Compare commits
50 Commits
9849ae5c14
...
ui-v2
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ea3b2b29d1 | ||
|
|
db877c52e6 | ||
|
|
8c053596b7 | ||
|
|
6a312bec9c | ||
|
|
455c1a1fae | ||
|
|
c08136d87b | ||
|
|
d962865944 | ||
|
|
a5417d200e | ||
|
|
95e7c64501 | ||
|
|
7f2327aea9 | ||
|
|
9c44cdf2a1 | ||
|
|
757008566c | ||
|
|
35b7701664 | ||
|
|
636c27ee88 | ||
|
|
8257ac24ab | ||
|
|
ac22f9a2f6 | ||
|
|
ebe8b29db2 | ||
|
|
b08a258931 | ||
|
|
ee6344dc74 | ||
|
|
312e1e3aa3 | ||
|
|
874e53ae46 | ||
|
|
1ad761ec53 | ||
|
|
258128de9f | ||
|
|
5692804c6f | ||
|
|
babd9e327c | ||
|
|
c45e5f732b | ||
|
|
0319039328 | ||
|
|
bba55a83f3 | ||
|
|
494925dff4 | ||
|
|
6a921415ea | ||
|
|
35e64d77d7 | ||
|
|
f77de40b7f | ||
|
|
19b8b8c509 | ||
|
|
0088158dc0 | ||
|
|
ee1159065a | ||
|
|
b6f20733fa | ||
|
|
93cb289940 | ||
|
|
88819c3a5f | ||
|
|
629628a522 | ||
|
|
a9253d830a | ||
|
|
c21497d71b | ||
|
|
56e5462647 | ||
|
|
88181b755d | ||
|
|
1dc8cf1efb | ||
|
|
f6bdbe006e | ||
|
|
c8c49ed57e | ||
|
|
18120e686f | ||
|
|
e3c31e43e5 | ||
|
|
fe7bf4ef07 | ||
|
|
289151214b |
@@ -52,7 +52,7 @@ TINY_ADAPTER=fake
|
||||
# SMTP_PASSWORD=...
|
||||
STORAGE_ADAPTER=s3-local
|
||||
MOCK_FREIGHT_CENTS=1500
|
||||
MAX_UPLOAD_BYTES=1073741824
|
||||
MAX_UPLOAD_BYTES=4294967296
|
||||
UPLOAD_PART_BYTES=8388608
|
||||
STORAGE_QUOTA_BYTES=53687091200
|
||||
OWNER_UPLOAD_QUOTA_BYTES=10737418240
|
||||
|
||||
@@ -86,7 +86,7 @@ jobs:
|
||||
# the generator's geometry. The provider suites use a fake transport: they
|
||||
# prove the documented contract, not the integration.
|
||||
- name: Print-file geometry and provider adapters
|
||||
run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_payment_messages tests.test_jadlog tests.test_correios tests.test_quote_review tests.test_large_files tests.test_grade_check tests.test_schema tests.test_customer_document tests.test_mail_html -v
|
||||
run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_payment_messages tests.test_jadlog tests.test_correios tests.test_quote_review tests.test_moves tests.test_large_files tests.test_grade_check tests.test_schema tests.test_customer_document tests.test_mail_html tests.test_layout_rules -v
|
||||
|
||||
- name: Runtime and retention regressions
|
||||
run: |
|
||||
@@ -189,7 +189,7 @@ jobs:
|
||||
set --
|
||||
[ -n "$PYTHON_BASE_IMAGE" ] && set -- --build-arg PYTHON_BASE_IMAGE="$PYTHON_BASE_IMAGE"
|
||||
docker build --file deploy/Dockerfile.api "$@" \
|
||||
--build-arg VCS_REF="${{ gitea.sha }}" \
|
||||
--build-arg VCS_REF="${{ gitea.sha }}" --build-arg PACKAGES_DAY="$(date -u +%F)" \
|
||||
--tag "$image:latest" --tag "$image:${{ gitea.sha }}" .
|
||||
- name: Build web
|
||||
run: |
|
||||
@@ -198,7 +198,7 @@ jobs:
|
||||
[ -n "$PYTHON_BASE_IMAGE" ] && set -- --build-arg PYTHON_BASE_IMAGE="$PYTHON_BASE_IMAGE"
|
||||
[ -n "$NGINX_BASE_IMAGE" ] && set -- "$@" --build-arg NGINX_BASE_IMAGE="$NGINX_BASE_IMAGE"
|
||||
docker build --file deploy/Dockerfile.web "$@" \
|
||||
--build-arg VCS_REF="${{ gitea.sha }}" \
|
||||
--build-arg VCS_REF="${{ gitea.sha }}" --build-arg PACKAGES_DAY="$(date -u +%F)" \
|
||||
--tag "$image:latest" --tag "$image:${{ gitea.sha }}" .
|
||||
# CRITICAL blocks, HIGH is reported. Both images carry zero CRITICAL after
|
||||
# the base pinning and OS upgrades, so this gate holds the line already
|
||||
|
||||
@@ -21,23 +21,25 @@ def begin_final(oid: UUID, body: UploadStart, user=Depends(can('produce'))):
|
||||
with db.connect() as c:
|
||||
row = c.execute('SELECT state FROM dtf_local.orders WHERE id=%s', (oid,)).fetchone()
|
||||
if not row: raise HTTPException(404, 'Order not found')
|
||||
if row['state'] not in ('rec','tra','cor'): raise HTTPException(409, 'Order is not in artwork review')
|
||||
if row['state'] not in ('rec','cor'): raise HTTPException(409, 'Order is not in artwork review')
|
||||
return begin_upload(body, session_id=operator_identity(user))
|
||||
|
||||
@router.get('/api/operator/uploads/{uid}')
|
||||
def final_status(uid: UUID, user=Depends(operator)):
|
||||
return upload_status(uid,session_id=operator_identity(user))
|
||||
|
||||
# The parts of an upload its operator started: a final (produce) or the
|
||||
# photo of a signed pickup receipt (deliver, which includes produce).
|
||||
@router.post('/api/operator/uploads/{uid}/parts/{number}')
|
||||
def final_part(uid: UUID, number: int, user=Depends(can('produce'))):
|
||||
def final_part(uid: UUID, number: int, user=Depends(can('deliver'))):
|
||||
return part_url(uid,number,session_id=operator_identity(user))
|
||||
|
||||
@router.post('/api/operator/uploads/{uid}/complete')
|
||||
def final_complete(uid: UUID, user=Depends(can('produce'))):
|
||||
def final_complete(uid: UUID, user=Depends(can('deliver'))):
|
||||
return complete_upload(uid,session_id=operator_identity(user))
|
||||
|
||||
@router.delete('/api/operator/uploads/{uid}')
|
||||
def final_cancel(uid: UUID, user=Depends(can('produce'))):
|
||||
def final_cancel(uid: UUID, user=Depends(can('deliver'))):
|
||||
return cancel_upload(uid,session_id=operator_identity(user))
|
||||
|
||||
@router.get('/api/operator/orders/{oid}/files')
|
||||
|
||||
@@ -3,6 +3,7 @@ import hashlib
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
from decimal import Decimal
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from typing import Literal
|
||||
from uuid import UUID
|
||||
@@ -12,14 +13,15 @@ from fastapi.responses import RedirectResponse
|
||||
from pydantic import Field
|
||||
|
||||
from ..core import db
|
||||
from ..core.auth import (COOKIE_SECURE, DESIGNER_STATES, DUMMY_PASSWORD_HASH, audit, can, client_ip, operator,
|
||||
login_failed, password_matches, throttle)
|
||||
from ..core.models import Move, OperatorLogin, Resolution, Review, StrictModel
|
||||
from ..printjobs import queue as queue_print_files
|
||||
from .. import cnpj, machines, mail, payments, quote_review
|
||||
from ..core.auth import (COOKIE_SECURE, DUMMY_PASSWORD_HASH, MOVERS, audit, can, client_ip, operator,
|
||||
login_failed, may_move, may_reorder, password_matches, throttle)
|
||||
from ..core.models import Move, OperatorLogin, Resolution, Review, StrictModel, UploadStart
|
||||
from ..printjobs import file_prefix, queue as queue_print_files
|
||||
from .. import cnpj, machines, mail, payments, proof, quote_review, receipt
|
||||
from .. import tiny
|
||||
from ..runtime import (BACK, BOARD_FINISHED_LIMIT, BOARD_QUOTE_LIMIT, ENVIRONMENT, PUBLIC_ORIGIN, STATES,
|
||||
TRANSITIONS, payment, enqueue, freight, quote_view, storage)
|
||||
TRANSITIONS, payment, enqueue, freight, operator_identity, quote_view, storage, upload_row)
|
||||
from .uploads import begin_upload
|
||||
from ..scanning import require_clean
|
||||
|
||||
router = APIRouter()
|
||||
@@ -100,7 +102,7 @@ def backup_now(user=Depends(can('integrations'))):
|
||||
|
||||
|
||||
@router.get('/api/operator/board')
|
||||
def board(request: Request, user=Depends(operator)):
|
||||
def board(user=Depends(operator)):
|
||||
with db.connect() as c:
|
||||
# Orders that arrived, or lost their machine, get one before the board is read.
|
||||
machines.route(c)
|
||||
@@ -125,7 +127,7 @@ def board(request: Request, user=Depends(operator)):
|
||||
approved_total = c.execute(f'''SELECT count(*) AS n FROM dtf_local.quotes q
|
||||
LEFT JOIN dtf_local.orders o ON o.quote_id=q.id
|
||||
WHERE o.id IS NULL AND q.approved IS NOT NULL AND {LIVE_QUOTE}''').fetchone()['n']
|
||||
orders = visible(request, with_print_files(c, active + list(reversed(finished))))
|
||||
orders = with_print_files(c, active + list(reversed(finished)))
|
||||
# A paid notification that did not become an order is money received
|
||||
# for nothing the factory will make. The board carries the count; the
|
||||
# Pagamentos tab pages through them until someone records a resolution.
|
||||
@@ -139,7 +141,7 @@ def board(request: Request, user=Depends(operator)):
|
||||
'mail': mail.status(c)},
|
||||
'environment': ENVIRONMENT, 'site_origin': PUBLIC_ORIGIN,
|
||||
'finished_shown': len(finished), 'finished_total': finished_total,
|
||||
'machines': machines.rows(c),
|
||||
'machines': machines.rows(c), 'printing_cap': machines.PRINTING_CAP,
|
||||
'quotes': quotes, 'thumbnails': thumbnails(c, orders, quotes),
|
||||
'names': company_names(c, orders, quotes),
|
||||
'pending_total': pending_total, 'approved_total': approved_total}
|
||||
@@ -175,28 +177,31 @@ def company_names(c, *groups):
|
||||
# An item's final counts while its file is still there and scanned clean: the
|
||||
# same rule that lets an order into the print queue.
|
||||
FINAL_OK = """f.kind='final' AND f.active AND u.expires_at>now() AND u.purged_at IS NULL AND u.scan_state='clean'"""
|
||||
# "Arte tratada" (Dropstar, 2026-10-27): a final someone prepared, not the
|
||||
# customer's own artwork. It is neither the file the system generated from
|
||||
# their art, nor one of their originals, nor a correction they sent. `f` is
|
||||
# the final in dtf_local.order_files, `o` its order.
|
||||
TREATED = """f.kind='final'
|
||||
AND NOT EXISTS (SELECT 1 FROM dtf_local.print_files p WHERE p.order_id=f.order_id AND p.upload_id=f.upload_id)
|
||||
AND NOT EXISTS (SELECT 1 FROM jsonb_array_elements(o.snapshot->'items') i WHERE i->'uploads' ? f.upload_id::text)
|
||||
AND NOT EXISTS (SELECT 1 FROM dtf_local.order_files k WHERE k.order_id=f.order_id AND k.upload_id=f.upload_id
|
||||
AND k.kind='correction')"""
|
||||
|
||||
|
||||
def assign_machines(c, orders):
|
||||
"""Each order's machine as stored (app/machines.py gives it): chosen by
|
||||
someone, or automatic. None while no machine prints its product."""
|
||||
someone, or automatic. None while no machine prints its product. In
|
||||
Imprimindo, also which of its machine's two places it holds."""
|
||||
names = {str(m['id']): m['name'] for m in c.execute('SELECT id,name FROM dtf_local.machines').fetchall()}
|
||||
slots = machines.printing_slots(c)
|
||||
for order in orders:
|
||||
key = str(order.get('machine_id') or '')
|
||||
order['machine'] = ({'id': key, 'name': names[key], 'chosen': bool(order.get('machine_chosen'))}
|
||||
if key in names else None)
|
||||
order['printing'] = slots.get(order['id'])
|
||||
return orders
|
||||
|
||||
|
||||
def visible(request, orders):
|
||||
"""An operator who works on some machines sees only their orders."""
|
||||
account = request.state.operator
|
||||
if account['role'] != 'operador' or not account['machines']:
|
||||
return orders
|
||||
mine = set(account['machines'])
|
||||
return [o for o in orders if o.get('machine') and o['machine']['id'] in mine]
|
||||
|
||||
|
||||
def with_print_files(c, orders):
|
||||
"""Each order with its generated print files, the items whose final file is
|
||||
approved, and the customer's corrections waiting to be approved as finals."""
|
||||
@@ -204,25 +209,45 @@ def with_print_files(c, orders):
|
||||
generated = c.execute('''SELECT p.order_id,p.item_index,p.status,p.upload_id,p.detail,u.name
|
||||
FROM dtf_local.print_files p LEFT JOIN dtf_local.uploads u ON u.id=p.upload_id
|
||||
WHERE p.order_id=ANY(%s) ORDER BY p.item_index''', (ids,)).fetchall()
|
||||
finals = c.execute(f'''SELECT DISTINCT f.order_id,f.item_index FROM dtf_local.order_files f
|
||||
finals = c.execute(f'''SELECT f.order_id,f.item_index,f.upload_id FROM dtf_local.order_files f
|
||||
JOIN dtf_local.uploads u ON u.id=f.upload_id WHERE f.order_id=ANY(%s) AND {FINAL_OK}''', (ids,)).fetchall()
|
||||
# Expired ones too: once corrected, a generated file is no longer the artwork.
|
||||
fixes = c.execute('''SELECT f.order_id,f.item_index,f.upload_id,u.name,
|
||||
(u.expires_at<=now() OR u.purged_at IS NOT NULL) AS expired FROM dtf_local.order_files f
|
||||
JOIN dtf_local.uploads u ON u.id=f.upload_id
|
||||
WHERE f.order_id=ANY(%s) AND f.kind='correction' AND f.active ORDER BY f.item_index''', (ids,)).fetchall()
|
||||
# The items whose approved final someone prepared, and who approved it.
|
||||
treated = c.execute(f'''SELECT f.order_id,f.item_index,f.created_by FROM dtf_local.order_files f
|
||||
JOIN dtf_local.orders o ON o.id=f.order_id WHERE f.order_id=ANY(%s) AND f.active AND {TREATED}
|
||||
ORDER BY f.item_index''', (ids,)).fetchall()
|
||||
# Each order's reworks (D-02 to D-04), with the names of who opened,
|
||||
# decided and printed.
|
||||
reworks = c.execute(f'''SELECT r.*, {person('r.opened_by')} AS opened_name, {person('r.decided_by')} AS decided_name,
|
||||
{person('r.printed_by')} AS printed_name FROM dtf_local.reworks r WHERE r.order_id=ANY(%s) ORDER BY r.id''',
|
||||
(ids,)).fetchall()
|
||||
# Why each order was last sent to correction, for the notice to the customer.
|
||||
reasons = {row['order_id']: row['reason'] for row in c.execute('''SELECT DISTINCT ON (order_id) order_id,reason
|
||||
FROM dtf_local.movements WHERE order_id=ANY(%s) AND to_state='cor' ORDER BY order_id,id DESC''', (ids,)).fetchall()}
|
||||
for order in orders:
|
||||
order['correction_reason'] = reasons.get(order['id']) if order['state'] == 'cor' else None
|
||||
order['print_files'] = [row for row in generated if row['order_id'] == order['id']]
|
||||
order['final_items'] = sorted(row['item_index'] for row in finals if row['order_id'] == order['id'])
|
||||
approved = [row for row in finals if row['order_id'] == order['id']]
|
||||
order['final_items'] = sorted({row['item_index'] for row in approved})
|
||||
# The approved finals themselves: "Tratar a arte" keeps those it does not replace.
|
||||
order['finals'] = [{'item_index': row['item_index'], 'upload_id': row['upload_id']} for row in approved]
|
||||
mine = [row for row in treated if row['order_id'] == order['id']]
|
||||
order['treated'] = {'items': [row['item_index'] for row in mine], 'by': mine[0]['created_by']} if mine else None
|
||||
order['corrections'] = [{k: row[k] for k in ('item_index', 'upload_id', 'name', 'expired')}
|
||||
for row in fixes if row['order_id'] == order['id']]
|
||||
order['reworks'] = [row for row in reworks if row['order_id'] == order['id']]
|
||||
return assign_machines(c, orders)
|
||||
|
||||
|
||||
def person(column):
|
||||
"""SQL: the team member's name for the e-mail in `column`, or the e-mail."""
|
||||
return f'COALESCE((SELECT op.name FROM dtf_local.operators op WHERE op.email={column}), {column})'
|
||||
|
||||
|
||||
def cursor_pair(first, second):
|
||||
if (first is None) != (second is None):
|
||||
raise HTTPException(422, 'Both cursor fields are required')
|
||||
@@ -230,7 +255,7 @@ def cursor_pair(first, second):
|
||||
|
||||
|
||||
@router.get('/api/operator/orders/finished')
|
||||
def finished_page(request: Request, before_created_at: datetime | None = None, before_id: UUID | None = None,
|
||||
def finished_page(before_created_at: datetime | None = None, before_id: UUID | None = None,
|
||||
limit: int = Query(default=50, ge=1, le=100), user=Depends(operator)):
|
||||
"""Older finished orders, newest first, beyond the board's recent window."""
|
||||
paged = cursor_pair(before_created_at, before_id)
|
||||
@@ -239,7 +264,7 @@ def finished_page(request: Request, before_created_at: datetime | None = None, b
|
||||
''' + ('AND (created_at,id)<(%s,%s) ' if paged else '') + '''
|
||||
ORDER BY created_at DESC,id DESC LIMIT %s''',
|
||||
((before_created_at, before_id) if paged else ()) + (limit + 1,)).fetchall()
|
||||
orders = visible(request, with_print_files(c, rows[:limit]))
|
||||
orders = with_print_files(c, rows[:limit])
|
||||
return {'orders': orders, 'has_more': len(rows) > limit, 'thumbnails': thumbnails(c, orders),
|
||||
'names': company_names(c, orders)}
|
||||
|
||||
@@ -247,7 +272,7 @@ def finished_page(request: Request, before_created_at: datetime | None = None, b
|
||||
@router.get('/api/operator/payment-events')
|
||||
def payment_events(state: Literal['open','resolved','all'] = 'open',
|
||||
offset: int = Query(default=0, ge=0),
|
||||
limit: int = Query(default=20, ge=1, le=100), user=Depends(can('manage'))):
|
||||
limit: int = Query(default=20, ge=1, le=100), user=Depends(can('payments'))):
|
||||
"""Payments that needed a person, newest first: open ones to act on, resolved ones as history."""
|
||||
where = {'open': 'AND resolved_at IS NULL', 'resolved': 'AND resolved_at IS NOT NULL', 'all': ''}[state]
|
||||
with db.connect() as c:
|
||||
@@ -359,7 +384,7 @@ def quote_page(kind: Literal['pending','approved'], before_created_at: datetime
|
||||
|
||||
|
||||
@router.get('/api/operator/search')
|
||||
def search(request: Request, q: str = Query(min_length=2, max_length=100), user=Depends(operator)):
|
||||
def search(q: str = Query(min_length=2, max_length=100), user=Depends(operator)):
|
||||
"""One search over orders (any stage) and unpaid quotes: customer e-mail,
|
||||
CNPJ or WhatsApp, the delivery recipient, or the order number."""
|
||||
match, params = customer_match('snapshot', q)
|
||||
@@ -382,7 +407,7 @@ def search(request: Request, q: str = Query(min_length=2, max_length=100), user=
|
||||
LEFT JOIN dtf_local.orders o ON o.quote_id=q.id
|
||||
WHERE o.id IS NULL AND {LIVE_QUOTE} AND {quote_match}
|
||||
ORDER BY q.created_at DESC LIMIT 8''', quote_params).fetchall()
|
||||
orders = visible(request, with_print_files(c, orders))
|
||||
orders = with_print_files(c, orders)
|
||||
quotes = [quote_view(c, row) for row in rows]
|
||||
return {'orders': orders, 'quotes': quotes, 'thumbnails': thumbnails(c, orders, quotes),
|
||||
'names': company_names(c, orders, quotes)}
|
||||
@@ -407,12 +432,101 @@ def test_order(uid: UUID, user=Depends(can('manage'))):
|
||||
raise HTTPException(404 if 'not found' in str(refusal) else 409, str(refusal))
|
||||
receipt = {'provider': payments.TEST_PROVIDER, 'id': f'teste-{uid}', 'status': 'paid',
|
||||
'total_cents': quote['approved']['total_cents'], 'operator': user}
|
||||
order, created = payments.create_order(c, quote, receipt)
|
||||
order, created = payments.create_order(c, quote, receipt, 'site')
|
||||
if created:
|
||||
audit('test_order_created', order=str(order['id']), operator=user)
|
||||
return order
|
||||
|
||||
|
||||
class PaidOutside(StrictModel):
|
||||
# No defaults (D-35): whoever registers the order says where it came from
|
||||
# and how it was paid.
|
||||
origin: Literal['site', 'dropflow', 'atendimento']
|
||||
method: Literal[payments.OUTSIDE_METHODS]
|
||||
note: str = Field(default='', max_length=300)
|
||||
|
||||
|
||||
@router.post('/api/operator/quotes/{uid}/register')
|
||||
def register_order(uid: UUID, body: PaidOutside, user=Depends(can('enter'))):
|
||||
"""The order for an approved quote paid outside the system (Dropstar's
|
||||
rule D-35): the team builds the cart on the Site, as a customer would, and
|
||||
registers it here with its origin and how it was paid. The price is the
|
||||
quote's, the Site's table price."""
|
||||
with db.connect() as c:
|
||||
try:
|
||||
quote = payments.approved_quote(c, uid)
|
||||
except payments.PaymentRefused as refusal:
|
||||
raise HTTPException(404 if 'not found' in str(refusal) else 409, str(refusal))
|
||||
receipt = {'provider': payments.MANUAL_PROVIDER, 'method': body.method, 'note': body.note.strip(),
|
||||
'status': 'paid', 'total_cents': quote['approved']['total_cents'], 'operator': user}
|
||||
order, created = payments.create_order(c, quote, receipt, body.origin)
|
||||
if not created:
|
||||
raise HTTPException(409, f"Esta cotação já virou o pedido #{order['number']}.")
|
||||
audit('manual_order_registered', order=str(order['id']), origin=body.origin, operator=user)
|
||||
return order
|
||||
|
||||
|
||||
# Rework (Dropstar's rules D-02 to D-04): four causes of the house, each with a
|
||||
# goal of 0,4% of the film printed (1,6% in all), and the customer's approved
|
||||
# bad art, recorded apart and outside the goal (D-04).
|
||||
HOUSE_CAUSES = ('impressao', 'perfil_cor', 'tratamento', 'pedido')
|
||||
CUSTOMER_CAUSE = 'arte_cliente'
|
||||
REWORK_GOAL_PERCENT = Decimal('0.4')
|
||||
|
||||
|
||||
class ReworkOpen(StrictModel):
|
||||
cause: Literal[HOUSE_CAUSES + (CUSTOMER_CAUSE,)]
|
||||
metres: Decimal = Field(gt=0, le=1000)
|
||||
note: str = Field(default='', max_length=1000)
|
||||
|
||||
|
||||
class ReworkDecision(StrictModel):
|
||||
authorized: bool
|
||||
reason: str = Field(default='', max_length=1000)
|
||||
|
||||
|
||||
@router.post('/api/operator/orders/{uid}/reworks')
|
||||
def open_rework(uid: UUID, body: ReworkOpen, user=Depends(can('rework'))):
|
||||
"""Coordination opens a rework with its cause (D-02). There is no way to
|
||||
change the cause afterwards (D-03)."""
|
||||
with db.connect() as c:
|
||||
order = c.execute('SELECT id,number,cancelled_at FROM dtf_local.orders WHERE id=%s', (uid,)).fetchone()
|
||||
if not order:
|
||||
raise HTTPException(404, 'Pedido não encontrado.')
|
||||
if order['cancelled_at']:
|
||||
raise HTTPException(409, 'Pedido cancelado não abre retrabalho.')
|
||||
# Who printed the sheet: who last sent it to Revisão.
|
||||
printed = c.execute('''SELECT operator FROM dtf_local.movements WHERE order_id=%s AND to_state='rev'
|
||||
AND NOT back ORDER BY id DESC LIMIT 1''', (uid,)).fetchone()
|
||||
row = c.execute('''INSERT INTO dtf_local.reworks(order_id,cause,metres,note,printed_by,opened_by)
|
||||
VALUES(%s,%s,%s,%s,%s,%s) RETURNING *''',
|
||||
(uid, body.cause, body.metres, body.note.strip(), printed['operator'] if printed else None,
|
||||
user)).fetchone()
|
||||
audit('rework_opened', order=order['number'], cause=body.cause, operator=user)
|
||||
return row
|
||||
|
||||
|
||||
@router.post('/api/operator/reworks/{rid}/decision')
|
||||
def decide_rework(rid: int, body: ReworkDecision, user=Depends(can('authorize'))):
|
||||
"""An Administrador authorizes a rework, and only then it counts, or
|
||||
declines it with a reason (D-02). Never one they opened themselves."""
|
||||
reason = body.reason.strip()
|
||||
if not body.authorized and len(reason) < 3:
|
||||
raise HTTPException(422, 'Diga por que o retrabalho não foi autorizado.')
|
||||
with db.connect() as c:
|
||||
row = c.execute('SELECT * FROM dtf_local.reworks WHERE id=%s FOR UPDATE', (rid,)).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(404, 'Retrabalho não encontrado.')
|
||||
if row['decided_at']:
|
||||
raise HTTPException(409, 'Este retrabalho já foi decidido.')
|
||||
if row['opened_by'] == user:
|
||||
raise HTTPException(409, 'Quem abriu o retrabalho não pode autorizá-lo.')
|
||||
row = c.execute('''UPDATE dtf_local.reworks SET authorized=%s, decided_by=%s, decided_at=now(), decline_reason=%s
|
||||
WHERE id=%s RETURNING *''', (body.authorized, user, None if body.authorized else reason, rid)).fetchone()
|
||||
audit('rework_decided', rework=rid, authorized=body.authorized, operator=user)
|
||||
return row
|
||||
|
||||
|
||||
@router.post('/api/operator/quotes/{uid}/discard')
|
||||
def discard_quote(uid: UUID, user=Depends(can('manage'))):
|
||||
"""An unpaid quote leaves the Kanban and can no longer be paid. Its files
|
||||
@@ -488,7 +602,7 @@ def release_files(c, uploads):
|
||||
|
||||
|
||||
@router.post('/api/operator/orders/{uid}/cancel')
|
||||
def cancel_order(uid: UUID, body: Resolution, user=Depends(can('manage'))):
|
||||
def cancel_order(uid: UUID, body: Resolution, user=Depends(can('cancel'))):
|
||||
"""A paid order leaves the board but keeps its payment and history. Nothing
|
||||
is refunded here (that is done at the provider); Tiny is told, so the
|
||||
order is cancelled there too while it was not invoiced (app/tiny.py)."""
|
||||
@@ -498,7 +612,7 @@ def cancel_order(uid: UUID, body: Resolution, user=Depends(can('manage'))):
|
||||
(user, body.note, uid)).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(404, 'Pedido não encontrado ou já cancelado.')
|
||||
if not payments.is_test(row):
|
||||
if payments.in_tiny(row):
|
||||
sale = c.execute("SELECT receipt FROM dtf_local.outbox WHERE event_key=%s AND delivered_at IS NOT NULL",
|
||||
(f'{uid}:paid:tiny',)).fetchone()
|
||||
enqueue(c, f'{uid}:cancelled:tiny', 'tiny',
|
||||
@@ -508,28 +622,29 @@ def cancel_order(uid: UUID, body: Resolution, user=Depends(can('manage'))):
|
||||
return {'ok': True}
|
||||
|
||||
|
||||
def designer_only(request, *states):
|
||||
"""A designer works on the artwork stages only: Arte recebida, Arte
|
||||
conferida and Correção. The queue onwards is the print room's."""
|
||||
if request.state.operator['role'] == 'designer' and not set(states) <= set(DESIGNER_STATES):
|
||||
raise HTTPException(403, 'O perfil Designer move pedidos só entre Arte recebida, Arte conferida e Correção.')
|
||||
|
||||
|
||||
class MachineChoice(StrictModel):
|
||||
machine_id: UUID | None = None
|
||||
|
||||
|
||||
@router.post('/api/operator/orders/{uid}/machine')
|
||||
def choose_machine(uid: UUID, body: MachineChoice, user=Depends(can('print'))):
|
||||
"""Send an order to a machine, or back to the automatic choice (None)."""
|
||||
def choose_machine(uid: UUID, body: MachineChoice, request: Request, user=Depends(can('print'))):
|
||||
"""Send an order to a machine, or back to the automatic choice (None).
|
||||
Not the operator: their pull makes an order their machine's (item 12)."""
|
||||
if request.state.operator['role'] == 'operador':
|
||||
raise HTTPException(403, 'A máquina do pedido é a de quem puxa para Imprimindo.')
|
||||
with db.connect() as c:
|
||||
if body.machine_id and not c.execute('SELECT 1 FROM dtf_local.machines WHERE id=%s', (body.machine_id,)).fetchone():
|
||||
raise HTTPException(404, 'Máquina não encontrada.')
|
||||
row = c.execute('UPDATE dtf_local.orders SET machine_id=%s, machine_chosen=%s WHERE id=%s RETURNING number',
|
||||
(body.machine_id, body.machine_id is not None, uid)).fetchone()
|
||||
row = c.execute('''UPDATE dtf_local.orders SET machine_id=%s, machine_chosen=%s WHERE id=%s
|
||||
RETURNING number, state, cancelled_at''', (body.machine_id, body.machine_id is not None, uid)).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(404, 'Pedido não encontrado.')
|
||||
machines.route(c)
|
||||
# Printing already: the machine it goes to must have a place in Imprimindo.
|
||||
if row['state'] == 'imp' and not row['cancelled_at']:
|
||||
now = c.execute('SELECT machine_id FROM dtf_local.orders WHERE id=%s', (uid,)).fetchone()
|
||||
if name := machines.full(c, now['machine_id'], uid):
|
||||
raise HTTPException(409, f'{name} já tem {machines.PRINTING_CAP} em Imprimindo.')
|
||||
audit('order_machine_chosen', order=row['number'], machine=str(body.machine_id or ''), operator=user)
|
||||
return {'ok': True}
|
||||
|
||||
@@ -554,10 +669,125 @@ def contact(uid: UUID, body: ContactWait, user=Depends(can('produce'))):
|
||||
(body.waiting, body.waiting, user, body.waiting, note, uid)).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(404, 'Pedido não encontrado.')
|
||||
# The wait's history, for the time figures that leave it out (D-38).
|
||||
c.execute('UPDATE dtf_local.contact_waits SET ended_at=now() WHERE order_id=%s AND ended_at IS NULL', (uid,))
|
||||
if body.waiting:
|
||||
c.execute('INSERT INTO dtf_local.contact_waits(order_id, started_at) VALUES(%s, now())', (uid,))
|
||||
audit('order_contact_waiting' if body.waiting else 'order_contact_done', order=row['number'], operator=user)
|
||||
return {'ok': True}
|
||||
|
||||
|
||||
@router.post('/api/operator/orders/{uid}/proof')
|
||||
def proof_ok(uid: UUID, user=Depends(can('print'))):
|
||||
"""The print room checked the proof: the order may reach Finalizado."""
|
||||
with db.connect() as c:
|
||||
row = c.execute('''UPDATE dtf_local.orders SET proof_ok_at=now(), proof_ok_by=%s, version=version+1
|
||||
WHERE id=%s AND cancelled_at IS NULL AND state<>'fin' RETURNING number, version''', (user, uid)).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(404, 'Pedido não encontrado.')
|
||||
audit('order_proof_ok', order=row['number'], operator=user)
|
||||
return {'ok': True, 'version': row['version']}
|
||||
|
||||
|
||||
def paid_with(c, order):
|
||||
"""How the order was paid, for its receipt: pix, card, cash, credit, or
|
||||
'teste' for an operator's test order."""
|
||||
paid = order.get('payment') or {}
|
||||
if paid.get('provider') == 'teste':
|
||||
return 'teste'
|
||||
if paid.get('provider') == payments.MANUAL_PROVIDER:
|
||||
return paid.get('method')
|
||||
row = c.execute('''SELECT method FROM dtf_local.payment_intents WHERE quote_id=%s AND status='approved'
|
||||
ORDER BY created_at DESC LIMIT 1''', (order['quote_id'],)).fetchone()
|
||||
return row and row['method']
|
||||
|
||||
|
||||
@router.get('/api/operator/orders/{uid}/receipt')
|
||||
def pickup_receipt(uid: UUID, user=Depends(operator)):
|
||||
"""The pickup receipt's PDF (item 14), for the folder to save or someone
|
||||
to print again."""
|
||||
with db.connect() as c:
|
||||
order = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s', (uid,)).fetchone()
|
||||
if not order:
|
||||
raise HTTPException(404, 'Pedido não encontrado.')
|
||||
if not receipt.is_pickup(order['snapshot']):
|
||||
raise HTTPException(409, 'Só pedido de retirada tem recibo.')
|
||||
body = receipt.render(order, paid_with(c, order))
|
||||
return Response(body, media_type='application/pdf',
|
||||
headers={'Content-Disposition': f'inline; filename="{receipt.file_name(order)}"'})
|
||||
|
||||
|
||||
@router.post('/api/operator/orders/{uid}/receipt/claim')
|
||||
def claim_receipt(uid: UUID, user=Depends(can('print'))):
|
||||
"""One computer's folder takes the receipt to save: once, so the counter's
|
||||
queue never prints it twice."""
|
||||
with db.connect() as c:
|
||||
row = c.execute('''UPDATE dtf_local.orders SET receipt_saved_at=now(), receipt_saved_by=%s
|
||||
WHERE id=%s AND receipt_due_at IS NOT NULL AND receipt_saved_at IS NULL AND cancelled_at IS NULL
|
||||
RETURNING number''', (user, uid)).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(409, 'Este recibo já foi salvo.')
|
||||
audit('pickup_receipt_saved', order=row['number'], operator=user)
|
||||
return {'ok': True}
|
||||
|
||||
|
||||
@router.post('/api/operator/orders/{uid}/receipt/release')
|
||||
def release_receipt(uid: UUID, user=Depends(can('print'))):
|
||||
"""The folder could not save the receipt it took: another computer may."""
|
||||
with db.connect() as c:
|
||||
c.execute('''UPDATE dtf_local.orders SET receipt_saved_at=NULL, receipt_saved_by=NULL
|
||||
WHERE id=%s AND receipt_saved_by=%s''', (uid, user))
|
||||
return {'ok': True}
|
||||
|
||||
|
||||
def pickup_order(c, uid, lock=False):
|
||||
"""An order in Finalizado to be picked up, or why it cannot be marked."""
|
||||
order = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s' + (' FOR UPDATE' if lock else ''), (uid,)).fetchone()
|
||||
if not order:
|
||||
raise HTTPException(404, 'Pedido não encontrado.')
|
||||
if order['cancelled_at'] or order['state'] != 'fin' or not receipt.is_pickup(order['snapshot']):
|
||||
raise HTTPException(409, 'Só um pedido de retirada em Finalizado é marcado como retirado.')
|
||||
if order['picked_up_at']:
|
||||
raise HTTPException(409, 'Este pedido já foi marcado como retirado.')
|
||||
return order
|
||||
|
||||
|
||||
@router.post('/api/operator/orders/{uid}/pickup-uploads')
|
||||
def begin_pickup_photo(uid: UUID, body: UploadStart, user=Depends(can('deliver'))):
|
||||
"""The photo of the signed receipt, sent before marking the order."""
|
||||
with db.connect() as c:
|
||||
pickup_order(c, uid)
|
||||
return begin_upload(body, session_id=operator_identity(user))
|
||||
|
||||
|
||||
class PickedUp(StrictModel):
|
||||
photo: UUID | None = None
|
||||
|
||||
|
||||
PHOTO_TYPES = ('.jpg', '.jpeg', '.png', '.webp', '.heic', '.heif')
|
||||
|
||||
|
||||
@router.post('/api/operator/orders/{uid}/picked-up')
|
||||
def picked_up(uid: UUID, body: PickedUp, user=Depends(can('deliver'))):
|
||||
""""Retirado": when and who handed the order over, and the photo of the
|
||||
signed receipt when there is one (item 14). Finalizado means ready; this
|
||||
closes the cycle. The photo is kept 30 days, as the order's files are."""
|
||||
with db.connect() as c:
|
||||
order = pickup_order(c, uid, lock=True)
|
||||
if body.photo:
|
||||
photo = upload_row(c, body.photo, operator_identity(user), lock=True)
|
||||
if not photo['complete']:
|
||||
raise HTTPException(409, 'Espere a foto terminar de enviar.')
|
||||
if not photo['name'].lower().endswith(PHOTO_TYPES):
|
||||
raise HTTPException(422, 'A foto do recibo precisa ser uma imagem (JPG, PNG, WebP ou HEIC).')
|
||||
require_clean(photo)
|
||||
c.execute("UPDATE dtf_local.uploads SET expires_at=now()+interval '30 days' WHERE id=%s", (body.photo,))
|
||||
row = c.execute('''UPDATE dtf_local.orders SET picked_up_at=now(), picked_up_by=%s, picked_up_photo=%s
|
||||
WHERE id=%s RETURNING picked_up_at''', (user, body.photo, uid)).fetchone()
|
||||
audit('order_picked_up', order=order['number'], operator=user, photo=bool(body.photo))
|
||||
return {'ok': True, 'picked_up_at': row['picked_up_at']}
|
||||
|
||||
|
||||
class QueuePlace(StrictModel):
|
||||
"""Where a dragged card lands: between two orders of its column, either
|
||||
of them absent at the top or the bottom."""
|
||||
@@ -569,17 +799,22 @@ QUEUE_KEY = 'COALESCE(queue_key, extract(epoch FROM created_at))'
|
||||
|
||||
|
||||
@router.post('/api/operator/orders/{uid}/queue')
|
||||
def queue_place(uid: UUID, body: QueuePlace, request: Request, user=Depends(can('produce'))):
|
||||
def queue_place(uid: UUID, body: QueuePlace, request: Request, user=Depends(operator)):
|
||||
"""An order's place in its column: by default its payment time; dragged,
|
||||
halfway between the orders it was dropped between. It neither changes the
|
||||
order's stage nor counts as activity (the stalled clock keeps running)."""
|
||||
if not body.after and not body.before:
|
||||
raise HTTPException(422, 'Informe entre quais pedidos ele fica.')
|
||||
with db.connect() as c:
|
||||
row = c.execute('SELECT state FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
|
||||
row = c.execute('SELECT state, machine_id FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(404, 'Order not found')
|
||||
designer_only(request, row['state'])
|
||||
if not may_reorder(request.state.operator['role'], row['state']):
|
||||
raise HTTPException(403, 'Seu perfil não muda a ordem dos pedidos desta etapa.')
|
||||
mine = request.state.operator['machine']
|
||||
if (request.state.operator['role'] == 'operador' and row['state'] != 'tra'
|
||||
and (not mine or str(row['machine_id'] or '') != mine['id'])):
|
||||
raise HTTPException(403, 'Este pedido é de outra máquina: só quem está nela move o card.')
|
||||
keys = {}
|
||||
for side in ('after', 'before'):
|
||||
other = getattr(body, side)
|
||||
@@ -600,7 +835,9 @@ def queue_place(uid: UUID, body: QueuePlace, request: Request, user=Depends(can(
|
||||
|
||||
|
||||
@router.post('/api/operator/orders/{uid}/move')
|
||||
def move(uid: UUID, body: Move, request: Request, user=Depends(can('produce'))):
|
||||
def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
|
||||
if request.state.operator['role'] not in MOVERS:
|
||||
raise HTTPException(403, 'Seu perfil não permite esta ação.')
|
||||
with db.connect() as c:
|
||||
row = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
|
||||
if not row:
|
||||
@@ -611,30 +848,69 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(can('produce'))):
|
||||
raise HTTPException(409, 'Pedido cancelado.')
|
||||
if body.state == row['state']:
|
||||
return row
|
||||
designer_only(request, row['state'], body.state)
|
||||
back = BACK.get(row['state']) == body.state
|
||||
if body.state not in TRANSITIONS[row['state']] and not back:
|
||||
raise HTTPException(409, f"Não dá para ir de {STATES[row['state']]} para {STATES[body.state]}.")
|
||||
if not may_move(request.state.operator['role'], row['state'], body.state, back):
|
||||
raise HTTPException(403, 'Só o Revisor manda o pedido para Finalizado.' if body.state == 'fin' and not back
|
||||
else f"Seu perfil não move pedidos de {STATES[row['state']]} para {STATES[body.state]}.")
|
||||
if body.state == 'cor' and not body.reason.strip():
|
||||
raise HTTPException(422, 'Informe o motivo da correção.')
|
||||
if back and not body.reason.strip():
|
||||
raise HTTPException(422, 'Informe por que o pedido está voltando de etapa.')
|
||||
if body.state in ('fil','imp'):
|
||||
# The machine of this session (item 12): pulling a card from the queue
|
||||
# makes it that machine's ("a máquina real do card é a que puxou"); an
|
||||
# operator pulls any card but moves only their machine's.
|
||||
account = request.state.operator
|
||||
session_machine = account['machine']
|
||||
pulling = row['state'] == 'tra' and body.state == 'imp'
|
||||
if account['role'] == 'operador':
|
||||
if not session_machine:
|
||||
raise HTTPException(409, 'Escolha a máquina em que você está.')
|
||||
if not pulling and str(row['machine_id'] or '') != session_machine['id']:
|
||||
raise HTTPException(403, 'Este pedido é de outra máquina: só quem está nela move o card.')
|
||||
if pulling and session_machine and (account['role'] == 'operador' or not row['machine_chosen']):
|
||||
prints = c.execute('SELECT products FROM dtf_local.machines WHERE id=%s', (session_machine['id'],)).fetchone()
|
||||
if machines.product_family(row) in (prints or {}).get('products', []):
|
||||
row['machine_id'] = session_machine['id']
|
||||
c.execute('UPDATE dtf_local.orders SET machine_id=%s, machine_chosen=true WHERE id=%s',
|
||||
(session_machine['id'], uid))
|
||||
elif account['role'] == 'operador':
|
||||
raise HTTPException(409, f"A {session_machine['name']} não imprime este produto.")
|
||||
# Arte conferida is the queue: what enters it has its final files approved.
|
||||
if body.state in ('tra','imp'):
|
||||
coverage = c.execute(f'''SELECT DISTINCT f.item_index FROM dtf_local.order_files f
|
||||
JOIN dtf_local.uploads u ON u.id=f.upload_id WHERE f.order_id=%s AND {FINAL_OK}''', (uid,)).fetchall()
|
||||
if {r['item_index'] for r in coverage} != set(range(len(row['snapshot']['items']))):
|
||||
raise HTTPException(409, 'Aprove os arquivos finais de todos os itens antes de colocar na fila.')
|
||||
raise HTTPException(409, 'Aprove os arquivos finais de todos os itens antes de mandar para Arte conferida.')
|
||||
# Two at most per machine in Imprimindo (app/machines.py).
|
||||
if body.state == 'imp' and (name := machines.full(c, row['machine_id'], uid)):
|
||||
raise HTTPException(409, f'{name} já tem {machines.PRINTING_CAP} em Imprimindo.')
|
||||
if body.state == 'fin' and proof.needs_proof(row['snapshot']) and not row['proof_ok_at']:
|
||||
raise HTTPException(409, 'Falta a prova: confira a prova impressa e marque Prova OK antes de finalizar.')
|
||||
if body.state == 'cor':
|
||||
c.execute("UPDATE dtf_local.order_files SET active=false WHERE order_id=%s AND kind='final'", (uid,))
|
||||
c.execute('INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason,back) VALUES(%s,%s,%s,%s,%s,%s)',
|
||||
(uid,row['state'],body.state,user,body.reason,back))
|
||||
changed = c.execute('UPDATE dtf_local.orders SET state=%s, version=version+1, updated_at=now(), queue_key=NULL WHERE id=%s RETURNING *', (body.state,uid)).fetchone()
|
||||
events = {'imp':'production_started','cor':'correction_needed','fin':'ready'}
|
||||
if body.state in events and not back and not payments.is_test(row):
|
||||
# Who moved it, and on which machine: the one it goes to print on, or
|
||||
# else the mover's.
|
||||
machine_name = (session_machine or {}).get('name')
|
||||
if body.state == 'imp' and row['machine_id']:
|
||||
machine_name = (c.execute('SELECT name FROM dtf_local.machines WHERE id=%s',
|
||||
(row['machine_id'],)).fetchone() or {}).get('name')
|
||||
c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason,back,machine)
|
||||
VALUES(%s,%s,%s,%s,%s,%s,%s)''', (uid,row['state'],body.state,user,body.reason,back,machine_name))
|
||||
# A pickup reaching Finalizado has its receipt due (item 14), once.
|
||||
due = body.state == 'fin' and not back and receipt.is_pickup(row['snapshot'])
|
||||
changed = c.execute('''UPDATE dtf_local.orders SET state=%s, version=version+1, updated_at=now(), queue_key=NULL,
|
||||
receipt_due_at=CASE WHEN %s THEN COALESCE(receipt_due_at, now()) ELSE receipt_due_at END
|
||||
WHERE id=%s RETURNING *''', (body.state, due, uid)).fetchone()
|
||||
# Entering the queue (Arte conferida) is Tiny's "Preparando envio";
|
||||
# Finalizado its "Pronto para envio" (Dropstar's flow, 2026-10-23).
|
||||
events = {'tra':'production_started','cor':'correction_needed','fin':'ready'}
|
||||
if body.state in events and not back and payments.in_tiny(row):
|
||||
# "Production started" and "ready" reach the customer once per order,
|
||||
# even if a mistaken move is undone and made again. Each correction
|
||||
# is a new request, so it keeps one message per movement.
|
||||
once = body.state in ('imp','fin')
|
||||
once = body.state in ('tra','fin')
|
||||
event = {'order_id':str(uid), 'number':row['number'], 'event':events[body.state], 'reason':body.reason,
|
||||
'customer_path': f'/portal.html?order={uid}'}
|
||||
# Tiny needs the order (customer, pickup or delivery) and, once the
|
||||
@@ -761,9 +1037,20 @@ def thumbnail(uid: UUID, user=Depends(operator)):
|
||||
|
||||
# Real work only: an operator's test order and a cancelled one are not production.
|
||||
REAL_ORDER = "o.cancelled_at IS NULL AND COALESCE(o.payment->>'provider','') <> 'teste'"
|
||||
# Where orders come from (D-21), in the order Números lists them.
|
||||
ORIGINS = ('site', 'dropflow', 'atendimento')
|
||||
LOCAL_DAY = "(o.created_at AT TIME ZONE 'America/Sao_Paulo')::date"
|
||||
|
||||
|
||||
def waited(order, start, end):
|
||||
"""SQL: the seconds `order` spent in "Aguardando contato" between `start`
|
||||
and `end`. Dropstar's rule D-38: that wait has no deadline and does not
|
||||
count in the time figures."""
|
||||
return f'''COALESCE((SELECT sum(extract(epoch FROM least({end}, COALESCE(w.ended_at, now()))
|
||||
- greatest({start}, w.started_at))) FROM dtf_local.contact_waits w
|
||||
WHERE w.order_id={order} AND w.started_at<{end} AND COALESCE(w.ended_at, now())>{start}), 0)'''
|
||||
|
||||
|
||||
# Longest period one request may cover: a year and a day, for a year against the last.
|
||||
STATS_MAX_DAYS = 366
|
||||
|
||||
@@ -814,11 +1101,12 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start
|
||||
# that came back twice reads as three quick passages, not one slow order.
|
||||
stages = c.execute(f'''SELECT state, count(*) AS orders, sum(passages)::int AS passages,
|
||||
percentile_cont(0.5) WITHIN GROUP (ORDER BY seconds) / 3600 AS median_hours
|
||||
FROM (SELECT id, state, count(*) AS passages, sum(extract(epoch FROM until-at)) AS seconds
|
||||
FROM (SELECT id, state, count(*) AS passages,
|
||||
sum(extract(epoch FROM until-at) - {waited('s.id', 's.at', 's.until')}) AS seconds
|
||||
FROM ({spans}) s WHERE until IS NOT NULL GROUP BY id, state) per_order
|
||||
GROUP BY state''', period + period).fetchall()
|
||||
lead = c.execute(f'''SELECT count(*) AS orders, percentile_cont(0.5) WITHIN GROUP (ORDER BY extract(epoch FROM
|
||||
f.at - o.created_at)) / 3600 AS median_hours FROM dtf_local.orders o
|
||||
f.at - o.created_at) - {waited('o.id', 'o.created_at', 'f.at')}) / 3600 AS median_hours FROM dtf_local.orders o
|
||||
JOIN LATERAL (SELECT min(created_at) AS at FROM dtf_local.movements m WHERE m.order_id=o.id AND m.to_state='fin') f
|
||||
ON f.at IS NOT NULL
|
||||
WHERE {REAL_ORDER} AND {within}''', period).fetchone()
|
||||
@@ -828,6 +1116,40 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start
|
||||
o.created_at))) / 3600 AS oldest_hours
|
||||
FROM dtf_local.orders o WHERE {REAL_ORDER} AND o.state<>'fin' GROUP BY o.state''').fetchall()
|
||||
printed = machine_output(c, start, end)
|
||||
# Rework of the period (D-02 to D-04): the authorized ones, by the day
|
||||
# they were opened, over the film the machines printed in it.
|
||||
not_test = "COALESCE(o.payment->>'provider','') <> 'teste'"
|
||||
opened = "(r.opened_at AT TIME ZONE 'America/Sao_Paulo')::date BETWEEN %s AND %s"
|
||||
redone = {row['cause']: row for row in c.execute(f'''SELECT r.cause, sum(r.metres) AS metres,
|
||||
count(DISTINCT r.order_id) AS orders FROM dtf_local.reworks r JOIN dtf_local.orders o ON o.id=r.order_id
|
||||
WHERE r.authorized AND {not_test} AND {opened} GROUP BY r.cause''', period).fetchall()}
|
||||
# The house's rework enters the pay of who printed it (D-02).
|
||||
by_printer = c.execute(f'''SELECT COALESCE({person('r.printed_by')}, 'Sem registro') AS who,
|
||||
sum(r.metres) AS metres FROM dtf_local.reworks r JOIN dtf_local.orders o ON o.id=r.order_id
|
||||
WHERE r.authorized AND r.cause<>%s AND {not_test} AND {opened} GROUP BY 1 ORDER BY 2 DESC''',
|
||||
(CUSTOMER_CAUSE,) + period).fetchall()
|
||||
undecided = c.execute(f'''SELECT r.id, r.order_id, o.number, r.cause, r.metres, r.opened_at,
|
||||
{person('r.opened_by')} AS opened_name FROM dtf_local.reworks r JOIN dtf_local.orders o ON o.id=r.order_id
|
||||
WHERE r.decided_at IS NULL AND {not_test} ORDER BY r.opened_at''').fetchall()
|
||||
# Arte tratada, for the designer's productivity: orders of the period
|
||||
# whose final someone prepared, by who approved it (any version).
|
||||
treated = c.execute(f'''SELECT COALESCE(op.name, f.created_by) AS who, count(DISTINCT f.order_id) AS orders
|
||||
FROM dtf_local.order_files f JOIN dtf_local.orders o ON o.id=f.order_id
|
||||
LEFT JOIN dtf_local.operators op ON op.email=f.created_by
|
||||
WHERE {REAL_ORDER} AND {within} AND {TREATED} GROUP BY 1 ORDER BY 2 DESC, 1''', period).fetchall()
|
||||
treated_orders = c.execute(f'''SELECT count(DISTINCT f.order_id) AS n FROM dtf_local.order_files f
|
||||
JOIN dtf_local.orders o ON o.id=f.order_id WHERE {REAL_ORDER} AND {within} AND {TREATED}''',
|
||||
period).fetchone()['n']
|
||||
# Each way in apart (D-21): what came from where, and how long it took
|
||||
# from payment to Finalizado, Aguardando contato left out as above.
|
||||
origins = {row['origin']: row for row in c.execute(f'''SELECT o.origin, count(*) AS orders,
|
||||
COALESCE(sum((o.snapshot->>'total_cents')::bigint),0) AS cents, COALESCE(sum({metres}),0) AS metres,
|
||||
count(f.at) AS finished, percentile_cont(0.5) WITHIN GROUP (ORDER BY extract(epoch FROM
|
||||
f.at - o.created_at) - {waited('o.id', 'o.created_at', 'f.at')}) / 3600 AS median_hours
|
||||
FROM dtf_local.orders o
|
||||
LEFT JOIN LATERAL (SELECT min(created_at) AS at FROM dtf_local.movements m
|
||||
WHERE m.order_id=o.id AND m.to_state='fin') f ON true
|
||||
WHERE {REAL_ORDER} AND {within} GROUP BY o.origin''', period).fetchall()}
|
||||
series = []
|
||||
for offset in range((end - start).days + 1):
|
||||
day = start + timedelta(days=offset)
|
||||
@@ -838,11 +1160,40 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start
|
||||
return {'days': len(series), 'start': start.isoformat(), 'end': end.isoformat(),
|
||||
'orders': total['orders'], 'cents': int(total['cents']), 'metres': float(total['metres']),
|
||||
'corrected': total['corrected'], 'daily': series,
|
||||
'treated': {'orders': treated_orders, 'by': [{'who': row['who'], 'orders': row['orders']} for row in treated]},
|
||||
'origins': [{'origin': name, 'orders': origins[name]['orders'] if name in origins else 0,
|
||||
'cents': int(origins[name]['cents']) if name in origins else 0,
|
||||
'metres': float(origins[name]['metres']) if name in origins else 0.0,
|
||||
'finished': origins[name]['finished'] if name in origins else 0,
|
||||
'median_hours': hours(origins[name]['median_hours']) if name in origins else None}
|
||||
for name in ORIGINS],
|
||||
'lead': {'orders': lead['orders'], 'median_hours': hours(lead['median_hours'])},
|
||||
'stages': {row['state']: {'orders': row['orders'], 'passages': row['passages'],
|
||||
'median_hours': hours(row['median_hours'])} for row in stages},
|
||||
'waiting': {row['state']: {'orders': row['orders'], 'oldest_hours': hours(row['oldest_hours'])} for row in waiting},
|
||||
'machines': printed}
|
||||
'machines': printed, 'rework': rework_figures(printed, redone, by_printer, undecided)}
|
||||
|
||||
|
||||
def rework_figures(printed, redone, by_printer, undecided):
|
||||
"""Números' rework: per cause, the metres redone over the film printed,
|
||||
against the goal; the house's total against four times it."""
|
||||
film = Decimal(str(sum(m['metres'] for m in printed)))
|
||||
share = lambda metres: float(round(100 * metres / film, 2)) if film else None
|
||||
causes = []
|
||||
for cause in HOUSE_CAUSES + (CUSTOMER_CAUSE,):
|
||||
row = redone.get(cause)
|
||||
metres = Decimal(row['metres']) if row else Decimal(0)
|
||||
causes.append({'cause': cause, 'metres': float(metres), 'orders': row['orders'] if row else 0,
|
||||
'percent': share(metres)})
|
||||
house = sum(Decimal(str(c['metres'])) for c in causes if c['cause'] != CUSTOMER_CAUSE)
|
||||
return {'film_metres': float(film), 'goal_percent': float(REWORK_GOAL_PERCENT),
|
||||
'house': {'metres': float(house), 'percent': share(house),
|
||||
'goal_percent': float(REWORK_GOAL_PERCENT * len(HOUSE_CAUSES))},
|
||||
'causes': causes,
|
||||
'by_printer': [{'who': row['who'], 'metres': float(row['metres'])} for row in by_printer],
|
||||
'pending': [{'id': row['id'], 'order_id': str(row['order_id']), 'number': row['number'],
|
||||
'cause': row['cause'], 'metres': float(row['metres']), 'opened_at': row['opened_at'].isoformat(),
|
||||
'opened_by': row['opened_name']} for row in undecided]}
|
||||
|
||||
|
||||
def machine_output(c, start, end):
|
||||
@@ -883,7 +1234,7 @@ def machine_output(c, start, end):
|
||||
'metres': made, 'printing_hours': round(hours_in, 2),
|
||||
'metres_per_hour': round(made / hours_in, 1) if hours_in > 0 else None,
|
||||
'last_finished': last[m['id']].isoformat() if m['id'] in last else None,
|
||||
'now': {state: m['states'].get(state, 0) for state in ('fil', 'imp')}})
|
||||
'now': {state: m['states'].get(state, 0) for state in ('tra', 'imp')}})
|
||||
loose = [row for row in done if row['machine_id'] is None]
|
||||
if loose:
|
||||
result.append({'id': None, 'name': 'Sem máquina', 'active': True, 'orders': len(loose),
|
||||
@@ -910,8 +1261,14 @@ def named_files(rows):
|
||||
readable, with a link straight to storage."""
|
||||
files, names = [], set()
|
||||
for row in rows:
|
||||
prefix = f"pedido-{row['number']}-item-{row['item_index'] + 1}"
|
||||
name = row['name'] if row['name'].startswith(prefix) else f"{prefix}-{row['name']}"
|
||||
prefix = file_prefix(row['number'], row['item_index'])
|
||||
# Generated before 2026-10-23, a file was called pedido-23-item-1.
|
||||
older = f"pedido-{row['number']}-item-{row['item_index'] + 1}"
|
||||
name = row['name']
|
||||
if name.startswith(older):
|
||||
name = prefix + name[len(older):]
|
||||
elif not name.startswith(prefix):
|
||||
name = f"{prefix}-{name}"
|
||||
stem, dot, ext = name.rpartition('.')
|
||||
copy = 2
|
||||
while name in names:
|
||||
@@ -924,40 +1281,53 @@ def named_files(rows):
|
||||
return files
|
||||
|
||||
|
||||
def print_ready(c, request, states):
|
||||
def print_ready(c, states, only=None, paid_after=None):
|
||||
"""The file to print for each item of the orders in these stages, in queue
|
||||
order: the approved final, or before approval the generated print file
|
||||
(unless the customer has sent a correction since). An operator who works
|
||||
on some machines gets only those machines' orders."""
|
||||
(unless the customer has sent a correction since). `only` narrows it to
|
||||
these orders, `paid_after` to the orders paid since then."""
|
||||
ids = None if only is None else list(only)
|
||||
rows = c.execute(f'''SELECT o.id AS order_id,o.state,o.number,f.item_index,f.upload_id,u.object_key,u.name,
|
||||
COALESCE(o.queue_key, extract(epoch FROM o.created_at)) AS position
|
||||
FROM dtf_local.orders o
|
||||
JOIN dtf_local.order_files f ON f.order_id=o.id JOIN dtf_local.uploads u ON u.id=f.upload_id
|
||||
WHERE o.state=ANY(%s) AND o.cancelled_at IS NULL AND {FINAL_OK}
|
||||
WHERE o.state=ANY(%s) AND (%s::uuid[] IS NULL OR o.id=ANY(%s))
|
||||
AND (%s::timestamptz IS NULL OR o.created_at>=%s) AND o.cancelled_at IS NULL AND {FINAL_OK}
|
||||
UNION ALL
|
||||
SELECT o.id,o.state,o.number,p.item_index,p.upload_id,u.object_key,u.name,
|
||||
COALESCE(o.queue_key, extract(epoch FROM o.created_at))
|
||||
FROM dtf_local.orders o
|
||||
JOIN dtf_local.print_files p ON p.order_id=o.id JOIN dtf_local.uploads u ON u.id=p.upload_id
|
||||
WHERE o.state=ANY(%s) AND o.state IN ('rec','tra') AND o.cancelled_at IS NULL AND p.status='ready'
|
||||
WHERE o.state=ANY(%s) AND (%s::uuid[] IS NULL OR o.id=ANY(%s))
|
||||
AND (%s::timestamptz IS NULL OR o.created_at>=%s) AND o.state IN ('rec','tra') AND o.cancelled_at IS NULL AND p.status='ready'
|
||||
AND u.expires_at>now() AND u.purged_at IS NULL AND u.scan_state='clean'
|
||||
AND NOT EXISTS (SELECT 1 FROM dtf_local.order_files f WHERE f.order_id=o.id AND f.kind='final'
|
||||
AND f.active AND f.item_index=p.item_index)
|
||||
AND NOT EXISTS (SELECT 1 FROM dtf_local.order_files f WHERE f.order_id=o.id AND f.kind='correction')
|
||||
ORDER BY position,order_id,item_index''', (list(states), list(states))).fetchall()
|
||||
staged = assign_machines(c, c.execute('''SELECT * FROM dtf_local.orders
|
||||
WHERE state=ANY(%s) AND cancelled_at IS NULL''', (list(states),)).fetchall())
|
||||
mine = {o['id'] for o in visible(request, staged)}
|
||||
return [row for row in rows if row['order_id'] in mine]
|
||||
ORDER BY position,order_id,item_index''',
|
||||
(list(states), ids, ids, paid_after, paid_after, list(states), ids, ids, paid_after, paid_after)).fetchall()
|
||||
return rows
|
||||
|
||||
|
||||
@router.get('/api/operator/orders/{uid}/folder-files')
|
||||
def folder_files(uid: UUID, user=Depends(can('produce'))):
|
||||
"""What each item's file is called in the order's stage folder, as the
|
||||
automatic folders save it: "Tratar a arte" shows where to open it."""
|
||||
with db.connect() as c:
|
||||
row = c.execute('SELECT state FROM dtf_local.orders WHERE id=%s', (uid,)).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(404, 'Pedido não encontrado.')
|
||||
files = named_files(print_ready(c, (row['state'],), only=[uid]))
|
||||
return {'state': row['state'], 'files': [{'item': f['item'], 'name': f['name']} for f in files]}
|
||||
|
||||
|
||||
@router.get('/api/operator/queue/finals')
|
||||
def queue_finals(request: Request, auto: bool = False, user=Depends(can('print'))):
|
||||
"""The approved final files of every order in the print queue. The browser
|
||||
downloads them straight from storage: a zip of multi-GB sheets would go
|
||||
through the server."""
|
||||
def queue_finals(auto: bool = False, user=Depends(can('print'))):
|
||||
"""The approved final files of every order in the print queue (Arte
|
||||
conferida). The browser downloads them straight from storage: a zip of
|
||||
multi-GB sheets would go through the server."""
|
||||
with db.connect() as c:
|
||||
files = named_files(print_ready(c, request, ('fil',)))
|
||||
files = named_files(print_ready(c, ('tra',)))
|
||||
# The automatic folder asks whenever the queue changes; only a person's download is logged.
|
||||
if not auto:
|
||||
audit('queue_finals_downloaded', operator=user, files=len(files))
|
||||
@@ -967,21 +1337,43 @@ def queue_finals(request: Request, auto: bool = False, user=Depends(can('print')
|
||||
class FolderSync(StrictModel):
|
||||
early: bool = False
|
||||
held: list[UUID] = Field(default_factory=list, max_length=1000)
|
||||
# When the folders were chosen: the orders paid since are fetched whatever
|
||||
# their stage, so what passed while the computer was off is not lost.
|
||||
since: datetime | None = None
|
||||
|
||||
|
||||
@router.post('/api/operator/queue/folder')
|
||||
def queue_folder(body: FolderSync, request: Request, user=Depends(can('print'))):
|
||||
"""What the Kanban's automatic folder should hold. Early, it also gets the
|
||||
files of orders just received (to a "Recebidos" folder), so a large sheet is
|
||||
already on the computer when the order reaches the queue. `states` answers
|
||||
for the orders the folder already holds files of: a stage, 'cancelled', or
|
||||
nothing when the order was deleted, so their files can be removed."""
|
||||
def queue_folder(body: FolderSync, user=Depends(can('print'))):
|
||||
"""What the Kanban's automatic folders should hold. `early` is Dropstar's
|
||||
stage folders (2026-10-26): the files of orders in Arte recebida and Arte
|
||||
conferida, and, for the orders the folders already hold, their files while
|
||||
they print, are checked in Revisão and sit in Finalizado, so one taken out
|
||||
of a folder can be fetched again when the order moves on. With `since`,
|
||||
also every order paid after the folders were chosen, whatever its stage:
|
||||
a computer that was off catches up on what passed meanwhile (Dropstar's
|
||||
rules, 2026-10-26). Without it, only
|
||||
the queue's (Firefox's downloads). `states` answers for the orders the
|
||||
folders hold files of: a stage, 'cancelled', or nothing when the order was
|
||||
deleted, so their files can be removed."""
|
||||
with db.connect() as c:
|
||||
files = named_files(print_ready(c, request, ('rec', 'tra', 'fil') if body.early else ('fil',)))
|
||||
rows = print_ready(c, ('rec', 'tra') if body.early else ('tra',))
|
||||
if body.early and body.held:
|
||||
rows += print_ready(c, ('imp', 'rev', 'fin'), only=body.held)
|
||||
if body.early and body.since:
|
||||
seen = {(r['order_id'], r['item_index'], r['upload_id']) for r in rows}
|
||||
rows += [r for r in print_ready(c, ('imp', 'rev', 'fin'), paid_after=body.since)
|
||||
if (r['order_id'], r['item_index'], r['upload_id']) not in seen]
|
||||
files = named_files(rows)
|
||||
held = c.execute('SELECT id,state,cancelled_at FROM dtf_local.orders WHERE id=ANY(%s)',
|
||||
(body.held,)).fetchall() if body.held else []
|
||||
# The pickup receipts no computer saved yet (item 14), due since the
|
||||
# folders were chosen: one that was off catches up, like the files.
|
||||
due = c.execute('''SELECT id, number FROM dtf_local.orders WHERE receipt_due_at IS NOT NULL
|
||||
AND receipt_saved_at IS NULL AND cancelled_at IS NULL AND (%s::timestamptz IS NULL OR receipt_due_at>=%s)
|
||||
ORDER BY receipt_due_at''', (body.since, body.since)).fetchall() if body.early else []
|
||||
return {'files': files,
|
||||
'states': {str(o['id']): 'cancelled' if o['cancelled_at'] else o['state'] for o in held}}
|
||||
'states': {str(o['id']): 'cancelled' if o['cancelled_at'] else o['state'] for o in held},
|
||||
'receipts': [{'order': str(o['id']), 'number': o['number'], 'name': receipt.file_name(o)} for o in due]}
|
||||
|
||||
|
||||
@router.get('/api/operator/uploads/{uid}/download')
|
||||
|
||||
@@ -34,5 +34,5 @@ def dev_paid(body: Pay, session_id=Depends(owner)):
|
||||
# The charge happens inside the transaction that persists the order, so a
|
||||
# failure to record it cannot leave a customer charged without an order.
|
||||
receipt = payment.pay(str(body.quote_id), quote['approved']['total_cents'])
|
||||
order, _ = payments.create_order(c, quote, receipt)
|
||||
order, _ = payments.create_order(c, quote, receipt, 'site')
|
||||
return order
|
||||
|
||||
@@ -43,10 +43,14 @@ def create_quote(body: QuoteRequest, session_id=Depends(owner)):
|
||||
row = upload_row(c, uid, session_id)
|
||||
if not row['complete']:
|
||||
raise HTTPException(409, 'Espere o envio de todos os arquivos terminar antes de continuar.')
|
||||
# No transparency: the background prints, and loose art packs as a box (2026-10-23).
|
||||
if row['name'].lower().endswith(('.jpg', '.jpeg')):
|
||||
raise HTTPException(422, 'JPG não tem fundo transparente. Envie a arte em PNG ou PDF.')
|
||||
require_clean(row)
|
||||
rows[str(uid)] = row
|
||||
# The grade sets the price and came from the browser: before a cart is
|
||||
# approved at checkout, the server works it out from the files.
|
||||
# The grade came from the browser and is shown with the order (it no
|
||||
# longer sets the price): before a cart is approved at checkout, the
|
||||
# server works it out from the files.
|
||||
note = mismatch(Files(storage), draft['items'], rows) if reason is None else None
|
||||
reason = reason or note
|
||||
uid = uuid4()
|
||||
|
||||
105
app/api/users.py
105
app/api/users.py
@@ -15,8 +15,10 @@ from pydantic import Field, field_validator
|
||||
|
||||
from .. import machines, mail
|
||||
from ..core import db
|
||||
from ..core.auth import CAPABILITIES, audit, can, password_hash, password_matches, signed_in
|
||||
from ..core.auth import (CAPABILITIES, MACHINE_QUESTION, audit, can, may_move, may_reorder, password_hash,
|
||||
password_matches, signed_in)
|
||||
from ..core.models import StrictModel
|
||||
from ..runtime import BACK, STATES, TRANSITIONS
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -24,9 +26,11 @@ class UserIn(StrictModel):
|
||||
# The profiles an administrator may give; superadmin only comes from the console.
|
||||
name: str = Field(min_length=1, max_length=80)
|
||||
email: str = Field(min_length=3, max_length=254)
|
||||
role: Literal['admin', 'gestao', 'designer', 'operador', 'vendedor']
|
||||
role: Literal['admin', 'gestao', 'designer', 'operador', 'revisor', 'vendedor', 'financeiro']
|
||||
password: str | None = Field(default=None, min_length=8, max_length=128)
|
||||
active: bool = True
|
||||
# No longer used: an operator's machine is the one chosen after signing in
|
||||
# (item 12). Kept so a page loaded before still saves.
|
||||
machines: list[UUID] = Field(default_factory=list, max_length=50)
|
||||
|
||||
@field_validator('email')
|
||||
@@ -44,7 +48,8 @@ class MachineIn(StrictModel):
|
||||
active: bool = True
|
||||
# Metres open before the next order goes to another machine; None is no limit.
|
||||
limit_metres: Decimal | None = Field(default=None, gt=0, le=99999, decimal_places=1)
|
||||
# The operators who work on it; None leaves them as they are.
|
||||
# No longer used (item 12): who is on a machine is who chose it after
|
||||
# signing in. Kept so a page loaded before still saves.
|
||||
operators: list[UUID] | None = Field(default=None, max_length=200)
|
||||
|
||||
|
||||
@@ -55,11 +60,58 @@ class PasswordChange(StrictModel):
|
||||
|
||||
@router.get('/api/operator/me')
|
||||
def me(request: Request):
|
||||
"""Who is signed in, and what the Kanban should offer them."""
|
||||
"""Who is signed in, and what the Kanban should offer them: the moves
|
||||
their profile makes (forward, and the step back) and the columns whose
|
||||
order they set."""
|
||||
account = signed_in(request)
|
||||
return {'email': account['email'], 'name': account['name'], 'role': account['role'],
|
||||
'machines': account['machines'],
|
||||
'can': sorted(cap for cap, roles in CAPABILITIES.items() if account['role'] in roles)}
|
||||
role = account['role']
|
||||
moves = [[a, b] for a, nexts in TRANSITIONS.items() for b in nexts if may_move(role, a, b)]
|
||||
moves += [[a, b] for a, b in BACK.items() if may_move(role, a, b, back=True)]
|
||||
return {'email': account['email'], 'name': account['name'], 'role': role,
|
||||
# The machine this session is on, and whether to ask (item 12).
|
||||
'machine': account['machine'], 'machine_question': MACHINE_QUESTION.get(role),
|
||||
'machine_answered': account['machine_answered'],
|
||||
'can': sorted(cap for cap, roles in CAPABILITIES.items() if role in roles),
|
||||
'moves': moves, 'reorder': [state for state in STATES if may_reorder(role, state)]}
|
||||
|
||||
|
||||
class MachineAnswer(StrictModel):
|
||||
# None: "Não estou em máquina", for the profiles that may say so.
|
||||
machine_id: UUID | None = None
|
||||
# Taken while someone else is on it: a shift change, not a mistake.
|
||||
confirm: bool = False
|
||||
|
||||
|
||||
@router.post('/api/operator/me/machine')
|
||||
def choose_session_machine(body: MachineAnswer, request: Request):
|
||||
"""The machine this session works on (Dropstar's third round, item 12):
|
||||
the operator's pulls go to it, and the history names it. Per session, so a
|
||||
person runs two machines from two computers. Someone else already on it is
|
||||
a warning, not a refusal: shifts overlap for a few minutes."""
|
||||
account = signed_in(request)
|
||||
question = MACHINE_QUESTION.get(account['role'])
|
||||
if not question:
|
||||
raise HTTPException(403, 'Seu perfil não trabalha em máquina.')
|
||||
with db.connect() as c:
|
||||
name = None
|
||||
if body.machine_id is None:
|
||||
if question == 'required':
|
||||
raise HTTPException(422, 'Escolha a máquina em que você está.')
|
||||
else:
|
||||
row = c.execute('SELECT name FROM dtf_local.machines WHERE id=%s AND active', (body.machine_id,)).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(404, 'Máquina não encontrada ou desligada.')
|
||||
name = row['name']
|
||||
others = [r['who'] for r in c.execute('''SELECT DISTINCT COALESCE(NULLIF(o.name,''), o.email) AS who
|
||||
FROM dtf_local.operator_sessions s JOIN dtf_local.operators o ON o.email=s.username AND o.active
|
||||
WHERE s.machine_id=%s AND s.expires_at>now() AND s.username<>%s ORDER BY 1''',
|
||||
(body.machine_id, account['email'])).fetchall()]
|
||||
if others and not body.confirm:
|
||||
raise HTTPException(409, f"{name} já tem {' e '.join(others)} ligado.")
|
||||
c.execute('''UPDATE dtf_local.operator_sessions SET machine_id=%s, machine_at=CASE WHEN %s THEN now() END,
|
||||
machine_answered=true WHERE token_hash=%s''', (body.machine_id, name is not None, account['session']))
|
||||
audit('operator_machine_chosen', operator=account['email'], machine=name or '')
|
||||
return {'machine': {'id': str(body.machine_id), 'name': name} if name else None}
|
||||
|
||||
|
||||
@router.post('/api/operator/me/password')
|
||||
@@ -75,9 +127,11 @@ def change_password(body: PasswordChange, request: Request):
|
||||
|
||||
|
||||
def user_rows(c):
|
||||
"""Every account, with the machines its open sessions are on now (item 12)."""
|
||||
rows = c.execute('''SELECT o.id,o.email,o.name,o.role,o.active,o.last_login_at,o.created_at,
|
||||
COALESCE(array_agg(m.machine_id) FILTER (WHERE m.machine_id IS NOT NULL), '{}') AS machines
|
||||
FROM dtf_local.operators o LEFT JOIN dtf_local.operator_machines m ON m.operator_id=o.id
|
||||
COALESCE(array_agg(DISTINCT s.machine_id) FILTER (WHERE s.machine_id IS NOT NULL), '{}') AS machines
|
||||
FROM dtf_local.operators o LEFT JOIN dtf_local.operator_sessions s
|
||||
ON s.username=o.email AND s.expires_at>now() AND s.machine_id IS NOT NULL
|
||||
GROUP BY o.id ORDER BY o.active DESC, o.name, o.email''').fetchall()
|
||||
for row in rows:
|
||||
row['machines'] = [str(m) for m in row['machines']]
|
||||
@@ -100,20 +154,6 @@ def target(c, uid, request):
|
||||
return row
|
||||
|
||||
|
||||
def set_machines(c, uid, chosen, role):
|
||||
"""An operator's machines. Only operators have them: they limit what an
|
||||
operator sees, and every other profile sees every order."""
|
||||
if role != 'operador':
|
||||
chosen = []
|
||||
known = {str(r['id']) for r in c.execute('SELECT id FROM dtf_local.machines WHERE id=ANY(%s)',
|
||||
([str(m) for m in chosen],)).fetchall()}
|
||||
if len(known) != len(set(map(str, chosen))):
|
||||
raise HTTPException(422, 'Uma das máquinas escolhidas não existe mais.')
|
||||
c.execute('DELETE FROM dtf_local.operator_machines WHERE operator_id=%s', (uid,))
|
||||
for machine in known:
|
||||
c.execute('INSERT INTO dtf_local.operator_machines(operator_id,machine_id) VALUES(%s,%s)', (uid, machine))
|
||||
|
||||
|
||||
@router.post('/api/operator/users')
|
||||
def create_user(body: UserIn, request: Request, user=Depends(can('users'))):
|
||||
if not body.password:
|
||||
@@ -125,7 +165,6 @@ def create_user(body: UserIn, request: Request, user=Depends(can('users'))):
|
||||
c.execute('''INSERT INTO dtf_local.operators(id,email,name,password_hash,role,active)
|
||||
VALUES(%s,%s,%s,%s,%s,%s)''', (uid, body.email, body.name.strip(), password_hash(body.password),
|
||||
body.role, body.active))
|
||||
set_machines(c, uid, body.machines, body.role)
|
||||
audit('operator_created', operator=user, account=body.email, role=body.role)
|
||||
return {'id': str(uid)}
|
||||
|
||||
@@ -151,7 +190,6 @@ def update_user(uid: UUID, body: UserIn, request: Request, user=Depends(can('use
|
||||
if not body.active or body.password:
|
||||
# Disabled, or given a new password: whoever was signed in signs in again.
|
||||
c.execute('DELETE FROM dtf_local.operator_sessions WHERE username=%s', (body.email,))
|
||||
set_machines(c, uid, body.machines, role)
|
||||
audit('operator_updated', operator=user, account=body.email, role=role, active=body.active,
|
||||
password_reset=bool(body.password))
|
||||
return {'ok': True}
|
||||
@@ -170,14 +208,10 @@ def delete_user(uid: UUID, request: Request, user=Depends(can('users'))):
|
||||
return {'ok': True}
|
||||
|
||||
|
||||
def set_operators(c, mid, operators):
|
||||
"""The machine's operators, from its own form. Other profiles are ignored."""
|
||||
if operators is None:
|
||||
return
|
||||
ids = [str(o) for o in operators]
|
||||
c.execute('DELETE FROM dtf_local.operator_machines WHERE machine_id=%s', (mid,))
|
||||
c.execute("""INSERT INTO dtf_local.operator_machines(operator_id,machine_id)
|
||||
SELECT id,%s FROM dtf_local.operators WHERE id=ANY(%s::uuid[]) AND role='operador'""", (mid, ids))
|
||||
def release_sessions(c, mid):
|
||||
"""Whoever was on a machine switched off or deleted is asked again."""
|
||||
c.execute('''UPDATE dtf_local.operator_sessions SET machine_id=NULL, machine_at=NULL, machine_answered=false
|
||||
WHERE machine_id=%s''', (mid,))
|
||||
|
||||
|
||||
@router.get('/api/operator/machines')
|
||||
@@ -194,7 +228,6 @@ def create_machine(body: MachineIn, user=Depends(can('users'))):
|
||||
raise HTTPException(409, 'Já existe uma máquina com este nome.')
|
||||
c.execute('INSERT INTO dtf_local.machines(id,name,products,active,limit_metres) VALUES(%s,%s,%s,%s,%s)',
|
||||
(mid, body.name.strip(), sorted(set(body.products)), body.active, body.limit_metres))
|
||||
set_operators(c, mid, body.operators)
|
||||
machines.route(c)
|
||||
audit('machine_created', operator=user, machine=body.name)
|
||||
return {'id': str(mid)}
|
||||
@@ -210,7 +243,8 @@ def update_machine(mid: UUID, body: MachineIn, user=Depends(can('users'))):
|
||||
WHERE id=%s RETURNING id''', (body.name.strip(), sorted(set(body.products)), body.active,
|
||||
body.limit_metres, mid)).fetchone():
|
||||
raise HTTPException(404, 'Máquina não encontrada.')
|
||||
set_operators(c, mid, body.operators)
|
||||
if not body.active:
|
||||
release_sessions(c, mid)
|
||||
machines.route(c)
|
||||
audit('machine_updated', operator=user, machine=body.name)
|
||||
return {'ok': True}
|
||||
@@ -220,6 +254,7 @@ def update_machine(mid: UUID, body: MachineIn, user=Depends(can('users'))):
|
||||
def delete_machine(mid: UUID, user=Depends(can('users'))):
|
||||
"""Its orders go back to the automatic choice; its operators lose it."""
|
||||
with db.connect() as c:
|
||||
release_sessions(c, mid)
|
||||
row = c.execute('DELETE FROM dtf_local.machines WHERE id=%s RETURNING name', (mid,)).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(404, 'Máquina não encontrada.')
|
||||
|
||||
@@ -50,8 +50,9 @@ def correction_owner(c, order, ref, kind):
|
||||
def submit_files(c, order, body, identity, kind, actor):
|
||||
if order['version'] != body.version:
|
||||
raise HTTPException(409, 'O pedido mudou. Atualize a página e envie de novo.')
|
||||
if kind == 'final' and order['state'] not in ('rec','tra','cor'):
|
||||
raise HTTPException(409, 'O arquivo final só pode mudar antes da fila de impressão.')
|
||||
# Arte conferida is the print queue (2026-10-23): what is in it keeps its finals.
|
||||
if kind == 'final' and order['state'] not in ('rec','cor'):
|
||||
raise HTTPException(409, 'O arquivo final só muda antes de Arte conferida, a fila. Volte o pedido para Arte recebida para trocar.')
|
||||
if kind == 'correction' and order['state'] != 'cor':
|
||||
raise HTTPException(409, 'Este pedido não está esperando correção.')
|
||||
if len({f.upload_id for f in body.files}) != len(body.files):
|
||||
@@ -66,7 +67,18 @@ def submit_files(c, order, body, identity, kind, actor):
|
||||
expiry = first + timedelta(days=30)
|
||||
if expiry <= datetime.now(timezone.utc):
|
||||
raise HTTPException(410, 'Os arquivos deste pedido expiraram (30 dias).')
|
||||
# A final already approved for its item may stay as it is beside a new
|
||||
# one for another item: "Tratar a arte" replaces only the item treated
|
||||
# (Dropstar, 2026-10-29). Something has to change, though.
|
||||
current = {(row['upload_id'], row['item_index']) for row in c.execute(
|
||||
"SELECT upload_id,item_index FROM dtf_local.order_files WHERE order_id=%s AND kind='final' AND active",
|
||||
(order['id'],)).fetchall()} if kind == 'final' else set()
|
||||
kept = {ref.upload_id for ref in body.files if (ref.upload_id, ref.item_index) in current}
|
||||
if kept and len(kept) == len(body.files):
|
||||
raise HTTPException(409, 'Estes já são os arquivos finais. Envie o arquivo novo.')
|
||||
for ref in body.files:
|
||||
if ref.upload_id in kept:
|
||||
continue
|
||||
corrected = correction_owner(c, order, ref, kind)
|
||||
upload = upload_row(c, ref.upload_id, corrected or generated_owner(c, order, ref, kind) or identity, lock=True)
|
||||
if not upload['complete']:
|
||||
@@ -83,6 +95,10 @@ def submit_files(c, order, body, identity, kind, actor):
|
||||
else:
|
||||
c.execute('UPDATE dtf_local.order_files SET active=false WHERE order_id=%s AND kind=%s', (order['id'],kind))
|
||||
for ref in body.files:
|
||||
if ref.upload_id in kept:
|
||||
c.execute("UPDATE dtf_local.order_files SET active=true WHERE order_id=%s AND upload_id=%s AND kind='final'",
|
||||
(order['id'], ref.upload_id))
|
||||
continue
|
||||
c.execute('INSERT INTO dtf_local.order_files(id,order_id,upload_id,item_index,kind,note,created_by) VALUES(%s,%s,%s,%s,%s,%s,%s)',
|
||||
(uuid4(),order['id'],ref.upload_id,ref.item_index,kind,body.note,actor))
|
||||
# The order's window, whatever the upload's own hold was.
|
||||
|
||||
BIN
app/assets/logo-dropstar.png
Normal file
BIN
app/assets/logo-dropstar.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 97 KiB |
@@ -121,18 +121,74 @@ def login_failed(email):
|
||||
# Integrações but the print room's folder (connecting Tiny, the checks, the
|
||||
# backup, the Tiny log): the others see there only what is on and off.
|
||||
# The designer approves and refuses artwork and asks for corrections, on every
|
||||
# order whatever its machine, and moves cards only among DESIGNER_STATES.
|
||||
ROLES = ('superadmin', 'admin', 'gestao', 'designer', 'operador', 'vendedor')
|
||||
DESIGNER_STATES = ('rec', 'tra', 'cor')
|
||||
# order whatever its machine. Which cards each profile moves is MOVES.
|
||||
ROLES = ('superadmin', 'admin', 'gestao', 'designer', 'operador', 'revisor', 'vendedor', 'financeiro')
|
||||
CAPABILITIES = {
|
||||
'view': set(ROLES),
|
||||
'produce': {'superadmin', 'admin', 'gestao', 'designer', 'operador'},
|
||||
'print': {'superadmin', 'admin', 'gestao', 'operador'},
|
||||
'manage': {'superadmin', 'admin', 'gestao'},
|
||||
# Registering an order paid outside the system, from its Site quote (D-35).
|
||||
# Not the seller: Vendedor only views the board (D-30).
|
||||
'enter': {'superadmin', 'admin', 'gestao'},
|
||||
# Rework (D-02): coordination opens it with its cause, an Administrador
|
||||
# (Thales or Alexandre) authorizes it.
|
||||
'rework': {'superadmin', 'gestao'},
|
||||
'authorize': {'superadmin', 'admin'},
|
||||
'users': {'superadmin', 'admin'},
|
||||
'integrations': {'superadmin'},
|
||||
# Financeiro (Dropstar, 2026-10-30): sees the board, Pagamentos, Números and
|
||||
# Cotações, and cancels an order with its reason; moves no card, touches no
|
||||
# file. Resolving a payment stays with "manage".
|
||||
'payments': {'superadmin', 'admin', 'gestao', 'financeiro'},
|
||||
'cancel': {'superadmin', 'admin', 'gestao', 'financeiro'},
|
||||
# "Retirado" at the counter (Dropstar's third round, item 14): everyone
|
||||
# but the seller, who only views (D-30). It includes everyone who produces,
|
||||
# so an operator upload (artwork.py) takes it for its parts.
|
||||
'deliver': {'superadmin', 'admin', 'gestao', 'designer', 'operador', 'revisor'},
|
||||
}
|
||||
|
||||
# Who moves which card (Dropstar's flow, 2026-10-23, and their rules of
|
||||
# 2026-10-26): the designer the artwork, the operator the printing, and the
|
||||
# Revisor to Finalizado, so nobody in the room releases their own print (D-29);
|
||||
# Admin, Dropstar's own login, may release too (the user, 2026-10-28), and we,
|
||||
# the superadmin, for support. Gestão, the coordination, pulls back and
|
||||
# never forward, always with a reason (D-20): a step back, or Correção. Admin,
|
||||
# Dropstar's own login, makes every other move. A step back undoes a mistaken
|
||||
# move: open to whoever may make the move it undoes.
|
||||
MOVES = {
|
||||
'designer': {('rec', 'tra'), ('rec', 'cor'), ('tra', 'cor'), ('cor', 'rec'), ('cor', 'tra')},
|
||||
'operador': {('tra', 'imp'), ('imp', 'rev')},
|
||||
'revisor': {('rev', 'fin')},
|
||||
}
|
||||
ADMINS = ('superadmin', 'admin')
|
||||
COORDINATION = ('gestao',)
|
||||
MANAGERS = ADMINS + COORDINATION
|
||||
RELEASERS = ('revisor', 'admin', 'superadmin')
|
||||
# Who is asked "Em qual máquina você está?" after signing in (Dropstar, 2026-10-30):
|
||||
# the operator must answer; Gestão and the administrators may say they are on
|
||||
# none. The other profiles are never asked.
|
||||
MACHINE_QUESTION = {'operador': 'required', 'gestao': 'optional', 'admin': 'optional'}
|
||||
MOVERS = MANAGERS + tuple(MOVES)
|
||||
|
||||
|
||||
def may_move(role, from_state, to_state, back=False):
|
||||
"""Whether this profile may move a card; `back` is the step back that
|
||||
undoes the move to_state -> from_state."""
|
||||
if back:
|
||||
return role in MANAGERS or (to_state, from_state) in MOVES.get(role, ())
|
||||
if to_state == 'fin':
|
||||
return role in RELEASERS
|
||||
if to_state == 'cor' and role in COORDINATION:
|
||||
return True
|
||||
return role in ADMINS or (from_state, to_state) in MOVES.get(role, ())
|
||||
|
||||
|
||||
def may_reorder(role, state):
|
||||
"""Changing a card's place in its column, the order it is worked in: for
|
||||
whoever takes cards forward out of it."""
|
||||
return role in MANAGERS or any(a == state and b != 'cor' for a, b in MOVES.get(role, ()))
|
||||
|
||||
|
||||
def signed_in(request: Request):
|
||||
"""The operator behind this session, active, with the profile read now: a
|
||||
@@ -142,14 +198,17 @@ def signed_in(request: Request):
|
||||
raise HTTPException(401, 'Entre no Kanban.')
|
||||
digest = hashlib.sha256(token.encode()).hexdigest()
|
||||
with connect() as c:
|
||||
row = c.execute('''SELECT o.id,o.email,o.name,o.role FROM dtf_local.operator_sessions s
|
||||
row = c.execute('''SELECT o.id,o.email,o.name,o.role,s.machine_answered,m.id AS machine_id,m.name AS machine_name
|
||||
FROM dtf_local.operator_sessions s
|
||||
JOIN dtf_local.operators o ON o.email=s.username AND o.active
|
||||
LEFT JOIN dtf_local.machines m ON m.id=s.machine_id
|
||||
WHERE s.token_hash=%s AND s.expires_at>now()''', (digest,)).fetchone()
|
||||
if row:
|
||||
row['machines'] = [str(r['machine_id']) for r in c.execute(
|
||||
'SELECT machine_id FROM dtf_local.operator_machines WHERE operator_id=%s', (row['id'],)).fetchall()]
|
||||
if not row:
|
||||
raise HTTPException(401, 'Sua sessão expirou. Entre de novo.')
|
||||
# The machine this session works on (item 12), or None.
|
||||
machine_id, machine_name = row.pop('machine_id'), row.pop('machine_name')
|
||||
row['machine'] = {'id': str(machine_id), 'name': machine_name} if machine_id else None
|
||||
row['session'] = digest
|
||||
request.state.operator = row
|
||||
return row
|
||||
|
||||
|
||||
@@ -10,4 +10,4 @@ def scan_limit_bytes():
|
||||
|
||||
|
||||
def upload_limit_bytes():
|
||||
return int(os.environ.get('MAX_UPLOAD_BYTES', '1073741824'))
|
||||
return int(os.environ.get('MAX_UPLOAD_BYTES', str(4 * 1024 ** 3)))
|
||||
|
||||
@@ -158,13 +158,17 @@ class Item(StrictModel):
|
||||
production: ProductionSpec
|
||||
quality_status: Literal['ok', 'warning', 'unverified']
|
||||
quality_acknowledged: bool
|
||||
# Residue dots under 2 mm the customer accepted printing on a ready sheet,
|
||||
# rather than erasing them (Dropstar, 2026-10-29): 0 when none.
|
||||
residue_accepted: int = Field(default=0, ge=0, le=1000000, strict=True)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def production_matches_uploads(self):
|
||||
if [source.upload_id for source in self.production.sources] != self.uploads:
|
||||
raise ValueError('Production sources must match uploaded files in order')
|
||||
is_sheet = self.mode in ('file', 'uvfile')
|
||||
film_width = Decimal('28.5') if self.mode in ('uvfile', 'uv') else Decimal('57')
|
||||
# UV is 27 cm wide (Dropstar, 2026-10-28; it was 28,5).
|
||||
film_width = Decimal('27') if self.mode in ('uvfile', 'uv') else Decimal('57')
|
||||
if self.production.film_width_cm != film_width:
|
||||
raise ValueError('Production film width does not match the product')
|
||||
for source in self.production.sources:
|
||||
@@ -172,6 +176,9 @@ class Item(StrictModel):
|
||||
raise ValueError('Production source does not fit the selected product')
|
||||
if is_sheet and (source.rotation_degrees or source.mirrored):
|
||||
raise ValueError('Finished sheets cannot be rotated or mirrored by the layout')
|
||||
# A textile transfer is pressed face down: mirrored, it prints backwards.
|
||||
if self.mode == 'avulsa' and source.mirrored:
|
||||
raise ValueError('Textile artwork cannot be mirrored')
|
||||
expected={(index,copy) for index,source in enumerate(self.production.sources)
|
||||
for copy in range(source.copies)}
|
||||
placed=set()
|
||||
@@ -204,6 +211,8 @@ class QuoteRequest(StrictModel):
|
||||
items: list[Item] = Field(min_length=1, max_length=30)
|
||||
freight: Freight
|
||||
destination: Destination | None = None
|
||||
# "Quero aprovar uma prova antes de imprimir": the order waits for the customer.
|
||||
proof: bool = False
|
||||
|
||||
@model_validator(mode='after')
|
||||
def destination_matches_freight(self):
|
||||
@@ -252,7 +261,7 @@ class PaymentIntent(StrictModel):
|
||||
method: PaymentMethod
|
||||
|
||||
class Move(StrictModel):
|
||||
state: Literal['rec','tra','fil','imp','cor','fin']
|
||||
state: Literal['rec','tra','imp','cor','rev','fin']
|
||||
version: int = Field(ge=0)
|
||||
reason: str = Field(default='', max_length=1000)
|
||||
|
||||
|
||||
@@ -1,23 +1,19 @@
|
||||
"""Exact approved Site DTF price ladders; integer BRL cents at the boundary.
|
||||
"""Dropstar's single price per metre for each product; integer BRL cents at the boundary.
|
||||
|
||||
Quantity/grade must be supplied by an authenticated commercial reviewer.
|
||||
This module does not inspect artwork or perform pre-flight.
|
||||
One price per product (Dropstar, 2026-10-23). The grade is still recorded with
|
||||
each item, for the customer and the print room, but it no longer changes the
|
||||
price. This module does not inspect artwork or perform pre-flight.
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
from decimal import Decimal, ROUND_CEILING
|
||||
|
||||
TIERS = {
|
||||
'file': [(90,1490),(75,1620),(60,1750),(40,1870),(0,1990)],
|
||||
'avulsa': [(90,2490),(75,2620),(60,2750),(40,2870),(0,2990)],
|
||||
'uvfile': [(90,6990),(75,7390),(60,7790),(40,8190),(0,8590)],
|
||||
'uv': [(90,8390),(75,8790),(60,9190),(40,9590),(0,9990)],
|
||||
}
|
||||
PRICES = {'file': 1990, 'avulsa': 2190, 'uvfile': 7990, 'uv': 8990}
|
||||
|
||||
# A finished sheet the Site cannot open (CDR, AI, PSD, TIFF) is opened by a
|
||||
# person before printing. It is priced at the top of the ladder, plus this per
|
||||
# metre when the business sets it, to make the formats the robot reads the
|
||||
# cheaper path. Zero (the default) adds nothing.
|
||||
# person before printing. It pays this per metre on top of the product's price
|
||||
# when the business sets it, to make the formats the robot reads the cheaper
|
||||
# path. Zero adds nothing.
|
||||
MANUAL_FORMATS = re.compile(r'\.(cdr|ai|psd|psb|tiff?)$', re.I)
|
||||
|
||||
|
||||
@@ -37,21 +33,20 @@ def is_manual(item, names) -> bool:
|
||||
|
||||
|
||||
def price(mode: str, metres: str, grade: int, extra_cents: int = 0) -> dict:
|
||||
"""The item's charge. The grade is validated and kept with the item; the
|
||||
price does not depend on it."""
|
||||
length = Decimal(str(metres))
|
||||
if mode not in TIERS or not length.is_finite() or not 0 < length <= 12000:
|
||||
if mode not in PRICES or not length.is_finite() or not 0 < length <= 12000:
|
||||
raise ValueError('Invalid product or length')
|
||||
if isinstance(grade, bool) or not isinstance(grade, int) or not 0 <= grade <= 100:
|
||||
raise ValueError('Grade must be an integer between 0 and 100')
|
||||
billed = max(Decimal('1'), (length * 10).to_integral_value(rounding=ROUND_CEILING) / 10)
|
||||
if isinstance(extra_cents, bool) or not isinstance(extra_cents, int) or extra_cents < 0:
|
||||
raise ValueError('Invalid extra charge')
|
||||
tier = next(cents for minimum, cents in TIERS[mode] if grade >= minimum)
|
||||
unit = tier + extra_cents
|
||||
unit = PRICES[mode] + extra_cents
|
||||
priced = {'mode': mode, 'metres': str(length), 'grade': grade,
|
||||
'billed_metres': str(billed), 'unit_cents': unit,
|
||||
'total_cents': int(billed * unit),
|
||||
'discount_cents': int(billed * (TIERS[mode][-1][1] - tier))}
|
||||
'total_cents': int(billed * unit)}
|
||||
if extra_cents:
|
||||
priced['manual_extra_cents'] = extra_cents
|
||||
return priced
|
||||
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
"""The grade (the resolution discount) recomputed from the uploaded files.
|
||||
"""The grade recomputed from the uploaded files.
|
||||
|
||||
The Site grades the art in the customer's browser and sends the grade with the
|
||||
cart, and the price depends on it. A customer who edits the page could claim a
|
||||
better grade, so before a cart is approved at checkout the server reads the
|
||||
files it already has and works the grade out again, by the Site's own rules:
|
||||
cart. The price no longer depends on it (one price per product, 2026-10-23),
|
||||
but the grade is shown with the order on the Kanban and in Tiny. A customer
|
||||
who edits the page could claim a better grade, so before a cart is approved at
|
||||
checkout the server reads the files it already has and works the grade out
|
||||
again, by the Site's own rules:
|
||||
|
||||
- a finished sheet: its pixel width over the sheet width is its DPI, and the
|
||||
item's grade comes from the worst sheet (web/site-quality.js);
|
||||
@@ -180,7 +182,7 @@ def mismatch(files, items, rows):
|
||||
"""Why a cart's grades cannot be approved at checkout, or None."""
|
||||
for item in items:
|
||||
if item['grade'] == 0:
|
||||
continue # full price: nothing to verify
|
||||
continue # no grade claimed: nothing to verify
|
||||
verified = item_grade(files, item, rows)
|
||||
if verified is None:
|
||||
return 'Nota não conferida no servidor'
|
||||
|
||||
@@ -10,11 +10,15 @@ orders back to that choice, unless they are already printing.
|
||||
from decimal import Decimal
|
||||
|
||||
# Not finished: the work still ahead of a machine.
|
||||
OPEN = ('rec', 'tra', 'fil', 'imp', 'cor')
|
||||
OPEN = ('rec', 'tra', 'imp', 'cor')
|
||||
# Stages an automatic order may still move from: not once it is printing.
|
||||
MOVABLE = ('rec', 'tra', 'fil', 'cor')
|
||||
MOVABLE = ('rec', 'tra', 'cor')
|
||||
# One routing at a time, so two at once cannot both pick the same "least loaded".
|
||||
LOCK = 7_041_901
|
||||
# Two orders at most in Imprimindo per machine (Dropstar, 2026-10-29): one
|
||||
# printing, the next being ripped by FlexiPRINT meanwhile. A third would
|
||||
# make the RIP choke; two mean the next sheet is ready when one ends.
|
||||
PRINTING_CAP = 2
|
||||
|
||||
|
||||
def product_family(order):
|
||||
@@ -90,9 +94,13 @@ def rows(c, with_operators=False):
|
||||
load = loads(c)
|
||||
operators = {}
|
||||
if with_operators:
|
||||
for r in c.execute('''SELECT om.machine_id, o.id, o.name, o.email FROM dtf_local.operator_machines om
|
||||
JOIN dtf_local.operators o ON o.id=om.operator_id ORDER BY o.name, o.email''').fetchall():
|
||||
operators.setdefault(str(r['machine_id']), []).append({'id': str(r['id']), 'name': r['name'] or r['email']})
|
||||
# Who is on it now: the open sessions that chose it (item 12).
|
||||
for r in c.execute('''SELECT DISTINCT ON (s.machine_id, o.id) s.machine_id, o.id, o.name, o.email, s.machine_at
|
||||
FROM dtf_local.operator_sessions s JOIN dtf_local.operators o ON o.email=s.username AND o.active
|
||||
WHERE s.machine_id IS NOT NULL AND s.expires_at>now()
|
||||
ORDER BY s.machine_id, o.id, s.machine_at''').fetchall():
|
||||
operators.setdefault(str(r['machine_id']), []).append(
|
||||
{'id': str(r['id']), 'name': r['name'] or r['email'], 'since': r['machine_at']})
|
||||
result = []
|
||||
for m in machines:
|
||||
key = str(m['id'])
|
||||
@@ -104,3 +112,26 @@ def rows(c, with_operators=False):
|
||||
row['operators'] = operators.get(key, [])
|
||||
result.append(row)
|
||||
return result
|
||||
|
||||
|
||||
def full(c, machine_id, order_id):
|
||||
"""The machine's name when it already has PRINTING_CAP other orders in
|
||||
Imprimindo, so this one cannot join them; None when it has room. The
|
||||
machine's row is locked, so two pulls at once cannot both take the last
|
||||
place."""
|
||||
if machine_id is None:
|
||||
return None
|
||||
machine = c.execute('SELECT name FROM dtf_local.machines WHERE id=%s FOR UPDATE', (machine_id,)).fetchone()
|
||||
printing = c.execute('''SELECT count(*) AS n FROM dtf_local.orders WHERE machine_id=%s AND state='imp'
|
||||
AND cancelled_at IS NULL AND id<>%s''', (machine_id, order_id)).fetchone()['n']
|
||||
return machine['name'] if machine and printing >= PRINTING_CAP else None
|
||||
|
||||
|
||||
def printing_slots(c):
|
||||
"""Per order in Imprimindo: 'imprimindo' for the first to enter it on its
|
||||
machine (ripped, running), 'ripando' for the one after it."""
|
||||
return {row['id']: 'imprimindo' if row['place'] == 1 else 'ripando' for row in c.execute('''
|
||||
SELECT o.id, row_number() OVER (PARTITION BY o.machine_id ORDER BY m.at, o.number) AS place
|
||||
FROM dtf_local.orders o, LATERAL (SELECT max(created_at) AS at FROM dtf_local.movements
|
||||
WHERE order_id=o.id AND to_state='imp') m
|
||||
WHERE o.state='imp' AND o.cancelled_at IS NULL AND o.machine_id IS NOT NULL''').fetchall()}
|
||||
|
||||
@@ -16,7 +16,7 @@ from uuid import UUID, uuid4
|
||||
|
||||
from psycopg.types.json import Jsonb
|
||||
|
||||
from . import machines, mail
|
||||
from . import machines, mail, proof
|
||||
from .core.auth import audit
|
||||
from .core.models import PRODUCTION_VERSIONS
|
||||
from .printjobs import queue as queue_print_files
|
||||
@@ -55,6 +55,19 @@ def is_test(order):
|
||||
return (order.get('payment') or {}).get('provider') == TEST_PROVIDER
|
||||
|
||||
|
||||
# An order paid outside the system (Pix or cash at the counter, a card machine,
|
||||
# the customer's credit) and registered by the team from its Site quote
|
||||
# (Dropstar's rule D-35, 2026-10-26; the user's answers of 2026-10-27).
|
||||
MANUAL_PROVIDER = 'manual'
|
||||
OUTSIDE_METHODS = ('pix', 'card', 'cash', 'credit')
|
||||
|
||||
|
||||
def in_tiny(order):
|
||||
"""Whether the order goes to Tiny: every order but a test. A Dropflow
|
||||
order goes in its own revenue category (app/tiny.py, CATEGORIES)."""
|
||||
return not is_test(order)
|
||||
|
||||
|
||||
# How long a file is kept while nothing has been paid for it. A cart's files
|
||||
# are uploaded before payment, so the price and the security check are done on
|
||||
# the file itself; a cart that is never paid must not keep them for 30 days.
|
||||
@@ -75,8 +88,9 @@ def hold_uploads(c, upload_ids, interval):
|
||||
WHERE id=ANY(%s) AND purged_at IS NULL''', (interval, [str(u) for u in upload_ids]))
|
||||
|
||||
|
||||
def create_order(c, quote, payment):
|
||||
def create_order(c, quote, payment, origin):
|
||||
"""Create the order for a reviewed quote, or return the one already there.
|
||||
`origin` is where it came from (D-21): each way in names its own.
|
||||
|
||||
Returns (order, created). The caller decides what to do about a duplicate;
|
||||
the important part is that asking twice cannot produce two orders, because
|
||||
@@ -92,23 +106,34 @@ def create_order(c, quote, payment):
|
||||
require_clean(upload_row(c, UUID(upload_id), quote['owner']))
|
||||
|
||||
order = c.execute(
|
||||
'INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment) VALUES(%s,%s,%s,%s,%s) RETURNING *',
|
||||
(uuid4(), quote['id'], quote['owner'], Jsonb(approved), Jsonb(payment))).fetchone()
|
||||
'''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,origin)
|
||||
VALUES(%s,%s,%s,%s,%s,%s) RETURNING *''',
|
||||
(uuid4(), quote['id'], quote['owner'], Jsonb(approved), Jsonb(payment), origin)).fetchone()
|
||||
# Paid: the files are kept for the order's retention, counted from upload.
|
||||
c.execute('''UPDATE dtf_local.uploads SET expires_at=GREATEST(expires_at, created_at+%s::interval)
|
||||
WHERE id=ANY(%s) AND purged_at IS NULL''', (ORDER_RETENTION, quote_uploads(approved)))
|
||||
queue_print_files(c, order['id'], len(approved['items']))
|
||||
if approved.get('proof'):
|
||||
# The customer asked for a proof: the order waits for their word.
|
||||
order = c.execute('''UPDATE dtf_local.orders SET contact_since=now(), contact_by='Site', contact_note=%s
|
||||
WHERE id=%s RETURNING *''', (proof.CUSTOMER_NOTE, order['id'])).fetchone()
|
||||
c.execute('INSERT INTO dtf_local.contact_waits(order_id, started_at) VALUES(%s, now())', (order['id'],))
|
||||
machines.route(c)
|
||||
if is_test(order):
|
||||
return order, True
|
||||
mail.order_paid(c, order, PUBLIC_ORIGIN)
|
||||
if not in_tiny(order):
|
||||
return order, True
|
||||
# How it was paid, for the order's payment in Tiny.
|
||||
paid = c.execute('''SELECT method FROM dtf_local.payment_intents WHERE quote_id=%s AND status='approved'
|
||||
ORDER BY created_at DESC LIMIT 1''', (quote['id'],)).fetchone()
|
||||
if payment.get('provider') == MANUAL_PROVIDER:
|
||||
paid = {'method': payment['method'], 'outside': True}
|
||||
else:
|
||||
paid = c.execute('''SELECT method FROM dtf_local.payment_intents WHERE quote_id=%s AND status='approved'
|
||||
ORDER BY created_at DESC LIMIT 1''', (quote['id'],)).fetchone()
|
||||
enqueue(c, f"{order['id']}:paid:tiny", 'tiny',
|
||||
{'order_id': str(order['id']), 'number': order['number'],
|
||||
'event': 'payment_approved', 'order': approved,
|
||||
'payment': {'method': paid['method']} if paid else {}})
|
||||
'event': 'payment_approved', 'order': approved, 'origin': origin,
|
||||
'payment': dict(paid) if paid else {}})
|
||||
return order, True
|
||||
|
||||
|
||||
@@ -165,7 +190,7 @@ def apply(c, event):
|
||||
expected_cents=expected, paid_cents=event.amount_cents)
|
||||
return f'refused: paid {event.amount_cents} but quote total is {expected}'
|
||||
|
||||
order, created = create_order(c, quote, {'provider': event.raw.get('provider', 'webhook'), **event.raw})
|
||||
order, created = create_order(c, quote, {'provider': event.raw.get('provider', 'webhook'), **event.raw}, 'site')
|
||||
return f"order {order['number']}" + ('' if created else ' (already existed)')
|
||||
|
||||
|
||||
|
||||
110
app/printfile.py
110
app/printfile.py
@@ -29,9 +29,20 @@ from PIL import Image, ImageOps
|
||||
from .core.models import PRODUCTION_VERSIONS
|
||||
|
||||
PT_PER_CM = 72 / 2.54
|
||||
# Acrobat's page limit. Longer layouts scale user space with /UserUnit (PDF 1.6)
|
||||
# rather than cutting the film into pages a RIP might print with gaps.
|
||||
# Acrobat's page limit, 200 inches (5,08 m). A longer sheet is written at its
|
||||
# real size, on one page: CorelDRAW, where Dropstar checks the files, ignores
|
||||
# /UserUnit and showed a 12,8 m sheet at a third of its size (2026-10-28).
|
||||
# PRINT_PAGE_SCALE=true goes back to scaling user space with /UserUnit (PDF
|
||||
# 1.6), for software that refuses pages over the limit. Either way the film is
|
||||
# never cut into pages a RIP might print with gaps.
|
||||
MAX_PAGE_PT = 14400
|
||||
|
||||
|
||||
def page_unit(width_pt, height_pt):
|
||||
"""The page's /UserUnit: 1 (real size) unless PRINT_PAGE_SCALE is on."""
|
||||
if os.environ.get('PRINT_PAGE_SCALE', 'false').strip().lower() != 'true':
|
||||
return 1
|
||||
return max(1, math.ceil(max(width_pt, height_pt) / MAX_PAGE_PT))
|
||||
# How far a file's proportions may drift from the quoted size before the item
|
||||
# is refused: rounding in the Site keeps real files well inside this.
|
||||
ASPECT_TOLERANCE = 0.01
|
||||
@@ -396,10 +407,78 @@ def check_layout(item, sizes, vector=()):
|
||||
return lowest
|
||||
|
||||
|
||||
def render(item, files, out, title):
|
||||
# The footer (Dropstar, 2026-10-21): a 1,5 cm band after the last piece with one
|
||||
# line of black text on no background, saying which order, item, date and length
|
||||
# the sheet is, so a sheet cut off or dropped in the room is still known. The band
|
||||
# is outside the billed length: the page grows by it and never covers artwork.
|
||||
FOOTER_CM = Decimal('1.5')
|
||||
# The line about 1 cm tall, from the top of a "d" to the bottom of a "p"
|
||||
# (Dropstar, 2026-10-28; it was 18 pt, about 0,6 cm), smaller only when the
|
||||
# line would not fit the film's width (the 27 cm UV).
|
||||
FOOTER_PT = 31
|
||||
FOOTER_FONTS = {'F1': 'Helvetica-Bold', 'F2': 'Helvetica'}
|
||||
# Helvetica's widths (thousandths of the size), regular and bold, for the
|
||||
# characters the line uses; anything else counts as wide.
|
||||
_HELVETICA = dict(zip(' ,-./0123456789:ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\xb7',
|
||||
[278, 278, 333, 278, 278] + [556] * 10 + [278] +
|
||||
[667, 667, 722, 722, 667, 611, 778, 722, 278, 500, 667, 556, 833, 722, 778, 667, 778, 722, 667, 611,
|
||||
722, 667, 944, 667, 667, 611] +
|
||||
[556, 556, 500, 556, 556, 278, 556, 556, 222, 222, 500, 222, 833, 556, 556, 556, 556, 333, 500, 278,
|
||||
556, 500, 722, 500, 500, 500] + [278]))
|
||||
_HELVETICA_BOLD = dict(zip(' ,-./0123456789:ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\xb7',
|
||||
[278, 278, 333, 278, 278] + [556] * 10 + [333] +
|
||||
[722, 722, 722, 722, 667, 611, 778, 722, 278, 556, 722, 611, 833, 722, 778, 667, 778, 722, 667, 611,
|
||||
722, 667, 944, 667, 667, 611] +
|
||||
[556, 611, 556, 611, 556, 333, 611, 611, 278, 278, 556, 278, 889, 611, 611, 611, 611, 389, 556, 333,
|
||||
611, 556, 778, 556, 556, 500] + [278]))
|
||||
|
||||
|
||||
def text_width(text, bold=False):
|
||||
"""The width of `text` in Helvetica at size 1, in points."""
|
||||
widths = _HELVETICA_BOLD if bold else _HELVETICA
|
||||
return sum(widths.get(ch, 1000) for ch in text) / 1000
|
||||
# Dropstar's logo (sent 2026-10-23): black on transparent, so no white base is
|
||||
# printed around it. It takes the place of the brand's name at the line's start.
|
||||
FOOTER_LOGO = os.path.join(os.path.dirname(__file__), 'assets', 'logo-dropstar.png')
|
||||
FOOTER_LOGO_CM = 1.3
|
||||
|
||||
|
||||
def footer_commands(text, logo_size=None, width_pt=57 * PT_PER_CM):
|
||||
"""The footer's line, 0,5 cm from the left: the logo then the rest, or,
|
||||
without a logo, the line's first part (the brand) in bold. It is
|
||||
FOOTER_PT, or less when that would not fit `width_pt`, the film."""
|
||||
brand, _, rest = text.partition(' · ')
|
||||
# A warning closing the line (ESPELHADO) goes in bold.
|
||||
rest, mark, _ = rest.rpartition(' · ESPELHADO') if rest.endswith(' · ESPELHADO') else (rest, '', '')
|
||||
def literal(value):
|
||||
raw = value.encode('cp1252', 'replace')
|
||||
return b'(' + raw.replace(b'\\', b'\\\\').replace(b'(', b'\\(').replace(b')', b'\\)') + b')'
|
||||
def sized(room, line):
|
||||
fit = room / max(sum(text_width(part, bold) for part, bold in line), 1e-9)
|
||||
return int(min(FOOTER_PT, fit))
|
||||
x = 0.5 * PT_PER_CM
|
||||
if logo_size:
|
||||
height = FOOTER_LOGO_CM * PT_PER_CM
|
||||
width = height * logo_size[0] / logo_size[1]
|
||||
start = x + width + 0.4 * PT_PER_CM
|
||||
size = sized(width_pt - start - x, [(rest, False), (mark, True)])
|
||||
y = (float(FOOTER_CM) * PT_PER_CM - size * 0.7) / 2
|
||||
bottom = (float(FOOTER_CM) * PT_PER_CM - height) / 2
|
||||
return (b'q %s 0 0 %s %s %s cm /Logo Do Q\n' % (serialize(width), serialize(height), serialize(x), serialize(bottom))
|
||||
+ b'q 0 g BT /F2 %d Tf %s %s Td %s Tj /F1 %d Tf %s Tj ET Q\n'
|
||||
% (size, serialize(start), serialize(y), literal(rest), size, literal(mark)))
|
||||
middle = ' · ' + rest if rest else ''
|
||||
size = sized(width_pt - 2 * x, [(brand, True), (middle, False), (mark, True)])
|
||||
y = (float(FOOTER_CM) * PT_PER_CM - size * 0.7) / 2
|
||||
return (b'q 0 g BT /F1 %d Tf %s %s Td %s Tj /F2 %d Tf %s Tj /F1 %d Tf %s Tj ET Q\n'
|
||||
% (size, serialize(x), serialize(y), literal(brand), size, literal(middle), size, literal(mark)))
|
||||
|
||||
|
||||
def render(item, files, out, title, footer=None):
|
||||
"""Write the PDF for one approved order item.
|
||||
|
||||
`files` maps each source index to (local path, original name). Returns the
|
||||
`files` maps each source index to (local path, original name). With
|
||||
`footer`, the page gets the footer band and that line in it. Returns the
|
||||
evidence the Kanban shows: page size, what was billed, and the lowest DPI.
|
||||
|
||||
Raster sources are written by the streaming writer above. PDF sources are
|
||||
@@ -418,12 +497,13 @@ def render(item, files, out, title):
|
||||
lowest_dpi = check_layout(item, [source.size for source in sources], vector)
|
||||
|
||||
width_pt = float(production['film_width_cm']) * PT_PER_CM
|
||||
height_pt = float(production['height_cm']) * PT_PER_CM
|
||||
unit = max(1, math.ceil(max(width_pt, height_pt) / MAX_PAGE_PT))
|
||||
page_cm = Decimal(str(production['height_cm'])) + (FOOTER_CM if footer else 0)
|
||||
height_pt = float(page_cm) * PT_PER_CM
|
||||
unit = page_unit(width_pt, height_pt)
|
||||
|
||||
first = tempfile.TemporaryFile() if vector else out
|
||||
try:
|
||||
write_rasters(production, sources, first, title, width_pt, height_pt, unit)
|
||||
write_rasters(production, sources, first, title, width_pt, height_pt, unit, footer)
|
||||
if vector:
|
||||
first.seek(0)
|
||||
add_vector_pages(production, sources, first, out, height_pt)
|
||||
@@ -435,6 +515,8 @@ def render(item, files, out, title):
|
||||
source.close()
|
||||
return {'film_width_cm': str(production['film_width_cm']),
|
||||
'height_cm': str(production['height_cm']),
|
||||
'page_height_cm': str(page_cm),
|
||||
'footer': footer,
|
||||
'billed_metres': str(item['billed_metres']),
|
||||
'placements': len(production['placements']),
|
||||
'sources': len(sources),
|
||||
@@ -443,7 +525,7 @@ def render(item, files, out, title):
|
||||
'user_unit': unit}
|
||||
|
||||
|
||||
def write_rasters(production, sources, out, title, width_pt, height_pt, unit):
|
||||
def write_rasters(production, sources, out, title, width_pt, height_pt, unit, footer=None):
|
||||
pdf = PdfWriter(out)
|
||||
images = {index: source.embed(pdf) for index, source in enumerate(sources)
|
||||
if isinstance(source, SourceImage)}
|
||||
@@ -456,12 +538,20 @@ def write_rasters(production, sources, out, title, width_pt, height_pt, unit):
|
||||
matrix = placement_matrix(placement, height_pt)
|
||||
commands.append(b'q ' + b' '.join(serialize(v) for v in matrix) +
|
||||
b' cm /Im%d Do Q\n' % placement['source_index'])
|
||||
resources = {'XObject': {f'Im{index}': ref for index, ref in images.items()}}
|
||||
if footer:
|
||||
logo = SourceImage(FOOTER_LOGO, 'logo') if os.path.exists(FOOTER_LOGO) else None
|
||||
if logo:
|
||||
resources['XObject']['Logo'] = logo.embed(pdf)
|
||||
logo.close()
|
||||
commands.append(footer_commands(footer, logo.size if logo else None, width_pt))
|
||||
resources['Font'] = {key: {'Type': Name('Font'), 'Subtype': Name('Type1'), 'BaseFont': Name(font),
|
||||
'Encoding': Name('WinAnsiEncoding')} for key, font in FOOTER_FONTS.items()}
|
||||
content = pdf.stream({'Filter': Name('FlateDecode')}, deflate(commands))
|
||||
pages = pdf.alloc()
|
||||
page_box = [0, 0, width_pt / unit, height_pt / unit]
|
||||
page = {'Type': Name('Page'), 'Parent': pages, 'MediaBox': page_box, 'TrimBox': page_box,
|
||||
'Resources': {'XObject': {f'Im{index}': ref for index, ref in images.items()}},
|
||||
'Contents': content}
|
||||
'Resources': resources, 'Contents': content}
|
||||
if unit > 1:
|
||||
page['UserUnit'] = unit
|
||||
page_ref = pdf.obj(page)
|
||||
|
||||
@@ -21,6 +21,8 @@ import os
|
||||
import tempfile
|
||||
import time
|
||||
from datetime import timedelta
|
||||
from decimal import Decimal
|
||||
from zoneinfo import ZoneInfo
|
||||
from uuid import NAMESPACE_URL, UUID, uuid4, uuid5
|
||||
|
||||
from psycopg.types.json import Jsonb
|
||||
@@ -28,6 +30,9 @@ from psycopg.types.json import Jsonb
|
||||
from .core.auth import audit
|
||||
from .core.db import connect
|
||||
from .printfile import Unsupported, render
|
||||
from .tiny import purchase_order
|
||||
|
||||
LOCAL = ZoneInfo('America/Sao_Paulo')
|
||||
|
||||
CLAIM_TIMEOUT = timedelta(minutes=15)
|
||||
MAX_ATTEMPTS = 3
|
||||
@@ -55,7 +60,7 @@ def queue(c, order_id, items, only_missing=False):
|
||||
|
||||
|
||||
def claim(c):
|
||||
return c.execute('''SELECT p.*, o.snapshot, o.number FROM dtf_local.print_files p
|
||||
return c.execute('''SELECT p.*, o.snapshot, o.number, o.created_at AS ordered_at FROM dtf_local.print_files p
|
||||
JOIN dtf_local.orders o ON o.id=p.order_id
|
||||
WHERE p.status='pending' OR (p.status='rendering' AND p.claimed_at < now()-%s)
|
||||
ORDER BY p.created_at FOR UPDATE OF p SKIP LOCKED LIMIT 1''', (CLAIM_TIMEOUT,)).fetchone()
|
||||
@@ -137,6 +142,29 @@ def whole_sheet(item, uploads):
|
||||
return row
|
||||
|
||||
|
||||
def file_prefix(number, item_index):
|
||||
"""How an order's files are named: DTF-23-item-1, the code the Kanban
|
||||
copies, the footer prints and Tiny keeps (Dropstar, 2026-10-23)."""
|
||||
return f'DTF-{number}-item-{item_index + 1}'
|
||||
|
||||
|
||||
def footer(job, item):
|
||||
"""The print file's footer line: DROPSTAR · Pedido DTF-123 · Item 1/2 ·
|
||||
21/10/2026 · 0,90 m, and · ESPELHADO when the artwork is mirrored. The
|
||||
order is named by its Kanban number, which Tiny keeps; the length is the
|
||||
one billed."""
|
||||
count = len(job['snapshot']['items'])
|
||||
day = job['ordered_at'].astimezone(LOCAL).strftime('%d/%m/%Y')
|
||||
billed = f"{Decimal(str(item['billed_metres'])):.2f}".replace('.', ',')
|
||||
fields = ['DROPSTAR', f'Pedido {purchase_order(job["number"])}',
|
||||
f'Item {job["item_index"] + 1}/{count}', day, f'{billed} m']
|
||||
# A mirrored artwork (UV only) is named on the sheet, for the room to see
|
||||
# before printing (Dropstar, 2026-10-23).
|
||||
if any(source.get('mirrored') for source in item['production']['sources']):
|
||||
fields.append('ESPELHADO')
|
||||
return ' · '.join(fields)
|
||||
|
||||
|
||||
def produce(storage, job, item, uploads):
|
||||
"""Fetch the item's artwork and render it. Returns (pdf path, name, size, evidence)."""
|
||||
for upload_id in item['uploads']:
|
||||
@@ -146,7 +174,7 @@ def produce(storage, job, item, uploads):
|
||||
if row['purged_at'] or row['expired']:
|
||||
raise Unsupported('um arquivo original passou do prazo de guarda')
|
||||
number = job['number']
|
||||
name = f'pedido-{number}-item-{job["item_index"] + 1}.pdf'
|
||||
name = f'{file_prefix(number, job["item_index"])}.pdf'
|
||||
with tempfile.TemporaryDirectory(prefix='print-') as scratch:
|
||||
files = {}
|
||||
for index, upload_id in enumerate(item['uploads']):
|
||||
@@ -156,7 +184,8 @@ def produce(storage, job, item, uploads):
|
||||
handle, output = tempfile.mkstemp(prefix='print-', suffix='.pdf')
|
||||
try:
|
||||
with os.fdopen(handle, 'wb') as out:
|
||||
detail = render(item, files, out, f'Pedido {number} - item {job["item_index"] + 1}')
|
||||
detail = render(item, files, out, f'Pedido {number} - item {job["item_index"] + 1}',
|
||||
footer=footer(job, item))
|
||||
except BaseException:
|
||||
os.unlink(output)
|
||||
raise
|
||||
|
||||
26
app/proof.py
Normal file
26
app/proof.py
Normal file
@@ -0,0 +1,26 @@
|
||||
"""The print proof (Dropstar, 2026-10-21).
|
||||
|
||||
An order above 10 m prints a proof before the rest, checked by the print room
|
||||
without stopping the order. Dropstar's rule (2026-10-23): up to 30 cm, from
|
||||
the part with the thinnest lines, a piece of each different artwork, at most
|
||||
three proofs per order, never billed. On an order above 10 m the customer
|
||||
may also ask for a proof at checkout (below 10 m there is none, Dropstar
|
||||
2026-10-28): that order waits for them, marked "Aguardando contato", until
|
||||
they approve the photo sent by WhatsApp. Either way the room
|
||||
marks "Prova OK" once the proof is checked, and without it the order does not
|
||||
reach Finalizado.
|
||||
"""
|
||||
from decimal import Decimal
|
||||
|
||||
PROOF_ABOVE_METRES = Decimal('10')
|
||||
CUSTOMER_NOTE = ('O cliente pediu uma prova antes de imprimir: mande a foto da prova pelo WhatsApp '
|
||||
'e espere o aceite.')
|
||||
|
||||
|
||||
def billed_metres(snapshot):
|
||||
return sum((Decimal(str(item.get('billed_metres') or 0)) for item in snapshot.get('items') or []), Decimal(0))
|
||||
|
||||
|
||||
def needs_proof(snapshot):
|
||||
"""Whether the order prints a proof first: asked for, or above 10 m."""
|
||||
return bool(snapshot.get('proof')) or billed_metres(snapshot) > PROOF_ABOVE_METRES
|
||||
@@ -1,16 +1,17 @@
|
||||
"""Quote approval: automatic at checkout, by an operator for the exceptions.
|
||||
|
||||
A quote the customer can pay is priced here from the server's own ladders,
|
||||
A quote the customer can pay is priced here from the server's own prices,
|
||||
whether an operator approved it on the Kanban or the Site approved it the
|
||||
moment it was created. The Site is a shop: a customer who can price the order
|
||||
should be able to pay for it straight away, at any hour, so only orders a
|
||||
person must look at before charging wait for the Kanban (review_reason).
|
||||
|
||||
The grade (and so the discount) is worked out in the customer's browser and
|
||||
checked against the files before an automatic approval (app/grade_check.py);
|
||||
a grade the files do not support waits for review. The layout is still the
|
||||
browser's (roadmap 3.9): the API checks its geometry. Operators see every
|
||||
order's grade and artwork at Arte recebida.
|
||||
Each product has one price (Dropstar, 2026-10-23): the grade no longer changes
|
||||
what is charged. It is still worked out in the customer's browser and shown
|
||||
with the order, so it is checked against the files before an automatic
|
||||
approval (app/grade_check.py); a grade the files do not support waits for
|
||||
review. The layout is still the browser's (roadmap 3.9): the API checks its
|
||||
geometry. Operators see every order's grade and artwork at Arte recebida.
|
||||
"""
|
||||
import os
|
||||
from decimal import Decimal
|
||||
@@ -19,6 +20,7 @@ from fastapi import HTTPException
|
||||
from psycopg.types.json import Jsonb
|
||||
|
||||
from . import payments
|
||||
from .proof import PROOF_ABOVE_METRES
|
||||
from .core.models import PRODUCTION_VERSIONS
|
||||
from .core.pricing import is_manual, manual_extra_cents, price
|
||||
from .runtime import freight, upload_row
|
||||
@@ -45,10 +47,6 @@ def review_reason(draft):
|
||||
for item in draft['items']:
|
||||
if item.get('production', {}).get('version') not in PRODUCTION_VERSIONS:
|
||||
return 'Montagem antiga'
|
||||
# The Site grades only the art it could analyse; anything else is
|
||||
# priced at the full rate. A discount on it did not come from the Site.
|
||||
if item['quality_status'] == 'unverified' and item['grade'] != 0:
|
||||
return 'Nota informada sem análise da arte'
|
||||
return None
|
||||
|
||||
|
||||
@@ -66,7 +64,7 @@ def approve(c, row, items, reviewer):
|
||||
for item, original in zip(items, draft['items']):
|
||||
if item.mode != original['mode'] or list(map(str, item.uploads)) != original['uploads']:
|
||||
raise HTTPException(422, 'O produto e os arquivos não podem mudar na revisão.')
|
||||
if item.production.model_dump(mode='json') != original['production'] or item.quality_status != original['quality_status'] or item.quality_acknowledged != original['quality_acknowledged']:
|
||||
if item.production.model_dump(mode='json') != original['production'] or item.quality_status != original['quality_status'] or item.quality_acknowledged != original['quality_acknowledged'] or item.residue_accepted != original.get('residue_accepted', 0):
|
||||
raise HTTPException(422, 'A montagem e a confirmação do cliente não podem mudar na revisão.')
|
||||
names = {}
|
||||
for upload_id in item.uploads:
|
||||
@@ -77,7 +75,8 @@ def approve(c, row, items, reviewer):
|
||||
priced.append({**price(item.mode, str(item.metres), item.grade, extra),
|
||||
'uploads': original['uploads'], 'production': original['production'],
|
||||
'quality_status': original['quality_status'],
|
||||
'quality_acknowledged': original['quality_acknowledged']})
|
||||
'quality_acknowledged': original['quality_acknowledged'],
|
||||
'residue_accepted': original.get('residue_accepted', 0)})
|
||||
metres = sum(Decimal(i['billed_metres']) for i in priced)
|
||||
try:
|
||||
quoted_freight = freight.quote(draft['freight']['service'], draft['freight'].get('postal_code', ''),
|
||||
@@ -86,6 +85,8 @@ def approve(c, row, items, reviewer):
|
||||
raise HTTPException(422, str(exc))
|
||||
approved = {'customer': draft['customer'], 'items': priced, 'freight': quoted_freight,
|
||||
'destination': draft.get('destination'),
|
||||
# The customer's proof only above 10 m (Dropstar, 2026-10-28).
|
||||
**({'proof': True} if draft.get('proof') and metres > PROOF_ABOVE_METRES else {}),
|
||||
'total_cents': sum(i['total_cents'] for i in priced) + quoted_freight['total_cents']}
|
||||
c.execute('UPDATE dtf_local.quotes SET approved=%s, reviewed_by=%s, approved_at=now() WHERE id=%s',
|
||||
(Jsonb(approved), reviewer, row['id']))
|
||||
|
||||
137
app/receipt.py
Normal file
137
app/receipt.py
Normal file
@@ -0,0 +1,137 @@
|
||||
"""The pickup receipt (Dropstar's third round, item 14, 2026-10-29).
|
||||
|
||||
A PDF for the counter's 80 mm thermal roll: the order number large at the
|
||||
top, the customer and their CPF or CNPJ, each product and its metres, the
|
||||
amount and how it was paid, when it was issued, and blank lines for the
|
||||
date of pickup and the signature. Only for orders picked up in Franca: one
|
||||
sent by a carrier has none. The Kanban's folder saves it in Recibos/, and the
|
||||
counter's print queue sends it to the Bematech.
|
||||
"""
|
||||
import io
|
||||
import unicodedata
|
||||
from datetime import datetime
|
||||
|
||||
from .printfile import Name, PdfWriter, deflate, serialize, _HELVETICA, _HELVETICA_BOLD
|
||||
from .printjobs import LOCAL, file_prefix
|
||||
|
||||
MM = 72 / 25.4
|
||||
WIDTH = 80 * MM
|
||||
MARGIN = 4 * MM
|
||||
ROOM = WIDTH - 2 * MARGIN
|
||||
FONTS = {'F1': 'Helvetica-Bold', 'F2': 'Helvetica'}
|
||||
PRODUCTS = {'file': 'DTF Têxtil · folha montada', 'avulsa': 'DTF Têxtil · artes avulsas',
|
||||
'uvfile': 'DTF UV · folha montada', 'uv': 'DTF UV · artes avulsas'}
|
||||
METHODS = {'pix': 'Pix', 'card': 'Cartão', 'cash': 'Dinheiro', 'credit': 'Crédito do cliente'}
|
||||
# Helvetica's widths for what the tables in printfile.py leave out.
|
||||
EXTRA = {'$': 556, '(': 333, ')': 333, '_': 556, '#': 556, '—': 1000, '@': 1015, '&': 667, '+': 584, "'": 191}
|
||||
|
||||
|
||||
def code(order):
|
||||
"""DTF-123: the order as the Kanban, the files and Tiny name it."""
|
||||
return file_prefix(order['number'], 0).rsplit('-item-', 1)[0]
|
||||
|
||||
|
||||
def is_pickup(snapshot):
|
||||
return ((snapshot or {}).get('freight') or {}).get('service') == 'pickup'
|
||||
|
||||
|
||||
def money(cents):
|
||||
whole, cents = divmod(int(cents), 100)
|
||||
return 'R$ ' + f'{whole:,}'.replace(',', '.') + f',{cents:02d}'
|
||||
|
||||
|
||||
def document(value):
|
||||
digits = ''.join(ch for ch in str(value or '') if ch.isdigit())
|
||||
if len(digits) == 14:
|
||||
return 'CNPJ', f'{digits[:2]}.{digits[2:5]}.{digits[5:8]}/{digits[8:12]}-{digits[12:]}'
|
||||
if len(digits) == 11:
|
||||
return 'CPF', f'{digits[:3]}.{digits[3:6]}.{digits[6:9]}-{digits[9:]}'
|
||||
return 'CPF/CNPJ', str(value or '')
|
||||
|
||||
|
||||
def width(text, bold=False):
|
||||
"""The width of `text` in Helvetica at size 1: an accented letter is as
|
||||
wide as its letter."""
|
||||
table = _HELVETICA_BOLD if bold else _HELVETICA
|
||||
total = 0
|
||||
for ch in text:
|
||||
base = unicodedata.normalize('NFD', ch)[0]
|
||||
total += table.get(ch) or table.get(base) or EXTRA.get(ch) or 600
|
||||
return total / 1000
|
||||
|
||||
|
||||
def wrap(text, size, bold=False):
|
||||
"""The text in lines that fit the roll, broken between words."""
|
||||
lines, line = [], ''
|
||||
for word in str(text).split():
|
||||
attempt = f'{line} {word}' if line else word
|
||||
if line and width(attempt, bold) * size > ROOM:
|
||||
lines.append(line)
|
||||
line = word
|
||||
else:
|
||||
line = attempt
|
||||
return lines + [line] if line else lines or ['']
|
||||
|
||||
|
||||
def literal(text):
|
||||
raw = text.encode('cp1252', 'replace')
|
||||
return b'(' + raw.replace(b'\\', b'\\\\').replace(b'(', b'\\(').replace(b')', b'\\)') + b')'
|
||||
|
||||
|
||||
def lines(order, paid_with, issued):
|
||||
"""What the receipt says, top to bottom: (text, size, bold, space before)."""
|
||||
snapshot = order['snapshot']
|
||||
customer = snapshot.get('customer') or {}
|
||||
kind, number = document(customer.get('cnpj'))
|
||||
name = code(order)
|
||||
# The number as large as the roll takes, up to 34 pt.
|
||||
big = min(34, int(ROOM / width(name, True)))
|
||||
out = [('DROPSTAR · Recibo de retirada', 9, True, 0), (name, big, True, 4)]
|
||||
if paid_with == 'teste':
|
||||
out.append(('PEDIDO DE TESTE', 10, True, 2))
|
||||
out.append(('Cliente', 7.5, False, 10))
|
||||
out += [(part, 10, True, 1) for part in wrap(customer.get('name') or customer.get('mail') or '', 10, True)]
|
||||
out += [(kind, 7.5, False, 6), (number, 10, False, 1)]
|
||||
out.append(('Produto', 7.5, False, 10))
|
||||
for item in snapshot.get('items') or []:
|
||||
metres = str(item.get('billed_metres') or item.get('metres') or '').replace('.', ',')
|
||||
out += [(part, 9.5, False, 2) for part in wrap(f"{PRODUCTS.get(item.get('mode'), item.get('mode'))} — {metres} m", 9.5)]
|
||||
out += [('Valor', 7.5, False, 10), (money(snapshot.get('total_cents') or 0), 12, True, 1),
|
||||
('Pagamento', 7.5, False, 6), (METHODS.get(paid_with, 'Teste' if paid_with == 'teste' else paid_with or '—'), 10, False, 1),
|
||||
(f"Emitido em {issued.astimezone(LOCAL).strftime('%d/%m/%Y %H:%M')}", 8.5, False, 10),
|
||||
('Retirado em ____/____/________', 10, False, 22),
|
||||
('Assinatura ______________________', 10, False, 26)]
|
||||
return out
|
||||
|
||||
|
||||
def render(order, paid_with, issued=None):
|
||||
"""The receipt's PDF bytes, 80 mm wide and as long as what it says."""
|
||||
rows = lines(order, paid_with, issued or datetime.now(LOCAL))
|
||||
height = MARGIN * 2 + sum(size * 1.2 + space for _, size, _, space in rows)
|
||||
y = height - MARGIN
|
||||
commands = [b'0 g\n']
|
||||
for text, size, bold, space in rows:
|
||||
y -= space + size
|
||||
commands.append(b'BT /%s %s Tf %s %s Td %s Tj ET\n' % (b'F1' if bold else b'F2', serialize(size),
|
||||
serialize(MARGIN), serialize(y), literal(text)))
|
||||
y -= size * 0.2
|
||||
out = io.BytesIO()
|
||||
pdf = PdfWriter(out)
|
||||
content = pdf.stream({'Filter': Name('FlateDecode')}, deflate(commands))
|
||||
pages = pdf.alloc()
|
||||
fonts = {key: {'Type': Name('Font'), 'Subtype': Name('Type1'), 'BaseFont': Name(font),
|
||||
'Encoding': Name('WinAnsiEncoding')} for key, font in FONTS.items()}
|
||||
box = [0, 0, WIDTH, height]
|
||||
page = pdf.obj({'Type': Name('Page'), 'Parent': pages, 'MediaBox': box, 'Resources': {'Font': fonts},
|
||||
'Contents': content})
|
||||
pdf.obj({'Type': Name('Pages'), 'Kids': [page], 'Count': 1}, pages)
|
||||
root = pdf.obj({'Type': Name('Catalog'), 'Pages': pages})
|
||||
info = pdf.obj({'Title': f'Recibo {code(order)}',
|
||||
'Producer': 'DTF System'})
|
||||
pdf.finish(root, info)
|
||||
return out.getvalue()
|
||||
|
||||
|
||||
def file_name(order):
|
||||
"""Recibo-DTF-123.pdf"""
|
||||
return f'Recibo-{code(order)}.pdf'
|
||||
@@ -51,13 +51,18 @@ BOARD_QUOTE_LIMIT = int(os.environ.get('BOARD_QUOTE_LIMIT', '100'))
|
||||
PART_BYTES = int(os.environ.get('UPLOAD_PART_BYTES', '8388608'))
|
||||
if not 5242880 <= PART_BYTES <= 67108864:
|
||||
raise RuntimeError('UPLOAD_PART_BYTES must be between 5 and 64 MiB')
|
||||
STATES = {'rec': 'Arte recebida', 'tra': 'Arte conferida', 'fil': 'Fila de impressão',
|
||||
'imp': 'Imprimindo', 'cor': 'Correção', 'fin': 'Finalizado'}
|
||||
TRANSITIONS = {'rec': ['tra','cor'], 'tra': ['fil','cor'], 'fil': ['imp','cor'],
|
||||
'imp': ['fin','cor'], 'cor': ['rec','tra'], 'fin': []}
|
||||
# Dropstar's flow of 2026-10-23: Arte conferida is the print queue (Fila de
|
||||
# impressão, 'fil', left the board), and Revisão checks the printed sheet
|
||||
# before Finalizado. After a correction the new art goes back through Arte
|
||||
# recebida or Arte conferida; Gestão may also take it straight to Revisão.
|
||||
# Who may make each move is app/core/auth.py's MOVES.
|
||||
STATES = {'rec': 'Arte recebida', 'tra': 'Arte conferida', 'imp': 'Imprimindo',
|
||||
'cor': 'Correção', 'rev': 'Revisão', 'fin': 'Finalizado'}
|
||||
TRANSITIONS = {'rec': ['tra','cor'], 'tra': ['imp','cor'], 'imp': ['rev','cor'],
|
||||
'rev': ['fin','cor'], 'cor': ['rec','tra','rev'], 'fin': []}
|
||||
# Undoing a move made by mistake: one stage back, with an internal reason. It
|
||||
# is not a correction: the customer is not told and approved finals stay.
|
||||
BACK = {'tra': 'rec', 'fil': 'tra', 'imp': 'fil', 'fin': 'imp'}
|
||||
BACK = {'tra': 'rec', 'imp': 'tra', 'rev': 'imp', 'fin': 'rev'}
|
||||
|
||||
|
||||
def real_delivery():
|
||||
|
||||
@@ -75,6 +75,37 @@ RIFF_FORMS = {'cdr': re.compile(rb'^RIFF....CDR', re.S), 'webp': re.compile(rb'^
|
||||
HEAD_BYTES = 64
|
||||
|
||||
|
||||
# Dropstar's rule D-13 (2026-10-26): the content decides a file's type, never
|
||||
# its extension. A third of their ".cdr" files are PDFs renamed.
|
||||
def detected_format(head):
|
||||
"""The format a file's first bytes show, as an extension, or None."""
|
||||
for ext in ('pdf', 'png', 'jpg', 'tif', 'psd'):
|
||||
if any(head.startswith(sig) for sig in SIGNATURES[ext]):
|
||||
return ext
|
||||
for ext, form in RIFF_FORMS.items():
|
||||
if form.match(head):
|
||||
return ext
|
||||
return None
|
||||
|
||||
|
||||
def real_name(name, head):
|
||||
"""The file's name with the extension of what it really is: a ".cdr" that
|
||||
is a PDF is "x.pdf", a JPG called ".png" is "x.jpg". A name its content
|
||||
agrees with stays, so an Illustrator file, which is a PDF inside, is still
|
||||
".ai" and handled by hand; unknown content keeps the name too."""
|
||||
found = detected_format(head)
|
||||
if not found or format_matches(name, head):
|
||||
return name
|
||||
stem, dot, _ = name.rpartition('.')
|
||||
return (stem if dot else name) + '.' + found
|
||||
|
||||
|
||||
def head_of(storage, row):
|
||||
"""A stored file's first bytes."""
|
||||
return storage.client.get_object(Bucket=storage.bucket, Key=row['object_key'],
|
||||
Range=f'bytes=0-{HEAD_BYTES - 1}')['Body'].read()
|
||||
|
||||
|
||||
def format_matches(name, head):
|
||||
"""Whether a file's first bytes are those of the format its name claims."""
|
||||
ext = name.rsplit('.', 1)[-1].lower() if '.' in name else ''
|
||||
@@ -83,11 +114,10 @@ def format_matches(name, head):
|
||||
return any(head.startswith(sig) for sig in SIGNATURES.get(ext, ()))
|
||||
|
||||
|
||||
def check_large(storage, row):
|
||||
def check_large(head, row):
|
||||
"""Release decision for a file above the antivirus limit."""
|
||||
head = storage.client.get_object(Bucket=storage.bucket, Key=row['object_key'],
|
||||
Range=f'bytes=0-{HEAD_BYTES - 1}')['Body'].read()
|
||||
if format_matches(row['name'], head):
|
||||
# The content decides (D-13): a ".cdr" that is a PDF is still a PDF.
|
||||
if format_matches(row['name'], head) or detected_format(head):
|
||||
return 'clean', 'Acima do limite do antivírus; formato do arquivo conferido'
|
||||
return 'rejected', 'O conteúdo do arquivo não corresponde ao formato do nome'
|
||||
|
||||
@@ -99,19 +129,25 @@ def scan_one(storage, scanner=None):
|
||||
AND expires_at>now() AND scan_state IN ('pending','error') AND scan_after<=now()
|
||||
ORDER BY created_at FOR UPDATE SKIP LOCKED LIMIT 1''').fetchone()
|
||||
if not row:return False
|
||||
name=row['name']
|
||||
try:
|
||||
# Every later decision reads the stored name (the manual charge,
|
||||
# the JPG refusal, the grade, the print file, the folders), so the
|
||||
# name is made to say what the file is (D-13).
|
||||
head=head_of(storage,row)
|
||||
name=real_name(name,head)
|
||||
if row['size'] > scan_limit_bytes():
|
||||
state,reason=check_large(storage,row)
|
||||
state,reason=check_large(head,row)
|
||||
else:
|
||||
stream=storage.client.get_object(Bucket=storage.bucket,Key=row['object_key'])['Body']
|
||||
try:state,reason=scanner.scan(stream,row['size'])
|
||||
finally:stream.close()
|
||||
except Exception:
|
||||
state,reason='error','Malware scanner unavailable; file remains blocked'
|
||||
c.execute("""UPDATE dtf_local.uploads SET scan_state=%s,scan_reason=%s,scanned_at=now(),
|
||||
c.execute("""UPDATE dtf_local.uploads SET name=%s,scan_state=%s,scan_reason=%s,scanned_at=now(),
|
||||
scan_after=now()+interval '1 minute',
|
||||
expires_at=CASE WHEN %s IN ('rejected','error') THEN LEAST(expires_at,now()+interval '3 days') ELSE expires_at END
|
||||
WHERE id=%s""",(state,reason,state,row['id']))
|
||||
WHERE id=%s""",(name,state,reason,state,row['id']))
|
||||
audit('artwork_scan', upload=str(row['id']), result=state)
|
||||
return True
|
||||
|
||||
|
||||
@@ -247,11 +247,13 @@ CREATE TABLE IF NOT EXISTS dtf_local.cnpj_names (
|
||||
|
||||
-- Who may do what on the Kanban. superadmin is the system's own account (set
|
||||
-- from the console); administrators manage users and machines; gestão runs
|
||||
-- the business; designers approve artwork; operadores produce; vendedores only read.
|
||||
-- the business; designers approve artwork; operadores print; revisores check
|
||||
-- the printed sheet and are the only ones to release it to Finalizado;
|
||||
-- vendedores only read.
|
||||
ALTER TABLE dtf_local.operators ADD COLUMN IF NOT EXISTS role text NOT NULL DEFAULT 'admin';
|
||||
ALTER TABLE dtf_local.operators DROP CONSTRAINT IF EXISTS operators_role;
|
||||
ALTER TABLE dtf_local.operators ADD CONSTRAINT operators_role
|
||||
CHECK (role IN ('superadmin','admin','gestao','designer','operador','vendedor'));
|
||||
CHECK (role IN ('superadmin','admin','gestao','designer','operador','revisor','vendedor','financeiro'));
|
||||
-- The print machines, and which products each prints. An order keeps the
|
||||
-- machine someone chose (machine_chosen) or the one given automatically: the
|
||||
-- active machine of its product with the fewest metres open (app/machines.py).
|
||||
@@ -342,3 +344,85 @@ UPDATE dtf_local.accounts a SET email_verified=true WHERE NOT a.email_verified A
|
||||
ALTER TABLE dtf_local.mail_queue DROP CONSTRAINT IF EXISTS mail_queue_kind_check;
|
||||
ALTER TABLE dtf_local.mail_queue ADD CONSTRAINT mail_queue_kind_check
|
||||
CHECK(kind IN ('reset','code','account','notice','order','alert','test'));
|
||||
|
||||
-- The print proof (Dropstar, 2026-10-21): an order above 10 m, or one whose
|
||||
-- customer asked for a proof at checkout, prints 20 cm first; the room marks
|
||||
-- "Prova OK" once it is checked, and without it the order does not reach
|
||||
-- Finalizado.
|
||||
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS proof_ok_at timestamptz;
|
||||
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS proof_ok_by text;
|
||||
|
||||
-- Fila de impressão left the board (Dropstar, 2026-10-23): Arte conferida is
|
||||
-- the queue. An order still in it moves there once, with a line in its history.
|
||||
WITH moved AS (UPDATE dtf_local.orders SET state='tra', version=version+1, updated_at=now()
|
||||
WHERE state='fil' RETURNING id)
|
||||
INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason)
|
||||
SELECT id,'fil','tra','sistema','A Fila de impressão saiu do quadro: Arte conferida é a fila.' FROM moved;
|
||||
|
||||
-- Each time an order waited for a word with the customer ("Aguardando
|
||||
-- contato"): that wait has no deadline and does not count in the time figures
|
||||
-- of Números (Dropstar's rule D-38, 2026-10-26). An open wait has no end. The
|
||||
-- waits already open when this table came are recorded from their start.
|
||||
CREATE TABLE IF NOT EXISTS dtf_local.contact_waits (
|
||||
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||
order_id uuid NOT NULL REFERENCES dtf_local.orders(id) ON DELETE CASCADE,
|
||||
started_at timestamptz NOT NULL, ended_at timestamptz
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS contact_waits_order ON dtf_local.contact_waits(order_id);
|
||||
INSERT INTO dtf_local.contact_waits(order_id, started_at)
|
||||
SELECT o.id, o.contact_since FROM dtf_local.orders o
|
||||
WHERE o.contact_since IS NOT NULL AND NOT EXISTS (SELECT 1 FROM dtf_local.contact_waits w WHERE w.order_id=o.id);
|
||||
|
||||
-- Every card is born with its origin (Dropstar's rules D-21 and D-35,
|
||||
-- 2026-10-26): site, dropflow (the montador's batches) or atendimento (an
|
||||
-- order the team enters). No order without one, and no default: a default
|
||||
-- would become the origin of almost everything, so each way in names its own.
|
||||
-- The orders from before this column all came from the Site.
|
||||
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS origin text;
|
||||
UPDATE dtf_local.orders SET origin='site' WHERE origin IS NULL;
|
||||
ALTER TABLE dtf_local.orders ALTER COLUMN origin SET NOT NULL;
|
||||
ALTER TABLE dtf_local.orders DROP CONSTRAINT IF EXISTS orders_origin_check;
|
||||
ALTER TABLE dtf_local.orders ADD CONSTRAINT orders_origin_check CHECK (origin IN ('site','dropflow','atendimento'));
|
||||
|
||||
-- Rework (Dropstar's rules D-02 to D-04, 2026-10-26; the user's answers of
|
||||
-- 2026-10-27). Gestão opens it with its cause, and the cause never changes
|
||||
-- after (D-03); an Administrador authorizes or declines it, never one they
|
||||
-- opened, and only an authorized rework counts. Bad art the customer approved
|
||||
-- is recorded apart, outside the goal (D-04). printed_by is who sent the
|
||||
-- sheet to Revisão, as the rework enters the printer's pay.
|
||||
CREATE TABLE IF NOT EXISTS dtf_local.reworks (
|
||||
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||
order_id uuid NOT NULL REFERENCES dtf_local.orders(id) ON DELETE CASCADE,
|
||||
cause text NOT NULL CHECK (cause IN ('impressao','perfil_cor','tratamento','pedido','arte_cliente')),
|
||||
metres numeric NOT NULL CHECK (metres > 0),
|
||||
note text NOT NULL DEFAULT '',
|
||||
printed_by text,
|
||||
opened_by text NOT NULL, opened_at timestamptz NOT NULL DEFAULT now(),
|
||||
authorized boolean, decided_by text, decided_at timestamptz, decline_reason text
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS reworks_order ON dtf_local.reworks(order_id);
|
||||
|
||||
-- The pickup receipt (Dropstar's third round, item 14, 2026-10-29): due when
|
||||
-- an order to be picked up reaches Finalizado; one computer's folder claims
|
||||
-- it and saves the PDF in Recibos/, where the counter's print queue sends it
|
||||
-- to the Bematech. Claimed once, so it is never printed twice.
|
||||
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS receipt_due_at timestamptz;
|
||||
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS receipt_saved_at timestamptz;
|
||||
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS receipt_saved_by text;
|
||||
-- "Retirado": when, who handed it over and, optionally, a photo of the
|
||||
-- signed receipt. Finalizado means ready; this means delivered.
|
||||
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS picked_up_at timestamptz;
|
||||
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS picked_up_by text;
|
||||
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS picked_up_photo uuid REFERENCES dtf_local.uploads(id) ON DELETE SET NULL;
|
||||
|
||||
-- The machine a session works on (Dropstar's third round, item 12, 2026-10-30):
|
||||
-- chosen after signing in, per session, so one person may be on two machines,
|
||||
-- one per computer. machine_answered: the question was answered, "Não estou em
|
||||
-- máquina" included. The links Usuários showed before (operator_machines)
|
||||
-- are no longer read.
|
||||
ALTER TABLE dtf_local.operator_sessions ADD COLUMN IF NOT EXISTS machine_id uuid REFERENCES dtf_local.machines(id) ON DELETE SET NULL;
|
||||
ALTER TABLE dtf_local.operator_sessions ADD COLUMN IF NOT EXISTS machine_at timestamptz;
|
||||
ALTER TABLE dtf_local.operator_sessions ADD COLUMN IF NOT EXISTS machine_answered boolean NOT NULL DEFAULT false;
|
||||
-- The machine of whoever moved a card, as it was named then: "Imprimindo ·
|
||||
-- Thales · máquina2".
|
||||
ALTER TABLE dtf_local.movements ADD COLUMN IF NOT EXISTS machine text;
|
||||
|
||||
76
app/tiny.py
76
app/tiny.py
@@ -20,19 +20,24 @@ sum, 1,30 m = 1 × "1 metro" + 1 × "30 cm", at the price the customer paid.
|
||||
Idempotency: the outbox may deliver the same event more than once. Every order
|
||||
carries numeroOrdemCompra = "DTF-<order number>", and before creating one the
|
||||
customer's recent orders are searched for that number, so a second delivery
|
||||
finds the first order instead of creating another.
|
||||
finds the first order instead of creating another. The same number goes in
|
||||
numeroPedidoEcommerce (Dropstar, 2026-10-23), which n8n reads as
|
||||
numero_ecommerce.
|
||||
|
||||
Customer notices: the client sends WhatsApp messages from Tiny's order
|
||||
situação (Tiny webhook -> their middleware -> n8n), on Aprovado, Pronto para
|
||||
envio (pickup only), Enviado and Entregue. With TINY_STATUS_UPDATES on, the
|
||||
Kanban moves the Tiny order along with it:
|
||||
envio, Enviado and Entregue. With TINY_STATUS_UPDATES on, the Kanban moves
|
||||
the Tiny order along with it (Dropstar's flow, 2026-10-23: two changes of
|
||||
situação, none for Imprimindo, Correção or Revisão):
|
||||
|
||||
paid (Arte recebida) -> Aprovada (the "approved" notice)
|
||||
Imprimindo -> Preparando envio (no notice)
|
||||
Finalizado, pickup -> Pronto para envio (the pickup notice)
|
||||
Finalizado, delivery -> unchanged: the team invoices and ships in Tiny
|
||||
Arte conferida (queue) -> Preparando envio (no notice)
|
||||
Finalizado -> Pronto para envio (pickup or delivery)
|
||||
cancelled -> Cancelada (no notice)
|
||||
|
||||
After Pronto para envio the order goes on in Tiny like any other: Enviada,
|
||||
Entregue.
|
||||
|
||||
An order someone already moved further in Tiny is never moved back, and an
|
||||
invoiced one is not cancelled here (its nota fiscal is cancelled in Tiny).
|
||||
Pickup orders carry the client's "retirar pessoalmente" forma de envio.
|
||||
@@ -72,8 +77,8 @@ STEP_DEFAULTS = {'uvfile': 'DTFIMP.UV.010CM', 'uv': 'DTFIMP.UV.010CM'}
|
||||
METRE_DEFAULTS = {'uvfile': 'DTFIMP.UV.1MT', 'uv': 'DTFIMP.UV.1MT'}
|
||||
PRODUCTS = {'file': 'DTF Têxtil 57 cm · folha montada',
|
||||
'avulsa': 'DTF Têxtil 57 cm · artes avulsas',
|
||||
'uvfile': 'DTF UV 28,5 cm · folha montada',
|
||||
'uv': 'DTF UV 28,5 cm · artes avulsas'}
|
||||
'uvfile': 'DTF UV 27 cm · folha montada',
|
||||
'uv': 'DTF UV 27 cm · artes avulsas'}
|
||||
# How far back to look for an order a previous delivery may already have made.
|
||||
SEARCH_DAYS = 7
|
||||
# A "ready" event can come after corrections; it normally knows the Tiny id.
|
||||
@@ -87,6 +92,18 @@ SITUACOES = {0: 'Aberta', 3: 'Aprovada', 4: 'Preparando envio', 1: 'Faturada', 7
|
||||
# react to these situações. Off until go-live: while n8n still sends the
|
||||
# designer message for DTFIMP products on "Aprovado", setting it would reach
|
||||
# Site customers.
|
||||
# Where the order came from (D-21) and, when the team registered it, how it was
|
||||
# paid outside the system (D-35), for whoever reads the order in Tiny.
|
||||
ORIGIN_NOTES = {'site': 'Site DTF', 'atendimento': 'Atendimento DTF', 'dropflow': 'Dropflow DTF'}
|
||||
OUTSIDE_NOTES = {'pix': 'Pix', 'card': 'cartão', 'cash': 'dinheiro', 'credit': 'crédito do cliente'}
|
||||
|
||||
|
||||
def internal_note(payload):
|
||||
paid = payload.get('payment') or {}
|
||||
how = f"pago fora do site ({OUTSIDE_NOTES.get(paid.get('method'), paid.get('method'))})" if paid.get('outside') else 'pago'
|
||||
return f"{ORIGIN_NOTES.get(payload.get('origin') or 'site')} · {how} · {payload['order_id']}"
|
||||
|
||||
|
||||
STATUS_UPDATES_SETTING = 'TINY_STATUS_UPDATES'
|
||||
# The client's custom "retirar pessoalmente" forma de envio (v2 code X), which
|
||||
# the pickup notice is keyed on. Found in Tiny by name; this setting, an id,
|
||||
@@ -97,15 +114,22 @@ PICKUP_EXACT = 'retirar pessoalmente'
|
||||
# Dropstar's own ids, read from its store orders with app.tiny_probe exemplo
|
||||
# (2026-10-19). The app may not list formas de recebimento, so these are not
|
||||
# looked up: Pix and credit card, as the store's orders are paid, and the
|
||||
# DropStar carrier its pickup orders name.
|
||||
RECEIPT_METHODS = {'pix': 919478952, 'card': 977460722}
|
||||
# DropStar carrier its pickup orders name. Dinheiro and, for the customer's
|
||||
# credit, Dropstar's own "CORREÇÃO DTF" were sent by Marcus on 2026-10-27, for
|
||||
# the orders the team registers as paid outside the site (D-35).
|
||||
RECEIPT_METHODS = {'pix': 919478952, 'card': 977460722, 'cash': 919478944, 'credit': 977493654}
|
||||
PICKUP_CARRIER = 761565838
|
||||
# Dropstar's answers (2026-10-21): the store's financial category "DUPLICADO
|
||||
# DROP" (it goes in pagamento.categoria), no seller (the team links one in
|
||||
# Tiny), and the marcador KANBANDTF, added after the order is created: POST
|
||||
# /pedidos does not take marcadores.
|
||||
CATEGORY = 965775137
|
||||
TAG = 'KANBANDTF'
|
||||
# Dropstar's answers: the financial category "DTF SITE" (RECEITAS, id sent on
|
||||
# 2026-10-26; it goes in pagamento.categoria, and replaced the store's
|
||||
# "DUPLICADO DROP", 965775137), no seller (Tiny sets it from the contact,
|
||||
# 2026-10-23), and the marcador SITE DTF, added after the order is created:
|
||||
# POST /pedidos does not take marcadores. Capitals, no accent, no extra
|
||||
# space: the string Kondado reads for Power BI.
|
||||
CATEGORY = 986932924
|
||||
# Dropflow's orders in their own category, "DTF DROPFLOW" (sent 2026-10-27):
|
||||
# the rules document (D-21) keeps the two channels apart in the financial.
|
||||
CATEGORIES = {'dropflow': 987032506}
|
||||
TAG = 'SITE DTF'
|
||||
# Freight is the sender's (CIF), as on the store's orders.
|
||||
FREIGHT_PAID_BY = 'R'
|
||||
# The forma de envio each delivery service uses, by name; a Correios service
|
||||
@@ -475,7 +499,7 @@ def order_payload(payload, contact_id, today=None, product_id=None, shipping=Non
|
||||
'itens': items,
|
||||
'valorFrete': money(freight['total_cents']),
|
||||
'observacoes': f"Pedido DTF #{payload['number']}" + (' · retirada em Franca' if pickup else ''),
|
||||
'observacoesInternas': f"Site DTF · pago · {payload['order_id']}"}
|
||||
'observacoesInternas': internal_note(payload)}
|
||||
carrier = shipping(service) if shipping else None
|
||||
if carrier:
|
||||
pedido['transportador'] = {'fretePorConta': FREIGHT_PAID_BY, **carrier}
|
||||
@@ -484,7 +508,7 @@ def order_payload(payload, contact_id, today=None, product_id=None, shipping=Non
|
||||
if days is not None:
|
||||
pedido['dataPrevista'] = business_days_after(day, int(days)).isoformat()
|
||||
# Paid at once, in full, as the store's orders: one parcel on the day.
|
||||
pedido['pagamento'] = {'categoria': {'id': CATEGORY}}
|
||||
pedido['pagamento'] = {'categoria': {'id': CATEGORIES.get(payload.get('origin'), CATEGORY)}}
|
||||
received = RECEIPT_METHODS.get((payload.get('payment') or {}).get('method'))
|
||||
if received:
|
||||
total = money(order['total_cents'])
|
||||
@@ -496,9 +520,11 @@ def order_payload(payload, contact_id, today=None, product_id=None, shipping=Non
|
||||
pedido['enderecoEntrega'] = {**address(destination), 'enderecoNro': destination['number'],
|
||||
'nomeDestinatario': destination['recipient']}
|
||||
del pedido['enderecoEntrega']['numero']
|
||||
# The channel id is optional in Tiny's v3 model; TINY_ECOMMERCE_ID adds it.
|
||||
pedido['ecommerce'] = {'numeroPedidoEcommerce': purchase_order(payload['number'])}
|
||||
ecommerce = os.environ.get('TINY_ECOMMERCE_ID', '')
|
||||
if ecommerce.isdigit():
|
||||
pedido['ecommerce'] = {'id': int(ecommerce), 'numeroPedidoEcommerce': purchase_order(payload['number'])}
|
||||
pedido['ecommerce']['id'] = int(ecommerce)
|
||||
return pedido
|
||||
|
||||
|
||||
@@ -698,7 +724,7 @@ class TinyOrders:
|
||||
return None
|
||||
|
||||
def tag(self, tiny_id, known=False):
|
||||
"""The KANBANDTF marcador on the order, once. A retry that finds the
|
||||
"""The SITE DTF marcador on the order, once. A retry that finds the
|
||||
order already created checks first, since POST adds another."""
|
||||
if known:
|
||||
have = self.request('GET', f'/pedidos/{tiny_id}/marcadores')
|
||||
@@ -752,13 +778,9 @@ class TinyOrders:
|
||||
return receipt
|
||||
|
||||
def ready(self, event_key, payload):
|
||||
"""A pickup order became ready: "Pronto para envio", which the client's
|
||||
notices turn into the pickup message. Shipped orders get "Enviada"
|
||||
once freight exists (1.2)."""
|
||||
base = {'provider': 'tiny', 'event_key': event_key}
|
||||
order = payload.get('order') or {}
|
||||
if (order.get('freight') or {}).get('service') != 'pickup':
|
||||
return {**base, 'status': 'not-applicable', 'event': 'ready'}
|
||||
"""The order reached Finalizado: "Pronto para envio", for pickup and
|
||||
delivery alike (Dropstar, 2026-10-23). From there the team ships it in
|
||||
Tiny as any other order."""
|
||||
return self.move(event_key, payload, PRONTO_ENVIO, (ABERTA, APROVADA, PREPARANDO, FATURADA, INCOMPLETA))
|
||||
|
||||
def move(self, event_key, payload, target, from_situacoes):
|
||||
|
||||
@@ -12,6 +12,12 @@ Tiny has no sandbox, so this is how the adapter is proven on the real account.
|
||||
python -m app.tiny_probe pedido --cnpj ... --email ... --celular ... [--modo file] [--metros 1.3]
|
||||
show the test order; --confirmar creates it, then cancels it
|
||||
python -m app.tiny_probe cancelar TINY_ID cancel a test order (DTF-TESTE-...) left open; nothing else
|
||||
python -m app.tiny_probe usuarios the account's users and their type, and which one the
|
||||
integration is connected as (read-only; needs the app's
|
||||
Usuários (Leitura) and a reconnect)
|
||||
python -m app.tiny_probe diagnostico --cpf ... --email ... --celular ...
|
||||
when Tiny refuses the order: sends it again without one
|
||||
part at a time, stops at the first it accepts (cancelled)
|
||||
|
||||
The test order goes through TinyOrders.deliver, exactly as the worker sends a
|
||||
paid order. The duplicate guard is then proven read-only first (the order must
|
||||
@@ -22,13 +28,14 @@ test order is then cancelled through the API (Tiny has no delete, and the
|
||||
team's users may not cancel by hand), and read back to show it is.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
from datetime import datetime
|
||||
from decimal import Decimal, InvalidOperation
|
||||
|
||||
from .core.pricing import TIERS
|
||||
from .core.pricing import PRICES
|
||||
from .core.secrets import load as load_secret_files
|
||||
from . import tiny
|
||||
|
||||
@@ -38,7 +45,7 @@ FIND_WAIT_SECONDS = 5
|
||||
|
||||
def test_order(cnpj, email, celular, mode, now=None, metres='1'):
|
||||
number = 'TESTE-' + (now or datetime.now(tiny.BRASILIA)).strftime('%Y%m%d%H%M')
|
||||
unit = TIERS[mode][0][1]
|
||||
unit = PRICES[mode]
|
||||
total = int(Decimal(metres) * unit)
|
||||
return {'order_id': 'teste-integracao', 'number': number, 'event': 'payment_approved',
|
||||
'order': {'customer': {'cnpj': cnpj, 'mail': email, 'zap': celular},
|
||||
@@ -198,16 +205,91 @@ def pedido(orders, payload, confirm, out, wait=time.sleep):
|
||||
out(f'FALHA: a busca por {tiny.purchase_order(payload["number"])} não encontrou o pedido. '
|
||||
'Um reenvio criaria um duplicado; o 2º envio não foi feito.')
|
||||
return False
|
||||
# What Tiny kept of the e-commerce number, read back from the order.
|
||||
wanted = tiny.purchase_order(payload['number'])
|
||||
shop = orders.request('GET', f"/pedidos/{first['tiny_id']}").get('ecommerce') or {}
|
||||
out(f"E-commerce no Tiny: numeroPedidoEcommerce {shop.get('numeroPedidoEcommerce') or '(vazio)'}" +
|
||||
(f" · canal {shop.get('nome') or '?'} (id {shop['id']})" if shop.get('id') else ' · sem canal'))
|
||||
numbered = shop.get('numeroPedidoEcommerce') == wanted
|
||||
if not numbered:
|
||||
out(f'FALHA: o Tiny não guardou {wanted} em numeroPedidoEcommerce.')
|
||||
second = orders.deliver('teste-integracao', payload)
|
||||
out(f"2º envio: {second['status']} · Tiny id {second['tiny_id']}")
|
||||
passed = second['status'] == 'already-created' and second['tiny_id'] == first['tiny_id']
|
||||
out('OK: o reenvio encontrou o mesmo pedido.' if passed else 'FALHA: o reenvio não devolveu o mesmo pedido.')
|
||||
return passed
|
||||
found_again = second['status'] == 'already-created' and second['tiny_id'] == first['tiny_id']
|
||||
out('OK: o reenvio encontrou o mesmo pedido.' if found_again else 'FALHA: o reenvio não devolveu o mesmo pedido.')
|
||||
return numbered and found_again
|
||||
finally:
|
||||
# Whatever happened above, the test order does not stay open.
|
||||
cancelar(orders, first['tiny_id'], out)
|
||||
|
||||
|
||||
def connected_as(orders):
|
||||
"""Who logged in when the integration was connected: the name and e-mail
|
||||
in the access token's claims (an OpenID token), never the token itself."""
|
||||
try:
|
||||
part = orders.auth.access_token().split('.')[1]
|
||||
claims = json.loads(base64.urlsafe_b64decode(part + '=' * (-len(part) % 4)))
|
||||
except Exception:
|
||||
return {}
|
||||
return {key: claims[key] for key in ('name', 'email', 'preferred_username') if claims.get(key)}
|
||||
|
||||
|
||||
def usuarios(orders, out):
|
||||
"""The account's users, with their type, and the one the integration
|
||||
acts as: the API does what that user may do (read-only)."""
|
||||
me = connected_as(orders)
|
||||
if me:
|
||||
out('Integração conectada como: ' + ' · '.join(str(v) for v in me.values()))
|
||||
try:
|
||||
found = orders.request('GET', '/usuarios', params={'limit': 100}).get('itens') or []
|
||||
except tiny.TinyError as exc:
|
||||
if ': 403 ' in str(exc) or ': 401 ' in str(exc):
|
||||
out(f'Tiny recusou a lista de usuários ({exc}). Marque Usuários (Leitura) nas permissões do '
|
||||
'aplicativo e conecte o Tiny de novo no Kanban (Integrações).')
|
||||
return False
|
||||
raise
|
||||
ours = {str(v).lower() for v in me.values()}
|
||||
for user in found:
|
||||
mine = str(user.get('email') or '').lower() in ours or str(user.get('emailComunicacao') or '').lower() in ours
|
||||
out(f"{user.get('id')}\t{user.get('tipo') or '-'}\t{user.get('nome')}\t{user.get('email')}"
|
||||
+ ('\t<- integração' if mine else ''))
|
||||
out(f'{len(found)} usuário(s).')
|
||||
return True
|
||||
|
||||
|
||||
def diagnostico(orders, payload, out):
|
||||
"""Which part of the order Tiny refuses, when it says only 403. The same
|
||||
test order is sent whole, then without one part at a time, then with only
|
||||
what an order cannot go without; the first version Tiny accepts names the
|
||||
part, and that order is cancelled at once. The contact must exist already:
|
||||
this never creates one."""
|
||||
cnpj = payload['order']['customer']['cnpj']
|
||||
known = orders.find_contact(cnpj)
|
||||
if not known:
|
||||
out(f'Contato {tiny.punctuated(cnpj)} não existe no Tiny; use o CPF de um contato que já existe.')
|
||||
return False
|
||||
out(f'Contato {tiny.punctuated(cnpj)}: já existe no Tiny (id {known})')
|
||||
full = tiny.order_payload(payload, known, product_id=orders.product_id, shipping=orders.shipping)
|
||||
without = lambda key: {k: v for k, v in full.items() if k != key}
|
||||
versions = [('completo', full)] + [(f'sem {key}', without(key)) for key in
|
||||
('ecommerce', 'pagamento', 'transportador', 'dataPrevista')
|
||||
if key in full]
|
||||
versions.append(('só o essencial (data, contato, itens, nº de compra)',
|
||||
{k: full[k] for k in ('data', 'idContato', 'numeroOrdemCompra', 'itens')}))
|
||||
for name, body in versions:
|
||||
try:
|
||||
created = orders.request('POST', '/pedidos', json=body)
|
||||
except tiny.TinyError as exc:
|
||||
out(f'{name}: recusado ({exc})')
|
||||
continue
|
||||
out(f"{name}: ACEITO (Tiny id {created.get('id')}). O que falta no completo é o que foi tirado aqui.")
|
||||
cancelar(orders, created.get('id'), out)
|
||||
return True
|
||||
out('Todas as versões foram recusadas, até a essencial: não é o conteúdo do pedido, é a permissão '
|
||||
'do usuário do Tiny para incluir pedidos de venda.')
|
||||
return False
|
||||
|
||||
|
||||
def cancelar(orders, tiny_id, out):
|
||||
"""Cancel a test order through the API and read it back. Only orders
|
||||
this probe made (purchase order DTF-TESTE-...) are touched."""
|
||||
@@ -252,6 +334,11 @@ def main(argv=None, orders=None, out=print):
|
||||
order.add_argument('--modo', choices=sorted(tiny.PRODUCT_SETTINGS), default='file')
|
||||
order.add_argument('--metros', default='1', help='metragem cobrada, em passos de 10 cm (ex.: 1.3)')
|
||||
order.add_argument('--confirmar', action='store_true')
|
||||
commands.add_parser('usuarios')
|
||||
probe = commands.add_parser('diagnostico')
|
||||
probe.add_argument('--cnpj', '--cpf', dest='cnpj', required=True, help='CNPJ ou CPF de um contato que já existe')
|
||||
probe.add_argument('--email', required=True)
|
||||
probe.add_argument('--celular', required=True)
|
||||
args = parser.parse_args(argv)
|
||||
if orders is None:
|
||||
load_secret_files()
|
||||
@@ -273,10 +360,14 @@ def main(argv=None, orders=None, out=print):
|
||||
return 0 if exemplo(orders, args.numero, out) else 1
|
||||
if args.command == 'cancelar':
|
||||
return 0 if cancelar(orders, args.tiny_id, out) else 1
|
||||
if args.command == 'usuarios':
|
||||
return 0 if usuarios(orders, out) else 1
|
||||
cnpj = ''.join(ch for ch in args.cnpj if ch.isdigit())
|
||||
if len(cnpj) not in (11, 14):
|
||||
out('Informe um CPF (11 dígitos) ou um CNPJ (14 dígitos).')
|
||||
return 2
|
||||
if args.command == 'diagnostico':
|
||||
return 0 if diagnostico(orders, test_order(cnpj, args.email, args.celular, 'file'), out) else 1
|
||||
try:
|
||||
metres = Decimal(args.metros.replace(',', '.'))
|
||||
except InvalidOperation:
|
||||
|
||||
@@ -91,12 +91,12 @@ x-app: &app
|
||||
SMTP_PASSWORD: ${SMTP_PASSWORD:-}
|
||||
STORAGE_ADAPTER: s3-local
|
||||
MOCK_FREIGHT_CENTS: ${MOCK_FREIGHT_CENTS:-1500}
|
||||
MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-1073741824}
|
||||
MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-4294967296}
|
||||
UPLOAD_PART_BYTES: ${UPLOAD_PART_BYTES:-8388608}
|
||||
STORAGE_QUOTA_BYTES: ${STORAGE_QUOTA_BYTES:-53687091200}
|
||||
OWNER_UPLOAD_QUOTA_BYTES: ${OWNER_UPLOAD_QUOTA_BYTES:-10737418240}
|
||||
MAX_PENDING_UPLOADS: ${MAX_PENDING_UPLOADS:-10}
|
||||
SCAN_MAX_BYTES: ${SCAN_MAX_BYTES:-1073741824}
|
||||
SCAN_MAX_BYTES: ${SCAN_MAX_BYTES:-2097152000}
|
||||
networks: [local]
|
||||
init: true
|
||||
security_opt: [no-new-privileges:true]
|
||||
|
||||
@@ -15,7 +15,10 @@ LABEL org.opencontainers.image.title="DTF Portal/API" \
|
||||
# is what the production image was doing while the local one already did this.
|
||||
# pg_dump and age are for the database backup (ops/db_backup.py). Debian 13
|
||||
# ships PostgreSQL 17, the server's major version, which pg_dump must match.
|
||||
RUN apt-get update \
|
||||
# The day (PACKAGES_DAY, set by CI) is part of this layer, so a cached build
|
||||
# still fetches the fixes published since.
|
||||
ARG PACKAGES_DAY=unset
|
||||
RUN echo "packages refreshed: $PACKAGES_DAY" && apt-get update \
|
||||
&& apt-get upgrade -y \
|
||||
&& apt-get install -y --no-install-recommends postgresql-client-17 age \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
@@ -14,8 +14,12 @@ ENV NGINX_TEMPLATE=/build/deploy/nginx.conf.template
|
||||
RUN python infra/compile_web.py
|
||||
|
||||
FROM ${NGINX_BASE_IMAGE}
|
||||
# Same reason as the API image: a pinned base freezes its packages.
|
||||
RUN apk upgrade --no-cache
|
||||
# Same reason as the API image: a pinned base freezes its packages. The day
|
||||
# (PACKAGES_DAY, set by CI) is part of this layer, so a cached build still
|
||||
# fetches the fixes published since: brotli-libs 1.2.1 on 2026-10-29 was
|
||||
# missed by a cached upgrade layer and blocked the release gate.
|
||||
ARG PACKAGES_DAY=unset
|
||||
RUN echo "packages refreshed: $PACKAGES_DAY" && apk upgrade --no-cache
|
||||
ARG VCS_REF=unknown
|
||||
LABEL org.opencontainers.image.title="DTF Site and Kanban" \
|
||||
org.opencontainers.image.revision="$VCS_REF" \
|
||||
|
||||
@@ -58,6 +58,11 @@ server {
|
||||
expires -1;
|
||||
try_files /portal.html =404;
|
||||
}
|
||||
# The DTF's own terms: exchanges, file keeping and privacy.
|
||||
location ~ ^/termos/?$ {
|
||||
expires -1;
|
||||
try_files /termos.html =404;
|
||||
}
|
||||
location / {
|
||||
expires -1;
|
||||
try_files $uri $uri/ =404;
|
||||
|
||||
@@ -56,7 +56,7 @@ SMTP_PASSWORD=TBD
|
||||
STORAGE_QUOTA_BYTES=TBD
|
||||
OWNER_UPLOAD_QUOTA_BYTES=TBD
|
||||
MAX_PENDING_UPLOADS=10
|
||||
MAX_UPLOAD_BYTES=1073741824
|
||||
MAX_UPLOAD_BYTES=4294967296
|
||||
UPLOAD_PART_BYTES=8388608
|
||||
SCAN_MAX_BYTES=134217728
|
||||
# Daily encrypted database backup to its own bucket (docs/BACKUP.md).
|
||||
|
||||
@@ -72,9 +72,13 @@ x-app-environment: &app-environment
|
||||
QUOTE_AUTO_APPROVE: ${QUOTE_AUTO_APPROVE:-true}
|
||||
QUOTE_AUTO_MAX_METRES: ${QUOTE_AUTO_MAX_METRES:-50}
|
||||
# Cents added to each metre of a finished sheet someone has to open by hand
|
||||
# (CDR, AI, PSD, TIFF, or a length the customer typed). 0 adds nothing; 500
|
||||
# is R$ 5,00 a metro. The Site shows it before the customer pays.
|
||||
MANUAL_FILE_EXTRA_CENTS: ${MANUAL_FILE_EXTRA_CENTS:-0}
|
||||
# (CDR, AI, PSD, TIFF, or a length the customer typed). Dropstar set R$ 2,00
|
||||
# a metro on 2026-10-23; 0 adds nothing. The Site shows it before payment.
|
||||
MANUAL_FILE_EXTRA_CENTS: ${MANUAL_FILE_EXTRA_CENTS:-200}
|
||||
# Print files longer than 5,08 m are written at their real size, which Corel
|
||||
# reads (2026-10-28). true goes back to PDF's /UserUnit scale, for a RIP that
|
||||
# refuses pages over 5,08 m.
|
||||
PRINT_PAGE_SCALE: ${PRINT_PAGE_SCALE:-false}
|
||||
# Order creation in Tiny stays off until it has been tested against the
|
||||
# client's account (Tiny has no sandbox). The application credentials can be
|
||||
# set now: they let an operator connect Tiny from the Kanban, and the worker
|
||||
@@ -106,6 +110,9 @@ x-app-environment: &app-environment
|
||||
TINY_SKU_METRO_UV_AVULSA: ${TINY_SKU_METRO_UV_AVULSA:-}
|
||||
# The client's "retirar pessoalmente" forma de envio id, on pickup orders.
|
||||
TINY_FORMA_ENVIO_RETIRADA: ${TINY_FORMA_ENVIO_RETIRADA:-}
|
||||
# Optional e-commerce channel id for Site orders. Without it the order still
|
||||
# carries DTF-<n> as numeroPedidoEcommerce, with no channel.
|
||||
TINY_ECOMMERCE_ID: ${TINY_ECOMMERCE_ID:-}
|
||||
# Sets "Aprovada" on paid orders and "Pronto para envio" on finished pickup
|
||||
# orders, which the client's Tiny -> n8n notices send to customers. Turn on
|
||||
# only together with TINY_ADAPTER=tiny and after n8n stops sending the
|
||||
@@ -129,17 +136,17 @@ x-app-environment: &app-environment
|
||||
ALLOWED_HOSTS: ${SITE_DOMAIN:?set SITE_DOMAIN},${KANBAN_DOMAIN:?set KANBAN_DOMAIN}
|
||||
ALLOWED_ORIGINS: https://${SITE_DOMAIN:?set SITE_DOMAIN},https://${KANBAN_DOMAIN:?set KANBAN_DOMAIN}
|
||||
COOKIE_SECURE: "true"
|
||||
# 1 GB per file (Dropstar, 2026-10-21): a 57 cm x 5 m sheet at 300 DPI is
|
||||
# 200 to 300 MB, and much more takes an hour to send on a common connection.
|
||||
MAX_UPLOAD_BYTES: "1073741824"
|
||||
# 4 GB per file (Dropstar, 2026-10-28; it was 5 GB, then 1 GB from 2026-10-21).
|
||||
MAX_UPLOAD_BYTES: "4294967296"
|
||||
UPLOAD_PART_BYTES: "8388608"
|
||||
# Sheets of several GB are the normal order, so room for many of them.
|
||||
STORAGE_QUOTA_BYTES: "${STORAGE_QUOTA_BYTES:-536870912000}"
|
||||
OWNER_UPLOAD_QUOTA_BYTES: "${OWNER_UPLOAD_QUOTA_BYTES:-53687091200}"
|
||||
MAX_PENDING_UPLOADS: "10"
|
||||
# ClamAV scans up to this, so every file up to MAX_UPLOAD_BYTES is scanned;
|
||||
# a larger one would be released after a file-format check (app/scanning.py).
|
||||
SCAN_MAX_BYTES: "1073741824"
|
||||
# ClamAV scans up to its own limit, 2000 MiB (infra/clamd.conf); a larger
|
||||
# file, up to the 4 GB above, is released after the file-format check
|
||||
# (app/scanning.py, check_large).
|
||||
SCAN_MAX_BYTES: "2097152000"
|
||||
|
||||
services:
|
||||
db:
|
||||
|
||||
233
docs/CONTEXT.md
233
docs/CONTEXT.md
@@ -143,13 +143,32 @@ taxes, and payment-provider fees before presenting a commercial quote.
|
||||
|
||||
## Commercial rules
|
||||
|
||||
The existing rules in `web/index.html` are approved as the current source of
|
||||
truth. Do **not** redesign, simplify, or change prices, discounts, minimums,
|
||||
rounding, or product modes without explicit approval.
|
||||
The rules in `web/index.html` and `app/core/pricing.py` are approved as the
|
||||
current source of truth. Do **not** redesign, simplify, or change prices,
|
||||
minimums, rounding, or product modes without explicit approval.
|
||||
|
||||
The current site contains four product modes, quality-based price tiers,
|
||||
artwork-ready discounts, separate assembly charges for loose artwork, a
|
||||
one-metre minimum, and ten-centimetre billing rounding.
|
||||
The Site has four product modes, each with one price per metre (Dropstar,
|
||||
2026-10-23, live in the code since 2026-10-26). It replaced the five-band
|
||||
ladder by grade, its "a partir de R$ 14,90" and the separate assembly charge
|
||||
for loose artwork:
|
||||
|
||||
| Product | Ready sheet | Loose artwork |
|
||||
|---|---:|---:|
|
||||
| DTF textile, 57 cm | R$ 19,90 | R$ 21,90 |
|
||||
| UV sticker, 27 cm (Dropstar, 2026-10-28; was 28,5) | R$ 79,90 | R$ 89,90 |
|
||||
|
||||
The grade (nota) is still computed and shown, to the customer, on the Kanban
|
||||
and in Tiny's item note: it explains the file and no longer changes the price.
|
||||
Artwork below 96 DPI is still refused, and a resolution warning must still be
|
||||
acknowledged. The server still recomputes the grade from the files at checkout
|
||||
(`app/grade_check.py`) and holds for review a cart whose grade the files do not
|
||||
support, so the grade shown stays honest; the review reason "Nota informada sem
|
||||
análise da arte" existed only to stop a discount and was removed. One-metre
|
||||
minimum and ten-centimetre billing rounding. The prices are `PRECO` in
|
||||
`web/site-config.js` and `PRICES` in `app/core/pricing.py`, and
|
||||
`tests/test_pricing.py` checks they agree; every price on the Site's pages (top
|
||||
chip, home example, product cards, product selector, price table) is filled
|
||||
from `PRECO` through `data-preco`.
|
||||
|
||||
Customers buy with a CPF (a person) or a CNPJ (a company), check digits
|
||||
validated on both sides. The value keeps the `cnpj` key in orders, quotes and
|
||||
@@ -157,7 +176,7 @@ accounts; Tiny gets a CPF contact as `tipoPessoa` F, Mercado Pago the matching
|
||||
identification type, and only CNPJs are looked up in the company registry.
|
||||
|
||||
The browser may display the calculation, but production payment creation must
|
||||
recalculate and validate all price, quantity, freight, and discount values on
|
||||
recalculate and validate all price, quantity, and freight values on
|
||||
the server. Client-provided totals are never authoritative.
|
||||
|
||||
Normal JPG/PNG uploads are individual artwork by default, including when uploaded
|
||||
@@ -165,14 +184,31 @@ from the by-metre panel. They use the existing loose-artwork editor, printed
|
||||
width, quantity, and live packing canvas; packed height determines metres.
|
||||
Customers uploading an already assembled film-width image must explicitly select
|
||||
the ready-sheet option before uploading. PDF and manual-format ready sheets keep
|
||||
their existing workflow. These models retain their separate approved price tiers;
|
||||
their existing workflow. These models keep their separate prices;
|
||||
image dimensions alone must never classify a normal artwork as a finished sheet.
|
||||
|
||||
A finished sheet someone must open by hand (CDR, AI, PSD, TIFF, or a length the
|
||||
customer typed) pays the top of the ladder plus `MANUAL_FILE_EXTRA_CENTS` per
|
||||
customer typed) pays the product's price plus `MANUAL_FILE_EXTRA_CENTS` per
|
||||
metre (2026-10-13, asked at the 7 October meeting to steer customers to PNG).
|
||||
It defaults to 0; the amount is the client's to set. The Site reads it from
|
||||
`/api/session` and shows it before checkout; `app/core/pricing.py` charges it.
|
||||
The production stack sets it to 200, R$ 2,00 a metre (Dropstar, 2026-10-23);
|
||||
a value set in Portainer overrides it, and it is 0 locally and in CI. The
|
||||
amount is the client's to set. The Site reads it from `/api/session` and shows
|
||||
it before checkout (product page, help text, price table);
|
||||
`app/core/pricing.py` charges it.
|
||||
|
||||
What a file is comes from its first bytes, never from its name (Dropstar's
|
||||
rule D-13, 2026-10-26; a third of their ".cdr" files are PDFs). The Site reads
|
||||
the first bytes when a file is chosen and renames it to its real extension
|
||||
(`nomeReal` in web/site-upload.js): a ".cdr" that is a PDF becomes ".pdf" and
|
||||
is measured and checked as a PDF, without the manual charge; a JPG called
|
||||
".png" is refused as a JPG, naming the file. The server does the same when it
|
||||
scans an upload (`real_name` in app/scanning.py) and stores the real name, so
|
||||
every later decision that reads the name (the manual charge, the JPG refusal,
|
||||
the grade, the original used as its own print file, the folder file names)
|
||||
follows the content even if the browser was bypassed. A name its content
|
||||
agrees with stays: an Illustrator ".ai" is a PDF inside but is still handled
|
||||
by hand, since one saved without PDF content prints a placeholder page. A file
|
||||
too large for the antivirus passes when its content is any accepted format.
|
||||
|
||||
## Freight
|
||||
|
||||
@@ -314,14 +350,26 @@ docs/guias/telas/.
|
||||
|
||||
### Kanban automatic folder (agreed in the 2026-10-07 meeting)
|
||||
|
||||
The Kanban, open on the print room's computer, saves the files to a folder
|
||||
chosen in Integrações (Chrome or Edge; Firefox only downloads). Per computer,
|
||||
it downloads as soon as the order arrives in Arte recebida (the default since
|
||||
2026-10-20), into a `Recebidos` folder inside the chosen one, moved up when
|
||||
the order enters the queue; or only when the order enters the print queue.
|
||||
Files of orders cancelled, deleted or sent back for correction, and files
|
||||
replaced by another final, are removed from the folder
|
||||
(`POST /api/operator/queue/folder`).
|
||||
Dropstar's three folders (asked 2026-10-23, agreed 2026-10-26): the Kanban,
|
||||
open in Chrome or Edge on a factory computer that reaches the server's
|
||||
folder, signed in with a profile that sees every order (Gestão), keeps the
|
||||
orders' files in three folders it creates inside the one chosen in
|
||||
Integrações ("Pastas dos pedidos"), numbered to sort in the flow's order:
|
||||
"1. Arte recebida" (the file arrives when the order does), "2. Arte
|
||||
conferida" (the queue; the file moves there with the card and stays while it
|
||||
prints and is checked in Revisão) and "3. Finalizado" (when the order is
|
||||
released, kept 30 days there). They are created as soon as the main folder
|
||||
is chosen. Correção, a cancellation or a
|
||||
deletion takes the file out; a replaced final is swapped. Orders already
|
||||
printing when the folder is chosen are not downloaded; every order paid after
|
||||
it is, whatever its stage, so a computer that was off catches up when it
|
||||
comes back (Dropstar's rules, 2026-10-26: the folder must reproduce what
|
||||
passed, not only what sits in the columns). A file someone took
|
||||
out is fetched again only when its order moves on (`POST
|
||||
/api/operator/queue/folder`, which also returns the files of orders the
|
||||
folders hold once they print). Who opens each folder is set in the server's
|
||||
folder permissions. Firefox cannot write into folders: it only downloads the
|
||||
files entering Arte conferida.
|
||||
|
||||
Integrações (2026-10-20): only the superadmin (us) has the buttons, the
|
||||
details and the Tiny log there (`integrations` capability, app/core/auth.py).
|
||||
@@ -330,7 +378,7 @@ produces also gets the folder's row with its buttons.
|
||||
|
||||
Machines (2026-10-20, app/machines.py): each order keeps one machine, either
|
||||
chosen in the order panel or given on arrival: the active machine of its
|
||||
product with the fewest metres open (rec, tra, fil, imp, cor), preferring
|
||||
product with the fewest metres open (rec, tra, imp, cor), preferring
|
||||
those below their optional limit in metres, else the least loaded anyway (the
|
||||
Usuários page shows it over the limit). A machine switched off, deleted or no
|
||||
longer printing the product hands its automatic orders, not yet printing, to
|
||||
@@ -339,20 +387,147 @@ the machine form); a linked operator sees only those machines' orders.
|
||||
|
||||
Dropstar's corrections of 2026-10-21 already done: the home example priced as
|
||||
a ready sheet; opening hours 7h to 18h with "send your art any time"; uploads
|
||||
up to 1 GB (MAX_UPLOAD_BYTES, scanned whole by ClamAV); a Designer profile
|
||||
(artwork stages only, every order, no machine, queue or cancelling;
|
||||
DESIGNER_STATES in app/core/auth.py, the "print" capability for the room's
|
||||
side); Números by date range, per machine (metres finished, metres per hour
|
||||
up to 1 GB (MAX_UPLOAD_BYTES; Dropstar moved it to 4 GB on 2026-10-28: ClamAV scans
|
||||
up to its 2000 MiB, a larger file passes by the format check); a Designer profile
|
||||
(artwork stages only, every order, no machine, queue or cancelling; MOVES
|
||||
in app/core/auth.py, the "print" capability for the room's side); Números by date range, per machine (metres finished, metres per hour
|
||||
in Imprimindo, last finished, now) and orders apart from passages. A machine's
|
||||
metres are the film printed (item `metres`), never the billed ones, and time
|
||||
two orders spent in Imprimindo together counts once; a stage's median is per
|
||||
order, the sum of its passages. Layout version 3 (web/site-packing.js): rows
|
||||
with exact sizes, 5 mm margins top and bottom and between rows, and across
|
||||
the width 5 mm or the space left shared out equally (1,5 mm at least); the
|
||||
shape packing is used only when it saves 1 cm or more. Waiting on
|
||||
Dropstar: the Tiny category/seller/tag conflict, residue and opaque background
|
||||
blocking, the print-file footer, the packing margins, the DTF terms, the
|
||||
manual-file value, the proof print, and mirroring.
|
||||
shape packing is used only when it saves 1 cm or more. A ready sheet with a
|
||||
residue (ink under 2 mm on both sides, measured in pixels from the ink map in
|
||||
web/site-sheet.js) or without transparency (under 1,5 % of transparent
|
||||
pixels; every JPG) cannot be paid for; the preview circles each dot. PDFs
|
||||
over 150 MB and CDR/AI/PSD/TIFF are not checked. The generated print PDF ends
|
||||
in a 1,5 cm footer band below the layout, outside the billed length: "DROPSTAR
|
||||
· Pedido DTF-<Kanban number> · Item 1/2 · date · billed metres" in black
|
||||
Helvetica, after Dropstar's logo (app/assets), about 1 cm tall (31 pt, Dropstar
|
||||
2026-10-28; smaller only when it would not fit the 27 cm UV film). A sheet
|
||||
longer than 5,08 m (Acrobat's page limit) is written at its real size on one
|
||||
page since 2026-10-28: with PDF's /UserUnit scale, CorelDRAW, where Dropstar
|
||||
checks files, showed a 12,8 m sheet as 18,9 x 425 cm. PRINT_PAGE_SCALE=true
|
||||
in the stack goes back to /UserUnit, for a RIP that refuses pages over 5,08 m. An original used whole as its
|
||||
own print file (over 300 MB) has no footer. The print proof (app/proof.py):
|
||||
an order above 10 m, or one whose customer ticked "quero aprovar uma prova" at
|
||||
checkout (that one arrives marked Aguardando contato; the box shows, and the
|
||||
server keeps it, only above 10 m since 2026-10-28), cannot reach Finalizado
|
||||
before the print room marks Prova OK; the proof is not billed (up to 30 cm,
|
||||
at most 3 per order). Dropstar's answers of 2026-10-23: JPG is refused in every
|
||||
product; a PDF over 150 MB is flagged before payment; any non-square piece is
|
||||
tried both ways; a mirrored (UV) order is flagged on the card and in the PDF
|
||||
footer; files are named DTF-<number>-item-<n>, the code the Kanban copies;
|
||||
manual files cost R$ 2,00 more a metre. Also settled by Dropstar on
|
||||
2026-10-23: no seller on Tiny orders (Tiny sets it from the contact; the
|
||||
marcador SITE DTF separates the channel), the DTF terms page approved, the UV
|
||||
mirror stays, the designer does not move to the print queue, and Aguardando
|
||||
contato has no deadline of its own. There is no videocall: open points are
|
||||
settled in writing.
|
||||
|
||||
Done on 2026-10-26: the single price per product Dropstar asked for on
|
||||
2026-10-23 (see Commercial rules), on the Site and the server.
|
||||
|
||||
Dropstar's flow of 2026-10-23, in the code since 2026-10-26 (app/runtime.py,
|
||||
app/core/auth.py): the board is Arte recebida, Arte conferida, Imprimindo,
|
||||
Correção, Revisão, Finalizado. Fila de impressão left: Arte conferida is the
|
||||
queue, entered only with every item's final file approved, kept as approved
|
||||
there (to change one, the order goes back to Arte recebida), with its card
|
||||
order as the print order and "Baixar" for the room; orders that were in the
|
||||
queue were moved to Arte conferida with a line in their history. Who moves
|
||||
what (MOVES): the Designer Arte recebida to Arte conferida, asks for
|
||||
corrections and brings the new art back to Arte recebida or Arte conferida;
|
||||
the Operador Arte conferida to Imprimindo to Revisão; the Revisor Revisão to
|
||||
Finalizado, so nobody in the room releases their own print, and the
|
||||
Administrador may release too (the user, 2026-10-28; the superadmin for
|
||||
support); Gestão, the coordination, only pulls back, always with a reason
|
||||
(rule D-20 of Dropstar's internal rules, 2026-10-26): Correção from any
|
||||
stage, or a step back; Admin, Dropstar's own login, every other move,
|
||||
including Correção straight to Revisão. A step back belongs to whoever makes
|
||||
the move it undoes, and to Admin and Gestão. Tiny: Arte
|
||||
conferida sets "Preparando envio" and Finalizado "Pronto para envio", for
|
||||
delivery orders too; nothing for Imprimindo, Correção or Revisão. Prova OK
|
||||
still comes before Finalizado. The customer's portal shows the same steps.
|
||||
|
||||
Still to do (2026-10-26):
|
||||
- The DTF number in Tiny's `numeroPedidoEcommerce`: sent since 2026-10-26,
|
||||
next to the purchase order `numeroOrdemCompra` (which the resend check
|
||||
searches). Tiny keeps it only with a channel: `TINY_ECOMMERCE_ID=9594`,
|
||||
Dropstar's "API do ERP" integration (installed 2026-10-27). The store's own
|
||||
channel (DROPSTAR, 9336) refuses orders sent through the API. Confirmed
|
||||
with test order 145329.
|
||||
- Before TINY_STATUS_UPDATES goes on: Finalizado now sets "Pronto para
|
||||
envio" on delivery orders too, so the client's n8n must not send them the
|
||||
pickup message it sends on that situação.
|
||||
- Dropstar creates the Revisor users right after the redeploy that brings the
|
||||
new flow (the profile exists only from then): until then orders wait in
|
||||
Revisão, and only the superadmin can release them.
|
||||
- Done 2026-10-27, from Dropstar's answers on their internal rules: "Arte
|
||||
tratada", an order whose approved final is not the customer's art (not the
|
||||
file generated from it, not an original, not a correction they sent), is
|
||||
flagged on the card and in the order, and Números counts those orders by who
|
||||
approved the final, for the designer's productivity; a cancelled order's
|
||||
money stays as the customer's credit in their financial control (D-15, the
|
||||
Kanban's cancel text says so, nothing on the Site); the Kanban keeps
|
||||
deleting Finalizado files after 30 days; the footer gets the white spot.
|
||||
- Every order has an origin (Dropstar's rules D-21 and D-35, 2026-10-26):
|
||||
`site`, `dropflow` or `atendimento`, in dtf_local.orders.origin, required
|
||||
and without a default (a default would become the origin of almost
|
||||
everything, the document says), limited to the three by a check. The Site's
|
||||
orders are marked `site` where they are created (app/payments.py); the
|
||||
orders from before the column became `site`. The Kanban shows it on every
|
||||
card and in the order panel, filters by it (Origem), and Números has a "Por
|
||||
origem" table: orders, metres, money received and the median time from
|
||||
payment to Finalizado for each way in, Aguardando contato left out.
|
||||
- An order paid outside the system is registered from its Site quote (D-35;
|
||||
the user's answers of 2026-10-27): the team builds the cart on the Site as
|
||||
a customer would (the art comes in through the Site, D-08), stops at the
|
||||
payment step, and in the Kanban's Cotações, on the approved quote, picks the
|
||||
origin and how it was paid (Pix, cartão, dinheiro, crédito do cliente),
|
||||
neither preselected, with an optional note. The price is the quote's, the
|
||||
Site's table price. Allowed to Administrador and Gestão (the "enter"
|
||||
capability); not Vendedor, who only views the board (D-30). The order's payment is `{'provider': 'manual',
|
||||
'method', 'note', 'operator'}`; it counts in Números like any paid order and
|
||||
the customer gets the usual paid e-mail. An Atendimento (or Site) order
|
||||
goes to Tiny like a Site one, its internal note saying "pago fora do site"
|
||||
and how, each way named as Tiny's forma de recebimento (Pix, cartão, and
|
||||
from Marcus on 2026-10-27 Dinheiro 919478944 and, for the customer's credit,
|
||||
their "CORREÇÃO DTF" 977493654; RECEIPT_METHODS in app/tiny.py). A Dropflow
|
||||
order goes to Tiny too, in its own revenue category "DTF DROPFLOW"
|
||||
(987032506, CATEGORIES in app/tiny.py), not DTF SITE (D-21).
|
||||
- Rework register (Dropstar's rules D-02 to D-04; the user's answers of
|
||||
2026-10-27), dtf_local.reworks. Gestão opens it from the order panel's menu
|
||||
("Abrir retrabalho") with its cause, the metres redone (the order's printed
|
||||
metres to start) and a note: falha de impressão, perfil de cor, erro de
|
||||
tratamento, erro de pedido, or arte aprovada pelo cliente (outside the
|
||||
goal, D-04). The cause never changes after (D-03: there is no route for it).
|
||||
An Administrador authorizes it or declines it with a reason, never one they
|
||||
opened; the reprint is never held up, and only an authorized rework counts.
|
||||
Who printed it (who last sent the order to Revisão) is kept, as the house's
|
||||
rework enters the printer's pay. Números, "Retrabalho": per cause, the
|
||||
metres redone over the film printed in the period (Por máquina), by the day
|
||||
the rework was opened, against 0,4% per cause and 1,6% for the house; the
|
||||
house's by who printed it; and the ones waiting for authorization. A card
|
||||
with a rework carries a "Retrabalho" badge.
|
||||
- Still open from the internal rules (docs received 2026-10-26): customer
|
||||
credit as a payment the system keeps track of (today "crédito do cliente"
|
||||
is only how a registered order was paid). Done 2026-10-27: the folders catch up on what passed while the Kanban
|
||||
computer was off, time in "Aguardando contato" no longer counts in Números'
|
||||
time figures (D-38; each wait is kept in dtf_local.contact_waits, from mark
|
||||
to clear), and a file's type comes from its first bytes (D-13, see the
|
||||
commercial rules).
|
||||
- Settled on 2026-10-26: the DTF SITE category (986932924, CATEGORY in app/tiny.py),
|
||||
the white spot also under the print PDF's footer (nothing to change here),
|
||||
and the montador's order format (customer, files, product, the batch with
|
||||
the customer's ERP sale numbers, labels or pickup) with a record of each
|
||||
batch, both for after launch.
|
||||
- The three folders, once deployed: Marcus sets the main folder on the
|
||||
factory computer (Chrome, Integrações > Pastas dos pedidos); check on the
|
||||
first print whether FlexiPRINT keeps reading the file in Arte conferida
|
||||
after import (the file only leaves that folder at Finalizado).
|
||||
- Anchor-customer orders from the montador: after the launch; the team's idea
|
||||
is that Graphs handles that side and sends the orders to this Kanban.
|
||||
|
||||
### Active localhost milestone (2026-09-15)
|
||||
|
||||
@@ -381,7 +556,7 @@ as references and are not imported or started by Compose.
|
||||
one-metre minimum, ten-centimetre rounding, freight, and final totals. Immutable
|
||||
approved quotes expire after 24 hours. A customer confirms the server total
|
||||
on the Site to create one idempotent local paid order.
|
||||
- Paid orders use `rec`, `tra`, `fil`, `imp`, `cor`, `fin`, with allowed transitions,
|
||||
- Paid orders use `rec`, `tra`, `imp`, `cor`, `rev`, `fin` (`fil` until 2026-10-26), with allowed transitions,
|
||||
operator authentication, concurrency checks, and durable movement history.
|
||||
Local mock integration receipts are visible in the Kanban.
|
||||
- The customer portal at `/portal.html` supports local registration/login,
|
||||
|
||||
@@ -202,8 +202,10 @@ Kanban, then switch on "Receber alertas por e-mail" for whoever wants alerts in
|
||||
Usuários. Use a sending domain with SPF and DKIM, or the messages land in spam.
|
||||
|
||||
`MANUAL_FILE_EXTRA_CENTS` is the per-metre charge on finished sheets someone
|
||||
opens by hand (CDR, AI, PSD, TIFF); 500 is R$ 5,00 a metro. Change it only on
|
||||
the client's instruction; the Site shows the new price after the redeploy.
|
||||
opens by hand (CDR, AI, PSD, TIFF). The default is 200, R$ 2,00 a metro
|
||||
(Dropstar, 2026-10-23); a value set in the stack's environment overrides it.
|
||||
Change it only on the client's instruction; the Site shows the new price after
|
||||
the redeploy.
|
||||
|
||||
## 8. Correios
|
||||
|
||||
|
||||
@@ -847,6 +847,8 @@ print-file evidence still need correction before this item can close.
|
||||
where a server-side packer (3.2) has to agree, which was the point of splitting.
|
||||
- `[ ]` 5.7 — Commercial rules duplicated between `FAIXAS` (JS) and `TIERS` (Python)
|
||||
`(F26)`. `test_pricing` guards parity; generate one from the other instead.
|
||||
2026-10-26: one price per product now, `PRECO` (JS) and `PRICES` (Python);
|
||||
`test_pricing` still guards parity.
|
||||
- `[ ]` 5.11 — Nothing tests the schema against an empty database. The 4.1 indexes
|
||||
were added next to the existing one, which sits before the tables they name, so
|
||||
`CREATE INDEX ... ON dtf_local.order_files` ran before that table existed. Every
|
||||
|
||||
@@ -27,6 +27,9 @@ server {
|
||||
location ~ ^/conta(/(entrar|pedidos|dados|redefinir))?/?$ {
|
||||
try_files /portal.html =404;
|
||||
}
|
||||
location ~ ^/termos/?$ {
|
||||
try_files /termos.html =404;
|
||||
}
|
||||
location / { try_files $uri $uri/ =404; }
|
||||
}
|
||||
server {
|
||||
|
||||
@@ -51,14 +51,14 @@ def main():
|
||||
approved_quote(client, quote, [item])
|
||||
orders.append(client.call('/orders/dev-paid', {'quote_id': quote['id']}))
|
||||
# Spread them over the production stages, one waiting for a correction.
|
||||
stages = {0: ['tra', 'fil', 'imp', 'fin'], 1: ['tra', 'fil', 'imp', 'fin'], 2: ['tra', 'fil', 'imp'],
|
||||
3: ['tra', 'fil'], 4: ['tra'], 5: ['cor']}
|
||||
stages = {0: ['tra', 'imp', 'rev', 'fin'], 1: ['tra', 'imp', 'rev', 'fin'], 2: ['tra', 'imp', 'rev'],
|
||||
3: ['tra', 'imp'], 4: ['tra'], 5: ['cor']}
|
||||
for index, path in stages.items():
|
||||
order = orders[index]
|
||||
version = order['version']
|
||||
for state in path:
|
||||
if state == 'fil':
|
||||
# The print queue takes approved final files, as on the Kanban.
|
||||
if state == 'tra':
|
||||
# Arte conferida, the print queue, takes approved final files, as on the Kanban.
|
||||
final = upload_bytes(client, b'DEMO FINAL %d' % index, order_id=order['id'])
|
||||
version = client.call('/operator/orders/' + order['id'] + '/final-files',
|
||||
{'version': version, 'files': [{'item_index': 0, 'upload_id': final}],
|
||||
|
||||
@@ -122,7 +122,7 @@ try{
|
||||
encaixar=(pieces,width)=>{const result=original(pieces,width);
|
||||
if(pieces.some(p=>p.a))window.lastLayout={altura:result.altura,pos:result.pos.map(p=>({x:p.x,y:p.y,w:p.w,h:p.h,rot:p.rot}))};
|
||||
return result;};
|
||||
window.sendImage=async(type='image/jpeg',drop=false)=>{
|
||||
window.sendImage=async(type='image/png',drop=false)=>{
|
||||
const c=document.createElement('canvas');c.width=200;c.height=400;
|
||||
const ctx=c.getContext('2d');ctx.fillStyle='white';ctx.fillRect(0,0,200,400);
|
||||
ctx.fillStyle='#222';ctx.fillRect(85,20,20,360);ctx.fillRect(25,100,140,20);
|
||||
@@ -133,12 +133,15 @@ try{
|
||||
if(drop)$('zona').dispatchEvent(new DragEvent('drop',{dataTransfer:dt,bubbles:true,cancelable:true}));
|
||||
else{$('inp').files=dt.files;$('inp').dispatchEvent(new Event('change',{bubbles:true}));}
|
||||
};
|
||||
// A genuine mounted sheet spans the film width with printable resolution.
|
||||
window.sendSheet=async()=>{
|
||||
// A genuine mounted sheet spans the film width with printable resolution,
|
||||
// on a transparent background; or with a solid one, or a residue dot.
|
||||
window.sendSheet=async({fundo=false,ponto=false}={})=>{
|
||||
const cm=larguraFilme(), px=Math.ceil(cm/2.54*150);
|
||||
const c=document.createElement('canvas');c.width=px;c.height=Math.round(px*0.6);
|
||||
const ctx=c.getContext('2d');ctx.fillStyle='white';ctx.fillRect(0,0,c.width,c.height);
|
||||
const ctx=c.getContext('2d');
|
||||
if(fundo){ctx.fillStyle='white';ctx.fillRect(0,0,c.width,c.height);}
|
||||
ctx.fillStyle='#222';ctx.fillRect(40,40,px/4,px/4);
|
||||
if(ponto)ctx.fillRect(Math.round(px*0.8),Math.round(c.height/2),4,4);
|
||||
const blob=await new Promise(r=>c.toBlob(r,'image/png'));
|
||||
const dt=new DataTransfer();dt.items.add(new File([blob],'folha-montada.png',{type:'image/png'}));
|
||||
$('inp').files=dt.files;$('inp').dispatchEvent(new Event('change',{bubbles:true}));
|
||||
@@ -148,6 +151,14 @@ try{
|
||||
// Reproduce the reported entry path, with no navigation workaround.
|
||||
// Navigation links must reach the chooser, never preselect a product.
|
||||
assert.equal(await evaluate(`document.querySelectorAll('[data-modo-cta]').length`),0);
|
||||
// One price per product (Dropstar, 2026-10-23), the same in the top chip, the
|
||||
// home example, the product cards and the price table; nothing on the page
|
||||
// still prices by the grade.
|
||||
assert.deepEqual(await evaluate(`(()=>{const de=m=>[...document.querySelectorAll('[data-preco="'+m+'"]')].map(e=>e.textContent);
|
||||
return {file:de('file'),avulsa:de('avulsa'),uvfile:de('uvfile'),uv:de('uv'),
|
||||
stale:/14,90|conforme a nota|desconto|escada|menor preço da tabela/i.test(document.body.textContent)};})()`),
|
||||
{file:['R$ 19,90','R$ 19,90','R$ 19,90','R$ 19,90'],avulsa:['R$ 21,90','R$ 21,90'],
|
||||
uvfile:['R$ 79,90','R$ 79,90'],uv:['R$ 89,90','R$ 89,90'],stale:false});
|
||||
await click('[data-modo="file"]');
|
||||
// Opening a product paints on the next frame; on a busy runner the check
|
||||
// must wait for it rather than race it.
|
||||
@@ -156,33 +167,41 @@ try{
|
||||
assert.deepEqual(await evaluate(`({shown:!$('tipoEnvio').hidden,
|
||||
on:[...document.querySelectorAll('#tipoEnvio .cam.on')].map(b=>b.dataset.tipo)})`),
|
||||
{shown:true,on:['folha']});
|
||||
await evaluate(`(()=>{const f=new File(['x'],'oversize.cdr');Object.defineProperty(f,'size',{value:1073741824+1});sel([f]);})()`);
|
||||
assert.equal(await evaluate(`folhas.length===0 && $('recusa').textContent.includes('1 GB')`),true,
|
||||
'files beyond the 1 GB upload limit are rejected before browser analysis');
|
||||
await evaluate(`(()=>{const f=new File(['x'],'oversize.cdr');Object.defineProperty(f,'size',{value:4294967296+1});return sel([f]);})()`);
|
||||
assert.equal(await evaluate(`folhas.length===0 && $('recusa').textContent.includes('4 GB')`),true,
|
||||
'files beyond the 4 GB upload limit are rejected before browser analysis');
|
||||
// A large sheet (here 900 MB) is the normal order: graded from the pixel size in its
|
||||
// header, never decoded. 6732 x 35433 px across 57 cm is 3 m at 300 DPI.
|
||||
await evaluate(`(()=>{const h=new Uint8Array(33);h.set([0x89,0x50,0x4E,0x47,0x0D,0x0A,0x1A,0x0A,0,0,0,13,0x49,0x48,0x44,0x52]);
|
||||
const v=new DataView(h.buffer);v.setUint32(16,6732);v.setUint32(20,35433);h.set([8,6,0,0,0],24);
|
||||
const f=new File([h],'folha-grande.png');Object.defineProperty(f,'size',{value:900*1048576});sel([f]);})()`);
|
||||
const f=new File([h],'folha-grande.png');Object.defineProperty(f,'size',{value:900*1048576});return sel([f]);})()`);
|
||||
await waitFor(()=>evaluate(`folhas.length===1 && !!folhas[0].an`),'large sheet graded from its header');
|
||||
assert.deepEqual(await evaluate(`({grande:folhas[0].an.grande,dpi:folhas[0].an.dpi,alt:folhas[0].med.alt,preview:!!folhas[0].previewSrc})`),
|
||||
{grande:true,dpi:300,alt:300,preview:false});
|
||||
await evaluate(`folhas=[];pintaFolha()`);
|
||||
await evaluate(`pickTipo('avulsa')`);
|
||||
assert.equal(await evaluate('modo'),'avulsa');
|
||||
// A large JPG artwork cannot be read in parts: it is measured from its
|
||||
// header and placed as a full box, with the discount, instead of refused.
|
||||
await evaluate(`(()=>{const h=new Uint8Array(20);h.set([0xFF,0xD8,0xFF,0xC0,0,17,8,0x09,0x3A,0x09,0x3A,3]);
|
||||
const f=new File([h],'arte-grande.jpg');Object.defineProperty(f,'size',{value:400*1048576});sel([f]);})()`);
|
||||
await waitFor(()=>evaluate(`artes.length===1 && artes[0].semPrevia===true`),'large JPG artwork measured from its header');
|
||||
// JPG has no transparency: refused in loose artwork as in a sheet (Dropstar,
|
||||
// 2026-10-23), with the reason, before anything is read.
|
||||
await evaluate(`sel([new File(['x'],'arte.jpg',{type:'image/jpeg'})])`);
|
||||
assert.equal(await evaluate(`artes.length===0 && $('recusa').textContent.includes('JPG não dá para enviar')`),true);
|
||||
// The content decides, not the name (D-13): a JPG called ".png" is refused as a JPG.
|
||||
await evaluate(`sel([new File([new Uint8Array([0xFF,0xD8,0xFF,0xE0])],'disfarce.png',{type:'image/png'})])`);
|
||||
assert.equal(await evaluate(`artes.length===0 && $('recusa').textContent.includes('disfarce.png é JPG')`),true);
|
||||
// A large WebP artwork cannot be read in parts: it is measured from its
|
||||
// header and placed as a full box, with its grade, instead of refused.
|
||||
await evaluate(`(()=>{const h=new Uint8Array(30);h.set([0x52,0x49,0x46,0x46,0,0,0,0,0x57,0x45,0x42,0x50,0x56,0x50,0x38,0x58]);
|
||||
h.set([0x39,0x09,0x00,0x39,0x09,0x00],24);
|
||||
const f=new File([h],'arte-grande.webp');Object.defineProperty(f,'size',{value:400*1048576});return sel([f]);})()`);
|
||||
await waitFor(()=>evaluate(`artes.length===1 && artes[0].semPrevia===true`),'large WebP artwork measured from its header');
|
||||
await fill('[data-cm]',20);
|
||||
await waitFor(()=>evaluate(`!!itemAtual?.production?.sources?.length`),'large JPG artwork packed');
|
||||
await waitFor(()=>evaluate(`!!itemAtual?.production?.sources?.length`),'large WebP artwork packed');
|
||||
assert.deepEqual(await evaluate(`({dpi:Math.round(dpiDe(artes[0])),src:!!artes[0].src,
|
||||
measurement:itemAtual.production.sources[0].measurement,note:$('lista').textContent.includes('Sem prévia')})`),
|
||||
{dpi:300,src:false,measurement:'file',note:true});
|
||||
await evaluate(`artes=[];pintaArtes()`);
|
||||
await evaluate('sendImage()');
|
||||
await waitFor(()=>evaluate(`artes.length===1 && !!artes[0].src`),'JPG artwork model');
|
||||
await waitFor(()=>evaluate(`artes.length===1 && !!artes[0].src`),'PNG artwork model');
|
||||
assert.deepEqual(await evaluate(`({mode:modo,sheets:folhas.length,width:artes[0].cm,quantity:artes[0].q})`),{mode:'avulsa',sheets:0,width:0,quantity:1});
|
||||
await fill('[data-cm]',20);await fill('[data-q]',6);
|
||||
let layout=await packed(6);
|
||||
@@ -205,11 +224,11 @@ try{
|
||||
await fill('[data-q]',9);layout=await packed(9);assert.equal(layout.height,92);
|
||||
await click('[data-giro]');
|
||||
await waitFor(()=>evaluate('lastLayout?.altura===24.5 && metros===0.245'),'rotation updates packing');
|
||||
const beforeMirror=await evaluate(`$('vArea').querySelector('canvas').toDataURL()`);
|
||||
await click('[data-esp]');
|
||||
await waitFor(()=>evaluate(`$('vArea').querySelector('canvas').toDataURL()!==${JSON.stringify(beforeMirror)}`),'mirror updates pixels');
|
||||
// A textile transfer is pressed face down: mirrored, it prints backwards on
|
||||
// the garment. Textile has no mirror button (Dropstar, 2026-10-21).
|
||||
assert.equal(await evaluate(`!!document.querySelector('[data-esp]')`),false,'textile has no mirror button');
|
||||
assert.equal(await evaluate('metros'),0.245);
|
||||
await waitFor(()=>evaluate(`itemAtual?.production?.sources[0]?.mirrored===true`),'transforms in production record');
|
||||
await waitFor(()=>evaluate(`itemAtual?.production?.sources[0]?.mirrored===false`),'transforms in production record');
|
||||
assert.deepEqual(await evaluate(`({rotation:itemAtual.production.sources[0].rotation_degrees,copies:itemAtual.production.sources[0].copies})`),
|
||||
{rotation:90,copies:9});
|
||||
await waitFor(()=>evaluate(`itemAtual?.qualityStatus==='rejected'`),'low resolution refusal');
|
||||
@@ -240,14 +259,19 @@ try{
|
||||
return {altura:+r.altura.toFixed(2),folga:+r.folga.toFixed(3),
|
||||
xs:[...new Set(r.pos.map(p=>+p.x.toFixed(2)))],ys:[...new Set(r.pos.map(p=>+p.y.toFixed(2)))]};})()`),
|
||||
{altura:89.42,folga:0.2,xs:[0.2,28.6],ys:[0.5,30.14,59.78]});
|
||||
// UV, 28,5 cm: two 14 cm pieces still share a row, 1,67 mm apart.
|
||||
assert.equal(await evaluate(`(()=>{const a={};const r=encaixar([{w:14,h:10,img:null,a},{w:14,h:10,img:null,a}],28.5);
|
||||
return new Set(r.pos.map(p=>p.y)).size===1 && Math.abs(r.folga-0.5/3)<1e-9})()`),true);
|
||||
// UV, 27 cm: two 13,2 cm pieces still share a row, 2 mm apart.
|
||||
assert.equal(await evaluate(`(()=>{const a={};const r=encaixar([{w:13.2,h:10,img:null,a},{w:13.2,h:10,img:null,a}],27);
|
||||
return new Set(r.pos.map(p=>p.y)).size===1 && Math.abs(r.folga-0.6/3)<1e-9})()`),true);
|
||||
// A long piece stands up when that shortens the sheet: 30 x 10 cm, eight copies,
|
||||
// five to a row turned instead of one to a row as sent.
|
||||
assert.deepEqual(await evaluate(`(()=>{const a={};const r=encaixar(Array.from({length:8},()=>({w:30,h:10,img:null,a})),57);
|
||||
return {rot:[...new Set(r.pos.map(p=>p.rot))],altura:+r.altura.toFixed(2)}})()`),
|
||||
{rot:[90],altura:61.5});
|
||||
// Any piece that is not square is tried both ways (Dropstar, 2026-10-23):
|
||||
// 19,5 x 18,5 cm fits 2 to a row standing and 3 lying down.
|
||||
assert.deepEqual(await evaluate(`(()=>{const a={};const r=encaixar(Array.from({length:6},()=>({w:19.5,h:18.5,img:null,a})),57);
|
||||
return {rot:[...new Set(r.pos.map(p=>p.rot))],altura:+r.altura.toFixed(2)}})()`),
|
||||
{rot:[90],altura:40.5});
|
||||
await click('[data-rm]');
|
||||
assert.equal(await evaluate(`artes.length===0 && itemAtual===null && !cartPodeEnviar()`),true,
|
||||
'removed artwork cannot remain in the cart');
|
||||
@@ -264,7 +288,22 @@ try{
|
||||
await click('#bVoltar');await click('[data-modo="file"]');
|
||||
await evaluate('sendSheet()');
|
||||
await waitFor(()=>evaluate('folhas.length===1 && !!folhas[0].previewSrc && metros===0.342'),'ready-sheet image');
|
||||
assert.deepEqual(await evaluate(`({mode:modo,art:artes.length,title:$('montcabTit').textContent,rate:precoBase(100)})`),{mode:'file',art:0,title:'Sua folha',rate:14.9});
|
||||
// On its way at once, with its own row under the uploader (Dropstar,
|
||||
// 2026-10-29). There is no storage here, so it fails, and says so with a
|
||||
// way to try again; tests/browser_test.mjs sends it for real.
|
||||
await waitFor(()=>evaluate(`!!dtfEnvio.estado(folhas[0].f)`),'the sheet starts uploading at once');
|
||||
await waitFor(()=>evaluate(`$('envios').textContent.includes('Não foi possível enviar folha-montada.png') &&
|
||||
!!$('envios').querySelector('[data-envio]')`),'a failed upload says so under the uploader');
|
||||
assert.deepEqual(await evaluate(`({mode:modo,art:artes.length,title:$('montcabTit').textContent,rate:precoMetro()})`),{mode:'file',art:0,title:'Sua folha',rate:19.9});
|
||||
// One price per product (Dropstar, 2026-10-23): the sheet is graded, and the
|
||||
// grade is shown, but the metre costs the same as for any other grade.
|
||||
await waitFor(()=>evaluate('itemAtual?.nota>0'),'graded ready sheet');
|
||||
assert.deepEqual(await evaluate(`({unit:itemAtual.unit,total:itemAtual.total,shown:$('cNota').textContent===itemAtual.nota+'/100',
|
||||
metre:$('cMetro').textContent,ladder:!!document.getElementById('cEscada'),
|
||||
discount:/desconto/i.test($('carrLin').textContent+$('resLin').textContent+$('compra').textContent)})`),
|
||||
{unit:19.9,total:19.9,shown:true,metre:'R$ 19,90',ladder:false,discount:false});
|
||||
assert.deepEqual(await evaluate(`({folha:$('tipoFolhaPreco').textContent,avulsa:$('tipoAvulsaPreco').textContent})`),
|
||||
{folha:'R$ 19,90 /m',avulsa:'R$ 21,90 /m'});
|
||||
assert.equal(await evaluate(`document.querySelectorAll('[data-cm]').length`),0);
|
||||
// With a sheet loaded the declaration is locked; it cannot flip under the customer.
|
||||
assert.equal(await evaluate(`document.querySelector('#tipoEnvio .cam[data-tipo="avulsa"]').disabled`),true);
|
||||
@@ -272,7 +311,47 @@ try{
|
||||
await waitFor(()=>evaluate('metros===0.684'),'ready-sheet repetitions');
|
||||
assert.equal(await evaluate(`document.querySelectorAll('.folhaPrevia').length`),1);
|
||||
await evaluate(`(()=>{folhas.push({f:new File(['manual'],'manual.cdr'),med:null,rep:1,m:1,an:null});pintaFolha();})()`);
|
||||
await waitFor(()=>evaluate(`itemAtual?.nota===0 && itemAtual?.unit===TABELA[modo]`),'mixed analyzed and manual sheets use table pricing');
|
||||
await waitFor(()=>evaluate(`itemAtual?.nota===0 && itemAtual?.unit===PRECO[modo]+TAXA_MANUAL`),'mixed analyzed and manual sheets: the price plus the manual charge');
|
||||
// Residue and a solid background stop the order before payment (Dropstar,
|
||||
// 2026-10-21). A residue is ink under 2 mm on both sides, measured in real
|
||||
// millimetres: the same dot, wherever it falls on the 1 mm grid, gets the
|
||||
// same verdict, from 0,5 to 4 mm.
|
||||
assert.deepEqual(await evaluate(`(async()=>{
|
||||
const medir=async(mm,dx,dy)=>{const c=document.createElement('canvas');c.width=5700;c.height=600;
|
||||
const ctx=c.getContext('2d');ctx.fillStyle='#000';ctx.fillRect(100,100,3000,300);
|
||||
const lado=Math.round(mm*10);ctx.fillRect(4000+dx,300+dy,lado,lado);
|
||||
return analisarMapa(await mapaDaImagem(c,57)).residuos;};
|
||||
const out={};
|
||||
for(const mm of [0.5,1.5,1.9,2.1,4])out[mm]=[await medir(mm,0,0),await medir(mm,5,0),await medir(mm,0,5),await medir(mm,5,5)];
|
||||
return out;})()`),
|
||||
{'0.5':[1,1,1,1],'1.5':[1,1,1,1],'1.9':[1,1,1,1],'2.1':[0,0,0,0],'4':[0,0,0,0]});
|
||||
// A large PNG is read as a stream; every pixel goes into the same ink map.
|
||||
assert.deepEqual(await evaluate(`(async()=>{
|
||||
const c=document.createElement('canvas');c.width=5700;c.height=600;
|
||||
const ctx=c.getContext('2d');ctx.fillStyle='#000';ctx.fillRect(100,100,3000,300);ctx.fillRect(4005,305,12,12);
|
||||
const blob=await new Promise(r=>c.toBlob(r,'image/png'));
|
||||
const lido=await previaPngGrande(new File([blob],'folha.png'),600,null,57);
|
||||
const a=analisarMapa(lido.mapa), b=analisarMapa(await mapaDaImagem(c,57));
|
||||
return {stream:[a.residuos,a.artes,a.fundoChapado,a.pontos[0].mm],direct:[b.residuos,b.artes,b.fundoChapado,b.pontos[0].mm]};})()`),
|
||||
{stream:[1,1,false,1.2],direct:[1,1,false,1.2]});
|
||||
await click('#bVoltar');await click('[data-modo="file"]');
|
||||
await evaluate('sendSheet({ponto:true})');
|
||||
await waitFor(()=>evaluate(`folhas.length===1 && folhas[0].pct==null && folhas[0].an?.residuos===1`),'residue found');
|
||||
await waitFor(()=>evaluate(`$('aoVivo').textContent.includes('ponto de recorte') && itemAtual===null`),'residue stops the order');
|
||||
assert.equal(await evaluate(`$('lista').textContent.includes('Sobrou 1 ponto de recorte na sua folha')`),true);
|
||||
await waitFor(()=>evaluate(`folhas[0].previewSrc.startsWith('data:image/webp')`),'residue circled on the preview');
|
||||
// Unless the customer accepts printing the dot (Dropstar, 2026-10-29): ticked,
|
||||
// the sheet goes on and the item says how many dots were accepted.
|
||||
assert.equal(await evaluate(`$('lista').textContent.includes('Esta arte tem 1 ponto menor que 2 mm. Estou ciente e aceito imprimir assim')`),true);
|
||||
await click('[data-residuo="0"]');
|
||||
await waitFor(()=>evaluate(`itemAtual?.residueAccepted===1 && !$('lista').textContent.includes('Sobrou 1 ponto')`),'accepted residue lets the sheet go on');
|
||||
await click('[data-residuo="0"]');
|
||||
await waitFor(()=>evaluate(`itemAtual===null && $('aoVivo').textContent.includes('ponto de recorte')`),'unticked, the residue stops it again');
|
||||
await evaluate(`folhas=[];pintaFolha()`);
|
||||
await evaluate('sendSheet({fundo:true})');
|
||||
await waitFor(()=>evaluate(`folhas[0]?.an?.fundoChapado===true && itemAtual===null && $('aoVivo').textContent.includes('fundo transparente')`),'solid background stops the order');
|
||||
assert.equal(await evaluate(`$('lista').textContent.includes('O fundo da sua folha não é transparente')`),true);
|
||||
await evaluate(`folhas=[];pintaFolha()`);
|
||||
// An image too small to span the film is refused, never silently repriced.
|
||||
await click('#bVoltar');await click('[data-modo="file"]');
|
||||
await evaluate('sendImage()');
|
||||
@@ -296,6 +375,10 @@ try{
|
||||
assert.deepEqual(rotated,{larg:50.8,alt:25.4,fonte:'página do PDF · UserUnit 2'});
|
||||
const rendered=await evaluate(`rasterizarPdf(${pdfFile(pdfData({media:'[0 0 720 1440]',crop:'[0 0 360 720]',rotate:90,unit:2}))},50.8,25.4).then(r=>({ok:!!r.tela,error:r.erro||null}))`);
|
||||
assert.deepEqual(rendered,{ok:true,error:null});
|
||||
// A PDF sheet gets the same ink map, rendered in strips: a blank page is all transparent.
|
||||
const mapped=await evaluate(`rasterizarPdf(${pdfFile(pdfData())},25.4,12.7,true).then(r=>{const a=analisarMapa(r.mapa);
|
||||
return {fundo:a.fundoChapado,residuos:a.residuos,largura:r.mapa.wPx}})`);
|
||||
assert.deepEqual(mapped,{fundo:false,residuos:0,largura:1270});
|
||||
const multi=await evaluate(`medirFolha(${pdfFile(pdfData({pages:2}))})`);
|
||||
assert.equal(multi.rejected,true);assert.match(multi.reason,/2 páginas/);
|
||||
const beyondSpec=await evaluate(`medirFolha(${pdfFile(pdfData({media:'[0 0 20000 720]'}))})`);
|
||||
@@ -308,6 +391,13 @@ try{
|
||||
assert.equal(await evaluate(`avaliar().pronto`),false);
|
||||
assert.equal(await evaluate(`cartPodeEnviar()`),false);
|
||||
assert.match(await evaluate(`$('lista').textContent`),/não pode ser orçado/);
|
||||
// A ".cdr" that is a PDF (D-13) is renamed and measured as a PDF, not handled by hand.
|
||||
await click('#bVoltar');await click('[data-modo="file"]');
|
||||
await evaluate(`sel([${pdfFile(pdfData(),'folha.cdr')}])`);
|
||||
// Measured, and its ink check finished: a check still running repaints the list after the mode below changes.
|
||||
await waitFor(()=>evaluate(`folhas.length===1 && !!(folhas[0].med || folhas[0].measurementError) && folhas[0].pct==null`),'renamed PDF measured');
|
||||
assert.deepEqual(await evaluate(`({name:folhas[0].f.name,measured:!!folhas[0].med,manual:folhaManual()})`),
|
||||
{name:'folha.pdf',measured:true,manual:false});
|
||||
await click('#bVoltar');await click('[data-modo="avulsa"]');
|
||||
await evaluate(`sel([new File(['not an image'],'broken.png',{type:'image/png'})])`);
|
||||
await waitFor(()=>evaluate('artes.length===1 && artes[0].decodeError===true'),'failed image decode');
|
||||
@@ -323,6 +413,12 @@ try{
|
||||
assert.equal(await evaluate('modo'),expected);
|
||||
await fill('[data-cm]',10);await fill('[data-q]',4);await packed(4);
|
||||
}
|
||||
// UV keeps the mirror until Dropstar decides; it changes the pixels and the record.
|
||||
const beforeMirror=await evaluate(`$('vArea').querySelector('canvas').toDataURL()`);
|
||||
await click('[data-esp]');
|
||||
await waitFor(()=>evaluate(`$('vArea').querySelector('canvas').toDataURL()!==${JSON.stringify(beforeMirror)}`),'mirror updates pixels');
|
||||
await waitFor(()=>evaluate(`itemAtual?.production?.sources[0]?.mirrored===true`),'UV mirror in production record');
|
||||
await click('[data-esp]');
|
||||
// An older image load must not overwrite a newer edit, even before debounce.
|
||||
// The packing loads each artwork's image through imagemDaArte.
|
||||
await evaluate(`(()=>{window.realLoad=imagemDaArte;window.delayed=[];
|
||||
@@ -362,6 +458,6 @@ try{
|
||||
console.log('Supplied image:',JSON.stringify(layout));
|
||||
}
|
||||
assert.deepEqual(errors,[]);
|
||||
console.log('PASS: JPG/PNG upload and drop, packed copies, 5 mm gaps, aspect ratio, live width/quantity/rotation/mirror, metres, ready-sheet pricing/repeats, UV, stale renders, strict inline CSP.');
|
||||
console.log('PASS: PNG upload and drop, JPG refused, packed copies, 5 mm gaps, aspect ratio, live width/quantity/rotation/mirror, metres, ready-sheet pricing/repeats, residue and solid background stop the order, UV, stale renders, strict inline CSP.');
|
||||
}catch(error){console.error(error);if(stderr)console.error(stderr.slice(-1200));process.exitCode=1;}
|
||||
finally{ws?.close();chrome.kill();server.closeAllConnections();await new Promise(r=>server.close(r));}
|
||||
|
||||
@@ -52,7 +52,7 @@ try{
|
||||
await waitFor(()=>site.eval('typeof window.dtfCheckout === "function"'),'checkout bridge');
|
||||
// Prove escaping itself, independently of the CSP's second line of defense.
|
||||
await site.call('Page.setBypassCSP',{enabled:true});
|
||||
await site.eval(`(()=>{window.xssProbe=0;abrir('file');sel([new File(['test'],'<img src=x onerror=window.xssProbe=1>.cdr')]);})()`);
|
||||
await site.eval(`(()=>{window.xssProbe=0;abrir('file');return sel([new File(['test'],'<img src=x onerror=window.xssProbe=1>.cdr')]);})()`);
|
||||
await pause(500);
|
||||
assert.equal(await site.eval('window.xssProbe'),0);
|
||||
assert.equal(await site.eval('document.querySelectorAll("#lista img[onerror]").length'),0);
|
||||
@@ -73,6 +73,10 @@ try{
|
||||
const input=await site.call('DOM.querySelector',{nodeId:root.root.nodeId,selector:'#inp'});
|
||||
await site.call('DOM.setFileInputFiles',{nodeId:input.nodeId,files:[resolve('tests/fixtures/local-test.cdr')]});
|
||||
await waitFor(()=>site.eval('!!document.querySelector("[data-comp]")'),'manual length field');
|
||||
// On its way from the product page already, with its own row under the
|
||||
// uploader (Dropstar, 2026-10-29).
|
||||
await waitFor(()=>site.eval(`$('envios').textContent.includes('local-test.cdr') && !$('envios').textContent.includes('Não foi possível')`),
|
||||
'the file uploads from the product page',45000);
|
||||
await site.fill('[data-comp]','1.01','change');
|
||||
await waitFor(()=>site.eval('!!itemAtual'),'cart calculation');
|
||||
// A CDR is opened by hand: the full price, plus the per-metre charge when
|
||||
@@ -183,7 +187,7 @@ try{
|
||||
assert.equal(await kanban.eval(`board.orders.find(o=>o.id===${JSON.stringify(oid)}).snapshot.customer.name`),'Maria da Silva');
|
||||
assert.deepEqual(await kanban.eval(`(()=>{const spec=board.orders.find(o=>o.id===${JSON.stringify(oid)}).snapshot.items[0].production;const source=spec.sources[0];return {kind:source.kind,copies:source.copies,length:Number(source.length_cm),height:Number(spec.height_cm),placed:spec.placements.length}})()`),
|
||||
{kind:'sheet',copies:1,length:101,height:101,placed:1});
|
||||
// The print queue's folder, switched on in Integrações. The native picker
|
||||
// The orders' three folders, switched on in Integrações. The native picker
|
||||
// cannot be driven headless: it answers with a folder in the browser's own
|
||||
// storage, which has the same file API.
|
||||
await kanban.click('[data-tab="integrations"]');
|
||||
@@ -193,24 +197,24 @@ try{
|
||||
window.showDirectoryPicker=async()=>window.picked;FOLDER.mode='folder';renderIntegrations();
|
||||
[...document.querySelectorAll('#folder-card button')].find(b=>b.textContent==='Escolher pasta').click();})()`);
|
||||
await waitFor(()=>kanban.eval('folderActive()&&!FOLDER.busy'),'folder chosen');
|
||||
// Downloaded as the order arrives, into Recebidos; up to the folder at the queue.
|
||||
await waitFor(()=>kanban.eval(`!!document.querySelector('#folder-card select')`),'download timing choice');
|
||||
await kanban.eval(`(()=>{const s=document.querySelector('#folder-card select');s.value='rec';s.dispatchEvent(new Event('change'));})()`);
|
||||
await waitFor(()=>kanban.eval(`FOLDER.when==='rec'&&!FOLDER.busy`),'download on arrival');
|
||||
const savedFiles=(sub)=>kanban.eval(`(async()=>{const dir=${sub?`await window.picked.getDirectoryHandle(${JSON.stringify(sub)},{create:true})`:'window.picked'};
|
||||
// Dropstar's three folders (2026-10-26): the file arrives in Arte recebida,
|
||||
// goes to Arte conferida with the card and to Finalizado at the end.
|
||||
await waitFor(()=>kanban.eval(`!FOLDER.busy`),'folder idle');
|
||||
const savedFiles=(sub)=>kanban.eval(`(async()=>{const dir=await window.picked.getDirectoryHandle(${JSON.stringify(sub)},{create:true});
|
||||
const out=[];for await(const [name,h] of dir.entries())if(h.kind==='file')out.push(name);return out;})()`);
|
||||
// Open the order's panel from its card, then click the real transition
|
||||
// buttons there, including the rerender after each move.
|
||||
await kanban.click('[data-tab="board"]');
|
||||
await kanban.click(`[data-card="${oid}"]`);
|
||||
await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-move]')`),'order panel');
|
||||
for(const [title,state] of [['Arte conferida','tra'],['Fila de impressão','fil'],['Imprimindo','imp'],['Finalizado','fin']]){
|
||||
if(state==='fil'){
|
||||
// Dropstar's flow (2026-10-23): Arte conferida is the queue, Revisão before Finalizado.
|
||||
for(const [title,state] of [['Arte conferida','tra'],['Imprimindo','imp'],['Revisão','rev'],['Finalizado','fin']]){
|
||||
if(state==='tra'){
|
||||
// Without an approved final, the next step at the top is approving it,
|
||||
// not a move the server would refuse. The CDR has no ready file, so
|
||||
// the button opens the upload form there.
|
||||
await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-approve]')`),'approve final button');
|
||||
assert.equal(await kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-move="fil"]')`),false);
|
||||
assert.equal(await kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-move="tra"]')`),false);
|
||||
await kanban.click(`[data-order="${oid}"] [data-approve]`);
|
||||
await waitFor(()=>kanban.eval(`(()=>{const input=document.querySelector('[data-order="${oid}"] [data-final-item]');return !!input&&!input.closest('form').hidden;})()`),'final upload controls');
|
||||
const doc=await kanban.call('DOM.getDocument');
|
||||
@@ -218,40 +222,62 @@ try{
|
||||
await kanban.call('DOM.setFileInputFiles',{nodeId:input.nodeId,files:[resolve('tests/fixtures/local-test.cdr')]});
|
||||
await kanban.fill(`[data-order="${oid}"] input[placeholder="Nota da revisão"]`,'Browser test final file');
|
||||
await kanban.eval(`(()=>{const check=document.querySelector('[data-order="${oid}"] [data-confirm]');check.click();check.closest('form').requestSubmit();})()`);
|
||||
await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').version===2`),'final file approval');
|
||||
// Approved before the queue: already on this computer, in Recebidos.
|
||||
const early='pedido-'+await kanban.eval(`board.orders.find(o=>o.id==='${oid}').number`)+'-item-1';
|
||||
await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').version===1`),'final file approval');
|
||||
// Approved before the queue: already on this computer, in Arte recebida.
|
||||
const early='DTF-'+await kanban.eval(`board.orders.find(o=>o.id==='${oid}').number`)+'-item-1';
|
||||
await kanban.eval('syncFolder(true)');
|
||||
await waitFor(async()=>(await savedFiles('Recebidos')).some(n=>n.startsWith(early)&&!n.endsWith('.baixando')),'final file saved in Recebidos',45000);
|
||||
assert.equal((await savedFiles()).some(n=>n.startsWith(early)),false);
|
||||
await waitFor(async()=>(await savedFiles('1. Arte recebida')).some(n=>n.startsWith(early)&&!n.endsWith('.baixando')),'final file saved in Arte recebida',45000);
|
||||
assert.equal((await savedFiles('2. Arte conferida')).some(n=>n.startsWith(early)),false);
|
||||
}
|
||||
await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-move="${state}"]')`),'move to '+title);
|
||||
await kanban.click(`[data-order="${oid}"] [data-move="${state}"]`);
|
||||
await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').state==='${state}'`),'transition '+state);
|
||||
if(state==='fil'){
|
||||
// Entering the queue saves its final file there, whole and named after the order.
|
||||
const prefix='pedido-'+await kanban.eval(`board.orders.find(o=>o.id==='${oid}').number`)+'-item-1';
|
||||
await waitFor(async()=>(await savedFiles()).some(n=>n.startsWith(prefix)&&!n.endsWith('.baixando')),'final file saved in the folder',45000);
|
||||
if(state==='tra'){
|
||||
// Entering the queue moves its file to Arte conferida, whole and named after the order.
|
||||
const prefix='DTF-'+await kanban.eval(`board.orders.find(o=>o.id==='${oid}').number`)+'-item-1';
|
||||
await waitFor(async()=>(await savedFiles('2. Arte conferida')).some(n=>n.startsWith(prefix)&&!n.endsWith('.baixando')),'final file in Arte conferida',45000);
|
||||
// Other orders the earlier suites left in the queue may still be coming
|
||||
// down: only once the round ends must no half-written file be left.
|
||||
await waitFor(()=>kanban.eval('!FOLDER.busy'),'folder round finished',60000);
|
||||
assert.equal((await savedFiles()).some(n=>n.endsWith('.baixando')),false);
|
||||
assert.equal((await savedFiles('Recebidos')).some(n=>n.startsWith(prefix)),false);
|
||||
assert.equal((await savedFiles('2. Arte conferida')).some(n=>n.endsWith('.baixando')),false);
|
||||
assert.equal((await savedFiles('1. Arte recebida')).some(n=>n.startsWith(prefix)),false);
|
||||
// A file whose order was deleted leaves the folder.
|
||||
await kanban.eval(`(async()=>{const f=await window.picked.getFileHandle('pedido-0-item-1-excluido.png',{create:true});
|
||||
await kanban.eval(`(async()=>{const dir=await window.picked.getDirectoryHandle('2. Arte conferida',{create:true});
|
||||
const f=await dir.getFileHandle('pedido-0-item-1-excluido.png',{create:true});
|
||||
const w=await f.createWritable();await w.write('x');await w.close();
|
||||
FOLDER.saved.set(crypto.randomUUID(),{order:crypto.randomUUID(),item:1,name:'pedido-0-item-1-excluido.png',place:'queue'});})()`);
|
||||
FOLDER.saved.set(crypto.randomUUID(),{order:crypto.randomUUID(),item:1,name:'pedido-0-item-1-excluido.png',folder:'2. Arte conferida'});})()`);
|
||||
await waitFor(()=>kanban.eval('!FOLDER.busy'),'folder idle',60000);
|
||||
await kanban.eval('syncFolder(true)');
|
||||
await waitFor(async()=>!(await savedFiles()).includes('pedido-0-item-1-excluido.png'),'deleted order file removed',30000);
|
||||
await waitFor(async()=>!(await savedFiles('2. Arte conferida')).includes('pedido-0-item-1-excluido.png'),'deleted order file removed',30000);
|
||||
}
|
||||
if(state==='rev'||state==='fin'){
|
||||
// In Revisão the file leaves the queue for 4. Revisão; finalized, it
|
||||
// goes on to 5. Finalizado (Dropstar's numbering, 2026-10-30).
|
||||
const prefix='DTF-'+await kanban.eval(`board.orders.find(o=>o.id==='${oid}').number`)+'-item-1';
|
||||
const [now,before]=state==='rev'?['4. Revisão','2. Arte conferida']:['5. Finalizado','4. Revisão'];
|
||||
await waitFor(()=>kanban.eval('!FOLDER.busy'),'folder idle',60000);
|
||||
await kanban.eval('syncFolder(true)');
|
||||
await waitFor(async()=>(await savedFiles(now)).some(n=>n.startsWith(prefix)),'final file in '+now,30000);
|
||||
assert.equal((await savedFiles(before)).some(n=>n.startsWith(prefix)),false);
|
||||
}
|
||||
if(state==='fin'){
|
||||
// The folder of before the numbering goes once nothing is left in it.
|
||||
const folders=()=>kanban.eval(`(async()=>{const out=[];for await(const [name,h] of window.picked.entries())if(h.kind==='directory')out.push(name);return out.sort();})()`);
|
||||
await kanban.eval(`window.picked.getDirectoryHandle('3. Finalizado',{create:true})`);
|
||||
await waitFor(()=>kanban.eval('!FOLDER.busy'),'folder idle',60000);
|
||||
await kanban.eval('syncFolder(true)');
|
||||
await waitFor(async()=>!(await folders()).includes('3. Finalizado'),'old Finalizado folder removed',30000);
|
||||
const tree=await folders();
|
||||
for(const name of ['1. Arte recebida','2. Arte conferida','3. Imprimindo','4. Revisão','5. Finalizado','Recibos'])
|
||||
assert.ok(tree.includes(name),name+' missing from '+tree.join(', '));
|
||||
}
|
||||
}
|
||||
// Undo a mistaken move from the panel: one stage back with an internal reason.
|
||||
await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-back="imp"]')`),'back button');
|
||||
await kanban.click(`[data-order="${oid}"] [data-back="imp"]`);
|
||||
await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-back="rev"]')`),'back button');
|
||||
await kanban.click(`[data-order="${oid}"] [data-back="rev"]`);
|
||||
await kanban.fill(`[data-order="${oid}"] form.reason input`,'Movido por engano (teste)');
|
||||
await kanban.eval(`document.querySelector('[data-order="${oid}"] form.reason input').closest('form').requestSubmit()`);
|
||||
await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').state==='imp'`),'undo to Imprimindo');
|
||||
await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').state==='rev'`),'undo to Revisão');
|
||||
await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-move="fin"]')`),'move to Finalizado again');
|
||||
await kanban.click(`[data-order="${oid}"] [data-move="fin"]`);
|
||||
await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').state==='fin'`),'finished again');
|
||||
|
||||
@@ -11,6 +11,7 @@ from urllib.request import Request
|
||||
from uuid import uuid4
|
||||
|
||||
import httpx
|
||||
import psycopg
|
||||
from psycopg.types.json import Jsonb
|
||||
|
||||
from app.core import db
|
||||
@@ -81,8 +82,8 @@ def run():
|
||||
c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved)
|
||||
VALUES(%s,%s,%s,%s,%s,%s)''', (qid, owner, uuid4(), 'kanban-fixture', Jsonb(content),
|
||||
Jsonb(accepted) if accepted else None))
|
||||
number = c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment)
|
||||
VALUES(%s,%s,%s,%s,%s) RETURNING number''',
|
||||
number = c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,origin)
|
||||
VALUES(%s,%s,%s,%s,%s,'site') RETURNING number''',
|
||||
(order_id, paid, owner, Jsonb({**draft(item('file')), 'total_cents': 1490}),
|
||||
Jsonb({'provider': 'teste', 'id': f'kanban-{tag}'}))).fetchone()['number']
|
||||
|
||||
@@ -126,6 +127,20 @@ def run():
|
||||
assert (after['orders'], after['cents']) == (before['orders'] + 1, before['cents'] + 1490), (before, after)
|
||||
assert after['daily'][-1]['orders'] == before['daily'][-1]['orders'] + 1
|
||||
assert after['waiting']['rec']['orders'] == before.get('waiting', {}).get('rec', {}).get('orders', 0) + 1
|
||||
# Each way in apart (D-21), all three listed even when empty.
|
||||
assert [o['origin'] for o in after['origins']] == ['site', 'dropflow', 'atendimento']
|
||||
site = lambda stats: next(o for o in stats['origins'] if o['origin'] == 'site')
|
||||
assert (site(after)['orders'], site(after)['cents']) == (site(before)['orders'] + 1, site(before)['cents'] + 1490)
|
||||
# No order without an origin, and only the three (D-21, D-35).
|
||||
for origin in (None, 'whatsapp'):
|
||||
try:
|
||||
with db.connect() as c:
|
||||
c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,origin)
|
||||
VALUES(%s,%s,%s,'{}','{}',%s)''', (uuid4(), approved, owner, origin))
|
||||
except (psycopg.errors.NotNullViolation, psycopg.errors.CheckViolation):
|
||||
pass
|
||||
else:
|
||||
raise AssertionError(f'an order with origin {origin!r} was accepted')
|
||||
client.call('/operator/stats?days=3', operator=True, expected=422)
|
||||
# Or two dates: the same week asked as a range gives the same numbers.
|
||||
week = client.call(f"/operator/stats?start={after['start']}&end={after['end']}", operator=True)
|
||||
@@ -138,7 +153,7 @@ def run():
|
||||
assert isinstance(after['machines'], list)
|
||||
# An order sent back counts once per stage; its passages are counted apart.
|
||||
with db.connect() as c:
|
||||
for step, (frm, to) in enumerate((('rec', 'tra'), ('tra', 'cor'), ('cor', 'tra'), ('tra', 'fil'))):
|
||||
for step, (frm, to) in enumerate((('rec', 'tra'), ('tra', 'cor'), ('cor', 'tra'), ('tra', 'imp'))):
|
||||
c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason,back,created_at)
|
||||
VALUES(%s,%s,%s,'kanban-test','',false,now()+%s*interval '1 second')''', (order_id, frm, to, step + 1))
|
||||
moved = client.call('/operator/stats?days=7', operator=True)
|
||||
@@ -151,12 +166,19 @@ def run():
|
||||
with db.connect() as c:
|
||||
c.execute('UPDATE dtf_local.orders SET created_at=%s::timestamptz WHERE id=%s', (f'{alone} 08:00-03', order_id))
|
||||
c.execute('DELETE FROM dtf_local.movements WHERE order_id=%s', (order_id,))
|
||||
for hour, (frm, to) in enumerate((('rec', 'tra'), ('tra', 'cor'), ('cor', 'tra'), ('tra', 'fil')), start=9):
|
||||
for hour, (frm, to) in enumerate((('rec', 'tra'), ('tra', 'cor'), ('cor', 'tra'), ('tra', 'imp')), start=9):
|
||||
c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason,back,created_at)
|
||||
VALUES(%s,%s,%s,'kanban-test','',false,%s::timestamptz)''', (order_id, frm, to, f'{alone} {hour}:00-03'))
|
||||
day = client.call(f'/operator/stats?start={alone}&end={alone}', operator=True)
|
||||
assert day['stages']['tra'] == {'orders': 1, 'passages': 2, 'median_hours': 2.0}, day['stages']
|
||||
assert day['stages']['rec']['median_hours'] == 1.0, day['stages']
|
||||
# Half an hour of it waiting for the customer does not count (D-38).
|
||||
with db.connect() as c:
|
||||
c.execute('''INSERT INTO dtf_local.contact_waits(order_id, started_at, ended_at)
|
||||
VALUES(%s, %s::timestamptz, %s::timestamptz)''', (order_id, f'{alone} 09:15-03', f'{alone} 09:45-03'))
|
||||
day = client.call(f'/operator/stats?start={alone}&end={alone}', operator=True)
|
||||
assert day['stages']['tra']['median_hours'] == 1.5, day['stages']
|
||||
assert day['stages']['rec']['median_hours'] == 1.0, day['stages']
|
||||
|
||||
# The company's name from the registry: on the board, and found by the search.
|
||||
from app import cnpj as registry
|
||||
|
||||
@@ -17,7 +17,7 @@ def run():
|
||||
c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved,approved_at)
|
||||
VALUES(%s,%s,%s,'reset-fixture',%s,%s,now())''',
|
||||
(quote, owner, uuid4(), Jsonb({'customer': {}, 'items': []}), Jsonb({'items': [], 'total_cents': 1490})))
|
||||
c.execute('INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment) VALUES(%s,%s,%s,%s,%s)',
|
||||
c.execute("INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,origin) VALUES(%s,%s,%s,%s,%s,'site')",
|
||||
(order, quote, owner, Jsonb({'items': [], 'total_cents': 1490}), Jsonb({'provider': 'teste'})))
|
||||
live = c.execute('''INSERT INTO dtf_local.payment_intents(id,quote_id,provider,provider_payment_id,method,
|
||||
status,amount_cents,response) VALUES(%s,%s,'mercadopago',%s,'card','approved',1490,%s) RETURNING id''',
|
||||
@@ -52,8 +52,8 @@ def run():
|
||||
c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved,approved_at)
|
||||
VALUES(%s,%s,%s,'reset-fixture',%s,%s,now())''',
|
||||
(quote, owner, uuid4(), Jsonb({'customer': {}, 'items': []}), Jsonb({'items': [], 'total_cents': 1490})))
|
||||
first = c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment)
|
||||
VALUES(%s,%s,%s,%s,%s) RETURNING number''', (uuid4(), quote, owner, Jsonb({'items': []}),
|
||||
first = c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,origin)
|
||||
VALUES(%s,%s,%s,%s,%s,'site') RETURNING number''', (uuid4(), quote, owner, Jsonb({'items': []}),
|
||||
Jsonb({'provider': 'teste'}))).fetchone()['number']
|
||||
assert first == 1, first
|
||||
c.execute('DELETE FROM dtf_local.orders WHERE quote_id=%s', (quote,))
|
||||
|
||||
@@ -27,7 +27,7 @@ def run():
|
||||
c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved,approved_at)
|
||||
VALUES(%s,%s,%s,'actions-fixture',%s,%s,now())''',
|
||||
(qid, owner, uuid4(), Jsonb({'customer': {'mail': mail}, 'items': []}), Jsonb(approved)))
|
||||
c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment) VALUES(%s,%s,%s,%s,%s)''',
|
||||
c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,origin) VALUES(%s,%s,%s,%s,%s,'site')''',
|
||||
(paid_order, paid_quote, owner, Jsonb(approved), Jsonb({'provider': 'mercadopago', 'id': '1'})))
|
||||
listed = lambda: {q['id'] for q in client.call('/operator/quotes?' + urlencode({'kind': 'approved', 'q': mail}),
|
||||
operator=True)['quotes']}
|
||||
@@ -63,6 +63,11 @@ def run():
|
||||
client.call(f'/operator/orders/{paid_order}/contact', {'waiting': False}, operator=True)
|
||||
cleared = {o['id']: o for o in client.call('/operator/board', operator=True)['orders']}[str(paid_order)]
|
||||
assert cleared['contact_since'] is None and cleared['contact_note'] is None
|
||||
# The wait is kept, from mark to clear, for the time figures that leave it out (D-38).
|
||||
with db.connect() as c:
|
||||
waits = c.execute('SELECT started_at, ended_at FROM dtf_local.contact_waits WHERE order_id=%s',
|
||||
(paid_order,)).fetchall()
|
||||
assert len(waits) == 1 and waits[0]['ended_at'] and waits[0]['ended_at'] >= waits[0]['started_at'], waits
|
||||
|
||||
# A paid order is cancelled with a reason, kept, and can no longer move.
|
||||
# A paid order in progress is not deleted: it is cancelled first.
|
||||
@@ -89,8 +94,8 @@ def run():
|
||||
# Dragged within its column: first paid first, unless moved; moving on resets it.
|
||||
with db.connect() as c:
|
||||
c.execute("UPDATE dtf_local.orders SET created_at=now()-interval '1 hour' WHERE id=%s", (paid_order,))
|
||||
c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,created_at)
|
||||
VALUES(%s,%s,%s,%s,%s,now())''', (newer_order, newer_quote, owner, Jsonb(approved),
|
||||
c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,created_at,origin)
|
||||
VALUES(%s,%s,%s,%s,%s,now(),'site')''', (newer_order, newer_quote, owner, Jsonb(approved),
|
||||
Jsonb({'provider': 'teste', 'id': 't'})))
|
||||
client.call(f'/operator/orders/{newer_order}/queue', {'before': str(paid_order)}, operator=True)
|
||||
with db.connect() as c:
|
||||
@@ -124,8 +129,8 @@ def run():
|
||||
'total_cents': 1490}
|
||||
c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved,approved_at)
|
||||
VALUES(%s,%s,%s,'actions-fixture',%s,%s,now())''', (quote, owner, uuid4(), Jsonb(content), Jsonb(content)))
|
||||
c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,cancelled_at,cancelled_by,cancel_reason)
|
||||
VALUES(%s,%s,%s,%s,%s,%s,%s,%s)''', (order, quote, owner, Jsonb(content), Jsonb({'provider': provider, 'id': '1'}),
|
||||
c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,cancelled_at,cancelled_by,cancel_reason,origin)
|
||||
VALUES(%s,%s,%s,%s,%s,%s,%s,%s,'site')''', (order, quote, owner, Jsonb(content), Jsonb({'provider': provider, 'id': '1'}),
|
||||
'now()' if cancelled else None, 'x' if cancelled else None,
|
||||
'teste' if cancelled else None))
|
||||
place(gone_quote, gone_order, [files['original'], files['shared']], 'mercadopago', True)
|
||||
|
||||
@@ -152,6 +152,11 @@ def run():
|
||||
assert order['payment']['provider'] == 'teste' and order['state'] == 'rec', order
|
||||
assert tester.call('/operator/quotes/' + test_quote + '/test-order', {}, operator=True)['id'] == order['id']
|
||||
version = order['version']
|
||||
# Arte conferida, the print queue, takes the order once its final is approved.
|
||||
final = upload_bytes(tester, b'TEST ORDER FINAL', order_id=order['id'])
|
||||
version = tester.call('/operator/orders/' + order['id'] + '/final-files',
|
||||
{'version': version, 'files': [{'item_index': 0, 'upload_id': final}], 'note': 'Teste'},
|
||||
operator=True)['version']
|
||||
for state in ('tra',):
|
||||
moved = tester.call('/operator/orders/' + order['id'] + '/move', {'state': state, 'version': version}, operator=True)
|
||||
version = moved['version']
|
||||
@@ -161,6 +166,47 @@ def run():
|
||||
assert queued == 0 and jobs == 1, (queued, jobs)
|
||||
print('PASS: an operator test order reaches the board and the print queue, never Tiny')
|
||||
|
||||
# An order paid outside the system, registered by the team from its Site
|
||||
# quote (D-35): origin and payment are chosen, never assumed.
|
||||
_, counter_quote, counter_total = reviewed_quote()
|
||||
register = lambda qid, body, expected=200: board.call('/operator/quotes/' + qid + '/register', body,
|
||||
operator=True, expected=expected)
|
||||
for body in ({'method': 'pix'}, {'origin': 'atendimento'}, {'origin': 'whatsapp', 'method': 'pix'},
|
||||
{'origin': 'atendimento', 'method': 'boleto'}):
|
||||
register(counter_quote, body, expected=422)
|
||||
order = register(counter_quote, {'origin': 'atendimento', 'method': 'cash', 'note': 'Balcão'})
|
||||
assert (order['origin'], order['state'], order['payment']['provider'], order['payment']['method'],
|
||||
order['payment']['total_cents']) == ('atendimento', 'rec', 'manual', 'cash', counter_total), order
|
||||
register(counter_quote, {'origin': 'atendimento', 'method': 'cash'}, expected=409)
|
||||
with db.connect() as c:
|
||||
sent = c.execute("SELECT payload FROM dtf_local.outbox WHERE event_key=%s", (order['id'] + ':paid:tiny',)).fetchone()
|
||||
assert sent and sent['payload']['origin'] == 'atendimento' and sent['payload']['payment'] == {'method': 'cash', 'outside': True}, sent
|
||||
# A Dropflow batch reaches Tiny too, carrying its origin for its own category; and its cancel.
|
||||
_, batch_quote, _ = reviewed_quote()
|
||||
batch = register(batch_quote, {'origin': 'dropflow', 'method': 'credit'})
|
||||
board.call('/operator/orders/' + batch['id'] + '/cancel', {'note': 'Lote refeito'}, operator=True)
|
||||
with db.connect() as c:
|
||||
events = {r['event_key']: r['payload'] for r in c.execute(
|
||||
"SELECT event_key, payload FROM dtf_local.outbox WHERE event_key LIKE %s", (batch['id'] + ':%',)).fetchall()}
|
||||
paid = events.get(batch['id'] + ':paid:tiny')
|
||||
assert batch['origin'] == 'dropflow' and paid and paid['origin'] == 'dropflow', (batch, events)
|
||||
assert batch['id'] + ':cancelled:tiny' in events, events
|
||||
print('PASS: an order paid outside is registered with its origin and payment, Dropflow ones included')
|
||||
|
||||
# The customer's proof only above 10 m (Dropstar, 2026-10-28): asked for on a
|
||||
# shorter order, the server leaves it out.
|
||||
for metres, kept in (('1.01', False), ('12', True)):
|
||||
asker = Client()
|
||||
asker.call('/session')
|
||||
art = upload_bytes(asker, b'PROOF ' + metres.encode())
|
||||
spec = item_spec('file', metres, 0, art)
|
||||
profile = {'cnpj': '11222333000181', 'zap': '11999999999', 'mail': 'proof-' + uuid4().hex[:8] + '@example.test'}
|
||||
asked = asker.call('/quotes', {'request_key': str(uuid4()), 'customer': profile, 'items': [spec],
|
||||
'freight': {'service': 'pickup'}, 'proof': True})
|
||||
approved = approved_quote(asker, asked, [spec])
|
||||
assert bool(approved.get('proof')) is kept, (metres, approved.get('proof'))
|
||||
print('PASS: a proof asked for at checkout is kept only above 10 m')
|
||||
|
||||
# Files are uploaded before payment. An unpaid cart keeps them briefly; a
|
||||
# paid order keeps them for its 30 days; a payment never starts for files
|
||||
# that are gone.
|
||||
|
||||
@@ -87,8 +87,10 @@ def run():
|
||||
pdf = response.read()
|
||||
assert pdf.startswith(b'%PDF-') and pdf.rstrip().endswith(b'%%EOF')
|
||||
width, height = map(float, re.search(rb'/MediaBox \[0 0 ([\d.]+) ([\d.]+)\]', pdf).groups())
|
||||
assert abs(width - 57 * PT_PER_CM) < 0.01 and abs(height - 10 * PT_PER_CM) < 0.01, (width, height)
|
||||
print('PASS: paid order generated a 57 x 10 cm print file with both copies')
|
||||
# The layout's 10 cm and the 1,5 cm footer band, outside the billed length.
|
||||
assert abs(width - 57 * PT_PER_CM) < 0.01 and abs(height - 11.5 * PT_PER_CM) < 0.01, (width, height)
|
||||
assert row['detail']['footer'].startswith('DROPSTAR · Pedido DTF-%d · Item 1/1 · ' % order['number']), row['detail']
|
||||
print('PASS: paid order generated a 57 x 10 cm print file with both copies and its footer')
|
||||
|
||||
# The automatic folder, downloading on arrival, gets the generated file
|
||||
# before anyone approves it; at the queue only, it does not.
|
||||
@@ -96,7 +98,7 @@ def run():
|
||||
early = client.call('/operator/queue/folder', {'early': True, 'held': [oid]}, operator=True)
|
||||
mine = [f for f in early['files'] if f['order'] == oid]
|
||||
assert [(f['upload_id'], f['state']) for f in mine] == [(str(row['upload_id']), 'rec')], early['files']
|
||||
assert mine[0]['name'].startswith('pedido-%d-item-1' % order['number']) and early['states'] == {oid: 'rec'}
|
||||
assert mine[0]['name'].startswith('DTF-%d-item-1' % order['number']) and early['states'] == {oid: 'rec'}
|
||||
late = client.call('/operator/queue/folder', {'early': False, 'held': []}, operator=True)
|
||||
assert not [f for f in late['files'] if f['order'] == oid] and late['states'] == {}
|
||||
client.call('/operator/queue/folder', {'early': True, 'held': []}, expected=401)
|
||||
@@ -108,9 +110,30 @@ def run():
|
||||
{'version': order['version'], 'files': [{'item_index': 0, 'upload_id': str(row['upload_id'])}],
|
||||
'note': 'Generated print file checked'}, operator=True)
|
||||
version = result['version']
|
||||
for state in ('tra', 'fil'):
|
||||
client.call('/operator/orders/' + oid + '/move', {'state': state, 'version': version}, operator=True)
|
||||
version += 1
|
||||
# The file the system generated from the customer's art is not "Arte tratada".
|
||||
board = client.call('/operator/board', operator=True)['orders']
|
||||
assert next(o for o in board if o['id'] == oid)['treated'] is None
|
||||
# Arte conferida is the print queue (2026-10-23).
|
||||
client.call('/operator/orders/' + oid + '/move', {'state': 'tra', 'version': version}, operator=True)
|
||||
version += 1
|
||||
# Printing, the folders still get the file of an order they hold (to take
|
||||
# it to Finalizado later), and no one else's.
|
||||
client.call('/operator/orders/' + oid + '/move', {'state': 'imp', 'version': version}, operator=True)
|
||||
version += 1
|
||||
held = client.call('/operator/queue/folder', {'early': True, 'held': [oid]}, operator=True)
|
||||
assert [(f['state'], f['upload_id']) for f in held['files'] if f['order'] == oid] == [('imp', str(row['upload_id']))], held
|
||||
assert held['states'] == {oid: 'imp'}
|
||||
others = client.call('/operator/queue/folder', {'early': True, 'held': []}, operator=True)
|
||||
assert not [f for f in others['files'] if f['order'] == oid], others['files']
|
||||
# A folder chosen before this order was paid catches up on it, printing or
|
||||
# not, as a computer that was off does when it comes back; one chosen
|
||||
# after it does not.
|
||||
earlier = client.call('/operator/queue/folder', {'early': True, 'held': [], 'since': '2000-01-01T00:00:00Z'},
|
||||
operator=True)
|
||||
assert [(f['state'], f['upload_id']) for f in earlier['files'] if f['order'] == oid] == [('imp', str(row['upload_id']))]
|
||||
later = client.call('/operator/queue/folder', {'early': True, 'held': [], 'since': '2999-01-01T00:00:00Z'},
|
||||
operator=True)
|
||||
assert not [f for f in later['files'] if f['order'] == oid], later['files']
|
||||
# Once queued for printing, the final set can no longer change.
|
||||
client.call('/operator/orders/' + oid + '/final-files',
|
||||
{'version': version, 'files': [{'item_index': 0, 'upload_id': str(row['upload_id'])}],
|
||||
|
||||
@@ -93,7 +93,7 @@ def upload_bytes(client, content, name='LOCAL-TEST.cdr', order_id=None, expected
|
||||
return uid
|
||||
|
||||
def item_spec(mode, metres, grade, uid):
|
||||
film_width=28.5 if mode in ('uvfile','uv') else 57
|
||||
film_width=27 if mode in ('uvfile','uv') else 57
|
||||
length_cm=float(metres)*100
|
||||
return {'mode':mode,'metres':str(metres),'grade':grade,'uploads':[uid],
|
||||
'production':{'version':2,'film_width_cm':film_width,'height_cm':length_cm,
|
||||
@@ -117,8 +117,8 @@ def run():
|
||||
client=Client();other=Client()
|
||||
config=client.call('/session');other.call('/session')
|
||||
assert client.call('/health')['integrations']=='fake'
|
||||
# 1 GB per file: a 57 cm x 5 m sheet at 300 DPI is 200 to 300 MB.
|
||||
assert config['max_upload_bytes'] == 1024 ** 3
|
||||
# 4 GB per file (Dropstar, 2026-10-28).
|
||||
assert config['max_upload_bytes'] == 4 * 1024 ** 3
|
||||
client.call('/uploads',{'name':'too-large.cdr',
|
||||
'size':config['max_upload_bytes']+1},expected=413)
|
||||
cancelled=client.call('/uploads',{'name':'CANCELLED-PART.cdr','size':3})['id']
|
||||
@@ -181,11 +181,16 @@ def run():
|
||||
altered={**items[0],'production':{**items[0]['production'],
|
||||
'sources':[{**items[0]['production']['sources'][0],'measurement':'file'}]}}
|
||||
client.call('/operator/quotes/'+qid+'/approve',{'items':[altered,*items[1:]]},operator=True,expected=422)
|
||||
# Nor does the review change the residue the customer accepted (Dropstar, 2026-10-29).
|
||||
client.call('/operator/quotes/'+qid+'/approve',{'items':[{**items[0],'residue_accepted':2},*items[1:]]},
|
||||
operator=True,expected=422)
|
||||
# Reviewer corrects a browser-supplied grade and length. Browser values are proposals.
|
||||
# One price per product (2026-10-23): the grade is kept, the price ignores it.
|
||||
corrected=[{**items[0],'metres':'1.01','grade':0},*items[1:]]
|
||||
approved=client.call('/operator/quotes/'+qid+'/approve',{'items':corrected},operator=True)
|
||||
assert approved['items'][0]['total_cents']==2189
|
||||
assert approved['total_cents']==2189+32370+90870+109070+int(os.environ.get('MOCK_FREIGHT_CENTS','1500'))
|
||||
assert approved['items'][0]['total_cents']==2189 and approved['items'][0]['grade']==0
|
||||
assert [i['unit_cents'] for i in approved['items'][1:]]==[2190,7990,8990]
|
||||
assert approved['total_cents']==2189+28470+103870+116870+int(os.environ.get('MOCK_FREIGHT_CENTS','1500'))
|
||||
assert approved['destination']=={**draft['destination'],'complement':''}
|
||||
client.call('/operator/quotes/'+qid+'/approve',{'items':items},operator=True,expected=409)
|
||||
assert not client.call('/quotes/'+qid)['auto_approved']
|
||||
@@ -200,15 +205,23 @@ def run():
|
||||
assert auto['status']=='approved'
|
||||
seen=client.call('/quotes/'+auto['id'])
|
||||
assert seen['auto_approved'] and seen['review_reason'] is None
|
||||
assert seen['approved']['total_cents']==6972+int(os.environ.get('MOCK_FREIGHT_CENTS','1500'))
|
||||
assert seen['approved']['total_cents']==6132+int(os.environ.get('MOCK_FREIGHT_CENTS','1500'))
|
||||
assert client.call('/quotes',small)['status']=='approved'
|
||||
client.call('/operator/quotes/'+auto['id']+'/approve',{'items':small['items']},operator=True,expected=409)
|
||||
# The Site grades only art it analysed; a discount on unanalysed art waits for a person.
|
||||
# The residue dots the customer accepted printing stay with the item.
|
||||
accepted={**small,'request_key':str(uuid4()),'items':[{**item_spec('avulsa','2.75',90,graded),'residue_accepted':3}]}
|
||||
client.call('/quotes',{**accepted,'items':[{**accepted['items'][0],'residue_accepted':-1}]},expected=422)
|
||||
kept=client.call('/quotes',accepted)
|
||||
assert kept['status']=='approved'
|
||||
assert client.call('/quotes/'+kept['id'])['approved']['items'][0]['residue_accepted']==3
|
||||
# The Site grades only art it analysed. A grade on art it did not analyse
|
||||
# is checked against the file like any other, and this one cannot be.
|
||||
claimed={**item_spec('avulsa','2.75',0,uid),'grade':90}
|
||||
held=client.call('/quotes',{**small,'request_key':str(uuid4()),'items':[claimed]})
|
||||
assert held['status']=='pending_review'
|
||||
assert client.call('/quotes/'+held['id'])['review_reason']=='Nota informada sem análise da arte'
|
||||
# A better grade than the file supports, or one the server cannot check, waits too.
|
||||
assert client.call('/quotes/'+held['id'])['review_reason']=='Nota não conferida no servidor'
|
||||
# A better grade than the file supports, or one the server cannot check, waits too:
|
||||
# the price ignores the grade, but the order shows it.
|
||||
inflated=client.call('/quotes',{**small,'request_key':str(uuid4()),'items':[item_spec('avulsa','2.75',100,graded)]})
|
||||
assert inflated['status']=='pending_review'
|
||||
assert client.call('/quotes/'+inflated['id'])['review_reason']=='Nota 100 maior que a do arquivo (90)'
|
||||
@@ -228,12 +241,18 @@ def run():
|
||||
client.call('/operator/orders/'+oid+'/move',{'state':'fin','version':0},operator=True,expected=409)
|
||||
client.call('/operator/orders/'+oid+'/move',{'state':'cor','version':0},operator=True,expected=422)
|
||||
version=0
|
||||
for state in ('cor','rec','tra','fil','imp','fin'):
|
||||
if state=='fil':
|
||||
client.call('/operator/orders/'+oid+'/move',{'state':'fil','version':version},operator=True,expected=409)
|
||||
# Dropstar's flow (2026-10-23): Arte conferida is the queue, Revisão comes before Finalizado.
|
||||
for state in ('cor','rec','tra','imp','rev','fin'):
|
||||
if state=='tra':
|
||||
# The queue takes approved final files only.
|
||||
client.call('/operator/orders/'+oid+'/move',{'state':'tra','version':version},operator=True,expected=409)
|
||||
files=[{'item_index':i,'upload_id':upload_bytes(client,b'LOCAL FINAL FIXTURE '+str(i).encode(),order_id=oid)} for i in range(4)]
|
||||
result=client.call('/operator/orders/'+oid+'/final-files',{'version':version,'files':files,'note':'Local test manual final-file approval'},operator=True)
|
||||
version=result['version']
|
||||
if state=='fin':
|
||||
# Above 10 m the proof comes first: no Finalizado before Prova OK (app/proof.py).
|
||||
client.call('/operator/orders/'+oid+'/move',{'state':'fin','version':version},operator=True,expected=409)
|
||||
version=client.call('/operator/orders/'+oid+'/proof',{},operator=True)['version']
|
||||
moved=client.call('/operator/orders/'+oid+'/move',{'state':state,'version':version,'reason':'Local test correction' if state=='cor' else ''},operator=True)
|
||||
version+=1;assert moved['version']==version
|
||||
client.call('/operator/orders/'+oid+'/move',{'state':'rec','version':0},operator=True,expected=409)
|
||||
@@ -241,10 +260,10 @@ def run():
|
||||
# A mistaken move can be undone one stage at a time, with an internal
|
||||
# reason. The customer is not told again: going back and forward once more
|
||||
# adds no messages (the outbox count below stays 4).
|
||||
client.call('/operator/orders/'+oid+'/move',{'state':'imp','version':version},operator=True,expected=422)
|
||||
client.call('/operator/orders/'+oid+'/move',{'state':'tra','version':version},operator=True,expected=409)
|
||||
back=client.call('/operator/orders/'+oid+'/move',{'state':'imp','version':version,'reason':'Movido por engano'},operator=True)
|
||||
assert back['state']=='imp';version+=1
|
||||
client.call('/operator/orders/'+oid+'/move',{'state':'rev','version':version},operator=True,expected=422)
|
||||
client.call('/operator/orders/'+oid+'/move',{'state':'imp','version':version},operator=True,expected=409)
|
||||
back=client.call('/operator/orders/'+oid+'/move',{'state':'rev','version':version,'reason':'Movido por engano'},operator=True)
|
||||
assert back['state']=='rev';version+=1
|
||||
client.call('/operator/orders/'+oid+'/move',{'state':'fin','version':version},operator=True);version+=1
|
||||
history=client.call('/operator/orders/'+oid+'/history',operator=True)
|
||||
assert len(history)==8 and history[-2]['back'] and history[-2]['reason']=='Movido por engano' and not history[-1]['back']
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import unittest
|
||||
|
||||
from app.printjobs import whole_sheet
|
||||
from app.scanning import format_matches
|
||||
from app.scanning import check_large, format_matches, real_name
|
||||
|
||||
ROW = {'id': 'u1', 'name': 'folha.png', 'size': 3 * 1024 ** 3, 'scan_state': 'clean',
|
||||
'purged_at': None, 'expired': False}
|
||||
@@ -37,6 +37,20 @@ class FormatTest(unittest.TestCase):
|
||||
self.assertFalse(format_matches('a.png', b'%PDF-1.4'))
|
||||
self.assertFalse(format_matches('semextensao', b'\x89PNG\r\n\x1a\n'))
|
||||
|
||||
def test_the_content_names_the_file(self):
|
||||
# Dropstar's rule D-13: a ".cdr" that is a PDF is a PDF, a JPG called
|
||||
# ".png" is a JPG; a name its content agrees with stays (".ai" is a PDF inside).
|
||||
self.assertEqual(real_name('folha.cdr', b'%PDF-1.7'), 'folha.pdf')
|
||||
self.assertEqual(real_name('arte.png', b'\xff\xd8\xff\xe0'), 'arte.jpg')
|
||||
self.assertEqual(real_name('semextensao', b'%PDF-1.4'), 'semextensao.pdf')
|
||||
for name, head in (('folha.cdr', b'RIFF\0\0\0\0CDR9'), ('arte.ai', b'%PDF-1.5'), ('arte.ai', b'%!PS-Adobe'),
|
||||
('foto.jpeg', b'\xff\xd8\xff'), ('arte.png', b'GIF89a')):
|
||||
self.assertEqual(real_name(name, head), name, (name, head))
|
||||
|
||||
def test_a_large_file_passes_on_its_content(self):
|
||||
self.assertEqual(check_large(b'%PDF-1.7', {'name': 'folha.cdr'})[0], 'clean')
|
||||
self.assertEqual(check_large(b'MZ\x90\x00', {'name': 'folha.cdr'})[0], 'rejected')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
|
||||
41
tests/test_layout_rules.py
Normal file
41
tests/test_layout_rules.py
Normal file
@@ -0,0 +1,41 @@
|
||||
"""What an order's layout may carry: the layout version, and no mirrored textile."""
|
||||
import unittest
|
||||
from uuid import uuid4
|
||||
|
||||
from pydantic import ValidationError
|
||||
|
||||
from app.core.models import Item
|
||||
|
||||
|
||||
def item(mode='avulsa', mirrored=False, version=3):
|
||||
upload = uuid4()
|
||||
film = 27 if mode in ('uv', 'uvfile') else 57
|
||||
return {'mode': mode, 'metres': '0.21', 'grade': 100, 'uploads': [str(upload)],
|
||||
'quality_status': 'ok', 'quality_acknowledged': False,
|
||||
'production': {'version': version, 'film_width_cm': film, 'height_cm': 21,
|
||||
'sources': [{'upload_id': str(upload), 'kind': 'artwork', 'width_cm': 10,
|
||||
'length_cm': 20, 'copies': 1, 'rotation_degrees': 0,
|
||||
'mirrored': mirrored, 'measurement': 'file'}],
|
||||
'placements': [{'source_index': 0, 'copy_index': 0, 'x_cm': 0.5, 'y_cm': 0.5,
|
||||
'width_cm': 10, 'length_cm': 20, 'rotation_degrees': 0,
|
||||
'mirrored': mirrored}]}}
|
||||
|
||||
|
||||
class LayoutRulesTest(unittest.TestCase):
|
||||
def test_a_textile_transfer_is_never_mirrored(self):
|
||||
# Pressed face down, a mirrored transfer prints backwards (Dropstar, 2026-10-21).
|
||||
with self.assertRaises(ValidationError):
|
||||
Item.model_validate(item('avulsa', mirrored=True))
|
||||
Item.model_validate(item('avulsa'))
|
||||
# UV keeps the choice until Dropstar decides.
|
||||
Item.model_validate(item('uv', mirrored=True))
|
||||
|
||||
def test_layout_versions(self):
|
||||
Item.model_validate(item(version=3))
|
||||
Item.model_validate(item(version=2))
|
||||
with self.assertRaises(ValidationError):
|
||||
Item.model_validate(item(version=1))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
53
tests/test_moves.py
Normal file
53
tests/test_moves.py
Normal file
@@ -0,0 +1,53 @@
|
||||
"""Who moves which card on the Kanban: Dropstar's flow of 2026-10-23."""
|
||||
import unittest
|
||||
|
||||
from app.core.auth import ROLES, may_move, may_reorder
|
||||
from app.runtime import BACK, STATES, TRANSITIONS
|
||||
|
||||
|
||||
def moves(role):
|
||||
return {(a, b) for a, nexts in TRANSITIONS.items() for b in nexts if may_move(role, a, b)}
|
||||
|
||||
|
||||
class MovesTest(unittest.TestCase):
|
||||
def test_the_board(self):
|
||||
# Fila de impressão left: Arte conferida is the queue; Revisão before Finalizado.
|
||||
self.assertEqual(list(STATES), ['rec', 'tra', 'imp', 'cor', 'rev', 'fin'])
|
||||
self.assertEqual(BACK, {'tra': 'rec', 'imp': 'tra', 'rev': 'imp', 'fin': 'rev'})
|
||||
self.assertIn('revisor', ROLES)
|
||||
|
||||
def test_each_profile_moves_its_part(self):
|
||||
self.assertEqual(moves('designer'), {('rec', 'tra'), ('rec', 'cor'), ('tra', 'cor'), ('cor', 'rec'), ('cor', 'tra')})
|
||||
self.assertEqual(moves('operador'), {('tra', 'imp'), ('imp', 'rev')})
|
||||
self.assertEqual(moves('revisor'), {('rev', 'fin')})
|
||||
self.assertEqual(moves('vendedor'), set())
|
||||
# Gestão, the coordination, pulls back and never forward (D-20): Correção
|
||||
# from any stage, and steps back. Admin, Dropstar's login, moves forward too.
|
||||
self.assertEqual(moves('gestao'), {('rec', 'cor'), ('tra', 'cor'), ('imp', 'cor'), ('rev', 'cor')})
|
||||
for pair in (('tra', 'imp'), ('rec', 'tra'), ('cor', 'rev'), ('cor', 'tra'), ('imp', 'rev')):
|
||||
self.assertFalse(may_move('gestao', *pair), pair)
|
||||
self.assertTrue(may_move('admin', *pair), pair)
|
||||
|
||||
def test_the_revisor_and_the_administrator_release_to_finalizado(self):
|
||||
for role in ROLES:
|
||||
self.assertEqual(may_move(role, 'rev', 'fin'), role in ('revisor', 'admin', 'superadmin'), role)
|
||||
|
||||
def test_a_step_back_belongs_to_whoever_makes_the_move_it_undoes(self):
|
||||
self.assertTrue(may_move('operador', 'rev', 'imp', back=True))
|
||||
self.assertTrue(may_move('operador', 'imp', 'tra', back=True))
|
||||
self.assertFalse(may_move('operador', 'tra', 'rec', back=True))
|
||||
self.assertTrue(may_move('designer', 'tra', 'rec', back=True))
|
||||
self.assertTrue(may_move('revisor', 'fin', 'rev', back=True))
|
||||
self.assertTrue(may_move('gestao', 'fin', 'rev', back=True))
|
||||
self.assertFalse(may_move('vendedor', 'tra', 'rec', back=True))
|
||||
|
||||
def test_a_column_is_ordered_by_whoever_takes_its_cards_forward(self):
|
||||
self.assertEqual([s for s in STATES if may_reorder('operador', s)], ['tra', 'imp'])
|
||||
self.assertEqual([s for s in STATES if may_reorder('designer', s)], ['rec', 'cor'])
|
||||
self.assertEqual([s for s in STATES if may_reorder('revisor', s)], ['rev'])
|
||||
self.assertEqual([s for s in STATES if may_reorder('vendedor', s)], [])
|
||||
self.assertTrue(all(may_reorder('gestao', s) for s in STATES))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -3,39 +3,51 @@ import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import unittest
|
||||
from app.core.pricing import is_manual, price, TIERS
|
||||
from app.core.pricing import is_manual, price, PRICES
|
||||
|
||||
class PricingTests(unittest.TestCase):
|
||||
def test_every_grade_against_actual_site_javascript(self):
|
||||
# The ladders live with the rest of the Site's behaviour; this test exists
|
||||
def test_every_length_against_actual_site_javascript(self):
|
||||
# The prices live with the rest of the Site's behaviour; this test exists
|
||||
# to prove the server agrees with whatever the customer is shown.
|
||||
source = Path('web/site-config.js').read_text()
|
||||
tiers = source.split('const FAIXAS=')[1].split('\n};',1)[0]+'\n}'
|
||||
prices = source.split('const PRECO=')[1].split(';',1)[0]
|
||||
calculator = source.split('const cobrar=')[1].split(';',1)[0]
|
||||
js = f'const FAIXAS={tiers};const MINIMO_M=1;const cobrar={calculator};'
|
||||
js += '''const results=[];for(const mode of Object.keys(FAIXAS))for(let grade=0;grade<=100;grade++)
|
||||
js = f'const PRECO={prices};const MINIMO_M=1;const cobrar={calculator};'
|
||||
js += '''const results=[];for(const mode of Object.keys(PRECO))
|
||||
for(const metres of [0.01,0.99,1,1.01,1.1,2.75,2.8,2.8000000000000003,19.99,60,12000]){
|
||||
const unit=FAIXAS[mode].find(x=>grade>=x[0])[1];
|
||||
results.push([mode,String(metres),grade,cobrar(metres),Math.round(unit*100),Math.round(cobrar(metres)*unit*100)]);
|
||||
const unit=PRECO[mode];
|
||||
results.push([mode,String(metres),cobrar(metres),Math.round(unit*100),Math.round(cobrar(metres)*unit*100)]);
|
||||
}process.stdout.write(JSON.stringify(results));'''
|
||||
cases = json.loads(subprocess.check_output(['node','-e',js],text=True))
|
||||
for mode,metres,grade,billed,unit,total in cases:
|
||||
with self.subTest(mode=mode,metres=metres,grade=grade):
|
||||
result=price(mode,metres,grade)
|
||||
self.assertEqual(float(result['billed_metres']),billed)
|
||||
self.assertEqual(result['unit_cents'],unit)
|
||||
self.assertEqual(result['total_cents'],total)
|
||||
self.assertEqual({mode for mode, *_ in cases}, set(PRICES))
|
||||
for mode,metres,billed,unit,total in cases:
|
||||
for grade in (0, 39, 40, 75, 90, 100):
|
||||
with self.subTest(mode=mode,metres=metres,grade=grade):
|
||||
result=price(mode,metres,grade)
|
||||
self.assertEqual(float(result['billed_metres']),billed)
|
||||
self.assertEqual(result['unit_cents'],unit)
|
||||
self.assertEqual(result['total_cents'],total)
|
||||
|
||||
def test_assembly_is_included_at_every_tier(self):
|
||||
for grade in range(101):
|
||||
self.assertEqual(price('avulsa','1',grade)['total_cents']-price('file','1',grade)['total_cents'],1000)
|
||||
self.assertEqual(price('uv','1',grade)['total_cents']-price('uvfile','1',grade)['total_cents'],1400)
|
||||
def test_one_price_per_product(self):
|
||||
# Dropstar, 2026-10-23: textile R$ 19,90 ready sheet and R$ 21,90 loose
|
||||
# art; UV R$ 79,90 and R$ 89,90.
|
||||
self.assertEqual(PRICES, {'file': 1990, 'avulsa': 2190, 'uvfile': 7990, 'uv': 8990})
|
||||
self.assertEqual(price('avulsa', '2.75', 90)['total_cents'], 6132)
|
||||
|
||||
def test_manual_file_extra_is_per_metre_and_not_a_discount(self):
|
||||
def test_the_grade_never_changes_the_price(self):
|
||||
for mode in PRICES:
|
||||
charges = {(p['unit_cents'], p['total_cents']) for p in (price(mode, '2.75', g) for g in range(101))}
|
||||
self.assertEqual(len(charges), 1, mode)
|
||||
self.assertNotIn('discount_cents', price(mode, '1', 100))
|
||||
# The grade is still kept with the item, for the Kanban and Tiny.
|
||||
self.assertEqual(price('file', '1', 92)['grade'], 92)
|
||||
|
||||
def test_manual_file_extra_is_per_metre(self):
|
||||
plain, extra = price('file', '1.01', 0), price('file', '1.01', 0, 500)
|
||||
self.assertEqual(extra['unit_cents'], plain['unit_cents'] + 500)
|
||||
self.assertEqual(extra['total_cents'], plain['total_cents'] + 550)
|
||||
self.assertEqual(extra['discount_cents'], 0)
|
||||
# On top of the single price, whatever grade the item carries.
|
||||
self.assertEqual(price('file', '1', 100, 200)['unit_cents'], 2190)
|
||||
self.assertEqual(extra['manual_extra_cents'], 500)
|
||||
self.assertNotIn('manual_extra_cents', plain)
|
||||
for bad in (-1, True, 1.5):
|
||||
|
||||
@@ -10,6 +10,7 @@ import re
|
||||
import tempfile
|
||||
import unittest
|
||||
import zlib
|
||||
from unittest import mock
|
||||
|
||||
from PIL import Image
|
||||
|
||||
@@ -87,6 +88,64 @@ class PrintFileTests(unittest.TestCase):
|
||||
streams = re.findall(rb'/Filter /FlateDecode/Length \d+ 0 R>>\nstream\n(.*?)\nendstream', pdf, re.S)
|
||||
return zlib.decompress(streams[-1])
|
||||
|
||||
def test_footer_band_is_added_below_the_layout(self):
|
||||
# Dropstar, 2026-10-21: 1,5 cm after the last piece, black text, no fill.
|
||||
path = self.save(quadrants(), 'a.png')
|
||||
spec = item([placement(0, 0, 20, 10)], [source(20, 10)], 10)
|
||||
out = io.BytesIO()
|
||||
line = 'DROPSTAR · Pedido DTF-7 · Item 1/2 · 21/10/2026 · 1,00 m'
|
||||
detail = render(spec, {0: (path, 'a.png')}, out, 'test', footer=line)
|
||||
pdf = out.getvalue()
|
||||
height = float(re.search(rb'/MediaBox \[0 0 [\d.]+ ([\d.]+)\]', pdf).group(1))
|
||||
self.assertAlmostEqual(height, 11.5 * PT_PER_CM, places=2)
|
||||
self.assertEqual((detail['height_cm'], detail['page_height_cm'], detail['footer']), ('10', '11.5', line))
|
||||
content = self.content(pdf)
|
||||
# Dropstar's logo first (black on transparent: a soft mask), then the line.
|
||||
self.assertIn(b' cm /Logo Do Q', content)
|
||||
self.assertIn(b'/Logo ', pdf)
|
||||
self.assertIn(b'/SMask', pdf)
|
||||
self.assertNotIn(b'(DROPSTAR) Tj', content)
|
||||
self.assertIn(b'/F2 31 Tf', content)
|
||||
self.assertIn('(Pedido DTF-7 · Item 1/2 · 21/10/2026 · 1,00 m) Tj'.encode('cp1252'), content)
|
||||
self.assertNotIn(b' re f', content) # no filled background
|
||||
# Without the logo file, the brand's name in bold.
|
||||
with mock.patch('app.printfile.FOOTER_LOGO', os.path.join(self.dir.name, 'none.png')):
|
||||
bare = io.BytesIO()
|
||||
render(spec, {0: (path, 'a.png')}, bare, 'test', footer=line)
|
||||
self.assertIn(b'(DROPSTAR) Tj', self.content(bare.getvalue()))
|
||||
self.assertIn(b'/BaseFont /Helvetica-Bold', bare.getvalue())
|
||||
# The artwork keeps its place from the top: the band is below it.
|
||||
matrix = re.search(rb'q ([\d. -]+) cm /Im0 Do Q', content).group(1).split()
|
||||
self.assertAlmostEqual(float(matrix[5]), 1.5 * PT_PER_CM, places=2)
|
||||
# Without a footer, the page is the layout.
|
||||
plain = io.BytesIO()
|
||||
self.assertEqual(render(spec, {0: (path, 'a.png')}, plain, 'test')['page_height_cm'], '10')
|
||||
|
||||
def test_a_mirrored_item_says_so_in_bold_at_the_end(self):
|
||||
from datetime import datetime, timezone
|
||||
from app.printfile import footer_commands
|
||||
from app.printjobs import file_prefix, footer
|
||||
spec = item([placement(0, 0, 20, 10, mirrored=True)], [source(20, 10, mirrored=True)], 10)
|
||||
job = {'snapshot': {'items': [spec, spec]}, 'number': 7, 'item_index': 1,
|
||||
'ordered_at': datetime(2026, 10, 23, 15, 0, tzinfo=timezone.utc)}
|
||||
line = footer(job, spec)
|
||||
self.assertEqual(line, 'DROPSTAR · Pedido DTF-7 · Item 2/2 · 23/10/2026 · 1,00 m · ESPELHADO')
|
||||
self.assertIn(b'/F1 31 Tf ( \xb7 ESPELHADO) Tj', footer_commands(line, (100, 80)))
|
||||
# About 1 cm tall on the 57 cm film (Dropstar, 2026-10-28); on the 27 cm UV
|
||||
# the line shrinks to fit the width instead of running off the film.
|
||||
from app.printfile import PT_PER_CM, text_width
|
||||
long_line = 'DROPSTAR · Pedido DTF-12345 · Item 10/12 · 28/10/2026 · 123,40 m · ESPELHADO'
|
||||
uv = footer_commands(long_line, (100, 80), 27 * PT_PER_CM)
|
||||
size = int(re.search(rb'/F2 (\d+) Tf', uv).group(1))
|
||||
self.assertLess(size, 31)
|
||||
logo = 1.3 * 100 / 80 * PT_PER_CM
|
||||
used = 0.5 * PT_PER_CM + logo + 0.4 * PT_PER_CM + size * (
|
||||
text_width('Pedido DTF-12345 · Item 10/12 · 28/10/2026 · 123,40 m') + text_width(' · ESPELHADO', True))
|
||||
self.assertLessEqual(used, 27 * PT_PER_CM - 0.5 * PT_PER_CM)
|
||||
self.assertNotIn(b'ESPELHADO', footer_commands(footer(job, item([placement(0, 0, 20, 10)], [source(20, 10)], 10)), (100, 80)))
|
||||
# The files start with the code the Kanban copies.
|
||||
self.assertEqual(file_prefix(7, 1), 'DTF-7-item-2')
|
||||
|
||||
def test_jpeg_bytes_are_embedded_unchanged(self):
|
||||
path = self.save(quadrants(), 'a.jpg', quality=90)
|
||||
pdf, _ = self.render(item([placement(0, 0, 20, 10)], [source(20, 10)], 10), [path])
|
||||
@@ -130,11 +189,19 @@ class PrintFileTests(unittest.TestCase):
|
||||
with self.assertRaisesRegex(Unsupported, 'não é uma imagem'):
|
||||
self.render(item([placement(0, 0, 20, 10)], [source(20, 10)], 10), [cdr])
|
||||
|
||||
def test_long_layouts_scale_user_space_instead_of_splitting(self):
|
||||
# 6 m is longer than a PDF page may be (about 5.08 m).
|
||||
def test_long_layouts_stay_one_page_at_real_size(self):
|
||||
# 6 m is longer than Acrobat's page limit (5,08 m). Corel ignores
|
||||
# /UserUnit, so the page is written at its real size (2026-10-28).
|
||||
path = self.save(quadrants(40, 800), 'a.png')
|
||||
pdf, detail = self.render(item([placement(0, 0, 30, 600)], [source(30, 600)], 600,
|
||||
billed='6.0'), [path])
|
||||
spec = item([placement(0, 0, 30, 600)], [source(30, 600)], 600, billed='6.0')
|
||||
pdf, detail = self.render(spec, [path])
|
||||
self.assertEqual(detail['user_unit'], 1)
|
||||
self.assertNotIn(b'/UserUnit', pdf)
|
||||
box = re.search(rb'/MediaBox \[ ?([\d. ]+)\]', pdf).group(1).split()
|
||||
self.assertAlmostEqual(float(box[3]) / PT_PER_CM, 600, places=1)
|
||||
# PRINT_PAGE_SCALE=true goes back to scaling user space instead.
|
||||
with mock.patch.dict(os.environ, {'PRINT_PAGE_SCALE': 'true'}):
|
||||
pdf, detail = self.render(spec, [path])
|
||||
self.assertEqual(detail['user_unit'], 2)
|
||||
self.assertIn(b'/UserUnit 2', pdf)
|
||||
|
||||
|
||||
@@ -26,8 +26,10 @@ class ReviewReasonTest(unittest.TestCase):
|
||||
self.assertEqual(self.reason(item(metres='30'), item(metres='20.1')), 'Pedido acima de 50 m')
|
||||
self.assertEqual(self.reason(item(metres='6'), QUOTE_AUTO_MAX_METRES='5'), 'Pedido acima de 5 m')
|
||||
|
||||
def test_a_discount_the_site_could_not_have_given_waits(self):
|
||||
self.assertEqual(self.reason(item(grade=90, quality='unverified')), 'Nota informada sem análise da arte')
|
||||
def test_a_grade_on_unanalysed_art_no_longer_waits_here(self):
|
||||
# The grade no longer sets the price; the server checks it against the
|
||||
# files instead (app/grade_check.py), as for any other cart.
|
||||
self.assertIsNone(self.reason(item(grade=90, quality='unverified')))
|
||||
|
||||
def test_old_layouts_and_switching_it_off(self):
|
||||
self.assertEqual(self.reason(item(version=1)), 'Montagem antiga')
|
||||
|
||||
@@ -131,6 +131,10 @@ class TinyTests(FakeTinyCase):
|
||||
pedido = order_payload(PAID, 777, date(2026, 9, 24))
|
||||
self.assertEqual((pedido['idContato'], pedido['numeroOrdemCompra'], pedido['data']),
|
||||
(777, 'DTF-42', '2026-09-24'))
|
||||
# The DTF number is also the e-commerce order number; no channel unless one is set.
|
||||
self.assertEqual(pedido['ecommerce'], {'numeroPedidoEcommerce': 'DTF-42'})
|
||||
with mock.patch.dict(os.environ, {'TINY_ECOMMERCE_ID': '555'}):
|
||||
self.assertEqual(order_payload(PAID, 777)['ecommerce'], {'numeroPedidoEcommerce': 'DTF-42', 'id': 555})
|
||||
item = pedido['itens'][0]
|
||||
self.assertEqual((item['produto'], item['quantidade'], item['valorUnitario']),
|
||||
({'id': 102}, 2.8, 24.9))
|
||||
@@ -209,8 +213,8 @@ class TinyTests(FakeTinyCase):
|
||||
self.products['103']['situacao'] = 'I'
|
||||
with mock.patch.dict(os.environ, {'TINY_PRODUCT_UV_AVULSA': ''}):
|
||||
results = check(auth=FakeAuth(), transport=httpx.MockTransport(self.handler))
|
||||
self.assertIn('não está ativo', results['DTF UV 28,5 cm · folha montada'])
|
||||
self.assertEqual(results['DTF UV 28,5 cm · artes avulsas'], 'TINY_PRODUCT_UV_AVULSA sem id')
|
||||
self.assertIn('não está ativo', results['DTF UV 27 cm · folha montada'])
|
||||
self.assertEqual(results['DTF UV 27 cm · artes avulsas'], 'TINY_PRODUCT_UV_AVULSA sem id')
|
||||
self.assertEqual(results['pedidos'], 'ok')
|
||||
# The order list is asked by date: unfiltered, Tiny times out on a large account.
|
||||
asked = []
|
||||
@@ -298,15 +302,15 @@ class TinyStatusTests(FakeTinyCase):
|
||||
self.assertEqual(self.puts(), [])
|
||||
|
||||
@mock.patch.dict(os.environ, {'TINY_STATUS_UPDATES': 'true'})
|
||||
def test_ready_delivery_order_waits_for_freight(self):
|
||||
self.tiny.deliver('k1', PAID)
|
||||
self.calls.clear()
|
||||
ready = self.tiny.deliver('k2', {**READY, 'order': PAID['order']})
|
||||
self.assertEqual(ready['status'], 'not-applicable')
|
||||
self.assertEqual(self.calls, [])
|
||||
def test_a_finished_delivery_order_is_ready_too(self):
|
||||
# Dropstar's flow, 2026-10-23: Finalizado is "Pronto para envio" for every order.
|
||||
sale = self.tiny.deliver('k1', PAID)
|
||||
ready = self.tiny.deliver('k2', {**READY, 'order': PAID['order'], 'tiny_id': sale['tiny_id']})
|
||||
self.assertEqual((ready['status'], ready['situacao']), ('status-updated', 'Pronto para envio'))
|
||||
self.assertEqual(self.orders[0]['situacao'], 7)
|
||||
|
||||
@mock.patch.dict(os.environ, {'TINY_STATUS_UPDATES': 'true'})
|
||||
def test_printing_is_preparando_envio_but_never_moves_an_invoiced_order_back(self):
|
||||
def test_the_queue_is_preparando_envio_but_never_moves_an_invoiced_order_back(self):
|
||||
sale = self.tiny.deliver('k1', PAID)
|
||||
started = {**READY, 'event': 'production_started', 'order': PAID['order'], 'tiny_id': sale['tiny_id']}
|
||||
moved = self.tiny.deliver('k2', started)
|
||||
@@ -339,6 +343,7 @@ class TinyStatusTests(FakeTinyCase):
|
||||
def test_orders_are_filled_in_as_the_store_s_own(self):
|
||||
from datetime import date
|
||||
from app.tiny import CATEGORY, PICKUP_CARRIER, RECEIPT_METHODS
|
||||
self.assertEqual(CATEGORY, 986932924) # DTF SITE, Dropstar 2026-10-26
|
||||
thursday = date(2026, 9, 24)
|
||||
with mock.patch.dict(os.environ, {'FREIGHT_PRODUCTION_DAYS': '1'}):
|
||||
pickup = order_payload({**PICKUP, 'payment': {'method': 'pix'}}, 1, thursday, shipping=self.tiny.shipping)
|
||||
@@ -365,16 +370,36 @@ class TinyStatusTests(FakeTinyCase):
|
||||
self.assertNotIn('transportador', plain)
|
||||
self.assertEqual(plain['pagamento'], {'categoria': {'id': CATEGORY}})
|
||||
self.assertNotIn('vendedor', plain)
|
||||
self.assertTrue(plain['observacoesInternas'].startswith('Site DTF · pago · '))
|
||||
# An order the team registered (D-35): its origin, and how it was paid
|
||||
# outside the site, each way named as Tiny's forma de recebimento.
|
||||
counter = order_payload({**PAID, 'origin': 'atendimento', 'payment': {'method': 'cash', 'outside': True}},
|
||||
1, thursday, shipping=self.tiny.shipping)
|
||||
self.assertTrue(counter['observacoesInternas'].startswith('Atendimento DTF · pago fora do site (dinheiro) · '))
|
||||
self.assertEqual(counter['pagamento']['categoria'], {'id': CATEGORY})
|
||||
self.assertEqual(counter['pagamento']['formaRecebimento'], {'id': RECEIPT_METHODS['cash']})
|
||||
pix = order_payload({**PAID, 'origin': 'atendimento', 'payment': {'method': 'pix', 'outside': True}},
|
||||
1, thursday, shipping=self.tiny.shipping)
|
||||
self.assertEqual(pix['pagamento']['formaRecebimento'], {'id': RECEIPT_METHODS['pix']})
|
||||
self.assertEqual(pix['pagamento']['categoria'], {'id': CATEGORY})
|
||||
# Dinheiro and the customer's credit (CORREÇÃO DTF), Marcus's ids of 2026-10-27.
|
||||
self.assertEqual((RECEIPT_METHODS['cash'], RECEIPT_METHODS['credit']), (919478944, 977493654))
|
||||
# A Dropflow order goes in DTF DROPFLOW, not DTF SITE (D-21).
|
||||
batch = order_payload({**PAID, 'origin': 'dropflow', 'payment': {'method': 'credit', 'outside': True}},
|
||||
1, thursday, shipping=self.tiny.shipping)
|
||||
self.assertEqual(batch['pagamento']['categoria'], {'id': 987032506})
|
||||
self.assertEqual(batch['pagamento']['formaRecebimento'], {'id': 977493654})
|
||||
self.assertTrue(batch['observacoesInternas'].startswith('Dropflow DTF · pago fora do site (crédito do cliente) · '))
|
||||
|
||||
def test_the_order_is_tagged_kanbandtf_once(self):
|
||||
first = self.tiny.deliver('k1', PAID)
|
||||
self.assertEqual(first['marcador'], 'KANBANDTF')
|
||||
self.assertEqual(first['marcador'], 'SITE DTF')
|
||||
tiny_id = self.orders[0]['id']
|
||||
self.assertEqual(self.tags[tiny_id], [{'descricao': 'KANBANDTF'}])
|
||||
self.assertEqual(self.tags[tiny_id], [{'descricao': 'SITE DTF'}])
|
||||
# A second delivery finds the order and its tag, and adds nothing.
|
||||
self.tiny.deliver('k1', PAID)
|
||||
self.assertEqual(len(self.orders), 1)
|
||||
self.assertEqual(self.tags[tiny_id], [{'descricao': 'KANBANDTF'}])
|
||||
self.assertEqual(self.tags[tiny_id], [{'descricao': 'SITE DTF'}])
|
||||
|
||||
def test_a_failed_tag_is_retried_without_a_second_order(self):
|
||||
self.refuse_tag = 1
|
||||
@@ -382,9 +407,9 @@ class TinyStatusTests(FakeTinyCase):
|
||||
self.tiny.deliver('k1', PAID)
|
||||
self.assertEqual(len(self.orders), 1)
|
||||
retry = self.tiny.deliver('k1', PAID)
|
||||
self.assertEqual((retry['status'], retry['marcador']), ('already-created', 'KANBANDTF'))
|
||||
self.assertEqual((retry['status'], retry['marcador']), ('already-created', 'SITE DTF'))
|
||||
self.assertEqual(len(self.orders), 1)
|
||||
self.assertEqual(self.tags[self.orders[0]['id']], [{'descricao': 'KANBANDTF'}])
|
||||
self.assertEqual(self.tags[self.orders[0]['id']], [{'descricao': 'SITE DTF'}])
|
||||
|
||||
def test_pickup_forma_de_envio_is_found_by_name(self):
|
||||
from app.tiny import check, find_pickup
|
||||
@@ -462,8 +487,10 @@ class TinySkuTests(FakeTinyCase):
|
||||
tiny_probe.main(['pedido', '--cnpj', '11222333000181', '--email', 'a@example.test',
|
||||
'--celular', '16999999999', '--metros', '1,3'], orders=self.tiny, out=lines.append)
|
||||
text = '\n'.join(lines)
|
||||
# 1,30 m at the single price, R$ 19,90: one "1 metro" and three "10 cm".
|
||||
self.assertIn('"quantidade": 1', text)
|
||||
self.assertIn('"valorUnitario": 4.47', text)
|
||||
self.assertIn('"valorUnitario": 19.9', text)
|
||||
self.assertIn('"valorUnitario": 5.97', text)
|
||||
# A new contact is previewed with the name it will get.
|
||||
self.assertIn('será criado como "a@example.test"', text)
|
||||
self.tiny.names = lambda cnpj: {'legal': 'EMPRESA TESTE LTDA', 'trade': 'Teste'}
|
||||
@@ -501,10 +528,10 @@ class TinyStepSkuTests(FakeTinyCase):
|
||||
def test_settings_and_check_know_the_step_sku(self):
|
||||
from app.tiny import check, required_settings
|
||||
self.assertNotIn('TINY_PRODUCT_UV_FOLHA', required_settings())
|
||||
self.assertEqual(check(orders=self.tiny)['DTF UV 28,5 cm · folha montada'], 'ok')
|
||||
self.assertEqual(check(orders=self.tiny)['DTF UV 27 cm · folha montada'], 'ok')
|
||||
del self.products['300']
|
||||
self.tiny.skus.clear()
|
||||
self.assertIn('DTFIMP.UV.010CM', check(orders=self.tiny)['DTF UV 28,5 cm · folha montada'])
|
||||
self.assertIn('DTFIMP.UV.010CM', check(orders=self.tiny)['DTF UV 27 cm · folha montada'])
|
||||
|
||||
|
||||
@product_ids
|
||||
@@ -528,10 +555,10 @@ class TinyMetreAndStepSkuTests(FakeTinyCase):
|
||||
def test_whole_metres_alone_and_the_check(self):
|
||||
from app.tiny import check, step_lines
|
||||
self.assertEqual(step_lines({'billed_metres': '2', 'unit_cents': 6990}, 'C', 'M'), [('M', 2, 6990)])
|
||||
self.assertEqual(check(orders=self.tiny)['DTF UV 28,5 cm · folha montada'], 'ok')
|
||||
self.assertEqual(check(orders=self.tiny)['DTF UV 27 cm · folha montada'], 'ok')
|
||||
del self.products['301']
|
||||
self.tiny.skus.clear()
|
||||
self.assertIn('DTFIMP.UV.1MT', check(orders=self.tiny)['DTF UV 28,5 cm · folha montada'])
|
||||
self.assertIn('DTFIMP.UV.1MT', check(orders=self.tiny)['DTF UV 27 cm · folha montada'])
|
||||
|
||||
|
||||
@product_ids
|
||||
@@ -551,12 +578,84 @@ class TinyProbeTests(FakeTinyCase):
|
||||
self.assertIn('101\tDTF-101\tProduto 101', text)
|
||||
code, text = self.probe('conferir')
|
||||
self.assertEqual(code, 0)
|
||||
self.assertIn('TINY_PRODUCT_UV_AVULSA (DTF UV 28,5 cm · artes avulsas): ok DTF-104', text)
|
||||
self.assertIn('TINY_PRODUCT_UV_AVULSA (DTF UV 27 cm · artes avulsas): ok DTF-104', text)
|
||||
self.assertIn('TINY_FORMA_ENVIO_RETIRADA (retirada): ok Retirar pessoalmente', text)
|
||||
code, text = self.probe('formas-envio')
|
||||
self.assertIn('77\t6\tRetirar pessoalmente', text)
|
||||
self.assertTrue(all(method == 'GET' for method, _ in self.calls))
|
||||
|
||||
def test_usuarios_lists_the_types_and_marks_the_integration_user(self):
|
||||
import base64 as b64
|
||||
handler = self.handler
|
||||
allowed = {'on': True}
|
||||
|
||||
def account(request):
|
||||
if request.url.path.endswith('/usuarios'):
|
||||
if not allowed['on']:
|
||||
return httpx.Response(403, text='')
|
||||
return httpx.Response(200, json={'itens': [
|
||||
{'id': 1, 'nome': 'Marcus', 'email': 'marcus@example.test', 'tipo': 'administrador'},
|
||||
{'id': 2, 'nome': 'Integração', 'email': 'dev@example.test', 'tipo': 'usuario'}]})
|
||||
return handler(request)
|
||||
self.tiny.http = httpx.Client(base_url=tiny_module.API, transport=httpx.MockTransport(account))
|
||||
claims = b64.urlsafe_b64encode(json.dumps({'name': 'Integração', 'email': 'dev@example.test'}).encode()).decode().rstrip('=')
|
||||
with mock.patch.object(self.tiny.auth, 'access_token', return_value=f'h.{claims}.s'):
|
||||
code, text = self.probe('usuarios')
|
||||
self.assertEqual(code, 0, text)
|
||||
self.assertIn('Integração conectada como: Integração · dev@example.test', text)
|
||||
self.assertIn('2\tusuario\tIntegração\tdev@example.test\t<- integração', text)
|
||||
self.assertIn('1\tadministrador\tMarcus\tmarcus@example.test', text)
|
||||
self.assertNotIn(claims, text)
|
||||
# Without the app's Usuários permission: says what to tick.
|
||||
allowed['on'] = False
|
||||
code, text = self.probe('usuarios')
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn('Marque Usuários (Leitura)', text)
|
||||
|
||||
def test_diagnostico_finds_the_part_tiny_refuses(self):
|
||||
handler = self.handler
|
||||
|
||||
def refusing(request):
|
||||
path = request.url.path.removeprefix('/public-api/v3')
|
||||
if request.method == 'POST' and path == '/pedidos' and 'ecommerce' in json.loads(request.content):
|
||||
self.calls.append((request.method, path))
|
||||
return httpx.Response(403, text='')
|
||||
return handler(request)
|
||||
self.tiny.http = httpx.Client(base_url=tiny_module.API, transport=httpx.MockTransport(refusing))
|
||||
args = ('diagnostico', '--cpf', '130.323.978-71', '--email', 'a@example.test', '--celular', '16999999999')
|
||||
# Never creates a contact: one that exists is required.
|
||||
code, text = self.probe(*args)
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn('não existe no Tiny', text)
|
||||
self.assertNotIn(('POST', '/contatos'), self.calls)
|
||||
self.assertNotIn(('POST', '/pedidos'), self.calls)
|
||||
self.contacts.append({'id': 600, 'cpfCnpj': '130.323.978-71', 'nome': 'Teste Fernandes'})
|
||||
code, text = self.probe(*args)
|
||||
self.assertEqual(code, 0, text)
|
||||
self.assertIn('completo: recusado', text)
|
||||
self.assertIn('sem ecommerce: ACEITO', text)
|
||||
# The one order Tiny accepted is cancelled at once, and nothing after it is sent.
|
||||
self.assertEqual(len(self.orders), 1)
|
||||
self.assertEqual(self.orders[0]['situacao'], tiny_module.CANCELADA)
|
||||
self.assertIn('cancelado no Tiny', text)
|
||||
self.assertNotIn(('POST', '/contatos'), self.calls)
|
||||
|
||||
def test_diagnostico_blames_the_permission_when_all_are_refused(self):
|
||||
handler = self.handler
|
||||
|
||||
def refusing(request):
|
||||
if request.method == 'POST' and request.url.path.endswith('/pedidos'):
|
||||
return httpx.Response(403, text='')
|
||||
return handler(request)
|
||||
self.tiny.http = httpx.Client(base_url=tiny_module.API, transport=httpx.MockTransport(refusing))
|
||||
self.contacts.append({'id': 600, 'cpfCnpj': '130.323.978-71', 'nome': 'Teste Fernandes'})
|
||||
code, text = self.probe('diagnostico', '--cpf', '13032397871', '--email', 'a@example.test',
|
||||
'--celular', '16999999999')
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn('só o essencial', text)
|
||||
self.assertIn('permissão do usuário do Tiny', text)
|
||||
self.assertEqual(self.orders, [])
|
||||
|
||||
def test_campos_says_which_lookup_needs_a_permission(self):
|
||||
handler = self.handler
|
||||
|
||||
@@ -594,7 +693,7 @@ class TinyProbeTests(FakeTinyCase):
|
||||
self.assertIn('"numeroOrdemCompra": "DTF-TESTE-', text)
|
||||
self.assertIn('Nada foi criado', text)
|
||||
self.assertIn('"categoria": {', text)
|
||||
self.assertIn('Marcador: KANBANDTF', text)
|
||||
self.assertIn('Marcador: SITE DTF', text)
|
||||
self.assertEqual(self.orders, [])
|
||||
self.assertTrue(all(method == 'GET' for method, _ in self.calls))
|
||||
|
||||
@@ -613,10 +712,26 @@ class TinyProbeTests(FakeTinyCase):
|
||||
self.assertEqual(len(self.orders), 1)
|
||||
self.assertEqual(self.orders[0]['itens'][0]['produto'], {'id': 104})
|
||||
self.assertIn('2º envio: already-created', text)
|
||||
self.assertIn('E-commerce no Tiny: numeroPedidoEcommerce DTF-TESTE-', text)
|
||||
# Then cancelled through the API, and read back: it does not stay open.
|
||||
self.assertEqual(self.orders[0]['situacao'], 2)
|
||||
self.assertIn(f"Pedido nº {self.orders[0]['numeroPedido']} cancelado no Tiny.", text)
|
||||
self.assertEqual(self.tags[self.orders[0]['id']], [{'descricao': 'KANBANDTF'}])
|
||||
self.assertEqual(self.tags[self.orders[0]['id']], [{'descricao': 'SITE DTF'}])
|
||||
|
||||
def test_a_number_tiny_did_not_keep_fails_the_supervised_order(self):
|
||||
# Tiny may drop the e-commerce block of an order with no channel.
|
||||
def dropping(request):
|
||||
if request.method == 'POST' and request.url.path.endswith('/pedidos'):
|
||||
body = {k: v for k, v in json.loads(request.content).items() if k != 'ecommerce'}
|
||||
request = httpx.Request(request.method, request.url, headers=request.headers, content=json.dumps(body))
|
||||
return self.handler(request)
|
||||
self.tiny = TinyOrders(auth=FakeAuth(), transport=httpx.MockTransport(dropping), today=date(2026, 9, 24))
|
||||
code, text = self.probe('pedido', '--cnpj', '11222333000181', '--email', 'a@example.test',
|
||||
'--celular', '16999999999', '--confirmar')
|
||||
self.assertEqual(code, 1, text)
|
||||
self.assertIn('numeroPedidoEcommerce (vazio) · sem canal', text)
|
||||
self.assertIn('FALHA: o Tiny não guardou DTF-TESTE-', text)
|
||||
self.assertEqual(self.orders[0]['situacao'], 2)
|
||||
|
||||
def test_cancelar_touches_only_test_orders(self):
|
||||
self.tiny.deliver('k1', PAID)
|
||||
|
||||
@@ -44,7 +44,7 @@ def run():
|
||||
items = [{'mode': 'file', 'uploads': [str(image), str(drawing)]}]
|
||||
c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft)
|
||||
VALUES(%s,%s,%s,'backfill-fixture',%s)''', (quote, owner, uuid4(), Jsonb({'items': items})))
|
||||
c.execute('INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment) VALUES(%s,%s,%s,%s,%s)',
|
||||
c.execute("INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,origin) VALUES(%s,%s,%s,%s,%s,'site')",
|
||||
(order, quote, owner, Jsonb({'items': items, 'total_cents': 1490}), Jsonb({'provider': 'teste'})))
|
||||
lines = []
|
||||
assert backfill_thumbnails.main([], out=lines.append, storage=storage) == 0
|
||||
|
||||
@@ -3,14 +3,17 @@
|
||||
Run inside the API container: python -m tests.users_test
|
||||
"""
|
||||
import secrets
|
||||
import time
|
||||
from decimal import Decimal
|
||||
from urllib.request import Request, urlopen
|
||||
from uuid import uuid4
|
||||
|
||||
from psycopg.types.json import Jsonb
|
||||
|
||||
from app import machines as routing
|
||||
from app import payments, proof
|
||||
from app.core import db
|
||||
from tests.smoke_test import Client
|
||||
from tests.smoke_test import BASE, Client, with_host
|
||||
|
||||
PASSWORD = 'senha-de-teste-123'
|
||||
|
||||
@@ -33,11 +36,31 @@ def order_fixture(c, owner, mode, metres='1', printed=None):
|
||||
'items': [item], 'freight': {'service': 'pickup'}, 'total_cents': 1490}
|
||||
c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved,approved_at)
|
||||
VALUES(%s,%s,%s,'users-fixture',%s,%s,now())''', (quote, owner, uuid4(), Jsonb(content), Jsonb(content)))
|
||||
c.execute('INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment) VALUES(%s,%s,%s,%s,%s)',
|
||||
c.execute("INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,origin) VALUES(%s,%s,%s,%s,%s,'site')",
|
||||
(order, quote, owner, Jsonb(content), Jsonb({'provider': 'teste', 'id': str(order)})))
|
||||
return quote, order
|
||||
|
||||
|
||||
def raw(client, path):
|
||||
"""A response's bytes, for what is not JSON (the receipt's PDF)."""
|
||||
with client.opener.open(Request(BASE + '/api' + path, headers=with_host()), timeout=30) as response:
|
||||
return response.read()
|
||||
|
||||
|
||||
def pickup_photo(client, oid, content):
|
||||
"""The photo of a signed receipt, sent as the counter does, until scanned clean."""
|
||||
uid = client.call(f'/operator/orders/{oid}/pickup-uploads', {'name': 'recibo.png', 'size': len(content)})['id']
|
||||
url = client.call(f'/operator/uploads/{uid}/parts/1', {})['url']
|
||||
with urlopen(Request(url, data=content, method='PUT'), timeout=30) as response:
|
||||
assert response.status == 200
|
||||
client.call(f'/operator/uploads/{uid}/complete', {})
|
||||
deadline = time.monotonic() + 150
|
||||
while client.call(f'/operator/uploads/{uid}')['scan_state'] != 'clean':
|
||||
assert time.monotonic() < deadline, 'photo scan did not finish'
|
||||
time.sleep(0.5)
|
||||
return uid
|
||||
|
||||
|
||||
def expected_machine(su, product, metres=1.0):
|
||||
"""What app/machines.py should pick now: the active machine of the product
|
||||
with the fewest metres open, among those with room, else among all."""
|
||||
@@ -70,7 +93,7 @@ def run():
|
||||
su = Client()
|
||||
su.call('/session')
|
||||
assert su.call('/operator/me', operator=True)['role'] == 'superadmin'
|
||||
emails = {r: f'{r}-{tag}@example.test' for r in ('admin', 'operador', 'vendedor', 'designer')}
|
||||
emails = {r: f'{r}-{tag}@example.test' for r in ('admin', 'operador', 'vendedor', 'designer', 'revisor')}
|
||||
owner = uuid4()
|
||||
machines, made = [], []
|
||||
try:
|
||||
@@ -93,7 +116,7 @@ def run():
|
||||
admin.call(path, {}, expected=403)
|
||||
admin.call('/operator/events', expected=403)
|
||||
admin.call('/operator/users', {'name': 'Op', 'email': emails['operador'], 'role': 'operador',
|
||||
'password': PASSWORD, 'machines': [uv]})
|
||||
'password': PASSWORD})
|
||||
admin.call('/operator/users', {'name': 'Vendas', 'email': emails['vendedor'], 'role': 'vendedor',
|
||||
'password': PASSWORD})
|
||||
admin.call('/operator/users', {'name': 'Again', 'email': emails['vendedor'], 'role': 'vendedor',
|
||||
@@ -122,17 +145,45 @@ def run():
|
||||
# On the UV machine of this test, whatever the others carry.
|
||||
su.call(f'/operator/orders/{uv_o}/machine', {'machine_id': uv}, operator=True)
|
||||
|
||||
# The operator of the UV machine sees only its orders, moves them, and nothing more.
|
||||
# The operator prints: Arte conferida to Imprimindo to Revisão, nothing
|
||||
# else (Dropstar, 2026-10-23). After signing in they say which machine
|
||||
# they are on, and must (item 12, 2026-10-30); they see the whole board.
|
||||
op = signed_in(emails['operador'])
|
||||
seen = {o['id'] for o in op.call('/operator/board')['orders']}
|
||||
assert str(uv_o) in seen and str(textil_o) not in seen, seen
|
||||
op.call(f'/operator/orders/{uv_o}/move', {'state': 'tra', 'version': 0, 'reason': ''})
|
||||
me = op.call('/operator/me')
|
||||
assert (me['machine_question'], me['machine_answered'], me['machine']) == ('required', False, None), me
|
||||
assert {str(uv_o), str(textil_o)} <= {o['id'] for o in op.call('/operator/board')['orders']}
|
||||
assert sorted(me['moves']) == [['imp', 'rev'], ['imp', 'tra'], ['rev', 'imp'], ['tra', 'imp']]
|
||||
op.call(f'/operator/orders/{uv_o}/move', {'state': 'tra', 'version': 0, 'reason': ''}, expected=403)
|
||||
with db.connect() as c:
|
||||
c.execute("UPDATE dtf_local.orders SET state='imp' WHERE id=%s", (uv_o,))
|
||||
op.call(f'/operator/orders/{uv_o}/move', {'state': 'rev', 'version': 0, 'reason': ''}, expected=409)
|
||||
op.call('/operator/me/machine', {'machine_id': None}, expected=422)
|
||||
op.call('/operator/me/machine', {'machine_id': uv})
|
||||
assert op.call('/operator/me')['machine'] == {'id': uv, 'name': f'UV {tag}'}
|
||||
op.call(f'/operator/orders/{uv_o}/move', {'state': 'cor', 'version': 0, 'reason': 'borrou'}, expected=403)
|
||||
printed = op.call(f'/operator/orders/{uv_o}/move', {'state': 'rev', 'version': 0, 'reason': ''})
|
||||
# The history names the machine with the person.
|
||||
last = op.call(f'/operator/orders/{uv_o}/history')[-1]
|
||||
assert (last['operator'], last['machine']) == (emails['operador'], f'UV {tag}'), last
|
||||
refused = op.call(f'/operator/orders/{uv_o}/move', {'state': 'fin', 'version': printed['version'], 'reason': ''},
|
||||
expected=403)
|
||||
assert refused['detail'] == 'Só o Revisor manda o pedido para Finalizado.', refused
|
||||
op.call(f'/operator/orders/{uv_o}/cancel', {'note': 'não pode'}, expected=403)
|
||||
op.call('/operator/users', expected=403)
|
||||
op.call('/operator/payment-events', expected=403)
|
||||
# Sent to the UV machine by hand, the Têxtil order appears for them.
|
||||
su.call(f'/operator/orders/{textil_o}/machine', {'machine_id': uv}, operator=True)
|
||||
assert str(textil_o) in {o['id'] for o in op.call('/operator/board')['orders']}
|
||||
# Another machine's card shows, but only who is on that machine moves it,
|
||||
# and the operator does not send orders to machines.
|
||||
with db.connect() as c:
|
||||
c.execute("UPDATE dtf_local.orders SET state='imp' WHERE id=%s", (textil_o,))
|
||||
refused = op.call(f'/operator/orders/{textil_o}/move', {'state': 'rev', 'version': 0, 'reason': ''}, expected=403)
|
||||
assert 'outra máquina' in refused['detail'], refused
|
||||
op.call(f'/operator/orders/{textil_o}/machine', {'machine_id': uv}, expected=403)
|
||||
with db.connect() as c:
|
||||
c.execute("UPDATE dtf_local.orders SET state='rec' WHERE id=%s", (textil_o,))
|
||||
# Gestão and the administrators may be on no machine; the others are never asked.
|
||||
assert admin.call('/operator/me')['machine_question'] == 'optional'
|
||||
admin.call('/operator/me/machine', {'machine_id': None})
|
||||
assert admin.call('/operator/me')['machine_answered'] and admin.call('/operator/me')['machine'] is None
|
||||
|
||||
# The seller reads and changes nothing.
|
||||
seller = signed_in(emails['vendedor'])
|
||||
@@ -142,17 +193,85 @@ def run():
|
||||
seller.call(f'/operator/quotes/{uv_q}/discard', {}, expected=403)
|
||||
seller.call(f'/operator/orders/{textil_o}/machine', {'machine_id': None}, expected=403)
|
||||
seller.call(f'/operator/orders/{textil_o}/contact', {'waiting': True, 'note': 'Ligar'}, expected=403)
|
||||
# The seller only views the board (D-30): no order registered by hand either.
|
||||
assert seller.call('/operator/me')['can'] == ['view']
|
||||
seller.call(f'/operator/quotes/{uv_q}/register', {'origin': 'atendimento', 'method': 'pix'}, expected=403)
|
||||
# Financeiro (Dropstar, 2026-10-30): the board, Pagamentos, Números and
|
||||
# Cotações, and cancels an order with its reason; moves nothing.
|
||||
emails['financeiro'] = f'financeiro-{tag}@example.test'
|
||||
admin.call('/operator/users', {'name': 'Contas', 'email': emails['financeiro'], 'role': 'financeiro',
|
||||
'password': PASSWORD})
|
||||
money = signed_in(emails['financeiro'])
|
||||
me = money.call('/operator/me')
|
||||
assert me['can'] == ['cancel', 'payments', 'view'] and me['moves'] == [] and me['reorder'] == [], me
|
||||
money.call('/operator/payment-events')
|
||||
money.call('/operator/stats?days=7')
|
||||
assert str(uv_o) in {o['id'] for o in money.call('/operator/board')['orders']}
|
||||
money.call(f'/operator/orders/{textil_o}/move', {'state': 'tra', 'version': 0, 'reason': ''}, expected=403)
|
||||
money.call(f'/operator/quotes/{uv_q}/discard', {}, expected=403)
|
||||
money.call(f'/operator/payment-events/{uuid4()}/resolve', {'note': 'Pago'}, expected=403)
|
||||
money.call(f'/operator/orders/{textil_o}/machine', {'machine_id': None}, expected=403)
|
||||
seller.call('/operator/payment-events', expected=403)
|
||||
with db.connect() as c:
|
||||
gone_q, gone_o = order_fixture(c, owner, 'file')
|
||||
made.append((gone_q, gone_o))
|
||||
seller.call(f'/operator/orders/{gone_o}/cancel', {'note': 'Cliente desistiu'}, expected=403)
|
||||
money.call(f'/operator/orders/{gone_o}/cancel', {'note': 'Cliente desistiu'})
|
||||
# The Revisor releases to Finalizado, and the administrator may too (2026-10-28).
|
||||
assert ['rev', 'fin'] in admin.call('/operator/me')['moves']
|
||||
admin.call('/operator/users', {'name': 'Confere', 'email': emails['revisor'], 'role': 'revisor',
|
||||
'password': PASSWORD})
|
||||
reviewer = signed_in(emails['revisor'])
|
||||
me = reviewer.call('/operator/me')
|
||||
assert me['can'] == ['deliver', 'view'] and sorted(me['moves']) == [['fin', 'rev'], ['rev', 'fin']] and me['reorder'] == ['rev'], me
|
||||
reviewer.call(f'/operator/orders/{textil_o}/move', {'state': 'tra', 'version': 0, 'reason': ''}, expected=403)
|
||||
assert reviewer.call(f'/operator/orders/{uv_o}/move', {'state': 'fin', 'version': printed['version'],
|
||||
'reason': ''})['state'] == 'fin'
|
||||
# A pickup in Finalizado has its receipt (item 14): 80 mm wide, saved
|
||||
# in Recibos/ by one computer only, and printed again from the panel.
|
||||
pdf = raw(su.operator_client, f'/operator/orders/{uv_o}/receipt')
|
||||
assert pdf.startswith(b'%PDF') and b'/MediaBox [0 0 226.7717 ' in pdf, pdf[:200]
|
||||
due = lambda: {r['order']: r['name'] for r in su.call('/operator/queue/folder', {'early': True}, operator=True)['receipts']}
|
||||
number = next(o for o in su.call('/operator/board', operator=True)['orders'] if o['id'] == str(uv_o))['number']
|
||||
assert due()[str(uv_o)] == f'Recibo-DTF-{number}.pdf'
|
||||
su.call(f'/operator/orders/{uv_o}/receipt/claim', {}, operator=True)
|
||||
su.call(f'/operator/orders/{uv_o}/receipt/claim', {}, operator=True, expected=409)
|
||||
assert str(uv_o) not in due()
|
||||
# Not saved after all: it goes back for another computer to take.
|
||||
su.call(f'/operator/orders/{uv_o}/receipt/release', {}, operator=True)
|
||||
assert str(uv_o) in due()
|
||||
su.call(f'/operator/orders/{uv_o}/receipt/claim', {}, operator=True)
|
||||
# "Retirado": anyone but the seller, only in Finalizado, once, with the
|
||||
# photo of the signed receipt.
|
||||
seller.call(f'/operator/orders/{uv_o}/picked-up', {}, expected=403)
|
||||
reviewer.call(f'/operator/orders/{textil_o}/picked-up', {}, expected=409)
|
||||
png = b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR' + (40).to_bytes(4, 'big') + (60).to_bytes(4, 'big') + b'\x08\x06\x00\x00\x00' + b'\x00' * 4
|
||||
photo = pickup_photo(reviewer, uv_o, png)
|
||||
reviewer.call(f'/operator/orders/{uv_o}/picked-up', {'photo': photo})
|
||||
reviewer.call(f'/operator/orders/{uv_o}/picked-up', {}, expected=409)
|
||||
shown = next(o for o in su.call('/operator/board', operator=True)['orders'] if o['id'] == str(uv_o))
|
||||
assert (shown['picked_up_by'], shown['picked_up_photo']) == (emails['revisor'], photo) and shown['picked_up_at'], shown
|
||||
|
||||
# The designer: every order, whatever its machine; the artwork stages only.
|
||||
admin.call('/operator/users', {'name': 'Arte', 'email': emails['designer'], 'role': 'designer',
|
||||
'password': PASSWORD, 'machines': [uv]})
|
||||
assert next(u for u in admin.call('/operator/users')['users'] if u['email'] == emails['designer'])['machines'] == []
|
||||
designer = signed_in(emails['designer'])
|
||||
assert set(designer.call('/operator/me')['can']) == {'view', 'produce'}
|
||||
assert set(designer.call('/operator/me')['can']) == {'view', 'produce', 'deliver'}
|
||||
designer.call(f'/operator/quotes/{uv_q}/register', {'origin': 'atendimento', 'method': 'pix'}, expected=403)
|
||||
assert {str(uv_o), str(textil_o)} <= {o['id'] for o in designer.call('/operator/board')['orders']}
|
||||
version = next(o for o in designer.call('/operator/board')['orders'] if o['id'] == str(textil_o))['version']
|
||||
moved = designer.call(f'/operator/orders/{textil_o}/move', {'state': 'tra', 'version': version, 'reason': ''})
|
||||
designer.call(f'/operator/orders/{textil_o}/move', {'state': 'fil', 'version': moved['version'], 'reason': ''},
|
||||
# A correction and back; Arte conferida only with the final approved.
|
||||
moved = designer.call(f'/operator/orders/{textil_o}/move', {'state': 'cor', 'version': version,
|
||||
'reason': 'fundo branco'})
|
||||
moved = designer.call(f'/operator/orders/{textil_o}/move', {'state': 'rec', 'version': moved['version'],
|
||||
'reason': ''})
|
||||
designer.call(f'/operator/orders/{textil_o}/move', {'state': 'tra', 'version': moved['version'], 'reason': ''},
|
||||
expected=409)
|
||||
# In the queue the card is the print room's; the designer only takes it back.
|
||||
with db.connect() as c:
|
||||
c.execute("UPDATE dtf_local.orders SET state='tra' WHERE id=%s", (textil_o,))
|
||||
designer.call(f'/operator/orders/{textil_o}/move', {'state': 'imp', 'version': moved['version'], 'reason': ''},
|
||||
expected=403)
|
||||
designer.call(f'/operator/orders/{textil_o}/move', {'state': 'rec', 'version': moved['version'],
|
||||
'reason': 'arte trocada'})
|
||||
@@ -161,6 +280,41 @@ def run():
|
||||
designer.call('/operator/queue/finals', expected=403)
|
||||
designer.call('/operator/users', expected=403)
|
||||
|
||||
# The print proof (Dropstar, 2026-10-21): above 10 m, no Finalizado before
|
||||
# "Prova OK", which the print room marks and the designer cannot.
|
||||
with db.connect() as c:
|
||||
long_q, long_o = order_fixture(c, owner, 'file', metres='12')
|
||||
made.append((long_q, long_o))
|
||||
c.execute("UPDATE dtf_local.orders SET state='rev' WHERE id=%s", (long_o,))
|
||||
version = next(o for o in su.call('/operator/board', operator=True)['orders'] if o['id'] == str(long_o))['version']
|
||||
su.call(f'/operator/orders/{long_o}/move', {'state': 'fin', 'version': version, 'reason': ''},
|
||||
operator=True, expected=409)
|
||||
designer.call(f'/operator/orders/{long_o}/proof', {}, expected=403)
|
||||
seller.call(f'/operator/orders/{long_o}/proof', {}, expected=403)
|
||||
version = su.call(f'/operator/orders/{long_o}/proof', {}, operator=True)['version']
|
||||
board = {o['id']: o for o in su.call('/operator/board', operator=True)['orders']}
|
||||
assert board[str(long_o)]['proof_ok_at'] and board[str(long_o)]['proof_ok_by']
|
||||
su.call(f'/operator/orders/{long_o}/move', {'state': 'fin', 'version': version, 'reason': ''}, operator=True)
|
||||
# Up to 10 m, nothing to wait for.
|
||||
with db.connect() as c:
|
||||
short_q, short_o = order_fixture(c, owner, 'file', metres='10')
|
||||
made.append((short_q, short_o))
|
||||
c.execute("UPDATE dtf_local.orders SET state='rev' WHERE id=%s", (short_o,))
|
||||
version = next(o for o in su.call('/operator/board', operator=True)['orders'] if o['id'] == str(short_o))['version']
|
||||
su.call(f'/operator/orders/{short_o}/move', {'state': 'fin', 'version': version, 'reason': ''}, operator=True)
|
||||
# Asked for at checkout: the paid order arrives waiting for the customer's word.
|
||||
with db.connect() as c:
|
||||
asked = uuid4()
|
||||
content = {'customer': {'mail': 'm@example.test', 'cnpj': '11222333000181', 'zap': '16999999999'},
|
||||
'items': [{'mode': 'file', 'grade': 100, 'billed_metres': '1', 'unit_cents': 1490, 'uploads': []}],
|
||||
'freight': {'service': 'pickup'}, 'total_cents': 1490, 'proof': True}
|
||||
c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved,approved_at)
|
||||
VALUES(%s,%s,%s,'users-fixture',%s,%s,now())''', (asked, owner, uuid4(), Jsonb(content), Jsonb(content)))
|
||||
quote = c.execute('SELECT * FROM dtf_local.quotes WHERE id=%s', (asked,)).fetchone()
|
||||
order, created = payments.create_order(c, quote, {'provider': 'teste', 'id': f'proof-{tag}'}, 'site')
|
||||
made.append((asked, order['id']))
|
||||
assert created and order['contact_since'] and order['contact_note'] == proof.CUSTOMER_NOTE, order
|
||||
|
||||
# Their own password: the current one is asked for.
|
||||
seller.call('/operator/me/password', {'current': 'errada', 'new': 'outra-senha-de-teste'}, expected=403)
|
||||
# Eight characters or more.
|
||||
@@ -170,15 +324,14 @@ def run():
|
||||
seller.call('/operator/me/password', {'current': 'oito-888', 'new': 'outra-senha-de-teste'})
|
||||
signed_in(emails['vendedor'], 'outra-senha-de-teste').call('/operator/me')
|
||||
|
||||
# A second Têxtil machine, its operators ticked on the machine itself: only
|
||||
# operators are linked, the seller is not.
|
||||
op_id, seller_id = users[emails['operador']]['id'], users[emails['vendedor']]['id']
|
||||
textil2 = admin.call('/operator/machines', {'name': f'Têxtil B {tag}', 'products': ['textil'],
|
||||
'operators': [op_id, seller_id]})['id']
|
||||
# A second Têxtil machine. Who is on each machine is who chose it after
|
||||
# signing in: Usuários only shows it (item 12).
|
||||
op_id = users[emails['operador']]['id']
|
||||
textil2 = admin.call('/operator/machines', {'name': f'Têxtil B {tag}', 'products': ['textil']})['id']
|
||||
machines.append(textil2)
|
||||
listed = {m['id']: m for m in admin.call('/operator/machines')['machines']}
|
||||
assert [o['id'] for o in listed[textil2]['operators']] == [op_id]
|
||||
assert set(next(u for u in admin.call('/operator/users')['users'] if u['id'] == op_id)['machines']) == {uv, textil2}
|
||||
assert listed[textil2]['operators'] == [] and [o['id'] for o in listed[uv]['operators']] == [op_id], listed[uv]
|
||||
assert next(u for u in admin.call('/operator/users')['users'] if u['id'] == op_id)['machines'] == [uv]
|
||||
# The next order goes to the one with fewer metres open.
|
||||
target = expected_machine(su, 'textil')
|
||||
with db.connect() as c:
|
||||
@@ -197,8 +350,6 @@ def run():
|
||||
'limit_metres': round(open_now + 0.5, 1)})
|
||||
listed = {m['id']: m for m in su.call('/operator/machines', operator=True)['machines']}
|
||||
assert listed[textil2]['limit_metres'] == round(open_now + 0.5, 1)
|
||||
# Left out, the operators stay as they were.
|
||||
assert [o['id'] for o in listed[textil2]['operators']] == [op_id]
|
||||
target = expected_machine(su, 'textil')
|
||||
assert target != textil2
|
||||
with db.connect() as c:
|
||||
@@ -243,6 +394,81 @@ def run():
|
||||
assert (shared['orders'], shared['metres'], shared['printing_hours'], shared['metres_per_hour']) == \
|
||||
(2, 1.5, 0.5, 3.0), shared
|
||||
|
||||
# Two at most in Imprimindo per machine (Dropstar, 2026-10-29): the first
|
||||
# to come in is printing, the second ripping; a third waits for a place.
|
||||
cap = admin.call('/operator/machines', {'name': f'Cap {tag}', 'products': ['textil']})['id']
|
||||
machines.append(cap)
|
||||
with db.connect() as c:
|
||||
pulled = [order_fixture(c, owner, 'file') for _ in range(4)]
|
||||
made.extend(pulled)
|
||||
for _, oid in pulled:
|
||||
upload = uuid4()
|
||||
c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,complete,
|
||||
expires_at,scan_state) VALUES(%s,%s,'final.pdf',1,%s,'m',true,now()+interval '20 days','clean')''',
|
||||
(upload, owner, f'test/{upload}'))
|
||||
c.execute('''INSERT INTO dtf_local.order_files(id,order_id,upload_id,item_index,kind,note,created_by)
|
||||
VALUES(%s,%s,%s,0,'final','ok','t')''', (uuid4(), oid, upload))
|
||||
c.execute("UPDATE dtf_local.orders SET state='tra', machine_id=%s, machine_chosen=true WHERE id=%s",
|
||||
(cap, oid))
|
||||
first, second_in, third, elsewhere = (str(oid) for _, oid in pulled)
|
||||
pull = lambda oid, version=0: su.call(f'/operator/orders/{oid}/move', {'state': 'imp', 'version': version,
|
||||
'reason': ''}, operator=True)
|
||||
running = pull(first)
|
||||
pull(second_in)
|
||||
refused = su.call(f'/operator/orders/{third}/move', {'state': 'imp', 'version': 0, 'reason': ''},
|
||||
operator=True, expected=409)
|
||||
assert refused['detail'] == f'Cap {tag} já tem 2 em Imprimindo.', refused
|
||||
loaded = su.call('/operator/board', operator=True)
|
||||
board = {o['id']: o for o in loaded['orders']}
|
||||
assert (board[first]['printing'], board[second_in]['printing'], board[third]['printing']) == \
|
||||
('imprimindo', 'ripando', None)
|
||||
assert loaded['printing_cap'] == 2
|
||||
assert next(m for m in loaded['machines'] if m['id'] == cap)['states'] == {'imp': 2, 'tra': 2}
|
||||
# Nor does an order already printing elsewhere come onto the full machine.
|
||||
with db.connect() as c:
|
||||
c.execute("UPDATE dtf_local.orders SET state='imp', machine_id=%s WHERE id=%s", (textil, elsewhere))
|
||||
su.call(f'/operator/orders/{elsewhere}/machine', {'machine_id': cap}, operator=True, expected=409)
|
||||
assert next(o for o in su.call('/operator/board', operator=True)['orders']
|
||||
if o['id'] == elsewhere)['machine']['id'] == textil
|
||||
# The one printing goes to Revisão: the one ripping is now printing, and a place opens.
|
||||
su.call(f'/operator/orders/{first}/move', {'state': 'rev', 'version': running['version'], 'reason': ''},
|
||||
operator=True)
|
||||
pull(third)
|
||||
board = {o['id']: o for o in su.call('/operator/board', operator=True)['orders']}
|
||||
assert (board[first]['printing'], board[second_in]['printing'], board[third]['printing']) == \
|
||||
(None, 'imprimindo', 'ripando')
|
||||
|
||||
# Pulled by an operator, a queued card becomes their machine's, whatever
|
||||
# machine it had (item 12); a machine that does not print its product
|
||||
# does not take it. Someone already on a machine is a warning, not a refusal.
|
||||
free = admin.call('/operator/machines', {'name': f'Livre {tag}', 'products': ['textil']})['id']
|
||||
machines.append(free)
|
||||
with db.connect() as c:
|
||||
queued = [order_fixture(c, owner, 'file') for _ in range(2)]
|
||||
made.extend(queued)
|
||||
for _, oid in queued:
|
||||
upload = uuid4()
|
||||
c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,complete,
|
||||
expires_at,scan_state) VALUES(%s,%s,'final.pdf',1,%s,'m',true,now()+interval '20 days','clean')''',
|
||||
(upload, owner, f'test/{upload}'))
|
||||
c.execute('''INSERT INTO dtf_local.order_files(id,order_id,upload_id,item_index,kind,note,created_by)
|
||||
VALUES(%s,%s,%s,0,'final','ok','t')''', (uuid4(), oid, upload))
|
||||
c.execute("UPDATE dtf_local.orders SET state='tra', machine_id=%s, machine_chosen=true WHERE id=%s",
|
||||
(textil, oid))
|
||||
taken_id, other_id = (str(oid) for _, oid in queued)
|
||||
wrong = op.call(f'/operator/orders/{other_id}/move', {'state': 'imp', 'version': 0, 'reason': ''}, expected=409)
|
||||
assert wrong['detail'] == f'A UV {tag} não imprime este produto.', wrong
|
||||
op.call('/operator/me/machine', {'machine_id': free})
|
||||
taken = op.call(f'/operator/orders/{taken_id}/move', {'state': 'imp', 'version': 0, 'reason': ''})
|
||||
assert str(taken['machine_id']) == free and taken['machine_chosen'], taken
|
||||
assert op.call(f'/operator/orders/{taken_id}/history')[-1]['machine'] == f'Livre {tag}'
|
||||
warned = admin.call('/operator/me/machine', {'machine_id': free}, expected=409)
|
||||
assert warned['detail'] == f'Livre {tag} já tem Op ligado.', warned
|
||||
admin.call('/operator/me/machine', {'machine_id': free, 'confirm': True})
|
||||
on_free = next(m for m in admin.call('/operator/machines')['machines'] if m['id'] == free)['operators']
|
||||
assert {o['name'] for o in on_free} == {'Op', 'Marcus'}, on_free
|
||||
designer.call('/operator/me/machine', {'machine_id': free}, expected=403)
|
||||
|
||||
# Switched off, a machine gives its automatic orders to another one.
|
||||
with db.connect() as c:
|
||||
c.execute('UPDATE dtf_local.orders SET machine_id=%s, machine_chosen=false WHERE id=%s', (textil2, second))
|
||||
@@ -263,6 +489,54 @@ def run():
|
||||
board = {o['id']: o for o in su.call('/operator/board', operator=True)['orders']}
|
||||
back = board[str(textil_o)]['machine']
|
||||
assert back and back['id'] != uv and not back['chosen']
|
||||
# Rework (D-02 to D-04): Gestão opens it with its cause, an Administrador
|
||||
# authorizes it, never their own, and only then it counts in Números.
|
||||
emails['gestao'] = f'gestao-{tag}@example.test'
|
||||
admin.call('/operator/users', {'name': 'Mayana', 'email': emails['gestao'], 'role': 'gestao', 'password': PASSWORD})
|
||||
coord = signed_in(emails['gestao'])
|
||||
with db.connect() as c:
|
||||
c.execute('UPDATE dtf_local.orders SET payment=%s WHERE id=%s',
|
||||
(Jsonb({'provider': 'mercadopago', 'id': f'rework-{tag}'}), uv_o))
|
||||
figures = lambda: admin.call('/operator/stats?days=7')['rework']
|
||||
cause = lambda figures, name: next(r for r in figures['causes'] if r['cause'] == name)['metres']
|
||||
before = figures()
|
||||
coord.call(f'/operator/orders/{uv_o}/reworks', {'cause': 'outra', 'metres': '1'}, expected=422)
|
||||
coord.call(f'/operator/orders/{uv_o}/reworks', {'cause': 'impressao', 'metres': '0'}, expected=422)
|
||||
admin.call(f'/operator/orders/{uv_o}/reworks', {'cause': 'impressao', 'metres': '1'}, expected=403)
|
||||
signed_in(emails['vendedor'], 'outra-senha-de-teste').call(f'/operator/orders/{uv_o}/reworks',
|
||||
{'cause': 'impressao', 'metres': '1'}, expected=403)
|
||||
redo = coord.call(f'/operator/orders/{uv_o}/reworks', {'cause': 'impressao', 'metres': '0.5', 'note': 'Falhou'})
|
||||
# Who printed it: the operator who sent it to Revisão, for their pay.
|
||||
assert redo['printed_by'] == emails['operador'] and redo['authorized'] is None, redo
|
||||
shown = next(o for o in admin.call('/operator/board')['orders'] if o['id'] == str(uv_o))['reworks']
|
||||
# Names where the account exists; the operator's was deleted above, so their e-mail.
|
||||
assert [(r['cause'], r['opened_name'], r['printed_name']) for r in shown] == [
|
||||
('impressao', 'Mayana', emails['operador'])], shown
|
||||
# Undecided, it does not count; it waits in Números.
|
||||
waiting = figures()
|
||||
assert cause(waiting, 'impressao') == cause(before, 'impressao')
|
||||
assert redo['id'] in [p['id'] for p in waiting['pending']]
|
||||
coord.call(f"/operator/reworks/{redo['id']}/decision", {'authorized': True}, expected=403)
|
||||
admin.call(f"/operator/reworks/{redo['id']}/decision", {'authorized': False}, expected=422)
|
||||
admin.call(f"/operator/reworks/{redo['id']}/decision", {'authorized': True})
|
||||
admin.call(f"/operator/reworks/{redo['id']}/decision", {'authorized': True}, expected=409)
|
||||
after = figures()
|
||||
assert cause(after, 'impressao') == cause(before, 'impressao') + 0.5
|
||||
assert after['house']['metres'] == before['house']['metres'] + 0.5 and after['house']['goal_percent'] == 1.6
|
||||
# The customer's approved bad art counts apart, outside the house (D-04).
|
||||
art = coord.call(f'/operator/orders/{uv_o}/reworks', {'cause': 'arte_cliente', 'metres': '2'})
|
||||
admin.call(f"/operator/reworks/{art['id']}/decision", {'authorized': True})
|
||||
last = figures()
|
||||
assert cause(last, 'arte_cliente') == cause(after, 'arte_cliente') + 2
|
||||
assert last['house']['metres'] == after['house']['metres']
|
||||
# Declined, with its reason; and nobody decides a rework they opened.
|
||||
wrong = coord.call(f'/operator/orders/{uv_o}/reworks', {'cause': 'pedido', 'metres': '1'})
|
||||
declined = admin.call(f"/operator/reworks/{wrong['id']}/decision", {'authorized': False, 'reason': 'Não houve reimpressão'})
|
||||
assert declined['authorized'] is False and declined['decline_reason'] == 'Não houve reimpressão'
|
||||
assert cause(figures(), 'pedido') == cause(last, 'pedido')
|
||||
own = su.call(f'/operator/orders/{uv_o}/reworks', {'cause': 'pedido', 'metres': '1'}, operator=True)
|
||||
su.call(f"/operator/reworks/{own['id']}/decision", {'authorized': True}, operator=True, expected=409)
|
||||
|
||||
print('PASS: profiles limit actions, admins manage users but not the superadmin or themselves, '
|
||||
'machines take orders by load and limit, keep a choice, and limit what their operators see')
|
||||
finally:
|
||||
@@ -270,9 +544,11 @@ def run():
|
||||
for _, oid in made:
|
||||
c.execute('DELETE FROM dtf_local.movements WHERE order_id=%s', (oid,))
|
||||
c.execute('DELETE FROM dtf_local.print_files WHERE order_id=%s', (oid,))
|
||||
c.execute('DELETE FROM dtf_local.order_files WHERE order_id=%s', (oid,))
|
||||
c.execute('DELETE FROM dtf_local.outbox WHERE event_key LIKE %s', (f'{oid}:%',))
|
||||
c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (oid,))
|
||||
c.execute('DELETE FROM dtf_local.quotes WHERE id=ANY(%s)', ([q for q, _ in made],))
|
||||
c.execute('DELETE FROM dtf_local.uploads WHERE owner=%s', (owner,))
|
||||
c.execute('DELETE FROM dtf_local.operators WHERE email LIKE %s', (f'%-{tag}@example.test',))
|
||||
c.execute('DELETE FROM dtf_local.machines WHERE id=ANY(%s::uuid[])', (machines,))
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""Customer identity, correction and final-file trust boundaries against local stack."""
|
||||
import os
|
||||
from uuid import uuid4
|
||||
from urllib.request import urlopen
|
||||
from tests.smoke_test import Client, approved_quote, upload_bytes, item_spec, register
|
||||
@@ -11,6 +12,8 @@ def run():
|
||||
q=customer.call('/quotes',{'request_key':str(uuid4()),'customer':profile,'items':[item],'freight':{'service':'pickup'}})
|
||||
approved_quote(customer,q,[item])
|
||||
order=customer.call('/orders/dev-paid',{'quote_id':q['id']});oid=order['id']
|
||||
# A Site order is born marked as one (Dropstar's rule D-21).
|
||||
assert next(o for o in customer.call('/operator/board',operator=True)['orders'] if o['id']==oid)['origin']=='site'
|
||||
before=list(customer.jar)[0].value
|
||||
password='local-test-password-'+uuid4().hex
|
||||
register(customer,profile,password)
|
||||
@@ -49,23 +52,28 @@ def run():
|
||||
|
||||
def move(state,version):
|
||||
return customer.call('/operator/orders/'+oid+'/move',{'state':state,'version':version,'reason':'Please replace the artwork' if state=='cor' else ''},operator=True)['version']
|
||||
version=move('tra',0)
|
||||
customer.call('/operator/orders/'+oid+'/move',{'state':'fil','version':version},operator=True,expected=409)
|
||||
# Arte conferida is the print queue (2026-10-23): it takes approved finals only.
|
||||
version=0
|
||||
customer.call('/operator/orders/'+oid+'/move',{'state':'tra','version':version},operator=True,expected=409)
|
||||
final_id=upload_bytes(customer,b'LOCAL FINAL VERSION ONE',order_id=oid)
|
||||
customer.call('/uploads/'+final_id,expected=404)
|
||||
body={'version':version,'files':[{'item_index':0,'upload_id':final_id}],'note':'Manually checked final'}
|
||||
customer.call('/operator/orders/'+oid+'/final-files',body,expected=401)
|
||||
version=customer.call('/operator/orders/'+oid+'/final-files',body,operator=True)['version']
|
||||
# A final the team uploaded is not the customer's art: "Arte tratada" (2026-10-27).
|
||||
treated=lambda:next(o for o in customer.call('/operator/board',operator=True)['orders'] if o['id']==oid)['treated']
|
||||
operator_email=os.environ.get('OPERATOR_EMAIL','operator@example.test')
|
||||
assert treated()=={'items':[0],'by':operator_email}, treated()
|
||||
detail=customer.call('/customer/orders/'+oid)
|
||||
final=detail['files'][0]
|
||||
link=customer.call('/customer/orders/'+oid+'/files/'+final['id']+'/download')
|
||||
assert urlopen(link['url']).read()==b'LOCAL FINAL VERSION ONE'
|
||||
guest=Client();guest.call('/session');guest.call('/customer/orders/'+oid+'/files/'+final['id']+'/download',expected=404)
|
||||
version=move('fil',version)
|
||||
version=move('tra',version)
|
||||
# The print queue's files come named after their order, straight from storage.
|
||||
queued=customer.call('/operator/queue/finals',operator=True)['files']
|
||||
mine=[f for f in queued if urlopen(f['url']).read()==b'LOCAL FINAL VERSION ONE']
|
||||
assert len(mine)==1 and mine[0]['name'].startswith('pedido-%d-item-1-' % mine[0]['number']), queued
|
||||
assert len(mine)==1 and mine[0]['name'].startswith('DTF-%d-item-1-' % mine[0]['number']), queued
|
||||
customer.call('/operator/queue/finals',expected=401)
|
||||
version=move('imp',version);version=move('cor',version)
|
||||
customer.call('/customer/orders/'+oid+'/files/'+final['id']+'/download',expected=404)
|
||||
@@ -81,16 +89,22 @@ def run():
|
||||
files=customer.call('/operator/orders/'+oid+'/files',operator=True)
|
||||
assert any(f['kind']=='correction' and f['active'] and f['upload_id']==correction_id for f in files)
|
||||
assert not any(f['kind']=='final' and f['active'] for f in files), 'new correction kept a stale final active'
|
||||
version=move('tra',version)
|
||||
customer.call('/operator/orders/'+oid+'/move',{'state':'fil','version':version},operator=True,expected=409)
|
||||
customer.call('/operator/orders/'+oid+'/move',{'state':'tra','version':version},operator=True,expected=409)
|
||||
# The correction itself can be approved as the final of the item it corrects.
|
||||
version=customer.call('/operator/orders/'+oid+'/final-files',{'version':version,'files':[{'item_index':0,'upload_id':correction_id}],'note':'Correction is print-ready'},operator=True)['version']
|
||||
files=customer.call('/operator/orders/'+oid+'/files',operator=True)
|
||||
assert any(f['kind']=='final' and f['active'] and f['upload_id']==correction_id for f in files)
|
||||
# The customer's own correction approved as it is: not treated.
|
||||
assert treated() is None, treated()
|
||||
customer.call('/operator/orders/'+oid+'/final-files',{'version':version,'files':[{'item_index':0,'upload_id':correction_id}],'note':'Twice'},operator=True,expected=409)
|
||||
new_final=upload_bytes(customer,b'LOCAL FINAL VERSION TWO',order_id=oid)
|
||||
version=customer.call('/operator/orders/'+oid+'/final-files',{'version':version,'files':[{'item_index':0,'upload_id':new_final}],'note':'Checked corrected final'},operator=True)['version']
|
||||
for state in ('fil','imp','fin'):version=move(state,version)
|
||||
assert treated()=={'items':[0],'by':operator_email}, treated()
|
||||
stats=customer.call('/operator/stats?days=7',operator=True)['treated']
|
||||
assert stats['orders']>=1 and any(t['orders']>=1 for t in stats['by']), stats
|
||||
for state in ('tra','imp','rev','fin'):version=move(state,version)
|
||||
# In the queue the finals stay as approved.
|
||||
customer.call('/operator/orders/'+oid+'/final-files',{'version':version,'files':[{'item_index':0,'upload_id':new_final}],'note':'Too late'},operator=True,expected=409)
|
||||
detail=other.call('/customer/orders/'+oid)
|
||||
assert detail['state']=='fin'
|
||||
assert sum(f['active'] and f['kind']=='final' for f in detail['files'])==1
|
||||
@@ -101,5 +115,37 @@ def run():
|
||||
cookie.value=old_cookie;revoked.jar.set_cookie(cookie);revoked.call('/customer/orders',expected=401)
|
||||
other.call('/session');assert other.call('/customer/orders')['items']==[]
|
||||
print('PASS: logout revokes server session and signed-out visitors cannot see account orders')
|
||||
treating()
|
||||
|
||||
def treating():
|
||||
""""Tratar a arte" (Dropstar, 2026-10-29): the item's name in the folder,
|
||||
and a treated file that replaces only its own item's final."""
|
||||
customer=Client();customer.call('/session')
|
||||
originals=[upload_bytes(customer,b'LOCAL TREAT ORIGINAL %d' % n) for n in (1,2)]
|
||||
items=[item_spec('file','1.01',0,uid) for uid in originals]
|
||||
profile={'cnpj':'11222333000181','zap':'11999999999','mail':'treat-'+uuid4().hex[:8]+'@example.test'}
|
||||
q=customer.call('/quotes',{'request_key':str(uuid4()),'customer':profile,'items':items,'freight':{'service':'pickup'}})
|
||||
approved_quote(customer,q,items)
|
||||
order=customer.call('/orders/dev-paid',{'quote_id':q['id']});oid=order['id'];number=order['number']
|
||||
files=lambda:[f for f in customer.call('/operator/orders/'+oid+'/files',operator=True) if f['kind']=='final' and f['active']]
|
||||
first=[upload_bytes(customer,b'LOCAL FIRST FINAL %d' % n,order_id=oid) for n in (1,2)]
|
||||
version=customer.call('/operator/orders/'+oid+'/final-files',{'version':0,'note':'Aprovado',
|
||||
'files':[{'item_index':i,'upload_id':u} for i,u in enumerate(first)]},operator=True)['version']
|
||||
# Where each item is in the stage folder, named as the folders save it.
|
||||
folder=customer.call('/operator/orders/'+oid+'/folder-files',operator=True)
|
||||
assert folder['state']=='rec' and [f['item'] for f in folder['files']]==[1,2], folder
|
||||
assert all(f['name'].startswith('DTF-%d-item-%d' % (number,f['item'])) for f in folder['files']), folder
|
||||
customer.call('/operator/orders/'+oid+'/folder-files',expected=401)
|
||||
# Saved over with the same name and sent back: item 1 changes, item 2 keeps its final.
|
||||
png=b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR'+(6059).to_bytes(4,'big')+(2000).to_bytes(4,'big')+b'\x08\x06\x00\x00\x00'+b'\x00'*4
|
||||
treated=upload_bytes(customer,png,name='DTF-%d-item-1.png' % number,order_id=oid)
|
||||
both=[{'item_index':0,'upload_id':treated},{'item_index':1,'upload_id':first[1]}]
|
||||
version=customer.call('/operator/orders/'+oid+'/final-files',{'version':version,'files':both,'note':'Arte tratada'},operator=True)['version']
|
||||
assert sorted((f['item_index'],f['upload_id']) for f in files())==[(0,treated),(1,first[1])], files()
|
||||
assert customer.call('/operator/orders/'+oid+'/folder-files',operator=True)['files'][0]['name']=='DTF-%d-item-1.png' % number
|
||||
# Nothing new: refused.
|
||||
customer.call('/operator/orders/'+oid+'/final-files',{'version':version,'files':both,'note':'De novo'},operator=True,expected=409)
|
||||
customer.call('/operator/orders/'+oid+'/cancel',{'note':'Teste de arte tratada'},operator=True)
|
||||
print('PASS: treating the art: the file in the folder, and one item replaced while the other keeps its final')
|
||||
|
||||
if __name__=='__main__':run()
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
mode:item.modo,metres:item.metros,grade:item.nota,production:item.production,
|
||||
quality:item.qualityStatus,
|
||||
acknowledged:item.qualityAcknowledged,
|
||||
residue:item.residueAccepted||0,
|
||||
files:(item.localFiles||[]).map(file=>({name:file.name,size:file.size,lastModified:file.lastModified}))
|
||||
}))});
|
||||
}
|
||||
@@ -57,11 +58,17 @@
|
||||
window.dtfUploadMaxBytes=session.max_upload_bytes;
|
||||
const limit=document.getElementById('zLimite');
|
||||
if(limit)limit.textContent='Até '+(session.max_upload_bytes/1073741824).toFixed(0)+' GB por arquivo.';
|
||||
// What the server charges for a file opened by hand, never the page's own text.
|
||||
const zona=document.getElementById('zManual');
|
||||
const extra=session.manual_extra_cents>0?rs(session.manual_extra_cents/100):'';
|
||||
if(zona)zona.innerHTML='Tem <b>CDR, AI, PSD ou TIFF</b>? Pode mandar também. Alguém abre na mão'+
|
||||
(extra?', e o metro custa '+extra+' a mais':'')+'.';
|
||||
const duvida=document.getElementById('duvidaManual');
|
||||
if(duvida)duvida.textContent='alguém abre na mão'+(extra?', sai mais devagar e o metro custa '+extra+' a mais':' e sai mais devagar');
|
||||
const tabela=document.getElementById('tabelaManual');
|
||||
if(tabela){tabela.hidden=!extra;tabela.textContent='Arquivo em CDR, AI, PSD ou TIFF, que alguém abre na mão: + '+extra+' por metro.';}
|
||||
if(session.manual_extra_cents>0){
|
||||
TAXA_MANUAL=session.manual_extra_cents/100;
|
||||
const zona=document.getElementById('zManual');
|
||||
if(zona)zona.innerHTML='Tem <b>CDR, AI, PSD ou TIFF</b>? Pode mandar também. Alguém abre na mão: '+
|
||||
'o metro sai pelo preço cheio, mais '+rs(TAXA_MANUAL)+'.';
|
||||
if(typeof folhas!=='undefined'&&folhas.length&&typeof pintaFolha==='function')pintaFolha();
|
||||
if(typeof itemAtual!=='undefined'&&itemAtual&&typeof carrinho==='function')carrinho();
|
||||
}
|
||||
@@ -119,27 +126,42 @@
|
||||
message('Nenhum pedido aguardando pagamento.');
|
||||
button('Ir para o carrinho', () => vaiPara(CARRINHO));
|
||||
}
|
||||
// Files start uploading as soon as they are in the cart, so a sheet of
|
||||
// several GB is on its way while the customer fills in the order. The
|
||||
// checkout waits for whatever is still going.
|
||||
// Files start uploading as soon as they are on the product page (Dropstar,
|
||||
// 2026-10-29; before, once in the cart), so a sheet of several GB is on its
|
||||
// way while the customer builds the order. The checkout waits for whatever
|
||||
// is still going.
|
||||
const envios=new Map();
|
||||
const chaveArquivo=f=>[f.name,f.size,f.lastModified].join('|');
|
||||
function enviar(file) {
|
||||
const k=chaveArquivo(file);
|
||||
let e=envios.get(k);
|
||||
if (!e) {
|
||||
e={file, sent:0, done:false, failed:null};
|
||||
e={file, sent:0, done:false, failed:null, stop:new AbortController()};
|
||||
e.promise=(async()=>{
|
||||
const session=await ready;
|
||||
return window.dtfUpload(file,{api,scope:session.cart_scope,progress:()=>{},
|
||||
return window.dtfUpload(file,{api,scope:session.cart_scope,progress:()=>{},signal:e.stop.signal,
|
||||
onBytes:n=>{e.sent=n;pintaEnvio();}});
|
||||
})();
|
||||
e.promise.then(()=>{e.done=true;falhas.delete(k);pintaEnvio();},
|
||||
error=>{envios.delete(k);falhas.set(k,{file,error});pintaEnvio();});
|
||||
error=>{envios.delete(k);if(error?.name!=='AbortError')falhas.set(k,{file,error});pintaEnvio();});
|
||||
envios.set(k,e);
|
||||
}
|
||||
return e.promise;
|
||||
}
|
||||
// Each file's upload as the product page shows it, under the uploader.
|
||||
window.dtfEnvio={
|
||||
enviar:file=>{if(!falhas.has(chaveArquivo(file)))enviar(file).catch(()=>{});},
|
||||
estado:file=>{const k=chaveArquivo(file),e=envios.get(k),f=falhas.get(k);
|
||||
return f?{fase:'falhou',erro:f.error?.message||'erro no envio'}
|
||||
:!e?null:e.done?{fase:'pronto'}:e.sent>=file.size?{fase:'verificando'}:{fase:'enviando',enviado:e.sent};},
|
||||
deNovo:file=>{falhas.delete(chaveArquivo(file));enviar(file).catch(()=>{});pintaEnvio();},
|
||||
// A file taken off the page, and in no cart item, stops going.
|
||||
manter:files=>{
|
||||
const quero=new Set([...files,...pedido.flatMap(it=>it.localFiles||[]),...(itemAtual?.localFiles||[])].map(chaveArquivo));
|
||||
for(const [k,e] of envios) if(!e.done && !quero.has(k)) e.stop.abort();
|
||||
for(const k of falhas.keys()) if(!quero.has(k)) falhas.delete(k);
|
||||
},
|
||||
};
|
||||
// The Kanban shows each order's artwork from the small picture this page
|
||||
// already made of it (site-upload.js). Never blocks the order: a picture that
|
||||
// fails to go leaves the Kanban with the layout drawing it shows today.
|
||||
@@ -196,6 +218,7 @@
|
||||
return 'Enviando seus arquivos · '+restante(e);
|
||||
}
|
||||
function pintaEnvio() {
|
||||
window.dispatchEvent(new Event('dtf-envio'));
|
||||
const e=estadoEnvio(), texto=textoEnvio(e);
|
||||
const el=document.getElementById('envioArq');
|
||||
const falhou=arquivosDoCarrinho().map(f=>falhas.get(chaveArquivo(f))).filter(Boolean);
|
||||
@@ -311,18 +334,22 @@
|
||||
uploads.push(await upload(file));
|
||||
enviaFoto(uploads[index], item.fotos?.[index]);
|
||||
}
|
||||
if (item.production?.version!==2 || item.production.sources?.length!==uploads.length)
|
||||
// Layout versions the server takes: 3 since 2026-10-21, 2 for a cart saved before.
|
||||
if (![2,3].includes(item.production?.version) || item.production.sources?.length!==uploads.length)
|
||||
throw new Error('A montagem deste item precisa ser refeita antes da cotação.');
|
||||
items.push({mode:item.modo, metres:String(item.metros), grade:item.nota, uploads,
|
||||
production:{...item.production,sources:item.production.sources.map((source,index)=>({
|
||||
upload_id:uploads[index],...source}))},
|
||||
quality_status:item.qualityStatus,quality_acknowledged:item.qualityAcknowledged});
|
||||
quality_status:item.qualityStatus,quality_acknowledged:item.qualityAcknowledged,
|
||||
residue_accepted:item.residueAccepted||0});
|
||||
}
|
||||
const service = entrega.tipo==='retira' ? 'pickup' : entrega.servico;
|
||||
if (!service) throw new Error('A entrega ainda não está disponível. Escolha a retirada em Franca.');
|
||||
const content = {customer:{...cliente},items,freight:{service,postal_code:entrega.tipo==='retira'?'':entrega.cep}};
|
||||
const destination = destinoApi();
|
||||
if (destination) content.destination = destination;
|
||||
// "Quero aprovar uma prova antes de imprimir": the order waits for the customer.
|
||||
if ($('fProva')?.checked) content.proof = true;
|
||||
if (cartSnapshot()!==initialCart) throw new Error('O carrinho mudou durante o envio. Confira os itens e envie de novo.');
|
||||
const serialized = JSON.stringify(content);
|
||||
if (!requestKey || serialized !== requestBody) {
|
||||
|
||||
@@ -676,7 +676,7 @@ h2 em{font-style:normal;color:var(--laranja)}
|
||||
<a href="/#envio">Impressão DTF</a>
|
||||
<div class="sub">
|
||||
<a href="/#envio">DTF Têxtil · 57 cm</a>
|
||||
<a href="/#envio">DTF UV · 28,5 cm</a>
|
||||
<a href="/#envio">DTF UV · 27 cm</a>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mi">
|
||||
@@ -713,7 +713,7 @@ h2 em{font-style:normal;color:var(--laranja)}
|
||||
<div class="w hero2-grid">
|
||||
<div class="hero2-text">
|
||||
<div class="chips">
|
||||
<span class="chip2 destaque">Metro a partir de R$ 14,90</span>
|
||||
<span class="chip2 destaque">Metro a partir de <span data-preco="file">R$ 19,90</span></span>
|
||||
<span class="chip2">Franca · SP · envio em até 24 h</span>
|
||||
</div>
|
||||
<h1>A gente encaixa sua folha e você paga <em>menos metro</em></h1>
|
||||
@@ -737,14 +737,14 @@ h2 em{font-style:normal;color:var(--laranja)}
|
||||
<div class="hf-num">
|
||||
<div><span>Metragem</span><b>0,60 m</b></div>
|
||||
<div><span>Nota da arte</span><b class="verde">92</b></div>
|
||||
<div><span>Preço do metro</span><b class="laranja">R$ 14,90</b></div>
|
||||
<div><span>Preço do metro</span><b class="laranja" data-preco="file">R$ 19,90</b></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<section class="etapas2"><div class="w">
|
||||
<div><span>1</span><div><b>Envie a arte</b><p>PNG, JPG ou PDF, conforme o produto. Sem cadastro.</p></div></div>
|
||||
<div><span>1</span><div><b>Envie a arte</b><p>PNG ou PDF, conforme o produto. Sem cadastro.</p></div></div>
|
||||
<div><span>2</span><div><b>Veja nota e montagem</b><p>A folha e o preço aparecem na hora.</p></div></div>
|
||||
<div><span>3</span><div><b>Pague na hora</b><p>Cartão de crédito ou PIX, na própria página.</p></div></div>
|
||||
<div><span>4</span><div><b>Acompanhe</b><p>Em Minha conta, com aviso no WhatsApp quando ficar pronto.</p></div></div>
|
||||
@@ -767,7 +767,7 @@ h2 em{font-style:normal;color:var(--laranja)}
|
||||
<div class="cards-cab">
|
||||
<div><div class="et">Escolha o produto</div>
|
||||
<h2>Qual é o seu caso?</h2></div>
|
||||
<p>O preço do metro depende da nota da arte: quanto melhor o arquivo, menor o preço.</p>
|
||||
<p>Preço único por produto. A nota da arte aparece na tela para você entender o seu arquivo; ela não muda o preço.</p>
|
||||
</div>
|
||||
<div class="escolha">
|
||||
<button class="ec f" data-modo="file">
|
||||
@@ -775,7 +775,7 @@ h2 em{font-style:normal;color:var(--laranja)}
|
||||
<h3>Arquivo por metro</h3>
|
||||
<p>Você monta a folha e manda pronta. Revisamos, corrigimos e reencaixamos se sobrar espaço.</p>
|
||||
<div class="ec-pe">
|
||||
<div class="ec-preco"><span>de</span><b data-de="file">—</b><span>a <em data-ate="file">—</em> /m conforme a nota da arte</span></div>
|
||||
<div class="ec-preco"><b data-preco="file">R$ 19,90</b><span>por metro</span></div>
|
||||
<span class="ec-go">Enviar minha folha</span>
|
||||
</div>
|
||||
</button>
|
||||
@@ -784,25 +784,25 @@ h2 em{font-style:normal;color:var(--laranja)}
|
||||
<h3>Artes avulsas</h3>
|
||||
<p>Cada arte num arquivo. A gente monta a folha com o melhor encaixe. Montagem inclusa no preço.</p>
|
||||
<div class="ec-pe">
|
||||
<div class="ec-preco"><span>de</span><b data-de="avulsa">—</b><span>a <em data-ate="avulsa">—</em> /m conforme a nota da arte</span></div>
|
||||
<div class="ec-preco"><b data-preco="avulsa">R$ 21,90</b><span>por metro</span></div>
|
||||
<span class="ec-go">Enviar minhas artes</span>
|
||||
</div>
|
||||
</button>
|
||||
<button class="ec u" data-modo="uvfile">
|
||||
<div class="ec-top"><span class="ec-kind">ADESIVO UV · 28,5 CM</span></div>
|
||||
<div class="ec-top"><span class="ec-kind">ADESIVO UV · 27 CM</span></div>
|
||||
<h3>Arquivo por metro · UV</h3>
|
||||
<p>Sua folha de UV montada. Para rígidos: caneca, garrafa, case. Não precisa de prensa.</p>
|
||||
<div class="ec-pe">
|
||||
<div class="ec-preco"><span>de</span><b data-de="uvfile">—</b><span>a <em data-ate="uvfile">—</em> /m conforme a nota da arte</span></div>
|
||||
<div class="ec-preco"><b data-preco="uvfile">R$ 79,90</b><span>por metro</span></div>
|
||||
<span class="ec-go">Enviar folha de UV</span>
|
||||
</div>
|
||||
</button>
|
||||
<button class="ec u" data-modo="uv">
|
||||
<div class="ec-top"><span class="ec-kind">ADESIVO UV · 28,5 CM</span></div>
|
||||
<div class="ec-top"><span class="ec-kind">ADESIVO UV · 27 CM</span></div>
|
||||
<h3>Artes avulsas · UV</h3>
|
||||
<p>Cada arte num arquivo. Montamos a folha de UV com o melhor encaixe. Montagem inclusa no preço.</p>
|
||||
<div class="ec-pe">
|
||||
<div class="ec-preco"><span>de</span><b data-de="uv">—</b><span>a <em data-ate="uv">—</em> /m conforme a nota da arte</span></div>
|
||||
<div class="ec-preco"><b data-preco="uv">R$ 89,90</b><span>por metro</span></div>
|
||||
<span class="ec-go">Enviar artes de UV</span>
|
||||
</div>
|
||||
</button>
|
||||
@@ -834,35 +834,35 @@ h2 em{font-style:normal;color:var(--laranja)}
|
||||
<div class="foco2" id="foco2">
|
||||
<div class="fila">
|
||||
<div class="trocouCam" id="avisoTipo" style="display:none"></div>
|
||||
<div class="recusa" id="recusa" style="display:none"></div>
|
||||
<div id="lista"></div>
|
||||
<!-- The uploader on top, the newest file right under it (Dropstar, 2026-10-29). -->
|
||||
<div class="zona" id="zona" tabindex="0" role="button">
|
||||
<div class="ico"><svg class="ic" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="m17 8-5-5-5 5"/><path d="M12 3v12"/></svg></div>
|
||||
<b id="zTit">Arraste aqui</b><span id="zSub"></span>
|
||||
<span id="zLimite">Até 1 GB por arquivo.</span>
|
||||
<span id="zLimite">Até 4 GB por arquivo.</span>
|
||||
<span class="bt">ou escolher no computador</span>
|
||||
<span class="zOutra"><b id="zOutra">Adicionar outra folha</b> ou arraste aqui</span>
|
||||
<span class="zManual" id="zManual">Tem <b>CDR, AI, PSD ou TIFF</b>? Pode mandar também.
|
||||
Alguém abre na mão e o metro sai pelo preço cheio.</span>
|
||||
Alguém abre na mão, e o metro custa R$ 2,00 a mais.</span>
|
||||
</div>
|
||||
<div class="envios" id="envios" aria-live="polite"></div>
|
||||
<div class="recusa" id="recusa" style="display:none"></div>
|
||||
<div id="lista"></div>
|
||||
<div class="resumoA" id="rA" style="display:none"></div>
|
||||
<input type="file" id="inp" hidden>
|
||||
<aside class="req" id="req">
|
||||
<h3 class="reqcab">Dúvidas:</h3>
|
||||
|
||||
<details>
|
||||
<summary>Como pagar o menor metro</summary>
|
||||
<summary>Dicas para o seu arquivo</summary>
|
||||
<ul>
|
||||
<li class="s"><b>300 DPI no tamanho que vai imprimir.</b> É a nota máxima
|
||||
e o menor preço da tabela</li>
|
||||
<li class="s"><b>300 DPI no tamanho que vai imprimir.</b> É a nota máxima</li>
|
||||
<li class="s"><b>O tamanho manda mais que o arquivo.</b> A mesma arte passa
|
||||
em 20 cm e não passa em 40. Reduzir um pouco costuma pular uma faixa
|
||||
de preço inteira</li>
|
||||
em 20 cm e não passa em 40. Reduzir um pouco costuma subir a nota</li>
|
||||
<li class="s"><b>Larguras parecidas rendem mais.</b> Se as suas artes têm
|
||||
medidas próximas, cabem mais por fileira e a folha encolhe</li>
|
||||
</ul>
|
||||
<p class="obs2">Resolução é a única coisa que mexe no preço — porque é a
|
||||
única que a gente não consegue melhorar por você.</p>
|
||||
<p class="obs2">A nota não muda o preço do metro: ela serve para você
|
||||
entender o seu arquivo.</p>
|
||||
</details>
|
||||
|
||||
<details>
|
||||
@@ -879,8 +879,8 @@ h2 em{font-style:normal;color:var(--laranja)}
|
||||
<details>
|
||||
<summary>Manda em PNG e sai na hora</summary>
|
||||
<ul>
|
||||
<li class="s"><b>PNG ou JPG</b> com fundo transparente entram direto, sem passar
|
||||
por ninguém, e não têm limite de comprimento. Só que a gente lê a resolução
|
||||
<li class="s"><b>PNG</b> com fundo transparente entra direto, sem passar
|
||||
por ninguém, e não tem limite de comprimento. Só que a gente lê a resolução
|
||||
<b>do arquivo</b>: se a arte foi ampliada antes de exportar, isso não aparece
|
||||
para nós — e sai serrilhado no filme do mesmo jeito</li>
|
||||
<li class="s"><b>PDF é o que conferimos melhor.</b> Nele medimos a resolução de
|
||||
@@ -889,10 +889,12 @@ h2 em{font-style:normal;color:var(--laranja)}
|
||||
<li class="a"><b>PDF grande.</b> Sem UserUnit, a página passa do limite de 508 cm
|
||||
do formato; divida a folha ou mande PNG. Envie um PDF de uma página por folha.</li>
|
||||
<li class="a"><b>TIFF, PSD, AI e CDR</b> a gente aceita, mas ninguém consegue
|
||||
conferir sozinho: alguém abre na mão, sai mais devagar e o metro vai pela
|
||||
tabela, sem desconto de nota</li>
|
||||
<li class="a">Em <b>artes avulsas</b> só PNG e JPG: a montagem precisa
|
||||
enxergar a sua arte para encaixar pela forma</li>
|
||||
conferir sozinho: <span id="duvidaManual">alguém abre na mão, sai mais devagar
|
||||
e o metro custa R$ 2,00 a mais</span></li>
|
||||
<li class="a"><b>JPG não passa:</b> não tem fundo transparente, e o branco do
|
||||
fundo sai no filme. Exporte a folha em PNG ou PDF</li>
|
||||
<li class="a">Em <b>artes avulsas</b> só PNG com fundo transparente: a montagem
|
||||
precisa enxergar a sua arte para encaixar pela forma</li>
|
||||
</ul>
|
||||
</details>
|
||||
|
||||
@@ -900,9 +902,11 @@ h2 em{font-style:normal;color:var(--laranja)}
|
||||
<summary>O que só você resolve</summary>
|
||||
<ul>
|
||||
<li class="n"><b>Fundo branco ou colorido.</b> Precisa ser transparente de
|
||||
verdade — branco parecendo transparente sai branco no filme</li>
|
||||
verdade — branco parecendo transparente sai branco no filme. Sem isso, o site
|
||||
não deixa pagar</li>
|
||||
<li class="n"><b>Pontinho de recorte.</b> A impressora enxerga qualquer
|
||||
resíduo e imprime. Não existe pequeno demais</li>
|
||||
resíduo e imprime. Não existe pequeno demais: o site mostra onde cada um está
|
||||
e só deixa pagar depois que você apagar</li>
|
||||
<li class="n"><b>Cópias sobrepostas.</b> Duas iguais com 1 mm de diferença
|
||||
saem duplicadas</li>
|
||||
<li class="n"><b>Menos de 96 DPI.</b> Abaixo disso não imprimimos: sai
|
||||
@@ -925,15 +929,11 @@ h2 em{font-style:normal;color:var(--laranja)}
|
||||
<div class="compra" id="compra">
|
||||
<div class="aoVivo" id="aoVivo"></div>
|
||||
<div id="compraVals" hidden>
|
||||
<div class="cEscada">
|
||||
<span>Preço do metro pela resolução</span>
|
||||
<ol id="cEscada"></ol>
|
||||
</div>
|
||||
<div class="cLin"><span>Nota da arte</span><b id="cNota">—</b></div>
|
||||
<div class="cLin"><span id="cMetroLbl">Metro</span><b id="cMetro">—</b></div>
|
||||
<div class="cLin"><span>Metragem <small>(a cada 10 cm)</small></span><b id="cMetragem">—</b></div>
|
||||
<p class="cObs" id="cObs"></p>
|
||||
<div class="cTot"><span>Total</span><b id="cTotal">—</b></div>
|
||||
<p class="cEco" id="cEco"></p>
|
||||
<div id="qmsg" style="display:none"></div>
|
||||
<div class="ciente" id="ciente">
|
||||
<h4 id="cienteTit">Ressalva de resolução</h4>
|
||||
@@ -1074,6 +1074,14 @@ h2 em{font-style:normal;color:var(--laranja)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="cxE">
|
||||
<h4>Prova antes de imprimir</h4>
|
||||
<label class="provaOp"><input type="checkbox" id="fProva">
|
||||
<span><b>Quero aprovar uma prova antes de imprimir</b>
|
||||
Imprimimos até 30 cm da sua folha e mandamos a foto pelo WhatsApp. O resto só é impresso
|
||||
depois do seu ok, então o pedido espera a sua resposta. Até 3 provas por pedido, sem custo.</span></label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<aside class="resumo">
|
||||
@@ -1117,19 +1125,16 @@ h2 em{font-style:normal;color:var(--laranja)}
|
||||
<section id="info" class="info2"><div class="w info2-grid">
|
||||
<div class="info2-preco">
|
||||
<div class="et">Preço</div>
|
||||
<h2>Arte melhor, metro mais barato</h2>
|
||||
<p>A nota aparece na tela antes de você pagar. Preço da folha que você monta:</p>
|
||||
<h2>Preço único por produto</h2>
|
||||
<p>A nota da arte aparece na tela antes de você pagar, para você entender o seu arquivo. Ela não muda o preço. Preço do metro:</p>
|
||||
<table>
|
||||
<thead><tr><th scope="col">Nota da arte</th><th scope="col">Têxtil 57 cm</th><th scope="col">UV 28,5 cm</th></tr></thead>
|
||||
<thead><tr><th scope="col">Produto</th><th scope="col">Têxtil 57 cm</th><th scope="col">UV 27 cm</th></tr></thead>
|
||||
<tbody>
|
||||
<tr><td>90 a 100</td><td class="melhor">R$ 14,90</td><td class="melhor">R$ 69,90</td></tr>
|
||||
<tr><td>75 a 89</td><td>R$ 16,20</td><td>R$ 73,90</td></tr>
|
||||
<tr><td>60 a 74</td><td>R$ 17,50</td><td>R$ 77,90</td></tr>
|
||||
<tr><td>40 a 59</td><td>R$ 18,70</td><td>R$ 81,90</td></tr>
|
||||
<tr><td>abaixo de 40</td><td>R$ 19,90</td><td>R$ 85,90</td></tr>
|
||||
<tr><td>Folha pronta</td><td data-preco="file">R$ 19,90</td><td data-preco="uvfile">R$ 79,90</td></tr>
|
||||
<tr><td>Artes avulsas</td><td data-preco="avulsa">R$ 21,90</td><td data-preco="uv">R$ 89,90</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<p class="nota2">Montagem das artes avulsas: + R$ 10,00 no têxtil e + R$ 14,00 no UV, em qualquer faixa.</p>
|
||||
<p class="nota2" id="tabelaManual">Arquivo em CDR, AI, PSD ou TIFF, que alguém abre na mão: + R$ 2,00 por metro.</p>
|
||||
</div>
|
||||
<div class="info2-vant">
|
||||
<div><b class="n">57 cm</b><b>O dobro do filme padrão</b><span>Cabe o dobro de arte por metro corrido.</span></div>
|
||||
@@ -1149,7 +1154,7 @@ h2 em{font-style:normal;color:var(--laranja)}
|
||||
<span class="fmarca"><img src="https://cdn.vnda.com.br/dropstar/2025/12/17/logo-header-15125700-16129080.png?v=1766009286" alt="Dropstar">DTF</span>
|
||||
<div class="flinks">
|
||||
<a href="https://www.dropstaratacado.com.br" target="_blank" rel="noopener">Loja de atacado</a>
|
||||
<a href="https://www.dropstaratacado.com.br/p/termos" target="_blank" rel="noopener">Trocas e privacidade</a>
|
||||
<a href="/termos">Trocas e privacidade</a>
|
||||
<a href="https://www.dropstaratacado.com.br/p/atendimento" target="_blank" rel="noopener">Fale conosco</a>
|
||||
<a href="https://www.instagram.com/dropstar.ofc/" target="_blank" rel="noopener">Instagram</a>
|
||||
</div>
|
||||
@@ -1164,7 +1169,7 @@ h2 em{font-style:normal;color:var(--laranja)}
|
||||
<div class="fbase">
|
||||
<span>© Dropstar Atacado · CNPJ 55.786.635/0001-58 · Franca-SP</span>
|
||||
<span>Cartão de crédito (Visa · Master · Elo · Amex) · PIX</span>
|
||||
<span>têxtil 57 cm · UV 28,5 cm</span>
|
||||
<span>têxtil 57 cm · UV 27 cm</span>
|
||||
</div>
|
||||
</div></footer>
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
--line:#262A2F;--line2:#2A2F35;--line3:#3A4047;
|
||||
--tx:#ECE9E4;--tx2:#D5D2CC;--muted:#A3A9B0;--faint:#8B929A;
|
||||
--accent:#FF8B2B;--accent-tx:#FFB575;--ok:#6FD19C;--warn:#F2B33D;--bad:#F4968B;--bad-line:#5A3530;
|
||||
--rec:#2BB6D9;--tra:#E0508F;--fil:#E9C23A;--imp:#D9D6D0;--cor:#F06A5B;--fin:#3FB97A;
|
||||
--rec:#2BB6D9;--tra:#E0508F;--fil:#E9C23A;--imp:#D9D6D0;--cor:#F06A5B;--rev:#8E6BDE;--fin:#3FB97A;
|
||||
--mono:Manrope,system-ui,sans-serif;
|
||||
}
|
||||
*{box-sizing:border-box}
|
||||
@@ -73,7 +73,18 @@ input[type=file]{font-size:14px;color:var(--muted);max-width:100%}
|
||||
.tinydot{display:flex;align-items:center;gap:8px;font-size:14px;color:var(--muted);white-space:nowrap}
|
||||
.tinydot::before{content:"";width:8px;height:8px;border-radius:999px;background:var(--dot,#5B6168)}
|
||||
.tinydot:empty{display:none}
|
||||
.account{margin-left:0}
|
||||
/* .morewrap pushes the panel's menu right; here the search box already does. */
|
||||
.morewrap.account{margin-left:0}
|
||||
/* The session's machine (item 12): green when on one; a click changes it. */
|
||||
.mymachine{flex-shrink:0;display:inline-flex;align-items:center;gap:6px;height:36px;padding:0 12px;border:1px solid var(--line2);border-radius:8px;background:transparent;color:var(--muted);font:inherit;font-size:13.5px;font-weight:700;cursor:pointer;white-space:nowrap}
|
||||
.mymachine.on{border-color:var(--ok);color:var(--ok);background:rgba(111,209,156,.08)}
|
||||
.mymachine[hidden]{display:none}
|
||||
.card.mine{border-color:var(--ok);box-shadow:inset 0 0 0 1px var(--ok)}
|
||||
.col-head .slot-row.mine{margin:0 -6px;padding:3px 6px;border:1px solid var(--ok);border-radius:8px}
|
||||
.machine-choices{display:grid;grid-template-columns:repeat(auto-fill,minmax(150px,1fr));gap:10px;margin:14px 0}
|
||||
.machine-choice{display:flex;flex-direction:column;align-items:flex-start;gap:3px;padding:14px;border:1px solid var(--line2);border-radius:10px;background:var(--card2);color:var(--tx);font:inherit;text-align:left;cursor:pointer}
|
||||
.machine-choice b{font-size:15px}
|
||||
.machine-choice:hover,.machine-choice.on{border-color:var(--ok)}
|
||||
.account .btn{min-width:38px;padding:0 10px;font-weight:800;letter-spacing:.02em}
|
||||
.account .menu{min-width:240px}
|
||||
.menu-head{display:flex;flex-direction:column;gap:2px;padding:8px 10px 10px;border-bottom:1px solid var(--line2);margin-bottom:4px}
|
||||
@@ -122,6 +133,20 @@ main{padding:0 24px 24px}
|
||||
.col-head small{font-size:13.5px;color:var(--faint)}
|
||||
.col-head .col-sub{justify-content:space-between;min-height:30px}
|
||||
.col-head .col-sub small{white-space:nowrap}
|
||||
.col-head .slots{flex-direction:column;align-items:stretch;gap:5px;padding-top:2px}
|
||||
.col-head .slot-row{flex-wrap:wrap;gap:4px 6px;font-size:13px}
|
||||
.slot-name{flex:1 0 auto;white-space:nowrap;color:var(--tx2);font-weight:600}
|
||||
.col-head .slot-places{gap:4px;margin-left:auto}
|
||||
.slot{display:inline-flex;align-items:center;justify-content:center;min-width:46px;height:24px;padding:0 7px;border:0;border-radius:7px;font-family:var(--mono);font-size:12.5px;font-weight:700}
|
||||
button.slot{cursor:pointer}
|
||||
button.slot:hover{filter:brightness(1.2)}
|
||||
button.slot:focus-visible{outline:2px solid var(--accent);outline-offset:1px}
|
||||
.slot.ok{color:var(--ok);background:rgba(111,209,156,.14)}
|
||||
.slot.info{color:var(--rec);background:rgba(43,182,217,.16)}
|
||||
.slot.bad{color:var(--bad);background:rgba(244,150,139,.16)}
|
||||
.slot.muted{color:var(--muted);background:var(--card2);font-family:inherit;font-weight:600}
|
||||
.slot.free{border:1px dashed var(--line2);color:var(--faint);background:transparent;font-family:inherit;font-weight:500}
|
||||
.col-head .slot-free{display:block;font-size:12.5px;line-height:1.5;color:var(--muted)}
|
||||
.col .empty{font-size:13.5px;color:var(--faint);padding:8px 2px}
|
||||
.card{text-align:left;display:flex;flex-direction:column;gap:8px;padding:12px;border-radius:10px;border:1px solid var(--line2);background:var(--card);width:100%}
|
||||
.card:hover,.card.open{border-color:var(--line3);background:#1E2226}
|
||||
@@ -129,6 +154,7 @@ main{padding:0 24px 24px}
|
||||
.card .num{font-size:14.5px;font-weight:800}
|
||||
.card .age{margin-left:auto;font-size:13.5px;color:var(--faint)}
|
||||
.card .cust{font-size:14px;font-weight:600;color:var(--tx);width:100%;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
.origin{font-size:12px;font-weight:700;padding:1px 7px;border-radius:6px;border:1px solid var(--line3);color:var(--muted)}
|
||||
.tag-teste{font-size:12.5px;font-weight:800;letter-spacing:.04em;padding:2px 7px;border-radius:6px;background:var(--warn);color:#1a1300}
|
||||
.late{font-size:13.5px;color:#F06A5B;font-weight:600}
|
||||
|
||||
@@ -188,6 +214,10 @@ main{padding:0 24px 24px}
|
||||
.finalform input[type=file]{color:var(--muted);font:inherit;font-size:13.5px;font-weight:500}
|
||||
.finalform input[type=file]::file-selector-button{height:34px;padding:0 12px;margin-right:10px;border-radius:8px;border:1px solid var(--line2);background:var(--card2);color:var(--tx);font:inherit;font-size:13.5px;font-weight:600;cursor:pointer}
|
||||
.finalform .slot{display:flex;flex-direction:column;gap:6px;font-size:14px;font-weight:600}
|
||||
.treatline{display:flex;align-items:center;gap:8px}
|
||||
.pickup{display:flex;flex-direction:column;gap:10px}
|
||||
.pickup .buttons[hidden]{display:none}
|
||||
.treatpath{flex:1;min-width:0;padding:7px 10px;border-radius:8px;background:var(--card2);font-family:var(--mono);font-size:13px;font-weight:500;color:var(--tx);word-break:break-all}
|
||||
.timeline{margin:0;padding:0;list-style:none;display:flex;flex-direction:column;gap:10px}
|
||||
.timeline li::before{content:"";width:8px;height:8px;margin-top:6px;border-radius:999px;background:var(--c,var(--muted));flex-shrink:0}
|
||||
|
||||
@@ -220,6 +250,13 @@ main{padding:0 24px 24px}
|
||||
.pane .foot .total{margin-left:auto;font-family:var(--mono);color:var(--muted)}
|
||||
.pane .foot .total b{color:var(--tx)}
|
||||
.pane .note{padding:24px;color:var(--muted)}
|
||||
.pane .register{flex-direction:column;align-items:stretch;gap:10px;border-top:1px solid var(--line)}
|
||||
.register .opts{display:grid;grid-template-columns:110px 1fr;align-items:center;gap:8px}
|
||||
.register .optset{display:flex;flex-wrap:wrap;gap:8px 16px}
|
||||
.register .optlabel{font-size:13.5px;font-weight:600;color:var(--muted)}
|
||||
.register .opt{display:inline-flex;align-items:center;gap:6px;font-size:14px;color:var(--tx2);cursor:pointer}
|
||||
.register .optrow{display:flex;gap:12px;align-items:center;flex-wrap:wrap}
|
||||
.register .optrow input{flex:1;min-width:200px;height:38px;padding:0 10px;border-radius:8px;border:1px solid var(--line3);background:var(--bg);color:var(--tx)}
|
||||
|
||||
/* Payments and integrations */
|
||||
.page{display:flex;flex-direction:column;gap:22px;padding-top:18px}
|
||||
@@ -260,6 +297,9 @@ main{padding:0 24px 24px}
|
||||
.kpi b{font-size:24px;font-weight:700;letter-spacing:-.01em;font-variant-numeric:proportional-nums}
|
||||
.kpi small{font-size:13px;color:var(--faint)}
|
||||
.statbox{padding:16px 18px;border:1px solid var(--line2);border-radius:12px;background:var(--card)}
|
||||
.statbox .stats-sub{margin:18px 0 6px;font-size:14px;font-weight:700;color:var(--tx2)}
|
||||
.plainlist{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:2px;font-size:13.5px;color:var(--muted)}
|
||||
.plainlist .linkbtn{padding:2px 0;color:var(--tx)}
|
||||
.chart{position:relative}
|
||||
.chart svg{display:block;width:100%;height:auto}
|
||||
.chart .grid{stroke:var(--line);stroke-width:1}
|
||||
@@ -513,6 +553,6 @@ a.zap{display:inline-flex;align-items:center;gap:4px;vertical-align:bottom}
|
||||
.mload{display:flex;justify-content:space-between;gap:8px;font-size:13.5px;color:var(--tx2)}
|
||||
.mload.over{color:var(--bad);font-weight:600}
|
||||
.mtile-actions{display:flex;justify-content:flex-end;gap:6px;margin-top:4px}
|
||||
/* Fila de impressão's tools: Baixar. */
|
||||
/* The queue's tools (Arte conferida): Baixar. */
|
||||
.coltools{display:flex;gap:6px;flex-shrink:0}
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
<button type="button" data-tab="quotes" aria-selected="false">Cotações <span class="badge" id="badge-quotes"></span></button>
|
||||
<button type="button" data-tab="payments" aria-selected="false">Pagamentos <span class="badge warn" id="badge-payments"></span></button>
|
||||
<button type="button" data-tab="stats" aria-selected="false">Números</button>
|
||||
<button type="button" data-tab="integrations" aria-selected="false">Integrações <span class="badge warn" id="badge-integrations" title="A pasta da Fila de impressão precisa de atenção"></span></button>
|
||||
<button type="button" data-tab="integrations" aria-selected="false">Integrações <span class="badge warn" id="badge-integrations" title="A pasta da fila precisa de atenção"></span></button>
|
||||
<button type="button" data-tab="users" aria-selected="false" hidden>Usuários</button>
|
||||
</nav>
|
||||
<div class="searchbox">
|
||||
@@ -41,6 +41,7 @@
|
||||
<option value="60">1 min</option><option value="300">5 min</option><option value="900">15 min</option>
|
||||
</select>
|
||||
</div>
|
||||
<button class="mymachine" id="my-machine" type="button" hidden></button>
|
||||
<div class="morewrap account">
|
||||
<button class="btn ghost" id="account" type="button" aria-haspopup="menu" aria-label="Minha conta"><span id="initials">·</span></button>
|
||||
<div class="menu" id="account-menu" role="menu" hidden>
|
||||
@@ -94,17 +95,32 @@
|
||||
Metros por hora: sobre o tempo em Imprimindo; pedidos imprimindo juntos na mesma máquina contam esse tempo uma vez.</p>
|
||||
<table class="log"><thead><tr><th scope="col">Máquina</th><th scope="col">Impresso</th><th scope="col">Metros por hora</th><th scope="col">Último finalizado</th><th scope="col">Agora</th></tr></thead><tbody id="stats-machines"></tbody></table>
|
||||
</section>
|
||||
<section class="statbox"><h2>Retrabalho</h2>
|
||||
<p class="faint stats-hint">Metros refeitos sobre o filme impresso no período (Por máquina), só os retrabalhos autorizados, pela data em que foram abertos. Meta de 0,4% por causa, 1,6% no total da casa; arte ruim aprovada pelo cliente fica fora da meta. <span id="stats-rework-film"></span></p>
|
||||
<table class="log"><thead><tr><th scope="col">Causa</th><th scope="col">Refeito</th><th scope="col">Do impresso</th><th scope="col">Meta</th></tr></thead><tbody id="stats-rework"></tbody></table>
|
||||
<h3 class="stats-sub">Da casa, por quem imprimiu</h3>
|
||||
<table class="log"><thead><tr><th scope="col">Quem imprimiu</th><th scope="col">Refeito</th></tr></thead><tbody id="stats-rework-printers"></tbody></table>
|
||||
<h3 class="stats-sub">Aguardando autorização</h3>
|
||||
<ul class="plainlist" id="stats-rework-pending"></ul></section>
|
||||
<section class="statbox"><h2>Por origem</h2>
|
||||
<p class="faint stats-hint">Por onde o pedido entrou: o Site, os lotes do Dropflow ou a equipe, em Atendimento. O tempo vai do pagamento ao Finalizado, sem o tempo em Aguardando contato.</p>
|
||||
<table class="log"><thead><tr><th scope="col">Origem</th><th scope="col">Pedidos</th><th scope="col">Metros</th><th scope="col">Recebido</th><th scope="col">Do pagamento ao Finalizado</th></tr></thead><tbody id="stats-origins"></tbody></table></section>
|
||||
<section class="statbox"><h2>Artes tratadas</h2>
|
||||
<p class="faint stats-hint">Pedidos do período em que o arquivo final aprovado não é a arte do cliente: alguém da equipe preparou. Por quem aprovou o arquivo.</p>
|
||||
<table class="log"><thead><tr><th scope="col">Quem aprovou</th><th scope="col">Pedidos</th></tr></thead><tbody id="stats-treated"></tbody></table></section>
|
||||
<section class="statbox"><h2>Tempo em cada etapa</h2>
|
||||
<p class="faint stats-hint">Tempo mediano por pedido: um pedido que voltou para a etapa soma o tempo de cada passagem.</p>
|
||||
<p class="faint stats-hint">Tempo mediano por pedido: um pedido que voltou para a etapa soma o tempo de cada passagem. O tempo em Aguardando contato não conta, aqui nem em “Do pagamento ao Finalizado”.</p>
|
||||
<table class="log"><thead><tr><th scope="col">Etapa</th><th scope="col">Tempo mediano</th><th scope="col">Pedidos que passaram</th><th scope="col">Agora</th></tr></thead><tbody id="stats-stages"></tbody></table>
|
||||
</section>
|
||||
</section>
|
||||
<section id="tab-users" class="page" hidden>
|
||||
<div class="pagehead"><h1>Usuários</h1><button class="btn primary" id="new-user" type="button">Novo usuário</button></div>
|
||||
<p class="faint stats-note">Quem entra no Kanban e o que cada perfil pode fazer. Administrador: tudo, inclusive esta página.
|
||||
Gestão: tudo, menos usuários. Designer: aprova arquivos e pede correção, em Arte recebida, Arte conferida e Correção.
|
||||
Operador: move pedidos e aprova arquivos. Vendedor: só consulta.</p>
|
||||
<section class="statbox"><table class="log"><thead><tr><th scope="col">Nome</th><th scope="col">Perfil</th><th scope="col">Máquinas</th><th scope="col">Último acesso</th><th scope="col"></th></tr></thead><tbody id="users-list"></tbody></table></section>
|
||||
Gestão: tudo, menos usuários; no quadro só puxa para trás, com motivo (Correção ou voltar uma etapa). Designer: vê todos os pedidos, aprova e recusa o arquivo final, pede correção.
|
||||
Operador: escolhe a máquina ao entrar; vê o quadro todo, puxa da fila para a máquina dele, imprime e passa para a Revisão, e só move os cards da máquina dele. Revisor: confere a folha impressa e libera para Finalizado; o Administrador também pode liberar.
|
||||
Vendedor: só consulta. Financeiro: vê o quadro, Pagamentos, Números e Cotações e cancela pedido, com o motivo; não move card nem mexe em arquivo.
|
||||
Retrabalho: a Gestão abre, com a causa; o Administrador autoriza.</p>
|
||||
<section class="statbox"><table class="log"><thead><tr><th scope="col">Nome</th><th scope="col">Perfil</th><th scope="col">Máquina agora</th><th scope="col">Último acesso</th><th scope="col"></th></tr></thead><tbody id="users-list"></tbody></table></section>
|
||||
<div class="pagehead"><h2>Máquinas</h2><button class="btn" id="new-machine" type="button">Nova máquina</button></div>
|
||||
<p class="faint stats-note">Cada pedido vai para a máquina do produto com menos metros em aberto, dentro do limite. No pedido dá para trocar.</p>
|
||||
<div class="mtiles" id="machines-list"></div>
|
||||
|
||||
768
web/kanban.js
768
web/kanban.js
File diff suppressed because it is too large
Load Diff
@@ -155,3 +155,8 @@ button:disabled{opacity:.6;cursor:default}
|
||||
.trilha b{font-size:12.5px}
|
||||
.duas,.tres,.busca2{grid-template-columns:1fr}
|
||||
}
|
||||
/* Trocas e privacidade (/termos): the DTF's own terms, plain reading text. */
|
||||
.termos{max-width:760px}
|
||||
.termos .termosSub{color:var(--fraco);margin:0 0 28px;font-size:16px}
|
||||
.termos h2{font-size:19px;font-weight:800;margin:26px 0 8px}
|
||||
.termos p{font-size:16px;line-height:1.65;margin:0 0 10px}
|
||||
|
||||
@@ -200,7 +200,7 @@
|
||||
<span class="fmarca"><img src="https://cdn.vnda.com.br/dropstar/2025/12/17/logo-header-15125700-16129080.png?v=1766009286" alt="Dropstar">DTF</span>
|
||||
<div class="flinks">
|
||||
<a href="https://www.dropstaratacado.com.br" target="_blank" rel="noopener">Loja de atacado</a>
|
||||
<a href="https://www.dropstaratacado.com.br/p/termos" target="_blank" rel="noopener">Trocas e privacidade</a>
|
||||
<a href="/termos">Trocas e privacidade</a>
|
||||
<a href="https://www.dropstaratacado.com.br/p/atendimento" target="_blank" rel="noopener">Fale conosco</a>
|
||||
<a href="https://www.instagram.com/dropstar.ofc/" target="_blank" rel="noopener">Instagram</a>
|
||||
</div>
|
||||
@@ -215,7 +215,7 @@
|
||||
<div class="fbase">
|
||||
<span>© Dropstar Atacado · CNPJ 55.786.635/0001-58 · Franca-SP</span>
|
||||
<span>Cartão de crédito (Visa · Master · Elo · Amex) · PIX</span>
|
||||
<span>têxtil 57 cm · UV 28,5 cm</span>
|
||||
<span>têxtil 57 cm · UV 27 cm</span>
|
||||
</div>
|
||||
</div></footer>
|
||||
|
||||
|
||||
@@ -29,7 +29,8 @@ function icone(nome){
|
||||
}
|
||||
const PRODUTO={file:'DTF Têxtil · folha montada',avulsa:'DTF Têxtil · artes avulsas',
|
||||
uvfile:'DTF UV · folha montada',uv:'DTF UV · artes avulsas'};
|
||||
const TRILHA=['rec','tra','fil','imp','fin'];
|
||||
// The order's steps as the customer sees them (Dropstar's flow, 2026-10-23).
|
||||
const TRILHA=['rec','tra','imp','rev','fin'];
|
||||
const TAMANHO=10;
|
||||
let scope,states={},environment='',conta=null;
|
||||
let filtro={status:'all',code:'',days:0,page:1};
|
||||
|
||||
@@ -57,12 +57,8 @@ function pintaPedido(){
|
||||
const frete = entrega.tipo==='frete' && entrega.cotado ? entrega.valor : 0;
|
||||
const soma = itens + frete;
|
||||
const n = aPagar.length, noCarrinho = pedido.length + (itemAtual?1:0);
|
||||
const eco = aPagar
|
||||
.reduce((t,it)=>t+(TABELA[it.modo]-(it.unit-(it.extra||0)))*it.cob, 0);
|
||||
$('resLin').innerHTML =
|
||||
'<div class="l"><span>'+n+(n===1?' item':' itens')+'</span><b>'+rs(itens+eco)+'</b></div>'+
|
||||
(eco>0.01? '<div class="l" style="color:var(--verde-ml)"><span>Desconto pela nota</span>'+
|
||||
'<b style="color:var(--verde-ml)">− '+rs(eco)+'</b></div>' : '')+
|
||||
'<div class="l"><span>'+n+(n===1?' item':' itens')+'</span><b>'+rs(itens)+'</b></div>'+
|
||||
'<div class="l"><span>Frete'+(entrega.tipo==='frete' && entrega.cotado
|
||||
? ' · '+escapeHTML((entrega.opcoes||[]).find(o=>o.service===entrega.servico)?.description||'') : '')+
|
||||
'</span><b>'+
|
||||
@@ -74,6 +70,9 @@ function pintaPedido(){
|
||||
$('bPagarTx').textContent = n>1
|
||||
? 'Pagar os '+n+' itens de uma vez'
|
||||
: 'Ir para o pagamento';
|
||||
// The proof is only for orders above 10 m (Dropstar, 2026-10-28): below it the box is gone.
|
||||
const prova=$('fProva');
|
||||
if(prova){ const longo=aPagar.reduce((t,it)=>t+(it.cob||0),0)>10; prova.closest('.cxE').hidden=!longo; if(!longo) prova.checked=false; }
|
||||
$('bPagar').disabled = !cartPodeEnviar() || !entrega.cotado || !clienteOk() || !enderecoOk();
|
||||
if(pedido.length || itemAtual) $('carr').classList.add('on');
|
||||
if($('cartN')){ $('cartN').textContent=noCarrinho>99?'99+':noCarrinho; $('cartN').hidden=!noCarrinho;
|
||||
@@ -81,21 +80,14 @@ function pintaPedido(){
|
||||
window.dispatchEvent(new Event('dtf-cart-changed'));
|
||||
}
|
||||
|
||||
// Um preço por produto (Dropstar, 23/10/2026): a nota aparece, mas não entra na conta.
|
||||
function carrinho(){
|
||||
const base=precoBase(nota), cob=cobrar(metros);
|
||||
const base=precoMetro(), cob=cobrar(metros);
|
||||
const extra=folhaManual()? TAXA_MANUAL : 0;
|
||||
const unit=base+extra, tot=cob*unit, sobra=+(cob-metros).toFixed(2);
|
||||
$('carr').classList.add('on');
|
||||
let l='<div class="l"><span>'+MODOS[modo].tit+'</span><b>'+rs(base)+'/m</b></div>';
|
||||
{
|
||||
const teto=TABELA[modo], eco=(teto-base)*cob;
|
||||
l = '<div class="l"><span>'+MODOS[modo].tit+' · tabela</span><b>'+rs(teto)+'/m</b></div>';
|
||||
l += eco>0.01
|
||||
? '<div class="l" style="color:#7FD4A0"><span>Desconto pela nota '+nota+'</span><b>−'+rs(eco)+'</b></div>'
|
||||
: '<div class="l" style="color:#8D9AB0"><span>Nota '+nota+' · sem desconto</span><b>—</b></div>';
|
||||
}
|
||||
if(!ehFolha()) l += '<div class="l" style="color:#8D9AB0"><span>Montagem da folha</span>'+
|
||||
'<b>inclusa · '+rs(MONTAGEM[modo])+'/m</b></div>';
|
||||
if(!ehFolha()) l += '<div class="l" style="color:#8D9AB0"><span>Montagem da folha</span><b>inclusa</b></div>';
|
||||
if(extra) l += '<div class="l"><span>Arquivo aberto na mão</span><b>+'+rs(extra)+'/m</b></div>';
|
||||
l += '<div class="l"><span>Metragem'+(sobra>0.001?' · arredondada para 10 cm':'')+
|
||||
'</span><b>'+fmtM(cob)+' m</b></div>';
|
||||
@@ -137,14 +129,11 @@ function carrinho(){
|
||||
qualityStatus:$('ciente').classList.contains('recusa')?'rejected':
|
||||
$('ciente').classList.contains('on')?'warning':nota===0?'unverified':'ok',
|
||||
qualityAcknowledged:false,
|
||||
// The residue dots the customer accepted printing (Dropstar, 2026-10-29).
|
||||
residueAccepted:ehFolha()?residuosAceitos():0,
|
||||
desc:fmtM(cob)+' m · '+rs(unit)+'/m · nota '+nota};
|
||||
pintaPedido();
|
||||
previa();
|
||||
if(nota<90){
|
||||
const piso=pisoEscada(), ganho=(unit-piso)*cob;
|
||||
if(ganho>0.5) qm('<b>Dá para pagar menos.</b> Com a arte em 300 DPI, '+
|
||||
'o metro cai para '+rs(piso)+' — são '+rs(ganho)+' a menos neste pedido.','var(--verde)');
|
||||
}
|
||||
}
|
||||
// Removing is one click, and a wrong click is undone from the notice that follows.
|
||||
let desfazerAcao=null, desfazerTimer=null;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/* Site DTF — the product page's buy box: price ladder, price per metre, billed length,
|
||||
/* Site DTF — the product page's buy box: the grade, price per metre, billed length,
|
||||
total and the add-to-cart button, beside the live sheet. It shows the item
|
||||
the other site-*.js files already priced (itemAtual) and never computes a
|
||||
price of its own, so the box and the cart always agree. */
|
||||
@@ -9,23 +9,12 @@
|
||||
vals.hidden=!it;
|
||||
add.disabled=!it || !itemPodeEnviar(it);
|
||||
if(!it) return;
|
||||
const semNota=!it.nota;
|
||||
// The price ladder in resolution: nota = DPI ÷ 3, so 90 is 270 DPI.
|
||||
const faixas=FAIXAS[it.modo], ativa=faixas.findIndex(([min])=>it.nota>=min);
|
||||
$('cEscada').innerHTML=faixas.map(([min,v],i)=>
|
||||
'<li'+(i===ativa?' class="on" aria-current="true"':'')+'><span>'+
|
||||
(min? min*3+'+'+(i? '' : ' DPI') : semNota? 'cheio' : 'menos')+'</span>'+
|
||||
'<b>'+rs(v).slice(3)+'</b></li>').join('');
|
||||
const analisadas=ehFolha(it.modo) && folhas.length && folhas.every(x=>x.an);
|
||||
$('cMetroLbl').textContent = it.extra ? 'Metro · cheio + '+rs(it.extra)+' manual'
|
||||
: semNota ? 'Metro · preço cheio'
|
||||
: analisadas && folhas.every(x=>x.an.vetor) ? 'Metro · arte vetorial'
|
||||
: analisadas ? 'Metro · '+Math.min(...folhas.map(x=>x.an.dpi))+' DPI'
|
||||
: 'Metro';
|
||||
// One price per product (Dropstar, 2026-10-23): the grade is shown to explain
|
||||
// the file, on its own line, and never changes the metre.
|
||||
$('cNota').textContent = it.nota ? it.nota+'/100' : '—';
|
||||
$('cMetroLbl').textContent = it.extra ? 'Metro · com '+rs(it.extra)+' de arquivo manual' : 'Metro';
|
||||
$('cMetro').textContent=rs(it.unit);
|
||||
$('cMetragem').textContent=fmtM(it.cob)+' m';
|
||||
const economia=(TABELA[it.modo]-(it.unit-(it.extra||0)))*it.cob;
|
||||
$('cEco').textContent = economia>0.005 ? rs(economia)+' a menos pela resolução da arte' : '';
|
||||
const partes=ehFolha(it.modo) ? Math.ceil(it.metros/20) : 1;
|
||||
$('cPartes').textContent = partes>1 ? ' Sai em '+partes+' partes de até 20 m.' : '';
|
||||
const sobraCm=Math.round((it.cob-it.metros)*100);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/* Site DTF — Product tables, commercial ladders, shared state and field validation.
|
||||
/* Site DTF — Product tables, prices, shared state and field validation.
|
||||
Extracted verbatim from the single inline script in web/index.html.
|
||||
Loaded as classic scripts in the order listed there: they share one global
|
||||
scope and run top to bottom, exactly as the original did. */
|
||||
@@ -35,40 +35,36 @@ const fmt=b=>b<1048576?(b/1024).toFixed(0)+' KB'
|
||||
// ── modos
|
||||
const MODOS={
|
||||
file: {tit:'Arquivo por metro', lg:'DTF têxtil · 57 cm', larg:57, multi:true, folha:true,
|
||||
zt:'Arraste sua folha montada aqui', zs:'PNG, JPG ou PDF · 57 cm de largura'},
|
||||
zt:'Arraste sua folha montada aqui', zs:'PNG ou PDF com fundo transparente · 57 cm de largura'},
|
||||
avulsa:{tit:'Artes avulsas', lg:'DTF têxtil · 57 cm', larg:57, multi:true,
|
||||
zt:'Arraste suas artes aqui',
|
||||
zs:'PNG ou JPG com fundo transparente · informe a largura de cada uma'},
|
||||
uvfile:{tit:'Arquivo por metro · UV', lg:'Adesivo UV · 28,5 cm', larg:28.5, multi:true, folha:true,
|
||||
zt:'Arraste sua folha de UV aqui', zs:'PNG, JPG ou PDF · 28,5 cm de largura'},
|
||||
uv: {tit:'Artes avulsas · UV', lg:'Adesivo UV · 28,5 cm', larg:28.5, multi:true,
|
||||
zs:'PNG com fundo transparente · informe a largura de cada uma'},
|
||||
uvfile:{tit:'Arquivo por metro · UV', lg:'Adesivo UV · 27 cm', larg:27, multi:true, folha:true,
|
||||
zt:'Arraste sua folha de UV aqui', zs:'PNG ou PDF com fundo transparente · 27 cm de largura'},
|
||||
uv: {tit:'Artes avulsas · UV', lg:'Adesivo UV · 27 cm', larg:27, multi:true,
|
||||
zt:'Arraste suas artes de UV',
|
||||
zs:'PNG ou JPG com fundo transparente · informe a largura de cada arte'}
|
||||
zs:'PNG com fundo transparente · informe a largura de cada arte'}
|
||||
};
|
||||
// Quatro escadas. A de artes avulsas e a da folha pronta mais a montagem:
|
||||
// R$ 10,00 no têxtil, R$ 14,00 no UV, constante em todas as faixas.
|
||||
const FAIXAS={
|
||||
file: [[90,14.90],[75,16.20],[60,17.50],[40,18.70],[0,19.90]],
|
||||
avulsa:[[90,24.90],[75,26.20],[60,27.50],[40,28.70],[0,29.90]],
|
||||
uvfile:[[90,69.90],[75,73.90],[60,77.90],[40,81.90],[0,85.90]],
|
||||
uv: [[90,83.90],[75,87.90],[60,91.90],[40,95.90],[0,99.90]]
|
||||
};
|
||||
const TABELA={file:19.90, avulsa:29.90, uvfile:85.90, uv:99.90}; // teto de cada escada
|
||||
const MONTAGEM={avulsa:10.00, uv:14.00}; // o que a montagem soma sobre a folha pronta
|
||||
// Preço único por produto (Dropstar, 23/10/2026). A nota da arte continua na
|
||||
// tela, para o cliente entender o arquivo dele, mas não mexe no preço.
|
||||
// O servidor cobra o mesmo (app/core/pricing.py, conferido em tests/test_pricing.py).
|
||||
const PRECO={file:19.90, avulsa:21.90, uvfile:79.90, uv:89.90};
|
||||
// Folha que alguém abre na mão (CDR, AI, PSD, TIFF): R$ a mais por metro.
|
||||
// Vem do servidor (/api/session), que cobra o mesmo; zero não soma nada.
|
||||
let TAXA_MANUAL=0;
|
||||
const folhaManual=()=>ehFolha() && folhas.some(x=>!x.med);
|
||||
const ehFolha=m=>!!MODOS[m||modo].folha;
|
||||
const pisoEscada=m=>FAIXAS[m||modo][0][1];
|
||||
const precoMetro=m=>PRECO[m||modo];
|
||||
const MINIMO_M=1, GAP_CM=0.5, RODAPE_CM=5;
|
||||
const RENDERIZA=/[.](png|jpe?g|webp|gif|bmp)$/i;
|
||||
// Folha pronta: dá para medir PNG, JPG e PDF. PSD, AI, TIFF e CDR entram, mas
|
||||
// Folha pronta: dá para medir PNG e PDF. PSD, AI, TIFF e CDR entram, mas
|
||||
// o navegador não abre — o cliente informa o comprimento e o arquivo passa por
|
||||
// tratamento antes de imprimir.
|
||||
// JPG não tem canal alfa: o branco do fundo sai no filme, e na montagem a arte
|
||||
// vira uma caixa retangular. Não entra em produto nenhum (Dropstar, 23/10/2026).
|
||||
const ACEITA={
|
||||
folha: /[.](png|jpe?g|tiff?|pdf|psd|psb|ai|cdr)$/i,
|
||||
avulsa: /[.](png|jpe?g|webp)$/i
|
||||
folha: /[.](png|tiff?|pdf|psd|psb|ai|cdr)$/i,
|
||||
avulsa: /[.](png|webp)$/i
|
||||
};
|
||||
const MEDE=/[.](png|jpe?g|webp|gif|bmp|pdf)$/i;
|
||||
const DPI_RECUSA=96, DPI_AVISA=300; // régua dos designers · 02/09/2026
|
||||
@@ -160,11 +156,8 @@ const larguraFilme=()=>MODOS[modo].larg;
|
||||
// cobrança proporcional: arredonda para cima em 10 cm · 2,75 m vira 2,80 m
|
||||
const cobrar=m=>Math.max(MINIMO_M, Math.ceil(m*10)/10);
|
||||
const fmtM=m=>m.toFixed(2).replace('.',',');
|
||||
const precoBase=n=>
|
||||
(FAIXAS[modo].find(f=>n>=f[0])||FAIXAS[modo][FAIXAS[modo].length-1])[1];
|
||||
const descontoMetragem=()=>0; // sem progressão por quantidade
|
||||
const cls=n=>n>=85?'ok':n>=50?'av':'er';
|
||||
const dpiDe=a=>a.cm>0? (a.giro?a.py:a.px)/(a.cm/2.54) : 0;
|
||||
// girar 90° inverte a proporção · espelhar não muda medida, só o desenho
|
||||
const propDe=a=>{ const p=a.prop||1; return a.giro? 1/p : p; };
|
||||
const TAMANHOS={57:[10,15,20,25,28.2], 28.5:[5,8,10,14,28.2]};
|
||||
const TAMANHOS={57:[10,15,20,25,28.2], 27:[5,8,10,13,26.7]};
|
||||
|
||||
@@ -30,9 +30,10 @@ function pintaModo(){
|
||||
$('zOutra').textContent = ehFolha(m) ? 'Adicionar outra folha' : 'Adicionar mais artes';
|
||||
$('zona').classList.remove('compacta');
|
||||
$('inp').multiple=c.multi;
|
||||
// The file decides the price: PNG, JPG and PDF are checked here, the others by hand.
|
||||
$('inp').accept = ehFolha(m) ? '.png,.jpg,.jpeg,.pdf,.tif,.tiff,.psd,.psb,.ai,.cdr'
|
||||
: '.png,.jpg,.jpeg,.webp';
|
||||
// The file decides how it is checked: PNG and PDF here, the others by hand
|
||||
// (TAXA_MANUAL). JPG has no transparency and is refused (ACEITA, web/site-config.js).
|
||||
$('inp').accept = ehFolha(m) ? '.png,.pdf,.tif,.tiff,.psd,.psb,.ai,.cdr'
|
||||
: '.png,.webp';
|
||||
$('catFoco').className='cat '+(ehFolha(m)?'file':'av');
|
||||
$('larguraFolhaPronta').textContent=String(c.larg).replace('.',',');
|
||||
$('foco2').classList.remove('sofila'); // a caixa de requisitos vale nos 4 modos
|
||||
@@ -49,8 +50,8 @@ function pintaTipoEnvio(){
|
||||
if(el.hidden) return;
|
||||
const folha = ehFolha() ? modo : PAR[modo];
|
||||
const avulsa = ehFolha() ? PAR[modo] : modo;
|
||||
$('tipoFolhaPreco').textContent=rs(pisoEscada(folha))+' a '+rs(TABELA[folha]).slice(3)+' /m';
|
||||
$('tipoAvulsaPreco').textContent='+ '+rs(MONTAGEM[avulsa])+' /m';
|
||||
$('tipoFolhaPreco').textContent=rs(PRECO[folha])+' /m';
|
||||
$('tipoAvulsaPreco').textContent=rs(PRECO[avulsa])+' /m';
|
||||
$('larguraFolhaPronta').textContent=String(MODOS[folha].larg).replace('.',',');
|
||||
const atual = ehFolha() ? 'folha' : 'avulsa';
|
||||
el.querySelectorAll('.cam').forEach(b=>{
|
||||
@@ -72,7 +73,7 @@ function recusaFolha(x, md){
|
||||
'Para ocupar os '+n1(larguraFilme())+' cm do filme ela teria só '+md.dpiFolha+
|
||||
' DPI, e o mínimo para imprimir é '+DPI_RECUSA+'. '+
|
||||
'Se for uma arte para montarmos, use <b>'+MODOS[destino].tit+'</b>, '+
|
||||
'a partir de '+rs(pisoEscada(destino))+'/m. '+
|
||||
'a '+rs(PRECO[destino])+' o metro. '+
|
||||
'<button type="button" id="usarAvulsa">Enviar como '+MODOS[destino].tit.toLowerCase()+'</button>');
|
||||
const botao=$('usarAvulsa');
|
||||
if(botao) botao.addEventListener('click',()=>{
|
||||
|
||||
@@ -154,8 +154,10 @@ function encaixar(pecas,W){
|
||||
function encaixarEmLinhas(pecas,W){
|
||||
const arteDe=p=>p.a||p;
|
||||
const artes=[...new Set(pecas.map(arteDe))];
|
||||
// Toda peça que não é quadrada é testada nos dois sentidos (Dropstar,
|
||||
// 23/10/2026): 19,5 x 18,5 cm cabe 2 por linha de pé e 3 deitada.
|
||||
const giraveis=artes.filter(arte=>{const p=pecas.find(q=>arteDe(q)===arte);
|
||||
return !p.mPronta && !p.travado && Math.abs(p.w-p.h)>1 && p.h<=W;});
|
||||
return !p.mPronta && !p.travado && Math.abs(p.w-p.h)>0.01 && p.h<=W;});
|
||||
const deitadas=new Set();
|
||||
const montar=()=>emLinhas(pecas.map(p=>deitadas.has(arteDe(p))
|
||||
? {ref:p,w:p.h,h:p.w,rot:90} : {ref:p,w:p.w,h:p.h,rot:0}),W);
|
||||
@@ -236,7 +238,7 @@ function encaixarPelaForma(pecas,W){
|
||||
|
||||
ordem.forEach(p=>{
|
||||
const oris=[{w:p.w,h:p.h,rot:0}];
|
||||
if(!p.mPronta && !p.travado && Math.abs(p.w-p.h)>1 && p.h<=W) oris.push({w:p.h,h:p.w,rot:90});
|
||||
if(!p.mPronta && !p.travado && Math.abs(p.w-p.h)>0.01 && p.h<=W) oris.push({w:p.h,h:p.w,rot:90});
|
||||
|
||||
let melhor=null;
|
||||
oris.forEach(o=>{
|
||||
|
||||
160
web/site-pdf.js
160
web/site-pdf.js
@@ -85,11 +85,14 @@ function resumoDpi(lista){
|
||||
}
|
||||
|
||||
// Rasteriza a primeira página a 1 mm por pixel e devolve a tela para a análise
|
||||
async function rasterizarPdf(file, larguraCm, alturaCm){
|
||||
// The page drawn small for the preview and, with comMapa, again in strips at
|
||||
// about 0,2 mm per pixel for the ink map the residue check measures.
|
||||
const PDF_PX_POR_CM=50, PDF_MAPA_PX=30e6;
|
||||
async function rasterizarPdf(file, larguraCm, alturaCm, comMapa){
|
||||
const lib=await carregarPdfJs();
|
||||
if(!lib) return {erro:'não foi possível carregar o leitor de PDF'};
|
||||
// Decide after the worker check; the old timeout always used 30 seconds.
|
||||
const espera=temWorker===false ? 90000 : 30000;
|
||||
const espera=(temWorker===false ? 90000 : 30000)*(comMapa ? 2 : 1);
|
||||
const folga=temWorker===false ? 2.2 : 1;
|
||||
let loading=null, doc=null, rendering=null, expired=false, timer=null;
|
||||
const trabalho=(async()=>{
|
||||
@@ -117,7 +120,28 @@ async function rasterizarPdf(file, larguraCm, alturaCm){
|
||||
let dpis=[];
|
||||
try{ dpis=dpiDasImagens(page,ops); }catch(e){}
|
||||
const r=resumoDpi(dpis);
|
||||
return {tela:cv, dpi:r? r.ponderado:null, res:r};
|
||||
let mapa=null;
|
||||
if(comMapa){
|
||||
const altura=alturaCm||larguraCm*vp1.height/vp1.width;
|
||||
const pxPorCm=Math.min(PDF_PX_POR_CM, Math.sqrt(PDF_MAPA_PX/(larguraCm*altura)));
|
||||
const vpM=page.getViewport({scale:pxPorCm*larguraCm/vp1.width});
|
||||
const W=Math.max(1,Math.round(vpM.width)), H=Math.max(1,Math.round(vpM.height));
|
||||
mapa=novoMapa(W,H,larguraCm);
|
||||
const faixa=Math.max(1,Math.min(H,Math.floor(4e6/W)));
|
||||
const cvM=document.createElement('canvas'); cvM.width=W; cvM.height=faixa;
|
||||
const ctxM=cvM.getContext('2d',{willReadFrequently:true});
|
||||
for(let topo=0;topo<H;topo+=faixa){
|
||||
const n=Math.min(faixa,H-topo);
|
||||
ctxM.clearRect(0,0,W,faixa);
|
||||
rendering=page.render({canvasContext:ctxM, viewport:vpM, transform:[1,0,0,1,0,-topo],
|
||||
background:'rgba(0,0,0,0)'});
|
||||
await rendering.promise;
|
||||
if(expired) return null;
|
||||
const d=ctxM.getImageData(0,0,W,n).data;
|
||||
for(let k=0;k<n;k++) mapaLinha(mapa,topo+k,d,k*W*4+3,4);
|
||||
}
|
||||
}
|
||||
return {tela:cv, dpi:r? r.ponderado:null, res:r, mapa};
|
||||
}catch(e){
|
||||
if(expired) return null;
|
||||
return {erro:(e&&e.message)||'erro ao abrir o PDF', semWorker:temWorker===false};
|
||||
@@ -170,10 +194,11 @@ async function dimensoesImagem(file){
|
||||
}
|
||||
// A small copy of a large PNG, read as a stream: the file is inflated in
|
||||
// pieces and only every n-th pixel of every n-th row is kept, so memory stays
|
||||
// at a few MB whatever the file's size. It is the preview, and what the sheet
|
||||
// check (pieces, gaps, background) reads. 8- and 16-bit greyscale, RGB,
|
||||
// palette and alpha; interlaced files return null.
|
||||
async function previaPngGrande(file, larguraAlvo, progresso){
|
||||
// at a few MB whatever the file's size. It is the preview. Given the sheet's
|
||||
// width in cm (mapaCm), every pixel also goes into the ink map the sheet check
|
||||
// reads, and it returns {cv, mapa}. 8- and 16-bit greyscale, RGB, palette and
|
||||
// alpha; interlaced files return null.
|
||||
async function previaPngGrande(file, larguraAlvo, progresso, mapaCm){
|
||||
const leitor=file.stream().getReader();
|
||||
let pedacos=[], guardado=0, lidos=0, fim=false;
|
||||
// A queue of the file's pieces: take() never copies more than it returns.
|
||||
@@ -234,6 +259,18 @@ async function previaPngGrande(file, larguraAlvo, progresso){
|
||||
const cw=Math.ceil(w/passo), ch=Math.ceil(h/passo);
|
||||
const cv=document.createElement('canvas'); cv.width=cw; cv.height=ch;
|
||||
const ctx=cv.getContext('2d'), img=ctx.createImageData(cw,1), px=img.data;
|
||||
// The ink map reads each pixel's alpha: from the row itself when the file has
|
||||
// an alpha channel, else from the palette or the transparent colour.
|
||||
const mapa=mapaCm ? novoMapa(w,h,mapaCm) : null;
|
||||
const alfaLinha=mapa && ![4,6].includes(tipo) ? new Uint8Array(w).fill(255) : null;
|
||||
const alfaDaLinha=()=>{
|
||||
if(tipo===3){ for(let x=0;x<w;x++){ const q=atual[x]; alfaLinha[x]=trns&&q<trns.length?trns[q]:255; } }
|
||||
else if(trns && tipo===0){ for(let x=0,i=0;x<w;x++,i+=bpp)
|
||||
alfaLinha[x]=atual[i]===trns[2-b] && (b===1||atual[i+1]===trns[1]) ? 0 : 255; }
|
||||
else if(trns && tipo===2){ for(let x=0,i=0;x<w;x++,i+=bpp){ let igual=true;
|
||||
for(let k=0;k<3&&igual;k++) igual=atual[i+k*b]===trns[k*2+2-b] && (b===1||atual[i+k*b+1]===trns[k*2+1]);
|
||||
alfaLinha[x]=igual?0:255; } }
|
||||
};
|
||||
// Each row is gathered whole (filter byte + data), then unfiltered in one
|
||||
// tight loop for its filter type.
|
||||
let ant=new Uint8Array(linha), atual=new Uint8Array(linha), y=0;
|
||||
@@ -261,6 +298,11 @@ async function previaPngGrande(file, larguraAlvo, progresso){
|
||||
cheio=0;
|
||||
// Every row is unfiltered: Up, Average and Paeth read the previous one.
|
||||
desfiltra();
|
||||
if(mapa){
|
||||
if(tipo===6) mapaLinha(mapa,y,atual,3*b,bpp);
|
||||
else if(tipo===4) mapaLinha(mapa,y,atual,b,bpp);
|
||||
else{ alfaDaLinha(); mapaLinha(mapa,y,alfaLinha,0,1); }
|
||||
}
|
||||
if(y%passo===0 && y/passo<ch){
|
||||
for(let xx=0,k=0;xx<w;xx+=passo,k+=4){
|
||||
const i=xx*bpp;
|
||||
@@ -277,7 +319,8 @@ async function previaPngGrande(file, larguraAlvo, progresso){
|
||||
}
|
||||
await alimenta.catch(()=>{});
|
||||
leitor.cancel().catch(()=>{});
|
||||
return y>=h ? cv : null;
|
||||
if(y<h) return null;
|
||||
return mapa ? {cv, mapa} : cv;
|
||||
}
|
||||
// Large PDFs are read in ranges, never loaded whole into memory.
|
||||
async function fontePdf(lib, file){
|
||||
@@ -366,6 +409,26 @@ function miniatura(fonte, maxW=104, maxH=192){
|
||||
cv.getContext('2d').drawImage(fonte,0,0,cv.width,cv.height);
|
||||
return cv.toDataURL('image/webp',0.8);
|
||||
}
|
||||
// The preview with a red circle around each residue dot and its size, so the
|
||||
// customer finds what to erase: on the screen they are invisible.
|
||||
async function previaMarcada(src, pontos){
|
||||
const img=await new Promise(res=>{ const im=new Image(); im.onload=()=>res(im); im.onerror=()=>res(null); im.src=src; });
|
||||
if(!img) return src;
|
||||
const s=Math.min(1,1200/img.naturalWidth), cv=document.createElement('canvas');
|
||||
cv.width=Math.max(1,Math.round(img.naturalWidth*s)); cv.height=Math.max(1,Math.round(img.naturalHeight*s));
|
||||
const ctx=cv.getContext('2d');
|
||||
ctx.drawImage(img,0,0,cv.width,cv.height);
|
||||
const r=Math.max(9,cv.width*0.014);
|
||||
ctx.lineWidth=Math.max(2,r/4); ctx.strokeStyle='#E0301E'; ctx.font='700 '+Math.round(r*1.1)+'px Inter, sans-serif';
|
||||
for(const p of pontos){
|
||||
const x=p.x*cv.width, y=p.y*cv.height;
|
||||
ctx.beginPath(); ctx.arc(x,y,r,0,2*Math.PI); ctx.stroke();
|
||||
const t=n1(p.mm)+' mm', tw=ctx.measureText(t).width, tx=Math.min(x+r+4,cv.width-tw-4);
|
||||
ctx.fillStyle='rgba(255,255,255,.9)'; ctx.fillRect(tx-3,y-r*0.7,tw+6,r*1.4);
|
||||
ctx.fillStyle='#E0301E'; ctx.fillText(t,tx,y+r*0.4);
|
||||
}
|
||||
return cv.toDataURL('image/webp',0.9);
|
||||
}
|
||||
// Moves one sheet's progress bar in place: repainting the whole list and the
|
||||
// preview on every step made "Sua folha" flicker while a large file was read.
|
||||
function pintaProgressoFolha(x){
|
||||
@@ -376,22 +439,40 @@ function pintaProgressoFolha(x){
|
||||
}
|
||||
// What the check found, as chips: ok (verde), av (atenção), er (resolva você),
|
||||
// fix (arrumamos de graça), nt (a equipe confere). Details stay one click away.
|
||||
function chipsDaFolha(a){
|
||||
function chipsDaFolha(a,aceito){
|
||||
const chip=(k,t)=>'<li class="chip '+k+'">'+t+'</li>';
|
||||
const dpi = a.vetor ? chip('ok','Arte vetorial')
|
||||
: chip(a.dpi>=DPI_AVISA?'ok':a.dpi>=DPI_RECUSA?'av':'er', a.dpi+' DPI');
|
||||
if(a.grande) return dpi+chip('nt','Peças, resíduos e fundo: a equipe confere');
|
||||
return dpi+
|
||||
(a.fundoChapado? chip('er','Fundo chapado') : chip('ok','Fundo transparente'))+
|
||||
(a.residuos? chip('er',a.residuos+' resíduo'+(a.residuos>1?'s':'')) : chip('ok','Sem resíduos'))+
|
||||
// Sem transparência a folha inteira é uma peça só: não há resíduo a contar.
|
||||
if(a.fundoChapado) return dpi+chip('er','Fundo chapado');
|
||||
return dpi+chip('ok','Fundo transparente')+
|
||||
(a.residuos? chip(aceito?'av':'er',a.residuos+' resíduo'+(a.residuos>1?'s':'')+(aceito?' aceito'+(a.residuos>1?'s':''):''))
|
||||
: chip('ok','Sem resíduos'))+
|
||||
(a.encostadas? chip('fix',a.encostadas+' peças coladas · separamos grátis') : chip('ok','Peças separadas'));
|
||||
}
|
||||
function avisosDaFolha(a){
|
||||
// Resíduo e fundo chapado barram o pedido (Dropstar, 21/10/2026): o texto diz
|
||||
// quantos pontos, onde estão e o que fazer, sem "arquivo com problema". O
|
||||
// resíduo o cliente pode aceitar imprimir (29/10/2026); marcado, o aviso sai
|
||||
// e fica só o aceite.
|
||||
function avisosDaFolha(a,nome,i,aceito){
|
||||
if(a.grande) return '';
|
||||
return (a.fundoChapado? '<p class="avisoF"><b>O fundo não é transparente.</b> '+
|
||||
'Branco parecendo transparente sai branco no filme. Exporte com fundo transparente.</p>' : '')+
|
||||
(a.residuos? '<p class="avisoF"><b>'+a.residuos+' pontinho'+(a.residuos>1?'s soltos serão impressos':' solto será impresso')+
|
||||
'.</b> A impressora imprime qualquer resíduo de recorte. Apague no arquivo e envie de novo.</p>' : '');
|
||||
if(a.fundoChapado) return /\.jpe?g$/i.test(nome||'')
|
||||
? '<p class="avisoF"><b>JPG não tem fundo transparente.</b> O que parece branco na tela sai branco '+
|
||||
'no filme. Exporte a folha em PNG ou PDF, com fundo transparente, e envie de novo.</p>'
|
||||
: '<p class="avisoF"><b>O fundo da sua folha não é transparente.</b> O que parece branco na tela sai '+
|
||||
'branco no filme. Exporte a folha com fundo transparente, em PNG ou PDF, e envie de novo.</p>';
|
||||
if(!a.residuos) return '';
|
||||
const n=a.residuos, varios=n>1;
|
||||
const aceite='<label class="aceiteRes"><input type="checkbox" data-residuo="'+i+'"'+(aceito?' checked':'')+'>'+
|
||||
'<span>Esta arte tem '+n+(varios?' pontos menores':' ponto menor')+' que 2 mm. Estou ciente e aceito '+
|
||||
'imprimir assim — '+(varios?'eles podem':'ele pode')+' se perder no recorte.</span></label>';
|
||||
if(aceito) return aceite;
|
||||
return '<p class="avisoF"><b>'+(varios?'Sobraram ':'Sobrou ')+n+(varios?' pontos':' ponto')+
|
||||
' de recorte na sua folha.</b> São restos da remoção de fundo: não aparecem na sua tela, mas a '+
|
||||
'impressora enxerga e imprime. Apague '+(varios?'os pontos':'o ponto')+' na ferramenta que você '+
|
||||
'usou e envie de novo. '+(varios?'Os círculos vermelhos na prévia mostram onde estão.':'O círculo vermelho na prévia mostra onde está.')+
|
||||
' Se '+(varios?'os pontos são':'o ponto é')+' da própria arte, marque abaixo.</p>'+aceite;
|
||||
}
|
||||
function detalhesDaFolha(a,i,aberto){
|
||||
const linhas = a.grande
|
||||
@@ -411,7 +492,7 @@ function pintaFolha(){
|
||||
const L=larguraFilme();
|
||||
pintaTipoEnvio(); // trava o seletor enquanto houver folha
|
||||
$('zona').classList.toggle('compacta', folhas.length>0);
|
||||
if(!folhas.length){ $('lista').innerHTML=''; agendaAvaliacao(); previaAoVivo(); return; }
|
||||
if(!folhas.length){ $('lista').innerHTML=''; agendaAvaliacao(); previaAoVivo(); agendaEnvios(); return; }
|
||||
|
||||
const tot=folhaTotalM();
|
||||
$('lista').innerHTML = '<div class="listaCab"><h4>Seus arquivos</h4><span>'+
|
||||
@@ -423,7 +504,15 @@ function pintaFolha(){
|
||||
if(lido){
|
||||
medida='<div class="repMed"><b>'+n1(x.med.larg)+' × '+n1(x.med.alt)+' cm</b>'+
|
||||
'<span>'+escapeHTML(extDe(x.f.name))+' · '+fmt(x.f.size)+'</span></div>'+
|
||||
(a? '<ul class="chips">'+chipsDaFolha(a)+'</ul>'+avisosDaFolha(a)+detalhesDaFolha(a,i,x.detAberto) : '')+
|
||||
(a? '<ul class="chips">'+chipsDaFolha(a,residuoAceito(x))+'</ul>'+avisosDaFolha(a,x.f.name,i,residuoAceito(x))+
|
||||
detalhesDaFolha(a,i,x.detAberto) : '')+
|
||||
// Over 150 MB the browser cannot check a PDF: said before payment, as
|
||||
// for a file opened by hand (Dropstar, 2026-10-23).
|
||||
(x.pdfGrande? '<span class="chipSo">Conferência manual · sem conferência no site</span>'+
|
||||
'<p class="repTxt">Este PDF tem mais de 150 MB, e o site não confere arquivo desse tamanho: '+
|
||||
'resíduo de recorte, fundo e resolução ficam para a equipe, que abre antes de imprimir, e o '+
|
||||
'pedido pode voltar depois de pago. '+
|
||||
'Exportando em <b>PNG</b>, ou num PDF menor, a conferência sai aqui, antes de pagar.</p>' : '')+
|
||||
(suspeito? '<p class="avisoF"><b>Este PDF passa do tamanho que o formato comporta.</b> '+
|
||||
'A especificação para em 508 cm e o seu tem '+n1(x.med.alt)+' cm. '+
|
||||
'Ele abre certo só em quem o gerou — aqui vai precisar de tratamento. '+
|
||||
@@ -438,14 +527,16 @@ function pintaFolha(){
|
||||
medida='<span class="repPeso">'+escapeHTML(extDe(x.f.name))+' · '+fmt(x.f.size)+'</span>'+
|
||||
'<p class="avisoF"><b>Este PDF não pode ser orçado.</b> '+escapeHTML(x.measurementError)+'</p>';
|
||||
}else{
|
||||
const teto=TABELA[modo], piso=pisoEscada();
|
||||
const dif=(x.m>0)? (teto+TAXA_MANUAL-piso)*cobrar(x.m*(x.rep||1)) : 0;
|
||||
medida='<span class="chipSo">Conferência manual · preço cheio</span>'+
|
||||
// Só a abertura manual muda o metro (TAXA_MANUAL); a nota não mexe no preço.
|
||||
const dif=(x.m>0)? TAXA_MANUAL*cobrar(x.m*(x.rep||1)) : 0;
|
||||
medida='<span class="chipSo">Conferência manual</span>'+
|
||||
'<p class="repTxt">O navegador não abre '+escapeHTML(extDe(x.f.name))+', então alguém da equipe '+
|
||||
'confere antes de imprimir e o metro sai pela tabela, <b>'+rs(teto)+'</b>'+
|
||||
(TAXA_MANUAL? ', mais <b>'+rs(TAXA_MANUAL)+'</b> pela abertura manual' : '')+'. '+
|
||||
'Exportando em <b>PNG ou PDF</b>, o metro pode cair até <b>'+rs(piso)+'</b>'+
|
||||
(dif>0.5? ' — <b>'+rs(dif)+' a menos</b> só nesta folha' : '')+'.</p>';
|
||||
'confere antes de imprimir'+
|
||||
(TAXA_MANUAL? ' e o metro sai a <b>'+rs(precoMetro()+TAXA_MANUAL)+'</b>, com <b>'+rs(TAXA_MANUAL)+
|
||||
'</b> pela abertura manual' : '')+'. '+
|
||||
'Exportando em <b>PNG ou PDF</b>, a conferência sai aqui, antes de pagar'+
|
||||
(TAXA_MANUAL? ', e o metro fica em <b>'+rs(precoMetro())+'</b>'+
|
||||
(dif>0.5? ' — <b>'+rs(dif)+' a menos</b> só nesta folha' : '') : '')+'.</p>';
|
||||
manual='<div class="campo"><label for="comp'+i+'">Comprimento</label>'+
|
||||
'<span class="un"><input type="number" id="comp'+i+'" min="0.5" max="60" step="0.01" data-comp="'+i+'" '+
|
||||
'placeholder="0,00" value="'+(x.m? x.m.toFixed(2):'')+'"><i>m</i></span></div>';
|
||||
@@ -455,7 +546,7 @@ function pintaFolha(){
|
||||
'<span class="progT">'+textoProgresso(x)+'</span>'
|
||||
: x.semAnalise
|
||||
? '<div class="progF"><b>Não conseguimos conferir esta folha.</b> '+escapeHTML(x.semAnalise)+
|
||||
'. Seguimos com o preço de tabela — se quiser a nota e o desconto, exporte a mesma '+
|
||||
'. Seguimos sem a nota, e a conferência é feita na mão. Se quiser a nota, exporte a mesma '+
|
||||
'folha em <b>PNG</b>, que a conferência é bem mais leve.</div>'
|
||||
: '';
|
||||
// A small thumbnail made once: the list is rebuilt on every change, and the
|
||||
@@ -485,6 +576,9 @@ function pintaFolha(){
|
||||
$('lista').querySelectorAll('[data-rmf]').forEach(b=>b.addEventListener('click',()=>{
|
||||
folhas.splice(+b.dataset.rmf,1); pintaFolha();
|
||||
}));
|
||||
$('lista').querySelectorAll('[data-residuo]').forEach(el=>el.addEventListener('change',()=>{
|
||||
folhas[+el.dataset.residuo].residuoAceito=el.checked; pintaFolha();
|
||||
}));
|
||||
$('lista').querySelectorAll('[data-det]').forEach(d=>d.addEventListener('toggle',()=>{
|
||||
folhas[+d.dataset.det].detAberto=d.open;
|
||||
}));
|
||||
@@ -501,7 +595,7 @@ function pintaFolha(){
|
||||
}));
|
||||
$('lista').querySelectorAll('[data-repf], [data-comp]').forEach(el=>
|
||||
el.addEventListener('input',invalidaItemAtual));
|
||||
agendaAvaliacao(); previaAoVivo();
|
||||
agendaAvaliacao(); previaAoVivo(); agendaEnvios();
|
||||
}
|
||||
|
||||
// sugestão de largura
|
||||
@@ -529,10 +623,14 @@ function pintaProgressoArte(a){
|
||||
if(!barra){ pintaArtes(); return; }
|
||||
barra.style.width=a.lendo+'%'; if(texto) texto.textContent='arquivo grande · gerando a prévia · '+faltaLeitura(a.leitura);
|
||||
}
|
||||
// O transfer têxtil é prensado com o filme virado para baixo: espelhado, sai
|
||||
// invertido na peça. Só o UV espelha, até a Dropstar decidir (21/10/2026).
|
||||
const espelhavel=()=>modo==='uv';
|
||||
function pintaArtes(){
|
||||
// A file still being read when the customer left the product page lands
|
||||
// here with no product open: nothing to paint.
|
||||
if(!MODOS[modo]) return;
|
||||
if(!espelhavel()) artes.forEach(a=>{ a.esp=false; });
|
||||
invalidaItemAtual();
|
||||
$('zona').classList.toggle('compacta', artes.length>0);
|
||||
// The same card as a finished sheet: thumbnail, size, a DPI chip, then the
|
||||
@@ -546,7 +644,7 @@ function pintaArtes(){
|
||||
barra='<div class="prog"><i style="width:'+a.lendo+'%"></i></div>'+
|
||||
'<span class="progT">arquivo grande · gerando a prévia · '+faltaLeitura(a.leitura)+'</span>';
|
||||
}else if(a.decodeError){
|
||||
aviso='<p class="avisoF"><b>Não conseguimos ler esta imagem.</b> Exporte novamente em PNG ou JPG.</p>';
|
||||
aviso='<p class="avisoF"><b>Não conseguimos ler esta imagem.</b> Exporte novamente em PNG.</p>';
|
||||
}else if(a.cm>larguraFilme()){
|
||||
aviso='<p class="avisoF"><b>Largura maior que o filme.</b> O filme aqui tem '+n1(larguraFilme())+' cm.</p>';
|
||||
}else if(a.cm>0 && (a.src||a.semPrevia)){
|
||||
@@ -589,7 +687,7 @@ function pintaArtes(){
|
||||
'<button type="button" data-passoa="1" data-i="'+i+'" aria-label="Mais uma cópia">+</button></span></div>'+
|
||||
'<span class="giros">'+
|
||||
'<button class="gr'+(a.giro?' on':'')+'" data-giro="'+i+'" title="Girar 90°" aria-label="Girar 90°">'+icone('girar')+'</button>'+
|
||||
'<button class="gr'+(a.esp?' on':'')+'" data-esp="'+i+'" title="Espelhar" aria-label="Espelhar">'+icone('espelhar')+'</button></span>'+
|
||||
(espelhavel() ? '<button class="gr'+(a.esp?' on':'')+'" data-esp="'+i+'" title="Espelhar" aria-label="Espelhar">'+icone('espelhar')+'</button>' : '')+'</span>'+
|
||||
(sub? '<div class="conta">'+sub+'</div>' : '')+
|
||||
'<div class="atalhos">'+(TAMANHOS[larguraFilme()]||[]).map(t=>'<button class="tm'+
|
||||
(Math.abs(a.cm-t)<0.05?' on':'')+'" data-tam="'+i+'" data-t="'+t+'">'+n1(t)+' cm</button>').join('')+'</div>'+
|
||||
@@ -624,7 +722,7 @@ function pintaArtes(){
|
||||
const a=artes[+b.dataset.esp]; a.esp=!a.esp; pintaArtes();
|
||||
}));
|
||||
resumoArtes();
|
||||
previaAoVivo();
|
||||
previaAoVivo(); agendaEnvios();
|
||||
}
|
||||
function resumoArtes(){
|
||||
const r=$('rA'), prontas=artes.filter(a=>a.cm>0 && a.cm<=larguraFilme() && (a.src||a.semPrevia));
|
||||
|
||||
@@ -3,6 +3,14 @@
|
||||
Loaded as classic scripts in the order listed there: they share one global
|
||||
scope and run top to bottom, exactly as the original did. */
|
||||
// ── enviar
|
||||
// Folha que a impressora estragaria: com resíduo de recorte ou sem fundo
|
||||
// transparente. Só vale para o que o navegador conferiu. O resíduo que o
|
||||
// cliente aceita imprimir (Dropstar, 29/10/2026: às vezes os pontos são da
|
||||
// arte) não barra; o fundo chapado barra sempre.
|
||||
const residuoAceito=x=>!!(x.residuoAceito && x.an && x.an.residuos);
|
||||
const folhaBarrada=x=>!!(x.an && !x.an.grande && (x.an.fundoChapado || (x.an.residuos && !residuoAceito(x))));
|
||||
// Quantos pontos o cliente aceitou imprimir, somadas as folhas: vai no item.
|
||||
const residuosAceitos=()=>folhas.filter(residuoAceito).reduce((t,x)=>t+x.an.residuos,0);
|
||||
// Avalia sozinho conforme o cliente sobe e preenche. Devolve o que ainda falta,
|
||||
// para a fila dizer em texto em vez de travar num botão.
|
||||
function avaliar(){
|
||||
@@ -16,22 +24,29 @@ function avaliar(){
|
||||
const semMedida=folhas.filter(x=>!(x.m>0)).length;
|
||||
if(semMedida) return {pronto:false, falta:'Informe o comprimento de '+semMedida+
|
||||
' folha'+(semMedida>1?'s':'')+'.'};
|
||||
// Resíduo e fundo chapado barram antes do pagamento, com um ponto só
|
||||
// (Dropstar, 21/10/2026): então o pedido espera a conferência terminar.
|
||||
const lendo=folhas.find(x=>x.pct!=null);
|
||||
if(lendo) return {pronto:false, falta:'Conferindo '+lendo.f.name+'…'};
|
||||
const barrada=folhas.find(folhaBarrada);
|
||||
if(barrada) return {pronto:false, falta:barrada.an.fundoChapado
|
||||
? barrada.f.name+' está sem fundo transparente. Exporte a folha com fundo transparente, em PNG ou PDF, e envie de novo.'
|
||||
: barrada.f.name+' tem '+barrada.an.residuos+' ponto'+(barrada.an.residuos>1?'s':'')+
|
||||
' de recorte. Apague e envie de novo, ou marque que aceita imprimir assim.'};
|
||||
metros=folhaTotalM();
|
||||
reencaixado=false;
|
||||
const ans=folhas.map(x=>x.an).filter(Boolean);
|
||||
if(ans.length!==folhas.length){
|
||||
// A nota precisa cobrir cada folha faturada. Uma folha sem análise não
|
||||
// herda a nota/desconto de outra folha que o navegador conseguiu abrir.
|
||||
// A nota precisa cobrir cada folha. Uma folha sem análise não herda a
|
||||
// nota de outra folha que o navegador conseguiu abrir.
|
||||
const ausentes=folhas.filter(f=>!f.an);
|
||||
const exts=[...new Set(ausentes.map(f=>extDe(f.f.name)))].join(', ');
|
||||
mostraNota([
|
||||
['av','Sem nota · '+exts+' sem análise completa',
|
||||
ausentes.length+' de '+folhas.length+' folha(s) precisam de conferência manual'],
|
||||
['er','Metro pela tabela · '+rs(TABELA[modo]),
|
||||
'exportando em PNG ou PDF, cai até '+rs(pisoEscada())],
|
||||
['fix','Alguém abre seu arquivo','a conferência é feita na mão, na sala']
|
||||
], 0, folhas.length>1? folhas.length+' folhas' : folhas[0].f.name,
|
||||
larguraFilme()+' cm · '+fmtM(metros)+' m · preço de tabela');
|
||||
larguraFilme()+' cm · '+fmtM(metros)+' m');
|
||||
return {pronto:true};
|
||||
}
|
||||
const dpi=Math.min(...ans.map(a=>a.dpi));
|
||||
@@ -48,8 +63,8 @@ function avaliar(){
|
||||
ans.some(a=>a.grande) ? ['ok','Arquivo grande','peças, resíduos e fundo conferidos pela equipe'] : null,
|
||||
ans.some(a=>a.grande) ? null : ['ok', soma('artes')+' peças na folha',
|
||||
Math.round(soma('aproveitamento')/ans.length)+'% da folha virou arte'],
|
||||
ans.some(a=>a.grande) ? null : soma('residuos') ? ['er','Resíduo de recorte',
|
||||
soma('residuos')+' ponto'+(soma('residuos')>1?'s':'')+' abaixo de 2 mm · a impressora imprime']
|
||||
ans.some(a=>a.grande) ? null : soma('residuos') ? ['av','Resíduo aceito',
|
||||
soma('residuos')+' ponto'+(soma('residuos')>1?'s':'')+' abaixo de 2 mm · você aceitou imprimir assim']
|
||||
: ['ok','Sem resíduo de recorte','nada solto na folha'],
|
||||
ans.some(a=>a.grande) ? null : soma('encostadas') ? ['fix', soma('encostadas')+' peças a menos de 5 mm',
|
||||
'se forem artes diferentes, separamos com 5 mm sem custo']
|
||||
@@ -65,7 +80,7 @@ function avaliar(){
|
||||
if(!artes.length) return {pronto:false, falta:'Arraste suas artes para começar.'};
|
||||
if(artes.some(a=>a.lendo!=null)) return {pronto:false, falta:'Gerando a prévia das artes grandes…'};
|
||||
if(artes.some(a=>a.decodeError || !(a.src||a.semPrevia) || !(a.px>0) || !(a.py>0)))
|
||||
return {pronto:false, falta:'Não conseguimos ler uma das imagens. Exporte-a novamente em PNG ou JPG antes de continuar.'};
|
||||
return {pronto:false, falta:'Não conseguimos ler uma das imagens. Exporte-a novamente em PNG antes de continuar.'};
|
||||
if(artes.some(a=>!Number.isFinite(a.cm) || a.cm>larguraFilme()))
|
||||
return {pronto:false, falta:'A largura da arte precisa caber no filme de '+
|
||||
n1(larguraFilme())+' cm. Reduza a medida solicitada antes de continuar.'};
|
||||
@@ -79,7 +94,7 @@ function avaliar(){
|
||||
const media=Math.round(notas.reduce((s,n)=>s+n,0)/notas.length), pior=Math.min(...notas);
|
||||
mostraNota([
|
||||
['ok','Montagem por nossa conta','5 mm garantidos'],
|
||||
[cls(pior),'Pior arte em '+pior+'%',pior>=85?'todas em boa resolução':'reenviar maior sai mais barato']
|
||||
[cls(pior),'Pior arte em '+pior+'%',pior>=85?'todas em boa resolução':'há arte abaixo da resolução ideal']
|
||||
],media,artes.length+' arte'+(artes.length>1?'s':''),
|
||||
'folha montada por nós · '+fmtM(metros)+' m');
|
||||
return {pronto:true};
|
||||
@@ -130,7 +145,7 @@ function ressalvaResolucao(){
|
||||
const box=$('ciente'), chk=$('cienteOk');
|
||||
let baixas=[], geral=300, recusadas=[];
|
||||
if(ehFolha()){
|
||||
// Uma régua só: o número que precifica é o número que bloqueia.
|
||||
// Uma régua só: o número da nota é o número que bloqueia.
|
||||
// Recusa quando a média por área fica abaixo de 96 DPI — a folha inteira não
|
||||
// vale o filme. Se a média passa mas há peças ruins, é ressalva com aceite.
|
||||
folhas.forEach((x,k)=>{
|
||||
@@ -154,7 +169,7 @@ function ressalvaResolucao(){
|
||||
const todas=comTamanho.map(a=>dpiDe(a));
|
||||
geral = todas.length? Math.round(Math.max(...todas)) : 300;
|
||||
}
|
||||
// Abaixo de 96 DPI a sala não imprime. Não é desconto, é recusa —
|
||||
// Abaixo de 96 DPI a sala não imprime. Não é ressalva, é recusa —
|
||||
// e não existe aceite que destrave.
|
||||
if(recusadas.length){
|
||||
$('cienteTxt').innerHTML=
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
Loaded as classic scripts in the order listed there: they share one global
|
||||
scope and run top to bottom, exactly as the original did. */
|
||||
// ── Análise real da folha: lê o canal alfa, separa cada ilha de arte e mede.
|
||||
// Grade de 1 mm. Só roda em arquivo que o navegador abre; PDF precisa do servidor.
|
||||
// A grade de 1 mm agrupa a tinta; a medida de cada ilha sai dos pixels.
|
||||
const MM=0.1; // grade fina: 1 mm
|
||||
const CELULAS_MAX=1200000; // teto de custo da análise
|
||||
// Folha grande vira grade mais grossa. Sem isso, 57 x 480 cm dá 2,7 milhões de
|
||||
@@ -46,39 +46,77 @@ function grupos(bits,cw,ch){
|
||||
return {marca,n};
|
||||
}
|
||||
|
||||
// ── Mapa de tinta: cada pixel da folha lido, nenhum pulado.
|
||||
// Regra da Dropstar (21/10/2026): resíduo é uma ilha de tinta menor que 2 mm
|
||||
// nos dois lados, e um ponto só já barra o pedido. Reduzir a imagem antes de
|
||||
// olhar perde ponto pequeno, e medir pela grade erra até uma célula: o mesmo
|
||||
// ponto de 1,5 mm saía resíduo ou arte conforme caía na grade. Aqui a grade só
|
||||
// agrupa; cada célula guarda onde a tinta começa e termina, em pixels, e cada
|
||||
// ilha é medida por esses extremos, em milímetros reais.
|
||||
const ALFA_TINTA=10; // acima disto o pixel leva tinta (e branco de base)
|
||||
function novoMapa(wPx,hPx,larguraCm){
|
||||
const pxPorCm=wPx/larguraCm, passo=passoDe(larguraCm,hPx/pxPorCm), pxCel=passo*pxPorCm;
|
||||
const cw=Math.max(1,Math.ceil(wPx/pxCel)), ch=Math.max(1,Math.ceil(hPx/pxCel)), n=cw*ch;
|
||||
const colDe=new Uint32Array(wPx);
|
||||
for(let x=0;x<wPx;x++) colDe[x]=Math.min(cw-1,Math.floor(x/pxCel));
|
||||
return {wPx,hPx,larguraCm,pxPorCm,passo,pxCel,cw,ch,colDe,bits:new Uint8Array(n),
|
||||
x0:new Uint32Array(n),x1:new Uint32Array(n),y0:new Uint32Array(n),y1:new Uint32Array(n),tinta:0};
|
||||
}
|
||||
// A linha y da folha: o alfa de cada pixel em alfa[inicio + x*de].
|
||||
function mapaLinha(m,y,alfa,inicio,de){
|
||||
const base=Math.min(m.ch-1,Math.floor(y/m.pxCel))*m.cw;
|
||||
const {bits,x0,x1,y0,y1,colDe}=m;
|
||||
let tinta=0;
|
||||
for(let x=0,i=inicio;x<m.wPx;x++,i+=de){
|
||||
if(alfa[i]<=ALFA_TINTA) continue;
|
||||
tinta++;
|
||||
const c=base+colDe[x];
|
||||
if(!bits[c]){ bits[c]=1; x0[c]=x1[c]=x; y0[c]=y1[c]=y; }
|
||||
else{ if(x<x0[c]) x0[c]=x; else if(x>x1[c]) x1[c]=x; y1[c]=y; }
|
||||
}
|
||||
m.tinta+=tinta;
|
||||
}
|
||||
// Uma imagem que o navegador abre, lida em faixas no tamanho real (1:1).
|
||||
// Melhor um ImageBitmap: decodificado uma vez, não a cada faixa.
|
||||
async function mapaDaImagem(img,larguraCm,progresso){
|
||||
const w=img.naturalWidth||img.width, h=img.naturalHeight||img.height;
|
||||
const m=novoMapa(w,h,larguraCm);
|
||||
const faixa=Math.max(1,Math.min(h,Math.floor(4e6/w)));
|
||||
const cv=document.createElement('canvas'); cv.width=w; cv.height=faixa;
|
||||
const ctx=cv.getContext('2d',{willReadFrequently:true});
|
||||
ctx.imageSmoothingEnabled=false;
|
||||
for(let topo=0;topo<h;topo+=faixa){
|
||||
const n=Math.min(faixa,h-topo);
|
||||
ctx.clearRect(0,0,w,faixa);
|
||||
ctx.drawImage(img,0,topo,w,n,0,0,w,n);
|
||||
const d=ctx.getImageData(0,0,w,n).data;
|
||||
for(let r=0;r<n;r++) mapaLinha(m,topo+r,d,r*w*4+3,4);
|
||||
if(progresso) progresso((topo+n)/h);
|
||||
await new Promise(r=>setTimeout(r)); // a página não congela
|
||||
}
|
||||
return m;
|
||||
}
|
||||
|
||||
// ── O que a folha permite medir, e só isso.
|
||||
// Peça = pixels a menos de 2 mm entre si · letras de uma palavra ficam juntas.
|
||||
// Peça = tinta a menos de 2 mm entre si · letras de uma palavra ficam juntas.
|
||||
// Encostadas = peças que só se unem quando a folga chega a 6 mm.
|
||||
const R_PECA=1, R_PERTO=2; // peça: 2 mm · aviso de encostadas: 4 mm
|
||||
function analisarFolha(img, larguraCm){
|
||||
const alturaCmEst=larguraCm*img.height/img.width;
|
||||
const passo=passoDe(larguraCm, alturaCmEst);
|
||||
const cw=Math.max(8,Math.round(larguraCm/passo));
|
||||
const ch=Math.max(8,Math.round(cw*img.height/img.width));
|
||||
const cv=document.createElement('canvas'); cv.width=cw; cv.height=ch;
|
||||
const ctx=cv.getContext('2d',{willReadFrequently:true});
|
||||
ctx.clearRect(0,0,cw,ch); ctx.drawImage(img,0,0,cw,ch);
|
||||
const d=ctx.getImageData(0,0,cw,ch).data;
|
||||
|
||||
const bits=new Uint8Array(cw*ch);
|
||||
let opacos=0;
|
||||
for(let i=0,j=3;i<bits.length;i++,j+=4) if(d[j]>10){ bits[i]=1; opacos++; }
|
||||
|
||||
// peças: agrupa pela distância real entre pixels
|
||||
const RESIDUO_MM=2;
|
||||
function analisarMapa(m){
|
||||
const {cw,ch,bits}=m;
|
||||
const gp=grupos(inchar(bits,cw,ch,R_PECA), cw, ch);
|
||||
const caixas=[];
|
||||
for(let p=0;p<bits.length;p++){
|
||||
if(!bits[p]) continue;
|
||||
const id=gp.marca[p]; if(id<0) continue;
|
||||
const x=p%cw, y=(p/cw)|0;
|
||||
const c=caixas[id] || (caixas[id]={x0:x,x1:x,y0:y,y1:y,area:0,id});
|
||||
if(x<c.x0)c.x0=x; if(x>c.x1)c.x1=x; if(y<c.y0)c.y0=y; if(y>c.y1)c.y1=y;
|
||||
c.area++;
|
||||
const c=caixas[id] || (caixas[id]={x0:m.x0[p],x1:m.x1[p],y0:m.y0[p],y1:m.y1[p],id});
|
||||
if(m.x0[p]<c.x0)c.x0=m.x0[p]; if(m.x1[p]>c.x1)c.x1=m.x1[p];
|
||||
if(m.y0[p]<c.y0)c.y0=m.y0[p]; if(m.y1[p]>c.y1)c.y1=m.y1[p];
|
||||
}
|
||||
const pecasTodas=caixas.filter(Boolean);
|
||||
const limRes=Math.max(1, Math.round(0.2/passo)); // 2 mm na grade em uso
|
||||
const residuos=pecasTodas.filter(o=>(o.x1-o.x0)<limRes && (o.y1-o.y0)<limRes);
|
||||
const artes=pecasTodas.filter(o=>!((o.x1-o.x0)<limRes && (o.y1-o.y0)<limRes));
|
||||
const mm=px=>px/m.pxPorCm*10;
|
||||
const ilhas=caixas.filter(Boolean).map(c=>({...c, wMm:mm(c.x1-c.x0+1), hMm:mm(c.y1-c.y0+1)}));
|
||||
const residuos=ilhas.filter(c=>c.wMm<RESIDUO_MM && c.hMm<RESIDUO_MM);
|
||||
const deResiduo=new Set(residuos.map(c=>c.id));
|
||||
|
||||
// encostadas: peças diferentes que se unem quando a folga chega a 6 mm
|
||||
const gper=grupos(inchar(bits,cw,ch,R_PERTO), cw, ch);
|
||||
@@ -86,22 +124,27 @@ function analisarFolha(img, larguraCm){
|
||||
for(let p=0;p<bits.length;p++){
|
||||
if(!bits[p]) continue;
|
||||
const a=gp.marca[p], b=gper.marca[p];
|
||||
if(a<0||b<0) continue;
|
||||
if(a<0||b<0||deResiduo.has(a)) continue;
|
||||
if(!porPerto.has(b)) porPerto.set(b,new Set());
|
||||
porPerto.get(b).add(a);
|
||||
}
|
||||
let encostadas=0;
|
||||
porPerto.forEach(set=>{ if(set.size>1) encostadas+=set.size; });
|
||||
|
||||
const total=m.wPx*m.hPx;
|
||||
return {
|
||||
dpi: Math.round(img.width/(larguraCm/2.54)),
|
||||
artes: artes.length,
|
||||
dpi: Math.round(m.wPx/(m.larguraCm/2.54)),
|
||||
artes: ilhas.length-residuos.length,
|
||||
residuos: residuos.length,
|
||||
// Onde está cada ponto, em fração da folha: os círculos da prévia.
|
||||
pontos: residuos.map(c=>({x:(c.x0+c.x1+1)/2/m.wPx, y:(c.y0+c.y1+1)/2/m.hPx,
|
||||
mm:+Math.max(c.wMm,c.hMm).toFixed(1)})),
|
||||
encostadas,
|
||||
fundoChapado: opacos/(cw*ch) > 0.985,
|
||||
aproveitamento: Math.max(1,Math.min(100,Math.round(opacos/(cw*ch)*100))),
|
||||
alturaCm: ch*passo,
|
||||
grade: +(passo*10).toFixed(1) // mm por célula analisada
|
||||
// Sem transparência: o que parece branco na tela sai branco no filme.
|
||||
fundoChapado: (total-m.tinta)/total < 0.015,
|
||||
aproveitamento: Math.max(1,Math.min(100,Math.round(m.tinta/total*100))),
|
||||
alturaCm: m.hPx/m.pxPorCm,
|
||||
grade: +(m.passo*10).toFixed(1) // mm por célula que agrupa
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -3,9 +3,9 @@
|
||||
switches which page is shown and reads the page's state (the open product,
|
||||
the cart, the checkout status); orders, prices and files stay with the other
|
||||
site-*.js files. */
|
||||
// Card prices come from the same table the checkout uses, so they cannot drift.
|
||||
document.querySelectorAll('[data-de]').forEach(el=>{ el.textContent=rs(pisoEscada(el.dataset.de)); });
|
||||
document.querySelectorAll('[data-ate]').forEach(el=>{ el.textContent=rs(TABELA[el.dataset.ate]); });
|
||||
// Every price on the page (top chip, home example, product cards, price table)
|
||||
// comes from the same table the checkout uses, so they cannot drift.
|
||||
document.querySelectorAll('[data-preco]').forEach(el=>{ el.textContent=rs(PRECO[el.dataset.preco]); });
|
||||
|
||||
const TITULO_INICIO=document.title;
|
||||
function tituloPagina(){
|
||||
|
||||
@@ -7,15 +7,45 @@
|
||||
function escapeHTML(value){
|
||||
return String(value).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
||||
}
|
||||
// Dropstar's rule D-13 (2026-10-26): what a file is comes from its first bytes,
|
||||
// never from its name. A ".cdr" that is a PDF is renamed ".pdf" and checked as
|
||||
// a PDF, without the manual charge; a JPG called ".png" is refused as a JPG.
|
||||
// A name its content agrees with stays, so an Illustrator file, a PDF inside,
|
||||
// is still ".ai". The same signatures as the server (app/scanning.py).
|
||||
const TIFF_INICIOS=['II*\0','MM\0*','II+\0','MM\0+'];
|
||||
const INICIOS={png:['\x89PNG\r\n\x1a\n'], jpg:['\xff\xd8\xff'], jpeg:['\xff\xd8\xff'],
|
||||
tif:TIFF_INICIOS, tiff:TIFF_INICIOS, pdf:['%PDF-'], ai:['%PDF-','%!PS'], psd:['8BPS'], psb:['8BPS']};
|
||||
const RIFF_TIPOS={cdr:/^RIFF[\s\S]{4}CDR/, webp:/^RIFF[\s\S]{4}WEBP/};
|
||||
const confere=(ext,ini)=>RIFF_TIPOS[ext] ? RIFF_TIPOS[ext].test(ini) : (INICIOS[ext]||[]).some(a=>ini.startsWith(a));
|
||||
const formatoDe=ini=>['pdf','png','jpg','tif','psd','cdr','webp'].find(e=>confere(e,ini))||null;
|
||||
async function nomeReal(f){
|
||||
let ini;
|
||||
try{ ini=String.fromCharCode(...new Uint8Array(await f.slice(0,16).arrayBuffer())); }
|
||||
catch(e){ return f; }
|
||||
const real=formatoDe(ini);
|
||||
if(!real || confere(extDe(f.name).toLowerCase(),ini)) return f;
|
||||
const ponto=f.name.lastIndexOf('.');
|
||||
const g=new File([f], (ponto>0?f.name.slice(0,ponto):f.name)+'.'+real, {type:f.type, lastModified:f.lastModified});
|
||||
g.nomeEnviado=f.name;
|
||||
return g;
|
||||
}
|
||||
function recusa(lista){
|
||||
const el=$('recusa'); if(!el) return;
|
||||
if(!lista.length){ el.style.display='none'; el.innerHTML=''; return; }
|
||||
const exts=escapeHTML([...new Set(lista.map(f=>extDe(f.name)))].join(', '));
|
||||
el.style.display='block';
|
||||
if(lista.every(f=>/\.jpe?g$/i.test(f.name))){
|
||||
const disfarcados=lista.filter(f=>f.nomeEnviado).map(f=>f.nomeEnviado);
|
||||
el.innerHTML='<b>JPG não dá para enviar.</b> '+
|
||||
(disfarcados.length ? escapeHTML(disfarcados.join(', '))+' é JPG, mesmo com outro nome. ' : '')+
|
||||
'JPG não tem fundo transparente, e o branco do fundo '+
|
||||
'sai no filme. Exporte em '+(ehFolha()?'PNG ou PDF':'PNG')+' com fundo transparente e envie de novo.';
|
||||
return;
|
||||
}
|
||||
el.innerHTML = ehFolha()
|
||||
? '<b>'+exts+' não dá para enviar aqui.</b> A folha pronta aceita PNG, JPG, TIFF, '+
|
||||
'PDF, PSD, AI e CDR.'
|
||||
: '<b>'+exts+' não dá para enviar aqui.</b> Artes avulsas precisam de PNG ou JPG com '+
|
||||
? '<b>'+exts+' não dá para enviar aqui.</b> A folha pronta aceita PNG, PDF, TIFF, '+
|
||||
'PSD, AI e CDR, com fundo transparente.'
|
||||
: '<b>'+exts+' não dá para enviar aqui.</b> Artes avulsas precisam de PNG com '+
|
||||
'fundo transparente — é o que a montagem enxerga para encaixar. '+
|
||||
'Se o seu arquivo é CDR, AI ou PSD, exporte em PNG ou use <b>Arquivo por metro</b>.';
|
||||
}
|
||||
@@ -28,8 +58,49 @@ Z.addEventListener('keydown',e=>{if(e.key==='Enter'||e.key===' '){I.click();e.pr
|
||||
if(ev==='drop') sel([...e.dataTransfer.files]);
|
||||
}));
|
||||
I.addEventListener('change',()=>sel([...I.files]));
|
||||
function sel(fs){
|
||||
// Each file's upload, under the uploader (Dropstar, 2026-10-29): the bytes
|
||||
// sent of its size, then the security check; a failure says why. It starts
|
||||
// as soon as the file is on the page (checkout.js sends it).
|
||||
const ENVIADO_MS=4000;
|
||||
const enviadoEm=new WeakMap();
|
||||
// A few repaints a second, page in view or not: progress comes in far more often.
|
||||
let envioQuadro=0;
|
||||
function agendaEnvios(){ if(!envioQuadro) envioQuadro=setTimeout(()=>{ envioQuadro=0; pintaEnvios(); },120); }
|
||||
function pintaEnvios(){
|
||||
const el=$('envios'); if(!el || !window.dtfEnvio) return;
|
||||
dtfEnvio.manter([...artes,...folhas].map(x=>x.f));
|
||||
// Off the product page there is no uploader to paint under.
|
||||
if(!MODOS[modo]){ el.innerHTML=''; return; }
|
||||
const agora=Date.now();
|
||||
el.innerHTML=(ehFolha()?folhas:artes).map((x,i)=>{
|
||||
const f=x.f, e=dtfEnvio.estado(f), nome='<b>'+escapeHTML(f.name)+'</b>';
|
||||
if(!e) return '';
|
||||
if(e.fase==='pronto'){
|
||||
if(!enviadoEm.has(f)){ enviadoEm.set(f,agora); setTimeout(agendaEnvios,ENVIADO_MS+50); }
|
||||
return agora-enviadoEm.get(f)>ENVIADO_MS ? '' : '<div class="envio ok">'+icone('okCirculo')+'<span>'+nome+' enviado</span></div>';
|
||||
}
|
||||
if(e.fase==='falhou') return '<div class="envio erro"><span>Não foi possível enviar '+nome+': '+
|
||||
escapeHTML(e.erro.replace(/\.$/,''))+'.</span><button type="button" data-envio="'+i+'">Tentar de novo</button></div>';
|
||||
const pct=e.fase==='verificando' ? 100 : Math.floor(e.enviado/f.size*100);
|
||||
return '<div class="envio"><span>'+(e.fase==='verificando' ? 'Verificando a segurança de '+nome+'…'
|
||||
: 'Enviando '+nome+' · '+pct+'% · '+fmt(e.enviado)+' de '+fmt(f.size))+'</span>'+
|
||||
'<div class="envioBarra"><i style="width:'+pct+'%"></i></div></div>';
|
||||
}).join('');
|
||||
}
|
||||
addEventListener('dtf-envio',agendaEnvios);
|
||||
$('envios').addEventListener('click',e=>{
|
||||
const b=e.target.closest('[data-envio]'); if(!b || !MODOS[modo]) return;
|
||||
const x=(ehFolha()?folhas:artes)[+b.dataset.envio]; if(x) dtfEnvio.deNovo(x.f);
|
||||
});
|
||||
// A sheet with residue gets its preview circled where the dots are.
|
||||
async function marcaResiduos(x){
|
||||
if(!(x.an && x.an.residuos && !x.an.fundoChapado && x.previewSrc && x.an.pontos?.length)) return;
|
||||
const marcada=await previaMarcada(x.previewSrc, x.an.pontos);
|
||||
if(folhas.includes(x)){ x.previewSrc=marcada; pintaFolha(); }
|
||||
}
|
||||
async function sel(fs){
|
||||
if(!fs.length) return;
|
||||
fs=await Promise.all(fs.map(nomeReal));
|
||||
// Pixels cannot tell a loose artwork from a finished sheet, so the customer
|
||||
// declares it by choosing the product in the selector above. The declaration is
|
||||
// verified in medirFolha; the file never changes product or price on its own.
|
||||
@@ -37,7 +108,7 @@ function sel(fs){
|
||||
const fora = fs.filter(f=>!regra.test(f.name));
|
||||
fs = fs.filter(f=>regra.test(f.name));
|
||||
recusa(fora);
|
||||
const max=window.dtfUploadMaxBytes||1073741824;
|
||||
const max=window.dtfUploadMaxBytes||4294967296;
|
||||
const grandes=fs.filter(f=>f.size>max);
|
||||
if(grandes.length){
|
||||
const el=$('recusa');
|
||||
@@ -47,6 +118,8 @@ function sel(fs){
|
||||
fs=fs.filter(f=>f.size<=max);
|
||||
}
|
||||
if(!fs.length) return;
|
||||
// On their way at once; a JPG is refused at the order anyway.
|
||||
fs.filter(f=>!/\.jpe?g$/i.test(f.name)).forEach(f=>window.dtfEnvio?.enviar(f));
|
||||
if(ehFolha()){
|
||||
const novas=fs.map(f=>({f, med:null, rep:1, m:0, semAnalise:null}));
|
||||
folhas=folhas.concat(novas); // soma, não substitui
|
||||
@@ -64,6 +137,8 @@ function sel(fs){
|
||||
// stream into a small copy: the preview, and the sheet check.
|
||||
x.an={dpi:md.dpiFolha, grande:true, artes:0, residuos:0, encostadas:0,
|
||||
fundoChapado:false, aproveitamento:0, alturaCm:md.alt, fonteDpi:'arquivo'};
|
||||
// A JPG has no transparency: its background is always solid.
|
||||
if(/\.jpe?g$/i.test(x.f.name)){ x.an={...x.an, grande:false, fundoChapado:true, residuos:0, pontos:[]}; }
|
||||
if(!/\.png$/i.test(x.f.name)){ x.pct=null; pintaFolha(); return; }
|
||||
x.pct=60; x.leitura={inicio:Date.now(), p:0}; pintaFolha();
|
||||
let mostrado=0;
|
||||
@@ -71,36 +146,49 @@ function sel(fs){
|
||||
const pct=60+Math.floor(p*38);
|
||||
x.leitura.p=p;
|
||||
if(pct-mostrado>=1){ mostrado=pct; x.pct=pct; pintaProgressoFolha(x); }
|
||||
}).then(cv=>{
|
||||
if(cv && folhas.includes(x)){
|
||||
}, md.larg).then(lido=>{
|
||||
if(lido && folhas.includes(x)){
|
||||
const cv=lido.cv;
|
||||
x.previewSrc=cv.toDataURL('image/webp',0.85); x.miniSrc=miniatura(cv); x.fotoSrc=miniatura(cv,480,720);
|
||||
try{
|
||||
const an=analisarFolha(cv, md.larg);
|
||||
const an=analisarMapa(lido.mapa);
|
||||
x.an={...an, dpi:md.dpiFolha, fonteDpi:'arquivo', grande:false};
|
||||
}catch(e){}
|
||||
}
|
||||
}).catch(()=>{}).finally(()=>{ x.pct=null; pintaFolha(); });
|
||||
}).catch(()=>{}).finally(()=>{ x.pct=null; pintaFolha(); marcaResiduos(x); });
|
||||
}else if(md && RENDERIZA.test(x.f.name)){
|
||||
carregarImagem(x.f).then(img=>{
|
||||
if(img){ x.previewSrc=img.src; x.miniSrc=miniatura(img); x.fotoSrc=miniatura(img,480,720); try{ x.an=analisarFolha(img, md.larg); if(x.an) x.an.fonteDpi='arquivo'; }
|
||||
catch(e){} }
|
||||
x.pct=null; pintaFolha();
|
||||
carregarImagem(x.f).then(async img=>{
|
||||
if(img){
|
||||
// Decoded once and kept: drawn from the <img>, a large sheet is
|
||||
// decoded again for each strip the check reads.
|
||||
const fonte=await createImageBitmap(img).catch(()=>img);
|
||||
x.previewSrc=img.src; x.miniSrc=miniatura(fonte); x.fotoSrc=miniatura(fonte,480,720);
|
||||
x.pct=80; pintaFolha();
|
||||
let mostrado=80;
|
||||
try{ x.an={...analisarMapa(await mapaDaImagem(fonte, md.larg, p=>{
|
||||
const pct=80+Math.floor(p*19);
|
||||
if(pct>mostrado){ mostrado=pct; x.pct=pct; pintaProgressoFolha(x); }
|
||||
})), fonteDpi:'arquivo'}; }catch(e){}
|
||||
if(fonte.close) fonte.close();
|
||||
}
|
||||
x.pct=null; pintaFolha(); marcaResiduos(x);
|
||||
});
|
||||
}else if(md && /\.pdf$/i.test(x.f.name) && x.f.size>GRANDE_BYTES){
|
||||
x.semAnalise='PDF grande: a resolução das imagens de dentro é conferida pela equipe';
|
||||
x.pdfGrande=true; // a warning on the sheet, like a file opened by hand
|
||||
x.pct=null; pintaFolha();
|
||||
}else if(md && /\.pdf$/i.test(x.f.name)){
|
||||
x.pct=70; pintaFolha();
|
||||
rasterizarPdf(x.f, md.larg, md.alt).then(r=>{
|
||||
rasterizarPdf(x.f, md.larg, md.alt, true).then(r=>{
|
||||
if(r && r.erro){
|
||||
x.semAnalise = r.erro + (r.semWorker
|
||||
? ' · este navegador não deixa o leitor rodar em segundo plano'
|
||||
: '');
|
||||
}
|
||||
if(r && r.tela){
|
||||
if(r && r.tela && r.mapa){
|
||||
x.miniSrc=miniatura(r.tela); x.fotoSrc=miniatura(r.tela,480,720);
|
||||
x.previewSrc=r.tela.toDataURL('image/webp',0.85);
|
||||
try{
|
||||
x.an=analisarFolha(r.tela, md.larg);
|
||||
x.an=analisarMapa(r.mapa);
|
||||
// vetor puro não tem resolução · nota máxima, e está certo
|
||||
x.an.dpi = r.dpi==null ? DPI_AVISA : r.dpi;
|
||||
x.an.vetor = r.dpi==null;
|
||||
@@ -108,7 +196,7 @@ function sel(fs){
|
||||
x.an.res = r.res || null;
|
||||
}catch(e){}
|
||||
}
|
||||
x.pct=null; pintaFolha();
|
||||
x.pct=null; pintaFolha(); marcaResiduos(x);
|
||||
});
|
||||
}else{ x.pct=null; pintaFolha(); }
|
||||
});
|
||||
@@ -129,7 +217,7 @@ function medir(a){
|
||||
return dimensoesImagem(a.f).then(async d=>{
|
||||
if(!d || !(d.w>0) || !(d.h>0)){ a.decodeError=true; return a; }
|
||||
a.px=d.w; a.py=d.h; a.prop=d.h/d.w; a.grande=true;
|
||||
// JPG and WebP cannot be read in parts: the art is placed by its
|
||||
// WebP cannot be read in parts (JPG is refused): the art is placed by its
|
||||
// measurements, as a full box, and the team checks it before printing.
|
||||
if(!/\.png$/i.test(a.f.name)){ a.semPrevia=true; return a; }
|
||||
a.lendo=0; a.leitura={inicio:Date.now(), p:0}; pintaArtes();
|
||||
|
||||
@@ -68,8 +68,8 @@ section+section{border-top:0}
|
||||
.ec{text-align:left;padding:26px;gap:14px;border:1px solid var(--linha);border-radius:16px;box-shadow:none;cursor:pointer;font:inherit;color:inherit}
|
||||
.ec::before,.ec::after{display:none}
|
||||
.ec:hover{border-color:var(--laranja);box-shadow:0 10px 30px rgba(3,6,11,.08);transform:translateY(-2px)}
|
||||
.ec.f,.ec.f:hover{border-color:var(--linha)}
|
||||
.ec.f:hover{border-color:var(--laranja)}
|
||||
/* "Mais vendido": a thick green border, where the eye lands first (Dropstar, 2026-10-29). */
|
||||
.ec.f,.ec.f:hover{border:3px solid var(--verde-ml);padding:24px}
|
||||
.ec-top{display:flex;align-items:center;gap:10px}
|
||||
.ec-kind{font-family:"Inter",sans-serif;font-weight:700;font-size:14.5px;letter-spacing:.05em;color:#707070}
|
||||
.marc2{margin-left:auto;font-family:"Inter",sans-serif;font-weight:800;font-size:13.5px;letter-spacing:.05em;text-transform:uppercase;padding:4px 10px;border-radius:999px;background:var(--preto);color:var(--laranja)}
|
||||
@@ -78,10 +78,10 @@ section+section{border-top:0}
|
||||
.ec-pe{display:flex;align-items:flex-end;gap:12px;padding-top:14px;border-top:1px solid #EFEFEF}
|
||||
.ec-preco{display:flex;flex-direction:column;gap:2px}
|
||||
.ec-preco span{font-size:15px;color:#707070}
|
||||
.ec-preco em{font-style:normal}
|
||||
.ec-preco b{font-family:"Inter",sans-serif;font-size:29px;font-weight:900;letter-spacing:-.02em;color:var(--preto)}
|
||||
.ec-go{margin-left:auto;height:46px;padding:0 18px;border-radius:var(--raio2);background:var(--preto);color:#fff;font-family:"Inter",sans-serif;font-weight:700;font-size:16.5px;display:flex;align-items:center;white-space:nowrap}
|
||||
.ec:hover .ec-go{background:var(--laranja);color:var(--preto)}
|
||||
/* The four "Enviar…" buttons in one action colour, the border's green (2026-10-29). */
|
||||
.ec-go{margin-left:auto;height:46px;padding:0 18px;border-radius:var(--raio2);background:var(--verde-ml);color:#fff;font-family:"Inter",sans-serif;font-weight:700;font-size:16.5px;display:flex;align-items:center;white-space:nowrap}
|
||||
.ec:hover .ec-go{background:#008A43;color:#fff}
|
||||
|
||||
/* Progress bar */
|
||||
.passos{position:sticky;top:var(--topo,64px);z-index:30;display:flex;align-items:center;justify-content:center;gap:14px;margin:0 0 22px;padding:14px 16px;background:rgba(255,255,255,.96);backdrop-filter:blur(6px);border-bottom:1px solid var(--linha);font-family:"Inter",sans-serif;font-size:16px}
|
||||
@@ -140,11 +140,13 @@ section+section{border-top:0}
|
||||
.zona .zManual[hidden]{display:none}
|
||||
.zona .zManual b{display:inline;font-size:15px}
|
||||
.zona .zOutra{display:none}
|
||||
.zona.compacta{display:flex;justify-content:center;align-items:center;min-height:56px;padding:0 20px;border:1.5px dashed #D0D0D0;background:#fff;cursor:pointer}
|
||||
/* With files already in, the uploader stays on top, big and highlighted: the
|
||||
most visible thing on the page (Dropstar, 2026-10-29). */
|
||||
.zona.compacta{display:flex;justify-content:center;align-items:center;gap:14px;min-height:104px;padding:18px 20px;border:2px dashed #F2B25A;background:var(--aviso-fundo);cursor:pointer;margin-bottom:14px}
|
||||
.zona.compacta>*{display:none}
|
||||
.zona.compacta .zOutra{display:inline;font-size:16px;color:var(--fraco)}
|
||||
.zona.compacta .zOutra b{display:inline;font-size:16px;font-weight:600;color:var(--preto)}
|
||||
.zona.compacta .zOutra b::before{content:"+";margin-right:8px;font-weight:700}
|
||||
.zona.compacta .ico{display:flex}
|
||||
.zona.compacta .zOutra{display:inline;font-size:17px;color:var(--fraco)}
|
||||
.zona.compacta .zOutra b{display:inline;font-size:18px;font-weight:700;color:var(--preto)}
|
||||
.zona.compacta:hover,.zona.compacta.sobre{border-color:var(--laranja2)}
|
||||
#lista{display:flex;flex-direction:column;gap:10px}
|
||||
#lista:empty{display:none}
|
||||
@@ -181,6 +183,11 @@ section+section{border-top:0}
|
||||
.chipSo{align-self:flex-start;padding:5px 10px;border-radius:999px;background:#F1F1F1;color:var(--texto2);font-size:15px;font-weight:600}
|
||||
.avisoF{margin:4px 0 0;padding:10px 12px;border-radius:10px;background:#FDE8E6;font-size:15px;line-height:1.5;color:var(--preto)}
|
||||
.avisoF b{color:#B3261E}
|
||||
/* Aceite do resíduo (Dropstar, 29/10/2026): no lugar de barrar a folha. */
|
||||
/* .rep label (index.html) styles the small field labels: this one is a sentence. */
|
||||
.rep .aceiteRes{display:flex;gap:10px;align-items:flex-start;margin:6px 0 0;padding:10px 12px;border-radius:10px;
|
||||
background:#FFF1DB;font-size:15px;line-height:1.5;color:var(--preto);cursor:pointer}
|
||||
.rep .aceiteRes input{width:18px;height:18px;margin:2px 0 0;flex:none;accent-color:#8A4B00;cursor:pointer}
|
||||
.repTxt{margin:2px 0 0;font-size:15.5px;line-height:1.5;color:var(--texto2)}
|
||||
.repTxt b{color:var(--preto)}
|
||||
.confDet{font-size:15px}
|
||||
@@ -238,20 +245,8 @@ section+section{border-top:0}
|
||||
.ampliar:hover{border-color:var(--preto)}
|
||||
.ampliar[hidden]{display:none}
|
||||
.cat.file #vArea{max-height:340px}
|
||||
.cEscada{display:flex;flex-direction:column;gap:8px;margin-bottom:4px}
|
||||
.cEscada>span{font-size:15px;font-weight:600}
|
||||
.cEscada ol{list-style:none;margin:0;padding:0;display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:4px}
|
||||
.cEscada li{padding:8px 2px;border-radius:8px;background:#F4F4F2;border:1.5px solid transparent;display:flex;flex-direction:column;align-items:center;gap:2px}
|
||||
.cEscada li span{font-size:13.5px;color:var(--fraco);white-space:nowrap}
|
||||
.cEscada li b{font-size:15px;font-weight:500;color:var(--texto2)}
|
||||
.cEscada li.on{background:var(--verde-fundo);border-color:var(--verde)}
|
||||
.cEscada li.on span,.cEscada li.on b{font-weight:700;color:var(--verde)}
|
||||
.cEscada li.on:last-child{background:#F1F1F1;border-color:var(--preto)}
|
||||
.cEscada li.on:last-child span,.cEscada li.on:last-child b{color:var(--preto)}
|
||||
.cLin>span:first-child{color:var(--texto2)}
|
||||
.cLin small{font-size:14.5px;color:var(--fraco)}
|
||||
.cEco{margin:-6px 0 0;text-align:right;font-size:15px;font-weight:600;color:var(--verde)}
|
||||
.cEco:empty{display:none}
|
||||
#cPartes{display:block}
|
||||
.ampliaDlg{width:min(960px,calc(100vw - 32px));max-height:calc(100vh - 48px);padding:0;border:0;border-radius:16px;box-shadow:0 20px 60px rgba(3,6,11,.3)}
|
||||
.ampliaDlg::backdrop{background:rgba(3,6,11,.55)}
|
||||
@@ -323,6 +318,9 @@ section+section{border-top:0}
|
||||
.carr h3{font-size:24px;font-weight:800;letter-spacing:-.02em}
|
||||
.cxE{border-radius:var(--raio);border-color:var(--linha)}
|
||||
.cxE h4,.resumo h4{font-family:"Inter",sans-serif;font-weight:800;font-size:18px}
|
||||
.provaOp{display:flex;gap:10px;align-items:flex-start;cursor:pointer;font-size:15px;line-height:1.5;color:var(--fraco)}
|
||||
.provaOp input{margin-top:3px;width:17px;height:17px;flex:none;accent-color:var(--laranja)}
|
||||
.provaOp b{display:block;color:var(--preto);font-weight:700}
|
||||
.cp input,.cepL input{height:46px;border-radius:var(--raio2)}
|
||||
.cp input:focus,.cepL input:focus{border-color:var(--laranja2);box-shadow:0 0 0 3px rgba(255,168,26,.18)}
|
||||
.opE{border-radius:12px}
|
||||
@@ -383,6 +381,17 @@ html:is([data-rota="pagamento"],[data-rota="pix"]) .pagGrid{display:grid;grid-te
|
||||
.envioBarra{height:6px;border-radius:999px;background:#EDEDED;overflow:hidden;margin-bottom:6px}
|
||||
.envioBarra i{display:block;height:100%;background:var(--laranja);border-radius:999px;transition:width .4s}
|
||||
.cartEnvio{font-size:15px;font-weight:700;color:var(--laranja-escuro);margin-left:6px}
|
||||
/* Each file's upload under the uploader (Dropstar, 2026-10-29). */
|
||||
.envios{display:flex;flex-direction:column;gap:8px;margin:0 0 14px}
|
||||
.envios:empty{display:none}
|
||||
.envio{padding:12px 14px;border:1px solid #CFE9D8;border-radius:12px;background:#F2FBF5;font-size:15px;line-height:1.4;color:var(--preto);overflow-wrap:anywhere}
|
||||
.envio span{display:block;margin-bottom:8px}
|
||||
.envio .envioBarra{height:12px;margin:0;background:#DDEFE3}
|
||||
.envio .envioBarra i{background:var(--verde-ml)}
|
||||
.envio.ok{display:flex;align-items:center;gap:8px;color:#00753A}
|
||||
.envio.erro{display:flex;flex-wrap:wrap;align-items:center;gap:6px 10px;border-color:#F4C7C1;background:#FDE8E6;color:#B3261E}
|
||||
.envio.ok span,.envio.erro span{margin:0}
|
||||
.envio.erro button{padding:0;border:0;background:none;color:inherit;font:inherit;font-weight:700;text-decoration:underline;cursor:pointer}
|
||||
.cartEnvio:empty{display:none}
|
||||
.envioArq:empty{display:none}
|
||||
.pagCab{display:flex;align-items:baseline;justify-content:space-between;gap:16px;margin-bottom:20px}
|
||||
@@ -430,7 +439,6 @@ html:is([data-rota="pagamento"],[data-rota="pix"]) .pagGrid{display:grid;grid-te
|
||||
.info2 table{border-collapse:collapse;background:#fff;border:1px solid var(--linha);border-radius:12px;overflow:hidden;font-size:16.5px}
|
||||
.info2 th{text-align:left;background:var(--preto);color:#fff;font-family:"Inter",sans-serif;font-size:15px;padding:12px 18px}
|
||||
.info2 td{padding:11px 18px;border-top:1px solid #EFEFEF}
|
||||
.info2 td.melhor{font-weight:700;color:var(--verde)}
|
||||
.info2 .nota2{font-size:15px;color:#707070}
|
||||
.info2-vant{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:16px}
|
||||
.info2-vant>div{padding:22px;border-radius:var(--raio);background:#fff;border:1px solid var(--linha);display:flex;flex-direction:column;gap:6px}
|
||||
|
||||
80
web/termos.html
Normal file
80
web/termos.html
Normal file
@@ -0,0 +1,80 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="pt-BR">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Trocas e privacidade · DTF Dropstar</title>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&family=Roboto:wght@300;400;500;700&display=swap" rel="stylesheet">
|
||||
<link rel="stylesheet" href="/site-shell.css">
|
||||
<link rel="stylesheet" href="/site-v2.css">
|
||||
<link rel="stylesheet" href="/portal.css">
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<div class="tarja">
|
||||
ENVIE SEU ARQUIVO DTF PELO SITE · DTF TÊXTIL COM O MENOR PREÇO DO METRO EM FRANCA-SP
|
||||
</div>
|
||||
|
||||
<header class="topo"><div class="w">
|
||||
<a class="logo" href="/" aria-label="DTF Dropstar · página inicial"><img src="https://cdn.vnda.com.br/dropstar/2025/12/17/logo-header-15125700-16129080.png?v=1766009286" alt="Dropstar"></a>
|
||||
<div class="acts">
|
||||
<a href="/conta"><svg class="ic" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg><span class="actTx" id="quem">Minha conta</span></a>
|
||||
<a href="/carrinho"><svg class="ic" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M6 2 3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4Z"/><path d="M3 6h18"/><path d="M16 10a4 4 0 0 1-8 0"/></svg><span class="actTx">Carrinho</span></a>
|
||||
</div>
|
||||
</div></header>
|
||||
|
||||
<main class="ped w termos">
|
||||
<h1>Trocas e privacidade</h1>
|
||||
<p class="termosSub">Os termos do DTF Dropstar: o que vale para a sua arte, os seus arquivos e os seus dados.</p>
|
||||
|
||||
<h2>Sua arte</h2>
|
||||
<p>Imprimimos a arte do jeito que ela está no arquivo que você envia. Antes do pagamento, o site confere a
|
||||
resolução e, na folha pronta, o fundo e os resíduos de recorte, e mostra o que encontrar. O que está no
|
||||
arquivo e o direito de usar cada imagem, marca ou personagem nele são responsabilidade de quem envia.</p>
|
||||
|
||||
<h2>Guarda dos arquivos</h2>
|
||||
<p>Guardamos os arquivos do seu pedido por 30 dias, contados do envio. Depois disso eles são apagados.
|
||||
Para imprimir de novo depois desse prazo, é só enviar a arte outra vez.</p>
|
||||
|
||||
<h2>Trocas</h2>
|
||||
<p>O DTF é um produto personalizado, feito sob encomenda com a sua arte. Por isso não há troca nem
|
||||
devolução por arrependimento. Se algo chegar diferente do que você aprovou, fale com a gente pelo
|
||||
WhatsApp <a href="https://wa.me/message/NJ76CLIOUGXLB1" target="_blank" rel="noopener">16 99428-0056</a>,
|
||||
com o número do pedido.</p>
|
||||
|
||||
<h2>Seus dados</h2>
|
||||
<p>Pedimos nome, CPF ou CNPJ, e-mail, WhatsApp e, na entrega, o endereço. Eles servem para fazer o pedido,
|
||||
emitir a nota, receber o pagamento e entregar: por isso vão para o nosso sistema de gestão, para o Mercado
|
||||
Pago e para a transportadora que você escolher. Dúvidas sobre os seus dados:
|
||||
<a href="mailto:atendimentodropstar@gmail.com">atendimentodropstar@gmail.com</a>.</p>
|
||||
</main>
|
||||
|
||||
<footer><div class="w">
|
||||
<div class="frow">
|
||||
<span class="fmarca"><img src="https://cdn.vnda.com.br/dropstar/2025/12/17/logo-header-15125700-16129080.png?v=1766009286" alt="Dropstar">DTF</span>
|
||||
<div class="flinks">
|
||||
<a href="https://www.dropstaratacado.com.br" target="_blank" rel="noopener">Loja de atacado</a>
|
||||
<a href="/termos">Trocas e privacidade</a>
|
||||
<a href="https://www.dropstaratacado.com.br/p/atendimento" target="_blank" rel="noopener">Fale conosco</a>
|
||||
<a href="https://www.instagram.com/dropstar.ofc/" target="_blank" rel="noopener">Instagram</a>
|
||||
</div>
|
||||
<div class="fcont">
|
||||
<a href="https://wa.me/message/NJ76CLIOUGXLB1" target="_blank" rel="noopener">16 99428-0056</a>
|
||||
· arquivos 16 99230-2546<br>
|
||||
<a href="mailto:atendimentodropstar@gmail.com">atendimentodropstar@gmail.com</a><br>
|
||||
Mande sua arte em qualquer horário.<br>
|
||||
Retirada em Franca, de segunda a sexta, das 7h às 18h
|
||||
</div>
|
||||
</div>
|
||||
<div class="fbase">
|
||||
<span>© Dropstar Atacado · CNPJ 55.786.635/0001-58 · Franca-SP</span>
|
||||
<span>Cartão de crédito (Visa · Master · Elo · Amex) · PIX</span>
|
||||
<span>têxtil 57 cm · UV 27 cm</span>
|
||||
</div>
|
||||
</div></footer>
|
||||
|
||||
<script src="/privacy.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,5 +1,6 @@
|
||||
/* Shared direct multipart transport for customer originals/corrections and operator finals. */
|
||||
window.dtfUpload = async (file, {api, prefix='/uploads', startPath=prefix, progress=()=>{}, onBytes=()=>{}, scope='guest', resume=true}) => {
|
||||
window.dtfUpload = async (file, {api, prefix='/uploads', startPath=prefix, progress=()=>{}, onBytes=()=>{}, scope='guest', resume=true, signal=null}) => {
|
||||
const cancelled=()=>new DOMException('Envio cancelado.','AbortError');
|
||||
const samples=new Blob([file.slice(0,65536),file.slice(Math.max(0,file.size-65536))]);
|
||||
const hash=Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',await samples.arrayBuffer())),b=>b.toString(16).padStart(2,'0')).join('');
|
||||
const key='dtf-upload:'+JSON.stringify([scope,file.name,file.size,file.lastModified,hash]);
|
||||
@@ -22,15 +23,29 @@ window.dtfUpload = async (file, {api, prefix='/uploads', startPath=prefix, progr
|
||||
}
|
||||
if(state.complete)return waitForScan();
|
||||
const done=new Set(state.parts||[]),size=state.part_bytes;
|
||||
onBytes(Math.min(file.size,done.size*size));
|
||||
const length=part=>Math.min(size,file.size-(part-1)*size);
|
||||
let sent=[...done].reduce((t,part)=>t+length(part),0);
|
||||
onBytes(sent);
|
||||
// Each part through XMLHttpRequest, which reports the bytes as they go: the
|
||||
// bar moves while a part is on its way, not once per part (Dropstar, 2026-10-29).
|
||||
const put=(url,body)=>new Promise((resolve,reject)=>{
|
||||
if(signal?.aborted)return reject(cancelled());
|
||||
const xhr=new XMLHttpRequest();xhr.open('PUT',url);
|
||||
xhr.upload.onprogress=e=>onBytes(Math.min(file.size,sent+e.loaded));
|
||||
const lost=()=>reject(new Error('Upload interrompido. Tente novamente para retomar.'));
|
||||
xhr.onload=()=>xhr.status>=200&&xhr.status<300?resolve():lost();
|
||||
xhr.onerror=lost;xhr.ontimeout=lost;xhr.onabort=()=>reject(cancelled());
|
||||
signal?.addEventListener('abort',()=>xhr.abort(),{once:true});
|
||||
xhr.send(body);
|
||||
});
|
||||
for(let offset=0,part=1;offset<file.size;offset+=size,part++){
|
||||
if(done.has(part))continue;
|
||||
if(signal?.aborted)throw cancelled();
|
||||
progress('Enviando '+file.name+' · parte '+part+'/'+Math.ceil(file.size/size));
|
||||
const signed=await api(prefix+'/'+id+'/parts/'+part,{});
|
||||
const response=await fetch(signed.url,{method:'PUT',body:file.slice(offset,offset+size)});
|
||||
if(!response.ok)throw new Error('Upload interrompido. Tente novamente para retomar.');
|
||||
done.add(part);
|
||||
onBytes(Math.min(file.size,done.size*size));
|
||||
await put(signed.url,file.slice(offset,offset+size));
|
||||
done.add(part);sent+=length(part);
|
||||
onBytes(sent);
|
||||
}
|
||||
await api(prefix+'/'+id+'/complete',{});
|
||||
return waitForScan();
|
||||
|
||||
Reference in New Issue
Block a user