Merge main into fix-pdf-check
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -26,7 +26,10 @@ jobs:
|
|||||||
tests.test_db_pool \
|
tests.test_db_pool \
|
||||||
tests.test_coupons \
|
tests.test_coupons \
|
||||||
tests.test_grade_rules \
|
tests.test_grade_rules \
|
||||||
|
tests.test_hotfolder \
|
||||||
tests.test_migrate \
|
tests.test_migrate \
|
||||||
|
tests.test_label \
|
||||||
|
tests.test_observability \
|
||||||
tests.test_secrets -v
|
tests.test_secrets -v
|
||||||
sh -n infra/lock_dependencies.sh
|
sh -n infra/lock_dependencies.sh
|
||||||
|
|
||||||
@@ -84,7 +87,7 @@ jobs:
|
|||||||
# one a developer exercises on localhost.
|
# one a developer exercises on localhost.
|
||||||
- name: API and workflow regressions
|
- name: API and workflow regressions
|
||||||
run: |
|
run: |
|
||||||
for suite in smoke_test workflow_test security_test scanning_test payment_test unpaid_test quote_pagination_test kanban_test reconcile_test order_actions_test print_file_test users_test stage_limits_test mail_test thumbnail_backfill_test launch_reset_test finished_order_test machine_pull_test site_video_test treatment_gate_test review_media_test machine_log_test machine_stats_test site_admin_test coupons_test stamps_test grade_rules_test; do
|
for suite in smoke_test workflow_test security_test upload_limits_test scanning_test payment_test unpaid_test quote_pagination_test kanban_test label_test reconcile_test order_actions_test print_file_test users_test stage_limits_test mail_test thumbnail_backfill_test launch_reset_test finished_order_test machine_pull_test site_video_test treatment_gate_test review_media_test machine_log_test machine_stats_test site_admin_test coupons_test stamps_test grade_rules_test; do
|
||||||
echo "--- $suite"
|
echo "--- $suite"
|
||||||
$COMPOSE exec -T \
|
$COMPOSE exec -T \
|
||||||
-e SITE_BASE_URL=http://site \
|
-e SITE_BASE_URL=http://site \
|
||||||
@@ -97,7 +100,7 @@ jobs:
|
|||||||
# the generator's geometry. The provider suites use a fake transport: they
|
# the generator's geometry. The provider suites use a fake transport: they
|
||||||
# prove the documented contract, not the integration.
|
# prove the documented contract, not the integration.
|
||||||
- name: Print-file geometry and provider adapters
|
- name: Print-file geometry and provider adapters
|
||||||
run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_printpng 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 tests.test_proof_cut tests.test_proof_render tests.test_prumo tests.test_speed tests.test_printpng_validate tests.test_machine_log tests.test_machine_stats tests.test_worker_drain -v
|
run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_printpng 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 tests.test_proof_cut tests.test_proof_render tests.test_prumo tests.test_speed tests.test_printpng_validate tests.test_machine_log tests.test_machine_stats tests.test_label tests.test_observability tests.test_worker_drain -v
|
||||||
|
|
||||||
- name: Runtime and retention regressions
|
- name: Runtime and retention regressions
|
||||||
run: |
|
run: |
|
||||||
|
|||||||
@@ -190,10 +190,22 @@ class EventAdapter(Protocol):
|
|||||||
def deliver(self, event_key: str, payload: dict) -> dict: ...
|
def deliver(self, event_key: str, payload: dict) -> dict: ...
|
||||||
|
|
||||||
class FakeTiny:
|
class FakeTiny:
|
||||||
|
# The montador's Venda customer search (front 7a.3) has somewhere to look
|
||||||
|
# on the local stack and in CI. Two fixed contacts, always.
|
||||||
|
CONTACTS = [
|
||||||
|
{'id': 1001, 'name': 'Nexstar Marketplace Ltda', 'document': '11.222.333/0001-81',
|
||||||
|
'email': 'financeiro@nexstar.example', 'phone': '1633334444'},
|
||||||
|
{'id': 1002, 'name': 'Maria Souza', 'document': '123.456.789-09',
|
||||||
|
'email': 'maria.souza@example.test', 'phone': '16988887777'},
|
||||||
|
]
|
||||||
|
|
||||||
def deliver(self, event_key: str, payload: dict) -> dict:
|
def deliver(self, event_key: str, payload: dict) -> dict:
|
||||||
return {'provider': 'fake-tiny', 'reference': f"LOCAL-{payload['number']}",
|
return {'provider': 'fake-tiny', 'reference': f"LOCAL-{payload['number']}",
|
||||||
'event_key': event_key, 'status': 'recorded-locally'}
|
'event_key': event_key, 'status': 'recorded-locally'}
|
||||||
|
|
||||||
|
def search_contacts(self, query: str) -> list:
|
||||||
|
return [dict(contact) for contact in self.CONTACTS]
|
||||||
|
|
||||||
class ObjectStorage(Protocol):
|
class ObjectStorage(Protocol):
|
||||||
def begin(self, key: str) -> str: ...
|
def begin(self, key: str) -> str: ...
|
||||||
def parts(self, key: str, upload_id: str) -> list: ...
|
def parts(self, key: str, upload_id: str) -> list: ...
|
||||||
|
|||||||
@@ -47,8 +47,12 @@ def session(request: Request, response: Response):
|
|||||||
'password_recovery': mail.configured(),
|
'password_recovery': mail.configured(),
|
||||||
# Per metre on a finished sheet someone opens by hand (app/core/pricing.py).
|
# Per metre on a finished sheet someone opens by hand (app/core/pricing.py).
|
||||||
'manual_extra_cents': manual_extra_cents(),
|
'manual_extra_cents': manual_extra_cents(),
|
||||||
# Zero keeps the designer's treatment hidden, as an off product does.
|
# Zero keeps Ajuste Fino hidden, as an off product does. Its bands
|
||||||
|
# are counted in arts, not metres.
|
||||||
'treatment_cents': treatment['unit_cents'] if treatment['enabled'] else 0,
|
'treatment_cents': treatment['unit_cents'] if treatment['enabled'] else 0,
|
||||||
|
'treatment_bands': [{'from_metres': float(band['from_metres']),
|
||||||
|
'unit_cents': band['unit_cents']}
|
||||||
|
for band in treatment['bands']] if treatment['enabled'] else [],
|
||||||
# The grade rules the Site needs for the treatment requirement
|
# The grade rules the Site needs for the treatment requirement
|
||||||
# (front 8.5): {} when nothing is configured.
|
# (front 8.5): {} when nothing is configured.
|
||||||
'grade_rules': rules,
|
'grade_rules': rules,
|
||||||
@@ -59,6 +63,10 @@ def session(request: Request, response: Response):
|
|||||||
'unit_cents': band['unit_cents']}
|
'unit_cents': band['unit_cents']}
|
||||||
for band in products[mode]['bands']]}
|
for band in products[mode]['bands']]}
|
||||||
for mode in catalog.MODES},
|
for mode in catalog.MODES},
|
||||||
|
# Public by design: the browser initialises Sentry with these; empty is off.
|
||||||
|
'sentry_dsn_web': os.environ.get('SENTRY_DSN_WEB', '').strip(),
|
||||||
|
'sentry_environment': os.environ.get('SENTRY_ENVIRONMENT') or ENVIRONMENT,
|
||||||
|
'sentry_release': os.environ.get('IMAGE_TAG', ''),
|
||||||
# Public by design: Mercado Pago's card form needs it in the browser.
|
# Public by design: Mercado Pago's card form needs it in the browser.
|
||||||
'payment_public_key': os.environ.get('MP_PUBLIC_KEY', '') if payment.name == 'mercadopago' else '',
|
'payment_public_key': os.environ.get('MP_PUBLIC_KEY', '') if payment.name == 'mercadopago' else '',
|
||||||
# The delivery options the cart quotes, or none: pickup only.
|
# The delivery options the cart quotes, or none: pickup only.
|
||||||
|
|||||||
@@ -53,6 +53,8 @@ def sheet(mid: UUID, user=Depends(can('view'))):
|
|||||||
'counters': machine_log.counters(c, mid),
|
'counters': machine_log.counters(c, mid),
|
||||||
'supplies': machine_log.supply_estimates(c, mid),
|
'supplies': machine_log.supply_estimates(c, mid),
|
||||||
'minimums': minimums,
|
'minimums': minimums,
|
||||||
|
# The values the sheet shows when Gestão has not typed one.
|
||||||
|
'default_minimums': machine_log.DEFAULT_MINIMUMS,
|
||||||
'alerts': machine_log.alerts(c, mid),
|
'alerts': machine_log.alerts(c, mid),
|
||||||
'entries': [{**row, 'label': entry_label(row)} for row in entries],
|
'entries': [{**row, 'label': entry_label(row)} for row in entries],
|
||||||
'catalog': {'supplies': machine_log.SUPPLIES, 'parts': machine_log.PARTS,
|
'catalog': {'supplies': machine_log.SUPPLIES, 'parts': machine_log.PARTS,
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ includes and the names other modules imported from the old single file.
|
|||||||
"""
|
"""
|
||||||
from fastapi import APIRouter
|
from fastapi import APIRouter
|
||||||
|
|
||||||
from . import board, common, files, integrations, orders, quotes, rework, session, stats
|
from . import board, common, files, integrations, labels, orders, quotes, rework, session, stats
|
||||||
from .integrations import tiny_callback
|
from .integrations import tiny_callback
|
||||||
from .stats import speed_figures
|
from .stats import speed_figures
|
||||||
|
|
||||||
@@ -13,5 +13,5 @@ router = APIRouter()
|
|||||||
# The order the routes first appeared in the old file. Static paths that could
|
# The order the routes first appeared in the old file. Static paths that could
|
||||||
# meet a parameterised one stay ahead of it: /orders/finished before any
|
# meet a parameterised one stay ahead of it: /orders/finished before any
|
||||||
# /orders/{uid} GET.
|
# /orders/{uid} GET.
|
||||||
for module in (common, session, integrations, board, quotes, rework, orders, stats, files):
|
for module in (common, session, integrations, board, quotes, rework, orders, labels, stats, files):
|
||||||
router.include_router(module.router)
|
router.include_router(module.router)
|
||||||
|
|||||||
@@ -65,8 +65,8 @@ def cursor_pair(first, second):
|
|||||||
return first is not None
|
return first is not None
|
||||||
|
|
||||||
|
|
||||||
MODES = {'textil': {'file', 'avulsa'}, 'uv': {'uvfile', 'uv'},
|
MODES = {'textil': {'file', 'avulsa', 'premium'}, 'uv': {'uvfile', 'uv'},
|
||||||
'folha': {'file', 'uvfile'}, 'avulsa': {'avulsa', 'uv'}}
|
'folha': {'file', 'uvfile', 'premium'}, 'avulsa': {'avulsa', 'uv'}}
|
||||||
|
|
||||||
|
|
||||||
def like(text):
|
def like(text):
|
||||||
|
|||||||
@@ -133,6 +133,22 @@ def tiny_status(c=None):
|
|||||||
return {'configured': True, 'orders_enabled': os.environ.get('TINY_ADAPTER') == 'tiny',
|
return {'configured': True, 'orders_enabled': os.environ.get('TINY_ADAPTER') == 'tiny',
|
||||||
**tiny.TinyAuth().status(c)}
|
**tiny.TinyAuth().status(c)}
|
||||||
|
|
||||||
|
@router.get('/api/operator/tiny/contacts')
|
||||||
|
def tiny_contacts(q: str = Query(min_length=1, max_length=120), user=Depends(can('assemble'))):
|
||||||
|
"""The Tiny contacts a Venda customer is picked from (Fase 2, front
|
||||||
|
7a.3): by name, or by CPF/CNPJ when only digits were typed. The fake
|
||||||
|
adapter answers with two fixed contacts on the local stack and in CI."""
|
||||||
|
if os.environ.get('TINY_ADAPTER') != 'tiny':
|
||||||
|
from ...adapters import FakeTiny
|
||||||
|
return FakeTiny().search_contacts(q)
|
||||||
|
if not tiny.configured():
|
||||||
|
raise HTTPException(409, 'O Tiny não está conectado.')
|
||||||
|
try:
|
||||||
|
return tiny.search_contacts(tiny.TinyOrders(), q)
|
||||||
|
except tiny.TinyNotConnected:
|
||||||
|
raise HTTPException(409, 'O Tiny não está conectado.')
|
||||||
|
|
||||||
|
|
||||||
@router.post('/api/operator/tiny/connect')
|
@router.post('/api/operator/tiny/connect')
|
||||||
def tiny_connect(user=Depends(can('integrations'))):
|
def tiny_connect(user=Depends(can('integrations'))):
|
||||||
"""Start the one-time authorisation of this system in the client's Tiny."""
|
"""Start the one-time authorisation of this system in the client's Tiny."""
|
||||||
|
|||||||
81
app/api/operator/labels.py
Normal file
81
app/api/operator/labels.py
Normal file
@@ -0,0 +1,81 @@
|
|||||||
|
"""The 10x15 thermal label at Finalizado (Fase 2, front 10; Marcus, 2026-11-10).
|
||||||
|
|
||||||
|
The label page is rendered by the server; one computer prints it automatically
|
||||||
|
(the first claim), and the Expedição profile or the Revisor may reprint it.
|
||||||
|
"""
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, Response
|
||||||
|
|
||||||
|
from ... import label
|
||||||
|
from ...core import db
|
||||||
|
from ...core.auth import audit, can
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
def _order(c, uid, columns='number,state,cancelled_at'):
|
||||||
|
order = c.execute(f'SELECT {columns} FROM dtf_local.orders WHERE id=%s', (uid,)).fetchone()
|
||||||
|
if not order:
|
||||||
|
raise HTTPException(404, 'Pedido não encontrado.')
|
||||||
|
return order
|
||||||
|
|
||||||
|
|
||||||
|
def _tiny_number(c, uid):
|
||||||
|
"""The Tiny order number from the sale event's receipt, or None."""
|
||||||
|
row = c.execute("SELECT receipt->>'tiny_number' AS tiny_number FROM dtf_local.outbox WHERE event_key=%s",
|
||||||
|
(f'{uid}:paid:tiny',)).fetchone()
|
||||||
|
return row['tiny_number'] if row else None
|
||||||
|
|
||||||
|
|
||||||
|
def _finished(c, uid):
|
||||||
|
"""When the card reached Finalizado and who released it, from the movements."""
|
||||||
|
row = c.execute('''SELECT m.created_at,
|
||||||
|
COALESCE(NULLIF((SELECT o.name FROM dtf_local.operators o WHERE o.email=m.operator), ''),
|
||||||
|
m.operator) AS revisor
|
||||||
|
FROM dtf_local.movements m
|
||||||
|
WHERE m.order_id=%s AND m.to_state='fin' AND NOT m.back
|
||||||
|
ORDER BY m.created_at DESC, m.id DESC LIMIT 1''', (uid,)).fetchone()
|
||||||
|
return (row['created_at'], row['revisor']) if row else (None, None)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get('/api/operator/orders/{uid}/label')
|
||||||
|
def order_label(uid: UUID, user=Depends(can('label'))):
|
||||||
|
"""The printable label page (text/html), sized 100 x 150 mm."""
|
||||||
|
with db.connect() as c:
|
||||||
|
order = _order(c, uid, 'number,state,cancelled_at,updated_at,snapshot')
|
||||||
|
if order['cancelled_at'] or order['state'] != 'fin':
|
||||||
|
raise HTTPException(409, 'A etiqueta é impressa em Finalizado.')
|
||||||
|
tiny = _tiny_number(c, uid)
|
||||||
|
finished, revisor = _finished(c, uid)
|
||||||
|
fields = label.label_fields(order, tiny, finished or order['updated_at'], revisor)
|
||||||
|
return Response(label.label_html(fields), media_type='text/html; charset=utf-8',
|
||||||
|
headers={'Cache-Control': 'no-store'})
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/orders/{uid}/label/claim')
|
||||||
|
def claim_label(uid: UUID, user=Depends(can('label'))):
|
||||||
|
"""The first computer to ask prints the label; the unique partial index on
|
||||||
|
the 'auto' row decides, so two computers at once cannot both print it."""
|
||||||
|
with db.connect() as c:
|
||||||
|
order = _order(c, uid)
|
||||||
|
if order['cancelled_at'] or order['state'] != 'fin':
|
||||||
|
return {'print': False}
|
||||||
|
row = c.execute('''INSERT INTO dtf_local.label_prints(order_id,reason,printed_by)
|
||||||
|
VALUES(%s,'auto',%s) ON CONFLICT DO NOTHING RETURNING id''', (uid, user)).fetchone()
|
||||||
|
if row:
|
||||||
|
audit('label_printed', order=order['number'], reason='auto', operator=user)
|
||||||
|
return {'print': bool(row)}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/orders/{uid}/label/reprint')
|
||||||
|
def reprint_label(uid: UUID, user=Depends(can('label'))):
|
||||||
|
"""A new label for an order in Finalizado, from any computer."""
|
||||||
|
with db.connect() as c:
|
||||||
|
order = _order(c, uid)
|
||||||
|
if order['cancelled_at'] or order['state'] != 'fin':
|
||||||
|
raise HTTPException(409, 'A etiqueta é reimpressa em Finalizado.')
|
||||||
|
c.execute('''INSERT INTO dtf_local.label_prints(order_id,reason,printed_by)
|
||||||
|
VALUES(%s,'reprint',%s)''', (uid, user))
|
||||||
|
audit('label_printed', order=order['number'], reason='reprint', operator=user)
|
||||||
|
return {'print': True}
|
||||||
@@ -501,7 +501,7 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
|
|||||||
JOIN dtf_local.uploads u ON u.id=f.upload_id
|
JOIN dtf_local.uploads u ON u.id=f.upload_id
|
||||||
WHERE f.order_id=%s AND {FINAL_OK} AND {TREATED}''', (uid,)).fetchall()
|
WHERE f.order_id=%s AND {FINAL_OK} AND {TREATED}''', (uid,)).fetchall()
|
||||||
if {r['item_index'] for r in treated} != set(range(len(row['snapshot']['items']))):
|
if {r['item_index'] for r in treated} != set(range(len(row['snapshot']['items']))):
|
||||||
raise HTTPException(409, 'Tratamento pago: envie e aprove a arte tratada de todos os itens antes de entrar na fila.')
|
raise HTTPException(409, 'Ajuste Fino pago: envie e aprove a arte do Ajuste Fino de todos os itens antes de entrar na fila.')
|
||||||
# Two at most per machine in Imprimindo (app/machines.py).
|
# Two at most per machine in Imprimindo (app/machines.py).
|
||||||
if body.state == 'imp' and (name := machines.full(c, row['machine_id'], uid)):
|
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.')
|
raise HTTPException(409, f'{name} já tem {machines.PRINTING_CAP} em Imprimindo.')
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ from decimal import Decimal
|
|||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||||
|
|
||||||
from ... import machines, unpaid
|
from ... import machines, payments, unpaid
|
||||||
from ...core import db
|
from ...core import db
|
||||||
from ...core.auth import operator
|
from ...core.auth import operator
|
||||||
from .common import ORIGINS, REAL_ORDER, TREATED, person
|
from .common import ORIGINS, REAL_ORDER, TREATED, person
|
||||||
@@ -13,6 +13,11 @@ from .rework import CUSTOMER_CAUSE, HOUSE_CAUSES, REWORK_GOAL_PERCENT
|
|||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
|
|
||||||
LOCAL_DAY = "(o.created_at AT TIME ZONE 'America/Sao_Paulo')::date"
|
LOCAL_DAY = "(o.created_at AT TIME ZONE 'America/Sao_Paulo')::date"
|
||||||
|
# A montador "Interno" or "faturado" order records the table price, not money
|
||||||
|
# received (Marcus, 2026-11-10): the cash figures leave it out and Números
|
||||||
|
# shows it in its own block.
|
||||||
|
NOT_CASH = ('COALESCE(o.payment->>\'method\',\'\') NOT IN '
|
||||||
|
f"('{payments.INTERNAL_METHOD}','{payments.INVOICED_METHOD}')")
|
||||||
|
|
||||||
|
|
||||||
def waited(order, start, end):
|
def waited(order, start, end):
|
||||||
@@ -57,7 +62,8 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start
|
|||||||
limit_rows = c.execute('SELECT state,hours,responsible FROM dtf_local.stage_limits').fetchall()
|
limit_rows = c.execute('SELECT state,hours,responsible FROM dtf_local.stage_limits').fetchall()
|
||||||
limits = {row['state']: {'hours': float(row['hours']), 'responsible': row['responsible']}
|
limits = {row['state']: {'hours': float(row['hours']), 'responsible': row['responsible']}
|
||||||
for row in limit_rows}
|
for row in limit_rows}
|
||||||
total = c.execute(f'''SELECT count(*) AS orders, COALESCE(sum((o.snapshot->>'total_cents')::bigint),0) AS cents,
|
total = c.execute(f'''SELECT count(*) AS orders,
|
||||||
|
COALESCE(sum((o.snapshot->>'total_cents')::bigint) FILTER (WHERE {NOT_CASH}),0) AS cents,
|
||||||
COALESCE(sum({metres}),0) AS metres,
|
COALESCE(sum({metres}),0) AS metres,
|
||||||
count(*) FILTER (WHERE EXISTS (SELECT 1 FROM dtf_local.movements m WHERE m.order_id=o.id
|
count(*) FILTER (WHERE EXISTS (SELECT 1 FROM dtf_local.movements m WHERE m.order_id=o.id
|
||||||
AND m.to_state='cor' AND NOT m.back)) AS corrected
|
AND m.to_state='cor' AND NOT m.back)) AS corrected
|
||||||
@@ -131,20 +137,29 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start
|
|||||||
# Each way in apart (D-21): what came from where, and how long it took
|
# 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.
|
# 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,
|
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,
|
COALESCE(sum((o.snapshot->>'total_cents')::bigint) FILTER (WHERE {NOT_CASH}),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
|
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
|
f.at - o.created_at) - {waited('o.id', 'o.created_at', 'f.at')}) / 3600 AS median_hours
|
||||||
FROM dtf_local.orders o
|
FROM dtf_local.orders o
|
||||||
LEFT JOIN LATERAL (SELECT min(created_at) AS at FROM dtf_local.movements m
|
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 m.order_id=o.id AND m.to_state='fin') f ON true
|
||||||
WHERE {REAL_ORDER} AND {within} GROUP BY o.origin''', period).fetchall()}
|
WHERE {REAL_ORDER} AND {within} GROUP BY o.origin''', period).fetchall()}
|
||||||
|
# The table price of the montador's Interno and Venda orders, counted
|
||||||
|
# apart from the money received above (front 7a.3).
|
||||||
|
price_table = {row['method']: row for row in c.execute(f'''SELECT o.payment->>'method' AS method,
|
||||||
|
count(*) AS orders, COALESCE(sum({metres}),0) AS metres,
|
||||||
|
COALESCE(sum((o.snapshot->>'total_cents')::bigint),0) AS cents
|
||||||
|
FROM dtf_local.orders o WHERE {REAL_ORDER} AND {within}
|
||||||
|
AND o.payment->>'method' IN (%s,%s) GROUP BY 1''',
|
||||||
|
period + (payments.INTERNAL_METHOD, payments.INVOICED_METHOD)).fetchall()}
|
||||||
# Coupons used by the period's paid orders (front 8.3): what each code
|
# Coupons used by the period's paid orders (front 8.3): what each code
|
||||||
# brought in orders, billed metres, discount and money received.
|
# brought in orders, billed metres, discount and money received.
|
||||||
coupons_used = c.execute(f'''SELECT o.snapshot->'coupon'->>'id' AS id,
|
coupons_used = c.execute(f'''SELECT o.snapshot->'coupon'->>'id' AS id,
|
||||||
o.snapshot->'coupon'->>'code' AS code, count(*) AS orders,
|
o.snapshot->'coupon'->>'code' AS code, count(*) AS orders,
|
||||||
COALESCE(sum({metres}),0) AS metres,
|
COALESCE(sum({metres}),0) AS metres,
|
||||||
COALESCE(sum((o.snapshot->'coupon'->>'discount_cents')::bigint),0) AS discount_cents,
|
COALESCE(sum((o.snapshot->'coupon'->>'discount_cents')::bigint),0) AS discount_cents,
|
||||||
COALESCE(sum((o.snapshot->>'total_cents')::bigint),0) AS cents
|
COALESCE(sum((o.snapshot->>'total_cents')::bigint) FILTER (WHERE {NOT_CASH}),0) AS cents
|
||||||
FROM dtf_local.orders o
|
FROM dtf_local.orders o
|
||||||
WHERE {REAL_ORDER} AND {within} AND o.snapshot->'coupon'->>'id' IS NOT NULL
|
WHERE {REAL_ORDER} AND {within} AND o.snapshot->'coupon'->>'id' IS NOT NULL
|
||||||
GROUP BY 1,2 ORDER BY orders DESC, code''', period).fetchall()
|
GROUP BY 1,2 ORDER BY orders DESC, code''', period).fetchall()
|
||||||
@@ -224,6 +239,11 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start
|
|||||||
'median_hours': hours(origins[name]['median_hours']) if name in origins else None}
|
'median_hours': hours(origins[name]['median_hours']) if name in origins else None}
|
||||||
for name in ORIGINS],
|
for name in ORIGINS],
|
||||||
'unpaid': unpaid_figures,
|
'unpaid': unpaid_figures,
|
||||||
|
'price_table': [{'method': method,
|
||||||
|
'orders': price_table[method]['orders'] if method in price_table else 0,
|
||||||
|
'metres': float(price_table[method]['metres']) if method in price_table else 0.0,
|
||||||
|
'cents': int(price_table[method]['cents']) if method in price_table else 0}
|
||||||
|
for method in (payments.INVOICED_METHOD, payments.INTERNAL_METHOD)],
|
||||||
'lead': {'orders': lead['orders'], 'median_hours': hours(lead['median_hours'])},
|
'lead': {'orders': lead['orders'], 'median_hours': hours(lead['median_hours'])},
|
||||||
'stage_limits': limits, 'late': late,
|
'stage_limits': limits, 'late': late,
|
||||||
'stages': {row['state']: {'orders': row['orders'], 'passages': row['passages'],
|
'stages': {row['state']: {'orders': row['orders'], 'passages': row['passages'],
|
||||||
|
|||||||
@@ -29,21 +29,20 @@ def price_row(row):
|
|||||||
|
|
||||||
|
|
||||||
def checked_bands(product, bands):
|
def checked_bands(product, bands):
|
||||||
"""The bands the row will store; 422 in Portuguese for anything invalid."""
|
"""The bands the row will store; 422 in Portuguese for anything invalid.
|
||||||
if product == 'tratamento' and bands:
|
Ajuste Fino counts its bands in arts; the other products in metres."""
|
||||||
raise HTTPException(422, 'O tratamento é um valor por pedido: não tem faixas.')
|
|
||||||
if len(bands) > 5:
|
if len(bands) > 5:
|
||||||
raise HTTPException(422, 'Um preço pode ter no máximo 5 faixas.')
|
raise HTTPException(422, 'Um preço pode ter no máximo 5 faixas.')
|
||||||
checked, last = [], None
|
checked, last = [], None
|
||||||
for band in bands:
|
for band in bands:
|
||||||
if not band.from_metres.is_finite() or band.from_metres <= 0:
|
if not band.from_metres.is_finite() or band.from_metres <= 0:
|
||||||
raise HTTPException(422, 'A metragem de cada faixa precisa ser maior que zero.')
|
raise HTTPException(422, 'O início de cada faixa precisa ser maior que zero.')
|
||||||
if band.unit_cents <= 0:
|
if band.unit_cents <= 0:
|
||||||
raise HTTPException(422, 'O preço de cada faixa precisa ser maior que zero.')
|
raise HTTPException(422, 'O preço de cada faixa precisa ser maior que zero.')
|
||||||
if band.unit_cents > 10000000:
|
if band.unit_cents > 10000000:
|
||||||
raise HTTPException(422, 'O preço de cada faixa é alto demais.')
|
raise HTTPException(422, 'O preço de cada faixa é alto demais.')
|
||||||
if last is not None and band.from_metres <= last:
|
if last is not None and band.from_metres <= last:
|
||||||
raise HTTPException(422, 'As faixas precisam estar em ordem crescente de metragem.')
|
raise HTTPException(422, 'As faixas precisam estar em ordem crescente.')
|
||||||
last = band.from_metres
|
last = band.from_metres
|
||||||
checked.append({'from_metres': str(band.from_metres), 'unit_cents': band.unit_cents})
|
checked.append({'from_metres': str(band.from_metres), 'unit_cents': band.unit_cents})
|
||||||
return checked
|
return checked
|
||||||
@@ -247,7 +246,7 @@ def site_grade_rules(user=Depends(can('manage'))):
|
|||||||
@router.post('/api/operator/site/grade-rules')
|
@router.post('/api/operator/site/grade-rules')
|
||||||
def save_grade_rules(body: GradeRules, user=Depends(can('manage'))):
|
def save_grade_rules(body: GradeRules, user=Depends(can('manage'))):
|
||||||
if body.aviso is not None and body.tratamento is not None and body.tratamento > body.aviso:
|
if body.aviso is not None and body.tratamento is not None and body.tratamento > body.aviso:
|
||||||
raise HTTPException(422, 'A regra do tratamento precisa ser menor ou igual à do aviso.')
|
raise HTTPException(422, 'A regra do Ajuste Fino precisa ser menor ou igual à do aviso.')
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
for action, below in (('aviso', body.aviso), ('tratamento', body.tratamento)):
|
for action, below in (('aviso', body.aviso), ('tratamento', body.tratamento)):
|
||||||
if below is None:
|
if below is None:
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
"""The montador's stamp sizes and its invoiced orders (Fase 2, front 7)."""
|
"""The montador's stamp sizes, its brand per stamp, the internal customer and
|
||||||
|
the Interno and Venda orders a sheet becomes (Fase 2, fronts 7a to 7a.3)."""
|
||||||
import hashlib
|
import hashlib
|
||||||
import json
|
import json
|
||||||
|
import re
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||||
@@ -9,12 +11,22 @@ from psycopg.types.json import Jsonb
|
|||||||
from .. import payments, quote_review
|
from .. import payments, quote_review
|
||||||
from ..core import db
|
from ..core import db
|
||||||
from ..core.auth import audit, can
|
from ..core.auth import audit, can
|
||||||
from ..core.models import Freight, MontadorOrder, QuoteRequest, StampSizeTable, UploadStart
|
from ..core.models import (Customer, Freight, MontadorOrder, QuoteRequest, StampBrand,
|
||||||
|
StampSizeTable, UploadStart)
|
||||||
from ..runtime import operator_identity
|
from ..runtime import operator_identity
|
||||||
from .uploads import begin_upload
|
from .uploads import begin_upload
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
|
|
||||||
|
CODE = re.compile(r'^[A-Za-z0-9_-]{1,40}$')
|
||||||
|
INTERNAL_MISSING = 'Peça à Gestão para completar o cliente interno.'
|
||||||
|
# Who chooses which kind of order in the montador (Marcus, 2026-11-10): the
|
||||||
|
# Expedição only Interno, the Vendedor only Venda; Gestão and the
|
||||||
|
# administrators both.
|
||||||
|
MONTADOR_KINDS = {'expedicao': {'interno'}, 'vendedor': {'venda'},
|
||||||
|
'superadmin': {'interno', 'venda'}, 'admin': {'interno', 'venda'},
|
||||||
|
'gestao': {'interno', 'venda'}}
|
||||||
|
|
||||||
|
|
||||||
@router.get('/api/operator/stamp-sizes')
|
@router.get('/api/operator/stamp-sizes')
|
||||||
def stamp_sizes(user=Depends(can('assemble'))):
|
def stamp_sizes(user=Depends(can('assemble'))):
|
||||||
@@ -33,6 +45,63 @@ def save_stamp_sizes(body: StampSizeTable, user=Depends(can('manage'))):
|
|||||||
return {'ok': True}
|
return {'ok': True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get('/api/operator/internal-customer')
|
||||||
|
def read_internal_customer(user=Depends(can('assemble'))):
|
||||||
|
"""The customer every Interno order belongs to; empty fields mean Gestão
|
||||||
|
still has to complete it."""
|
||||||
|
with db.connect() as c:
|
||||||
|
row = c.execute('SELECT name,cnpj,zap,mail FROM dtf_local.internal_customer').fetchone()
|
||||||
|
return row or {'name': '', 'cnpj': '', 'zap': '', 'mail': ''}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/internal-customer')
|
||||||
|
def save_internal_customer(body: Customer, user=Depends(can('manage'))):
|
||||||
|
with db.connect() as c:
|
||||||
|
c.execute('''INSERT INTO dtf_local.internal_customer(id,name,cnpj,zap,mail,updated_by,updated_at)
|
||||||
|
VALUES(1,%s,%s,%s,%s,%s,now()) ON CONFLICT(id) DO UPDATE SET name=EXCLUDED.name,
|
||||||
|
cnpj=EXCLUDED.cnpj, zap=EXCLUDED.zap, mail=EXCLUDED.mail,
|
||||||
|
updated_by=EXCLUDED.updated_by, updated_at=now()''',
|
||||||
|
(body.name, body.cnpj, body.zap, body.mail, user))
|
||||||
|
audit('internal_customer_changed', operator=user)
|
||||||
|
return {'ok': True}
|
||||||
|
|
||||||
|
|
||||||
|
def internal_customer(c):
|
||||||
|
"""The fixed Interno customer, ready to use, or the reason Gestão must
|
||||||
|
complete it first."""
|
||||||
|
row = c.execute('SELECT name,cnpj,zap,mail FROM dtf_local.internal_customer').fetchone()
|
||||||
|
if not row or not all(str(row[key] or '').strip() for key in ('name', 'cnpj', 'zap', 'mail')):
|
||||||
|
raise HTTPException(409, INTERNAL_MISSING)
|
||||||
|
try:
|
||||||
|
return Customer(**row)
|
||||||
|
except ValueError:
|
||||||
|
raise HTTPException(409, INTERNAL_MISSING) from None
|
||||||
|
|
||||||
|
|
||||||
|
@router.get('/api/operator/stamps/{code}')
|
||||||
|
def read_stamp(code: str, user=Depends(can('assemble'))):
|
||||||
|
"""The brand recorded for a stamp code; nothing else uses it yet."""
|
||||||
|
if not CODE.fullmatch(code):
|
||||||
|
raise HTTPException(422, 'Código inválido.')
|
||||||
|
with db.connect() as c:
|
||||||
|
row = c.execute('SELECT code,brand,public FROM dtf_local.stamps WHERE code=%s', (code,)).fetchone()
|
||||||
|
return row or {'code': code, 'brand': '', 'public': False}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/stamps/{code}')
|
||||||
|
def save_stamp(code: str, body: StampBrand, user=Depends(can('manage'))):
|
||||||
|
if not CODE.fullmatch(code):
|
||||||
|
raise HTTPException(422, 'Código inválido.')
|
||||||
|
brand = body.brand.strip()
|
||||||
|
with db.connect() as c:
|
||||||
|
c.execute('''INSERT INTO dtf_local.stamps(code,brand,public,updated_by,updated_at)
|
||||||
|
VALUES(%s,%s,%s,%s,now()) ON CONFLICT(code) DO UPDATE SET brand=EXCLUDED.brand,
|
||||||
|
public=EXCLUDED.public, updated_by=EXCLUDED.updated_by, updated_at=now()''',
|
||||||
|
(code, brand, body.public, user))
|
||||||
|
audit('stamp_brand_saved', code=code, operator=user, public=body.public)
|
||||||
|
return {'ok': True}
|
||||||
|
|
||||||
|
|
||||||
@router.post('/api/operator/montador/uploads')
|
@router.post('/api/operator/montador/uploads')
|
||||||
def montador_upload(body: UploadStart, user=Depends(can('assemble'))):
|
def montador_upload(body: UploadStart, user=Depends(can('assemble'))):
|
||||||
if not body.name.lower().endswith('.png'):
|
if not body.name.lower().endswith('.png'):
|
||||||
@@ -42,16 +111,30 @@ def montador_upload(body: UploadStart, user=Depends(can('assemble'))):
|
|||||||
|
|
||||||
@router.post('/api/operator/montador/orders')
|
@router.post('/api/operator/montador/orders')
|
||||||
def montador_order(body: MontadorOrder, request: Request, user=Depends(can('assemble'))):
|
def montador_order(body: MontadorOrder, request: Request, user=Depends(can('assemble'))):
|
||||||
"""The order a montador sheet becomes, already invoiced (front 7a.2b):
|
"""The card a montador sheet becomes (fronts 7a.3 and 7a.4): Interno (the
|
||||||
typed customer, pickup, the Site's table price, and held out of Tiny until
|
fixed internal customer, origin dropflow, never Tiny) or Venda (a Tiny
|
||||||
Dropstar decides how it is invoiced there."""
|
customer, origin atendimento, invoiced and sent to Tiny), at the Site's
|
||||||
origin = 'dropflow' if request.state.operator['role'] == 'expedicao' else 'atendimento'
|
table price. A Venda is picked up, travels with a clothing order or ships
|
||||||
draft = QuoteRequest(request_key=body.request_key, customer=body.customer, items=body.items,
|
with the Site's freight; approve quotes the freight again."""
|
||||||
freight=Freight(service='pickup')).model_dump(mode='json', exclude={'request_key'})
|
role = request.state.operator['role']
|
||||||
draft['montador'] = True
|
if body.kind not in MONTADOR_KINDS.get(role, set()):
|
||||||
digest = hashlib.sha256(json.dumps(draft, sort_keys=True).encode()).hexdigest()
|
raise HTTPException(403, 'Seu perfil não permite este tipo de pedido.')
|
||||||
owner = operator_identity(user)
|
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
|
if body.kind == 'interno':
|
||||||
|
customer = internal_customer(c)
|
||||||
|
origin, method = 'dropflow', payments.INTERNAL_METHOD
|
||||||
|
else:
|
||||||
|
customer = body.customer
|
||||||
|
origin, method = 'atendimento', payments.INVOICED_METHOD
|
||||||
|
draft = QuoteRequest(request_key=body.request_key, customer=customer, items=body.items,
|
||||||
|
freight=body.freight or Freight(service='pickup'),
|
||||||
|
destination=body.destination).model_dump(mode='json', exclude={'request_key'})
|
||||||
|
draft['montador'] = True
|
||||||
|
draft['kind'] = body.kind
|
||||||
|
if body.with_order:
|
||||||
|
draft['with_order'] = body.with_order
|
||||||
|
digest = hashlib.sha256(json.dumps(draft, sort_keys=True).encode()).hexdigest()
|
||||||
|
owner = operator_identity(user)
|
||||||
c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft)
|
c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft)
|
||||||
VALUES(%s,%s,%s,%s,%s) ON CONFLICT(owner,request_key) DO NOTHING''',
|
VALUES(%s,%s,%s,%s,%s) ON CONFLICT(owner,request_key) DO NOTHING''',
|
||||||
(uuid4(), owner, body.request_key, digest, Jsonb(draft)))
|
(uuid4(), owner, body.request_key, digest, Jsonb(draft)))
|
||||||
@@ -60,12 +143,18 @@ def montador_order(body: MontadorOrder, request: Request, user=Depends(can('asse
|
|||||||
if quote['request_hash'] != digest:
|
if quote['request_hash'] != digest:
|
||||||
raise HTTPException(409, 'A montagem mudou durante o envio. Tente de novo.')
|
raise HTTPException(409, 'A montagem mudou durante o envio. Tente de novo.')
|
||||||
if not quote['approved']:
|
if not quote['approved']:
|
||||||
quote_review.approve(c, quote, body.items, user)
|
approved = quote_review.approve(c, quote, body.items, user)
|
||||||
|
# The order's kind and the clothing order it travels with, on the
|
||||||
|
# card and in Tiny's internal note.
|
||||||
|
approved = {**approved, 'kind': body.kind,
|
||||||
|
**({'with_order': body.with_order} if body.with_order else {})}
|
||||||
|
c.execute('UPDATE dtf_local.quotes SET approved=%s WHERE id=%s',
|
||||||
|
(Jsonb(approved), quote['id']))
|
||||||
quote = c.execute('SELECT * FROM dtf_local.quotes WHERE id=%s', (quote['id'],)).fetchone()
|
quote = c.execute('SELECT * FROM dtf_local.quotes WHERE id=%s', (quote['id'],)).fetchone()
|
||||||
receipt = {'provider': payments.MANUAL_PROVIDER, 'method': payments.INVOICED_METHOD, 'note': '',
|
receipt = {'provider': payments.MANUAL_PROVIDER, 'method': method, 'note': '',
|
||||||
'status': 'paid', 'total_cents': quote['approved']['total_cents'], 'operator': user}
|
'status': 'paid', 'total_cents': quote['approved']['total_cents'], 'operator': user}
|
||||||
order, created = payments.create_order(c, quote, receipt, origin)
|
order, created = payments.create_order(c, quote, receipt, origin)
|
||||||
if not created:
|
if not created:
|
||||||
raise HTTPException(409, f"Esta montagem já virou o pedido #{order['number']}.")
|
raise HTTPException(409, f"Esta montagem já virou o pedido #{order['number']}.")
|
||||||
audit('montador_order_created', order=str(order['id']), origin=origin, operator=user)
|
audit('montador_order_created', order=str(order['id']), origin=origin, kind=body.kind, operator=user)
|
||||||
return order
|
return order
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ from fastapi import APIRouter, Depends, HTTPException, Request
|
|||||||
from starlette.concurrency import run_in_threadpool
|
from starlette.concurrency import run_in_threadpool
|
||||||
|
|
||||||
from ..core import db
|
from ..core import db
|
||||||
from ..core.auth import audit, owner, rate_limit
|
from ..core.auth import audit, client_ip, owner, rate_limit
|
||||||
from ..core.limits import upload_limit_bytes
|
from ..core.limits import upload_limit_bytes
|
||||||
from ..core.models import UploadStart
|
from ..core.models import UploadStart
|
||||||
from ..payments import UNPAID_HOLD
|
from ..payments import UNPAID_HOLD
|
||||||
@@ -20,13 +20,25 @@ from ..runtime import PART_BYTES, storage, upload_row
|
|||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
|
|
||||||
|
# A cart of many files: 66 in Marcus's case (2026-11-11), and adding more or
|
||||||
|
# retrying must fit. The per-source bucket bounds abuse, not a real order.
|
||||||
|
UPLOAD_START_LIMIT = 1000
|
||||||
|
UPLOAD_START_IP_LIMIT = 3000
|
||||||
|
|
||||||
|
|
||||||
|
def upload_ip_limit(request: Request):
|
||||||
|
"""The public upload route's per-source bucket. The operator upload routes
|
||||||
|
reuse begin_upload directly and stay bound by their own session bucket."""
|
||||||
|
rate_limit('upload-start-ip', client_ip(request), UPLOAD_START_IP_LIMIT, 900)
|
||||||
|
|
||||||
|
|
||||||
@router.post('/api/uploads')
|
@router.post('/api/uploads')
|
||||||
def begin_upload(body: UploadStart, session_id=Depends(owner)):
|
def begin_upload(body: UploadStart, session_id=Depends(owner), _source=Depends(upload_ip_limit)):
|
||||||
if body.size > upload_limit_bytes():
|
if body.size > upload_limit_bytes():
|
||||||
raise HTTPException(413, 'O arquivo passa do tamanho máximo aceito. Escolha um arquivo menor.')
|
raise HTTPException(413, 'O arquivo passa do tamanho máximo aceito. Escolha um arquivo menor.')
|
||||||
uid = uuid4()
|
uid = uuid4()
|
||||||
key = f'originals/{uid}'
|
key = f'originals/{uid}'
|
||||||
rate_limit('upload-start', str(session_id), 60, 900)
|
rate_limit('upload-start', str(session_id), UPLOAD_START_LIMIT, 900)
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
# Serialize reservations across API processes, including changing guest IDs.
|
# Serialize reservations across API processes, including changing guest IDs.
|
||||||
c.execute('SELECT pg_advisory_xact_lock(804208)')
|
c.execute('SELECT pg_advisory_xact_lock(804208)')
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ changes it in "Minha senha". The superadmin is the system's own account, set fro
|
|||||||
administrators manage everyone else. Nobody can remove, disable or demote
|
administrators manage everyone else. Nobody can remove, disable or demote
|
||||||
themselves, so the last administrator cannot lock the team out by accident.
|
themselves, so the last administrator cannot lock the team out by accident.
|
||||||
"""
|
"""
|
||||||
|
import os
|
||||||
import re
|
import re
|
||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
from typing import Literal
|
from typing import Literal
|
||||||
@@ -18,7 +19,7 @@ from ..core import db
|
|||||||
from ..core.auth import (CAPABILITIES, MACHINE_QUESTION, audit, can, may_move, may_reorder, password_hash,
|
from ..core.auth import (CAPABILITIES, MACHINE_QUESTION, audit, can, may_move, may_reorder, password_hash,
|
||||||
password_matches, signed_in)
|
password_matches, signed_in)
|
||||||
from ..core.models import StrictModel
|
from ..core.models import StrictModel
|
||||||
from ..runtime import BACK, STATES, TRANSITIONS
|
from ..runtime import BACK, ENVIRONMENT, STATES, TRANSITIONS
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
|
|
||||||
@@ -68,6 +69,10 @@ def me(request: Request):
|
|||||||
moves = [[a, b] for a, nexts in TRANSITIONS.items() for b in nexts if may_move(role, a, b)]
|
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)]
|
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,
|
return {'email': account['email'], 'name': account['name'], 'role': role,
|
||||||
|
# Public by design: the Kanban browser initialises Sentry with these.
|
||||||
|
'sentry_dsn_web': os.environ.get('SENTRY_DSN_WEB', '').strip(),
|
||||||
|
'sentry_environment': os.environ.get('SENTRY_ENVIRONMENT') or ENVIRONMENT,
|
||||||
|
'sentry_release': os.environ.get('IMAGE_TAG', ''),
|
||||||
# The machine this session is on, and whether to ask (item 12).
|
# The machine this session is on, and whether to ask (item 12).
|
||||||
'machine': account['machine'], 'machine_question': MACHINE_QUESTION.get(role),
|
'machine': account['machine'], 'machine_question': MACHINE_QUESTION.get(role),
|
||||||
'machine_answered': account['machine_answered'],
|
'machine_answered': account['machine_answered'],
|
||||||
|
|||||||
@@ -10,11 +10,14 @@ from fastapi import FastAPI
|
|||||||
from fastapi.responses import JSONResponse
|
from fastapi.responses import JSONResponse
|
||||||
from starlette.middleware.trustedhost import TrustedHostMiddleware
|
from starlette.middleware.trustedhost import TrustedHostMiddleware
|
||||||
|
|
||||||
|
from . import observability
|
||||||
from .core import db
|
from .core import db
|
||||||
from .core.auth import audit, client_ip
|
from .core.auth import audit, client_ip
|
||||||
from .runtime import ALLOWED_HOSTS, ALLOWED_ORIGINS, storage
|
from .runtime import ALLOWED_HOSTS, ALLOWED_ORIGINS, storage
|
||||||
from .api import artwork, customer, health, machine_log, operator, orders, payments, quotes, reviews, site_admin, site_videos, stamps, uploads, users
|
from .api import artwork, customer, health, machine_log, operator, orders, payments, quotes, reviews, site_admin, site_videos, stamps, uploads, users
|
||||||
|
|
||||||
|
observability.init('api')
|
||||||
|
|
||||||
|
|
||||||
@asynccontextmanager
|
@asynccontextmanager
|
||||||
async def lifespan(app):
|
async def lifespan(app):
|
||||||
|
|||||||
@@ -11,6 +11,38 @@ from . import catalog, coupons, grade_rules
|
|||||||
from .core import pricing
|
from .core import pricing
|
||||||
|
|
||||||
|
|
||||||
|
def art_pairs(items):
|
||||||
|
"""[item_index, source_index] for every art in the cart: one artwork of
|
||||||
|
loose art, or one sheet file of a ready sheet."""
|
||||||
|
return [[index, source] for index, item in enumerate(items)
|
||||||
|
for source in range(len((item.get('production') or {}).get('sources') or []))]
|
||||||
|
|
||||||
|
|
||||||
|
def chosen_arts(items, choice):
|
||||||
|
"""The arts the draft's treatment selects: all of them for True (old carts
|
||||||
|
and the grade rule), the valid pairs for a list."""
|
||||||
|
if choice is True:
|
||||||
|
return art_pairs(items)
|
||||||
|
if not isinstance(choice, (list, tuple)):
|
||||||
|
return []
|
||||||
|
valid = {tuple(pair) for pair in art_pairs(items)}
|
||||||
|
return [list(pair) for pair in choice
|
||||||
|
if isinstance(pair, (list, tuple)) and len(pair) == 2 and tuple(pair) in valid]
|
||||||
|
|
||||||
|
|
||||||
|
def treatment_price(items, choice, offer):
|
||||||
|
"""Ajuste Fino for the chosen arts, with the row's bands counted in arts.
|
||||||
|
{} when it is not offered or no art is chosen."""
|
||||||
|
if not offer or not offer.get('enabled') or offer.get('unit_cents', 0) <= 0:
|
||||||
|
return {}
|
||||||
|
arts = chosen_arts(items, choice)
|
||||||
|
if not arts:
|
||||||
|
return {}
|
||||||
|
count = len(arts)
|
||||||
|
unit = catalog.band_price(offer['unit_cents'], offer.get('bands') or [], count)
|
||||||
|
return {'cents': unit * count, 'hours': 24, 'arts': count, 'unit_cents': unit}
|
||||||
|
|
||||||
|
|
||||||
def price_items(items, names, catalog_now, manual_extra):
|
def price_items(items, names, catalog_now, manual_extra):
|
||||||
"""Price the items without a database: price() per item with the product's
|
"""Price the items without a database: price() per item with the product's
|
||||||
base price and the manual extra, bill_splits, then the band of each mode's
|
base price and the manual extra, bill_splits, then the band of each mode's
|
||||||
@@ -41,9 +73,9 @@ def price_cart(c, items, names, *, coupon_code=None, customer_document=None,
|
|||||||
wants_treatment=False, treatment_rule=True):
|
wants_treatment=False, treatment_rule=True):
|
||||||
"""Price a cart exactly as an order is charged. Returns
|
"""Price a cart exactly as an order is charged. Returns
|
||||||
{'items': [priced item dicts], 'items_total': int, 'coupon': dict|None,
|
{'items': [priced item dicts], 'items_total': int, 'coupon': dict|None,
|
||||||
'treatment_cents': int, 'grade_flags': dict}.
|
'treatment': dict, 'treatment_cents': int, 'grade_flags': dict}.
|
||||||
Raises HTTPException(422) for a product switched off, a required treatment
|
Raises HTTPException(422) for a product switched off, a required Ajuste
|
||||||
the cart did not ask for, or a refused coupon (the same messages as today).
|
Fino the cart did not ask for, or a refused coupon.
|
||||||
`treatment_rule=False` is for the montador, which assembles the sheet."""
|
`treatment_rule=False` is for the montador, which assembles the sheet."""
|
||||||
from fastapi import HTTPException
|
from fastapi import HTTPException
|
||||||
catalog_now = catalog.current(c)
|
catalog_now = catalog.current(c)
|
||||||
@@ -56,14 +88,15 @@ def price_cart(c, items, names, *, coupon_code=None, customer_document=None,
|
|||||||
flags = grade_rules.triggered(grade_rules.current_rules(c), priced, offered)
|
flags = grade_rules.triggered(grade_rules.current_rules(c), priced, offered)
|
||||||
if not treatment_rule:
|
if not treatment_rule:
|
||||||
flags.pop('tratamento', None)
|
flags.pop('tratamento', None)
|
||||||
if 'tratamento' in flags and not wants_treatment:
|
treatment = treatment_price(items, wants_treatment, offer)
|
||||||
|
if 'tratamento' in flags and not treatment:
|
||||||
raise HTTPException(422, grade_rules.treatment_message(flags['tratamento']))
|
raise HTTPException(422, grade_rules.treatment_message(flags['tratamento']))
|
||||||
coupon = None
|
coupon = None
|
||||||
if coupon_code:
|
if coupon_code:
|
||||||
coupon = coupons.check(c, coupon_code, customer_document, priced)
|
coupon = coupons.check(c, coupon_code, customer_document, priced)
|
||||||
treatment = offer['unit_cents'] if wants_treatment and offer['enabled'] else 0
|
|
||||||
return {'items': priced,
|
return {'items': priced,
|
||||||
'items_total': sum(i['total_cents'] for i in priced),
|
'items_total': sum(i['total_cents'] for i in priced),
|
||||||
'coupon': coupon,
|
'coupon': coupon,
|
||||||
'treatment_cents': treatment,
|
'treatment': treatment,
|
||||||
|
'treatment_cents': treatment.get('cents', 0),
|
||||||
'grade_flags': flags}
|
'grade_flags': flags}
|
||||||
|
|||||||
@@ -2,25 +2,26 @@
|
|||||||
|
|
||||||
Dropstar, 2026-11-05 (Fase 2, front 8): the products and their prices leave the
|
Dropstar, 2026-11-05 (Fase 2, front 8): the products and their prices leave the
|
||||||
code and live in the database, with a start date and a history. `PRICES` in
|
code and live in the database, with a start date and a history. `PRICES` in
|
||||||
app/core/pricing.py stays as the seed and the fallback for the four modes;
|
app/core/pricing.py stays as the seed and the fallback for the five modes;
|
||||||
`treatment_cents()` stays as the fallback for `tratamento`. A price row is never
|
`treatment_cents()` stays as the fallback for `tratamento`. A price row is never
|
||||||
changed or deleted once its start date has passed (the table is the history),
|
changed or deleted once its start date has passed (the table is the history),
|
||||||
and an approved quote keeps the price it was approved with.
|
and an approved quote keeps the price it was approved with.
|
||||||
|
|
||||||
`tratamento` is the designer's treatment (front 5), a fixed amount per order:
|
`tratamento` is Ajuste Fino (front 1a): a price per art, with an optional band
|
||||||
it counts as offered only when it is switched on and priced above zero.
|
by the order's number of arts (front 8.2). It counts as offered only when it is
|
||||||
|
switched on and priced above zero.
|
||||||
|
|
||||||
A price row may carry bands by the order's total metres of that product (front
|
A price row may carry bands by the order's quantity of that product (metres, or
|
||||||
8.2): below the first band the base price, then the highest band reached wins
|
arts for Ajuste Fino): below the first band the base price, then the highest
|
||||||
and the whole quantity is charged at that one price. The bands travel with the
|
band reached wins and the whole quantity is charged at that one price. The
|
||||||
row, so they start and become history with it.
|
bands travel with the row, so they start and become history with it.
|
||||||
"""
|
"""
|
||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
|
|
||||||
from .core import pricing
|
from .core import pricing
|
||||||
|
|
||||||
# The four modes sold by the metre, and the treatment sold per order.
|
# The modes sold by the metre, and the treatment sold per order.
|
||||||
MODES = ('file', 'avulsa', 'uvfile', 'uv')
|
MODES = ('file', 'avulsa', 'uvfile', 'uv', 'premium')
|
||||||
PRODUCTS = (*MODES, 'tratamento')
|
PRODUCTS = (*MODES, 'tratamento')
|
||||||
|
|
||||||
TITLES = {
|
TITLES = {
|
||||||
@@ -28,10 +29,11 @@ TITLES = {
|
|||||||
'avulsa': 'Têxtil artes avulsas',
|
'avulsa': 'Têxtil artes avulsas',
|
||||||
'uvfile': 'UV folha pronta',
|
'uvfile': 'UV folha pronta',
|
||||||
'uv': 'UV artes avulsas',
|
'uv': 'UV artes avulsas',
|
||||||
'tratamento': 'Tratamento pelo designer',
|
'premium': 'Têxtil Premium · 8 passadas',
|
||||||
|
'tratamento': 'Ajuste Fino',
|
||||||
}
|
}
|
||||||
UNITS = {'file': 'metro', 'avulsa': 'metro', 'uvfile': 'metro', 'uv': 'metro',
|
UNITS = {'file': 'metro', 'avulsa': 'metro', 'uvfile': 'metro', 'uv': 'metro',
|
||||||
'tratamento': 'pedido'}
|
'premium': 'metro', 'tratamento': 'arte'}
|
||||||
|
|
||||||
|
|
||||||
def fallback_cents(product: str) -> int:
|
def fallback_cents(product: str) -> int:
|
||||||
@@ -39,15 +41,16 @@ def fallback_cents(product: str) -> int:
|
|||||||
return pricing.treatment_cents() if product == 'tratamento' else pricing.PRICES[product]
|
return pricing.treatment_cents() if product == 'tratamento' else pricing.PRICES[product]
|
||||||
|
|
||||||
|
|
||||||
def band_price(base_cents: int, bands: list, metres: Decimal) -> int:
|
def band_price(base_cents: int, bands: list, quantity: Decimal) -> int:
|
||||||
"""The per-metre price for this quantity: the base, or the highest band
|
"""The unit price for this quantity: the base, or the highest band reached.
|
||||||
reached. The whole quantity is charged at one price, not in steps."""
|
The quantity is metres for a product and arts for Ajuste Fino; the whole
|
||||||
metres = Decimal(str(metres))
|
quantity is charged at one price, not in steps."""
|
||||||
|
quantity = Decimal(str(quantity))
|
||||||
price = base_cents
|
price = base_cents
|
||||||
best = None
|
best = None
|
||||||
for band in bands or []:
|
for band in bands or []:
|
||||||
start = Decimal(str(band['from_metres']))
|
start = Decimal(str(band['from_metres']))
|
||||||
if metres >= start and (best is None or start >= best):
|
if quantity >= start and (best is None or start >= best):
|
||||||
best = start
|
best = start
|
||||||
price = band['unit_cents']
|
price = band['unit_cents']
|
||||||
return price
|
return price
|
||||||
@@ -76,14 +79,14 @@ def unit_cents(c, product: str) -> int:
|
|||||||
return row['unit_cents'] if row else fallback_cents(product)
|
return row['unit_cents'] if row else fallback_cents(product)
|
||||||
|
|
||||||
|
|
||||||
def unit_cents_for(c, product: str, metres: Decimal) -> int:
|
def unit_cents_for(c, product: str, quantity: Decimal) -> int:
|
||||||
"""The current price of one product for this quantity, bands included."""
|
"""The current price of one product for this quantity, bands included."""
|
||||||
row = c.execute('''SELECT unit_cents, bands FROM dtf_local.product_prices
|
row = c.execute('''SELECT unit_cents, bands FROM dtf_local.product_prices
|
||||||
WHERE product=%s AND starts_at <= now()
|
WHERE product=%s AND starts_at <= now()
|
||||||
ORDER BY starts_at DESC, id DESC LIMIT 1''', (product,)).fetchone()
|
ORDER BY starts_at DESC, id DESC LIMIT 1''', (product,)).fetchone()
|
||||||
if not row:
|
if not row:
|
||||||
return fallback_cents(product)
|
return fallback_cents(product)
|
||||||
return band_price(row['unit_cents'], row['bands'], metres)
|
return band_price(row['unit_cents'], row['bands'], quantity)
|
||||||
|
|
||||||
|
|
||||||
def treatment_offered(c) -> bool:
|
def treatment_offered(c) -> bool:
|
||||||
|
|||||||
@@ -164,6 +164,10 @@ CAPABILITIES = {
|
|||||||
# Montar folha (Fase 2, front 7): the new Expedição profile and the seller,
|
# Montar folha (Fase 2, front 7): the new Expedição profile and the seller,
|
||||||
# who gets this one action although otherwise view-only (D-30).
|
# who gets this one action although otherwise view-only (D-30).
|
||||||
'assemble': {'superadmin', 'admin', 'gestao', 'vendedor', 'expedicao'},
|
'assemble': {'superadmin', 'admin', 'gestao', 'vendedor', 'expedicao'},
|
||||||
|
# The 10x15 thermal label at Finalizado (Marcus, 2026-11-10, front 10): the
|
||||||
|
# Revisor who releases the card, the Expedição profile that ships it, and
|
||||||
|
# Gestão, which may stand in for either.
|
||||||
|
'label': {'superadmin', 'admin', 'gestao', 'revisor', 'expedicao'},
|
||||||
}
|
}
|
||||||
|
|
||||||
# Who moves which card (Dropstar's flow, 2026-10-23, and their rules of
|
# Who moves which card (Dropstar's flow, 2026-10-23, and their rules of
|
||||||
|
|||||||
@@ -174,7 +174,7 @@ def check_splits(items):
|
|||||||
|
|
||||||
|
|
||||||
class Item(StrictModel):
|
class Item(StrictModel):
|
||||||
mode: Literal['file','avulsa','uvfile','uv']
|
mode: Literal['file','avulsa','uvfile','uv','premium']
|
||||||
metres: Decimal = Field(gt=0, le=12000)
|
metres: Decimal = Field(gt=0, le=12000)
|
||||||
grade: int = Field(ge=0, le=100, strict=True)
|
grade: int = Field(ge=0, le=100, strict=True)
|
||||||
uploads: list[UUID] = Field(min_length=1, max_length=20)
|
uploads: list[UUID] = Field(min_length=1, max_length=20)
|
||||||
@@ -205,7 +205,7 @@ class Item(StrictModel):
|
|||||||
raise ValueError('Only loose artwork is split into sheets')
|
raise ValueError('Only loose artwork is split into sheets')
|
||||||
if [source.upload_id for source in self.production.sources] != self.uploads:
|
if [source.upload_id for source in self.production.sources] != self.uploads:
|
||||||
raise ValueError('Production sources must match uploaded files in order')
|
raise ValueError('Production sources must match uploaded files in order')
|
||||||
is_sheet = self.mode in ('file', 'uvfile')
|
is_sheet = self.mode in ('file', 'uvfile', 'premium')
|
||||||
# UV is 27 cm wide (Dropstar, 2026-10-28; it was 28,5).
|
# 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')
|
film_width = Decimal('27') if self.mode in ('uvfile', 'uv') else Decimal('57')
|
||||||
if self.production.film_width_cm != film_width:
|
if self.production.film_width_cm != film_width:
|
||||||
@@ -265,8 +265,9 @@ class QuoteRequest(StrictModel):
|
|||||||
destination: Destination | None = None
|
destination: Destination | None = None
|
||||||
# "Quero aprovar uma prova antes de imprimir": the order waits for the customer.
|
# "Quero aprovar uma prova antes de imprimir": the order waits for the customer.
|
||||||
proof: bool = False
|
proof: bool = False
|
||||||
# "Quero o tratamento pelo designer": a fixed service line, when priced (front 5).
|
# Ajuste Fino (front 1a): true selects every art of the cart (old carts and
|
||||||
treatment: bool = False
|
# the grade rule), a list selects [item_index, source_index] arts.
|
||||||
|
treatment: bool | list[tuple[int, int]] = False
|
||||||
# A coupon code typed at checkout (front 8.3); the server prices it.
|
# A coupon code typed at checkout (front 8.3); the server prices it.
|
||||||
coupon: str | None = Field(default=None, max_length=30)
|
coupon: str | None = Field(default=None, max_length=30)
|
||||||
# What the browser measured while the customer built the cart (item 0.12).
|
# What the browser measured while the customer built the cart (item 0.12).
|
||||||
@@ -277,6 +278,19 @@ class QuoteRequest(StrictModel):
|
|||||||
check_splits(self.items)
|
check_splits(self.items)
|
||||||
return self
|
return self
|
||||||
|
|
||||||
|
@model_validator(mode='after')
|
||||||
|
def treatment_arts_exist(self):
|
||||||
|
if isinstance(self.treatment, list):
|
||||||
|
seen = set()
|
||||||
|
for item_index, source_index in self.treatment:
|
||||||
|
if (item_index < 0 or source_index < 0 or item_index >= len(self.items)
|
||||||
|
or source_index >= len(self.items[item_index].production.sources)):
|
||||||
|
raise ValueError('Ajuste Fino: arte não encontrada no pedido.')
|
||||||
|
if (item_index, source_index) in seen:
|
||||||
|
raise ValueError('Ajuste Fino: cada arte aparece uma vez.')
|
||||||
|
seen.add((item_index, source_index))
|
||||||
|
return self
|
||||||
|
|
||||||
@model_validator(mode='after')
|
@model_validator(mode='after')
|
||||||
def destination_matches_freight(self):
|
def destination_matches_freight(self):
|
||||||
if self.freight.service == 'pickup':
|
if self.freight.service == 'pickup':
|
||||||
@@ -289,16 +303,43 @@ class QuoteRequest(StrictModel):
|
|||||||
return self
|
return self
|
||||||
|
|
||||||
class MontadorOrder(StrictModel):
|
class MontadorOrder(StrictModel):
|
||||||
"""What the montador sends (front 7a.2b): the typed customer, pickup only
|
"""What the montador sends (fronts 7a.3 and 7a.4): Interno or Venda, loose
|
||||||
and loose artwork only; the server prices and approves it as a quote."""
|
artwork only; the server prices and approves it as a quote. An Interno
|
||||||
|
order takes the fixed customer from the database, a Venda one the customer
|
||||||
|
picked from Tiny. A Venda ships with the Site's freight or travels with the
|
||||||
|
customer's clothing order; an Interno never ships."""
|
||||||
request_key: UUID
|
request_key: UUID
|
||||||
customer: Customer
|
kind: Literal['interno', 'venda']
|
||||||
|
# Empty for an Interno order: the server reads the internal customer.
|
||||||
|
customer: Customer | None = None
|
||||||
items: list[Item] = Field(min_length=1, max_length=30)
|
items: list[Item] = Field(min_length=1, max_length=30)
|
||||||
|
# A Venda that travels with the customer's clothing order; pickup freight.
|
||||||
|
with_order: int | None = Field(default=None, ge=1, le=999999, strict=True)
|
||||||
|
# A Venda with "Envio": the chosen freight service and the full address.
|
||||||
|
freight: Freight | None = None
|
||||||
|
destination: Destination | None = None
|
||||||
|
|
||||||
@model_validator(mode='after')
|
@model_validator(mode='after')
|
||||||
def loose_art_only(self):
|
def order_kind(self):
|
||||||
if any(item.mode != 'avulsa' for item in self.items):
|
if any(item.mode != 'avulsa' for item in self.items):
|
||||||
raise ValueError('O montador só monta artes avulsas.')
|
raise ValueError('O montador só monta artes avulsas.')
|
||||||
|
if self.kind == 'venda' and self.customer is None:
|
||||||
|
raise ValueError('O pedido de venda precisa do cliente.')
|
||||||
|
delivery = bool(self.freight and self.freight.service != 'pickup')
|
||||||
|
if self.kind == 'interno':
|
||||||
|
if self.with_order is not None:
|
||||||
|
raise ValueError('O pedido interno não tem envio.')
|
||||||
|
if delivery or self.destination is not None:
|
||||||
|
raise ValueError('O pedido interno não tem envio.')
|
||||||
|
elif delivery:
|
||||||
|
if self.with_order is not None:
|
||||||
|
raise ValueError('Escolha retirada, envio ou junto com o pedido de roupa.')
|
||||||
|
if self.destination is None:
|
||||||
|
raise ValueError('O envio precisa do endereço completo.')
|
||||||
|
if self.destination.postal_code != self.freight.postal_code:
|
||||||
|
raise ValueError('O CEP do frete e o do endereço precisam ser o mesmo.')
|
||||||
|
elif self.destination is not None:
|
||||||
|
raise ValueError('Só o pedido com envio tem endereço de entrega.')
|
||||||
return self
|
return self
|
||||||
|
|
||||||
class Review(StrictModel):
|
class Review(StrictModel):
|
||||||
@@ -396,7 +437,7 @@ class CouponNew(StrictModel):
|
|||||||
min_metres: Decimal | None = Field(default=None, gt=0, decimal_places=1)
|
min_metres: Decimal | None = Field(default=None, gt=0, decimal_places=1)
|
||||||
max_uses: int | None = Field(default=None, gt=0, strict=True)
|
max_uses: int | None = Field(default=None, gt=0, strict=True)
|
||||||
max_uses_per_customer: int | None = Field(default=None, gt=0, strict=True)
|
max_uses_per_customer: int | None = Field(default=None, gt=0, strict=True)
|
||||||
product: Literal['file', 'avulsa', 'uvfile', 'uv'] | None = None
|
product: Literal['file', 'avulsa', 'uvfile', 'uv', 'premium'] | None = None
|
||||||
note: str = Field(default='', max_length=1000)
|
note: str = Field(default='', max_length=1000)
|
||||||
|
|
||||||
|
|
||||||
@@ -409,7 +450,7 @@ class CouponUpdate(StrictModel):
|
|||||||
min_metres: Decimal | None = Field(default=None, gt=0, decimal_places=1)
|
min_metres: Decimal | None = Field(default=None, gt=0, decimal_places=1)
|
||||||
max_uses: int | None = Field(default=None, gt=0, strict=True)
|
max_uses: int | None = Field(default=None, gt=0, strict=True)
|
||||||
max_uses_per_customer: int | None = Field(default=None, gt=0, strict=True)
|
max_uses_per_customer: int | None = Field(default=None, gt=0, strict=True)
|
||||||
product: Literal['file', 'avulsa', 'uvfile', 'uv'] | None = None
|
product: Literal['file', 'avulsa', 'uvfile', 'uv', 'premium'] | None = None
|
||||||
note: str | None = Field(default=None, max_length=1000)
|
note: str | None = Field(default=None, max_length=1000)
|
||||||
paused: bool | None = None
|
paused: bool | None = None
|
||||||
|
|
||||||
@@ -528,3 +569,9 @@ class StampSizeTable(StrictModel):
|
|||||||
if len(letters) != len(set(letters)):
|
if len(letters) != len(set(letters)):
|
||||||
raise ValueError('Cada tamanho tem uma letra própria.')
|
raise ValueError('Cada tamanho tem uma letra própria.')
|
||||||
return self
|
return self
|
||||||
|
|
||||||
|
|
||||||
|
class StampBrand(StrictModel):
|
||||||
|
"""The brand recorded per stamp code, for the future catalogue (front 7a.3)."""
|
||||||
|
brand: str = Field(default='', max_length=120)
|
||||||
|
public: bool = False
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import os
|
|||||||
import re
|
import re
|
||||||
from decimal import Decimal, ROUND_CEILING
|
from decimal import Decimal, ROUND_CEILING
|
||||||
|
|
||||||
PRICES = {'file': 1990, 'avulsa': 2190, 'uvfile': 7990, 'uv': 8990}
|
PRICES = {'file': 1990, 'avulsa': 2190, 'uvfile': 7990, 'uv': 8990, 'premium': 3990}
|
||||||
|
|
||||||
# A finished sheet the Site cannot open (CDR, AI, PSD, TIFF) is opened by a
|
# A finished sheet the Site cannot open (CDR, AI, PSD, TIFF) is opened by a
|
||||||
# person before printing. It pays this per metre on top of the product's price
|
# person before printing. It pays this per metre on top of the product's price
|
||||||
@@ -25,7 +25,7 @@ def manual_extra_cents() -> int:
|
|||||||
|
|
||||||
|
|
||||||
def treatment_cents() -> int:
|
def treatment_cents() -> int:
|
||||||
"""The designer's treatment, a fixed amount per order (front 5).
|
"""Ajuste Fino, a fixed amount per art (front 1a).
|
||||||
|
|
||||||
Zero keeps the option hidden: the price is the client's decision, and the
|
Zero keeps the option hidden: the price is the client's decision, and the
|
||||||
server and the Site read the same `TREATMENT_CENTS`.
|
server and the Site read the same `TREATMENT_CENTS`.
|
||||||
|
|||||||
@@ -2,8 +2,8 @@
|
|||||||
|
|
||||||
With no rule nothing changes anywhere. An item triggers a rule when its grade
|
With no rule nothing changes anywhere. An item triggers a rule when its grade
|
||||||
is below the rule's `below`; the order's worst item decides. `aviso` flags the
|
is below the rule's `below`; the order's worst item decides. `aviso` flags the
|
||||||
order for the designer; `tratamento` makes the designer's treatment required,
|
order for the designer; `tratamento` makes Ajuste Fino required, but only while
|
||||||
but only while it is offered (enabled and priced above zero).
|
it is offered (enabled and priced above zero).
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
@@ -29,6 +29,6 @@ def triggered(rules: dict, items, treatment_offered: bool) -> dict:
|
|||||||
|
|
||||||
|
|
||||||
def treatment_message(grade: int) -> str:
|
def treatment_message(grade: int) -> str:
|
||||||
"""The refusal the customer sees when the treatment is required."""
|
"""The refusal the customer sees when Ajuste Fino is required."""
|
||||||
return (f'Sua arte tem nota {grade}: para imprimir com qualidade, o tratamento '
|
return (f'Sua arte tem nota {grade}: para imprimir com qualidade, o Ajuste Fino '
|
||||||
'pelo designer é obrigatório neste pedido.')
|
'é obrigatório neste pedido.')
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
"""Each machine's hot folders (Dropstar's third round, item 10, 2026-10-29/30).
|
"""Each machine's hot folders (Dropstar's third round, item 10, 2026-10-29/30).
|
||||||
|
|
||||||
FlexiPRINT watches 3. Imprimindo/<máquina>/<C1|C2|C3>/ and takes a file out
|
FlexiPRINT watches 3. Imprimindo/<máquina>/<C1|C2|C3|PREMIUM>/ and takes a
|
||||||
of it when it rips. When the operator pulls a card to Imprimindo, its files
|
file out of it when it rips. When the operator pulls a card to Imprimindo, its
|
||||||
go, as a copy, into its machine's folder for the item's contraction class;
|
files go, as a copy, into its machine's folder for the item's contraction
|
||||||
|
class; a premium item always goes to PREMIUM, whichever class it carries;
|
||||||
the order's own file stays in its stage folder. A film over 15 m is several
|
the order's own file stays in its stage folder. A film over 15 m is several
|
||||||
parts (item 13): all on the same machine, in order, never more than two in
|
parts (item 13): all on the same machine, in order, never more than two in
|
||||||
the folder at once. The third is written when Flexi takes the first.
|
the folder at once. The third is written when Flexi takes the first.
|
||||||
@@ -27,6 +28,8 @@ IN_FOLDER = 2
|
|||||||
# A computer that claimed a part and never said it was written.
|
# A computer that claimed a part and never said it was written.
|
||||||
CLAIM_TIMEOUT = timedelta(minutes=10)
|
CLAIM_TIMEOUT = timedelta(minutes=10)
|
||||||
CLASSES = ('C1', 'C2', 'C3')
|
CLASSES = ('C1', 'C2', 'C3')
|
||||||
|
# The premium product's own folder (Dropstar, 2026-11-10, front 3).
|
||||||
|
PREMIUM = 'PREMIUM'
|
||||||
|
|
||||||
|
|
||||||
def contraction(order, index):
|
def contraction(order, index):
|
||||||
@@ -41,6 +44,13 @@ def contraction(order, index):
|
|||||||
return item.get('stroke_class') if item.get('stroke_class') in CLASSES else None
|
return item.get('stroke_class') if item.get('stroke_class') in CLASSES else None
|
||||||
|
|
||||||
|
|
||||||
|
def folder_class(order, index):
|
||||||
|
"""The folder an item's parts go to: PREMIUM for the premium product,
|
||||||
|
whatever contraction class is recorded, else C1/C2/C3."""
|
||||||
|
item = order['snapshot']['items'][index]
|
||||||
|
return PREMIUM if item.get('mode') == 'premium' else contraction(order, index)
|
||||||
|
|
||||||
|
|
||||||
def start(c, order_id):
|
def start(c, order_id):
|
||||||
"""The order entered Imprimindo: its approved finals queue for its
|
"""The order entered Imprimindo: its approved finals queue for its
|
||||||
machine's folder, item by item, part by part."""
|
machine's folder, item by item, part by part."""
|
||||||
@@ -83,7 +93,7 @@ def claim(c, user):
|
|||||||
machine, order = row['machine_id'], row['order_id']
|
machine, order = row['machine_id'], row['order_id']
|
||||||
if row['state'] != 'queued' or order in blocked:
|
if row['state'] != 'queued' or order in blocked:
|
||||||
continue
|
continue
|
||||||
cls = contraction(row, row['item_index'])
|
cls = folder_class(row, row['item_index'])
|
||||||
# A part without its class waits, and the parts after it with it.
|
# A part without its class waits, and the parts after it with it.
|
||||||
if busy.get(machine, 0) >= IN_FOLDER or not cls:
|
if busy.get(machine, 0) >= IN_FOLDER or not cls:
|
||||||
blocked.add(order)
|
blocked.add(order)
|
||||||
|
|||||||
129
app/label.py
Normal file
129
app/label.py
Normal file
@@ -0,0 +1,129 @@
|
|||||||
|
"""The 10x15 cm thermal label printed at Finalizado (Fase 2, front 10).
|
||||||
|
|
||||||
|
Marcus, 2026-11-10: when a card reaches Finalizado the Kanban prints a label on
|
||||||
|
the Zebra ZD220: the Tiny order number, the customer, what the order is, pickup
|
||||||
|
or shipping, when it was released and by which Revisor, and a QR with the Tiny
|
||||||
|
order number only. The server renders the page so its content lives in one
|
||||||
|
place. The QR is an inline SVG from segno; nothing is loaded from outside.
|
||||||
|
|
||||||
|
`label_fields` is pure, for the tests; `label_html` only adds the markup and the
|
||||||
|
QR. Without a Tiny receipt the order keeps its own DTF-<number> as the number
|
||||||
|
and in the QR (an Interno order never reaches Tiny).
|
||||||
|
"""
|
||||||
|
import html
|
||||||
|
from datetime import timezone
|
||||||
|
from decimal import Decimal
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
|
LOCAL = ZoneInfo('America/Sao_Paulo')
|
||||||
|
|
||||||
|
SERVICE_NAMES = {'pac': 'Correios PAC', 'sedex': 'Correios SEDEX', 'jadlog': 'Jadlog'}
|
||||||
|
|
||||||
|
|
||||||
|
def _escape(value):
|
||||||
|
return html.escape(str(value if value is not None else ''), quote=True)
|
||||||
|
|
||||||
|
|
||||||
|
def _metres(items):
|
||||||
|
"""The order's billed metres with a comma and two decimals, as the card shows."""
|
||||||
|
total = sum((Decimal(str(item.get('billed_metres') or item.get('metres') or 0))
|
||||||
|
for item in items), Decimal(0))
|
||||||
|
return f'{total:.2f}'.replace('.', ',')
|
||||||
|
|
||||||
|
|
||||||
|
def _sheets(count):
|
||||||
|
return f'{count} folha' if count == 1 else f'{count} folhas'
|
||||||
|
|
||||||
|
|
||||||
|
def _delivery(snapshot):
|
||||||
|
"""Retirada, Envio with the carrier the card shows, junto com a roupa, or Interno."""
|
||||||
|
if snapshot.get('with_order'):
|
||||||
|
return f"Junto com pedido de roupa nº {snapshot['with_order']}"
|
||||||
|
if snapshot.get('kind') == 'interno':
|
||||||
|
return 'Interno'
|
||||||
|
if snapshot.get('destination'):
|
||||||
|
freight = snapshot.get('freight') or {}
|
||||||
|
service = freight.get('service')
|
||||||
|
return 'Envio · ' + (freight.get('description') or SERVICE_NAMES.get(service) or service or 'Frete')
|
||||||
|
return 'Retirada'
|
||||||
|
|
||||||
|
|
||||||
|
def _customer(snapshot):
|
||||||
|
customer = snapshot.get('customer') or {}
|
||||||
|
destination = snapshot.get('destination') or {}
|
||||||
|
return customer.get('name') or destination.get('recipient') or customer.get('mail') or '—'
|
||||||
|
|
||||||
|
|
||||||
|
def _finished_at(value):
|
||||||
|
if value is None:
|
||||||
|
return ''
|
||||||
|
if value.tzinfo is None:
|
||||||
|
value = value.replace(tzinfo=timezone.utc)
|
||||||
|
return value.astimezone(LOCAL).strftime('%d/%m/%Y %H:%M')
|
||||||
|
|
||||||
|
|
||||||
|
def label_fields(order, tiny_number, finished_at, revisor):
|
||||||
|
"""What the label says, from one order and its Tiny sale receipt."""
|
||||||
|
snapshot = order.get('snapshot') or {}
|
||||||
|
items = snapshot.get('items') or []
|
||||||
|
code = str(tiny_number) if tiny_number else f"DTF-{order['number']}"
|
||||||
|
return {'code': code, 'customer': _customer(snapshot), 'sheets': len(items),
|
||||||
|
'metres': _metres(items), 'delivery': _delivery(snapshot),
|
||||||
|
'finished_at': _finished_at(finished_at), 'revisor': revisor or '—',
|
||||||
|
'qr': code}
|
||||||
|
|
||||||
|
|
||||||
|
def qr_svg(text):
|
||||||
|
"""The QR as an inline SVG, dark on the label's white; segno is pure Python.
|
||||||
|
|
||||||
|
`omitsize` keeps a viewBox and drops the fixed width/height, so the CSS can
|
||||||
|
print it at the label's 30 mm without the modules staying pixel-sized.
|
||||||
|
"""
|
||||||
|
import segno
|
||||||
|
return segno.make_qr(text, error='m').svg_inline(border=1, omitsize=True)
|
||||||
|
|
||||||
|
|
||||||
|
def label_html(fields):
|
||||||
|
"""The printable page: 100 x 150 mm, black on white, no external resources."""
|
||||||
|
code = _escape(fields['code'])
|
||||||
|
# The number is as large as its length allows on the 88 mm of usable width.
|
||||||
|
code_size = 22 if len(str(fields['code'])) <= 7 else 18 if len(str(fields['code'])) <= 9 else 15
|
||||||
|
customer = _escape(fields['customer'])
|
||||||
|
sheets = _escape(_sheets(int(fields['sheets'])))
|
||||||
|
metres = _escape(fields['metres'])
|
||||||
|
delivery = _escape(fields['delivery'])
|
||||||
|
finished = _escape(fields['finished_at'])
|
||||||
|
revisor = _escape(fields['revisor'])
|
||||||
|
return f"""<!doctype html>
|
||||||
|
<html lang="pt-BR">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Etiqueta {code}</title>
|
||||||
|
<style>
|
||||||
|
@page {{ size: 100mm 150mm; margin: 0 }}
|
||||||
|
* {{ box-sizing: border-box }}
|
||||||
|
html, body {{ margin: 0; padding: 0; background: #fff; color: #000 }}
|
||||||
|
body {{ font-family: system-ui, -apple-system, "Segoe UI", Roboto, Arial, sans-serif }}
|
||||||
|
.label {{ width: 100mm; height: 150mm; padding: 6mm 6mm 5mm; display: flex;
|
||||||
|
flex-direction: column; gap: 2mm; overflow: hidden }}
|
||||||
|
.code {{ font-size: {code_size}mm; line-height: .95; font-weight: 800; letter-spacing: -.02em;
|
||||||
|
white-space: nowrap; overflow: hidden }}
|
||||||
|
.customer {{ font-size: 6mm; line-height: 1.15; font-weight: 700 }}
|
||||||
|
.line {{ font-size: 4.6mm; line-height: 1.2 }}
|
||||||
|
.foot {{ font-size: 3.6mm; line-height: 1.35; margin-top: 2mm }}
|
||||||
|
.qr {{ margin-top: auto; display: flex; justify-content: center }}
|
||||||
|
.qr svg {{ width: 30mm; height: 30mm; display: block }}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="label">
|
||||||
|
<div class="code">{code}</div>
|
||||||
|
<div class="customer">{customer}</div>
|
||||||
|
<div class="line">DTF · {sheets} · {metres} m</div>
|
||||||
|
<div class="line">{delivery}</div>
|
||||||
|
<div class="foot"><div>Finalizado em {finished}</div><div>Revisor: {revisor}</div></div>
|
||||||
|
<div class="qr">{qr_svg(fields['qr'])}</div>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
"""
|
||||||
@@ -16,8 +16,9 @@ once, which lets exactly one more card through.
|
|||||||
clean CLEAN_EVERY_METRES printed since the last "clean" event.
|
clean CLEAN_EVERY_METRES printed since the last "clean" event.
|
||||||
align ALIGN_AFTER_FILM_METRES printed since the last film change (a
|
align ALIGN_AFTER_FILM_METRES printed since the last film change (a
|
||||||
supply entry of "film") with no "align" event after it.
|
supply entry of "film") with no "align" event after it.
|
||||||
supply a supply whose estimated stock is at or below the minimum Gestão set
|
supply a supply whose estimated stock is at or below the machine's minimum:
|
||||||
for that machine (no minimum, no alert).
|
the one Gestão typed, or Dropstar's default for that supply (1 roll
|
||||||
|
of film, 1 L of each ink, 5 kg of powder).
|
||||||
|
|
||||||
The supply estimate assumes each entry refills what was used since the one
|
The supply estimate assumes each entry refills what was used since the one
|
||||||
before: the use per metre is the quantity entered over the metres printed in
|
before: the use per metre is the quantity entered over the metres printed in
|
||||||
@@ -40,6 +41,11 @@ SUPPLY_INTERVALS = 3
|
|||||||
SUPPLIES = {'film': ('Filme', 'rolo'), 'ink_c': ('Tinta ciano', 'L'), 'ink_m': ('Tinta magenta', 'L'),
|
SUPPLIES = {'film': ('Filme', 'rolo'), 'ink_c': ('Tinta ciano', 'L'), 'ink_m': ('Tinta magenta', 'L'),
|
||||||
'ink_y': ('Tinta amarela', 'L'), 'ink_k': ('Tinta preta', 'L'), 'ink_w': ('Tinta branca', 'L'),
|
'ink_y': ('Tinta amarela', 'L'), 'ink_k': ('Tinta preta', 'L'), 'ink_w': ('Tinta branca', 'L'),
|
||||||
'powder': ('Poliamida', 'kg')}
|
'powder': ('Poliamida', 'kg')}
|
||||||
|
# Dropstar's fixed minimums (2026-11-10): a machine with no minimum typed uses
|
||||||
|
# these. Units match the supplies: rolls, litres and kilograms.
|
||||||
|
DEFAULT_MINIMUMS = {'film': Decimal('1'), 'ink_c': Decimal('1'), 'ink_m': Decimal('1'),
|
||||||
|
'ink_y': Decimal('1'), 'ink_k': Decimal('1'), 'ink_w': Decimal('1'),
|
||||||
|
'powder': Decimal('5')}
|
||||||
PARTS = {'cap': 'Cap', 'damper': 'Damper', 'head': 'Cabeça de impressão', 'wiper': 'Wiper', 'other': 'Outra peça'}
|
PARTS = {'cap': 'Cap', 'damper': 'Damper', 'head': 'Cabeça de impressão', 'wiper': 'Wiper', 'other': 'Outra peça'}
|
||||||
EVENTS = {'clean': 'Limpeza', 'align': 'Alinhamento da cabeça', 'stop': 'Parada'}
|
EVENTS = {'clean': 'Limpeza', 'align': 'Alinhamento da cabeça', 'stop': 'Parada'}
|
||||||
|
|
||||||
@@ -130,8 +136,13 @@ def estimate(entries, metres_between, metres_since_last, minimum=None):
|
|||||||
'minimum': minimum}
|
'minimum': minimum}
|
||||||
|
|
||||||
|
|
||||||
|
def minimum_for(minimums, item):
|
||||||
|
"""The minimum typed for the machine, or Dropstar's default for that supply."""
|
||||||
|
return minimums.get(item, DEFAULT_MINIMUMS.get(item))
|
||||||
|
|
||||||
|
|
||||||
def supply_low(value):
|
def supply_low(value):
|
||||||
"""Whether an estimate is at or below the machine's minimum (no minimum, no alert)."""
|
"""Whether an estimate is at or below the machine's minimum (typed or default)."""
|
||||||
return bool(value) and value['minimum'] is not None and value['stock'] <= value['minimum']
|
return bool(value) and value['minimum'] is not None and value['stock'] <= value['minimum']
|
||||||
|
|
||||||
|
|
||||||
@@ -151,7 +162,8 @@ def supply_estimates(c, machine_id):
|
|||||||
continue
|
continue
|
||||||
printed = [printed_since(c, machine_id, row['created_at']) for row in rows]
|
printed = [printed_since(c, machine_id, row['created_at']) for row in rows]
|
||||||
between = [printed[index - 1] - printed[index] for index in range(1, len(printed))]
|
between = [printed[index - 1] - printed[index] for index in range(1, len(printed))]
|
||||||
value = estimate([row['quantity'] for row in rows], between, printed[-1], minimums.get(item))
|
value = estimate([row['quantity'] for row in rows], between, printed[-1],
|
||||||
|
minimum_for(minimums, item))
|
||||||
if value is not None:
|
if value is not None:
|
||||||
result[item] = value
|
result[item] = value
|
||||||
return result
|
return result
|
||||||
|
|||||||
@@ -93,7 +93,8 @@ def order_paid(c, order, origin):
|
|||||||
|
|
||||||
|
|
||||||
PRODUCTS = {'file': 'DTF Têxtil · folha montada', 'avulsa': 'DTF Têxtil · artes avulsas',
|
PRODUCTS = {'file': 'DTF Têxtil · folha montada', 'avulsa': 'DTF Têxtil · artes avulsas',
|
||||||
'uvfile': 'DTF UV · folha montada', 'uv': 'DTF UV · artes avulsas'}
|
'uvfile': 'DTF UV · folha montada', 'uv': 'DTF UV · artes avulsas',
|
||||||
|
'premium': 'DTF Têxtil Premium · folha montada'}
|
||||||
|
|
||||||
|
|
||||||
def quote_expired(c, quote, origin):
|
def quote_expired(c, quote, origin):
|
||||||
|
|||||||
24
app/migrations/202611111200_montador-interno-stamps.sql
Normal file
24
app/migrations/202611111200_montador-interno-stamps.sql
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
-- Front 7a.3: a brand per stamp, for the future catalogue, and the montador's
|
||||||
|
-- fixed internal customer. The brand is only recorded here for now; nothing
|
||||||
|
-- else reads it yet (Marcus, 2026-11-10).
|
||||||
|
CREATE TABLE IF NOT EXISTS dtf_local.stamps (
|
||||||
|
code text PRIMARY KEY CHECK (code ~ '^[A-Za-z0-9_-]{1,40}$'),
|
||||||
|
brand text NOT NULL DEFAULT '',
|
||||||
|
public boolean NOT NULL DEFAULT false,
|
||||||
|
updated_by text NOT NULL,
|
||||||
|
updated_at timestamptz NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
-- The one customer every Interno order belongs to (the marketplace's own
|
||||||
|
-- sales). Gestão completes it; until then an Interno order is refused.
|
||||||
|
CREATE TABLE IF NOT EXISTS dtf_local.internal_customer (
|
||||||
|
id integer PRIMARY KEY DEFAULT 1 CHECK (id=1),
|
||||||
|
name text NOT NULL DEFAULT '',
|
||||||
|
cnpj text NOT NULL DEFAULT '',
|
||||||
|
zap text NOT NULL DEFAULT '',
|
||||||
|
mail text NOT NULL DEFAULT '',
|
||||||
|
updated_by text NOT NULL DEFAULT 'sistema',
|
||||||
|
updated_at timestamptz NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
INSERT INTO dtf_local.internal_customer(id,name) VALUES(1,'Nexstar · Marketplace')
|
||||||
|
ON CONFLICT (id) DO NOTHING;
|
||||||
17
app/migrations/202611111200_premium-product.sql
Normal file
17
app/migrations/202611111200_premium-product.sql
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
-- Front 3: the Premium product (Marcus, 2026-11-10), built and switched OFF
|
||||||
|
-- until Dropstar prints the three test sheets and says "testado". The products
|
||||||
|
-- CHECK is the inline constraint of dtf_local.products.id, which Postgres
|
||||||
|
-- named products_id_check; widening a list is a new migration that drops and
|
||||||
|
-- adds that one constraint (never schema.sql).
|
||||||
|
ALTER TABLE dtf_local.products DROP CONSTRAINT IF EXISTS products_id_check;
|
||||||
|
ALTER TABLE dtf_local.products ADD CONSTRAINT products_id_check
|
||||||
|
CHECK (id IN ('file','avulsa','uvfile','uv','premium','tratamento'));
|
||||||
|
|
||||||
|
INSERT INTO dtf_local.products(id, enabled) VALUES ('premium', false)
|
||||||
|
ON CONFLICT (id) DO NOTHING;
|
||||||
|
|
||||||
|
-- A coupon may also target the new product (the Site tab lists every mode).
|
||||||
|
ALTER TABLE dtf_local.coupons DROP CONSTRAINT IF EXISTS coupons_product_check;
|
||||||
|
ALTER TABLE dtf_local.coupons ADD CONSTRAINT coupons_product_check
|
||||||
|
CHECK (product IN ('file','avulsa','uvfile','uv','premium'));
|
||||||
|
|
||||||
12
app/migrations/202611111530_label-prints.sql
Normal file
12
app/migrations/202611111530_label-prints.sql
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
-- Front 10: the 10x15 cm label at Finalizado (Marcus, 2026-11-10). One 'auto'
|
||||||
|
-- print per order, decided by the unique partial index, so two computers
|
||||||
|
-- asking at once cannot both print it; a reprint is always another row.
|
||||||
|
CREATE TABLE IF NOT EXISTS dtf_local.label_prints (
|
||||||
|
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||||
|
order_id uuid NOT NULL REFERENCES dtf_local.orders(id) ON DELETE CASCADE,
|
||||||
|
reason text NOT NULL CHECK (reason IN ('auto','reprint')),
|
||||||
|
printed_by text NOT NULL,
|
||||||
|
printed_at timestamptz NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS label_prints_one_auto
|
||||||
|
ON dtf_local.label_prints(order_id) WHERE reason='auto';
|
||||||
139
app/observability.py
Normal file
139
app/observability.py
Normal file
@@ -0,0 +1,139 @@
|
|||||||
|
"""Sentry for the API and the worker, off until a DSN arrives (note Sentry).
|
||||||
|
|
||||||
|
`init(component)` reads `SENTRY_DSN_API` and returns without importing the SDK
|
||||||
|
when it is empty, so local and CI runs carry no Sentry dependency or network
|
||||||
|
cost. When it is set, `scrub` keeps cookies, credentials, request bodies and
|
||||||
|
Brazilian personal data out of the events (LGPD).
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
|
||||||
|
|
||||||
|
EMAIL = re.compile(r'[^\s@]+@[^\s@]+\.[A-Za-z]{2,}')
|
||||||
|
# CPF (11 digits) or CNPJ (14), with or without punctuation.
|
||||||
|
DOCUMENT = re.compile(r'(?<!\d)(?:\d{2}\.?\d{3}\.?\d{3}/?\d{4}-?\d{2}'
|
||||||
|
r'|\d{3}\.?\d{3}\.?\d{3}-?\d{2})(?!\d)')
|
||||||
|
SENSITIVE_PARAM = re.compile(r'token|signature|x-amz', re.I)
|
||||||
|
SENSITIVE_HEADER = re.compile(r'^(cookie|authorization|x-.*token.*)$', re.I)
|
||||||
|
REDACTED = '[removido]'
|
||||||
|
|
||||||
|
|
||||||
|
def _clean(text):
|
||||||
|
"""Replace e-mail addresses and CPF/CNPJ in one string."""
|
||||||
|
if not isinstance(text, str):
|
||||||
|
return text
|
||||||
|
return DOCUMENT.sub(REDACTED, EMAIL.sub(REDACTED, text))
|
||||||
|
|
||||||
|
|
||||||
|
def _scrub_query(query):
|
||||||
|
"""A query string without token, signature and X-Amz parameters."""
|
||||||
|
if not isinstance(query, str) or not query:
|
||||||
|
return query
|
||||||
|
pairs = parse_qsl(query, keep_blank_values=True)
|
||||||
|
kept = [(key, value) for key, value in pairs if not SENSITIVE_PARAM.search(key)]
|
||||||
|
return query if len(kept) == len(pairs) else urlencode(kept, doseq=True)
|
||||||
|
|
||||||
|
|
||||||
|
def _scrub_url(url):
|
||||||
|
if not isinstance(url, str):
|
||||||
|
return url
|
||||||
|
parts = urlsplit(url)
|
||||||
|
if not parts.query:
|
||||||
|
return url
|
||||||
|
return urlunsplit(parts._replace(query=_scrub_query(parts.query)))
|
||||||
|
|
||||||
|
|
||||||
|
def _scrub_text(value):
|
||||||
|
"""Personal data and a URL query string inside a message or crumb."""
|
||||||
|
value = _clean(value)
|
||||||
|
if not isinstance(value, str) or '?' not in value:
|
||||||
|
return value
|
||||||
|
head, _, query = value.partition('?')
|
||||||
|
return head + '?' + _scrub_query(query)
|
||||||
|
|
||||||
|
|
||||||
|
def _scrub_value(value):
|
||||||
|
if isinstance(value, str):
|
||||||
|
return _scrub_text(value)
|
||||||
|
if isinstance(value, list):
|
||||||
|
return [_scrub_value(item) for item in value]
|
||||||
|
if isinstance(value, dict):
|
||||||
|
return {key: _scrub_value(item) for key, item in value.items()}
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def _scrub_request(request):
|
||||||
|
"""Cookies, credentials, query tokens and bodies never leave the server."""
|
||||||
|
if not isinstance(request, dict):
|
||||||
|
return
|
||||||
|
request.pop('cookies', None)
|
||||||
|
request.pop('data', None)
|
||||||
|
request.pop('body', None)
|
||||||
|
headers = request.get('headers')
|
||||||
|
if isinstance(headers, dict):
|
||||||
|
request['headers'] = {key: value for key, value in headers.items()
|
||||||
|
if not SENSITIVE_HEADER.match(str(key))}
|
||||||
|
if 'query_string' in request:
|
||||||
|
request['query_string'] = _scrub_query(request['query_string'])
|
||||||
|
if 'url' in request:
|
||||||
|
request['url'] = _scrub_url(request['url'])
|
||||||
|
|
||||||
|
|
||||||
|
def scrub(event, hint=None):
|
||||||
|
"""before_send: strip credentials, bodies and personal data from an event."""
|
||||||
|
if not isinstance(event, dict):
|
||||||
|
return event
|
||||||
|
_scrub_request(event.get('request'))
|
||||||
|
if 'message' in event:
|
||||||
|
event['message'] = _scrub_text(event['message'])
|
||||||
|
logentry = event.get('logentry')
|
||||||
|
if isinstance(logentry, dict) and 'message' in logentry:
|
||||||
|
logentry['message'] = _scrub_text(logentry['message'])
|
||||||
|
exception = event.get('exception')
|
||||||
|
if isinstance(exception, dict):
|
||||||
|
for value in exception.get('values') or []:
|
||||||
|
if isinstance(value, dict) and 'value' in value:
|
||||||
|
value['value'] = _scrub_text(value['value'])
|
||||||
|
breadcrumbs = event.get('breadcrumbs')
|
||||||
|
if isinstance(breadcrumbs, dict):
|
||||||
|
breadcrumbs = breadcrumbs.get('values') or []
|
||||||
|
if isinstance(breadcrumbs, list):
|
||||||
|
for crumb in breadcrumbs:
|
||||||
|
if not isinstance(crumb, dict):
|
||||||
|
continue
|
||||||
|
if 'message' in crumb:
|
||||||
|
crumb['message'] = _scrub_text(crumb['message'])
|
||||||
|
if 'data' in crumb:
|
||||||
|
crumb['data'] = _scrub_value(crumb['data'])
|
||||||
|
if 'extra' in event:
|
||||||
|
event['extra'] = _scrub_value(event['extra'])
|
||||||
|
return event
|
||||||
|
|
||||||
|
|
||||||
|
def _traces_rate():
|
||||||
|
try:
|
||||||
|
return float(os.environ.get('SENTRY_TRACES', '0') or 0)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return 0.0
|
||||||
|
|
||||||
|
|
||||||
|
def init(component):
|
||||||
|
"""Start Sentry for this process; False (and no imports) without a DSN."""
|
||||||
|
dsn = os.environ.get('SENTRY_DSN_API', '').strip()
|
||||||
|
if not dsn:
|
||||||
|
return False
|
||||||
|
import sentry_sdk
|
||||||
|
environment = os.environ.get('SENTRY_ENVIRONMENT')
|
||||||
|
if not environment:
|
||||||
|
from .runtime import ENVIRONMENT
|
||||||
|
environment = ENVIRONMENT
|
||||||
|
sentry_sdk.init(
|
||||||
|
dsn=dsn,
|
||||||
|
environment=environment,
|
||||||
|
release=os.environ.get('IMAGE_TAG') or None,
|
||||||
|
send_default_pii=False,
|
||||||
|
traces_sample_rate=_traces_rate(),
|
||||||
|
before_send=scrub,
|
||||||
|
)
|
||||||
|
sentry_sdk.set_tag('component', component)
|
||||||
|
return True
|
||||||
@@ -60,18 +60,19 @@ def is_test(order):
|
|||||||
# (Dropstar's rule D-35, 2026-10-26; the user's answers of 2026-10-27).
|
# (Dropstar's rule D-35, 2026-10-26; the user's answers of 2026-10-27).
|
||||||
MANUAL_PROVIDER = 'manual'
|
MANUAL_PROVIDER = 'manual'
|
||||||
OUTSIDE_METHODS = ('pix', 'card', 'cash', 'credit')
|
OUTSIDE_METHODS = ('pix', 'card', 'cash', 'credit')
|
||||||
# A montador order is invoiced, not paid at the counter: it is not one of the
|
# A montador Venda order is invoiced, not paid at the counter: it is not one of
|
||||||
# Cotações "registrar" methods.
|
# the Cotações "registrar" methods. It goes to Tiny as an approved quote does.
|
||||||
INVOICED_METHOD = 'faturado'
|
INVOICED_METHOD = 'faturado'
|
||||||
|
# A montador Interno order: the marketplace's own sale, already invoiced there.
|
||||||
|
# It stays in house and never reaches Tiny (Marcus, 2026-11-10).
|
||||||
|
INTERNAL_METHOD = 'interno'
|
||||||
|
|
||||||
|
|
||||||
def in_tiny(order):
|
def in_tiny(order):
|
||||||
"""Whether the order goes to Tiny: every order but a test or a proof card
|
"""Whether the order goes to Tiny: every order but an internal one, a test
|
||||||
(app/proof.py), which is no sale. A Dropflow order goes in its own revenue
|
or a proof card (app/proof.py), which is no sale. A Dropflow order goes in
|
||||||
category (app/tiny.py, CATEGORIES)."""
|
its own revenue category (app/tiny.py, CATEGORIES)."""
|
||||||
if (order.get('payment') or {}).get('method') == INVOICED_METHOD:
|
if (order.get('payment') or {}).get('method') == INTERNAL_METHOD:
|
||||||
# Held until Dropstar decides how invoiced montador orders reach Tiny
|
|
||||||
# (asked 2026-11-09).
|
|
||||||
return False
|
return False
|
||||||
return not is_test(order) and not order.get('parent_id')
|
return not is_test(order) and not order.get('parent_id')
|
||||||
|
|
||||||
@@ -153,9 +154,9 @@ def create_order(c, quote, payment, origin):
|
|||||||
proof.create_child(c, order)
|
proof.create_child(c, order)
|
||||||
if is_test(order):
|
if is_test(order):
|
||||||
return order, True
|
return order, True
|
||||||
# An invoiced montador order was not paid: no "pedido pago" e-mail until
|
# An invoiced or internal montador order was not paid here: no "pedido
|
||||||
# Dropstar says what the customer hears (asked 2026-11-09).
|
# pago" e-mail for either (front 7a.3).
|
||||||
if payment.get('method') != INVOICED_METHOD:
|
if payment.get('method') not in (INVOICED_METHOD, INTERNAL_METHOD):
|
||||||
mail.order_paid(c, order, PUBLIC_ORIGIN)
|
mail.order_paid(c, order, PUBLIC_ORIGIN)
|
||||||
if not in_tiny(order):
|
if not in_tiny(order):
|
||||||
return order, True
|
return order, True
|
||||||
|
|||||||
@@ -187,7 +187,7 @@ def render_one(storage):
|
|||||||
(source_ids,)).fetchone()['e']
|
(source_ids,)).fetchone()['e']
|
||||||
by_id = {str(row['id']): row for row in uploads}
|
by_id = {str(row['id']): row for row in uploads}
|
||||||
if job.get('wait_for_treatment'):
|
if job.get('wait_for_treatment'):
|
||||||
finish(job, 'manual', {'reason': 'Tratamento pago: prepare e aprove o PNG completo no pedido pai para gerar a prova.'})
|
finish(job, 'manual', {'reason': 'Ajuste Fino pago: prepare e aprove o PNG completo no pedido pai para gerar a prova.'})
|
||||||
return True
|
return True
|
||||||
if any(row['size'] > LARGE_SOURCE_BYTES and not row['name'].lower().endswith(STREAMED) for row in uploads):
|
if any(row['size'] > LARGE_SOURCE_BYTES and not row['name'].lower().endswith(STREAMED) for row in uploads):
|
||||||
finish(job, 'manual', {'reason': f'arquivo acima de {LARGE_SOURCE_BYTES // 1048576} MB que não é PNG nem PDF: '
|
finish(job, 'manual', {'reason': f'arquivo acima de {LARGE_SOURCE_BYTES // 1048576} MB que não é PNG nem PDF: '
|
||||||
|
|||||||
@@ -74,7 +74,7 @@ def approve(c, row, items, reviewer):
|
|||||||
c, [item.model_dump(mode='json') for item in items], names,
|
c, [item.model_dump(mode='json') for item in items], names,
|
||||||
coupon_code=draft.get('coupon'),
|
coupon_code=draft.get('coupon'),
|
||||||
customer_document=(draft.get('customer') or {}).get('cnpj'),
|
customer_document=(draft.get('customer') or {}).get('cnpj'),
|
||||||
wants_treatment=bool(draft.get('treatment')),
|
wants_treatment=draft.get('treatment', False),
|
||||||
treatment_rule=not draft.get('montador'))
|
treatment_rule=not draft.get('montador'))
|
||||||
# Keep the review snapshot's own fields with each priced item.
|
# Keep the review snapshot's own fields with each priced item.
|
||||||
priced = cart['items']
|
priced = cart['items']
|
||||||
@@ -99,7 +99,7 @@ def approve(c, row, items, reviewer):
|
|||||||
coupon = cart['coupon']
|
coupon = cart['coupon']
|
||||||
discount = coupon['discount_cents'] if coupon else 0
|
discount = coupon['discount_cents'] if coupon else 0
|
||||||
flags = cart['grade_flags']
|
flags = cart['grade_flags']
|
||||||
treatment = cart['treatment_cents']
|
treatment = cart['treatment']
|
||||||
metres = sum(Decimal(i['billed_metres']) for i in priced)
|
metres = sum(Decimal(i['billed_metres']) for i in priced)
|
||||||
try:
|
try:
|
||||||
quoted_freight = freight.quote(draft['freight']['service'], draft['freight'].get('postal_code', ''),
|
quoted_freight = freight.quote(draft['freight']['service'], draft['freight'].get('postal_code', ''),
|
||||||
@@ -110,15 +110,16 @@ def approve(c, row, items, reviewer):
|
|||||||
'destination': draft.get('destination'),
|
'destination': draft.get('destination'),
|
||||||
# The customer's proof only above 10 m (Dropstar, 2026-10-28).
|
# The customer's proof only above 10 m (Dropstar, 2026-10-28).
|
||||||
**({'proof': True} if draft.get('proof') and metres > PROOF_ABOVE_METRES else {}),
|
**({'proof': True} if draft.get('proof') and metres > PROOF_ABOVE_METRES else {}),
|
||||||
# Designer treatment is one fixed service line (front 5).
|
# Ajuste Fino: per art, with the row's band (front 1a).
|
||||||
**({'treatment': {'cents': treatment, 'hours': 24}} if treatment else {}),
|
**({'treatment': treatment} if treatment else {}),
|
||||||
# The art grade decision stored with the quote (front 8.5).
|
# The art grade decision stored with the quote (front 8.5).
|
||||||
**({'grade_flags': flags} if flags else {}),
|
**({'grade_flags': flags} if flags else {}),
|
||||||
# The coupon used, for the order card, Números and Tiny (front 8.3).
|
# The coupon used, for the order card, Números and Tiny (front 8.3).
|
||||||
**({'coupon': coupon} if coupon else {}),
|
**({'coupon': coupon} if coupon else {}),
|
||||||
# Browser timings are kept for Números, never for the price (0.12).
|
# Browser timings are kept for Números, never for the price (0.12).
|
||||||
**({'timings': draft['timings']} if draft.get('timings') else {}),
|
**({'timings': draft['timings']} if draft.get('timings') else {}),
|
||||||
'total_cents': items_total - discount + quoted_freight['total_cents'] + treatment}
|
'total_cents': items_total - discount + quoted_freight['total_cents']
|
||||||
|
+ treatment.get('cents', 0)}
|
||||||
c.execute('UPDATE dtf_local.quotes SET approved=%s, reviewed_by=%s, approved_at=now() WHERE id=%s',
|
c.execute('UPDATE dtf_local.quotes SET approved=%s, reviewed_by=%s, approved_at=now() WHERE id=%s',
|
||||||
(Jsonb(approved), reviewer, row['id']))
|
(Jsonb(approved), reviewer, row['id']))
|
||||||
# Approved and payable now: the files wait for the payment, not for ever.
|
# Approved and payable now: the files wait for the payment, not for ever.
|
||||||
|
|||||||
@@ -21,7 +21,8 @@ MARGIN = 4 * MM
|
|||||||
ROOM = WIDTH - 2 * MARGIN
|
ROOM = WIDTH - 2 * MARGIN
|
||||||
FONTS = {'F1': 'Helvetica-Bold', 'F2': 'Helvetica'}
|
FONTS = {'F1': 'Helvetica-Bold', 'F2': 'Helvetica'}
|
||||||
PRODUCTS = {'file': 'DTF Têxtil · folha montada', 'avulsa': 'DTF Têxtil · artes avulsas',
|
PRODUCTS = {'file': 'DTF Têxtil · folha montada', 'avulsa': 'DTF Têxtil · artes avulsas',
|
||||||
'uvfile': 'DTF UV · folha montada', 'uv': 'DTF UV · artes avulsas'}
|
'uvfile': 'DTF UV · folha montada', 'uv': 'DTF UV · artes avulsas',
|
||||||
|
'premium': 'DTF Têxtil Premium · folha montada'}
|
||||||
METHODS = {'pix': 'Pix', 'card': 'Cartão', 'cash': 'Dinheiro', 'credit': 'Crédito do cliente'}
|
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.
|
# Helvetica's widths for what the tables in printfile.py leave out.
|
||||||
EXTRA = {'$': 556, '(': 333, ')': 333, '_': 556, '#': 556, '—': 1000, '@': 1015, '&': 667, '+': 584, "'": 191}
|
EXTRA = {'$': 556, '(': 333, ')': 333, '_': 556, '#': 556, '—': 1000, '@': 1015, '&': 667, '+': 584, "'": 191}
|
||||||
|
|||||||
@@ -142,9 +142,9 @@ def quote_view(c, row, order=None, attempt=None, known=False):
|
|||||||
items = (row['approved'] or row['draft']).get('items') or []
|
items = (row['approved'] or row['draft']).get('items') or []
|
||||||
treatment = (row['approved'] or {}).get('treatment')
|
treatment = (row['approved'] or {}).get('treatment')
|
||||||
if not treatment and (row['draft'] or {}).get('treatment'):
|
if not treatment and (row['draft'] or {}).get('treatment'):
|
||||||
offer = catalog.current(c)['tratamento']
|
from .cart_pricing import treatment_price
|
||||||
if offer['enabled'] and offer['unit_cents'] > 0:
|
treatment = treatment_price(items, (row['draft'] or {}).get('treatment'),
|
||||||
treatment = {'cents': offer['unit_cents'], 'hours': 24}
|
catalog.current(c)['tratamento']) or None
|
||||||
return {'id': row['id'], 'created_at': row['created_at'],
|
return {'id': row['id'], 'created_at': row['created_at'],
|
||||||
'draft': row['draft'], 'approved': row['approved'],
|
'draft': row['draft'], 'approved': row['approved'],
|
||||||
'expires_at': expires_at.isoformat() if expires_at else None,
|
'expires_at': expires_at.isoformat() if expires_at else None,
|
||||||
|
|||||||
75
app/tiny.py
75
app/tiny.py
@@ -59,29 +59,34 @@ AUTH = 'https://accounts.tiny.com.br/realms/tiny/protocol/openid-connect'
|
|||||||
# Not TINY_PRODUCT_<MODE>: app/core/secrets.py reads any variable ending in
|
# Not TINY_PRODUCT_<MODE>: app/core/secrets.py reads any variable ending in
|
||||||
# _FILE as a path to a secret file, and one product mode is called "file".
|
# _FILE as a path to a secret file, and one product mode is called "file".
|
||||||
PRODUCT_SETTINGS = {'file': 'TINY_PRODUCT_TEXTIL_FOLHA', 'avulsa': 'TINY_PRODUCT_TEXTIL_AVULSA',
|
PRODUCT_SETTINGS = {'file': 'TINY_PRODUCT_TEXTIL_FOLHA', 'avulsa': 'TINY_PRODUCT_TEXTIL_AVULSA',
|
||||||
'uvfile': 'TINY_PRODUCT_UV_FOLHA', 'uv': 'TINY_PRODUCT_UV_AVULSA'}
|
'uvfile': 'TINY_PRODUCT_UV_FOLHA', 'uv': 'TINY_PRODUCT_UV_AVULSA',
|
||||||
|
'premium': 'TINY_PRODUCT_TEXTIL_PREMIUM'}
|
||||||
# The common code prefix of a mode's SKUs ("DTFIMP.TX" for DTFIMP.TX.100CM,
|
# The common code prefix of a mode's SKUs ("DTFIMP.TX" for DTFIMP.TX.100CM,
|
||||||
# the metre, and DTFIMP.TX.0010CM to DTFIMP.TX.0090CM). When set, it replaces
|
# the metre, and DTFIMP.TX.0010CM to DTFIMP.TX.0090CM). When set, it replaces
|
||||||
# the mode's product id.
|
# the mode's product id.
|
||||||
SKU_SETTINGS = {'file': 'TINY_SKU_TEXTIL_FOLHA', 'avulsa': 'TINY_SKU_TEXTIL_AVULSA',
|
SKU_SETTINGS = {'file': 'TINY_SKU_TEXTIL_FOLHA', 'avulsa': 'TINY_SKU_TEXTIL_AVULSA',
|
||||||
'uvfile': 'TINY_SKU_UV_FOLHA', 'uv': 'TINY_SKU_UV_AVULSA'}
|
'uvfile': 'TINY_SKU_UV_FOLHA', 'uv': 'TINY_SKU_UV_AVULSA',
|
||||||
|
'premium': 'TINY_SKU_TEXTIL_PREMIUM'}
|
||||||
# Or a SKU per 10 cm ("DTFIMP.UV.010CM"), alone (2,30 m is 23 of it) or after
|
# Or a SKU per 10 cm ("DTFIMP.UV.010CM"), alone (2,30 m is 23 of it) or after
|
||||||
# a metre SKU ("DTFIMP.UV.1MT"): 2,30 m is 2 metres and 3 of the 10 cm.
|
# a metre SKU ("DTFIMP.UV.1MT"): 2,30 m is 2 metres and 3 of the 10 cm.
|
||||||
STEP_SETTINGS = {'file': 'TINY_SKU10_TEXTIL_FOLHA', 'avulsa': 'TINY_SKU10_TEXTIL_AVULSA',
|
STEP_SETTINGS = {'file': 'TINY_SKU10_TEXTIL_FOLHA', 'avulsa': 'TINY_SKU10_TEXTIL_AVULSA',
|
||||||
'uvfile': 'TINY_SKU10_UV_FOLHA', 'uv': 'TINY_SKU10_UV_AVULSA'}
|
'uvfile': 'TINY_SKU10_UV_FOLHA', 'uv': 'TINY_SKU10_UV_AVULSA',
|
||||||
|
'premium': 'TINY_SKU10_TEXTIL_PREMIUM'}
|
||||||
METRE_SETTINGS = {'file': 'TINY_SKU_METRO_TEXTIL_FOLHA', 'avulsa': 'TINY_SKU_METRO_TEXTIL_AVULSA',
|
METRE_SETTINGS = {'file': 'TINY_SKU_METRO_TEXTIL_FOLHA', 'avulsa': 'TINY_SKU_METRO_TEXTIL_AVULSA',
|
||||||
'uvfile': 'TINY_SKU_METRO_UV_FOLHA', 'uv': 'TINY_SKU_METRO_UV_AVULSA'}
|
'uvfile': 'TINY_SKU_METRO_UV_FOLHA', 'uv': 'TINY_SKU_METRO_UV_AVULSA',
|
||||||
|
'premium': 'TINY_SKU_METRO_TEXTIL_PREMIUM'}
|
||||||
# Dropstar's own catalogue (checked against its Tiny export, 2026-10-14): Têxtil
|
# Dropstar's own catalogue (checked against its Tiny export, 2026-10-14): Têxtil
|
||||||
# as DTFIMP.TX.100CM per metre and DTFIMP.TX.0010CM to 0090CM for the rest, UV
|
# as DTFIMP.TX.100CM per metre and DTFIMP.TX.0010CM to 0090CM for the rest, UV
|
||||||
# as DTFIMP.UV.1MT per metre and DTFIMP.UV.010CM per 10 cm, the ready sheet and
|
# as DTFIMP.UV.1MT per metre and DTFIMP.UV.010CM per 10 cm, the ready sheet and
|
||||||
# loose artwork alike. The settings above only override these.
|
# loose artwork alike. The settings above only override these.
|
||||||
SKU_DEFAULTS = {'file': 'DTFIMP.TX', 'avulsa': 'DTFIMP.TX'}
|
SKU_DEFAULTS = {'file': 'DTFIMP.TX', 'avulsa': 'DTFIMP.TX', 'premium': 'DTFIMP.TXP'}
|
||||||
STEP_DEFAULTS = {'uvfile': 'DTFIMP.UV.010CM', 'uv': 'DTFIMP.UV.010CM'}
|
STEP_DEFAULTS = {'uvfile': 'DTFIMP.UV.010CM', 'uv': 'DTFIMP.UV.010CM'}
|
||||||
METRE_DEFAULTS = {'uvfile': 'DTFIMP.UV.1MT', 'uv': 'DTFIMP.UV.1MT'}
|
METRE_DEFAULTS = {'uvfile': 'DTFIMP.UV.1MT', 'uv': 'DTFIMP.UV.1MT'}
|
||||||
PRODUCTS = {'file': 'DTF Têxtil 57 cm · folha montada',
|
PRODUCTS = {'file': 'DTF Têxtil 57 cm · folha montada',
|
||||||
'avulsa': 'DTF Têxtil 57 cm · artes avulsas',
|
'avulsa': 'DTF Têxtil 57 cm · artes avulsas',
|
||||||
'uvfile': 'DTF UV 27 cm · folha montada',
|
'uvfile': 'DTF UV 27 cm · folha montada',
|
||||||
'uv': 'DTF UV 27 cm · artes avulsas'}
|
'uv': 'DTF UV 27 cm · artes avulsas',
|
||||||
|
'premium': 'DTF Têxtil Premium 57 cm · folha montada'}
|
||||||
# How far back to look for an order a previous delivery may already have made.
|
# How far back to look for an order a previous delivery may already have made.
|
||||||
SEARCH_DAYS = 7
|
SEARCH_DAYS = 7
|
||||||
# A "ready" event can come after corrections; it normally knows the Tiny id.
|
# A "ready" event can come after corrections; it normally knows the Tiny id.
|
||||||
@@ -103,8 +108,19 @@ OUTSIDE_NOTES = {'pix': 'Pix', 'card': 'cartão', 'cash': 'dinheiro', 'credit':
|
|||||||
|
|
||||||
def internal_note(payload):
|
def internal_note(payload):
|
||||||
paid = payload.get('payment') or {}
|
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'
|
method = paid.get('method')
|
||||||
return f"{ORIGIN_NOTES.get(payload.get('origin') or 'site')} · {how} · {payload['order_id']}"
|
if method == 'faturado':
|
||||||
|
# A montador Venda order is invoiced (front 7a.3): its forma de
|
||||||
|
# recebimento is "Boleto" when the client's id is configured.
|
||||||
|
boleto = os.environ.get('TINY_RECEIPT_BOLETO', '').strip()
|
||||||
|
how = 'faturado (Boleto)' if boleto.isdigit() else 'faturado: forma de recebimento a definir'
|
||||||
|
else:
|
||||||
|
how = f"pago fora do site ({OUTSIDE_NOTES.get(method, method)})" if paid.get('outside') else 'pago'
|
||||||
|
note = f"{ORIGIN_NOTES.get(payload.get('origin') or 'site')} · {how} · {payload['order_id']}"
|
||||||
|
with_order = (payload.get('order') or {}).get('with_order')
|
||||||
|
if with_order:
|
||||||
|
note += f' · junto com o pedido de roupa nº {with_order}'
|
||||||
|
return note
|
||||||
|
|
||||||
|
|
||||||
STATUS_UPDATES_SETTING = 'TINY_STATUS_UPDATES'
|
STATUS_UPDATES_SETTING = 'TINY_STATUS_UPDATES'
|
||||||
@@ -119,8 +135,12 @@ PICKUP_EXACT = 'retirar pessoalmente'
|
|||||||
# looked up: Pix and credit card, as the store's orders are paid, and the
|
# looked up: Pix and credit card, as the store's orders are paid, and the
|
||||||
# DropStar carrier its pickup orders name. Dinheiro and, for the customer's
|
# 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
|
# 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).
|
# the orders the team registers as paid outside the site (D-35). "Boleto" is
|
||||||
RECEIPT_METHODS = {'pix': 919478952, 'card': 977460722, 'cash': 919478944, 'credit': 977493654}
|
# for a montador Venda order (front 7a.3); no id is known yet, and while
|
||||||
|
# TINY_RECEIPT_BOLETO is empty the order goes without a forma de recebimento.
|
||||||
|
_BOLETO = os.environ.get('TINY_RECEIPT_BOLETO', '').strip()
|
||||||
|
RECEIPT_METHODS = {'pix': 919478952, 'card': 977460722, 'cash': 919478944, 'credit': 977493654,
|
||||||
|
**({'faturado': int(_BOLETO)} if _BOLETO.isdigit() else {})}
|
||||||
PICKUP_CARRIER = 761565838
|
PICKUP_CARRIER = 761565838
|
||||||
# Dropstar's answers: the financial category "DTF SITE" (RECEITAS, id sent on
|
# 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
|
# 2026-10-26; it goes in pagamento.categoria, and replaced the store's
|
||||||
@@ -438,6 +458,30 @@ def search_forms(document):
|
|||||||
return list(dict.fromkeys((punctuated(d), d)))
|
return list(dict.fromkeys((punctuated(d), d)))
|
||||||
|
|
||||||
|
|
||||||
|
def search_contacts(orders, query, limit=10):
|
||||||
|
"""Up to `limit` contacts matching what was typed (the montador's typeahead,
|
||||||
|
front 7a.3): by CPF/CNPJ when it is only digits and punctuation, else by
|
||||||
|
name. Tiny's own search does the matching."""
|
||||||
|
text = str(query or '').strip()
|
||||||
|
digits = ''.join(ch for ch in text if ch.isdigit())
|
||||||
|
found = []
|
||||||
|
if digits and not any(ch.isalpha() for ch in text):
|
||||||
|
for form in search_forms(digits):
|
||||||
|
found += orders.request('GET', '/contatos', params={'cpfCnpj': form, 'limit': limit}).get('itens') or []
|
||||||
|
else:
|
||||||
|
found = orders.request('GET', '/contatos', params={'nome': text, 'limit': limit}).get('itens') or []
|
||||||
|
contacts, seen = [], set()
|
||||||
|
for entry in found:
|
||||||
|
if entry.get('id') in seen:
|
||||||
|
continue
|
||||||
|
seen.add(entry.get('id'))
|
||||||
|
contacts.append({'id': entry.get('id'), 'name': entry.get('nome') or '',
|
||||||
|
'document': entry.get('cpfCnpj') or '',
|
||||||
|
'email': entry.get('email') or '',
|
||||||
|
'phone': entry.get('telefone') or entry.get('celular') or ''})
|
||||||
|
return contacts[:limit]
|
||||||
|
|
||||||
|
|
||||||
def contact_payload(order, company=None):
|
def contact_payload(order, company=None):
|
||||||
"""A new contact, named after the company's razão social when the
|
"""A new contact, named after the company's razão social when the
|
||||||
registry gave it (app/cnpj.py), else the customer's name, else the
|
registry gave it (app/cnpj.py), else the customer's name, else the
|
||||||
@@ -506,9 +550,14 @@ def order_payload(payload, contact_id, today=None, product_id=None, shipping=Non
|
|||||||
setting = os.environ.get('TINY_PRODUCT_TREATMENT', '')
|
setting = os.environ.get('TINY_PRODUCT_TREATMENT', '')
|
||||||
if not setting.isdigit():
|
if not setting.isdigit():
|
||||||
raise TinyError('TINY_PRODUCT_TREATMENT must be the Tiny product id')
|
raise TinyError('TINY_PRODUCT_TREATMENT must be the Tiny product id')
|
||||||
items.append({'produto': {'id': int(setting)}, 'quantidade': 1,
|
# Per art (front 1a): the line carries the band unit price and the arts
|
||||||
'valorUnitario': money(treatment['cents']),
|
# as its quantity. An old quote without those keeps one art at its total.
|
||||||
'infoAdicional': 'Tratamento da arte pelo designer · +24 h'})
|
arts = int(treatment.get('arts') or 1)
|
||||||
|
unit = int(treatment.get('unit_cents') or treatment['cents'])
|
||||||
|
items.append({'produto': {'id': int(setting)}, 'quantidade': arts,
|
||||||
|
'valorUnitario': money(unit),
|
||||||
|
'infoAdicional': 'Ajuste Fino · '+str(arts)+
|
||||||
|
(' arte' if arts == 1 else ' artes')+' · +24 h'})
|
||||||
freight = order['freight']
|
freight = order['freight']
|
||||||
service = freight.get('service')
|
service = freight.get('service')
|
||||||
pickup = service == 'pickup'
|
pickup = service == 'pickup'
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import threading
|
|||||||
import time
|
import time
|
||||||
from http.server import BaseHTTPRequestHandler, HTTPServer
|
from http.server import BaseHTTPRequestHandler, HTTPServer
|
||||||
from psycopg.types.json import Jsonb
|
from psycopg.types.json import Jsonb
|
||||||
from . import mail, unpaid
|
from . import mail, observability, unpaid
|
||||||
from .adapters import FakeTiny, LocalS3Storage, require_runtime
|
from .adapters import FakeTiny, LocalS3Storage, require_runtime
|
||||||
from .core.secrets import load as load_secret_files
|
from .core.secrets import load as load_secret_files
|
||||||
from .core.db import connect
|
from .core.db import connect
|
||||||
@@ -162,6 +162,7 @@ class Health(BaseHTTPRequestHandler):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
|
observability.init('worker')
|
||||||
scan_thread = threading.Thread(target=scan_loop,args=(storage,),daemon=True)
|
scan_thread = threading.Thread(target=scan_loop,args=(storage,),daemon=True)
|
||||||
scan_thread.start()
|
scan_thread.start()
|
||||||
render_thread = threading.Thread(target=render_loop,args=(storage,),daemon=True)
|
render_thread = threading.Thread(target=render_loop,args=(storage,),daemon=True)
|
||||||
|
|||||||
@@ -27,6 +27,10 @@ x-app: &app
|
|||||||
ALLOWED_HOSTS: ${ALLOWED_HOSTS:-localhost,127.0.0.1}
|
ALLOWED_HOSTS: ${ALLOWED_HOSTS:-localhost,127.0.0.1}
|
||||||
ALLOWED_ORIGINS: ${ALLOWED_ORIGINS:-http://localhost:${SITE_PORT:-8080},http://localhost:${KANBAN_PORT:-8081},http://127.0.0.1:${SITE_PORT:-8080},http://127.0.0.1:${KANBAN_PORT:-8081}}
|
ALLOWED_ORIGINS: ${ALLOWED_ORIGINS:-http://localhost:${SITE_PORT:-8080},http://localhost:${KANBAN_PORT:-8081},http://127.0.0.1:${SITE_PORT:-8080},http://127.0.0.1:${KANBAN_PORT:-8081}}
|
||||||
COOKIE_SECURE: "false"
|
COOKIE_SECURE: "false"
|
||||||
|
# Sentry stays off locally unless real DSNs are set in .env.
|
||||||
|
SENTRY_DSN_API: ${SENTRY_DSN_API:-}
|
||||||
|
SENTRY_DSN_WEB: ${SENTRY_DSN_WEB:-}
|
||||||
|
SENTRY_ENVIRONMENT: ${SENTRY_ENVIRONMENT:-}
|
||||||
# Sandbox testing only: set PAYMENT_ADAPTER=mercadopago with the MP_* test
|
# Sandbox testing only: set PAYMENT_ADAPTER=mercadopago with the MP_* test
|
||||||
# credentials, or TINY_ADAPTER=tiny with a TINY_TOKEN, in .env. Never real
|
# credentials, or TINY_ADAPTER=tiny with a TINY_TOKEN, in .env. Never real
|
||||||
# production credentials on a developer machine.
|
# production credentials on a developer machine.
|
||||||
@@ -274,6 +278,7 @@ services:
|
|||||||
# Empty unless testing Mercado Pago's card form; see docs/LOCAL_SETUP.md.
|
# Empty unless testing Mercado Pago's card form; see docs/LOCAL_SETUP.md.
|
||||||
PAYMENT_CSP_SOURCES: ${PAYMENT_CSP_SOURCES:-}
|
PAYMENT_CSP_SOURCES: ${PAYMENT_CSP_SOURCES:-}
|
||||||
PAYMENT_CHALLENGE_SOURCES: ${PAYMENT_CHALLENGE_SOURCES:-}
|
PAYMENT_CHALLENGE_SOURCES: ${PAYMENT_CHALLENGE_SOURCES:-}
|
||||||
|
SENTRY_CSP_SOURCES: ""
|
||||||
ports:
|
ports:
|
||||||
# Published ports are host-wide even bound to loopback, so on a shared
|
# Published ports are host-wide even bound to loopback, so on a shared
|
||||||
# machine any of them can collide with something unrelated. CI overrides
|
# machine any of them can collide with something unrelated. CI overrides
|
||||||
@@ -299,6 +304,7 @@ services:
|
|||||||
S3_PUBLIC_ENDPOINT: ${S3_PUBLIC_ENDPOINT:-http://localhost:${STORAGE_PORT:-9000}}
|
S3_PUBLIC_ENDPOINT: ${S3_PUBLIC_ENDPOINT:-http://localhost:${STORAGE_PORT:-9000}}
|
||||||
PAYMENT_CSP_SOURCES: ""
|
PAYMENT_CSP_SOURCES: ""
|
||||||
PAYMENT_CHALLENGE_SOURCES: ""
|
PAYMENT_CHALLENGE_SOURCES: ""
|
||||||
|
SENTRY_CSP_SOURCES: ""
|
||||||
ports: ["127.0.0.1:${KANBAN_PORT:-8081}:80"]
|
ports: ["127.0.0.1:${KANBAN_PORT:-8081}:80"]
|
||||||
networks: [local, edge]
|
networks: [local, edge]
|
||||||
depends_on:
|
depends_on:
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ server {
|
|||||||
add_header Referrer-Policy no-referrer always;
|
add_header Referrer-Policy no-referrer always;
|
||||||
add_header X-Frame-Options DENY always;
|
add_header X-Frame-Options DENY always;
|
||||||
add_header Permissions-Policy "camera=(self), microphone=(), geolocation=()" always;
|
add_header Permissions-Policy "camera=(self), microphone=(), geolocation=()" always;
|
||||||
add_header Content-Security-Policy "default-src 'self'; script-src 'self' @SCRIPT_HASHES@ ${PAYMENT_CSP_SOURCES}; script-src-attr 'none'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: blob: https://cdn.vnda.com.br ${S3_PUBLIC_ENDPOINT} ${PAYMENT_CSP_SOURCES}; media-src 'self' ${S3_PUBLIC_ENDPOINT}; connect-src 'self' ${S3_PUBLIC_ENDPOINT} https://cdn.vnda.com.br ${PAYMENT_CSP_SOURCES}; frame-src 'self' ${PAYMENT_CSP_SOURCES} ${PAYMENT_CHALLENGE_SOURCES}; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self' ${PAYMENT_CHALLENGE_SOURCES}" always;
|
add_header Content-Security-Policy "default-src 'self'; script-src 'self' @SCRIPT_HASHES@ ${PAYMENT_CSP_SOURCES}; script-src-attr 'none'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: blob: https://cdn.vnda.com.br ${S3_PUBLIC_ENDPOINT} ${PAYMENT_CSP_SOURCES}; media-src 'self' ${S3_PUBLIC_ENDPOINT}; connect-src 'self' ${S3_PUBLIC_ENDPOINT} https://cdn.vnda.com.br ${PAYMENT_CSP_SOURCES} ${SENTRY_CSP_SOURCES}; frame-src 'self' ${PAYMENT_CSP_SOURCES} ${PAYMENT_CHALLENGE_SOURCES}; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self' ${PAYMENT_CHALLENGE_SOURCES}" always;
|
||||||
|
|
||||||
location = /health { access_log off; return 200 'ok'; }
|
location = /health { access_log off; return 200 'ok'; }
|
||||||
location /api/ {
|
location /api/ {
|
||||||
@@ -49,7 +49,7 @@ server {
|
|||||||
# Always revalidate HTML/JS/CSS after a deployment. Without this, a browser
|
# Always revalidate HTML/JS/CSS after a deployment. Without this, a browser
|
||||||
# can pair a new Kanban page with a cached older script after a rollout.
|
# can pair a new Kanban page with a cached older script after a rollout.
|
||||||
# The Site's product pages and cart are addresses of the same page (web/site-pages.js).
|
# The Site's product pages and cart are addresses of the same page (web/site-pages.js).
|
||||||
location ~ ^/(arquivo-por-metro|artes-avulsas|uv-arquivo-por-metro|uv-artes-avulsas|carrinho|pagamento|pagamento/pix)/?$ {
|
location ~ ^/(arquivo-por-metro|artes-avulsas|uv-arquivo-por-metro|uv-artes-avulsas|premium|carrinho|pagamento|pagamento/pix)/?$ {
|
||||||
expires -1;
|
expires -1;
|
||||||
try_files /index.html =404;
|
try_files /index.html =404;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -51,6 +51,8 @@ TINY_PRODUCT_TREATMENT=TBD
|
|||||||
TINY_FORMA_ENVIO_RETIRADA=TBD
|
TINY_FORMA_ENVIO_RETIRADA=TBD
|
||||||
# true only at go-live, after the n8n DTFIMP designer branch is removed.
|
# true only at go-live, after the n8n DTFIMP designer branch is removed.
|
||||||
TINY_STATUS_UPDATES=false
|
TINY_STATUS_UPDATES=false
|
||||||
|
# Tiny id of the forma de recebimento "Boleto" (montador Venda orders).
|
||||||
|
TINY_RECEIPT_BOLETO=
|
||||||
# E-mail (password recovery and team alerts). off until the SMTP account exists.
|
# E-mail (password recovery and team alerts). off until the SMTP account exists.
|
||||||
MAIL_ADAPTER=off
|
MAIL_ADAPTER=off
|
||||||
MAIL_FROM=DTF Dropstar <nao-responda@SITE_DOMAIN>
|
MAIL_FROM=DTF Dropstar <nao-responda@SITE_DOMAIN>
|
||||||
@@ -74,6 +76,11 @@ BACKUP_SECRET_ACCESS_KEY=TBD
|
|||||||
BACKUP_AGE_RECIPIENT=age1...
|
BACKUP_AGE_RECIPIENT=age1...
|
||||||
BACKUP_HOUR=3
|
BACKUP_HOUR=3
|
||||||
|
|
||||||
|
# Sentry: empty DSNs keep it off; the environment defaults to production.
|
||||||
|
SENTRY_DSN_API=
|
||||||
|
SENTRY_DSN_WEB=
|
||||||
|
SENTRY_ENVIRONMENT=
|
||||||
|
|
||||||
# Names of external Portainer/Docker Swarm secrets, never their values.
|
# Names of external Portainer/Docker Swarm secrets, never their values.
|
||||||
DATABASE_URL_SECRET=TBD
|
DATABASE_URL_SECRET=TBD
|
||||||
DATABASE_ADMIN_URL_SECRET=TBD
|
DATABASE_ADMIN_URL_SECRET=TBD
|
||||||
|
|||||||
@@ -12,6 +12,10 @@ x-app-environment: &app-environment
|
|||||||
# connection per `with` block, exactly as before (the production default).
|
# connection per `with` block, exactly as before (the production default).
|
||||||
DB_POOL: ${DB_POOL:-off}
|
DB_POOL: ${DB_POOL:-off}
|
||||||
DB_POOL_SIZE: ${DB_POOL_SIZE:-20}
|
DB_POOL_SIZE: ${DB_POOL_SIZE:-20}
|
||||||
|
# Sentry: empty DSNs leave it off; the environment defaults to production.
|
||||||
|
SENTRY_DSN_API: ${SENTRY_DSN_API:-}
|
||||||
|
SENTRY_DSN_WEB: ${SENTRY_DSN_WEB:-}
|
||||||
|
SENTRY_ENVIRONMENT: ${SENTRY_ENVIRONMENT:-production}
|
||||||
S3_ENDPOINT: ${R2_ENDPOINT:?set R2_ENDPOINT}
|
S3_ENDPOINT: ${R2_ENDPOINT:?set R2_ENDPOINT}
|
||||||
S3_PUBLIC_ENDPOINT: ${R2_ENDPOINT:?set R2_ENDPOINT}
|
S3_PUBLIC_ENDPOINT: ${R2_ENDPOINT:?set R2_ENDPOINT}
|
||||||
S3_BUCKET: ${R2_BUCKET:?set R2_BUCKET}
|
S3_BUCKET: ${R2_BUCKET:?set R2_BUCKET}
|
||||||
@@ -120,6 +124,9 @@ x-app-environment: &app-environment
|
|||||||
# Optional e-commerce channel id for Site orders. Without it the order still
|
# Optional e-commerce channel id for Site orders. Without it the order still
|
||||||
# carries DTF-<n> as numeroPedidoEcommerce, with no channel.
|
# carries DTF-<n> as numeroPedidoEcommerce, with no channel.
|
||||||
TINY_ECOMMERCE_ID: ${TINY_ECOMMERCE_ID:-}
|
TINY_ECOMMERCE_ID: ${TINY_ECOMMERCE_ID:-}
|
||||||
|
# The Tiny forma de recebimento id of "Boleto", for invoiced montador Venda
|
||||||
|
# orders (front 7a.3). Empty: the order goes without one and its note says so.
|
||||||
|
TINY_RECEIPT_BOLETO: ${TINY_RECEIPT_BOLETO:-}
|
||||||
# Sets "Aprovada" on paid orders and "Pronto para envio" on finished pickup
|
# 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
|
# 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
|
# only together with TINY_ADAPTER=tiny and after n8n stops sending the
|
||||||
@@ -298,6 +305,8 @@ services:
|
|||||||
# Mercado Pago's card form loads from these origins; empty keeps the
|
# Mercado Pago's card form loads from these origins; empty keeps the
|
||||||
# Site at script-src 'self'. Set together with the Mercado Pago adapter.
|
# Site at script-src 'self'. Set together with the Mercado Pago adapter.
|
||||||
PAYMENT_CSP_SOURCES: ${PAYMENT_CSP_SOURCES:-}
|
PAYMENT_CSP_SOURCES: ${PAYMENT_CSP_SOURCES:-}
|
||||||
|
# The Sentry ingest origin(s) for connect-src; empty until the DSN exists.
|
||||||
|
SENTRY_CSP_SOURCES: ${SENTRY_CSP_SOURCES:-https://o4510863040905216.ingest.us.sentry.io}
|
||||||
# The bank's confirmation page for debit and other 3-D Secure cards is
|
# The bank's confirmation page for debit and other 3-D Secure cards is
|
||||||
# on the issuer's own domain, so it cannot be listed: "https:" lets
|
# on the issuer's own domain, so it cannot be listed: "https:" lets
|
||||||
# frames and form posts reach it (never scripts). Empty turns it off.
|
# frames and form posts reach it (never scripts). Empty turns it off.
|
||||||
@@ -326,6 +335,8 @@ services:
|
|||||||
S3_PUBLIC_ENDPOINT: ${R2_ENDPOINT:?set R2_ENDPOINT}
|
S3_PUBLIC_ENDPOINT: ${R2_ENDPOINT:?set R2_ENDPOINT}
|
||||||
PAYMENT_CSP_SOURCES: ""
|
PAYMENT_CSP_SOURCES: ""
|
||||||
PAYMENT_CHALLENGE_SOURCES: ""
|
PAYMENT_CHALLENGE_SOURCES: ""
|
||||||
|
# The Kanban reports to Sentry too; set from the browser DSN host.
|
||||||
|
SENTRY_CSP_SOURCES: ${SENTRY_CSP_SOURCES:-https://o4510863040905216.ingest.us.sentry.io}
|
||||||
networks: [backend]
|
networks: [backend]
|
||||||
ports:
|
ports:
|
||||||
- target: 8080
|
- target: 8080
|
||||||
|
|||||||
@@ -243,6 +243,19 @@ behaviour). Set it to `on` in the stack's environment and redeploy to keep
|
|||||||
between 1 and `DB_POOL_SIZE` connections per process (`DB_POOL_SIZE` defaults
|
between 1 and `DB_POOL_SIZE` connections per process (`DB_POOL_SIZE` defaults
|
||||||
to 20); set it back to `off` to return to one connection per block.
|
to 20); set it back to `off` to return to one connection per block.
|
||||||
|
|
||||||
|
## 11. Sentry
|
||||||
|
|
||||||
|
Sentry is built into the API, the worker, the Site and the Kanban, and stays
|
||||||
|
off while the DSNs are empty. Set `SENTRY_DSN_API` and `SENTRY_DSN_WEB` in the
|
||||||
|
stack's environment, and optionally `SENTRY_ENVIRONMENT` (defaults to
|
||||||
|
`production`). The API and worker initialise from `SENTRY_DSN_API`; the browser
|
||||||
|
reads `SENTRY_DSN_WEB` from `/api/session` on the Site and from
|
||||||
|
`/api/operator/me` on the Kanban. When the DSNs exist, also set
|
||||||
|
`SENTRY_CSP_SOURCES` to the Sentry ingest origin, such as
|
||||||
|
`https://o123.ingest.sentry.io` (or `https://*.ingest.sentry.io`), so the CSP
|
||||||
|
`connect-src` allows the browser to send events. No image change is needed to
|
||||||
|
switch it on: update the stack variables and redeploy.
|
||||||
|
|
||||||
## Current blocker
|
## Current blocker
|
||||||
|
|
||||||
This is the final deployment shape, but it is not authorized for production
|
This is the final deployment shape, but it is not authorized for production
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ server {
|
|||||||
add_header Referrer-Policy no-referrer always;
|
add_header Referrer-Policy no-referrer always;
|
||||||
add_header X-Frame-Options DENY always;
|
add_header X-Frame-Options DENY always;
|
||||||
add_header Permissions-Policy "camera=(self), microphone=(), geolocation=()" always;
|
add_header Permissions-Policy "camera=(self), microphone=(), geolocation=()" always;
|
||||||
add_header Content-Security-Policy "default-src 'self'; script-src 'self' @SCRIPT_HASHES@ ${PAYMENT_CSP_SOURCES}; script-src-attr 'none'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: blob: https://cdn.vnda.com.br ${S3_PUBLIC_ENDPOINT} ${PAYMENT_CSP_SOURCES}; media-src 'self' ${S3_PUBLIC_ENDPOINT}; connect-src 'self' ${S3_PUBLIC_ENDPOINT} https://cdn.vnda.com.br ${PAYMENT_CSP_SOURCES}; frame-src 'self' ${PAYMENT_CSP_SOURCES} ${PAYMENT_CHALLENGE_SOURCES}; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self' ${PAYMENT_CHALLENGE_SOURCES}" always;
|
add_header Content-Security-Policy "default-src 'self'; script-src 'self' @SCRIPT_HASHES@ ${PAYMENT_CSP_SOURCES}; script-src-attr 'none'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: blob: https://cdn.vnda.com.br ${S3_PUBLIC_ENDPOINT} ${PAYMENT_CSP_SOURCES}; media-src 'self' ${S3_PUBLIC_ENDPOINT}; connect-src 'self' ${S3_PUBLIC_ENDPOINT} https://cdn.vnda.com.br ${PAYMENT_CSP_SOURCES} ${SENTRY_CSP_SOURCES}; frame-src 'self' ${PAYMENT_CSP_SOURCES} ${PAYMENT_CHALLENGE_SOURCES}; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self' ${PAYMENT_CHALLENGE_SOURCES}" always;
|
||||||
location = /health { access_log off; return 200 'ok'; }
|
location = /health { access_log off; return 200 'ok'; }
|
||||||
location /api/ {
|
location /api/ {
|
||||||
limit_req zone=api_limit burst=100 nodelay;
|
limit_req zone=api_limit burst=100 nodelay;
|
||||||
|
|||||||
@@ -34,6 +34,7 @@ certifi==2026.10.19 \
|
|||||||
# via
|
# via
|
||||||
# httpcore
|
# httpcore
|
||||||
# httpx
|
# httpx
|
||||||
|
# sentry-sdk
|
||||||
click==8.5.0 \
|
click==8.5.0 \
|
||||||
--hash=sha256:255bc9599cf7748b4b1a446ccc735421bd08a2ae529a8b88597d3de5664ee360 \
|
--hash=sha256:255bc9599cf7748b4b1a446ccc735421bd08a2ae529a8b88597d3de5664ee360 \
|
||||||
--hash=sha256:ba0d2089de75ea0310e2dde03160e6ca10009947fb95a182f9b54021bb272e34
|
--hash=sha256:ba0d2089de75ea0310e2dde03160e6ca10009947fb95a182f9b54021bb272e34
|
||||||
@@ -616,6 +617,14 @@ s3transfer==0.13.1 \
|
|||||||
--hash=sha256:a981aa7429be23fe6dfc13e80e4020057cbab622b08c0315288758d67cabc724 \
|
--hash=sha256:a981aa7429be23fe6dfc13e80e4020057cbab622b08c0315288758d67cabc724 \
|
||||||
--hash=sha256:c3fdba22ba1bd367922f27ec8032d6a1cf5f10c934fb5d68cf60fd5a23d936cf
|
--hash=sha256:c3fdba22ba1bd367922f27ec8032d6a1cf5f10c934fb5d68cf60fd5a23d936cf
|
||||||
# via boto3
|
# via boto3
|
||||||
|
segno==1.6.6 \
|
||||||
|
--hash=sha256:28c7d081ed0cf935e0411293a465efd4d500704072cdb039778a2ab8736190c7 \
|
||||||
|
--hash=sha256:e60933afc4b52137d323a4434c8340e0ce1e58cec71439e46680d4db188f11b3
|
||||||
|
# via -r infra/requirements.txt
|
||||||
|
sentry-sdk==2.74.0 \
|
||||||
|
--hash=sha256:40b205af015649df3ec9986e057ce24ce85956bee3fb75efa72c93aa7036bdff \
|
||||||
|
--hash=sha256:dd91d75aacaef636006b579ac3ddb2fdbc9dce35f00f4b353b6b1b110c6b256a
|
||||||
|
# via -r infra/requirements.txt
|
||||||
six==1.17.0 \
|
six==1.17.0 \
|
||||||
--hash=sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274 \
|
--hash=sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274 \
|
||||||
--hash=sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81
|
--hash=sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81
|
||||||
@@ -647,7 +656,9 @@ typing-inspection==0.4.4 \
|
|||||||
urllib3==2.7.0 \
|
urllib3==2.7.0 \
|
||||||
--hash=sha256:231e0ec3b63ceb14667c67be60f2f2c40a518cb38b03af60abc813da26505f4c \
|
--hash=sha256:231e0ec3b63ceb14667c67be60f2f2c40a518cb38b03af60abc813da26505f4c \
|
||||||
--hash=sha256:9fb4c81ebbb1ce9531cce37674bbc6f1360472bc18ca9a553ede278ef7276897
|
--hash=sha256:9fb4c81ebbb1ce9531cce37674bbc6f1360472bc18ca9a553ede278ef7276897
|
||||||
# via botocore
|
# via
|
||||||
|
# botocore
|
||||||
|
# sentry-sdk
|
||||||
uvicorn==0.34.2 \
|
uvicorn==0.34.2 \
|
||||||
--hash=sha256:0e929828f6186353a80b58ea719861d2629d766293b6d19baf086ba31d4f3328 \
|
--hash=sha256:0e929828f6186353a80b58ea719861d2629d766293b6d19baf086ba31d4f3328 \
|
||||||
--hash=sha256:deb49af569084536d269fe0a6d67e3754f104cf03aba7c11c40f01aadf33c403
|
--hash=sha256:deb49af569084536d269fe0a6d67e3754f104cf03aba7c11c40f01aadf33c403
|
||||||
|
|||||||
@@ -8,3 +8,5 @@ httpx==0.28.1
|
|||||||
pillow==13.0.0
|
pillow==13.0.0
|
||||||
pikepdf==10.13.0.post1
|
pikepdf==10.13.0.post1
|
||||||
pypdfium2==5.14.0
|
pypdfium2==5.14.0
|
||||||
|
segno==1.6.6
|
||||||
|
sentry-sdk==2.74.0
|
||||||
|
|||||||
@@ -49,17 +49,17 @@ def run():
|
|||||||
|
|
||||||
refused = client.call('/quotes', quote_body(item, False, mail), expected=422)
|
refused = client.call('/quotes', quote_body(item, False, mail), expected=422)
|
||||||
assert refused['detail'] == ('Sua arte tem nota 50: para imprimir com qualidade, '
|
assert refused['detail'] == ('Sua arte tem nota 50: para imprimir com qualidade, '
|
||||||
'o tratamento pelo designer é obrigatório neste pedido.'), refused
|
'o Ajuste Fino é obrigatório neste pedido.'), refused
|
||||||
|
|
||||||
made = client.call('/quotes', quote_body(item, True, mail))
|
made = client.call('/quotes', quote_body(item, True, mail))
|
||||||
quote_id = made['id']
|
quote_id = made['id']
|
||||||
assert made['status'] == 'approved', made
|
assert made['status'] == 'approved', made
|
||||||
approved = client.call('/quotes/' + quote_id)['approved']
|
approved = client.call('/quotes/' + quote_id)['approved']
|
||||||
assert approved['grade_flags'] == {'aviso': 50, 'tratamento': 50}, approved
|
assert approved['grade_flags'] == {'aviso': 50, 'tratamento': 50}, approved
|
||||||
assert approved['treatment']['cents'] == 1000, approved
|
assert approved['treatment'] == {'cents': 1000, 'hours': 24, 'arts': 1,
|
||||||
|
'unit_cents': 1000}, approved
|
||||||
assert approved['total_cents'] == 9990, approved
|
assert approved['total_cents'] == 9990, approved
|
||||||
print('PASS: the grade rule requires the designer treatment and flags the order'
|
print('PASS: the grade rule requires Ajuste Fino and flags the order with the worst grade')
|
||||||
' with the worst grade')
|
|
||||||
finally:
|
finally:
|
||||||
if rules_set:
|
if rules_set:
|
||||||
try:
|
try:
|
||||||
|
|||||||
99
tests/label_test.py
Normal file
99
tests/label_test.py
Normal file
@@ -0,0 +1,99 @@
|
|||||||
|
"""The 10x15 thermal label at Finalizado (Fase 2, front 10).
|
||||||
|
|
||||||
|
Run inside the API container: python -m tests.label_test
|
||||||
|
"""
|
||||||
|
from urllib.error import HTTPError
|
||||||
|
from urllib.request import Request
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
from psycopg.types.json import Jsonb
|
||||||
|
|
||||||
|
from app.core import db
|
||||||
|
from tests.smoke_test import BASE, Client, with_host
|
||||||
|
from tests.users_test import PASSWORD, order_fixture
|
||||||
|
|
||||||
|
|
||||||
|
def label_page(client, order_id, expected=200):
|
||||||
|
"""GET the label as the browser does; returns the HTML (or the error body)."""
|
||||||
|
request = Request(BASE + '/api/operator/orders/' + order_id + '/label', headers=with_host())
|
||||||
|
try:
|
||||||
|
with client.opener.open(request, timeout=30) as response:
|
||||||
|
assert response.status == expected, (response.status, expected)
|
||||||
|
assert response.headers.get_content_type() == 'text/html', response.headers
|
||||||
|
return response.read().decode()
|
||||||
|
except HTTPError as error:
|
||||||
|
if error.code != expected:
|
||||||
|
raise AssertionError((error.code, expected, error.read().decode())) from error
|
||||||
|
return error.read().decode()
|
||||||
|
|
||||||
|
|
||||||
|
def user(superadmin, tag, role, name):
|
||||||
|
email = f'etiqueta-{tag}-{role}@example.test'
|
||||||
|
superadmin.call('/operator/users',
|
||||||
|
{'name': name, 'email': email, 'role': role, 'password': PASSWORD}, operator=True)
|
||||||
|
client = Client()
|
||||||
|
client.call('/session')
|
||||||
|
client.call('/operator/login', {'email': email, 'password': PASSWORD})
|
||||||
|
return client
|
||||||
|
|
||||||
|
|
||||||
|
def run():
|
||||||
|
su = Client()
|
||||||
|
su.call('/session')
|
||||||
|
su.call('/operator/me', operator=True) # the default superadmin
|
||||||
|
tag = uuid4().hex[:6]
|
||||||
|
revisor_email = f'etiqueta-{tag}-revisor@example.test'
|
||||||
|
revisor = user(su, tag, 'revisor', 'Revisor Etiqueta')
|
||||||
|
designer = user(su, tag, 'designer', 'Designer Etiqueta')
|
||||||
|
expedicao = user(su, tag, 'expedicao', 'Expedição Etiqueta')
|
||||||
|
|
||||||
|
owner = uuid4()
|
||||||
|
with db.connect() as c:
|
||||||
|
_, order_id = order_fixture(c, owner, 'file', metres='2.5')
|
||||||
|
snapshot = c.execute('SELECT snapshot FROM dtf_local.orders WHERE id=%s', (order_id,)).fetchone()['snapshot']
|
||||||
|
snapshot['customer']['name'] = 'Cliente Etiqueta'
|
||||||
|
snapshot['destination'] = {'recipient': 'Loja Etiqueta', 'street': 'Rua A', 'number': '10',
|
||||||
|
'complement': '', 'district': 'Centro', 'city': 'Franca',
|
||||||
|
'state': 'SP', 'postal_code': '14400000'}
|
||||||
|
snapshot['freight'] = {'service': 'jadlog', 'description': 'Jadlog .Package', 'total_cents': 1500}
|
||||||
|
c.execute("UPDATE dtf_local.orders SET snapshot=%s, state='fin' WHERE id=%s",
|
||||||
|
(Jsonb(snapshot), order_id))
|
||||||
|
c.execute("INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason) "
|
||||||
|
"VALUES(%s,'rev','fin',%s,'')", (order_id, revisor_email))
|
||||||
|
number = c.execute('SELECT number FROM dtf_local.orders WHERE id=%s', (order_id,)).fetchone()['number']
|
||||||
|
oid = str(order_id)
|
||||||
|
|
||||||
|
# The first computer claims the automatic print; the second does not.
|
||||||
|
assert su.call(f'/operator/orders/{oid}/label/claim', {}, operator=True) == {'print': True}
|
||||||
|
assert su.call(f'/operator/orders/{oid}/label/claim', {}, operator=True) == {'print': False}
|
||||||
|
# A reprint always prints, on any computer.
|
||||||
|
assert su.call(f'/operator/orders/{oid}/label/reprint', {}, operator=True) == {'print': True}
|
||||||
|
|
||||||
|
# The page is the server's HTML: customer, what the order is, delivery, QR.
|
||||||
|
page = label_page(revisor, oid)
|
||||||
|
assert 'Cliente Etiqueta' in page, page
|
||||||
|
assert 'DTF · 1 folha · 2,50 m' in page, page
|
||||||
|
assert 'Envio · Jadlog .Package' in page, page
|
||||||
|
assert 'Revisor Etiqueta' in page, page
|
||||||
|
assert '<svg' in page, page
|
||||||
|
# No Tiny receipt: the order's own DTF number, also in the QR.
|
||||||
|
assert f'DTF-{number}' in page, page
|
||||||
|
|
||||||
|
# With the Tiny sale receipt, its number takes the big type and the QR.
|
||||||
|
with db.connect() as c:
|
||||||
|
c.execute('''INSERT INTO dtf_local.outbox(event_key,provider,payload,receipt,delivered_at)
|
||||||
|
VALUES(%s,'tiny',%s,%s,now())''', (f'{oid}:paid:tiny', Jsonb({}),
|
||||||
|
Jsonb({'tiny_number': '98765'})))
|
||||||
|
page = label_page(revisor, oid)
|
||||||
|
assert '98765' in page, page
|
||||||
|
assert f'DTF-{number}' not in page, page
|
||||||
|
|
||||||
|
# Only the label profiles print it: the designer may not, Expedição may.
|
||||||
|
label_page(designer, oid, expected=403)
|
||||||
|
label_page(expedicao, oid)
|
||||||
|
print('PASS: the label page, one automatic print, reprint, Tiny number, designer refused '
|
||||||
|
'and Expedição allowed')
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
run()
|
||||||
@@ -3,22 +3,52 @@
|
|||||||
Run against the local stack: SITE_BASE_URL=http://site SITE_HOST_HEADER=localhost
|
Run against the local stack: SITE_BASE_URL=http://site SITE_HOST_HEADER=localhost
|
||||||
python -m tests.site_admin_test
|
python -m tests.site_admin_test
|
||||||
"""
|
"""
|
||||||
|
import io
|
||||||
|
import os
|
||||||
import secrets
|
import secrets
|
||||||
from datetime import datetime, timedelta, timezone
|
from datetime import date, datetime, timedelta, timezone
|
||||||
|
from unittest import mock
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
||||||
|
from PIL import Image, ImageDraw
|
||||||
|
|
||||||
|
from app import tiny
|
||||||
from app.core import db
|
from app.core import db
|
||||||
from tests.print_file_test import artwork
|
from tests.print_file_test import artwork
|
||||||
from tests.smoke_test import Client, item_spec, upload_bytes
|
from tests.smoke_test import Client, item_spec, upload_bytes
|
||||||
|
|
||||||
PASSWORD = 'senha-de-teste-123'
|
PASSWORD = 'senha-de-teste-123'
|
||||||
UV = 'uv'
|
UV = 'uv'
|
||||||
|
PREMIUM = 'premium'
|
||||||
|
|
||||||
|
|
||||||
def quote(client, item, mail):
|
def premium_sheet():
|
||||||
|
"""A 57 cm wide sheet above 96 DPI at that width, so the server accepts it."""
|
||||||
|
image = Image.new('RGBA', (2400, 800), (0, 0, 0, 0))
|
||||||
|
ImageDraw.Draw(image).rectangle([40, 40, 2360, 760], fill=(220, 30, 60, 255))
|
||||||
|
out = io.BytesIO()
|
||||||
|
image.save(out, 'PNG', dpi=(300, 300))
|
||||||
|
return out.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
def quote(client, item, mail, expected=200):
|
||||||
return client.call('/quotes', {'request_key': str(uuid4()),
|
return client.call('/quotes', {'request_key': str(uuid4()),
|
||||||
'customer': {'cnpj': '11222333000181', 'zap': '11999999999', 'mail': mail},
|
'customer': {'cnpj': '11222333000181', 'zap': '11999999999', 'mail': mail},
|
||||||
'items': [item], 'freight': {'service': 'pickup'}})
|
'items': [item], 'freight': {'service': 'pickup'}}, expected=expected)
|
||||||
|
|
||||||
|
|
||||||
|
def arts_item(upload_id, arts):
|
||||||
|
"""One loose-art item with `arts` sources of 10 x 10 cm, one metre long."""
|
||||||
|
sources = [{'upload_id': upload_id, 'kind': 'artwork', 'width_cm': 10, 'length_cm': 10,
|
||||||
|
'copies': 1, 'rotation_degrees': 0, 'mirrored': False,
|
||||||
|
'measurement': 'customer'} for _ in range(arts)]
|
||||||
|
placements = [{'source_index': index, 'copy_index': 0, 'x_cm': 0, 'y_cm': index * 10,
|
||||||
|
'width_cm': 10, 'length_cm': 10, 'rotation_degrees': 0, 'mirrored': False}
|
||||||
|
for index in range(arts)]
|
||||||
|
return {'mode': 'avulsa', 'metres': '1', 'grade': 90, 'uploads': [upload_id] * arts,
|
||||||
|
'production': {'version': 3, 'film_width_cm': 57, 'height_cm': arts * 10,
|
||||||
|
'sources': sources, 'placements': placements},
|
||||||
|
'quality_status': 'ok', 'quality_acknowledged': False}
|
||||||
|
|
||||||
|
|
||||||
def run():
|
def run():
|
||||||
@@ -31,11 +61,72 @@ def run():
|
|||||||
manager.call('/session')
|
manager.call('/session')
|
||||||
manager.call('/operator/me', operator=True)
|
manager.call('/operator/me', operator=True)
|
||||||
manager = manager.operator_client
|
manager = manager.operator_client
|
||||||
prices, user = [], None
|
prices, user, treatment_enabled = [], None, None
|
||||||
try:
|
try:
|
||||||
products = manager.call('/operator/site/products')['products']
|
products = manager.call('/operator/site/products')['products']
|
||||||
assert {product['id'] for product in products} == {'file', 'avulsa', 'uvfile', 'uv', 'tratamento'}
|
assert {product['id'] for product in products} == \
|
||||||
assert all(product['unit'] in ('metro', 'pedido') and product['title'] for product in products)
|
{'file', 'avulsa', 'uvfile', 'uv', 'premium', 'tratamento'}
|
||||||
|
assert all(product['unit'] in ('metro', 'pedido', 'arte') and product['title'] for product in products)
|
||||||
|
|
||||||
|
# Front 3: Premium is listed and starts switched off (Marcus, 2026-11-10).
|
||||||
|
premium_entry = next(product for product in products if product['id'] == PREMIUM)
|
||||||
|
assert premium_entry['enabled'] is False, premium_entry
|
||||||
|
assert premium_entry['title'] == 'Têxtil Premium · 8 passadas', premium_entry
|
||||||
|
assert client.call('/session')['products'][PREMIUM]['enabled'] is False
|
||||||
|
premium_item = {**item_spec(PREMIUM, '1', 0, upload_bytes(
|
||||||
|
client, premium_sheet(), name='LOCAL-SITE-PREMIUM.png')),
|
||||||
|
'quality_status': 'warning', 'quality_acknowledged': True}
|
||||||
|
refused = quote(client, premium_item, mail, expected=422)
|
||||||
|
assert refused['detail'] == 'Este produto não está à venda agora.', refused
|
||||||
|
manager.call(f'/operator/site/products/{PREMIUM}', {'enabled': True})
|
||||||
|
assert client.call('/session')['products'][PREMIUM]['enabled'] is True
|
||||||
|
created = quote(client, premium_item, mail)
|
||||||
|
assert created['status'] == 'approved', created
|
||||||
|
approved = client.call('/quotes/' + created['id'])['approved']
|
||||||
|
assert approved['items'][0]['mode'] == PREMIUM, approved
|
||||||
|
assert approved['items'][0]['unit_cents'] == 3990, approved
|
||||||
|
assert approved['total_cents'] == 3990, approved
|
||||||
|
manager.call(f'/operator/site/products/{PREMIUM}', {'enabled': False})
|
||||||
|
|
||||||
|
# Front 1a: Ajuste Fino per art, with the batch band set in the Site tab.
|
||||||
|
treatment = next(product for product in products if product['id'] == 'tratamento')
|
||||||
|
treatment_enabled = treatment['enabled']
|
||||||
|
manager.call('/operator/site/products/tratamento', {'enabled': True})
|
||||||
|
made = manager.call('/operator/site/products/tratamento/prices', {
|
||||||
|
'unit_cents': 990, 'bands': [{'from_metres': '10', 'unit_cents': 690}]})
|
||||||
|
prices.append(made['id'])
|
||||||
|
session = client.call('/session')
|
||||||
|
assert session['treatment_cents'] == 990, session
|
||||||
|
assert session['treatment_bands'] == [{'from_metres': 10.0, 'unit_cents': 690}], session
|
||||||
|
arts = arts_item(upload_bytes(client, artwork(), name='LOCAL-AJUSTE-FINO.png'), 10)
|
||||||
|
customer = {'cnpj': '11222333000181', 'zap': '11999999999', 'mail': mail}
|
||||||
|
three = client.call('/quotes', {'request_key': str(uuid4()), 'customer': customer,
|
||||||
|
'items': [arts], 'treatment': [[0, 0], [0, 1], [0, 2]],
|
||||||
|
'freight': {'service': 'pickup'}})
|
||||||
|
assert three['status'] == 'approved', three
|
||||||
|
ajuste = client.call('/quotes/' + three['id'])['approved']
|
||||||
|
assert ajuste['treatment'] == {'cents': 2970, 'hours': 24, 'arts': 3,
|
||||||
|
'unit_cents': 990}, ajuste
|
||||||
|
assert ajuste['total_cents'] == ajuste['items'][0]['total_cents'] + 2970, ajuste
|
||||||
|
ten = client.call('/quotes', {'request_key': str(uuid4()), 'customer': customer,
|
||||||
|
'items': [arts], 'treatment': [[0, index] for index in range(10)],
|
||||||
|
'freight': {'service': 'pickup'}})
|
||||||
|
ten = client.call('/quotes/' + ten['id'])['approved']
|
||||||
|
assert ten['treatment'] == {'cents': 6900, 'hours': 24, 'arts': 10,
|
||||||
|
'unit_cents': 690}, ten
|
||||||
|
old = client.call('/quotes', {'request_key': str(uuid4()), 'customer': customer,
|
||||||
|
'items': [arts], 'treatment': True, 'freight': {'service': 'pickup'}})
|
||||||
|
old = client.call('/quotes/' + old['id'])['approved']
|
||||||
|
assert old['treatment'] == {'cents': 6900, 'hours': 24, 'arts': 10,
|
||||||
|
'unit_cents': 690}, old
|
||||||
|
# Tiny: the quantity is the number of arts and the unit is the band price.
|
||||||
|
with mock.patch.dict(os.environ, {'TINY_PRODUCT_TREATMENT': '105'}):
|
||||||
|
pedido = tiny.order_payload({'order_id': three['id'], 'order': ajuste,
|
||||||
|
'number': 1, 'payment': {}, 'origin': 'site'}, 777,
|
||||||
|
date(2026, 11, 11), product_id=lambda code: 999)
|
||||||
|
assert [line for line in pedido['itens'] if line['produto']['id'] == 105] == [
|
||||||
|
{'produto': {'id': 105}, 'quantidade': 3, 'valorUnitario': 9.9,
|
||||||
|
'infoAdicional': 'Ajuste Fino · 3 artes · +24 h'}], pedido['itens']
|
||||||
|
|
||||||
manager.call(f'/operator/site/products/{UV}', {'enabled': True})
|
manager.call(f'/operator/site/products/{UV}', {'enabled': True})
|
||||||
uid = upload_bytes(client, artwork(), name='LOCAL-SITE-ADMIN.png')
|
uid = upload_bytes(client, artwork(), name='LOCAL-SITE-ADMIN.png')
|
||||||
@@ -109,8 +200,6 @@ def run():
|
|||||||
manager.call(f'/operator/site/products/{UV}/prices', {
|
manager.call(f'/operator/site/products/{UV}/prices', {
|
||||||
'unit_cents': 12345, 'bands': [{'from_metres': str(i), 'unit_cents': 1900}
|
'unit_cents': 12345, 'bands': [{'from_metres': str(i), 'unit_cents': 1900}
|
||||||
for i in range(1, 7)]}, expected=422)
|
for i in range(1, 7)]}, expected=422)
|
||||||
manager.call('/operator/site/products/tratamento/prices', {
|
|
||||||
'unit_cents': 1000, 'bands': [{'from_metres': '5', 'unit_cents': 900}]}, expected=422)
|
|
||||||
|
|
||||||
# A profile without "manage" cannot see or change the Site tab.
|
# A profile without "manage" cannot see or change the Site tab.
|
||||||
email = f'site-staff-{tag}@example.test'
|
email = f'site-staff-{tag}@example.test'
|
||||||
@@ -123,13 +212,20 @@ def run():
|
|||||||
staff.call(f'/operator/site/products/{UV}', {'enabled': True}, expected=403)
|
staff.call(f'/operator/site/products/{UV}', {'enabled': True}, expected=403)
|
||||||
staff.call(f'/operator/site/products/{UV}/prices', {'unit_cents': 1000}, expected=403)
|
staff.call(f'/operator/site/products/{UV}/prices', {'unit_cents': 1000}, expected=403)
|
||||||
staff.call(f'/operator/site/prices/{made["id"]}/cancel', {}, expected=403)
|
staff.call(f'/operator/site/prices/{made["id"]}/cancel', {}, expected=403)
|
||||||
print('PASS: the Site tab switches a product off and refuses quotes, schedules and cancels prices,'
|
print('PASS: the Site tab switches a product off and refuses quotes, lists Premium switched off'
|
||||||
' charges the new price, and refuses a non-manage profile')
|
' and accepts it once enabled, prices Ajuste Fino per art with its band,'
|
||||||
|
' schedules and cancels prices, charges the new price, and refuses a non-manage profile')
|
||||||
finally:
|
finally:
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
if prices:
|
if prices:
|
||||||
c.execute('DELETE FROM dtf_local.product_prices WHERE id=ANY(%s::bigint[])', (prices,))
|
c.execute('DELETE FROM dtf_local.product_prices WHERE id=ANY(%s::bigint[])', (prices,))
|
||||||
c.execute("UPDATE dtf_local.products SET enabled=true WHERE id=%s", (UV,))
|
c.execute("UPDATE dtf_local.products SET enabled=true WHERE id=%s", (UV,))
|
||||||
|
c.execute("UPDATE dtf_local.products SET enabled=false WHERE id=%s", (PREMIUM,))
|
||||||
|
if treatment_enabled is not None:
|
||||||
|
try:
|
||||||
|
manager.call('/operator/site/products/tratamento', {'enabled': treatment_enabled})
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
if user:
|
if user:
|
||||||
try:
|
try:
|
||||||
manager.call('/operator/users/' + str(user['id']) + '/delete', {}, expected=200)
|
manager.call('/operator/users/' + str(user['id']) + '/delete', {}, expected=200)
|
||||||
|
|||||||
@@ -131,7 +131,7 @@ def item_spec(mode, metres, grade, uid):
|
|||||||
return {'mode':mode,'metres':str(metres),'grade':grade,'uploads':[uid],
|
return {'mode':mode,'metres':str(metres),'grade':grade,'uploads':[uid],
|
||||||
'production':{'version':2,'film_width_cm':film_width,'height_cm':length_cm,
|
'production':{'version':2,'film_width_cm':film_width,'height_cm':length_cm,
|
||||||
'sources':[{'upload_id':uid,
|
'sources':[{'upload_id':uid,
|
||||||
'kind':'sheet' if mode in ('file','uvfile') else 'artwork',
|
'kind':'sheet' if mode in ('file','uvfile','premium') else 'artwork',
|
||||||
'width_cm':film_width,'length_cm':length_cm,'copies':1,
|
'width_cm':film_width,'length_cm':length_cm,'copies':1,
|
||||||
'rotation_degrees':0,'mirrored':False,'measurement':'customer'}],
|
'rotation_degrees':0,'mirrored':False,'measurement':'customer'}],
|
||||||
'placements':[{'source_index':0,'copy_index':0,'x_cm':0,'y_cm':0,
|
'placements':[{'source_index':0,'copy_index':0,'x_cm':0,'y_cm':0,
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
"""The montador: stamp sizes, and the invoiced order a sheet becomes.
|
"""The montador: stamp sizes, brand per stamp, and the Interno and Venda
|
||||||
|
orders a sheet becomes (fronts 7a to 7a.3).
|
||||||
|
|
||||||
Run against the local stack: python -m tests.stamps_test
|
Run against the local stack: python -m tests.stamps_test
|
||||||
"""
|
"""
|
||||||
@@ -14,6 +15,7 @@ from tests.smoke_test import Client
|
|||||||
|
|
||||||
PASSWORD = 'senha-de-teste-123'
|
PASSWORD = 'senha-de-teste-123'
|
||||||
PNG = (Path(__file__).resolve().parent / 'fixtures' / 'final-300.png').read_bytes()
|
PNG = (Path(__file__).resolve().parent / 'fixtures' / 'final-300.png').read_bytes()
|
||||||
|
INTERNAL_MISSING = 'Peça à Gestão para completar o cliente interno.'
|
||||||
|
|
||||||
|
|
||||||
def signed_in(email, password=PASSWORD):
|
def signed_in(email, password=PASSWORD):
|
||||||
@@ -55,6 +57,10 @@ def montador_item(uid, mode='avulsa'):
|
|||||||
'quality_status': 'ok', 'quality_acknowledged': False, 'residue_accepted': 0}
|
'quality_status': 'ok', 'quality_acknowledged': False, 'residue_accepted': 0}
|
||||||
|
|
||||||
|
|
||||||
|
def price_table(stats):
|
||||||
|
return {row['method']: row for row in stats['price_table']}
|
||||||
|
|
||||||
|
|
||||||
def run():
|
def run():
|
||||||
tag = secrets.token_hex(3)
|
tag = secrets.token_hex(3)
|
||||||
su = Client()
|
su = Client()
|
||||||
@@ -62,27 +68,39 @@ def run():
|
|||||||
assert su.call('/operator/me', operator=True)['role'] == 'superadmin'
|
assert su.call('/operator/me', operator=True)['role'] == 'superadmin'
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
original = c.execute('SELECT letter,width_cm FROM dtf_local.stamp_sizes ORDER BY width_cm, letter').fetchall()
|
original = c.execute('SELECT letter,width_cm FROM dtf_local.stamp_sizes ORDER BY width_cm, letter').fetchall()
|
||||||
emails = {role: f'{role}-{tag}@example.test' for role in ('expedicao', 'designer', 'gestao')}
|
internal = c.execute('SELECT name,cnpj,zap,mail FROM dtf_local.internal_customer').fetchone()
|
||||||
|
# The seed state: only the name, so Interno must be refused until
|
||||||
|
# Gestão completes the other fields.
|
||||||
|
c.execute("UPDATE dtf_local.internal_customer SET name='Nexstar · Marketplace',"
|
||||||
|
"cnpj='',zap='',mail=''")
|
||||||
|
emails = {role: f'{role}-{tag}@example.test' for role in ('expedicao', 'vendedor', 'designer', 'gestao')}
|
||||||
table = [(row['letter'], float(row['width_cm'])) for row in original]
|
table = [(row['letter'], float(row['width_cm'])) for row in original]
|
||||||
customer = {'name': 'Cliente Montador', 'cnpj': '11222333000181', 'zap': '16999999999',
|
internal_customer = {'name': 'Nexstar · Marketplace', 'cnpj': '11222333000181',
|
||||||
'mail': f'montador-{tag}@example.test'}
|
'zap': '1633334444', 'mail': f'interno-{tag}@example.test'}
|
||||||
identity = operator_identity(emails['expedicao'])
|
venda_customer = {'name': 'Maria Souza', 'cnpj': '12345678909',
|
||||||
|
'zap': '16988887777', 'mail': f'venda-{tag}@example.test'}
|
||||||
|
envio_customer = {'name': 'Maria Souza', 'cnpj': '12345678909',
|
||||||
|
'zap': '16988887777', 'mail': f'envio-{tag}@example.test'}
|
||||||
|
identities = [operator_identity(emails['expedicao']), operator_identity(emails['vendedor'])]
|
||||||
made_orders, made_quotes = [], []
|
made_orders, made_quotes = [], []
|
||||||
|
# A code of its own, so a brand someone saved in Estampas/ is never touched.
|
||||||
|
stamp_code = 'T' + tag
|
||||||
try:
|
try:
|
||||||
for role, email in emails.items():
|
for role, email in emails.items():
|
||||||
su.call('/operator/users', {'name': role.title(), 'email': email, 'role': role,
|
su.call('/operator/users', {'name': role.title(), 'email': email, 'role': role,
|
||||||
'password': PASSWORD}, operator=True)
|
'password': PASSWORD}, operator=True)
|
||||||
# The new profile creates through the users API and reads the table.
|
# The new profile creates through the users API and reads the table.
|
||||||
shipping = signed_in(emails['expedicao'])
|
shipping = signed_in(emails['expedicao'])
|
||||||
|
seller = signed_in(emails['vendedor'])
|
||||||
|
manager = signed_in(emails['gestao'])
|
||||||
|
designer = signed_in(emails['designer'])
|
||||||
me = shipping.call('/operator/me')
|
me = shipping.call('/operator/me')
|
||||||
assert me['role'] == 'expedicao' and me['can'] == ['assemble', 'view'], me
|
assert me['role'] == 'expedicao' and me['can'] == ['assemble', 'label', 'view'], me
|
||||||
read = shipping.call('/operator/stamp-sizes')['sizes']
|
read = shipping.call('/operator/stamp-sizes')['sizes']
|
||||||
assert [(row['letter'], float(row['width_cm'])) for row in read] == table, read
|
assert [(row['letter'], float(row['width_cm'])) for row in read] == table, read
|
||||||
# The designer does not assemble: no reading the table.
|
# The designer does not assemble: no reading the table.
|
||||||
designer = signed_in(emails['designer'])
|
|
||||||
designer.call('/operator/stamp-sizes', expected=403)
|
designer.call('/operator/stamp-sizes', expected=403)
|
||||||
# Gestão replaces the whole table in one go and reads it back, by width.
|
# Gestão replaces the whole table in one go and reads it back, by width.
|
||||||
manager = signed_in(emails['gestao'])
|
|
||||||
manager.call('/operator/stamp-sizes', {'sizes': [{'letter': 'D', 'width_cm': 30},
|
manager.call('/operator/stamp-sizes', {'sizes': [{'letter': 'D', 'width_cm': 30},
|
||||||
{'letter': 'A', 'width_cm': 20},
|
{'letter': 'A', 'width_cm': 20},
|
||||||
{'letter': 'B', 'width_cm': 24.5}]})
|
{'letter': 'B', 'width_cm': 24.5}]})
|
||||||
@@ -102,35 +120,123 @@ def run():
|
|||||||
read = manager.call('/operator/stamp-sizes')['sizes']
|
read = manager.call('/operator/stamp-sizes')['sizes']
|
||||||
assert [(row['letter'], float(row['width_cm'])) for row in read] == [('A', 20), ('B', 24.5), ('D', 30)], read
|
assert [(row['letter'], float(row['width_cm'])) for row in read] == [('A', 20), ('B', 24.5), ('D', 30)], read
|
||||||
|
|
||||||
# The montador's order: the stamp upload, then the invoiced card in rec.
|
# The brand per stamp: read by whoever assembles, saved by Gestão.
|
||||||
|
default = shipping.call('/operator/stamps/' + stamp_code)
|
||||||
|
assert default == {'code': stamp_code, 'brand': '', 'public': False}, default
|
||||||
|
manager.call('/operator/stamps/' + stamp_code, {'brand': 'Dropstar', 'public': True})
|
||||||
|
saved = shipping.call('/operator/stamps/' + stamp_code)
|
||||||
|
assert saved == {'code': stamp_code, 'brand': 'Dropstar', 'public': True}, saved
|
||||||
|
designer.call('/operator/stamps/' + stamp_code, {'brand': 'X', 'public': False}, expected=403)
|
||||||
|
shipping.call('/operator/stamps/' + stamp_code, {'brand': 'X', 'public': False}, expected=403)
|
||||||
|
|
||||||
|
# The fake Tiny answers the Venda customer search with two contacts.
|
||||||
|
contacts = shipping.call('/operator/tiny/contacts?q=Nexstar')
|
||||||
|
assert len(contacts) == 2, contacts
|
||||||
|
assert set(contacts[0]) == {'id', 'name', 'document', 'email', 'phone'}, contacts[0]
|
||||||
|
assert contacts[0]['document'] == '11.222.333/0001-81', contacts[0]
|
||||||
|
|
||||||
|
# Interno is refused while Gestão has not completed the customer.
|
||||||
stamp = upload_stamp(shipping)
|
stamp = upload_stamp(shipping)
|
||||||
request_key = uuid4()
|
interno = {'kind': 'interno', 'items': [montador_item(stamp)]}
|
||||||
body = {'request_key': str(request_key), 'customer': customer,
|
refused = shipping.call('/operator/montador/orders', {'request_key': str(uuid4()), **interno},
|
||||||
'items': [montador_item(stamp)]}
|
expected=409)
|
||||||
order = shipping.call('/operator/montador/orders', body)
|
assert refused['detail'] == INTERNAL_MISSING, refused
|
||||||
made_orders.append(UUID(order['id']))
|
manager.call('/operator/internal-customer', internal_customer)
|
||||||
made_quotes.append(UUID(order['quote_id']))
|
completed = shipping.call('/operator/internal-customer')
|
||||||
assert order['state'] == 'rec' and order['origin'] == 'dropflow', order
|
assert (completed['name'], completed['cnpj'], completed['zap'], completed['mail']) == (
|
||||||
payment = order['payment']
|
'Nexstar · Marketplace', '11222333000181', '1633334444', internal_customer['mail']), completed
|
||||||
assert (payment['provider'], payment['method'], payment['status']) == ('manual', 'faturado', 'paid'), payment
|
|
||||||
assert payment['total_cents'] == order['snapshot']['total_cents'], payment
|
before_stats = manager.call('/operator/stats?days=30')
|
||||||
|
before = price_table(before_stats)
|
||||||
|
# Interno: the fixed customer, origin dropflow, no Tiny, no paid e-mail.
|
||||||
|
order_interno = shipping.call('/operator/montador/orders', {'request_key': str(uuid4()), **interno})
|
||||||
|
made_orders.append(UUID(order_interno['id']))
|
||||||
|
made_quotes.append(UUID(order_interno['quote_id']))
|
||||||
|
assert order_interno['state'] == 'rec' and order_interno['origin'] == 'dropflow', order_interno
|
||||||
|
assert order_interno['snapshot']['kind'] == 'interno', order_interno['snapshot'].get('kind')
|
||||||
|
assert order_interno['snapshot']['customer']['cnpj'] == '11222333000181', order_interno['snapshot']
|
||||||
|
payment = order_interno['payment']
|
||||||
|
assert (payment['provider'], payment['method'], payment['status']) == ('manual', 'interno', 'paid'), payment
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
assert c.execute('SELECT 1 FROM dtf_local.print_files WHERE order_id=%s',
|
assert c.execute('SELECT 1 FROM dtf_local.print_files WHERE order_id=%s',
|
||||||
(UUID(order['id']),)).fetchone()
|
(UUID(order_interno['id']),)).fetchone()
|
||||||
assert not c.execute('SELECT 1 FROM dtf_local.outbox WHERE event_key=%s',
|
assert not c.execute('SELECT 1 FROM dtf_local.outbox WHERE event_key=%s',
|
||||||
(f"{order['id']}:paid:tiny",)).fetchone()
|
(f"{order_interno['id']}:paid:tiny",)).fetchone()
|
||||||
|
assert not c.execute('SELECT 1 FROM dtf_local.mail_queue WHERE to_addr=%s',
|
||||||
|
(internal_customer['mail'],)).fetchone()
|
||||||
|
|
||||||
|
# Venda: a Tiny customer, origin atendimento, invoiced and sent to Tiny.
|
||||||
|
venda_stamp = upload_stamp(seller)
|
||||||
|
venda = {'kind': 'venda', 'customer': venda_customer, 'with_order': 4321,
|
||||||
|
'items': [montador_item(venda_stamp)]}
|
||||||
|
venda_body = {'request_key': str(uuid4()), **venda}
|
||||||
|
order_venda = seller.call('/operator/montador/orders', venda_body)
|
||||||
|
made_orders.append(UUID(order_venda['id']))
|
||||||
|
made_quotes.append(UUID(order_venda['quote_id']))
|
||||||
|
assert order_venda['state'] == 'rec' and order_venda['origin'] == 'atendimento', order_venda
|
||||||
|
assert order_venda['snapshot']['with_order'] == 4321, order_venda['snapshot'].get('with_order')
|
||||||
|
payment = order_venda['payment']
|
||||||
|
assert (payment['provider'], payment['method'], payment['status']) == ('manual', 'faturado', 'paid'), payment
|
||||||
|
with db.connect() as c:
|
||||||
|
assert c.execute('SELECT 1 FROM dtf_local.outbox WHERE event_key=%s AND provider=%s',
|
||||||
|
(f"{order_venda['id']}:paid:tiny", 'tiny')).fetchone()
|
||||||
|
assert not c.execute('SELECT 1 FROM dtf_local.mail_queue WHERE to_addr=%s',
|
||||||
|
(venda_customer['mail'],)).fetchone()
|
||||||
|
|
||||||
|
# Números: both are counted apart from the money received.
|
||||||
|
after_stats = manager.call('/operator/stats?days=30')
|
||||||
|
after = price_table(after_stats)
|
||||||
|
for method, order in (('interno', order_interno), ('faturado', order_venda)):
|
||||||
|
assert after[method]['orders'] == before[method]['orders'] + 1, (method, before[method], after[method])
|
||||||
|
assert after[method]['cents'] == before[method]['cents'] + order['snapshot']['total_cents'], (method, before[method], after[method])
|
||||||
|
assert after[method]['metres'] > before[method]['metres'], (method, before[method], after[method])
|
||||||
|
assert after_stats['cents'] == before_stats['cents'], (before_stats['cents'], after_stats['cents'])
|
||||||
|
|
||||||
# The same montagem cannot become a second order.
|
# The same montagem cannot become a second order.
|
||||||
refused = shipping.call('/operator/montador/orders', body, expected=409)
|
refused = seller.call('/operator/montador/orders', venda_body, expected=409)
|
||||||
assert refused['detail'] == f"Esta montagem já virou o pedido #{order['number']}.", refused
|
assert refused['detail'] == f"Esta montagem já virou o pedido #{order_venda['number']}.", refused
|
||||||
# A designer does not use the montador, and only loose art becomes one.
|
# Each profile makes only its own kind, and only loose art becomes one.
|
||||||
|
seller.call('/operator/montador/orders', {'request_key': str(uuid4()), **interno}, expected=403)
|
||||||
|
shipping.call('/operator/montador/orders', {'request_key': str(uuid4()), **venda}, expected=403)
|
||||||
designer.call('/operator/montador/uploads', {'name': 'ESTAMPA.png', 'size': 1}, expected=403)
|
designer.call('/operator/montador/uploads', {'name': 'ESTAMPA.png', 'size': 1}, expected=403)
|
||||||
designer.call('/operator/montador/orders', body, expected=403)
|
designer.call('/operator/montador/orders', {'request_key': str(uuid4()), **venda}, expected=403)
|
||||||
shipping.call('/operator/montador/orders', {'request_key': str(uuid4()), 'customer': customer,
|
shipping.call('/operator/montador/orders', {'request_key': str(uuid4()), 'kind': 'interno',
|
||||||
'items': [montador_item(stamp, 'file')]}, expected=422)
|
'items': [montador_item(stamp, 'file')]}, expected=422)
|
||||||
print('PASS: Expedição reads the sizes, uploads a stamp and gets the invoiced montador card; '
|
|
||||||
'Gestão edits the table; invalid rows, profiles and modes are refused')
|
# Venda with Envio: the Site's freight, re-quoted by the server.
|
||||||
|
destination = {'recipient': 'Maria Souza', 'street': 'Rua das Flores', 'number': '100',
|
||||||
|
'complement': 'Sala 2', 'district': 'Centro', 'city': 'Franca',
|
||||||
|
'state': 'SP', 'postal_code': '14400000'}
|
||||||
|
envio_stamp = upload_stamp(seller)
|
||||||
|
envio = {'kind': 'venda', 'customer': envio_customer, 'items': [montador_item(envio_stamp)],
|
||||||
|
'freight': {'service': 'mock-standard', 'postal_code': '14400000'},
|
||||||
|
'destination': destination}
|
||||||
|
order_envio = seller.call('/operator/montador/orders', {'request_key': str(uuid4()), **envio})
|
||||||
|
made_orders.append(UUID(order_envio['id']))
|
||||||
|
made_quotes.append(UUID(order_envio['quote_id']))
|
||||||
|
snapshot = order_envio['snapshot']
|
||||||
|
assert snapshot['destination'] == destination, snapshot.get('destination')
|
||||||
|
assert snapshot['freight']['service'] == 'mock-standard', snapshot.get('freight')
|
||||||
|
assert snapshot['freight']['total_cents'] > 0, snapshot.get('freight')
|
||||||
|
assert snapshot['total_cents'] == (sum(item['total_cents'] for item in snapshot['items']) +
|
||||||
|
snapshot['freight']['total_cents']), snapshot['total_cents']
|
||||||
|
with db.connect() as c:
|
||||||
|
assert c.execute('SELECT 1 FROM dtf_local.outbox WHERE event_key=%s AND provider=%s',
|
||||||
|
(f"{order_envio['id']}:paid:tiny", 'tiny')).fetchone()
|
||||||
|
# Envio needs the full address; an Interno order never ships.
|
||||||
|
sem_destino = {key: value for key, value in envio.items() if key != 'destination'}
|
||||||
|
seller.call('/operator/montador/orders', {'request_key': str(uuid4()), **sem_destino}, expected=422)
|
||||||
|
shipping.call('/operator/montador/orders', {'request_key': str(uuid4()), 'kind': 'interno',
|
||||||
|
'items': [montador_item(stamp)],
|
||||||
|
'destination': destination}, expected=422)
|
||||||
|
print('PASS: Expedição makes Interno and Vendedor makes Venda; the internal customer, the Tiny '
|
||||||
|
'contacts, the stamp brand and the table price in Números work; a Venda with Envio carries '
|
||||||
|
'the destination and the quoted freight; invalid profiles, modes and deliveries are refused')
|
||||||
finally:
|
finally:
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
|
if made_orders:
|
||||||
|
c.execute("DELETE FROM dtf_local.outbox WHERE payload->>'order_id' = ANY(%s::text[])",
|
||||||
|
([str(oid) for oid in made_orders],))
|
||||||
for oid in made_orders:
|
for oid in made_orders:
|
||||||
c.execute('DELETE FROM dtf_local.print_files 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.order_files WHERE order_id=%s', (oid,))
|
||||||
@@ -139,8 +245,13 @@ def run():
|
|||||||
c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (oid,))
|
c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (oid,))
|
||||||
if made_quotes:
|
if made_quotes:
|
||||||
c.execute('DELETE FROM dtf_local.quotes WHERE id=ANY(%s)', (made_quotes,))
|
c.execute('DELETE FROM dtf_local.quotes WHERE id=ANY(%s)', (made_quotes,))
|
||||||
c.execute('DELETE FROM dtf_local.mail_queue WHERE to_addr=%s', (customer['mail'],))
|
c.execute('DELETE FROM dtf_local.mail_queue WHERE to_addr IN (%s,%s,%s)',
|
||||||
c.execute('DELETE FROM dtf_local.uploads WHERE owner=%s', (identity,))
|
(internal_customer['mail'], venda_customer['mail'], envio_customer['mail']))
|
||||||
|
for identity in identities:
|
||||||
|
c.execute('DELETE FROM dtf_local.uploads WHERE owner=%s', (identity,))
|
||||||
|
c.execute('DELETE FROM dtf_local.stamps WHERE code=%s', (stamp_code,))
|
||||||
|
c.execute('UPDATE dtf_local.internal_customer SET name=%s,cnpj=%s,zap=%s,mail=%s',
|
||||||
|
(internal['name'], internal['cnpj'], internal['zap'], internal['mail']))
|
||||||
c.execute('DELETE FROM dtf_local.stamp_sizes')
|
c.execute('DELETE FROM dtf_local.stamp_sizes')
|
||||||
c.cursor().executemany('INSERT INTO dtf_local.stamp_sizes(letter,width_cm) VALUES(%s,%s)', table)
|
c.cursor().executemany('INSERT INTO dtf_local.stamp_sizes(letter,width_cm) VALUES(%s,%s)', table)
|
||||||
c.execute('DELETE FROM dtf_local.operators WHERE email LIKE %s', (f'%-{tag}@example.test',))
|
c.execute('DELETE FROM dtf_local.operators WHERE email LIKE %s', (f'%-{tag}@example.test',))
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import unittest
|
|||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
|
|
||||||
from app import catalog
|
from app import catalog
|
||||||
from app.cart_pricing import price_items
|
from app.cart_pricing import price_items, treatment_price
|
||||||
from app.core import pricing
|
from app.core import pricing
|
||||||
|
|
||||||
|
|
||||||
@@ -156,6 +156,21 @@ class CartPricingCharacterizationTest(unittest.TestCase):
|
|||||||
floating = priced('band-floating-metres')[0]
|
floating = priced('band-floating-metres')[0]
|
||||||
self.assertEqual((floating['billed_metres'], floating['total_cents']), ('2.9', 24650))
|
self.assertEqual((floating['billed_metres'], floating['total_cents']), ('2.9', 24650))
|
||||||
|
|
||||||
|
def test_ajuste_fino_is_per_art_with_the_band(self):
|
||||||
|
# Front 1a: 1 to 9 arts at R$ 9,90, from 10 at R$ 6,90, all arts charged
|
||||||
|
# at the band. `true` keeps meaning every art of the cart.
|
||||||
|
offer = {'enabled': True, 'unit_cents': 990,
|
||||||
|
'bands': [{'from_metres': '10', 'unit_cents': 690}]}
|
||||||
|
for arts, unit in ((1, 990), (9, 990), (10, 690), (12, 690)):
|
||||||
|
items = [item('avulsa', '1', uid=f'u{index}') for index in range(arts)]
|
||||||
|
self.assertEqual(treatment_price(items, True, offer),
|
||||||
|
{'cents': unit * arts, 'hours': 24, 'arts': arts, 'unit_cents': unit})
|
||||||
|
items = [item('file', '1', uid='u1'), item('file', '1', uid='u2')]
|
||||||
|
self.assertEqual(treatment_price(items, [[1, 0]], offer),
|
||||||
|
{'cents': 990, 'hours': 24, 'arts': 1, 'unit_cents': 990})
|
||||||
|
self.assertEqual(treatment_price(items, [], offer), {})
|
||||||
|
self.assertEqual(treatment_price(items, True, {**offer, 'enabled': False}), {})
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
unittest.main()
|
unittest.main()
|
||||||
|
|||||||
@@ -34,7 +34,7 @@ class GradeRulesTest(unittest.TestCase):
|
|||||||
def test_treatment_message(self):
|
def test_treatment_message(self):
|
||||||
self.assertEqual(
|
self.assertEqual(
|
||||||
treatment_message(45),
|
treatment_message(45),
|
||||||
'Sua arte tem nota 45: para imprimir com qualidade, o tratamento pelo designer '
|
'Sua arte tem nota 45: para imprimir com qualidade, o Ajuste Fino '
|
||||||
'é obrigatório neste pedido.')
|
'é obrigatório neste pedido.')
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
26
tests/test_hotfolder.py
Normal file
26
tests/test_hotfolder.py
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
"""The machine hot folder class (Fase 2, front 3), without a database."""
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
from app.hotfolder import PREMIUM, contraction, folder_class
|
||||||
|
|
||||||
|
|
||||||
|
def order(mode, stroke_class='C2', chosen=None):
|
||||||
|
return {'snapshot': {'items': [{'mode': mode, 'stroke_class': stroke_class}]},
|
||||||
|
'contraction': {'0': {'class': chosen}} if chosen else {}}
|
||||||
|
|
||||||
|
|
||||||
|
class FolderClassTest(unittest.TestCase):
|
||||||
|
def test_premium_always_goes_to_its_own_folder(self):
|
||||||
|
# Marcus, 2026-11-10: every premium item, whatever its contraction class.
|
||||||
|
self.assertEqual(folder_class(order('premium', 'C3'), 0), PREMIUM)
|
||||||
|
self.assertEqual(folder_class(order('premium', 'C1', chosen='C2'), 0), PREMIUM)
|
||||||
|
|
||||||
|
def test_a_recorded_contraction_class_still_wins_for_other_products(self):
|
||||||
|
self.assertEqual(folder_class(order('file', 'C1', chosen='C2'), 0), 'C2')
|
||||||
|
self.assertEqual(folder_class(order('file'), 0), 'C2')
|
||||||
|
self.assertIsNone(contraction(order('file', None), 0))
|
||||||
|
self.assertIsNone(folder_class(order('file', None), 0))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
unittest.main()
|
||||||
80
tests/test_label.py
Normal file
80
tests/test_label.py
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
"""The 10x15 label's fields and page (Fase 2, front 10), without a database."""
|
||||||
|
import importlib.util
|
||||||
|
import unittest
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
from app.label import label_fields, label_html
|
||||||
|
|
||||||
|
HAS_SEGNO = importlib.util.find_spec('segno') is not None
|
||||||
|
|
||||||
|
|
||||||
|
def order(**snapshot):
|
||||||
|
content = {'customer': {'name': 'Cliente Etiqueta', 'mail': 'cliente@example.test'},
|
||||||
|
'items': [{'billed_metres': '1.5'}, {'billed_metres': '1'}],
|
||||||
|
'destination': {'recipient': 'Loja Etiqueta'},
|
||||||
|
'freight': {'service': 'jadlog', 'description': 'Jadlog .Package'}}
|
||||||
|
content.update(snapshot)
|
||||||
|
return {'number': 42, 'snapshot': content}
|
||||||
|
|
||||||
|
|
||||||
|
FINISHED = datetime(2026, 11, 11, 17, 32, tzinfo=timezone.utc)
|
||||||
|
|
||||||
|
|
||||||
|
class LabelFieldsTest(unittest.TestCase):
|
||||||
|
def test_the_order_number_falls_back_to_dtf_when_tiny_did_not_answer(self):
|
||||||
|
fields = label_fields(order(), None, FINISHED, 'Revisor Etiqueta')
|
||||||
|
self.assertEqual(fields['code'], 'DTF-42')
|
||||||
|
self.assertEqual(fields['qr'], 'DTF-42')
|
||||||
|
fields = label_fields(order(), '98765', FINISHED, 'Revisor Etiqueta')
|
||||||
|
self.assertEqual(fields['code'], '98765')
|
||||||
|
self.assertEqual(fields['qr'], '98765')
|
||||||
|
|
||||||
|
def test_customer_sheets_and_billed_metres(self):
|
||||||
|
fields = label_fields(order(), '98765', FINISHED, 'Revisor Etiqueta')
|
||||||
|
self.assertEqual(fields['customer'], 'Cliente Etiqueta')
|
||||||
|
self.assertEqual(fields['sheets'], 2)
|
||||||
|
self.assertEqual(fields['metres'], '2,50')
|
||||||
|
self.assertEqual(fields['finished_at'], '11/11/2026 14:32')
|
||||||
|
self.assertEqual(fields['revisor'], 'Revisor Etiqueta')
|
||||||
|
|
||||||
|
def test_pickup_shipping_interno_and_junto_com_a_roupa(self):
|
||||||
|
pickup = order(destination=None, freight={'service': 'pickup'})
|
||||||
|
self.assertEqual(label_fields(pickup, None, FINISHED, None)['delivery'], 'Retirada')
|
||||||
|
self.assertEqual(label_fields(order(), None, FINISHED, None)['delivery'],
|
||||||
|
'Envio · Jadlog .Package')
|
||||||
|
self.assertEqual(label_fields(order(kind='interno'), None, FINISHED, None)['delivery'], 'Interno')
|
||||||
|
self.assertEqual(label_fields(order(with_order='4321'), None, FINISHED, None)['delivery'],
|
||||||
|
'Junto com pedido de roupa nº 4321')
|
||||||
|
# The internal customer's name is the one on the label.
|
||||||
|
self.assertEqual(label_fields(order(kind='interno', destination=None), None, FINISHED, None)['customer'],
|
||||||
|
'Cliente Etiqueta')
|
||||||
|
|
||||||
|
|
||||||
|
class LabelHtmlTest(unittest.TestCase):
|
||||||
|
@unittest.skipUnless(HAS_SEGNO, 'segno is installed with the API image')
|
||||||
|
def test_the_page_is_sized_for_the_10x15_label(self):
|
||||||
|
fields = label_fields(order(), '98765', FINISHED, 'Revisor Etiqueta')
|
||||||
|
page = label_html(fields)
|
||||||
|
self.assertIn('@page { size: 100mm 150mm; margin: 0 }', page)
|
||||||
|
self.assertIn('98765', page)
|
||||||
|
self.assertIn('Cliente Etiqueta', page)
|
||||||
|
self.assertIn('DTF · 2 folhas · 2,50 m', page)
|
||||||
|
self.assertIn('Envio · Jadlog .Package', page)
|
||||||
|
self.assertIn('Finalizado em 11/11/2026 14:32', page)
|
||||||
|
self.assertIn('Revisor: Revisor Etiqueta', page)
|
||||||
|
self.assertIn('<svg', page)
|
||||||
|
# The viewBox lets the CSS print the QR at 30 mm; a fixed pixel width
|
||||||
|
# would leave the modules tiny.
|
||||||
|
self.assertIn('viewBox=', page)
|
||||||
|
|
||||||
|
@unittest.skipUnless(HAS_SEGNO, 'segno is installed with the API image')
|
||||||
|
def test_the_customer_name_is_escaped(self):
|
||||||
|
fields = label_fields(order(customer={'name': '<b>Loja</b>', 'mail': 'x@example.test'}),
|
||||||
|
None, FINISHED, None)
|
||||||
|
page = label_html(fields)
|
||||||
|
self.assertIn('<b>Loja</b>', page)
|
||||||
|
self.assertNotIn('<b>Loja</b>', page)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
unittest.main()
|
||||||
@@ -2,8 +2,8 @@
|
|||||||
import unittest
|
import unittest
|
||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
|
|
||||||
from app.machine_log import (ALIGN_AFTER_FILM_METRES, CLEAN_EVERY_METRES, estimate,
|
from app.machine_log import (ALIGN_AFTER_FILM_METRES, CLEAN_EVERY_METRES, DEFAULT_MINIMUMS,
|
||||||
one_decimal, supply_low)
|
estimate, minimum_for, one_decimal, supply_low)
|
||||||
|
|
||||||
|
|
||||||
class EstimateTest(unittest.TestCase):
|
class EstimateTest(unittest.TestCase):
|
||||||
@@ -38,6 +38,22 @@ class EstimateTest(unittest.TestCase):
|
|||||||
self.assertEqual(CLEAN_EVERY_METRES, Decimal('10'))
|
self.assertEqual(CLEAN_EVERY_METRES, Decimal('10'))
|
||||||
self.assertEqual(ALIGN_AFTER_FILM_METRES, Decimal('20'))
|
self.assertEqual(ALIGN_AFTER_FILM_METRES, Decimal('20'))
|
||||||
|
|
||||||
|
def test_a_machine_without_typed_minimums_alerts_at_dropstars_defaults(self):
|
||||||
|
# Marcus, 2026-11-10: 1 roll of film, 1 L of each ink, 5 kg of powder.
|
||||||
|
self.assertEqual(DEFAULT_MINIMUMS, {'film': Decimal('1'), 'ink_c': Decimal('1'),
|
||||||
|
'ink_m': Decimal('1'), 'ink_y': Decimal('1'),
|
||||||
|
'ink_k': Decimal('1'), 'ink_w': Decimal('1'),
|
||||||
|
'powder': Decimal('5')})
|
||||||
|
for item, default in DEFAULT_MINIMUMS.items():
|
||||||
|
with self.subTest(item=item):
|
||||||
|
minimum = minimum_for({}, item)
|
||||||
|
self.assertEqual(minimum, default)
|
||||||
|
value = estimate([Decimal('1'), Decimal('1')], [Decimal('10')],
|
||||||
|
Decimal('9'), minimum)
|
||||||
|
self.assertTrue(supply_low(value))
|
||||||
|
# A minimum Gestão typed still wins over the default.
|
||||||
|
self.assertEqual(minimum_for({'film': Decimal('0')}, 'film'), Decimal('0'))
|
||||||
|
|
||||||
|
|
||||||
class AlertTextTest(unittest.TestCase):
|
class AlertTextTest(unittest.TestCase):
|
||||||
def test_one_decimal_uses_a_comma(self):
|
def test_one_decimal_uses_a_comma(self):
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
"""Who moves which card on the Kanban: Dropstar's flow of 2026-10-23."""
|
"""Who moves which card on the Kanban: Dropstar's flow of 2026-10-23."""
|
||||||
|
import os
|
||||||
import unittest
|
import unittest
|
||||||
from unittest import mock
|
from unittest import mock
|
||||||
|
|
||||||
from app import payments
|
from app import payments, tiny
|
||||||
from app.core import auth
|
from app.core import auth
|
||||||
from app.core.auth import CAPABILITIES, ROLES, may_move, may_reorder
|
from app.core.auth import CAPABILITIES, ROLES, may_move, may_reorder
|
||||||
from app.runtime import BACK, STATES, TRANSITIONS
|
from app.runtime import BACK, STATES, TRANSITIONS
|
||||||
@@ -55,6 +56,15 @@ class MovesTest(unittest.TestCase):
|
|||||||
self.assertEqual(CAPABILITIES['assemble'],
|
self.assertEqual(CAPABILITIES['assemble'],
|
||||||
{'superadmin', 'admin', 'gestao', 'vendedor', 'expedicao'})
|
{'superadmin', 'admin', 'gestao', 'vendedor', 'expedicao'})
|
||||||
|
|
||||||
|
def test_the_label_is_printed_by_these_profiles(self):
|
||||||
|
# Marcus, 2026-11-10: the Revisor who releases the card, Expedição and
|
||||||
|
# Gestão; the designer, the operator and the seller do not print it.
|
||||||
|
self.assertEqual(CAPABILITIES['label'],
|
||||||
|
{'superadmin', 'admin', 'gestao', 'revisor', 'expedicao'})
|
||||||
|
for role in ROLES:
|
||||||
|
self.assertEqual(role in CAPABILITIES['label'],
|
||||||
|
role in ('superadmin', 'admin', 'gestao', 'revisor', 'expedicao'), role)
|
||||||
|
|
||||||
def test_a_column_is_ordered_by_whoever_takes_its_cards_forward(self):
|
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('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('designer', s)], ['rec', 'cor'])
|
||||||
@@ -78,14 +88,31 @@ class CanAnyTest(unittest.TestCase):
|
|||||||
route(None)
|
route(None)
|
||||||
|
|
||||||
|
|
||||||
class InvoicedOrderTest(unittest.TestCase):
|
class MontadorPaymentTest(unittest.TestCase):
|
||||||
def test_an_invoiced_montador_order_is_held_out_of_tiny(self):
|
def test_a_faturado_order_goes_to_tiny_and_an_internal_one_does_not(self):
|
||||||
self.assertEqual(payments.INVOICED_METHOD, 'faturado')
|
self.assertEqual(payments.INVOICED_METHOD, 'faturado')
|
||||||
# It is not one of the Cotações "registrar" methods.
|
self.assertEqual(payments.INTERNAL_METHOD, 'interno')
|
||||||
|
# Neither is one of the Cotações "registrar" methods.
|
||||||
self.assertNotIn(payments.INVOICED_METHOD, payments.OUTSIDE_METHODS)
|
self.assertNotIn(payments.INVOICED_METHOD, payments.OUTSIDE_METHODS)
|
||||||
self.assertFalse(payments.in_tiny({'payment': {'provider': 'manual', 'method': 'faturado'}}))
|
self.assertNotIn(payments.INTERNAL_METHOD, payments.OUTSIDE_METHODS)
|
||||||
|
self.assertTrue(payments.in_tiny({'payment': {'provider': 'manual', 'method': 'faturado'}}))
|
||||||
|
self.assertFalse(payments.in_tiny({'payment': {'provider': 'manual', 'method': 'interno'}}))
|
||||||
self.assertTrue(payments.in_tiny({'payment': {'provider': 'manual', 'method': 'pix'}}))
|
self.assertTrue(payments.in_tiny({'payment': {'provider': 'manual', 'method': 'pix'}}))
|
||||||
|
|
||||||
|
|
||||||
|
class InternalNoteTest(unittest.TestCase):
|
||||||
|
payload = {'order_id': 'b6f1c0de-0000-4000-8000-000000000001', 'number': 42,
|
||||||
|
'origin': 'atendimento', 'payment': {'method': 'faturado', 'outside': True},
|
||||||
|
'order': {'with_order': 4321}}
|
||||||
|
|
||||||
|
def test_an_invoiced_order_says_how_it_is_received(self):
|
||||||
|
with mock.patch.dict(os.environ, {'TINY_RECEIPT_BOLETO': ''}):
|
||||||
|
note = tiny.internal_note(self.payload)
|
||||||
|
self.assertIn('faturado: forma de recebimento a definir', note)
|
||||||
|
self.assertIn('junto com o pedido de roupa nº 4321', note)
|
||||||
|
with mock.patch.dict(os.environ, {'TINY_RECEIPT_BOLETO': '123456'}):
|
||||||
|
self.assertIn('faturado (Boleto)', tiny.internal_note(self.payload))
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
unittest.main()
|
unittest.main()
|
||||||
|
|||||||
83
tests/test_observability.py
Normal file
83
tests/test_observability.py
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
"""Sentry's scrubbing rules and its off switch (note Sentry)."""
|
||||||
|
import os
|
||||||
|
import unittest
|
||||||
|
from unittest import mock
|
||||||
|
|
||||||
|
try:
|
||||||
|
import sentry_sdk
|
||||||
|
except ImportError: # pragma: no cover - the host may not have the dependency
|
||||||
|
sentry_sdk = None
|
||||||
|
|
||||||
|
from app import observability
|
||||||
|
|
||||||
|
|
||||||
|
@unittest.skipUnless(sentry_sdk, 'sentry-sdk is installed with the API image')
|
||||||
|
class ScrubTest(unittest.TestCase):
|
||||||
|
def test_request_credentials_tokens_and_bodies_are_removed(self):
|
||||||
|
event = {'request': {
|
||||||
|
'url': 'https://dtf.example/api/quotes?page=2&token=abc&X-Amz-Signature=def',
|
||||||
|
'query_string': 'page=2&token=abc&X-Amz-Signature=def',
|
||||||
|
'cookies': {'dtf_session': 'secret'},
|
||||||
|
'data': '{"customer":{"mail":"maria@example.com"}}',
|
||||||
|
'headers': {'Cookie': 'dtf_session=secret', 'Authorization': 'Bearer x',
|
||||||
|
'X-Auth-Token': 'x', 'X-Amz-Security-Token': 'x',
|
||||||
|
'X-Forwarded-For': '1.2.3.4'},
|
||||||
|
}}
|
||||||
|
observability.scrub(event)
|
||||||
|
request = event['request']
|
||||||
|
self.assertNotIn('cookies', request)
|
||||||
|
self.assertNotIn('data', request)
|
||||||
|
self.assertEqual(request['headers'], {'X-Forwarded-For': '1.2.3.4'})
|
||||||
|
self.assertEqual(request['query_string'], 'page=2')
|
||||||
|
self.assertEqual(request['url'], 'https://dtf.example/api/quotes?page=2')
|
||||||
|
|
||||||
|
def test_personal_data_in_messages_exceptions_and_breadcrumbs(self):
|
||||||
|
event = {
|
||||||
|
'message': 'Falha para maria@example.com, CPF 123.456.789-01, CNPJ 11.222.333/0001-81',
|
||||||
|
'exception': {'values': [{'value': 'e-mail ana@example.com'}]},
|
||||||
|
'breadcrumbs': [
|
||||||
|
{'message': 'GET https://x/y?token=abc',
|
||||||
|
'data': {'url': 'https://x/y?page=1&token=abc', 'note': 'CPF 12345678901'}},
|
||||||
|
{'message': 'CNPJ 11222333000181'},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
observability.scrub(event)
|
||||||
|
self.assertNotIn('maria@example.com', event['message'])
|
||||||
|
self.assertNotIn('123.456.789-01', event['message'])
|
||||||
|
self.assertNotIn('11.222.333/0001-81', event['message'])
|
||||||
|
self.assertEqual(event['message'].count(observability.REDACTED), 3)
|
||||||
|
self.assertNotIn('ana@example.com', event['exception']['values'][0]['value'])
|
||||||
|
self.assertNotIn('token=abc', event['breadcrumbs'][0]['message'])
|
||||||
|
self.assertNotIn('token=abc', event['breadcrumbs'][0]['data']['url'])
|
||||||
|
self.assertNotIn('12345678901', event['breadcrumbs'][0]['data']['note'])
|
||||||
|
self.assertNotIn('11222333000181', event['breadcrumbs'][1]['message'])
|
||||||
|
|
||||||
|
|
||||||
|
@unittest.skipUnless(sentry_sdk, 'sentry-sdk is installed with the API image')
|
||||||
|
class InitTest(unittest.TestCase):
|
||||||
|
def test_no_dsn_does_nothing(self):
|
||||||
|
with mock.patch.dict(os.environ, {'SENTRY_DSN_API': ''}):
|
||||||
|
with mock.patch.object(sentry_sdk, 'init') as init:
|
||||||
|
self.assertFalse(observability.init('api'))
|
||||||
|
init.assert_not_called()
|
||||||
|
|
||||||
|
def test_a_dsn_initialises_without_pii_and_scrubs(self):
|
||||||
|
env = {'SENTRY_DSN_API': 'https://key@o1.ingest.sentry.io/1',
|
||||||
|
'SENTRY_ENVIRONMENT': 'test', 'IMAGE_TAG': 'abc123',
|
||||||
|
'SENTRY_TRACES': '0.2'}
|
||||||
|
with mock.patch.dict(os.environ, env):
|
||||||
|
with mock.patch.object(sentry_sdk, 'init') as init, \
|
||||||
|
mock.patch.object(sentry_sdk, 'set_tag') as set_tag:
|
||||||
|
self.assertTrue(observability.init('api'))
|
||||||
|
options = init.call_args.kwargs
|
||||||
|
self.assertEqual(options['dsn'], env['SENTRY_DSN_API'])
|
||||||
|
self.assertEqual(options['environment'], 'test')
|
||||||
|
self.assertEqual(options['release'], 'abc123')
|
||||||
|
self.assertIs(options['send_default_pii'], False)
|
||||||
|
self.assertEqual(options['traces_sample_rate'], 0.2)
|
||||||
|
self.assertIs(options['before_send'], observability.scrub)
|
||||||
|
set_tag.assert_called_once_with('component', 'api')
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
unittest.main()
|
||||||
@@ -34,8 +34,9 @@ class PricingTests(unittest.TestCase):
|
|||||||
|
|
||||||
def test_one_price_per_product(self):
|
def test_one_price_per_product(self):
|
||||||
# Dropstar, 2026-10-23: textile R$ 19,90 ready sheet and R$ 21,90 loose
|
# Dropstar, 2026-10-23: textile R$ 19,90 ready sheet and R$ 21,90 loose
|
||||||
# art; UV R$ 79,90 and R$ 89,90.
|
# art; UV R$ 79,90 and R$ 89,90. Premium R$ 39,90 (2026-11-10).
|
||||||
self.assertEqual(PRICES, {'file': 1990, 'avulsa': 2190, 'uvfile': 7990, 'uv': 8990})
|
self.assertEqual(PRICES, {'file': 1990, 'avulsa': 2190, 'uvfile': 7990, 'uv': 8990,
|
||||||
|
'premium': 3990})
|
||||||
self.assertEqual(price('avulsa', '2.75', 90)['total_cents'], 6132)
|
self.assertEqual(price('avulsa', '2.75', 90)['total_cents'], 6132)
|
||||||
|
|
||||||
def test_the_grade_never_changes_the_price(self):
|
def test_the_grade_never_changes_the_price(self):
|
||||||
@@ -132,6 +133,22 @@ class PricingTests(unittest.TestCase):
|
|||||||
with self.subTest(metres=metres):
|
with self.subTest(metres=metres):
|
||||||
self.assertEqual(cents, band_price(PRICES['file'], bands, Decimal(metres)))
|
self.assertEqual(cents, band_price(PRICES['file'], bands, Decimal(metres)))
|
||||||
|
|
||||||
|
def test_ajuste_fino_band_against_actual_site_javascript(self):
|
||||||
|
# Ajuste Fino counts its band in arts: the Site helper must charge the
|
||||||
|
# same unit price as catalog.band_price.
|
||||||
|
source = Path('web/site-config.js').read_text()
|
||||||
|
body = source.split('function precoAjuste', 1)[1].split('\n}', 1)[0]
|
||||||
|
bands = [{'from_metres': 10, 'unit_cents': 690}]
|
||||||
|
js = ('const TAXA_TRATAMENTO=9.9;const FAIXAS=' + json.dumps({'tratamento': bands}) + ';'
|
||||||
|
'function precoAjuste' + body + '\n}'
|
||||||
|
';const results=[];for(const n of [1,9,10,12])'
|
||||||
|
'results.push([n,Math.round(precoAjuste(n)*100)]);'
|
||||||
|
'process.stdout.write(JSON.stringify(results));')
|
||||||
|
cases = json.loads(subprocess.check_output(['node', '-e', js], text=True))
|
||||||
|
for arts, cents in cases:
|
||||||
|
with self.subTest(arts=arts):
|
||||||
|
self.assertEqual(cents, band_price(990, bands, Decimal(arts)))
|
||||||
|
|
||||||
def test_which_items_are_opened_by_hand(self):
|
def test_which_items_are_opened_by_hand(self):
|
||||||
def item(kind, measurement, uid='u1'):
|
def item(kind, measurement, uid='u1'):
|
||||||
return {'production': {'sources': [{'kind': kind, 'measurement': measurement, 'upload_id': uid}]}}
|
return {'production': {'sources': [{'kind': kind, 'measurement': measurement, 'upload_id': uid}]}}
|
||||||
|
|||||||
@@ -24,7 +24,8 @@ PAID = {'order_id': 'b6f1c0de-0000-4000-8000-000000000001', 'number': 42, 'event
|
|||||||
'state': 'SP', 'postal_code': '14400000'},
|
'state': 'SP', 'postal_code': '14400000'},
|
||||||
'total_cents': 8472}}
|
'total_cents': 8472}}
|
||||||
PRODUCTS = {'TINY_PRODUCT_TEXTIL_FOLHA': '101', 'TINY_PRODUCT_TEXTIL_AVULSA': '102',
|
PRODUCTS = {'TINY_PRODUCT_TEXTIL_FOLHA': '101', 'TINY_PRODUCT_TEXTIL_AVULSA': '102',
|
||||||
'TINY_PRODUCT_UV_FOLHA': '103', 'TINY_PRODUCT_UV_AVULSA': '104', 'TINY_FORMA_ENVIO_RETIRADA': '77'}
|
'TINY_PRODUCT_UV_FOLHA': '103', 'TINY_PRODUCT_UV_AVULSA': '104',
|
||||||
|
'TINY_PRODUCT_TEXTIL_PREMIUM': '105', 'TINY_FORMA_ENVIO_RETIRADA': '77'}
|
||||||
PICKUP = {**PAID, 'order': {**PAID['order'], 'destination': None, 'freight': {'service': 'pickup', 'total_cents': 0}}}
|
PICKUP = {**PAID, 'order': {**PAID['order'], 'destination': None, 'freight': {'service': 'pickup', 'total_cents': 0}}}
|
||||||
READY = {'order_id': PAID['order_id'], 'number': 42, 'event': 'ready', 'reason': '', 'order': PICKUP['order']}
|
READY = {'order_id': PAID['order_id'], 'number': 42, 'event': 'ready', 'reason': '', 'order': PICKUP['order']}
|
||||||
|
|
||||||
@@ -159,8 +160,17 @@ class TinyTests(FakeTinyCase):
|
|||||||
with mock.patch.dict(os.environ, {'TINY_PRODUCT_TREATMENT': '105'}):
|
with mock.patch.dict(os.environ, {'TINY_PRODUCT_TREATMENT': '105'}):
|
||||||
pedido = order_payload(treatment, 777, date(2026, 9, 24))
|
pedido = order_payload(treatment, 777, date(2026, 9, 24))
|
||||||
self.assertIn({'produto': {'id': 105}, 'quantidade': 1, 'valorUnitario': 9.9,
|
self.assertIn({'produto': {'id': 105}, 'quantidade': 1, 'valorUnitario': 9.9,
|
||||||
'infoAdicional': 'Tratamento da arte pelo designer · +24 h'}, pedido['itens'])
|
'infoAdicional': 'Ajuste Fino · 1 arte · +24 h'}, pedido['itens'])
|
||||||
self.assertNotEqual(pedido['dataPrevista'], order_payload(plain, 777, date(2026, 9, 24))['dataPrevista'])
|
self.assertNotEqual(pedido['dataPrevista'], order_payload(plain, 777, date(2026, 9, 24))['dataPrevista'])
|
||||||
|
# Per art: the quantity is the number of arts and the unit is the band price.
|
||||||
|
per_art = {'order': {**base, 'treatment': {'cents': 2070, 'hours': 24, 'arts': 3,
|
||||||
|
'unit_cents': 690},
|
||||||
|
'total_cents': base['total_cents'] + 2070},
|
||||||
|
**{k: v for k, v in PAID.items() if k != 'order'}}
|
||||||
|
with mock.patch.dict(os.environ, {'TINY_PRODUCT_TREATMENT': '105'}):
|
||||||
|
pedido = order_payload(per_art, 777, date(2026, 9, 24))
|
||||||
|
self.assertIn({'produto': {'id': 105}, 'quantidade': 3, 'valorUnitario': 6.9,
|
||||||
|
'infoAdicional': 'Ajuste Fino · 3 artes · +24 h'}, pedido['itens'])
|
||||||
|
|
||||||
def test_second_delivery_finds_the_first_order(self):
|
def test_second_delivery_finds_the_first_order(self):
|
||||||
first = self.tiny.deliver('k1', PAID)
|
first = self.tiny.deliver('k1', PAID)
|
||||||
@@ -221,7 +231,7 @@ class TinyTests(FakeTinyCase):
|
|||||||
from app.tiny import check
|
from app.tiny import check
|
||||||
results = check(auth=FakeAuth(), transport=httpx.MockTransport(self.handler))
|
results = check(auth=FakeAuth(), transport=httpx.MockTransport(self.handler))
|
||||||
self.assertEqual(set(results.values()), {'ok'})
|
self.assertEqual(set(results.values()), {'ok'})
|
||||||
self.assertEqual(len(results), 7)
|
self.assertEqual(len(results), 8)
|
||||||
self.assertTrue(all(method == 'GET' for method, _ in self.calls))
|
self.assertTrue(all(method == 'GET' for method, _ in self.calls))
|
||||||
self.products['103']['situacao'] = 'I'
|
self.products['103']['situacao'] = 'I'
|
||||||
with mock.patch.dict(os.environ, {'TINY_PRODUCT_UV_AVULSA': ''}):
|
with mock.patch.dict(os.environ, {'TINY_PRODUCT_UV_AVULSA': ''}):
|
||||||
@@ -794,6 +804,9 @@ class DefaultSkuTests(unittest.TestCase):
|
|||||||
self.assertEqual(tiny.mode_codes('file'), tiny.sku_codes('DTFIMP.TX'))
|
self.assertEqual(tiny.mode_codes('file'), tiny.sku_codes('DTFIMP.TX'))
|
||||||
self.assertEqual(tiny.mode_codes('avulsa'), tiny.sku_codes('DTFIMP.TX'))
|
self.assertEqual(tiny.mode_codes('avulsa'), tiny.sku_codes('DTFIMP.TX'))
|
||||||
self.assertEqual(tiny.mode_codes('uv'), ['DTFIMP.UV.1MT', 'DTFIMP.UV.010CM'])
|
self.assertEqual(tiny.mode_codes('uv'), ['DTFIMP.UV.1MT', 'DTFIMP.UV.010CM'])
|
||||||
|
# Premium's own catalogue: DTFIMP.TXP.100CM per metre and DTFIMP.TXP.0010CM to 0090CM (Marcus, 2026-11-11).
|
||||||
|
self.assertEqual(tiny.mode_codes('premium'), tiny.sku_codes('DTFIMP.TXP'))
|
||||||
|
self.assertIn('DTFIMP.TXP.0010CM', tiny.mode_codes('premium'))
|
||||||
self.assertEqual(tiny.required_settings(), ['TINY_CLIENT_ID', 'TINY_CLIENT_SECRET', 'TINY_REDIRECT_URI'])
|
self.assertEqual(tiny.required_settings(), ['TINY_CLIENT_ID', 'TINY_CLIENT_SECRET', 'TINY_REDIRECT_URI'])
|
||||||
with mock.patch.dict(os.environ, {'TINY_SKU10_UV_FOLHA': 'UV.X'}):
|
with mock.patch.dict(os.environ, {'TINY_SKU10_UV_FOLHA': 'UV.X'}):
|
||||||
self.assertEqual(tiny.mode_codes('uvfile'), ['UV.X'])
|
self.assertEqual(tiny.mode_codes('uvfile'), ['UV.X'])
|
||||||
|
|||||||
@@ -24,14 +24,14 @@ def run():
|
|||||||
'note': 'Gerado pelo Prumo'}, operator=True)
|
'note': 'Gerado pelo Prumo'}, operator=True)
|
||||||
blocked = client.call('/operator/orders/' + order['id'] + '/move',
|
blocked = client.call('/operator/orders/' + order['id'] + '/move',
|
||||||
{'state': 'tra', 'version': approved['version']}, operator=True, expected=409)
|
{'state': 'tra', 'version': approved['version']}, operator=True, expected=409)
|
||||||
assert 'Tratamento pago' in blocked['detail'], blocked
|
assert 'Ajuste Fino pago' in blocked['detail'], blocked
|
||||||
prepared = upload_bytes(client, artwork(), name='LOCAL-TREATMENT-FINAL.png', order_id=order['id'])
|
prepared = upload_bytes(client, artwork(), name='LOCAL-TREATMENT-FINAL.png', order_id=order['id'])
|
||||||
approved = client.call('/operator/orders/' + order['id'] + '/final-files',
|
approved = client.call('/operator/orders/' + order['id'] + '/final-files',
|
||||||
{'version': approved['version'], 'files': [{'item_index': 0, 'upload_id': prepared}],
|
{'version': approved['version'], 'files': [{'item_index': 0, 'upload_id': prepared}],
|
||||||
'note': 'PNG tratado pelo designer'}, operator=True)
|
'note': 'PNG tratado pelo designer'}, operator=True)
|
||||||
client.call('/operator/orders/' + order['id'] + '/move',
|
client.call('/operator/orders/' + order['id'] + '/move',
|
||||||
{'state': 'tra', 'version': approved['version']}, operator=True)
|
{'state': 'tra', 'version': approved['version']}, operator=True)
|
||||||
print('PASS: generated artwork cannot satisfy paid treatment; designer PNG opens the print queue')
|
print('PASS: generated artwork cannot satisfy paid Ajuste Fino; designer PNG opens the print queue')
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
|
|||||||
40
tests/upload_limits_test.py
Normal file
40
tests/upload_limits_test.py
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
"""The upload start limit: a large cart fits, and the per-source bucket
|
||||||
|
still refuses above its own limit (Marcus's bugs of 2026-11-11, B1).
|
||||||
|
|
||||||
|
Run against the local stack: python -m tests.upload_limits_test
|
||||||
|
"""
|
||||||
|
import secrets
|
||||||
|
|
||||||
|
from fastapi import HTTPException
|
||||||
|
|
||||||
|
from app.api.uploads import UPLOAD_START_IP_LIMIT, UPLOAD_START_LIMIT
|
||||||
|
from app.core.auth import rate_limit
|
||||||
|
from tests.smoke_test import Client
|
||||||
|
|
||||||
|
|
||||||
|
def run():
|
||||||
|
assert (UPLOAD_START_LIMIT, UPLOAD_START_IP_LIMIT) == (1000, 3000)
|
||||||
|
client = Client()
|
||||||
|
client.call('/session')
|
||||||
|
# A 66-file cart, with retries, fits in one session. Each reservation is
|
||||||
|
# cancelled so the pending-upload quota (unchanged) does not stop the test.
|
||||||
|
for index in range(70):
|
||||||
|
uid = client.call('/uploads', {'name': f'LIMIT-{index}.png', 'size': 1})['id']
|
||||||
|
client.call(f'/uploads/{uid}', expected=200, method='DELETE')
|
||||||
|
# The per-source bucket, exercised directly with a small limit: 3000 real
|
||||||
|
# starts would only slow CI. A unique key keeps other suites out of it.
|
||||||
|
key = 'upload-start-ip-test-' + secrets.token_hex(8)
|
||||||
|
for _ in range(3):
|
||||||
|
rate_limit('upload-start-ip', key, 3, 900)
|
||||||
|
try:
|
||||||
|
rate_limit('upload-start-ip', key, 3, 900)
|
||||||
|
except HTTPException as error:
|
||||||
|
assert error.status_code == 429, error
|
||||||
|
assert error.headers.get('Retry-After') == '900', error.headers
|
||||||
|
else:
|
||||||
|
raise AssertionError('the per-source upload bucket accepted above its limit')
|
||||||
|
print('PASS: 70 upload starts in one session; the per-source bucket refuses above its limit')
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
run()
|
||||||
@@ -203,7 +203,7 @@ def run():
|
|||||||
'password': PASSWORD})
|
'password': PASSWORD})
|
||||||
reviewer = signed_in(emails['revisor'])
|
reviewer = signed_in(emails['revisor'])
|
||||||
me = reviewer.call('/operator/me')
|
me = reviewer.call('/operator/me')
|
||||||
assert me['can'] == ['deliver', 'inspect', 'view'] and sorted(me['moves']) == [['fin', 'rev'], ['rev', 'fin']] and me['reorder'] == ['rev'], me
|
assert me['can'] == ['deliver', 'inspect', 'label', '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)
|
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'],
|
assert reviewer.call(f'/operator/orders/{uv_o}/move', {'state': 'fin', 'version': printed['version'],
|
||||||
'reason': ''})['state'] == 'fin'
|
'reason': ''})['state'] == 'fin'
|
||||||
|
|||||||
@@ -27,7 +27,7 @@
|
|||||||
stroke:item.strokeClass||null,strokeChoice:item.strokeChoice||null,
|
stroke:item.strokeClass||null,strokeChoice:item.strokeChoice||null,
|
||||||
sheets:(item.partes||[]).map(part=>part.production),
|
sheets:(item.partes||[]).map(part=>part.production),
|
||||||
files:(item.localFiles||[]).map(file=>({name:file.name,size:file.size,lastModified:file.lastModified}))
|
files:(item.localFiles||[]).map(file=>({name:file.name,size:file.size,lastModified:file.lastModified}))
|
||||||
})),treatment:!!$('fTratamento')?.checked,coupon:cupomCode()});
|
})),treatment:ajusteSnapshot(),coupon:cupomCode()});
|
||||||
}
|
}
|
||||||
// The quote this browser is paying, forgotten. clearDraft also empties the
|
// The quote this browser is paying, forgotten. clearDraft also empties the
|
||||||
// payment area; forgetDraft leaves on screen what is there (a confirmation).
|
// payment area; forgetDraft leaves on screen what is there (a confirmation).
|
||||||
@@ -46,7 +46,18 @@
|
|||||||
let data;
|
let data;
|
||||||
try { data = text ? JSON.parse(text) : {}; }
|
try { data = text ? JSON.parse(text) : {}; }
|
||||||
catch (_) { throw new Error(response.ok ? 'Resposta inválida do serviço.' : 'O serviço está indisponível. Tente novamente em instantes.'); }
|
catch (_) { throw new Error(response.ok ? 'Resposta inválida do serviço.' : 'O serviço está indisponível. Tente novamente em instantes.'); }
|
||||||
if (!response.ok) { const error=new Error(problem(data.detail));error.status=response.status;throw error; }
|
if (!response.ok) {
|
||||||
|
const text=problem(data.detail);
|
||||||
|
// A validation the customer cannot read still needs to reach us (Sentry
|
||||||
|
// picks up console.error later); the customer keeps the generic sentence.
|
||||||
|
if (response.status===422 && text==='Não foi possível concluir. Confira os dados e tente de novo.')
|
||||||
|
console.error('Detalhe da validação recusada:',data.detail);
|
||||||
|
const error=new Error(text);error.status=response.status;
|
||||||
|
const retry=response.headers.get('Retry-After');
|
||||||
|
if(retry!=null)error.retryAfter=retry;
|
||||||
|
window.dtfObservability?.apiError?.(path,response.status,error.message,data.detail);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
return data;
|
return data;
|
||||||
};
|
};
|
||||||
// A refusal as one sentence: the server's own, or the first field a form
|
// A refusal as one sentence: the server's own, or the first field a form
|
||||||
@@ -60,6 +71,9 @@
|
|||||||
}
|
}
|
||||||
const ready = api('/session');
|
const ready = api('/session');
|
||||||
ready.then(session=>{
|
ready.then(session=>{
|
||||||
|
window.dtfEnvironment=session.sentry_environment||session.environment;
|
||||||
|
window.dtfRelease=session.sentry_release||undefined;
|
||||||
|
window.dtfObservability?.start?.(session.sentry_dsn_web,'site');
|
||||||
window.dtfUploadMaxBytes=session.max_upload_bytes;
|
window.dtfUploadMaxBytes=session.max_upload_bytes;
|
||||||
const limit=document.getElementById('zLimite');
|
const limit=document.getElementById('zLimite');
|
||||||
if(limit)limit.textContent='Até '+(session.max_upload_bytes/1073741824).toFixed(0)+' GB por arquivo.';
|
if(limit)limit.textContent='Até '+(session.max_upload_bytes/1073741824).toFixed(0)+' GB por arquivo.';
|
||||||
@@ -80,9 +94,11 @@
|
|||||||
// The art grade rules (front 8.5): the Site uses only the treatment rule,
|
// The art grade rules (front 8.5): the Site uses only the treatment rule,
|
||||||
// forcing the checkbox when the cart's worst grade is below it.
|
// forcing the checkbox when the cart's worst grade is below it.
|
||||||
window.dtfGradeRules=session.grade_rules||{};
|
window.dtfGradeRules=session.grade_rules||{};
|
||||||
// Treatment by the designer (front 5): only offered when TREATMENT_CENTS
|
// Ajuste Fino (front 1a): per art, with a band by the order's number of
|
||||||
// is set; the server adds the same amount and the 24 h to the quote.
|
// arts. Only offered when TREATMENT_CENTS is set; the server adds the
|
||||||
|
// same amount and the 24 h to the quote.
|
||||||
TAXA_TRATAMENTO=(session.treatment_cents||0)/100;
|
TAXA_TRATAMENTO=(session.treatment_cents||0)/100;
|
||||||
|
FAIXAS.tratamento=session.treatment_bands||[];
|
||||||
const tratamentoBox=document.getElementById('tratamentoBox');
|
const tratamentoBox=document.getElementById('tratamentoBox');
|
||||||
if(tratamentoBox){
|
if(tratamentoBox){
|
||||||
tratamentoBox.hidden=!(TAXA_TRATAMENTO>0);
|
tratamentoBox.hidden=!(TAXA_TRATAMENTO>0);
|
||||||
@@ -97,7 +113,8 @@
|
|||||||
PRECO[mode]=product.unit_cents/100;
|
PRECO[mode]=product.unit_cents/100;
|
||||||
FAIXAS[mode]=product.bands||[];
|
FAIXAS[mode]=product.bands||[];
|
||||||
const card=document.querySelector('button.ec[data-modo="'+mode+'"]');
|
const card=document.querySelector('button.ec[data-modo="'+mode+'"]');
|
||||||
if(card&&!product.enabled)card.hidden=true;
|
// Premium starts hidden in the HTML and only appears once enabled.
|
||||||
|
if(card)card.hidden=!product.enabled;
|
||||||
}
|
}
|
||||||
document.querySelectorAll('[data-preco]').forEach(el=>{
|
document.querySelectorAll('[data-preco]').forEach(el=>{
|
||||||
const product=session.products[el.dataset.preco];
|
const product=session.products[el.dataset.preco];
|
||||||
@@ -115,6 +132,7 @@
|
|||||||
}
|
}
|
||||||
window.dtfProducts=session.products;
|
window.dtfProducts=session.products;
|
||||||
if(typeof folhas!=='undefined'&&folhas.length&&typeof pintaFolha==='function')pintaFolha();
|
if(typeof folhas!=='undefined'&&folhas.length&&typeof pintaFolha==='function')pintaFolha();
|
||||||
|
if(typeof artes!=='undefined'&&artes.length&&typeof pintaArtes==='function')pintaArtes();
|
||||||
if(typeof itemAtual!=='undefined'&&itemAtual&&typeof carrinho==='function')carrinho();
|
if(typeof itemAtual!=='undefined'&&itemAtual&&typeof carrinho==='function')carrinho();
|
||||||
if(typeof pintaTipoEnvio==='function')pintaTipoEnvio();
|
if(typeof pintaTipoEnvio==='function')pintaTipoEnvio();
|
||||||
semPedidos=!Object.values(session.products).some(product=>product.enabled);
|
semPedidos=!Object.values(session.products).some(product=>product.enabled);
|
||||||
@@ -173,8 +191,11 @@
|
|||||||
const prazo = approved.freight.days ? ' · até '+approved.freight.days+' dias úteis' : '';
|
const prazo = approved.freight.days ? ' · até '+approved.freight.days+' dias úteis' : '';
|
||||||
rows.push(linha(pickup ? 'Retirada em Franca' : (approved.freight.description || 'Frete')+prazo,
|
rows.push(linha(pickup ? 'Retirada em Franca' : (approved.freight.description || 'Frete')+prazo,
|
||||||
approved.freight.total_cents ? rs(approved.freight.total_cents/100) : 'Grátis'));
|
approved.freight.total_cents ? rs(approved.freight.total_cents/100) : 'Grátis'));
|
||||||
if(quote.treatment?.cents)
|
if(quote.treatment?.cents){
|
||||||
rows.push(linha('Tratamento da arte pelo designer · +24 h', rs(quote.treatment.cents/100)));
|
const arts=Number(quote.treatment.arts)||0;
|
||||||
|
rows.push(linha('Ajuste Fino'+(arts?' · '+arts+(arts===1?' arte':' artes'):'')+' · +24 h',
|
||||||
|
rs(quote.treatment.cents/100)));
|
||||||
|
}
|
||||||
if(approved.coupon)
|
if(approved.coupon)
|
||||||
rows.push(linha('Cupom '+approved.coupon.code, '− '+rs(approved.coupon.discount_cents/100)));
|
rows.push(linha('Cupom '+approved.coupon.code, '− '+rs(approved.coupon.discount_cents/100)));
|
||||||
rows.push(linha('Total', rs(approved.total_cents/100), 'tot'));
|
rows.push(linha('Total', rs(approved.total_cents/100), 'tot'));
|
||||||
@@ -261,10 +282,35 @@
|
|||||||
pintaEnvio();
|
pintaEnvio();
|
||||||
}
|
}
|
||||||
const arquivosDoCarrinho=()=>[...pedido.filter(it=>it.marcado!==false),...(busy&&itemAtual?[itemAtual]:[])].flatMap(it=>it.localFiles||[]);
|
const arquivosDoCarrinho=()=>[...pedido.filter(it=>it.marcado!==false),...(busy&&itemAtual?[itemAtual]:[])].flatMap(it=>it.localFiles||[]);
|
||||||
|
// Every file of the paying cart must be sent (and none failed) before the
|
||||||
|
// quote and before the payment button (bugs B2 and B4, Marcus 2026-11-11).
|
||||||
|
function faltaEnvio(){
|
||||||
|
const files=arquivosDoCarrinho();
|
||||||
|
let pending=0,failed=0;
|
||||||
|
for(const f of files){
|
||||||
|
const k=chaveArquivo(f);
|
||||||
|
if(falhas.has(k)){failed++;continue;}
|
||||||
|
const e=envios.get(k);
|
||||||
|
if(!e||!e.done)pending++;
|
||||||
|
}
|
||||||
|
return {total:files.length,pending,failed,falta:pending+failed};
|
||||||
|
}
|
||||||
|
window.dtfFaltaEnvio=faltaEnvio;
|
||||||
|
function faltaEnvioMensagem(){
|
||||||
|
const missing=[];
|
||||||
|
for(const f of arquivosDoCarrinho()){
|
||||||
|
const k=chaveArquivo(f),e=envios.get(k);
|
||||||
|
if(falhas.has(k)||!e||!e.done)missing.push(f);
|
||||||
|
}
|
||||||
|
if(!missing.length) return '';
|
||||||
|
return 'Falta enviar '+missing[0].name+
|
||||||
|
(missing.length>1?' (e mais '+(missing.length-1)+')':'');
|
||||||
|
}
|
||||||
const gb=n=>(n/1073741824).toLocaleString('pt-BR',{maximumFractionDigits:1})+' GB';
|
const gb=n=>(n/1073741824).toLocaleString('pt-BR',{maximumFractionDigits:1})+' GB';
|
||||||
const mb=n=>n>=1073741824 ? gb(n) : Math.round(n/1048576)+' MB';
|
const mb=n=>n>=1073741824 ? gb(n) : Math.round(n/1048576)+' MB';
|
||||||
// Where the uploads stand, and roughly how long is left from the recent speed.
|
// Where the uploads stand, and roughly how long is left from the recent speed.
|
||||||
const amostras=[];
|
const amostras=[];
|
||||||
|
let ultimaFalta=null;
|
||||||
function estadoEnvio() {
|
function estadoEnvio() {
|
||||||
const files=arquivosDoCarrinho(); if(!files.length) return null;
|
const files=arquivosDoCarrinho(); if(!files.length) return null;
|
||||||
let total=0, sent=0, pendentes=0;
|
let total=0, sent=0, pendentes=0;
|
||||||
@@ -291,6 +337,13 @@
|
|||||||
return 'Enviando seus arquivos · '+restante(e);
|
return 'Enviando seus arquivos · '+restante(e);
|
||||||
}
|
}
|
||||||
function pintaEnvio() {
|
function pintaEnvio() {
|
||||||
|
// The cart button carries the uploads too (B2): repaint it only when the
|
||||||
|
// number of missing files changes, not on every progress tick.
|
||||||
|
const falta=faltaEnvio().falta;
|
||||||
|
if(falta!==ultimaFalta){
|
||||||
|
ultimaFalta=falta;
|
||||||
|
if(typeof pintaPedido==='function')pintaPedido();
|
||||||
|
}
|
||||||
window.dispatchEvent(new Event('dtf-envio'));
|
window.dispatchEvent(new Event('dtf-envio'));
|
||||||
const e=estadoEnvio(), texto=textoEnvio(e);
|
const e=estadoEnvio(), texto=textoEnvio(e);
|
||||||
const el=document.getElementById('envioArq');
|
const el=document.getElementById('envioArq');
|
||||||
@@ -390,6 +443,8 @@
|
|||||||
if (!clienteOk() || !entrega.cotado) return;
|
if (!clienteOk() || !entrega.cotado) return;
|
||||||
if (!enderecoOk()) return message('Preencha o endereço de entrega.','error');
|
if (!enderecoOk()) return message('Preencha o endereço de entrega.','error');
|
||||||
if (!cartPodeEnviar()) return message('Revise a qualidade e confirme a ressalva de cada item antes de enviar o pedido.','error');
|
if (!cartPodeEnviar()) return message('Revise a qualidade e confirme a ressalva de cada item antes de enviar o pedido.','error');
|
||||||
|
const semArquivo=faltaEnvioMensagem();
|
||||||
|
if (semArquivo) return message(semArquivo+'.','error');
|
||||||
const cart = itensAPagar();
|
const cart = itensAPagar();
|
||||||
if (!cart.length) return message('Adicione um item ao pedido.','error');
|
if (!cart.length) return message('Adicione um item ao pedido.','error');
|
||||||
const initialCart=cartSnapshot();
|
const initialCart=cartSnapshot();
|
||||||
@@ -434,7 +489,9 @@
|
|||||||
if (destination) content.destination = destination;
|
if (destination) content.destination = destination;
|
||||||
// "Quero aprovar uma prova antes de imprimir": the order waits for the customer.
|
// "Quero aprovar uma prova antes de imprimir": the order waits for the customer.
|
||||||
if ($('fProva')?.checked) content.proof = true;
|
if ($('fProva')?.checked) content.proof = true;
|
||||||
if ($('fTratamento')?.checked) content.treatment = true;
|
// Ajuste Fino: true for every art, or the [item, source] pairs chosen.
|
||||||
|
const treatment=tratamentoParaItens(sheets);
|
||||||
|
if (treatment) content.treatment = treatment;
|
||||||
if (cartSnapshot()!==initialCart) throw new Error('O carrinho mudou durante o envio. Confira os itens e envie de novo.');
|
if (cartSnapshot()!==initialCart) throw new Error('O carrinho mudou durante o envio. Confira os itens e envie de novo.');
|
||||||
// Browser timings for Números (item 0.12); they never affect the price.
|
// Browser timings for Números (item 0.12); they never affect the price.
|
||||||
const T=window.dtfTimings, timings={};
|
const T=window.dtfTimings, timings={};
|
||||||
|
|||||||
@@ -75,6 +75,7 @@ h1 em{font-style:normal;color:var(--laranja)}
|
|||||||
.escolha{display:grid;grid-template-columns:repeat(4,1fr);gap:14px;margin-top:24px;
|
.escolha{display:grid;grid-template-columns:repeat(4,1fr);gap:14px;margin-top:24px;
|
||||||
align-items:stretch}
|
align-items:stretch}
|
||||||
.escolha .ec{display:flex;flex-direction:column}
|
.escolha .ec{display:flex;flex-direction:column}
|
||||||
|
.escolha .ec[hidden]{display:none}
|
||||||
.escolha .ec .in{flex:1}
|
.escolha .ec .in{flex:1}
|
||||||
@media(max-width:1000px){.escolha{grid-template-columns:repeat(2,1fr)}}
|
@media(max-width:1000px){.escolha{grid-template-columns:repeat(2,1fr)}}
|
||||||
@media(max-width:600px){.escolha{grid-template-columns:1fr}}
|
@media(max-width:600px){.escolha{grid-template-columns:1fr}}
|
||||||
@@ -640,6 +641,8 @@ h2 em{font-style:normal;color:var(--laranja)}
|
|||||||
@media(prefers-reduced-motion:reduce){*{transition:none!important;scroll-behavior:auto}}
|
@media(prefers-reduced-motion:reduce){*{transition:none!important;scroll-behavior:auto}}
|
||||||
</style>
|
</style>
|
||||||
<link rel="stylesheet" href="/site-v2.css">
|
<link rel="stylesheet" href="/site-v2.css">
|
||||||
|
<script src="/vendor/sentry.min.js"></script>
|
||||||
|
<script src="/observability.js"></script>
|
||||||
<script src="/site-pages.js"></script>
|
<script src="/site-pages.js"></script>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
@@ -815,6 +818,15 @@ h2 em{font-style:normal;color:var(--laranja)}
|
|||||||
<span class="ec-go">Enviar artes de UV</span>
|
<span class="ec-go">Enviar artes de UV</span>
|
||||||
</div>
|
</div>
|
||||||
</button>
|
</button>
|
||||||
|
<button class="ec p" data-modo="premium" hidden>
|
||||||
|
<div class="ec-top"><span class="ec-kind">DTF TÊXTIL PREMIUM · 57 CM</span></div>
|
||||||
|
<h3>Premium · 8 passadas</h3>
|
||||||
|
<p>Branco no máximo e cor mais fechada, para marca própria.</p>
|
||||||
|
<div class="ec-pe">
|
||||||
|
<div class="ec-preco"><b data-preco="premium">R$ 39,90</b><span>por metro</span></div>
|
||||||
|
<span class="ec-go">Enviar minha folha</span>
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -1111,9 +1123,9 @@ h2 em{font-style:normal;color:var(--laranja)}
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="cxE" id="tratamentoBox" hidden>
|
<div class="cxE" id="tratamentoBox" hidden>
|
||||||
<h4>Tratamento da arte</h4>
|
<h4>Ajuste Fino</h4>
|
||||||
<label class="provaOp"><input type="checkbox" id="fTratamento">
|
<label class="provaOp"><input type="checkbox" id="fTratamento">
|
||||||
<span><b>Quero o tratamento pelo designer — <span id="tratamentoPreco"></span></b>
|
<span><b>Ajuste Fino em todas as artes — <span id="tratamentoPreco"></span> por arte</b>
|
||||||
O designer ajusta a arte para DTF, com fundo transparente e 300 DPI, e sobe o arquivo
|
O designer ajusta a arte para DTF, com fundo transparente e 300 DPI, e sobe o arquivo
|
||||||
pelo card. O prazo do pedido aumenta em 24 h.</span></label>
|
pelo card. O prazo do pedido aumenta em 24 h.</span></label>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
147
web/kanban-label.js
Normal file
147
web/kanban-label.js
Normal file
@@ -0,0 +1,147 @@
|
|||||||
|
/* Kanban DTF — the 10x15 cm label at Finalizado (Fase 2, front 10).
|
||||||
|
|
||||||
|
Marcus, 2026-11-10: when a card reaches Finalizado the Kanban prints a Zebra
|
||||||
|
ZD220 label by itself. The server renders the page (app/label.py), so this
|
||||||
|
file only decides which computer prints it: the first to claim it prints it
|
||||||
|
once, and whoever may see labels can reprint. The browser opts in here, in
|
||||||
|
Integrações, and only orders that reach Finalizado after that moment are
|
||||||
|
printed automatically, never the whole history. */
|
||||||
|
|
||||||
|
const LABEL_SINCE = 'label-print-since';
|
||||||
|
const LABEL_ASKED = new Set(); // claimed from this browser in this session
|
||||||
|
const LABEL_BUSY = new Set(); // a claim in flight, so two loads do not repeat it
|
||||||
|
|
||||||
|
function labelSince() {
|
||||||
|
try {
|
||||||
|
const value = localStorage.getItem(LABEL_SINCE);
|
||||||
|
const date = value ? new Date(value) : null;
|
||||||
|
return date && !Number.isNaN(date.getTime()) ? date : null;
|
||||||
|
} catch (error) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function labelSetSince(on) {
|
||||||
|
try {
|
||||||
|
if (on) localStorage.setItem(LABEL_SINCE, new Date().toISOString());
|
||||||
|
else localStorage.removeItem(LABEL_SINCE);
|
||||||
|
} catch (error) {
|
||||||
|
// A browser that cannot store it simply never prints automatically.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function labelEnabled() {
|
||||||
|
return !!labelSince();
|
||||||
|
}
|
||||||
|
|
||||||
|
// The label page is rendered by the server; this prints what it returns.
|
||||||
|
async function labelPrint(orderId) {
|
||||||
|
const response = await fetch('/api/operator/orders/' + encodeURIComponent(orderId) + '/label',
|
||||||
|
{credentials: 'same-origin', cache: 'no-store'});
|
||||||
|
if (!response.ok) throw new Error('Não foi possível abrir a etiqueta (' + response.status + ').');
|
||||||
|
const page = await response.text();
|
||||||
|
await new Promise((resolve, reject) => {
|
||||||
|
const frame = document.createElement('iframe');
|
||||||
|
frame.setAttribute('aria-hidden', 'true');
|
||||||
|
frame.tabIndex = -1;
|
||||||
|
frame.style.cssText = 'position:fixed;left:-10000px;top:0;width:100mm;height:150mm;border:0';
|
||||||
|
let closed = false;
|
||||||
|
const done = () => {
|
||||||
|
if (closed) return;
|
||||||
|
closed = true;
|
||||||
|
frame.remove();
|
||||||
|
resolve();
|
||||||
|
};
|
||||||
|
frame.addEventListener('load', () => {
|
||||||
|
try {
|
||||||
|
const view = frame.contentWindow;
|
||||||
|
view.addEventListener('afterprint', done, {once: true});
|
||||||
|
// A browser that never fires afterprint still releases the frame.
|
||||||
|
setTimeout(done, 120000);
|
||||||
|
view.focus();
|
||||||
|
view.print();
|
||||||
|
} catch (error) {
|
||||||
|
done();
|
||||||
|
reject(error);
|
||||||
|
}
|
||||||
|
}, {once: true});
|
||||||
|
// The gateway adds X-Frame-Options: DENY and frame-ancestors 'none' to
|
||||||
|
// /api responses, so the label URL cannot be framed directly. The page is
|
||||||
|
// still the server's: it is fetched and written into a srcdoc iframe,
|
||||||
|
// which is not a framed navigation and inherits this page's policy.
|
||||||
|
frame.srcdoc = page;
|
||||||
|
document.body.append(frame);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function labelReprintButton(order, className = 'btn lg') {
|
||||||
|
if (!may('label') || order.state !== 'fin' || order.cancelled_at) return null;
|
||||||
|
const print = button('Reimprimir etiqueta', async () => {
|
||||||
|
try {
|
||||||
|
await api('/orders/' + order.id + '/label/reprint', {});
|
||||||
|
await labelPrint(order.id);
|
||||||
|
say('Etiqueta do pedido #' + order.number + ' enviada para a impressora.');
|
||||||
|
} catch (error) {
|
||||||
|
say(error.message, true);
|
||||||
|
}
|
||||||
|
}, className);
|
||||||
|
print.prepend(svgIcon(IC.printer, 'i m'));
|
||||||
|
return print;
|
||||||
|
}
|
||||||
|
|
||||||
|
// After every board load: claim the labels of the orders that reached
|
||||||
|
// Finalizado after this browser opted in. Only one computer gets print:true.
|
||||||
|
async function labelAfterLoad() {
|
||||||
|
if (!may('label') || !labelEnabled() || !board) return;
|
||||||
|
const since = labelSince();
|
||||||
|
for (const order of board.orders) {
|
||||||
|
if (order.state !== 'fin' || order.cancelled_at || !order.finished_at) continue;
|
||||||
|
if (new Date(order.finished_at) <= since) continue;
|
||||||
|
if (LABEL_ASKED.has(order.id) || LABEL_BUSY.has(order.id)) continue;
|
||||||
|
LABEL_BUSY.add(order.id);
|
||||||
|
try {
|
||||||
|
const answer = await api('/orders/' + order.id + '/label/claim', {});
|
||||||
|
LABEL_ASKED.add(order.id);
|
||||||
|
if (answer.print) {
|
||||||
|
try {
|
||||||
|
await labelPrint(order.id);
|
||||||
|
} catch (error) {
|
||||||
|
say('Etiqueta do pedido #' + order.number + ': ' + error.message, true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
// The claim did not answer: not marked, so the next board load retries it.
|
||||||
|
} finally {
|
||||||
|
LABEL_BUSY.delete(order.id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The Integrações row: the switch that makes this browser the label printer.
|
||||||
|
function labelIntegrationRow() {
|
||||||
|
if (!may('label')) return null;
|
||||||
|
const on = labelEnabled();
|
||||||
|
const input = node('input');
|
||||||
|
const toggle = checkbox('Esta tela imprime as etiquetas', input);
|
||||||
|
input.checked = on;
|
||||||
|
input.onchange = () => {
|
||||||
|
labelSetSince(input.checked);
|
||||||
|
say(input.checked
|
||||||
|
? 'Etiqueta ligada: os pedidos que chegarem em Finalizado daqui em diante serão impressos.'
|
||||||
|
: 'Etiqueta desligada nesta tela.');
|
||||||
|
renderIntegrations();
|
||||||
|
};
|
||||||
|
const since = labelSince();
|
||||||
|
return integration({
|
||||||
|
name: 'Etiqueta 10×15', state: on ? 'Ligada' : 'Desligada', tone: on ? 'ok' : 'off',
|
||||||
|
summary: on ? 'Esta tela imprime as etiquetas de pedidos que chegam em Finalizado.'
|
||||||
|
: 'Esta tela não imprime etiquetas.',
|
||||||
|
actions: [toggle],
|
||||||
|
details: [
|
||||||
|
node('p', 'A etiqueta é impressa uma vez, no primeiro computador que a pegar; os outros não a imprimem de novo. ' +
|
||||||
|
'O Revisor e a Expedição também podem reimprimir pelo card do pedido em Finalizado.'),
|
||||||
|
node('p', 'Para imprimir sem a janela de confirmação, abra o Chrome com --kiosk-printing e deixe a Zebra ZD220 como impressora padrão.'),
|
||||||
|
...(since ? [['Ligada desde', when(since.toISOString())]] : [])
|
||||||
|
]
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -1,20 +1,239 @@
|
|||||||
/* Kanban DTF: "Montar folha" (Fase 2, front 7). The stamps are the PNG files
|
/* Kanban DTF: "Montar folha" (Fase 2, front 7). The stamps are the PNG files
|
||||||
in Estampas/ inside the folder chosen in Integrações; the sizes are the
|
in Estampas/ inside the folder chosen in Integrações; the sizes are the
|
||||||
table Gestão edits. The packing is the Site's own engine (web/packing.js).
|
table Gestão edits. The packing is the Site's own engine (web/packing.js).
|
||||||
Montar, which creates the card, is slice 2b. Uses the globals of kanban.js
|
Montar creates the card: Interno for the Expedição, Venda for a customer
|
||||||
and packing.js, loaded first. */
|
picked from Tiny (front 7a.3). Uses the globals of kanban.js and packing.js,
|
||||||
|
loaded first. */
|
||||||
const MONTAR_CODE=/^[A-Za-z0-9_-]{1,40}$/;
|
const MONTAR_CODE=/^[A-Za-z0-9_-]{1,40}$/;
|
||||||
// The Site's ruler (web/site-config.js): the same numbers, copied there too.
|
// The Site's ruler (web/site-config.js): the same numbers, copied there too.
|
||||||
const MONTAR_DPI_REFUSE=96, MONTAR_DPI_WARN=200;
|
const MONTAR_DPI_REFUSE=96, MONTAR_DPI_WARN=200;
|
||||||
const MONTAR_FILM_CM=57, MONTAR_GAP_CM=0.5;
|
const MONTAR_FILM_CM=57, MONTAR_GAP_CM=0.5;
|
||||||
const MONTAR={sizes:[],lines:[],seq:0,preview:null,timer:null,dirty:false,token:0,
|
const MONTAR={sizes:[],lines:[],seq:0,preview:null,timer:null,dirty:false,token:0,
|
||||||
layout:null,layoutTimer:null,layoutToken:0,layoutPending:false,creating:false,requestKey:null};
|
layout:null,layoutTimer:null,layoutToken:0,layoutPending:false,creating:false,requestKey:null,
|
||||||
|
kind:null,internal:null,internalDirty:false,brands:new Map(),contactToken:0,contactTimer:null,
|
||||||
|
freights:null,freight:null,catalog:null};
|
||||||
|
|
||||||
const montarFolderReady=()=>!!FOLDER.handle&&!!FOLDER.granted;
|
const montarFolderReady=()=>!!FOLDER.handle&&!!FOLDER.granted;
|
||||||
const montarDpi=found=>found.width/(found.widthCm/2.54);
|
const montarDpi=found=>found.width/(found.widthCm/2.54);
|
||||||
const montarHeight=found=>found.widthCm*(found.height/found.width);
|
const montarHeight=found=>found.widthCm*(found.height/found.width);
|
||||||
const montarSelected=()=>MONTAR.sizes.find(size=>size.letter===$('montar-size').value)||null;
|
const montarSelected=()=>MONTAR.sizes.find(size=>size.letter===$('montar-size').value)||null;
|
||||||
|
|
||||||
|
// ---- Interno or Venda ------------------------------------------------------
|
||||||
|
// Marcus's answers of 2026-11-10 (front 7a.3): the Expedição only makes
|
||||||
|
// Interno orders, the Vendedor only Venda, and Gestão and the administrators
|
||||||
|
// both. An Interno order uses the fixed internal customer; a Venda one is
|
||||||
|
// picked from Tiny.
|
||||||
|
const montarKindNames=()=>ME?.role==='expedicao'?['interno']:ME?.role==='vendedor'?['venda']:['interno','venda'];
|
||||||
|
const montarInternalField=key=>String(MONTAR.internal?.[key]||'');
|
||||||
|
const montarInternalReady=()=>!!MONTAR.internal&&['name','cnpj','zap','mail'].every(key=>montarInternalField(key).trim());
|
||||||
|
function montarPaintKind(){
|
||||||
|
const kinds=montarKindNames();
|
||||||
|
if(!MONTAR.kind||!kinds.includes(MONTAR.kind))MONTAR.kind=kinds.length===1?kinds[0]:'venda';
|
||||||
|
if(MONTAR.kind==='interno'&&!montarInternalReady()&&kinds.length>1){
|
||||||
|
MONTAR.kind='venda';
|
||||||
|
for(const id of ['montar-name','montar-doc','montar-zap','montar-mail'])$(id).value='';
|
||||||
|
}
|
||||||
|
const box=$('montar-kind');
|
||||||
|
$('montar-kind-hint').textContent=kinds.length===1
|
||||||
|
?(MONTAR.kind==='interno'?'Interno, para a Expedição.':'Venda, para o Vendedor.')
|
||||||
|
:'Interno para a Expedição; Venda para um cliente do Tiny.';
|
||||||
|
box.hidden=kinds.length<2;
|
||||||
|
box.replaceChildren(...kinds.map(kind=>{
|
||||||
|
const b=node('button',kind==='interno'?'Interno':'Venda',kind===MONTAR.kind?'on':'');b.type='button';
|
||||||
|
b.setAttribute('aria-pressed',String(kind===MONTAR.kind));
|
||||||
|
b.disabled=kind==='interno'&&!montarInternalReady();
|
||||||
|
b.title=b.disabled?'Peça à Gestão para completar o cliente interno.':'';
|
||||||
|
b.onclick=()=>montarSetKind(kind);
|
||||||
|
return b;
|
||||||
|
}));
|
||||||
|
$('montar-interno-missing').hidden=montarInternalReady();
|
||||||
|
}
|
||||||
|
function montarSetKind(kind){
|
||||||
|
if(MONTAR.kind===kind)return;
|
||||||
|
MONTAR.kind=kind;
|
||||||
|
montarClearCustomer();
|
||||||
|
montarPaintKind();montarPaintCustomer();montarPaintActions();
|
||||||
|
}
|
||||||
|
function montarPaintCustomer(){
|
||||||
|
const interno=MONTAR.kind==='interno';
|
||||||
|
$('montar-customer-title').textContent=interno?'Cliente interno':'Cliente';
|
||||||
|
$('montar-customer-search').hidden=interno;
|
||||||
|
$('montar-interno-note').hidden=!interno;
|
||||||
|
$('montar-delivery').hidden=interno;
|
||||||
|
for(const [id,key] of [['montar-name','name'],['montar-doc','cnpj'],['montar-zap','zap'],['montar-mail','mail']]){
|
||||||
|
$(id).disabled=interno;
|
||||||
|
if(interno)$(id).value=montarInternalField(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const montarDelivery=()=>document.querySelector('input[name="montar-delivery"]:checked')?.value||'pickup';
|
||||||
|
function montarPaintDelivery(){
|
||||||
|
const delivery=montarDelivery(),withOrder=delivery==='with_order',ship=delivery==='ship';
|
||||||
|
$('montar-with-order').disabled=!withOrder;
|
||||||
|
if(!withOrder)$('montar-with-order').value='';
|
||||||
|
$('montar-shipping').hidden=!ship;
|
||||||
|
if(ship&&!$('montar-ship-recipient').value.trim())
|
||||||
|
$('montar-ship-recipient').value=$('montar-name').value.trim();
|
||||||
|
montarPaintFreights();
|
||||||
|
}
|
||||||
|
function montarWithOrder(){
|
||||||
|
if(MONTAR.kind!=='venda'||montarDelivery()!=='with_order')return null;
|
||||||
|
const value=Math.round(Number($('montar-with-order').value));
|
||||||
|
return Number.isInteger(value)&&value>=1&&value<=999999?value:null;
|
||||||
|
}
|
||||||
|
// ---- Envio (front 7a.4): the Site's own freight ---------------------------
|
||||||
|
// The Site's public routes for the CEP and the carrier quotes (app/api/health.py);
|
||||||
|
// the Kanban's api() helper only reaches /api/operator.
|
||||||
|
// The Site's UFS list (web/site-config.js), copied for the address select.
|
||||||
|
const MONTAR_UFS='AC AL AP AM BA CE DF ES GO MA MT MS MG PA PB PR PE PI RJ RN RS RO RR SC SP SE TO'.split(' ');
|
||||||
|
const montarCep=()=>$('montar-ship-cep').value.replace(/\D/g,'').slice(0,8);
|
||||||
|
function montarDestination(){
|
||||||
|
const destination={recipient:$('montar-ship-recipient').value.trim(),
|
||||||
|
street:$('montar-ship-street').value.trim(),number:$('montar-ship-number').value.trim(),
|
||||||
|
complement:$('montar-ship-complement').value.trim(),
|
||||||
|
district:$('montar-ship-district').value.trim(),city:$('montar-ship-city').value.trim(),
|
||||||
|
state:$('montar-ship-state').value.trim().toUpperCase(),postal_code:montarCep()};
|
||||||
|
const ok=destination.postal_code.length===8&&destination.recipient.length>=2&&
|
||||||
|
destination.street.length>=2&&destination.number.length>=1&&
|
||||||
|
destination.district.length>=2&&destination.city.length>=2&&MONTAR_UFS.includes(destination.state);
|
||||||
|
return ok?destination:null;
|
||||||
|
}
|
||||||
|
const montarShipReady=()=>montarDelivery()==='ship'&&!!montarDestination()&&
|
||||||
|
!!MONTAR.freight&&MONTAR.freight.postal_code===montarCep();
|
||||||
|
function montarResetFreight(){
|
||||||
|
MONTAR.freights=null;MONTAR.freight=null;
|
||||||
|
$('montar-freights').replaceChildren();$('montar-freights').hidden=true;
|
||||||
|
$('montar-freight-msg').textContent='';
|
||||||
|
}
|
||||||
|
async function montarPublic(path,options={}){
|
||||||
|
const response=await fetch('/api'+path,options);
|
||||||
|
const data=await response.json().catch(()=>({}));
|
||||||
|
if(!response.ok)throw new Error(typeof data.detail==='string'?data.detail:'Não foi possível agora ('+response.status+').');
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
async function montarCepLookup(){
|
||||||
|
const msg=$('montar-ship-msg'),cep=montarCep();
|
||||||
|
if(cep.length!==8){msg.textContent='Informe um CEP com oito dígitos.';return;}
|
||||||
|
msg.textContent='Buscando o endereço…';
|
||||||
|
try{
|
||||||
|
const address=await montarPublic('/cep/'+cep);
|
||||||
|
$('montar-ship-street').value=address.street||'';
|
||||||
|
$('montar-ship-district').value=address.district||'';
|
||||||
|
$('montar-ship-city').value=address.city||'';
|
||||||
|
if(MONTAR_UFS.includes(address.state))$('montar-ship-state').value=address.state;
|
||||||
|
if(!$('montar-ship-recipient').value.trim())$('montar-ship-recipient').value=$('montar-name').value.trim();
|
||||||
|
msg.textContent='';MONTAR.requestKey=null;montarPaintActions();
|
||||||
|
}catch(e){msg.textContent=e.message;}
|
||||||
|
}
|
||||||
|
// The item's packed metres and the table value of the items, as the server
|
||||||
|
// will price them: the band price of the loose-art mode on the billed metres.
|
||||||
|
function montarQuoteFigures(lines){
|
||||||
|
const heights=montarGroups(lines).map(group=>{
|
||||||
|
const cargas=[];
|
||||||
|
group.sources.forEach((source,sourceIndex)=>{
|
||||||
|
for(let copyIndex=0;copyIndex<source.copies;copyIndex++)
|
||||||
|
cargas.push({a:{sourceIndex,giro:0,esp:false},img:source.line.img,copyIndex,
|
||||||
|
w:source.line.widthCm,h:source.line.heightCm,travado:false});
|
||||||
|
});
|
||||||
|
return encaixar(cargas,MONTAR_FILM_CM).altura/100;
|
||||||
|
});
|
||||||
|
const catalog=MONTAR.catalog?.avulsa;
|
||||||
|
if(!catalog)throw new Error('Preço de tabela indisponível agora.');
|
||||||
|
const billed=heights.map(metres=>Math.max(1,Math.ceil(metres*10)/10));
|
||||||
|
const total=+billed.reduce((sum,metres)=>sum+metres,0).toFixed(2);
|
||||||
|
let unit=catalog.unit_cents,best=null;
|
||||||
|
for(const band of catalog.bands||[]){
|
||||||
|
const from=Number(band.from_metres);
|
||||||
|
if(total>=from&&(best===null||from>=best)){best=from;unit=band.unit_cents;}
|
||||||
|
}
|
||||||
|
return {metres:+heights.reduce((sum,metres)=>sum+metres,0).toFixed(4),
|
||||||
|
cents:billed.reduce((sum,metres)=>sum+Math.floor(Number((metres*unit).toFixed(6))),0)};
|
||||||
|
}
|
||||||
|
async function montarCatalog(){
|
||||||
|
if(MONTAR.catalog)return MONTAR.catalog;
|
||||||
|
const session=await montarPublic('/session');
|
||||||
|
MONTAR.catalog=session.products||null;
|
||||||
|
return MONTAR.catalog;
|
||||||
|
}
|
||||||
|
async function montarFreightQuote(){
|
||||||
|
const msg=$('montar-freight-msg'),cep=montarCep();
|
||||||
|
if(cep.length!==8){msg.textContent='Informe o CEP de entrega primeiro.';return;}
|
||||||
|
if(!MONTAR.lines.length||!MONTAR.layout||MONTAR.layoutPending){
|
||||||
|
msg.textContent='Monte a folha antes de cotar o frete.';return;
|
||||||
|
}
|
||||||
|
msg.textContent='Cotando o frete…';
|
||||||
|
const token=MONTAR.layoutToken;
|
||||||
|
try{
|
||||||
|
await montarCatalog();
|
||||||
|
if(token!==MONTAR.layoutToken||montarCep()!==cep)return;
|
||||||
|
const figures=montarQuoteFigures([...MONTAR.lines]);
|
||||||
|
const result=await montarPublic('/freight/options',{method:'POST',
|
||||||
|
headers:{'Content-Type':'application/json'},
|
||||||
|
body:JSON.stringify({postal_code:cep,metres:figures.metres,declared_cents:figures.cents})});
|
||||||
|
if(token!==MONTAR.layoutToken||montarCep()!==cep)return;
|
||||||
|
MONTAR.freights=result.options||[];
|
||||||
|
MONTAR.freight=MONTAR.freights.length?{...MONTAR.freights[0],postal_code:cep}:null;
|
||||||
|
MONTAR.requestKey=null;
|
||||||
|
msg.textContent='';montarPaintFreights();montarPaintActions();
|
||||||
|
}catch(e){
|
||||||
|
if(token!==MONTAR.layoutToken||montarCep()!==cep)return;
|
||||||
|
MONTAR.freights=null;MONTAR.freight=null;
|
||||||
|
$('montar-freights').replaceChildren();$('montar-freights').hidden=true;
|
||||||
|
msg.textContent=e.message;montarPaintActions();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function montarPaintFreights(){
|
||||||
|
const box=$('montar-freights'),options=MONTAR.freights||[];
|
||||||
|
box.hidden=!options.length;
|
||||||
|
box.replaceChildren(...options.map(option=>{
|
||||||
|
const label=node('label',undefined,'montar-freight');
|
||||||
|
const radio=node('input');radio.type='radio';radio.name='montar-freight';radio.value=option.service;
|
||||||
|
radio.checked=!!MONTAR.freight&&option.service===MONTAR.freight.service;
|
||||||
|
radio.onchange=()=>{
|
||||||
|
MONTAR.freight={...option,postal_code:montarCep()};MONTAR.requestKey=null;montarPaintActions();
|
||||||
|
};
|
||||||
|
const meta=node('span',undefined,'montar-freight-meta');
|
||||||
|
meta.append(node('b',option.description||option.service),
|
||||||
|
node('span',option.days?'até '+option.days+' dias úteis':'','sub'),
|
||||||
|
node('em',money(option.total_cents)));
|
||||||
|
label.append(radio,meta);
|
||||||
|
return label;
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
// The brand of a stamp, recorded for the future catalogue (Marcus, 10/11):
|
||||||
|
// only Gestão edits it; everyone who assembles reads it.
|
||||||
|
async function montarStampBrand(code){
|
||||||
|
if(MONTAR.brands.has(code))return MONTAR.brands.get(code);
|
||||||
|
const stamp=await api('/stamps/'+encodeURIComponent(code));
|
||||||
|
MONTAR.brands.set(code,stamp);
|
||||||
|
return stamp;
|
||||||
|
}
|
||||||
|
function montarBrandRow(code,stamp){
|
||||||
|
const current=stamp||{brand:'',public:false};
|
||||||
|
const row=node('div',undefined,'montar-brand');
|
||||||
|
row.append(node('span','Marca','lbl'));
|
||||||
|
if(!may('manage')){
|
||||||
|
row.append(node('b',current.brand||'—'),node('span',current.public?'Pública':'Não pública','lbl'));
|
||||||
|
return row;
|
||||||
|
}
|
||||||
|
const brand=node('input',undefined,'montar-brandinput');
|
||||||
|
brand.value=current.brand||'';brand.maxLength=120;brand.autocomplete='off';brand.spellcheck=false;
|
||||||
|
brand.setAttribute('aria-label','Marca da estampa '+code);
|
||||||
|
const pub=node('label',undefined,'montar-public');
|
||||||
|
const check=node('input');check.type='checkbox';check.checked=!!current.public;
|
||||||
|
pub.append(check,'Pública');
|
||||||
|
const save=node('button','Salvar marca','btn');save.type='button';
|
||||||
|
save.onclick=async()=>{
|
||||||
|
save.disabled=true;
|
||||||
|
try{
|
||||||
|
await api('/stamps/'+encodeURIComponent(code),{brand:brand.value.trim(),public:check.checked});
|
||||||
|
MONTAR.brands.set(code,{code,brand:brand.value.trim(),public:check.checked});
|
||||||
|
say('Marca salva.');
|
||||||
|
}catch(e){say(e.message,true);}finally{save.disabled=false;}
|
||||||
|
};
|
||||||
|
row.append(brand,pub,save);
|
||||||
|
return row;
|
||||||
|
}
|
||||||
|
|
||||||
// Without the folder there is no Estampas/ to read: only the size table works.
|
// Without the folder there is no Estampas/ to read: only the size table works.
|
||||||
function montarPaintFolder(){
|
function montarPaintFolder(){
|
||||||
const ok=montarFolderReady();
|
const ok=montarFolderReady();
|
||||||
@@ -59,14 +278,16 @@ function montarDropPreview(){
|
|||||||
if(MONTAR.preview)URL.revokeObjectURL(MONTAR.preview.url);
|
if(MONTAR.preview)URL.revokeObjectURL(MONTAR.preview.url);
|
||||||
MONTAR.preview=null;
|
MONTAR.preview=null;
|
||||||
}
|
}
|
||||||
function montarPaintPreview(found){
|
function montarPaintPreview(found,stamp){
|
||||||
montarDropPreview();
|
montarDropPreview();
|
||||||
MONTAR.preview=found;
|
MONTAR.preview=found;
|
||||||
const words=node('span',undefined,'montar-stampinfo');
|
const words=node('span',undefined,'montar-stampinfo');
|
||||||
words.append(node('b',found.code),
|
words.append(node('b',found.code),
|
||||||
node('span',cm(found.widthCm)+' cm de largura · '+cm(montarHeight(found))+' cm de altura · '+Math.floor(montarDpi(found))+' DPI'));
|
node('span',cm(found.widthCm)+' cm de largura · '+cm(montarHeight(found))+' cm de altura · '+Math.floor(montarDpi(found))+' DPI'));
|
||||||
const img=node('img');img.src=found.url;img.alt='Estampa '+found.code;
|
const img=node('img');img.src=found.url;img.alt='Estampa '+found.code;
|
||||||
const wrap=node('div',undefined,'montar-stamp');wrap.append(img,words);
|
const body=node('div',undefined,'montar-stampbody');
|
||||||
|
body.append(words,montarBrandRow(found.code,stamp));
|
||||||
|
const wrap=node('div',undefined,'montar-stamp');wrap.append(img,body);
|
||||||
$('montar-preview').replaceChildren(wrap);
|
$('montar-preview').replaceChildren(wrap);
|
||||||
}
|
}
|
||||||
function montarPaintNotFound(){
|
function montarPaintNotFound(){
|
||||||
@@ -88,7 +309,12 @@ async function montarPreview(){
|
|||||||
try{found=await montarRead(code,size);}
|
try{found=await montarRead(code,size);}
|
||||||
catch(e){if(token===MONTAR.token&&!montarFolderError(e))say(e.message,true);return;}
|
catch(e){if(token===MONTAR.token&&!montarFolderError(e))say(e.message,true);return;}
|
||||||
if(token!==MONTAR.token){if(found)URL.revokeObjectURL(found.url);return;}
|
if(token!==MONTAR.token){if(found)URL.revokeObjectURL(found.url);return;}
|
||||||
if(found)montarPaintPreview(found);else montarPaintNotFound();
|
if(found){
|
||||||
|
let stamp=null;
|
||||||
|
try{stamp=await montarStampBrand(code);}catch(e){stamp={code,brand:'',public:false};}
|
||||||
|
if(token!==MONTAR.token){URL.revokeObjectURL(found.url);return;}
|
||||||
|
montarPaintPreview(found,stamp);
|
||||||
|
}else montarPaintNotFound();
|
||||||
}
|
}
|
||||||
function montarQueuePreview(){
|
function montarQueuePreview(){
|
||||||
clearTimeout(MONTAR.timer);
|
clearTimeout(MONTAR.timer);
|
||||||
@@ -129,6 +355,7 @@ function montarChanged(){
|
|||||||
MONTAR.layout=null;
|
MONTAR.layout=null;
|
||||||
MONTAR.layoutPending=true;
|
MONTAR.layoutPending=true;
|
||||||
MONTAR.requestKey=null;
|
MONTAR.requestKey=null;
|
||||||
|
montarResetFreight();
|
||||||
montarPaintLines();
|
montarPaintLines();
|
||||||
if(!MONTAR.lines.length)montarDrawPreview(null);
|
if(!MONTAR.lines.length)montarDrawPreview(null);
|
||||||
clearTimeout(MONTAR.layoutTimer);
|
clearTimeout(MONTAR.layoutTimer);
|
||||||
@@ -198,15 +425,32 @@ function montarCustomer(){
|
|||||||
const montarCustomerFilled=()=>MONTAR_CUSTOMER.every(id=>$(id).value.trim());
|
const montarCustomerFilled=()=>MONTAR_CUSTOMER.every(id=>$(id).value.trim());
|
||||||
function montarClearCustomer(){
|
function montarClearCustomer(){
|
||||||
for(const id of MONTAR_CUSTOMER)$(id).value='';
|
for(const id of MONTAR_CUSTOMER)$(id).value='';
|
||||||
|
$('montar-customer-q').value='';
|
||||||
|
$('montar-customer-hits').hidden=true;
|
||||||
|
for(const id of ['montar-ship-cep','montar-ship-recipient','montar-ship-street','montar-ship-number',
|
||||||
|
'montar-ship-complement','montar-ship-district','montar-ship-city','montar-ship-state'])
|
||||||
|
$(id).value='';
|
||||||
|
$('montar-ship-msg').textContent='';
|
||||||
|
montarResetFreight();
|
||||||
|
document.querySelector('input[name="montar-delivery"][value="pickup"]').checked=true;
|
||||||
|
montarPaintDelivery();
|
||||||
MONTAR.requestKey=null;
|
MONTAR.requestKey=null;
|
||||||
}
|
}
|
||||||
// Montar is the real thing now: a sheet, its layout and the customer.
|
// Montar is the real thing now: a sheet, its layout and the customer, which
|
||||||
|
// Interno reads from the database and Venda from Tiny.
|
||||||
function montarPaintActions(){
|
function montarPaintActions(){
|
||||||
const build=$('montar-build');
|
const build=$('montar-build');
|
||||||
|
const customerReady=MONTAR.kind==='interno'?montarInternalReady():montarCustomerFilled();
|
||||||
|
const deliveryReady=MONTAR.kind!=='venda'||montarDelivery()!=='ship'||montarShipReady();
|
||||||
const ready=!!(MONTAR.lines.length&&MONTAR.layout&&!MONTAR.layoutPending&&
|
const ready=!!(MONTAR.lines.length&&MONTAR.layout&&!MONTAR.layoutPending&&
|
||||||
montarCustomerFilled()&&!MONTAR.creating);
|
customerReady&&deliveryReady&&!MONTAR.creating);
|
||||||
build.disabled=!ready;
|
build.disabled=!ready;
|
||||||
build.title=ready?'':(MONTAR.lines.length?'Aguarde a montagem e preencha o cliente.':'Monte a folha primeiro.');
|
build.title=ready?'':(!MONTAR.lines.length?'Monte a folha primeiro.'
|
||||||
|
:(MONTAR.layoutPending||!MONTAR.layout)?'Aguarde a montagem da folha.'
|
||||||
|
:MONTAR.kind==='interno'?'Peça à Gestão para completar o cliente interno.'
|
||||||
|
:!customerReady?'Preencha os dados do cliente.'
|
||||||
|
:!deliveryReady?(!montarDestination()?'Preencha o endereço de entrega.':'Cote o frete e escolha uma opção.')
|
||||||
|
:'');
|
||||||
}
|
}
|
||||||
// The Site's grade for loose art (web/site-quality.js): each stamp's DPI over
|
// The Site's grade for loose art (web/site-quality.js): each stamp's DPI over
|
||||||
// the ideal 200, from 6 to 100; the item's is the average of its stamps'.
|
// the ideal 200, from 6 to 100; the item's is the average of its stamps'.
|
||||||
@@ -234,13 +478,11 @@ function montarItem(sources){
|
|||||||
}
|
}
|
||||||
// 20 sources and 4000 copies per item; a stamp above 200 copies becomes
|
// 20 sources and 4000 copies per item; a stamp above 200 copies becomes
|
||||||
// several sources of the same upload, 200 each; items in list order.
|
// several sources of the same upload, 200 each; items in list order.
|
||||||
function montarItems(lines,uploads){
|
function montarGroups(lines){
|
||||||
const pool=[];
|
const pool=[];
|
||||||
for(const line of lines){
|
for(const line of lines)
|
||||||
const uploadId=uploads.get(line.id);
|
|
||||||
for(let left=line.qty;left>0;left-=200)
|
for(let left=line.qty;left>0;left-=200)
|
||||||
pool.push({line,uploadId,copies:Math.min(200,left)});
|
pool.push({line,copies:Math.min(200,left)});
|
||||||
}
|
|
||||||
const groups=[];let current=null;
|
const groups=[];let current=null;
|
||||||
for(const source of pool){
|
for(const source of pool){
|
||||||
if(!current||current.sources.length>=20||current.copies+source.copies>4000){
|
if(!current||current.sources.length>=20||current.copies+source.copies>4000){
|
||||||
@@ -248,17 +490,41 @@ function montarItems(lines,uploads){
|
|||||||
}
|
}
|
||||||
current.sources.push(source);current.copies+=source.copies;
|
current.sources.push(source);current.copies+=source.copies;
|
||||||
}
|
}
|
||||||
return groups.map(group=>montarItem(group.sources));
|
return groups;
|
||||||
|
}
|
||||||
|
function montarItems(lines,uploads){
|
||||||
|
return montarGroups(lines).map(group=>montarItem(group.sources.map(source=>
|
||||||
|
({...source,uploadId:uploads.get(source.line.id)}))));
|
||||||
}
|
}
|
||||||
async function montarCreate(){
|
async function montarCreate(){
|
||||||
if(MONTAR.creating)return;
|
if(MONTAR.creating)return;
|
||||||
const customer=montarCustomer();
|
const kind=MONTAR.kind||'venda';
|
||||||
if(!montarCustomerFilled())return say('Preencha os dados do cliente.',true);
|
let customer=null,name='';
|
||||||
|
if(kind==='interno'){
|
||||||
|
if(!montarInternalReady())return say('Peça à Gestão para completar o cliente interno.',true);
|
||||||
|
name=montarInternalField('name');
|
||||||
|
}else{
|
||||||
|
customer=montarCustomer();
|
||||||
|
if(!montarCustomerFilled())return say('Preencha os dados do cliente.',true);
|
||||||
|
name=customer.name;
|
||||||
|
}
|
||||||
|
let withOrder=null,deliveryFreight=null,destination=null;
|
||||||
|
if(kind==='venda'&&montarDelivery()==='with_order'){
|
||||||
|
withOrder=montarWithOrder();
|
||||||
|
if(!withOrder)return say('Informe o número do pedido de roupa.',true);
|
||||||
|
}
|
||||||
|
if(kind==='venda'&&montarDelivery()==='ship'){
|
||||||
|
destination=montarDestination();
|
||||||
|
if(!destination)return say('Preencha o endereço de entrega.',true);
|
||||||
|
if(!MONTAR.freight)return say('Cote o frete e escolha uma opção.',true);
|
||||||
|
if(MONTAR.freight.postal_code!==montarCep())return say('Cote o frete de novo para este CEP.',true);
|
||||||
|
deliveryFreight={service:MONTAR.freight.service,postal_code:montarCep()};
|
||||||
|
}
|
||||||
if(!MONTAR.lines.length)return say('Monte a folha primeiro.',true);
|
if(!MONTAR.lines.length)return say('Monte a folha primeiro.',true);
|
||||||
if(!MONTAR.layout||MONTAR.layoutPending)return say('A montagem ainda está sendo calculada.',true);
|
if(!MONTAR.layout||MONTAR.layoutPending)return say('A montagem ainda está sendo calculada.',true);
|
||||||
const lines=[...MONTAR.lines];
|
const lines=[...MONTAR.lines];
|
||||||
if(!await ask('Criar pedido','Criar o pedido com '+plural(lines.reduce((t,line)=>t+line.qty,0),'estampa','estampas')+
|
if(!await ask('Criar pedido','Criar o pedido com '+plural(lines.reduce((t,line)=>t+line.qty,0),'estampa','estampas')+
|
||||||
', '+metres(MONTAR.layout.altura/100)+', para '+customer.name+'?','Criar pedido'))return;
|
', '+metres(MONTAR.layout.altura/100)+', para '+name+'?','Criar pedido'))return;
|
||||||
MONTAR.creating=true;montarPaintActions();
|
MONTAR.creating=true;montarPaintActions();
|
||||||
try{
|
try{
|
||||||
const uploads=new Map();
|
const uploads=new Map();
|
||||||
@@ -271,11 +537,18 @@ async function montarCreate(){
|
|||||||
}
|
}
|
||||||
say('Criando o pedido…');
|
say('Criando o pedido…');
|
||||||
if(!MONTAR.requestKey)MONTAR.requestKey=crypto.randomUUID();
|
if(!MONTAR.requestKey)MONTAR.requestKey=crypto.randomUUID();
|
||||||
const order=await api('/montador/orders',{request_key:MONTAR.requestKey,
|
const body={request_key:MONTAR.requestKey,kind,items:montarItems(lines,uploads)};
|
||||||
customer,items:montarItems(lines,uploads)});
|
if(kind==='venda'){
|
||||||
|
body.customer=customer;
|
||||||
|
if(withOrder)body.with_order=withOrder;
|
||||||
|
if(deliveryFreight)body.freight=deliveryFreight;
|
||||||
|
if(destination)body.destination=destination;
|
||||||
|
}
|
||||||
|
const order=await api('/montador/orders',body);
|
||||||
MONTAR.requestKey=null;
|
MONTAR.requestKey=null;
|
||||||
montarClear();
|
montarClear();
|
||||||
montarClearCustomer();
|
montarClearCustomer();
|
||||||
|
montarPaintCustomer();
|
||||||
say('Pedido #'+order.number+' criado em Arte recebida.',false,10000);
|
say('Pedido #'+order.number+' criado em Arte recebida.',false,10000);
|
||||||
load(true).catch(()=>{});
|
load(true).catch(()=>{});
|
||||||
}catch(e){say(e.message,true);}
|
}catch(e){say(e.message,true);}
|
||||||
@@ -328,7 +601,9 @@ async function montarAdd(){
|
|||||||
try{found=await montarRead(code,size);}
|
try{found=await montarRead(code,size);}
|
||||||
catch(e){if(!montarFolderError(e))say(e.message,true);return;}
|
catch(e){if(!montarFolderError(e))say(e.message,true);return;}
|
||||||
if(!found){montarPaintNotFound();return say('Código não existe em Estampas/.',true);}
|
if(!found){montarPaintNotFound();return say('Código não existe em Estampas/.',true);}
|
||||||
montarPaintPreview(found);
|
let stamp=null;
|
||||||
|
try{stamp=await montarStampBrand(code);}catch(e){stamp={code,brand:'',public:false};}
|
||||||
|
montarPaintPreview(found,stamp);
|
||||||
if(found.widthCm>56)return say('A estampa tem '+cm(found.widthCm)+' cm de largura: o máximo é 56 cm.',true);
|
if(found.widthCm>56)return say('A estampa tem '+cm(found.widthCm)+' cm de largura: o máximo é 56 cm.',true);
|
||||||
const dpi=montarDpi(found);
|
const dpi=montarDpi(found);
|
||||||
if(dpi<MONTAR_DPI_REFUSE)return say('A estampa tem só '+Math.floor(dpi)+' DPI em '+size.letter+': pequena demais.',true);
|
if(dpi<MONTAR_DPI_REFUSE)return say('A estampa tem só '+Math.floor(dpi)+' DPI em '+size.letter+': pequena demais.',true);
|
||||||
@@ -392,9 +667,80 @@ async function montarLoadSizes(repaint){
|
|||||||
montarPaintSelect();
|
montarPaintSelect();
|
||||||
if(repaint||!MONTAR.dirty)montarPaintSizeEditor();
|
if(repaint||!MONTAR.dirty)montarPaintSizeEditor();
|
||||||
}
|
}
|
||||||
|
// The fixed internal customer, completed by Gestão in the panel next to the
|
||||||
|
// size table. Copied into the form only while it is not being edited.
|
||||||
|
function montarPaintInternalFields(){
|
||||||
|
if(!may('manage'))return;
|
||||||
|
$('montar-interno-name').value=montarInternalField('name');
|
||||||
|
$('montar-interno-doc').value=montarInternalField('cnpj');
|
||||||
|
$('montar-interno-zap').value=montarInternalField('zap');
|
||||||
|
$('montar-interno-mail').value=montarInternalField('mail');
|
||||||
|
}
|
||||||
|
async function montarLoadInternal(repaint){
|
||||||
|
MONTAR.internal=await api('/internal-customer');
|
||||||
|
const panel=$('montar-interno-panel');
|
||||||
|
panel.hidden=!may('manage');
|
||||||
|
if(may('manage')&&(repaint||!MONTAR.internalDirty))montarPaintInternalFields();
|
||||||
|
montarPaintKind();
|
||||||
|
montarPaintCustomer();
|
||||||
|
montarPaintActions();
|
||||||
|
}
|
||||||
|
async function montarSaveInternal(){
|
||||||
|
const customer={name:$('montar-interno-name').value.trim(),cnpj:$('montar-interno-doc').value.trim(),
|
||||||
|
zap:$('montar-interno-zap').value.trim(),mail:$('montar-interno-mail').value.trim()};
|
||||||
|
if(!['name','cnpj','zap','mail'].every(key=>customer[key]))return say('Preencha todos os campos do cliente interno.',true);
|
||||||
|
await api('/internal-customer',customer);
|
||||||
|
MONTAR.internalDirty=false;
|
||||||
|
say('Cliente interno salvo.');
|
||||||
|
await montarLoadInternal(true);
|
||||||
|
}
|
||||||
|
// The Venda customer comes from Tiny's contacts, by name or CPF/CNPJ.
|
||||||
|
async function montarSearchContacts(){
|
||||||
|
const token=++MONTAR.contactToken,q=$('montar-customer-q').value.trim(),hits=$('montar-customer-hits');
|
||||||
|
if(q.length<2){hits.hidden=true;hits.replaceChildren();return;}
|
||||||
|
let contacts;
|
||||||
|
try{contacts=await api('/tiny/contacts?q='+encodeURIComponent(q));}
|
||||||
|
catch(e){
|
||||||
|
if(token!==MONTAR.contactToken)return;
|
||||||
|
hits.replaceChildren(node('p',e.message,'montar-hint'));hits.hidden=false;return;
|
||||||
|
}
|
||||||
|
if(token!==MONTAR.contactToken)return;
|
||||||
|
if(!contacts.length){hits.replaceChildren(node('p','Nenhum contato no Tiny.','montar-hint'));hits.hidden=false;return;}
|
||||||
|
hits.replaceChildren(...contacts.map(contact=>{
|
||||||
|
const hit=node('button',undefined,'montar-hit');hit.type='button';hit.setAttribute('role','option');
|
||||||
|
hit.append(node('b',contact.name||contact.document||'Contato'),
|
||||||
|
node('span',[contact.document,contact.email,contact.phone].filter(Boolean).join(' · '),'sub'));
|
||||||
|
hit.onclick=()=>montarPickContact(contact);
|
||||||
|
return hit;
|
||||||
|
}));
|
||||||
|
hits.hidden=false;
|
||||||
|
}
|
||||||
|
function montarQueueContacts(){
|
||||||
|
clearTimeout(MONTAR.contactTimer);
|
||||||
|
MONTAR.contactTimer=setTimeout(()=>montarSearchContacts().catch(e=>say(e.message,true)),300);
|
||||||
|
}
|
||||||
|
function montarPickContact(contact){
|
||||||
|
const previous=$('montar-name').value.trim();
|
||||||
|
$('montar-name').value=contact.name||'';
|
||||||
|
$('montar-doc').value=contact.document||'';
|
||||||
|
$('montar-zap').value=contact.phone||'';
|
||||||
|
$('montar-mail').value=contact.email||'';
|
||||||
|
$('montar-customer-q').value=contact.name||contact.document||'';
|
||||||
|
$('montar-customer-hits').hidden=true;
|
||||||
|
const recipient=$('montar-ship-recipient').value.trim();
|
||||||
|
if(montarDelivery()==='ship'&&(!recipient||recipient===previous))
|
||||||
|
$('montar-ship-recipient').value=contact.name||'';
|
||||||
|
MONTAR.requestKey=null;
|
||||||
|
montarPaintActions();
|
||||||
|
const missing=MONTAR_CUSTOMER.find(id=>!$(id).value.trim());
|
||||||
|
if(missing)$(missing).focus();
|
||||||
|
}
|
||||||
async function loadMontador(){
|
async function loadMontador(){
|
||||||
montarPaintFolder();
|
montarPaintFolder();
|
||||||
try{await montarLoadSizes(false);}
|
// Paint the chosen kind and customer before the fetch answers: an Expedição
|
||||||
|
// never sees an editable customer field, not even for a moment.
|
||||||
|
montarPaintKind();montarPaintCustomer();
|
||||||
|
try{await Promise.all([montarLoadSizes(false),montarLoadInternal(false)]);}
|
||||||
catch(e){say(e.message,true);return;}
|
catch(e){say(e.message,true);return;}
|
||||||
if(montarFolderReady()){
|
if(montarFolderReady()){
|
||||||
if($('montar-code').value.trim()){if(!MONTAR.preview)montarQueuePreview();}
|
if($('montar-code').value.trim()){if(!MONTAR.preview)montarQueuePreview();}
|
||||||
@@ -433,3 +779,45 @@ $('montar-size-save').onclick=async()=>{
|
|||||||
$('montar-size-save').disabled=true;
|
$('montar-size-save').disabled=true;
|
||||||
try{await montarSaveSizes();}catch(e){say(e.message,true);}finally{$('montar-size-save').disabled=false;}
|
try{await montarSaveSizes();}catch(e){say(e.message,true);}finally{$('montar-size-save').disabled=false;}
|
||||||
};
|
};
|
||||||
|
for(const id of ['montar-interno-name','montar-interno-doc','montar-interno-zap','montar-interno-mail'])
|
||||||
|
$(id).addEventListener('input',()=>{MONTAR.internalDirty=true;});
|
||||||
|
$('montar-interno-save').onclick=async()=>{
|
||||||
|
$('montar-interno-save').disabled=true;
|
||||||
|
try{await montarSaveInternal();}catch(e){say(e.message,true);}finally{$('montar-interno-save').disabled=false;}
|
||||||
|
};
|
||||||
|
$('montar-customer-q').addEventListener('input',montarQueueContacts);
|
||||||
|
$('montar-customer-q').addEventListener('focus',()=>{if($('montar-customer-hits').children.length)$('montar-customer-hits').hidden=false;});
|
||||||
|
$('montar-with-order').addEventListener('focus',()=>{
|
||||||
|
document.querySelector('input[name="montar-delivery"][value="with_order"]').checked=true;
|
||||||
|
montarPaintDelivery();
|
||||||
|
});
|
||||||
|
$('montar-with-order').addEventListener('input',()=>{MONTAR.requestKey=null;});
|
||||||
|
for(const radio of document.querySelectorAll('input[name="montar-delivery"]'))
|
||||||
|
radio.addEventListener('change',()=>{MONTAR.requestKey=null;montarPaintDelivery();montarPaintActions();});
|
||||||
|
$('montar-ship-cep').addEventListener('input',()=>{
|
||||||
|
const digits=$('montar-ship-cep').value.replace(/\D/g,'').slice(0,8);
|
||||||
|
$('montar-ship-cep').value=digits.length>5?digits.slice(0,5)+'-'+digits.slice(5):digits;
|
||||||
|
MONTAR.requestKey=null;montarResetFreight();montarPaintActions();
|
||||||
|
});
|
||||||
|
$('montar-cep-find').onclick=async()=>{
|
||||||
|
$('montar-cep-find').disabled=true;
|
||||||
|
try{await montarCepLookup();}catch(e){say(e.message,true);}
|
||||||
|
finally{$('montar-cep-find').disabled=false;}
|
||||||
|
};
|
||||||
|
$('montar-freight-quote').onclick=async()=>{
|
||||||
|
$('montar-freight-quote').disabled=true;
|
||||||
|
try{await montarFreightQuote();}catch(e){say(e.message,true);}
|
||||||
|
finally{$('montar-freight-quote').disabled=false;}
|
||||||
|
};
|
||||||
|
for(const id of ['montar-ship-recipient','montar-ship-street','montar-ship-number',
|
||||||
|
'montar-ship-complement','montar-ship-district','montar-ship-city'])
|
||||||
|
$(id).addEventListener('input',()=>{MONTAR.requestKey=null;montarPaintActions();});
|
||||||
|
$('montar-ship-state').addEventListener('change',()=>{MONTAR.requestKey=null;montarPaintActions();});
|
||||||
|
document.addEventListener('click',event=>{
|
||||||
|
if(!event.target.closest('.montar-customer-search'))$('montar-customer-hits').hidden=true;
|
||||||
|
});
|
||||||
|
const montarUfPlaceholder=node('option','UF');montarUfPlaceholder.value='';
|
||||||
|
$('montar-ship-state').append(montarUfPlaceholder,...MONTAR_UFS.map(uf=>{
|
||||||
|
const option=node('option',uf);option.value=uf;return option;
|
||||||
|
}));
|
||||||
|
montarPaintDelivery();
|
||||||
|
|||||||
@@ -181,14 +181,17 @@ async function loadStats(){
|
|||||||
const mk=(label,value,unit)=>{const k=node('div',undefined,'mk');const b=node('b',value);if(unit)b.append(node('small',unit));k.append(node('span',label),b);return k;};
|
const mk=(label,value,unit)=>{const k=node('div',undefined,'mk');const b=node('b',value);if(unit)b.append(node('small',unit));k.append(node('span',label),b);return k;};
|
||||||
const pct=n=>data.orders?Math.round(100*n/data.orders)+'%':'';
|
const pct=n=>data.orders?Math.round(100*n/data.orders)+'%':'';
|
||||||
const [reais,centavos]=money(data.cents).split(',');
|
const [reais,centavos]=money(data.cents).split(',');
|
||||||
|
// The ticket is the cash received over the cash orders only: an Interno or
|
||||||
|
// faturado order records the table price, not money received (front 7a.3).
|
||||||
|
const cashOrders=Math.max(0,Number(data.orders)-(data.price_table||[]).reduce((sum,row)=>sum+(row.orders||0),0));
|
||||||
const hero=node('div',undefined,'hero');
|
const hero=node('div',undefined,'hero');
|
||||||
hero.append(hk('Metros vendidos',metres(data.metres).replace(' m',''),'m',plural(data.orders,'pedido pago','pedidos pagos')),
|
hero.append(hk('Metros vendidos',metres(data.metres).replace(' m',''),'m',plural(data.orders,'pedido pago','pedidos pagos')),
|
||||||
hk('Recebido, com frete',reais,','+centavos,data.orders?'ticket médio de '+money(Math.round(data.cents/data.orders)):''),
|
hk('Recebido, com frete',reais,','+centavos,cashOrders?'ticket médio de '+money(Math.round(data.cents/cashOrders)):''),
|
||||||
hk('Do pagamento ao Finalizado',duration(data.lead.median_hours),'',data.lead.orders?'mediana de '+plural(data.lead.orders,'pedido','pedidos')+', sem o tempo em Aguardando contato':'nenhum finalizado no período'));
|
hk('Do pagamento ao Finalizado',duration(data.lead.median_hours),'',data.lead.orders?'mediana de '+plural(data.lead.orders,'pedido','pedidos')+', sem o tempo em Aguardando contato':'nenhum finalizado no período'));
|
||||||
const rw=data.rework, share=v=>v==null?'—':String(v).replace('.',',')+'%';
|
const rw=data.rework, share=v=>v==null?'—':String(v).replace('.',',')+'%';
|
||||||
const minis=node('div',undefined,'minis');
|
const minis=node('div',undefined,'minis');
|
||||||
minis.append(mk('Pedidos pagos',String(data.orders)),
|
minis.append(mk('Pedidos pagos',String(data.orders)),
|
||||||
mk('Ticket médio',data.orders?money(Math.round(data.cents/data.orders)):'—'),
|
mk('Ticket médio',cashOrders?money(Math.round(data.cents/cashOrders)):'—'),
|
||||||
mk('Com correção',String(data.corrected),pct(data.corrected)),
|
mk('Com correção',String(data.corrected),pct(data.corrected)),
|
||||||
mk('Artes tratadas',String(data.treated.orders),pct(data.treated.orders)),
|
mk('Artes tratadas',String(data.treated.orders),pct(data.treated.orders)),
|
||||||
mk('Retrabalho da casa',share(rw.house.percent),'meta '+share(rw.house.goal_percent)),
|
mk('Retrabalho da casa',share(rw.house.percent),'meta '+share(rw.house.goal_percent)),
|
||||||
@@ -211,6 +214,12 @@ async function loadStats(){
|
|||||||
tr.append(node('td',ORIGINS[o.origin]),node('td',String(o.orders),'r'),node('td',metres(o.metres).replace(' m',''),'r'),node('td',money(o.cents),'r'),
|
tr.append(node('td',ORIGINS[o.origin]),node('td',String(o.orders),'r'),node('td',metres(o.metres).replace(' m',''),'r'),node('td',money(o.cents),'r'),
|
||||||
node('td',o.finished?duration(o.median_hours):'—','r'));
|
node('td',o.finished?duration(o.median_hours):'—','r'));
|
||||||
if(!o.orders)tr.classList.add('off');return tr;}));
|
if(!o.orders)tr.classList.add('off');return tr;}));
|
||||||
|
// The montador's table price, apart from the money received (front 7a.3).
|
||||||
|
const priceNames={faturado:'Faturado',interno:'Interno'};
|
||||||
|
$('stats-price-table').replaceChildren(...(data.price_table||[]).map(p=>{const tr=node('tr');
|
||||||
|
tr.append(node('td',priceNames[p.method]||p.method),node('td',String(p.orders),'r'),
|
||||||
|
node('td',metres(p.metres).replace(' m',''),'r'),node('td',money(p.cents),'r'));
|
||||||
|
if(!p.orders)tr.classList.add('off');return tr;}));
|
||||||
// Approved orders never paid: made, paid, expired and the abandonment rate.
|
// Approved orders never paid: made, paid, expired and the abandonment rate.
|
||||||
const unpaid=data.unpaid;
|
const unpaid=data.unpaid;
|
||||||
const unpaidRows=[['Pedidos feitos',String(unpaid.made)],['Pagos',String(unpaid.paid)],
|
const unpaidRows=[['Pedidos feitos',String(unpaid.made)],['Pagos',String(unpaid.paid)],
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
which defines api, may, money, when, say, node and button.
|
which defines api, may, money, when, say, node and button.
|
||||||
A price is history: one that has started is never changed or deleted, so
|
A price is history: one that has started is never changed or deleted, so
|
||||||
only a scheduled (future) price may be cancelled. */
|
only a scheduled (future) price may be cancelled. */
|
||||||
const SITE_UNIT_LABEL={metro:' /m',pedido:' por pedido'};
|
const SITE_UNIT_LABEL={metro:' /m',pedido:' por pedido',arte:' por arte'};
|
||||||
|
|
||||||
// Reais with a comma, as the Site shows them: "19,90" is 1990 cents.
|
// Reais with a comma, as the Site shows them: "19,90" is 1990 cents.
|
||||||
function moneyInputCents(value){
|
function moneyInputCents(value){
|
||||||
@@ -18,10 +18,11 @@ function moneyInputCents(value){
|
|||||||
// A price that already started is refused by the server (409).
|
// A price that already started is refused by the server (409).
|
||||||
const cancelScheduledPrice=id=>api('/site/prices/'+id+'/cancel',{});
|
const cancelScheduledPrice=id=>api('/site/prices/'+id+'/cancel',{});
|
||||||
|
|
||||||
// "5" or "5,5": a band's start in metres, as the table reads it.
|
// "5" or "5,5": a band's start, in metres or arts, as the table reads it.
|
||||||
function bandMetres(value){return String(Number(value)).replace('.',',');}
|
function bandMetres(value){return String(Number(value)).replace('.',',');}
|
||||||
function bandsText(bands){
|
function bandsText(bands,unit='metro'){
|
||||||
return (bands||[]).map(band=>' · '+bandMetres(band.from_metres)+' m: '+money(band.unit_cents)).join('');
|
return (bands||[]).map(band=>' · '+bandMetres(band.from_metres)+' '+
|
||||||
|
(unit==='arte'?(Number(band.from_metres)===1?'arte':'artes'):'m')+': '+money(band.unit_cents)).join('');
|
||||||
}
|
}
|
||||||
|
|
||||||
function siteProductRow(product){
|
function siteProductRow(product){
|
||||||
@@ -66,17 +67,18 @@ function sitePriceBlock(product){
|
|||||||
starts.setAttribute('aria-label','Quando o novo preço de '+product.title+' começa');
|
starts.setAttribute('aria-label','Quando o novo preço de '+product.title+' começa');
|
||||||
startsLabel.append(starts);
|
startsLabel.append(starts);
|
||||||
// Faixas progressivas (front 8.2): a nova tabela começa vazia; as faixas
|
// Faixas progressivas (front 8.2): a nova tabela começa vazia; as faixas
|
||||||
// viajam com este preço. O tratamento é um valor por pedido, sem faixas.
|
// viajam com este preço. Ajuste Fino conta as faixas em artes, os produtos em metros.
|
||||||
|
const bandUnit=product.unit==='arte'?'artes':'m';
|
||||||
const bandRows=node('div',undefined,'siteBandRows');
|
const bandRows=node('div',undefined,'siteBandRows');
|
||||||
const addBand=node('button','Adicionar faixa','btn ghost');addBand.type='button';
|
const addBand=node('button','Adicionar faixa','btn ghost');addBand.type='button';
|
||||||
const paintAdd=()=>{addBand.disabled=bandRows.children.length>=5;};
|
const paintAdd=()=>{addBand.disabled=bandRows.children.length>=5;};
|
||||||
const bandRow=()=>{
|
const bandRow=()=>{
|
||||||
const row=node('div',undefined,'siteBandRow');
|
const row=node('div',undefined,'siteBandRow');
|
||||||
const fromLabel=node('label');fromLabel.append(node('span','A partir de (m)'));
|
const fromLabel=node('label');fromLabel.append(node('span','A partir de ('+bandUnit+')'));
|
||||||
const from=node('input');from.type='text';from.inputMode='decimal';from.className='siteBandFrom';
|
const from=node('input');from.type='text';from.inputMode='decimal';from.className='siteBandFrom';
|
||||||
from.setAttribute('aria-label','Metragem da faixa de '+product.title);
|
from.setAttribute('aria-label','Início da faixa em '+bandUnit+' de '+product.title);
|
||||||
fromLabel.append(from);
|
fromLabel.append(from);
|
||||||
const priceLabel=node('label');priceLabel.append(node('span','R$ por metro'));
|
const priceLabel=node('label');priceLabel.append(node('span','R$ por '+(product.unit==='arte'?'arte':'metro')));
|
||||||
const bandPrice=node('input');bandPrice.type='text';bandPrice.inputMode='decimal';bandPrice.className='siteBandPrice';
|
const bandPrice=node('input');bandPrice.type='text';bandPrice.inputMode='decimal';bandPrice.className='siteBandPrice';
|
||||||
bandPrice.setAttribute('aria-label','Preço da faixa de '+product.title);
|
bandPrice.setAttribute('aria-label','Preço da faixa de '+product.title);
|
||||||
priceLabel.append(bandPrice);
|
priceLabel.append(bandPrice);
|
||||||
@@ -93,7 +95,7 @@ function sitePriceBlock(product){
|
|||||||
const from=Number(row.querySelector('.siteBandFrom').value.replace(',','.'));
|
const from=Number(row.querySelector('.siteBandFrom').value.replace(',','.'));
|
||||||
const unit=moneyInputCents(row.querySelector('.siteBandPrice').value);
|
const unit=moneyInputCents(row.querySelector('.siteBandPrice').value);
|
||||||
if(!Number.isFinite(from)||from<=0||unit===null||unit<=0)
|
if(!Number.isFinite(from)||from<=0||unit===null||unit<=0)
|
||||||
throw new Error('Confira as faixas: metragem e preço maiores que zero.');
|
throw new Error('Confira as faixas: início e preço maiores que zero.');
|
||||||
return {from_metres:String(from),unit_cents:unit};
|
return {from_metres:String(from),unit_cents:unit};
|
||||||
});
|
});
|
||||||
const save=button('Salvar',async()=>{
|
const save=button('Salvar',async()=>{
|
||||||
@@ -103,18 +105,17 @@ function sitePriceBlock(product){
|
|||||||
if(whenDate&&Number.isNaN(whenDate.getTime()))throw new Error('Data inválida.');
|
if(whenDate&&Number.isNaN(whenDate.getTime()))throw new Error('Data inválida.');
|
||||||
await api('/site/products/'+product.id+'/prices',
|
await api('/site/products/'+product.id+'/prices',
|
||||||
{unit_cents:cents,starts_at:whenDate?whenDate.toISOString():null,
|
{unit_cents:cents,starts_at:whenDate?whenDate.toISOString():null,
|
||||||
bands:product.id==='tratamento'?[]:formBands()});
|
bands:formBands()});
|
||||||
say(whenDate?'Preço salvo para '+when(whenDate)+'.':'Preço salvo. Vale a partir de agora.');
|
say(whenDate?'Preço salvo para '+when(whenDate)+'.':'Preço salvo. Vale a partir de agora.');
|
||||||
await loadSiteAdmin();
|
await loadSiteAdmin();
|
||||||
},'btn pri');
|
},'btn pri');
|
||||||
form.append(priceLabel,startsLabel,save);
|
form.append(priceLabel,startsLabel,save,bands);
|
||||||
if(product.id!=='tratamento')form.append(bands);
|
|
||||||
|
|
||||||
const scheduled=node('div',undefined,'siteScheduled');
|
const scheduled=node('div',undefined,'siteScheduled');
|
||||||
if(product.scheduled.length){
|
if(product.scheduled.length){
|
||||||
for(const row of product.scheduled){
|
for(const row of product.scheduled){
|
||||||
const line=node('div',undefined,'siteScheduledRow');
|
const line=node('div',undefined,'siteScheduledRow');
|
||||||
line.append(node('span',money(row.unit_cents)+SITE_UNIT_LABEL[product.unit]+bandsText(row.bands)+
|
line.append(node('span',money(row.unit_cents)+SITE_UNIT_LABEL[product.unit]+bandsText(row.bands,product.unit)+
|
||||||
' a partir de '+when(row.starts_at)));
|
' a partir de '+when(row.starts_at)));
|
||||||
line.append(button('Cancelar',async()=>{
|
line.append(button('Cancelar',async()=>{
|
||||||
await cancelScheduledPrice(row.id);
|
await cancelScheduledPrice(row.id);
|
||||||
@@ -132,7 +133,7 @@ function sitePriceBlock(product){
|
|||||||
const body=node('tbody');
|
const body=node('tbody');
|
||||||
for(const row of product.history){
|
for(const row of product.history){
|
||||||
const tr=node('tr');
|
const tr=node('tr');
|
||||||
tr.append(node('td',money(row.unit_cents)+bandsText(row.bands),'nowrap'),node('td',when(row.starts_at),'nowrap'),
|
tr.append(node('td',money(row.unit_cents)+bandsText(row.bands,product.unit),'nowrap'),node('td',when(row.starts_at),'nowrap'),
|
||||||
node('td',row.created_by),node('td',when(row.created_at),'nowrap'));
|
node('td',row.created_by),node('td',when(row.created_at),'nowrap'));
|
||||||
body.append(tr);
|
body.append(tr);
|
||||||
}
|
}
|
||||||
@@ -188,7 +189,7 @@ async function loadGradeRules(){
|
|||||||
ensureGradePanel();
|
ensureGradePanel();
|
||||||
const data=await api('/site/grade-rules');
|
const data=await api('/site/grade-rules');
|
||||||
const aviso=gradeRuleRow('Avisar o designer abaixo de',data.aviso);
|
const aviso=gradeRuleRow('Avisar o designer abaixo de',data.aviso);
|
||||||
const tratamento=gradeRuleRow('Exigir o tratamento abaixo de',data.tratamento);
|
const tratamento=gradeRuleRow('Exigir o Ajuste Fino abaixo de',data.tratamento);
|
||||||
const save=button('Salvar',async()=>{
|
const save=button('Salvar',async()=>{
|
||||||
const avisoValue=aviso.on.checked?Number(aviso.num.value):null;
|
const avisoValue=aviso.on.checked?Number(aviso.num.value):null;
|
||||||
const tratamentoValue=tratamento.on.checked?Number(tratamento.num.value):null;
|
const tratamentoValue=tratamento.on.checked?Number(tratamento.num.value):null;
|
||||||
@@ -196,14 +197,14 @@ async function loadGradeRules(){
|
|||||||
if(value!==null&&(!Number.isInteger(value)||value<1||value>100))
|
if(value!==null&&(!Number.isInteger(value)||value<1||value>100))
|
||||||
throw new Error('A nota vai de 1 a 100.');
|
throw new Error('A nota vai de 1 a 100.');
|
||||||
if(avisoValue!==null&&tratamentoValue!==null&&tratamentoValue>avisoValue)
|
if(avisoValue!==null&&tratamentoValue!==null&&tratamentoValue>avisoValue)
|
||||||
throw new Error('A regra do tratamento precisa ser menor ou igual à do aviso.');
|
throw new Error('A regra do Ajuste Fino precisa ser menor ou igual à do aviso.');
|
||||||
await api('/site/grade-rules',{aviso:avisoValue,tratamento:tratamentoValue});
|
await api('/site/grade-rules',{aviso:avisoValue,tratamento:tratamentoValue});
|
||||||
say('Regras da nota da arte salvas.');
|
say('Regras da nota da arte salvas.');
|
||||||
await loadGradeRules();
|
await loadGradeRules();
|
||||||
},'btn pri');
|
},'btn pri');
|
||||||
const children=[aviso.row,tratamento.row];
|
const children=[aviso.row,tratamento.row];
|
||||||
if(!data.treatment_offered)
|
if(!data.treatment_offered)
|
||||||
children.push(node('p','Ative e dê preço ao Tratamento pelo designer para esta regra valer.','siteGradeWarn'));
|
children.push(node('p','Ative e dê preço ao Ajuste Fino para esta regra valer.','siteGradeWarn'));
|
||||||
const foot=node('div',undefined,'siteGradeSave');foot.append(save);children.push(foot);
|
const foot=node('div',undefined,'siteGradeSave');foot.append(save);children.push(foot);
|
||||||
$('site-grade-body').replaceChildren(...children);
|
$('site-grade-body').replaceChildren(...children);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1289,6 +1289,48 @@ dialog.viewer::backdrop{background:var(--scrim)}
|
|||||||
#tab-montar .montar-size-head{font-size:12.5px;color:var(--tx3)}
|
#tab-montar .montar-size-head{font-size:12.5px;color:var(--tx3)}
|
||||||
#tab-montar .montar-size-row input{height:36px;padding:0 10px;border-radius:9px;border:1px solid var(--ln2);background:var(--bg);color:var(--tx)}
|
#tab-montar .montar-size-row input{height:36px;padding:0 10px;border-radius:9px;border:1px solid var(--ln2);background:var(--bg);color:var(--tx)}
|
||||||
#tab-montar .montar-size-row input:focus{border-color:var(--acc)}
|
#tab-montar .montar-size-row input:focus{border-color:var(--acc)}
|
||||||
|
/* The Tiny typeahead opens over the sheet: the panel must not clip it. */
|
||||||
|
#tab-montar #montar-sheet{overflow:visible}
|
||||||
|
#tab-montar .montar-kindbar{display:flex;align-items:center;gap:14px;flex-wrap:wrap;padding:12px 18px}
|
||||||
|
#tab-montar .montar-kindbar .phint{margin:0}
|
||||||
|
#tab-montar .montar-customer-search{position:relative;margin-bottom:12px}
|
||||||
|
#tab-montar .montar-hits{position:absolute;z-index:30;left:0;right:0;top:calc(100% + 4px);max-height:260px;overflow:auto;border:1px solid var(--ln2);border-radius:10px;background:var(--sf);box-shadow:0 12px 32px rgba(0,0,0,.25);padding:4px}
|
||||||
|
#tab-montar .montar-hit{display:flex;flex-direction:column;gap:2px;width:100%;padding:8px 10px;border:0;border-radius:7px;background:transparent;color:var(--tx);text-align:left;cursor:pointer}
|
||||||
|
#tab-montar .montar-hit:hover{background:var(--sf3)}
|
||||||
|
#tab-montar .montar-hit b{font-size:13.5px;font-weight:650}
|
||||||
|
#tab-montar .montar-hit .sub{font-size:12.5px;color:var(--tx3)}
|
||||||
|
#tab-montar .montar-delivery{border-top:1px solid var(--ln);padding:14px 18px}
|
||||||
|
#tab-montar .montar-delivery h3{margin:0 0 10px;font-size:13px;font-weight:650;color:var(--tx2)}
|
||||||
|
#tab-montar .montar-delivery-options{display:flex;flex-wrap:wrap;gap:8px}
|
||||||
|
#tab-montar .montar-radio{display:inline-flex;align-items:center;gap:8px;height:36px;padding:0 12px;border-radius:9px;border:1px solid var(--ln2);font-size:13px;font-weight:550;color:var(--tx2);cursor:pointer}
|
||||||
|
#tab-montar .montar-radio:has(input[type="radio"]:checked){border-color:var(--acc);color:var(--tx)}
|
||||||
|
#tab-montar .montar-radio input[type="number"]{width:110px;height:28px;padding:0 8px;border-radius:7px;border:1px solid var(--ln2);background:var(--bg);color:var(--tx);font-family:inherit;font-size:13px}
|
||||||
|
#tab-montar .montar-radio input[type="number"]:disabled{opacity:.5}
|
||||||
|
#tab-montar .montar-shipping{margin-top:12px}
|
||||||
|
#tab-montar .montar-cep{display:flex;align-items:flex-end;gap:10px;flex-wrap:wrap}
|
||||||
|
#tab-montar .montar-cep .fld{flex:1;min-width:180px}
|
||||||
|
#tab-montar .montar-cep .btn{height:42px}
|
||||||
|
#tab-montar #montar-ship-msg,#tab-montar #montar-freight-msg{margin:8px 0 0;padding:0}
|
||||||
|
#tab-montar #montar-freight-msg{flex:1;min-width:180px}
|
||||||
|
#tab-montar .montar-ship-fields{margin-top:12px}
|
||||||
|
#tab-montar .montar-freight-actions{display:flex;align-items:center;gap:12px;margin-top:14px;flex-wrap:wrap}
|
||||||
|
#tab-montar .montar-freights{display:flex;flex-direction:column;gap:6px;margin-top:10px}
|
||||||
|
#tab-montar .montar-freight{display:flex;align-items:center;gap:10px;padding:9px 12px;border:1px solid var(--ln2);border-radius:9px;cursor:pointer}
|
||||||
|
#tab-montar .montar-freight:has(input:checked){border-color:var(--acc)}
|
||||||
|
#tab-montar .montar-freight input{accent-color:var(--acc)}
|
||||||
|
#tab-montar .montar-freight-meta{display:flex;flex:1;align-items:baseline;gap:10px;flex-wrap:wrap;min-width:0}
|
||||||
|
#tab-montar .montar-freight-meta b{font-size:13.5px;font-weight:650}
|
||||||
|
#tab-montar .montar-freight-meta .sub{font-size:12.5px;color:var(--tx3)}
|
||||||
|
#tab-montar .montar-freight-meta em{margin-left:auto;font-style:normal;font-weight:650}
|
||||||
|
#tab-montar .montar-brand{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-top:8px}
|
||||||
|
#tab-montar .montar-brand .lbl{font-size:12px;color:var(--tx3)}
|
||||||
|
#tab-montar .montar-brand b{font-size:13.5px;font-weight:650}
|
||||||
|
#tab-montar .montar-brandinput{width:190px;height:34px;padding:0 10px;border-radius:8px;border:1px solid var(--ln2);background:var(--bg);color:var(--tx);font-family:inherit;font-size:13px}
|
||||||
|
#tab-montar .montar-brandinput:focus{border-color:var(--acc)}
|
||||||
|
#tab-montar .montar-public{display:inline-flex;align-items:center;gap:6px;font-size:12.5px;color:var(--tx2);cursor:pointer}
|
||||||
|
#tab-montar .montar-public input{accent-color:var(--acc)}
|
||||||
|
#tab-montar .montar-stampbody{display:flex;flex-direction:column;gap:4px;min-width:0}
|
||||||
|
#tab-montar .montar-interno-fields{padding:0 18px}
|
||||||
@media (max-width:700px){
|
@media (max-width:700px){
|
||||||
#tab-montar .montar-add{grid-template-columns:minmax(0,1fr) minmax(0,1fr);padding:14px 14px 0}
|
#tab-montar .montar-add{grid-template-columns:minmax(0,1fr) minmax(0,1fr);padding:14px 14px 0}
|
||||||
#tab-montar .montar-add>.btn{grid-column:1/-1}
|
#tab-montar .montar-add>.btn{grid-column:1/-1}
|
||||||
@@ -1307,4 +1349,8 @@ dialog.viewer::backdrop{background:var(--scrim)}
|
|||||||
#tab-montar .montar-warn{padding:10px 14px}
|
#tab-montar .montar-warn{padding:10px 14px}
|
||||||
#tab-montar .montar-layout{height:260px;padding:8px}
|
#tab-montar .montar-layout{height:260px;padding:8px}
|
||||||
#tab-montar .montar-size-head,#tab-montar .montar-size-row{grid-template-columns:70px minmax(0,1fr) 36px;padding:6px 14px}
|
#tab-montar .montar-size-head,#tab-montar .montar-size-row{grid-template-columns:70px minmax(0,1fr) 36px;padding:6px 14px}
|
||||||
|
#tab-montar .montar-kindbar{padding:12px 14px}
|
||||||
|
#tab-montar .montar-delivery{padding:12px 14px}
|
||||||
|
#tab-montar .montar-interno-fields{padding:0 14px}
|
||||||
|
#tab-montar .montar-brandinput{width:100%}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -117,6 +117,13 @@
|
|||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
<section id="tab-montar" class="page" hidden>
|
<section id="tab-montar" class="page" hidden>
|
||||||
|
<section class="panel clip" id="montar-kind-panel">
|
||||||
|
<div class="phead"><h2>Pedido</h2><span class="n" id="montar-kind-hint"></span></div>
|
||||||
|
<div class="montar-kindbar">
|
||||||
|
<div class="seg" id="montar-kind" role="group" aria-label="Tipo de pedido"></div>
|
||||||
|
<p class="phint" id="montar-interno-missing" hidden>Peça à Gestão para completar o cliente interno.</p>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
<section class="panel clip" id="montar-setup">
|
<section class="panel clip" id="montar-setup">
|
||||||
<div class="phead"><h2>Estampas</h2><span class="n" id="montar-folder"></span></div>
|
<div class="phead"><h2>Estampas</h2><span class="n" id="montar-folder"></span></div>
|
||||||
<p class="phint" id="montar-nofolder" hidden>Para ler as estampas, escolha a pasta dos pedidos em Integrações neste computador.</p>
|
<p class="phint" id="montar-nofolder" hidden>Para ler as estampas, escolha a pasta dos pedidos em Integrações neste computador.</p>
|
||||||
@@ -133,13 +140,47 @@
|
|||||||
<div id="montar-lines"></div>
|
<div id="montar-lines"></div>
|
||||||
<div id="montar-layout" class="montar-layout" hidden><canvas id="montar-canvas"></canvas></div>
|
<div id="montar-layout" class="montar-layout" hidden><canvas id="montar-canvas"></canvas></div>
|
||||||
<div class="montar-customer">
|
<div class="montar-customer">
|
||||||
<h3>Cliente</h3>
|
<h3 id="montar-customer-title">Cliente</h3>
|
||||||
|
<div class="montar-customer-search" id="montar-customer-search">
|
||||||
|
<label class="fld"><span>Cliente no Tiny</span><input id="montar-customer-q" type="search" maxlength="120" autocomplete="off" spellcheck="false" placeholder="Nome ou CPF/CNPJ" role="combobox" aria-expanded="false" aria-controls="montar-customer-hits"></label>
|
||||||
|
<div class="montar-hits" id="montar-customer-hits" role="listbox" aria-label="Contatos do Tiny" hidden></div>
|
||||||
|
</div>
|
||||||
<div class="montar-customer-fields">
|
<div class="montar-customer-fields">
|
||||||
<label class="fld"><span>Nome</span><input id="montar-name" maxlength="80" autocomplete="off" placeholder="Como devemos chamar"></label>
|
<label class="fld"><span>Nome</span><input id="montar-name" maxlength="80" autocomplete="off" placeholder="Como devemos chamar"></label>
|
||||||
<label class="fld"><span>CPF ou CNPJ</span><input id="montar-doc" inputmode="numeric" maxlength="18" autocomplete="off" placeholder="CPF ou CNPJ"></label>
|
<label class="fld"><span>CPF ou CNPJ</span><input id="montar-doc" inputmode="numeric" maxlength="18" autocomplete="off" placeholder="CPF ou CNPJ"></label>
|
||||||
<label class="fld"><span>WhatsApp</span><input id="montar-zap" inputmode="numeric" maxlength="15" autocomplete="off" placeholder="(16) 99999-9999"></label>
|
<label class="fld"><span>WhatsApp</span><input id="montar-zap" inputmode="numeric" maxlength="15" autocomplete="off" placeholder="(16) 99999-9999"></label>
|
||||||
<label class="fld"><span>E-mail</span><input id="montar-mail" type="email" maxlength="254" autocomplete="off" placeholder="voce@empresa.com.br"></label>
|
<label class="fld"><span>E-mail</span><input id="montar-mail" type="email" maxlength="254" autocomplete="off" placeholder="voce@empresa.com.br"></label>
|
||||||
</div>
|
</div>
|
||||||
|
<p class="phint" id="montar-interno-note" hidden>O cliente fixo dos pedidos internos.</p>
|
||||||
|
</div>
|
||||||
|
<div class="montar-delivery" id="montar-delivery">
|
||||||
|
<h3>Entrega</h3>
|
||||||
|
<div class="montar-delivery-options">
|
||||||
|
<label class="montar-radio"><input type="radio" name="montar-delivery" value="pickup" checked> Retirada</label>
|
||||||
|
<label class="montar-radio"><input type="radio" name="montar-delivery" value="with_order"> Junto com o pedido de roupa nº <input id="montar-with-order" type="number" min="1" max="999999" step="1" inputmode="numeric" disabled></label>
|
||||||
|
<label class="montar-radio"><input type="radio" name="montar-delivery" value="ship"> Envio</label>
|
||||||
|
</div>
|
||||||
|
<div class="montar-shipping" id="montar-shipping" hidden>
|
||||||
|
<div class="montar-cep">
|
||||||
|
<label class="fld"><span>CEP de entrega</span><input id="montar-ship-cep" inputmode="numeric" maxlength="9" autocomplete="off" placeholder="00000-000"></label>
|
||||||
|
<button class="btn" id="montar-cep-find" type="button">Buscar endereço</button>
|
||||||
|
</div>
|
||||||
|
<p class="phint" id="montar-ship-msg" role="status"></p>
|
||||||
|
<div class="montar-customer-fields montar-ship-fields">
|
||||||
|
<label class="fld"><span>Quem recebe</span><input id="montar-ship-recipient" maxlength="120" autocomplete="off" placeholder="Nome ou empresa"></label>
|
||||||
|
<label class="fld"><span>Rua / avenida</span><input id="montar-ship-street" maxlength="160" autocomplete="off"></label>
|
||||||
|
<label class="fld"><span>Número</span><input id="montar-ship-number" maxlength="20" autocomplete="off" placeholder="123 ou S/N"></label>
|
||||||
|
<label class="fld"><span>Complemento</span><input id="montar-ship-complement" maxlength="80" autocomplete="off"></label>
|
||||||
|
<label class="fld"><span>Bairro</span><input id="montar-ship-district" maxlength="80" autocomplete="off"></label>
|
||||||
|
<label class="fld"><span>Cidade</span><input id="montar-ship-city" maxlength="80" autocomplete="off"></label>
|
||||||
|
<label class="fld"><span>UF</span><select id="montar-ship-state"></select></label>
|
||||||
|
</div>
|
||||||
|
<div class="montar-freight-actions">
|
||||||
|
<button class="btn" id="montar-freight-quote" type="button">Cotar frete</button>
|
||||||
|
<span class="phint" id="montar-freight-msg" role="status"></span>
|
||||||
|
</div>
|
||||||
|
<div class="montar-freights" id="montar-freights" role="radiogroup" aria-label="Opções de entrega" hidden></div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="montar-actions">
|
<div class="montar-actions">
|
||||||
<button class="btn ghost" id="montar-clear" type="button">Limpar lista</button>
|
<button class="btn ghost" id="montar-clear" type="button">Limpar lista</button>
|
||||||
@@ -154,6 +195,19 @@
|
|||||||
<button class="btn pri" id="montar-size-save" type="button">Salvar</button>
|
<button class="btn pri" id="montar-size-save" type="button">Salvar</button>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
<section class="panel clip" id="montar-interno-panel" hidden>
|
||||||
|
<div class="phead"><h2>Cliente interno</h2><span class="n">O cliente fixo dos pedidos Internos.</span></div>
|
||||||
|
<p class="phint">Enquanto algum campo estiver vazio, o pedido Interno fica indisponível.</p>
|
||||||
|
<div class="montar-customer-fields montar-interno-fields">
|
||||||
|
<label class="fld"><span>Nome</span><input id="montar-interno-name" maxlength="80" autocomplete="off" placeholder="Nexstar · Marketplace"></label>
|
||||||
|
<label class="fld"><span>CPF ou CNPJ</span><input id="montar-interno-doc" inputmode="numeric" maxlength="18" autocomplete="off" placeholder="CPF ou CNPJ"></label>
|
||||||
|
<label class="fld"><span>WhatsApp</span><input id="montar-interno-zap" inputmode="numeric" maxlength="15" autocomplete="off" placeholder="(16) 99999-9999"></label>
|
||||||
|
<label class="fld"><span>E-mail</span><input id="montar-interno-mail" type="email" maxlength="254" autocomplete="off" placeholder="voce@empresa.com.br"></label>
|
||||||
|
</div>
|
||||||
|
<div class="montar-actions">
|
||||||
|
<button class="btn pri" id="montar-interno-save" type="button">Salvar</button>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
</section>
|
</section>
|
||||||
<section id="tab-payments" class="page" hidden>
|
<section id="tab-payments" class="page" hidden>
|
||||||
<section id="payments"></section>
|
<section id="payments"></section>
|
||||||
@@ -174,6 +228,8 @@
|
|||||||
<section class="panel s4"><div class="phead"><h2>Artes tratadas, por quem aprovou</h2><span class="hint tip-l" tabindex="0" data-tip="Pedidos do período em que o arquivo final aprovado não é a arte do cliente: alguém da equipe preparou."><svg class="i s" viewBox="0 0 20 20" aria-hidden="true"><path d="M2.75 10a7.25 7.25 0 1 0 14.5 0a7.25 7.25 0 1 0 -14.5 0 M10 9v4.5 M10 6.25v.75"></path></svg></span></div>
|
<section class="panel s4"><div class="phead"><h2>Artes tratadas, por quem aprovou</h2><span class="hint tip-l" tabindex="0" data-tip="Pedidos do período em que o arquivo final aprovado não é a arte do cliente: alguém da equipe preparou."><svg class="i s" viewBox="0 0 20 20" aria-hidden="true"><path d="M2.75 10a7.25 7.25 0 1 0 14.5 0a7.25 7.25 0 1 0 -14.5 0 M10 9v4.5 M10 6.25v.75"></path></svg></span></div>
|
||||||
<div class="fillbox short"><div class="scrollin bylist" id="stats-treated"></div></div></section>
|
<div class="fillbox short"><div class="scrollin bylist" id="stats-treated"></div></div></section>
|
||||||
</div>
|
</div>
|
||||||
|
<section class="panel clip"><div class="phead"><h2>Preço de tabela (não é caixa)</h2><span class="hint tip-l" tabindex="0" data-tip="Pedidos Internos e faturados do período: o preço de tabela fica registrado no pedido, mas esse valor não é dinheiro recebido."><svg class="i s" viewBox="0 0 20 20" aria-hidden="true"><path d="M2.75 10a7.25 7.25 0 1 0 14.5 0a7.25 7.25 0 1 0 -14.5 0 M10 9v4.5 M10 6.25v.75"></path></svg></span></div>
|
||||||
|
<table class="table"><thead><tr><th scope="col">Forma</th><th scope="col" class="r">Pedidos</th><th scope="col" class="r">Metros</th><th scope="col" class="r">Valor</th></tr></thead><tbody id="stats-price-table"></tbody></table></section>
|
||||||
<div class="g12">
|
<div class="g12">
|
||||||
<section class="panel clip s6"><div class="phead"><h2>Retrabalho</h2><span class="hint" tabindex="0" data-tip="Metros refeitos sobre o filme impresso no período, só os autorizados, pela data em que foram abertos. Arte ruim aprovada pelo cliente fica fora da meta."><svg class="i s" viewBox="0 0 20 20" aria-hidden="true"><path d="M2.75 10a7.25 7.25 0 1 0 14.5 0a7.25 7.25 0 1 0 -14.5 0 M10 9v4.5 M10 6.25v.75"></path></svg></span><span class="pill warn right" id="stats-rework-pending-pill" hidden></span></div>
|
<section class="panel clip s6"><div class="phead"><h2>Retrabalho</h2><span class="hint" tabindex="0" data-tip="Metros refeitos sobre o filme impresso no período, só os autorizados, pela data em que foram abertos. Arte ruim aprovada pelo cliente fica fora da meta."><svg class="i s" viewBox="0 0 20 20" aria-hidden="true"><path d="M2.75 10a7.25 7.25 0 1 0 14.5 0a7.25 7.25 0 1 0 -14.5 0 M10 9v4.5 M10 6.25v.75"></path></svg></span><span class="pill warn right" id="stats-rework-pending-pill" hidden></span></div>
|
||||||
<table class="table"><thead><tr><th scope="col">Causa</th><th scope="col" class="r">Refeito</th><th scope="col" class="w50" id="stats-rework-film">Do impresso, contra a meta</th></tr></thead><tbody id="stats-rework"></tbody></table>
|
<table class="table"><thead><tr><th scope="col">Causa</th><th scope="col" class="r">Refeito</th><th scope="col" class="w50" id="stats-rework-film">Do impresso, contra a meta</th></tr></thead><tbody id="stats-rework"></tbody></table>
|
||||||
@@ -241,4 +297,4 @@
|
|||||||
<div class="scrim" id="scrim"></div>
|
<div class="scrim" id="scrim"></div>
|
||||||
<aside class="drawer" id="panel" aria-label="Pedido"></aside>
|
<aside class="drawer" id="panel" aria-label="Pedido"></aside>
|
||||||
</div>
|
</div>
|
||||||
<script src="/upload.js"></script><script src="/kanban-viewer.js"></script><script src="/kanban.js"></script><script src="/kanban-numbers.js"></script><script src="/kanban-site.js"></script><script src="/packing.js"></script><script src="/kanban-montador.js"></script></body></html>
|
<script src="/vendor/sentry.min.js"></script><script src="/observability.js"></script><script src="/upload.js"></script><script src="/kanban-viewer.js"></script><script src="/kanban.js"></script><script src="/kanban-label.js"></script><script src="/kanban-numbers.js"></script><script src="/kanban-site.js"></script><script src="/packing.js"></script><script src="/kanban-montador.js"></script></body></html>
|
||||||
|
|||||||
@@ -10,11 +10,11 @@ sessionStorage.removeItem('dtf-operator');
|
|||||||
const FLOW=['rec','tra','imp','rev','fin'];
|
const FLOW=['rec','tra','imp','rev','fin'];
|
||||||
const FORMER_STATES={fil:'Fila de impressão'};
|
const FORMER_STATES={fil:'Fila de impressão'};
|
||||||
const stateName=s=>board.states[s]||FORMER_STATES[s]||s;
|
const stateName=s=>board.states[s]||FORMER_STATES[s]||s;
|
||||||
const PRODUCT={file:'DTF Têxtil · folha montada',avulsa:'DTF Têxtil · artes avulsas',uvfile:'DTF UV · folha montada',uv:'DTF UV · artes avulsas'};
|
const PRODUCT={file:'DTF Têxtil · folha montada',avulsa:'DTF Têxtil · artes avulsas',uvfile:'DTF UV · folha montada',uv:'DTF UV · artes avulsas',premium:'DTF Têxtil Premium · folha montada'};
|
||||||
// Loose art the Site split by stroke (item 17): each sheet is an item of its own.
|
// Loose art the Site split by stroke (item 17): each sheet is an item of its own.
|
||||||
const productName=item=>PRODUCT[item.mode]+(item.split?' · folha '+item.split.part+' de '+item.split.of+
|
const productName=item=>PRODUCT[item.mode]+(item.split?' · folha '+item.split.part+' de '+item.split.of+
|
||||||
', '+(item.stroke_class==='C3'?'chapado':'traço fino'):'');
|
', '+(item.stroke_class==='C3'?'chapado':'traço fino'):'');
|
||||||
const SHORT={file:'Têxtil folha',avulsa:'Têxtil avulsa',uvfile:'UV folha',uv:'UV avulsa'};
|
const SHORT={file:'Têxtil folha',avulsa:'Têxtil avulsa',uvfile:'UV folha',uv:'UV avulsa',premium:'Premium'};
|
||||||
const EVENTS={payment_approved:'Pagamento aprovado',production_started:'Produção iniciada',correction_needed:'Correção necessária',ready:'Pedido pronto',cancelled:'Pedido cancelado'};
|
const EVENTS={payment_approved:'Pagamento aprovado',production_started:'Produção iniciada',correction_needed:'Correção necessária',ready:'Pedido pronto',cancelled:'Pedido cancelado'};
|
||||||
// Payment outcomes are recorded by the API in English; operators read Portuguese.
|
// Payment outcomes are recorded by the API in English; operators read Portuguese.
|
||||||
function outcomeText(outcome){
|
function outcomeText(outcome){
|
||||||
@@ -60,7 +60,7 @@ const mayAct=order=>ME?.role!=='operador'||order.state==='tra'||isMine(order);
|
|||||||
const consults=()=>['vendedor','financeiro'].includes(ME?.role);
|
const consults=()=>['vendedor','financeiro'].includes(ME?.role);
|
||||||
const TAB_NEEDS={quotes:o=>may('manage')||consults(),payments:()=>may('payments'),
|
const TAB_NEEDS={quotes:o=>may('manage')||consults(),payments:()=>may('payments'),
|
||||||
stats:()=>may('manage')||consults(),site:()=>may('manage'),
|
stats:()=>may('manage')||consults(),site:()=>may('manage'),
|
||||||
integrations:()=>may('manage')||may('print'),users:()=>may('users'),montar:()=>may('assemble')};
|
integrations:()=>may('manage')||may('print')||may('label'),users:()=>may('users'),montar:()=>may('assemble')};
|
||||||
function applyRole(){
|
function applyRole(){
|
||||||
for(const b of document.querySelectorAll('[data-tab]')){const need=TAB_NEEDS[b.dataset.tab];b.hidden=!!need&&!need();}
|
for(const b of document.querySelectorAll('[data-tab]')){const need=TAB_NEEDS[b.dataset.tab];b.hidden=!!need&&!need();}
|
||||||
if(TAB_NEEDS[tab]&&!TAB_NEEDS[tab]())showTab('board');
|
if(TAB_NEEDS[tab]&&!TAB_NEEDS[tab]())showTab('board');
|
||||||
@@ -230,7 +230,14 @@ function freightWeight(fr){
|
|||||||
function downloadButton(text,fn,className){const b=button(text,fn,className);b.prepend(svgIcon(IC.download,'i m'));return b;}
|
function downloadButton(text,fn,className){const b=button(text,fn,className);b.prepend(svgIcon(IC.download,'i m'));return b;}
|
||||||
async function api(path,body){
|
async function api(path,body){
|
||||||
const r=await fetch('/api/operator'+path,{headers:{'Content-Type':'application/json'},...(body===undefined?{}:{method:'POST',body:JSON.stringify(body)})});
|
const r=await fetch('/api/operator'+path,{headers:{'Content-Type':'application/json'},...(body===undefined?{}:{method:'POST',body:JSON.stringify(body)})});
|
||||||
const d=await r.json();if(!r.ok){const error=new Error(typeof d.detail==='string'?d.detail:'Confira os campos ('+r.status+').');error.status=r.status;throw error;}return d;
|
const d=await r.json();
|
||||||
|
if(!r.ok){
|
||||||
|
const error=new Error(typeof d.detail==='string'?d.detail:'Confira os campos ('+r.status+').');
|
||||||
|
error.status=r.status;
|
||||||
|
window.dtfObservability?.apiError?.(path,r.status,error.message,d.detail);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
return d;
|
||||||
}
|
}
|
||||||
function download(uid,orderId){return async()=>{
|
function download(uid,orderId){return async()=>{
|
||||||
const result=await api('/uploads/'+uid+'/download'+(orderId?'?order_id='+encodeURIComponent(orderId):''));
|
const result=await api('/uploads/'+uid+'/download'+(orderId?'?order_id='+encodeURIComponent(orderId):''));
|
||||||
@@ -427,7 +434,7 @@ async function fetchInto(dir,file){
|
|||||||
await writeWhole(dir,file.name,r.body);
|
await writeWhole(dir,file.name,r.body);
|
||||||
}
|
}
|
||||||
|
|
||||||
// The machines' hot folders (item 10): 3. Imprimindo/<máquina>/<C1|C2|C3>/.
|
// The machines' hot folders (item 10): 3. Imprimindo/<máquina>/<C1|C2|C3|PREMIUM>/.
|
||||||
// The server says what this computer writes now (claimed for it alone, two
|
// The server says what this computer writes now (claimed for it alone, two
|
||||||
// parts at most per machine); a written part gone from its folder was taken
|
// parts at most per machine); a written part gone from its folder was taken
|
||||||
// by FlexiPRINT, and is never written again; a withdrawn one, from a card that
|
// by FlexiPRINT, and is never written again; a withdrawn one, from a card that
|
||||||
@@ -636,7 +643,11 @@ let seenOrders=null, seenPending=null, unseen=0;
|
|||||||
async function load(quiet=false){
|
async function load(quiet=false){
|
||||||
try{
|
try{
|
||||||
const [loaded,me]=await Promise.all([api('/board'),api('/me')]);
|
const [loaded,me]=await Promise.all([api('/board'),api('/me')]);
|
||||||
board=absorb(loaded);ME=me;applyRole();paintMyMachine();
|
board=absorb(loaded);ME=me;
|
||||||
|
window.dtfEnvironment=me.sentry_environment||me.environment;
|
||||||
|
window.dtfRelease=me.sentry_release||undefined;
|
||||||
|
window.dtfObservability?.start?.(me.sentry_dsn_web,'kanban');
|
||||||
|
applyRole();paintMyMachine();
|
||||||
noticeNew(quiet);
|
noticeNew(quiet);
|
||||||
const known=new Set(board.orders.map(o=>o.id));
|
const known=new Set(board.orders.map(o=>o.id));
|
||||||
board.orders.push(...olderFinished.filter(o=>!known.has(o.id)));
|
board.orders.push(...olderFinished.filter(o=>!known.has(o.id)));
|
||||||
@@ -647,6 +658,7 @@ async function load(quiet=false){
|
|||||||
render();
|
render();
|
||||||
askMachine();
|
askMachine();
|
||||||
syncFolder();
|
syncFolder();
|
||||||
|
if(typeof labelAfterLoad==='function')labelAfterLoad();
|
||||||
}catch(e){
|
}catch(e){
|
||||||
if(e.status===401||e.status===503){$('app').hidden=true;$('login').hidden=false;$('drawer').hidden=true;}
|
if(e.status===401||e.status===503){$('app').hidden=true;$('login').hidden=false;$('drawer').hidden=true;}
|
||||||
// Not being signed in yet is the normal start, not an error.
|
// Not being signed in yet is the normal start, not an error.
|
||||||
@@ -757,7 +769,7 @@ const FILTER_TESTS={
|
|||||||
site:o=>o.origin==='site',
|
site:o=>o.origin==='site',
|
||||||
dropflow:o=>o.origin==='dropflow',
|
dropflow:o=>o.origin==='dropflow',
|
||||||
atendimento:o=>o.origin==='atendimento',
|
atendimento:o=>o.origin==='atendimento',
|
||||||
textil:o=>o.snapshot.items.some(i=>i.mode==='file'||i.mode==='avulsa'),
|
textil:o=>o.snapshot.items.some(i=>i.mode==='file'||i.mode==='avulsa'||i.mode==='premium'),
|
||||||
uv:o=>o.snapshot.items.some(i=>i.mode==='uvfile'||i.mode==='uv'),
|
uv:o=>o.snapshot.items.some(i=>i.mode==='uvfile'||i.mode==='uv'),
|
||||||
entrega:o=>!!o.snapshot.destination,
|
entrega:o=>!!o.snapshot.destination,
|
||||||
retirada:o=>!o.snapshot.destination,
|
retirada:o=>!o.snapshot.destination,
|
||||||
@@ -1052,7 +1064,11 @@ function cardFlags(order){
|
|||||||
if(redo.length)out.push(['bad','Retrabalho',redo.map(r=>'Retrabalho · '+REWORK_CAUSES[r.cause]+' · '+metres(r.metres)+(r.authorized?'':' · aguardando autorização')).join(' · ')]);
|
if(redo.length)out.push(['bad','Retrabalho',redo.map(r=>'Retrabalho · '+REWORK_CAUSES[r.cause]+' · '+metres(r.metres)+(r.authorized?'':' · aguardando autorização')).join(' · ')]);
|
||||||
if(live&&s.items.some(mirroredItem))out.push(['warn','Espelhada',MIRROR_NOTE]);
|
if(live&&s.items.some(mirroredItem))out.push(['warn','Espelhada',MIRROR_NOTE]);
|
||||||
if(waitingContact(order))out.push(['warn','Contato','Aguardando contato: '+order.contact_note+' · '+contactWho(order)]);
|
if(waitingContact(order))out.push(['warn','Contato','Aguardando contato: '+order.contact_note+' · '+contactWho(order)]);
|
||||||
if(order.snapshot.treatment)out.push(['warn','Tratamento pago','O designer trata a arte antes de imprimir; prazo +24 h']);
|
if(order.snapshot.treatment){
|
||||||
|
const n=Number(order.snapshot.treatment.arts)||1;
|
||||||
|
out.push(['warn','Ajuste Fino · '+n+(n===1?' arte':' artes'),
|
||||||
|
'O designer faz o Ajuste Fino antes de imprimir; prazo +24 h']);
|
||||||
|
}
|
||||||
if(order.proof_parent)out.push(['warn','Prova do #'+order.proof_parent.number,'Card da prova do pedido #'+order.proof_parent.number]);
|
if(order.proof_parent)out.push(['warn','Prova do #'+order.proof_parent.number,'Card da prova do pedido #'+order.proof_parent.number]);
|
||||||
if(live&&waitingProof(order)&&order.state!=='tra')out.push(['warn','Aguardando prova','Entra na fila com Prova OK no card #'+order.proof_card.number]);
|
if(live&&waitingProof(order)&&order.state!=='tra')out.push(['warn','Aguardando prova','Entra na fila com Prova OK no card #'+order.proof_card.number]);
|
||||||
if(live&&proofRejected(order))out.push(['bad','Prova reprovada',order.proof_card.proof_reason+' · '+order.proof_card.proof_decided_by]);
|
if(live&&proofRejected(order))out.push(['bad','Prova reprovada',order.proof_card.proof_reason+' · '+order.proof_card.proof_decided_by]);
|
||||||
@@ -1114,6 +1130,9 @@ function card(order,place){
|
|||||||
row.append(node('span','#'+order.number,'num'),originTag(order),age);
|
row.append(node('span','#'+order.number,'num'),originTag(order),age);
|
||||||
const name=node('span',who.title,'cname');name.title=[who.legal,who.mail].filter(Boolean).join(' · ')||who.title;
|
const name=node('span',who.title,'cname');name.title=[who.legal,who.mail].filter(Boolean).join(' · ')||who.title;
|
||||||
const meta=node('span',undefined,'cmeta');meta.append(node('span',productLine(s.items)));
|
const meta=node('span',undefined,'cmeta');meta.append(node('span',productLine(s.items)));
|
||||||
|
const special=specialDelivery(s);
|
||||||
|
if(special){const tag=node('span',special,'origin');tag.title=special;meta.append(tag);}
|
||||||
|
if(s.items.some(i=>i.mode==='premium'))meta.append(badge('Premium','','DTF Têxtil Premium: 8 passadas, branco no máximo'));
|
||||||
if(order.machine){const m=node('span',order.machine.name,'mach'+(mine?' mine':''));m.title=mine?'Sua máquina':'Máquina';meta.append(m);}
|
if(order.machine){const m=node('span',order.machine.name,'mach'+(mine?' mine':''));m.title=mine?'Sua máquina':'Máquina';meta.append(m);}
|
||||||
meta.append(node('b',metres(orderMetres(order)),'mtr'));
|
meta.append(node('b',metres(orderMetres(order)),'mtr'));
|
||||||
info.append(row,name,meta);
|
info.append(row,name,meta);
|
||||||
@@ -1141,8 +1160,10 @@ function miniCard(order){
|
|||||||
const name=node('span',who.title,'cname');name.title=who.mail||who.title;
|
const name=node('span',who.title,'cname');name.title=who.mail||who.title;
|
||||||
let text,ic=IC.check,warn=false;
|
let text,ic=IC.check,warn=false;
|
||||||
const days=Math.floor((Date.now()-new Date(order.updated_at))/86400000);
|
const days=Math.floor((Date.now()-new Date(order.updated_at))/86400000);
|
||||||
|
const special=specialDelivery(order.snapshot);
|
||||||
if(order.cancelled_at){text='Cancelado';ic=IC.ban;warn=true;}
|
if(order.cancelled_at){text='Cancelado';ic=IC.ban;warn=true;}
|
||||||
else if(order.picked_up_at)text='Retirado';
|
else if(order.picked_up_at)text='Retirado';
|
||||||
|
else if(special){text=special;ic=IC.box;}
|
||||||
else if(order.snapshot.destination){text='Entrega, '+order.snapshot.destination.city+'/'+order.snapshot.destination.state;ic=IC.truck;}
|
else if(order.snapshot.destination){text='Entrega, '+order.snapshot.destination.city+'/'+order.snapshot.destination.state;ic=IC.truck;}
|
||||||
else if(days>=PICKUP_WARN_DAYS){text='Não retirado, '+plural(days,'dia','dias');ic=IC.bag;warn=true;}
|
else if(days>=PICKUP_WARN_DAYS){text='Não retirado, '+plural(days,'dia','dias');ic=IC.bag;warn=true;}
|
||||||
else{text='Aguardando retirada';ic=IC.bag;}
|
else{text='Aguardando retirada';ic=IC.bag;}
|
||||||
@@ -1425,7 +1446,7 @@ function renderPanel(order){
|
|||||||
// A proof card is no sale (app/proof.py): it says whose proof it is.
|
// A proof card is no sale (app/proof.py): it says whose proof it is.
|
||||||
if(order.proof_parent)paid.append(node('b','Prova do pedido #'+order.proof_parent.number),', sem custo, criada em '+when(order.created_at));
|
if(order.proof_parent)paid.append(node('b','Prova do pedido #'+order.proof_parent.number),', sem custo, criada em '+when(order.created_at));
|
||||||
else paid.append(node('b',money(s.total_cents)),isTest(order)?' sem pagamento, '+when(order.created_at):
|
else paid.append(node('b',money(s.total_cents)),isTest(order)?' sem pagamento, '+when(order.created_at):
|
||||||
paidOutside(order)?' pago fora do site ('+PAID_OUTSIDE[order.payment.method]+'), registrado em '+when(order.created_at):' pago em '+when(order.created_at));
|
paidOutside(order)?' pago fora do site ('+(PAID_OUTSIDE[order.payment.method]||order.payment.method)+'), registrado em '+when(order.created_at):' pago em '+when(order.created_at));
|
||||||
const code=node('span',undefined,'chip');
|
const code=node('span',undefined,'chip');
|
||||||
code.append(node('span','DTF-'+order.number,'code'),copyButton(fileCode(order),'Copiar “'+fileCode(order)+'”, o começo do nome dos arquivos deste pedido'));
|
code.append(node('span','DTF-'+order.number,'code'),copyButton(fileCode(order),'Copiar “'+fileCode(order)+'”, o começo do nome dos arquivos deste pedido'));
|
||||||
const theirs=node('span','Código do cliente ','tip-l');theirs.append(node('span',orderCode(order.id),'code strong'));theirs.dataset.tip='O código que aparece para o cliente';
|
const theirs=node('span','Código do cliente ','tip-l');theirs.append(node('span',orderCode(order.id),'code strong'));theirs.dataset.tip='O código que aparece para o cliente';
|
||||||
@@ -1436,6 +1457,7 @@ function renderPanel(order){
|
|||||||
sub.append(badge('Nota '+s.grade_flags.aviso+': conferir a arte','warn',
|
sub.append(badge('Nota '+s.grade_flags.aviso+': conferir a arte','warn',
|
||||||
'A nota da arte ficou abaixo do limite configurado: confira antes de imprimir'));
|
'A nota da arte ficou abaixo do limite configurado: confira antes de imprimir'));
|
||||||
if(isTest(order))sub.append(badge('Teste','','Pedido de teste: sem pagamento, não vai ao Tiny'));
|
if(isTest(order))sub.append(badge('Teste','','Pedido de teste: sem pagamento, não vai ao Tiny'));
|
||||||
|
if(s.items.some(i=>i.mode==='premium'))sub.append(badge('Premium','','DTF Têxtil Premium: 8 passadas, branco no máximo'));
|
||||||
if(stalled(order)&&!order.cancelled_at)sub.append(badge('Parado há '+hoursSince(order.updated_at)+' h','bad','Sem mudar de etapa desde '+when(order.updated_at)));
|
if(stalled(order)&&!order.cancelled_at)sub.append(badge('Parado há '+hoursSince(order.updated_at)+' h','bad','Sem mudar de etapa desde '+when(order.updated_at)));
|
||||||
const steps=node('ol',undefined,'stepper');steps.setAttribute('aria-label','Etapas');
|
const steps=node('ol',undefined,'stepper');steps.setAttribute('aria-label','Etapas');
|
||||||
const at=FLOW.indexOf(order.state);
|
const at=FLOW.indexOf(order.state);
|
||||||
@@ -1593,9 +1615,9 @@ function contractionList(order){
|
|||||||
}
|
}
|
||||||
function approveParts(order,main=true){
|
function approveParts(order,main=true){
|
||||||
if(order.snapshot.treatment){
|
if(order.snapshot.treatment){
|
||||||
const approve=button('Enviar arte tratada',()=>treatDialog(order),'btn lg'+(main?' pri':''));
|
const approve=button('Enviar arte do Ajuste Fino',()=>treatDialog(order),'btn lg'+(main?' pri':''));
|
||||||
approve.dataset.treat='';
|
approve.dataset.treat='';
|
||||||
return {text:'Tratamento pago: o designer precisa enviar o PNG tratado de cada item antes da fila.',
|
return {text:'Ajuste Fino pago: o designer precisa enviar o PNG do Ajuste Fino de cada item antes da fila.',
|
||||||
files:null,approve,extra:[]};
|
files:null,approve,extra:[]};
|
||||||
}
|
}
|
||||||
const ready=readyFinals(order), all=ready.every(Boolean), many=ready.length>1;
|
const ready=readyFinals(order), all=ready.every(Boolean), many=ready.length>1;
|
||||||
@@ -1626,6 +1648,12 @@ function nextBox(order){
|
|||||||
// Pulling to a machine goes through the sheet's alerts first (front 1a).
|
// Pulling to a machine goes through the sheet's alerts first (front 1a).
|
||||||
const fn=to==='imp'?()=>pullTo(order,order.machine?.id||myMachine()?.id||null):()=>move(order,to);
|
const fn=to==='imp'?()=>pullTo(order,order.machine?.id||myMachine()?.id||null):()=>move(order,to);
|
||||||
const b=button(label||'Mover para '+board.states[to],fn,className);b.dataset.move=to;return b;};
|
const b=button(label||'Mover para '+board.states[to],fn,className);b.dataset.move=to;return b;};
|
||||||
|
// The 10x15 label at Finalizado: added here so a view-only Expedição sees it
|
||||||
|
// too (the read-only branch below skips the stage blocks).
|
||||||
|
if(st==='fin'&&typeof labelReprintButton==='function'){
|
||||||
|
const reprint=labelReprintButton(order);
|
||||||
|
if(reprint)more.push(reprint);
|
||||||
|
}
|
||||||
if(waitingProof(order)){
|
if(waitingProof(order)){
|
||||||
title='Aguardando prova do #'+order.proof_card.number;
|
title='Aguardando prova do #'+order.proof_card.number;
|
||||||
const manual=(board.orders.find(o=>o.id===order.proof_card.id)?.print_files||[]).some(r=>r.status==='manual');
|
const manual=(board.orders.find(o=>o.id===order.proof_card.id)?.print_files||[]).some(r=>r.status==='manual');
|
||||||
@@ -1681,8 +1709,8 @@ function nextBox(order){
|
|||||||
}
|
}
|
||||||
if(st==='rec'||st==='cor'){
|
if(st==='rec'||st==='cor'){
|
||||||
if(st==='rec'&&order.snapshot.treatment&&!treatmentDone(order)&&finalDone(order)){
|
if(st==='rec'&&order.snapshot.treatment&&!treatmentDone(order)&&finalDone(order)){
|
||||||
title='Enviar a arte tratada';
|
title='Enviar a arte do Ajuste Fino';
|
||||||
note('O tratamento foi pago. Envie o PNG tratado de cada item antes de colocar o pedido na fila.');
|
note('O Ajuste Fino foi pago. Envie o PNG ajustado de cada item antes de colocar o pedido na fila.');
|
||||||
if(may('produce'))main.push(button('Tratar a arte',()=>treatDialog(order),'btn pri lg'));
|
if(may('produce'))main.push(button('Tratar a arte',()=>treatDialog(order),'btn pri lg'));
|
||||||
return composeNext(title,body,main,more);
|
return composeNext(title,body,main,more);
|
||||||
}
|
}
|
||||||
@@ -1822,6 +1850,10 @@ function pickupDialog(order){
|
|||||||
}
|
}
|
||||||
// Pickup or delivery, from the freight the customer chose.
|
// Pickup or delivery, from the freight the customer chose.
|
||||||
const isPickup=order=>order.snapshot.freight?.service==='pickup';
|
const isPickup=order=>order.snapshot.freight?.service==='pickup';
|
||||||
|
// An internal order stays in house, and a sale can travel with the customer's
|
||||||
|
// clothing order (Fase 2, front 7a.3): the card and the panel say so instead
|
||||||
|
// of "Retirada".
|
||||||
|
const specialDelivery=s=>s.kind==='interno'?'Interno':s.with_order?'Junto com o pedido de roupa nº '+s.with_order:null;
|
||||||
// ---- Final files: the file each item is printed from, approved by an operator.
|
// ---- Final files: the file each item is printed from, approved by an operator.
|
||||||
const finalDone=order=>order.snapshot.items.every((_,index)=>(order.final_items||[]).includes(index));
|
const finalDone=order=>order.snapshot.items.every((_,index)=>(order.final_items||[]).includes(index));
|
||||||
const treatmentDone=order=>order.snapshot.items.every((_,index)=>order.treated?.items?.includes(index));
|
const treatmentDone=order=>order.snapshot.items.every((_,index)=>order.treated?.items?.includes(index));
|
||||||
@@ -1919,6 +1951,10 @@ function cardOpenAction(order){
|
|||||||
const row=node('span',undefined,'card-open-row');row.append(action,review);
|
const row=node('span',undefined,'card-open-row');row.append(action,review);
|
||||||
return row;
|
return row;
|
||||||
}
|
}
|
||||||
|
if(order.state==='fin'&&typeof labelReprintButton==='function'){
|
||||||
|
const reprint=labelReprintButton(order,'card-open');
|
||||||
|
if(reprint){const row=node('span',undefined,'card-open-row');row.append(action,reprint);return row;}
|
||||||
|
}
|
||||||
return action;
|
return action;
|
||||||
}
|
}
|
||||||
// "Revisar" (Fase 2, front 2): the sheet's photo or a video of up to 30 s,
|
// "Revisar" (Fase 2, front 2): the sheet's photo or a video of up to 30 s,
|
||||||
@@ -2230,7 +2266,7 @@ function phoneFacts(order){
|
|||||||
const box=node('div',undefined,'mblock mfacts');
|
const box=node('div',undefined,'mblock mfacts');
|
||||||
const row=(k,v)=>{if(!v)return;const r=node('div',undefined,'mfact');r.append(node('span',k),node('b',v));box.append(r);};
|
const row=(k,v)=>{if(!v)return;const r=node('div',undefined,'mfact');r.append(node('span',k),node('b',v));box.append(r);};
|
||||||
row('Cliente',who.title);row('E-mail',s.customer.mail);row(docKind(s.customer.cnpj),cnpj(s.customer.cnpj));
|
row('Cliente',who.title);row('E-mail',s.customer.mail);row(docKind(s.customer.cnpj),cnpj(s.customer.cnpj));
|
||||||
row('Entrega',dest?dest.city+'/'+dest.state:'Retirada em Franca');
|
row('Entrega',specialDelivery(s)||(dest?dest.city+'/'+dest.state:'Retirada em Franca'));
|
||||||
row('Máquina',order.machine?.name||'Nenhuma');row('Código','DTF-'+order.number+', cliente '+orderCode(order.id));
|
row('Máquina',order.machine?.name||'Nenhuma');row('Código','DTF-'+order.number+', cliente '+orderCode(order.id));
|
||||||
// Choosing the machine stays where it is allowed.
|
// Choosing the machine stays where it is allowed.
|
||||||
if(may('print')&&ME?.role!=='operador'&&board.machines?.length){const m=machineCard(order).querySelector('select');if(m)box.append(m);}
|
if(may('print')&&ME?.role!=='operador'&&board.machines?.length){const m=machineCard(order).querySelector('select');if(m)box.append(m);}
|
||||||
@@ -2246,9 +2282,10 @@ function orderFacts(order){
|
|||||||
client.append(node('span','Cliente','lbl'),title,...(who.mail?[node('span',who.mail)]:[]),doc);
|
client.append(node('span','Cliente','lbl'),title,...(who.mail?[node('span',who.mail)]:[]),doc);
|
||||||
const zap=whatsappLink(s.customer.zap);
|
const zap=whatsappLink(s.customer.zap);
|
||||||
if(zap){const a=node('a','Abrir conversa','btn lnk');a.href=zap;a.target='_blank';a.rel='noopener noreferrer';a.title=s.customer.zap;a.prepend(svgIcon(IC.chat,'i s'));client.append(a);}
|
if(zap){const a=node('a','Abrir conversa','btn lnk');a.href=zap;a.target='_blank';a.rel='noopener noreferrer';a.title=s.customer.zap;a.prepend(svgIcon(IC.chat,'i s'));client.append(a);}
|
||||||
const where=node('div',undefined,'fact');
|
const where=node('div',undefined,'fact'),special=specialDelivery(s);
|
||||||
where.append(node('span','Entrega','lbl'),node('b',dest?dest.recipient:'Retirada em Franca'),
|
where.append(node('span','Entrega','lbl'),node('b',special||(dest?dest.recipient:'Retirada em Franca')),
|
||||||
node('span',dest?dest.street+', '+dest.number+(dest.complement?' '+dest.complement:'')+', '+dest.district+', '+dest.city+'/'+dest.state+', CEP '+dest.postal_code:'O cliente retira na fábrica'));
|
node('span',special?(special==='Interno'?'Fica na fábrica':'Sem frete próprio'):
|
||||||
|
dest?dest.street+', '+dest.number+(dest.complement?' '+dest.complement:'')+', '+dest.district+', '+dest.city+'/'+dest.state+', CEP '+dest.postal_code:'O cliente retira na fábrica'));
|
||||||
if(dest&&s.freight?.total_cents)where.append(node('span',(s.freight.description||'Jadlog')+', '+money(s.freight.total_cents)+(s.freight.weight_kg?', '+freightWeight(s.freight):''),'faint'));
|
if(dest&&s.freight?.total_cents)where.append(node('span',(s.freight.description||'Jadlog')+', '+money(s.freight.total_cents)+(s.freight.weight_kg?', '+freightWeight(s.freight):''),'faint'));
|
||||||
grid.append(client,where);
|
grid.append(client,where);
|
||||||
if(order.machine||board.machines?.length)grid.append(machineCard(order));
|
if(order.machine||board.machines?.length)grid.append(machineCard(order));
|
||||||
@@ -2370,7 +2407,7 @@ function filesView(order,revisions,view){
|
|||||||
// Rework (Dropstar's rules D-02 to D-04). Gestão opens it with its cause,
|
// Rework (Dropstar's rules D-02 to D-04). Gestão opens it with its cause,
|
||||||
// which never changes after; an Administrador authorizes or declines it,
|
// which never changes after; an Administrador authorizes or declines it,
|
||||||
// never one they opened. Bad art the customer approved is outside the goal.
|
// never one they opened. Bad art the customer approved is outside the goal.
|
||||||
const REWORK_CAUSES={impressao:'Falha de impressão',perfil_cor:'Perfil de cor',tratamento:'Erro de tratamento',
|
const REWORK_CAUSES={impressao:'Falha de impressão',perfil_cor:'Perfil de cor',tratamento:'Erro de Ajuste Fino',
|
||||||
pedido:'Erro de pedido',arte_cliente:'Arte aprovada pelo cliente'};
|
pedido:'Erro de pedido',arte_cliente:'Arte aprovada pelo cliente'};
|
||||||
const REWORK_OUTSIDE='arte_cliente';
|
const REWORK_OUTSIDE='arte_cliente';
|
||||||
function reworkForm(order){
|
function reworkForm(order){
|
||||||
@@ -2429,7 +2466,7 @@ function historyView(order,rows,view){
|
|||||||
item.stroke_choice==='client_c3'?'proteger chapado (C3)':'imprimir assim (C1)'));
|
item.stroke_choice==='client_c3'?'proteger chapado (C3)':'imprimir assim (C1)'));
|
||||||
}
|
}
|
||||||
list.append(entry('Pedido recebido',board.environment==='local'&&order.payment?.provider==='fake'?'pagamento de teste':isTest(order)?'teste, sem pagamento':
|
list.append(entry('Pedido recebido',board.environment==='local'&&order.payment?.provider==='fake'?'pagamento de teste':isTest(order)?'teste, sem pagamento':
|
||||||
paidOutside(order)?ORIGINS[order.origin]+', pago fora do site ('+PAID_OUTSIDE[order.payment.method]+'), registrado por '+order.payment.operator:ORIGINS[order.origin]||'Site',
|
paidOutside(order)?ORIGINS[order.origin]+', pago fora do site ('+(PAID_OUTSIDE[order.payment.method]||order.payment.method)+'), registrado por '+order.payment.operator:ORIGINS[order.origin]||'Site',
|
||||||
order.created_at,paidOutside(order)?order.payment.note:''));
|
order.created_at,paidOutside(order)?order.payment.note:''));
|
||||||
view.replaceChildren(list);
|
view.replaceChildren(list);
|
||||||
}
|
}
|
||||||
@@ -2565,9 +2602,9 @@ const PRODUCT_LABEL={textil:'Têxtil',uv:'UV'};
|
|||||||
// What each profile is for, in a line (app/core/auth.py).
|
// What each profile is for, in a line (app/core/auth.py).
|
||||||
const ROLE_HINTS={superadmin:'Tudo, e o suporte do sistema.',admin:'Tudo, inclusive usuários e máquinas.',
|
const ROLE_HINTS={superadmin:'Tudo, e o suporte do sistema.',admin:'Tudo, inclusive usuários e máquinas.',
|
||||||
gestao:'Tudo menos usuários; no quadro só puxa para trás, com motivo.',designer:'Aprova e recusa o arquivo final e pede correção.',
|
gestao:'Tudo menos usuários; no quadro só puxa para trás, com motivo.',designer:'Aprova e recusa o arquivo final e pede correção.',
|
||||||
operador:'Escolhe a máquina ao entrar, puxa da fila, imprime e passa para a Revisão.',revisor:'Confere a folha impressa e libera para Finalizado.',
|
operador:'Escolhe a máquina ao entrar, puxa da fila, imprime e passa para a Revisão.',revisor:'Confere a folha impressa, libera para Finalizado e reimprime a etiqueta.',
|
||||||
vendedor:'Só consulta.',financeiro:'Pagamentos, Números e Cotações; cancela pedido com motivo.',
|
vendedor:'Só consulta.',financeiro:'Pagamentos, Números e Cotações; cancela pedido com motivo.',
|
||||||
expedicao:'Monta folhas no Kanban; só consulta o resto.'};
|
expedicao:'Monta folhas no Kanban e imprime a etiqueta; só consulta o resto.'};
|
||||||
// Who is on the system: used it in the last 15 minutes, signed in before,
|
// Who is on the system: used it in the last 15 minutes, signed in before,
|
||||||
// never, or switched off.
|
// never, or switched off.
|
||||||
const PRESENCE={on:'Ativo agora: usou o sistema nos últimos 15 minutos',away:'Inativo',never:'Nunca entrou',off:'Desativado: não entra no sistema'};
|
const PRESENCE={on:'Ativo agora: usou o sistema nos últimos 15 minutos',away:'Inativo',never:'Nunca entrou',off:'Desativado: não entra no sistema'};
|
||||||
@@ -2582,7 +2619,8 @@ const ROLE_COLUMNS=['admin','gestao','designer','operador','revisor','vendedor',
|
|||||||
const ROLE_MATRIX=[['Aprovar o arquivo final','YYYNNNNN'],['Pedir correção','YYYNNNNN'],['Puxar da fila e imprimir','YNNYNNNN'],
|
const ROLE_MATRIX=[['Aprovar o arquivo final','YYYNNNNN'],['Pedir correção','YYYNNNNN'],['Puxar da fila e imprimir','YNNYNNNN'],
|
||||||
['Lançar na ficha da máquina','YYNYNNNN'],['Liberar para Finalizado','YNNNYNNN'],['Foto da revisão','YYNNYNNN'],['Voltar uma etapa, com motivo','YYYYYNNN'],['Marcar retirado','YYYYYNNN'],
|
['Lançar na ficha da máquina','YYNYNNNN'],['Liberar para Finalizado','YNNNYNNN'],['Foto da revisão','YYNNYNNN'],['Voltar uma etapa, com motivo','YYYYYNNN'],['Marcar retirado','YYYYYNNN'],
|
||||||
['Cotações e Números','YYNNNVVN'],['Pagamentos','YYNNNNVN'],['Pedido pago fora do site','YYNNNNNN'],['Prova OK ou reprovada','YYNNNYNN'],['Cancelar pedido','YYNNNNYN'],
|
['Cotações e Números','YYNNNVVN'],['Pagamentos','YYNNNNVN'],['Pedido pago fora do site','YYNNNNNN'],['Prova OK ou reprovada','YYNNNYNN'],['Cancelar pedido','YYNNNNYN'],
|
||||||
['Abrir retrabalho','NYNNNNNN'],['Autorizar retrabalho','YNNNNNNN'],['Usuários e máquinas','YNNNNNNN'],['Montar folha','YYNNNYNY']];
|
['Abrir retrabalho','NYNNNNNN'],['Autorizar retrabalho','YNNNNNNN'],['Usuários e máquinas','YNNNNNNN'],['Montar folha','YYNNNYNY'],
|
||||||
|
['Imprimir a etiqueta 10×15','YYNNYNNY']];
|
||||||
let usersData=null;
|
let usersData=null;
|
||||||
async function loadUsers(){
|
async function loadUsers(){
|
||||||
usersData=await api('/users');
|
usersData=await api('/users');
|
||||||
@@ -2815,7 +2853,11 @@ async function openMachineSheet(machineId){
|
|||||||
box.append(field('Preço de compra (R$)',price),field('Data de instalação',installed));
|
box.append(field('Preço de compra (R$)',price),field('Data de instalação',installed));
|
||||||
for(const [item,[label,unit]] of Object.entries(data.catalog.supplies)){
|
for(const [item,[label,unit]] of Object.entries(data.catalog.supplies)){
|
||||||
const input=node('input');input.type='number';input.min='0';input.step='0.001';input.inputMode='decimal';
|
const input=node('input');input.type='number';input.min='0';input.step='0.001';input.inputMode='decimal';
|
||||||
input.value=data.minimums[item]!==null&&data.minimums[item]!==undefined?Number(data.minimums[item]).toString():'';
|
// Dropstar's fixed minimums are the defaults: a machine with none typed
|
||||||
|
// shows and uses them until Gestão changes them.
|
||||||
|
const typed=data.minimums[item], fallback=data.default_minimums?.[item];
|
||||||
|
input.value=typed!==null&&typed!==undefined?Number(typed).toString()
|
||||||
|
:fallback!==null&&fallback!==undefined?Number(fallback).toString():'';
|
||||||
minimums[item]=input;
|
minimums[item]=input;
|
||||||
box.append(field('Mínimo de '+label.toLowerCase()+' ('+unit+')',input));
|
box.append(field('Mínimo de '+label.toLowerCase()+' ('+unit+')',input));
|
||||||
}
|
}
|
||||||
@@ -3316,7 +3358,7 @@ function tinyDetail(t){
|
|||||||
// buttons) opens under "Detalhes", so every row keeps the same height. Which
|
// buttons) opens under "Detalhes", so every row keeps the same height. Which
|
||||||
// rows are open survives the page's automatic refresh.
|
// rows are open survives the page's automatic refresh.
|
||||||
const OPEN_INTEG=new Set();
|
const OPEN_INTEG=new Set();
|
||||||
const INTEG_ICONS={'Pastas dos pedidos':IC.folder,'Tiny':IC.box,'Mercado Pago':IC.card,'Frete':IC.truck,'E-mail':IC.mail,'Backup do banco':IC.database};
|
const INTEG_ICONS={'Pastas dos pedidos':IC.folder,'Etiqueta 10×15':IC.printer,'Tiny':IC.box,'Mercado Pago':IC.card,'Frete':IC.truck,'E-mail':IC.mail,'Backup do banco':IC.database};
|
||||||
const TONE_PILL={ok:'ok',warn:'warn',off:''};
|
const TONE_PILL={ok:'ok',warn:'warn',off:''};
|
||||||
function statePill(text,tone){const p=badge(text,TONE_PILL[tone]??tone);p.prepend(node('span',undefined,'dot'));return p;}
|
function statePill(text,tone){const p=badge(text,TONE_PILL[tone]??tone);p.prepend(node('span',undefined,'dot'));return p;}
|
||||||
function integration({name,state,tone,summary,actions=[],details=[],extra=[]}){
|
function integration({name,state,tone,summary,actions=[],details=[],extra=[]}){
|
||||||
@@ -3565,6 +3607,8 @@ const integRow=o=>may('integrations')?integration(o):integration({name:o.name,st
|
|||||||
let mpCheck=null;
|
let mpCheck=null;
|
||||||
function renderIntegrations(){
|
function renderIntegrations(){
|
||||||
const t=board.tiny||{};const rows=may('print')?[folderCard()]:[];
|
const t=board.tiny||{};const rows=may('print')?[folderCard()]:[];
|
||||||
|
const labelRow=typeof labelIntegrationRow==='function'?labelIntegrationRow():null;
|
||||||
|
if(labelRow)rows.push(labelRow);
|
||||||
$('event-log').hidden=!may('integrations');
|
$('event-log').hidden=!may('integrations');
|
||||||
if(!may('manage')){$('integrations').replaceChildren(...rows);return;}
|
if(!may('manage')){$('integrations').replaceChildren(...rows);return;}
|
||||||
const act=(text,fn)=>button(text,fn,'btn');
|
const act=(text,fn)=>button(text,fn,'btn');
|
||||||
@@ -3685,7 +3729,7 @@ function hitRow(items,title,sub,meta,state,tone,open){
|
|||||||
function orderHit(order){
|
function orderHit(order){
|
||||||
const s=order.snapshot;
|
const s=order.snapshot;
|
||||||
return hitRow(s.items,'#'+order.number+' · '+orderCode(order.id),buyer(s).title,
|
return hitRow(s.items,'#'+order.number+' · '+orderCode(order.id),buyer(s).title,
|
||||||
s.items.map(i=>SHORT[i.mode]+' · '+metres(i.billed_metres)).join(' + ')+' · '+(s.destination?'Entrega':'Retirada')+' · pago '+when(order.created_at),
|
s.items.map(i=>SHORT[i.mode]+' · '+metres(i.billed_metres)).join(' + ')+' · '+(specialDelivery(s)||(s.destination?'Entrega':'Retirada'))+' · pago '+when(order.created_at),
|
||||||
order.cancelled_at?'Cancelado':board.states[order.state],order.cancelled_at?'bad':'',()=>{
|
order.cancelled_at?'Cancelado':board.states[order.state],order.cancelled_at?'bad':'',()=>{
|
||||||
// An older finished order is not on the board yet: it joins, like "Carregar mais".
|
// An older finished order is not on the board yet: it joins, like "Carregar mais".
|
||||||
if(!board.orders.some(o=>o.id===order.id)){olderFinished.push(order);board.orders.push(order);}
|
if(!board.orders.some(o=>o.id===order.id)){olderFinished.push(order);board.orders.push(order);}
|
||||||
|
|||||||
120
web/observability.js
Normal file
120
web/observability.js
Normal file
@@ -0,0 +1,120 @@
|
|||||||
|
/* Sentry for the Site and the Kanban, used only when the DSN arrives from the
|
||||||
|
API. It loads after web/vendor/sentry.min.js and never fetches anything
|
||||||
|
itself; DSNs are public by design, so an empty one leaves everything off.
|
||||||
|
|
||||||
|
beforeSend follows the server (app/observability.py): no cookies, credential
|
||||||
|
headers, request bodies or signed/token query strings, and CPF/CNPJ and
|
||||||
|
e-mails replaced by [removido]. */
|
||||||
|
(function () {
|
||||||
|
const EMAIL = /[^\s@]+@[^\s@]+\.[A-Za-z]{2,}/g;
|
||||||
|
const DOCUMENT = /(?<!\d)(?:\d{2}\.?\d{3}\.?\d{3}\/?\d{4}-?\d{2}|\d{3}\.?\d{3}\.?\d{3}-?\d{2})(?!\d)/g;
|
||||||
|
const SENSITIVE_PARAM = /token|signature|x-amz/i;
|
||||||
|
const SENSITIVE_HEADER = /^(cookie|authorization|x-.*token.*)$/i;
|
||||||
|
const REDACTED = '[removido]';
|
||||||
|
let started = false;
|
||||||
|
let app = '';
|
||||||
|
|
||||||
|
const clean = value => String(value == null ? '' : value)
|
||||||
|
.replace(EMAIL, REDACTED).replace(DOCUMENT, REDACTED);
|
||||||
|
|
||||||
|
function scrubQuery(query) {
|
||||||
|
if (!query) return query;
|
||||||
|
return String(query).split('&').filter(part => {
|
||||||
|
let key = part.split('=')[0] || '';
|
||||||
|
try { key = decodeURIComponent(key.replace(/\+/g, ' ')); } catch (error) { /* keep the raw key */ }
|
||||||
|
return !SENSITIVE_PARAM.test(key);
|
||||||
|
}).join('&');
|
||||||
|
}
|
||||||
|
|
||||||
|
function scrubText(value) {
|
||||||
|
if (typeof value !== 'string') return value;
|
||||||
|
value = clean(value);
|
||||||
|
const at = value.indexOf('?');
|
||||||
|
return at < 0 ? value : value.slice(0, at + 1) + scrubQuery(value.slice(at + 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
function scrubUrl(url) {
|
||||||
|
if (typeof url !== 'string') return url;
|
||||||
|
const at = url.indexOf('?');
|
||||||
|
return at < 0 ? url : url.slice(0, at + 1) + scrubQuery(url.slice(at + 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
function scrubValue(value) {
|
||||||
|
if (typeof value === 'string') return scrubText(value);
|
||||||
|
if (Array.isArray(value)) return value.map(scrubValue);
|
||||||
|
if (value && typeof value === 'object') {
|
||||||
|
const out = {};
|
||||||
|
for (const [key, item] of Object.entries(value)) out[key] = scrubValue(item);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
function scrubRequest(request) {
|
||||||
|
if (!request || typeof request !== 'object') return;
|
||||||
|
delete request.cookies;
|
||||||
|
delete request.data;
|
||||||
|
delete request.body;
|
||||||
|
if (request.headers && typeof request.headers === 'object') {
|
||||||
|
for (const key of Object.keys(request.headers)) {
|
||||||
|
if (SENSITIVE_HEADER.test(key)) delete request.headers[key];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (request.query_string) request.query_string = scrubQuery(request.query_string);
|
||||||
|
if (request.url) request.url = scrubUrl(request.url);
|
||||||
|
}
|
||||||
|
|
||||||
|
function scrub(event) {
|
||||||
|
if (!event || typeof event !== 'object') return event;
|
||||||
|
scrubRequest(event.request);
|
||||||
|
if (typeof event.message === 'string') event.message = scrubText(event.message);
|
||||||
|
if (event.logentry && typeof event.logentry.message === 'string')
|
||||||
|
event.logentry.message = scrubText(event.logentry.message);
|
||||||
|
if (event.exception && Array.isArray(event.exception.values)) {
|
||||||
|
for (const value of event.exception.values) {
|
||||||
|
if (value && typeof value.value === 'string') value.value = scrubText(value.value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let breadcrumbs = event.breadcrumbs;
|
||||||
|
if (breadcrumbs && !Array.isArray(breadcrumbs)) breadcrumbs = breadcrumbs.values;
|
||||||
|
if (Array.isArray(breadcrumbs)) {
|
||||||
|
for (const crumb of breadcrumbs) {
|
||||||
|
if (!crumb || typeof crumb !== 'object') continue;
|
||||||
|
if (typeof crumb.message === 'string') crumb.message = scrubText(crumb.message);
|
||||||
|
if (crumb.data) crumb.data = scrubValue(crumb.data);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (event.extra) event.extra = scrubValue(event.extra);
|
||||||
|
if (event.user) event.user = scrubValue(event.user);
|
||||||
|
return event;
|
||||||
|
}
|
||||||
|
|
||||||
|
function start(dsn, component) {
|
||||||
|
if (started || !dsn || typeof Sentry === 'undefined') return;
|
||||||
|
started = true;
|
||||||
|
app = component || '';
|
||||||
|
const options = {dsn, sendDefaultPii: false, beforeSend: scrub};
|
||||||
|
if (window.dtfEnvironment) options.environment = window.dtfEnvironment;
|
||||||
|
if (window.dtfRelease) options.release = window.dtfRelease;
|
||||||
|
try {
|
||||||
|
Sentry.init(options);
|
||||||
|
Sentry.setTag('app', app);
|
||||||
|
} catch (error) {
|
||||||
|
started = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function apiError(path, status, message, detail) {
|
||||||
|
if (!started || status === 401 || typeof Sentry === 'undefined') return;
|
||||||
|
try {
|
||||||
|
const extra = {path, status, page: location.pathname};
|
||||||
|
if (status === 422 && detail) extra.detail = detail;
|
||||||
|
Sentry.captureMessage(clean('API ' + status + ' ' + path + ': ' + (message || '')),
|
||||||
|
{level: 'error', tags: {app}, extra});
|
||||||
|
} catch (error) {
|
||||||
|
// Reporting an error must never break the page.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
window.dtfObservability = {start, apiError, scrub};
|
||||||
|
})();
|
||||||
128
web/site-cart.js
128
web/site-cart.js
@@ -4,6 +4,77 @@
|
|||||||
scope and run top to bottom, exactly as the original did. */
|
scope and run top to bottom, exactly as the original did. */
|
||||||
// ── carrinho
|
// ── carrinho
|
||||||
let itemAtual=null;
|
let itemAtual=null;
|
||||||
|
// Ajuste Fino (front 1a): each art may be chosen under its warning, or the
|
||||||
|
// general switch chooses every art of the paying items.
|
||||||
|
function artesDoItem(it){
|
||||||
|
if(it.partes && it.partes.length)
|
||||||
|
return it.partes.reduce((t,p)=>t+((p.production&&p.production.sources||[]).length),0);
|
||||||
|
return (it.production&&it.production.sources||[]).length;
|
||||||
|
}
|
||||||
|
function artesSelecionadas(aPagar=itensAPagar()){
|
||||||
|
if(ajusteTudo) return aPagar.reduce((t,it)=>t+artesDoItem(it),0);
|
||||||
|
return aPagar.reduce((t,it)=>{
|
||||||
|
if(it.partes && it.partes.length)
|
||||||
|
return t+it.partes.reduce((s,p)=>s+(p.ajusteSources||[]).length,0);
|
||||||
|
return t+(it.ajusteSources||[]).length;
|
||||||
|
},0);
|
||||||
|
}
|
||||||
|
// While a product is open, its files are not in the cart yet; the rule must
|
||||||
|
// still see the arts the customer already checked under their warnings.
|
||||||
|
function artesEscolhidasNaTela(){
|
||||||
|
if(!modo) return 0;
|
||||||
|
return (ehFolha()?folhas:artes).filter(x=>x.ajuste).length;
|
||||||
|
}
|
||||||
|
// What the cart snapshot compares: the switch and every chosen source.
|
||||||
|
function ajusteSnapshot(){
|
||||||
|
return {tudo:!!ajusteTudo, itens:itensAPagar().map(it=>({
|
||||||
|
escolhas:it.ajusteSources||[],
|
||||||
|
partes:(it.partes||[]).map(p=>p.ajusteSources||[])
|
||||||
|
}))};
|
||||||
|
}
|
||||||
|
// A final cart item (after a split sheet becomes its own items) to the pairs.
|
||||||
|
function tratamentoParaItens(itens){
|
||||||
|
if(!(TAXA_TRATAMENTO>0)) return false;
|
||||||
|
if(ajusteTudo) return true;
|
||||||
|
const pairs=[];
|
||||||
|
itens.forEach((it,itemIndex)=>{
|
||||||
|
for(const source of it.ajusteSources||[]) pairs.push([itemIndex,source]);
|
||||||
|
});
|
||||||
|
return pairs.length?pairs:false;
|
||||||
|
}
|
||||||
|
function materializaAjuste(){
|
||||||
|
if(!ajusteTudo) return;
|
||||||
|
ajusteTudo=false;
|
||||||
|
for(const it of itensAPagar()){
|
||||||
|
if(it.partes && it.partes.length){
|
||||||
|
for(const part of it.partes)
|
||||||
|
part.ajusteSources=Array.from({length:(part.production&&part.production.sources||[]).length},(_,i)=>i);
|
||||||
|
}else{
|
||||||
|
it.ajusteSources=Array.from({length:(it.production&&it.production.sources||[]).length},(_,i)=>i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for(const x of folhas) x.ajuste=true;
|
||||||
|
for(const a of artes) a.ajuste=true;
|
||||||
|
}
|
||||||
|
function limpaAjuste(){
|
||||||
|
ajusteTudo=false;
|
||||||
|
for(const it of itensAPagar()){
|
||||||
|
it.ajusteSources=[];
|
||||||
|
for(const part of it.partes||[]) part.ajusteSources=[];
|
||||||
|
}
|
||||||
|
for(const x of folhas) x.ajuste=false;
|
||||||
|
for(const a of artes) a.ajuste=false;
|
||||||
|
}
|
||||||
|
// Update the per-art boxes without repainting the list, which would discard
|
||||||
|
// the item the customer is still building.
|
||||||
|
function pintaAjusteCheckboxes(){
|
||||||
|
document.querySelectorAll('[data-ajuste]').forEach(el=>{
|
||||||
|
const x=folhas[+el.dataset.ajuste]; if(x)el.checked=ajusteTudo||!!x.ajuste;
|
||||||
|
});
|
||||||
|
document.querySelectorAll('[data-ajustea]').forEach(el=>{
|
||||||
|
const a=artes[+el.dataset.ajustea]; if(a)el.checked=ajusteTudo||!!a.ajuste;
|
||||||
|
});
|
||||||
|
}
|
||||||
function invalidaItemAtual(){
|
function invalidaItemAtual(){
|
||||||
if(!itemAtual) return;
|
if(!itemAtual) return;
|
||||||
itemAtual=null;
|
itemAtual=null;
|
||||||
@@ -31,7 +102,8 @@ function limpaPaineis(){
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Front 8.5: when the worst grade of the paying items is below the rule and
|
// Front 8.5: when the worst grade of the paying items is below the rule and
|
||||||
// the treatment is offered, the designer's treatment is required.
|
// Ajuste Fino is offered, it is required. The simple rule the server keeps:
|
||||||
|
// at least one art must be chosen; with none, the general switch selects all.
|
||||||
function mostraAvisoTratamento(texto){
|
function mostraAvisoTratamento(texto){
|
||||||
const box=$('tratamentoBox'); if(!box)return;
|
const box=$('tratamentoBox'); if(!box)return;
|
||||||
let el=$('tratamentoAviso');
|
let el=$('tratamentoAviso');
|
||||||
@@ -48,12 +120,27 @@ function aplicaTratamento(aPagar){
|
|||||||
const required=offered&&rule>0&&worst!==null&&worst<rule;
|
const required=offered&&rule>0&&worst!==null&&worst<rule;
|
||||||
box.hidden=!offered;
|
box.hidden=!offered;
|
||||||
if(!offered){
|
if(!offered){
|
||||||
check.checked=false;check.disabled=false;mostraAvisoTratamento('');
|
check.checked=false;check.disabled=false;
|
||||||
|
ajusteTudo=false;
|
||||||
|
for(const it of aPagar){
|
||||||
|
it.ajusteSources=[];
|
||||||
|
for(const part of it.partes||[]) part.ajusteSources=[];
|
||||||
|
}
|
||||||
|
for(const x of folhas) x.ajuste=false;
|
||||||
|
for(const a of artes) a.ajuste=false;
|
||||||
|
mostraAvisoTratamento('');
|
||||||
}else if(required){
|
}else if(required){
|
||||||
check.checked=true;check.disabled=true;
|
const chosen=!!ajusteTudo || artesSelecionadas(aPagar)>0 || artesEscolhidasNaTela()>0;
|
||||||
mostraAvisoTratamento('Sua arte tem nota '+worst+': para imprimir com qualidade, o tratamento pelo designer é obrigatório neste pedido.');
|
if(!chosen){
|
||||||
|
ajusteTudo=true;
|
||||||
|
for(const x of folhas) x.ajuste=true;
|
||||||
|
for(const a of artes) a.ajuste=true;
|
||||||
|
document.querySelectorAll('[data-ajuste],[data-ajustea]').forEach(el=>{el.checked=true;});
|
||||||
|
}
|
||||||
|
check.checked=ajusteTudo;check.disabled=true;
|
||||||
|
mostraAvisoTratamento('Sua arte tem nota '+worst+': para imprimir com qualidade, o Ajuste Fino é obrigatório neste pedido.');
|
||||||
}else{
|
}else{
|
||||||
check.disabled=false;mostraAvisoTratamento('');
|
check.checked=ajusteTudo;check.disabled=false;mostraAvisoTratamento('');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// O carrinho junta itens de produtos diferentes e cobra uma vez só.
|
// O carrinho junta itens de produtos diferentes e cobra uma vez só.
|
||||||
@@ -100,7 +187,8 @@ function pintaPedido(){
|
|||||||
$('bEsvaziar').hidden = pedido.length+(itemAtual?1:0) < 2;
|
$('bEsvaziar').hidden = pedido.length+(itemAtual?1:0) < 2;
|
||||||
const itens = aPagar.reduce((t,it)=>t+it.total,0);
|
const itens = aPagar.reduce((t,it)=>t+it.total,0);
|
||||||
const frete = entrega.tipo==='frete' && entrega.cotado ? entrega.valor : 0;
|
const frete = entrega.tipo==='frete' && entrega.cotado ? entrega.valor : 0;
|
||||||
const tratamento=$('fTratamento')?.checked&&TAXA_TRATAMENTO>0?TAXA_TRATAMENTO:0;
|
const artesAjuste = TAXA_TRATAMENTO>0 ? artesSelecionadas(aPagar) : 0;
|
||||||
|
const tratamento = artesAjuste ? Math.round(precoAjuste(artesAjuste)*artesAjuste*100)/100 : 0;
|
||||||
const soma = itens + frete + tratamento;
|
const soma = itens + frete + tratamento;
|
||||||
const n = aPagar.length, noCarrinho = pedido.length + (itemAtual?1:0);
|
const n = aPagar.length, noCarrinho = pedido.length + (itemAtual?1:0);
|
||||||
$('resLin').innerHTML =
|
$('resLin').innerHTML =
|
||||||
@@ -110,17 +198,23 @@ function pintaPedido(){
|
|||||||
'</span><b>'+
|
'</span><b>'+
|
||||||
(entrega.tipo==='retira' ? '<span style="color:var(--verde-ml)">Grátis</span>'
|
(entrega.tipo==='retira' ? '<span style="color:var(--verde-ml)">Grátis</span>'
|
||||||
: entrega.cotado ? rs(frete) : 'a cotar')+'</b></div>'+
|
: entrega.cotado ? rs(frete) : 'a cotar')+'</b></div>'+
|
||||||
(tratamento?'<div class="l"><span>Tratamento da arte · +24 h</span><b>'+rs(tratamento)+'</b></div>':'')+
|
(tratamento?'<div class="l"><span>Ajuste Fino · '+artesAjuste+(artesAjuste===1?' arte':' artes')+
|
||||||
|
' · +24 h</span><b>'+rs(tratamento)+'</b></div>':'')+
|
||||||
'<div class="l"><span>Revisão e reencaixe</span>'+
|
'<div class="l"><span>Revisão e reencaixe</span>'+
|
||||||
'<b><span style="color:var(--verde-ml)">Grátis</span></b></div>';
|
'<b><span style="color:var(--verde-ml)">Grátis</span></b></div>';
|
||||||
$('carrTot').textContent=rs(soma);
|
$('carrTot').textContent=rs(soma);
|
||||||
$('bPagarTx').textContent = n>1
|
// A file still on its way (or failed) keeps the payment closed (B2).
|
||||||
? 'Pagar os '+n+' itens de uma vez'
|
const faltaEnvio=window.dtfFaltaEnvio?window.dtfFaltaEnvio():null;
|
||||||
: 'Ir para o pagamento';
|
const falta=faltaEnvio?.falta||0;
|
||||||
|
$('bPagarTx').textContent = falta
|
||||||
|
? 'Falta enviar '+falta+(falta===1?' arquivo':' arquivos')
|
||||||
|
: 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.
|
// The proof is only for orders above 10 m (Dropstar, 2026-10-28): below it the box is gone.
|
||||||
const prova=$('fProva');
|
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; }
|
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();
|
$('bPagar').disabled = !cartPodeEnviar() || !entrega.cotado || !clienteOk() || !enderecoOk() || falta>0;
|
||||||
if(pedido.length || itemAtual) $('carr').classList.add('on');
|
if(pedido.length || itemAtual) $('carr').classList.add('on');
|
||||||
if($('cartN')){ $('cartN').textContent=noCarrinho>99?'99+':noCarrinho; $('cartN').hidden=!noCarrinho;
|
if($('cartN')){ $('cartN').textContent=noCarrinho>99?'99+':noCarrinho; $('cartN').hidden=!noCarrinho;
|
||||||
$('cartLink').setAttribute('aria-label','Carrinho, '+noCarrinho+(noCarrinho===1?' item':' itens')); }
|
$('cartLink').setAttribute('aria-label','Carrinho, '+noCarrinho+(noCarrinho===1?' item':' itens')); }
|
||||||
@@ -151,6 +245,7 @@ function carrinho(){
|
|||||||
'<div class="l" style="color:var(--laranja2)"><span>Revisão e reencaixe</span><b>grátis</b></div>';
|
'<div class="l" style="color:var(--laranja2)"><span>Revisão e reencaixe</span><b>grátis</b></div>';
|
||||||
$('carrLin').innerHTML=l;
|
$('carrLin').innerHTML=l;
|
||||||
$('atual').style.display='';
|
$('atual').style.display='';
|
||||||
|
const escolhidas=lista=>lista.map((x,i)=>ajusteTudo||x.ajuste?i:null).filter(i=>i!==null);
|
||||||
const sources=(ehFolha()?folhas:artes).map(x=>ehFolha()
|
const sources=(ehFolha()?folhas:artes).map(x=>ehFolha()
|
||||||
? {kind:'sheet',width_cm:x.med?.larg||larguraFilme(),length_cm:+(x.m*100).toFixed(4),
|
? {kind:'sheet',width_cm:x.med?.larg||larguraFilme(),length_cm:+(x.m*100).toFixed(4),
|
||||||
copies:x.rep||1,rotation_degrees:0,mirrored:false,
|
copies:x.rep||1,rotation_degrees:0,mirrored:false,
|
||||||
@@ -175,6 +270,7 @@ function carrinho(){
|
|||||||
localFiles:f.artes.map(x=>x.f), fotos:f.artes.map(x=>x.fotoSrc||null),
|
localFiles:f.artes.map(x=>x.f), fotos:f.artes.map(x=>x.fotoSrc||null),
|
||||||
metros:+(f.layout.height_cm/100).toFixed(4),
|
metros:+(f.layout.height_cm/100).toFixed(4),
|
||||||
production:{version:3,film_width_cm:larguraFilme(),sources:f.artes.map(fonteDaArte),...f.layout},
|
production:{version:3,film_width_cm:larguraFilme(),sources:f.artes.map(fonteDaArte),...f.layout},
|
||||||
|
ajusteSources:escolhidas(f.artes),
|
||||||
residueAccepted:residuosDasArtes(f.artes), ...tracoDoItem(f.artes,f.layout)}));
|
residueAccepted:residuosDasArtes(f.artes), ...tracoDoItem(f.artes,f.layout)}));
|
||||||
layout=null;
|
layout=null;
|
||||||
}else{
|
}else{
|
||||||
@@ -189,6 +285,7 @@ function carrinho(){
|
|||||||
arquivos:(ehFolha()?folhas:artes).length,
|
arquivos:(ehFolha()?folhas:artes).length,
|
||||||
production:layout?{version:3,film_width_cm:larguraFilme(),sources,...layout}:null,
|
production:layout?{version:3,film_width_cm:larguraFilme(),sources,...layout}:null,
|
||||||
partes,
|
partes,
|
||||||
|
...(partes?{}:{ajusteSources:escolhidas(ehFolha()?folhas:artes)}),
|
||||||
qualityStatus:$('ciente').classList.contains('recusa')?'rejected':
|
qualityStatus:$('ciente').classList.contains('recusa')?'rejected':
|
||||||
$('ciente').classList.contains('on')?'warning':nota===0?'unverified':'ok',
|
$('ciente').classList.contains('on')?'warning':nota===0?'unverified':'ok',
|
||||||
qualityAcknowledged:false,
|
qualityAcknowledged:false,
|
||||||
@@ -210,7 +307,14 @@ function avisaDesfazer(texto,acao){
|
|||||||
function fechaDesfazer(){ clearTimeout(desfazerTimer); desfazerAcao=null; $('desfazer').hidden=true; }
|
function fechaDesfazer(){ clearTimeout(desfazerTimer); desfazerAcao=null; $('desfazer').hidden=true; }
|
||||||
addEventListener('dtf-page-changed',fechaDesfazer);
|
addEventListener('dtf-page-changed',fechaDesfazer);
|
||||||
$('desfazerBtn').addEventListener('click',()=>{ const acao=desfazerAcao; fechaDesfazer(); if(acao) acao(); });
|
$('desfazerBtn').addEventListener('click',()=>{ const acao=desfazerAcao; fechaDesfazer(); if(acao) acao(); });
|
||||||
$('fTratamento')?.addEventListener('change',()=>pintaPedido());
|
$('fTratamento')?.addEventListener('change',()=>{
|
||||||
|
if($('fTratamento').checked) ajusteTudo=true;
|
||||||
|
else limpaAjuste();
|
||||||
|
// The art cards show the same choice, one checkbox under each warning; do
|
||||||
|
// not repaint them, or the item being built is discarded.
|
||||||
|
pintaAjusteCheckboxes();
|
||||||
|
pintaPedido();
|
||||||
|
});
|
||||||
$('bEsvaziar').addEventListener('click',()=>{
|
$('bEsvaziar').addEventListener('click',()=>{
|
||||||
const antes=pedido.slice();
|
const antes=pedido.slice();
|
||||||
pedido=[]; invalidaItemAtual(); pintaPedido();
|
pedido=[]; invalidaItemAtual(); pintaPedido();
|
||||||
|
|||||||
@@ -51,12 +51,14 @@ const MODOS={
|
|||||||
zt:'Arraste sua folha de UV aqui', zs:'PNG ou PDF com fundo transparente · 27 cm de largura'},
|
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,
|
uv: {tit:'Artes avulsas · UV', lg:'Adesivo UV · 27 cm', larg:27, multi:true,
|
||||||
zt:'Arraste suas artes de UV',
|
zt:'Arraste suas artes de UV',
|
||||||
zs:'PNG com fundo transparente · informe a largura de cada arte'}
|
zs:'PNG com fundo transparente · informe a largura de cada arte'},
|
||||||
|
premium:{tit:'DTF Premium', lg:'DTF têxtil premium · 57 cm', larg:57, multi:true, folha:true,
|
||||||
|
zt:'Arraste sua folha montada aqui', zs:'PNG ou PDF com fundo transparente · 57 cm de largura'}
|
||||||
};
|
};
|
||||||
// Preço único por produto (Dropstar, 23/10/2026). A nota da arte continua na
|
// 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.
|
// 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).
|
// 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};
|
const PRECO={file:19.90, avulsa:21.90, uvfile:79.90, uv:89.90, premium:39.90};
|
||||||
// Faixas por metragem (front 8.2): o preço do metro depende do total do
|
// Faixas por metragem (front 8.2): o preço do metro depende do total do
|
||||||
// produto no pedido, não de cada item. Vem do servidor (/api/session), que
|
// produto no pedido, não de cada item. Vem do servidor (/api/session), que
|
||||||
// cobra o mesmo (app/catalog.py band_price).
|
// cobra o mesmo (app/catalog.py band_price).
|
||||||
@@ -64,8 +66,11 @@ const FAIXAS={};
|
|||||||
// Folha que alguém abre na mão (CDR, AI, PSD, TIFF): R$ a mais por metro.
|
// 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.
|
// Vem do servidor (/api/session), que cobra o mesmo; zero não soma nada.
|
||||||
let TAXA_MANUAL=0;
|
let TAXA_MANUAL=0;
|
||||||
// Fixed price of the designer treatment, set by the server (TREATMENT_CENTS).
|
// Ajuste Fino, per art, set by the server (TREATMENT_CENTS).
|
||||||
let TAXA_TRATAMENTO=0;
|
let TAXA_TRATAMENTO=0;
|
||||||
|
// Ajuste Fino for every art of the cart: the general switch, or true when
|
||||||
|
// the grade rule requires it. Individual choices live on the art objects.
|
||||||
|
let ajusteTudo=false;
|
||||||
const folhaManual=()=>ehFolha() && folhas.some(x=>!x.med);
|
const folhaManual=()=>ehFolha() && folhas.some(x=>!x.med);
|
||||||
const ehFolha=m=>!!MODOS[m||modo].folha;
|
const ehFolha=m=>!!MODOS[m||modo].folha;
|
||||||
const precoMetro=m=>PRECO[m||modo];
|
const precoMetro=m=>PRECO[m||modo];
|
||||||
@@ -77,6 +82,16 @@ function precoNaMetragem(m, metros){
|
|||||||
for(const band of bands) if(metros>=Number(band.from_metres) && (!alta || Number(band.from_metres)>=Number(alta.from_metres))) alta=band;
|
for(const band of bands) if(metros>=Number(band.from_metres) && (!alta || Number(band.from_metres)>=Number(alta.from_metres))) alta=band;
|
||||||
return alta ? alta.unit_cents/100 : PRECO[m];
|
return alta ? alta.unit_cents/100 : PRECO[m];
|
||||||
}
|
}
|
||||||
|
// Ajuste Fino: the price of one art when the order has n arts. Below the first
|
||||||
|
// band it is the base, then the highest band reached, as app/catalog.py does.
|
||||||
|
function precoAjuste(n, base = TAXA_TRATAMENTO, bands = FAIXAS.tratamento) {
|
||||||
|
let price = base, best = null;
|
||||||
|
for (const band of bands || []) {
|
||||||
|
const start = Number(band.from_metres);
|
||||||
|
if (n >= start && (best === null || start >= best)) { best = start; price = band.unit_cents / 100; }
|
||||||
|
}
|
||||||
|
return price;
|
||||||
|
}
|
||||||
// A próxima faixa à frente, para o aviso de quanto falta.
|
// A próxima faixa à frente, para o aviso de quanto falta.
|
||||||
function proximaFaixa(m, metros){
|
function proximaFaixa(m, metros){
|
||||||
const bands=FAIXAS[m]||[];
|
const bands=FAIXAS[m]||[];
|
||||||
|
|||||||
@@ -46,7 +46,8 @@ function pintaModo(){
|
|||||||
// dá para voltar atrás sem recomeçar o pedido.
|
// dá para voltar atrás sem recomeçar o pedido.
|
||||||
function pintaTipoEnvio(){
|
function pintaTipoEnvio(){
|
||||||
const el=$('tipoEnvio'); if(!el) return;
|
const el=$('tipoEnvio'); if(!el) return;
|
||||||
el.hidden=!modo;
|
// A product without its loose-art counterpart (Premium) has nothing to choose.
|
||||||
|
el.hidden=!modo || (ehFolha() && !PAR[modo]);
|
||||||
if(el.hidden) return;
|
if(el.hidden) return;
|
||||||
const folha = ehFolha() ? modo : PAR[modo];
|
const folha = ehFolha() ? modo : PAR[modo];
|
||||||
const avulsa = ehFolha() ? PAR[modo] : modo;
|
const avulsa = ehFolha() ? PAR[modo] : modo;
|
||||||
@@ -80,7 +81,7 @@ function recusaFolha(x, md){
|
|||||||
'<button type="button" id="usarAvulsa">Enviar como '+MODOS[destino].tit.toLowerCase()+'</button>');
|
'<button type="button" id="usarAvulsa">Enviar como '+MODOS[destino].tit.toLowerCase()+'</button>');
|
||||||
const botao=$('usarAvulsa');
|
const botao=$('usarAvulsa');
|
||||||
if(botao) botao.addEventListener('click',()=>{
|
if(botao) botao.addEventListener('click',()=>{
|
||||||
avisoTipo(''); trocaTipo(PAR[modo]); sel([arquivo]);
|
avisoTipo(''); trocaTipo(destino); sel([arquivo]);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
document.querySelectorAll('#tipoEnvio .cam').forEach(b=>b.addEventListener('click',()=>{
|
document.querySelectorAll('#tipoEnvio .cam').forEach(b=>b.addEventListener('click',()=>{
|
||||||
|
|||||||
@@ -6,7 +6,8 @@
|
|||||||
addresses. Loaded in <head> so the right page is the first one painted;
|
addresses. Loaded in <head> so the right page is the first one painted;
|
||||||
site-steps.js does the navigation. */
|
site-steps.js does the navigation. */
|
||||||
const PAGINAS={file:'/arquivo-por-metro', avulsa:'/artes-avulsas',
|
const PAGINAS={file:'/arquivo-por-metro', avulsa:'/artes-avulsas',
|
||||||
uvfile:'/uv-arquivo-por-metro', uv:'/uv-artes-avulsas'};
|
uvfile:'/uv-arquivo-por-metro', uv:'/uv-artes-avulsas',
|
||||||
|
premium:'/premium'};
|
||||||
const CARRINHO='/carrinho', PAGAMENTO='/pagamento', PAGAMENTO_PIX='/pagamento/pix';
|
const CARRINHO='/carrinho', PAGAMENTO='/pagamento', PAGAMENTO_PIX='/pagamento/pix';
|
||||||
function paginaDe(caminho){
|
function paginaDe(caminho){
|
||||||
caminho=caminho.replace(/\/+$/,'')||'/';
|
caminho=caminho.replace(/\/+$/,'')||'/';
|
||||||
|
|||||||
@@ -483,6 +483,27 @@ function avisosDaFolha(a,nome,i,aceito,aceitavel=false){
|
|||||||
'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á.')+
|
'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á.')+
|
||||||
(aceitavel?' Se '+(varios?'os pontos são':'o ponto é')+' da própria arte, marque abaixo.</p>'+aceite:'</p>');
|
(aceitavel?' Se '+(varios?'os pontos são':'o ponto é')+' da própria arte, marque abaixo.</p>'+aceite:'</p>');
|
||||||
}
|
}
|
||||||
|
// Ajuste Fino (front 1a): under a Prumo warning, the customer may hand this
|
||||||
|
// art to the designer. One choice per art; the cart has the general switch.
|
||||||
|
function temAvisoFolha(x){
|
||||||
|
const a=x.an;
|
||||||
|
if(!a || a.grande) return false;
|
||||||
|
return !!(a.fundoChapado || a.residuos || a.dpi<DPI_AVISA ||
|
||||||
|
(typeof tracoDoArquivo==='function' && typeof mista==='function' && mista(tracoDoArquivo(x))));
|
||||||
|
}
|
||||||
|
function temAvisoArte(a){
|
||||||
|
const an=analiseDaArte(a);
|
||||||
|
if(!an || an.grande) return false;
|
||||||
|
return !!(an.fundoChapado || an.residuos || an.dpi<DPI_AVISA ||
|
||||||
|
(typeof mista==='function' && mista(tracoDaArte(a))));
|
||||||
|
}
|
||||||
|
function ajusteLinha(i,attr){
|
||||||
|
if(!(TAXA_TRATAMENTO>0)) return '';
|
||||||
|
const marcado=ajusteTudo || (attr==='data-ajuste' ? folhas[i].ajuste : artes[i].ajuste);
|
||||||
|
return '<label class="aceiteRes ajusteArte"><input type="checkbox" '+attr+'="'+i+'"'+
|
||||||
|
(marcado?' checked':'')+'>'+
|
||||||
|
'<span>Quer que um designer resolva? <b>Ajuste Fino</b> — '+rs(TAXA_TRATAMENTO)+'</span></label>';
|
||||||
|
}
|
||||||
function detalhesDaFolha(a,i,aberto){
|
function detalhesDaFolha(a,i,aberto){
|
||||||
const linhas = a.grande
|
const linhas = a.grande
|
||||||
? ['Resolução '+a.dpi+' DPI, lida do arquivo',
|
? ['Resolução '+a.dpi+' DPI, lida do arquivo',
|
||||||
@@ -514,6 +535,7 @@ function pintaFolha(){
|
|||||||
medida='<div class="repMed"><b>'+n1(x.med.larg)+' × '+n1(x.med.alt)+' cm</b>'+
|
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>'+
|
'<span>'+escapeHTML(extDe(x.f.name))+' · '+fmt(x.f.size)+'</span></div>'+
|
||||||
(a? '<ul class="chips">'+chipsDaFolha(a,residuoAceito(x))+'</ul>'+avisosDaFolha(a,x.f.name,i,residuoAceito(x),true)+
|
(a? '<ul class="chips">'+chipsDaFolha(a,residuoAceito(x))+'</ul>'+avisosDaFolha(a,x.f.name,i,residuoAceito(x),true)+
|
||||||
|
(temAvisoFolha(x)?ajusteLinha(i,'data-ajuste'):'')+
|
||||||
detalhesDaFolha(a,i,x.detAberto) : '')+
|
detalhesDaFolha(a,i,x.detAberto) : '')+
|
||||||
// Over 150 MB the browser cannot check a PDF: said before payment, as
|
// Over 150 MB the browser cannot check a PDF: said before payment, as
|
||||||
// for a file opened by hand (Dropstar, 2026-10-23).
|
// for a file opened by hand (Dropstar, 2026-10-23).
|
||||||
@@ -524,7 +546,7 @@ function pintaFolha(){
|
|||||||
'Exportando em <b>PNG</b>, ou num PDF menor, a conferência sai aqui, antes de pagar.</p>' : '')+
|
'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> '+
|
(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. '+
|
'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. '+
|
'Ele abre certo só em quem o gerou — aqui vai precisar do Ajuste Fino. '+
|
||||||
'Manda em <b>PNG ou TIFF</b>, ou divide em partes de até 5 m, que sai na hora.</p>':'')+
|
'Manda em <b>PNG ou TIFF</b>, ou divide em partes de até 5 m, que sai na hora.</p>':'')+
|
||||||
(larga? '<p class="avisoF"><b>Esta folha não roda neste filme.</b> Ela tem '+n1(x.med.larg)+
|
(larga? '<p class="avisoF"><b>Esta folha não roda neste filme.</b> Ela tem '+n1(x.med.larg)+
|
||||||
' cm de largura e o filme aqui tem '+n1(L)+' cm. Não dá para reduzir: '+
|
' cm de largura e o filme aqui tem '+n1(L)+' cm. Não dá para reduzir: '+
|
||||||
@@ -588,6 +610,11 @@ function pintaFolha(){
|
|||||||
$('lista').querySelectorAll('[data-residuo]').forEach(el=>el.addEventListener('change',()=>{
|
$('lista').querySelectorAll('[data-residuo]').forEach(el=>el.addEventListener('change',()=>{
|
||||||
folhas[+el.dataset.residuo].residuoAceito=el.checked; pintaFolha();
|
folhas[+el.dataset.residuo].residuoAceito=el.checked; pintaFolha();
|
||||||
}));
|
}));
|
||||||
|
$('lista').querySelectorAll('[data-ajuste]').forEach(el=>el.addEventListener('change',()=>{
|
||||||
|
if(ajusteTudo) materializaAjuste();
|
||||||
|
folhas[+el.dataset.ajuste].ajuste=el.checked;
|
||||||
|
pintaFolha(); pintaPedido();
|
||||||
|
}));
|
||||||
$('lista').querySelectorAll('[data-det]').forEach(d=>d.addEventListener('toggle',()=>{
|
$('lista').querySelectorAll('[data-det]').forEach(d=>d.addEventListener('toggle',()=>{
|
||||||
folhas[+d.dataset.det].detAberto=d.open;
|
folhas[+d.dataset.det].detAberto=d.open;
|
||||||
}));
|
}));
|
||||||
@@ -688,7 +715,8 @@ function pintaArtes(){
|
|||||||
'<button data-rm="'+i+'" aria-label="Remover '+escapeHTML(a.f.name)+'">'+icone('fechar')+'</button></div>'+
|
'<button data-rm="'+i+'" aria-label="Remover '+escapeHTML(a.f.name)+'">'+icone('fechar')+'</button></div>'+
|
||||||
'<div class="repMed">'+medida+'<span>'+(a.px>0? a.px+' × '+a.py+' px · ' : '')+
|
'<div class="repMed">'+medida+'<span>'+(a.px>0? a.px+' × '+a.py+' px · ' : '')+
|
||||||
escapeHTML(extDe(a.f.name))+' · '+fmt(a.f.size)+'</span></div>'+
|
escapeHTML(extDe(a.f.name))+' · '+fmt(a.f.size)+'</span></div>'+
|
||||||
barra+chips+aviso+dica+
|
barra+chips+aviso+
|
||||||
|
(a.cm>0 && (a.src||a.semPrevia) && temAvisoArte(a) ? ajusteLinha(i,'data-ajustea') : '')+dica+
|
||||||
'</div></div>'+
|
'</div></div>'+
|
||||||
'<div class="cps">'+
|
'<div class="cps">'+
|
||||||
'<div class="campo"><label for="cm'+i+'">Largura</label>'+
|
'<div class="campo"><label for="cm'+i+'">Largura</label>'+
|
||||||
@@ -715,6 +743,11 @@ function pintaArtes(){
|
|||||||
$('lista').querySelectorAll('[data-rm]').forEach(b=>b.addEventListener('click',()=>{artes.splice(+b.dataset.rm,1);pintaArtes();}));
|
$('lista').querySelectorAll('[data-rm]').forEach(b=>b.addEventListener('click',()=>{artes.splice(+b.dataset.rm,1);pintaArtes();}));
|
||||||
$('lista').querySelectorAll('[data-residuoa]').forEach(el=>el.addEventListener('change',()=>{
|
$('lista').querySelectorAll('[data-residuoa]').forEach(el=>el.addEventListener('change',()=>{
|
||||||
artes[+el.dataset.residuoa].residuoAceito=el.checked; pintaArtes();}));
|
artes[+el.dataset.residuoa].residuoAceito=el.checked; pintaArtes();}));
|
||||||
|
$('lista').querySelectorAll('[data-ajustea]').forEach(el=>el.addEventListener('change',()=>{
|
||||||
|
if(ajusteTudo) materializaAjuste();
|
||||||
|
artes[+el.dataset.ajustea].ajuste=el.checked;
|
||||||
|
pintaArtes(); pintaPedido();
|
||||||
|
}));
|
||||||
$('lista').querySelectorAll('[data-cm]').forEach(i=>i.addEventListener('change',()=>{artes[+i.dataset.cm].cm=+i.value||0;pintaArtes();}));
|
$('lista').querySelectorAll('[data-cm]').forEach(i=>i.addEventListener('change',()=>{artes[+i.dataset.cm].cm=+i.value||0;pintaArtes();}));
|
||||||
$('lista').querySelectorAll('[data-q]').forEach(i=>i.addEventListener('change',()=>{artes[+i.dataset.q].q=Math.max(1,Math.min(200,Math.floor(+i.value||1)));pintaArtes();}));
|
$('lista').querySelectorAll('[data-q]').forEach(i=>i.addEventListener('change',()=>{artes[+i.dataset.q].q=Math.max(1,Math.min(200,Math.floor(+i.value||1)));pintaArtes();}));
|
||||||
$('lista').querySelectorAll('[data-cm], [data-q]').forEach(i=>i.addEventListener('input',()=>{
|
$('lista').querySelectorAll('[data-cm], [data-q]').forEach(i=>i.addEventListener('input',()=>{
|
||||||
|
|||||||
@@ -66,9 +66,44 @@ const enviadoEm=new WeakMap();
|
|||||||
// A few repaints a second, page in view or not: progress comes in far more often.
|
// A few repaints a second, page in view or not: progress comes in far more often.
|
||||||
let envioQuadro=0;
|
let envioQuadro=0;
|
||||||
function agendaEnvios(){ if(!envioQuadro) envioQuadro=setTimeout(()=>{ envioQuadro=0; pintaEnvios(); },120); }
|
function agendaEnvios(){ if(!envioQuadro) envioQuadro=setTimeout(()=>{ envioQuadro=0; pintaEnvios(); },120); }
|
||||||
|
// A failed upload must show on the file's own card too (B2, Marcus 11/11):
|
||||||
|
// the same red block and "Tentar de novo" as the row under the uploader, on
|
||||||
|
// the sheet/art card itself, so the list does not look complete.
|
||||||
|
function pintaErrosDosArquivos(){
|
||||||
|
const lista=$('lista'); if(!lista || !window.dtfEnvio) return;
|
||||||
|
const decorate=(selector,items,kind)=>{
|
||||||
|
items.forEach((item,index)=>{
|
||||||
|
const card=lista.querySelector(selector.replace('{i}',index));
|
||||||
|
if(!card) return;
|
||||||
|
const estado=dtfEnvio.estado(item.f);
|
||||||
|
const atual=card.querySelector('[data-envio-falha]');
|
||||||
|
if(!estado || estado.fase!=='falhou'){ if(atual) atual.remove(); return; }
|
||||||
|
if(atual){
|
||||||
|
// Keep the block while the file is failed: a repaint for another
|
||||||
|
// file's progress must not take the button from under the pointer.
|
||||||
|
const texto=atual.querySelector('span');
|
||||||
|
if(texto) texto.textContent='Não foi possível enviar '+item.f.name+': '+
|
||||||
|
(estado.erro||'erro no envio').replace(/\.$/,'')+'.';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const box=document.createElement('div');
|
||||||
|
box.className='envio erro';box.dataset.envioFalha='1';
|
||||||
|
const texto=document.createElement('span');
|
||||||
|
texto.textContent='Não foi possível enviar '+item.f.name+': '+
|
||||||
|
(estado.erro||'erro no envio').replace(/\.$/,'')+'.';
|
||||||
|
const button=document.createElement('button');
|
||||||
|
button.type='button';button.textContent='Tentar de novo';
|
||||||
|
button.dataset.envioCard=kind;button.dataset.envioIndex=String(index);
|
||||||
|
box.append(texto,button);card.append(box);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
decorate('[data-folha="{i}"]',folhas,'folha');
|
||||||
|
decorate('[data-arte="{i}"]',artes,'arte');
|
||||||
|
}
|
||||||
function pintaEnvios(){
|
function pintaEnvios(){
|
||||||
const el=$('envios'); if(!el || !window.dtfEnvio) return;
|
const el=$('envios'); if(!el || !window.dtfEnvio) return;
|
||||||
dtfEnvio.manter([...artes,...folhas].map(x=>x.f));
|
dtfEnvio.manter([...artes,...folhas].map(x=>x.f));
|
||||||
|
pintaErrosDosArquivos();
|
||||||
// Off the product page there is no uploader to paint under.
|
// Off the product page there is no uploader to paint under.
|
||||||
if(!MODOS[modo]){ el.innerHTML=''; return; }
|
if(!MODOS[modo]){ el.innerHTML=''; return; }
|
||||||
const agora=Date.now();
|
const agora=Date.now();
|
||||||
@@ -92,6 +127,11 @@ $('envios').addEventListener('click',e=>{
|
|||||||
const b=e.target.closest('[data-envio]'); if(!b || !MODOS[modo]) return;
|
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);
|
const x=(ehFolha()?folhas:artes)[+b.dataset.envio]; if(x) dtfEnvio.deNovo(x.f);
|
||||||
});
|
});
|
||||||
|
$('lista').addEventListener('click',e=>{
|
||||||
|
const b=e.target.closest('[data-envio-card]'); if(!b || !window.dtfEnvio) return;
|
||||||
|
const x=(b.dataset.envioCard==='folha'?folhas:artes)[+b.dataset.envioIndex];
|
||||||
|
if(x) dtfEnvio.deNovo(x.f);
|
||||||
|
});
|
||||||
// A sheet with residue gets its preview circled where the dots are.
|
// A sheet with residue gets its preview circled where the dots are.
|
||||||
async function marcaResiduos(x){
|
async function marcaResiduos(x){
|
||||||
if(!(x.an && x.an.residuos && !x.an.fundoChapado && x.previewSrc && x.an.pontos?.length)) return;
|
if(!(x.an && x.an.residuos && !x.an.fundoChapado && x.previewSrc && x.an.pontos?.length)) return;
|
||||||
|
|||||||
@@ -4,9 +4,36 @@ window.dtfUpload = async (file, {api, prefix='/uploads', startPath=prefix, progr
|
|||||||
const samples=new Blob([file.slice(0,65536),file.slice(Math.max(0,file.size-65536))]);
|
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 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]);
|
const key='dtf-upload:'+JSON.stringify([scope,file.name,file.size,file.lastModified,hash]);
|
||||||
|
// A busy server asks for a wait: retry this file alone, quietly, before the
|
||||||
|
// customer sees the failure (Marcus, 2026-11-11). Only a 429 that carries
|
||||||
|
// Retry-After; the quota refusal has none and is shown at once.
|
||||||
|
const retryWait=error=>{
|
||||||
|
const seconds=Number(error?.retryAfter);
|
||||||
|
return error?.status===429&&Number.isFinite(seconds)?Math.min(60,Math.max(1,Math.ceil(seconds))):null;
|
||||||
|
};
|
||||||
|
const withRetry=async call=>{
|
||||||
|
for(let attempt=0;;attempt++){
|
||||||
|
try{return await call();}
|
||||||
|
catch(error){
|
||||||
|
const wait=retryWait(error);
|
||||||
|
if(wait===null||attempt>=3)throw error;
|
||||||
|
await new Promise(resolve=>setTimeout(resolve,wait*1000));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
let id=resume?localStorage.getItem(key):null,state;
|
let id=resume?localStorage.getItem(key):null,state;
|
||||||
if(id){try{state=await api(prefix+'/'+id);}catch(error){if(![404,410].includes(error.status))throw error;id=null;}}
|
if(id){
|
||||||
if(!id){state=await api(startPath,{name:file.name,size:file.size});id=state.id;if(resume)localStorage.setItem(key,id);}
|
try{state=await api(prefix+'/'+id);}
|
||||||
|
catch(error){
|
||||||
|
// The id was started under another session (a sign-in changes the scope):
|
||||||
|
// the new session does not own it, so this file starts again as a new
|
||||||
|
// upload. A 403/404/410 must never keep the retry on the old id.
|
||||||
|
if(![403,404,410].includes(error.status))throw error;
|
||||||
|
id=null;
|
||||||
|
if(resume)localStorage.removeItem(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if(!id){state=await withRetry(()=>api(startPath,{name:file.name,size:file.size}));id=state.id;if(resume)localStorage.setItem(key,id);}
|
||||||
async function waitForScan(){
|
async function waitForScan(){
|
||||||
onBytes(file.size);
|
onBytes(file.size);
|
||||||
// The antivirus streams the whole file: about a second per 2 MB, and at
|
// The antivirus streams the whole file: about a second per 2 MB, and at
|
||||||
@@ -42,7 +69,7 @@ window.dtfUpload = async (file, {api, prefix='/uploads', startPath=prefix, progr
|
|||||||
if(done.has(part))continue;
|
if(done.has(part))continue;
|
||||||
if(signal?.aborted)throw cancelled();
|
if(signal?.aborted)throw cancelled();
|
||||||
progress('Enviando '+file.name+' · parte '+part+'/'+Math.ceil(file.size/size));
|
progress('Enviando '+file.name+' · parte '+part+'/'+Math.ceil(file.size/size));
|
||||||
const signed=await api(prefix+'/'+id+'/parts/'+part,{});
|
const signed=await withRetry(()=>api(prefix+'/'+id+'/parts/'+part,{}));
|
||||||
await put(signed.url,file.slice(offset,offset+size));
|
await put(signed.url,file.slice(offset,offset+size));
|
||||||
done.add(part);sent+=length(part);
|
done.add(part);sent+=length(part);
|
||||||
onBytes(sent);
|
onBytes(sent);
|
||||||
|
|||||||
21
web/vendor/LICENSE-sentry.txt
vendored
Normal file
21
web/vendor/LICENSE-sentry.txt
vendored
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2019 Functional Software, Inc. dba Sentry
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||||
|
this software and associated documentation files (the "Software"), to deal in
|
||||||
|
the Software without restriction, including without limitation the rights to
|
||||||
|
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||||
|
of the Software, and to permit persons to whom the Software is furnished to do
|
||||||
|
so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
7
web/vendor/README.md
vendored
7
web/vendor/README.md
vendored
@@ -31,3 +31,10 @@ curl -s "https://api.cdnjs.com/libraries/pdf.js/<version>?fields=sri"
|
|||||||
documented workaround is `isEvalSupported: false`; `web/index.html` already passes
|
documented workaround is `isEvalSupported: false`; `web/index.html` already passes
|
||||||
that, so the known path is closed. Upgrading is worthwhile but is an API change,
|
that, so the known path is closed. Upgrading is worthwhile but is an API change,
|
||||||
not a file swap, and belongs with its own browser testing — see `ROADMAP.md` 2.7.
|
not a file swap, and belongs with its own browser testing — see `ROADMAP.md` 2.7.
|
||||||
|
|
||||||
|
## Sentry browser SDK 11.12.0
|
||||||
|
|
||||||
|
One line per vendored file: source, version, date and SHA-256.
|
||||||
|
|
||||||
|
- `sentry.min.js` — https://browser.sentry-cdn.com/11.12.0/bundle.min.js — @sentry/browser 11.12.0 — 2026-11-11 — sha256 `388cdc69ba60b5a883097874ee8e5e010543990d60b5846d9dd1a4e736a49902`
|
||||||
|
- `LICENSE-sentry.txt` — https://registry.npmjs.org/@sentry/browser/-/browser-11.12.0.tgz (`package/LICENSE`) — @sentry/browser 11.12.0 — 2026-11-11 — sha256 `f3df0b92efcd9d8cc0de5a36c151569a12a647d65b851abbb696ef7b13dee10b`
|
||||||
|
|||||||
3
web/vendor/sentry.min.js
vendored
Normal file
3
web/vendor/sentry.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user