Merge main into label
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -26,6 +26,7 @@ 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_label \
|
||||||
tests.test_secrets -v
|
tests.test_secrets -v
|
||||||
|
|||||||
@@ -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: ...
|
||||||
|
|||||||
@@ -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,
|
||||||
|
|||||||
@@ -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."""
|
||||||
|
|||||||
@@ -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'],
|
||||||
|
|||||||
@@ -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,29 @@ 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 (front 7a.3): Interno (the fixed
|
||||||
typed customer, pickup, the Site's table price, and held out of Tiny until
|
internal customer, origin dropflow, never Tiny) or Venda (a Tiny customer,
|
||||||
Dropstar decides how it is invoiced there."""
|
origin atendimento, invoiced and sent to Tiny). Pickup in both, at the
|
||||||
origin = 'dropflow' if request.state.operator['role'] == 'expedicao' else 'atendimento'
|
Site's table price; the order records whether it travels with a clothing
|
||||||
draft = QuoteRequest(request_key=body.request_key, customer=body.customer, items=body.items,
|
order."""
|
||||||
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=Freight(service='pickup')).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 +142,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
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
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.
|
||||||
@@ -19,8 +19,8 @@ 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 +28,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',
|
||||||
|
'premium': 'Têxtil Premium · 8 passadas',
|
||||||
'tratamento': 'Tratamento pelo designer',
|
'tratamento': 'Tratamento pelo designer',
|
||||||
}
|
}
|
||||||
UNITS = {'file': 'metro', 'avulsa': 'metro', 'uvfile': 'metro', 'uv': 'metro',
|
UNITS = {'file': 'metro', 'avulsa': 'metro', 'uvfile': 'metro', 'uv': 'metro',
|
||||||
'tratamento': 'pedido'}
|
'premium': 'metro', 'tratamento': 'pedido'}
|
||||||
|
|
||||||
|
|
||||||
def fallback_cents(product: str) -> int:
|
def fallback_cents(product: str) -> int:
|
||||||
|
|||||||
@@ -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:
|
||||||
@@ -289,16 +289,26 @@ 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 (front 7a.3): Interno or Venda, loose artwork
|
||||||
and loose artwork only; the server prices and approves it as a quote."""
|
only and pickup; 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."""
|
||||||
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)
|
||||||
|
|
||||||
@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.')
|
||||||
|
if self.kind == 'interno' and self.with_order is not None:
|
||||||
|
raise ValueError('O pedido interno não tem envio.')
|
||||||
return self
|
return self
|
||||||
|
|
||||||
class Review(StrictModel):
|
class Review(StrictModel):
|
||||||
@@ -396,7 +406,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 +419,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 +538,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
|
||||||
|
|||||||
@@ -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)
|
||||||
|
|||||||
@@ -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'));
|
||||||
|
|
||||||
@@ -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
|
||||||
|
|||||||
@@ -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}
|
||||||
|
|||||||
64
app/tiny.py
64
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
|
||||||
|
|||||||
@@ -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>
|
||||||
|
|||||||
@@ -120,6 +120,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
|
||||||
|
|||||||
@@ -3,22 +3,35 @@
|
|||||||
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 secrets
|
import secrets
|
||||||
from datetime import datetime, timedelta, timezone
|
from datetime import datetime, timedelta, timezone
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
||||||
|
from PIL import Image, ImageDraw
|
||||||
|
|
||||||
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 run():
|
def run():
|
||||||
@@ -34,9 +47,30 @@ def run():
|
|||||||
prices, user = [], None
|
prices, user = [], 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} == \
|
||||||
|
{'file', 'avulsa', 'uvfile', 'uv', 'premium', 'tratamento'}
|
||||||
assert all(product['unit'] in ('metro', 'pedido') and product['title'] for product in products)
|
assert all(product['unit'] in ('metro', 'pedido') 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})
|
||||||
|
|
||||||
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')
|
||||||
item = {**item_spec('uv', '1', 0, uid), 'quality_status': 'warning', 'quality_acknowledged': True}
|
item = {**item_spec('uv', '1', 0, uid), 'quality_status': 'warning', 'quality_acknowledged': True}
|
||||||
@@ -123,13 +157,15 @@ 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, 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 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,37 @@ 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'}
|
||||||
|
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', 'label', '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 +118,95 @@ 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; '
|
print('PASS: Expedição makes Interno and Vendedor makes Venda; the internal customer, the Tiny '
|
||||||
'Gestão edits the table; invalid rows, profiles and modes are refused')
|
'contacts, the stamp brand and the table price in Números work; invalid profiles and modes 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 +215,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)',
|
||||||
c.execute('DELETE FROM dtf_local.uploads WHERE owner=%s', (identity,))
|
(internal_customer['mail'], venda_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',))
|
||||||
|
|||||||
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()
|
||||||
@@ -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
|
||||||
@@ -87,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()
|
||||||
|
|||||||
@@ -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):
|
||||||
|
|||||||
@@ -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']}
|
||||||
|
|
||||||
@@ -221,7 +222,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 +795,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'])
|
||||||
|
|||||||
@@ -97,7 +97,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];
|
||||||
|
|||||||
@@ -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}}
|
||||||
@@ -815,6 +816,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>
|
||||||
|
|
||||||
|
|||||||
@@ -1,20 +1,115 @@
|
|||||||
/* 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};
|
||||||
|
|
||||||
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 withOrder=montarDelivery()==='with_order';
|
||||||
|
$('montar-with-order').disabled=!withOrder;
|
||||||
|
if(!withOrder)$('montar-with-order').value='';
|
||||||
|
}
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
// 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 +154,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 +185,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);
|
||||||
@@ -198,15 +300,24 @@ 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;
|
||||||
|
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 ready=!!(MONTAR.lines.length&&MONTAR.layout&&!MONTAR.layoutPending&&
|
const ready=!!(MONTAR.lines.length&&MONTAR.layout&&!MONTAR.layoutPending&&
|
||||||
montarCustomerFilled()&&!MONTAR.creating);
|
customerReady&&!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.'
|
||||||
|
:'Preencha os dados do cliente.');
|
||||||
}
|
}
|
||||||
// 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'.
|
||||||
@@ -252,13 +363,23 @@ function montarItems(lines,uploads){
|
|||||||
}
|
}
|
||||||
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;
|
||||||
|
}
|
||||||
|
if(kind==='venda'&&montarDelivery()==='with_order'&&!montarWithOrder())
|
||||||
|
return say('Informe o número do pedido de roupa.',true);
|
||||||
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 +392,17 @@ 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;
|
||||||
|
const withOrder=montarWithOrder();
|
||||||
|
if(withOrder)body.with_order=withOrder;
|
||||||
|
}
|
||||||
|
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 +455,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 +521,76 @@ 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){
|
||||||
|
$('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;
|
||||||
|
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 +629,22 @@ $('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();});
|
||||||
|
document.addEventListener('click',event=>{
|
||||||
|
if(!event.target.closest('.montar-customer-search'))$('montar-customer-hits').hidden=true;
|
||||||
|
});
|
||||||
|
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)],
|
||||||
|
|||||||
@@ -1289,6 +1289,32 @@ 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-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 +1333,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,26 @@
|
|||||||
<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>Envio</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>
|
||||||
|
</div>
|
||||||
|
<p class="phint">Envio com o frete do Site chega na próxima etapa.</p>
|
||||||
</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 +174,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 +207,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>
|
||||||
|
|||||||
@@ -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){
|
||||||
@@ -427,7 +427,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
|
||||||
@@ -758,7 +758,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,
|
||||||
@@ -1115,6 +1115,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);
|
||||||
@@ -1142,8 +1145,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;}
|
||||||
@@ -1426,7 +1431,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';
|
||||||
@@ -1437,6 +1442,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);
|
||||||
@@ -1829,6 +1835,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));
|
||||||
@@ -2241,7 +2251,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);}
|
||||||
@@ -2257,9 +2267,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));
|
||||||
@@ -2440,7 +2451,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);
|
||||||
}
|
}
|
||||||
@@ -2827,7 +2838,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));
|
||||||
}
|
}
|
||||||
@@ -3699,7 +3714,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);}
|
||||||
|
|||||||
@@ -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).
|
||||||
|
|||||||
@@ -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(/\/+$/,'')||'/';
|
||||||
|
|||||||
Reference in New Issue
Block a user