Compare commits
140 Commits
5ca6792221
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
aeb43500a7 | ||
|
|
857eea3379 | ||
|
|
f739c9d4e4 | ||
|
|
7fc091a1bd | ||
|
|
7e33e6fb1d | ||
|
|
37d747697a | ||
|
|
c4f8ba1b70 | ||
|
|
4283c93526 | ||
|
|
eb7a92bb89 | ||
|
|
9fc4d4e906 | ||
|
|
6ec0ea31a6 | ||
|
|
5f84db708c | ||
|
|
2ff11688bc | ||
|
|
a652d734ea | ||
|
|
48d8b2f434 | ||
|
|
4a1994bd06 | ||
|
|
bb6fb14b1a | ||
|
|
6970434e5d | ||
|
|
7454f6b840 | ||
|
|
ba85168c09 | ||
|
|
b64947eb76 | ||
|
|
f35a347a28 | ||
|
|
194797c412 | ||
|
|
742ea5f5bd | ||
|
|
b2876487bd | ||
|
|
331e43aa14 | ||
|
|
eb56c49016 | ||
|
|
3204ec4368 | ||
|
|
00261af931 | ||
|
|
6a8855504f | ||
|
|
b027bb5013 | ||
|
|
b8496b858f | ||
|
|
47f3251d3e | ||
|
|
5dc4135562 | ||
|
|
ffc7d3153a | ||
|
|
70837e2e06 | ||
|
|
8af6d576e9 | ||
|
|
f58b0701b4 | ||
|
|
64a017e0a4 | ||
|
|
3b9575b94b | ||
|
|
617868945a | ||
|
|
8ba30e057c | ||
|
|
2fcec0b809 | ||
|
|
6d8dbf24ff | ||
|
|
4c6e2aac4a | ||
|
|
a88e7a3288 | ||
|
|
5ed8109d50 | ||
|
|
9c23654937 | ||
|
|
a5820eb147 | ||
|
|
3da1c9c11c | ||
|
|
5db8661a1a | ||
|
|
449b45b520 | ||
|
|
a1fad7698a | ||
|
|
242a56aae8 | ||
|
|
d51fe24eea | ||
|
|
6e05dd93c2 | ||
|
|
65f8dd211e | ||
|
|
177694edd3 | ||
|
|
662d6f9c41 | ||
|
|
29187e6c9f | ||
|
|
378266afa2 | ||
|
|
9e31345cf7 | ||
|
|
70eb6947eb | ||
|
|
b3ecba590b | ||
|
|
a52856f3f6 | ||
|
|
9bbfa42cd4 | ||
|
|
2d8d7c78b1 | ||
|
|
06f4ec9f20 | ||
|
|
ad3a966ae2 | ||
|
|
a28cd165c4 | ||
|
|
2f67fdc123 | ||
|
|
d76288c335 | ||
|
|
27b26cd1ae | ||
|
|
e8931c2818 | ||
|
|
aaa6090642 | ||
|
|
c61ac27ca4 | ||
|
|
5d9a78b63c | ||
|
|
b6837023bf | ||
|
|
bd25cb9c1c | ||
|
|
9630baa970 | ||
|
|
2439948249 | ||
|
|
0e7b6eb019 | ||
|
|
8cc35c100f | ||
|
|
5ca4872e79 | ||
|
|
5cf8cd1d54 | ||
|
|
9de9b6abe1 | ||
|
|
c799fd9be4 | ||
|
|
aa0ba92b68 | ||
|
|
4cba424149 | ||
|
|
66bc2b9b03 | ||
|
|
4f584fed8a | ||
|
|
050a823bcb | ||
|
|
f2b825b652 | ||
|
|
8daf3084aa | ||
|
|
397e55c81d | ||
|
|
52b8bb368f | ||
|
|
08b822104c | ||
|
|
3d01b81a31 | ||
|
|
b3daed649a | ||
|
|
ccdd72c4ce | ||
|
|
9a0efb3b41 | ||
|
|
fb23b63090 | ||
|
|
a34d8e1888 | ||
|
|
243138fea1 | ||
|
|
e8423bec45 | ||
|
|
392a21082e | ||
|
|
040ef46f94 | ||
|
|
9e5811d58f | ||
|
|
92ffb679d6 | ||
|
|
2c740da4c1 | ||
|
|
d6c80ff447 | ||
|
|
4e6f96bfe2 | ||
|
|
ee772a43ff | ||
|
|
bcba1fbe67 | ||
|
|
00c7fa3dfa | ||
|
|
2478c05ae6 | ||
|
|
70bdaf1a8d | ||
|
|
0e247e6b4c | ||
|
|
8fa76b7819 | ||
|
|
fe224cfc9c | ||
|
|
034f3bfbb5 | ||
|
|
445d686f43 | ||
|
|
5a7fc0f378 | ||
|
|
9ae865619e | ||
|
|
6be7e15f9f | ||
|
|
eef899e838 | ||
|
|
d0ec629c4e | ||
|
|
7abd215d13 | ||
|
|
e80f376d91 | ||
|
|
b8ee3fb35a | ||
|
|
057643e167 | ||
|
|
9cf4da0dea | ||
|
|
a17287a118 | ||
|
|
c42e273c5b | ||
|
|
57851abffc | ||
|
|
461bd6bbcc | ||
|
|
912bab0278 | ||
|
|
0964cdae1f | ||
|
|
38f947d632 | ||
|
|
973cd87b36 |
@@ -101,7 +101,7 @@ jobs:
|
||||
# the generator's geometry. The provider suites use a fake transport: they
|
||||
# prove the documented contract, not the integration.
|
||||
- name: Print-file geometry and provider adapters
|
||||
run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_printpng tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_payment_messages tests.test_jadlog tests.test_correios tests.test_quote_review tests.test_moves tests.test_large_files tests.test_grade_check tests.test_schema tests.test_customer_document tests.test_mail_html tests.test_layout_rules tests.test_proof_cut tests.test_proof_render tests.test_prumo tests.test_speed tests.test_printpng_validate tests.test_machine_log tests.test_machine_stats tests.test_label tests.test_observability tests.test_worker_drain -v
|
||||
run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_printpng tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_payment_messages tests.test_jadlog tests.test_correios tests.test_quote_review tests.test_moves tests.test_large_files tests.test_grade_check tests.test_schema tests.test_customer_document tests.test_mail_html tests.test_layout_rules tests.test_proof_cut tests.test_proof_render tests.test_sheet_trim tests.test_one_machine tests.test_profiles tests.test_sheet_gap tests.test_reprint tests.test_proof_parts tests.test_prumo tests.test_speed tests.test_printpng_validate tests.test_machine_log tests.test_machine_stats tests.test_label tests.test_observability tests.test_worker_drain tests.test_db_outage tests.test_health tests.test_saved_size -v
|
||||
|
||||
- name: Runtime and retention regressions
|
||||
run: |
|
||||
|
||||
@@ -198,6 +198,16 @@ class FakeTiny:
|
||||
{'id': 1002, 'name': 'Maria Souza', 'document': '123.456.789-09',
|
||||
'email': 'maria.souza@example.test', 'phone': '16988887777'},
|
||||
]
|
||||
# The code's SKUs, so a payload can be built on the local stack without
|
||||
# asking Tiny: the modes' defaults and the designer services (front 1b).
|
||||
SKUS = {
|
||||
'DTFIMP.TX.100CM': 8001,
|
||||
**{f'DTFIMP.TX.{cm:04d}CM': 8000 + cm // 10 for cm in range(10, 100, 10)},
|
||||
'DTFIMP.UV.1MT': 8101, 'DTFIMP.UV.010CM': 8102,
|
||||
'DTFIMP.TXP.100CM': 8201,
|
||||
**{f'DTFIMP.TXP.{cm:04d}CM': 8200 + cm // 10 for cm in range(10, 100, 10)},
|
||||
'DTFIMP.AJF.UN': 9001, 'DTFIMP.AJF.RED': 9002,
|
||||
}
|
||||
|
||||
def deliver(self, event_key: str, payload: dict) -> dict:
|
||||
return {'provider': 'fake-tiny', 'reference': f"LOCAL-{payload['number']}",
|
||||
@@ -206,13 +216,23 @@ class FakeTiny:
|
||||
def search_contacts(self, query: str) -> list:
|
||||
return [dict(contact) for contact in self.CONTACTS]
|
||||
|
||||
# Tiny's sellers, for the Kanban users' "Vendedor no Tiny".
|
||||
SELLERS = [{'id': 2001, 'name': 'Lais'}, {'id': 2002, 'name': 'Marcus'}]
|
||||
|
||||
def list_sellers(self) -> list:
|
||||
return [dict(seller) for seller in self.SELLERS]
|
||||
|
||||
def product_id(self, code: str) -> int:
|
||||
"""The fake Tiny product id for a SKU code, as the real catalogue does."""
|
||||
return self.SKUS[code]
|
||||
|
||||
class ObjectStorage(Protocol):
|
||||
def begin(self, key: str) -> str: ...
|
||||
def parts(self, key: str, upload_id: str) -> list: ...
|
||||
def part_url(self, key: str, upload_id: str, part: int, size: int) -> str: ...
|
||||
def complete(self, key: str, upload_id: str, parts: list): ...
|
||||
def size(self, key: str) -> int: ...
|
||||
def download(self, key: str, name: str) -> str: ...
|
||||
def download(self, key: str, name: str, expires: int = 300) -> str: ...
|
||||
def fetch(self, key: str, path: str): ...
|
||||
def store(self, key: str, path: str, content_type: str): ...
|
||||
def health(self): ...
|
||||
@@ -226,6 +246,12 @@ class LocalS3Storage:
|
||||
connect_timeout=3, read_timeout=10, retries={'max_attempts': 2})
|
||||
self.client = boto3.client('s3', endpoint_url=os.environ['S3_ENDPOINT'], config=config)
|
||||
self.public = boto3.client('s3', endpoint_url=os.environ['S3_PUBLIC_ENDPOINT'], config=config)
|
||||
# The worker's own reads and writes wait out a short storage outage
|
||||
# (an R2 503, Sentry DTF-API-A): up to 10 tries with growing backoff,
|
||||
# about two minutes. Requests a person waits on keep the 2 tries.
|
||||
patient = Config(signature_version='s3v4', s3={'addressing_style': 'path'},
|
||||
connect_timeout=3, read_timeout=30, retries={'max_attempts': 10, 'mode': 'standard'})
|
||||
self.patient = boto3.client('s3', endpoint_url=os.environ['S3_ENDPOINT'], config=patient)
|
||||
self.bucket = os.environ['S3_BUCKET']
|
||||
|
||||
def initialize(self):
|
||||
@@ -267,18 +293,18 @@ class LocalS3Storage:
|
||||
|
||||
def fetch(self, key, path):
|
||||
"""Copy a stored object to a local file (the worker's scratch space)."""
|
||||
self.client.download_file(self.bucket, key, path)
|
||||
self.patient.download_file(self.bucket, key, path)
|
||||
|
||||
def store(self, key, path, content_type):
|
||||
"""Upload a file the service generated itself, such as a print file."""
|
||||
self.client.upload_file(path, self.bucket, key, ExtraArgs={'ContentType': content_type})
|
||||
self.patient.upload_file(path, self.bucket, key, ExtraArgs={'ContentType': content_type})
|
||||
|
||||
def download(self, key, name):
|
||||
def download(self, key, name, expires=300):
|
||||
from urllib.parse import quote
|
||||
return self.public.generate_presigned_url('get_object', Params={
|
||||
'Bucket': self.bucket, 'Key': key,
|
||||
'ResponseContentDisposition': "attachment; filename*=UTF-8''" + quote(name, safe=''),
|
||||
'ResponseContentType': 'application/octet-stream'}, ExpiresIn=300)
|
||||
'ResponseContentType': 'application/octet-stream'}, ExpiresIn=expires)
|
||||
|
||||
def view(self, key, content_type, expires=3600):
|
||||
"""A link to show an object in the page, not download it: the Kanban's
|
||||
|
||||
@@ -6,13 +6,15 @@ one transport serves both and there is only one place where parts are signed.
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import Field
|
||||
|
||||
from ..core import db
|
||||
from .. import proof
|
||||
from ..artwork import submit_files
|
||||
from ..core.auth import can, can_any, operator
|
||||
from ..core.models import ArtworkSubmission, UploadStart
|
||||
from ..runtime import file_rows, operator_identity
|
||||
from ..core.models import ArtworkSubmission, StrictModel, UploadStart
|
||||
from ..printpng_validate import final_png_problem
|
||||
from ..runtime import file_rows, operator_identity, storage
|
||||
from .uploads import begin_upload, cancel_upload, complete_upload, part_url, upload_status
|
||||
|
||||
router = APIRouter()
|
||||
@@ -54,6 +56,35 @@ def operator_files(oid: UUID, user=Depends(operator)):
|
||||
with db.connect() as c:
|
||||
return file_rows(c,oid)
|
||||
|
||||
class FinalCheck(StrictModel):
|
||||
uploads: list[UUID] = Field(min_length=1, max_length=400)
|
||||
|
||||
|
||||
@router.post('/api/operator/orders/{oid}/final-check')
|
||||
def final_check(oid: UUID, body: FinalCheck, user=Depends(can('produce'))):
|
||||
"""Whether these files of the order can be approved as its finals, asked
|
||||
before approving (Sentry DTF-WEB-11): a customer's correction or an
|
||||
original may not be the transparent 300 DPI PNG a final must be. The
|
||||
answer lists the problems with 200, so a file to treat is guidance in
|
||||
the panel, not a refusal. Only the order's own files are read."""
|
||||
with db.connect() as c:
|
||||
order = c.execute('SELECT snapshot FROM dtf_local.orders WHERE id=%s', (oid,)).fetchone()
|
||||
if not order:
|
||||
raise HTTPException(404, 'Pedido não encontrado.')
|
||||
originals = {uid for item in order['snapshot']['items'] for uid in item['uploads']}
|
||||
rows = c.execute('''SELECT u.id,u.name,u.object_key FROM dtf_local.uploads u WHERE u.id=ANY(%s) AND (
|
||||
u.id::text=ANY(%s)
|
||||
OR EXISTS (SELECT 1 FROM dtf_local.order_files f WHERE f.order_id=%s AND f.upload_id=u.id)
|
||||
OR EXISTS (SELECT 1 FROM dtf_local.print_parts p WHERE p.order_id=%s AND p.upload_id=u.id))''',
|
||||
(body.uploads, list(originals), oid, oid)).fetchall()
|
||||
problems = []
|
||||
for row in rows:
|
||||
issue = final_png_problem(storage, row)
|
||||
if issue:
|
||||
problems.append({'upload_id': str(row['id']), 'name': row['name'], 'message': issue})
|
||||
return {'problems': problems}
|
||||
|
||||
|
||||
@router.post('/api/operator/orders/{oid}/final-files')
|
||||
def final_files(oid: UUID, body: ArtworkSubmission, user=Depends(can('produce'))):
|
||||
with db.connect() as c:
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
"""Health, session bootstrap, freight quoting and the address of a CEP."""
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
|
||||
import httpx
|
||||
from fastapi import APIRouter, HTTPException, Request, Response
|
||||
@@ -16,17 +18,53 @@ from ..runtime import (ENVIRONMENT, GUEST_SESSION_LIMIT, PART_BYTES, delivery_se
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
# Since when storage has failed the check, and whether Sentry heard of it.
|
||||
# R2 answers HeadBucket with a 500 now and then (Sentry DTF-API-B, 34 times
|
||||
# from 20/11): a blip is not the API being down.
|
||||
STORAGE_DOWN_AFTER = 300
|
||||
_storage = {'down_since': None, 'reported': False}
|
||||
|
||||
|
||||
def storage_answers():
|
||||
"""Whether storage answers, trying twice in well under the 3 s the
|
||||
container's health check allows."""
|
||||
for attempt in range(2):
|
||||
try:
|
||||
storage.health()
|
||||
return True
|
||||
except Exception as exc:
|
||||
error = exc
|
||||
if attempt == 0:
|
||||
time.sleep(0.3)
|
||||
logging.warning('Storage health check failed: %s', error)
|
||||
return False
|
||||
|
||||
|
||||
@router.get('/health')
|
||||
@router.get('/api/health')
|
||||
def health():
|
||||
"""The database down is the API down: 503 at once. Storage failing is
|
||||
reported in the answer and is a 503, with one error for Sentry, only when
|
||||
it has lasted STORAGE_DOWN_AFTER seconds."""
|
||||
try:
|
||||
with db.connect() as c:
|
||||
c.execute('SELECT 1')
|
||||
storage.health()
|
||||
except Exception:
|
||||
raise HTTPException(503, 'Database or storage unavailable')
|
||||
return {'status': 'ok', 'environment': ENVIRONMENT,
|
||||
'storage': 'minio' if ENVIRONMENT == 'local' else 'r2', 'integrations': 'fake'}
|
||||
raise HTTPException(503, 'Database unavailable')
|
||||
if storage_answers():
|
||||
_storage.update(down_since=None, reported=False)
|
||||
state = 'minio' if ENVIRONMENT == 'local' else 'r2'
|
||||
else:
|
||||
if _storage['down_since'] is None:
|
||||
_storage['down_since'] = time.monotonic()
|
||||
since = _storage['down_since']
|
||||
if time.monotonic() - since >= STORAGE_DOWN_AFTER:
|
||||
if not _storage['reported']:
|
||||
_storage['reported'] = True
|
||||
logging.error('Storage has failed the health check for %d minutes', STORAGE_DOWN_AFTER // 60)
|
||||
raise HTTPException(503, 'Storage unavailable')
|
||||
state = 'unavailable'
|
||||
return {'status': 'ok', 'environment': ENVIRONMENT, 'storage': state, 'integrations': 'fake'}
|
||||
|
||||
@router.get('/api/session')
|
||||
def session(request: Request, response: Response):
|
||||
@@ -42,6 +80,7 @@ def session(request: Request, response: Response):
|
||||
products = catalog.current(c)
|
||||
rules = grade_rules.current_rules(c)
|
||||
treatment = products['tratamento']
|
||||
redesign = products['redesenho']
|
||||
return {'environment': ENVIRONMENT, 'cart_scope': str(session_id), 'part_bytes': PART_BYTES,
|
||||
'max_upload_bytes': upload_limit_bytes(), 'payment_provider': payment.name,
|
||||
'password_recovery': mail.configured(),
|
||||
@@ -53,6 +92,9 @@ def session(request: Request, response: Response):
|
||||
'treatment_bands': [{'from_metres': float(band['from_metres']),
|
||||
'unit_cents': band['unit_cents']}
|
||||
for band in treatment['bands']] if treatment['enabled'] else [],
|
||||
# Zero keeps Redesenho hidden, as an off product does. One price
|
||||
# per art, never a band (front 1b).
|
||||
'redesign_cents': redesign['unit_cents'] if redesign['enabled'] else 0,
|
||||
# The grade rules the Site needs for the treatment requirement
|
||||
# (front 8.5): {} when nothing is configured.
|
||||
'grade_rules': rules,
|
||||
|
||||
@@ -5,7 +5,7 @@ from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
|
||||
from .. import machine_log, machine_stats
|
||||
from ..core import db
|
||||
from ..core.auth import audit, can, operator
|
||||
from ..core.auth import audit, can, operator, operator_only, roles_of
|
||||
from ..core.models import MachineEntry, MachineSheet
|
||||
|
||||
router = APIRouter()
|
||||
@@ -25,7 +25,7 @@ def machine_row(c, mid):
|
||||
def own_machine(request, mid):
|
||||
"""An operator enters only on the machine of their session; management, anywhere."""
|
||||
account = request.state.operator
|
||||
if account['role'] != 'operador':
|
||||
if not operator_only(account, 'print'):
|
||||
return
|
||||
session_machine = account['machine']
|
||||
if not session_machine or str(session_machine['id']) != str(mid):
|
||||
@@ -127,7 +127,7 @@ def snooze_alert(mid: UUID, key: str, request: Request, user=Depends(can('print'
|
||||
@router.get('/api/operator/stats/machines')
|
||||
def machine_stats_month(request: Request, month: str | None = None, user=Depends(operator)):
|
||||
"""Números per machine, month by month (Fase 2, front 1b)."""
|
||||
if request.state.operator['role'] not in STATS_ROLES:
|
||||
if not set(roles_of(request.state.operator)) & set(STATS_ROLES):
|
||||
raise HTTPException(403, 'Seu perfil não permite esta ação.')
|
||||
try:
|
||||
start, _ = machine_stats.month_bounds(month)
|
||||
|
||||
@@ -8,6 +8,7 @@ from fastapi import APIRouter, Depends, HTTPException, Query, Response
|
||||
from pydantic import Field
|
||||
|
||||
from ... import hotfolder, machines, mail, payments, prumo, receipt, reviews
|
||||
from ...cart_pricing import designer_hours
|
||||
from ...core import db
|
||||
from ...core.auth import audit, can, operator
|
||||
from ...core.models import StrictModel
|
||||
@@ -66,7 +67,7 @@ def board(user=Depends(operator)):
|
||||
'environment': ENVIRONMENT, 'site_origin': PUBLIC_ORIGIN,
|
||||
'finished_shown': len(finished), 'finished_total': finished_total,
|
||||
# Who is on each machine now, for the machine question (item 12).
|
||||
'machines': machines.rows(c, with_operators=True), 'printing_cap': machines.PRINTING_CAP,
|
||||
'machines': machines.rows(c, with_operators=True), 'printing_cap': machines.DEFAULT_PLACES,
|
||||
'quotes': quotes, 'thumbnails': thumbnails(c, orders, quotes),
|
||||
'names': company_names(c, orders, quotes),
|
||||
'pending_total': pending_total, 'approved_total': approved_total,
|
||||
@@ -138,10 +139,10 @@ def assign_late(c, orders, limits):
|
||||
since = since or order['created_at']
|
||||
hours = max(0.0, (now - since).total_seconds() / 3600)
|
||||
limit_hours = float(limit['hours'])
|
||||
# A paid treatment gives Art received its extra hours to prepare the art.
|
||||
treatment = (order.get('snapshot') or {}).get('treatment') or {}
|
||||
if order['state'] == 'rec' and treatment:
|
||||
limit_hours += float(treatment.get('hours', 24))
|
||||
# Paid designer work gives Art received its extra hours to prepare the
|
||||
# art: 48 h for a Redesenho, 24 h for the basic Ajuste Fino.
|
||||
if order['state'] == 'rec':
|
||||
limit_hours += designer_hours(order.get('snapshot') or {})
|
||||
order['state_hours'] = round(hours, 2)
|
||||
order['limit_hours'] = limit_hours
|
||||
order['limit_by'] = limit['responsible']
|
||||
@@ -172,8 +173,8 @@ def with_print_files(c, orders):
|
||||
ids = [o['id'] for o in orders]
|
||||
generated = c.execute('''SELECT p.order_id,p.item_index,p.status,p.upload_id,p.detail,p.claimed_at,p.finished_at,
|
||||
p.created_at,
|
||||
(p.status='rendering' AND p.claimed_at<now()-%s) AS timed_out,
|
||||
p.claimed_at+%s AS timeout_at,u.name
|
||||
(p.status='rendering' AND COALESCE(p.deadline_at,p.claimed_at+%s)<now()) AS timed_out,
|
||||
COALESCE(p.deadline_at,p.claimed_at+%s) AS timeout_at,u.name
|
||||
FROM dtf_local.print_files p LEFT JOIN dtf_local.uploads u ON u.id=p.upload_id
|
||||
WHERE p.order_id=ANY(%s) ORDER BY p.item_index''', (CLAIM_TIMEOUT, CLAIM_TIMEOUT, ids)).fetchall()
|
||||
upload_ids = sorted({str(uid) for order in orders for item in order['snapshot']['items']
|
||||
@@ -208,20 +209,30 @@ def with_print_files(c, orders):
|
||||
FROM dtf_local.movements WHERE order_id=ANY(%s) AND to_state='cor' ORDER BY order_id,id DESC''', (ids,)).fetchall()}
|
||||
# Where a printing order's files are in its machine's hot folder (item 10).
|
||||
hot = hotfolder.progress(c, [o['id'] for o in orders if o['state'] == 'imp'])
|
||||
# Orders the machine already printed: a reprint chooses which items go
|
||||
# again (#105), the ones whose final changed suggested.
|
||||
taken = hotfolder.printed(c, [o['id'] for o in orders if o['state'] in ('rec', 'tra', 'cor')])
|
||||
# Each parent's latest proof card, and each card's parent (app/proof.py).
|
||||
children = {r['parent_id']: r for r in c.execute('''SELECT DISTINCT ON (parent_id) parent_id,id,number,state,
|
||||
proof_result,proof_decided_at,proof_decided_by,proof_reason FROM dtf_local.orders
|
||||
proof_result,proof_decided_at,proof_decided_by,proof_reason,machine_id FROM dtf_local.orders
|
||||
WHERE parent_id=ANY(%s) AND cancelled_at IS NULL ORDER BY parent_id, created_at DESC''', (ids,)).fetchall()}
|
||||
parents = {r['id']: r for r in c.execute('SELECT id,number,state FROM dtf_local.orders WHERE id=ANY(%s)',
|
||||
([o['parent_id'] for o in orders if o.get('parent_id')],)).fetchall()}
|
||||
# Every order's review photos and videos, in one query like the print files.
|
||||
review_rows = reviews.by_order(c, ids)
|
||||
# The proof card's go on its order too: an answered card leaves the board,
|
||||
# and the photo the seller answered on must stay a click away (Marcus,
|
||||
# 2026-11-17, the proof of #30).
|
||||
proof_reviews = reviews.by_order(c, [r['id'] for r in children.values()])
|
||||
for order in orders:
|
||||
order['hot'] = hot.get(order['id'])
|
||||
order['reviews'] = review_rows.get(str(order['id']), [])
|
||||
child = children.get(order['id'])
|
||||
order['proof_card'] = child and {k: child[k] for k in ('id', 'number', 'state', 'proof_result',
|
||||
'proof_decided_at', 'proof_decided_by', 'proof_reason')}
|
||||
# Its machine: an order prints where its approved proof did (Dropstar, 2026-11-05).
|
||||
order['proof_card'] = child and {**{k: child[k] for k in ('id', 'number', 'state', 'proof_result',
|
||||
'proof_decided_at', 'proof_decided_by', 'proof_reason',
|
||||
'machine_id')},
|
||||
'reviews': proof_reviews.get(str(child['id']), [])}
|
||||
parent = parents.get(order.get('parent_id'))
|
||||
order['proof_parent'] = parent and {'id': parent['id'], 'number': parent['number'], 'state': parent['state']}
|
||||
order['correction_reason'] = reasons.get(order['id']) if order['state'] == 'cor' else None
|
||||
@@ -231,6 +242,11 @@ def with_print_files(c, orders):
|
||||
order['final_items'] = sorted({row['item_index'] for row in approved})
|
||||
# The approved finals themselves: "Tratar a arte" keeps those it does not replace.
|
||||
order['finals'] = [{'item_index': row['item_index'], 'upload_id': row['upload_id']} for row in approved]
|
||||
if order['id'] in taken:
|
||||
order['printed_before'] = True
|
||||
order['print_suggested'] = hotfolder.reprint_default(
|
||||
[(f['item_index'], f['upload_id']) for f in order.get('finals') or []], taken[order['id']],
|
||||
len(order['snapshot']['items']))
|
||||
mine = [row for row in treated if row['order_id'] == order['id']]
|
||||
order['treated'] = {'items': [row['item_index'] for row in mine], 'by': mine[0]['created_by']} if mine else None
|
||||
order['corrections'] = [{k: row[k] for k in ('item_index', 'upload_id', 'name', 'expired')}
|
||||
|
||||
@@ -5,6 +5,7 @@ from fastapi import APIRouter, HTTPException
|
||||
|
||||
from ... import cnpj
|
||||
from ...core import db
|
||||
from ...finals import FINAL_OK, TREATED # noqa: F401 (the board, files and stats use them)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -40,20 +41,6 @@ def company_names(c, *groups):
|
||||
for rows in groups for row in rows])
|
||||
|
||||
|
||||
# An item's final counts while its file is still there and scanned clean: the
|
||||
# same rule that lets an order into the print queue.
|
||||
FINAL_OK = """f.kind='final' AND f.active AND u.expires_at>now() AND u.purged_at IS NULL AND u.scan_state='clean'"""
|
||||
# "Arte tratada" (Dropstar, 2026-10-27): a final someone prepared, not the
|
||||
# customer's own artwork. It is neither the file the system generated from
|
||||
# their art, nor one of their originals, nor a correction they sent. `f` is
|
||||
# the final in dtf_local.order_files, `o` its order.
|
||||
TREATED = """f.kind='final'
|
||||
AND NOT EXISTS (SELECT 1 FROM dtf_local.print_parts p WHERE p.order_id=f.order_id AND p.upload_id=f.upload_id)
|
||||
AND NOT EXISTS (SELECT 1 FROM jsonb_array_elements(o.snapshot->'items') i WHERE i->'uploads' ? f.upload_id::text)
|
||||
AND NOT EXISTS (SELECT 1 FROM dtf_local.order_files k WHERE k.order_id=f.order_id AND k.upload_id=f.upload_id
|
||||
AND k.kind='correction')"""
|
||||
|
||||
|
||||
def person(column):
|
||||
"""SQL: the team member's name for the e-mail in `column`, or the e-mail."""
|
||||
return f'COALESCE((SELECT op.name FROM dtf_local.operators op WHERE op.email={column}), {column})'
|
||||
|
||||
@@ -16,6 +16,10 @@ from ...scanning import require_clean
|
||||
from .common import FINAL_OK
|
||||
|
||||
router = APIRouter()
|
||||
# The folders download a whole list of files, one after another, from links
|
||||
# made when the list was asked for: with films of 10 m, 5 minutes ran out
|
||||
# before the last ones began (erro 403). Only the team's computers see them.
|
||||
FOLDER_LINK_SECONDS = 3600
|
||||
|
||||
def named_files(rows):
|
||||
"""Each file named after its order and item, so a folder of them stays
|
||||
@@ -28,7 +32,8 @@ def named_files(rows):
|
||||
name = row['name']
|
||||
if name.startswith(older):
|
||||
name = prefix + name[len(older):]
|
||||
elif not name.startswith(prefix):
|
||||
# DTF-23-item-1 or, generated again, DTF-23-v2-item-1: already named.
|
||||
elif not name.startswith(f"DTF-{row['number']}-"):
|
||||
name = f"{prefix}-{name}"
|
||||
stem, dot, ext = name.rpartition('.')
|
||||
copy = 2
|
||||
@@ -38,7 +43,7 @@ def named_files(rows):
|
||||
names.add(name)
|
||||
files.append({'order': str(row['order_id']), 'state': row['state'], 'number': row['number'],
|
||||
'item': row['item_index'] + 1, 'name': name, 'upload_id': str(row['upload_id']),
|
||||
'url': storage.download(row['object_key'], name)})
|
||||
'url': storage.download(row['object_key'], name, FOLDER_LINK_SECONDS)})
|
||||
return files
|
||||
|
||||
|
||||
@@ -49,14 +54,16 @@ def print_ready(c, states, only=None, paid_after=None):
|
||||
these orders, `paid_after` to the orders paid since then."""
|
||||
ids = None if only is None else list(only)
|
||||
rows = c.execute(f'''SELECT o.id AS order_id,o.state,o.number,f.item_index,f.upload_id,u.object_key,u.name,
|
||||
COALESCE(o.queue_key, extract(epoch FROM o.created_at)) AS position
|
||||
COALESCE(o.queue_key, extract(epoch FROM o.created_at)) AS position, pp.part
|
||||
FROM dtf_local.orders o
|
||||
JOIN dtf_local.order_files f ON f.order_id=o.id JOIN dtf_local.uploads u ON u.id=f.upload_id
|
||||
LEFT JOIN dtf_local.print_parts pp ON pp.order_id=f.order_id AND pp.item_index=f.item_index
|
||||
AND pp.upload_id=f.upload_id
|
||||
WHERE o.state=ANY(%s) AND (%s::uuid[] IS NULL OR o.id=ANY(%s))
|
||||
AND (%s::timestamptz IS NULL OR o.created_at>=%s) AND o.cancelled_at IS NULL AND {FINAL_OK}
|
||||
UNION ALL
|
||||
SELECT o.id,o.state,o.number,p.item_index,pp.upload_id,u.object_key,u.name,
|
||||
COALESCE(o.queue_key, extract(epoch FROM o.created_at))
|
||||
COALESCE(o.queue_key, extract(epoch FROM o.created_at)), pp.part
|
||||
FROM dtf_local.orders o
|
||||
JOIN dtf_local.print_files p ON p.order_id=o.id
|
||||
JOIN dtf_local.print_parts pp ON pp.order_id=p.order_id AND pp.item_index=p.item_index
|
||||
@@ -67,7 +74,7 @@ def print_ready(c, states, only=None, paid_after=None):
|
||||
AND NOT EXISTS (SELECT 1 FROM dtf_local.order_files f WHERE f.order_id=o.id AND f.kind='final'
|
||||
AND f.active AND f.item_index=p.item_index)
|
||||
AND NOT EXISTS (SELECT 1 FROM dtf_local.order_files f WHERE f.order_id=o.id AND f.kind='correction')
|
||||
ORDER BY position,order_id,item_index,name''',
|
||||
ORDER BY position,order_id,item_index,part NULLS LAST,name''',
|
||||
(list(states), ids, ids, paid_after, paid_after, list(states), ids, ids, paid_after, paid_after)).fetchall()
|
||||
return rows
|
||||
|
||||
@@ -160,7 +167,7 @@ def queue_hot(user=Depends(can('print'))):
|
||||
watched = hotfolder.watched(c)
|
||||
return {'folder': hotfolder.PRINTING_FOLDER,
|
||||
'write': [{'id': r['id'], 'order': str(r['order_id']), 'folder': r['folder'], 'name': r['name'],
|
||||
'url': storage.download(keys[str(r['upload_id'])], r['name'])} for r in due],
|
||||
'url': storage.download(keys[str(r['upload_id'])], r['name'], FOLDER_LINK_SECONDS)} for r in due],
|
||||
'watch': [{'id': r['id'], 'order': str(r['order_id']), 'folder': r['folder'], 'name': r['name']}
|
||||
for r in watched if r['state'] == 'written'],
|
||||
'withdraw': [{'id': r['id'], 'order': str(r['order_id']), 'folder': r['folder'], 'name': r['name']}
|
||||
|
||||
@@ -149,6 +149,28 @@ def tiny_contacts(q: str = Query(min_length=1, max_length=120), user=Depends(can
|
||||
raise HTTPException(409, 'O Tiny não está conectado.')
|
||||
|
||||
|
||||
@router.get('/api/operator/tiny/sellers')
|
||||
def tiny_sellers(user=Depends(can('users'))):
|
||||
"""Tiny's sellers, for the "Vendedor no Tiny" of each Kanban user: a
|
||||
Venda they assemble reaches Tiny with that seller (Marcus, 2026-11-17)."""
|
||||
if os.environ.get('TINY_ADAPTER') != 'tiny':
|
||||
from ...adapters import FakeTiny
|
||||
return FakeTiny().list_sellers()
|
||||
if not tiny.configured():
|
||||
raise HTTPException(409, 'O Tiny não está conectado.')
|
||||
try:
|
||||
return tiny.list_sellers(tiny.TinyOrders())
|
||||
except tiny.TinyNotConnected:
|
||||
raise HTTPException(409, 'O Tiny não está conectado.')
|
||||
except tiny.TinyError as exc:
|
||||
# Tiny checks the connected user's module permissions on every call:
|
||||
# our user needs to see Vendedores (app/tiny.py, 2026-10-27).
|
||||
if ': 403 ' in str(exc) or ': 401 ' in str(exc):
|
||||
raise HTTPException(409, 'O Tiny recusou a leitura dos vendedores: o usuário do Kanban no Tiny precisa da '
|
||||
'permissão de ver Vendedores. Resposta do Tiny: ' + str(exc).split(': ', 1)[-1][:200])
|
||||
raise
|
||||
|
||||
|
||||
@router.post('/api/operator/tiny/connect')
|
||||
def tiny_connect(user=Depends(can('integrations'))):
|
||||
"""Start the one-time authorisation of this system in the client's Tiny."""
|
||||
|
||||
@@ -9,11 +9,13 @@ from pydantic import Field
|
||||
from psycopg.types.json import Jsonb
|
||||
|
||||
from ... import hotfolder, machine_log, machines, payments, proof, receipt, reviews
|
||||
from ...cart_pricing import needs_designer
|
||||
from ...core import db
|
||||
from ...core.auth import MOVERS, audit, can, may_move, may_reorder, operator
|
||||
from ...core.auth import (MOVERS, audit, can, machine_bound, may_move, may_reorder, operator, operator_only,
|
||||
reorder_machine_bound, roles_of)
|
||||
from ...core.models import Contraction, Move, Resolution, StrictModel, UploadStart
|
||||
from ...payments import release_files
|
||||
from ...printjobs import queue as queue_print_files
|
||||
from ...printjobs import queue as queue_print_files, requeue as requeue_print_files
|
||||
from ...runtime import BACK, STATES, TRANSITIONS, enqueue, operator_identity, upload_row
|
||||
from ...scanning import require_clean
|
||||
from ..uploads import begin_upload
|
||||
@@ -48,6 +50,10 @@ def delete_order(uid: UUID, user=Depends(can('manage'))):
|
||||
cards = [r['id'] for r in c.execute('SELECT id FROM dtf_local.orders WHERE parent_id=%s', (uid,)).fetchall()]
|
||||
for table in ('movements', 'order_files', 'print_files'):
|
||||
c.execute(f'DELETE FROM dtf_local.{table} WHERE order_id=ANY(%s)', ([uid] + cards,))
|
||||
# A real order's Tiny events stay: its cancellation may not have
|
||||
# reached Tiny yet (Tiny down, or deleted at once), and what was sent
|
||||
# stays on record. A test order never goes to Tiny.
|
||||
if test:
|
||||
c.execute('DELETE FROM dtf_local.outbox WHERE event_key LIKE %s', (f'{uid}:%',))
|
||||
c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (uid,))
|
||||
if not test:
|
||||
@@ -71,6 +77,14 @@ def cancel_order(uid: UUID, body: Resolution, user=Depends(can('cancel'))):
|
||||
if not row:
|
||||
raise HTTPException(404, 'Pedido não encontrado ou já cancelado.')
|
||||
hotfolder.stop(c, uid)
|
||||
# Its proof card not yet answered goes with it: left on the board, it
|
||||
# could still be pulled and printed for an order no one will take.
|
||||
cards = c.execute('''UPDATE dtf_local.orders SET cancelled_at=now(), cancelled_by=%s, cancel_reason=%s,
|
||||
version=version+1, updated_at=now()
|
||||
WHERE parent_id=%s AND cancelled_at IS NULL AND proof_result IS NULL RETURNING id''',
|
||||
(user, f"Pedido #{row['number']} cancelado: {body.note}", uid)).fetchall()
|
||||
for card in cards:
|
||||
hotfolder.stop(c, card['id'])
|
||||
if payments.in_tiny(row):
|
||||
sale = c.execute("SELECT receipt FROM dtf_local.outbox WHERE event_key=%s AND delivered_at IS NOT NULL",
|
||||
(f'{uid}:paid:tiny',)).fetchone()
|
||||
@@ -88,7 +102,7 @@ class MachineChoice(StrictModel):
|
||||
@router.post('/api/operator/orders/{uid}/machine')
|
||||
def choose_machine(uid: UUID, body: MachineChoice, request: Request, user=Depends(can('print'))):
|
||||
"""Exceptional manual choice before printing; the operator's pull is final."""
|
||||
if request.state.operator['role'] == 'operador':
|
||||
if operator_only(request.state.operator, 'print'):
|
||||
raise HTTPException(403, 'A máquina do pedido é a de quem puxa para Imprimindo.')
|
||||
with db.connect() as c:
|
||||
current = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
|
||||
@@ -204,35 +218,9 @@ def proof_answer(uid: UUID, body: ProofAnswer, user=Depends(can('proof'))):
|
||||
c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason)
|
||||
VALUES(%s,'rev','fin',%s,%s)''', (uid, user, label))
|
||||
if body.result == 'ok':
|
||||
# A prova aprovada é a conferência do pai: os arquivos completos
|
||||
# que o Prumo gerou entram como finais, e o pai segue para a fila.
|
||||
# Itens que ainda dependem de preparo manual continuam em Arte
|
||||
# recebida, com o botão de final disponível.
|
||||
if parent['state'] == 'rec' and not parent['snapshot'].get('treatment'):
|
||||
generated = c.execute('''SELECT p.item_index,p.upload_id FROM dtf_local.print_files p
|
||||
WHERE p.order_id=%s AND p.status='ready' AND p.upload_id IS NOT NULL
|
||||
AND NOT EXISTS (SELECT 1 FROM dtf_local.order_files f
|
||||
WHERE f.order_id=p.order_id AND f.item_index=p.item_index
|
||||
AND f.kind='final' AND f.active)
|
||||
ORDER BY p.item_index''', (parent['id'],)).fetchall()
|
||||
for row in generated:
|
||||
c.execute('''INSERT INTO dtf_local.order_files
|
||||
(id,order_id,upload_id,item_index,kind,note,created_by)
|
||||
VALUES(%s,%s,%s,%s,'final',%s,'Prumo')''',
|
||||
(uuid4(), parent['id'], row['upload_id'], row['item_index'],
|
||||
f'Aprovado pela prova do #{card["number"]}'))
|
||||
treatment_clause = f'AND {TREATED}' if parent['snapshot'].get('treatment') else ''
|
||||
ready = parent['state'] == 'rec' and all(c.execute(f'''SELECT 1 FROM dtf_local.order_files f
|
||||
JOIN dtf_local.orders o ON o.id=f.order_id
|
||||
JOIN dtf_local.uploads u ON u.id=f.upload_id
|
||||
WHERE f.order_id=%s AND f.item_index=%s AND {FINAL_OK}
|
||||
{treatment_clause} LIMIT 1''', (parent['id'], i)).fetchone()
|
||||
for i in range(len(parent['snapshot']['items'])))
|
||||
c.execute('''UPDATE dtf_local.orders SET proof_ok_at=now(), proof_ok_by=%s, version=version+1, updated_at=now(),
|
||||
state=CASE WHEN %s THEN 'tra' ELSE state END WHERE id=%s''', (user, ready, parent['id']))
|
||||
if ready:
|
||||
c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason)
|
||||
VALUES(%s,'rec','tra',%s,'Prova OK')''', (parent['id'], user))
|
||||
c.execute('''UPDATE dtf_local.orders SET proof_ok_at=now(), proof_ok_by=%s, version=version+1,
|
||||
updated_at=now() WHERE id=%s''', (user, parent['id']))
|
||||
proof.approve_parent(c, parent, user)
|
||||
elif parent['state'] in ('rec', 'tra') and not parent['cancelled_at']:
|
||||
# Back to Arte recebida with the reason; its final is approved again.
|
||||
c.execute("UPDATE dtf_local.order_files SET active=false WHERE order_id=%s AND kind='final'", (parent['id'],))
|
||||
@@ -404,10 +392,10 @@ def queue_place(uid: UUID, body: QueuePlace, request: Request, user=Depends(oper
|
||||
if not row:
|
||||
raise HTTPException(404, 'Order not found')
|
||||
proof.require_unlocked(c, row)
|
||||
if not may_reorder(request.state.operator['role'], row['state']):
|
||||
if not may_reorder(roles_of(request.state.operator), row['state']):
|
||||
raise HTTPException(403, 'Seu perfil não muda a ordem dos pedidos desta etapa.')
|
||||
mine = request.state.operator['machine']
|
||||
if (request.state.operator['role'] == 'operador' and row['state'] != 'tra'
|
||||
if (reorder_machine_bound(request.state.operator, row['state']) and row['state'] != 'tra'
|
||||
and (not mine or str(row['machine_id'] or '') != mine['id'])):
|
||||
raise HTTPException(403, 'Este pedido é de outra máquina: só quem está nela move o card.')
|
||||
keys = {}
|
||||
@@ -431,7 +419,7 @@ def queue_place(uid: UUID, body: QueuePlace, request: Request, user=Depends(oper
|
||||
|
||||
@router.post('/api/operator/orders/{uid}/move')
|
||||
def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
|
||||
if request.state.operator['role'] not in MOVERS:
|
||||
if not set(roles_of(request.state.operator)) & set(MOVERS):
|
||||
raise HTTPException(403, 'Seu perfil não permite esta ação.')
|
||||
with db.connect() as c:
|
||||
row = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
|
||||
@@ -447,7 +435,7 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
|
||||
back = BACK.get(row['state']) == body.state
|
||||
if body.state not in TRANSITIONS[row['state']] and not back:
|
||||
raise HTTPException(409, f"Não dá para ir de {STATES[row['state']]} para {STATES[body.state]}.")
|
||||
if not may_move(request.state.operator['role'], row['state'], body.state, back):
|
||||
if not may_move(roles_of(request.state.operator), row['state'], body.state, back):
|
||||
raise HTTPException(403, 'Só o Revisor manda o pedido para Finalizado.' if body.state == 'fin' and not back
|
||||
else f"Seu perfil não move pedidos de {STATES[row['state']]} para {STATES[body.state]}.")
|
||||
if body.state == 'cor' and not body.reason.strip():
|
||||
@@ -459,7 +447,9 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
|
||||
account = request.state.operator
|
||||
session_machine = account['machine']
|
||||
pulling = row['state'] == 'tra' and body.state == 'imp'
|
||||
if account['role'] == 'operador':
|
||||
# The operator's machine rules, when only the Operador profile allows the move.
|
||||
bound = machine_bound(account, row['state'], body.state, back)
|
||||
if bound:
|
||||
if not session_machine:
|
||||
raise HTTPException(409, 'Escolha a máquina em que você está.')
|
||||
if not pulling and str(row['machine_id'] or '') != session_machine['id']:
|
||||
@@ -468,7 +458,7 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
|
||||
chosen = body.machine_id or (UUID(session_machine['id']) if session_machine else row['machine_id'])
|
||||
if not chosen:
|
||||
raise HTTPException(409, 'Escolha a máquina que está puxando este card.')
|
||||
if account['role'] == 'operador' and str(chosen) != session_machine['id']:
|
||||
if bound and str(chosen) != session_machine['id']:
|
||||
raise HTTPException(409, f"Você está na {session_machine['name']}: o que você puxa vai para ela.")
|
||||
target = c.execute('SELECT name,products,active FROM dtf_local.machines WHERE id=%s', (chosen,)).fetchone()
|
||||
if not target or not target['active']:
|
||||
@@ -495,16 +485,16 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
|
||||
JOIN dtf_local.uploads u ON u.id=f.upload_id WHERE f.order_id=%s AND {FINAL_OK}''', (uid,)).fetchall()
|
||||
if {r['item_index'] for r in coverage} != set(range(len(row['snapshot']['items']))):
|
||||
raise HTTPException(409, 'Aprove os arquivos finais de todos os itens antes de mandar para Arte conferida.')
|
||||
if row['snapshot'].get('treatment') and not row['parent_id']:
|
||||
if needs_designer(row['snapshot']) and not row['parent_id']:
|
||||
treated = c.execute(f'''SELECT DISTINCT f.item_index FROM dtf_local.order_files f
|
||||
JOIN dtf_local.orders o ON o.id=f.order_id
|
||||
JOIN dtf_local.uploads u ON u.id=f.upload_id
|
||||
WHERE f.order_id=%s AND {FINAL_OK} AND {TREATED}''', (uid,)).fetchall()
|
||||
if {r['item_index'] for r in treated} != set(range(len(row['snapshot']['items']))):
|
||||
raise HTTPException(409, 'Ajuste Fino pago: envie e aprove a arte do Ajuste Fino de todos os itens antes de entrar na fila.')
|
||||
# Two at most per machine in Imprimindo (app/machines.py).
|
||||
if body.state == 'imp' and (name := machines.full(c, row['machine_id'], uid)):
|
||||
raise HTTPException(409, f'{name} já tem {machines.PRINTING_CAP} em Imprimindo.')
|
||||
# The machine's places in Imprimindo (app/machines.py).
|
||||
if body.state == 'imp' and (full := machines.full(c, row['machine_id'], uid)):
|
||||
raise HTTPException(409, f'{full[0]} já tem {full[1]} em Imprimindo.')
|
||||
# A proof card ends with its answer, not in Finalizado; its order waits
|
||||
# for that answer outside the queue (app/proof.py).
|
||||
if row.get('parent_id') and body.state == 'fin':
|
||||
@@ -526,14 +516,40 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
|
||||
if body.state == 'imp' and row['machine_id']:
|
||||
machine_name = (c.execute('SELECT name FROM dtf_local.machines WHERE id=%s',
|
||||
(row['machine_id'],)).fetchone() or {}).get('name')
|
||||
c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason,back,machine)
|
||||
VALUES(%s,%s,%s,%s,%s,%s,%s)''', (uid,row['state'],body.state,user,body.reason,back,machine_name))
|
||||
# A pass from Imprimindo to Revisão keeps the items it printed, when
|
||||
# only some went again (machine_log counts their metres).
|
||||
printed_items = row.get('print_items') if row['state'] == 'imp' and body.state == 'rev' and not back else None
|
||||
c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason,back,machine,items)
|
||||
VALUES(%s,%s,%s,%s,%s,%s,%s,%s)''', (uid,row['state'],body.state,user,body.reason,back,machine_name,printed_items))
|
||||
# Back in the queue after a print: only the items whose final changed
|
||||
# go to the machine again, unless the team already chose (#105).
|
||||
if body.state == 'tra' and not back and row.get('print_items') is None:
|
||||
taken = hotfolder.printed(c, [uid]).get(uid)
|
||||
if taken:
|
||||
finals = [(r['item_index'], r['upload_id']) for r in c.execute('''SELECT item_index,upload_id
|
||||
FROM dtf_local.order_files WHERE order_id=%s AND kind='final' AND active''', (uid,)).fetchall()]
|
||||
default = hotfolder.reprint_default(finals, taken, len(row['snapshot']['items']))
|
||||
if default:
|
||||
c.execute('UPDATE dtf_local.orders SET print_items=%s WHERE id=%s', (default, uid))
|
||||
# Printed (its items kept on the movement above) or finished: the
|
||||
# choice is done with, and the next pass to the queue works it out
|
||||
# again from what changed since.
|
||||
if printed_items is not None or (body.state == 'fin' and not back):
|
||||
c.execute('UPDATE dtf_local.orders SET print_items=NULL WHERE id=%s', (uid,))
|
||||
# Back to Imprimindo from Revisão (a mistaken move undone): the items
|
||||
# that pass printed are the choice again, and only what Flexi had not
|
||||
# taken goes back to the folder, never the whole order.
|
||||
if body.state == 'imp' and back:
|
||||
undone = c.execute('''SELECT items FROM dtf_local.movements WHERE order_id=%s
|
||||
AND from_state='imp' AND to_state='rev' AND NOT back ORDER BY id DESC LIMIT 1''', (uid,)).fetchone()
|
||||
if undone and undone['items'] is not None:
|
||||
c.execute('UPDATE dtf_local.orders SET print_items=%s WHERE id=%s', (undone['items'], uid))
|
||||
# Pulled to Imprimindo, its files go to its machine's hot folder; out
|
||||
# of it, what Flexi did not take leaves (item 10).
|
||||
if row['state'] == 'imp':
|
||||
hotfolder.stop(c, uid)
|
||||
if body.state == 'imp':
|
||||
hotfolder.start(c, uid)
|
||||
(hotfolder.resume if back else hotfolder.start)(c, uid)
|
||||
# A pickup reaching Finalizado has its receipt due (item 14), once.
|
||||
due = body.state == 'fin' and not back and receipt.is_pickup(row['snapshot'])
|
||||
changed = c.execute('''UPDATE dtf_local.orders SET state=%s, version=version+1, updated_at=now(),
|
||||
@@ -542,23 +558,38 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
|
||||
WHERE id=%s RETURNING *''', (body.state, body.state, due, uid)).fetchone()
|
||||
# Entering the queue (Arte conferida) is Tiny's "Preparando envio";
|
||||
# Finalizado its "Pronto para envio" (Dropstar's flow, 2026-10-23).
|
||||
events = {'tra':'production_started','cor':'correction_needed','fin':'ready'}
|
||||
if body.state in events and not back and payments.in_tiny(row):
|
||||
# "Production started" and "ready" reach the customer once per order,
|
||||
# even if a mistaken move is undone and made again. Each correction
|
||||
# is a new request, so it keeps one message per movement.
|
||||
once = body.state in ('tra','fin')
|
||||
event = {'order_id':str(uid), 'number':row['number'], 'event':events[body.state], 'reason':body.reason,
|
||||
'customer_path': f'/portal.html?order={uid}'}
|
||||
# Tiny needs the order (customer, pickup or delivery) and, once the
|
||||
# sale reached it, its id, to set the situação without a search.
|
||||
sale = c.execute("SELECT receipt FROM dtf_local.outbox WHERE event_key=%s AND delivered_at IS NOT NULL",
|
||||
(f'{uid}:paid:tiny',)).fetchone()
|
||||
tiny = {**event, 'order': row['snapshot'], 'tiny_id': ((sale or {}).get('receipt') or {}).get('tiny_id')}
|
||||
key = f'{uid}:{events[body.state]}:tiny' if once else f'{uid}:{changed["version"]}:tiny'
|
||||
enqueue(c, key, 'tiny', tiny)
|
||||
if not back:
|
||||
payments.stage_event(c, row, body.state, body.reason, changed['version'])
|
||||
return changed
|
||||
|
||||
class PrintItems(StrictModel):
|
||||
items: list[int] = Field(min_length=1, max_length=200)
|
||||
|
||||
|
||||
@router.post('/api/operator/orders/{uid}/print-items')
|
||||
def choose_print_items(uid: UUID, body: PrintItems, user=Depends(can('produce'))):
|
||||
"""Which items go to the machine this time (Marcus, 2026-11-26, #105):
|
||||
a reprint sends only those. Every item: all go, as on the first print."""
|
||||
with db.connect() as c:
|
||||
row = c.execute('SELECT id,number,state,snapshot,cancelled_at FROM dtf_local.orders WHERE id=%s FOR UPDATE',
|
||||
(uid,)).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(404, 'Pedido não encontrado.')
|
||||
if row['cancelled_at'] or row['state'] not in ('rec', 'tra', 'cor'):
|
||||
raise HTTPException(409, 'Os itens que vão para a máquina são escolhidos antes de Imprimindo.')
|
||||
count = len(row['snapshot']['items'])
|
||||
items = sorted(set(body.items))
|
||||
if any(i < 0 or i >= count for i in items):
|
||||
raise HTTPException(422, 'Item do pedido inválido.')
|
||||
# Every item is kept as the whole list, not NULL: NULL is "not chosen
|
||||
# yet", which the pass to the queue would replace with the suggestion.
|
||||
chosen = items
|
||||
c.execute('UPDATE dtf_local.orders SET print_items=%s, version=version+1, updated_at=now() WHERE id=%s',
|
||||
(chosen, uid))
|
||||
audit('order_print_items', order=row['number'], items=','.join(str(i + 1) for i in items), operator=user)
|
||||
return {'ok': True, 'print_items': chosen}
|
||||
|
||||
|
||||
@router.post('/api/operator/orders/{uid}/print-files')
|
||||
def regenerate(uid: UUID, user=Depends(can('produce'))):
|
||||
"""Queue generation again for items that failed or went to manual preparation,
|
||||
@@ -585,3 +616,42 @@ def regenerate(uid: UUID, user=Depends(can('produce'))):
|
||||
queue_print_files(c, uid, len(row['snapshot']['items']), only_missing=True)
|
||||
audit('print_file_requeued', order=str(uid), operator=user, c=c)
|
||||
return c.execute('SELECT * FROM dtf_local.print_files WHERE order_id=%s ORDER BY item_index', (uid,)).fetchall()
|
||||
|
||||
|
||||
@router.post('/api/operator/orders/{uid}/print-files/again')
|
||||
def regenerate_ready(uid: UUID, user=Depends(can('produce'))):
|
||||
"""Generate the print files again although they are ready, for the part
|
||||
size of now (PRINT_PART_CM): a 15 m part is more than the FlexiPRINT
|
||||
opens (order #36, 2026-11-17). The finals that were the generated files
|
||||
stop counting, and an order in Arte conferida or Imprimindo goes back to
|
||||
Arte recebida, where the new files are approved again; from Imprimindo
|
||||
what Flexi has not taken leaves the hot folder (app/hotfolder.py)."""
|
||||
with db.connect() as c:
|
||||
row = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(404, 'Pedido não encontrado.')
|
||||
if row['cancelled_at']:
|
||||
raise HTTPException(409, 'Pedido cancelado.')
|
||||
proof.require_unlocked(c, row)
|
||||
if row['state'] not in ('rec', 'tra', 'imp'):
|
||||
raise HTTPException(409, 'O arquivo é gerado de novo até Imprimindo.')
|
||||
if c.execute("SELECT 1 FROM dtf_local.order_files WHERE order_id=%s AND kind='correction' LIMIT 1",
|
||||
(uid,)).fetchone():
|
||||
raise HTTPException(409, 'O cliente mandou uma correção: o arquivo final é preparado à mão.')
|
||||
c.execute('''UPDATE dtf_local.order_files f SET active=false
|
||||
WHERE f.order_id=%s AND f.kind='final' AND f.active AND (
|
||||
EXISTS (SELECT 1 FROM dtf_local.print_parts p WHERE p.order_id=f.order_id AND p.upload_id=f.upload_id)
|
||||
OR EXISTS (SELECT 1 FROM dtf_local.print_files p WHERE p.order_id=f.order_id AND p.upload_id=f.upload_id))''',
|
||||
(uid,))
|
||||
# The new version tells the board and the folders the files changed;
|
||||
# every file is new, so any choice of items to reprint is over.
|
||||
c.execute('''UPDATE dtf_local.orders SET state='rec', print_items=NULL, version=version+1, updated_at=now()
|
||||
WHERE id=%s''', (uid,))
|
||||
if row['state'] == 'imp':
|
||||
hotfolder.stop(c, uid)
|
||||
if row['state'] != 'rec':
|
||||
c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason,back)
|
||||
VALUES(%s,%s,'rec',%s,'Arquivo gerado de novo',true)''', (uid, row['state'], user))
|
||||
requeue_print_files(c, uid, len(row['snapshot']['items']))
|
||||
audit('print_file_regenerated', order=str(uid), operator=user)
|
||||
return {'ok': True}
|
||||
|
||||
@@ -136,6 +136,11 @@ def register_order(uid: UUID, body: PaidOutside, user=Depends(can('enter'))):
|
||||
'status': 'paid', 'total_cents': quote['approved']['total_cents'], 'operator': user}
|
||||
order, created = payments.create_order(c, quote, receipt, body.origin)
|
||||
if not created:
|
||||
# A test order holds the quote too (orders.quote_id is unique): say so,
|
||||
# and how to free it (Sentry DTF-WEB-D).
|
||||
if payments.is_test(order):
|
||||
raise HTTPException(409, f"Esta cotação já virou o pedido de teste #{order['number']}. "
|
||||
'Exclua o pedido de teste para registrar o pagamento.')
|
||||
raise HTTPException(409, f"Esta cotação já virou o pedido #{order['number']}.")
|
||||
audit('manual_order_registered', order=str(order['id']), origin=body.origin, operator=user)
|
||||
return order
|
||||
|
||||
@@ -5,6 +5,8 @@ from decimal import Decimal
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
|
||||
from ... import machines, payments, unpaid
|
||||
from ...machine_stats import pace
|
||||
from ...cart_pricing import designer_hours
|
||||
from ...core import db
|
||||
from ...core.auth import operator
|
||||
from .common import ORIGINS, REAL_ORDER, TREATED, person
|
||||
@@ -106,7 +108,7 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start
|
||||
late_rows = c.execute(f'''SELECT s.state,
|
||||
extract(epoch FROM s.until-s.at) - {waited('s.id', 's.at', 's.until')} AS seconds,
|
||||
(s.until AT TIME ZONE 'America/Sao_Paulo')::date AS day,
|
||||
o.snapshot->'treatment' AS treatment
|
||||
o.snapshot->'treatment' AS treatment, o.snapshot->'redesign' AS redesign
|
||||
FROM ({spans}) s LEFT JOIN dtf_local.orders o ON o.id=s.id WHERE s.until IS NOT NULL''',
|
||||
period + period).fetchall()
|
||||
printed = machine_output(c, start, end)
|
||||
@@ -214,9 +216,8 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start
|
||||
if not limit:
|
||||
continue
|
||||
hours = float(limit['hours'])
|
||||
treatment = row.get('treatment') or {}
|
||||
if row['state'] == 'rec' and treatment:
|
||||
hours += float(treatment.get('hours', 24))
|
||||
if row['state'] == 'rec':
|
||||
hours += designer_hours({'treatment': row.get('treatment'), 'redesign': row.get('redesign')})
|
||||
if row['seconds'] > hours * 3600:
|
||||
late[row['state']]['count'] += 1
|
||||
if row['day'] == today:
|
||||
@@ -336,7 +337,7 @@ def machine_output(c, start, end):
|
||||
made = float(sum(row['metres'] for row in mine))
|
||||
result.append({'id': m['id'], 'name': m['name'], 'active': m['active'], 'orders': len(mine),
|
||||
'metres': made, 'printing_hours': round(hours_in, 2),
|
||||
'metres_per_hour': round(made / hours_in, 1) if hours_in > 0 else None,
|
||||
'metres_per_hour': pace(made, hours_in),
|
||||
'last_finished': last[m['id']].isoformat() if m['id'] in last else None,
|
||||
'now': {state: m['states'].get(state, 0) for state in ('tra', 'imp')}})
|
||||
loose = [row for row in done if row['machine_id'] is None]
|
||||
|
||||
@@ -11,7 +11,7 @@ import httpx
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from psycopg.types.json import Jsonb
|
||||
|
||||
from .. import payment_messages as messages, payments
|
||||
from .. import coupons, payment_messages as messages, payments
|
||||
from ..core import db
|
||||
from ..core.auth import audit, client_ip, owner, rate_limit
|
||||
from ..core.models import PaymentIntent
|
||||
@@ -104,6 +104,15 @@ def intent(body: PaymentIntent, session_id=Depends(owner)):
|
||||
raise HTTPException(404 if 'not found' in str(refusal) else 409, messages.quote_refusal(refusal))
|
||||
if c.execute('SELECT 1 FROM dtf_local.orders WHERE quote_id=%s', (body.quote_id,)).fetchone():
|
||||
raise HTTPException(409, 'Este pedido já foi pago.')
|
||||
# A coupon's limits are spent at payment (app/coupons.py): one used up,
|
||||
# paused or ended since the cart was made no longer gives its discount.
|
||||
coupon = quote['approved'].get('coupon')
|
||||
if coupon:
|
||||
try:
|
||||
coupons.check(c, coupon['code'], (quote['approved'].get('customer') or {}).get('cnpj'),
|
||||
quote['approved']['items'])
|
||||
except HTTPException as refusal:
|
||||
raise HTTPException(409, f'{refusal.detail} Monte o carrinho de novo, sem o cupom, para pagar.')
|
||||
# Never charge for files that are gone: an unpaid cart's files are
|
||||
# removed after a while. A payment under way keeps them a day longer,
|
||||
# time enough for the provider's notice to become the order.
|
||||
@@ -113,7 +122,8 @@ def intent(body: PaymentIntent, session_id=Depends(owner)):
|
||||
if live != len(set(uploads)):
|
||||
raise HTTPException(410, 'Os arquivos deste pedido expiraram porque ele não foi pago a tempo. '
|
||||
'Monte o pedido de novo para pagar.')
|
||||
payments.hold_uploads(c, uploads, '1 day')
|
||||
# A card may sit in review for days (payments.CARD_REVIEW_HOURS).
|
||||
payments.hold_uploads(c, uploads, f'{payments.CARD_REVIEW_HOURS} hours' if body.method.type == 'card' else '1 day')
|
||||
# Never a second charge: an approved payment is waiting for its
|
||||
# notification to become the order, and a card in review may still be.
|
||||
# A card waiting for the bank's confirmation (3-D Secure) blocks only
|
||||
|
||||
@@ -13,7 +13,7 @@ from ..core import db
|
||||
from ..core.auth import owner
|
||||
from ..core.models import QuoteRequest
|
||||
from .. import quote_review
|
||||
from ..grade_check import Files, mismatch, resolution_issue, source_dpi
|
||||
from ..grade_check import Files, mismatch, proportion_issue, resolution_issue, source_dpi
|
||||
from ..runtime import freight, payment, quote_view, require_delivery_available, storage, upload_row
|
||||
from ..scanning import require_clean
|
||||
|
||||
@@ -57,7 +57,8 @@ def create_quote(body: QuoteRequest, session_id=Depends(owner)):
|
||||
cart = cart_pricing.price_cart(
|
||||
c, draft['items'], names, coupon_code=code,
|
||||
customer_document=body.customer.cnpj,
|
||||
wants_treatment=draft.get('treatment', False))
|
||||
wants_treatment=draft.get('treatment', False),
|
||||
wants_redesign=draft.get('redesign', []))
|
||||
if reason is not None:
|
||||
freight.quote(body.freight.service, body.freight.postal_code,
|
||||
sum(Decimal(i['billed_metres']) for i in cart['items']),
|
||||
@@ -78,7 +79,7 @@ def create_quote(body: QuoteRequest, session_id=Depends(owner)):
|
||||
dpis.append(dpi)
|
||||
if dpis:
|
||||
draft_item['source_dpi'] = round(min(dpis))
|
||||
issue = resolution_issue(files, draft['items'], rows)
|
||||
issue = proportion_issue(files, draft['items'], rows) or resolution_issue(files, draft['items'], rows)
|
||||
if issue:
|
||||
raise HTTPException(422, issue)
|
||||
note = mismatch(files, draft['items'], rows) if reason is None else None
|
||||
|
||||
@@ -95,8 +95,11 @@ def toggle_product(product: str, body: SiteProductToggle, user=Depends(can('mana
|
||||
def schedule_price(product: str, body: SitePriceNew, user=Depends(can('manage'))):
|
||||
if product not in catalog.PRODUCTS:
|
||||
raise HTTPException(404, 'Produto não encontrado.')
|
||||
if product != 'tratamento' and body.unit_cents <= 0:
|
||||
if product not in ('tratamento', 'redesenho') and body.unit_cents <= 0:
|
||||
raise HTTPException(422, 'O preço precisa ser maior que zero.')
|
||||
# Redesenho is one price per art: its batch band belongs to the basic only.
|
||||
if product == 'redesenho' and body.bands:
|
||||
raise HTTPException(422, 'O Redesenho não tem faixas de preço.')
|
||||
bands = checked_bands(product, body.bands)
|
||||
now = datetime.now(timezone.utc)
|
||||
starts_at = body.starts_at or now
|
||||
|
||||
@@ -16,7 +16,7 @@ router = APIRouter()
|
||||
|
||||
CATALOG = {
|
||||
'subindo': 'Subindo a arte pelo celular',
|
||||
'nota': 'O que é a nota da arte — e o que ela não é',
|
||||
'nota': 'O que a nota da arte mostra',
|
||||
'png': 'Por que PNG com fundo transparente',
|
||||
'avulsas': 'Montando artes avulsas e vendo a folha ao vivo',
|
||||
'retirada': 'Retirada em Franca em 24 h',
|
||||
@@ -97,6 +97,14 @@ def update_video(video_id: str, body: VideoUpdate, user=Depends(can('manage'))):
|
||||
with db.connect() as c:
|
||||
previous = c.execute('SELECT upload_id,captions_id,video_key,captions_key FROM dtf_local.site_videos WHERE id=%s FOR UPDATE',
|
||||
(video_id,)).fetchone() or {}
|
||||
# One floating video per product page; checked before any copy, and
|
||||
# the refusal names the video that holds the product (DTF-WEB-G).
|
||||
if body.enabled and body.product:
|
||||
other = c.execute('SELECT id FROM dtf_local.site_videos WHERE id<>%s AND product=%s AND enabled',
|
||||
(video_id, body.product)).fetchone()
|
||||
if other:
|
||||
raise HTTPException(409, f'Este produto já tem o vídeo "{CATALOG.get(other["id"], other["id"])}" '
|
||||
'publicado. Tire esse do Site antes, ou escolha outro lugar.')
|
||||
identity = operator_identity(user)
|
||||
keys = []
|
||||
for uid, expected, previous_id, previous_key in (
|
||||
@@ -113,11 +121,6 @@ def update_video(video_id: str, body: VideoUpdate, user=Depends(can('manage'))):
|
||||
CopySource={'Bucket': storage.bucket, 'Key': upload['object_key']},
|
||||
Key=key, ContentType=mime, MetadataDirective='REPLACE')
|
||||
keys.append(key)
|
||||
if body.enabled and body.product:
|
||||
other = c.execute('SELECT id FROM dtf_local.site_videos WHERE id<>%s AND product=%s AND enabled',
|
||||
(video_id, body.product)).fetchone()
|
||||
if other:
|
||||
raise HTTPException(409, 'Já existe um vídeo flutuante ativo para este produto.')
|
||||
c.execute('''INSERT INTO dtf_local.site_videos(id,upload_id,captions_id,video_key,captions_key,product,enabled,updated_by)
|
||||
VALUES(%s,%s,%s,%s,%s,%s,%s,%s)
|
||||
ON CONFLICT (id) DO UPDATE SET upload_id=EXCLUDED.upload_id,captions_id=EXCLUDED.captions_id,
|
||||
|
||||
@@ -10,7 +10,7 @@ from psycopg.types.json import Jsonb
|
||||
|
||||
from .. import payments, quote_review
|
||||
from ..core import db
|
||||
from ..core.auth import audit, can
|
||||
from ..core.auth import audit, can, roles_of
|
||||
from ..core.models import (Customer, Freight, MontadorOrder, QuoteRequest, StampBrand,
|
||||
StampSizeTable, UploadStart)
|
||||
from ..runtime import operator_identity
|
||||
@@ -18,7 +18,8 @@ from .uploads import begin_upload
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
CODE = re.compile(r'^[A-Za-z0-9_-]{1,40}$')
|
||||
# Dropstar's codes carry dots (NX.226); not as the first character.
|
||||
CODE = re.compile(r'^[A-Za-z0-9_-][A-Za-z0-9._-]{0,39}$')
|
||||
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
|
||||
@@ -116,8 +117,8 @@ def montador_order(body: MontadorOrder, request: Request, user=Depends(can('asse
|
||||
customer, origin atendimento, invoiced and sent to Tiny), at the Site's
|
||||
table price. A Venda is picked up, travels with a clothing order or ships
|
||||
with the Site's freight; approve quotes the freight again."""
|
||||
role = request.state.operator['role']
|
||||
if body.kind not in MONTADOR_KINDS.get(role, set()):
|
||||
kinds = set().union(*(MONTADOR_KINDS.get(r, set()) for r in roles_of(request.state.operator)))
|
||||
if body.kind not in kinds:
|
||||
raise HTTPException(403, 'Seu perfil não permite este tipo de pedido.')
|
||||
with db.connect() as c:
|
||||
if body.kind == 'interno':
|
||||
@@ -148,6 +149,13 @@ def montador_order(body: MontadorOrder, request: Request, user=Depends(can('asse
|
||||
# card and in Tiny's internal note.
|
||||
approved = {**approved, 'kind': body.kind,
|
||||
**({'with_order': body.with_order} if body.with_order else {})}
|
||||
# A Venda's seller in Tiny is who assembled it, when their user
|
||||
# names one (Marcus, 2026-11-17, app/tiny.py order_payload).
|
||||
if body.kind == 'venda':
|
||||
seller = c.execute('''SELECT tiny_seller_id AS id, tiny_seller_name AS name
|
||||
FROM dtf_local.operators WHERE email=%s AND tiny_seller_id IS NOT NULL''', (user,)).fetchone()
|
||||
if seller:
|
||||
approved['seller'] = dict(seller)
|
||||
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()
|
||||
|
||||
@@ -24,6 +24,10 @@ router = APIRouter()
|
||||
# retrying must fit. The per-source bucket bounds abuse, not a real order.
|
||||
UPLOAD_START_LIMIT = 1000
|
||||
UPLOAD_START_IP_LIMIT = 3000
|
||||
# A reservation counts toward the pending cap while its upload is alive: begun
|
||||
# or given a part in the last 20 minutes (a part is 8 MB). One left behind by an
|
||||
# interrupted upload stops holding a place long before its hour (DTF-WEB-14).
|
||||
PENDING_IDLE_MINUTES = 20
|
||||
|
||||
|
||||
def upload_ip_limit(request: Request):
|
||||
@@ -44,9 +48,10 @@ def begin_upload(body: UploadStart, session_id=Depends(owner), _source=Depends(u
|
||||
c.execute('SELECT pg_advisory_xact_lock(804208)')
|
||||
usage = c.execute('''SELECT COALESCE(sum(size),0) AS total,
|
||||
COALESCE(sum(size) FILTER(WHERE owner=%s),0) AS owned,
|
||||
count(*) FILTER(WHERE owner=%s AND NOT complete) AS pending
|
||||
count(*) FILTER(WHERE owner=%s AND NOT complete
|
||||
AND expires_at > now() + interval '1 hour' - make_interval(mins => %s)) AS pending
|
||||
FROM dtf_local.uploads WHERE purged_at IS NULL''',
|
||||
(session_id,session_id)).fetchone()
|
||||
(session_id,session_id,PENDING_IDLE_MINUTES)).fetchone()
|
||||
storage_full = (usage['total']+body.size > int(os.environ.get('STORAGE_QUOTA_BYTES','53687091200')) or
|
||||
usage['owned']+body.size > int(os.environ.get('OWNER_UPLOAD_QUOTA_BYTES','10737418240')))
|
||||
pending_full = usage['pending'] >= int(os.environ.get('MAX_PENDING_UPLOADS','30'))
|
||||
|
||||
120
app/api/users.py
120
app/api/users.py
@@ -16,23 +16,37 @@ from pydantic import Field, field_validator
|
||||
|
||||
from .. import machines, mail, observability
|
||||
from ..core import db
|
||||
from ..core.auth import (CAPABILITIES, MACHINE_QUESTION, audit, can, may_move, may_reorder, password_hash,
|
||||
password_matches, signed_in)
|
||||
from ..core.auth import (CAPABILITIES, audit, can, has, machine_bound, machine_question, may_move, may_reorder,
|
||||
password_hash, password_matches, roles_of, signed_in)
|
||||
from ..core.models import StrictModel
|
||||
from ..runtime import BACK, ENVIRONMENT, STATES, TRANSITIONS
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
class TinySeller(StrictModel):
|
||||
id: int = Field(gt=0)
|
||||
name: str = Field(min_length=1, max_length=120)
|
||||
|
||||
|
||||
ASSIGNABLE = Literal['admin', 'gestao', 'designer', 'operador', 'revisor', 'vendedor', 'financeiro', 'expedicao']
|
||||
|
||||
|
||||
class UserIn(StrictModel):
|
||||
# The profiles an administrator may give; superadmin only comes from the console.
|
||||
name: str = Field(min_length=1, max_length=80)
|
||||
email: str = Field(min_length=3, max_length=254)
|
||||
role: Literal['admin', 'gestao', 'designer', 'operador', 'revisor', 'vendedor', 'financeiro', 'expedicao']
|
||||
# The main profile, and every other one the user has (Marcus, 2026-11-26):
|
||||
# what they may do is the sum.
|
||||
role: ASSIGNABLE
|
||||
roles: list[ASSIGNABLE] = Field(default_factory=list, max_length=8)
|
||||
password: str | None = Field(default=None, min_length=8, max_length=128)
|
||||
active: bool = True
|
||||
# No longer used: an operator's machine is the one chosen after signing in
|
||||
# (item 12). Kept so a page loaded before still saves.
|
||||
machines: list[UUID] = Field(default_factory=list, max_length=50)
|
||||
# The Tiny seller this user is (app/tiny.py list_sellers): a Venda they
|
||||
# assemble reaches Tiny with it. None: no seller.
|
||||
tiny_seller: TinySeller | None = None
|
||||
|
||||
@field_validator('email')
|
||||
@classmethod
|
||||
@@ -42,6 +56,10 @@ class UserIn(StrictModel):
|
||||
raise ValueError('Informe um e-mail válido.')
|
||||
return value
|
||||
|
||||
def profiles(self):
|
||||
"""The main profile first, then the others, each once."""
|
||||
return [self.role] + [r for r in dict.fromkeys(self.roles) if r != self.role]
|
||||
|
||||
|
||||
class MachineIn(StrictModel):
|
||||
name: str = Field(min_length=1, max_length=60)
|
||||
@@ -49,11 +67,18 @@ class MachineIn(StrictModel):
|
||||
active: bool = True
|
||||
# Metres open before the next order goes to another machine; None is no limit.
|
||||
limit_metres: Decimal | None = Field(default=None, gt=0, le=99999, decimal_places=1)
|
||||
# Orders at once in Imprimindo and files in its hot folder (app/machines.py);
|
||||
# None keeps what it has, or machines.DEFAULT_PLACES for a new one.
|
||||
places: int | None = Field(default=None, ge=1, le=machines.MAX_PLACES)
|
||||
# No longer used (item 12): who is on a machine is who chose it after
|
||||
# signing in. Kept so a page loaded before still saves.
|
||||
operators: list[UUID] | None = Field(default=None, max_length=200)
|
||||
|
||||
|
||||
class MachinePlaces(StrictModel):
|
||||
places: int = Field(ge=1, le=machines.MAX_PLACES)
|
||||
|
||||
|
||||
class PasswordChange(StrictModel):
|
||||
current: str = Field(min_length=1, max_length=128)
|
||||
new: str = Field(min_length=8, max_length=128)
|
||||
@@ -65,19 +90,22 @@ def me(request: Request):
|
||||
their profile makes (forward, and the step back) and the columns whose
|
||||
order they set."""
|
||||
account = signed_in(request)
|
||||
role = account['role']
|
||||
moves = [[a, b] for a, nexts in TRANSITIONS.items() for b in nexts if may_move(role, a, b)]
|
||||
moves += [[a, b] for a, b in BACK.items() if may_move(role, a, b, back=True)]
|
||||
return {'email': account['email'], 'name': account['name'], 'role': role,
|
||||
role, roles = account['role'], roles_of(account)
|
||||
moves = [[a, b] for a, nexts in TRANSITIONS.items() for b in nexts if may_move(roles, a, b)]
|
||||
moves += [[a, b] for a, b in BACK.items() if may_move(roles, a, b, back=True)]
|
||||
return {'email': account['email'], 'name': account['name'], 'role': role, 'roles': list(roles),
|
||||
# Public by design: the Kanban browser initialises Sentry with these.
|
||||
'sentry_dsn_web': os.environ.get('SENTRY_DSN_WEB', '').strip(),
|
||||
'sentry_environment': os.environ.get('SENTRY_ENVIRONMENT') or ENVIRONMENT,
|
||||
'sentry_release': observability.release() or '',
|
||||
# The machine this session is on, and whether to ask (item 12).
|
||||
'machine': account['machine'], 'machine_question': MACHINE_QUESTION.get(role),
|
||||
'machine': account['machine'], 'machine_question': machine_question(account),
|
||||
'machine_answered': account['machine_answered'],
|
||||
'can': sorted(cap for cap, roles in CAPABILITIES.items() if role in roles),
|
||||
'moves': moves, 'reorder': [state for state in STATES if may_reorder(role, state)]}
|
||||
'can': sorted(cap for cap in CAPABILITIES if has(account, cap)),
|
||||
'moves': moves, 'reorder': [state for state in STATES if may_reorder(roles, state)],
|
||||
# The moves only the Operador profile allows: kept to the session's machine.
|
||||
'machine_moves': [[a, b] for a, b in moves
|
||||
if machine_bound(account, a, b, back=BACK.get(a) == b)]}
|
||||
|
||||
|
||||
class MachineAnswer(StrictModel):
|
||||
@@ -94,7 +122,7 @@ def choose_session_machine(body: MachineAnswer, request: Request):
|
||||
person runs two machines from two computers. Someone else already on it is
|
||||
a warning, not a refusal: shifts overlap for a few minutes."""
|
||||
account = signed_in(request)
|
||||
question = MACHINE_QUESTION.get(account['role'])
|
||||
question = machine_question(account)
|
||||
if not question:
|
||||
raise HTTPException(403, 'Seu perfil não trabalha em máquina.')
|
||||
with db.connect() as c:
|
||||
@@ -133,7 +161,8 @@ def change_password(body: PasswordChange, request: Request):
|
||||
|
||||
def user_rows(c):
|
||||
"""Every account, with the machines its open sessions are on now (item 12)."""
|
||||
rows = c.execute('''SELECT o.id,o.email,o.name,o.role,o.active,o.last_login_at,o.created_at,
|
||||
rows = c.execute('''SELECT o.id,o.email,o.name,o.role,o.roles,o.active,o.last_login_at,o.created_at,
|
||||
o.tiny_seller_id,o.tiny_seller_name,
|
||||
COALESCE(array_agg(DISTINCT s.machine_id) FILTER (WHERE s.machine_id IS NOT NULL), '{}') AS machines,
|
||||
-- The last use of any open session: "Ativo agora" in Usuários.
|
||||
(SELECT max(x.seen_at) FROM dtf_local.operator_sessions x
|
||||
@@ -143,6 +172,9 @@ def user_rows(c):
|
||||
GROUP BY o.id ORDER BY o.active DESC, o.name, o.email''').fetchall()
|
||||
for row in rows:
|
||||
row['machines'] = [str(m) for m in row['machines']]
|
||||
row['roles'] = list(roles_of(row))
|
||||
seller_id, seller_name = row.pop('tiny_seller_id'), row.pop('tiny_seller_name')
|
||||
row['tiny_seller'] = {'id': seller_id, 'name': seller_name} if seller_id else None
|
||||
return rows
|
||||
|
||||
|
||||
@@ -170,10 +202,12 @@ def create_user(body: UserIn, request: Request, user=Depends(can('users'))):
|
||||
with db.connect() as c:
|
||||
if c.execute('SELECT 1 FROM dtf_local.operators WHERE email=%s', (body.email,)).fetchone():
|
||||
raise HTTPException(409, 'Já existe um usuário com este e-mail.')
|
||||
c.execute('''INSERT INTO dtf_local.operators(id,email,name,password_hash,role,active)
|
||||
VALUES(%s,%s,%s,%s,%s,%s)''', (uid, body.email, body.name.strip(), password_hash(body.password),
|
||||
body.role, body.active))
|
||||
audit('operator_created', operator=user, account=body.email, role=body.role)
|
||||
seller = body.tiny_seller
|
||||
c.execute('''INSERT INTO dtf_local.operators(id,email,name,password_hash,role,roles,active,tiny_seller_id,tiny_seller_name)
|
||||
VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s)''', (uid, body.email, body.name.strip(), password_hash(body.password),
|
||||
body.role, body.profiles(), body.active,
|
||||
seller and seller.id, seller and seller.name))
|
||||
audit('operator_created', operator=user, account=body.email, role='/'.join(body.profiles()))
|
||||
return {'id': str(uid)}
|
||||
|
||||
|
||||
@@ -184,13 +218,16 @@ def update_user(uid: UUID, body: UserIn, request: Request, user=Depends(can('use
|
||||
row = target(c, uid, request)
|
||||
# A superadmin keeps that profile: the form offers only the assignable ones.
|
||||
role = row['role'] if row['role'] == 'superadmin' else body.role
|
||||
if str(row['id']) == str(me_['id']) and (not body.active or role != row['role']):
|
||||
roles = list(roles_of(row)) if row['role'] == 'superadmin' else body.profiles()
|
||||
if str(row['id']) == str(me_['id']) and (not body.active or role != row['role'] or roles != list(roles_of(row))):
|
||||
raise HTTPException(409, 'Você não pode desativar a sua conta nem mudar o seu perfil.')
|
||||
if body.email != row['email'] and c.execute(
|
||||
'SELECT 1 FROM dtf_local.operators WHERE email=%s AND id<>%s', (body.email, uid)).fetchone():
|
||||
raise HTTPException(409, 'Já existe um usuário com este e-mail.')
|
||||
c.execute('UPDATE dtf_local.operators SET name=%s,email=%s,role=%s,active=%s WHERE id=%s',
|
||||
(body.name.strip(), body.email, role, body.active, uid))
|
||||
seller = body.tiny_seller
|
||||
c.execute('''UPDATE dtf_local.operators SET name=%s,email=%s,role=%s,roles=%s,active=%s,tiny_seller_id=%s,
|
||||
tiny_seller_name=%s WHERE id=%s''', (body.name.strip(), body.email, role, roles, body.active,
|
||||
seller and seller.id, seller and seller.name, uid))
|
||||
if body.password:
|
||||
c.execute('UPDATE dtf_local.operators SET password_hash=%s WHERE id=%s', (password_hash(body.password), uid))
|
||||
if body.email != row['email']:
|
||||
@@ -198,7 +235,7 @@ def update_user(uid: UUID, body: UserIn, request: Request, user=Depends(can('use
|
||||
if not body.active or body.password:
|
||||
# Disabled, or given a new password: whoever was signed in signs in again.
|
||||
c.execute('DELETE FROM dtf_local.operator_sessions WHERE username=%s', (body.email,))
|
||||
audit('operator_updated', operator=user, account=body.email, role=role, active=body.active,
|
||||
audit('operator_updated', operator=user, account=body.email, role='/'.join(roles), active=body.active,
|
||||
password_reset=bool(body.password))
|
||||
return {'ok': True}
|
||||
|
||||
@@ -232,10 +269,14 @@ def list_machines(user=Depends(can('view'))):
|
||||
def create_machine(body: MachineIn, user=Depends(can('users'))):
|
||||
mid = uuid4()
|
||||
with db.connect() as c:
|
||||
if c.execute('SELECT 1 FROM dtf_local.machines WHERE lower(name)=lower(%s)', (body.name.strip(),)).fetchone():
|
||||
raise HTTPException(409, 'Já existe uma máquina com este nome.')
|
||||
c.execute('INSERT INTO dtf_local.machines(id,name,products,active,limit_metres) VALUES(%s,%s,%s,%s,%s)',
|
||||
(mid, body.name.strip(), sorted(set(body.products)), body.active, body.limit_metres))
|
||||
# A machine's hot folder is its first name, for good: no other machine
|
||||
# may be called that, or two would share one folder.
|
||||
if c.execute('SELECT 1 FROM dtf_local.machines WHERE lower(name)=lower(%s) OR lower(folder)=lower(%s)',
|
||||
(body.name.strip(), body.name.strip())).fetchone():
|
||||
raise HTTPException(409, 'Já existe uma máquina, ou a pasta de uma máquina, com este nome.')
|
||||
c.execute('''INSERT INTO dtf_local.machines(id,name,folder,products,active,limit_metres,places)
|
||||
VALUES(%s,%s,%s,%s,%s,%s,%s)''', (mid, body.name.strip(), body.name.strip(), sorted(set(body.products)),
|
||||
body.active, body.limit_metres, body.places or machines.DEFAULT_PLACES))
|
||||
audit('machine_created', operator=user, machine=body.name)
|
||||
return {'id': str(mid)}
|
||||
|
||||
@@ -243,12 +284,13 @@ def create_machine(body: MachineIn, user=Depends(can('users'))):
|
||||
@router.post('/api/operator/machines/{mid}')
|
||||
def update_machine(mid: UUID, body: MachineIn, user=Depends(can('users'))):
|
||||
with db.connect() as c:
|
||||
if c.execute('SELECT 1 FROM dtf_local.machines WHERE lower(name)=lower(%s) AND id<>%s',
|
||||
(body.name.strip(), mid)).fetchone():
|
||||
raise HTTPException(409, 'Já existe uma máquina com este nome.')
|
||||
if not c.execute('''UPDATE dtf_local.machines SET name=%s,products=%s,active=%s,limit_metres=%s
|
||||
WHERE id=%s RETURNING id''', (body.name.strip(), sorted(set(body.products)), body.active,
|
||||
body.limit_metres, mid)).fetchone():
|
||||
if c.execute('''SELECT 1 FROM dtf_local.machines WHERE (lower(name)=lower(%s) OR lower(folder)=lower(%s))
|
||||
AND id<>%s''', (body.name.strip(), body.name.strip(), mid)).fetchone():
|
||||
raise HTTPException(409, 'Já existe uma máquina, ou a pasta de uma máquina, com este nome.')
|
||||
if not c.execute('''UPDATE dtf_local.machines SET name=%s,products=%s,active=%s,limit_metres=%s,
|
||||
places=COALESCE(%s,places) WHERE id=%s RETURNING id''',
|
||||
(body.name.strip(), sorted(set(body.products)), body.active, body.limit_metres,
|
||||
body.places, mid)).fetchone():
|
||||
raise HTTPException(404, 'Máquina não encontrada.')
|
||||
if not body.active:
|
||||
release_sessions(c, mid)
|
||||
@@ -256,6 +298,20 @@ def update_machine(mid: UUID, body: MachineIn, user=Depends(can('users'))):
|
||||
return {'ok': True}
|
||||
|
||||
|
||||
@router.post('/api/operator/machines/{mid}/places')
|
||||
def machine_places(mid: UUID, body: MachinePlaces, user=Depends(can('manage'))):
|
||||
"""How many orders the machine takes in Imprimindo, and files in its hot
|
||||
folder: Admin and Gestão set it from the machine's sheet (Marcus,
|
||||
2026-11-17). Orders already there stay; the next waits for a place."""
|
||||
with db.connect() as c:
|
||||
row = c.execute('UPDATE dtf_local.machines SET places=%s WHERE id=%s RETURNING name',
|
||||
(body.places, mid)).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(404, 'Máquina não encontrada.')
|
||||
audit('machine_places', operator=user, machine=row['name'], places=body.places)
|
||||
return {'ok': True}
|
||||
|
||||
|
||||
@router.post('/api/operator/machines/{mid}/delete')
|
||||
def delete_machine(mid: UUID, user=Depends(can('users'))):
|
||||
"""Its orders lose that machine; its operators lose the session choice."""
|
||||
@@ -276,8 +332,8 @@ def test_mail(request: Request, user=Depends(can('integrations'))):
|
||||
"""A message to whoever asked, to prove the mail server works."""
|
||||
with db.connect() as c:
|
||||
if not mail.queue(c, 'test', user, 'Teste de e-mail · Kanban DTF',
|
||||
'Este é um teste do Kanban DTF. Se chegou, o envio de e-mails está funcionando: '
|
||||
'os e-mails dos clientes.'):
|
||||
'Este é um teste do Kanban DTF. Se chegou, o envio de e-mails aos clientes '
|
||||
'está funcionando.'):
|
||||
raise HTTPException(409, 'O envio de e-mails não está configurado no servidor.')
|
||||
audit('mail_test_queued', operator=user)
|
||||
return {'ok': True, 'to': user}
|
||||
|
||||
36
app/app.py
36
app/app.py
@@ -4,9 +4,13 @@ Configuration and shared helpers are in local.runtime; every route lives in a
|
||||
router under local.api. This module creates the application, applies the
|
||||
cross-cutting middleware, and includes them.
|
||||
"""
|
||||
import asyncio
|
||||
import logging
|
||||
import time
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI
|
||||
import psycopg
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
from starlette.middleware.trustedhost import TrustedHostMiddleware
|
||||
|
||||
@@ -19,17 +23,47 @@ from .api import artwork, customer, health, machine_log, operator, orders, payme
|
||||
observability.init('api')
|
||||
|
||||
|
||||
RETRY_SECONDS = (1, 2, 4, 8, 15)
|
||||
STARTUP_BUDGET_SECONDS = 90
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app):
|
||||
# A redeploy briefly removes the database name; wait it out, warning once
|
||||
# per attempt (a warning, not an error: Sentry only takes errors).
|
||||
deadline = time.monotonic() + STARTUP_BUDGET_SECONDS
|
||||
attempt = 0
|
||||
while True:
|
||||
try:
|
||||
with db.connect() as c:
|
||||
c.execute('SELECT 1 FROM dtf_local.operator_sessions LIMIT 1')
|
||||
storage.health()
|
||||
break
|
||||
except Exception:
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
raise
|
||||
delay = min(RETRY_SECONDS[min(attempt, len(RETRY_SECONDS) - 1)], remaining)
|
||||
logging.warning('Database not reachable yet, retrying in %d s', max(1, round(delay)))
|
||||
await asyncio.sleep(delay)
|
||||
attempt += 1
|
||||
yield
|
||||
|
||||
|
||||
app = FastAPI(title='DTF Portal/API', lifespan=lifespan, docs_url=None, redoc_url=None)
|
||||
app.add_middleware(TrustedHostMiddleware, allowed_hosts=ALLOWED_HOSTS)
|
||||
|
||||
# The seconds a restart takes the database away (Sentry DTF-API-9): the
|
||||
# request is answered "try again" instead of a 500, and only a warning is
|
||||
# logged (Sentry takes errors). The page retries by itself or on reload.
|
||||
RESTARTING = 'O servidor está reiniciando. Tente de novo em alguns segundos.'
|
||||
|
||||
|
||||
@app.exception_handler(psycopg.OperationalError)
|
||||
async def database_unavailable(request: Request, exc):
|
||||
logging.warning('Database unavailable for %s %s: %s', request.method, request.url.path, exc)
|
||||
return JSONResponse({'detail': RESTARTING}, status_code=503, headers={'Retry-After': '5'})
|
||||
|
||||
@app.middleware('http')
|
||||
async def safe_headers(request, call_next):
|
||||
if request.method not in ('GET','HEAD','OPTIONS'):
|
||||
|
||||
@@ -74,22 +74,45 @@ def submit_files(c, order, body, identity, kind, actor):
|
||||
current = {(row['upload_id'], row['item_index']) for row in c.execute(
|
||||
"SELECT upload_id,item_index FROM dtf_local.order_files WHERE order_id=%s AND kind='final' AND active",
|
||||
(order['id'],)).fetchall()} if kind == 'final' else set()
|
||||
# A film in parts is approved whole: with only some of its parts, the
|
||||
# others never reach the folders or the machine (#114, #128, #130).
|
||||
if kind == 'final':
|
||||
sent = {}
|
||||
for ref in body.files:
|
||||
sent.setdefault(ref.item_index, set()).add(str(ref.upload_id))
|
||||
for row in c.execute('''SELECT item_index, array_agg(upload_id::text ORDER BY part) AS uploads,
|
||||
array_agg(part ORDER BY part) AS numbers FROM dtf_local.print_parts WHERE order_id=%s
|
||||
GROUP BY item_index HAVING count(*) > 1''', (order['id'],)).fetchall():
|
||||
mine = sent.get(row['item_index'], set())
|
||||
missing = [n for n, u in zip(row['numbers'], row['uploads']) if u not in mine]
|
||||
if mine & set(row['uploads']) and missing:
|
||||
raise HTTPException(422, f"O filme do item {row['item_index'] + 1} tem {len(row['uploads'])} partes: "
|
||||
f"envie todas (faltam {', '.join('p' + str(n) for n in missing)}).")
|
||||
kept = {ref.upload_id for ref in body.files if (ref.upload_id, ref.item_index) in current}
|
||||
if kept and len(kept) == len(body.files):
|
||||
raise HTTPException(409, 'Estes já são os arquivos finais. Envie o arquivo novo.')
|
||||
revived = set()
|
||||
for ref in body.files:
|
||||
if ref.upload_id in kept:
|
||||
continue
|
||||
corrected = correction_owner(c, order, ref, kind)
|
||||
upload = upload_row(c, ref.upload_id, corrected or generated_owner(c, order, ref, kind) or identity, lock=True)
|
||||
generated = None if corrected else generated_owner(c, order, ref, kind)
|
||||
upload = upload_row(c, ref.upload_id, corrected or generated or identity, lock=True)
|
||||
if not upload['complete']:
|
||||
raise HTTPException(409, 'Espere o envio de todos os arquivos terminar.')
|
||||
require_clean(upload)
|
||||
if kind == 'final':
|
||||
require_final_png(storage, upload)
|
||||
# Attached once, except a correction approved as its own final.
|
||||
if c.execute('SELECT id FROM dtf_local.order_files WHERE upload_id=%s'+(" AND kind<>'correction'" if corrected else ''),
|
||||
(ref.upload_id,)).fetchone():
|
||||
# Attached once, except a correction approved as its own final, and a
|
||||
# generated file or a correction that was this item's final and
|
||||
# stopped counting (a step back, Correção): it is turned back on
|
||||
# (Sentry DTF-WEB-10).
|
||||
rows = c.execute('SELECT order_id,item_index,kind FROM dtf_local.order_files WHERE upload_id=%s'
|
||||
+ (" AND kind<>'correction'" if corrected else ''), (ref.upload_id,)).fetchall()
|
||||
if rows and (corrected or generated) and all(
|
||||
r['order_id'] == order['id'] and r['kind'] == 'final' and r['item_index'] == ref.item_index for r in rows):
|
||||
revived.add(ref.upload_id)
|
||||
elif rows:
|
||||
raise HTTPException(409, 'Este arquivo já está no pedido. Envie uma nova versão.')
|
||||
# A new customer correction supersedes every final prepared from earlier
|
||||
# artwork, including finals uploaded while this order was in correction.
|
||||
@@ -97,8 +120,11 @@ def submit_files(c, order, body, identity, kind, actor):
|
||||
c.execute("UPDATE dtf_local.order_files SET active=false WHERE order_id=%s AND kind IN ('correction','final')", (order['id'],))
|
||||
else:
|
||||
c.execute('UPDATE dtf_local.order_files SET active=false WHERE order_id=%s AND kind=%s', (order['id'],kind))
|
||||
# A final changed: which items go to the machine again is worked out
|
||||
# anew when the order enters the queue (#105).
|
||||
c.execute('UPDATE dtf_local.orders SET print_items=NULL WHERE id=%s', (order['id'],))
|
||||
for ref in body.files:
|
||||
if ref.upload_id in kept:
|
||||
if ref.upload_id in kept or ref.upload_id in revived:
|
||||
c.execute("UPDATE dtf_local.order_files SET active=true WHERE order_id=%s AND upload_id=%s AND kind='final'",
|
||||
(order['id'], ref.upload_id))
|
||||
continue
|
||||
|
||||
@@ -43,6 +43,35 @@ def treatment_price(items, choice, offer):
|
||||
return {'cents': unit * count, 'hours': 24, 'arts': count, 'unit_cents': unit}
|
||||
|
||||
|
||||
def redesign_price(items, choice, offer):
|
||||
"""Ajuste Fino Redesenho for the chosen arts: one price per art, never a
|
||||
band. {} when it is not offered or no art is chosen."""
|
||||
if not offer or not offer.get('enabled') or offer.get('unit_cents', 0) <= 0:
|
||||
return {}
|
||||
arts = chosen_arts(items, choice)
|
||||
if not arts:
|
||||
return {}
|
||||
count = len(arts)
|
||||
unit = offer['unit_cents']
|
||||
return {'cents': unit * count, 'hours': 48, 'arts': count, 'unit_cents': unit}
|
||||
|
||||
|
||||
def designer_hours(snapshot):
|
||||
"""The extra hours the paid designer work adds to the deadline: 48 h when
|
||||
any art was sent to Redesenho, else 24 h for the basic Ajuste Fino."""
|
||||
# The hours recorded with the order win (an order keeps what it was sold
|
||||
# with); 48 and 24 are the defaults for snapshots that carry none.
|
||||
hours = [int((snapshot[key] if isinstance(snapshot.get(key), dict) else {}).get('hours') or default)
|
||||
for key, default in (('redesign', 48), ('treatment', 24)) if snapshot.get(key)]
|
||||
return max(hours, default=0)
|
||||
|
||||
|
||||
def needs_designer(snapshot):
|
||||
"""Whether a designer must prepare the final PNG before the print queue:
|
||||
a paid Ajuste Fino or Redesenho on any art."""
|
||||
return bool(snapshot.get('treatment') or snapshot.get('redesign'))
|
||||
|
||||
|
||||
def price_items(items, names, catalog_now, manual_extra):
|
||||
"""Price the items without a database: price() per item with the product's
|
||||
base price and the manual extra, bill_splits, then the band of each mode's
|
||||
@@ -70,13 +99,15 @@ def price_items(items, names, catalog_now, manual_extra):
|
||||
|
||||
|
||||
def price_cart(c, items, names, *, coupon_code=None, customer_document=None,
|
||||
wants_treatment=False, treatment_rule=True):
|
||||
wants_treatment=False, wants_redesign=(), treatment_rule=True):
|
||||
"""Price a cart exactly as an order is charged. Returns
|
||||
{'items': [priced item dicts], 'items_total': int, 'coupon': dict|None,
|
||||
'treatment': dict, 'treatment_cents': int, 'grade_flags': dict}.
|
||||
Raises HTTPException(422) for a product switched off, a required Ajuste
|
||||
Fino the cart did not ask for, or a refused coupon.
|
||||
`treatment_rule=False` is for the montador, which assembles the sheet."""
|
||||
'treatment': dict, 'treatment_cents': int, 'redesign': dict,
|
||||
'redesign_cents': int, 'grade_flags': dict}.
|
||||
Raises HTTPException(422) for a product switched off, a Redesenho not
|
||||
offered, a required designer service the cart did not ask for, or a
|
||||
refused coupon. `treatment_rule=False` is for the montador, which
|
||||
assembles the sheet."""
|
||||
from fastapi import HTTPException
|
||||
catalog_now = catalog.current(c)
|
||||
for item in items:
|
||||
@@ -89,7 +120,12 @@ def price_cart(c, items, names, *, coupon_code=None, customer_document=None,
|
||||
if not treatment_rule:
|
||||
flags.pop('tratamento', None)
|
||||
treatment = treatment_price(items, wants_treatment, offer)
|
||||
if 'tratamento' in flags and not treatment:
|
||||
redesign = redesign_price(items, wants_redesign, catalog_now['redesenho'])
|
||||
if chosen_arts(items, wants_redesign) and not redesign:
|
||||
raise HTTPException(422, 'O Redesenho não está disponível agora.')
|
||||
# The grade rule wants a designer on the art: the stronger Redesenho
|
||||
# satisfies it just as the basic Ajuste Fino does.
|
||||
if 'tratamento' in flags and not treatment and not redesign:
|
||||
raise HTTPException(422, grade_rules.treatment_message(flags['tratamento']))
|
||||
coupon = None
|
||||
if coupon_code:
|
||||
@@ -99,4 +135,6 @@ def price_cart(c, items, names, *, coupon_code=None, customer_document=None,
|
||||
'coupon': coupon,
|
||||
'treatment': treatment,
|
||||
'treatment_cents': treatment.get('cents', 0),
|
||||
'redesign': redesign,
|
||||
'redesign_cents': redesign.get('cents', 0),
|
||||
'grade_flags': flags}
|
||||
|
||||
@@ -9,7 +9,8 @@ and an approved quote keeps the price it was approved with.
|
||||
|
||||
`tratamento` is Ajuste Fino (front 1a): a price per art, with an optional band
|
||||
by the order's number of arts (front 8.2). It counts as offered only when it is
|
||||
switched on and priced above zero.
|
||||
switched on and priced above zero. `redesenho` is Ajuste Fino Redesenho (front
|
||||
1b): one price per art, no bands, and the same rule for being offered.
|
||||
|
||||
A price row may carry bands by the order's quantity of that product (metres, or
|
||||
arts for Ajuste Fino): below the first band the base price, then the highest
|
||||
@@ -20,9 +21,9 @@ from decimal import Decimal
|
||||
|
||||
from .core import pricing
|
||||
|
||||
# The modes sold by the metre, and the treatment sold per order.
|
||||
# The modes sold by the metre, and the services sold per art.
|
||||
MODES = ('file', 'avulsa', 'uvfile', 'uv', 'premium')
|
||||
PRODUCTS = (*MODES, 'tratamento')
|
||||
PRODUCTS = (*MODES, 'tratamento', 'redesenho')
|
||||
|
||||
TITLES = {
|
||||
'file': 'Têxtil folha pronta',
|
||||
@@ -31,14 +32,21 @@ TITLES = {
|
||||
'uv': 'UV artes avulsas',
|
||||
'premium': 'Têxtil Premium · 8 passadas',
|
||||
'tratamento': 'Ajuste Fino',
|
||||
'redesenho': 'Ajuste Fino Redesenho',
|
||||
}
|
||||
UNITS = {'file': 'metro', 'avulsa': 'metro', 'uvfile': 'metro', 'uv': 'metro',
|
||||
'premium': 'metro', 'tratamento': 'arte'}
|
||||
'premium': 'metro', 'tratamento': 'arte', 'redesenho': 'arte'}
|
||||
|
||||
|
||||
def fallback_cents(product: str) -> int:
|
||||
"""The price in the code, used until a row in the database takes over."""
|
||||
return pricing.treatment_cents() if product == 'tratamento' else pricing.PRICES[product]
|
||||
"""The price in the code, used until a row in the database takes over.
|
||||
Redesenho has no price in the code: it starts disabled and unpriced, and
|
||||
Gestão sets both in the Site tab."""
|
||||
if product == 'tratamento':
|
||||
return pricing.treatment_cents()
|
||||
if product == 'redesenho':
|
||||
return 0
|
||||
return pricing.PRICES[product]
|
||||
|
||||
|
||||
def band_price(base_cents: int, bands: list, quantity: Decimal) -> int:
|
||||
|
||||
@@ -4,6 +4,9 @@ import os
|
||||
import secrets
|
||||
import logging
|
||||
import json
|
||||
import psycopg
|
||||
import sys
|
||||
import time
|
||||
from uuid import UUID, uuid4
|
||||
from fastapi import HTTPException, Request
|
||||
from ..core.db import connect
|
||||
@@ -71,10 +74,14 @@ def transfer_guest(c, previous, identity):
|
||||
c.execute(f'UPDATE dtf_local.{table} SET owner=%s WHERE owner=%s', (identity,previous['owner']))
|
||||
c.execute('DELETE FROM dtf_local.sessions WHERE owner=%s', (previous['owner'],))
|
||||
|
||||
_persistence_error_at = None
|
||||
|
||||
|
||||
def audit(event, c=None, **fields):
|
||||
"""Record a security event. `c` is the caller's open connection, when there
|
||||
is one, so the event commits with that transaction instead of opening a
|
||||
second connection."""
|
||||
global _persistence_error_at
|
||||
# Only explicit metadata: never cookies, passwords, signed URLs or request bodies.
|
||||
logging.getLogger('dtf.security').warning(json.dumps({'event':event, **fields}, sort_keys=True))
|
||||
try:
|
||||
@@ -85,8 +92,14 @@ def audit(event, c=None, **fields):
|
||||
with connect() as c:
|
||||
c.execute('INSERT INTO dtf_local.security_events(event,details) VALUES(%s,%s)',(event,Jsonb(fields)))
|
||||
except Exception:
|
||||
# Logging must still work during a DB outage without recursively auditing itself.
|
||||
logging.getLogger('dtf.security').error('Security event persistence unavailable')
|
||||
# Logging must still work during a DB outage without recursively auditing
|
||||
# itself; the error is reported once per minute, not on every event.
|
||||
now = time.monotonic()
|
||||
if _persistence_error_at is None or now-_persistence_error_at >= 60:
|
||||
_persistence_error_at = now
|
||||
log = logging.getLogger('dtf.security')
|
||||
(log.warning if isinstance(sys.exc_info()[1], psycopg.OperationalError) else log.error)(
|
||||
'Security event persistence unavailable')
|
||||
|
||||
def rate_limit(scope, identity, limit, seconds=900):
|
||||
key = hashlib.sha256((scope+'|'+identity).encode()).hexdigest()
|
||||
@@ -194,9 +207,19 @@ MACHINE_QUESTION = {'operador': 'required', 'gestao': 'optional', 'admin': 'opti
|
||||
MOVERS = MANAGERS + tuple(MOVES)
|
||||
|
||||
|
||||
def _profiles(role):
|
||||
"""One profile or several: a user with more than one profile may do what
|
||||
any of them may (Marcus, 2026-11-26: operador/revisor, gestor/operador)."""
|
||||
return (role,) if isinstance(role, str) else tuple(role)
|
||||
|
||||
|
||||
def may_move(role, from_state, to_state, back=False):
|
||||
"""Whether this profile may move a card; `back` is the step back that
|
||||
undoes the move to_state -> from_state."""
|
||||
"""Whether this profile (or any of these) may move a card; `back` is the
|
||||
step back that undoes the move to_state -> from_state."""
|
||||
return any(_may_move(r, from_state, to_state, back) for r in _profiles(role))
|
||||
|
||||
|
||||
def _may_move(role, from_state, to_state, back):
|
||||
if back:
|
||||
return role in MANAGERS or (to_state, from_state) in MOVES.get(role, ())
|
||||
if to_state == 'fin':
|
||||
@@ -209,7 +232,44 @@ def may_move(role, from_state, to_state, back=False):
|
||||
def may_reorder(role, state):
|
||||
"""Changing a card's place in its column, the order it is worked in: for
|
||||
whoever takes cards forward out of it."""
|
||||
return role in MANAGERS or any(a == state and b != 'cor' for a, b in MOVES.get(role, ()))
|
||||
return any(r in MANAGERS or any(a == state and b != 'cor' for a, b in MOVES.get(r, ()))
|
||||
for r in _profiles(role))
|
||||
|
||||
|
||||
def roles_of(account):
|
||||
"""Every profile of a signed-in user, the main one first. Rows written
|
||||
before profiles became a list have only `role`."""
|
||||
return tuple(account.get('roles') or ()) or (account['role'],)
|
||||
|
||||
|
||||
def has(account, capability):
|
||||
return any(r in CAPABILITIES[capability] for r in roles_of(account))
|
||||
|
||||
|
||||
def machine_bound(account, from_state, to_state, back=False):
|
||||
"""Whether only the Operador profile allows this move, so the operator's
|
||||
machine rules apply to it: an operator who is also Revisor releases any
|
||||
machine's sheet, as a Revisor does."""
|
||||
roles = roles_of(account)
|
||||
return 'operador' in roles and not may_move([r for r in roles if r != 'operador'], from_state, to_state, back)
|
||||
|
||||
|
||||
def reorder_machine_bound(account, state):
|
||||
roles = roles_of(account)
|
||||
return 'operador' in roles and not may_reorder([r for r in roles if r != 'operador'], state)
|
||||
|
||||
|
||||
def operator_only(account, capability):
|
||||
"""Whether this capability comes to the user only through Operador."""
|
||||
roles = roles_of(account)
|
||||
return 'operador' in roles and not any(r in CAPABILITIES[capability] for r in roles if r != 'operador')
|
||||
|
||||
|
||||
def machine_question(account):
|
||||
""""Em qual máquina você está?": optional for management, required for an
|
||||
operator who is nothing more, never for the others."""
|
||||
answers = {MACHINE_QUESTION.get(r) for r in roles_of(account)}
|
||||
return 'optional' if 'optional' in answers else 'required' if 'required' in answers else None
|
||||
|
||||
|
||||
def signed_in(request: Request):
|
||||
@@ -220,7 +280,7 @@ def signed_in(request: Request):
|
||||
raise HTTPException(401, 'Entre no Kanban.')
|
||||
digest = hashlib.sha256(token.encode()).hexdigest()
|
||||
with connect() as c:
|
||||
row = c.execute('''SELECT o.id,o.email,o.name,o.role,s.machine_answered,m.id AS machine_id,m.name AS machine_name
|
||||
row = c.execute('''SELECT o.id,o.email,o.name,o.role,o.roles,s.machine_answered,m.id AS machine_id,m.name AS machine_name
|
||||
FROM dtf_local.operator_sessions s
|
||||
JOIN dtf_local.operators o ON o.email=s.username AND o.active
|
||||
LEFT JOIN dtf_local.machines m ON m.id=s.machine_id
|
||||
@@ -245,7 +305,7 @@ def can(capability):
|
||||
returns the operator's e-mail, as the routes record it."""
|
||||
def check(request: Request):
|
||||
account = signed_in(request)
|
||||
if account['role'] not in CAPABILITIES[capability]:
|
||||
if not has(account, capability):
|
||||
raise HTTPException(403, 'Seu perfil não permite esta ação.')
|
||||
return account['email']
|
||||
return check
|
||||
@@ -256,7 +316,7 @@ def can_any(*capabilities):
|
||||
and returns the operator's e-mail, as the routes record it."""
|
||||
def check(request: Request):
|
||||
account = signed_in(request)
|
||||
if not any(account['role'] in CAPABILITIES[capability] for capability in capabilities):
|
||||
if not any(has(account, capability) for capability in capabilities):
|
||||
raise HTTPException(403, 'Seu perfil não permite esta ação.')
|
||||
return account['email']
|
||||
return check
|
||||
|
||||
@@ -127,6 +127,15 @@ class ProductionSource(StrictModel):
|
||||
rotation_degrees: Literal[0, 90] = 0
|
||||
mirrored: bool = False
|
||||
measurement: Literal['file', 'customer']
|
||||
# The fully transparent strips the Site cut from the top and the bottom of
|
||||
# a ready sheet (Marcus, 2026-11-18): length_cm is what is left, billed
|
||||
# and printed; the file itself is length_cm plus both trims long.
|
||||
trim_top_cm: Decimal = Field(default=Decimal(0), ge=0, le=6000)
|
||||
trim_bottom_cm: Decimal = Field(default=Decimal(0), ge=0, le=6000)
|
||||
# The size the PNG itself recorded (item A1, round 5), only for the Prumo
|
||||
# report; nothing on the server prices or packs by it.
|
||||
saved_width_cm: Decimal | None = Field(default=None, gt=0, le=10000)
|
||||
saved_dpi: int | None = Field(default=None, ge=1, le=10000, strict=True)
|
||||
|
||||
class ProductionPlacement(StrictModel):
|
||||
source_index: int = Field(ge=0, le=199, strict=True)
|
||||
@@ -160,6 +169,37 @@ class Split(StrictModel):
|
||||
of: int = Field(ge=2, le=10, strict=True)
|
||||
|
||||
|
||||
UV_MODES = ('uvfile', 'uv')
|
||||
SHEET_MODES = ('file', 'uvfile', 'premium')
|
||||
# Clear film between the copies of a ready sheet, and between its sheets, for
|
||||
# cutting; billed like the rest (Marcus, 2026-11-26).
|
||||
SHEET_GAP_CM = Decimal('0.8')
|
||||
SHEET_GAP_CHANGED = ('O espaço entre as cópias da folha pronta passou a ser de 8 mm. '
|
||||
'Remova este item do carrinho e adicione de novo.')
|
||||
|
||||
|
||||
def check_sheet_gaps(items):
|
||||
"""A ready sheet's copies and sheets are SHEET_GAP_CM apart. Only a new
|
||||
cart is held to it: a quote made before still goes through review."""
|
||||
for item in items:
|
||||
if item.mode not in SHEET_MODES:
|
||||
continue
|
||||
placements = sorted(item.production.placements, key=lambda p: p.y_cm)
|
||||
for above, below in zip(placements, placements[1:]):
|
||||
if below.y_cm < above.y_cm + above.length_cm + SHEET_GAP_CM - Decimal('0.02'):
|
||||
raise ValueError(SHEET_GAP_CHANGED)
|
||||
ONE_MACHINE = ('Esse produto é impresso em outra máquina e precisa de um pedido separado. '
|
||||
'Finalize este pedido e faça um novo com ele.')
|
||||
|
||||
|
||||
def check_one_machine(items):
|
||||
"""One order, one machine (Marcus, 2026-11-26): UV and textile never share
|
||||
an order, since its card goes to one machine. Basic and premium textile
|
||||
print on the same machines and may."""
|
||||
if len({item.mode in UV_MODES for item in items}) > 1:
|
||||
raise ValueError(ONE_MACHINE)
|
||||
|
||||
|
||||
def check_splits(items):
|
||||
"""Every split group has each of its parts once, of one product."""
|
||||
groups = {}
|
||||
@@ -184,6 +224,10 @@ class Item(StrictModel):
|
||||
# Residue dots under 2 mm the customer accepted printing on a ready sheet,
|
||||
# rather than erasing them (Dropstar, 2026-10-29): 0 when none.
|
||||
residue_accepted: int = Field(default=0, ge=0, le=1000000, strict=True)
|
||||
# Pieces of a ready sheet under 5 mm from another, as the Site measured
|
||||
# them: shown on the Kanban card so the room sees it before printing
|
||||
# (Marcus, 2026-11-26, #81). 0 when none.
|
||||
close_pieces: int = Field(default=0, ge=0, le=1000000, strict=True)
|
||||
# The thinnest stroke the browser measured, in pixels at 300 DPI, and its
|
||||
# contraction class (Dropstar, 2026-10-30): up to 4 C1, 5 to 19 C2, 20+ C3.
|
||||
stroke_px: int | None = Field(default=None, ge=1, le=10000, strict=True)
|
||||
@@ -224,6 +268,8 @@ class Item(StrictModel):
|
||||
raise ValueError('Production source does not fit the selected product')
|
||||
if is_sheet and (source.rotation_degrees or source.mirrored):
|
||||
raise ValueError('Finished sheets cannot be rotated or mirrored by the layout')
|
||||
if (source.trim_top_cm or source.trim_bottom_cm) and (not is_sheet or source.measurement != 'file'):
|
||||
raise ValueError('Only a measured finished sheet has its empty strips cut')
|
||||
# A textile transfer is pressed face down: mirrored, it prints backwards.
|
||||
if self.mode == 'avulsa' and source.mirrored:
|
||||
raise ValueError('Textile artwork cannot be mirrored')
|
||||
@@ -249,21 +295,46 @@ class Item(StrictModel):
|
||||
raise ValueError('Finished sheets must retain their original orientation')
|
||||
if placed != expected:
|
||||
raise ValueError('Production layout does not cover every source copy')
|
||||
# No piece on top of another: stacked pieces bill less film than they
|
||||
# print on, and print over each other. Swept down the film, so only
|
||||
# the pieces still open at each row are compared.
|
||||
boxes = sorted((p.y_cm, p.y_cm + p.length_cm, p.x_cm, p.x_cm + p.width_cm)
|
||||
for p in self.production.placements)
|
||||
open_boxes = []
|
||||
for top, bottom, left, right in boxes:
|
||||
open_boxes = [b for b in open_boxes if b[0] > top + tolerance]
|
||||
if any(l < right - tolerance and left < r - tolerance for _, l, r in open_boxes):
|
||||
raise ValueError('Duas peças da montagem ficaram uma sobre a outra. Monte o pedido de novo.')
|
||||
open_boxes.append((bottom, left, right))
|
||||
if self.quality_status == 'warning' and not self.quality_acknowledged:
|
||||
raise ValueError('Resolution warning must be acknowledged')
|
||||
return self
|
||||
|
||||
TIMING_MAX = {'page_ms': 600000, 'upload_ms': 3600000, 'upload_bytes': 10**12,
|
||||
'analysis_ms': 3600000, 'montage_ms': 3600000}
|
||||
|
||||
|
||||
class ClientTimings(StrictModel):
|
||||
"""What the browser measured on the way to a quote (item 0.12).
|
||||
|
||||
They are only numbers for Números; a cart may send none of them, and the
|
||||
server never uses them to price or accept an order.
|
||||
server never uses them to price or accept an order: a value out of range
|
||||
(a cart left open for hours, DTF-WEB-9) is dropped, never refused.
|
||||
"""
|
||||
page_ms: int | None = Field(default=None, ge=0, le=600000)
|
||||
upload_ms: int | None = Field(default=None, ge=0, le=3600000)
|
||||
upload_bytes: int | None = Field(default=None, ge=0, le=10**12)
|
||||
analysis_ms: int | None = Field(default=None, ge=0, le=3600000)
|
||||
montage_ms: int | None = Field(default=None, ge=0, le=3600000)
|
||||
page_ms: int | None = None
|
||||
upload_ms: int | None = None
|
||||
upload_bytes: int | None = None
|
||||
analysis_ms: int | None = None
|
||||
montage_ms: int | None = None
|
||||
|
||||
@model_validator(mode='before')
|
||||
@classmethod
|
||||
def drop_out_of_range(cls, data):
|
||||
if not isinstance(data, dict):
|
||||
return data
|
||||
return {name: value for name, value in data.items()
|
||||
if name not in TIMING_MAX or (isinstance(value, int) and not isinstance(value, bool)
|
||||
and 0 <= value <= TIMING_MAX[name])}
|
||||
|
||||
|
||||
class QuoteRequest(StrictModel):
|
||||
@@ -277,6 +348,9 @@ class QuoteRequest(StrictModel):
|
||||
# Ajuste Fino (front 1a): true selects every art of the cart (old carts and
|
||||
# the grade rule), a list selects [item_index, source_index] arts.
|
||||
treatment: bool | list[tuple[int, int]] = False
|
||||
# Ajuste Fino Redesenho (front 1b): the arts sent to be redrawn, in the
|
||||
# same [item_index, source_index] identifiers. One service per art.
|
||||
redesign: list[tuple[int, int]] = Field(default_factory=list)
|
||||
# A coupon code typed at checkout (front 8.3); the server prices it.
|
||||
coupon: str | None = Field(default=None, max_length=30)
|
||||
# What the browser measured while the customer built the cart (item 0.12).
|
||||
@@ -285,6 +359,8 @@ class QuoteRequest(StrictModel):
|
||||
@model_validator(mode='after')
|
||||
def splits_complete(self):
|
||||
check_splits(self.items)
|
||||
check_one_machine(self.items)
|
||||
check_sheet_gaps(self.items)
|
||||
return self
|
||||
|
||||
@model_validator(mode='after')
|
||||
@@ -300,6 +376,24 @@ class QuoteRequest(StrictModel):
|
||||
seen.add((item_index, source_index))
|
||||
return self
|
||||
|
||||
@model_validator(mode='after')
|
||||
def redesign_arts_exist(self):
|
||||
seen = set()
|
||||
for item_index, source_index in self.redesign:
|
||||
if (item_index < 0 or source_index < 0 or item_index >= len(self.items)
|
||||
or source_index >= len(self.items[item_index].production.sources)):
|
||||
raise ValueError('Redesenho: arte não encontrada no pedido.')
|
||||
if (item_index, source_index) in seen:
|
||||
raise ValueError('Redesenho: cada arte aparece uma vez.')
|
||||
seen.add((item_index, source_index))
|
||||
# The customer chooses one service per art: basic or Redesenho.
|
||||
if self.treatment is True:
|
||||
if seen:
|
||||
raise ValueError('Escolha Ajuste Fino ou Redesenho para cada arte, não os dois.')
|
||||
elif isinstance(self.treatment, list) and seen & {(i, s) for i, s in self.treatment}:
|
||||
raise ValueError('Escolha Ajuste Fino ou Redesenho para cada arte, não os dois.')
|
||||
return self
|
||||
|
||||
@model_validator(mode='after')
|
||||
def destination_matches_freight(self):
|
||||
if self.freight.service == 'pickup':
|
||||
@@ -357,6 +451,7 @@ class Review(StrictModel):
|
||||
@model_validator(mode='after')
|
||||
def splits_complete(self):
|
||||
check_splits(self.items)
|
||||
check_one_machine(self.items)
|
||||
return self
|
||||
|
||||
class Pay(StrictModel):
|
||||
@@ -371,8 +466,8 @@ class PaymentMethod(StrictModel):
|
||||
# Up to 3, as Dropstar sells; the card form offers no more.
|
||||
installments: int = Field(default=1, ge=1, le=3, strict=True)
|
||||
issuer_id: str | None = Field(default=None, max_length=40)
|
||||
# The cardholder's document from the card form: for a card, the payer is
|
||||
# the cardholder, not necessarily the company on the invoice.
|
||||
# The document in the card form, which opens with the order's: the payer
|
||||
# when it is a valid CPF or CNPJ (app/mercadopago.py payer).
|
||||
payer_document_type: Literal['CPF', 'CNPJ'] | None = None
|
||||
payer_document: str | None = Field(default=None, pattern=r'^[0-9]{11,14}$')
|
||||
|
||||
|
||||
@@ -8,6 +8,19 @@ import os
|
||||
import re
|
||||
from decimal import Decimal, ROUND_CEILING
|
||||
|
||||
# Billed in steps of 10 cm, with 8 mm of grace for the customer (Marcus,
|
||||
# 2026-11-27): a length that passes a step by up to 8 mm is billed at that
|
||||
# step, by more at the next one. The Site rounds the same (web/site-config.js).
|
||||
STEP_GRACE_M = Decimal('0.008')
|
||||
|
||||
|
||||
def billed_length(length):
|
||||
"""The metres billed for `length` metres, before any minimum; never 0 for
|
||||
a sheet that has a length."""
|
||||
steps = ((Decimal(str(length)) - STEP_GRACE_M) * 10).to_integral_value(rounding=ROUND_CEILING)
|
||||
return max(Decimal('0.1'), steps / 10)
|
||||
|
||||
|
||||
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
|
||||
@@ -55,7 +68,7 @@ def price(mode: str, metres: str, grade: int, extra_cents: int = 0, minimum: Dec
|
||||
raise ValueError('Invalid product or length')
|
||||
if isinstance(grade, bool) or not isinstance(grade, int) or not 0 <= grade <= 100:
|
||||
raise ValueError('Grade must be an integer between 0 and 100')
|
||||
billed = max(minimum, (length * 10).to_integral_value(rounding=ROUND_CEILING) / 10)
|
||||
billed = max(minimum, billed_length(length))
|
||||
if isinstance(extra_cents, bool) or not isinstance(extra_cents, int) or extra_cents < 0:
|
||||
raise ValueError('Invalid extra charge')
|
||||
unit = (PRICES[mode] if unit_cents is None else unit_cents) + extra_cents
|
||||
|
||||
14
app/finals.py
Normal file
14
app/finals.py
Normal file
@@ -0,0 +1,14 @@
|
||||
"""Which of an order's finals count: shared by the board, the proof and the worker."""
|
||||
|
||||
# An item's final counts while its file is still there and scanned clean: the
|
||||
# same rule that lets an order into the print queue.
|
||||
FINAL_OK = """f.kind='final' AND f.active AND u.expires_at>now() AND u.purged_at IS NULL AND u.scan_state='clean'"""
|
||||
# "Arte tratada" (Dropstar, 2026-10-27): a final someone prepared, not the
|
||||
# customer's own artwork. It is neither the file the system generated from
|
||||
# their art, nor one of their originals, nor a correction they sent. `f` is
|
||||
# the final in dtf_local.order_files, `o` its order.
|
||||
TREATED = """f.kind='final'
|
||||
AND NOT EXISTS (SELECT 1 FROM dtf_local.print_parts p WHERE p.order_id=f.order_id AND p.upload_id=f.upload_id)
|
||||
AND NOT EXISTS (SELECT 1 FROM jsonb_array_elements(o.snapshot->'items') i WHERE i->'uploads' ? f.upload_id::text)
|
||||
AND NOT EXISTS (SELECT 1 FROM dtf_local.order_files k WHERE k.order_id=f.order_id AND k.upload_id=f.upload_id
|
||||
AND k.kind='correction')"""
|
||||
@@ -32,6 +32,14 @@ PDF_VECTOR_DPI = 300
|
||||
# grade them, so neither does this.
|
||||
PDF_MAX_BYTES = 150 * 1048576
|
||||
HEAD_BYTES = 1048576
|
||||
# How much of a PDF's drawing is walked for its DPI: images and forms drawn
|
||||
# (Do), however many paths a vector page has. A page whose forms draw other
|
||||
# forms, ten times each, eight deep, is 10^8 draws in a 2 KB file: it
|
||||
# held the scanner's one thread for hours and every upload behind it
|
||||
# (security review, 2026-11-27). Past either limit the DPI is unknown, as for
|
||||
# a format this cannot read, and the order is reviewed by a person.
|
||||
PDF_MAX_DRAWS = 5000
|
||||
PDF_MAX_SECONDS = 10
|
||||
# Rounding in the browser and here can differ by a point on the same file.
|
||||
TOLERANCE = 2
|
||||
|
||||
@@ -84,10 +92,27 @@ def _multiply(a, b):
|
||||
a[0] * b[4] + a[2] * b[5] + a[4], a[1] * b[4] + a[3] * b[5] + a[5]]
|
||||
|
||||
|
||||
class _TooMuch(Exception):
|
||||
"""The PDF's drawing is larger than PDF_MAX_DRAWS or PDF_MAX_SECONDS."""
|
||||
|
||||
|
||||
def pdf_dpi(path):
|
||||
"""The page's area-weighted image DPI, 300 for vectors only, None if the
|
||||
file is not a one-page PDF this can read."""
|
||||
file is not a one-page PDF this can read, or draws more than it is worth
|
||||
walking (PDF_MAX_DRAWS, PDF_MAX_SECONDS)."""
|
||||
import time
|
||||
import pikepdf
|
||||
deadline = time.monotonic() + PDF_MAX_SECONDS
|
||||
steps = [0]
|
||||
parsed = {}
|
||||
|
||||
def instructions_of(stream):
|
||||
# A form drawn many times is read once.
|
||||
key = stream.objgen if stream.objgen != (0, 0) else id(stream)
|
||||
if key not in parsed:
|
||||
parsed[key] = pikepdf.parse_content_stream(stream)
|
||||
return parsed[key]
|
||||
|
||||
try:
|
||||
with pikepdf.open(path) as pdf:
|
||||
if len(pdf.pages) != 1:
|
||||
@@ -99,7 +124,9 @@ def pdf_dpi(path):
|
||||
def walk(resources, instructions, ctm, depth):
|
||||
stack = []
|
||||
xobjects = resources.get('/XObject', {}) if resources is not None else {}
|
||||
for operands, operator in instructions:
|
||||
for count, (operands, operator) in enumerate(instructions):
|
||||
if count % 1000 == 0 and time.monotonic() > deadline:
|
||||
raise _TooMuch
|
||||
op = str(operator)
|
||||
if op == 'q':
|
||||
stack.append(ctm)
|
||||
@@ -108,6 +135,9 @@ def pdf_dpi(path):
|
||||
elif op == 'cm':
|
||||
ctm = _multiply(ctm, [float(v) for v in operands])
|
||||
elif op == 'Do' and operands:
|
||||
steps[0] += 1
|
||||
if steps[0] > PDF_MAX_DRAWS or time.monotonic() > deadline:
|
||||
raise _TooMuch
|
||||
xobject = xobjects.get(str(operands[0]))
|
||||
if xobject is None:
|
||||
continue
|
||||
@@ -120,9 +150,14 @@ def pdf_dpi(path):
|
||||
elif subtype == '/Form' and depth < 8:
|
||||
matrix = [float(v) for v in xobject.get('/Matrix', [1, 0, 0, 1, 0, 0])]
|
||||
walk(xobject.get('/Resources', resources),
|
||||
pikepdf.parse_content_stream(xobject), _multiply(ctm, matrix), depth + 1)
|
||||
instructions_of(xobject), _multiply(ctm, matrix), depth + 1)
|
||||
|
||||
walk(page.obj.get('/Resources'), pikepdf.parse_content_stream(page), [1, 0, 0, 1, 0, 0], 0)
|
||||
except _TooMuch:
|
||||
import logging
|
||||
logging.warning('PDF %s draws more than %s images and forms, or takes over %s s: its DPI is left unknown',
|
||||
os.path.basename(path), PDF_MAX_DRAWS, PDF_MAX_SECONDS)
|
||||
return None
|
||||
except Exception:
|
||||
return None
|
||||
found = [(dpi, area) for dpi, area in found if dpi > 0]
|
||||
@@ -132,14 +167,47 @@ def pdf_dpi(path):
|
||||
return js_round(sum(dpi * area for dpi, area in found) / total)
|
||||
|
||||
|
||||
def _pdf_dpi_child(result, path):
|
||||
result.put(pdf_dpi(path))
|
||||
|
||||
|
||||
def bounded_pdf_dpi(path):
|
||||
"""pdf_dpi in a process of its own, ended past PDF_MAX_SECONDS: the PDF
|
||||
library itself can be held by a file (a huge compressed stream), where
|
||||
pdf_dpi's own limits cannot reach. None when it did not finish."""
|
||||
import multiprocessing
|
||||
from queue import Empty
|
||||
context = multiprocessing.get_context('spawn')
|
||||
result = context.Queue()
|
||||
process = context.Process(target=_pdf_dpi_child, args=(result, path))
|
||||
process.start()
|
||||
try:
|
||||
process.join(PDF_MAX_SECONDS + 5)
|
||||
if process.is_alive():
|
||||
process.kill()
|
||||
process.join()
|
||||
import logging
|
||||
logging.warning('PDF %s took over %s s to read: its DPI is left unknown',
|
||||
os.path.basename(path), PDF_MAX_SECONDS + 5)
|
||||
return None
|
||||
try:
|
||||
return result.get(timeout=5)
|
||||
except Empty:
|
||||
return None
|
||||
finally:
|
||||
result.close()
|
||||
result.join_thread()
|
||||
|
||||
|
||||
def stored_pdf_dpi(storage, row):
|
||||
"""A stored PDF's DPI, read once; None when it is above PDF_MAX_BYTES."""
|
||||
"""A stored PDF's DPI, read once; None when it is above PDF_MAX_BYTES or
|
||||
takes too long to read (bounded_pdf_dpi)."""
|
||||
if row['size'] > PDF_MAX_BYTES:
|
||||
return None
|
||||
with tempfile.NamedTemporaryFile(suffix='.pdf') as handle:
|
||||
storage.client.download_fileobj(storage.bucket, row['object_key'], handle)
|
||||
handle.flush()
|
||||
return pdf_dpi(handle.name)
|
||||
return bounded_pdf_dpi(handle.name)
|
||||
|
||||
|
||||
class Files:
|
||||
@@ -227,6 +295,35 @@ def resolution_issue(files, items, rows):
|
||||
return None
|
||||
|
||||
|
||||
def proportion_issue(files, items, rows):
|
||||
"""Why a cart's layout cannot be priced, or None: a raster file laid out
|
||||
at proportions it does not have (a 5 m sheet sent as 10 cm, say). The
|
||||
print file refuses the same thing (app/printfile.py check_layout), but
|
||||
only after payment; here it is refused before. A PDF, or a file whose
|
||||
size the first bytes do not tell, is left to that later check."""
|
||||
from .printfile import ASPECT_TOLERANCE
|
||||
for index, item in enumerate(items, 1):
|
||||
for number, source in enumerate(item['production']['sources'], 1):
|
||||
row = rows.get(str(source['upload_id']))
|
||||
if not row or row['name'].lower().endswith('.pdf'):
|
||||
continue
|
||||
size = image_size(files.head(row))
|
||||
if not size or not all(size):
|
||||
continue
|
||||
width_px, height_px = size
|
||||
if source.get('rotation_degrees') in (90, 270):
|
||||
width_px, height_px = height_px, width_px
|
||||
# A ready sheet's empty strips were cut from its length: the file
|
||||
# is the length plus both strips (app/core/models.py).
|
||||
length = (float(source['length_cm']) + float(source.get('trim_top_cm') or 0)
|
||||
+ float(source.get('trim_bottom_cm') or 0))
|
||||
drift = abs((width_px / height_px) / (float(source['width_cm']) / length) - 1)
|
||||
if drift > ASPECT_TOLERANCE:
|
||||
return (f'Item {index}: o arquivo {number} foi montado com {source["width_cm"]} × '
|
||||
f'{source["length_cm"]} cm, que não são as proporções dele. Monte o pedido de novo.')
|
||||
return None
|
||||
|
||||
|
||||
def mismatch(files, items, rows):
|
||||
"""Why a cart's grades cannot be approved at checkout, or None."""
|
||||
for item in items:
|
||||
|
||||
@@ -29,6 +29,7 @@ def triggered(rules: dict, items, treatment_offered: bool) -> dict:
|
||||
|
||||
|
||||
def treatment_message(grade: int) -> str:
|
||||
"""The refusal the customer sees when Ajuste Fino is required."""
|
||||
return (f'Sua arte tem nota {grade}: para imprimir com qualidade, o Ajuste Fino '
|
||||
"""The refusal the customer sees when Ajuste Fino is required. The grade
|
||||
stays on the Kanban: the customer never sees the number (Rodada 5, D6)."""
|
||||
return ('Sua arte está abaixo da resolução mínima, então o Ajuste Fino '
|
||||
'é obrigatório neste pedido.')
|
||||
|
||||
@@ -4,9 +4,10 @@ FlexiPRINT watches 3. Imprimindo/<máquina>/<C1|C2|C3|PREMIUM>/ and takes a
|
||||
file out of it when it rips. When the operator pulls a card to Imprimindo, its
|
||||
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
|
||||
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 order's own file stays in its stage folder. A film longer than a part
|
||||
(10 m) is several parts (item 13): all on the same machine, in order. A machine's folder holds
|
||||
as many files at once as it has places in Imprimindo (machines.places, three
|
||||
since 2026-11-17); the next is written when Flexi takes one.
|
||||
|
||||
Only the server knows what each folder should get, and the Kanban's
|
||||
computers write it: a part is claimed by one computer, so two never write
|
||||
@@ -14,7 +15,8 @@ the same file and Flexi never prints it twice. A claim that did not finish
|
||||
goes back to the queue. A written part that is gone from its folder was
|
||||
taken by Flexi, and is never written again. A card that leaves Imprimindo
|
||||
(Revisão, Correção, a step back, a cancellation) withdraws what Flexi has not
|
||||
taken yet, and its computer deletes it.
|
||||
taken yet, and its computer deletes it. A step back from Revisão to
|
||||
Imprimindo writes again only what Flexi had not taken (resume()).
|
||||
|
||||
Each part's life is one row of dtf_local.hot_parts:
|
||||
queued -> claimed -> written -> consumed, or withdraw -> gone.
|
||||
@@ -23,8 +25,6 @@ from datetime import timedelta
|
||||
|
||||
# The machines' folders, inside the Kanban's main folder (Dropstar, 2026-10-30).
|
||||
PRINTING_FOLDER = '3. Imprimindo'
|
||||
# Two parts at most in a machine's folder (Dropstar, 2026-10-30).
|
||||
IN_FOLDER = 2
|
||||
# A computer that claimed a part and never said it was written.
|
||||
CLAIM_TIMEOUT = timedelta(minutes=10)
|
||||
CLASSES = ('C1', 'C2', 'C3')
|
||||
@@ -53,10 +53,17 @@ def folder_class(order, index):
|
||||
|
||||
def start(c, order_id):
|
||||
"""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; on a reprint only the items
|
||||
chosen to go again (orders.print_items)."""
|
||||
# A film's parts in their own order, p2 before p10: by name, a 91 m film
|
||||
# would print p10 second.
|
||||
files = c.execute('''SELECT f.item_index, f.upload_id, u.name FROM dtf_local.order_files f
|
||||
JOIN dtf_local.uploads u ON u.id=f.upload_id
|
||||
WHERE f.order_id=%s AND f.kind='final' AND f.active ORDER BY f.item_index, u.name''', (order_id,)).fetchall()
|
||||
JOIN dtf_local.uploads u ON u.id=f.upload_id JOIN dtf_local.orders o ON o.id=f.order_id
|
||||
LEFT JOIN dtf_local.print_parts pp ON pp.order_id=f.order_id AND pp.item_index=f.item_index
|
||||
AND pp.upload_id=f.upload_id
|
||||
WHERE f.order_id=%s AND f.kind='final' AND f.active
|
||||
AND (o.print_items IS NULL OR f.item_index = ANY(o.print_items))
|
||||
ORDER BY f.item_index, pp.part NULLS LAST, length(u.name), u.name''', (order_id,)).fetchall()
|
||||
round_ = c.execute('SELECT COALESCE(max(round), 0) + 1 AS r FROM dtf_local.hot_parts WHERE order_id=%s',
|
||||
(order_id,)).fetchone()['r']
|
||||
for seq, row in enumerate(files, 1):
|
||||
@@ -64,6 +71,40 @@ def start(c, order_id):
|
||||
VALUES(%s,%s,%s,%s,%s,%s)''', (order_id, round_, seq, row['item_index'], row['upload_id'], row['name']))
|
||||
|
||||
|
||||
def resume(c, order_id):
|
||||
"""A step back from Revisão to Imprimindo, undoing a move made by
|
||||
mistake: the parts of the last round Flexi had not taken go back to the
|
||||
folder, in their order; what it took was printed and is never written
|
||||
again (start() would send the whole order to the machine once more)."""
|
||||
last = c.execute('SELECT max(round) AS r FROM dtf_local.hot_parts WHERE order_id=%s', (order_id,)).fetchone()['r']
|
||||
if last is None:
|
||||
return
|
||||
c.execute('''INSERT INTO dtf_local.hot_parts(order_id,round,seq,item_index,upload_id,name)
|
||||
SELECT order_id, round + 1, row_number() OVER (ORDER BY seq), item_index, upload_id, name
|
||||
FROM dtf_local.hot_parts WHERE order_id=%s AND round=%s AND state<>'consumed' ''', (order_id, last))
|
||||
|
||||
|
||||
def printed(c, order_ids):
|
||||
"""The files each order's machine has already taken, {order id: {upload
|
||||
ids}}: an order in it was printed before."""
|
||||
rows = c.execute('''SELECT order_id, upload_id FROM dtf_local.hot_parts
|
||||
WHERE order_id=ANY(%s) AND state IN ('written','consumed')''', (list(order_ids),)).fetchall()
|
||||
out = {}
|
||||
for row in rows:
|
||||
out.setdefault(row['order_id'], set()).add(row['upload_id'])
|
||||
return out
|
||||
|
||||
|
||||
def reprint_default(finals, taken, count):
|
||||
"""The items to print again: those whose current final the machine has
|
||||
not taken. `finals` is [(item, upload id)]; None when all go (never printed,
|
||||
or nothing new)."""
|
||||
if not taken:
|
||||
return None
|
||||
changed = sorted({item for item, upload in finals if upload not in taken})
|
||||
return changed if changed and len(changed) < count else None
|
||||
|
||||
|
||||
def stop(c, order_id):
|
||||
"""The order left Imprimindo or was cancelled: what is not written stays
|
||||
unwritten, and what Flexi has not taken is withdrawn from the folder."""
|
||||
@@ -75,15 +116,15 @@ def stop(c, order_id):
|
||||
def claim(c, user):
|
||||
"""The parts due in the folders now, claimed for this computer to write:
|
||||
for each machine, the next parts of its orders in Imprimindo, in the order
|
||||
they entered it, until the machine has two in its folder."""
|
||||
they entered it, until the machine has its places' worth in its folder."""
|
||||
c.execute('''UPDATE dtf_local.hot_parts SET state='queued', claimed_at=NULL, claimed_by=NULL
|
||||
WHERE state='claimed' AND claimed_at < now() - %s''', (CLAIM_TIMEOUT,))
|
||||
rows = c.execute('''SELECT h.*, o.machine_id, o.contraction, o.snapshot, m.name AS machine_name,
|
||||
rows = c.execute('''SELECT h.*, o.machine_id, o.contraction, o.snapshot, COALESCE(m.folder, m.name) AS machine_folder, m.places,
|
||||
(SELECT max(v.id) FROM dtf_local.movements v WHERE v.order_id=o.id AND v.to_state='imp') AS entered
|
||||
FROM dtf_local.hot_parts h JOIN dtf_local.orders o ON o.id=h.order_id
|
||||
JOIN dtf_local.machines m ON m.id=o.machine_id
|
||||
WHERE h.state IN ('queued','claimed','written') AND o.state='imp' AND o.cancelled_at IS NULL
|
||||
ORDER BY m.name, entered, h.order_id, h.seq FOR UPDATE OF h''').fetchall()
|
||||
ORDER BY m.created_at, m.id, entered, h.order_id, h.seq FOR UPDATE OF h''').fetchall()
|
||||
due, busy, blocked = [], {}, set()
|
||||
for row in rows:
|
||||
machine = row['machine_id']
|
||||
@@ -95,10 +136,12 @@ def claim(c, user):
|
||||
continue
|
||||
cls = folder_class(row, row['item_index'])
|
||||
# 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) >= row['places'] or not cls:
|
||||
blocked.add(order)
|
||||
continue
|
||||
folder = f"{row['machine_name']}/{cls}"
|
||||
# The machine's folder, fixed at its creation: a renamed machine keeps
|
||||
# the path FlexiPRINT watches.
|
||||
folder = f"{row['machine_folder']}/{cls}"
|
||||
c.execute('''UPDATE dtf_local.hot_parts SET state='claimed', claimed_at=now(), claimed_by=%s, folder=%s
|
||||
WHERE id=%s''', (user, folder, row['id']))
|
||||
busy[machine] = busy.get(machine, 0) + 1
|
||||
|
||||
@@ -28,7 +28,8 @@ entry. Fewer than two entries, no estimate.
|
||||
|
||||
"Printed" is what left Imprimindo for Revisão on the machine (orders.machine_id,
|
||||
the movement imp -> rev not back): the film metres of the items
|
||||
(COALESCE(metres, billed_metres)), and PROOF_SHEET_CM per item for a proof card.
|
||||
(COALESCE(metres, billed_metres)), and for a proof card the length of each
|
||||
proof sheet (film_metres).
|
||||
"""
|
||||
from datetime import datetime, timezone
|
||||
from decimal import Decimal
|
||||
@@ -58,21 +59,40 @@ def one_decimal(value):
|
||||
return f'{Decimal(str(value)):.1f}'.replace('.', ',')
|
||||
|
||||
|
||||
def printed_since(c, machine_id, since):
|
||||
"""Film metres the machine printed after `since` (None: ever), as Decimal."""
|
||||
# A pass to Revisão undone at once (a mistaken move, back to Imprimindo):
|
||||
# the pass after the undo counts the film, so this one must not, or the
|
||||
# machine's metres count it twice. `m` is the pass in dtf_local.movements.
|
||||
NOT_UNDONE = """NOT EXISTS (SELECT 1 FROM dtf_local.movements u WHERE u.order_id=m.order_id AND u.back
|
||||
AND u.from_state='rev' AND u.to_state='imp'
|
||||
AND u.id=(SELECT min(n.id) FROM dtf_local.movements n WHERE n.order_id=m.order_id AND n.id>m.id))"""
|
||||
|
||||
|
||||
# Each proof sheet's stretches of film, {item index: [[top, bottom], ...]},
|
||||
# from its print file (app/printpng.py); `o` is the order.
|
||||
PROOF_WINDOWS = """(SELECT jsonb_object_agg(p.item_index::text, p.detail->'proof_windows')
|
||||
FROM dtf_local.print_files p WHERE p.order_id=o.id AND p.detail ? 'proof_windows') AS windows"""
|
||||
|
||||
|
||||
def film_metres(snapshot, items=None, windows=None):
|
||||
"""The film one pass to Revisão printed, in metres, as Decimal: each
|
||||
item's metres, on a reprint only the `items` that went again (#105). A
|
||||
proof card's item is its sheet: the finest stroke's window and the colour
|
||||
samples with the clear film between them, up to 30 cm (Marcus,
|
||||
2026-11-26), from `windows` ({item index: [[top, bottom], ...]} in cm);
|
||||
PROOF_SHEET_CM for a sheet made before the samples."""
|
||||
from .printpng import PROOF_GAP_CM
|
||||
from .proof import PROOF_SHEET_CM
|
||||
rows = c.execute('''SELECT o.snapshot FROM dtf_local.movements m
|
||||
JOIN dtf_local.orders o ON o.id=m.order_id
|
||||
WHERE o.machine_id=%s AND m.from_state='imp' AND m.to_state='rev' AND NOT m.back
|
||||
AND (%s::timestamptz IS NULL OR m.created_at > %s::timestamptz)''',
|
||||
(machine_id, since, since)).fetchall()
|
||||
total = Decimal(0)
|
||||
for row in rows:
|
||||
snapshot = row['snapshot'] or {}
|
||||
snapshot = snapshot or {}
|
||||
proof = bool(snapshot.get('proof_of'))
|
||||
for item in snapshot.get('items') or []:
|
||||
total = Decimal(0)
|
||||
for index, item in enumerate(snapshot.get('items') or []):
|
||||
if items is not None and index not in items:
|
||||
continue
|
||||
if proof:
|
||||
total += PROOF_SHEET_CM
|
||||
stretches = (windows or {}).get(str(index)) or []
|
||||
cm = (sum((Decimal(str(b)) - Decimal(str(a)) for a, b in stretches), Decimal(0))
|
||||
+ PROOF_GAP_CM * (len(stretches) - 1)) if stretches else PROOF_SHEET_CM
|
||||
total += cm / 100
|
||||
else:
|
||||
value = item.get('metres')
|
||||
if value is None:
|
||||
@@ -81,6 +101,16 @@ def printed_since(c, machine_id, since):
|
||||
return total
|
||||
|
||||
|
||||
def printed_since(c, machine_id, since):
|
||||
"""Film metres the machine printed after `since` (None: ever), as Decimal."""
|
||||
rows = c.execute(f'''SELECT o.snapshot, m.items, {PROOF_WINDOWS} FROM dtf_local.movements m
|
||||
JOIN dtf_local.orders o ON o.id=m.order_id
|
||||
WHERE o.machine_id=%s AND m.from_state='imp' AND m.to_state='rev' AND NOT m.back AND {NOT_UNDONE}
|
||||
AND (%s::timestamptz IS NULL OR m.created_at > %s::timestamptz)''',
|
||||
(machine_id, since, since)).fetchall()
|
||||
return sum((film_metres(row['snapshot'], row.get('items'), row.get('windows')) for row in rows), Decimal(0))
|
||||
|
||||
|
||||
def _last_entry(c, machine_id, kind, item):
|
||||
return c.execute('''SELECT * FROM dtf_local.machine_entries
|
||||
WHERE machine_id=%s AND kind=%s AND item=%s
|
||||
@@ -175,7 +205,7 @@ def alerts(c, machine_id):
|
||||
'snoozable': bool, 'blocking': bool}. blocking is False when it was
|
||||
postponed this cycle and no card was pulled on the machine since.
|
||||
Texts, with metres in one decimal and a comma:
|
||||
clean "<máquina>: 10,4 m desde a última limpeza — limpe antes do próximo arquivo"
|
||||
clean "<máquina>: 10,4 m desde a última limpeza: limpe antes do próximo arquivo"
|
||||
align "<máquina>: 19,8 m desde a troca de filme — alinhe a cabeça antes do próximo"
|
||||
supply "<label minúsculo> da <máquina> deve acabar em ~3 m" (e.g. "tinta branca da máquina2 deve acabar em ~3,0 m")
|
||||
"""
|
||||
@@ -206,11 +236,11 @@ def alerts(c, machine_id):
|
||||
|
||||
if counts['clean']['metres'] >= CLEAN_EVERY_METRES:
|
||||
due('clean', f"{name}: {one_decimal(counts['clean']['metres'])} m desde a última limpeza "
|
||||
'— limpe antes do próximo arquivo', counts['clean']['since'])
|
||||
': limpe antes do próximo arquivo', counts['clean']['since'])
|
||||
if (counts['film']['since'] is not None and not counts['film']['aligned']
|
||||
and counts['film']['metres'] >= ALIGN_AFTER_FILM_METRES):
|
||||
due('align', f"{name}: {one_decimal(counts['film']['metres'])} m desde a troca de filme "
|
||||
'— alinhe a cabeça antes do próximo', counts['film']['since'])
|
||||
': alinhe a cabeça antes do próximo', counts['film']['since'])
|
||||
for item, value in supplies.items():
|
||||
if not supply_low(value):
|
||||
continue
|
||||
|
||||
@@ -5,7 +5,7 @@ what the board already knows it printed, per machine and calendar month
|
||||
(America/Sao_Paulo):
|
||||
|
||||
Produção printed metres (machine_log rule: imp -> rev, film metres,
|
||||
PROOF_SHEET_CM per proof item); hours running = the union of the
|
||||
a proof sheet its real length); hours running = the union of the
|
||||
time its orders spent in Imprimindo, clipped to the month (two
|
||||
orders printing together count once); metres per hour = printed
|
||||
/ hours running; hours stopped = the "stop" events' minutes, in
|
||||
@@ -33,7 +33,7 @@ from datetime import datetime, time
|
||||
from decimal import Decimal, ROUND_HALF_UP
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from .machine_log import SUPPLIES
|
||||
from .machine_log import NOT_UNDONE, PROOF_WINDOWS, SUPPLIES, film_metres
|
||||
|
||||
SAO_PAULO = ZoneInfo('America/Sao_Paulo')
|
||||
# The five inks Números lists, in the order the sheet knows them.
|
||||
@@ -41,6 +41,17 @@ INK_ITEMS = tuple(item for item in SUPPLIES if item.startswith('ink_'))
|
||||
# Average month, for the monthly contribution since installation.
|
||||
_MONTH_SECONDS = Decimal('30.4375') * 86400
|
||||
|
||||
# Below a quarter of an hour in Imprimindo the pace is noise: an order moved
|
||||
# through in seconds made a machine show 110671,5 m/h (16/11). No pace then.
|
||||
MIN_PACE_HOURS = 0.25
|
||||
|
||||
|
||||
def pace(metres, hours):
|
||||
"""Metres per hour, one decimal; None below MIN_PACE_HOURS of printing."""
|
||||
if not hours or float(hours) < MIN_PACE_HOURS:
|
||||
return None
|
||||
return round(float(metres) / float(hours), 1)
|
||||
|
||||
|
||||
def month_bounds(month):
|
||||
"""'2026-11' (None: the current month, local) -> (first day, first day of
|
||||
@@ -79,8 +90,7 @@ def ratios(printed, hours_running=None, supplies_cents=0, parts_cents=0, rolls=N
|
||||
return int((Decimal(cents) / printed).quantize(Decimal('1'), rounding=ROUND_HALF_UP))
|
||||
|
||||
result = {
|
||||
'metres_per_hour': (round(float(printed) / float(hours_running), 1)
|
||||
if hours_running else None),
|
||||
'metres_per_hour': pace(printed, hours_running),
|
||||
'metres_per_roll': round(float(printed / Decimal(str(rolls))), 1) if rolls else None,
|
||||
'ink_per_100m': {
|
||||
item: (None if quantity is None or not printed
|
||||
@@ -109,27 +119,15 @@ def ratios(printed, hours_running=None, supplies_cents=0, parts_cents=0, rolls=N
|
||||
def _printed_orders(c, machine_id, start, end):
|
||||
"""The orders that left Imprimindo for Revisão on the machine in the
|
||||
period, with what is needed to count film and what they sold."""
|
||||
return c.execute('''SELECT o.id, o.snapshot, o.parent_id, o.cancelled_at, o.payment
|
||||
return c.execute(f'''SELECT o.id, o.snapshot, o.parent_id, o.cancelled_at, o.payment, m.items, {PROOF_WINDOWS}
|
||||
FROM dtf_local.movements m JOIN dtf_local.orders o ON o.id=m.order_id
|
||||
WHERE o.machine_id=%s AND m.from_state='imp' AND m.to_state='rev' AND NOT m.back
|
||||
WHERE o.machine_id=%s AND m.from_state='imp' AND m.to_state='rev' AND NOT m.back AND {NOT_UNDONE}
|
||||
AND m.created_at>=%s AND m.created_at<%s''', (machine_id, start, end)).fetchall()
|
||||
|
||||
|
||||
def _film(snapshot):
|
||||
"""The film printed for one order (machine_log's rule), as Decimal."""
|
||||
from .proof import PROOF_SHEET_CM
|
||||
snapshot = snapshot or {}
|
||||
proof = bool(snapshot.get('proof_of'))
|
||||
total = Decimal(0)
|
||||
for item in snapshot.get('items') or []:
|
||||
if proof:
|
||||
total += PROOF_SHEET_CM
|
||||
else:
|
||||
value = item.get('metres')
|
||||
if value is None:
|
||||
value = item.get('billed_metres')
|
||||
total += Decimal(str(value or 0))
|
||||
return total
|
||||
def _film(row):
|
||||
"""The film one printed order took (machine_log's rule), as Decimal."""
|
||||
return film_metres(row['snapshot'], row.get('items'), row.get('windows'))
|
||||
|
||||
|
||||
def _sold(row):
|
||||
@@ -144,7 +142,7 @@ def _sold(row):
|
||||
|
||||
def printed_between(c, machine_id, start, end):
|
||||
"""Film metres the machine printed in [start, end), as Decimal."""
|
||||
return sum((_film(row['snapshot']) for row in _printed_orders(c, machine_id, start, end)),
|
||||
return sum((_film(row) for row in _printed_orders(c, machine_id, start, end)),
|
||||
Decimal(0))
|
||||
|
||||
|
||||
@@ -176,7 +174,7 @@ def machine_month(c, machine, start, end):
|
||||
'contribution_cents'}. `machine` is its row from dtf_local.machines."""
|
||||
mid = machine['id']
|
||||
rows = _printed_orders(c, mid, start, end)
|
||||
printed = sum((_film(row['snapshot']) for row in rows), Decimal(0))
|
||||
printed = sum((_film(row) for row in rows), Decimal(0))
|
||||
sold = sum((_sold(row) for row in rows), 0)
|
||||
ids = [row['id'] for row in rows]
|
||||
spans = c.execute('''WITH events AS (
|
||||
@@ -265,9 +263,9 @@ def report(c, month=None):
|
||||
'''SELECT DISTINCT machine_id FROM dtf_local.machine_entries
|
||||
WHERE created_at>=%s AND created_at<%s''', (start, end)).fetchall()}
|
||||
printed = {str(row['machine_id']) for row in c.execute(
|
||||
'''SELECT DISTINCT o.machine_id FROM dtf_local.movements m
|
||||
f'''SELECT DISTINCT o.machine_id FROM dtf_local.movements m
|
||||
JOIN dtf_local.orders o ON o.id=m.order_id
|
||||
WHERE m.from_state='imp' AND m.to_state='rev' AND NOT m.back
|
||||
WHERE m.from_state='imp' AND m.to_state='rev' AND NOT m.back AND {NOT_UNDONE}
|
||||
AND m.created_at>=%s AND m.created_at<%s''', (start, end)).fetchall()}
|
||||
result = []
|
||||
for machine in machines:
|
||||
|
||||
@@ -1,14 +1,17 @@
|
||||
"""The print machines, their load and the two printing places on each one."""
|
||||
"""The print machines, their load and the printing places on each one."""
|
||||
from decimal import Decimal
|
||||
|
||||
from . import machine_log
|
||||
|
||||
# Not finished: the work still ahead of a machine.
|
||||
OPEN = ('rec', 'tra', 'imp', 'cor')
|
||||
# Two orders at most in Imprimindo per machine (Dropstar, 2026-10-29): one
|
||||
# printing, the next being ripped by FlexiPRINT meanwhile. A third would
|
||||
# make the RIP choke; two mean the next sheet is ready when one ends.
|
||||
PRINTING_CAP = 2
|
||||
# Orders at most in Imprimindo per machine, and files in its hot folder at
|
||||
# once: dtf_local.machines.places, set per machine by Admin and Gestão
|
||||
# (Marcus, 2026-11-17). It was two for all (Dropstar, 2026-10-29): one
|
||||
# printing, the next ripped by FlexiPRINT meanwhile; three keeps one more
|
||||
# waiting in the folder. A new machine starts with DEFAULT_PLACES.
|
||||
DEFAULT_PLACES = 3
|
||||
MAX_PLACES = 6
|
||||
|
||||
|
||||
def product_family(order):
|
||||
@@ -36,7 +39,8 @@ def loads(c):
|
||||
|
||||
def rows(c, with_operators=False):
|
||||
"""Every machine with its load, for the Kanban."""
|
||||
machines = c.execute('''SELECT id, name, products, active, limit_metres FROM dtf_local.machines
|
||||
machines = c.execute('''SELECT id, name, COALESCE(folder, name) AS folder, products, active, limit_metres, places
|
||||
FROM dtf_local.machines
|
||||
ORDER BY created_at, name''').fetchall()
|
||||
load = loads(c)
|
||||
operators = {}
|
||||
@@ -52,8 +56,9 @@ def rows(c, with_operators=False):
|
||||
for m in machines:
|
||||
key = str(m['id'])
|
||||
used = load.get(key, {'metres': Decimal(0), 'orders': 0, 'states': {}})
|
||||
row = {'id': key, 'name': m['name'], 'products': m['products'], 'active': m['active'],
|
||||
row = {'id': key, 'name': m['name'], 'folder': m['folder'], 'products': m['products'], 'active': m['active'],
|
||||
'limit_metres': float(m['limit_metres']) if m['limit_metres'] is not None else None,
|
||||
'places': m['places'],
|
||||
'open_metres': float(used['metres']), 'open_orders': used['orders'], 'states': used['states'],
|
||||
'alerts': machine_log.alerts(c, m['id'])}
|
||||
if with_operators:
|
||||
@@ -63,22 +68,23 @@ def rows(c, with_operators=False):
|
||||
|
||||
|
||||
def full(c, machine_id, order_id):
|
||||
"""The machine's name when it already has PRINTING_CAP other orders in
|
||||
Imprimindo, so this one cannot join them; None when it has room. The
|
||||
machine's row is locked, so two pulls at once cannot both take the last
|
||||
place."""
|
||||
"""(name, places) when the machine already has its places' worth of
|
||||
other orders in Imprimindo, so this one cannot join them; None when it
|
||||
has room. The machine's row is locked, so two pulls at once cannot both
|
||||
take the last place."""
|
||||
if machine_id is None:
|
||||
return None
|
||||
machine = c.execute('SELECT name FROM dtf_local.machines WHERE id=%s FOR UPDATE', (machine_id,)).fetchone()
|
||||
machine = c.execute('SELECT name, places FROM dtf_local.machines WHERE id=%s FOR UPDATE', (machine_id,)).fetchone()
|
||||
printing = c.execute('''SELECT count(*) AS n FROM dtf_local.orders WHERE machine_id=%s AND state='imp'
|
||||
AND cancelled_at IS NULL AND id<>%s''', (machine_id, order_id)).fetchone()['n']
|
||||
return machine['name'] if machine and printing >= PRINTING_CAP else None
|
||||
return (machine['name'], machine['places']) if machine and printing >= machine['places'] else None
|
||||
|
||||
|
||||
def printing_slots(c):
|
||||
"""Per order in Imprimindo: 'imprimindo' for the first to enter it on its
|
||||
machine (ripped, running), 'ripando' for the one after it."""
|
||||
return {row['id']: 'imprimindo' if row['place'] == 1 else 'ripando' for row in c.execute('''
|
||||
machine (ripped, running), 'ripando' for the one after it, 'aguardando'
|
||||
for those after that, waiting in the hot folder."""
|
||||
return {row['id']: {1: 'imprimindo', 2: 'ripando'}.get(row['place'], 'aguardando') for row in c.execute('''
|
||||
SELECT o.id, row_number() OVER (PARTITION BY o.machine_id ORDER BY m.at, o.number) AS place
|
||||
FROM dtf_local.orders o, LATERAL (SELECT max(created_at) AS at FROM dtf_local.movements
|
||||
WHERE order_id=o.id AND to_state='imp') m
|
||||
|
||||
@@ -84,10 +84,10 @@ def order_paid(c, order, origin):
|
||||
number, link = order['number'], f"{origin}/conta/pedidos?order={order['id']}"
|
||||
text = '\n'.join([mail_html.greeting(customer.get('name')), '',
|
||||
f'Seu pagamento foi aprovado e o pedido #{number} já está com a nossa equipe. '
|
||||
'Agora a gente confere a arte e coloca na fila de impressão.', '',
|
||||
'Conferimos a arte e colocamos na fila de impressão.', '',
|
||||
*(f'{key}: {value}' for key, value in rows), '',
|
||||
f'Acompanhe cada etapa em Minha conta: {link}', '',
|
||||
'Ainda não tem conta? Crie com este e-mail e o mesmo CPF/CNPJ do pedido: ele aparece lá na hora.'])
|
||||
'Se ainda não tem conta, crie com este e-mail e o mesmo CPF/CNPJ do pedido: ele aparece lá na hora.'])
|
||||
return queue(c, 'order', customer['mail'], f'Recebemos seu pedido #{number} · DTF Dropstar', text,
|
||||
mail_html.order_paid(customer.get('name'), number, rows, link))
|
||||
|
||||
@@ -108,14 +108,14 @@ def quote_expired(c, quote, origin):
|
||||
link = f'{origin}/'
|
||||
text = '\n'.join([mail_html.greeting(customer.get('name')), '',
|
||||
'Seu pedido não foi pago em 24 horas e expirou. Os arquivos que você enviou foram apagados.', '',
|
||||
f'Quando quiser, é só montar de novo no site: {link}'])
|
||||
f'Para pedir de novo, monte no site: {link}'])
|
||||
html = mail_html.layout('Seu pedido não foi pago em 24 horas e expirou.', 'Seu pedido', [
|
||||
mail_html.pill('Pedido expirado', 'info'),
|
||||
mail_html.title('Seu pedido expirou'),
|
||||
mail_html.para(f'{mail_html.greeting(customer.get("name"))} Seu pedido não foi pago em 24 horas e '
|
||||
'expirou. Os arquivos que você enviou foram apagados.'),
|
||||
mail_html.button('Montar de novo', link),
|
||||
mail_html.small(f'Quando quiser, é só montar de novo no site: {link}'),
|
||||
mail_html.small(f'Para pedir de novo, monte no site: {link}'),
|
||||
])
|
||||
return queue(c, 'notice', customer['mail'], 'Seu pedido expirou · DTF Dropstar', text, html)
|
||||
|
||||
|
||||
@@ -152,12 +152,11 @@ def reset(name, link, minutes):
|
||||
hours = 'por 1 hora' if minutes == 60 else f'por {minutes} minutos'
|
||||
return layout('Clique no botão para criar uma nova senha.', 'Sua conta', [
|
||||
title('Crie uma nova senha'),
|
||||
para(f'{greeting(name)} Recebemos um pedido para criar uma nova senha na sua conta. '
|
||||
'É só clicar no botão abaixo.'),
|
||||
para(f'{greeting(name)} Recebemos um pedido de nova senha para a sua conta.'),
|
||||
button('Criar nova senha', link),
|
||||
small(f'O link vale {hours} e funciona uma vez só. Se não foi você, ignore este e-mail: '
|
||||
'sua senha continua a mesma.'),
|
||||
small('O botão não abriu? Copie este endereço no navegador: ',
|
||||
small('Se o botão não abrir, copie este endereço no navegador: ',
|
||||
f'<br><a href="{escape(link, quote=True)}" style="color:{DARK_ORANGE};word-break:break-all">'
|
||||
f'{escape(link)}</a>'),
|
||||
])
|
||||
@@ -167,7 +166,7 @@ def account_exists(name, login_link):
|
||||
return layout('Este e-mail já tem conta no DTF Dropstar.', 'Sua conta', [
|
||||
title('Este e-mail já tem uma conta'),
|
||||
para(f'{greeting(name)} Alguém tentou criar uma conta no DTF Dropstar com este e-mail, mas ele já está '
|
||||
'cadastrado. Para ver seus pedidos, é só entrar.'),
|
||||
'cadastrado. Entre para ver seus pedidos.'),
|
||||
button('Entrar na minha conta', login_link),
|
||||
callout('Esqueceu a senha?', 'Na página de entrada, clique em “Esqueci minha senha” e enviamos um link '
|
||||
'para criar outra.'),
|
||||
@@ -180,7 +179,7 @@ def email_changed(name, old, new):
|
||||
title('O e-mail da sua conta foi trocado'),
|
||||
para(f'{greeting(name)} A partir de agora, sua conta no DTF Dropstar entra com outro e-mail:'),
|
||||
facts([('Antes', old), ('Agora', new)]),
|
||||
callout('Não foi você?', 'Fale com a Dropstar agora pelo WhatsApp: a gente ajuda a recuperar a conta.',
|
||||
callout('Não foi você?', 'Fale com a Dropstar pelo WhatsApp para recuperar a conta.',
|
||||
warn=True),
|
||||
button('Falar no WhatsApp', WHATSAPP, dark=True),
|
||||
])
|
||||
@@ -190,14 +189,14 @@ def order_paid(name, number, rows, link):
|
||||
return layout(f'Pagamento aprovado. O pedido #{number} já está com a nossa equipe.', 'Seu pedido', [
|
||||
pill('Pagamento aprovado'),
|
||||
title(f'Recebemos seu pedido #{number}'),
|
||||
para(f'{greeting(name)} Seu pagamento foi aprovado e o pedido já está com a nossa equipe. Agora a gente '
|
||||
'confere a arte e coloca na fila de impressão.'),
|
||||
para(f'{greeting(name)} Seu pagamento foi aprovado e o pedido já está com a nossa equipe. '
|
||||
'Conferimos a arte e colocamos na fila de impressão.'),
|
||||
facts(rows),
|
||||
steps([('Pagamento aprovado', 'Pedido recebido pela equipe', True),
|
||||
('Arte conferida', 'A equipe confere se está tudo certo para imprimir', False),
|
||||
('Impressão', 'Seu filme entra na máquina', False),
|
||||
('Pronto', 'Você recebe o aviso pelo WhatsApp', False)]),
|
||||
button('Ver meu pedido', link),
|
||||
small('Acompanhe cada etapa em Minha conta. Ainda não tem conta? Crie com este e-mail e o mesmo CPF/CNPJ '
|
||||
'do pedido: ele aparece lá na hora.'),
|
||||
small('Acompanhe cada etapa em Minha conta. Se ainda não tem conta, crie com este e-mail e o mesmo '
|
||||
'CPF/CNPJ do pedido: ele aparece lá na hora.'),
|
||||
])
|
||||
|
||||
@@ -28,6 +28,7 @@ from typing import Mapping
|
||||
import httpx
|
||||
|
||||
from .adapters import PaymentEvent
|
||||
from .core.models import cnpj_ok, cpf_ok
|
||||
|
||||
API = 'https://api.mercadopago.com'
|
||||
# How old a signed timestamp may be. Mercado Pago retries a failed delivery
|
||||
@@ -41,6 +42,29 @@ PIX_MINUTES = 30
|
||||
BRASILIA = timezone(timedelta(hours=-3))
|
||||
|
||||
|
||||
def payer(customer, method=None):
|
||||
"""Who pays, as Dropstar's finance reconciles it and the invoice is issued
|
||||
(Marcus, 2026-11-18): a real CPF or CNPJ, never a placeholder such as
|
||||
999.999.999-99, with the order's name and e-mail.
|
||||
|
||||
The card form opens with the order's document already in it (web/
|
||||
checkout.js), so the card token and the payer agree. A valid document
|
||||
the customer typed there instead (someone else's card) is the payer, as
|
||||
the token says; anything else, and PIX, is the order's own."""
|
||||
document = customer['cnpj']
|
||||
identification = {'type': 'CPF' if len(document) == 11 else 'CNPJ', 'number': document}
|
||||
typed = ''.join(ch for ch in str((method or {}).get('payer_document') or '') if ch.isdigit())
|
||||
kind = (method or {}).get('payer_document_type')
|
||||
if (kind == 'CPF' and cpf_ok(typed)) or (kind == 'CNPJ' and cnpj_ok(typed)):
|
||||
identification = {'type': kind, 'number': typed}
|
||||
who = {'email': customer['mail'], 'identification': identification}
|
||||
names = (customer.get('name') or '').split()
|
||||
if names:
|
||||
who['first_name'] = names[0]
|
||||
who['last_name'] = ' '.join(names[1:]) or names[0]
|
||||
return who
|
||||
|
||||
|
||||
class MercadoPagoPayment:
|
||||
name = 'mercadopago'
|
||||
|
||||
@@ -76,9 +100,10 @@ class MercadoPagoPayment:
|
||||
body = {'transaction_amount': float(Decimal(total_cents) / 100),
|
||||
'description': f'DTF - cotação {quote_id[:8]}',
|
||||
'external_reference': quote_id,
|
||||
'payer': {'email': customer['mail'],
|
||||
'identification': {'type': 'CPF' if len(customer['cnpj']) == 11 else 'CNPJ',
|
||||
'number': customer['cnpj']}}}
|
||||
'payer': payer(customer, method if method['type'] == 'card' else None),
|
||||
# The order's own document, kept on the payment for finance
|
||||
# even when the card's holder is someone else.
|
||||
'metadata': {'documento_pedido': customer['cnpj']}}
|
||||
if self.notification_url:
|
||||
body['notification_url'] = self.notification_url
|
||||
expires_at = None
|
||||
@@ -93,9 +118,6 @@ class MercadoPagoPayment:
|
||||
# it; asking it of every card was refused as a rule (10113).
|
||||
if method['payment_method_id'].startswith('deb'):
|
||||
body['three_d_secure_mode'] = 'optional'
|
||||
if method.get('payer_document_type') and method.get('payer_document'):
|
||||
body['payer']['identification'] = {'type': method['payer_document_type'],
|
||||
'number': method['payer_document']}
|
||||
# No issuer_id: Mercado Pago takes the issuer from the card number.
|
||||
# The form's suggestion was refused for its own test cards
|
||||
# (10111, "the issuer does not have the BIN configured").
|
||||
|
||||
11
app/migrations/202611121200_redesign-product.sql
Normal file
11
app/migrations/202611121200_redesign-product.sql
Normal file
@@ -0,0 +1,11 @@
|
||||
-- Front 1b (Marcus, 2026-11-12): Ajuste Fino Redesenho, a per-art service
|
||||
-- beside the basic Ajuste Fino. Created switched OFF and without a price:
|
||||
-- Gestão sets both in the Site tab. The products CHECK is the inline
|
||||
-- constraint of dtf_local.products.id (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','redesenho'));
|
||||
|
||||
INSERT INTO dtf_local.products(id, enabled) VALUES ('redesenho', false)
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
3
app/migrations/202611121500_print-deadline.sql
Normal file
3
app/migrations/202611121500_print-deadline.sql
Normal file
@@ -0,0 +1,3 @@
|
||||
-- A print file's render limit grows with its film (RENDER_SECONDS per 15 m
|
||||
-- part, app/printjobs.py): each claim records when it counts as abandoned.
|
||||
ALTER TABLE dtf_local.print_files ADD COLUMN IF NOT EXISTS deadline_at timestamptz;
|
||||
5
app/migrations/202611161600_stamp-code-dot.sql
Normal file
5
app/migrations/202611161600_stamp-code-dot.sql
Normal file
@@ -0,0 +1,5 @@
|
||||
-- Dropstar's stamp codes carry dots (NX.226, Marcus 2026-11-16); not as the
|
||||
-- first character, as in app/api/stamps.py CODE.
|
||||
ALTER TABLE dtf_local.stamps DROP CONSTRAINT IF EXISTS stamps_code_check;
|
||||
ALTER TABLE dtf_local.stamps ADD CONSTRAINT stamps_code_check
|
||||
CHECK (code ~ '^[A-Za-z0-9_-][A-Za-z0-9._-]{0,39}$');
|
||||
5
app/migrations/202611171300_machine-places.sql
Normal file
5
app/migrations/202611171300_machine-places.sql
Normal file
@@ -0,0 +1,5 @@
|
||||
-- How many orders each machine takes in Imprimindo, and files in its hot
|
||||
-- folder at once: three, set per machine by Admin and Gestão (Marcus,
|
||||
-- 2026-11-17; it was two for every machine, app/machines.py).
|
||||
ALTER TABLE dtf_local.machines ADD COLUMN IF NOT EXISTS places smallint NOT NULL DEFAULT 3
|
||||
CHECK (places BETWEEN 1 AND 6);
|
||||
5
app/migrations/202611171310_operator-tiny-seller.sql
Normal file
5
app/migrations/202611171310_operator-tiny-seller.sql
Normal file
@@ -0,0 +1,5 @@
|
||||
-- The Tiny seller (vendedor) each Kanban user is, so a Venda the user
|
||||
-- assembles reaches Tiny with them as its seller (Marcus, 2026-11-17).
|
||||
-- Tiny takes the seller by its id; the name is kept to show it.
|
||||
ALTER TABLE dtf_local.operators ADD COLUMN IF NOT EXISTS tiny_seller_id bigint;
|
||||
ALTER TABLE dtf_local.operators ADD COLUMN IF NOT EXISTS tiny_seller_name text;
|
||||
13
app/migrations/202611261200_operator-roles.sql
Normal file
13
app/migrations/202611261200_operator-roles.sql
Normal file
@@ -0,0 +1,13 @@
|
||||
-- More than one profile per user (Marcus, 2026-11-26: operador/revisor,
|
||||
-- gestor/operador/revisor): what a user may do is the sum of their profiles.
|
||||
-- `role` stays the main one, shown first and kept for superadmin; `roles`
|
||||
-- holds every profile, the main one included.
|
||||
ALTER TABLE dtf_local.operators ADD COLUMN IF NOT EXISTS roles text[] NOT NULL DEFAULT '{}';
|
||||
UPDATE dtf_local.operators SET roles=ARRAY[role] WHERE cardinality(roles)=0;
|
||||
DO $$ BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname='operators_roles'
|
||||
AND conrelid='dtf_local.operators'::regclass) THEN
|
||||
ALTER TABLE dtf_local.operators ADD CONSTRAINT operators_roles
|
||||
CHECK (roles <@ ARRAY['superadmin','admin','gestao','designer','operador','revisor','vendedor','financeiro','expedicao']::text[]);
|
||||
END IF;
|
||||
END $$;
|
||||
5
app/migrations/202611271200_reprint-items.sql
Normal file
5
app/migrations/202611271200_reprint-items.sql
Normal file
@@ -0,0 +1,5 @@
|
||||
-- Reprinting some items of an order (Marcus, 2026-11-26, #105): the items
|
||||
-- that go to the machine this time (NULL: all), and on each pass from
|
||||
-- Imprimindo to Revisão the items that were printed, for the machine's metres.
|
||||
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS print_items integer[];
|
||||
ALTER TABLE dtf_local.movements ADD COLUMN IF NOT EXISTS items integer[];
|
||||
24
app/migrations/202611271400_print-file-version.sql
Normal file
24
app/migrations/202611271400_print-file-version.sql
Normal file
@@ -0,0 +1,24 @@
|
||||
-- "Gerar de novo" names the new files with a version (Marcus, 2026-11-27,
|
||||
-- #130): DTF-130-v2-item-1-p2.png, so neither the Kanban, the FlexiPRINT
|
||||
-- queue nor the Hoson list mixes them up with the first ones.
|
||||
ALTER TABLE dtf_local.print_files ADD COLUMN IF NOT EXISTS generation integer NOT NULL DEFAULT 1;
|
||||
|
||||
-- A Prova OK approved only the first part of a film in parts (the print
|
||||
-- file's first upload), so the other parts never reached the folders (#114,
|
||||
-- #128, #130). For the orders still before Imprimindo, the missing parts join
|
||||
-- the parts the Prumo already approved.
|
||||
-- The order's version goes up, so the board and the folders see the new finals.
|
||||
WITH added AS (
|
||||
INSERT INTO dtf_local.order_files(id,order_id,upload_id,item_index,kind,note,created_by)
|
||||
SELECT gen_random_uuid(), p.order_id, p.upload_id, p.item_index, 'final', 'Parte completada (prova)', 'Prumo'
|
||||
FROM dtf_local.print_parts p JOIN dtf_local.orders o ON o.id=p.order_id
|
||||
WHERE o.state IN ('rec','tra') AND o.cancelled_at IS NULL AND o.parent_id IS NULL
|
||||
AND EXISTS (SELECT 1 FROM dtf_local.order_files f JOIN dtf_local.print_parts q
|
||||
ON q.order_id=f.order_id AND q.item_index=f.item_index AND q.upload_id=f.upload_id
|
||||
WHERE f.order_id=p.order_id AND f.item_index=p.item_index AND f.kind='final' AND f.active
|
||||
AND f.created_by='Prumo')
|
||||
AND NOT EXISTS (SELECT 1 FROM dtf_local.order_files f WHERE f.order_id=p.order_id
|
||||
AND f.item_index=p.item_index AND f.upload_id=p.upload_id)
|
||||
RETURNING order_id
|
||||
)
|
||||
UPDATE dtf_local.orders SET version=version+1, updated_at=now() WHERE id IN (SELECT order_id FROM added);
|
||||
5
app/migrations/202611272000_machine-folder.sql
Normal file
5
app/migrations/202611272000_machine-folder.sql
Normal file
@@ -0,0 +1,5 @@
|
||||
-- Each machine's hot folder (3. Imprimindo/<folder>/C1..) is fixed when the
|
||||
-- machine is created: FlexiPRINT watches that path, so renaming the machine
|
||||
-- must not send its files to a folder nobody watches (2026-11-27).
|
||||
ALTER TABLE dtf_local.machines ADD COLUMN IF NOT EXISTS folder text;
|
||||
UPDATE dtf_local.machines SET folder=name WHERE folder IS NULL;
|
||||
@@ -45,10 +45,10 @@ def seed_from_environment(cursor):
|
||||
'SELECT id FROM dtf_local.operators WHERE email=%s', (email,)).fetchone()
|
||||
if existing:
|
||||
# The configured account is the system's own: it stays superadmin.
|
||||
cursor.execute("UPDATE dtf_local.operators SET role='superadmin' WHERE email=%s", (email,))
|
||||
cursor.execute("UPDATE dtf_local.operators SET role='superadmin',roles=ARRAY['superadmin'] WHERE email=%s", (email,))
|
||||
return None
|
||||
cursor.execute(
|
||||
"INSERT INTO dtf_local.operators(id,email,name,password_hash,role) VALUES(%s,%s,%s,%s,'superadmin')",
|
||||
"INSERT INTO dtf_local.operators(id,email,name,password_hash,role,roles) VALUES(%s,%s,%s,%s,'superadmin',ARRAY['superadmin'])",
|
||||
(uuid4(), email, 'Operador', password_hash(password)))
|
||||
return email
|
||||
|
||||
@@ -69,8 +69,8 @@ def add(email, name='', role='admin'):
|
||||
with connect() as c:
|
||||
if c.execute('SELECT id FROM dtf_local.operators WHERE email=%s', (email,)).fetchone():
|
||||
raise SystemExit(f'{email} already exists. Use "password" or "enable".')
|
||||
c.execute('INSERT INTO dtf_local.operators(id,email,name,password_hash,role) VALUES(%s,%s,%s,%s,%s)',
|
||||
(uuid4(), email, name, password_hash(_ask_password(email)), role))
|
||||
c.execute('INSERT INTO dtf_local.operators(id,email,name,password_hash,role,roles) VALUES(%s,%s,%s,%s,%s,%s)',
|
||||
(uuid4(), email, name, password_hash(_ask_password(email)), role, [role]))
|
||||
print(f'Added {email} as {role}.')
|
||||
|
||||
|
||||
@@ -79,7 +79,8 @@ def set_role(email, role):
|
||||
if role not in ROLES:
|
||||
raise SystemExit('Role must be one of: ' + ', '.join(ROLES))
|
||||
with connect() as c:
|
||||
if not c.execute('UPDATE dtf_local.operators SET role=%s WHERE email=%s RETURNING id', (role, email)).fetchone():
|
||||
if not c.execute('UPDATE dtf_local.operators SET role=%s,roles=%s WHERE email=%s RETURNING id',
|
||||
(role, [role], email)).fetchone():
|
||||
raise SystemExit(f'{email} does not exist.')
|
||||
print(f'{email} is now {role}.')
|
||||
|
||||
|
||||
@@ -24,14 +24,20 @@ from .runtime import PUBLIC_ORIGIN, enqueue, upload_row
|
||||
from .scanning import require_clean
|
||||
|
||||
QUOTE_VALID_HOURS = 24
|
||||
# A card the provider holds "em análise" may be approved hours or days later:
|
||||
# its quote stays open, its files kept and the provider asked this long.
|
||||
CARD_REVIEW_HOURS = 72
|
||||
|
||||
|
||||
class PaymentRefused(Exception):
|
||||
"""The payment cannot become an order, with a reason worth recording."""
|
||||
|
||||
|
||||
def approved_quote(c, quote_id, owner=None):
|
||||
"""The reviewed quote behind a payment, or a refusal explaining why not."""
|
||||
def approved_quote(c, quote_id, owner=None, payment_id=None):
|
||||
"""The reviewed quote behind a payment, or a refusal explaining why not.
|
||||
`payment_id`, from a provider's notice: a payment started while the quote
|
||||
was valid is honoured whenever its approval arrives (a PIX paid in its
|
||||
last minutes, a card approved after review)."""
|
||||
sql = 'SELECT * FROM dtf_local.quotes WHERE id=%s' + (' AND owner=%s' if owner else '')
|
||||
row = c.execute(sql + ' FOR UPDATE', (quote_id, owner) if owner else (quote_id,)).fetchone()
|
||||
if not row:
|
||||
@@ -42,7 +48,12 @@ def approved_quote(c, quote_id, owner=None):
|
||||
raise PaymentRefused('quote was discarded')
|
||||
if any(item.get('production', {}).get('version') not in PRODUCTION_VERSIONS for item in row['approved']['items']):
|
||||
raise PaymentRefused('quote uses an obsolete production layout; request a new quote')
|
||||
if row['approved_at'] < datetime.now(timezone.utc) - timedelta(hours=QUOTE_VALID_HOURS):
|
||||
deadline = row['approved_at'] + timedelta(hours=QUOTE_VALID_HOURS)
|
||||
if deadline < datetime.now(timezone.utc):
|
||||
started = payment_id and c.execute('''SELECT 1 FROM dtf_local.payment_intents
|
||||
WHERE quote_id=%s AND provider_payment_id=%s AND created_at <= %s''',
|
||||
(quote_id, str(payment_id), deadline)).fetchone()
|
||||
if not started:
|
||||
raise PaymentRefused('quote expired before payment')
|
||||
return row
|
||||
|
||||
@@ -77,6 +88,34 @@ def in_tiny(order):
|
||||
return not is_test(order) and not order.get('parent_id')
|
||||
|
||||
|
||||
# What a stage tells Tiny: entering the queue (Arte conferida) is its
|
||||
# "Preparando envio", Finalizado its "Pronto para envio" (Dropstar's flow,
|
||||
# 2026-10-23); a correction has no situação and is only recorded.
|
||||
STAGE_EVENTS = {'tra': 'production_started', 'cor': 'correction_needed', 'fin': 'ready'}
|
||||
|
||||
|
||||
def stage_event(c, order, state, reason, version):
|
||||
"""Queue Tiny's event for an order that entered `state` (not by a step
|
||||
back), whoever moved it: a card dragged, or the Prova OK that puts the
|
||||
order in the queue (app/proof.py). `order` is its row before the move,
|
||||
`version` its version after."""
|
||||
if state not in STAGE_EVENTS or not in_tiny(order):
|
||||
return
|
||||
# "Production started" and "ready" reach the customer once per order,
|
||||
# even if a mistaken move is undone and made again. Each correction is a
|
||||
# new request, so it keeps one message per movement.
|
||||
once = state in ('tra', 'fin')
|
||||
event = {'order_id': str(order['id']), 'number': order['number'], 'event': STAGE_EVENTS[state],
|
||||
'reason': reason, 'customer_path': f"/portal.html?order={order['id']}"}
|
||||
# Tiny needs the order (customer, pickup or delivery) and, once the sale
|
||||
# reached it, its id, to set the situação without a search.
|
||||
sale = c.execute("SELECT receipt FROM dtf_local.outbox WHERE event_key=%s AND delivered_at IS NOT NULL",
|
||||
(f"{order['id']}:paid:tiny",)).fetchone()
|
||||
tiny = {**event, 'order': order['snapshot'], 'tiny_id': ((sale or {}).get('receipt') or {}).get('tiny_id')}
|
||||
key = f"{order['id']}:{STAGE_EVENTS[state]}:tiny" if once else f"{order['id']}:{version}:tiny"
|
||||
enqueue(c, key, 'tiny', tiny)
|
||||
|
||||
|
||||
# How long a file is kept while nothing has been paid for it. A cart's files
|
||||
# are uploaded before payment, so the price and the security check are done on
|
||||
# the file itself; a cart that is never paid must not keep them for 30 days.
|
||||
@@ -212,7 +251,7 @@ def apply(c, event):
|
||||
return 'refused: reference is not a quote id'
|
||||
|
||||
try:
|
||||
quote = approved_quote(c, quote_id)
|
||||
quote = approved_quote(c, quote_id, payment_id=provider_id)
|
||||
except PaymentRefused as refusal:
|
||||
return f'refused: {refusal}'
|
||||
|
||||
@@ -227,7 +266,16 @@ def apply(c, event):
|
||||
return f'refused: paid {event.amount_cents} but quote total is {expected}'
|
||||
|
||||
order, created = create_order(c, quote, {'provider': event.raw.get('provider', 'webhook'), **event.raw}, 'site')
|
||||
return f"order {order['number']}" + ('' if created else ' (already existed)')
|
||||
if created:
|
||||
return f"order {order['number']}"
|
||||
# The order exists, paid by another payment (a PIX and a card for the same
|
||||
# cart, or paid outside the site too): the customer paid twice. Listed on
|
||||
# the Kanban until someone refunds one, like a reversal.
|
||||
first = str((order.get('payment') or {}).get('payment_id') or '')
|
||||
if provider_id and str(provider_id) != first:
|
||||
audit('payment_duplicate', order=order['number'], payment=str(provider_id), c=c)
|
||||
return f"attention: second payment {provider_id} for order {order['number']}; refund one"
|
||||
return f"order {order['number']} (already existed)"
|
||||
|
||||
|
||||
def reconcile(connect, provider, quote_id=None, limit=20):
|
||||
@@ -245,7 +293,7 @@ def reconcile(connect, provider, quote_id=None, limit=20):
|
||||
WHERE o.id IS NULL AND i.provider=%s AND i.status IN ('pending','approved')
|
||||
AND i.created_at > now() - make_interval(hours => %s)''' +
|
||||
(' AND i.quote_id=%s' if quote_id else '') + ' ORDER BY i.created_at DESC LIMIT %s',
|
||||
(provider.name, QUOTE_VALID_HOURS + 1, *([quote_id] if quote_id else []), limit)).fetchall()
|
||||
(provider.name, CARD_REVIEW_HOURS + 1, *([quote_id] if quote_id else []), limit)).fetchall()
|
||||
outcomes = []
|
||||
for row in rows:
|
||||
# Asked outside any transaction: no lock is held while the provider answers.
|
||||
|
||||
@@ -27,6 +27,7 @@ from decimal import Decimal
|
||||
from PIL import Image, ImageOps
|
||||
|
||||
from .core.models import PRODUCTION_VERSIONS
|
||||
from .core.pricing import STEP_GRACE_M
|
||||
|
||||
PT_PER_CM = 72 / 2.54
|
||||
# Acrobat's page limit, 200 inches (5,08 m). A longer sheet is written at its
|
||||
@@ -387,7 +388,8 @@ def check_layout(item, sizes, vector=(), proof=False):
|
||||
production = item['production']
|
||||
height = Decimal(str(production['height_cm']))
|
||||
billed = Decimal(str(item['billed_metres'])) * 100
|
||||
if not proof and height > billed + HEIGHT_TOLERANCE_CM:
|
||||
# Up to 8 mm past the billed length is the customer's grace (app/core/pricing.py).
|
||||
if not proof and height > billed + STEP_GRACE_M * 100 + HEIGHT_TOLERANCE_CM:
|
||||
raise Unsupported(f'a montagem tem {height} cm, mas só {billed} cm foram cobrados')
|
||||
lowest = None
|
||||
for placement in production['placements']:
|
||||
|
||||
175
app/printjobs.py
175
app/printjobs.py
@@ -2,11 +2,12 @@
|
||||
|
||||
A paid order queues one job per item. The worker claims a job, commits the
|
||||
claim, and renders outside any transaction, so a long render never holds a row
|
||||
lock or a database connection. A claim older than CLAIM_TIMEOUT is assumed to
|
||||
belong to a worker that died and is taken again.
|
||||
lock or a database connection. A claim past its deadline (the render limit
|
||||
plus a margin; CLAIM_TIMEOUT for a claim made before deadlines existed) is
|
||||
assumed to belong to a worker that died and is taken again.
|
||||
|
||||
The result is a 300 DPI PNG (item 13, app/printpng.py), or its parts for a
|
||||
film over 15 m: ordinary upload rows owned by an identity derived from the
|
||||
film longer than a part (10 m): ordinary upload rows owned by an identity derived from the
|
||||
order, already marked clean, since their only inputs are artwork that passed
|
||||
the malware scan and the bytes are written here. dtf_local.print_parts lists
|
||||
them in order. The operator still decides whether they become the final
|
||||
@@ -29,27 +30,48 @@ from decimal import Decimal
|
||||
from zoneinfo import ZoneInfo
|
||||
from uuid import NAMESPACE_URL, UUID, uuid4, uuid5
|
||||
|
||||
import psycopg
|
||||
from psycopg.types.json import Jsonb
|
||||
from PIL import Image
|
||||
|
||||
from .cart_pricing import needs_designer
|
||||
from .core.auth import audit
|
||||
from .core.db import connect
|
||||
from .printfile import Unsupported
|
||||
from .printpng import render
|
||||
from .printpng import part_cuts, render
|
||||
from . import proof
|
||||
from .proof import PROOF_SHEET_CM
|
||||
from .tiny import purchase_order
|
||||
|
||||
LOCAL = ZoneInfo('America/Sao_Paulo')
|
||||
|
||||
# A 15 m part takes minutes to write; a long film, several parts.
|
||||
RENDER_SECONDS = int(os.environ.get('PRINT_RENDER_TIMEOUT_SECONDS', '900'))
|
||||
CLAIM_TIMEOUT = timedelta(minutes=18)
|
||||
# A 15 m part takes about 7 min to write on a fast core; a long film, several
|
||||
# parts. The limit is per part: order #20's 23.6 m film (2026-11-12) ran past a
|
||||
# single 15 min limit for the whole film.
|
||||
RENDER_SECONDS = int(os.environ.get('PRINT_RENDER_TIMEOUT_SECONDS', '1200'))
|
||||
CLAIM_MARGIN = timedelta(minutes=3)
|
||||
CLAIM_TIMEOUT = timedelta(seconds=RENDER_SECONDS) + CLAIM_MARGIN
|
||||
# A claim is stale once past its deadline.
|
||||
STALE = 'COALESCE({p}.deadline_at, {p}.claimed_at + %s) < now()'
|
||||
MAX_ATTEMPTS = 3
|
||||
LARGE_SOURCE_BYTES = int(os.environ.get('PRINT_DECODE_MAX_BYTES', str(300 * 1024 * 1024)))
|
||||
# Read band by band, whatever their size.
|
||||
STREAMED = ('.png', '.pdf')
|
||||
|
||||
|
||||
def render_seconds(item):
|
||||
"""The render limit of one item: RENDER_SECONDS for each part of its
|
||||
film, and one more for a film in parts: a cut moved back to a clear band
|
||||
(#136) can leave one part more than the layout alone counts."""
|
||||
production = item.get('production') or {}
|
||||
try:
|
||||
parts = len(part_cuts(production)) - 1 if production.get('placements') else 1
|
||||
except (KeyError, TypeError, ValueError, ArithmeticError):
|
||||
parts = 1
|
||||
parts = max(1, parts)
|
||||
return RENDER_SECONDS * (parts + 1 if parts > 1 else 1)
|
||||
|
||||
|
||||
def generated_identity(order_id):
|
||||
return uuid5(NAMESPACE_URL, f'dtf-print-file:{order_id}')
|
||||
|
||||
@@ -92,17 +114,29 @@ def queue(c, order_id, items, only_missing=False):
|
||||
ON CONFLICT(order_id,item_index) DO UPDATE SET status='pending', attempts=0,
|
||||
claimed_at=NULL, claim_token=NULL, finished_at=NULL, upload_id=NULL, detail='{}'
|
||||
WHERE dtf_local.print_files.status IN ('failed','manual') OR
|
||||
(dtf_local.print_files.status='rendering' AND dtf_local.print_files.claimed_at<now()-%s)''',
|
||||
(dtf_local.print_files.status='rendering' AND '''
|
||||
+ STALE.format(p='dtf_local.print_files') + ')',
|
||||
(uuid4(), order_id, index, CLAIM_TIMEOUT))
|
||||
else:
|
||||
c.execute('''INSERT INTO dtf_local.print_files(id,order_id,item_index) VALUES(%s,%s,%s)
|
||||
ON CONFLICT(order_id,item_index) DO NOTHING''', (uuid4(), order_id, index))
|
||||
|
||||
|
||||
def requeue(c, order_id, items):
|
||||
"""Generate every item again, a ready one too: after the part size
|
||||
changed (PART_CM; order #36, 2026-11-17). One rendering now is left alone."""
|
||||
for index in range(items):
|
||||
c.execute('''INSERT INTO dtf_local.print_files(id,order_id,item_index) VALUES(%s,%s,%s)
|
||||
ON CONFLICT(order_id,item_index) DO UPDATE SET status='pending', attempts=0,
|
||||
claimed_at=NULL, claim_token=NULL, finished_at=NULL, upload_id=NULL, detail='{}',
|
||||
generation=dtf_local.print_files.generation+1
|
||||
WHERE dtf_local.print_files.status<>'rendering' ''', (uuid4(), order_id, index))
|
||||
|
||||
|
||||
def claim(c):
|
||||
return c.execute('''SELECT p.*, o.snapshot, o.number, o.parent_id, o.created_at AS ordered_at FROM dtf_local.print_files p
|
||||
JOIN dtf_local.orders o ON o.id=p.order_id
|
||||
WHERE p.status='pending' OR (p.status='rendering' AND p.claimed_at < now()-%s)
|
||||
WHERE p.status='pending' OR (p.status='rendering' AND ''' + STALE.format(p='p') + ''')
|
||||
ORDER BY CASE WHEN o.parent_id IS NOT NULL THEN 0 ELSE 1 END, p.created_at
|
||||
FOR UPDATE OF p SKIP LOCKED LIMIT 1''', (CLAIM_TIMEOUT,)).fetchone()
|
||||
|
||||
@@ -119,13 +153,13 @@ def _render_child(result_queue, job, item, uploads):
|
||||
result_queue.put(('error', type(exc).__name__))
|
||||
|
||||
|
||||
def render_with_timeout(job, item, uploads):
|
||||
def render_with_timeout(job, item, uploads, seconds=RENDER_SECONDS):
|
||||
ctx = multiprocessing.get_context('spawn')
|
||||
result_queue = ctx.Queue()
|
||||
process = ctx.Process(target=_render_child, args=(result_queue, job, item, uploads))
|
||||
process.start()
|
||||
try:
|
||||
process.join(RENDER_SECONDS)
|
||||
process.join(seconds)
|
||||
if process.is_alive():
|
||||
process.terminate()
|
||||
process.join(5)
|
||||
@@ -148,10 +182,12 @@ def render_one(storage):
|
||||
if not job:
|
||||
return False
|
||||
token = uuid4()
|
||||
c.execute('''UPDATE dtf_local.print_files SET status='rendering', claimed_at=now(),
|
||||
attempts=attempts+1,claim_token=%s WHERE id=%s''', (token, job['id']))
|
||||
job['claim_token'] = token
|
||||
item = job['snapshot']['items'][job['item_index']]
|
||||
seconds = render_seconds(item)
|
||||
c.execute('''UPDATE dtf_local.print_files SET status='rendering', claimed_at=now(),
|
||||
deadline_at=now()+%s, attempts=attempts+1,claim_token=%s WHERE id=%s''',
|
||||
(timedelta(seconds=seconds) + CLAIM_MARGIN, token, job['id']))
|
||||
job['claim_token'] = token
|
||||
source_ids = [UUID(u) for u in item['uploads']]
|
||||
# A format such as CDR needs a human to prepare the full-size final on
|
||||
# the parent. The child still generates its own 15 cm proof from that PNG,
|
||||
@@ -177,8 +213,14 @@ def render_one(storage):
|
||||
source_ids = [source['id']]
|
||||
item = {**item, 'uploads': [str(source['id'])]}
|
||||
job['proof_fallback'] = True
|
||||
elif job['snapshot'].get('treatment'):
|
||||
elif needs_designer(job['snapshot']):
|
||||
job['wait_for_treatment'] = True
|
||||
# The small pictures the Site sent of each file: where a proof finds
|
||||
# the colours to sample (app/printpng.py film_scan).
|
||||
if job['snapshot'].get('proof_of') and not job.get('proof_fallback'):
|
||||
job['pictures'] = {str(r['upload_id']): bytes(r['data']) for r in c.execute(
|
||||
'SELECT upload_id,data FROM dtf_local.upload_thumbnails WHERE upload_id=ANY(%s)',
|
||||
(source_ids,)).fetchall()}
|
||||
uploads = c.execute('''SELECT id,name,size,object_key,scan_state,purged_at,expires_at,
|
||||
(expires_at<=now()) AS expired FROM dtf_local.uploads WHERE id=ANY(%s)''',
|
||||
(source_ids,)).fetchall()
|
||||
@@ -194,17 +236,23 @@ def render_one(storage):
|
||||
'monte a folha a partir do original'})
|
||||
audit('print_file_manual', order=str(job['order_id']), item=job['item_index'])
|
||||
return True
|
||||
outcome, result = render_with_timeout(job, item, by_id)
|
||||
outcome, result = render_with_timeout(job, item, by_id, seconds)
|
||||
if outcome == 'manual':
|
||||
finish(job, 'manual', {'reason': result})
|
||||
audit('print_file_manual', order=str(job['order_id']), item=job['item_index'])
|
||||
return True
|
||||
if outcome == 'timeout':
|
||||
finish(job, 'failed', {'reason': f'Tempo limite de {RENDER_SECONDS // 60} min excedido. Gere de novo.'})
|
||||
finish(job, 'failed', {'reason': f'Tempo limite de {seconds // 60} min excedido. Gere de novo.'})
|
||||
audit('print_file_timeout', order=str(job['order_id']), item=job['item_index'])
|
||||
# The card says so too, but Sentry (and the Vigia) hear of it first.
|
||||
logging.error('Print file generation timed out after %s min: order #%s item %s',
|
||||
seconds // 60, job['number'], job['item_index'] + 1)
|
||||
return True
|
||||
if outcome == 'error':
|
||||
final = job['attempts'] + 1 >= MAX_ATTEMPTS
|
||||
if final:
|
||||
logging.error('Print file generation failed: order #%s item %s: %s',
|
||||
job['number'], job['item_index'] + 1, result)
|
||||
finish(job, 'failed' if final else 'pending', {'error': result,
|
||||
'reason': 'A geração falhou. Gere de novo.' if final else ''})
|
||||
return True
|
||||
@@ -218,9 +266,17 @@ def render_one(storage):
|
||||
stored.append((uid, name, os.path.getsize(path), key))
|
||||
store_tiles(storage, os.path.join(scratch, 'tiles', name), uid)
|
||||
except Exception as exc:
|
||||
# Storage failing is an attempt like any other, not a claim held for an hour.
|
||||
logging.exception('Storing the print file failed')
|
||||
finish(job, 'failed' if job['attempts'] + 1 >= MAX_ATTEMPTS else 'pending', {'error': type(exc).__name__})
|
||||
# Storage failing is an attempt like any other, not a claim held for an
|
||||
# hour. The storage client already waited out a short outage; Sentry
|
||||
# hears of one that outlasts every attempt, once, not of each retry
|
||||
# (Sentry DTF-API-A).
|
||||
final = job['attempts'] + 1 >= MAX_ATTEMPTS
|
||||
if final:
|
||||
logging.exception('Storing the print file failed: order #%s item %s', job['number'], job['item_index'] + 1)
|
||||
else:
|
||||
logging.warning('Storing the print file failed, retrying: order #%s item %s: %s',
|
||||
job['number'], job['item_index'] + 1, exc)
|
||||
finish(job, 'failed' if final else 'pending', {'error': type(exc).__name__})
|
||||
return True
|
||||
finally:
|
||||
shutil.rmtree(scratch, ignore_errors=True)
|
||||
@@ -252,6 +308,11 @@ def render_one(storage):
|
||||
(id,order_id,upload_id,item_index,kind,note,created_by)
|
||||
VALUES(%s,%s,%s,%s,'final','Prova gerada automaticamente pelo Prumo','Prumo')''',
|
||||
(uuid4(), job['order_id'], stored[0][0], job['item_index']))
|
||||
elif not job['parent_id']:
|
||||
# A Prova OK given while this file was still being generated.
|
||||
order = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (job['order_id'],)).fetchone()
|
||||
if order['proof_ok_at']:
|
||||
proof.approve_parent(c, order, 'Prumo')
|
||||
audit('print_file_ready', order=str(job['order_id']), item=job['item_index'], parts=len(stored))
|
||||
return True
|
||||
|
||||
@@ -266,17 +327,31 @@ def store_tiles(storage, folder, upload_id):
|
||||
storage.store(f'originals/tiles/{upload_id}/{level}/{strip}', os.path.join(folder, level, strip), 'image/png')
|
||||
|
||||
|
||||
def file_prefix(number, item_index):
|
||||
def file_prefix(number, item_index, generation=1):
|
||||
"""How an order's files are named: DTF-23-item-1, the code the Kanban
|
||||
copies, the footer prints and Tiny keeps (Dropstar, 2026-10-23)."""
|
||||
return f'DTF-{number}-item-{item_index + 1}'
|
||||
copies, the footer prints and Tiny keeps (Dropstar, 2026-10-23); after
|
||||
"Gerar de novo", DTF-23-v2-item-1, so no one takes the new files for the
|
||||
old ones (Marcus, 2026-11-27, #130)."""
|
||||
version = f'-v{generation}' if generation and generation > 1 else ''
|
||||
return f'DTF-{number}{version}-item-{item_index + 1}'
|
||||
|
||||
|
||||
def _footer_name(name):
|
||||
"""A customer name for the footer: tidy, printable in cp1252 and at most
|
||||
24 characters, the last one an ellipsis when cut."""
|
||||
cleaned = ' '.join(str(name or '').split())
|
||||
cleaned = cleaned.encode('cp1252', 'ignore').decode('cp1252')
|
||||
cleaned = ' '.join(cleaned.split())
|
||||
if len(cleaned) > 24:
|
||||
cleaned = cleaned[:23] + '…'
|
||||
return cleaned
|
||||
|
||||
|
||||
def footer(job, item):
|
||||
"""The print file's footer line: DROPSTAR · Pedido DTF-123 · Item 1/2 ·
|
||||
21/10/2026 · 0,90 m, and · ESPELHADO when the artwork is mirrored. The
|
||||
order is named by its Kanban number, which Tiny keeps; the length is the
|
||||
one billed."""
|
||||
"""The print file's footer line: DROPSTAR · Pedido DTF-123 · <customer> ·
|
||||
Item 1/2 · 21/10/2026 · 0,90 m · <pieces>, and · ESPELHADO when the
|
||||
artwork is mirrored. The order is named by its Kanban number, which Tiny
|
||||
keeps; the length is the one billed."""
|
||||
count = len(job['snapshot']['items'])
|
||||
day = job['ordered_at'].astimezone(LOCAL).strftime('%d/%m/%Y')
|
||||
billed = f"{Decimal(str(item['billed_metres'])):.2f}".replace('.', ',')
|
||||
@@ -284,15 +359,38 @@ def footer(job, item):
|
||||
if proof_of:
|
||||
return ' · '.join(['DROPSTAR', f'PROVA do #{proof_of}',
|
||||
f'Classe {item.get("stroke_class") or "C3"}', day])
|
||||
fields = ['DROPSTAR', f'Pedido {purchase_order(job["number"])}',
|
||||
f'Item {job["item_index"] + 1}/{count}', day, f'{billed} m']
|
||||
fields = ['DROPSTAR', f'Pedido {purchase_order(job["number"])}']
|
||||
customer = _footer_name((job['snapshot'].get('customer') or {}).get('name'))
|
||||
if customer:
|
||||
fields.append(customer)
|
||||
fields += [f'Item {job["item_index"] + 1}/{count}', day, f'{billed} m']
|
||||
production = item.get('production') or {}
|
||||
sources = production.get('sources') or []
|
||||
placements = production.get('placements') or []
|
||||
if any(source.get('kind') == 'artwork' for source in sources):
|
||||
pieces = len(placements)
|
||||
if pieces:
|
||||
fields.append(f'{pieces} peça' if pieces == 1 else f'{pieces} peças')
|
||||
elif any(source.get('kind') == 'sheet' for source in sources):
|
||||
copies = sum(source.get('copies') or 0 for source in sources)
|
||||
if copies > 1:
|
||||
fields.append(f'{copies} cópias')
|
||||
# A mirrored artwork (UV only) is named on the sheet, for the room to see
|
||||
# before printing (Dropstar, 2026-10-23).
|
||||
if any(source.get('mirrored') for source in item['production']['sources']):
|
||||
if any(source.get('mirrored') for source in sources):
|
||||
fields.append('ESPELHADO')
|
||||
return ' · '.join(fields)
|
||||
|
||||
|
||||
def pictures_by_source(item, pictures):
|
||||
"""The small pictures by source index, as the proof's scan reads them."""
|
||||
if not pictures:
|
||||
return None
|
||||
sources = item['production']['sources']
|
||||
found = {i: pictures[str(s['upload_id'])] for i, s in enumerate(sources) if str(s['upload_id']) in pictures}
|
||||
return found or None
|
||||
|
||||
|
||||
def produce(storage, job, item, uploads):
|
||||
"""Fetch the item's artwork and render it. Returns (folder, [(png path,
|
||||
name)], evidence); the caller removes the folder."""
|
||||
@@ -335,10 +433,11 @@ def produce(storage, job, item, uploads):
|
||||
proof_of = job['snapshot'].get('proof_of')
|
||||
# The child owns its final file; the class names its proof.
|
||||
prefix = (f'DTF-{job["number"]}-prova-{item.get("stroke_class") or "C3"}' if proof_of
|
||||
else file_prefix(job['number'], job['item_index']))
|
||||
else file_prefix(job['number'], job['item_index'], job.get('generation')))
|
||||
parts, detail = render(item, files, output, prefix, footer=footer(job, item), tiles=True,
|
||||
limit_cm=PROOF_SHEET_CM if proof_of else None,
|
||||
proof_fraction=item.get('proof_y_fraction') if proof_of else None)
|
||||
proof_fraction=item.get('proof_y_fraction') if proof_of else None,
|
||||
pictures=pictures_by_source(item, job.get('pictures')))
|
||||
except BaseException:
|
||||
shutil.rmtree(output, ignore_errors=True)
|
||||
raise
|
||||
@@ -354,10 +453,22 @@ def finish(job, status, detail):
|
||||
|
||||
|
||||
def render_loop(storage):
|
||||
down_since, delay = None, 2
|
||||
while True:
|
||||
try:
|
||||
if render_one(storage):
|
||||
continue
|
||||
except psycopg.OperationalError as exc:
|
||||
# A restart takes the database away for seconds: say so once.
|
||||
if down_since is None:
|
||||
down_since = time.monotonic()
|
||||
logging.warning('Print render worker: database unavailable, retrying: %s', exc)
|
||||
time.sleep(delay)
|
||||
delay = min(delay * 2, 15)
|
||||
continue
|
||||
except Exception:
|
||||
logging.exception('Print render worker tick failed')
|
||||
if down_since is not None:
|
||||
logging.info('Print render worker: database back after %s s', int(time.monotonic() - down_since))
|
||||
down_since, delay = None, 2
|
||||
time.sleep(2)
|
||||
|
||||
384
app/printpng.py
384
app/printpng.py
@@ -19,10 +19,12 @@ holds a whole sheet: the film is composed and written in bands of rows.
|
||||
- Loose artwork is small: each file is decoded, turned and scaled to its place
|
||||
once, and copied into every band it crosses.
|
||||
|
||||
A layout longer than 15 m leaves as parts of up to 15 m (Dropstar,
|
||||
2026-10-30), DTF-7-item-1-p3.png, each with its footer saying which part it
|
||||
is. Loose artwork is cut where no piece crosses; a finished sheet is cut
|
||||
between copies when it can be, and through the artwork when not.
|
||||
A layout longer than a part leaves as parts of up to PART_CM, 10 m since
|
||||
Marcus's 18/11 answer (Flexi opens up to 4 GB per image; Dropstar,
|
||||
2026-10-30, was 15 m), DTF-7-item-1-p3.png, each with its footer saying which part it
|
||||
is. Loose artwork is cut where no piece crosses; a finished sheet between
|
||||
copies, or else in a clear band of its own pixels, and through the artwork
|
||||
only when it has none (#136).
|
||||
"""
|
||||
import io
|
||||
import math
|
||||
@@ -40,11 +42,14 @@ from .printtiles import Pyramid
|
||||
|
||||
DPI = 300
|
||||
PX_PER_CM = DPI / 2.54
|
||||
# Parts of up to 15 m, 6732 x 177165 px (Dropstar, 2026-10-30).
|
||||
PART_CM = Decimal(os.environ.get('PRINT_PART_CM', '1500'))
|
||||
# Parts of up to 10 m (Marcus, 2026-11-18): a 15 m part, 6732 x 177165 px, is
|
||||
# 4,8 GB decoded and FlexiPRINT refuses it. PRINT_PART_CM overrides it.
|
||||
PART_CM = Decimal(os.environ.get('PRINT_PART_CM', '1000'))
|
||||
# A cut through artwork only when no gap between pieces is this close to the limit.
|
||||
CUT_SEARCH_CM = Decimal('200')
|
||||
BAND_ROWS = 512
|
||||
# A pixel above this alpha takes ink (web/site-sheet.js ALFA_TINTA).
|
||||
INK_ALPHA = 10
|
||||
# Above this a source is read band by band instead of decoded whole.
|
||||
STREAM_ABOVE_PIXELS = 40_000_000
|
||||
FOOTER_TEXT_CM = 1.1
|
||||
@@ -68,8 +73,9 @@ class PngWriter:
|
||||
def __init__(self, fp, width, height):
|
||||
self.fp, self.width, self.height = fp, width, height
|
||||
self.rows = 0
|
||||
self.previous = None # the last row written, as an image
|
||||
self.z = zlib.compressobj(6)
|
||||
# Level 1 and no row filter: the same size as Pillow's filters at
|
||||
# level 6, in under half the time. #81's 91,5 m took 6 hours (2026-11-25).
|
||||
self.z = zlib.compressobj(1)
|
||||
self.pending = []
|
||||
fp.write(b'\x89PNG\r\n\x1a\n')
|
||||
_chunk(fp, b'IHDR', struct.pack('>IIBBBBB', width, height, 8, 6, 0, 0, 0))
|
||||
@@ -83,18 +89,9 @@ class PngWriter:
|
||||
rows = image.height
|
||||
if self.rows + rows > self.height:
|
||||
raise ValueError('more rows than the file has')
|
||||
# The previous row on top, so each row's filter refers to the real row
|
||||
# above it; that first filtered row is dropped.
|
||||
lead = 1 if self.previous is not None else 0
|
||||
framed = Image.new('RGBA', (self.width, rows + lead))
|
||||
if lead:
|
||||
framed.paste(self.previous, (0, 0))
|
||||
framed.paste(image, (0, lead))
|
||||
encoded = io.BytesIO()
|
||||
framed.save(encoded, 'PNG', compress_level=0)
|
||||
filtered = zlib.decompress(_idat(encoded.getvalue()))
|
||||
self._write(filtered[lead * (1 + 4 * self.width):])
|
||||
self.previous = image.crop((0, rows - 1, self.width, rows))
|
||||
raw, stride = image.tobytes(), 4 * self.width
|
||||
# Each row behind its filter byte, 0 (none).
|
||||
self._write(b''.join(b'\x00' + raw[i * stride:(i + 1) * stride] for i in range(rows)))
|
||||
self.rows += rows
|
||||
|
||||
def _write(self, data):
|
||||
@@ -117,17 +114,6 @@ class PngWriter:
|
||||
_chunk(self.fp, b'IEND', b'')
|
||||
|
||||
|
||||
def _idat(png):
|
||||
"""The concatenated IDAT data of an in-memory PNG."""
|
||||
data, at = [], 8
|
||||
while at < len(png):
|
||||
size, kind = struct.unpack('>I4s', png[at:at + 8])
|
||||
if kind == b'IDAT':
|
||||
data.append(png[at + 8:at + 8 + size])
|
||||
at += 12 + size
|
||||
return b''.join(data)
|
||||
|
||||
|
||||
# ---- Reading ----------------------------------------------------------------
|
||||
|
||||
class PngRows:
|
||||
@@ -226,6 +212,8 @@ class Source:
|
||||
|
||||
def __init__(self, path, name):
|
||||
self.path, self.name = path, name
|
||||
# File rows left out at the top and the bottom (trim()).
|
||||
self.cut = (0, 0)
|
||||
with open(path, 'rb') as handle:
|
||||
head = handle.read(1024)
|
||||
self.pdf = b'%PDF-' in head
|
||||
@@ -268,6 +256,58 @@ class Source:
|
||||
pass
|
||||
image.close()
|
||||
|
||||
def trim(self, spec):
|
||||
"""Leave out the empty strips the Site cut from a ready sheet's top and
|
||||
bottom (Marcus, 2026-11-18). From then on `size` is what is printed."""
|
||||
top_cm = Decimal(str(spec.get('trim_top_cm') or 0))
|
||||
bottom_cm = Decimal(str(spec.get('trim_bottom_cm') or 0))
|
||||
if not (top_cm or bottom_cm):
|
||||
return
|
||||
if self.pdf:
|
||||
raise Unsupported(f'"{self.name}": o corte das faixas vazias só vale para imagens')
|
||||
full_cm = Decimal(str(spec['length_cm'])) + top_cm + bottom_cm
|
||||
width, height = self.size
|
||||
top, bottom = round(height * top_cm / full_cm), round(height * bottom_cm / full_cm)
|
||||
if top + bottom >= height:
|
||||
raise Unsupported(f'"{self.name}": o corte das faixas vazias tiraria o arquivo inteiro')
|
||||
self._require_clear(top, bottom)
|
||||
self.cut = (top, bottom)
|
||||
self.size = (width, height - top - bottom)
|
||||
|
||||
def _require_clear(self, top, bottom):
|
||||
"""The strips the Site measured as empty must be: cut on a measure the
|
||||
file does not bear out, artwork would leave the print unseen. A pixel
|
||||
takes ink above INK_ALPHA, as the Site counts it. Not clear, or too
|
||||
big to read here: the item goes to hand preparation, with the reason."""
|
||||
width, height = self.size
|
||||
where = lambda first: 'do começo' if first else 'do fim'
|
||||
|
||||
def check(band, offset):
|
||||
for start, stop, first in ((0, top, True), (height - bottom, height, False)):
|
||||
a, b = max(start, offset), min(stop, offset + band.height)
|
||||
if a < b and rgba(band.crop((0, a - offset, band.width, b - offset))).getchannel('A').getextrema()[1] > INK_ALPHA:
|
||||
raise Unsupported(f'"{self.name}": a faixa que o site cortou {where(first)} do arquivo tem arte. '
|
||||
'Confira o arquivo e prepare a folha à mão')
|
||||
|
||||
if self.streamable:
|
||||
reader = PngRows(self.path)
|
||||
try:
|
||||
done = 0
|
||||
# Read in order to the end of the bottom strip (or of the top one).
|
||||
while done < (height if bottom else top):
|
||||
band = reader.band(BAND_ROWS)
|
||||
if done < top or done + band.height > height - bottom:
|
||||
check(band, done)
|
||||
done += band.height
|
||||
finally:
|
||||
reader.close()
|
||||
return
|
||||
if width * height > MAX_DECODED_PIXELS:
|
||||
raise Unsupported(f'"{self.name}" é grande demais para conferir as faixas cortadas; prepare a folha à mão')
|
||||
with Image.open(self.path) as image:
|
||||
image = ImageOps.exif_transpose(image) if self.orientation != 1 else image
|
||||
check(image, 0)
|
||||
|
||||
def decoded(self, width, height):
|
||||
"""The whole file at (width, height) px, upright, RGBA."""
|
||||
if self.pdf:
|
||||
@@ -325,6 +365,14 @@ class Piece:
|
||||
key = (id(self.source), self.rotation, self.mirrored, self.w, self.h)
|
||||
if key not in cache:
|
||||
upright = (self.h, self.w) if self.rotation in (90, 270) else (self.w, self.h)
|
||||
top, bottom = self.source.cut
|
||||
if top or bottom:
|
||||
# A trimmed sheet (never turned): the file at the piece's scale,
|
||||
# then the rows between the strips.
|
||||
scale = self.h / self.source.size[1]
|
||||
image = self.source.decoded(self.w, max(1, round((self.source.size[1] + top + bottom) * scale)))
|
||||
image = image.crop((0, round(top * scale), self.w, round(top * scale) + self.h))
|
||||
else:
|
||||
image = self.source.decoded(*upright)
|
||||
if self.mirrored:
|
||||
image = ImageOps.mirror(image)
|
||||
@@ -349,10 +397,13 @@ class Piece:
|
||||
self.reader = PngRows(self.source.path)
|
||||
self.buffer, self.buffer_top = None, 0
|
||||
sw, sh = self.reader.width, self.reader.height
|
||||
per_row = sh / self.h
|
||||
# A trimmed sheet starts `skip` file rows down and stops `cut` rows short.
|
||||
skip, cut = self.source.cut
|
||||
per_row = (sh - skip - cut) / self.h
|
||||
# The source rows behind [a, b), with room for the filter on each side.
|
||||
margin = 0 if per_row == 1 and sw == self.w else math.ceil(3 * max(per_row, 1)) + 2
|
||||
want_top, want_bottom = max(0, math.floor(a * per_row) - margin), min(sh, math.ceil(b * per_row) + margin)
|
||||
want_top = max(0, math.floor(a * per_row) + skip - margin)
|
||||
want_bottom = min(sh, math.ceil(b * per_row) + skip + margin)
|
||||
while self.buffer_top + (self.buffer.height if self.buffer else 0) < want_bottom:
|
||||
band = rgba(self.reader.band(BAND_ROWS))
|
||||
if self.buffer is None:
|
||||
@@ -366,8 +417,8 @@ class Piece:
|
||||
self.buffer = self.buffer.crop((0, want_top - self.buffer_top, sw, self.buffer.height))
|
||||
self.buffer_top = want_top
|
||||
if per_row == 1 and sw == self.w:
|
||||
return self.buffer.crop((0, a - self.buffer_top, sw, b - self.buffer_top))
|
||||
box = (0, a * per_row - self.buffer_top, sw, b * per_row - self.buffer_top)
|
||||
return self.buffer.crop((0, a + skip - self.buffer_top, sw, b + skip - self.buffer_top))
|
||||
box = (0, a * per_row + skip - self.buffer_top, sw, b * per_row + skip - self.buffer_top)
|
||||
return self.buffer.resize((self.w, b - a), Image.LANCZOS, box=box)
|
||||
|
||||
def close(self):
|
||||
@@ -378,8 +429,16 @@ class Piece:
|
||||
|
||||
# ---- Parts and footer -------------------------------------------------------
|
||||
|
||||
def part_cuts(production, part_cm=None):
|
||||
"""Where the film is cut into parts, in cm from its top: [0, ..., height]."""
|
||||
# A cut needs this much clear film: it then falls in the middle of it.
|
||||
CLEAR_CUT_CM = Decimal('0.3')
|
||||
|
||||
|
||||
def part_cuts(production, part_cm=None, clear=None):
|
||||
"""Where the film is cut into parts, in cm from its top: [0, ..., height].
|
||||
A cut falls in a gap between pieces; where the layout has none, as inside
|
||||
a ready sheet (one piece to it), `clear(from_cm, to_cm)` finds a clear band
|
||||
in the film's own pixels, so no artwork is cut in two (Marcus, 2026-11-27,
|
||||
#136). Only without one either is the cut at the part's length."""
|
||||
limit = Decimal(str(part_cm or PART_CM))
|
||||
height = Decimal(str(production['height_cm']))
|
||||
spans = [(Decimal(str(p['y_cm'])), Decimal(str(p['y_cm'])) + Decimal(str(p['length_cm'])))
|
||||
@@ -390,11 +449,46 @@ def part_cuts(production, part_cm=None):
|
||||
free = [end for _, end in spans
|
||||
if start + limit - CUT_SEARCH_CM <= end <= start + limit
|
||||
and not any(top < end < bottom for top, bottom in spans)]
|
||||
cuts.append(max(free) if free else start + limit)
|
||||
# The search never goes back past half a part: no part comes out short.
|
||||
found = clear(max(start + limit / 2, start + limit - CUT_SEARCH_CM), start + limit) if clear and not free else None
|
||||
cuts.append(max(free) if free else found if found and found > start else start + limit)
|
||||
cuts.append(height)
|
||||
return cuts
|
||||
|
||||
|
||||
def clear_band(pieces, width, from_cm, to_cm):
|
||||
"""Where to cut the film between the two, in cm, so the artwork suffers
|
||||
least (Marcus, 2026-11-27, #136): the middle of the clear band of at least
|
||||
CLEAR_CUT_CM nearest `to_cm`; else of the widest clear band there is (a
|
||||
sheet packed edge to edge may have only 2 mm between rows); else the row
|
||||
with the least ink. None when the stretch is empty of rows."""
|
||||
top = px(from_cm)
|
||||
ink_rows, amounts = [], []
|
||||
for _, band in film_bands(pieces, top, px(to_cm), width):
|
||||
ink = band.getchannel('A').point(lambda a: 255 if a > 8 else 0)
|
||||
ink_rows.extend(ink.getprojection()[1])
|
||||
amounts.extend(ink.resize((1, ink.height), Image.BOX).tobytes())
|
||||
if not ink_rows:
|
||||
return None
|
||||
runs, end = [], None # (length, last row, first row), clear rows only
|
||||
for row in range(len(ink_rows) - 1, -2, -1):
|
||||
if row >= 0 and not ink_rows[row]:
|
||||
end = row if end is None else end
|
||||
continue
|
||||
if end is not None:
|
||||
runs.append((end - row, end, row + 1))
|
||||
end = None
|
||||
to_cm_of = lambda row: Decimal(top + row) / Decimal(str(PX_PER_CM))
|
||||
need = px(CLEAR_CUT_CM)
|
||||
wide = [run for run in runs if run[0] >= need]
|
||||
if wide or runs:
|
||||
# runs go from the bottom up: the first wide one is the nearest the limit.
|
||||
length, last, first = wide[0] if wide else max(runs, key=lambda run: (run[0], run[1]))
|
||||
return to_cm_of((first + last) // 2)
|
||||
least = min(amounts)
|
||||
return to_cm_of(max(row for row, amount in enumerate(amounts) if amount == least))
|
||||
|
||||
|
||||
def proof_cut(height_cm, limit_cm, fraction=None):
|
||||
"""A proof's window, in cm from the film's top: `limit_cm` centred on the
|
||||
thinnest stroke (fraction 0 at the top, 1 at the bottom), clamped inside
|
||||
@@ -438,16 +532,136 @@ def footer_band(text, width):
|
||||
return band
|
||||
|
||||
|
||||
# ---- The proof's samples ----------------------------------------------------
|
||||
#
|
||||
# Marcus, 2026-11-26: a proof of the finest stroke alone missed the colours
|
||||
# (#100's caught only white art). The proof keeps its window on the finest
|
||||
# stroke and adds short samples of the colours that window lacks, up to
|
||||
# PROOF_MAX_CM in all, each apart by PROOF_GAP_CM of clear film.
|
||||
PROOF_MAX_CM = Decimal('30')
|
||||
PROOF_SAMPLE_CM = Decimal('5')
|
||||
PROOF_GAP_CM = Decimal('1')
|
||||
# Colour groups: 12 hues, then grey, white and black; 15 is no ink.
|
||||
GREY, WHITE, BLACK, CLEAR = 12, 13, 14, 15
|
||||
# A colour counts when it is this share of the film's ink, and is in a stretch
|
||||
# when it is this share of the stretch's ink.
|
||||
COLOUR_SHARE, PRESENT_SHARE = 0.02, 0.03
|
||||
|
||||
|
||||
def colour_counts(band):
|
||||
"""The band's ink by colour group, read on a copy an eighth the size."""
|
||||
small = band.reduce(8) if min(band.size) >= 8 else band
|
||||
alpha = small.getchannel('A')
|
||||
hue, sat, val = small.convert('RGB').convert('HSV').split()
|
||||
groups = hue.point(lambda h: h * 12 // 256)
|
||||
achromatic = sat.point(lambda s: 255 if s < 46 else 0)
|
||||
groups.paste(GREY, mask=achromatic)
|
||||
groups.paste(WHITE, mask=Image.composite(val.point(lambda v: 255 if v > 217 else 0),
|
||||
Image.new('L', small.size), achromatic))
|
||||
groups.paste(BLACK, mask=val.point(lambda v: 255 if v < 64 else 0))
|
||||
groups.paste(CLEAR, mask=alpha.point(lambda a: 255 if a < 128 else 0))
|
||||
return groups.histogram()[:CLEAR]
|
||||
|
||||
|
||||
def present(counts):
|
||||
ink = sum(counts)
|
||||
return {k for k, n in enumerate(counts) if ink and n >= PRESENT_SHARE * ink}
|
||||
|
||||
|
||||
SCAN_PX_CM = 4
|
||||
|
||||
|
||||
def film_scan(production, pictures):
|
||||
"""The film's colours a centimetre at a time, [(top_cm, bottom_cm,
|
||||
counts)], drawn from each file's small picture (the one the Site sends
|
||||
for the Kanban, at most 480 x 720 px), so a 100 m film is read in a
|
||||
moment. `pictures` maps a source index to its image bytes; a file
|
||||
without one leaves its place empty."""
|
||||
k = SCAN_PX_CM
|
||||
film = Image.new('RGBA', (max(1, round(float(production['film_width_cm']) * k)),
|
||||
max(1, round(float(production['height_cm']) * k))))
|
||||
images = {}
|
||||
for index, data in pictures.items():
|
||||
try:
|
||||
image = rgba(ImageOps.exif_transpose(Image.open(io.BytesIO(data))))
|
||||
except Exception:
|
||||
continue
|
||||
spec = production['sources'][index]
|
||||
top, bottom = (float(spec.get('trim_top_cm') or 0), float(spec.get('trim_bottom_cm') or 0))
|
||||
if top or bottom:
|
||||
# The picture is of the whole file: the Site cut the empty strips.
|
||||
full = float(spec['length_cm']) + top + bottom
|
||||
image = image.crop((0, round(image.height * top / full), image.width,
|
||||
round(image.height * (full - bottom) / full)))
|
||||
images[index] = image
|
||||
for placement in production['placements']:
|
||||
image = images.get(placement['source_index'])
|
||||
if image is None:
|
||||
continue
|
||||
w = max(1, round(float(placement['width_cm']) * k))
|
||||
h = max(1, round(float(placement['length_cm']) * k))
|
||||
if placement['mirrored']:
|
||||
image = ImageOps.mirror(image)
|
||||
if placement['rotation_degrees'] % 360:
|
||||
image = image.rotate(-placement['rotation_degrees'], expand=True)
|
||||
film.alpha_composite(image.resize((w, h), Image.BOX),
|
||||
(round(float(placement['x_cm']) * k), round(float(placement['y_cm']) * k)))
|
||||
return [(Decimal(y) / k, Decimal(min(film.height, y + k)) / k, colour_counts(film.crop((0, y, film.width, y + k))))
|
||||
for y in range(0, film.height, k)]
|
||||
|
||||
|
||||
def proof_windows(height_cm, limit_cm, fraction, scan):
|
||||
"""The proof's stretches of film, [(top, bottom)] in cm, from the top: the
|
||||
finest stroke's window, then a PROOF_SAMPLE_CM sample for each colour
|
||||
still missing, the most missing first. `scan` is [(top_cm, bottom_cm,
|
||||
counts)] over the film."""
|
||||
first = proof_cut(height_cm, limit_cm, fraction)
|
||||
windows = [tuple(first)]
|
||||
height = Decimal(str(height_cm))
|
||||
total = sum((b - a for a, b in windows), Decimal(0))
|
||||
ink = [sum(c[k] for _, _, c in scan) for k in range(CLEAR)]
|
||||
wanted = {k for k, n in enumerate(ink) if sum(ink) and n >= COLOUR_SHARE * sum(ink)}
|
||||
|
||||
def inside(a, b):
|
||||
# Only the centimetres wholly in the stretch: one on its edge may hold
|
||||
# a colour the proof does not show.
|
||||
return [c for top, bottom, c in scan if top >= a and bottom <= b]
|
||||
|
||||
covered = set().union(*(present(c) for a, b in windows for c in inside(a, b)))
|
||||
while total + PROOF_GAP_CM + PROOF_SAMPLE_CM <= PROOF_MAX_CM and wanted - covered:
|
||||
best = None
|
||||
for top, bottom, counts in scan:
|
||||
gain = (wanted - covered) & present(counts)
|
||||
if not gain:
|
||||
continue
|
||||
centre = (top + bottom) / 2
|
||||
a = min(height - PROOF_SAMPLE_CM, max(Decimal(0), centre - PROOF_SAMPLE_CM / 2)).quantize(Decimal('0.1'))
|
||||
b = a + PROOF_SAMPLE_CM
|
||||
if any(a < wb + PROOF_GAP_CM and b > wa - PROOF_GAP_CM for wa, wb in windows):
|
||||
continue
|
||||
score = (len(gain), sum(counts[k] for k in gain))
|
||||
if best is None or score > best[0]:
|
||||
best = (score, a, b)
|
||||
if best is None:
|
||||
break
|
||||
_, a, b = best
|
||||
windows.append((a, b))
|
||||
total += PROOF_GAP_CM + (b - a)
|
||||
covered |= set().union(*(present(c) for c in inside(a, b)))
|
||||
return sorted(windows)
|
||||
|
||||
|
||||
# ---- The file ---------------------------------------------------------------
|
||||
|
||||
def render(item, files, out_dir, prefix, footer=None, part_cm=None, tiles=False, limit_cm=None,
|
||||
proof_fraction=None):
|
||||
proof_fraction=None, pictures=None):
|
||||
"""Write the PNG part(s) of one approved order item into `out_dir`.
|
||||
|
||||
`files` maps each source index to (local path, original name). With
|
||||
`tiles`, each part's pieces for the Kanban's viewer go in
|
||||
out_dir/tiles/<part name>/<level>/<index>.png (app/printtiles.py).
|
||||
A proof (`limit_cm`) is a free 15 cm window around `proof_fraction`.
|
||||
A proof (`limit_cm`) is a free 15 cm window around `proof_fraction`,
|
||||
and samples of the colours it lacks, found in `pictures` (film_scan).
|
||||
Returns the parts, [(path, name)], and the evidence the Kanban shows.
|
||||
"""
|
||||
production = item['production']
|
||||
@@ -455,23 +669,45 @@ def render(item, files, out_dir, prefix, footer=None, part_cm=None, tiles=False,
|
||||
raise Unsupported('o item usa uma montagem antiga')
|
||||
sources = [Source(*files[index]) for index in range(len(production['sources']))]
|
||||
try:
|
||||
for spec, source in zip(production['sources'], sources):
|
||||
source.trim(spec)
|
||||
vector = {index for index, source in enumerate(sources) if source.pdf}
|
||||
lowest = check_layout(item, [source.size for source in sources], vector, proof=bool(limit_cm))
|
||||
width = px(production['film_width_cm'])
|
||||
pieces = sorted((Piece(placement, sources[placement['source_index']])
|
||||
|
||||
def laid_out():
|
||||
return sorted((Piece(placement, sources[placement['source_index']])
|
||||
for placement in production['placements']), key=lambda piece: piece.y)
|
||||
# A proof sheet is a 15 cm window around the finest stroke; a normal
|
||||
# file is cut into parts (app/proof.py, item 0.1).
|
||||
cuts = (proof_cut(production['height_cm'], limit_cm, proof_fraction) if limit_cm
|
||||
else part_cuts(production, part_cm))
|
||||
windows = None
|
||||
if limit_cm:
|
||||
# A proof: the finest stroke's window and samples of the other
|
||||
# colours, stacked in one sheet; a normal file is cut into parts.
|
||||
windows = [tuple(proof_cut(production['height_cm'], limit_cm, proof_fraction))]
|
||||
if pictures and Decimal(str(production['height_cm'])) > Decimal(str(limit_cm)):
|
||||
windows = proof_windows(production['height_cm'], limit_cm, proof_fraction,
|
||||
film_scan(production, pictures))
|
||||
cuts = [windows[0][0], windows[-1][1]]
|
||||
else:
|
||||
def clear(from_cm, to_cm):
|
||||
# Read on pieces of its own: the film is read forward only.
|
||||
scanned = laid_out()
|
||||
try:
|
||||
return clear_band(scanned, width, from_cm, to_cm)
|
||||
finally:
|
||||
for piece in scanned:
|
||||
piece.close()
|
||||
cuts = part_cuts(production, part_cm, clear)
|
||||
pieces = laid_out()
|
||||
count = len(cuts) - 1
|
||||
parts, manifests = [], []
|
||||
for number in range(count):
|
||||
name = f'{prefix}.png' if count == 1 else f'{prefix}-p{number + 1}.png'
|
||||
path = os.path.join(out_dir, name)
|
||||
line = footer and (footer + (f' · Parte {number + 1}/{count}' if count > 1 else ''))
|
||||
ranges = ([(px(a), px(b)) for a, b in windows] if windows
|
||||
else [(px(cuts[number]), px(cuts[number + 1]))])
|
||||
with open(path, 'wb') as out:
|
||||
manifests.append(write_part(out, pieces, px(cuts[number]), px(cuts[number + 1]), width, line,
|
||||
manifests.append(write_part(out, pieces, ranges, width, line,
|
||||
tiles=os.path.join(out_dir, 'tiles', name) if tiles else None))
|
||||
parts.append((path, name))
|
||||
finally:
|
||||
@@ -484,6 +720,8 @@ def render(item, files, out_dir, prefix, footer=None, part_cm=None, tiles=False,
|
||||
'parts': [{'name': name, 'from_cm': str(cuts[i]), 'to_cm': str(cuts[i + 1]),
|
||||
**({'tiles': manifests[i]} if manifests[i] else {})}
|
||||
for i, (_, name) in enumerate(parts)],
|
||||
**({'proof_windows': [[f'{Decimal(a).normalize():f}', f'{Decimal(b).normalize():f}']
|
||||
for a, b in windows]} if windows else {}),
|
||||
'footer': footer,
|
||||
'billed_metres': str(item['billed_metres']),
|
||||
'placements': len(production['placements']),
|
||||
@@ -492,20 +730,9 @@ def render(item, files, out_dir, prefix, footer=None, part_cm=None, tiles=False,
|
||||
'min_dpi': round(lowest) if lowest else None}
|
||||
|
||||
|
||||
def write_part(out, pieces, top, bottom, width, footer=None, tiles=None):
|
||||
"""Rows [top, bottom) of the film, then the footer, as one PNG; with
|
||||
`tiles`, a folder, also its pieces for the viewer. Returns their manifest."""
|
||||
foot = footer_band(footer, width) if footer else None
|
||||
height = bottom - top + (foot.height if foot else 0)
|
||||
writer = PngWriter(out, width, height)
|
||||
pyramid = None
|
||||
if tiles:
|
||||
def emit(level, index, data):
|
||||
folder = os.path.join(tiles, str(level))
|
||||
os.makedirs(folder, exist_ok=True)
|
||||
with open(os.path.join(folder, f'{index}.png'), 'wb') as strip:
|
||||
strip.write(data)
|
||||
pyramid = Pyramid(width, height, emit)
|
||||
def film_bands(pieces, top, bottom, width):
|
||||
"""The film's rows [top, bottom) composed, BAND_ROWS at a time: (band top,
|
||||
RGBA image). Pieces are read forward only, so ranges go down the film."""
|
||||
cache = {}
|
||||
for band_top in range(top, bottom, BAND_ROWS):
|
||||
band_bottom = min(bottom, band_top + BAND_ROWS)
|
||||
@@ -521,9 +748,7 @@ def write_part(out, pieces, top, bottom, width, footer=None, tiles=None):
|
||||
if left or piece.x + rows.width > width:
|
||||
rows = rows.crop((left, 0, min(rows.width, width - piece.x), rows.height))
|
||||
band.alpha_composite(rows, (max(0, piece.x), a - band_top))
|
||||
writer.band(band)
|
||||
if pyramid:
|
||||
pyramid.band(band)
|
||||
yield band_top, band
|
||||
# A piece the film has passed is done with: its pixels can go.
|
||||
for piece in pieces:
|
||||
if piece.y + piece.h <= band_bottom:
|
||||
@@ -531,9 +756,36 @@ def write_part(out, pieces, top, bottom, width, footer=None, tiles=None):
|
||||
live = {(id(p.source), p.rotation, p.mirrored, p.w, p.h) for p in pieces if p.y + p.h > band_bottom}
|
||||
for key in [key for key in cache if key not in live]:
|
||||
del cache[key]
|
||||
if foot:
|
||||
writer.band(foot)
|
||||
|
||||
|
||||
def write_part(out, pieces, ranges, width, footer=None, tiles=None):
|
||||
"""The film's rows in `ranges` [(top, bottom)], top to bottom and apart by
|
||||
PROOF_GAP_CM of clear film when there are several (a proof's samples),
|
||||
then the footer, as one PNG; with `tiles`, a folder, also its pieces for
|
||||
the viewer. Returns their manifest."""
|
||||
foot = footer_band(footer, width) if footer else None
|
||||
gap = px(PROOF_GAP_CM)
|
||||
height = (sum(b - a for a, b in ranges) + gap * (len(ranges) - 1) + (foot.height if foot else 0))
|
||||
writer = PngWriter(out, width, height)
|
||||
pyramid = None
|
||||
if tiles:
|
||||
def emit(level, index, data):
|
||||
folder = os.path.join(tiles, str(level))
|
||||
os.makedirs(folder, exist_ok=True)
|
||||
with open(os.path.join(folder, f'{index}.png'), 'wb') as strip:
|
||||
strip.write(data)
|
||||
pyramid = Pyramid(width, height, emit)
|
||||
|
||||
def put(band):
|
||||
writer.band(band)
|
||||
if pyramid:
|
||||
pyramid.band(foot)
|
||||
pyramid.band(band)
|
||||
for i, (top, bottom) in enumerate(ranges):
|
||||
if i:
|
||||
put(Image.new('RGBA', (width, gap)))
|
||||
for _, band in film_bands(pieces, top, bottom, width):
|
||||
put(band)
|
||||
if foot:
|
||||
put(foot)
|
||||
writer.close()
|
||||
return pyramid.close() if pyramid else None
|
||||
|
||||
@@ -47,12 +47,18 @@ def final_png_issue(data):
|
||||
return None
|
||||
|
||||
|
||||
def require_final_png(storage, upload):
|
||||
from fastapi import HTTPException
|
||||
def final_png_problem(storage, upload):
|
||||
"""Why this upload cannot be a final file, or None: its name and the
|
||||
header chunks of the stored file."""
|
||||
if not upload['name'].lower().endswith('.png'):
|
||||
raise HTTPException(422, 'O arquivo final precisa ser PNG transparente a 300 DPI. Converta PDF/TIFF antes de enviar.')
|
||||
return 'O arquivo final precisa ser PNG transparente a 300 DPI. Converta PDF/TIFF antes de enviar.'
|
||||
response = storage.client.get_object(Bucket=storage.bucket, Key=upload['object_key'],
|
||||
Range=f'bytes=0-{HEADER_BYTES - 1}')
|
||||
issue = final_png_issue(response['Body'].read())
|
||||
return final_png_issue(response['Body'].read())
|
||||
|
||||
|
||||
def require_final_png(storage, upload):
|
||||
from fastapi import HTTPException
|
||||
issue = final_png_problem(storage, upload)
|
||||
if issue:
|
||||
raise HTTPException(422, issue)
|
||||
|
||||
@@ -78,8 +78,13 @@ class Pyramid:
|
||||
self._feed(level + 1, small)
|
||||
|
||||
def _strip(self, level, image):
|
||||
# The print file's own writer, the fast one (imported here: printpng
|
||||
# imports this module).
|
||||
from .printpng import PngWriter
|
||||
out = io.BytesIO()
|
||||
image.save(out, 'PNG', compress_level=1)
|
||||
writer = PngWriter(out, image.width, image.height)
|
||||
writer.band(image)
|
||||
writer.close()
|
||||
self.emit(level, self.count[level], out.getvalue())
|
||||
self.count[level] += 1
|
||||
|
||||
|
||||
64
app/proof.py
64
app/proof.py
@@ -1,8 +1,9 @@
|
||||
"""The print proof (Dropstar, 2026-10-21).
|
||||
|
||||
An order above 10 m prints a proof before the rest, checked by the print room
|
||||
without stopping the order. Dropstar's current rule: up to 15 cm, from
|
||||
the part with the thinnest lines, a piece of each different artwork, at most
|
||||
without stopping the order. Dropstar's current rule: 15 cm from the part
|
||||
with the thinnest lines plus samples of the file's main colours, up to 30 cm
|
||||
in all (Marcus, 2026-11-26), a piece of each different artwork, at most
|
||||
three proofs per order, never billed. On an order above 10 m the customer
|
||||
may also ask for a proof at checkout (below 10 m there is none, Dropstar
|
||||
2026-10-28): that order waits for them, marked "Aguardando contato", until
|
||||
@@ -16,6 +17,9 @@ from uuid import NAMESPACE_URL, uuid4, uuid5
|
||||
from psycopg.types.json import Jsonb
|
||||
from fastapi import HTTPException
|
||||
|
||||
from .cart_pricing import needs_designer
|
||||
from .finals import FINAL_OK, TREATED
|
||||
|
||||
PROOF_ABOVE_METRES = Decimal('10')
|
||||
CUSTOMER_NOTE = ('O cliente pediu uma prova antes de imprimir: mande a foto da prova pelo WhatsApp '
|
||||
'e espere o aceite.')
|
||||
@@ -34,12 +38,14 @@ def needs_proof(snapshot):
|
||||
#
|
||||
# An order with a proof becomes a parent and a child. The child, the card
|
||||
# "Prova", is an order of its own (orders.parent_id) with a pre-built proof
|
||||
# sheet of up to 15 cm per contraction class, and follows the normal flow up
|
||||
# sheet of up to 30 cm per contraction class, and follows the normal flow up
|
||||
# to Revisão. The parent waits outside the queue, "Aguardando prova". On the
|
||||
# child, the Vendedor (Gestão and the Administrador too) marks Prova OK, and
|
||||
# the parent enters the queue; or Prova reprovada, with its reason, and the
|
||||
# parent goes back to Arte recebida and the child closes. The child is no
|
||||
# sale: it is not in Tiny, Números, the customer's account or their e-mails.
|
||||
# The finest stroke's window; with the colour samples the sheet reaches
|
||||
# app/printpng.py PROOF_MAX_CM.
|
||||
PROOF_SHEET_CM = Decimal('15')
|
||||
# Three proofs at most per order, one per item (Dropstar, 2026-10-23).
|
||||
MAX_PROOFS = 3
|
||||
@@ -103,3 +109,55 @@ def require_unlocked(c, order):
|
||||
if waiting(c, order):
|
||||
child = open_child(c, order['id'])
|
||||
raise HTTPException(409, f'Aguardando prova do #{child["number"]}: responda no card da prova.')
|
||||
|
||||
|
||||
def approve_parent(c, parent, operator):
|
||||
"""Prova OK is the parent's check: the full files the Prumo generated
|
||||
become its finals, and with every item's final the parent enters the
|
||||
queue. Items that still need a manual final stay in Arte recebida. Runs at
|
||||
the answer, and again when a file finishes after it: #81's 91,5 m was
|
||||
still being generated at its Prova OK and stayed behind (2026-11-24).
|
||||
Returns whether the parent entered the queue."""
|
||||
card = c.execute('''SELECT number FROM dtf_local.orders WHERE parent_id=%s AND proof_result='ok'
|
||||
AND cancelled_at IS NULL ORDER BY created_at DESC LIMIT 1''', (parent['id'],)).fetchone()
|
||||
if parent['state'] != 'rec' or parent['cancelled_at'] or not card:
|
||||
return False
|
||||
designer = needs_designer(parent['snapshot'])
|
||||
if not designer:
|
||||
generated = c.execute('''SELECT p.item_index,p.upload_id FROM dtf_local.print_files p
|
||||
WHERE p.order_id=%s AND p.status='ready' AND p.upload_id IS NOT NULL
|
||||
ORDER BY p.item_index''', (parent['id'],)).fetchall()
|
||||
for row in generated:
|
||||
# Every part of a film in parts, not only its first: the others
|
||||
# never reached the folders (#114, #128, #130).
|
||||
parts = [r['upload_id'] for r in c.execute('''SELECT upload_id FROM dtf_local.print_parts
|
||||
WHERE order_id=%s AND item_index=%s ORDER BY part''', (parent['id'], row['item_index'])).fetchall()]
|
||||
parts = parts or [row['upload_id']]
|
||||
active = {r['upload_id'] for r in c.execute('''SELECT upload_id FROM dtf_local.order_files
|
||||
WHERE order_id=%s AND item_index=%s AND kind='final' AND active''',
|
||||
(parent['id'], row['item_index'])).fetchall()}
|
||||
# A final someone prepared or approved stays as it is.
|
||||
if active and not active <= set(parts):
|
||||
continue
|
||||
for upload_id in parts:
|
||||
if upload_id not in active:
|
||||
c.execute('''INSERT INTO dtf_local.order_files(id,order_id,upload_id,item_index,kind,note,created_by)
|
||||
VALUES(%s,%s,%s,%s,'final',%s,'Prumo')''',
|
||||
(uuid4(), parent['id'], upload_id, row['item_index'],
|
||||
f'Aprovado pela prova do #{card["number"]}'))
|
||||
treatment_clause = f'AND {TREATED}' if designer else ''
|
||||
ready = all(c.execute(f'''SELECT 1 FROM dtf_local.order_files f
|
||||
JOIN dtf_local.orders o ON o.id=f.order_id
|
||||
JOIN dtf_local.uploads u ON u.id=f.upload_id
|
||||
WHERE f.order_id=%s AND f.item_index=%s AND {FINAL_OK} {treatment_clause} LIMIT 1''',
|
||||
(parent['id'], i)).fetchone() for i in range(len(parent['snapshot']['items'])))
|
||||
if ready:
|
||||
version = c.execute('''UPDATE dtf_local.orders SET state='tra', version=version+1, updated_at=now()
|
||||
WHERE id=%s RETURNING version''', (parent['id'],)).fetchone()['version']
|
||||
c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason)
|
||||
VALUES(%s,'rec','tra',%s,'Prova OK')''', (parent['id'], operator))
|
||||
# Entering the queue this way is Tiny's "Preparando envio" too, as a
|
||||
# card moved by hand: orders with a proof skipped it.
|
||||
from .payments import stage_event
|
||||
stage_event(c, parent, 'tra', 'Prova OK', version)
|
||||
return ready
|
||||
|
||||
30
app/prumo.py
30
app/prumo.py
@@ -103,15 +103,41 @@ def report(order, uploads):
|
||||
lines.append(f'{lead}{len(placements)} arte{"s" if len(placements) != 1 else ""}, '
|
||||
f'{rotated} girada{"s" if rotated != 1 else ""} (couberam melhor), '
|
||||
f'altura {_cm(production.get("height_cm"))} cm')
|
||||
# The size the PNG said it had (item A1, round 5): whether the
|
||||
# customer kept it or changed it.
|
||||
for k, source in enumerate(production.get('sources') or []):
|
||||
saved = source.get('saved_width_cm')
|
||||
if not saved:
|
||||
continue
|
||||
width = Decimal(str(source.get('width_cm')))
|
||||
length = Decimal(str(source.get('length_cm')))
|
||||
# Turned 90°, the art's own width runs along the film.
|
||||
if source.get('rotation_degrees') == 90:
|
||||
width, length = length, width
|
||||
saved_w = Decimal(str(saved))
|
||||
altura = saved_w * length / width if width else Decimal(0)
|
||||
dpi = source.get('saved_dpi')
|
||||
if abs(width - saved_w) < Decimal('0.05'):
|
||||
lines.append(f'{lead}Arte {k + 1}: tamanho lido do arquivo '
|
||||
f'{_cm(saved_w)} × {_cm(altura)} cm ({dpi} DPI), mantido')
|
||||
else:
|
||||
lines.append(f'{lead}Arte {k + 1}: tamanho lido do arquivo '
|
||||
f'{_cm(saved_w)} × {_cm(altura)} cm ({dpi} DPI), '
|
||||
f'alterado pelo cliente para {_cm(width)} cm')
|
||||
# The empty strips the Site cut from a ready sheet (Marcus, 2026-11-18).
|
||||
trimmed = sum(Decimal(str(s.get('trim_top_cm') or 0)) + Decimal(str(s.get('trim_bottom_cm') or 0))
|
||||
for s in production.get('sources') or [])
|
||||
if trimmed:
|
||||
lines.append(f'{lead}Faixas vazias cortadas: {_cm(trimmed)} cm')
|
||||
billed = item.get('billed_metres') or item.get('metres')
|
||||
if billed:
|
||||
lines.append(f'{lead}Cobrado {_m(billed)} m (height_cm {_cm(production.get("height_cm"))})')
|
||||
if item.get('stroke_px') and item.get('stroke_class'):
|
||||
lines.append(f'{lead}Menor traço {item["stroke_px"]} px → {item["stroke_class"]}')
|
||||
if item.get('stroke_choice') == 'client_c3':
|
||||
lines.append(f'{lead}Aviso de traço fino disparou — cliente escolheu proteger as áreas chapadas (C3)')
|
||||
lines.append(f'{lead}Aviso de traço fino: cliente escolheu proteger as áreas chapadas (C3)')
|
||||
elif item.get('stroke_choice') == 'measured':
|
||||
lines.append(f'{lead}Aviso de traço fino disparou — cliente escolheu imprimir em C1')
|
||||
lines.append(f'{lead}Aviso de traço fino: cliente escolheu imprimir em C1')
|
||||
else:
|
||||
lines.append(f'{lead}Aviso de traço fino não disparou')
|
||||
if row:
|
||||
|
||||
@@ -63,7 +63,7 @@ def approve(c, row, items, reviewer):
|
||||
for item, original in zip(items, draft['items']):
|
||||
if item.mode != original['mode'] or list(map(str, item.uploads)) != original['uploads']:
|
||||
raise HTTPException(422, 'O produto e os arquivos não podem mudar na revisão.')
|
||||
if item.production.model_dump(mode='json') != original['production'] or item.quality_status != original['quality_status'] or item.quality_acknowledged != original['quality_acknowledged'] or item.residue_accepted != original.get('residue_accepted', 0) or item.stroke_class != original.get('stroke_class') or item.stroke_px != original.get('stroke_px') or item.stroke_choice != original.get('stroke_choice') or (item.split and item.split.model_dump()) != original.get('split'):
|
||||
if item.production.model_dump(mode='json') != original['production'] or item.quality_status != original['quality_status'] or item.quality_acknowledged != original['quality_acknowledged'] or item.residue_accepted != original.get('residue_accepted', 0) or item.close_pieces != original.get('close_pieces', 0) or item.stroke_class != original.get('stroke_class') or item.stroke_px != original.get('stroke_px') or item.stroke_choice != original.get('stroke_choice') or (item.split and item.split.model_dump()) != original.get('split'):
|
||||
raise HTTPException(422, 'A montagem e a confirmação do cliente não podem mudar na revisão.')
|
||||
for upload_id in item.uploads:
|
||||
upload = upload_row(c, upload_id, row['owner'])
|
||||
@@ -75,6 +75,7 @@ def approve(c, row, items, reviewer):
|
||||
coupon_code=draft.get('coupon'),
|
||||
customer_document=(draft.get('customer') or {}).get('cnpj'),
|
||||
wants_treatment=draft.get('treatment', False),
|
||||
wants_redesign=draft.get('redesign', []),
|
||||
treatment_rule=not draft.get('montador'))
|
||||
# Keep the review snapshot's own fields with each priced item.
|
||||
priced = cart['items']
|
||||
@@ -94,12 +95,14 @@ def approve(c, row, items, reviewer):
|
||||
**({'proof_y_fraction': original['proof_y_fraction']}
|
||||
if original.get('proof_y_fraction') is not None else {}),
|
||||
**({'source_dpi': original['source_dpi']} if original.get('source_dpi') else {}),
|
||||
**({'close_pieces': original['close_pieces']} if original.get('close_pieces') else {}),
|
||||
**({'split': original['split']} if original.get('split') else {})})
|
||||
items_total = cart['items_total']
|
||||
coupon = cart['coupon']
|
||||
discount = coupon['discount_cents'] if coupon else 0
|
||||
flags = cart['grade_flags']
|
||||
treatment = cart['treatment']
|
||||
redesign = cart['redesign']
|
||||
metres = sum(Decimal(i['billed_metres']) for i in priced)
|
||||
try:
|
||||
quoted_freight = freight.quote(draft['freight']['service'], draft['freight'].get('postal_code', ''),
|
||||
@@ -112,6 +115,8 @@ def approve(c, row, items, reviewer):
|
||||
**({'proof': True} if draft.get('proof') and metres > PROOF_ABOVE_METRES else {}),
|
||||
# Ajuste Fino: per art, with the row's band (front 1a).
|
||||
**({'treatment': treatment} if treatment else {}),
|
||||
# Ajuste Fino Redesenho: per art, one price, 48 h (front 1b).
|
||||
**({'redesign': redesign} if redesign else {}),
|
||||
# The art grade decision stored with the quote (front 8.5).
|
||||
**({'grade_flags': flags} if flags else {}),
|
||||
# The coupon used, for the order card, Números and Tiny (front 8.3).
|
||||
@@ -119,7 +124,7 @@ def approve(c, row, items, reviewer):
|
||||
# Browser timings are kept for Números, never for the price (0.12).
|
||||
**({'timings': draft['timings']} if draft.get('timings') else {}),
|
||||
'total_cents': items_total - discount + quoted_freight['total_cents']
|
||||
+ treatment.get('cents', 0)}
|
||||
+ treatment.get('cents', 0) + redesign.get('cents', 0)}
|
||||
c.execute('UPDATE dtf_local.quotes SET approved=%s, reviewed_by=%s, approved_at=now() WHERE id=%s',
|
||||
(Jsonb(approved), reviewer, row['id']))
|
||||
# Approved and payable now: the files wait for the payment, not for ever.
|
||||
|
||||
@@ -145,11 +145,17 @@ def quote_view(c, row, order=None, attempt=None, known=False):
|
||||
from .cart_pricing import treatment_price
|
||||
treatment = treatment_price(items, (row['draft'] or {}).get('treatment'),
|
||||
catalog.current(c)['tratamento']) or None
|
||||
redesign = (row['approved'] or {}).get('redesign')
|
||||
if not redesign and (row['draft'] or {}).get('redesign'):
|
||||
from .cart_pricing import redesign_price
|
||||
redesign = redesign_price(items, (row['draft'] or {}).get('redesign'),
|
||||
catalog.current(c)['redesenho']) or None
|
||||
return {'id': row['id'], 'created_at': row['created_at'],
|
||||
'draft': row['draft'], 'approved': row['approved'],
|
||||
'expires_at': expires_at.isoformat() if expires_at else None,
|
||||
'expired_at': row['expired_at'].isoformat() if row.get('expired_at') else None,
|
||||
'prumo': prumo.customer_summary(items), 'treatment': treatment,
|
||||
'redesign': redesign,
|
||||
'status': 'paid' if order else 'discarded' if row.get('discarded_at') else 'expired' if expired
|
||||
else 'approved' if row['approved'] else 'pending_review',
|
||||
'auto_approved': row.get('reviewed_by') == 'auto',
|
||||
|
||||
@@ -124,13 +124,32 @@ def check_large(head, row):
|
||||
return 'rejected', 'O conteúdo do arquivo não corresponde ao formato do nome'
|
||||
|
||||
|
||||
# When the scan of the file now in hand began (None between files): the
|
||||
# worker's health reports a scan held on one file for longer than
|
||||
# SCAN_STUCK_SECONDS, since every upload waits behind it.
|
||||
busy_since=None
|
||||
SCAN_STUCK_SECONDS=900
|
||||
|
||||
def stuck():
|
||||
"""Whether the scan has been on the same file for SCAN_STUCK_SECONDS."""
|
||||
return busy_since is not None and time.monotonic()-busy_since>SCAN_STUCK_SECONDS
|
||||
|
||||
def scan_one(storage, scanner=None):
|
||||
global busy_since
|
||||
scanner=scanner or ClamAV()
|
||||
with connect() as c:
|
||||
row=c.execute('''SELECT * FROM dtf_local.uploads WHERE complete AND purged_at IS NULL
|
||||
AND expires_at>now() AND scan_state IN ('pending','error') AND scan_after<=now()
|
||||
ORDER BY created_at FOR UPDATE SKIP LOCKED LIMIT 1''').fetchone()
|
||||
if not row:return False
|
||||
busy_since=time.monotonic()
|
||||
try:
|
||||
_scan_row(c, storage, scanner, row)
|
||||
finally:
|
||||
busy_since=None
|
||||
return True
|
||||
|
||||
def _scan_row(c, storage, scanner, row):
|
||||
name=row['name']
|
||||
try:
|
||||
# Every later decision reads the stored name (the manual charge,
|
||||
@@ -162,7 +181,6 @@ def scan_one(storage, scanner=None):
|
||||
expires_at=CASE WHEN %s IN ('rejected','error') THEN LEAST(expires_at,now()+interval '3 days') ELSE expires_at END
|
||||
WHERE id=%s""",(name,state,reason,checked,checked,pdf_dpi_value,state,row['id']))
|
||||
audit('artwork_scan', upload=str(row['id']), result=state, c=c)
|
||||
return True
|
||||
|
||||
def scan_loop(storage):
|
||||
while True:
|
||||
|
||||
204
app/tiny.py
204
app/tiny.py
@@ -42,6 +42,7 @@ An order someone already moved further in Tiny is never moved back, and an
|
||||
invoiced one is not cancelled here (its nota fiscal is cancelled in Tiny).
|
||||
Pickup orders carry the client's "retirar pessoalmente" forma de envio.
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
import secrets
|
||||
import time
|
||||
@@ -51,9 +52,6 @@ from urllib.parse import urlencode
|
||||
|
||||
import httpx
|
||||
|
||||
from . import catalog
|
||||
from .core import db
|
||||
|
||||
API = 'https://api.tiny.com.br/public-api/v3'
|
||||
AUTH = 'https://accounts.tiny.com.br/realms/tiny/protocol/openid-connect'
|
||||
# Not TINY_PRODUCT_<MODE>: app/core/secrets.py reads any variable ending in
|
||||
@@ -82,6 +80,13 @@ METRE_SETTINGS = {'file': 'TINY_SKU_METRO_TEXTIL_FOLHA', 'avulsa': 'TINY_SKU_MET
|
||||
SKU_DEFAULTS = {'file': 'DTFIMP.TX', 'avulsa': 'DTFIMP.TX', 'premium': 'DTFIMP.TXP'}
|
||||
STEP_DEFAULTS = {'uvfile': 'DTFIMP.UV.010CM', 'uv': 'DTFIMP.UV.010CM'}
|
||||
METRE_DEFAULTS = {'uvfile': 'DTFIMP.UV.1MT', 'uv': 'DTFIMP.UV.1MT'}
|
||||
# Ajuste Fino and Redesenho are sold per art by their own SKUs (Marcus,
|
||||
# 2026-11-12). TINY_PRODUCT_TREATMENT, a numeric id, still replaces the
|
||||
# treatment SKU; the Redesenho front will use its SKU later.
|
||||
TREATMENT_SKU_SETTING = 'TINY_SKU_TREATMENT'
|
||||
TREATMENT_SKU_DEFAULT = 'DTFIMP.AJF.UN'
|
||||
REDESIGN_SKU_SETTING = 'TINY_SKU_REDESIGN'
|
||||
REDESIGN_SKU_DEFAULT = 'DTFIMP.AJF.RED'
|
||||
PRODUCTS = {'file': 'DTF Têxtil 57 cm · folha montada',
|
||||
'avulsa': 'DTF Têxtil 57 cm · artes avulsas',
|
||||
'uvfile': 'DTF UV 27 cm · folha montada',
|
||||
@@ -133,19 +138,20 @@ PICKUP_EXACT = 'retirar pessoalmente'
|
||||
# Dropstar's own ids, read from its store orders with app.tiny_probe exemplo
|
||||
# (2026-10-19). The app may not list formas de recebimento, so these are not
|
||||
# looked up: Pix and credit card, as the store's orders are paid, and the
|
||||
# DropStar carrier its pickup orders name. Dinheiro and, for the customer's
|
||||
# credit, Dropstar's own "CORREÇÃO DTF" were sent by Marcus on 2026-10-27, for
|
||||
# the orders the team registers as paid outside the site (D-35). "Boleto" is
|
||||
# DropStar carrier its pickup orders name. Dinheiro was sent by Marcus on
|
||||
# 2026-10-27, for the orders the team registers as paid outside the site
|
||||
# (D-35). The customer's credit is "CREDITO PRE-PAGO" (Marcus, 2026-11-18);
|
||||
# "CORREÇÃO DTF", used for it before, is for correction orders only. "Boleto" is
|
||||
# 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,
|
||||
RECEIPT_METHODS = {'pix': 919478952, 'card': 977460722, 'cash': 919478944, 'credit': 987762591,
|
||||
**({'faturado': int(_BOLETO)} if _BOLETO.isdigit() else {})}
|
||||
PICKUP_CARRIER = 761565838
|
||||
# Dropstar's answers: the financial category "DTF SITE" (RECEITAS, id sent on
|
||||
# 2026-10-26; it goes in pagamento.categoria, and replaced the store's
|
||||
# "DUPLICADO DROP", 965775137), no seller (Tiny sets it from the contact,
|
||||
# 2026-10-23), and the marcador SITE DTF, added after the order is created:
|
||||
# 2026-10-23; a montador Venda carries who assembled it, 2026-11-17), and the marcador SITE DTF, added after the order is created:
|
||||
# POST /pedidos does not take marcadores. Capitals, no accent, no extra
|
||||
# space: the string Kondado reads for Power BI.
|
||||
CATEGORY = 986932924
|
||||
@@ -153,6 +159,15 @@ CATEGORY = 986932924
|
||||
# the rules document (D-21) keeps the two channels apart in the financial.
|
||||
CATEGORIES = {'dropflow': 987032506}
|
||||
TAG = 'SITE DTF'
|
||||
# An order paid with the customer's credit also carries this marcador
|
||||
# (Marcus, 2026-11-18), beside SITE DTF.
|
||||
CREDIT_TAG = 'CREDITO PRE-PAGO'
|
||||
|
||||
|
||||
def order_tags(payload):
|
||||
"""The marcadores an order gets in Tiny."""
|
||||
paid = payload.get('payment') or {}
|
||||
return [TAG] + ([CREDIT_TAG] if paid.get('method') == 'credit' else [])
|
||||
# Freight is the sender's (CIF), as on the store's orders.
|
||||
FREIGHT_PAID_BY = 'R'
|
||||
# The forma de envio each delivery service uses, by name; a Correios service
|
||||
@@ -174,6 +189,17 @@ class TinyError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class TinyRateLimit(TinyError):
|
||||
"""Too many calls for the moment: the outbox's next try goes through
|
||||
(Sentry DTF-API-C). `transient`: the worker reports it only if it repeats."""
|
||||
transient = True
|
||||
|
||||
|
||||
class TinyUnavailable(TinyError):
|
||||
"""Tiny answered with a server error (5xx): down for a moment, so what
|
||||
depends on the answer waits for the outbox's next try."""
|
||||
|
||||
|
||||
class TinyNotConnected(TinyError):
|
||||
"""No authorised connection yet: an operator must click "Conectar Tiny"."""
|
||||
|
||||
@@ -189,15 +215,8 @@ def configured():
|
||||
|
||||
def required_settings():
|
||||
"""The OAuth application, and a product id for each mode not sold by SKU."""
|
||||
required = ['TINY_CLIENT_ID', 'TINY_CLIENT_SECRET', 'TINY_REDIRECT_URI'] + [
|
||||
return ['TINY_CLIENT_ID', 'TINY_CLIENT_SECRET', 'TINY_REDIRECT_URI'] + [
|
||||
setting for mode, setting in PRODUCT_SETTINGS.items() if not (sku_prefix(mode) or step_sku(mode))]
|
||||
# A paid treatment is a line of its own: missing, every treated order would
|
||||
# fail at the Tiny, so ask for it with the rest of the settings.
|
||||
with db.connect() as c:
|
||||
treatment = catalog.current(c)['tratamento']
|
||||
if treatment['enabled'] and treatment['unit_cents'] > 0:
|
||||
required.append('TINY_PRODUCT_TREATMENT')
|
||||
return required
|
||||
|
||||
|
||||
# The stack passes every setting, empty when unset, so empty means "the
|
||||
@@ -221,6 +240,11 @@ def metre_sku(mode):
|
||||
return setting(METRE_SETTINGS[mode]) or ('' if setting(STEP_SETTINGS[mode]) else METRE_DEFAULTS.get(mode, ''))
|
||||
|
||||
|
||||
def treatment_sku():
|
||||
"""The Ajuste Fino SKU, the client's catalogue default when unset."""
|
||||
return setting(TREATMENT_SKU_SETTING) or TREATMENT_SKU_DEFAULT
|
||||
|
||||
|
||||
def mode_codes(mode):
|
||||
"""Every SKU code a mode sold by SKU uses, or [] for a mode sold by product id."""
|
||||
if step_sku(mode):
|
||||
@@ -458,6 +482,24 @@ def search_forms(document):
|
||||
return list(dict.fromkeys((punctuated(d), d)))
|
||||
|
||||
|
||||
def list_sellers(orders, pages=10):
|
||||
"""Tiny's sellers (vendedores) as [{id, name}], for the Kanban user a
|
||||
Venda's seller comes from (Marcus, 2026-11-17). v3 names the seller on
|
||||
the entry or on its contact; both are read."""
|
||||
sellers = []
|
||||
for page in range(pages):
|
||||
found = orders.request('GET', '/vendedores', params={'limit': 100, 'offset': page * 100})
|
||||
items = found if isinstance(found, list) else (found.get('itens') or [])
|
||||
for entry in items:
|
||||
contact = entry.get('contato') or {}
|
||||
name = entry.get('nome') or contact.get('nome') or contact.get('fantasia') or ''
|
||||
if entry.get('id'):
|
||||
sellers.append({'id': entry['id'], 'name': name or f"Vendedor {entry['id']}"})
|
||||
if len(items) < 100:
|
||||
break
|
||||
return sorted(sellers, key=lambda s: s['name'].lower())
|
||||
|
||||
|
||||
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
|
||||
@@ -517,7 +559,7 @@ def business_days_after(day, days):
|
||||
return day
|
||||
|
||||
|
||||
def order_payload(payload, contact_id, today=None, product_id=None, shipping=None):
|
||||
def order_payload(payload, contact_id, today=None, product_id=None, shipping=None, contact_seller=None):
|
||||
"""The v3 'pedido' for a paid order's approved snapshot, filled in as the
|
||||
store's own orders are: payment, carrier and expected date. product_id finds
|
||||
a SKU's product id by its code; shipping(service) the forma de envio and de
|
||||
@@ -537,27 +579,47 @@ def order_payload(payload, contact_id, today=None, product_id=None, shipping=Non
|
||||
line['infoAdicional'] = note + f" · {item['billed_metres']} m"
|
||||
items.append(line)
|
||||
continue
|
||||
setting = PRODUCT_SETTINGS[item['mode']]
|
||||
product = os.environ.get(setting, '')
|
||||
product_setting = PRODUCT_SETTINGS[item['mode']]
|
||||
product = os.environ.get(product_setting, '')
|
||||
if not product.isdigit():
|
||||
raise TinyError(f'{setting} must be the Tiny product id')
|
||||
raise TinyError(f'{product_setting} must be the Tiny product id')
|
||||
items.append({'produto': {'id': int(product)},
|
||||
'quantidade': float(Decimal(item['billed_metres'])),
|
||||
'valorUnitario': money(item['unit_cents']),
|
||||
'infoAdicional': note})
|
||||
treatment = order.get('treatment') or {}
|
||||
if treatment.get('cents'):
|
||||
setting = os.environ.get('TINY_PRODUCT_TREATMENT', '')
|
||||
if not setting.isdigit():
|
||||
raise TinyError('TINY_PRODUCT_TREATMENT must be the Tiny product id')
|
||||
# Per art (front 1a): the line carries the band unit price and the arts
|
||||
# as its quantity. An old quote without those keeps one art at its total.
|
||||
arts = int(treatment.get('arts') or 1)
|
||||
unit = int(treatment.get('unit_cents') or treatment['cents'])
|
||||
items.append({'produto': {'id': int(setting)}, 'quantidade': arts,
|
||||
# The numeric product id the client gave still wins; otherwise the SKU
|
||||
# Marcus registered is resolved in the catalogue.
|
||||
legacy = os.environ.get('TINY_PRODUCT_TREATMENT', '')
|
||||
if legacy.isdigit():
|
||||
product = int(legacy)
|
||||
else:
|
||||
code = treatment_sku()
|
||||
if product_id is None:
|
||||
raise TinyError(f'{TREATMENT_SKU_SETTING} needs the SKUs looked up in Tiny')
|
||||
product = product_id(code)
|
||||
items.append({'produto': {'id': product}, 'quantidade': arts,
|
||||
'valorUnitario': money(unit),
|
||||
'infoAdicional': 'Ajuste Fino · '+str(arts)+
|
||||
(' arte' if arts == 1 else ' artes')+' · +24 h'})
|
||||
redesign = order.get('redesign') or {}
|
||||
if redesign.get('cents'):
|
||||
# Ajuste Fino Redesenho (front 1b): per art, resolved by its SKU code,
|
||||
# one price (never a band), 48 h. Empty setting means the default code.
|
||||
if product_id is None:
|
||||
raise TinyError('TINY_SKU_REDESIGN needs the SKU looked up in Tiny')
|
||||
code = setting(REDESIGN_SKU_SETTING) or REDESIGN_SKU_DEFAULT
|
||||
arts = int(redesign.get('arts') or 1)
|
||||
unit = int(redesign.get('unit_cents') or redesign['cents'])
|
||||
items.append({'produto': {'id': product_id(code)}, 'quantidade': arts,
|
||||
'valorUnitario': money(unit),
|
||||
'infoAdicional': 'Ajuste Fino Redesenho · '+str(arts)+
|
||||
(' arte' if arts == 1 else ' artes')+' · +48 h'})
|
||||
freight = order['freight']
|
||||
service = freight.get('service')
|
||||
pickup = service == 'pickup'
|
||||
@@ -569,6 +631,13 @@ def order_payload(payload, contact_id, today=None, product_id=None, shipping=Non
|
||||
'valorFrete': money(freight['total_cents']),
|
||||
'observacoes': f"Pedido DTF #{payload['number']}" + (' · retirada em Franca' if pickup else ''),
|
||||
'observacoesInternas': internal_note(payload)}
|
||||
# The seller in the customer's Tiny registration (dados complementares):
|
||||
# Tiny does not fill it on an order made this way, and it cannot be set
|
||||
# after (Marcus, 2026-11-26). Without one, a montador Venda goes with who
|
||||
# assembled it (Marcus, 2026-11-17), a Site order without.
|
||||
seller = contact_seller or (order.get('seller') or {}).get('id')
|
||||
if seller:
|
||||
pedido['vendedor'] = {'id': int(seller)}
|
||||
coupon = order.get('coupon') or {}
|
||||
if coupon:
|
||||
# Tiny's v3 order has the order-level discount next to valorFrete.
|
||||
@@ -579,16 +648,24 @@ def order_payload(payload, contact_id, today=None, product_id=None, shipping=Non
|
||||
# The carrier's time already counts production; a pickup is ready after it.
|
||||
days = freight.get('days') if not pickup else int(os.environ.get('FREIGHT_PRODUCTION_DAYS') or 0)
|
||||
if days is not None:
|
||||
days = int(days) + (1 if treatment.get('cents') else 0)
|
||||
# Redesenho adds 48 h (two working days); the basic adds one.
|
||||
extra = 2 if redesign.get('cents') else 1 if treatment.get('cents') else 0
|
||||
days = int(days) + extra
|
||||
pedido['dataPrevista'] = business_days_after(day, days).isoformat()
|
||||
# Paid at once, in full, as the store's orders: one parcel on the day.
|
||||
pedido['pagamento'] = {'categoria': {'id': CATEGORIES.get(payload.get('origin'), CATEGORY)}}
|
||||
received = RECEIPT_METHODS.get((payload.get('payment') or {}).get('method'))
|
||||
method = (payload.get('payment') or {}).get('method')
|
||||
received = RECEIPT_METHODS.get(method)
|
||||
if received:
|
||||
total = money(order['total_cents'])
|
||||
pedido['pagamento'].update({'formaRecebimento': {'id': received},
|
||||
'parcelas': [{'dias': 0, 'data': day.isoformat(), 'valor': total,
|
||||
'formaRecebimento': {'id': received}}]})
|
||||
parcela = {'dias': 0, 'data': day.isoformat(), 'valor': total,
|
||||
'formaRecebimento': {'id': received}}
|
||||
# A boleto installment names its bank account, so Tiny does not pick
|
||||
# its preferred one ("NEXSTAR COBRANÇA", Marcus 2026-11-12).
|
||||
account = setting('TINY_BOLETO_ACCOUNT')
|
||||
if method == 'faturado' and account.isdigit():
|
||||
parcela['meioPagamento'] = {'id': int(account)}
|
||||
pedido['pagamento'].update({'formaRecebimento': {'id': received}, 'parcelas': [parcela]})
|
||||
destination = order.get('destination')
|
||||
if destination:
|
||||
pedido['enderecoEntrega'] = {**address(destination), 'enderecoNro': destination['number'],
|
||||
@@ -625,6 +702,19 @@ def configured_skus(orders, mode):
|
||||
return 'ok' if not missing else 'SKU não encontrado entre os produtos ativos: ' + ', '.join(missing)
|
||||
|
||||
|
||||
def configured_treatment(orders):
|
||||
"""Whether Ajuste Fino's product is active: the numeric id when the client
|
||||
gave one, else the SKU from the catalogue."""
|
||||
value = os.environ.get('TINY_PRODUCT_TREATMENT', '')
|
||||
if value.isdigit():
|
||||
found = orders.request('GET', f'/produtos/{value}')
|
||||
if found.get('situacao') != 'A':
|
||||
return f"produto {value} não está ativo no Tiny ({found.get('situacao')})"
|
||||
return 'ok'
|
||||
orders.product_id(treatment_sku())
|
||||
return 'ok'
|
||||
|
||||
|
||||
def find_pickup(orders):
|
||||
"""The forma de envio named "Retirar pessoalmente" (Dropstar's), else the one
|
||||
named like "retirar", or why there is not one."""
|
||||
@@ -689,9 +779,9 @@ def configured_pickup(orders):
|
||||
|
||||
def check(auth=None, transport=None, orders=None):
|
||||
"""Read-only proof that the connection and permissions work: one order and
|
||||
one contact listed, each product's SKUs found active and the pickup
|
||||
forma de envio found, nothing created. Raises TinyNotConnected when there is no usable connection;
|
||||
otherwise reports each read separately."""
|
||||
one contact listed, each product's SKUs (and Ajuste Fino) found active and
|
||||
the pickup forma de envio found, nothing created. Raises TinyNotConnected
|
||||
when there is no usable connection; otherwise reports each read separately."""
|
||||
orders = orders or TinyOrders(auth=auth or TinyAuth(), transport=transport)
|
||||
|
||||
def listed(path, **filters):
|
||||
@@ -704,6 +794,7 @@ def check(auth=None, transport=None, orders=None):
|
||||
reads = [('pedidos', lambda: listed('/pedidos', dataInicial=since)), ('contatos', lambda: listed('/contatos'))]
|
||||
reads += [(PRODUCTS[mode], lambda mode=mode: configured_skus(orders, mode) if mode_codes(mode)
|
||||
else configured_product(orders, mode)[1]) for mode in PRODUCT_SETTINGS]
|
||||
reads.append(('Ajuste Fino', lambda: configured_treatment(orders)))
|
||||
reads.append(('forma de envio de retirada', lambda: configured_pickup(orders)[1]))
|
||||
results = {}
|
||||
for name, read in reads:
|
||||
@@ -735,7 +826,9 @@ class TinyOrders:
|
||||
headers = {'Authorization': f'Bearer {self.auth.access_token()}'}
|
||||
response = self.http.request(method, path, headers=headers, **kwargs)
|
||||
if response.status_code == 429:
|
||||
raise TinyError('Tiny rate limit reached; the outbox will retry')
|
||||
raise TinyRateLimit('Tiny rate limit reached; the outbox will retry')
|
||||
if response.status_code >= 500:
|
||||
raise TinyUnavailable(f'{method} {path}: {response.status_code} {response.text[:300]}')
|
||||
if response.status_code >= 400:
|
||||
raise TinyError(f'{method} {path}: {response.status_code} {response.text[:300]}')
|
||||
return response.json() if response.content else {}
|
||||
@@ -769,17 +862,34 @@ class TinyOrders:
|
||||
return None
|
||||
|
||||
def contact(self, order):
|
||||
"""The customer's contact id, and the seller of an existing one."""
|
||||
cnpj = order['customer']['cnpj']
|
||||
known = self.find_contact(cnpj)
|
||||
if known:
|
||||
return known
|
||||
return known, self.contact_seller(known)
|
||||
company = None
|
||||
if self.names and len(cnpj) == 14:
|
||||
try:
|
||||
company = self.names(cnpj)
|
||||
except Exception: # a name is a nicety; the order must still go
|
||||
company = None
|
||||
return self.request('POST', '/contatos', json=contact_payload(order, company))['id']
|
||||
return self.request('POST', '/contatos', json=contact_payload(order, company))['id'], None
|
||||
|
||||
def contact_seller(self, contact_id):
|
||||
"""The seller (vendedor) in a contact's registration, or None. A
|
||||
reading Tiny refuses leaves the order without one: it must still go.
|
||||
The seller cannot be set after the order is made, so a busy or
|
||||
unavailable Tiny (429, 5xx, no answer) tries the whole delivery again."""
|
||||
try:
|
||||
seller = (self.request('GET', f'/contatos/{contact_id}').get('vendedor') or {}).get('id')
|
||||
except (TinyRateLimit, TinyUnavailable):
|
||||
raise
|
||||
except TinyError as exc:
|
||||
# The order goes without its seller, for good: Sentry hears of it.
|
||||
logging.error('Tiny: could not read the seller of contact %s; the order goes without one: %s',
|
||||
contact_id, exc)
|
||||
return None
|
||||
return int(seller) if str(seller or '').isdigit() and int(seller) > 0 else None
|
||||
|
||||
def find(self, payload, days=SEARCH_DAYS):
|
||||
"""An order a previous delivery already created, or None."""
|
||||
@@ -797,15 +907,17 @@ class TinyOrders:
|
||||
return detail
|
||||
return None
|
||||
|
||||
def tag(self, tiny_id, known=False):
|
||||
"""The SITE DTF marcador on the order, once. A retry that finds the
|
||||
order already created checks first, since POST adds another."""
|
||||
def tag(self, tiny_id, tags, known=False):
|
||||
"""The order's marcadores (order_tags), once each. A retry that finds
|
||||
the order already created checks first, since POST adds another."""
|
||||
missing = list(tags)
|
||||
if known:
|
||||
have = self.request('GET', f'/pedidos/{tiny_id}/marcadores')
|
||||
have = have if isinstance(have, list) else have.get('itens') or []
|
||||
if any(str(m.get('descricao', '')).strip().upper() == TAG for m in have):
|
||||
return
|
||||
self.request('POST', f'/pedidos/{tiny_id}/marcadores', json=[{'descricao': TAG}])
|
||||
names = {str(m.get('descricao', '')).strip().upper() for m in have}
|
||||
missing = [tag for tag in tags if tag not in names]
|
||||
if missing:
|
||||
self.request('POST', f'/pedidos/{tiny_id}/marcadores', json=[{'descricao': tag} for tag in missing])
|
||||
|
||||
def set_situacao(self, tiny_id, situacao):
|
||||
self.request('PUT', f'/pedidos/{tiny_id}/situacao', json={'situacao': situacao})
|
||||
@@ -836,16 +948,18 @@ class TinyOrders:
|
||||
'tiny_id': str(existing.get('id')), 'tiny_number': str(existing.get('numeroPedido'))}
|
||||
tiny_id, situacao = existing.get('id'), existing.get('situacao')
|
||||
else:
|
||||
contact_id = self.contact(payload['order'])
|
||||
contact_id, seller = self.contact(payload['order'])
|
||||
created = self.request('POST', '/pedidos', json=order_payload(
|
||||
payload, contact_id, self.today, product_id=self.product_id, shipping=self.shipping))
|
||||
payload, contact_id, self.today, product_id=self.product_id, shipping=self.shipping,
|
||||
contact_seller=seller))
|
||||
receipt = {'provider': 'tiny', 'event_key': event_key, 'status': 'created',
|
||||
'tiny_id': str(created.get('id')), 'tiny_number': str(created.get('numeroPedido'))}
|
||||
tiny_id, situacao = created.get('id'), ABERTA
|
||||
# Tagged before it is approved, so a failure here is retried while the order is still open.
|
||||
if situacao == ABERTA:
|
||||
self.tag(tiny_id, known=bool(existing))
|
||||
receipt['marcador'] = TAG
|
||||
tags = order_tags(payload)
|
||||
self.tag(tiny_id, tags, known=bool(existing))
|
||||
receipt['marcador'] = ', '.join(tags)
|
||||
if status_updates() and situacao == ABERTA:
|
||||
self.set_situacao(tiny_id, APROVADA)
|
||||
receipt['situacao'] = SITUACOES[APROVADA]
|
||||
|
||||
@@ -30,6 +30,7 @@ team's users may not cancel by hand), and read back to show it is.
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from datetime import datetime
|
||||
@@ -165,6 +166,15 @@ def conferir(orders, out):
|
||||
method, result = tiny.configured_pickup(orders)
|
||||
ok &= result == 'ok'
|
||||
out(f"{tiny.PICKUP_SETTING} (retirada): {result} {method.get('nome') if method else ''}".rstrip())
|
||||
legacy = os.environ.get('TINY_PRODUCT_TREATMENT', '').strip()
|
||||
try:
|
||||
result = tiny.configured_treatment(orders)
|
||||
except tiny.TinyError as exc:
|
||||
result = str(exc)[:200]
|
||||
ok &= result == 'ok'
|
||||
label = 'TINY_PRODUCT_TREATMENT' if legacy.isdigit() else tiny.TREATMENT_SKU_SETTING
|
||||
code = legacy if legacy.isdigit() else tiny.treatment_sku()
|
||||
out(f'{label} (Ajuste Fino): {result} {code}'.rstrip())
|
||||
out(f"{tiny.STATUS_UPDATES_SETTING}: {'ligado' if tiny.status_updates() else 'desligado'}")
|
||||
for name, result in tiny.check(orders=orders).items():
|
||||
if name in ('pedidos', 'contatos'):
|
||||
|
||||
@@ -13,7 +13,7 @@ abandonment rate.
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from . import mail, payments
|
||||
from .payments import QUOTE_VALID_HOURS
|
||||
from .payments import CARD_REVIEW_HOURS, QUOTE_VALID_HOURS
|
||||
|
||||
# An intent in one of these no longer waits for money: approved (it became an
|
||||
# order), rejected, cancelled, expired or refunded (app/payments.py).
|
||||
@@ -34,11 +34,12 @@ def expire(c, origin):
|
||||
AND i.id = (SELECT i2.id FROM dtf_local.payment_intents i2
|
||||
WHERE i2.quote_id=q.id ORDER BY i2.created_at DESC LIMIT 1)
|
||||
AND i.status <> ALL(%s)
|
||||
AND i.created_at > now() - make_interval(hours => %s)
|
||||
-- a card in review may be approved days later (payments.CARD_REVIEW_HOURS)
|
||||
AND i.created_at > now() - make_interval(hours => CASE WHEN i.method='card' THEN %s ELSE %s END)
|
||||
AND (i.response->>'expires_at' IS NULL
|
||||
OR (i.response->>'expires_at')::timestamptz > now()))
|
||||
ORDER BY q.approved_at LIMIT 50 FOR UPDATE OF q SKIP LOCKED''',
|
||||
(QUOTE_VALID_HOURS, list(FINAL_INTENT), QUOTE_VALID_HOURS + 1)).fetchall()
|
||||
(QUOTE_VALID_HOURS, list(FINAL_INTENT), CARD_REVIEW_HOURS, QUOTE_VALID_HOURS + 1)).fetchall()
|
||||
for row in rows:
|
||||
c.execute('UPDATE dtf_local.quotes SET expired_at=now() WHERE id=%s', (row['id'],))
|
||||
# expired_at is set first: release_files must no longer see this quote
|
||||
|
||||
@@ -5,8 +5,10 @@ import os
|
||||
import threading
|
||||
import time
|
||||
from http.server import BaseHTTPRequestHandler, HTTPServer
|
||||
import psycopg
|
||||
from botocore.exceptions import ClientError
|
||||
from psycopg.types.json import Jsonb
|
||||
from . import mail, observability, unpaid
|
||||
from . import mail, observability, scanning, unpaid
|
||||
from .adapters import FakeTiny, LocalS3Storage, require_runtime
|
||||
from .core.secrets import load as load_secret_files
|
||||
from .core.db import connect
|
||||
@@ -15,18 +17,44 @@ from .scanning import ClamAV, scan_loop
|
||||
|
||||
load_secret_files()
|
||||
require_runtime()
|
||||
adapters = {'tiny': FakeTiny()}
|
||||
# Not yet confirmed against the client's account; see app/tiny.py.
|
||||
if os.environ.get('TINY_ADAPTER') == 'tiny':
|
||||
# Production without the real Tiny (TINY_ADAPTER missing from the stack):
|
||||
# the sends wait and Sentry is told, instead of the simulator marking real
|
||||
# orders delivered with made-up receipts that had to be queued again by hand.
|
||||
HELD = 'Tiny desligado em produção (TINY_ADAPTER não é tiny): o envio espera'
|
||||
|
||||
|
||||
class HeldTiny:
|
||||
def deliver(self, event_key, payload):
|
||||
raise RuntimeError(HELD)
|
||||
|
||||
|
||||
def tiny_adapter(adapter=None, environment=None):
|
||||
"""The Tiny the outbox delivers to: the real one when configured; in
|
||||
production otherwise none (HeldTiny); elsewhere the simulator."""
|
||||
adapter = os.environ.get('TINY_ADAPTER') if adapter is None else adapter
|
||||
environment = os.environ.get('APP_ENV', 'local') if environment is None else environment
|
||||
if adapter == 'tiny':
|
||||
from .tiny import TinyOrders
|
||||
from .cnpj import company
|
||||
adapters['tiny'] = TinyOrders(names=company)
|
||||
return TinyOrders(names=company)
|
||||
return HeldTiny() if environment == 'production' else FakeTiny()
|
||||
|
||||
|
||||
adapters = {'tiny': tiny_adapter()}
|
||||
|
||||
|
||||
def release_held(c):
|
||||
"""With the real Tiny back, the sends held meanwhile go at once instead
|
||||
of after their back-off."""
|
||||
return c.execute('''UPDATE dtf_local.outbox SET available_at=now() WHERE provider='tiny'
|
||||
AND delivered_at IS NULL AND last_error=%s''', (HELD,)).rowcount
|
||||
last_tick = 0.0
|
||||
last_cleanup = 0.0
|
||||
last_reconcile = 0.0
|
||||
last_names = 0.0
|
||||
names_thread = None
|
||||
last_tiny_keepalive = 0.0
|
||||
db_down_since = None
|
||||
storage = LocalS3Storage()
|
||||
scan_thread = None
|
||||
render_thread = None
|
||||
@@ -38,7 +66,16 @@ def cleanup():
|
||||
AND (expires_at<=now() OR (NOT complete AND created_at<now()-interval '1 day'))
|
||||
ORDER BY created_at FOR UPDATE SKIP LOCKED LIMIT 50""").fetchall()
|
||||
for row in rows:
|
||||
# A file this worker may not delete (outside the storage policy's
|
||||
# prefixes, or a storage refusal) must not stop the cleanup of
|
||||
# every file after it: it is reported and tried again tomorrow.
|
||||
try:
|
||||
storage.discard(row['object_key'],row['multipart_id'],row['complete'])
|
||||
except ClientError as exc:
|
||||
logging.error('Cleanup could not delete upload %s (%s): %s', row['id'],
|
||||
row['object_key'].split('/')[0], exc.response.get('Error',{}).get('Code'))
|
||||
c.execute("UPDATE dtf_local.uploads SET expires_at=now()+interval '1 day' WHERE id=%s", (row['id'],))
|
||||
continue
|
||||
# A generated PNG's pieces for the Kanban's viewer go with it (item 7).
|
||||
if row['name'].lower().endswith('.png'):
|
||||
storage.discard_prefix(f"originals/tiles/{row['id']}/")
|
||||
@@ -66,6 +103,15 @@ def tick():
|
||||
except Exception as exc:
|
||||
delay = min(1800, 2**min(job['attempts']+1, 10))
|
||||
c.execute("UPDATE dtf_local.outbox SET attempts=attempts+1, last_error=%s, available_at=now() + %s * interval '1 second' WHERE id=%s", (str(exc),delay,job['id']))
|
||||
# Sentry hears of a refused delivery on its first failure and
|
||||
# every tenth after, not only Integrações (the Tiny refused
|
||||
# #42 fourteen times unseen, 2026-11-18). One message
|
||||
# template, so Sentry keeps it as one issue per kind. A
|
||||
# passing refusal (the Tiny's rate limit) only from the tenth.
|
||||
attempt = job['attempts'] + 1
|
||||
if attempt == 1 and not getattr(exc, 'transient', False) or attempt % 10 == 0:
|
||||
logging.error('Outbox delivery to %s failed (%s, attempt %s): %s',
|
||||
job['provider'], job['event_key'], attempt, str(exc)[:500])
|
||||
last_tick = time.monotonic()
|
||||
return processed
|
||||
|
||||
@@ -126,7 +172,8 @@ def resolve_names():
|
||||
names_thread.start()
|
||||
|
||||
def loop():
|
||||
global last_cleanup
|
||||
global last_cleanup, db_down_since
|
||||
delay = 1
|
||||
while True:
|
||||
try:
|
||||
drain()
|
||||
@@ -140,17 +187,43 @@ def loop():
|
||||
tiny_keepalive()
|
||||
reconcile_payments()
|
||||
resolve_names()
|
||||
except psycopg.OperationalError as exc:
|
||||
if db_down_since is None:
|
||||
db_down_since = time.monotonic()
|
||||
logging.warning('Database unavailable, retrying: %s', exc)
|
||||
else:
|
||||
logging.debug('Database still unavailable, retrying in %s s', delay)
|
||||
time.sleep(delay)
|
||||
delay = min(delay * 2, 15)
|
||||
continue
|
||||
except Exception:
|
||||
logging.exception('Local worker tick failed')
|
||||
else:
|
||||
if db_down_since is not None:
|
||||
logging.info('Database back after %s s', int(time.monotonic()-db_down_since))
|
||||
db_down_since = None
|
||||
delay = 1
|
||||
time.sleep(1)
|
||||
|
||||
scan_stuck_reported = False
|
||||
|
||||
class Health(BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
global scan_stuck_reported
|
||||
scanner = False
|
||||
try:
|
||||
scanner = bool(scan_thread and scan_thread.is_alive() and ClamAV().ping())
|
||||
except Exception:
|
||||
pass
|
||||
# Alive but held on one file: every upload waits behind it.
|
||||
if scanning.stuck():
|
||||
scanner = False
|
||||
if not scan_stuck_reported:
|
||||
scan_stuck_reported = True
|
||||
logging.error('The upload scan has been on one file for over %s min: every upload waits',
|
||||
scanning.SCAN_STUCK_SECONDS // 60)
|
||||
else:
|
||||
scan_stuck_reported = False
|
||||
renderer = bool(render_thread and render_thread.is_alive())
|
||||
healthy = time.monotonic()-last_tick < 15 and scanner and renderer
|
||||
self.send_response(200 if self.path == '/health' and healthy else 503)
|
||||
@@ -163,6 +236,14 @@ class Health(BaseHTTPRequestHandler):
|
||||
|
||||
if __name__ == '__main__':
|
||||
observability.init('worker')
|
||||
if isinstance(adapters['tiny'], HeldTiny):
|
||||
logging.error('Worker started in production without the real Tiny: Tiny sends are held')
|
||||
elif not isinstance(adapters['tiny'], FakeTiny):
|
||||
try:
|
||||
with connect() as c:
|
||||
release_held(c)
|
||||
except Exception:
|
||||
logging.exception('Could not release the Tiny sends held while Tiny was off')
|
||||
scan_thread = threading.Thread(target=scan_loop,args=(storage,),daemon=True)
|
||||
scan_thread.start()
|
||||
render_thread = threading.Thread(target=render_loop,args=(storage,),daemon=True)
|
||||
|
||||
@@ -53,6 +53,8 @@ TINY_FORMA_ENVIO_RETIRADA=TBD
|
||||
TINY_STATUS_UPDATES=false
|
||||
# Tiny id of the forma de recebimento "Boleto" (montador Venda orders).
|
||||
TINY_RECEIPT_BOLETO=
|
||||
# Tiny id of the bank account each boleto installment names ("NEXSTAR COBRANÇA").
|
||||
TINY_BOLETO_ACCOUNT=
|
||||
# E-mail (password recovery and team alerts). off until the SMTP account exists.
|
||||
MAIL_ADAPTER=off
|
||||
MAIL_FROM=DTF Dropstar <nao-responda@SITE_DOMAIN>
|
||||
|
||||
@@ -41,9 +41,9 @@ SOURCE_BLOCKERS = {
|
||||
'app/runtime.py': (
|
||||
'payment = FakePayment()',
|
||||
),
|
||||
'app/worker.py': (
|
||||
"adapters = {'tiny': FakeTiny()}",
|
||||
),
|
||||
# app/worker.py's "adapters = {'tiny': FakeTiny()}" left on 2026-11-27: in
|
||||
# production the worker uses the real Tiny or holds the sends (HeldTiny),
|
||||
# never the simulator.
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -122,7 +122,6 @@ class ProductionPreflightTests(unittest.TestCase):
|
||||
def test_fake_checkout_is_explicitly_blocked(self):
|
||||
errors = source_errors()
|
||||
self.assertTrue(any('app/runtime.py remains local-only' in error for error in errors))
|
||||
self.assertTrue(any('app/worker.py remains local-only' in error for error in errors))
|
||||
|
||||
def test_secret_reuse_and_incoherent_limits_are_rejected(self):
|
||||
values = valid_config()
|
||||
|
||||
@@ -89,6 +89,10 @@ x-app-environment: &app-environment
|
||||
# reads (2026-10-28). true goes back to PDF's /UserUnit scale, for a RIP that
|
||||
# refuses pages over 5,08 m.
|
||||
PRINT_PAGE_SCALE: ${PRINT_PAGE_SCALE:-false}
|
||||
# Length of each print file part, in cm: 10 m, under FlexiPRINT's 4 GB per
|
||||
# image (Marcus, 2026-11-18). Before this line the stack's value never
|
||||
# reached the worker, and #81 came out in 15 m parts.
|
||||
PRINT_PART_CM: ${PRINT_PART_CM:-1000}
|
||||
# Order creation in Tiny stays off until it has been tested against the
|
||||
# client's account (Tiny has no sandbox). The application credentials can be
|
||||
# set now: they let an operator connect Tiny from the Kanban, and the worker
|
||||
@@ -107,6 +111,10 @@ x-app-environment: &app-environment
|
||||
TINY_PRODUCT_UV_FOLHA: ${TINY_PRODUCT_UV_FOLHA:-}
|
||||
TINY_PRODUCT_UV_AVULSA: ${TINY_PRODUCT_UV_AVULSA:-}
|
||||
TINY_PRODUCT_TREATMENT: ${TINY_PRODUCT_TREATMENT:-}
|
||||
# Ajuste Fino and Redesenho, per art, as the client's SKUs. The numeric
|
||||
# TINY_PRODUCT_TREATMENT above, when set, still replaces the treatment SKU.
|
||||
TINY_SKU_TREATMENT: ${TINY_SKU_TREATMENT:-}
|
||||
TINY_SKU_REDESIGN: ${TINY_SKU_REDESIGN:-}
|
||||
TINY_SKU_TEXTIL_FOLHA: ${TINY_SKU_TEXTIL_FOLHA:-}
|
||||
TINY_SKU_TEXTIL_AVULSA: ${TINY_SKU_TEXTIL_AVULSA:-}
|
||||
TINY_SKU_UV_FOLHA: ${TINY_SKU_UV_FOLHA:-}
|
||||
@@ -127,6 +135,9 @@ x-app-environment: &app-environment
|
||||
# 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:-}
|
||||
# The bank account every boleto installment names ("NEXSTAR COBRANÇA"), so
|
||||
# Tiny does not pick its preferred one. Empty: no account is sent.
|
||||
TINY_BOLETO_ACCOUNT: ${TINY_BOLETO_ACCOUNT:-}
|
||||
# Sets "Aprovada" on paid orders and "Pronto para envio" on finished pickup
|
||||
# orders, which the client's Tiny -> n8n notices send to customers. Turn on
|
||||
# only together with TINY_ADAPTER=tiny and after n8n stops sending the
|
||||
@@ -246,6 +257,7 @@ services:
|
||||
start_period: 30s
|
||||
deploy:
|
||||
replicas: 1
|
||||
update_config: {order: start-first, failure_action: rollback}
|
||||
restart_policy: {condition: on-failure, delay: 5s}
|
||||
|
||||
worker:
|
||||
@@ -325,6 +337,7 @@ services:
|
||||
start_period: 15s
|
||||
deploy:
|
||||
replicas: 1
|
||||
update_config: {order: start-first, failure_action: rollback}
|
||||
restart_policy: {condition: on-failure, delay: 5s}
|
||||
|
||||
kanban:
|
||||
@@ -351,6 +364,7 @@ services:
|
||||
start_period: 15s
|
||||
deploy:
|
||||
replicas: 1
|
||||
update_config: {order: start-first, failure_action: rollback}
|
||||
restart_policy: {condition: on-failure, delay: 5s}
|
||||
|
||||
configs:
|
||||
|
||||
@@ -210,6 +210,9 @@ opens by hand (CDR, AI, PSD, TIFF). The default is 200, R$ 2,00 a metro
|
||||
Change it only on the client's instruction; the Site shows the new price after
|
||||
the redeploy.
|
||||
|
||||
`TINY_SKU_TREATMENT` is the Ajuste Fino SKU (default `DTFIMP.AJF.UN`);
|
||||
`TINY_BOLETO_ACCOUNT` is the bank account each boleto installment names.
|
||||
|
||||
## 8. Correios
|
||||
|
||||
PAC and SEDEX appear in the cart once `CORREIOS_CODIGO_ACESSO` (the CWS access
|
||||
|
||||
@@ -11,7 +11,8 @@ Run from the worker's console (Portainer > Containers > worker > Console):
|
||||
Removes every order with its moves, files, notices and history, every quote,
|
||||
payment attempt and payment notification, and the artwork pictures. The
|
||||
artwork files are marked expired, so the worker deletes them from storage
|
||||
within a minute. Operators, machines, prices, the Tiny connection and the
|
||||
within a minute. Operators, machines, prices, the Site tab (products, coupons,
|
||||
videos with their files), the montador's tables, the Tiny connection and the
|
||||
backups are kept.
|
||||
|
||||
It refuses if any payment was made with real money (Mercado Pago's
|
||||
@@ -48,6 +49,10 @@ ACCOUNTS = [('sessions', 'sessões de clientes'), ('accounts', 'contas de client
|
||||
FLOW_FOLDERS = ('1. Arte recebida', '2. Arte conferida', '3. Imprimindo',
|
||||
'4. Revisão', '5. Finalizado', 'Recibos', 'Revisões')
|
||||
CONFIRM = 'APAGAR'
|
||||
# What stays points at some uploads: the Site's videos and captions (Marcus,
|
||||
# 2026-11-16: the whole Site tab stays). Their files are left alone.
|
||||
NOT_KEPT = '''id NOT IN (SELECT upload_id FROM dtf_local.site_videos WHERE upload_id IS NOT NULL
|
||||
UNION SELECT captions_id FROM dtf_local.site_videos WHERE captions_id IS NOT NULL)'''
|
||||
|
||||
|
||||
def counts(c, tables):
|
||||
@@ -86,7 +91,7 @@ def main(argv=None, out=print, connect=db.connect):
|
||||
out(f'Recusado: {live} pagamento(s) com dinheiro real (live_mode). Esses pedidos são de clientes.')
|
||||
return 1
|
||||
before = counts(c, tables)
|
||||
files = c.execute('SELECT count(*) AS n FROM dtf_local.uploads WHERE purged_at IS NULL').fetchone()['n']
|
||||
files = c.execute(f'SELECT count(*) AS n FROM dtf_local.uploads WHERE purged_at IS NULL AND {NOT_KEPT}').fetchone()['n']
|
||||
for table, label in tables:
|
||||
out(f'{before[table]:>7} {label}')
|
||||
out(f'{files:>7} arquivos de arte (o worker apaga do armazenamento)')
|
||||
@@ -99,7 +104,7 @@ def main(argv=None, out=print, connect=db.connect):
|
||||
return 0
|
||||
for table, _ in tables:
|
||||
c.execute(f'DELETE FROM dtf_local.{table}')
|
||||
c.execute('UPDATE dtf_local.uploads SET expires_at=now() WHERE purged_at IS NULL')
|
||||
c.execute(f'UPDATE dtf_local.uploads SET expires_at=now() WHERE purged_at IS NULL AND {NOT_KEPT}')
|
||||
if args.root and not args.keep_files:
|
||||
for folder in clean_folders(args.root, dry_run=False):
|
||||
out(f'esvaziada {folder}')
|
||||
|
||||
@@ -219,7 +219,7 @@ try{
|
||||
// JPG has no transparency: refused in loose artwork as in a sheet (Dropstar,
|
||||
// 2026-10-23), with the reason, before anything is read.
|
||||
await evaluate(`sel([new File(['x'],'arte.jpg',{type:'image/jpeg'})])`);
|
||||
assert.equal(await evaluate(`artes.length===0 && $('recusa').textContent.includes('JPG não dá para enviar')`),true);
|
||||
assert.equal(await evaluate(`artes.length===0 && $('recusa').textContent.includes('JPG não entra')`),true);
|
||||
// The content decides, not the name (D-13): a JPG called ".png" is refused as a JPG.
|
||||
await evaluate(`sel([new File([new Uint8Array([0xFF,0xD8,0xFF,0xE0])],'disfarce.png',{type:'image/png'})])`);
|
||||
assert.equal(await evaluate(`artes.length===0 && $('recusa').textContent.includes('disfarce.png é JPG')`),true);
|
||||
@@ -319,10 +319,14 @@ try{
|
||||
const m=result.pos[0].m;
|
||||
return !m.bits[2*m.cw+2] && !m.bits[2*m.cw+30] && !!m.bits[15*m.cw+30];
|
||||
})()`),true);
|
||||
// A real finished sheet keeps its own dimensions and by-metre price.
|
||||
// A real finished sheet keeps its own width and by-metre price. Its 19 cm
|
||||
// without ink at the bottom are cut, but for 0,5 cm (Marcus, 2026-11-18);
|
||||
// the 0,7 cm at the top stay, under the 1 cm the cut starts at.
|
||||
await click('#bVoltar');await click('[data-modo="file"]');
|
||||
await evaluate('sendSheet()');
|
||||
await waitFor(()=>evaluate('folhas.length===1 && !!folhas[0].previewSrc && metros===0.342'),'ready-sheet image');
|
||||
await waitFor(()=>evaluate(`folhas.length===1 && !!folhas[0].previewSrc && folhas[0].med.alt>34 && folhas[0].corte?.topo===0 &&
|
||||
folhas[0].corte.fim>18 && Math.abs(metros-(folhas[0].med.alt-folhas[0].corte.fim)/100)<0.0001`),'ready-sheet image, trimmed');
|
||||
assert.equal(await evaluate(`$('lista').textContent.includes('cm vazios do fim do arquivo. Cobrado: 1,00 m.')`),true);
|
||||
// On its way at once, with its own row under the uploader (Dropstar,
|
||||
// 2026-10-29). There is no storage here, so it fails, and says so with a
|
||||
// way to try again; tests/browser_test.mjs sends it for real.
|
||||
@@ -343,7 +347,8 @@ try{
|
||||
// With a sheet loaded the declaration is locked; it cannot flip under the customer.
|
||||
assert.equal(await evaluate(`document.querySelector('#tipoEnvio .cam[data-tipo="avulsa"]').disabled`),true);
|
||||
await evaluate(`(()=>{const el=$('lista').querySelector('[data-repf]');el.value=2;el.dispatchEvent(new Event('change',{bubbles:true}));})()`);
|
||||
await waitFor(()=>evaluate('metros===0.684'),'ready-sheet repetitions');
|
||||
// Two copies and the 8 mm between them (Marcus, 2026-11-26).
|
||||
await waitFor(()=>evaluate('Math.abs(metros-(2*folhas[0].m+0.008))<0.0001 && folhas[0].m<0.2'),'ready-sheet repetitions');
|
||||
assert.equal(await evaluate(`document.querySelectorAll('.folhaPrevia').length`),1);
|
||||
await evaluate(`(()=>{folhas.push({f:new File(['manual'],'manual.cdr'),med:null,rep:1,m:1,an:null});pintaFolha();})()`);
|
||||
await waitFor(()=>evaluate(`itemAtual?.nota===0 && itemAtual?.unit===PRECO[modo]+TAXA_MANUAL`),'mixed analyzed and manual sheets: the price plus the manual charge');
|
||||
@@ -378,7 +383,7 @@ try{
|
||||
// A ready sheet now offers the same acceptance as loose art (Dropstar,
|
||||
// 2026-11-05): the dots may be part of the art; the customer can take them.
|
||||
assert.deepEqual(await evaluate(`({box:!!document.querySelector('[data-residuo]'),
|
||||
text:$('lista').textContent.includes('Li e concordo'),stopped:itemAtual===null})`),{box:true,text:true,stopped:true});
|
||||
text:$('lista').textContent.includes('Quero imprimir assim'),stopped:itemAtual===null})`),{box:true,text:true,stopped:true});
|
||||
await evaluate(`(()=>{const el=document.querySelector('[data-residuo]');el.checked=true;
|
||||
el.dispatchEvent(new Event('change',{bubbles:true}));})()`);
|
||||
await waitFor(()=>evaluate('itemAtual!==null'),'accepted residue lets the sheet through');
|
||||
|
||||
@@ -91,7 +91,7 @@ try{
|
||||
const itemCents=Math.round(1.1*(1990+extraCents));
|
||||
const total=Math.round(itemCents)/100;
|
||||
await waitFor(()=>site.eval(`Math.abs(itemAtual.total-${total})<0.005`),'manual-file price');
|
||||
assert.equal(await site.eval(`$('carrLin').textContent.includes('Arquivo aberto na mão')`),extraCents>0);
|
||||
assert.equal(await site.eval(`$('carrLin').textContent.includes('Abertura manual do arquivo')`),extraCents>0);
|
||||
await site.fill('#fNome','Cliente Teste');
|
||||
await site.fill('#fCnpj','11222333000181');
|
||||
await site.fill('#fZap','11999999999');
|
||||
@@ -142,7 +142,9 @@ try{
|
||||
await site.click('[data-sel="0"]');
|
||||
assert.equal(await site.eval('pedido[0].marcado===true && itensAPagar().length===1'),true);
|
||||
assert.equal(await site.eval(`Math.abs(pedido[0].total-${total})<0.005`),true);
|
||||
assert.equal(await site.eval('document.getElementById("bPagar").disabled'),false);
|
||||
// The freight quote and the customer checks arrive on their own time: wait
|
||||
// for Pagar to open instead of reading it once (CI run 356).
|
||||
await waitFor(()=>site.eval('!document.getElementById("bPagar").disabled'),'Pagar enabled');
|
||||
await site.click('#bPagar');
|
||||
try{
|
||||
// A cart the Site can price is approved at once: the customer pays now.
|
||||
@@ -171,9 +173,15 @@ try{
|
||||
assert.equal(await kanban.eval('sessionStorage.getItem("dtf-operator")'),null);
|
||||
assert.equal(await kanban.eval('document.getElementById("password").value'),'');
|
||||
await kanban.click('[data-tab="site"]');
|
||||
await waitFor(()=>kanban.eval('!!document.querySelector("[data-site-tab=\\"videos\\"]")'),'Site tabs in Gestão');
|
||||
await kanban.click('[data-site-tab="videos"]');
|
||||
await waitFor(()=>kanban.eval('document.querySelectorAll("#site-videos-list .siteVideoRow").length===6'),
|
||||
'six video slots in Gestão');
|
||||
assert.equal(await kanban.eval('document.querySelectorAll("#site-videos-list input[type=file]").length'),12);
|
||||
assert.equal(await kanban.eval('document.querySelectorAll("#site-videos-list input[type=file]").length'),0);
|
||||
await kanban.click('#site-videos-list .siteVideoRow .btn');
|
||||
await waitFor(()=>kanban.eval('document.querySelectorAll(".modal input[type=file]").length===2'),'video edit dialog');
|
||||
await kanban.eval('document.querySelector(".modal .dlghead .btn.sq")?.click()');
|
||||
await waitFor(()=>kanban.eval('!document.querySelector(".modal")'),'video dialog closed');
|
||||
await mkdir('output/local',{recursive:true});
|
||||
await kanban.eval('document.getElementById("site-videos-panel").scrollIntoView()');
|
||||
await kanban.screenshot('output/local/kanban-videos.png');
|
||||
@@ -227,12 +235,10 @@ try{
|
||||
await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-move]')`),'order panel');
|
||||
// The Prumo report is on the card before the designer opens the file.
|
||||
await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] .prumo')`),'Prumo report');
|
||||
// No machine at payment (Dropstar, 2026-11-05): the pull chooses one. It is
|
||||
// the machine this test made after sign-in.
|
||||
// No machine at payment (Dropstar, 2026-11-05): pulling without a session
|
||||
// machine asks which machine takes the card (DTF-WEB-4). It is the machine
|
||||
// this test made after sign-in.
|
||||
const machineId=testMachine;
|
||||
await kanban.eval(`(()=>{const s=document.querySelector('[data-order="${oid}"] select[aria-label="Máquina do pedido"]');
|
||||
s.value=${JSON.stringify(machineId)};s.dispatchEvent(new Event('change',{bubbles:true}));})()`);
|
||||
await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').machine?.id===${JSON.stringify(machineId)}`),'machine chosen');
|
||||
// Dropstar's flow (2026-10-23): Arte conferida is the queue, Revisão before Finalizado.
|
||||
for(const [title,state] of [['Arte conferida','tra'],['Imprimindo','imp'],['Revisão','rev'],['Finalizado','fin']]){
|
||||
if(state==='tra'){
|
||||
@@ -275,6 +281,12 @@ try{
|
||||
}
|
||||
await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-move="${state}"]')`),'move to '+title);
|
||||
await kanban.click(`[data-order="${oid}"] [data-move="${state}"]`);
|
||||
if(state==='imp'){
|
||||
// The order has no machine and the session has none: pick it here.
|
||||
await waitFor(()=>kanban.eval(`!!document.querySelector('.mchoice[data-machine="${machineId}"]')`),'machine chooser');
|
||||
await kanban.click(`.mchoice[data-machine="${machineId}"]`);
|
||||
await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').machine?.id===${JSON.stringify(machineId)}`),'card machine chosen');
|
||||
}
|
||||
await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').state==='${state}'`),'transition '+state);
|
||||
if(state==='tra'){
|
||||
// The file opens from the card itself, without first expanding the order.
|
||||
@@ -290,7 +302,9 @@ try{
|
||||
// Other orders the earlier suites left in the queue may still be coming
|
||||
// down: only once the round ends must no half-written file be left.
|
||||
await waitFor(()=>kanban.eval('!FOLDER.busy'),'folder round finished',60000);
|
||||
assert.equal((await savedFiles('2. Arte conferida')).some(n=>n.endsWith('.baixando')),false);
|
||||
assert.equal((await savedFiles('2. Arte conferida')).some(n=>/\.(baixando|crswap)$/.test(n)),false);
|
||||
// Written in the work folder and moved in whole: nothing stays there (order #30).
|
||||
assert.deepEqual(await savedFiles('_tmp'),[]);
|
||||
assert.equal((await savedFiles('1. Arte recebida')).some(n=>n.startsWith(prefix)),false);
|
||||
// A file whose order was deleted leaves the folder.
|
||||
await kanban.eval(`(async()=>{const dir=await window.picked.getDirectoryHandle('2. Arte conferida',{create:true});
|
||||
@@ -344,6 +358,12 @@ try{
|
||||
await kanban.click('[data-tab="stats"]');
|
||||
await waitFor(()=>kanban.eval(`document.querySelector('#stats-kpis').children.length>0
|
||||
&& document.querySelector('#stats-machine-body').children.length>0`),'Números tab and machines by month');
|
||||
// The stage-times dialog (D1) opens from Números and keeps its five rows.
|
||||
await kanban.click('#edit-stage-limits');
|
||||
await waitFor(()=>kanban.eval('!!document.querySelector(".modal.limitsDialog")'),'stage-times dialog');
|
||||
assert.equal(await kanban.eval('document.querySelectorAll(".modal.limitsDialog tbody tr").length'),5);
|
||||
await kanban.eval('document.querySelector(".modal .dlghead .btn.sq").click()');
|
||||
await waitFor(()=>kanban.eval('!document.querySelector(".modal")'),'stage-times dialog closed');
|
||||
// Cotações lives in its own file now: the list and the review panel load too.
|
||||
await kanban.click('[data-tab="quotes"]');
|
||||
await waitFor(()=>kanban.eval(`document.querySelector('#quote-filters').children.length>0
|
||||
@@ -354,11 +374,32 @@ try{
|
||||
await waitFor(()=>kanban.eval(`document.querySelector('#users-list').children.length>0
|
||||
&& document.querySelector('#roles-matrix').children.length>0
|
||||
&& document.querySelector('#machines-list').children.length>0`),'Usuários tab, people, roles and machines');
|
||||
// More than one profile (Marcus, 2026-11-26): the form offers the others as chips.
|
||||
await kanban.eval('userForm()');
|
||||
await waitFor(()=>kanban.eval(`[...document.querySelectorAll('.fld > span')].some(s=>s.textContent==='Outros perfis')
|
||||
&& document.querySelectorAll('.fopts .fopt').length>=8`),'user form with other profiles');
|
||||
await kanban.eval(`document.querySelector('.fopts .fopt').click()`);
|
||||
assert.equal(await kanban.eval(`document.querySelector('.fopts .fopt').getAttribute('aria-pressed')`),'true');
|
||||
await kanban.eval(`[...document.querySelectorAll('.modal .dfoot button')].find(b=>b.textContent==='Cancelar').click()`);
|
||||
await waitFor(()=>kanban.eval(`!document.querySelector('.modal')`),'user form closed');
|
||||
// Pagamentos and Integrações live in their own file now: both lists still render.
|
||||
await kanban.click('[data-tab="payments"]');
|
||||
await waitFor(()=>kanban.eval(`document.querySelector('#payments').children.length>0`),'Pagamentos tab');
|
||||
await kanban.click('[data-tab="integrations"]');
|
||||
await waitFor(()=>kanban.eval(`document.querySelector('#integrations').children.length>0`),'Integrações tab');
|
||||
// The phone board lives in its own file now: open its Mais and filters.
|
||||
await kanban.call('Emulation.setDeviceMetricsOverride',{width:390,height:844,deviceScaleFactor:1,mobile:true});
|
||||
await waitFor(()=>kanban.eval('PHONE.matches'),'phone board');
|
||||
await kanban.click('#more-nav');
|
||||
await waitFor(()=>kanban.eval('!!document.querySelector(".msheet")'),'phone menu');
|
||||
await kanban.eval('document.querySelector(".mscrim").click()');
|
||||
await waitFor(()=>kanban.eval('!document.querySelector(".msheet")'),'phone menu closed');
|
||||
await kanban.click('#filter-open');
|
||||
await waitFor(()=>kanban.eval('!!document.querySelector(".msheet")'),'phone filters');
|
||||
await kanban.eval('document.querySelector(".mscrim").click()');
|
||||
await waitFor(()=>kanban.eval('!document.querySelector(".msheet")'),'phone filters closed');
|
||||
await kanban.call('Emulation.setDeviceMetricsOverride',{width:1440,height:1000,deviceScaleFactor:1,mobile:false});
|
||||
await waitFor(()=>kanban.eval('!PHONE.matches'),'desktop board again');
|
||||
// A guest sees the order paid in this browser; creating an account keeps it.
|
||||
const portal=await page(siteOrigin+'/conta/pedidos?order='+oid);
|
||||
await waitFor(async()=> (await portal.text()).includes('Finalizado'),'customer order tracking');
|
||||
|
||||
@@ -33,15 +33,16 @@ def run():
|
||||
manager = manager.operator_client
|
||||
coupon_id = None
|
||||
quote_id = None
|
||||
early_id = None
|
||||
order_id = None
|
||||
upload_id = None
|
||||
try:
|
||||
upload_id = upload_bytes(client, artwork(), name=f'LOCAL-COUPON-{tag}.png')
|
||||
sheet = {**item_spec('uvfile', '1', 0, upload_id),
|
||||
sheet = {**item_spec('uvfile', '1', 0, upload_id, aspect=2),
|
||||
'quality_status': 'warning', 'quality_acknowledged': True}
|
||||
# The sheet is the customer's own file, not one someone opens by hand.
|
||||
sheet['production']['sources'][0]['measurement'] = 'file'
|
||||
art = {**item_spec('uv', '1', 0, upload_id),
|
||||
art = {**item_spec('uv', '1', 0, upload_id, aspect=2),
|
||||
'quality_status': 'warning', 'quality_acknowledged': True}
|
||||
items = [sheet, art]
|
||||
|
||||
@@ -61,6 +62,9 @@ def run():
|
||||
assert [line['total_cents'] for line in approved['items']] == [7990, 8990], approved
|
||||
assert approved['total_cents'] == 16081, approved
|
||||
|
||||
# A second cart with the coupon, made while it still had uses.
|
||||
early_id = quote(client, items, code, mail)['id']
|
||||
|
||||
# One paid order spends a use (a fake payment, no print job).
|
||||
order_id = uuid4()
|
||||
with db.connect() as c:
|
||||
@@ -110,6 +114,10 @@ def run():
|
||||
manager.call('/operator/site/coupons/' + coupon_id, {'max_uses': 1})
|
||||
refused = quote(client, items, code, mail, expected=422)
|
||||
assert refused['detail'] == 'Este cupom já foi usado o máximo de vezes.', refused
|
||||
# The limit is spent at payment: the cart made before it ran out no
|
||||
# longer pays with its discount.
|
||||
refused = client.call('/payments/intent', {'quote_id': early_id, 'method': {'type': 'pix'}}, expected=409)
|
||||
assert 'máximo de vezes' in refused['detail'] and 'sem o cupom' in refused['detail'], refused
|
||||
manager.call('/operator/site/coupons/' + coupon_id,
|
||||
{'max_uses': None, 'max_uses_per_customer': 1})
|
||||
refused = quote(client, items, code, mail, expected=422)
|
||||
@@ -135,13 +143,16 @@ def run():
|
||||
stats = manager.call('/operator/stats?days=30')
|
||||
assert any(entry['id'] == coupon_id for entry in stats['coupons']), stats['coupons']
|
||||
print('PASS: a coupon discounts one product, refuses paused/expired/not-started/'
|
||||
'minimum/product/use states, reaches Tiny data and Números, and soft delete keeps history')
|
||||
'minimum/product/use states, also at payment, reaches Tiny data and Números, and soft delete keeps history')
|
||||
finally:
|
||||
with db.connect() as c:
|
||||
if order_id:
|
||||
c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (order_id,))
|
||||
if quote_id:
|
||||
c.execute('DELETE FROM dtf_local.quotes WHERE id=%s', (quote_id,))
|
||||
if early_id:
|
||||
c.execute('DELETE FROM dtf_local.payment_intents WHERE quote_id=%s', (early_id,))
|
||||
c.execute('DELETE FROM dtf_local.quotes WHERE id=%s', (early_id,))
|
||||
if coupon_id:
|
||||
c.execute('DELETE FROM dtf_local.coupons WHERE id=%s', (coupon_id,))
|
||||
if upload_id:
|
||||
|
||||
@@ -44,11 +44,11 @@ def run():
|
||||
assert rules['treatment_offered'] is True, rules
|
||||
|
||||
upload_id = upload_bytes(client, artwork(), name=f'LOCAL-GRADE-{tag}.png')
|
||||
item = {**item_spec('uv', '1', 50, upload_id),
|
||||
item = {**item_spec('uv', '1', 50, upload_id, aspect=2),
|
||||
'quality_status': 'warning', 'quality_acknowledged': True}
|
||||
|
||||
refused = client.call('/quotes', quote_body(item, False, mail), expected=422)
|
||||
assert refused['detail'] == ('Sua arte tem nota 50: para imprimir com qualidade, '
|
||||
assert refused['detail'] == ('Sua arte está abaixo da resolução mínima, então '
|
||||
'o Ajuste Fino é obrigatório neste pedido.'), refused
|
||||
|
||||
made = client.call('/quotes', quote_body(item, True, mail))
|
||||
|
||||
@@ -25,6 +25,16 @@ def run():
|
||||
status,amount_cents,response) VALUES(%s,%s,'mercadopago',%s,'card','approved',1490,%s) RETURNING id''',
|
||||
(uuid4(), quote, str(uuid4()), Jsonb({'live_mode': True}))).fetchone()['id']
|
||||
|
||||
# A Site video's file stays: the whole Site tab is kept (Marcus, 2026-11-16).
|
||||
video_upload, video_id = uuid4(), None
|
||||
with db.connect() as c:
|
||||
taken = {row['id'] for row in c.execute('SELECT id FROM dtf_local.site_videos').fetchall()}
|
||||
video_id = next(name for name in ('retirada', 'sala', 'nota', 'avulsas', 'subindo', 'png') if name not in taken)
|
||||
c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,complete,expires_at)
|
||||
VALUES(%s,%s,'reset-video.mp4',1,%s,'',true,now()+interval '30 days')''',
|
||||
(video_upload, owner, f'originals/reset-test-{video_upload}'))
|
||||
c.execute("INSERT INTO dtf_local.site_videos(id,upload_id) VALUES(%s,%s)", (video_id, video_upload))
|
||||
|
||||
lines = []
|
||||
# Real money paid: nothing happens, even when confirmed.
|
||||
assert launch_reset.main(['--confirmar', 'APAGAR'], out=lines.append) == 1
|
||||
@@ -47,7 +57,11 @@ def run():
|
||||
for table in ('orders', 'quotes', 'payment_intents', 'movements', 'outbox'):
|
||||
assert c.execute(f'SELECT count(*) AS n FROM dtf_local.{table}').fetchone()['n'] == 0, table
|
||||
assert not c.execute('''SELECT 1 FROM dtf_local.uploads WHERE purged_at IS NULL
|
||||
AND expires_at>now()''').fetchone()
|
||||
AND expires_at>now() AND id<>%s''', (video_upload,)).fetchone()
|
||||
assert c.execute('SELECT expires_at>now() AS kept FROM dtf_local.uploads WHERE id=%s',
|
||||
(video_upload,)).fetchone()['kept']
|
||||
c.execute('DELETE FROM dtf_local.site_videos WHERE id=%s', (video_id,))
|
||||
c.execute('DELETE FROM dtf_local.uploads WHERE id=%s', (video_upload,))
|
||||
assert c.execute('SELECT count(*) AS n FROM dtf_local.operators').fetchone()['n'] >= 1
|
||||
assert any('Apagado.' in line for line in lines) and 'continua de onde parou' in lines[-1], lines
|
||||
# The numbering is not reset: DTF-1…DTF-15 already exist in Tiny.
|
||||
@@ -77,7 +91,7 @@ def run():
|
||||
'4. Revisão', '5. Finalizado', 'Recibos', 'Revisões'):
|
||||
assert list((root / name).iterdir()) == [], name
|
||||
assert (root / 'Estampas' / '1001.png').read_bytes() == b'art'
|
||||
print('PASS: launch cleanup refuses real payments, counts first, then removes test orders and quotes, keeping the numbering and the art library')
|
||||
print('PASS: launch cleanup refuses real payments, counts first, then removes test orders and quotes, keeping the numbering, the Site videos\' files and the art library')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@@ -13,7 +13,7 @@ def final_stub(c, oid, owner):
|
||||
uid = uuid4()
|
||||
c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,complete,
|
||||
expires_at,scan_state) VALUES(%s,%s,'machine-log-test.png',1,%s,'',true,now()+interval '1 day','clean')''',
|
||||
(uid, owner, f'machine-log-test/{uid}'))
|
||||
(uid, owner, f'originals/machine-log-test-{uid}'))
|
||||
c.execute('''INSERT INTO dtf_local.order_files(id,order_id,upload_id,item_index,kind,note,created_by)
|
||||
VALUES(%s,%s,%s,0,'final','machine log test','test')''', (uuid4(), oid, uid))
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ def final_stub(c, oid, owner):
|
||||
uid = uuid4()
|
||||
c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,complete,
|
||||
expires_at,scan_state) VALUES(%s,%s,'machine-test.png',1,%s,'',true,now()+interval '1 day','clean')''',
|
||||
(uid, owner, f'machine-test/{uid}'))
|
||||
(uid, owner, f'originals/machine-test-{uid}'))
|
||||
c.execute('''INSERT INTO dtf_local.order_files(id,order_id,upload_id,item_index,kind,note,created_by)
|
||||
VALUES(%s,%s,%s,0,'final','machine test','test')''', (uuid4(), oid, uid))
|
||||
|
||||
|
||||
@@ -47,4 +47,42 @@ assert.notDeepEqual(
|
||||
apiError('/quotes/ba39b432-b0d1-4b1b-8971-09123e067067', 422, expired).options.fingerprint,
|
||||
apiError('/orders/ba39b432-b0d1-4b1b-8971-09123e067067', 422, expired).options.fingerprint);
|
||||
|
||||
// Every red message reaches Sentry, also one the page caught itself; the
|
||||
// same text an API error already sent (or deliberately skipped) is not doubled.
|
||||
captured = null;
|
||||
window.dtfObservability.uiError('Pastas automáticas: A última tentativa falhou: DTF-26-item-1.png bloqueado.', 'kanban');
|
||||
assert.ok(captured, 'uiError sends a caught error');
|
||||
assert.equal(captured.message, 'Aviso kanban: Pastas automáticas: A última tentativa falhou: :arquivo bloqueado.');
|
||||
assert.deepEqual(captured.options.fingerprint, ['ui-error', 'kanban', 'Pastas automáticas: A última tentativa falhou: :arquivo bloqueado.']);
|
||||
apiError('/orders', 409, 'Falta a foto da revisão.');
|
||||
captured = null;
|
||||
window.dtfObservability.uiError('Falta a foto da revisão.', 'kanban');
|
||||
assert.equal(captured, null, 'an API error shown in red is sent once');
|
||||
window.dtfObservability.apiError('/board', 503, 'O sistema está reiniciando.');
|
||||
window.dtfObservability.uiError('O sistema está reiniciando.', 'kanban');
|
||||
assert.equal(captured, null, 'a skipped restart 503 stays skipped');
|
||||
|
||||
// A refusal the server explains (a 4xx with a sentence) is no bug: on the
|
||||
// Kanban a warning, on the Site nothing; a field list or a 5xx is an error
|
||||
// (2026-11-30).
|
||||
const refused = (app, status, detail) => {
|
||||
// A fresh copy per app: a page starts Sentry once, for its own app.
|
||||
vm.runInThisContext(readFileSync('web/observability.js', 'utf8'));
|
||||
window.dtfObservability.start('https://key@o1.ingest.sentry.io/1', app);
|
||||
captured = null;
|
||||
window.dtfObservability.apiError('/orders/1/move', status, 'Puxe o pedido na mesma máquina.', detail);
|
||||
return captured;
|
||||
};
|
||||
assert.equal(refused('kanban', 409, 'Puxe o pedido na mesma máquina.').options.level, 'warning');
|
||||
assert.equal(refused('kanban', 409, 'Puxe o pedido na mesma máquina.').options.tags.recusa, 'sim');
|
||||
assert.equal(refused('site', 409, 'Cupom não encontrado.'), null, 'a refusal on the Site is not sent');
|
||||
assert.equal(refused('site', 422, [{loc: ['body', 'items'], msg: 'bad'}]).options.level, 'error');
|
||||
assert.equal(refused('site', 500, 'Internal Server Error').options.level, 'error');
|
||||
assert.equal(refused('kanban', 422, [{loc: ['body'], msg: 'bad'}]).options.level, 'error');
|
||||
// Shown in red after it, the refusal is not sent again as a page error.
|
||||
refused('site', 409, 'Cupom não encontrado.');
|
||||
captured = null;
|
||||
window.dtfObservability.uiError('Puxe o pedido na mesma máquina.', 'site');
|
||||
assert.equal(captured, null, 'a refusal shown in red is not sent as an error');
|
||||
|
||||
console.log('observability web checks passed');
|
||||
|
||||
@@ -109,6 +109,10 @@ def run():
|
||||
client.call(f'/operator/orders/{paid_order}/delete', {}, operator=True)
|
||||
with db.connect() as c:
|
||||
assert not c.execute('SELECT 1 FROM dtf_local.orders WHERE id=%s', (paid_order,)).fetchone()
|
||||
# Its cancellation still goes to Tiny: deleted at once, or with Tiny
|
||||
# down, it must not be lost with the order.
|
||||
assert c.execute('SELECT 1 FROM dtf_local.outbox WHERE event_key=%s',
|
||||
(f'{paid_order}:cancelled:tiny',)).fetchone(), 'the Tiny cancellation was lost'
|
||||
# Deleted: no state at all, so the folder removes its files too.
|
||||
assert client.call('/operator/queue/folder', {'held': [str(paid_order)]}, operator=True)['states'] == {}
|
||||
with db.connect() as c:
|
||||
@@ -123,7 +127,7 @@ def run():
|
||||
for name, fid in files.items():
|
||||
c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,complete,
|
||||
expires_at,scan_state) VALUES(%s,%s,%s,1,%s,'m',true,now()+interval '20 days','clean')''',
|
||||
(fid, owner, name + '.png', f'test/{fid}'))
|
||||
(fid, owner, name + '.png', f'originals/test-{fid}'))
|
||||
def place(quote, order, uploads, provider, cancelled):
|
||||
content = {'customer': {'mail': mail}, 'items': [{'mode': 'file', 'uploads': [str(u) for u in uploads]}],
|
||||
'total_cents': 1490}
|
||||
@@ -156,7 +160,7 @@ def run():
|
||||
c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (order,))
|
||||
c.execute('DELETE FROM dtf_local.quotes WHERE id=ANY(%s)', ([gone_quote, other_quote, test2_quote],))
|
||||
c.execute('DELETE FROM dtf_local.uploads WHERE id=ANY(%s)', (list(files.values()),))
|
||||
print('PASS: discard hides and blocks a quote; test orders delete; paid orders cancel, then delete '
|
||||
print('PASS: discard hides and blocks a quote; test orders delete; paid orders cancel, then delete, keeping the Tiny cancellation, '
|
||||
'and free their files')
|
||||
finally:
|
||||
with db.connect() as c:
|
||||
|
||||
@@ -121,7 +121,12 @@ def run():
|
||||
later = deliver({**payload, 'event_id': 'retry-' + uuid4().hex})
|
||||
assert 'already existed' in later.get('outcome', ''), later
|
||||
assert customer.call('/quotes/' + quote_id)['order']['id'] == order['id'], 'a second order appeared'
|
||||
print('PASS: one order from a repeated and re-sent approval')
|
||||
# Another payment of the same cart (a PIX and a card): the customer paid
|
||||
# twice, and it is listed for a refund, not taken for a re-sent approval.
|
||||
second = deliver({**payload, 'event_id': 'second-' + uuid4().hex, 'payment_id': 'second-' + uuid4().hex[:8]})
|
||||
assert second.get('outcome', '').startswith('attention: second payment'), second
|
||||
assert customer.call('/quotes/' + quote_id)['order']['id'] == order['id'], 'a second order appeared'
|
||||
print('PASS: one order from a repeated and re-sent approval; a second payment is listed for a refund')
|
||||
|
||||
assert customer.call('/orders/dev-paid', {'quote_id': quote_id})['id'] == order['id']
|
||||
other = Client()
|
||||
@@ -151,6 +156,10 @@ def run():
|
||||
order = tester.call('/operator/quotes/' + test_quote + '/test-order', {}, operator=True)
|
||||
assert order['payment']['provider'] == 'teste' and order['state'] == 'rec', order
|
||||
assert tester.call('/operator/quotes/' + test_quote + '/test-order', {}, operator=True)['id'] == order['id']
|
||||
# The quote is that test order's now: registering it names the test order (Sentry DTF-WEB-D).
|
||||
refused = tester.call('/operator/quotes/' + test_quote + '/register', {'origin': 'atendimento', 'method': 'cash'},
|
||||
operator=True, expected=409)
|
||||
assert 'pedido de teste #' + str(order['number']) in refused['detail'], refused
|
||||
version = order['version']
|
||||
# Arte conferida, the print queue, takes the order once its final is approved.
|
||||
from tests.smoke_test import final_png_bytes
|
||||
|
||||
@@ -9,6 +9,7 @@ Kanban until someone records what was done.
|
||||
Run inside the API container (it needs Pillow): python -m tests.print_file_test
|
||||
"""
|
||||
import io
|
||||
from decimal import Decimal
|
||||
import time
|
||||
from urllib.request import urlopen
|
||||
from uuid import uuid4
|
||||
@@ -32,7 +33,8 @@ def download_png(client, upload_id):
|
||||
image = Image.open(io.BytesIO(response.read()))
|
||||
assert image.format == 'PNG' and image.mode == 'RGBA', (image.format, image.mode)
|
||||
return image
|
||||
CUSTOMER = {'cnpj': '11222333000181', 'zap': '11999999999', 'mail': 'print-test@example.test'}
|
||||
CUSTOMER = {'cnpj': '11222333000181', 'zap': '11999999999', 'mail': 'print-test@example.test',
|
||||
'name': 'Cliente Print Test'}
|
||||
|
||||
|
||||
def artwork(kind='PNG'):
|
||||
@@ -103,9 +105,42 @@ def run():
|
||||
for copy in range(2):
|
||||
assert film.getpixel((px(20 * copy + 10), px(5))) == (220, 30, 60, 255), copy
|
||||
assert film.getpixel((px(50), px(5)))[3] == 0
|
||||
assert row['detail']['footer'].startswith('DROPSTAR · Pedido DTF-%d · Item 1/1 · ' % order['number']), row['detail']
|
||||
footer = row['detail']['footer']
|
||||
assert footer.startswith('DROPSTAR · Pedido DTF-%d · %s · Item 1/1 · '
|
||||
% (order['number'], CUSTOMER['name'])), footer
|
||||
assert footer.endswith(' · 2 peças'), footer
|
||||
print('PASS: paid order generated a 57 x 10 cm PNG print file with both copies and its footer')
|
||||
|
||||
# A ready sheet with its empty strips cut (Marcus, 2026-11-18): the cart
|
||||
# sends what the Site cut from the top and bottom of a 27 x 30 cm UV sheet
|
||||
# with 20 cm of art in the middle, as web/site-upload.js aplicaCorte does.
|
||||
# The order bills and prints the 21 cm left, the art whole.
|
||||
# At 300 DPI, so neither the Site nor the server asks for a resolution note.
|
||||
sheet = Image.new('RGBA', (px(27), px(30)))
|
||||
sheet.paste(Image.new('RGBA', (px(23), px(20)), (30, 60, 200, 255)), (px(2), px(5)))
|
||||
buffer = io.BytesIO()
|
||||
sheet.save(buffer, 'PNG', dpi=(300, 300))
|
||||
sheet_upload = upload_bytes(client, buffer.getvalue(), name='LOCAL-TRIMMED-SHEET.png')
|
||||
trimmed = {'mode': 'uvfile', 'metres': '0.21', 'grade': 90, 'uploads': [sheet_upload],
|
||||
'production': {'version': 3, 'film_width_cm': 27, 'height_cm': 21,
|
||||
'sources': [{'upload_id': sheet_upload, 'kind': 'sheet', 'width_cm': 27,
|
||||
'length_cm': 21, 'copies': 1, 'rotation_degrees': 0, 'mirrored': False,
|
||||
'measurement': 'file', 'trim_top_cm': 4.5, 'trim_bottom_cm': 4.5}],
|
||||
'placements': [{'source_index': 0, 'copy_index': 0, 'x_cm': 0, 'y_cm': 0,
|
||||
'width_cm': 27, 'length_cm': 21, 'rotation_degrees': 0,
|
||||
'mirrored': False}]},
|
||||
'quality_status': 'ok', 'quality_acknowledged': False}
|
||||
sheet_order, sheet_row = wait_print(client, paid_order(client, trimmed)['id'], 'ready')
|
||||
assert any(line.endswith('Faixas vazias cortadas: 9,0 cm') for line in sheet_order['prumo']), sheet_order['prumo']
|
||||
assert Decimal(sheet_order['snapshot']['items'][0]['billed_metres']) == 1, sheet_order['snapshot']['items'][0]
|
||||
trimmed_film = download_png(client, sheet_row['upload_id'])
|
||||
assert trimmed_film.size == (px(27), px(21) + px(1.5)), trimmed_film.size
|
||||
# 0,5 cm of margin above and below the art, which fills the rest.
|
||||
assert trimmed_film.getpixel((px(13), px(0.2)))[3] == 0 and trimmed_film.getpixel((px(13), px(20.8)))[3] == 0
|
||||
assert trimmed_film.getpixel((px(13), px(1))) == (30, 60, 200, 255)
|
||||
assert trimmed_film.getpixel((px(13), px(20))) == (30, 60, 200, 255)
|
||||
print('PASS: a ready sheet with its empty strips cut bills and prints only what is left')
|
||||
|
||||
# Item 7: "Abrir e conferir" gets the file in pieces, the first of which is
|
||||
# the top of the film, then the original.
|
||||
view = client.call('/operator/orders/' + order['id'] + '/view', operator=True)['files']
|
||||
@@ -124,6 +159,9 @@ def run():
|
||||
mine = [f for f in early['files'] if f['order'] == oid]
|
||||
assert [(f['upload_id'], f['state']) for f in mine] == [(str(row['upload_id']), 'rec')], early['files']
|
||||
assert mine[0]['name'].startswith('DTF-%d-item-1' % order['number']) and early['states'] == {oid: 'rec'}
|
||||
# The folders download a whole list one file after another: an hour's link,
|
||||
# not the 5 minutes that ran out before the last ones began.
|
||||
assert 'X-Amz-Expires=3600' in mine[0]['url'], mine[0]['url']
|
||||
late = client.call('/operator/queue/folder', {'early': False, 'held': []}, operator=True)
|
||||
assert not [f for f in late['files'] if f['order'] == oid] and late['states'] == {}
|
||||
client.call('/operator/queue/folder', {'early': True, 'held': []}, expected=401)
|
||||
@@ -169,6 +207,50 @@ def run():
|
||||
'note': 'again'}, operator=True, expected=409)
|
||||
print('PASS: generated file approved as final without re-uploading; order queued for printing')
|
||||
|
||||
# A ready file generated again for the part size of now (order #36,
|
||||
# 2026-11-17): from Arte conferida or Imprimindo the generated final goes,
|
||||
# the order is back in Arte recebida and the file is made once more.
|
||||
again_upload = upload_bytes(client, artwork(), name='LOCAL-AGAIN.png')
|
||||
again, made = wait_print(client, paid_order(client, loose_item(again_upload))['id'], 'ready')
|
||||
v = client.call('/operator/orders/' + again['id'] + '/final-files',
|
||||
{'version': again['version'], 'files': [{'item_index': 0, 'upload_id': str(made['upload_id'])}],
|
||||
'note': 'ok'}, operator=True)['version']
|
||||
client.call('/operator/orders/' + again['id'] + '/move', {'state': 'tra', 'version': v}, operator=True)
|
||||
client.call('/operator/orders/' + again['id'] + '/print-files/again', {}, operator=True)
|
||||
with db.connect() as c:
|
||||
state = c.execute('SELECT state FROM dtf_local.orders WHERE id=%s', (again['id'],)).fetchone()['state']
|
||||
finals = c.execute('''SELECT count(*) AS n FROM dtf_local.order_files
|
||||
WHERE order_id=%s AND kind='final' AND active''', (again['id'],)).fetchone()['n']
|
||||
back = c.execute('SELECT reason,back FROM dtf_local.movements WHERE order_id=%s ORDER BY id DESC LIMIT 1',
|
||||
(again['id'],)).fetchone()
|
||||
assert (state, finals, back['reason'], back['back']) == ('rec', 0, 'Arquivo gerado de novo', True), (state, finals, back)
|
||||
again, remade = wait_print(client, again['id'], 'ready')
|
||||
assert str(remade['upload_id']) != str(made['upload_id']), (made, remade)
|
||||
# Its name carries the version, so it is not taken for the first (#130).
|
||||
assert remade['name'] == 'DTF-%d-v2-item-1.png' % again['number'], remade['name']
|
||||
print('PASS: a ready file is generated again from Arte conferida, back in Arte recebida to approve')
|
||||
|
||||
# The generated file approved, sent to Correção (its final stops counting)
|
||||
# and back: the same file is approved again, not refused as already in
|
||||
# the order (Sentry DTF-WEB-10).
|
||||
redo, redo_row = wait_print(client, paid_order(client, loose_item(upload_bytes(client, artwork(), name='LOCAL-REDO.png')))['id'], 'ready')
|
||||
finals = [{'item_index': 0, 'upload_id': str(redo_row['upload_id'])}]
|
||||
v = client.call('/operator/orders/' + redo['id'] + '/final-files',
|
||||
{'version': redo['version'], 'files': finals, 'note': 'ok'}, operator=True)['version']
|
||||
def version_of(oid):
|
||||
with db.connect() as c:
|
||||
return c.execute('SELECT version FROM dtf_local.orders WHERE id=%s', (oid,)).fetchone()['version']
|
||||
client.call('/operator/orders/' + redo['id'] + '/move', {'state': 'cor', 'version': v, 'reason': 'Teste'}, operator=True)
|
||||
client.call('/operator/orders/' + redo['id'] + '/move', {'state': 'rec', 'version': version_of(redo['id']),
|
||||
'reason': 'Teste'}, operator=True)
|
||||
client.call('/operator/orders/' + redo['id'] + '/final-files',
|
||||
{'version': version_of(redo['id']), 'files': finals, 'note': 'de novo'}, operator=True)
|
||||
with db.connect() as c:
|
||||
rows = c.execute('''SELECT active FROM dtf_local.order_files WHERE order_id=%s AND kind='final' ''',
|
||||
(redo['id'],)).fetchall()
|
||||
assert [r['active'] for r in rows] == [True], rows
|
||||
print('PASS: a generated final that stopped counting is approved again')
|
||||
|
||||
# Item 10: printing, the file goes once into its machine's hot folder for
|
||||
# its class; Flexi taking it is reported; leaving Imprimindo withdraws
|
||||
# what Flexi did not take.
|
||||
@@ -176,6 +258,13 @@ def run():
|
||||
# No class measured or chosen: the part waits for one.
|
||||
assert not [p for p in client.call('/operator/queue/hot', {}, operator=True)['write'] if p['order'] == oid]
|
||||
client.call('/operator/orders/' + oid + '/contraction', {'item_index': 0, 'value': 'C2'}, operator=True)
|
||||
# Renamed, the machine keeps its folder, the path FlexiPRINT watches;
|
||||
# no other machine may then take that folder's name.
|
||||
client.call('/operator/machines/' + machine, {'name': f'Hot {tag} renomeada', 'products': ['textil']},
|
||||
operator=True)
|
||||
listed = next(m for m in client.call('/operator/machines', operator=True)['machines'] if m['id'] == machine)
|
||||
assert listed['name'] == f'Hot {tag} renomeada' and listed['folder'] == f'Hot {tag}', listed
|
||||
client.call('/operator/machines', {'name': f'Hot {tag}', 'products': ['textil']}, operator=True, expected=409)
|
||||
hot = client.call('/operator/queue/hot', {}, operator=True)
|
||||
due = [p for p in hot['write'] if p['order'] == oid]
|
||||
assert hot['folder'] == '3. Imprimindo' and [(p['folder'], p['name']) for p in due] == \
|
||||
@@ -192,7 +281,10 @@ def run():
|
||||
assert not client.call(f'/operator/queue/hot/{part}', {'state': 'consumed'}, operator=True)['ok']
|
||||
board = next(o for o in client.call('/operator/board', operator=True)['orders'] if o['id'] == oid)
|
||||
assert board['hot'] == {'parts': 1, 'taken': 1, 'waiting': 0}, board['hot']
|
||||
print('PASS: the printing file goes once into its machine\'s hot folder for its class')
|
||||
# Which items go again is chosen before Imprimindo, not while printing (#105).
|
||||
client.call('/operator/orders/' + oid + '/print-items', {'items': [0]}, operator=True, expected=409)
|
||||
print('PASS: the printing file goes once into its machine\'s hot folder for its class, '
|
||||
'and a renamed machine keeps its folder')
|
||||
finally:
|
||||
client.call('/operator/machines/' + machine, {'name': f'Hot {tag}', 'products': ['textil'], 'active': False},
|
||||
operator=True)
|
||||
@@ -207,6 +299,16 @@ def run():
|
||||
assert red[3] == 255 and red[0] > 200 and red[1] < 60, red
|
||||
print('PASS: PDF artwork drawn into the PNG print file at 300 DPI')
|
||||
|
||||
# Before approving, the panel asks whether the files can be finals: the
|
||||
# generated PNG can, the customer's PDF original cannot, and the answer
|
||||
# says why without a refusal (Sentry DTF-WEB-11). Another order's file is
|
||||
# not read.
|
||||
check = client.call('/operator/orders/' + pdf_order['id'] + '/final-check',
|
||||
{'uploads': [str(pdf_row['upload_id']), pdf_upload, str(row['upload_id'])]}, operator=True)
|
||||
assert [p['upload_id'] for p in check['problems']] == [pdf_upload], check
|
||||
assert '300 DPI' in check['problems'][0]['message'], check
|
||||
print('PASS: the panel learns before approving that a file cannot be a final')
|
||||
|
||||
# The proof card (Dropstar, 2026-10-30 and 2026-11-03): an order above
|
||||
# 10 m gets a child card "Prova"; the order waits outside the queue until
|
||||
# the card in Revisão gets its answer.
|
||||
@@ -294,15 +396,199 @@ def run():
|
||||
wait_print(client, card['id'], 'ready')
|
||||
with db.connect() as c:
|
||||
c.execute("UPDATE dtf_local.orders SET state='rev' WHERE id=%s", (card['id'],))
|
||||
# The proof's photo, taken in Revisão, stays reachable from its order once
|
||||
# the answered card leaves the board (the proof of #30, 2026-11-17).
|
||||
with db.connect() as c:
|
||||
c.execute('''INSERT INTO dtf_local.order_reviews(order_id,seq,upload_id,kind,width,height,created_by)
|
||||
VALUES(%s,1,%s,'photo',1600,1200,'Revisor')''', (card['id'], readable))
|
||||
client.call('/operator/orders/' + card['id'] + '/proof-answer', {'result': 'ok'}, operator=True)
|
||||
mine = next(o for o in client.call('/operator/board', operator=True)['orders'] if o['id'] == parent['id'])
|
||||
assert [r['kind'] for r in mine['proof_card']['reviews']] == ['photo'], mine['proof_card']
|
||||
view = client.call('/operator/orders/' + card['id'] + '/reviews/' + str(mine['proof_card']['reviews'][0]['id'])
|
||||
+ '/view', operator=True)
|
||||
assert view['url'] and view['kind'] == 'photo', view
|
||||
assert mine['state'] == 'tra' and mine['final_items'] == [0], mine
|
||||
assert mine['proof_ok_at'] and mine['proof_card']['proof_result'] == 'ok', mine
|
||||
with db.connect() as c:
|
||||
final = c.execute('''SELECT note,created_by FROM dtf_local.order_files
|
||||
WHERE order_id=%s AND kind='final' AND active''', (parent['id'],)).fetchone()
|
||||
assert final['created_by'] == 'Prumo' and 'prova' in final['note'].lower(), final
|
||||
print('PASS: Prova OK turns Prumo\'s full file into the parent final and queues it')
|
||||
# Entering the queue by Prova OK is Tiny's "Preparando envio", as a card
|
||||
# moved by hand (orders with a proof skipped it).
|
||||
with db.connect() as c:
|
||||
started = c.execute("SELECT payload FROM dtf_local.outbox WHERE event_key=%s",
|
||||
(f"{parent['id']}:production_started:tiny",)).fetchone()
|
||||
assert started and started['payload']['event'] == 'production_started', started
|
||||
print('PASS: Prova OK turns Prumo\'s full file into the parent final, queues it and tells Tiny')
|
||||
|
||||
# Prova OK while the parent's file is still being generated (#81, 91,5 m,
|
||||
# 2026-11-24): the parent waits in Arte recebida and enters the queue on
|
||||
# its own once the file is ready.
|
||||
readable = upload_bytes(client, artwork(), name='LOCAL-PROOF-LATE.png')
|
||||
parent = paid_order(client, loose_item(readable, copies=1))
|
||||
with db.connect() as c:
|
||||
c.execute("UPDATE dtf_local.orders SET snapshot=jsonb_set(snapshot,'{proof}','true') WHERE id=%s",
|
||||
(parent['id'],))
|
||||
card = client.call('/operator/orders/' + parent['id'] + '/proof-card', {}, operator=True)
|
||||
wait_print(client, parent['id'], 'ready')
|
||||
wait_print(client, card['id'], 'ready')
|
||||
with db.connect() as c:
|
||||
# The parent's file back to "being generated", held by a claim no worker owns.
|
||||
c.execute('''UPDATE dtf_local.print_files SET status='rendering', upload_id=NULL, finished_at=NULL,
|
||||
claimed_at=now(), deadline_at=now()+interval '1 hour', claim_token=%s WHERE order_id=%s''',
|
||||
(str(uuid4()), parent['id']))
|
||||
c.execute("UPDATE dtf_local.orders SET state='rev' WHERE id=%s", (card['id'],))
|
||||
client.call('/operator/orders/' + card['id'] + '/proof-answer', {'result': 'ok'}, operator=True)
|
||||
mine = next(o for o in client.call('/operator/board', operator=True)['orders'] if o['id'] == parent['id'])
|
||||
assert mine['state'] == 'rec' and mine['proof_ok_at'] and not mine['final_items'], mine
|
||||
with db.connect() as c:
|
||||
c.execute("UPDATE dtf_local.print_files SET status='pending', claim_token=NULL WHERE order_id=%s",
|
||||
(parent['id'],))
|
||||
wait_print(client, parent['id'], 'ready')
|
||||
deadline = time.monotonic() + 30
|
||||
while (mine := next(o for o in client.call('/operator/board', operator=True)['orders']
|
||||
if o['id'] == parent['id']))['state'] != 'tra' and time.monotonic() < deadline:
|
||||
time.sleep(1)
|
||||
assert mine['state'] == 'tra' and mine['final_items'] == [0], mine
|
||||
with db.connect() as c:
|
||||
moved = c.execute('''SELECT operator,reason FROM dtf_local.movements
|
||||
WHERE order_id=%s AND to_state='tra' ORDER BY id DESC LIMIT 1''', (parent['id'],)).fetchone()
|
||||
assert (moved['operator'], moved['reason']) == ('Prumo', 'Prova OK'), moved
|
||||
with db.connect() as c:
|
||||
assert c.execute("SELECT 1 FROM dtf_local.outbox WHERE event_key=%s",
|
||||
(f"{parent['id']}:production_started:tiny",)).fetchone()
|
||||
print('PASS: a file finished after Prova OK becomes the final, queues the order and tells Tiny')
|
||||
|
||||
# Cancelled, an order takes its proof card not yet answered with it: left
|
||||
# on the board, the card could still be pulled and printed.
|
||||
readable = upload_bytes(client, artwork(), name='LOCAL-PROOF-CANCEL.png')
|
||||
parent = paid_order(client, loose_item(readable, copies=1))
|
||||
with db.connect() as c:
|
||||
c.execute("UPDATE dtf_local.orders SET snapshot=jsonb_set(snapshot,'{proof}','true') WHERE id=%s",
|
||||
(parent['id'],))
|
||||
card = client.call('/operator/orders/' + parent['id'] + '/proof-card', {}, operator=True)
|
||||
client.call('/operator/orders/' + parent['id'] + '/cancel', {'note': 'cliente desistiu'}, operator=True)
|
||||
with db.connect() as c:
|
||||
gone = c.execute('SELECT cancelled_at, cancel_reason FROM dtf_local.orders WHERE id=%s', (card['id'],)).fetchone()
|
||||
assert gone['cancelled_at'] and 'cliente desistiu' in gone['cancel_reason'], gone
|
||||
print('PASS: cancelling an order cancels its open proof card')
|
||||
|
||||
# A film in parts is approved whole: only some of its parts are refused,
|
||||
# or the others never reach the machine (#114, #128, #130).
|
||||
whole = upload_bytes(client, artwork(), name='LOCAL-PARTS.png')
|
||||
film = paid_order(client, loose_item(whole, copies=1))
|
||||
_, film_row = wait_print(client, film['id'], 'ready')
|
||||
second = upload_bytes(client, artwork(), name='LOCAL-PARTS-P2.png')
|
||||
with db.connect() as c:
|
||||
c.execute('INSERT INTO dtf_local.print_parts(order_id,item_index,part,upload_id) VALUES(%s,0,2,%s)',
|
||||
(film['id'], second))
|
||||
refused = client.call('/operator/orders/' + film['id'] + '/final-files',
|
||||
{'version': version_of(film['id']), 'note': 'só a primeira',
|
||||
'files': [{'item_index': 0, 'upload_id': str(film_row['upload_id'])}]},
|
||||
operator=True, expected=422)
|
||||
assert 'faltam p2' in refused['detail'], refused
|
||||
print('PASS: a film in parts is approved with all its parts or not at all')
|
||||
|
||||
# Reprinting some items (Marcus, 2026-11-26, #105): an order the machine
|
||||
# already printed, back in the queue after one item's final changed, sends
|
||||
# only that item; the pass to Revisão keeps it for the machine's metres and
|
||||
# the choice is then over.
|
||||
first_art = upload_bytes(client, artwork(), name='LOCAL-REPRINT-A.png')
|
||||
second_art = upload_bytes(client, artwork(), name='LOCAL-REPRINT-B.png')
|
||||
two = [loose_item(first_art), loose_item(second_art)]
|
||||
quote = client.call('/quotes', {'request_key': str(uuid4()), 'customer': CUSTOMER,
|
||||
'items': two, 'freight': {'service': 'pickup'}})
|
||||
approval(client, quote, two)
|
||||
reprint = client.call('/orders/dev-paid', {'quote_id': quote['id']})
|
||||
rid = reprint['id']
|
||||
deadline = time.monotonic() + 120
|
||||
while True:
|
||||
board_order = next(o for o in client.call('/operator/board', operator=True)['orders'] if o['id'] == rid)
|
||||
made = {r['item_index']: r for r in board_order['print_files']}
|
||||
if len(made) == 2 and all(r['status'] == 'ready' for r in made.values()):
|
||||
break
|
||||
assert time.monotonic() < deadline, made
|
||||
time.sleep(1)
|
||||
generated = {i: str(made[i]['upload_id']) for i in (0, 1)}
|
||||
v = client.call('/operator/orders/' + rid + '/final-files',
|
||||
{'version': board_order['version'], 'note': 'ok',
|
||||
'files': [{'item_index': i, 'upload_id': generated[i]} for i in (0, 1)]}, operator=True)['version']
|
||||
with db.connect() as c:
|
||||
# The machine took both files on a first print.
|
||||
for i in (0, 1):
|
||||
c.execute('''INSERT INTO dtf_local.hot_parts(order_id,round,seq,item_index,upload_id,name,state)
|
||||
VALUES(%s,1,%s,%s,%s,%s,'consumed')''', (rid, i + 1, i, generated[i], f'item-{i + 1}.png'))
|
||||
# Item 2 is corrected; item 1 keeps its file ("Manter o arquivo atual").
|
||||
corrected = upload_bytes(client, artwork(), name='LOCAL-REPRINT-B2.png', order_id=rid)
|
||||
v = client.call('/operator/orders/' + rid + '/final-files',
|
||||
{'version': v, 'note': 'arte corrigida',
|
||||
'files': [{'item_index': 0, 'upload_id': generated[0]},
|
||||
{'item_index': 1, 'upload_id': corrected}]}, operator=True)['version']
|
||||
board_order = next(o for o in client.call('/operator/board', operator=True)['orders'] if o['id'] == rid)
|
||||
assert board_order['printed_before'] and board_order['print_suggested'] == [1], board_order.get('print_suggested')
|
||||
v = client.call('/operator/orders/' + rid + '/move', {'state': 'tra', 'version': v}, operator=True)['version']
|
||||
|
||||
def print_items():
|
||||
with db.connect() as c:
|
||||
return c.execute('SELECT print_items FROM dtf_local.orders WHERE id=%s', (rid,)).fetchone()['print_items']
|
||||
|
||||
def version():
|
||||
return next(o for o in client.call('/operator/board', operator=True)['orders'] if o['id'] == rid)['version']
|
||||
|
||||
assert print_items() == [1], print_items()
|
||||
# Every item ticked by hand in Arte recebida is a choice too: entering the
|
||||
# queue keeps it, the suggestion does not take its place.
|
||||
client.call('/operator/orders/' + rid + '/move', {'state': 'rec', 'version': v, 'reason': 'teste'}, operator=True)
|
||||
assert client.call('/operator/orders/' + rid + '/print-items', {'items': [0, 1]}, operator=True)['print_items'] == [0, 1]
|
||||
client.call('/operator/orders/' + rid + '/move', {'state': 'tra', 'version': version()}, operator=True)
|
||||
assert print_items() == [0, 1], print_items()
|
||||
# Back to only the corrected item, then pulled onto a machine for real.
|
||||
assert client.call('/operator/orders/' + rid + '/print-items', {'items': [1]}, operator=True)['print_items'] == [1]
|
||||
machine = client.call('/operator/machines', {'name': f'Reprint {uuid4().hex[:6]}', 'products': ['textil']},
|
||||
operator=True)['id']
|
||||
v = client.call('/operator/orders/' + rid + '/move', {'state': 'imp', 'version': version(), 'machine_id': machine},
|
||||
operator=True)['version']
|
||||
with db.connect() as c:
|
||||
queued = c.execute('SELECT item_index,upload_id FROM dtf_local.hot_parts WHERE order_id=%s AND round=2',
|
||||
(rid,)).fetchall()
|
||||
assert [(q['item_index'], str(q['upload_id'])) for q in queued] == [(1, corrected)], queued
|
||||
# Sent to Revisão by mistake before Flexi took the file, and undone: the
|
||||
# file goes back to the folder, alone, and the choice is the same.
|
||||
v = client.call('/operator/orders/' + rid + '/move', {'state': 'rev', 'version': v}, operator=True)['version']
|
||||
assert print_items() is None
|
||||
v = client.call('/operator/orders/' + rid + '/move', {'state': 'imp', 'version': v, 'reason': 'engano'},
|
||||
operator=True)['version']
|
||||
assert print_items() == [1], print_items()
|
||||
with db.connect() as c:
|
||||
again = c.execute('SELECT item_index,upload_id,state FROM dtf_local.hot_parts WHERE order_id=%s AND round=3',
|
||||
(rid,)).fetchall()
|
||||
assert [(r['item_index'], str(r['upload_id']), r['state']) for r in again] == [(1, corrected, 'queued')], again
|
||||
c.execute("UPDATE dtf_local.hot_parts SET state='consumed' WHERE order_id=%s AND round=3", (rid,))
|
||||
# Flexi took it: undoing a later pass to Revisão writes nothing again.
|
||||
v = client.call('/operator/orders/' + rid + '/move', {'state': 'rev', 'version': v}, operator=True)['version']
|
||||
v = client.call('/operator/orders/' + rid + '/move', {'state': 'imp', 'version': v, 'reason': 'engano'},
|
||||
operator=True)['version']
|
||||
with db.connect() as c:
|
||||
assert not c.execute('SELECT 1 FROM dtf_local.hot_parts WHERE order_id=%s AND round>3', (rid,)).fetchone()
|
||||
client.call('/operator/orders/' + rid + '/move', {'state': 'rev', 'version': v}, operator=True)
|
||||
from app import machine_log
|
||||
with db.connect() as c:
|
||||
moved = c.execute("SELECT items FROM dtf_local.movements WHERE order_id=%s AND to_state='rev' "
|
||||
"ORDER BY id DESC LIMIT 1", (rid,)).fetchone()
|
||||
item = c.execute('SELECT snapshot FROM dtf_local.orders WHERE id=%s', (rid,)).fetchone()['snapshot']['items'][1]
|
||||
metres = machine_log.printed_since(c, machine, None)
|
||||
assert moved['items'] == [1] and print_items() is None, moved
|
||||
# Three passes to Revisão, two of them undone: item 2's film, once.
|
||||
expected = Decimal(str(item['metres'] if item.get('metres') is not None else item.get('billed_metres') or 0))
|
||||
assert metres == expected, (metres, expected)
|
||||
# Chosen by hand: every item, or some; never an item the order lacks.
|
||||
with db.connect() as c:
|
||||
c.execute("UPDATE dtf_local.orders SET state='rec' WHERE id=%s", (rid,))
|
||||
assert client.call('/operator/orders/' + rid + '/print-items', {'items': [1, 0, 1]}, operator=True)['print_items'] == [0, 1]
|
||||
assert client.call('/operator/orders/' + rid + '/print-items', {'items': [0]}, operator=True)['print_items'] == [0]
|
||||
client.call('/operator/orders/' + rid + '/print-items', {'items': [5]}, operator=True, expected=422)
|
||||
print('PASS: a reprint sends only the items chosen, keeps an all-items choice, and an undone pass to Revisão '
|
||||
'neither writes again what Flexi took nor counts the film twice')
|
||||
|
||||
# A CDR cannot be decoded by the worker. The designer prepares the full
|
||||
# parent PNG, then the worker automatically cuts the child's proof from it.
|
||||
|
||||
@@ -27,6 +27,7 @@ def run():
|
||||
quote, payment_id = uuid4(), str(900_000_000 + uuid4().int % 99_999_999)
|
||||
approved = {'customer': {'mail': 'reconcile@example.test'}, 'items': [], 'total_cents': 1490}
|
||||
order_id = None
|
||||
extra = []
|
||||
try:
|
||||
with db.connect() as c:
|
||||
c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved,approved_at)
|
||||
@@ -55,7 +56,36 @@ def run():
|
||||
asked = paid.asked
|
||||
assert payments.reconcile(db.connect, paid, quote_id=quote) == [] and paid.asked == asked
|
||||
print('PASS: an approved payment is found by asking the provider; a short one is refused; each applies once')
|
||||
|
||||
# Approved after the quote's 24 h: a payment started in time (a PIX paid
|
||||
# in its last minutes, a card approved after review) is the order; one
|
||||
# started after the deadline is refused.
|
||||
for started, expected in (("now()-interval '3 hours'", 'order '), ("now()-interval '1 hour'", 'refused: quote expired')):
|
||||
late, late_payment = uuid4(), str(800_000_000 + uuid4().int % 99_999_999)
|
||||
extra.append((late, late_payment))
|
||||
with db.connect() as c:
|
||||
c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved,approved_at)
|
||||
VALUES(%s,%s,%s,'reconcile-fixture',%s,%s,now()-interval '26 hours')''',
|
||||
(late, uuid4(), uuid4(), Jsonb({'customer': approved['customer'], 'items': []}), Jsonb(approved)))
|
||||
c.execute(f'''INSERT INTO dtf_local.payment_intents(id,quote_id,provider,provider_payment_id,method,status,
|
||||
amount_cents,response,created_at) VALUES(%s,%s,'mercadopago',%s,'card','pending',1490,'{{}}',{started})''',
|
||||
(uuid4(), late, late_payment))
|
||||
provider = Provider({'id': late_payment, 'status': 'approved', 'currency_id': 'BRL',
|
||||
'transaction_amount': 14.9, 'external_reference': str(late)})
|
||||
outcomes = payments.reconcile(db.connect, provider, quote_id=late)
|
||||
assert len(outcomes) == 1 and outcomes[0].startswith(expected), (started, outcomes)
|
||||
print('PASS: a payment started within the 24 h is the order whenever approved; one started later is refused')
|
||||
finally:
|
||||
for late, late_payment in extra:
|
||||
with db.connect() as c:
|
||||
for row in c.execute('SELECT id FROM dtf_local.orders WHERE quote_id=%s', (late,)).fetchall():
|
||||
c.execute("DELETE FROM dtf_local.outbox WHERE event_key LIKE %s", (f"{row['id']}:%",))
|
||||
c.execute('DELETE FROM dtf_local.print_files WHERE order_id=%s', (row['id'],))
|
||||
c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (row['id'],))
|
||||
c.execute("DELETE FROM dtf_local.payment_events WHERE provider='mercadopago' AND event_id LIKE %s",
|
||||
(f'{late_payment}:%',))
|
||||
c.execute('DELETE FROM dtf_local.payment_intents WHERE quote_id=%s', (late,))
|
||||
c.execute('DELETE FROM dtf_local.quotes WHERE id=%s', (late,))
|
||||
with db.connect() as c:
|
||||
if order_id:
|
||||
c.execute("DELETE FROM dtf_local.outbox WHERE event_key LIKE %s", (f'{order_id}:%',))
|
||||
|
||||
@@ -18,6 +18,13 @@ def run():
|
||||
with connect() as c:
|
||||
c.execute('INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,complete,expires_at) VALUES(%s,%s,%s,%s,%s,%s,true,%s)',
|
||||
(uid,uuid4(),'LOCAL-RETENTION-TEST.txt',len(b'LOCAL RETENTION TEST'),key,upload,expiry))
|
||||
# A file outside the storage policy's prefixes cannot be deleted: it must
|
||||
# not stop the cleanup of the others, and is tried again a day later.
|
||||
denied=uuid4()
|
||||
with connect() as c:
|
||||
c.execute('INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,complete,expires_at,created_at) VALUES(%s,%s,%s,1,%s,%s,true,%s,%s)',
|
||||
(denied,uuid4(),'LOCAL-RETENTION-DENIED.txt',f'retention-denied/{denied}','',
|
||||
datetime.now(timezone.utc)-timedelta(days=1),datetime.now(timezone.utc)-timedelta(days=400)))
|
||||
# Cleanup takes 50 at a time, oldest first: the suites before this one
|
||||
# leave their own expired files ahead of the fixture.
|
||||
for _ in range(100):
|
||||
@@ -27,6 +34,10 @@ def run():
|
||||
with connect() as c:
|
||||
assert c.execute('SELECT purged_at FROM dtf_local.uploads WHERE id=%s',(ids[0],)).fetchone()['purged_at']
|
||||
assert not c.execute('SELECT purged_at FROM dtf_local.uploads WHERE id=%s',(ids[1],)).fetchone()['purged_at']
|
||||
with connect() as c:
|
||||
row=c.execute('SELECT purged_at,expires_at>now() AS later FROM dtf_local.uploads WHERE id=%s',(denied,)).fetchone()
|
||||
assert not row['purged_at'] and row['later'],row
|
||||
c.execute('DELETE FROM dtf_local.uploads WHERE id=%s',(denied,))
|
||||
try:storage.size(f'originals/{ids[0]}');raise AssertionError('Expired bytes still exist')
|
||||
except ClientError as exc:assert exc.response['ResponseMetadata']['HTTPStatusCode']==404
|
||||
assert storage.size(f'originals/{ids[1]}')==len(b'LOCAL RETENTION TEST')
|
||||
|
||||
@@ -13,6 +13,7 @@ from uuid import uuid4
|
||||
from PIL import Image, ImageDraw
|
||||
|
||||
from app import tiny
|
||||
from app.adapters import FakeTiny
|
||||
from app.core import db
|
||||
from tests.print_file_test import artwork
|
||||
from tests.smoke_test import Client, item_spec, upload_bytes
|
||||
@@ -20,6 +21,7 @@ from tests.smoke_test import Client, item_spec, upload_bytes
|
||||
PASSWORD = 'senha-de-teste-123'
|
||||
UV = 'uv'
|
||||
PREMIUM = 'premium'
|
||||
REDESIGN = 'redesenho'
|
||||
|
||||
|
||||
def premium_sheet():
|
||||
@@ -38,12 +40,13 @@ def quote(client, item, mail, expected=200):
|
||||
|
||||
|
||||
def arts_item(upload_id, arts):
|
||||
"""One loose-art item with `arts` sources of 10 x 10 cm, one metre long."""
|
||||
sources = [{'upload_id': upload_id, 'kind': 'artwork', 'width_cm': 10, 'length_cm': 10,
|
||||
"""One loose-art item with `arts` sources of 10 x 5 cm (artwork() is 2:1),
|
||||
one every 10 cm."""
|
||||
sources = [{'upload_id': upload_id, 'kind': 'artwork', 'width_cm': 10, 'length_cm': 5,
|
||||
'copies': 1, 'rotation_degrees': 0, 'mirrored': False,
|
||||
'measurement': 'customer'} for _ in range(arts)]
|
||||
placements = [{'source_index': index, 'copy_index': 0, 'x_cm': 0, 'y_cm': index * 10,
|
||||
'width_cm': 10, 'length_cm': 10, 'rotation_degrees': 0, 'mirrored': False}
|
||||
'width_cm': 10, 'length_cm': 5, 'rotation_degrees': 0, 'mirrored': False}
|
||||
for index in range(arts)]
|
||||
return {'mode': 'avulsa', 'metres': '1', 'grade': 90, 'uploads': [upload_id] * arts,
|
||||
'production': {'version': 3, 'film_width_cm': 57, 'height_cm': arts * 10,
|
||||
@@ -61,11 +64,11 @@ def run():
|
||||
manager.call('/session')
|
||||
manager.call('/operator/me', operator=True)
|
||||
manager = manager.operator_client
|
||||
prices, user, treatment_enabled = [], None, None
|
||||
prices, user, treatment_enabled, redesign_enabled = [], None, None, None
|
||||
try:
|
||||
products = manager.call('/operator/site/products')['products']
|
||||
assert {product['id'] for product in products} == \
|
||||
{'file', 'avulsa', 'uvfile', 'uv', 'premium', 'tratamento'}
|
||||
{'file', 'avulsa', 'uvfile', 'uv', 'premium', 'tratamento', REDESIGN}
|
||||
assert all(product['unit'] in ('metro', 'pedido', 'arte') and product['title'] for product in products)
|
||||
|
||||
# Front 3: Premium is listed and starts switched off (Marcus, 2026-11-10).
|
||||
@@ -74,7 +77,7 @@ def run():
|
||||
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')),
|
||||
client, premium_sheet(), name='LOCAL-SITE-PREMIUM.png'), aspect=3),
|
||||
'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
|
||||
@@ -128,9 +131,65 @@ def run():
|
||||
{'produto': {'id': 105}, 'quantidade': 3, 'valorUnitario': 9.9,
|
||||
'infoAdicional': 'Ajuste Fino · 3 artes · +24 h'}], pedido['itens']
|
||||
|
||||
# Front 1b: Ajuste Fino Redesenho, one price per art, never a band.
|
||||
redesign = next(product for product in products if product['id'] == REDESIGN)
|
||||
redesign_enabled = redesign['enabled']
|
||||
assert redesign['enabled'] is False, redesign
|
||||
assert redesign['title'] == 'Ajuste Fino Redesenho', redesign
|
||||
assert redesign['unit'] == 'arte', redesign
|
||||
manager.call(f'/operator/site/products/{REDESIGN}', {'enabled': True})
|
||||
# Enabled but still unpriced: the Site hides it and the server refuses it.
|
||||
refused = client.call('/quotes', {'request_key': str(uuid4()), 'customer': customer,
|
||||
'items': [arts], 'redesign': [[0, 0]], 'freight': {'service': 'pickup'}}, expected=422)
|
||||
assert refused['detail'] == 'O Redesenho não está disponível agora.', refused
|
||||
banded = manager.call(f'/operator/site/products/{REDESIGN}/prices', {
|
||||
'unit_cents': 2990,
|
||||
'bands': [{'from_metres': '10', 'unit_cents': 690}]}, expected=422)
|
||||
assert 'faixas' in banded['detail'], banded
|
||||
made = manager.call(f'/operator/site/products/{REDESIGN}/prices', {'unit_cents': 2990})
|
||||
prices.append(made['id'])
|
||||
assert client.call('/session')['redesign_cents'] == 2990
|
||||
two = client.call('/quotes', {'request_key': str(uuid4()), 'customer': customer,
|
||||
'items': [arts], 'redesign': [[0, 0], [0, 1]], 'freight': {'service': 'pickup'}})
|
||||
assert two['status'] == 'approved', two
|
||||
redesenho = client.call('/quotes/' + two['id'])['approved']
|
||||
assert redesenho['redesign'] == {'cents': 5980, 'hours': 48, 'arts': 2,
|
||||
'unit_cents': 2990}, redesenho
|
||||
assert redesenho['total_cents'] == redesenho['items'][0]['total_cents'] + 5980, redesenho
|
||||
# Basic and Redesenho on different arts: each priced on its own service,
|
||||
# and the basic band counts only the basic arts.
|
||||
mixed = client.call('/quotes', {'request_key': str(uuid4()), 'customer': customer,
|
||||
'items': [arts], 'treatment': [[0, 0], [0, 1], [0, 2]],
|
||||
'redesign': [[0, 3], [0, 4]], 'freight': {'service': 'pickup'}})
|
||||
mixed = client.call('/quotes/' + mixed['id'])['approved']
|
||||
assert mixed['treatment'] == {'cents': 2970, 'hours': 24, 'arts': 3,
|
||||
'unit_cents': 990}, mixed
|
||||
assert mixed['redesign'] == {'cents': 5980, 'hours': 48, 'arts': 2,
|
||||
'unit_cents': 2990}, mixed
|
||||
assert mixed['total_cents'] == mixed['items'][0]['total_cents'] + 2970 + 5980, mixed
|
||||
# Tiny: the line resolves DTFIMP.AJF.RED through the fake catalogue.
|
||||
fake = FakeTiny()
|
||||
pedido = tiny.order_payload({'order_id': two['id'], 'order': redesenho,
|
||||
'number': 2, 'payment': {}, 'origin': 'site'}, 777,
|
||||
date(2026, 11, 12), product_id=fake.product_id)
|
||||
red_code = fake.product_id('DTFIMP.AJF.RED')
|
||||
assert [line for line in pedido['itens'] if line['produto']['id'] == red_code] == [
|
||||
{'produto': {'id': red_code}, 'quantidade': 2, 'valorUnitario': 29.9,
|
||||
'infoAdicional': 'Ajuste Fino Redesenho · 2 artes · +48 h'}], pedido['itens']
|
||||
# One service per art: a pair in both lists is refused by the model.
|
||||
both = client.call('/quotes', {'request_key': str(uuid4()), 'customer': customer,
|
||||
'items': [arts], 'treatment': [[0, 0]], 'redesign': [[0, 0]],
|
||||
'freight': {'service': 'pickup'}}, expected=422)
|
||||
assert 'Escolha Ajuste Fino ou Redesenho' in str(both['detail']), both
|
||||
# Switched off again, a chosen Redesenho is refused.
|
||||
manager.call(f'/operator/site/products/{REDESIGN}', {'enabled': False})
|
||||
refused = client.call('/quotes', {'request_key': str(uuid4()), 'customer': customer,
|
||||
'items': [arts], 'redesign': [[0, 0]], 'freight': {'service': 'pickup'}}, expected=422)
|
||||
assert refused['detail'] == 'O Redesenho não está disponível agora.', refused
|
||||
|
||||
manager.call(f'/operator/site/products/{UV}', {'enabled': True})
|
||||
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, aspect=2), 'quality_status': 'warning', 'quality_acknowledged': True}
|
||||
before = client.call('/session')['products'][UV]['unit_cents']
|
||||
|
||||
# Switched off: the Site sees it off and the server refuses a new quote.
|
||||
@@ -214,6 +273,7 @@ def run():
|
||||
staff.call(f'/operator/site/prices/{made["id"]}/cancel', {}, expected=403)
|
||||
print('PASS: the Site tab switches a product off and refuses quotes, lists Premium switched off'
|
||||
' and accepts it once enabled, prices Ajuste Fino per art with its band,'
|
||||
' prices Redesenho per art without bands and sends it to Tiny,'
|
||||
' schedules and cancels prices, charges the new price, and refuses a non-manage profile')
|
||||
finally:
|
||||
with db.connect() as c:
|
||||
@@ -221,6 +281,9 @@ def run():
|
||||
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=false WHERE id=%s", (PREMIUM,))
|
||||
if redesign_enabled is not None:
|
||||
c.execute("UPDATE dtf_local.products SET enabled=%s WHERE id=%s",
|
||||
(redesign_enabled, REDESIGN))
|
||||
if treatment_enabled is not None:
|
||||
try:
|
||||
manager.call('/operator/site/products/tratamento', {'enabled': treatment_enabled})
|
||||
|
||||
@@ -48,6 +48,13 @@ def run():
|
||||
entry = next(row for row in published if row['id'] == 'sala')
|
||||
assert entry['product'] == 'file'
|
||||
assert entry['captions'] == '/api/site/videos/sala/captions'
|
||||
# One floating video per product: a second one is refused before any
|
||||
# copy, naming the video that holds the product (DTF-WEB-G).
|
||||
refused = operator.call('/operator/site-videos/png', {'upload_id': video,
|
||||
'product': 'file', 'enabled': True}, expected=409)
|
||||
assert 'A sala às 3 da manhã' in refused['detail'], refused
|
||||
with db.connect() as c:
|
||||
assert not c.execute("SELECT 1 FROM dtf_local.site_videos WHERE id='png'").fetchone()
|
||||
with urlopen(entry['src'], timeout=30) as response:
|
||||
assert response.read() == VIDEO
|
||||
with urlopen(Request(BASE + entry['captions'], headers=with_host()), timeout=30) as response:
|
||||
|
||||
@@ -57,6 +57,8 @@ class Client:
|
||||
self.operator_client=Client()
|
||||
self.operator_client.call('/operator/login',{'email':os.environ.get('OPERATOR_EMAIL','operator@example.test'),'password':os.environ.get('OPERATOR_PASSWORD','local-operator-only')})
|
||||
return self.operator_client.call(path,body,expected=expected,method=method)
|
||||
reset=False
|
||||
for attempt in range(20):
|
||||
request=Request(BASE+'/api'+path,data=None if body is None else json.dumps(body).encode(),
|
||||
headers=headers,method=method)
|
||||
try:
|
||||
@@ -64,8 +66,21 @@ class Client:
|
||||
assert response.status==expected,(path,response.status,expected)
|
||||
return json.load(response)
|
||||
except HTTPError as exc:
|
||||
if exc.code!=expected:raise AssertionError((path,exc.code,exc.read().decode())) from exc
|
||||
return json.load(exc)
|
||||
if exc.code==expected:return json.load(exc)
|
||||
text=exc.read().decode()
|
||||
# The gateway's own limit (nginx, 20 r/s per address, burst 100) is
|
||||
# an HTML page, not the API's JSON: a fast suite waits for it.
|
||||
if exc.code==429 and text.lstrip().startswith('<html') and attempt<19:
|
||||
time.sleep(1);continue
|
||||
# The API allows 60 sign-ins per address in 15 min (app/core/auth.py
|
||||
# throttle), and the whole suite signs in from one address: a test
|
||||
# that did not ask for the limit starts the count again.
|
||||
if exc.code==429 and path=='/operator/login' and not reset:
|
||||
from app.core import db
|
||||
with db.connect() as c:
|
||||
c.execute('DELETE FROM dtf_local.login_attempts')
|
||||
reset=True;continue
|
||||
raise AssertionError((path,exc.code,text)) from exc
|
||||
|
||||
def register(client, customer, password):
|
||||
"""Create an account as the Site does: with e-mail on, the code sent to the
|
||||
@@ -125,11 +140,15 @@ def review_photo(client, order_id):
|
||||
wait_scan(client,uid,operator=True)
|
||||
return client.call('/operator/orders/'+order_id+'/reviews',{'upload_id':uid},operator=True)
|
||||
|
||||
def item_spec(mode, metres, grade, uid):
|
||||
def item_spec(mode, metres, grade, uid, aspect=None):
|
||||
"""One file across the film, `metres` long. `aspect` (width / length) for
|
||||
a real image: the piece then keeps the file's proportions, as the server
|
||||
checks, inside the same billed length."""
|
||||
film_width=27 if mode in ('uvfile','uv') else 57
|
||||
length_cm=float(metres)*100
|
||||
height_cm=float(metres)*100
|
||||
length_cm=round(film_width/aspect,4) if aspect else height_cm
|
||||
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':height_cm,
|
||||
'sources':[{'upload_id':uid,
|
||||
'kind':'sheet' if mode in ('file','uvfile','premium') else 'artwork',
|
||||
'width_cm':film_width,'length_cm':length_cm,'copies':1,
|
||||
@@ -181,12 +200,16 @@ def run():
|
||||
print('PASS: multipart resume, incomplete rejection, immutable completion, ownership, private/downloaded bytes')
|
||||
|
||||
# Above QUOTE_AUTO_MAX_METRES (50 m by default), so a person reviews it.
|
||||
items=[item_spec(m,'13',90,uid) for m in ('file','avulsa','uvfile','uv')]
|
||||
# One order, one machine (Marcus, 2026-11-26): the two textile products;
|
||||
# UV goes in an order of its own.
|
||||
items=[item_spec(m,'26',90,uid) for m in ('file','avulsa')]
|
||||
draft={'request_key':str(uuid4()),'customer':{'cnpj':'11222333000181','zap':'11999999999','mail':'local-smoke@example.test'},
|
||||
'items':items,'freight':{'service':'mock-standard','postal_code':'14400000'},
|
||||
'destination':{'recipient':'Local Smoke Ltda','street':'Rua de Teste','number':'100',
|
||||
'district':'Centro','city':'Franca','state':'SP','postal_code':'14400000'}}
|
||||
client.call('/quotes',{**draft,'total_cents':1},expected=422)
|
||||
mixed_cart=client.call('/quotes',{**draft,'items':[items[0],item_spec('uvfile','13',90,uid)]},expected=422)['detail']
|
||||
assert any('outra máquina' in str(e.get('msg','')) for e in mixed_cart), mixed_cart
|
||||
# Freight quoted by CEP alone cannot ship: the address is required, must be
|
||||
# the quoted CEP, and a pickup order takes none.
|
||||
client.call('/quotes',{**draft,'destination':None},expected=422)
|
||||
@@ -222,18 +245,19 @@ def run():
|
||||
corrected=[{**items[0],'metres':'1.01','grade':0},*items[1:]]
|
||||
approved=client.call('/operator/quotes/'+qid+'/approve',{'items':corrected},operator=True)
|
||||
assert approved['items'][0]['total_cents']==2189 and approved['items'][0]['grade']==0
|
||||
assert [i['unit_cents'] for i in approved['items'][1:]]==[2190,7990,8990]
|
||||
assert approved['total_cents']==2189+28470+103870+116870+int(os.environ.get('MOCK_FREIGHT_CENTS','1500'))
|
||||
assert [i['unit_cents'] for i in approved['items'][1:]]==[2190]
|
||||
assert approved['total_cents']==2189+56940+int(os.environ.get('MOCK_FREIGHT_CENTS','1500'))
|
||||
assert approved['destination']=={**draft['destination'],'complement':''}
|
||||
client.call('/operator/quotes/'+qid+'/approve',{'items':items},operator=True,expected=409)
|
||||
assert not client.call('/quotes/'+qid)['auto_approved']
|
||||
# A cart the Site priced is approved at once and can be paid straight away,
|
||||
# at the server's own prices; no operator can then change it.
|
||||
# The server works the grade out from the file: this PNG is 6059 px across
|
||||
# 57 cm, 270 DPI, which is grade 100 under the 200 DPI clean threshold.
|
||||
png=b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR'+(6059).to_bytes(4,'big')+(2000).to_bytes(4,'big')+b'\x08\x06\x00\x00\x00'+b'\x00'*4
|
||||
# 57 cm, 270 DPI, which is grade 100 under the 200 DPI clean threshold;
|
||||
# 29232 px long, the 275 cm it is laid out at (the server checks it).
|
||||
png=b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR'+(6059).to_bytes(4,'big')+(29232).to_bytes(4,'big')+b'\x08\x06\x00\x00\x00'+b'\x00'*4
|
||||
graded=upload_bytes(client,png,name='arte-270dpi.png')
|
||||
low_png=b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR'+(3366).to_bytes(4,'big')+(2000).to_bytes(4,'big')+b'\x08\x06\x00\x00\x00'+b'\x00'*4
|
||||
low_png=b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR'+(3366).to_bytes(4,'big')+(16240).to_bytes(4,'big')+b'\x08\x06\x00\x00\x00'+b'\x00'*4
|
||||
low=upload_bytes(client,low_png,name='arte-150dpi.png')
|
||||
small={**draft,'request_key':str(uuid4()),'items':[item_spec('avulsa','2.75',90,graded)]}
|
||||
auto=client.call('/quotes',small)
|
||||
@@ -264,7 +288,11 @@ def run():
|
||||
assert mixed_item['stroke_choice']=='client_c3', mixed_item
|
||||
# Loose art split by stroke (item 17): each sheet is an item, and the pair
|
||||
# has one 1 m minimum, on its first sheet.
|
||||
part=lambda metres,n,mode='avulsa':{**item_spec(mode,metres,90,graded),'split':{'group':'f0','part':n,'of':2}}
|
||||
# Each sheet's own file, 6059 px across 57 cm, as long as the sheet.
|
||||
header=lambda rows:b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR'+(6059).to_bytes(4,'big')+rows.to_bytes(4,'big')+b'\x08\x06\x00\x00\x00'+b'\x00'*4
|
||||
sheet_files={'0.3':upload_bytes(client,header(3189),name='folha-30.png'),
|
||||
'0.15':upload_bytes(client,header(1594),name='folha-15.png')}
|
||||
part=lambda metres,n,mode='avulsa':{**item_spec(mode,metres,90,sheet_files[metres]),'split':{'group':'f0','part':n,'of':2}}
|
||||
split={**small,'request_key':str(uuid4()),'items':[part('0.3',1),part('0.15',2)]}
|
||||
client.call('/quotes',{**split,'items':split['items'][:1]},expected=422)
|
||||
client.call('/quotes',{**split,'items':[part('0.3',1),part('0.15',1)]},expected=422)
|
||||
@@ -316,7 +344,7 @@ def run():
|
||||
if state=='tra':
|
||||
# The queue takes approved final files only.
|
||||
client.call('/operator/orders/'+oid+'/move',{'state':'tra','version':version},operator=True,expected=409)
|
||||
files=[{'item_index':i,'upload_id':upload_bytes(client,final_png_bytes(str(i)),name=f'LOCAL-FINAL-{i}.png',order_id=oid)} for i in range(4)]
|
||||
files=[{'item_index':i,'upload_id':upload_bytes(client,final_png_bytes(str(i)),name=f'LOCAL-FINAL-{i}.png',order_id=oid)} for i in range(len(items))]
|
||||
result=client.call('/operator/orders/'+oid+'/final-files',{'version':version,'files':files,'note':'Local test manual final-file approval'},operator=True)
|
||||
version=result['version']
|
||||
body={'state':state,'version':version,'reason':'Local test correction' if state=='cor' else ''}
|
||||
|
||||
@@ -84,11 +84,20 @@ def run():
|
||||
identities = [operator_identity(emails['expedicao']), operator_identity(emails['vendedor'])]
|
||||
made_orders, made_quotes = [], []
|
||||
# A code of its own, so a brand someone saved in Estampas/ is never touched.
|
||||
stamp_code = 'T' + tag
|
||||
# With a dot, as Dropstar's own codes (NX.226).
|
||||
stamp_code = 'T.' + tag
|
||||
try:
|
||||
# The seller is a Tiny seller too (Marcus, 2026-11-17): the fake Tiny
|
||||
# lists two, and a Venda this user assembles carries the one chosen.
|
||||
sellers = su.call('/operator/tiny/sellers', operator=True)
|
||||
assert sellers == [{'id': 2001, 'name': 'Lais'}, {'id': 2002, 'name': 'Marcus'}], sellers
|
||||
for role, email in emails.items():
|
||||
su.call('/operator/users', {'name': role.title(), 'email': email, 'role': role,
|
||||
'password': PASSWORD}, operator=True)
|
||||
su.call('/operator/users', {'name': role.title(), 'email': email, 'role': role, 'password': PASSWORD,
|
||||
**({'tiny_seller': sellers[0]} if role == 'vendedor' else {})},
|
||||
operator=True)
|
||||
listed = {u['email']: u for u in su.call('/operator/users', operator=True)['users']}
|
||||
assert listed[emails['vendedor']]['tiny_seller'] == sellers[0], listed[emails['vendedor']]
|
||||
assert listed[emails['gestao']]['tiny_seller'] is None, listed[emails['gestao']]
|
||||
# The new profile creates through the users API and reads the table.
|
||||
shipping = signed_in(emails['expedicao'])
|
||||
seller = signed_in(emails['vendedor'])
|
||||
@@ -175,6 +184,8 @@ def run():
|
||||
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')
|
||||
assert order_venda['snapshot']['seller'] == {'id': 2001, 'name': 'Lais'}, order_venda['snapshot'].get('seller')
|
||||
assert 'seller' not in order_interno['snapshot'], order_interno['snapshot'].get('seller')
|
||||
payment = order_venda['payment']
|
||||
assert (payment['provider'], payment['method'], payment['status']) == ('manual', 'faturado', 'paid'), payment
|
||||
with db.connect() as c:
|
||||
|
||||
@@ -8,10 +8,21 @@ extra. app/cart_pricing.price_items must return exactly the same list.
|
||||
import unittest
|
||||
from decimal import Decimal
|
||||
|
||||
from uuid import uuid4
|
||||
|
||||
from app import catalog
|
||||
from app.cart_pricing import price_items, treatment_price
|
||||
from app.cart_pricing import (designer_hours, needs_designer, price_items,
|
||||
redesign_price, treatment_price)
|
||||
from app.core import pricing
|
||||
|
||||
try:
|
||||
from pydantic import ValidationError
|
||||
from app.core.models import QuoteRequest
|
||||
except ImportError:
|
||||
# The validate job runs this file on the host, without the runtime image's
|
||||
# dependencies; the runtime suites exercise the model there.
|
||||
QuoteRequest = ValidationError = None
|
||||
|
||||
|
||||
BASE = {'file': 1990, 'avulsa': 2190, 'uvfile': 7990, 'uv': 8990}
|
||||
UV_BANDS = [{'from_metres': '5', 'unit_cents': 8000},
|
||||
@@ -24,6 +35,7 @@ def catalog_now(bands=None, prices=None):
|
||||
now = {mode: {'enabled': True, 'unit_cents': prices[mode],
|
||||
'bands': bands.get(mode, [])} for mode in BASE}
|
||||
now['tratamento'] = {'enabled': True, 'unit_cents': 1000, 'bands': []}
|
||||
now['redesenho'] = {'enabled': True, 'unit_cents': 2990, 'bands': []}
|
||||
return now
|
||||
|
||||
|
||||
@@ -153,8 +165,10 @@ class CartPricingCharacterizationTest(unittest.TestCase):
|
||||
split = priced('split-under-one-metre')
|
||||
self.assertEqual([(p['billed_metres'], p['total_cents']) for p in split],
|
||||
[('0.8', 1752), ('0.2', 438)])
|
||||
# A float's noise past 2,80 m is inside the 8 mm grace (Marcus,
|
||||
# 2026-11-27): billed 2,80 m at the band from 2,8 m, no longer 2,90 m.
|
||||
floating = priced('band-floating-metres')[0]
|
||||
self.assertEqual((floating['billed_metres'], floating['total_cents']), ('2.9', 24650))
|
||||
self.assertEqual((floating['billed_metres'], floating['total_cents']), ('2.8', 23800))
|
||||
|
||||
def test_ajuste_fino_is_per_art_with_the_band(self):
|
||||
# Front 1a: 1 to 9 arts at R$ 9,90, from 10 at R$ 6,90, all arts charged
|
||||
@@ -171,6 +185,67 @@ class CartPricingCharacterizationTest(unittest.TestCase):
|
||||
self.assertEqual(treatment_price(items, [], offer), {})
|
||||
self.assertEqual(treatment_price(items, True, {**offer, 'enabled': False}), {})
|
||||
|
||||
def test_redesenho_is_per_art_never_a_band(self):
|
||||
# Front 1b: R$ 29,90 per art, and the basic batch band never applies.
|
||||
offer = {'enabled': True, 'unit_cents': 2990,
|
||||
'bands': [{'from_metres': '10', 'unit_cents': 690}]}
|
||||
items = [item('file', '1', uid='u1'), item('file', '1', uid='u2')]
|
||||
self.assertEqual(redesign_price(items, [[0, 0], [1, 0]], offer),
|
||||
{'cents': 5980, 'hours': 48, 'arts': 2, 'unit_cents': 2990})
|
||||
self.assertEqual(redesign_price(items, [], offer), {})
|
||||
self.assertEqual(redesign_price(items, [[0, 0]], {**offer, 'enabled': False}), {})
|
||||
self.assertEqual(redesign_price(items, [[0, 0]], {**offer, 'unit_cents': 0}), {})
|
||||
|
||||
def test_the_basic_band_counts_only_basic_arts(self):
|
||||
offer = {'enabled': True, 'unit_cents': 990,
|
||||
'bands': [{'from_metres': '10', 'unit_cents': 690}]}
|
||||
items = [item('avulsa', '1', uid=f'u{index}') for index in range(10)]
|
||||
basic = [[index, 0] for index in range(9)]
|
||||
self.assertEqual(treatment_price(items, basic, offer),
|
||||
{'cents': 8910, 'hours': 24, 'arts': 9, 'unit_cents': 990})
|
||||
redesign = redesign_price(items, [[9, 0]], offer={**offer, 'unit_cents': 2990})
|
||||
self.assertEqual(redesign['arts'], 1)
|
||||
|
||||
def test_designer_helpers_read_both_services(self):
|
||||
self.assertEqual(designer_hours({}), 0)
|
||||
self.assertEqual(designer_hours({'treatment': {'cents': 990}}), 24)
|
||||
self.assertEqual(designer_hours({'redesign': {'cents': 2990}}), 48)
|
||||
self.assertEqual(designer_hours({'treatment': {'cents': 990},
|
||||
'redesign': {'cents': 2990}}), 48)
|
||||
self.assertFalse(needs_designer({}))
|
||||
self.assertTrue(needs_designer({'treatment': {'cents': 990}}))
|
||||
self.assertTrue(needs_designer({'redesign': {'cents': 2990}}))
|
||||
|
||||
@unittest.skipUnless(QuoteRequest, 'pydantic is only in the runtime image')
|
||||
def test_a_pair_cannot_be_basic_and_redesenho(self):
|
||||
def quote(treatment=None, redesign=None, items=1):
|
||||
entries = []
|
||||
for _ in range(items):
|
||||
uid = str(uuid4())
|
||||
data = item('avulsa', '1', uid=uid)
|
||||
data['production']['placements'] = [{
|
||||
'source_index': 0, 'copy_index': 0, 'x_cm': 0, 'y_cm': 0,
|
||||
'width_cm': 10, 'length_cm': 10, 'rotation_degrees': 0, 'mirrored': False}]
|
||||
entries.append(data)
|
||||
payload = {'request_key': str(uuid4()),
|
||||
'customer': {'cnpj': '11222333000181', 'zap': '11999999999',
|
||||
'mail': 'arte@example.test'},
|
||||
'items': entries, 'freight': {'service': 'pickup'}}
|
||||
if treatment is not None:
|
||||
payload['treatment'] = treatment
|
||||
if redesign is not None:
|
||||
payload['redesign'] = redesign
|
||||
return payload
|
||||
QuoteRequest.model_validate(quote(treatment=[[0, 0]], redesign=[[1, 0]], items=2))
|
||||
with self.assertRaises(ValidationError):
|
||||
QuoteRequest.model_validate(quote(treatment=[[0, 0]], redesign=[[0, 0]]))
|
||||
with self.assertRaises(ValidationError):
|
||||
QuoteRequest.model_validate(quote(treatment=True, redesign=[[0, 0]]))
|
||||
with self.assertRaises(ValidationError):
|
||||
QuoteRequest.model_validate(quote(redesign=[[0, 0], [0, 0]]))
|
||||
with self.assertRaises(ValidationError):
|
||||
QuoteRequest.model_validate(quote(redesign=[[1, 0]]))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
|
||||
109
tests/test_db_outage.py
Normal file
109
tests/test_db_outage.py
Normal file
@@ -0,0 +1,109 @@
|
||||
"""A short database outage during a redeploy: bounded retries, one report.
|
||||
|
||||
Run from the repository root: python3 -m unittest tests.test_db_outage -v.
|
||||
The worker imports psycopg and boto3, so a host without the API image's
|
||||
dependencies cannot import it; CI runs this in the api container.
|
||||
"""
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
import psycopg
|
||||
|
||||
from app import worker
|
||||
from app.core import auth
|
||||
|
||||
|
||||
class WorkerDatabaseOutageTest(unittest.TestCase):
|
||||
class StopLoop(Exception):
|
||||
pass
|
||||
|
||||
class Connection:
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc_info):
|
||||
return False
|
||||
|
||||
def execute(self, *args, **kwargs):
|
||||
return self
|
||||
|
||||
def fetchone(self):
|
||||
return None
|
||||
|
||||
def setUp(self):
|
||||
worker.db_down_since = None
|
||||
self.addCleanup(setattr, worker, 'db_down_since', None)
|
||||
|
||||
def test_one_error_and_one_info_with_growing_sleeps(self):
|
||||
outage = psycopg.OperationalError('connection refused')
|
||||
with mock.patch.object(worker, 'connect',
|
||||
side_effect=[outage, outage, outage, self.Connection()]), \
|
||||
mock.patch.object(worker, 'last_cleanup', worker.time.monotonic()), \
|
||||
mock.patch.object(worker, 'cleanup'), \
|
||||
mock.patch.object(worker, 'tiny_keepalive'), \
|
||||
mock.patch.object(worker, 'reconcile_payments'), \
|
||||
mock.patch.object(worker, 'resolve_names'), \
|
||||
mock.patch.object(worker.mail, 'send_pending'), \
|
||||
mock.patch.object(worker.time, 'sleep',
|
||||
side_effect=[None, None, None, self.StopLoop]) as sleep, \
|
||||
mock.patch.object(worker.logging, 'warning') as warning, \
|
||||
mock.patch.object(worker.logging, 'info') as info, \
|
||||
mock.patch.object(worker.logging, 'debug') as debug:
|
||||
with self.assertRaises(self.StopLoop):
|
||||
worker.loop()
|
||||
# A warning, not an error: a restart is expected (Sentry DTF-API-8).
|
||||
self.assertEqual(warning.call_count, 1)
|
||||
self.assertIn('Database unavailable', warning.call_args[0][0])
|
||||
self.assertEqual(info.call_count, 1)
|
||||
self.assertIn('Database back after', info.call_args[0][0])
|
||||
self.assertEqual(debug.call_count, 2)
|
||||
self.assertEqual([call.args[0] for call in sleep.call_args_list[:3]],
|
||||
[1, 2, 4])
|
||||
|
||||
|
||||
class AuditPersistenceOutageTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
auth._persistence_error_at = None
|
||||
self.addCleanup(setattr, auth, '_persistence_error_at', None)
|
||||
|
||||
def test_persistence_error_is_logged_at_most_once_per_minute(self):
|
||||
logger = auth.logging.getLogger('dtf.security')
|
||||
outage = psycopg.OperationalError('database is down')
|
||||
with mock.patch.object(auth, 'connect', side_effect=outage), \
|
||||
mock.patch.object(auth.time, 'monotonic',
|
||||
side_effect=[100.0, 130.0, 161.0]), \
|
||||
mock.patch.object(logger, 'error') as error, \
|
||||
mock.patch.object(logger, 'warning') as warning:
|
||||
auth.audit('first')
|
||||
auth.audit('second')
|
||||
auth.audit('third')
|
||||
# A connection outage: the event lines and, once a minute, a warning.
|
||||
self.assertEqual(error.call_count, 0)
|
||||
self.assertEqual(warning.call_count, 5)
|
||||
|
||||
def test_any_other_persistence_failure_is_an_error(self):
|
||||
logger = auth.logging.getLogger('dtf.security')
|
||||
with mock.patch.object(auth, 'connect', side_effect=RuntimeError('bad table')), \
|
||||
mock.patch.object(auth.time, 'monotonic', return_value=100.0), \
|
||||
mock.patch.object(logger, 'error') as error, \
|
||||
mock.patch.object(logger, 'warning'):
|
||||
auth.audit('first')
|
||||
self.assertEqual(error.call_count, 1)
|
||||
|
||||
|
||||
class RequestDuringOutageTest(unittest.TestCase):
|
||||
def test_a_request_gets_503_with_retry_after(self):
|
||||
"""Sentry DTF-API-9: the board answered 500 while the database restarted."""
|
||||
import asyncio
|
||||
from app import app as module
|
||||
request = mock.Mock(method='GET', url=mock.Mock(path='/api/operator/board'))
|
||||
with mock.patch.object(module.logging, 'warning') as warning:
|
||||
response = asyncio.run(module.database_unavailable(request, psycopg.OperationalError('down')))
|
||||
self.assertEqual(response.status_code, 503)
|
||||
self.assertEqual(response.headers['retry-after'], '5')
|
||||
self.assertIn(b'reiniciando', response.body)
|
||||
self.assertEqual(warning.call_count, 1)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -105,7 +105,7 @@ class GradeCheckTests(unittest.TestCase):
|
||||
storage = CountingStorage({'k.pdf': b'%PDF-1.4 test', 'k.png': encoded('PNG', (100, 50))})
|
||||
files = grade_check.Files(storage)
|
||||
pdf_row = {'object_key': 'k.pdf', 'size': 15, 'name': 'a.pdf'}
|
||||
with mock.patch.object(grade_check, 'pdf_dpi', return_value=300):
|
||||
with mock.patch.object(grade_check, 'bounded_pdf_dpi', return_value=300):
|
||||
self.assertEqual(files.pdf_dpi(pdf_row), 300)
|
||||
self.assertEqual(files.pdf_dpi(pdf_row), 300)
|
||||
self.assertEqual(storage.downloads, 1)
|
||||
@@ -158,5 +158,89 @@ class GradeCheckTests(unittest.TestCase):
|
||||
self.assertIn('confirme a ressalva', issue(199.4))
|
||||
|
||||
|
||||
def nested_forms_pdf(path, fanout=10, levels=8):
|
||||
"""A 2 KB PDF whose page draws form F0 ten times, F0 draws F1 ten times,
|
||||
eight deep: 10^8 draws for a reader that walks them."""
|
||||
pdf = pikepdf.new()
|
||||
pdf.add_blank_page(page_size=(200, 200))
|
||||
forms = []
|
||||
for level in reversed(range(levels)):
|
||||
if forms:
|
||||
content = b''.join(b'q /F%d Do Q\n' % (level + 1) for _ in range(fanout))
|
||||
resources = pikepdf.Dictionary(XObject=pikepdf.Dictionary({'/F%d' % (level + 1): forms[0]}))
|
||||
else:
|
||||
content, resources = b'0 0 1 1 re f\n', pikepdf.Dictionary()
|
||||
form = pikepdf.Stream(pdf, content)
|
||||
form.Type, form.Subtype, form.BBox, form.Resources = (pikepdf.Name.XObject, pikepdf.Name.Form,
|
||||
[0, 0, 1, 1], resources)
|
||||
forms.insert(0, pdf.make_indirect(form))
|
||||
page = pdf.pages[0]
|
||||
page.obj.Resources = pikepdf.Dictionary(XObject=pikepdf.Dictionary({'/F0': forms[0]}))
|
||||
page.obj.Contents = pdf.make_indirect(pikepdf.Stream(pdf, b''.join(b'q /F0 Do Q\n' for _ in range(fanout))))
|
||||
pdf.save(path)
|
||||
|
||||
|
||||
class HostilePdfTests(unittest.TestCase):
|
||||
"""A tiny PDF must not hold the scanner's one thread (security review,
|
||||
2026-11-27): it held it for hours, and every upload behind it."""
|
||||
|
||||
def test_nested_forms_end_unknown_in_seconds(self):
|
||||
import time
|
||||
with tempfile.NamedTemporaryFile(suffix='.pdf') as handle:
|
||||
nested_forms_pdf(handle.name)
|
||||
start = time.monotonic()
|
||||
self.assertIsNone(grade_check.pdf_dpi(handle.name))
|
||||
self.assertLess(time.monotonic() - start, grade_check.PDF_MAX_SECONDS + 2)
|
||||
start = time.monotonic()
|
||||
self.assertIsNone(grade_check.bounded_pdf_dpi(handle.name))
|
||||
self.assertLess(time.monotonic() - start, grade_check.PDF_MAX_SECONDS + 10)
|
||||
|
||||
def test_a_heavy_vector_page_is_still_read(self):
|
||||
# Vector art has many paths and few draws: only draws are counted.
|
||||
pdf = pikepdf.new()
|
||||
pdf.add_blank_page(page_size=(200, 200))
|
||||
pdf.pages[0].obj.Contents = pdf.make_indirect(pikepdf.Stream(pdf, b'0 0 1 1 re f\n' * 200000))
|
||||
with tempfile.NamedTemporaryFile(suffix='.pdf') as handle:
|
||||
pdf.save(handle.name)
|
||||
self.assertEqual(grade_check.pdf_dpi(handle.name), grade_check.PDF_VECTOR_DPI)
|
||||
|
||||
def test_a_scan_held_on_one_file_is_reported(self):
|
||||
from app import scanning
|
||||
import time
|
||||
self.assertFalse(scanning.stuck())
|
||||
with mock.patch.object(scanning, 'busy_since', time.monotonic() - scanning.SCAN_STUCK_SECONDS - 1):
|
||||
self.assertTrue(scanning.stuck())
|
||||
with mock.patch.object(scanning, 'busy_since', time.monotonic()):
|
||||
self.assertFalse(scanning.stuck())
|
||||
|
||||
|
||||
class ProportionTests(unittest.TestCase):
|
||||
"""A file laid out at proportions it does not have is refused before
|
||||
payment, not found at print time (a 5 m sheet sent as 10 cm)."""
|
||||
|
||||
def cart(self, length, rotation=0, top=0, bottom=0, name='sheet.png'):
|
||||
source = {'upload_id': name, 'kind': 'sheet', 'width_cm': 57, 'length_cm': length,
|
||||
'rotation_degrees': rotation, 'trim_top_cm': top, 'trim_bottom_cm': bottom}
|
||||
return [{'production': {'sources': [source]}}], {name: {'name': name}}
|
||||
|
||||
def test_the_files_own_proportions_pass(self):
|
||||
files = FakeFiles({'sheet.png': encoded('PNG', (570, 1000)), 'turned.png': encoded('PNG', (1000, 570))})
|
||||
for args in ((100,), (90, 0, 4, 6)):
|
||||
items, rows = self.cart(*args)
|
||||
self.assertIsNone(grade_check.proportion_issue(files, items, rows), args)
|
||||
items, rows = self.cart(100, 90, name='turned.png')
|
||||
self.assertIsNone(grade_check.proportion_issue(files, items, rows))
|
||||
|
||||
def test_other_proportions_are_refused(self):
|
||||
files = FakeFiles({'sheet.png': encoded('PNG', (570, 50000))})
|
||||
items, rows = self.cart(10)
|
||||
self.assertIn('não são as proporções', grade_check.proportion_issue(files, items, rows))
|
||||
|
||||
def test_a_pdf_is_left_to_the_print_file(self):
|
||||
files = FakeFiles({})
|
||||
items, rows = self.cart(10, name='sheet.pdf')
|
||||
self.assertIsNone(grade_check.proportion_issue(files, items, rows))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
|
||||
@@ -34,7 +34,7 @@ class GradeRulesTest(unittest.TestCase):
|
||||
def test_treatment_message(self):
|
||||
self.assertEqual(
|
||||
treatment_message(45),
|
||||
'Sua arte tem nota 45: para imprimir com qualidade, o Ajuste Fino '
|
||||
'Sua arte está abaixo da resolução mínima, então o Ajuste Fino '
|
||||
'é obrigatório neste pedido.')
|
||||
|
||||
|
||||
|
||||
67
tests/test_health.py
Normal file
67
tests/test_health.py
Normal file
@@ -0,0 +1,67 @@
|
||||
"""The health check (Sentry DTF-API-B): an R2 blip is not the API down.
|
||||
|
||||
Runs in the API image: python -m unittest tests.test_health -v.
|
||||
"""
|
||||
import unittest
|
||||
from contextlib import contextmanager
|
||||
from unittest import mock
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
from app.api import health as module
|
||||
|
||||
|
||||
@contextmanager
|
||||
def database(up=True):
|
||||
if not up:
|
||||
raise RuntimeError('no database')
|
||||
yield mock.MagicMock()
|
||||
|
||||
|
||||
class HealthTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
module._storage.update(down_since=None, reported=False)
|
||||
patches = [mock.patch.object(module.db, 'connect', database), mock.patch.object(module.time, 'sleep')]
|
||||
for patch in patches:
|
||||
patch.start()
|
||||
self.addCleanup(patch.stop)
|
||||
|
||||
def check(self, storage_up, now=0):
|
||||
storage = mock.MagicMock()
|
||||
if not storage_up:
|
||||
storage.health.side_effect = RuntimeError('R2 500')
|
||||
with mock.patch.object(module, 'storage', storage), \
|
||||
mock.patch.object(module.time, 'monotonic', return_value=now), \
|
||||
mock.patch.object(module.logging, 'error') as error:
|
||||
try:
|
||||
return module.health(), error.call_count
|
||||
except HTTPException as exc:
|
||||
return exc.status_code, error.call_count
|
||||
|
||||
def test_a_storage_blip_is_reported_but_not_a_503(self):
|
||||
answer, errors = self.check(storage_up=False, now=100)
|
||||
self.assertEqual((answer['storage'], errors), ('unavailable', 0))
|
||||
answer, _ = self.check(storage_up=True, now=150)
|
||||
self.assertNotEqual(answer['storage'], 'unavailable')
|
||||
|
||||
def test_storage_down_for_five_minutes_is_a_503_reported_once(self):
|
||||
self.check(storage_up=False, now=0)
|
||||
self.assertEqual(self.check(storage_up=False, now=299)[0]['storage'], 'unavailable')
|
||||
self.assertEqual(self.check(storage_up=False, now=300), (503, 1))
|
||||
self.assertEqual(self.check(storage_up=False, now=400), (503, 0))
|
||||
|
||||
def test_one_retry_rides_out_a_single_failure(self):
|
||||
storage = mock.MagicMock()
|
||||
storage.health.side_effect = [RuntimeError('R2 500'), None]
|
||||
with mock.patch.object(module, 'storage', storage):
|
||||
self.assertTrue(module.storage_answers())
|
||||
|
||||
def test_the_database_down_is_a_503_at_once(self):
|
||||
with mock.patch.object(module.db, 'connect', lambda: database(up=False)):
|
||||
with self.assertRaises(HTTPException) as caught:
|
||||
module.health()
|
||||
self.assertEqual(caught.exception.status_code, 503)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -3,7 +3,7 @@ import unittest
|
||||
from datetime import datetime, timedelta
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from app.machine_stats import month_bounds, ratios
|
||||
from app.machine_stats import month_bounds, pace, ratios
|
||||
|
||||
SAO_PAULO = ZoneInfo('America/Sao_Paulo')
|
||||
|
||||
@@ -74,5 +74,18 @@ class RatiosTest(unittest.TestCase):
|
||||
self.assertIsNone(value['payback_months'])
|
||||
|
||||
|
||||
|
||||
class PaceTest(unittest.TestCase):
|
||||
def test_seconds_in_imprimindo_give_no_pace(self):
|
||||
# 16/11: an order moved through Imprimindo in seconds showed 110671,5 m/h.
|
||||
self.assertIsNone(pace(1.01, 10 / 3600))
|
||||
self.assertIsNone(pace(5, 0))
|
||||
self.assertIsNone(pace(5, None))
|
||||
|
||||
def test_a_quarter_of_an_hour_gives_the_pace(self):
|
||||
self.assertEqual(pace(5, 0.25), 20.0)
|
||||
self.assertEqual(pace(1.5, 0.5), 3.0)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
|
||||
@@ -137,6 +137,11 @@ class MercadoPagoTests(unittest.TestCase):
|
||||
self.mp.create('22222222-2222-3333-4444-555555555555', 1000, {'mail': 'a@example.test', 'cnpj': '52998224725'})
|
||||
person = json.loads(self.requests[-1].content)
|
||||
self.assertEqual(person['payer']['identification'], {'type': 'CPF', 'number': '52998224725'})
|
||||
# A one-word name is both first and last name.
|
||||
self.mp.create('33333333-2222-3333-4444-555555555555', 1000,
|
||||
{'mail': 'a@example.test', 'cnpj': '52998224725', 'name': 'Kenia'})
|
||||
self.assertEqual({k: v for k, v in json.loads(self.requests[-1].content)['payer'].items() if 'name' in k},
|
||||
{'first_name': 'Kenia', 'last_name': 'Kenia'})
|
||||
self.assertEqual((created['pix_qr_code'], created['status']), ('000201PIX', 'pending'))
|
||||
# The code expires in 30 minutes, in the format Mercado Pago documents.
|
||||
expires = datetime.fromisoformat(body['date_of_expiration'])
|
||||
@@ -161,15 +166,30 @@ class MercadoPagoTests(unittest.TestCase):
|
||||
{'type': 'card', 'token': 'tok_def', 'payment_method_id': 'visa'})
|
||||
self.assertNotEqual(self.requests[-1].headers['x-idempotency-key'], first_key)
|
||||
self.assertTrue(first_key.startswith('dtf-quote-q-card-'))
|
||||
# 3-D Secure is asked of debit only; the cardholder is the payer.
|
||||
# 3-D Secure is asked of debit only. The payer is a real document
|
||||
# (Marcus, 2026-11-18): a placeholder from the card form (999...) gives
|
||||
# way to the order's, with the order's name; the order's document is
|
||||
# always kept in the metadata for finance.
|
||||
self.assertNotIn('three_d_secure_mode', body)
|
||||
self.mp.create('q', 1000, {'mail': 'a@example.test', 'cnpj': '11222333000181'},
|
||||
self.mp.create('q', 1000, {'mail': 'a@example.test', 'cnpj': '11222333000181', 'name': 'Maria da Silva'},
|
||||
{'type': 'card', 'token': 'tok_deb', 'payment_method_id': 'debmaster',
|
||||
'payer_document_type': 'CPF', 'payer_document': '12345678909'})
|
||||
'payer_document_type': 'CPF', 'payer_document': '99999999999'})
|
||||
debit = json.loads(self.requests[-1].content)
|
||||
self.assertEqual(debit['three_d_secure_mode'], 'optional')
|
||||
self.assertEqual(debit['payer']['identification'], {'type': 'CPF', 'number': '12345678909'})
|
||||
self.assertEqual(debit['payer'], {'email': 'a@example.test', 'first_name': 'Maria', 'last_name': 'da Silva',
|
||||
'identification': {'type': 'CNPJ', 'number': '11222333000181'}})
|
||||
self.assertEqual(debit['metadata'], {'documento_pedido': '11222333000181'})
|
||||
self.assertEqual(body['payer']['identification'], {'type': 'CNPJ', 'number': '11222333000181'})
|
||||
# An order from before the Site asked the name sends none.
|
||||
self.assertNotIn('first_name', body['payer'])
|
||||
# A valid document typed in the card form (someone else's card) is the
|
||||
# payer, as the card token says; the order's stays in the metadata.
|
||||
self.mp.create('q', 1000, {'mail': 'a@example.test', 'cnpj': '11222333000181', 'name': 'Maria da Silva'},
|
||||
{'type': 'card', 'token': 'tok_other', 'payment_method_id': 'visa',
|
||||
'payer_document_type': 'CPF', 'payer_document': '52998224725'})
|
||||
other = json.loads(self.requests[-1].content)
|
||||
self.assertEqual(other['payer']['identification'], {'type': 'CPF', 'number': '52998224725'})
|
||||
self.assertEqual(other['metadata'], {'documento_pedido': '11222333000181'})
|
||||
self.mp.create('q', 1000, {'mail': 'a@example.test', 'cnpj': '11222333000181'},
|
||||
{'type': 'card', 'token': 'tok_iss', 'payment_method_id': 'master', 'issuer_id': '24'})
|
||||
self.assertNotIn('issuer_id', json.loads(self.requests[-1].content))
|
||||
|
||||
29
tests/test_one_machine.py
Normal file
29
tests/test_one_machine.py
Normal file
@@ -0,0 +1,29 @@
|
||||
"""One order, one machine (Marcus, 2026-11-26): UV and textile never share an
|
||||
order; basic and premium textile may.
|
||||
|
||||
Run from the repository root: python3 -m unittest tests.test_one_machine -v.
|
||||
"""
|
||||
import unittest
|
||||
|
||||
from app.core.models import ONE_MACHINE, Item, check_one_machine
|
||||
from tests.test_sheet_trim import sheet_item
|
||||
|
||||
|
||||
def items(*modes):
|
||||
return [Item.model_validate(sheet_item(mode=mode)) for mode in modes]
|
||||
|
||||
|
||||
class OneMachineTests(unittest.TestCase):
|
||||
def test_uv_and_textile_never_share_an_order(self):
|
||||
for modes in (('file', 'uvfile'), ('premium', 'uvfile'), ('uvfile', 'file', 'file')):
|
||||
with self.assertRaises(ValueError) as caught:
|
||||
check_one_machine(items(*modes))
|
||||
self.assertEqual(str(caught.exception), ONE_MACHINE)
|
||||
|
||||
def test_one_line_passes(self):
|
||||
check_one_machine(items('file', 'premium', 'file'))
|
||||
check_one_machine(items('uvfile', 'uvfile'))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -16,9 +16,14 @@ class PricingTests(unittest.TestCase):
|
||||
source = Path('web/site-config.js').read_text()
|
||||
prices = source.split('const PRECO=')[1].split(';',1)[0]
|
||||
calculator = source.split('const cobrar=')[1].split(';',1)[0]
|
||||
js = f'const PRECO={prices};const MINIMO_M=1;const cobrar={calculator};'
|
||||
# Every 10 cm with 8 mm of grace (Marcus, 2026-11-27): the Site's own rounding.
|
||||
grace = source.split('const TOLERANCIA_M=')[1].split(';',1)[0]
|
||||
rounding = source.split('const arredonda10=')[1].split(';',1)[0]
|
||||
js = (f'const PRECO={prices};const MINIMO_M=1;const TOLERANCIA_M={grace};'
|
||||
f'const arredonda10={rounding};const cobrar={calculator};')
|
||||
js += '''const results=[];for(const mode of Object.keys(PRECO))
|
||||
for(const metres of [0.01,0.99,1,1.01,1.1,2.75,2.8,2.8000000000000003,19.99,60,12000]){
|
||||
for(const metres of [0.01,0.99,1,1.01,1.1,2.75,2.8,2.8000000000000003,19.99,60,12000,
|
||||
1.008,1.0081,4.452,6.001,6.008,6.0081,6.009,5.992]){
|
||||
const unit=PRECO[mode];
|
||||
results.push([mode,String(metres),cobrar(metres),Math.round(unit*100),Math.round(cobrar(metres)*unit*100)]);
|
||||
}process.stdout.write(JSON.stringify(results));'''
|
||||
@@ -32,6 +37,18 @@ class PricingTests(unittest.TestCase):
|
||||
self.assertEqual(result['unit_cents'],unit)
|
||||
self.assertEqual(result['total_cents'],total)
|
||||
|
||||
def test_every_10_cm_with_8_mm_in_the_customers_favour(self):
|
||||
# Marcus, 2026-11-27: up to 8 mm past a step stays in it, more goes on.
|
||||
from app.core.pricing import billed_length
|
||||
for metres, billed in (('6.001', '6'), ('6.008', '6'), ('6.0081', '6.1'), ('6.009', '6.1'),
|
||||
('4.452', '4.5'), ('4.42', '4.5'), ('2.75', '2.8'), ('0.005', '0.1')):
|
||||
with self.subTest(metres=metres):
|
||||
self.assertEqual(billed_length(metres), Decimal(billed))
|
||||
# Marcus's two examples: 3 copies of ~199,5 cm with 8 mm between them,
|
||||
# and 5 copies of 88,4 cm.
|
||||
self.assertEqual(price('file', '6.001', 100)['billed_metres'], '6')
|
||||
self.assertEqual(price('file', '4.452', 100)['billed_metres'], '4.5')
|
||||
|
||||
def test_one_price_per_product(self):
|
||||
# Dropstar, 2026-10-23: textile R$ 19,90 ready sheet and R$ 21,90 loose
|
||||
# art; UV R$ 79,90 and R$ 89,90. Premium R$ 39,90 (2026-11-10).
|
||||
|
||||
@@ -129,7 +129,7 @@ class PrintFileTests(unittest.TestCase):
|
||||
job = {'snapshot': {'items': [spec, spec]}, 'number': 7, 'item_index': 1,
|
||||
'ordered_at': datetime(2026, 10, 23, 15, 0, tzinfo=timezone.utc)}
|
||||
line = footer(job, spec)
|
||||
self.assertEqual(line, 'DROPSTAR · Pedido DTF-7 · Item 2/2 · 23/10/2026 · 1,00 m · ESPELHADO')
|
||||
self.assertEqual(line, 'DROPSTAR · Pedido DTF-7 · Item 2/2 · 23/10/2026 · 1,00 m · 1 peça · ESPELHADO')
|
||||
self.assertIn(b'/F1 31 Tf ( \xb7 ESPELHADO) Tj', footer_commands(line, (100, 80)))
|
||||
# About 1 cm tall on the 57 cm film (Dropstar, 2026-10-28); on the 27 cm UV
|
||||
# the line shrinks to fit the width instead of running off the film.
|
||||
@@ -145,6 +145,38 @@ class PrintFileTests(unittest.TestCase):
|
||||
self.assertNotIn(b'ESPELHADO', footer_commands(footer(job, item([placement(0, 0, 20, 10)], [source(20, 10)], 10)), (100, 80)))
|
||||
# The files start with the code the Kanban copies.
|
||||
self.assertEqual(file_prefix(7, 1), 'DTF-7-item-2')
|
||||
# Generated again: the version in the name (Marcus, 2026-11-27, #130).
|
||||
self.assertEqual(file_prefix(130, 0, 2), 'DTF-130-v2-item-1')
|
||||
self.assertEqual(file_prefix(130, 0, 1), 'DTF-130-item-1')
|
||||
|
||||
def test_the_footer_names_the_customer_and_the_pieces(self):
|
||||
from datetime import datetime, timezone
|
||||
from app.printjobs import footer
|
||||
|
||||
def line(name, spec, items=2):
|
||||
customer = {} if name is None else {'name': name}
|
||||
job = {'snapshot': {'items': [spec] * items, 'customer': customer},
|
||||
'number': 7, 'item_index': 0,
|
||||
'ordered_at': datetime(2026, 10, 21, 15, 0, tzinfo=timezone.utc)}
|
||||
return footer(job, spec)
|
||||
|
||||
spec = item([placement(0, 0, 20, 10)], [source(20, 10)], 10)
|
||||
start = 'DROPSTAR · Pedido DTF-7 · '
|
||||
end = ' · Item 1/2 · 21/10/2026 · 1,00 m · 1 peça'
|
||||
# An accent stays; an emoji does not; a long name is cut with an ellipsis.
|
||||
self.assertEqual(line('Gráfica São José', spec), start + 'Gráfica São José' + end)
|
||||
self.assertEqual(line('Loja 🌟 Azul', spec), start + 'Loja Azul' + end)
|
||||
self.assertEqual(line('Gráfica São José do Vale do Paraíba', spec),
|
||||
start + 'Gráfica São José do Val…' + end)
|
||||
# Without a name the field is left out, with no stray separator.
|
||||
self.assertEqual(line(None, spec), 'DROPSTAR · Pedido DTF-7' + end)
|
||||
# A ready sheet counts its copies, and only says so above one.
|
||||
sheet = item([placement(0, 0, 20, 10)], [{**source(20, 10), 'kind': 'sheet', 'copies': 3}], 10)
|
||||
self.assertEqual(line('Cliente', sheet),
|
||||
'DROPSTAR · Pedido DTF-7 · Cliente · Item 1/2 · 21/10/2026 · 1,00 m · 3 cópias')
|
||||
single = item([placement(0, 0, 20, 10)], [{**source(20, 10), 'kind': 'sheet', 'copies': 1}], 10)
|
||||
self.assertEqual(line('Cliente', single),
|
||||
'DROPSTAR · Pedido DTF-7 · Cliente · Item 1/2 · 21/10/2026 · 1,00 m')
|
||||
|
||||
def test_jpeg_bytes_are_embedded_unchanged(self):
|
||||
path = self.save(quadrants(), 'a.jpg', quality=90)
|
||||
|
||||
@@ -115,6 +115,26 @@ class PngRenderTests(unittest.TestCase):
|
||||
self.assertGreater(film.crop((0, 59, film.width, film.height)).getextrema()[3][1], 0)
|
||||
self.assertEqual(detail['format'], 'png')
|
||||
|
||||
def test_a_trimmed_sheet_prints_only_what_is_between_its_empty_strips(self):
|
||||
# The Site cut 1 cm of transparency above and below 0,5 cm of art
|
||||
# (Marcus, 2026-11-18): the film is the art alone, read whole or in bands.
|
||||
art = quadrants(118, 59, alpha=True)
|
||||
sheet = Image.new('RGBA', (118, 118 + 59 + 118))
|
||||
sheet.paste(art, (0, 118))
|
||||
spec = item([placement(0, 0, 1, 0.5)], [{**source(1, 0.5), 'kind': 'sheet',
|
||||
'trim_top_cm': 1, 'trim_bottom_cm': 1}], 0.5)
|
||||
for stream in (False, True):
|
||||
with mock.patch.object(printpng, 'STREAM_ABOVE_PIXELS', 0 if stream else 10 ** 9):
|
||||
parts, detail = self.render(spec, [self.save(sheet, 'trimmed.png')])
|
||||
film = Image.open(parts[0][0])
|
||||
self.assertEqual(film.size, (px(57), 59), stream)
|
||||
self.assertEqual(film.crop((0, 0, 118, 59)).tobytes(), art.tobytes(), stream)
|
||||
self.assertEqual(detail['height_cm'], '0.5')
|
||||
# A cut that does not match the file is refused, so the room prepares it.
|
||||
spec['production']['sources'][0].update(trim_top_cm=2, trim_bottom_cm=2)
|
||||
with self.assertRaises(printpng.Unsupported):
|
||||
self.render(spec, [self.save(sheet, 'trimmed.png')])
|
||||
|
||||
def test_loose_art_is_turned_and_mirrored_like_the_site(self):
|
||||
art = quadrants(80, 40, alpha=True)
|
||||
# 80 x 40 px at 300 DPI is 6,773 x 3,387 cm; placed turned 90 degrees.
|
||||
@@ -146,6 +166,40 @@ class PngRenderTests(unittest.TestCase):
|
||||
self.assertEqual(second.convert('RGBA').getpixel((10, px(22) - px(21) + 5))[:3], RED)
|
||||
self.assertEqual([p['name'] for p in detail['parts']], ['DTF-7-item-1-p1.png', 'DTF-7-item-1-p2.png'])
|
||||
|
||||
def sheet_spec(self, height_cm, film=10):
|
||||
spec = item([placement(0, 0, film, height_cm)], [source(film, height_cm)], height_cm, film=film)
|
||||
spec['production']['sources'][0]['kind'] = 'sheet'
|
||||
return spec
|
||||
|
||||
def test_a_ready_sheet_is_cut_in_a_clear_band_not_through_the_art(self):
|
||||
# Marcus, 2026-11-27, #136: one ready sheet is one piece to the layout;
|
||||
# the cut finds the clear band in its pixels (30 to 31 cm) under 35 cm.
|
||||
sheet = Image.new('RGBA', (px(10), px(40)), (220, 30, 60, 255))
|
||||
sheet.paste((0, 0, 0, 0), (0, px(30), px(10), px(31)))
|
||||
parts, detail = self.render(self.sheet_spec(40), [self.save(sheet, 'sheet.png')], part_cm=35)
|
||||
cut = float(detail['parts'][0]['to_cm'])
|
||||
self.assertTrue(30 < cut < 31, cut)
|
||||
first = Image.open(parts[0][0]).convert('RGBA')
|
||||
self.assertEqual(first.getpixel((10, first.height - 2))[3], 0) # ends in the clear band
|
||||
|
||||
def test_a_packed_sheet_is_cut_in_its_widest_clear_band(self):
|
||||
# A sheet packed edge to edge (#83: 2 mm at most between rows): the
|
||||
# widest clear band, here 2 mm between dots, still cuts no ink.
|
||||
sheet = Image.new('RGBA', (px(10), px(40)), (220, 30, 60, 255))
|
||||
sheet.paste((0, 0, 0, 0), (0, px(30), px(10), px(31)))
|
||||
dots = [px(30 + tenth / 10) for tenth in range(1, 10, 2)] # a dot every 2 mm
|
||||
for row in dots:
|
||||
sheet.putpixel((px(5), row), (0, 0, 0, 255))
|
||||
_, detail = self.render(self.sheet_spec(40), [self.save(sheet, 'sheet.png')], part_cm=35)
|
||||
cut = px(float(detail['parts'][0]['to_cm']))
|
||||
self.assertTrue(px(30) < cut < px(31) and cut not in dots, cut)
|
||||
|
||||
def test_without_any_clear_row_the_cut_takes_the_least_ink(self):
|
||||
sheet = Image.new('RGBA', (px(10), px(40)), (220, 30, 60, 255))
|
||||
sheet.paste((0, 0, 0, 0), (px(1), px(32), px(10), px(32) + 3)) # only a thin edge of ink there
|
||||
_, detail = self.render(self.sheet_spec(40), [self.save(sheet, 'sheet.png')], part_cm=35)
|
||||
self.assertTrue(px(32) <= px(float(detail['parts'][0]['to_cm'])) < px(32) + 3, detail['parts'][0])
|
||||
|
||||
def test_pieces_for_the_viewer_come_with_the_file(self):
|
||||
art = quadrants(118, 59, alpha=True)
|
||||
spec = item([placement(0, 0, 1, 0.5)], [source(1, 0.5)], 0.5)
|
||||
|
||||
53
tests/test_profiles.py
Normal file
53
tests/test_profiles.py
Normal file
@@ -0,0 +1,53 @@
|
||||
"""Users with more than one profile (Marcus, 2026-11-26): what they may do is
|
||||
the sum of their profiles, and an operator's machine rules apply only to the
|
||||
moves that come from Operador.
|
||||
|
||||
Run from the repository root: python3 -m unittest tests.test_profiles -v.
|
||||
"""
|
||||
import unittest
|
||||
|
||||
from app.core.auth import has, machine_bound, machine_question, may_move, operator_only, roles_of
|
||||
from tests.test_moves import moves
|
||||
|
||||
|
||||
def user(*roles):
|
||||
return {'role': roles[0], 'roles': list(roles)}
|
||||
|
||||
|
||||
class ProfilesTest(unittest.TestCase):
|
||||
def test_moves_are_the_sum_of_the_profiles(self):
|
||||
self.assertEqual(moves(['operador', 'revisor']), moves('operador') | moves('revisor'))
|
||||
# Gestão and Operador: the coordination's pulls back, and the operator's moves forward.
|
||||
self.assertEqual(moves(['gestao', 'operador']), moves('gestao') | moves('operador'))
|
||||
self.assertTrue(may_move(['gestao', 'operador'], 'tra', 'imp'))
|
||||
self.assertFalse(may_move('gestao', 'tra', 'imp'))
|
||||
|
||||
def test_operador_and_revisor_release_what_they_printed(self):
|
||||
# D-29 does not block a user with both profiles (Marcus, 2026-11-26).
|
||||
self.assertTrue(may_move(['operador', 'revisor'], 'rev', 'fin'))
|
||||
|
||||
def test_the_machine_rules_follow_the_profile_that_allows_the_move(self):
|
||||
both = user('operador', 'revisor')
|
||||
self.assertTrue(machine_bound(both, 'tra', 'imp'))
|
||||
self.assertTrue(machine_bound(both, 'imp', 'rev'))
|
||||
self.assertFalse(machine_bound(both, 'rev', 'fin')) # as a Revisor, any machine
|
||||
self.assertFalse(machine_bound(user('gestao', 'operador'), 'imp', 'cor'))
|
||||
self.assertTrue(machine_bound(user('operador'), 'imp', 'rev'))
|
||||
self.assertFalse(machine_bound(user('admin'), 'tra', 'imp'))
|
||||
|
||||
def test_capabilities_and_the_machine_question(self):
|
||||
both = user('operador', 'revisor')
|
||||
self.assertTrue(has(both, 'inspect') and has(both, 'print'))
|
||||
self.assertTrue(operator_only(both, 'print'))
|
||||
self.assertFalse(operator_only(user('gestao', 'operador'), 'print'))
|
||||
self.assertEqual(machine_question(user('operador')), 'required')
|
||||
self.assertEqual(machine_question(both), 'required')
|
||||
self.assertEqual(machine_question(user('gestao', 'operador', 'revisor')), 'optional')
|
||||
self.assertIsNone(machine_question(user('revisor')))
|
||||
|
||||
def test_a_row_from_before_the_list_has_its_one_profile(self):
|
||||
self.assertEqual(roles_of({'role': 'designer', 'roles': []}), ('designer',))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -38,5 +38,22 @@ class ProofCutTests(unittest.TestCase):
|
||||
self.assertEqual(proof_cut(100, 15, None), [Decimal(0), Decimal(15)])
|
||||
|
||||
|
||||
class RenderLimitTests(unittest.TestCase):
|
||||
"""Order #20 (2026-11-12): a 23.6 m film ran past one 15 min limit."""
|
||||
|
||||
def test_the_limit_grows_with_the_parts(self):
|
||||
from app.printjobs import RENDER_SECONDS, render_seconds
|
||||
|
||||
def film(height):
|
||||
return {'production': {'height_cm': height, 'placements': [
|
||||
{'y_cm': 0, 'length_cm': height, 'source_index': 0}]}}
|
||||
self.assertEqual(render_seconds(film(800)), RENDER_SECONDS)
|
||||
# Parts of 10 m (Marcus, 2026-11-18), and a film in parts gets one
|
||||
# part more: a cut moved to a clear band (#136).
|
||||
self.assertEqual(render_seconds(film(2359.2)), 4 * RENDER_SECONDS)
|
||||
self.assertEqual(render_seconds(film(4600)), 6 * RENDER_SECONDS)
|
||||
self.assertEqual(render_seconds({'mode': 'file'}), RENDER_SECONDS)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
|
||||
78
tests/test_proof_parts.py
Normal file
78
tests/test_proof_parts.py
Normal file
@@ -0,0 +1,78 @@
|
||||
"""Prova OK approves every part of a film in parts (#114, #128, #130): only
|
||||
the first part became a final, and the others never reached the folders.
|
||||
|
||||
Run from the repository root: python3 -m unittest tests.test_proof_parts -v.
|
||||
"""
|
||||
import unittest
|
||||
|
||||
from app.proof import approve_parent
|
||||
|
||||
|
||||
class Rows:
|
||||
def __init__(self, rows):
|
||||
self.rows = rows
|
||||
|
||||
def fetchone(self):
|
||||
return self.rows[0] if self.rows else None
|
||||
|
||||
def fetchall(self):
|
||||
return self.rows
|
||||
|
||||
|
||||
class Database:
|
||||
"""Just the reads and writes approve_parent makes."""
|
||||
|
||||
def __init__(self, parts, active):
|
||||
self.parts, self.active, self.inserted, self.outbox = parts, active, [], []
|
||||
|
||||
def execute(self, sql, params=()):
|
||||
text = ' '.join(sql.split())
|
||||
if 'proof_result' in text:
|
||||
return Rows([{'number': 131}])
|
||||
if 'FROM dtf_local.print_files' in text:
|
||||
return Rows([{'item_index': 0, 'upload_id': self.parts[0]}])
|
||||
if 'FROM dtf_local.print_parts' in text:
|
||||
return Rows([{'upload_id': u} for u in self.parts])
|
||||
if text.startswith('SELECT upload_id FROM dtf_local.order_files'):
|
||||
return Rows([{'upload_id': u} for u in self.active])
|
||||
if text.startswith('INSERT INTO dtf_local.order_files'):
|
||||
self.inserted.append(params[2])
|
||||
if text.startswith('UPDATE dtf_local.orders SET state'):
|
||||
return Rows([{'version': 2}])
|
||||
if 'FROM dtf_local.outbox' in text:
|
||||
return Rows([])
|
||||
if text.startswith('INSERT INTO dtf_local.outbox'):
|
||||
self.outbox.append((params[0], params[2].obj['event']))
|
||||
return Rows([{'ok': 1}])
|
||||
|
||||
|
||||
ORDER = {'id': 'o', 'number': 131, 'state': 'rec', 'cancelled_at': None, 'payment': {'provider': 'mercadopago'},
|
||||
'snapshot': {'items': [{'mode': 'file'}]}}
|
||||
|
||||
|
||||
class ProofPartsTests(unittest.TestCase):
|
||||
def test_every_part_becomes_a_final(self):
|
||||
db = Database(['p1', 'p2', 'p3'], set())
|
||||
approve_parent(db, ORDER, 'Prumo')
|
||||
self.assertEqual(db.inserted, ['p1', 'p2', 'p3'])
|
||||
|
||||
def test_the_missing_parts_join_a_first_part_already_approved(self):
|
||||
db = Database(['p1', 'p2'], {'p1'})
|
||||
approve_parent(db, ORDER, 'Prumo')
|
||||
self.assertEqual(db.inserted, ['p2'])
|
||||
|
||||
def test_entering_the_queue_by_prova_ok_tells_tiny(self):
|
||||
# Tiny's "Preparando envio", as for a card moved by hand: orders with
|
||||
# a proof skipped it.
|
||||
db = Database(['p1'], set())
|
||||
self.assertTrue(approve_parent(db, ORDER, 'Prumo'))
|
||||
self.assertEqual(db.outbox, [('o:production_started:tiny', 'production_started')])
|
||||
|
||||
def test_a_final_someone_prepared_stays(self):
|
||||
db = Database(['p1', 'p2'], {'treated'})
|
||||
approve_parent(db, ORDER, 'Prumo')
|
||||
self.assertEqual(db.inserted, [])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -1,4 +1,5 @@
|
||||
"""A free proof is a 15 cm window around the measured fine stroke, not the top."""
|
||||
"""A free proof is a 15 cm window around the measured fine stroke, not the top,
|
||||
and samples of the colours that window lacks, up to 30 cm (Marcus, 2026-11-26)."""
|
||||
import io
|
||||
import tempfile
|
||||
import unittest
|
||||
@@ -28,38 +29,78 @@ def item(height_cm=30, fraction='0.75'):
|
||||
}
|
||||
|
||||
|
||||
RED, BLUE, GREEN = (220, 30, 60, 255), (30, 60, 220, 255), (40, 180, 70, 255)
|
||||
|
||||
|
||||
def cm(value):
|
||||
return round(value * PX_CM)
|
||||
|
||||
|
||||
def picture(path):
|
||||
"""The small picture the Site sends of a file: WebP within 480 x 720 px."""
|
||||
with Image.open(path) as image:
|
||||
image.thumbnail((480, 720))
|
||||
out = io.BytesIO()
|
||||
image.save(out, 'WEBP', quality=80)
|
||||
return out.getvalue()
|
||||
|
||||
|
||||
class ProofRenderTests(unittest.TestCase):
|
||||
def _sheet(self, folder):
|
||||
height = round(30 * PX_CM)
|
||||
width = round(20 * PX_CM)
|
||||
image = Image.new('RGBA', (width, height), (220, 30, 60, 255))
|
||||
ImageDraw.Draw(image).rectangle((0, height // 2, width - 1, height - 1),
|
||||
fill=(30, 60, 220, 255))
|
||||
def _sheet(self, folder, bands, height_cm=30):
|
||||
"""A 20 cm wide sheet painted in [(from_cm, colour)] bands."""
|
||||
image = Image.new('RGBA', (cm(20), cm(height_cm)), bands[0][1])
|
||||
draw = ImageDraw.Draw(image)
|
||||
for start, colour in bands[1:]:
|
||||
draw.rectangle((0, cm(start), cm(20) - 1, cm(height_cm) - 1), fill=colour)
|
||||
path = Path(folder) / 'sheet.png'
|
||||
image.save(path, 'PNG', dpi=(300, 300))
|
||||
return str(path)
|
||||
|
||||
def test_the_window_follows_the_finest_stroke(self):
|
||||
def proof(self, bands, height_cm=30, fraction='0.75'):
|
||||
with tempfile.TemporaryDirectory() as source, tempfile.TemporaryDirectory() as out:
|
||||
sheet = self._sheet(source)
|
||||
parts, detail = render(item(), {0: (sheet, 'sheet.png')}, out, 'proof',
|
||||
limit_cm=15, proof_fraction='0.75')
|
||||
sheet = self._sheet(source, bands, height_cm)
|
||||
parts, detail = render(item(height_cm, fraction), {0: (sheet, 'sheet.png')}, out, 'proof',
|
||||
limit_cm=15, proof_fraction=fraction, pictures={0: picture(sheet)})
|
||||
self.assertEqual(len(parts), 1)
|
||||
self.assertEqual(detail['parts'][0]['from_cm'], '15')
|
||||
with Image.open(parts[0][0]) as proof:
|
||||
self.assertEqual(proof.width, round(20 * PX_CM))
|
||||
self.assertLessEqual(abs(proof.height - round(15 * PX_CM)), 1)
|
||||
# The bottom half is blue: the window covered 15 to 30 cm.
|
||||
self.assertEqual(proof.getpixel((proof.width // 2, round(5 * PX_CM))), (30, 60, 220, 255))
|
||||
with Image.open(parts[0][0]) as image:
|
||||
return image.convert('RGBA'), detail
|
||||
|
||||
def test_the_top_is_still_the_default_without_a_measure(self):
|
||||
def test_the_window_follows_the_finest_stroke_and_samples_the_rest(self):
|
||||
# The stroke is in the blue half: its 15 cm window, then a 5 cm red
|
||||
# sample from above, 1 cm of clear film between them.
|
||||
image, detail = self.proof([(0, RED), (15, BLUE)])
|
||||
self.assertEqual(detail['proof_windows'], [['0', '5'], ['15', '30']])
|
||||
self.assertEqual(image.width, cm(20))
|
||||
self.assertLessEqual(abs(image.height - cm(21)), 2)
|
||||
self.assertEqual(image.getpixel((image.width // 2, cm(2))), RED)
|
||||
self.assertEqual(image.getpixel((image.width // 2, cm(5.5)))[3], 0)
|
||||
self.assertEqual(image.getpixel((image.width // 2, cm(10))), BLUE)
|
||||
|
||||
def test_the_top_is_still_the_window_without_a_measure(self):
|
||||
image, detail = self.proof([(0, RED), (15, BLUE)], fraction=None)
|
||||
self.assertEqual(detail['proof_windows'][0], ['0', '15'])
|
||||
self.assertEqual(image.getpixel((image.width // 2, cm(5))), RED)
|
||||
self.assertEqual(image.getpixel((image.width // 2, cm(18))), BLUE)
|
||||
|
||||
def test_without_pictures_the_proof_is_the_stroke_window(self):
|
||||
with tempfile.TemporaryDirectory() as source, tempfile.TemporaryDirectory() as out:
|
||||
sheet = self._sheet(source)
|
||||
parts, detail = render(item(fraction=None), {0: (sheet, 'sheet.png')}, out, 'proof',
|
||||
limit_cm=15)
|
||||
self.assertEqual(detail['parts'][0]['from_cm'], '0')
|
||||
with Image.open(parts[0][0]) as proof:
|
||||
self.assertEqual(proof.getpixel((proof.width // 2, round(5 * PX_CM))), (220, 30, 60, 255))
|
||||
sheet = self._sheet(source, [(0, RED), (15, BLUE)])
|
||||
_, detail = render(item(), {0: (sheet, 'sheet.png')}, out, 'proof', limit_cm=15, proof_fraction='0.75')
|
||||
self.assertEqual(detail['proof_windows'], [['15', '30']])
|
||||
|
||||
def test_one_colour_keeps_the_15_cm_proof(self):
|
||||
image, detail = self.proof([(0, BLUE)])
|
||||
self.assertEqual(detail['proof_windows'], [['15', '30']])
|
||||
self.assertLessEqual(abs(image.height - cm(15)), 1)
|
||||
|
||||
def test_every_colour_within_30_cm(self):
|
||||
# Red, blue and green in a 100 cm sheet, the stroke in the blue.
|
||||
image, detail = self.proof([(0, RED), (30, BLUE), (60, GREEN)], height_cm=100, fraction='0.45')
|
||||
windows = [(float(a), float(b)) for a, b in detail['proof_windows']]
|
||||
self.assertEqual(len(windows), 3)
|
||||
self.assertLessEqual(sum(b - a for a, b in windows) + 1 * (len(windows) - 1), 30)
|
||||
colours = {image.getpixel((image.width // 2, y)) for y in range(0, image.height, cm(1))}
|
||||
self.assertTrue({RED, BLUE, GREEN} <= colours, colours)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@@ -37,6 +37,30 @@ class PrumoReportTests(unittest.TestCase):
|
||||
self.assertIn('Prumo levou 41 s', text)
|
||||
self.assertNotIn('Prumo levou 341 s', text)
|
||||
|
||||
def test_saved_png_size_says_whether_the_customer_kept_it(self):
|
||||
order = self.order()
|
||||
item = order['snapshot']['items'][0]
|
||||
item['production']['sources'] = [
|
||||
{'width_cm': '28.0', 'length_cm': '35.2',
|
||||
'saved_width_cm': '28.0', 'saved_dpi': 300},
|
||||
{'width_cm': '20', 'length_cm': '25',
|
||||
'saved_width_cm': '15', 'saved_dpi': 240},
|
||||
]
|
||||
text = '\n'.join(report(order, {'u1': {'name': 'arte.pdf'}}))
|
||||
self.assertIn('Arte 1: tamanho lido do arquivo 28,0 × 35,2 cm (300 DPI), mantido', text)
|
||||
self.assertIn('Arte 2: tamanho lido do arquivo 15,0 × 18,8 cm (240 DPI), '
|
||||
'alterado pelo cliente para 20,0 cm', text)
|
||||
# Turned 90°: the art's own width is the length along the film.
|
||||
item['production']['sources'] = [
|
||||
{'width_cm': '35.2', 'length_cm': '28.0', 'rotation_degrees': 90,
|
||||
'saved_width_cm': '28.0', 'saved_dpi': 300}]
|
||||
text = '\n'.join(report(order, {'u1': {'name': 'arte.pdf'}}))
|
||||
self.assertIn('Arte 1: tamanho lido do arquivo 28,0 × 35,2 cm (300 DPI), mantido', text)
|
||||
|
||||
def test_without_a_saved_png_size_no_line_is_added(self):
|
||||
text = '\n'.join(report(self.order(), {'u1': {'name': 'arte.pdf'}}))
|
||||
self.assertNotIn('tamanho lido do arquivo', text)
|
||||
|
||||
def test_without_a_claim_time_the_generation_line_is_hidden(self):
|
||||
order = self.order()
|
||||
del order['print_files'][0]['claimed_at']
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user