Compare commits
255 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 | ||
|
|
5ca6792221 | ||
|
|
1a756a0beb | ||
|
|
6896e6a161 | ||
|
|
31776ca353 | ||
|
|
d3918e83dc | ||
|
|
c0905ac28d | ||
|
|
c9a7931eed | ||
|
|
aae8a8d49a | ||
|
|
d85e505097 | ||
|
|
ab3ac65b69 | ||
|
|
139f5ad67a | ||
|
|
2791f550c2 | ||
|
|
26ed5cecef | ||
|
|
8d9a59b210 | ||
|
|
77c04633e2 | ||
|
|
fb3a5003b8 | ||
|
|
55419d8364 | ||
|
|
f2fa2b7748 | ||
|
|
a747c01ec3 | ||
|
|
1b299827ea | ||
|
|
b980e1849c | ||
|
|
d840d2741f | ||
|
|
7a24c66997 | ||
|
|
61548fd6b2 | ||
|
|
457ed4cbdf | ||
|
|
d129a5164e | ||
|
|
49e5ff2081 | ||
|
|
dedcbb6aad | ||
|
|
b4b34ab3fb | ||
|
|
07515abbd8 | ||
|
|
9fd90f33d6 | ||
|
|
223bd61798 | ||
|
|
71980884a9 | ||
|
|
b69e3c1f53 | ||
|
|
e657551e66 | ||
|
|
c38a89f021 | ||
|
|
d044da1a5e | ||
|
|
52ed978e39 | ||
|
|
b5a51137fb | ||
|
|
a9a4b61d99 | ||
|
|
9952495c4e | ||
|
|
e6197d6e40 | ||
|
|
29b79db806 | ||
|
|
09ff22cde5 | ||
|
|
17463c0298 | ||
|
|
512a134e3e | ||
|
|
494356a211 | ||
|
|
0dd00f626c | ||
|
|
5b7e95ad86 | ||
|
|
085c2d0009 | ||
|
|
4d8f1aeb69 | ||
|
|
81c8cfc520 | ||
|
|
31b44a4fac | ||
|
|
f5df5b96e4 | ||
|
|
a6e4d4cb08 | ||
|
|
d85aa10fdd | ||
|
|
122a72c542 | ||
|
|
c383a4c93b | ||
|
|
74ac2c978b | ||
|
|
272755d2bc | ||
|
|
6b7ef1c4c8 | ||
|
|
63af984e83 | ||
|
|
89be0a045b | ||
|
|
f74a6f4fe1 | ||
|
|
31dbd0b062 | ||
|
|
3d8be36d65 | ||
|
|
2c80de0c0a | ||
|
|
60105e7cbe | ||
|
|
1d0353fe54 | ||
|
|
8993eb25db | ||
|
|
07ee38d677 | ||
|
|
2f85a38562 | ||
|
|
2a6732eb37 | ||
|
|
04761e63e3 | ||
|
|
7a5116ab19 | ||
|
|
c5e7a80b64 | ||
|
|
c88d81588e | ||
|
|
e9db9dec06 | ||
|
|
049f51b56a | ||
|
|
a69b9f71c2 | ||
|
|
4219db8215 | ||
|
|
29518795a5 | ||
|
|
b280e0cfa6 | ||
|
|
5aafd9ee91 | ||
|
|
5a51084c8f | ||
|
|
1a9611942d | ||
|
|
448a7fa8c3 | ||
|
|
a712c69aca | ||
|
|
f4cd1842ca | ||
|
|
c8d03d3b94 | ||
|
|
bdff73b76b | ||
|
|
7e22262280 | ||
|
|
b10eeead6e | ||
|
|
25e4ac541a | ||
|
|
dc87d46801 | ||
|
|
c291f00e96 | ||
|
|
b97b895993 | ||
|
|
f78cb93ba7 | ||
|
|
3d1293a3af | ||
|
|
2bcdb060fd | ||
|
|
6351a094f4 | ||
|
|
945c9e366a | ||
|
|
054a642a61 | ||
|
|
392e7da85b | ||
|
|
d69e326125 | ||
|
|
0fc01315c7 | ||
|
|
94f1bfa733 | ||
|
|
5520081184 | ||
|
|
8b7d9f0bdb | ||
|
|
e3a5ad6fa0 | ||
|
|
353935bed3 | ||
|
|
bd1e1772a7 | ||
|
|
a17f5fc08d | ||
|
|
67fad3a2d7 | ||
|
|
2615163fd3 | ||
|
|
388408d4d6 | ||
|
|
a010b2507e | ||
|
|
df601a7b6e | ||
|
|
67a9cd9533 | ||
|
|
0b8eb143ad | ||
|
|
f5c8bcfb90 | ||
|
|
d2e340032e | ||
|
|
6f294e168b | ||
|
|
c76d2fa7f3 | ||
|
|
05139b71ff |
@@ -14,3 +14,14 @@ staging/staging.env
|
|||||||
deploy/portainer.env
|
deploy/portainer.env
|
||||||
portal
|
portal
|
||||||
kanban
|
kanban
|
||||||
|
# Local test files in the repository root, kept out of every build context:
|
||||||
|
# pasta-teste-download alone is 1.5 GB and made each image build wait on it.
|
||||||
|
pasta-teste-download
|
||||||
|
pasta-teste-3-pasta
|
||||||
|
pasta-3-teste-producao
|
||||||
|
manifesto-pedido-1
|
||||||
|
imagens-teste
|
||||||
|
teste-4m
|
||||||
|
/*.png
|
||||||
|
/*.cdr
|
||||||
|
/dtf-site*.html
|
||||||
|
|||||||
@@ -18,6 +18,8 @@ OPERATOR_EMAIL=operator@example.test
|
|||||||
OPERATOR_PASSWORD=local-operator-only
|
OPERATOR_PASSWORD=local-operator-only
|
||||||
APP_ENV=local
|
APP_ENV=local
|
||||||
PAYMENT_ADAPTER=fake
|
PAYMENT_ADAPTER=fake
|
||||||
|
# Designer treatment, fixed per order in cents; 0 hides the option.
|
||||||
|
TREATMENT_CENTS=0
|
||||||
FREIGHT_ADAPTER=fake
|
FREIGHT_ADAPTER=fake
|
||||||
TINY_ADAPTER=fake
|
TINY_ADAPTER=fake
|
||||||
# Sandbox only (see docs/LOCAL_SETUP.md, "Provider sandboxes"):
|
# Sandbox only (see docs/LOCAL_SETUP.md, "Provider sandboxes"):
|
||||||
@@ -56,6 +58,6 @@ MAX_UPLOAD_BYTES=4294967296
|
|||||||
UPLOAD_PART_BYTES=8388608
|
UPLOAD_PART_BYTES=8388608
|
||||||
STORAGE_QUOTA_BYTES=53687091200
|
STORAGE_QUOTA_BYTES=53687091200
|
||||||
OWNER_UPLOAD_QUOTA_BYTES=10737418240
|
OWNER_UPLOAD_QUOTA_BYTES=10737418240
|
||||||
MAX_PENDING_UPLOADS=10
|
MAX_PENDING_UPLOADS=30
|
||||||
# Files above 128 MiB remain blocked (ClamAV config must agree with this limit).
|
# Files above 128 MiB remain blocked (ClamAV config must agree with this limit).
|
||||||
SCAN_MAX_BYTES=134217728
|
SCAN_MAX_BYTES=134217728
|
||||||
|
|||||||
@@ -16,13 +16,22 @@ jobs:
|
|||||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
|
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
|
||||||
- name: Run fast regression checks
|
- name: Run fast regression checks
|
||||||
run: |
|
run: |
|
||||||
python3 -m py_compile app/*.py app/**/*.py ops/*.py deploy/*.py
|
python3 -m py_compile app/*.py app/*/*.py app/*/*/*.py ops/*.py deploy/*.py
|
||||||
python3 -m unittest \
|
python3 -m unittest \
|
||||||
tests.test_dependency_lock \
|
tests.test_dependency_lock \
|
||||||
tests.test_staging_readiness \
|
tests.test_staging_readiness \
|
||||||
deploy.test_production_preflight \
|
deploy.test_production_preflight \
|
||||||
tests.test_pricing \
|
tests.test_pricing \
|
||||||
|
tests.test_cart_pricing \
|
||||||
|
tests.test_db_pool \
|
||||||
|
tests.test_coupons \
|
||||||
|
tests.test_grade_rules \
|
||||||
|
tests.test_hotfolder \
|
||||||
|
tests.test_migrate \
|
||||||
|
tests.test_label \
|
||||||
|
tests.test_observability \
|
||||||
tests.test_secrets -v
|
tests.test_secrets -v
|
||||||
|
node tests/observability_web_test.mjs
|
||||||
sh -n infra/lock_dependencies.sh
|
sh -n infra/lock_dependencies.sh
|
||||||
|
|
||||||
integration:
|
integration:
|
||||||
@@ -66,6 +75,12 @@ jobs:
|
|||||||
$COMPOSE up --build -d --wait --wait-timeout 600
|
$COMPOSE up --build -d --wait --wait-timeout 600
|
||||||
$COMPOSE ps
|
$COMPOSE ps
|
||||||
|
|
||||||
|
# The database never blocks a rollback. Runs in db-init, the only job
|
||||||
|
# with the administrator connection; the whole test is rolled back, so
|
||||||
|
# nothing it inserts or alters remains.
|
||||||
|
- name: Rollback and migrations
|
||||||
|
run: $COMPOSE run --rm --no-deps db-init python -m tests.migrations_test
|
||||||
|
|
||||||
# Run inside the stack's own network. The runner is itself a container, so
|
# Run inside the stack's own network. The runner is itself a container, so
|
||||||
# ports published on the host's loopback are in a different namespace and
|
# ports published on the host's loopback are in a different namespace and
|
||||||
# unreachable from here. SITE_HOST_HEADER keeps the Host the gateway and
|
# unreachable from here. SITE_HOST_HEADER keeps the Host the gateway and
|
||||||
@@ -73,7 +88,7 @@ jobs:
|
|||||||
# one a developer exercises on localhost.
|
# one a developer exercises on localhost.
|
||||||
- name: API and workflow regressions
|
- name: API and workflow regressions
|
||||||
run: |
|
run: |
|
||||||
for suite in smoke_test workflow_test security_test scanning_test payment_test quote_pagination_test kanban_test reconcile_test order_actions_test print_file_test users_test mail_test thumbnail_backfill_test launch_reset_test; do
|
for suite in smoke_test workflow_test security_test upload_limits_test scanning_test payment_test unpaid_test quote_pagination_test kanban_test label_test reconcile_test order_actions_test print_file_test users_test stage_limits_test mail_test thumbnail_backfill_test launch_reset_test finished_order_test machine_pull_test site_video_test treatment_gate_test review_media_test machine_log_test machine_stats_test site_admin_test coupons_test stamps_test grade_rules_test; do
|
||||||
echo "--- $suite"
|
echo "--- $suite"
|
||||||
$COMPOSE exec -T \
|
$COMPOSE exec -T \
|
||||||
-e SITE_BASE_URL=http://site \
|
-e SITE_BASE_URL=http://site \
|
||||||
@@ -86,7 +101,7 @@ jobs:
|
|||||||
# the generator's geometry. The provider suites use a fake transport: they
|
# the generator's geometry. The provider suites use a fake transport: they
|
||||||
# prove the documented contract, not the integration.
|
# prove the documented contract, not the integration.
|
||||||
- name: Print-file geometry and provider adapters
|
- name: Print-file geometry and provider adapters
|
||||||
run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_payment_messages tests.test_jadlog tests.test_correios tests.test_quote_review tests.test_moves tests.test_large_files tests.test_grade_check tests.test_schema tests.test_customer_document tests.test_mail_html tests.test_layout_rules -v
|
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 -v
|
||||||
|
|
||||||
- name: Runtime and retention regressions
|
- name: Runtime and retention regressions
|
||||||
run: |
|
run: |
|
||||||
|
|||||||
@@ -190,21 +190,55 @@ class EventAdapter(Protocol):
|
|||||||
def deliver(self, event_key: str, payload: dict) -> dict: ...
|
def deliver(self, event_key: str, payload: dict) -> dict: ...
|
||||||
|
|
||||||
class FakeTiny:
|
class FakeTiny:
|
||||||
|
# The montador's Venda customer search (front 7a.3) has somewhere to look
|
||||||
|
# on the local stack and in CI. Two fixed contacts, always.
|
||||||
|
CONTACTS = [
|
||||||
|
{'id': 1001, 'name': 'Nexstar Marketplace Ltda', 'document': '11.222.333/0001-81',
|
||||||
|
'email': 'financeiro@nexstar.example', 'phone': '1633334444'},
|
||||||
|
{'id': 1002, 'name': 'Maria Souza', 'document': '123.456.789-09',
|
||||||
|
'email': 'maria.souza@example.test', 'phone': '16988887777'},
|
||||||
|
]
|
||||||
|
# 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:
|
def deliver(self, event_key: str, payload: dict) -> dict:
|
||||||
return {'provider': 'fake-tiny', 'reference': f"LOCAL-{payload['number']}",
|
return {'provider': 'fake-tiny', 'reference': f"LOCAL-{payload['number']}",
|
||||||
'event_key': event_key, 'status': 'recorded-locally'}
|
'event_key': event_key, 'status': 'recorded-locally'}
|
||||||
|
|
||||||
|
def search_contacts(self, query: str) -> list:
|
||||||
|
return [dict(contact) for contact in self.CONTACTS]
|
||||||
|
|
||||||
|
# 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):
|
class ObjectStorage(Protocol):
|
||||||
def begin(self, key: str) -> str: ...
|
def begin(self, key: str) -> str: ...
|
||||||
def parts(self, key: str, upload_id: str) -> list: ...
|
def parts(self, key: str, upload_id: str) -> list: ...
|
||||||
def part_url(self, key: str, upload_id: str, part: int, size: int) -> str: ...
|
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 complete(self, key: str, upload_id: str, parts: list): ...
|
||||||
def size(self, key: str) -> int: ...
|
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 fetch(self, key: str, path: str): ...
|
||||||
def store(self, key: str, path: str, content_type: str): ...
|
def store(self, key: str, path: str, content_type: str): ...
|
||||||
def health(self): ...
|
def health(self): ...
|
||||||
def discard(self, key: str, upload_id: str, complete: bool): ...
|
def discard(self, key: str, upload_id: str, complete: bool): ...
|
||||||
|
def discard_prefix(self, prefix: str): ...
|
||||||
|
def view(self, key: str, content_type: str, expires: int = 3600) -> str: ...
|
||||||
|
|
||||||
class LocalS3Storage:
|
class LocalS3Storage:
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
@@ -212,6 +246,12 @@ class LocalS3Storage:
|
|||||||
connect_timeout=3, read_timeout=10, retries={'max_attempts': 2})
|
connect_timeout=3, read_timeout=10, retries={'max_attempts': 2})
|
||||||
self.client = boto3.client('s3', endpoint_url=os.environ['S3_ENDPOINT'], config=config)
|
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)
|
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']
|
self.bucket = os.environ['S3_BUCKET']
|
||||||
|
|
||||||
def initialize(self):
|
def initialize(self):
|
||||||
@@ -222,7 +262,7 @@ class LocalS3Storage:
|
|||||||
raise
|
raise
|
||||||
self.client.create_bucket(Bucket=self.bucket)
|
self.client.create_bucket(Bucket=self.bucket)
|
||||||
self.client.put_bucket_lifecycle_configuration(Bucket=self.bucket, LifecycleConfiguration={
|
self.client.put_bucket_lifecycle_configuration(Bucket=self.bucket, LifecycleConfiguration={
|
||||||
'Rules': [{'ID': 'local-artwork-retention', 'Status': 'Enabled', 'Filter': {'Prefix': ''},
|
'Rules': [{'ID': 'local-artwork-retention', 'Status': 'Enabled', 'Filter': {'Prefix': 'originals/'},
|
||||||
'Expiration': {'Days': 30}, 'AbortIncompleteMultipartUpload': {'DaysAfterInitiation': 1}}]})
|
'Expiration': {'Days': 30}, 'AbortIncompleteMultipartUpload': {'DaysAfterInitiation': 1}}]})
|
||||||
|
|
||||||
def health(self):
|
def health(self):
|
||||||
@@ -253,18 +293,37 @@ class LocalS3Storage:
|
|||||||
|
|
||||||
def fetch(self, key, path):
|
def fetch(self, key, path):
|
||||||
"""Copy a stored object to a local file (the worker's scratch space)."""
|
"""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):
|
def store(self, key, path, content_type):
|
||||||
"""Upload a file the service generated itself, such as a print file."""
|
"""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
|
from urllib.parse import quote
|
||||||
return self.public.generate_presigned_url('get_object', Params={
|
return self.public.generate_presigned_url('get_object', Params={
|
||||||
'Bucket': self.bucket, 'Key': key,
|
'Bucket': self.bucket, 'Key': key,
|
||||||
'ResponseContentDisposition': "attachment; filename*=UTF-8''" + quote(name, safe=''),
|
'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
|
||||||
|
viewer reads a film's pieces for as long as it is open (item 7)."""
|
||||||
|
return self.public.generate_presigned_url('get_object', Params={
|
||||||
|
'Bucket': self.bucket, 'Key': key, 'ResponseContentType': content_type}, ExpiresIn=expires)
|
||||||
|
|
||||||
|
def discard_prefix(self, prefix):
|
||||||
|
"""Delete every object under `prefix`, such as a print file's pieces."""
|
||||||
|
token = None
|
||||||
|
while True:
|
||||||
|
page = self.client.list_objects_v2(Bucket=self.bucket, Prefix=prefix,
|
||||||
|
**({'ContinuationToken': token} if token else {}))
|
||||||
|
keys = [{'Key': item['Key']} for item in page.get('Contents', [])]
|
||||||
|
if keys:
|
||||||
|
self.client.delete_objects(Bucket=self.bucket, Delete={'Objects': keys, 'Quiet': True})
|
||||||
|
if not page.get('IsTruncated'):
|
||||||
|
return
|
||||||
|
token = page['NextContinuationToken']
|
||||||
|
|
||||||
def discard(self, key, upload_id, complete):
|
def discard(self, key, upload_id, complete):
|
||||||
if not complete:
|
if not complete:
|
||||||
|
|||||||
@@ -6,21 +6,30 @@ one transport serves both and there is only one place where parts are signed.
|
|||||||
from uuid import UUID
|
from uuid import UUID
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
|
from pydantic import Field
|
||||||
|
|
||||||
from ..core import db
|
from ..core import db
|
||||||
|
from .. import proof
|
||||||
from ..artwork import submit_files
|
from ..artwork import submit_files
|
||||||
from ..core.auth import can, operator
|
from ..core.auth import can, can_any, operator
|
||||||
from ..core.models import ArtworkSubmission, UploadStart
|
from ..core.models import ArtworkSubmission, StrictModel, UploadStart
|
||||||
from ..runtime import file_rows, operator_identity
|
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
|
from .uploads import begin_upload, cancel_upload, complete_upload, part_url, upload_status
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
|
|
||||||
@router.post('/api/operator/orders/{oid}/uploads')
|
@router.post('/api/operator/orders/{oid}/uploads')
|
||||||
def begin_final(oid: UUID, body: UploadStart, user=Depends(can('produce'))):
|
def begin_final(oid: UUID, body: UploadStart, user=Depends(can('produce'))):
|
||||||
|
if not body.name.lower().endswith('.png'):
|
||||||
|
raise HTTPException(422, 'O arquivo final precisa ser PNG transparente a 300 DPI. Converta PDF/TIFF antes de enviar.')
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
row = c.execute('SELECT state FROM dtf_local.orders WHERE id=%s', (oid,)).fetchone()
|
row = c.execute('SELECT id,state,parent_id,proof_ok_at FROM dtf_local.orders WHERE id=%s', (oid,)).fetchone()
|
||||||
if not row: raise HTTPException(404, 'Order not found')
|
if not row: raise HTTPException(404, 'Order not found')
|
||||||
|
if row['parent_id']:
|
||||||
|
raise HTTPException(409, 'A prova recebe o PNG final automaticamente.')
|
||||||
|
if not proof.manual_source_needed(c, row):
|
||||||
|
proof.require_unlocked(c, row)
|
||||||
if row['state'] not in ('rec','cor'): raise HTTPException(409, 'Order is not in artwork review')
|
if row['state'] not in ('rec','cor'): raise HTTPException(409, 'Order is not in artwork review')
|
||||||
return begin_upload(body, session_id=operator_identity(user))
|
return begin_upload(body, session_id=operator_identity(user))
|
||||||
|
|
||||||
@@ -31,15 +40,15 @@ def final_status(uid: UUID, user=Depends(operator)):
|
|||||||
# The parts of an upload its operator started: a final (produce) or the
|
# The parts of an upload its operator started: a final (produce) or the
|
||||||
# photo of a signed pickup receipt (deliver, which includes produce).
|
# photo of a signed pickup receipt (deliver, which includes produce).
|
||||||
@router.post('/api/operator/uploads/{uid}/parts/{number}')
|
@router.post('/api/operator/uploads/{uid}/parts/{number}')
|
||||||
def final_part(uid: UUID, number: int, user=Depends(can('deliver'))):
|
def final_part(uid: UUID, number: int, user=Depends(can_any('deliver', 'assemble'))):
|
||||||
return part_url(uid,number,session_id=operator_identity(user))
|
return part_url(uid,number,session_id=operator_identity(user))
|
||||||
|
|
||||||
@router.post('/api/operator/uploads/{uid}/complete')
|
@router.post('/api/operator/uploads/{uid}/complete')
|
||||||
def final_complete(uid: UUID, user=Depends(can('deliver'))):
|
def final_complete(uid: UUID, user=Depends(can_any('deliver', 'assemble'))):
|
||||||
return complete_upload(uid,session_id=operator_identity(user))
|
return complete_upload(uid,session_id=operator_identity(user))
|
||||||
|
|
||||||
@router.delete('/api/operator/uploads/{uid}')
|
@router.delete('/api/operator/uploads/{uid}')
|
||||||
def final_cancel(uid: UUID, user=Depends(can('deliver'))):
|
def final_cancel(uid: UUID, user=Depends(can_any('deliver', 'assemble'))):
|
||||||
return cancel_upload(uid,session_id=operator_identity(user))
|
return cancel_upload(uid,session_id=operator_identity(user))
|
||||||
|
|
||||||
@router.get('/api/operator/orders/{oid}/files')
|
@router.get('/api/operator/orders/{oid}/files')
|
||||||
@@ -47,9 +56,42 @@ def operator_files(oid: UUID, user=Depends(operator)):
|
|||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
return file_rows(c,oid)
|
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')
|
@router.post('/api/operator/orders/{oid}/final-files')
|
||||||
def final_files(oid: UUID, body: ArtworkSubmission, user=Depends(can('produce'))):
|
def final_files(oid: UUID, body: ArtworkSubmission, user=Depends(can('produce'))):
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
order = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (oid,)).fetchone()
|
order = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (oid,)).fetchone()
|
||||||
if not order: raise HTTPException(404, 'Order not found')
|
if not order: raise HTTPException(404, 'Order not found')
|
||||||
|
if order['parent_id']:
|
||||||
|
raise HTTPException(409, 'O arquivo final da prova é gerado automaticamente. Use Gerar de novo se falhar.')
|
||||||
|
if not proof.manual_source_needed(c, order):
|
||||||
|
proof.require_unlocked(c, order)
|
||||||
return submit_files(c,order,body,operator_identity(user),'final',user)
|
return submit_files(c,order,body,operator_identity(user),'final',user)
|
||||||
|
|||||||
@@ -90,7 +90,7 @@ def checked_code(c, table, key, code, request, extra=''):
|
|||||||
return row, None
|
return row, None
|
||||||
c.execute(f'UPDATE dtf_local.{table} SET attempts=attempts+1 WHERE id=%s', (row['id'],))
|
c.execute(f'UPDATE dtf_local.{table} SET attempts=attempts+1 WHERE id=%s', (row['id'],))
|
||||||
left = CODE_ATTEMPTS - row['attempts'] - 1
|
left = CODE_ATTEMPTS - row['attempts'] - 1
|
||||||
audit('code_wrong', kind=table, ip=client_ip(request))
|
audit('code_wrong', kind=table, ip=client_ip(request), c=c)
|
||||||
return None, HTTPException(400, 'Código incorreto. ' + (f'Restam {left} tentativas.' if left > 1 else
|
return None, HTTPException(400, 'Código incorreto. ' + (f'Restam {left} tentativas.' if left > 1 else
|
||||||
'Resta 1 tentativa.' if left == 1 else 'Clique em “Reenviar código”.'))
|
'Resta 1 tentativa.' if left == 1 else 'Clique em “Reenviar código”.'))
|
||||||
|
|
||||||
@@ -157,7 +157,7 @@ def claim_orders(c, identity, profile):
|
|||||||
c.execute('UPDATE dtf_local.uploads SET owner=%s WHERE id=ANY(%s::uuid[]) AND owner=%s',
|
c.execute('UPDATE dtf_local.uploads SET owner=%s WHERE id=ANY(%s::uuid[]) AND owner=%s',
|
||||||
(identity, [str(uid) for uid in uploads], order['owner']))
|
(identity, [str(uid) for uid in uploads], order['owner']))
|
||||||
if orders:
|
if orders:
|
||||||
audit('account_orders_claimed', account=str(identity), orders=len(orders))
|
audit('account_orders_claimed', account=str(identity), orders=len(orders), c=c)
|
||||||
return len(orders)
|
return len(orders)
|
||||||
|
|
||||||
|
|
||||||
@@ -501,10 +501,18 @@ def detail(oid: UUID, identity=Depends(owner)):
|
|||||||
# only a correction's reason is written for the customer.
|
# only a correction's reason is written for the customer.
|
||||||
history = c.execute('''SELECT from_state,to_state,CASE WHEN to_state='cor' THEN reason ELSE '' END AS reason,
|
history = c.execute('''SELECT from_state,to_state,CASE WHEN to_state='cor' THEN reason ELSE '' END AS reason,
|
||||||
created_at FROM dtf_local.movements WHERE order_id=%s AND NOT back ORDER BY id''', (oid,)).fetchall()
|
created_at FROM dtf_local.movements WHERE order_id=%s AND NOT back ORDER BY id''', (oid,)).fetchall()
|
||||||
|
# The review photos only once the order is Finalizado; a video stays
|
||||||
|
# on the Kanban card (app/reviews.py).
|
||||||
|
photos = c.execute('''SELECT r.id,u.name,r.created_at FROM dtf_local.order_reviews r
|
||||||
|
JOIN dtf_local.uploads u ON u.id=r.upload_id
|
||||||
|
WHERE r.order_id=%s AND r.kind='photo' ORDER BY r.seq''', (oid,)).fetchall() \
|
||||||
|
if row['state'] == 'fin' else []
|
||||||
return {'id': row['id'], 'number': row['number'], 'code': order_code(row['id']),
|
return {'id': row['id'], 'number': row['number'], 'code': order_code(row['id']),
|
||||||
'state': row['state'], 'version': row['version'],
|
'state': row['state'], 'version': row['version'],
|
||||||
'created_at': row['created_at'], 'snapshot': row['snapshot'], 'history': history,
|
'created_at': row['created_at'], 'snapshot': row['snapshot'], 'history': history,
|
||||||
'files': file_rows(c,oid)}
|
'files': file_rows(c,oid),
|
||||||
|
'reviews': [{'id': photo['id'], 'name': photo['name'], 'created_at': photo['created_at']}
|
||||||
|
for photo in photos]}
|
||||||
|
|
||||||
@router.post('/api/customer/orders/{oid}/corrections')
|
@router.post('/api/customer/orders/{oid}/corrections')
|
||||||
def correction(oid: UUID, body: ArtworkSubmission, identity=Depends(owner)):
|
def correction(oid: UUID, body: ArtworkSubmission, identity=Depends(owner)):
|
||||||
|
|||||||
@@ -1,12 +1,14 @@
|
|||||||
"""Health, session bootstrap, freight quoting and the address of a CEP."""
|
"""Health, session bootstrap, freight quoting and the address of a CEP."""
|
||||||
|
import logging
|
||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
|
import time
|
||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
from fastapi import APIRouter, HTTPException, Request, Response
|
from fastapi import APIRouter, HTTPException, Request, Response
|
||||||
|
|
||||||
from ..core import db
|
from ..core import db
|
||||||
from .. import mail
|
from .. import catalog, grade_rules, mail, observability
|
||||||
from ..core.auth import client_ip, owner, new_session, rate_limit
|
from ..core.auth import client_ip, owner, new_session, rate_limit
|
||||||
from ..core.limits import upload_limit_bytes
|
from ..core.limits import upload_limit_bytes
|
||||||
from ..core.pricing import manual_extra_cents
|
from ..core.pricing import manual_extra_cents
|
||||||
@@ -16,17 +18,53 @@ from ..runtime import (ENVIRONMENT, GUEST_SESSION_LIMIT, PART_BYTES, delivery_se
|
|||||||
|
|
||||||
router = APIRouter()
|
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('/health')
|
||||||
@router.get('/api/health')
|
@router.get('/api/health')
|
||||||
def 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:
|
try:
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
c.execute('SELECT 1')
|
c.execute('SELECT 1')
|
||||||
storage.health()
|
|
||||||
except Exception:
|
except Exception:
|
||||||
raise HTTPException(503, 'Database or storage unavailable')
|
raise HTTPException(503, 'Database unavailable')
|
||||||
return {'status': 'ok', 'environment': ENVIRONMENT,
|
if storage_answers():
|
||||||
'storage': 'minio' if ENVIRONMENT == 'local' else 'r2', 'integrations': 'fake'}
|
_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')
|
@router.get('/api/session')
|
||||||
def session(request: Request, response: Response):
|
def session(request: Request, response: Response):
|
||||||
@@ -38,11 +76,39 @@ def session(request: Request, response: Response):
|
|||||||
rate_limit('guest-sessions', client_ip(request), GUEST_SESSION_LIMIT, 900)
|
rate_limit('guest-sessions', client_ip(request), GUEST_SESSION_LIMIT, 900)
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
session_id = new_session(c, response)
|
session_id = new_session(c, response)
|
||||||
|
with db.connect() as c:
|
||||||
|
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,
|
return {'environment': ENVIRONMENT, 'cart_scope': str(session_id), 'part_bytes': PART_BYTES,
|
||||||
'max_upload_bytes': upload_limit_bytes(), 'payment_provider': payment.name,
|
'max_upload_bytes': upload_limit_bytes(), 'payment_provider': payment.name,
|
||||||
'password_recovery': mail.configured(),
|
'password_recovery': mail.configured(),
|
||||||
# Per metre on a finished sheet someone opens by hand (app/core/pricing.py).
|
# Per metre on a finished sheet someone opens by hand (app/core/pricing.py).
|
||||||
'manual_extra_cents': manual_extra_cents(),
|
'manual_extra_cents': manual_extra_cents(),
|
||||||
|
# Zero keeps Ajuste Fino hidden, as an off product does. Its bands
|
||||||
|
# are counted in arts, not metres.
|
||||||
|
'treatment_cents': treatment['unit_cents'] if treatment['enabled'] else 0,
|
||||||
|
'treatment_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,
|
||||||
|
# What the Site sells now: a switched-off product is hidden there.
|
||||||
|
# Bands travel with the price; the Site reads them as numbers.
|
||||||
|
'products': {mode: {**products[mode],
|
||||||
|
'bands': [{'from_metres': float(band['from_metres']),
|
||||||
|
'unit_cents': band['unit_cents']}
|
||||||
|
for band in products[mode]['bands']]}
|
||||||
|
for mode in catalog.MODES},
|
||||||
|
# Public by design: the browser initialises Sentry with these; empty is off.
|
||||||
|
'sentry_dsn_web': os.environ.get('SENTRY_DSN_WEB', '').strip(),
|
||||||
|
'sentry_environment': os.environ.get('SENTRY_ENVIRONMENT') or ENVIRONMENT,
|
||||||
|
'sentry_release': observability.release() or '',
|
||||||
# Public by design: Mercado Pago's card form needs it in the browser.
|
# Public by design: Mercado Pago's card form needs it in the browser.
|
||||||
'payment_public_key': os.environ.get('MP_PUBLIC_KEY', '') if payment.name == 'mercadopago' else '',
|
'payment_public_key': os.environ.get('MP_PUBLIC_KEY', '') if payment.name == 'mercadopago' else '',
|
||||||
# The delivery options the cart quotes, or none: pickup only.
|
# The delivery options the cart quotes, or none: pickup only.
|
||||||
|
|||||||
139
app/api/machine_log.py
Normal file
139
app/api/machine_log.py
Normal file
@@ -0,0 +1,139 @@
|
|||||||
|
"""Routes of the machine sheet (Fase 2, front 1a, app/machine_log.py)."""
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||||
|
|
||||||
|
from .. import machine_log, machine_stats
|
||||||
|
from ..core import db
|
||||||
|
from ..core.auth import audit, can, operator, operator_only, roles_of
|
||||||
|
from ..core.models import MachineEntry, MachineSheet
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
# Números is read by management and by the seller and finance, who consult it.
|
||||||
|
STATS_ROLES = ('superadmin', 'admin', 'gestao', 'vendedor', 'financeiro')
|
||||||
|
|
||||||
|
|
||||||
|
def machine_row(c, mid):
|
||||||
|
row = c.execute('SELECT id,name,price_cents,installed_on FROM dtf_local.machines WHERE id=%s',
|
||||||
|
(mid,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(404, 'Máquina não encontrada.')
|
||||||
|
return row
|
||||||
|
|
||||||
|
|
||||||
|
def own_machine(request, mid):
|
||||||
|
"""An operator enters only on the machine of their session; management, anywhere."""
|
||||||
|
account = request.state.operator
|
||||||
|
if not operator_only(account, 'print'):
|
||||||
|
return
|
||||||
|
session_machine = account['machine']
|
||||||
|
if not session_machine or str(session_machine['id']) != str(mid):
|
||||||
|
raise HTTPException(403, 'Você só lança na máquina em que está.')
|
||||||
|
|
||||||
|
|
||||||
|
def entry_label(row):
|
||||||
|
if row['kind'] == 'supply':
|
||||||
|
return machine_log.SUPPLIES.get(row['item'], (row['item'],))[0]
|
||||||
|
if row['kind'] == 'part':
|
||||||
|
return machine_log.PARTS.get(row['item'], row['item'])
|
||||||
|
return machine_log.EVENTS.get(row['item'], row['item'])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get('/api/operator/machines/{mid}/sheet')
|
||||||
|
def sheet(mid: UUID, user=Depends(can('view'))):
|
||||||
|
with db.connect() as c:
|
||||||
|
machine = machine_row(c, mid)
|
||||||
|
entries = c.execute('''SELECT * FROM dtf_local.machine_entries
|
||||||
|
WHERE machine_id=%s ORDER BY created_at DESC, id DESC LIMIT 50''', (mid,)).fetchall()
|
||||||
|
minimums = {row['item']: row['minimum'] for row in c.execute(
|
||||||
|
'SELECT item,minimum FROM dtf_local.machine_minimums WHERE machine_id=%s', (mid,)).fetchall()}
|
||||||
|
return {'machine': {'id': str(machine['id']), 'name': machine['name'],
|
||||||
|
'price_cents': machine['price_cents'], 'installed_on': machine['installed_on']},
|
||||||
|
'counters': machine_log.counters(c, mid),
|
||||||
|
'supplies': machine_log.supply_estimates(c, mid),
|
||||||
|
'minimums': minimums,
|
||||||
|
# The values the sheet shows when Gestão has not typed one.
|
||||||
|
'default_minimums': machine_log.DEFAULT_MINIMUMS,
|
||||||
|
'alerts': machine_log.alerts(c, mid),
|
||||||
|
'entries': [{**row, 'label': entry_label(row)} for row in entries],
|
||||||
|
'catalog': {'supplies': machine_log.SUPPLIES, 'parts': machine_log.PARTS,
|
||||||
|
'events': machine_log.EVENTS}}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/machines/{mid}/entries')
|
||||||
|
def add_entry(mid: UUID, body: MachineEntry, request: Request, user=Depends(can('print'))):
|
||||||
|
own_machine(request, mid)
|
||||||
|
catalog = {'supply': machine_log.SUPPLIES, 'part': machine_log.PARTS,
|
||||||
|
'event': machine_log.EVENTS}[body.kind]
|
||||||
|
if body.item not in catalog:
|
||||||
|
raise HTTPException(422, 'Escolha um item da lista.')
|
||||||
|
if body.kind == 'supply':
|
||||||
|
if body.quantity is None:
|
||||||
|
raise HTTPException(422, 'Informe a quantidade que entrou.')
|
||||||
|
elif body.kind == 'part':
|
||||||
|
if body.cost_cents is None:
|
||||||
|
raise HTTPException(422, 'Informe o custo da peça.')
|
||||||
|
if body.item == 'other' and not (body.note or '').strip():
|
||||||
|
raise HTTPException(422, 'Descreva a outra peça.')
|
||||||
|
elif body.item == 'stop':
|
||||||
|
if not (body.note or '').strip() or body.stop_minutes is None:
|
||||||
|
raise HTTPException(422, 'Informe o motivo e os minutos da parada.')
|
||||||
|
elif body.quantity is not None or body.cost_cents is not None:
|
||||||
|
raise HTTPException(422, 'Limpeza e alinhamento não levam quantidade nem custo.')
|
||||||
|
with db.connect() as c:
|
||||||
|
machine_row(c, mid)
|
||||||
|
row = machine_log.add_entry(c, mid, body, user, from_alert=body.from_alert)
|
||||||
|
audit('machine_entry', operator=user, machine=str(mid), kind=body.kind, item=body.item,
|
||||||
|
from_alert=body.from_alert)
|
||||||
|
return row
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/machines/{mid}/sheet')
|
||||||
|
def save_sheet(mid: UUID, body: MachineSheet, user=Depends(can('manage'))):
|
||||||
|
unknown = set(body.minimums) - set(machine_log.SUPPLIES)
|
||||||
|
if unknown:
|
||||||
|
raise HTTPException(422, 'Só os insumos têm mínimo.')
|
||||||
|
for value in body.minimums.values():
|
||||||
|
if value is not None and value < 0:
|
||||||
|
raise HTTPException(422, 'O mínimo não pode ser negativo.')
|
||||||
|
with db.connect() as c:
|
||||||
|
machine_row(c, mid)
|
||||||
|
c.execute('UPDATE dtf_local.machines SET price_cents=%s, installed_on=%s WHERE id=%s',
|
||||||
|
(body.price_cents, body.installed_on, mid))
|
||||||
|
for item, value in body.minimums.items():
|
||||||
|
if value is None:
|
||||||
|
c.execute('DELETE FROM dtf_local.machine_minimums WHERE machine_id=%s AND item=%s',
|
||||||
|
(mid, item))
|
||||||
|
else:
|
||||||
|
c.execute('''INSERT INTO dtf_local.machine_minimums(machine_id,item,minimum)
|
||||||
|
VALUES(%s,%s,%s) ON CONFLICT (machine_id,item) DO UPDATE SET minimum=EXCLUDED.minimum''',
|
||||||
|
(mid, item, value))
|
||||||
|
audit('machine_sheet', operator=user, machine=str(mid), price_cents=body.price_cents,
|
||||||
|
installed_on=str(body.installed_on) if body.installed_on else None)
|
||||||
|
return {'ok': True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/machines/{mid}/alerts/{key}/snooze')
|
||||||
|
def snooze_alert(mid: UUID, key: str, request: Request, user=Depends(can('print'))):
|
||||||
|
own_machine(request, mid)
|
||||||
|
with db.connect() as c:
|
||||||
|
machine_row(c, mid)
|
||||||
|
machine_log.snooze(c, mid, key, user)
|
||||||
|
audit('machine_alert_snoozed', operator=user, machine=str(mid), alert=key)
|
||||||
|
return {'ok': True}
|
||||||
|
|
||||||
|
|
||||||
|
@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 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)
|
||||||
|
except ValueError:
|
||||||
|
raise HTTPException(422, 'Informe o mês como AAAA-MM.')
|
||||||
|
if start > machine_stats.month_bounds(None)[0]:
|
||||||
|
raise HTTPException(422, 'Esse mês ainda não começou.')
|
||||||
|
with db.connect() as c:
|
||||||
|
return machine_stats.report(c, month=month)
|
||||||
1388
app/api/operator.py
1388
app/api/operator.py
File diff suppressed because it is too large
Load Diff
17
app/api/operator/__init__.py
Normal file
17
app/api/operator/__init__.py
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
"""Kanban: sign-in, the board, commercial review and card movement, by area.
|
||||||
|
|
||||||
|
Each module owns its routes; this package keeps the single `router` app/app.py
|
||||||
|
includes and the names other modules imported from the old single file.
|
||||||
|
"""
|
||||||
|
from fastapi import APIRouter
|
||||||
|
|
||||||
|
from . import board, common, files, integrations, labels, orders, quotes, rework, session, stats
|
||||||
|
from .integrations import tiny_callback
|
||||||
|
from .stats import speed_figures
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
# The order the routes first appeared in the old file. Static paths that could
|
||||||
|
# meet a parameterised one stay ahead of it: /orders/finished before any
|
||||||
|
# /orders/{uid} GET.
|
||||||
|
for module in (common, session, integrations, board, quotes, rework, orders, labels, stats, files):
|
||||||
|
router.include_router(module.router)
|
||||||
290
app/api/operator/board.py
Normal file
290
app/api/operator/board.py
Normal file
@@ -0,0 +1,290 @@
|
|||||||
|
"""The board, its stage limits, and the finished orders beyond it."""
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from decimal import Decimal
|
||||||
|
from typing import Literal
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
|
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
|
||||||
|
from ...printjobs import CLAIM_TIMEOUT
|
||||||
|
from ...runtime import (BACK, BOARD_FINISHED_LIMIT, BOARD_QUOTE_LIMIT, ENVIRONMENT,
|
||||||
|
PUBLIC_ORIGIN, STATES, TRANSITIONS, payment, quote_views)
|
||||||
|
from .common import (FINAL_OK, LIVE_QUOTE, TREATED, company_names, cursor_pair, person,
|
||||||
|
thumbnails)
|
||||||
|
from .integrations import backup_status, freight_status, tiny_status
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
@router.get('/api/operator/board')
|
||||||
|
def board(user=Depends(operator)):
|
||||||
|
with db.connect() as c:
|
||||||
|
limits = {row['state']: {'hours': float(row['hours']), 'responsible': row['responsible']}
|
||||||
|
for row in c.execute('SELECT state,hours,responsible FROM dtf_local.stage_limits').fetchall()}
|
||||||
|
# Everything still in progress, however old: an operator must never lose a
|
||||||
|
# card they can act on. Finished orders are terminal and only accumulate,
|
||||||
|
# so the board carries a recent window of them and reports the true total.
|
||||||
|
active = c.execute("SELECT * FROM dtf_local.orders WHERE state<>'fin' ORDER BY created_at").fetchall()
|
||||||
|
# A proof card that got its answer is done with (app/proof.py).
|
||||||
|
finished = c.execute('''SELECT * FROM (
|
||||||
|
SELECT o.*, COALESCE((SELECT max(m.created_at) FROM dtf_local.movements m
|
||||||
|
WHERE m.order_id=o.id AND m.to_state='fin' AND NOT m.back), o.updated_at) AS finished_at
|
||||||
|
FROM dtf_local.orders o WHERE o.state='fin' AND o.parent_id IS NULL
|
||||||
|
) f ORDER BY finished_at DESC,id DESC LIMIT %s''', (BOARD_FINISHED_LIMIT,)).fetchall()
|
||||||
|
finished_total = c.execute("SELECT count(*) AS n FROM dtf_local.orders WHERE state='fin' AND parent_id IS NULL").fetchone()['n']
|
||||||
|
pending = c.execute(f'''SELECT q.* FROM dtf_local.quotes q
|
||||||
|
LEFT JOIN dtf_local.orders o ON o.quote_id=q.id
|
||||||
|
WHERE o.id IS NULL AND q.approved IS NULL AND {LIVE_QUOTE}
|
||||||
|
ORDER BY q.created_at DESC,q.id DESC LIMIT %s''', (BOARD_QUOTE_LIMIT,)).fetchall()
|
||||||
|
approved = c.execute(f'''SELECT q.* FROM dtf_local.quotes q
|
||||||
|
LEFT JOIN dtf_local.orders o ON o.quote_id=q.id
|
||||||
|
WHERE o.id IS NULL AND q.approved IS NOT NULL AND {LIVE_QUOTE}
|
||||||
|
ORDER BY q.created_at DESC,q.id DESC LIMIT 20''').fetchall()
|
||||||
|
pending_total = c.execute(f'''SELECT count(*) AS n FROM dtf_local.quotes q
|
||||||
|
LEFT JOIN dtf_local.orders o ON o.quote_id=q.id
|
||||||
|
WHERE o.id IS NULL AND q.approved IS NULL AND {LIVE_QUOTE}''').fetchone()['n']
|
||||||
|
approved_total = c.execute(f'''SELECT count(*) AS n FROM dtf_local.quotes q
|
||||||
|
LEFT JOIN dtf_local.orders o ON o.quote_id=q.id
|
||||||
|
WHERE o.id IS NULL AND q.approved IS NOT NULL AND {LIVE_QUOTE}''').fetchone()['n']
|
||||||
|
orders = with_print_files(c, active + finished)
|
||||||
|
assign_late(c, orders, limits)
|
||||||
|
# A paid notification that did not become an order is money received
|
||||||
|
# for nothing the factory will make. The board carries the count; the
|
||||||
|
# Pagamentos tab pages through them until someone records a resolution.
|
||||||
|
issues_total = c.execute('''SELECT count(*) AS n FROM dtf_local.payment_events
|
||||||
|
WHERE (outcome LIKE 'refused%' OR outcome LIKE 'attention%') AND resolved_at IS NULL''').fetchone()['n']
|
||||||
|
backup = backup_status(c)
|
||||||
|
quotes = quote_views(c, pending + approved)
|
||||||
|
return {'states': STATES, 'transitions': TRANSITIONS, 'back': BACK,
|
||||||
|
'orders': orders, 'payment_issues_total': issues_total, 'tiny': tiny_status(c), 'operator': user,
|
||||||
|
'providers': {'payment': payment.name, 'freight': freight_status(), 'backup': backup,
|
||||||
|
'mail': mail.status(c)},
|
||||||
|
'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.DEFAULT_PLACES,
|
||||||
|
'quotes': quotes, 'thumbnails': thumbnails(c, orders, quotes),
|
||||||
|
'names': company_names(c, orders, quotes),
|
||||||
|
'pending_total': pending_total, 'approved_total': approved_total,
|
||||||
|
'stage_limits': limits}
|
||||||
|
|
||||||
|
|
||||||
|
class StageLimit(StrictModel):
|
||||||
|
state: Literal['rec', 'tra', 'imp', 'rev', 'fin']
|
||||||
|
hours: Decimal = Field(gt=0, le=10000)
|
||||||
|
responsible: str = Field(default='', max_length=80)
|
||||||
|
|
||||||
|
|
||||||
|
class StageLimits(StrictModel):
|
||||||
|
limits: list[StageLimit] = Field(min_length=1, max_length=5)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get('/api/operator/stage-limits')
|
||||||
|
def get_stage_limits(user=Depends(operator)):
|
||||||
|
with db.connect() as c:
|
||||||
|
rows = c.execute('''SELECT state,hours,responsible,updated_by,updated_at
|
||||||
|
FROM dtf_local.stage_limits ORDER BY array_position(ARRAY['rec','tra','imp','rev','fin'],state)''').fetchall()
|
||||||
|
return {'limits': [{'state': row['state'], 'hours': float(row['hours']),
|
||||||
|
'responsible': row['responsible'], 'updated_by': row['updated_by'],
|
||||||
|
'updated_at': row['updated_at']} for row in rows]}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/stage-limits')
|
||||||
|
def set_stage_limits(body: StageLimits, user=Depends(can('manage'))):
|
||||||
|
seen = set()
|
||||||
|
with db.connect() as c:
|
||||||
|
for limit in body.limits:
|
||||||
|
if limit.state in seen:
|
||||||
|
raise HTTPException(422, 'Cada etapa aparece uma vez.')
|
||||||
|
seen.add(limit.state)
|
||||||
|
c.execute('''INSERT INTO dtf_local.stage_limits(state,hours,responsible,updated_by,updated_at)
|
||||||
|
VALUES(%s,%s,%s,%s,now())
|
||||||
|
ON CONFLICT (state) DO UPDATE SET hours=EXCLUDED.hours,responsible=EXCLUDED.responsible,
|
||||||
|
updated_by=EXCLUDED.updated_by,updated_at=now()''',
|
||||||
|
(limit.state, limit.hours, limit.responsible.strip(), user))
|
||||||
|
audit('stage_limits_changed', operator=user, states=','.join(sorted(seen)))
|
||||||
|
return {'ok': True}
|
||||||
|
|
||||||
|
|
||||||
|
def assign_late(c, orders, limits):
|
||||||
|
"""How long each card has been in its stage, and whether it passed the
|
||||||
|
limit Gestão set (front 11). A finished card with pickup is not late."""
|
||||||
|
ids = [order['id'] for order in orders]
|
||||||
|
if not ids:
|
||||||
|
return
|
||||||
|
entered = {}
|
||||||
|
for row in c.execute('''SELECT order_id,to_state,created_at FROM dtf_local.movements
|
||||||
|
WHERE order_id=ANY(%s) ORDER BY created_at,id''', (ids,)).fetchall():
|
||||||
|
entered[(str(row['order_id']), row['to_state'])] = row['created_at']
|
||||||
|
now = datetime.now(timezone.utc)
|
||||||
|
for order in orders:
|
||||||
|
if order.get('cancelled_at') or payments.is_test(order):
|
||||||
|
continue
|
||||||
|
limit = limits.get(order['state'])
|
||||||
|
if not limit:
|
||||||
|
continue
|
||||||
|
# Finalizado only has a pickup deadline; a delivery is done when it
|
||||||
|
# leaves, and a collected order is not waiting for anyone.
|
||||||
|
if order['state'] == 'fin' and (order.get('picked_up_at') or
|
||||||
|
not receipt.is_pickup(order['snapshot'])):
|
||||||
|
continue
|
||||||
|
since = entered.get((str(order['id']), order['state']))
|
||||||
|
if not since and order['state'] == 'fin':
|
||||||
|
since = order.get('finished_at')
|
||||||
|
since = since or order['created_at']
|
||||||
|
hours = max(0.0, (now - since).total_seconds() / 3600)
|
||||||
|
limit_hours = float(limit['hours'])
|
||||||
|
# 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']
|
||||||
|
order['late'] = 'bad' if hours >= limit_hours * 2 else 'warn' if hours >= limit_hours else None
|
||||||
|
|
||||||
|
|
||||||
|
def assign_machines(c, orders):
|
||||||
|
"""Each machine, its pull attribution, and its printing place."""
|
||||||
|
names = {str(m['id']): m['name'] for m in c.execute('SELECT id,name FROM dtf_local.machines').fetchall()}
|
||||||
|
slots = machines.printing_slots(c)
|
||||||
|
ids = [o['id'] for o in orders] + [o['proof_card']['id'] for o in orders if o.get('proof_card')]
|
||||||
|
pulled = {r['order_id']: r for r in c.execute('''SELECT DISTINCT ON (order_id) order_id,operator,created_at
|
||||||
|
FROM dtf_local.movements WHERE order_id=ANY(%s) AND to_state='imp' AND NOT back
|
||||||
|
ORDER BY order_id,id DESC''', (ids,)).fetchall()}
|
||||||
|
for order in orders:
|
||||||
|
key = str(order.get('machine_id') or '')
|
||||||
|
order['machine'] = ({'id': key, 'name': names[key], 'chosen': bool(order.get('machine_chosen'))}
|
||||||
|
if key in names else None)
|
||||||
|
order['printing'] = slots.get(order['id'])
|
||||||
|
by = pulled.get(order['id']) or (pulled.get(order['proof_card']['id']) if order.get('proof_card') else None)
|
||||||
|
order['machine_pulled'] = {'by': by['operator'], 'at': by['created_at']} if by else None
|
||||||
|
return orders
|
||||||
|
|
||||||
|
|
||||||
|
def with_print_files(c, orders):
|
||||||
|
"""Each order with its generated print files, the items whose final file is
|
||||||
|
approved, and the customer's corrections waiting to be approved as finals."""
|
||||||
|
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 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']
|
||||||
|
for uid in item.get('uploads') or []})
|
||||||
|
uploads = {row['id']: row for row in c.execute(
|
||||||
|
'''SELECT id::text AS id,name,original_name FROM dtf_local.uploads WHERE id::text=ANY(%s)''',
|
||||||
|
(upload_ids,)).fetchall()}
|
||||||
|
# A film over 15 m is several PNGs, in order (item 13).
|
||||||
|
parts = c.execute('''SELECT p.order_id,p.item_index,p.part,p.upload_id,u.name FROM dtf_local.print_parts p
|
||||||
|
JOIN dtf_local.uploads u ON u.id=p.upload_id WHERE p.order_id=ANY(%s) ORDER BY p.part''', (ids,)).fetchall()
|
||||||
|
for row in generated:
|
||||||
|
row['parts'] = [{'upload_id': part['upload_id'], 'name': part['name']} for part in parts
|
||||||
|
if part['order_id'] == row['order_id'] and part['item_index'] == row['item_index']]
|
||||||
|
finals = c.execute(f'''SELECT f.order_id,f.item_index,f.upload_id FROM dtf_local.order_files f
|
||||||
|
JOIN dtf_local.uploads u ON u.id=f.upload_id WHERE f.order_id=ANY(%s) AND {FINAL_OK}''', (ids,)).fetchall()
|
||||||
|
# Expired ones too: once corrected, a generated file is no longer the artwork.
|
||||||
|
fixes = c.execute('''SELECT f.order_id,f.item_index,f.upload_id,u.name,
|
||||||
|
(u.expires_at<=now() OR u.purged_at IS NOT NULL) AS expired FROM dtf_local.order_files f
|
||||||
|
JOIN dtf_local.uploads u ON u.id=f.upload_id
|
||||||
|
WHERE f.order_id=ANY(%s) AND f.kind='correction' AND f.active ORDER BY f.item_index''', (ids,)).fetchall()
|
||||||
|
# The items whose approved final someone prepared, and who approved it.
|
||||||
|
treated = c.execute(f'''SELECT f.order_id,f.item_index,f.created_by FROM dtf_local.order_files f
|
||||||
|
JOIN dtf_local.orders o ON o.id=f.order_id WHERE f.order_id=ANY(%s) AND f.active AND {TREATED}
|
||||||
|
ORDER BY f.item_index''', (ids,)).fetchall()
|
||||||
|
# Each order's reworks (D-02 to D-04), with the names of who opened,
|
||||||
|
# decided and printed.
|
||||||
|
reworks = c.execute(f'''SELECT r.*, {person('r.opened_by')} AS opened_name, {person('r.decided_by')} AS decided_name,
|
||||||
|
{person('r.printed_by')} AS printed_name FROM dtf_local.reworks r WHERE r.order_id=ANY(%s) ORDER BY r.id''',
|
||||||
|
(ids,)).fetchall()
|
||||||
|
# Why each order was last sent to correction, for the notice to the customer.
|
||||||
|
reasons = {row['order_id']: row['reason'] for row in c.execute('''SELECT DISTINCT ON (order_id) order_id,reason
|
||||||
|
FROM dtf_local.movements WHERE order_id=ANY(%s) AND to_state='cor' ORDER BY order_id,id DESC''', (ids,)).fetchall()}
|
||||||
|
# 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,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'])
|
||||||
|
# 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
|
||||||
|
order['print_files'] = [row for row in generated if row['order_id'] == order['id']]
|
||||||
|
order['prumo'] = prumo.report(order, uploads)
|
||||||
|
approved = [row for row in finals if row['order_id'] == order['id']]
|
||||||
|
order['final_items'] = sorted({row['item_index'] for row in approved})
|
||||||
|
# The approved finals themselves: "Tratar a arte" keeps those it does not replace.
|
||||||
|
order['finals'] = [{'item_index': row['item_index'], 'upload_id': row['upload_id']} for row in approved]
|
||||||
|
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')}
|
||||||
|
for row in fixes if row['order_id'] == order['id']]
|
||||||
|
order['reworks'] = [row for row in reworks if row['order_id'] == order['id']]
|
||||||
|
return assign_machines(c, orders)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get('/api/operator/orders/finished')
|
||||||
|
def finished_page(before_finished_at: datetime | None = None, before_id: UUID | None = None,
|
||||||
|
limit: int = Query(default=50, ge=1, le=100), user=Depends(operator)):
|
||||||
|
"""Older finished orders, newest first, beyond the board's recent window."""
|
||||||
|
paged = cursor_pair(before_finished_at, before_id)
|
||||||
|
with db.connect() as c:
|
||||||
|
rows = c.execute('''SELECT * FROM (
|
||||||
|
SELECT o.*, COALESCE((SELECT max(m.created_at) FROM dtf_local.movements m
|
||||||
|
WHERE m.order_id=o.id AND m.to_state='fin' AND NOT m.back), o.updated_at) AS finished_at
|
||||||
|
FROM dtf_local.orders o WHERE o.state='fin' AND o.parent_id IS NULL
|
||||||
|
) f ''' + ('WHERE (finished_at,id)<(%s,%s) ' if paged else '') + '''
|
||||||
|
ORDER BY finished_at DESC,id DESC LIMIT %s''',
|
||||||
|
((before_finished_at, before_id) if paged else ()) + (limit + 1,)).fetchall()
|
||||||
|
orders = with_print_files(c, rows[:limit])
|
||||||
|
return {'orders': orders, 'has_more': len(rows) > limit, 'thumbnails': thumbnails(c, orders),
|
||||||
|
'names': company_names(c, orders)}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get('/api/operator/orders/{uid}/history')
|
||||||
|
def history(uid: UUID, user=Depends(operator)):
|
||||||
|
with db.connect() as c:
|
||||||
|
return c.execute('SELECT * FROM dtf_local.movements WHERE order_id=%s ORDER BY id', (uid,)).fetchall()
|
||||||
|
|
||||||
|
@router.get('/api/operator/uploads/{uid}/thumbnail')
|
||||||
|
def thumbnail(uid: UUID, user=Depends(operator)):
|
||||||
|
"""The browser-made picture of an artwork. Cached by the operator's browser:
|
||||||
|
the board is redrawn on every refresh."""
|
||||||
|
with db.connect() as c:
|
||||||
|
row = c.execute('SELECT mime,data FROM dtf_local.upload_thumbnails WHERE upload_id=%s', (uid,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(404, 'No picture for this upload')
|
||||||
|
return Response(bytes(row['data']), media_type=row['mime'],
|
||||||
|
headers={'Cache-Control': 'private, max-age=86400', 'Content-Disposition': 'inline'})
|
||||||
91
app/api/operator/common.py
Normal file
91
app/api/operator/common.py
Normal file
@@ -0,0 +1,91 @@
|
|||||||
|
"""Helpers and constants shared by more than one Kanban router."""
|
||||||
|
import re
|
||||||
|
|
||||||
|
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()
|
||||||
|
|
||||||
|
# A quote that can still become an order: waiting for review, or approved and
|
||||||
|
# not expired yet. The worker marks it expired at 24 h (app/unpaid.py); until
|
||||||
|
# then it stays, even past the payment window while an attempt is still live.
|
||||||
|
LIVE_QUOTE = "(q.discarded_at IS NULL AND q.expired_at IS NULL)"
|
||||||
|
|
||||||
|
def uploads_of(rows):
|
||||||
|
"""Every upload id an order (its snapshot) or a quote (its draft) refers to."""
|
||||||
|
ids = set()
|
||||||
|
for row in rows:
|
||||||
|
content = row.get('snapshot') or row.get('draft') or {}
|
||||||
|
for item in content.get('items') or []:
|
||||||
|
ids.update(str(uid) for uid in item.get('uploads') or [])
|
||||||
|
return ids
|
||||||
|
|
||||||
|
|
||||||
|
def thumbnails(c, *groups):
|
||||||
|
"""The uploads among these orders and quotes that have an artwork picture,
|
||||||
|
so the Kanban asks only for pictures that exist."""
|
||||||
|
ids = set().union(*(uploads_of(rows) for rows in groups))
|
||||||
|
if not ids:
|
||||||
|
return []
|
||||||
|
rows = c.execute('SELECT upload_id FROM dtf_local.upload_thumbnails WHERE upload_id=ANY(%s::uuid[])',
|
||||||
|
(list(ids),)).fetchall()
|
||||||
|
return [str(r['upload_id']) for r in rows]
|
||||||
|
|
||||||
|
|
||||||
|
def company_names(c, *groups):
|
||||||
|
"""The registry's company names for these orders' and quotes' CNPJs (app/cnpj.py)."""
|
||||||
|
return cnpj.names(c, [((row.get('snapshot') or row.get('draft') or {}).get('customer') or {}).get('cnpj')
|
||||||
|
for rows in groups for row in rows])
|
||||||
|
|
||||||
|
|
||||||
|
def person(column):
|
||||||
|
"""SQL: the team member's name for the e-mail in `column`, or the e-mail."""
|
||||||
|
return f'COALESCE((SELECT op.name FROM dtf_local.operators op WHERE op.email={column}), {column})'
|
||||||
|
|
||||||
|
|
||||||
|
def cursor_pair(first, second):
|
||||||
|
if (first is None) != (second is None):
|
||||||
|
raise HTTPException(422, 'Both cursor fields are required')
|
||||||
|
return first is not None
|
||||||
|
|
||||||
|
|
||||||
|
MODES = {'textil': {'file', 'avulsa', 'premium'}, 'uv': {'uvfile', 'uv'},
|
||||||
|
'folha': {'file', 'uvfile', 'premium'}, 'avulsa': {'avulsa', 'uv'}}
|
||||||
|
|
||||||
|
|
||||||
|
def like(text):
|
||||||
|
"""A LIKE pattern that matches the text anywhere, its own % and _ literal."""
|
||||||
|
return '%' + re.sub(r'([\\%_])', r'\\\1', text) + '%'
|
||||||
|
|
||||||
|
|
||||||
|
def numeric(q):
|
||||||
|
"""The digits of a query made of digits and punctuation only ("#1042",
|
||||||
|
"11.222.333/0001-81", "(16) 99999-0000"); empty when it has letters."""
|
||||||
|
return '' if re.search(r'[^\W\d_]', q) else re.sub(r'\D', '', q)
|
||||||
|
|
||||||
|
|
||||||
|
def customer_match(column, q):
|
||||||
|
"""SQL and parameters matching a customer (e-mail, company name, CNPJ or
|
||||||
|
WhatsApp) in an order snapshot or a quote draft. CNPJ and phone match by
|
||||||
|
their digits, and only when nothing but digits and punctuation was typed:
|
||||||
|
the digits of an e-mail address are not a phone number."""
|
||||||
|
text, digits = q.strip().lower(), numeric(q)
|
||||||
|
cnpj = f"regexp_replace(coalesce({column}->'customer'->>'cnpj',''),'\\D','','g')"
|
||||||
|
sql = (f"lower({column}->'customer'->>'mail') LIKE %s OR {cnpj} IN (SELECT n.cnpj FROM dtf_local.cnpj_names n"
|
||||||
|
" WHERE lower(n.legal_name) LIKE %s OR lower(n.trade_name) LIKE %s)")
|
||||||
|
params = [like(text)] * 3
|
||||||
|
if len(digits) >= 3:
|
||||||
|
sql += (f" OR regexp_replace(coalesce({column}->'customer'->>'cnpj',''),'\\D','','g') LIKE %s"
|
||||||
|
f" OR regexp_replace(coalesce({column}->'customer'->>'zap',''),'\\D','','g') LIKE %s")
|
||||||
|
params += [like(digits), like(digits)]
|
||||||
|
return '(' + sql + ')', params
|
||||||
|
|
||||||
|
|
||||||
|
# Real work only: an operator's test order and a cancelled one are not production.
|
||||||
|
# A proof card (app/proof.py) is no sale either.
|
||||||
|
REAL_ORDER = "o.cancelled_at IS NULL AND COALESCE(o.payment->>'provider','') <> 'teste' AND o.parent_id IS NULL"
|
||||||
|
# Where orders come from (D-21), in the order Números lists them.
|
||||||
|
ORIGINS = ('site', 'dropflow', 'atendimento')
|
||||||
256
app/api/operator/files.py
Normal file
256
app/api/operator/files.py
Normal file
@@ -0,0 +1,256 @@
|
|||||||
|
"""The print room's files: queue, folders, downloads and the order viewer."""
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
from typing import Literal
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
|
from pydantic import Field
|
||||||
|
|
||||||
|
from ... import hotfolder, receipt
|
||||||
|
from ...core import db
|
||||||
|
from ...core.auth import audit, can, operator
|
||||||
|
from ...core.models import StrictModel
|
||||||
|
from ...printjobs import file_prefix
|
||||||
|
from ...runtime import storage
|
||||||
|
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
|
||||||
|
readable, with a link straight to storage."""
|
||||||
|
files, names = [], set()
|
||||||
|
for row in rows:
|
||||||
|
prefix = file_prefix(row['number'], row['item_index'])
|
||||||
|
# Generated before 2026-10-23, a file was called pedido-23-item-1.
|
||||||
|
older = f"pedido-{row['number']}-item-{row['item_index'] + 1}"
|
||||||
|
name = row['name']
|
||||||
|
if name.startswith(older):
|
||||||
|
name = prefix + name[len(older):]
|
||||||
|
# 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
|
||||||
|
while name in names:
|
||||||
|
name = f'{stem} ({copy}).{ext}' if dot else f'{ext} ({copy})'
|
||||||
|
copy += 1
|
||||||
|
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, FOLDER_LINK_SECONDS)})
|
||||||
|
return files
|
||||||
|
|
||||||
|
|
||||||
|
def print_ready(c, states, only=None, paid_after=None):
|
||||||
|
"""The file to print for each item of the orders in these stages, in queue
|
||||||
|
order: the approved final, or before approval the generated print file
|
||||||
|
(unless the customer has sent a correction since). `only` narrows it to
|
||||||
|
these orders, `paid_after` to the orders paid since then."""
|
||||||
|
ids = None if only is None else list(only)
|
||||||
|
rows = c.execute(f'''SELECT o.id AS order_id,o.state,o.number,f.item_index,f.upload_id,u.object_key,u.name,
|
||||||
|
COALESCE(o.queue_key, extract(epoch FROM o.created_at)) AS position, 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)), 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
|
||||||
|
JOIN dtf_local.uploads u ON u.id=pp.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.state IN ('rec','tra') AND o.cancelled_at IS NULL AND p.status='ready'
|
||||||
|
AND u.expires_at>now() AND u.purged_at IS NULL AND u.scan_state='clean'
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM dtf_local.order_files f WHERE f.order_id=o.id AND f.kind='final'
|
||||||
|
AND f.active AND f.item_index=p.item_index)
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM dtf_local.order_files f WHERE f.order_id=o.id AND f.kind='correction')
|
||||||
|
ORDER BY position,order_id,item_index,part NULLS LAST,name''',
|
||||||
|
(list(states), ids, ids, paid_after, paid_after, list(states), ids, ids, paid_after, paid_after)).fetchall()
|
||||||
|
return rows
|
||||||
|
|
||||||
|
|
||||||
|
@router.get('/api/operator/orders/{uid}/view')
|
||||||
|
def view_files(uid: UUID, user=Depends(operator)):
|
||||||
|
"""What "Abrir e conferir" shows (item 7): each item's generated PNG, part
|
||||||
|
by part, with links to its pieces, then the customer's originals, which
|
||||||
|
have only their picture."""
|
||||||
|
with db.connect() as c:
|
||||||
|
order = c.execute('SELECT snapshot FROM dtf_local.orders WHERE id=%s', (uid,)).fetchone()
|
||||||
|
if not order:
|
||||||
|
raise HTTPException(404, 'Pedido não encontrado.')
|
||||||
|
made = c.execute('''SELECT item_index, detail FROM dtf_local.print_files WHERE order_id=%s AND status='ready'
|
||||||
|
ORDER BY item_index''', (uid,)).fetchall()
|
||||||
|
parts = c.execute('''SELECT p.item_index, p.part, p.upload_id, u.name FROM dtf_local.print_parts p
|
||||||
|
JOIN dtf_local.uploads u ON u.id=p.upload_id WHERE p.order_id=%s AND u.purged_at IS NULL
|
||||||
|
ORDER BY p.item_index, p.part''', (uid,)).fetchall()
|
||||||
|
pictured = {str(r['upload_id']) for r in c.execute(
|
||||||
|
'SELECT upload_id FROM dtf_local.upload_thumbnails WHERE upload_id=ANY(%s)',
|
||||||
|
([UUID(u) for item in order['snapshot']['items'] for u in item['uploads']],)).fetchall()}
|
||||||
|
items = order['snapshot']['items']
|
||||||
|
many = len(items) > 1
|
||||||
|
files = []
|
||||||
|
for row in made:
|
||||||
|
mine = [p for p in parts if p['item_index'] == row['item_index']]
|
||||||
|
details = {d.get('name'): d for d in row['detail'].get('parts') or []}
|
||||||
|
for part in mine:
|
||||||
|
tiles = (details.get(part['name']) or {}).get('tiles')
|
||||||
|
label = (f"Item {row['item_index'] + 1}" if many else 'Arquivo') + \
|
||||||
|
(f" · parte {part['part']}/{len(mine)}" if len(mine) > 1 else '')
|
||||||
|
files.append({'name': part['name'], 'label': label, 'item': row['item_index'],
|
||||||
|
'manifest': tiles and {**tiles, 'urls': [
|
||||||
|
[storage.view(f"originals/tiles/{part['upload_id']}/{k}/{i}.png", 'image/png')
|
||||||
|
for i in range(level['strips'])] for k, level in enumerate(tiles['levels'])]}})
|
||||||
|
for index, item in enumerate(items):
|
||||||
|
for n, upload in enumerate(item['uploads']):
|
||||||
|
files.append({'name': ('Original ' + str(n + 1)) if len(item['uploads']) > 1 else 'Original',
|
||||||
|
'label': (f'Item {index + 1} · ' if many else '') + 'original' +
|
||||||
|
(f' {n + 1}' if len(item['uploads']) > 1 else ''),
|
||||||
|
'item': index, 'manifest': None,
|
||||||
|
'picture': f'/api/operator/uploads/{upload}/thumbnail' if upload in pictured else None})
|
||||||
|
return {'files': files}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get('/api/operator/orders/{uid}/folder-files')
|
||||||
|
def folder_files(uid: UUID, user=Depends(can('produce'))):
|
||||||
|
"""What each item's file is called in the order's stage folder, as the
|
||||||
|
automatic folders save it: "Tratar a arte" shows where to open it."""
|
||||||
|
with db.connect() as c:
|
||||||
|
row = c.execute('SELECT state FROM dtf_local.orders WHERE id=%s', (uid,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(404, 'Pedido não encontrado.')
|
||||||
|
files = named_files(print_ready(c, (row['state'],), only=[uid]))
|
||||||
|
return {'state': row['state'], 'files': [{'item': f['item'], 'name': f['name']} for f in files]}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get('/api/operator/queue/finals')
|
||||||
|
def queue_finals(auto: bool = False, user=Depends(can('print'))):
|
||||||
|
"""The approved final files of every order in the print queue (Arte
|
||||||
|
conferida). The browser downloads them straight from storage: a zip of
|
||||||
|
multi-GB sheets would go through the server."""
|
||||||
|
with db.connect() as c:
|
||||||
|
files = named_files(print_ready(c, ('tra',)))
|
||||||
|
# The automatic folder asks whenever the queue changes; only a person's download is logged.
|
||||||
|
if not auto:
|
||||||
|
audit('queue_finals_downloaded', operator=user, files=len(files))
|
||||||
|
return {'files': files}
|
||||||
|
|
||||||
|
|
||||||
|
class FolderSync(StrictModel):
|
||||||
|
early: bool = False
|
||||||
|
held: list[UUID] = Field(default_factory=list, max_length=1000)
|
||||||
|
# When the folders were chosen: the orders paid since are fetched whatever
|
||||||
|
# their stage, so what passed while the computer was off is not lost.
|
||||||
|
since: datetime | None = None
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/queue/hot')
|
||||||
|
def queue_hot(user=Depends(can('print'))):
|
||||||
|
"""For a computer with the automatic folders: the parts it should write
|
||||||
|
into the machines' hot folders now, claimed for it alone; those written
|
||||||
|
and not yet taken by Flexi, to see whether they still are; and those to
|
||||||
|
delete, withdrawn from cards that left Imprimindo (item 10)."""
|
||||||
|
with db.connect() as c:
|
||||||
|
due = hotfolder.claim(c, user)
|
||||||
|
keys = {str(r['upload_id']): r['object_key'] for r in c.execute(
|
||||||
|
'SELECT id AS upload_id, object_key FROM dtf_local.uploads WHERE id=ANY(%s)',
|
||||||
|
([r['upload_id'] for r in due],)).fetchall()} if due else {}
|
||||||
|
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'], 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']}
|
||||||
|
for r in watched if r['state'] == 'withdraw']}
|
||||||
|
|
||||||
|
|
||||||
|
class HotReport(StrictModel):
|
||||||
|
state: Literal['written', 'released', 'consumed', 'gone']
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/queue/hot/{part_id}')
|
||||||
|
def report_hot(part_id: int, body: HotReport, user=Depends(can('print'))):
|
||||||
|
"""What a computer saw of a part: written, not written, taken by Flexi,
|
||||||
|
or deleted after it was withdrawn."""
|
||||||
|
with db.connect() as c:
|
||||||
|
applied = hotfolder.report(c, part_id, body.state, user)
|
||||||
|
if applied and body.state == 'written':
|
||||||
|
audit('hot_folder_written', part=part_id, operator=user)
|
||||||
|
return {'ok': applied}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/queue/folder')
|
||||||
|
def queue_folder(body: FolderSync, user=Depends(can('print'))):
|
||||||
|
"""What the Kanban's automatic folders should hold. `early` is Dropstar's
|
||||||
|
stage folders (2026-10-26): the files of orders in Arte recebida and Arte
|
||||||
|
conferida, and, for the orders the folders already hold, their files while
|
||||||
|
they print, are checked in Revisão and sit in Finalizado, so one taken out
|
||||||
|
of a folder can be fetched again when the order moves on. With `since`,
|
||||||
|
also every order paid after the folders were chosen, whatever its stage:
|
||||||
|
a computer that was off catches up on what passed meanwhile (Dropstar's
|
||||||
|
rules, 2026-10-26). Without it, only
|
||||||
|
the queue's (Firefox's downloads). `states` answers for the orders the
|
||||||
|
folders hold files of: a stage, 'cancelled', or nothing when the order was
|
||||||
|
deleted, so their files can be removed."""
|
||||||
|
with db.connect() as c:
|
||||||
|
rows = print_ready(c, ('rec', 'tra') if body.early else ('tra',))
|
||||||
|
if body.early and body.held:
|
||||||
|
rows += print_ready(c, ('imp', 'rev', 'fin'), only=body.held)
|
||||||
|
if body.early and body.since:
|
||||||
|
seen = {(r['order_id'], r['item_index'], r['upload_id']) for r in rows}
|
||||||
|
rows += [r for r in print_ready(c, ('imp', 'rev', 'fin'), paid_after=body.since)
|
||||||
|
if (r['order_id'], r['item_index'], r['upload_id']) not in seen]
|
||||||
|
files = named_files(rows)
|
||||||
|
held = c.execute('SELECT id,state,cancelled_at FROM dtf_local.orders WHERE id=ANY(%s)',
|
||||||
|
(body.held,)).fetchall() if body.held else []
|
||||||
|
# The pickup receipts no computer saved yet (item 14), due since the
|
||||||
|
# folders were chosen: one that was off catches up, like the files.
|
||||||
|
due = c.execute('''SELECT id, number FROM dtf_local.orders WHERE receipt_due_at IS NOT NULL
|
||||||
|
AND receipt_saved_at IS NULL AND cancelled_at IS NULL AND (%s::timestamptz IS NULL OR receipt_due_at>=%s)
|
||||||
|
ORDER BY receipt_due_at''', (body.since, body.since)).fetchall() if body.early else []
|
||||||
|
# The review photos and videos to copy into Revisões/ (front 2). Without
|
||||||
|
# `since`, the last 30 days, so a new computer catches up.
|
||||||
|
since = body.since or datetime.now(timezone.utc) - timedelta(days=30)
|
||||||
|
review_rows = c.execute('''SELECT r.id,r.order_id,o.number,r.upload_id,u.name
|
||||||
|
FROM dtf_local.order_reviews r
|
||||||
|
JOIN dtf_local.orders o ON o.id=r.order_id
|
||||||
|
JOIN dtf_local.uploads u ON u.id=r.upload_id
|
||||||
|
WHERE o.cancelled_at IS NULL AND r.created_at>=%s ORDER BY r.created_at,r.id''', (since,)).fetchall()
|
||||||
|
return {'files': files,
|
||||||
|
'states': {str(o['id']): 'cancelled' if o['cancelled_at'] else o['state'] for o in held},
|
||||||
|
'receipts': [{'order': str(o['id']), 'number': o['number'], 'name': receipt.file_name(o)} for o in due],
|
||||||
|
'reviews': [{'id': r['id'], 'order': str(r['order_id']), 'number': r['number'],
|
||||||
|
'upload_id': str(r['upload_id']), 'name': r['name']} for r in review_rows]}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get('/api/operator/uploads/{uid}/download')
|
||||||
|
def download(uid: UUID, order_id: UUID | None = None, user=Depends(operator)):
|
||||||
|
with db.connect() as c:
|
||||||
|
row = c.execute('SELECT * FROM dtf_local.uploads WHERE id=%s AND complete', (uid,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(404, 'Completed upload not found')
|
||||||
|
if row['expires_at'] <= datetime.now(timezone.utc):
|
||||||
|
raise HTTPException(410, 'Artwork retention expired')
|
||||||
|
require_clean(row)
|
||||||
|
name = row['name']
|
||||||
|
if order_id:
|
||||||
|
order = c.execute('SELECT number,snapshot FROM dtf_local.orders WHERE id=%s', (order_id,)).fetchone()
|
||||||
|
if not order:
|
||||||
|
raise HTTPException(404, 'Pedido não encontrado.')
|
||||||
|
originals = [upload for item in order['snapshot']['items'] for upload in item['uploads']]
|
||||||
|
if str(uid) not in originals:
|
||||||
|
raise HTTPException(422, 'Este arquivo não é original do pedido.')
|
||||||
|
index = originals.index(str(uid)) + 1
|
||||||
|
suffix = row['name'].rsplit('.', 1)[-1].lower() if '.' in row['name'] else 'bin'
|
||||||
|
name = f'DTF-{order["number"]}-original-{index}.{suffix}'
|
||||||
|
return {'name':name, 'url':storage.download(row['object_key'],name), 'expires_in':300}
|
||||||
236
app/api/operator/integrations.py
Normal file
236
app/api/operator/integrations.py
Normal file
@@ -0,0 +1,236 @@
|
|||||||
|
"""Integrations: freight, backup, payment events, Tiny and Mercado Pago."""
|
||||||
|
import os
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from typing import Literal
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||||
|
from fastapi.responses import RedirectResponse
|
||||||
|
|
||||||
|
from ... import tiny
|
||||||
|
from ...core import db
|
||||||
|
from ...core.auth import audit, can
|
||||||
|
from ...core.models import Resolution
|
||||||
|
from ...runtime import freight, payment
|
||||||
|
from .common import thumbnails
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
def freight_status():
|
||||||
|
"""What delivery the Site offers, and the package rule it prices with."""
|
||||||
|
real = [carrier for carrier in freight.carriers if carrier.name != 'fake']
|
||||||
|
status = {'carriers': [carrier.name for carrier in real], 'services': freight.services if real else {}}
|
||||||
|
if real:
|
||||||
|
# One package for every carrier (app/package.py).
|
||||||
|
status.update(real[0].status())
|
||||||
|
return status
|
||||||
|
|
||||||
|
|
||||||
|
def backup_status(c):
|
||||||
|
"""The latest database backup and the latest run, which may have failed."""
|
||||||
|
ok = c.execute('''SELECT finished_at,bytes FROM dtf_local.backups WHERE status='ok'
|
||||||
|
ORDER BY finished_at DESC LIMIT 1''').fetchone()
|
||||||
|
last = c.execute('SELECT started_at,finished_at,status,detail FROM dtf_local.backups ORDER BY finished_at DESC LIMIT 1').fetchone()
|
||||||
|
asked = c.execute('''SELECT 1 FROM dtf_local.backup_requests WHERE requested_at>%s LIMIT 1''',
|
||||||
|
(last['started_at'] if last else datetime(2000, 1, 1, tzinfo=timezone.utc),)).fetchone()
|
||||||
|
return {'last_ok': ok['finished_at'].isoformat() if ok else None, 'bytes': ok['bytes'] if ok else None,
|
||||||
|
'failed': last['detail'] if last and last['status'] == 'failed' else None,
|
||||||
|
'failed_at': last['finished_at'].isoformat() if last and last['status'] == 'failed' else None,
|
||||||
|
'requested': asked is not None}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/backup/run')
|
||||||
|
def backup_now(user=Depends(can('integrations'))):
|
||||||
|
"""A backup now, outside the daily hour: the backup service, which alone
|
||||||
|
may read the whole database, starts it within a minute."""
|
||||||
|
with db.connect() as c:
|
||||||
|
c.execute('INSERT INTO dtf_local.backup_requests(requested_by) VALUES(%s)', (user,))
|
||||||
|
audit('backup_requested', operator=user)
|
||||||
|
return {'ok': True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get('/api/operator/payment-events')
|
||||||
|
def payment_events(state: Literal['open','resolved','all'] = 'open',
|
||||||
|
offset: int = Query(default=0, ge=0),
|
||||||
|
limit: int = Query(default=20, ge=1, le=100), user=Depends(can('payments'))):
|
||||||
|
"""Payments that needed a person, newest first: open ones to act on, resolved ones as history."""
|
||||||
|
where = {'open': 'AND resolved_at IS NULL', 'resolved': 'AND resolved_at IS NOT NULL', 'all': ''}[state]
|
||||||
|
with db.connect() as c:
|
||||||
|
rows = c.execute('''SELECT id,provider,event_id,reference,status,amount_cents,received_at,outcome,
|
||||||
|
resolved_at,resolved_by,resolution
|
||||||
|
FROM dtf_local.payment_events WHERE (outcome LIKE 'refused%%' OR outcome LIKE 'attention%%') ''' + where + '''
|
||||||
|
ORDER BY received_at DESC,id DESC LIMIT %s OFFSET %s''', (limit, offset)).fetchall()
|
||||||
|
total = c.execute('''SELECT count(*) AS n FROM dtf_local.payment_events
|
||||||
|
WHERE (outcome LIKE 'refused%' OR outcome LIKE 'attention%') ''' + where).fetchone()['n']
|
||||||
|
for row in rows:
|
||||||
|
row.update(payment_context(c, row))
|
||||||
|
return {'issues': rows, 'total': total, 'thumbnails': thumbnails(c, [r['quote'] for r in rows if r.get('quote')])}
|
||||||
|
|
||||||
|
|
||||||
|
def payment_context(c, row):
|
||||||
|
"""Who tried to pay and for what: the quote the payment points to (its
|
||||||
|
customer, items and total), its order if there is one, the method of the
|
||||||
|
last attempt and Mercado Pago's own words about the payment."""
|
||||||
|
payload = c.execute('SELECT payload FROM dtf_local.payment_events WHERE id=%s', (row['id'],)).fetchone()['payload'] or {}
|
||||||
|
out = {'payment_id': payload.get('payment_id'), 'status_detail': payload.get('status_detail'), 'quote': None, 'order': None, 'method': None}
|
||||||
|
try:
|
||||||
|
quote_id = UUID(str(row.get('reference') or ''))
|
||||||
|
except ValueError:
|
||||||
|
return out
|
||||||
|
quote = c.execute('SELECT id,draft,approved,created_at,approved_at FROM dtf_local.quotes WHERE id=%s', (quote_id,)).fetchone()
|
||||||
|
if not quote:
|
||||||
|
return out
|
||||||
|
out['quote'] = {'id': quote['id'], 'draft': quote['draft'], 'created_at': quote['created_at'], 'approved_at': quote['approved_at'],
|
||||||
|
'total_cents': (quote['approved'] or {}).get('total_cents')}
|
||||||
|
out['order'] = c.execute('SELECT id,number,state,cancelled_at FROM dtf_local.orders WHERE quote_id=%s', (quote_id,)).fetchone()
|
||||||
|
attempt = c.execute('''SELECT method,status FROM dtf_local.payment_intents WHERE quote_id=%s
|
||||||
|
ORDER BY created_at DESC LIMIT 1''', (quote_id,)).fetchone()
|
||||||
|
out['method'] = attempt['method'] if attempt else None
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
@router.get('/api/operator/events')
|
||||||
|
def events(provider: Literal['tiny'] | None = None,
|
||||||
|
status: Literal['delivered','queued','failing'] | None = None,
|
||||||
|
event: Literal['payment_approved','production_started','correction_needed','ready','cancelled'] | None = None,
|
||||||
|
order: int | None = Query(default=None, ge=1), offset: int = Query(default=0, ge=0),
|
||||||
|
limit: int = Query(default=20, ge=1, le=100), user=Depends(can('integrations'))):
|
||||||
|
"""The integration send log, newest first, filtered, by page with a total."""
|
||||||
|
clauses, params = [], []
|
||||||
|
if provider:
|
||||||
|
clauses.append('provider=%s'); params.append(provider)
|
||||||
|
if status == 'delivered':
|
||||||
|
clauses.append('delivered_at IS NOT NULL')
|
||||||
|
elif status == 'queued':
|
||||||
|
clauses.append('delivered_at IS NULL AND last_error IS NULL')
|
||||||
|
elif status == 'failing':
|
||||||
|
clauses.append('delivered_at IS NULL AND last_error IS NOT NULL')
|
||||||
|
if event:
|
||||||
|
clauses.append("payload->>'event'=%s"); params.append(event)
|
||||||
|
if order:
|
||||||
|
clauses.append("payload->>'number'=%s"); params.append(str(order))
|
||||||
|
where = ('WHERE ' + ' AND '.join(clauses)) if clauses else ''
|
||||||
|
with db.connect() as c:
|
||||||
|
rows = c.execute(f'SELECT * FROM dtf_local.outbox {where} ORDER BY id DESC LIMIT %s OFFSET %s',
|
||||||
|
(*params, limit, offset)).fetchall()
|
||||||
|
total = c.execute(f'SELECT count(*) AS n FROM dtf_local.outbox {where}', params).fetchone()['n']
|
||||||
|
return {'events': rows, 'total': total}
|
||||||
|
|
||||||
|
@router.post('/api/operator/payment-events/{uid}/resolve')
|
||||||
|
def resolve_payment(uid: UUID, body: Resolution, user=Depends(can('manage'))):
|
||||||
|
with db.connect() as c:
|
||||||
|
row = c.execute('''UPDATE dtf_local.payment_events SET resolved_at=now(), resolved_by=%s, resolution=%s
|
||||||
|
WHERE id=%s AND (outcome LIKE 'refused%%' OR outcome LIKE 'attention%%') AND resolved_at IS NULL RETURNING id''',
|
||||||
|
(user, body.note, uid)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(404, 'No open payment issue with this id')
|
||||||
|
audit('payment_issue_resolved', payment_event=str(uid), operator=user)
|
||||||
|
return {'ok': True}
|
||||||
|
|
||||||
|
def tiny_status(c=None):
|
||||||
|
if not tiny.configured():
|
||||||
|
return {'configured': False}
|
||||||
|
return {'configured': True, 'orders_enabled': os.environ.get('TINY_ADAPTER') == 'tiny',
|
||||||
|
**tiny.TinyAuth().status(c)}
|
||||||
|
|
||||||
|
@router.get('/api/operator/tiny/contacts')
|
||||||
|
def tiny_contacts(q: str = Query(min_length=1, max_length=120), user=Depends(can('assemble'))):
|
||||||
|
"""The Tiny contacts a Venda customer is picked from (Fase 2, front
|
||||||
|
7a.3): by name, or by CPF/CNPJ when only digits were typed. The fake
|
||||||
|
adapter answers with two fixed contacts on the local stack and in CI."""
|
||||||
|
if os.environ.get('TINY_ADAPTER') != 'tiny':
|
||||||
|
from ...adapters import FakeTiny
|
||||||
|
return FakeTiny().search_contacts(q)
|
||||||
|
if not tiny.configured():
|
||||||
|
raise HTTPException(409, 'O Tiny não está conectado.')
|
||||||
|
try:
|
||||||
|
return tiny.search_contacts(tiny.TinyOrders(), q)
|
||||||
|
except tiny.TinyNotConnected:
|
||||||
|
raise HTTPException(409, 'O Tiny não está conectado.')
|
||||||
|
|
||||||
|
|
||||||
|
@router.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."""
|
||||||
|
if not tiny.configured():
|
||||||
|
raise HTTPException(503, 'Tiny application is not configured')
|
||||||
|
audit('tiny_connect_started', operator=user)
|
||||||
|
return {'url': tiny.TinyAuth().authorize_url(user)}
|
||||||
|
|
||||||
|
@router.post('/api/operator/tiny/test')
|
||||||
|
def tiny_test(user=Depends(can('integrations'))):
|
||||||
|
"""Read one order and one contact from Tiny. Creates nothing."""
|
||||||
|
if not tiny.configured():
|
||||||
|
raise HTTPException(503, 'Tiny application is not configured')
|
||||||
|
try:
|
||||||
|
results = tiny.check()
|
||||||
|
except tiny.TinyNotConnected as exc:
|
||||||
|
raise HTTPException(409, str(exc))
|
||||||
|
audit('tiny_tested', operator=user, ok=all(v == 'ok' for v in results.values()))
|
||||||
|
return {'ok': all(v == 'ok' for v in results.values()), 'results': results}
|
||||||
|
|
||||||
|
@router.post('/api/operator/mercadopago/check')
|
||||||
|
def mercadopago_check(user=Depends(can('integrations'))):
|
||||||
|
"""The Mercado Pago account behind the configured token; reads only."""
|
||||||
|
if payment.name != 'mercadopago':
|
||||||
|
raise HTTPException(409, 'Mercado Pago não está configurado')
|
||||||
|
from ..mercadopago_probe import check
|
||||||
|
audit('mercadopago_check', operator=user)
|
||||||
|
result = check(payment.access_token)
|
||||||
|
# Whether Mercado Pago's notifications reach this server and pass the
|
||||||
|
# signature: every accepted one is recorded, a refused one is audited.
|
||||||
|
with db.connect() as c:
|
||||||
|
received = c.execute('''SELECT count(*) AS n, max(received_at) AS last FROM dtf_local.payment_events
|
||||||
|
WHERE provider='mercadopago' AND received_at > now()-interval '24 hours' ''').fetchone()
|
||||||
|
last = c.execute('''SELECT received_at,status,outcome FROM dtf_local.payment_events
|
||||||
|
WHERE provider='mercadopago' ORDER BY received_at DESC LIMIT 1''').fetchone()
|
||||||
|
refused = c.execute('''SELECT count(*) AS n FROM dtf_local.security_events
|
||||||
|
WHERE event='payment_webhook_rejected' AND created_at > now()-interval '24 hours' ''').fetchone()
|
||||||
|
result['webhooks'] = {'accepted_24h': received['n'], 'refused_24h': refused['n'], 'last': last}
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
@router.get('/api/operator/tiny/callback')
|
||||||
|
def tiny_callback(code: str = Query('', max_length=4096), state: str = Query('', max_length=128),
|
||||||
|
error: str = Query('', max_length=128)):
|
||||||
|
"""Tiny's redirect back. Cross-site, so the operator cookie is absent: the
|
||||||
|
single-use state an operator created is what authorises it. Tiny reports a
|
||||||
|
refusal (the operator declined, or offline access is not allowed for this
|
||||||
|
application) with `error` instead of a code."""
|
||||||
|
if not tiny.configured():
|
||||||
|
raise HTTPException(503, 'Tiny application is not configured')
|
||||||
|
try:
|
||||||
|
if error == 'invalid_scope':
|
||||||
|
retry = tiny.TinyAuth().without_offline(state)
|
||||||
|
audit('tiny_offline_refused')
|
||||||
|
return RedirectResponse(retry, status_code=303)
|
||||||
|
if error or not code:
|
||||||
|
raise tiny.TinyError(f'Tiny returned {error or "no code"}')
|
||||||
|
who = tiny.TinyAuth().complete(code, state)
|
||||||
|
except tiny.TinyError:
|
||||||
|
audit('tiny_connect_failed')
|
||||||
|
return RedirectResponse('/?tiny=failed', status_code=303)
|
||||||
|
audit('tiny_connected', operator=who)
|
||||||
|
return RedirectResponse('/?tiny=connected', status_code=303)
|
||||||
81
app/api/operator/labels.py
Normal file
81
app/api/operator/labels.py
Normal file
@@ -0,0 +1,81 @@
|
|||||||
|
"""The 10x15 thermal label at Finalizado (Fase 2, front 10; Marcus, 2026-11-10).
|
||||||
|
|
||||||
|
The label page is rendered by the server; one computer prints it automatically
|
||||||
|
(the first claim), and the Expedição profile or the Revisor may reprint it.
|
||||||
|
"""
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, Response
|
||||||
|
|
||||||
|
from ... import label
|
||||||
|
from ...core import db
|
||||||
|
from ...core.auth import audit, can
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
def _order(c, uid, columns='number,state,cancelled_at'):
|
||||||
|
order = c.execute(f'SELECT {columns} FROM dtf_local.orders WHERE id=%s', (uid,)).fetchone()
|
||||||
|
if not order:
|
||||||
|
raise HTTPException(404, 'Pedido não encontrado.')
|
||||||
|
return order
|
||||||
|
|
||||||
|
|
||||||
|
def _tiny_number(c, uid):
|
||||||
|
"""The Tiny order number from the sale event's receipt, or None."""
|
||||||
|
row = c.execute("SELECT receipt->>'tiny_number' AS tiny_number FROM dtf_local.outbox WHERE event_key=%s",
|
||||||
|
(f'{uid}:paid:tiny',)).fetchone()
|
||||||
|
return row['tiny_number'] if row else None
|
||||||
|
|
||||||
|
|
||||||
|
def _finished(c, uid):
|
||||||
|
"""When the card reached Finalizado and who released it, from the movements."""
|
||||||
|
row = c.execute('''SELECT m.created_at,
|
||||||
|
COALESCE(NULLIF((SELECT o.name FROM dtf_local.operators o WHERE o.email=m.operator), ''),
|
||||||
|
m.operator) AS revisor
|
||||||
|
FROM dtf_local.movements m
|
||||||
|
WHERE m.order_id=%s AND m.to_state='fin' AND NOT m.back
|
||||||
|
ORDER BY m.created_at DESC, m.id DESC LIMIT 1''', (uid,)).fetchone()
|
||||||
|
return (row['created_at'], row['revisor']) if row else (None, None)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get('/api/operator/orders/{uid}/label')
|
||||||
|
def order_label(uid: UUID, user=Depends(can('label'))):
|
||||||
|
"""The printable label page (text/html), sized 100 x 150 mm."""
|
||||||
|
with db.connect() as c:
|
||||||
|
order = _order(c, uid, 'number,state,cancelled_at,updated_at,snapshot')
|
||||||
|
if order['cancelled_at'] or order['state'] != 'fin':
|
||||||
|
raise HTTPException(409, 'A etiqueta é impressa em Finalizado.')
|
||||||
|
tiny = _tiny_number(c, uid)
|
||||||
|
finished, revisor = _finished(c, uid)
|
||||||
|
fields = label.label_fields(order, tiny, finished or order['updated_at'], revisor)
|
||||||
|
return Response(label.label_html(fields), media_type='text/html; charset=utf-8',
|
||||||
|
headers={'Cache-Control': 'no-store'})
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/orders/{uid}/label/claim')
|
||||||
|
def claim_label(uid: UUID, user=Depends(can('label'))):
|
||||||
|
"""The first computer to ask prints the label; the unique partial index on
|
||||||
|
the 'auto' row decides, so two computers at once cannot both print it."""
|
||||||
|
with db.connect() as c:
|
||||||
|
order = _order(c, uid)
|
||||||
|
if order['cancelled_at'] or order['state'] != 'fin':
|
||||||
|
return {'print': False}
|
||||||
|
row = c.execute('''INSERT INTO dtf_local.label_prints(order_id,reason,printed_by)
|
||||||
|
VALUES(%s,'auto',%s) ON CONFLICT DO NOTHING RETURNING id''', (uid, user)).fetchone()
|
||||||
|
if row:
|
||||||
|
audit('label_printed', order=order['number'], reason='auto', operator=user)
|
||||||
|
return {'print': bool(row)}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/orders/{uid}/label/reprint')
|
||||||
|
def reprint_label(uid: UUID, user=Depends(can('label'))):
|
||||||
|
"""A new label for an order in Finalizado, from any computer."""
|
||||||
|
with db.connect() as c:
|
||||||
|
order = _order(c, uid)
|
||||||
|
if order['cancelled_at'] or order['state'] != 'fin':
|
||||||
|
raise HTTPException(409, 'A etiqueta é reimpressa em Finalizado.')
|
||||||
|
c.execute('''INSERT INTO dtf_local.label_prints(order_id,reason,printed_by)
|
||||||
|
VALUES(%s,'reprint',%s)''', (uid, user))
|
||||||
|
audit('label_printed', order=order['number'], reason='reprint', operator=user)
|
||||||
|
return {'print': True}
|
||||||
657
app/api/operator/orders.py
Normal file
657
app/api/operator/orders.py
Normal file
@@ -0,0 +1,657 @@
|
|||||||
|
"""Order actions: cancel and delete, machine, contraction, contact, proof,
|
||||||
|
receipt and pickup, queue place, move, print-file regeneration."""
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from typing import Literal
|
||||||
|
from uuid import UUID, uuid4
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, Request, Response
|
||||||
|
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, 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, 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
|
||||||
|
from .common import FINAL_OK, TREATED
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
@router.post('/api/operator/orders/{uid}/delete')
|
||||||
|
def delete_order(uid: UUID, user=Depends(can('manage'))):
|
||||||
|
"""Deletes a test order, or a paid order already cancelled, with its
|
||||||
|
history and files' records. A paid order in progress must be cancelled
|
||||||
|
first, with its reason. A test order's quote is unpaid again; a cancelled
|
||||||
|
one's is discarded, so it neither returns to Cotações nor can be paid twice.
|
||||||
|
The payment itself stays recorded, and the audit log keeps who deleted what."""
|
||||||
|
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, 'Order not found')
|
||||||
|
test = payments.is_test(row)
|
||||||
|
if not test and not row.get('cancelled_at'):
|
||||||
|
raise HTTPException(409, 'Cancele o pedido antes de excluir. Só pedidos cancelados ou de teste podem ser excluídos.')
|
||||||
|
# Its files leave storage too: the finals, corrections and generated PDFs,
|
||||||
|
# and the customer's originals unless the quote can still be paid (a test
|
||||||
|
# order's). The worker deletes them within a minute.
|
||||||
|
originals = {str(u) for item in row['snapshot'].get('items') or [] for u in item.get('uploads') or []}
|
||||||
|
produced = {str(r['upload_id']) for r in c.execute('''SELECT upload_id FROM dtf_local.order_files WHERE order_id=%s
|
||||||
|
UNION SELECT upload_id FROM dtf_local.print_files WHERE order_id=%s AND upload_id IS NOT NULL
|
||||||
|
UNION SELECT upload_id FROM dtf_local.print_parts WHERE order_id=%s''',
|
||||||
|
(uid, uid, uid)).fetchall()}
|
||||||
|
candidates = produced - originals if test else produced | originals
|
||||||
|
# Its proof cards (app/proof.py) go with it.
|
||||||
|
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:
|
||||||
|
c.execute('UPDATE dtf_local.quotes SET discarded_at=COALESCE(discarded_at,now()), discarded_by=COALESCE(discarded_by,%s) WHERE id=%s',
|
||||||
|
(user, row['quote_id']))
|
||||||
|
freed = release_files(c, candidates)
|
||||||
|
audit('order_deleted', order=row['number'], test=test, operator=user,
|
||||||
|
reason=row.get('cancel_reason') or '', files_released=freed)
|
||||||
|
return {'ok': True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/orders/{uid}/cancel')
|
||||||
|
def cancel_order(uid: UUID, body: Resolution, user=Depends(can('cancel'))):
|
||||||
|
"""A paid order leaves the board but keeps its payment and history. Nothing
|
||||||
|
is refunded here (that is done at the provider); Tiny is told, so the
|
||||||
|
order is cancelled there too while it was not invoiced (app/tiny.py)."""
|
||||||
|
with db.connect() as c:
|
||||||
|
row = c.execute('''UPDATE dtf_local.orders SET cancelled_at=now(), cancelled_by=%s, cancel_reason=%s,
|
||||||
|
version=version+1, updated_at=now() WHERE id=%s AND cancelled_at IS NULL RETURNING *''',
|
||||||
|
(user, body.note, uid)).fetchone()
|
||||||
|
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()
|
||||||
|
enqueue(c, f'{uid}:cancelled:tiny', 'tiny',
|
||||||
|
{'order_id': str(uid), 'number': row['number'], 'event': 'cancelled', 'reason': body.note,
|
||||||
|
'order': row['snapshot'], 'tiny_id': ((sale or {}).get('receipt') or {}).get('tiny_id')})
|
||||||
|
audit('order_cancelled', order=row['number'], operator=user)
|
||||||
|
return {'ok': True}
|
||||||
|
|
||||||
|
|
||||||
|
class MachineChoice(StrictModel):
|
||||||
|
machine_id: UUID | None = None
|
||||||
|
|
||||||
|
|
||||||
|
@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 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()
|
||||||
|
if not current:
|
||||||
|
raise HTTPException(404, 'Pedido não encontrado.')
|
||||||
|
proof.require_unlocked(c, current)
|
||||||
|
if current['cancelled_at'] or current['state'] not in ('rec', 'tra', 'cor'):
|
||||||
|
raise HTTPException(409, 'A máquina não muda depois que o card entrou em Imprimindo.')
|
||||||
|
if body.machine_id:
|
||||||
|
target = c.execute('SELECT name,products,active FROM dtf_local.machines WHERE id=%s', (body.machine_id,)).fetchone()
|
||||||
|
if not target or not target['active']:
|
||||||
|
raise HTTPException(404, 'Máquina não encontrada ou desativada.')
|
||||||
|
if machines.product_family(current) not in target['products']:
|
||||||
|
raise HTTPException(409, f"A {target['name']} não imprime este produto.")
|
||||||
|
linked = c.execute('''SELECT id,state,machine_id,proof_result FROM dtf_local.orders
|
||||||
|
WHERE parent_id=%s AND cancelled_at IS NULL ORDER BY created_at DESC LIMIT 1''', (uid,)).fetchone()
|
||||||
|
if linked and linked['proof_result'] == 'ok' and linked['machine_id'] and body.machine_id != linked['machine_id']:
|
||||||
|
raise HTTPException(409, 'O pedido precisa ficar na mesma máquina que imprimiu a prova.')
|
||||||
|
row = c.execute('''UPDATE dtf_local.orders SET machine_id=%s, machine_chosen=%s WHERE id=%s
|
||||||
|
RETURNING number, state, cancelled_at''', (body.machine_id, body.machine_id is not None, uid)).fetchone()
|
||||||
|
if current['parent_id']:
|
||||||
|
c.execute('UPDATE dtf_local.orders SET machine_id=%s,machine_chosen=%s WHERE id=%s',
|
||||||
|
(body.machine_id, body.machine_id is not None, current['parent_id']))
|
||||||
|
elif linked and linked['proof_result'] is None and linked['state'] in ('rec', 'tra', 'cor'):
|
||||||
|
c.execute('UPDATE dtf_local.orders SET machine_id=%s,machine_chosen=%s WHERE id=%s',
|
||||||
|
(body.machine_id, body.machine_id is not None, linked['id']))
|
||||||
|
audit('order_machine_chosen', order=row['number'], machine=str(body.machine_id or ''), operator=user)
|
||||||
|
return {'ok': True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/orders/{uid}/contraction')
|
||||||
|
def choose_contraction(uid: UUID, body: Contraction, user=Depends(can('produce'))):
|
||||||
|
"""The contraction class of an item (Dropstar, 2026-10-30): the browser's
|
||||||
|
measure comes prefilled, and whoever prepares the art may change it until
|
||||||
|
the order prints. Both stay: the measure in the snapshot, the choice here."""
|
||||||
|
with db.connect() as c:
|
||||||
|
row = c.execute('SELECT id,parent_id,proof_ok_at,snapshot,state,cancelled_at,contraction FROM dtf_local.orders WHERE id=%s FOR UPDATE',
|
||||||
|
(uid,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(404, 'Pedido não encontrado.')
|
||||||
|
proof.require_unlocked(c, row)
|
||||||
|
if body.item_index >= len(row['snapshot']['items']):
|
||||||
|
raise HTTPException(422, 'Item não encontrado no pedido.')
|
||||||
|
# Printing, the class still changes while the item's files wait to go
|
||||||
|
# into the hot folder: the class is its folder (item 10).
|
||||||
|
written = row['state'] == 'imp' and c.execute('''SELECT 1 FROM dtf_local.hot_parts WHERE order_id=%s
|
||||||
|
AND item_index=%s AND state NOT IN ('queued','gone') LIMIT 1''', (uid, body.item_index)).fetchone()
|
||||||
|
if row['cancelled_at'] or row['state'] not in ('rec', 'tra', 'cor', 'imp') or written:
|
||||||
|
raise HTTPException(409, 'A contração muda até o arquivo ir para a hot folder da máquina.')
|
||||||
|
chosen = dict(row['contraction'] or {})
|
||||||
|
key = str(body.item_index)
|
||||||
|
if body.value is None:
|
||||||
|
chosen.pop(key, None)
|
||||||
|
else:
|
||||||
|
chosen[key] = {'class': body.value, 'by': user, 'at': datetime.now(timezone.utc).isoformat()}
|
||||||
|
c.execute('UPDATE dtf_local.orders SET contraction=%s WHERE id=%s', (Jsonb(chosen), uid))
|
||||||
|
audit('order_contraction_chosen', order=str(uid), item=body.item_index, value=body.value or '', operator=user)
|
||||||
|
return {'ok': True, 'contraction': chosen}
|
||||||
|
|
||||||
|
|
||||||
|
class ContactWait(StrictModel):
|
||||||
|
waiting: bool
|
||||||
|
note: str = Field(default='', max_length=500)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/orders/{uid}/contact')
|
||||||
|
def contact(uid: UUID, body: ContactWait, user=Depends(can('produce'))):
|
||||||
|
"""Mark an order as waiting for a word with the customer, with what has to
|
||||||
|
be agreed, or clear the mark once that is done. The stage does not change
|
||||||
|
and the customer is not told."""
|
||||||
|
note = ' '.join(body.note.split())
|
||||||
|
if body.waiting and len(note) < 3:
|
||||||
|
raise HTTPException(422, 'Escreva o que precisa ser combinado com o cliente.')
|
||||||
|
with db.connect() as c:
|
||||||
|
row = c.execute('''UPDATE dtf_local.orders SET contact_since=CASE WHEN %s THEN now() END,
|
||||||
|
contact_by=CASE WHEN %s THEN %s END, contact_note=CASE WHEN %s THEN %s END
|
||||||
|
WHERE id=%s AND cancelled_at IS NULL RETURNING number''',
|
||||||
|
(body.waiting, body.waiting, user, body.waiting, note, uid)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(404, 'Pedido não encontrado.')
|
||||||
|
# The wait's history, for the time figures that leave it out (D-38).
|
||||||
|
c.execute('UPDATE dtf_local.contact_waits SET ended_at=now() WHERE order_id=%s AND ended_at IS NULL', (uid,))
|
||||||
|
if body.waiting:
|
||||||
|
c.execute('INSERT INTO dtf_local.contact_waits(order_id, started_at) VALUES(%s, now())', (uid,))
|
||||||
|
audit('order_contact_waiting' if body.waiting else 'order_contact_done', order=row['number'], operator=user)
|
||||||
|
return {'ok': True}
|
||||||
|
|
||||||
|
|
||||||
|
class ProofAnswer(StrictModel):
|
||||||
|
result: Literal['ok', 'rejected']
|
||||||
|
reason: str = Field(default='', max_length=500)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/orders/{uid}/proof-answer')
|
||||||
|
def proof_answer(uid: UUID, body: ProofAnswer, user=Depends(can('proof'))):
|
||||||
|
"""The answer to a proof card in Revisão (Dropstar, 2026-11-03): Prova OK
|
||||||
|
puts its order in the queue; Prova reprovada, with its reason, sends the
|
||||||
|
order back to Arte recebida. Either way the card closes."""
|
||||||
|
reason = ' '.join(body.reason.split())
|
||||||
|
if body.result == 'rejected' and len(reason) < 3:
|
||||||
|
raise HTTPException(422, 'Diga por que a prova foi reprovada.')
|
||||||
|
with db.connect() as c:
|
||||||
|
card = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
|
||||||
|
if not card or not card.get('parent_id'):
|
||||||
|
raise HTTPException(404, 'Card de prova não encontrado.')
|
||||||
|
if card['cancelled_at'] or card['proof_result'] or card['state'] != 'rev':
|
||||||
|
raise HTTPException(409, 'A prova é respondida em Revisão, uma vez.')
|
||||||
|
parent = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (card['parent_id'],)).fetchone()
|
||||||
|
c.execute('''UPDATE dtf_local.orders SET proof_result=%s, proof_decided_at=now(), proof_decided_by=%s,
|
||||||
|
proof_reason=%s, state='fin', version=version+1, updated_at=now() WHERE id=%s''',
|
||||||
|
(body.result, user, reason or None, uid))
|
||||||
|
label = 'Prova OK' if body.result == 'ok' else 'Prova reprovada: ' + reason
|
||||||
|
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':
|
||||||
|
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'],))
|
||||||
|
c.execute('''UPDATE dtf_local.orders SET state='rec', proof_ok_at=NULL, proof_ok_by=NULL, queue_key=NULL,
|
||||||
|
machine_id=NULL,machine_chosen=false,
|
||||||
|
version=version+1, updated_at=now() WHERE id=%s''', (parent['id'],))
|
||||||
|
c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason)
|
||||||
|
VALUES(%s,%s,'rec',%s,%s)''', (parent['id'], parent['state'], user, label))
|
||||||
|
# The proof answer is the contact with the customer: the old
|
||||||
|
# "Aguardando contato" mark has done its job either way (0.1).
|
||||||
|
c.execute('''UPDATE dtf_local.orders SET contact_since=NULL, contact_by=NULL, contact_note=NULL
|
||||||
|
WHERE id=%s''', (parent['id'],))
|
||||||
|
c.execute('UPDATE dtf_local.contact_waits SET ended_at=now() WHERE order_id=%s AND ended_at IS NULL',
|
||||||
|
(parent['id'],))
|
||||||
|
audit('order_proof_answered', order=parent['number'], result=body.result, operator=user)
|
||||||
|
return {'ok': True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/orders/{uid}/proof-card')
|
||||||
|
def new_proof_card(uid: UUID, user=Depends(can('produce'))):
|
||||||
|
"""A new proof card for an order whose proof was rejected, or that has
|
||||||
|
none yet (an order from before the cards)."""
|
||||||
|
with db.connect() as c:
|
||||||
|
row = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
|
||||||
|
if not row or row.get('parent_id'):
|
||||||
|
raise HTTPException(404, 'Pedido não encontrado.')
|
||||||
|
if row['cancelled_at'] or row['state'] not in ('rec', 'tra') or row['proof_ok_at'] or proof.open_child(c, uid):
|
||||||
|
raise HTTPException(409, 'Este pedido já tem uma prova em andamento ou aprovada.')
|
||||||
|
child = proof.create_child(c, row)
|
||||||
|
if not child:
|
||||||
|
raise HTTPException(409, 'Este pedido não leva prova.')
|
||||||
|
audit('order_proof_card', order=row['number'], operator=user)
|
||||||
|
return {'ok': True, 'id': child['id'], 'number': child['number']}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/orders/{uid}/proof')
|
||||||
|
def proof_ok(uid: UUID, user=Depends(can('print'))):
|
||||||
|
"""An order from before the proof cards: the print room checked the
|
||||||
|
proof, and the order may reach Finalizado."""
|
||||||
|
with db.connect() as c:
|
||||||
|
if proof.open_child(c, uid):
|
||||||
|
raise HTTPException(409, 'Este pedido tem um card de prova: a resposta vai nele.')
|
||||||
|
row = c.execute('''UPDATE dtf_local.orders SET proof_ok_at=now(), proof_ok_by=%s, version=version+1
|
||||||
|
WHERE id=%s AND cancelled_at IS NULL AND state<>'fin' RETURNING number, version''', (user, uid)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(404, 'Pedido não encontrado.')
|
||||||
|
audit('order_proof_ok', order=row['number'], operator=user)
|
||||||
|
return {'ok': True, 'version': row['version']}
|
||||||
|
|
||||||
|
|
||||||
|
def paid_with(c, order):
|
||||||
|
"""How the order was paid, for its receipt: pix, card, cash, credit, or
|
||||||
|
'teste' for an operator's test order."""
|
||||||
|
paid = order.get('payment') or {}
|
||||||
|
if paid.get('provider') == 'teste':
|
||||||
|
return 'teste'
|
||||||
|
if paid.get('provider') == payments.MANUAL_PROVIDER:
|
||||||
|
return paid.get('method')
|
||||||
|
row = c.execute('''SELECT method FROM dtf_local.payment_intents WHERE quote_id=%s AND status='approved'
|
||||||
|
ORDER BY created_at DESC LIMIT 1''', (order['quote_id'],)).fetchone()
|
||||||
|
return row and row['method']
|
||||||
|
|
||||||
|
|
||||||
|
@router.get('/api/operator/orders/{uid}/receipt')
|
||||||
|
def pickup_receipt(uid: UUID, user=Depends(operator)):
|
||||||
|
"""The pickup receipt's PDF (item 14), for the folder to save or someone
|
||||||
|
to print again."""
|
||||||
|
with db.connect() as c:
|
||||||
|
order = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s', (uid,)).fetchone()
|
||||||
|
if not order:
|
||||||
|
raise HTTPException(404, 'Pedido não encontrado.')
|
||||||
|
if not receipt.is_pickup(order['snapshot']):
|
||||||
|
raise HTTPException(409, 'Só pedido de retirada tem recibo.')
|
||||||
|
body = receipt.render(order, paid_with(c, order))
|
||||||
|
return Response(body, media_type='application/pdf',
|
||||||
|
headers={'Content-Disposition': f'inline; filename="{receipt.file_name(order)}"'})
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/orders/{uid}/receipt/claim')
|
||||||
|
def claim_receipt(uid: UUID, user=Depends(can('print'))):
|
||||||
|
"""One computer's folder takes the receipt to save: once, so the counter's
|
||||||
|
queue never prints it twice."""
|
||||||
|
with db.connect() as c:
|
||||||
|
row = c.execute('''UPDATE dtf_local.orders SET receipt_saved_at=now(), receipt_saved_by=%s
|
||||||
|
WHERE id=%s AND receipt_due_at IS NOT NULL AND receipt_saved_at IS NULL AND cancelled_at IS NULL
|
||||||
|
RETURNING number''', (user, uid)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(409, 'Este recibo já foi salvo.')
|
||||||
|
audit('pickup_receipt_saved', order=row['number'], operator=user)
|
||||||
|
return {'ok': True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/orders/{uid}/receipt/release')
|
||||||
|
def release_receipt(uid: UUID, user=Depends(can('print'))):
|
||||||
|
"""The folder could not save the receipt it took: another computer may."""
|
||||||
|
with db.connect() as c:
|
||||||
|
c.execute('''UPDATE dtf_local.orders SET receipt_saved_at=NULL, receipt_saved_by=NULL
|
||||||
|
WHERE id=%s AND receipt_saved_by=%s''', (uid, user))
|
||||||
|
return {'ok': True}
|
||||||
|
|
||||||
|
|
||||||
|
def pickup_order(c, uid, lock=False):
|
||||||
|
"""An order in Finalizado to be picked up, or why it cannot be marked."""
|
||||||
|
order = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s' + (' FOR UPDATE' if lock else ''), (uid,)).fetchone()
|
||||||
|
if not order:
|
||||||
|
raise HTTPException(404, 'Pedido não encontrado.')
|
||||||
|
if order['cancelled_at'] or order['state'] != 'fin' or not receipt.is_pickup(order['snapshot']):
|
||||||
|
raise HTTPException(409, 'Só um pedido de retirada em Finalizado é marcado como retirado.')
|
||||||
|
if order['picked_up_at']:
|
||||||
|
raise HTTPException(409, 'Este pedido já foi marcado como retirado.')
|
||||||
|
return order
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/orders/{uid}/pickup-uploads')
|
||||||
|
def begin_pickup_photo(uid: UUID, body: UploadStart, user=Depends(can('deliver'))):
|
||||||
|
"""The photo of the signed receipt, sent before marking the order."""
|
||||||
|
with db.connect() as c:
|
||||||
|
pickup_order(c, uid)
|
||||||
|
return begin_upload(body, session_id=operator_identity(user))
|
||||||
|
|
||||||
|
|
||||||
|
class PickedUp(StrictModel):
|
||||||
|
photo: UUID | None = None
|
||||||
|
|
||||||
|
|
||||||
|
PHOTO_TYPES = ('.jpg', '.jpeg', '.png', '.webp', '.heic', '.heif')
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/orders/{uid}/picked-up')
|
||||||
|
def picked_up(uid: UUID, body: PickedUp, user=Depends(can('deliver'))):
|
||||||
|
""""Retirado": when and who handed the order over, and the photo of the
|
||||||
|
signed receipt when there is one (item 14). Finalizado means ready; this
|
||||||
|
closes the cycle. The photo is kept 30 days, as the order's files are."""
|
||||||
|
with db.connect() as c:
|
||||||
|
order = pickup_order(c, uid, lock=True)
|
||||||
|
if body.photo:
|
||||||
|
photo = upload_row(c, body.photo, operator_identity(user), lock=True)
|
||||||
|
if not photo['complete']:
|
||||||
|
raise HTTPException(409, 'Espere a foto terminar de enviar.')
|
||||||
|
if not photo['name'].lower().endswith(PHOTO_TYPES):
|
||||||
|
raise HTTPException(422, 'A foto do recibo precisa ser uma imagem (JPG, PNG, WebP ou HEIC).')
|
||||||
|
require_clean(photo)
|
||||||
|
c.execute("UPDATE dtf_local.uploads SET expires_at=now()+interval '30 days' WHERE id=%s", (body.photo,))
|
||||||
|
row = c.execute('''UPDATE dtf_local.orders SET picked_up_at=now(), picked_up_by=%s, picked_up_photo=%s
|
||||||
|
WHERE id=%s RETURNING picked_up_at''', (user, body.photo, uid)).fetchone()
|
||||||
|
audit('order_picked_up', order=order['number'], operator=user, photo=bool(body.photo))
|
||||||
|
return {'ok': True, 'picked_up_at': row['picked_up_at']}
|
||||||
|
|
||||||
|
|
||||||
|
class QueuePlace(StrictModel):
|
||||||
|
"""Where a dragged card lands: between two orders of its column, either
|
||||||
|
of them absent at the top or the bottom."""
|
||||||
|
after: UUID | None = None
|
||||||
|
before: UUID | None = None
|
||||||
|
|
||||||
|
|
||||||
|
QUEUE_KEY = 'COALESCE(queue_key, extract(epoch FROM created_at))'
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/orders/{uid}/queue')
|
||||||
|
def queue_place(uid: UUID, body: QueuePlace, request: Request, user=Depends(operator)):
|
||||||
|
"""An order's place in its column: by default its payment time; dragged,
|
||||||
|
halfway between the orders it was dropped between. It neither changes the
|
||||||
|
order's stage nor counts as activity (the stalled clock keeps running)."""
|
||||||
|
if not body.after and not body.before:
|
||||||
|
raise HTTPException(422, 'Informe entre quais pedidos ele fica.')
|
||||||
|
with db.connect() as c:
|
||||||
|
row = c.execute('SELECT id,parent_id,proof_ok_at,state,machine_id FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(404, 'Order not found')
|
||||||
|
proof.require_unlocked(c, row)
|
||||||
|
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 (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 = {}
|
||||||
|
for side in ('after', 'before'):
|
||||||
|
other = getattr(body, side)
|
||||||
|
if other:
|
||||||
|
near = c.execute(f'SELECT state, {QUEUE_KEY} AS key FROM dtf_local.orders WHERE id=%s', (other,)).fetchone()
|
||||||
|
if not near or near['state'] != row['state']:
|
||||||
|
raise HTTPException(409, 'Os pedidos mudaram de etapa. Clique em Atualizar.')
|
||||||
|
keys[side] = float(near['key'])
|
||||||
|
if 'after' in keys and 'before' in keys:
|
||||||
|
key = (keys['after'] + keys['before']) / 2
|
||||||
|
elif 'after' in keys:
|
||||||
|
key = keys['after'] + 60
|
||||||
|
else:
|
||||||
|
key = keys['before'] - 60
|
||||||
|
c.execute('UPDATE dtf_local.orders SET queue_key=%s WHERE id=%s', (key, uid))
|
||||||
|
audit('order_queue_moved', order=str(uid), operator=user)
|
||||||
|
return {'ok': True, 'queue_key': key}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/orders/{uid}/move')
|
||||||
|
def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
|
||||||
|
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()
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(404, 'Order not found')
|
||||||
|
if body.version != row['version']:
|
||||||
|
raise HTTPException(409, 'O pedido mudou. Clique em Atualizar.')
|
||||||
|
if row.get('cancelled_at'):
|
||||||
|
raise HTTPException(409, 'Pedido cancelado.')
|
||||||
|
proof.require_unlocked(c, row)
|
||||||
|
if body.state == row['state']:
|
||||||
|
return row
|
||||||
|
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(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():
|
||||||
|
raise HTTPException(422, 'Informe o motivo da correção.')
|
||||||
|
if back and not body.reason.strip():
|
||||||
|
raise HTTPException(422, 'Informe por que o pedido está voltando de etapa.')
|
||||||
|
# The machine of this session takes a card when it is pulled. A proof
|
||||||
|
# and its parent must keep the same physical machine.
|
||||||
|
account = request.state.operator
|
||||||
|
session_machine = account['machine']
|
||||||
|
pulling = row['state'] == 'tra' and body.state == 'imp'
|
||||||
|
# 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']:
|
||||||
|
raise HTTPException(403, 'Este pedido é de outra máquina: só quem está nela move o card.')
|
||||||
|
if pulling:
|
||||||
|
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 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']:
|
||||||
|
raise HTTPException(409, 'Essa máquina não existe mais ou está desativada.')
|
||||||
|
if machines.product_family(row) not in target['products']:
|
||||||
|
raise HTTPException(409, f"A {target['name']} não imprime este produto.")
|
||||||
|
# The machine's sheet speaks between one file and the next, never in
|
||||||
|
# the middle: a blocking alert stops this card here (app/machine_log.py).
|
||||||
|
blocking = [alert for alert in machine_log.alerts(c, chosen) if alert['blocking']]
|
||||||
|
if blocking:
|
||||||
|
raise HTTPException(409, 'Antes do próximo arquivo: ' + blocking[0]['text'])
|
||||||
|
linked = c.execute('''SELECT machine_id FROM dtf_local.orders WHERE parent_id=%s
|
||||||
|
AND proof_result='ok' AND cancelled_at IS NULL ORDER BY created_at DESC LIMIT 1''', (uid,)).fetchone()
|
||||||
|
if linked and linked['machine_id'] and chosen != linked['machine_id']:
|
||||||
|
raise HTTPException(409, 'Puxe o pedido na mesma máquina que imprimiu a prova.')
|
||||||
|
row['machine_id'] = chosen
|
||||||
|
c.execute('UPDATE dtf_local.orders SET machine_id=%s,machine_chosen=true WHERE id=%s', (chosen, uid))
|
||||||
|
if row['parent_id']:
|
||||||
|
c.execute('UPDATE dtf_local.orders SET machine_id=%s,machine_chosen=true WHERE id=%s',
|
||||||
|
(chosen, row['parent_id']))
|
||||||
|
# Arte conferida is the queue: what enters it has its final files approved.
|
||||||
|
if body.state in ('tra','imp'):
|
||||||
|
coverage = c.execute(f'''SELECT DISTINCT f.item_index FROM dtf_local.order_files f
|
||||||
|
JOIN dtf_local.uploads u ON u.id=f.upload_id WHERE f.order_id=%s AND {FINAL_OK}''', (uid,)).fetchall()
|
||||||
|
if {r['item_index'] for r in coverage} != set(range(len(row['snapshot']['items']))):
|
||||||
|
raise HTTPException(409, 'Aprove os arquivos finais de todos os itens antes de mandar para Arte conferida.')
|
||||||
|
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.')
|
||||||
|
# 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':
|
||||||
|
raise HTTPException(409, 'A prova termina com Prova OK ou Prova reprovada, não em Finalizado.')
|
||||||
|
if body.state == 'imp' and proof.waiting(c, row):
|
||||||
|
raise HTTPException(409, 'Aguardando prova: o pedido entra na fila com Prova OK no card da prova.')
|
||||||
|
if body.state == 'fin' and not row.get('parent_id') and proof.needs_proof(row['snapshot']) and not row['proof_ok_at']:
|
||||||
|
raise HTTPException(409, 'Falta a prova: confira a prova impressa e marque Prova OK antes de finalizar.')
|
||||||
|
# Above 1 m the review photo is the evidence the sheet was checked; a
|
||||||
|
# proof card is no sale and skips this (app/reviews.py).
|
||||||
|
if (body.state == 'fin' and not back and not row.get('parent_id')
|
||||||
|
and reviews.required(row['snapshot']) and not reviews.has_photo(c, uid)):
|
||||||
|
raise HTTPException(409, 'Pedido acima de 1 m: tire a foto da revisão antes de finalizar.')
|
||||||
|
if body.state == 'cor':
|
||||||
|
c.execute("UPDATE dtf_local.order_files SET active=false WHERE order_id=%s AND kind='final'", (uid,))
|
||||||
|
# Who moved it, and on which machine: the one it goes to print on, or
|
||||||
|
# else the mover's.
|
||||||
|
machine_name = (session_machine or {}).get('name')
|
||||||
|
if body.state == 'imp' and row['machine_id']:
|
||||||
|
machine_name = (c.execute('SELECT name FROM dtf_local.machines WHERE id=%s',
|
||||||
|
(row['machine_id'],)).fetchone() or {}).get('name')
|
||||||
|
# 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.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(),
|
||||||
|
queue_key=CASE WHEN %s='tra' AND parent_id IS NOT NULL THEN -extract(epoch FROM now()) ELSE NULL END,
|
||||||
|
receipt_due_at=CASE WHEN %s THEN COALESCE(receipt_due_at, now()) ELSE receipt_due_at END
|
||||||
|
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).
|
||||||
|
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,
|
||||||
|
and for orders paid before the generator existed."""
|
||||||
|
with db.connect() as c:
|
||||||
|
row = c.execute('SELECT id,parent_id,proof_ok_at,snapshot,state FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(404, 'Order not found')
|
||||||
|
proof.require_unlocked(c, row)
|
||||||
|
if row['state'] not in ('rec','tra'):
|
||||||
|
raise HTTPException(409, 'Print files are generated only before the order is queued')
|
||||||
|
if c.execute("SELECT 1 FROM dtf_local.order_files WHERE order_id=%s AND kind='correction' LIMIT 1", (uid,)).fetchone():
|
||||||
|
raise HTTPException(409, 'A customer correction replaced the original artwork; prepare the final file by hand')
|
||||||
|
if row['parent_id']:
|
||||||
|
manual = c.execute("SELECT item_index FROM dtf_local.print_files WHERE order_id=%s AND status='manual'",
|
||||||
|
(uid,)).fetchall()
|
||||||
|
for stuck in manual:
|
||||||
|
original_index = row['snapshot']['items'][stuck['item_index']]['proof_parent_item_index']
|
||||||
|
prepared = c.execute('''SELECT 1 FROM dtf_local.order_files WHERE order_id=%s
|
||||||
|
AND item_index=%s AND kind='final' AND active LIMIT 1''',
|
||||||
|
(row['parent_id'], original_index)).fetchone()
|
||||||
|
if not prepared:
|
||||||
|
raise HTTPException(409, 'Prepare e aprove o PNG completo no pedido pai antes de gerar a prova de novo.')
|
||||||
|
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}
|
||||||
164
app/api/operator/quotes.py
Normal file
164
app/api/operator/quotes.py
Normal file
@@ -0,0 +1,164 @@
|
|||||||
|
"""Quotes: review, search, test and outside-paid orders, discard."""
|
||||||
|
import re
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Literal
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||||
|
from pydantic import Field
|
||||||
|
|
||||||
|
from ... import payments, quote_review
|
||||||
|
from ...core import db
|
||||||
|
from ...core.auth import audit, can, operator
|
||||||
|
from ...core.models import Review, StrictModel
|
||||||
|
from ...runtime import quote_views
|
||||||
|
from .board import with_print_files
|
||||||
|
from .common import (LIVE_QUOTE, MODES, company_names, customer_match, like, numeric,
|
||||||
|
thumbnails)
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
@router.get('/api/operator/quotes')
|
||||||
|
def quote_page(kind: Literal['pending','approved'], before_created_at: datetime | None = None,
|
||||||
|
before_id: UUID | None = None, offset: int = Query(default=0, ge=0),
|
||||||
|
limit: int = Query(default=50, ge=1, le=100),
|
||||||
|
q: str | None = Query(default=None, max_length=100),
|
||||||
|
product: Literal['textil','uv'] | None = None, layout: Literal['folha','avulsa'] | None = None,
|
||||||
|
flag: Literal['ressalva'] | None = None, user=Depends(operator)):
|
||||||
|
"""Unpaid quotes, newest first: by cursor, or by page (offset) with a total;
|
||||||
|
filtered by customer, product, layout and an accepted resolution warning."""
|
||||||
|
if (before_created_at is None) != (before_id is None):
|
||||||
|
raise HTTPException(422, 'Both quote cursor fields are required')
|
||||||
|
clauses = ['o.id IS NULL', LIVE_QUOTE, 'q.approved IS NULL' if kind == 'pending' else 'q.approved IS NOT NULL']
|
||||||
|
params = []
|
||||||
|
if q and q.strip():
|
||||||
|
sql, values = customer_match('q.draft', q)
|
||||||
|
clauses.append(sql); params += values
|
||||||
|
if product or layout:
|
||||||
|
modes = set.intersection(*(MODES[k] for k in (product, layout) if k))
|
||||||
|
clauses.append("EXISTS (SELECT 1 FROM jsonb_array_elements(q.draft->'items') i WHERE i->>'mode'=ANY(%s))")
|
||||||
|
params.append(sorted(modes))
|
||||||
|
if flag:
|
||||||
|
clauses.append("EXISTS (SELECT 1 FROM jsonb_array_elements(q.draft->'items') i WHERE i->>'quality_status'='warning')")
|
||||||
|
where = ' AND '.join(clauses)
|
||||||
|
cursor = 'AND (q.created_at,q.id)<(%s,%s)' if before_created_at else ''
|
||||||
|
skip = 0 if before_created_at else offset
|
||||||
|
page = params + ([before_created_at, before_id] if before_created_at else []) + [limit+1, skip]
|
||||||
|
with db.connect() as c:
|
||||||
|
rows = c.execute(f'''SELECT q.* FROM dtf_local.quotes q
|
||||||
|
LEFT JOIN dtf_local.orders o ON o.quote_id=q.id
|
||||||
|
WHERE {where} {cursor}
|
||||||
|
ORDER BY q.created_at DESC,q.id DESC LIMIT %s OFFSET %s''', page).fetchall()
|
||||||
|
total = c.execute(f'''SELECT count(*) AS n FROM dtf_local.quotes q
|
||||||
|
LEFT JOIN dtf_local.orders o ON o.quote_id=q.id
|
||||||
|
WHERE {where}''', params).fetchone()['n']
|
||||||
|
quotes = quote_views(c, rows[:limit])
|
||||||
|
return {'quotes': quotes, 'has_more': len(rows)>limit, 'total': total,
|
||||||
|
'thumbnails': thumbnails(c, quotes), 'names': company_names(c, quotes)}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get('/api/operator/search')
|
||||||
|
def search(q: str = Query(min_length=2, max_length=100), user=Depends(operator)):
|
||||||
|
"""One search over orders (any stage) and unpaid quotes: customer e-mail,
|
||||||
|
CNPJ or WhatsApp, the delivery recipient, or the order number."""
|
||||||
|
match, params = customer_match('snapshot', q)
|
||||||
|
digits = numeric(q)
|
||||||
|
sql = match + " OR lower(coalesce(snapshot->'destination'->>'recipient','')) LIKE %s"
|
||||||
|
params.append(like(q.strip().lower()))
|
||||||
|
if digits and len(digits) <= 9:
|
||||||
|
sql += ' OR number=%s'
|
||||||
|
params.append(int(digits))
|
||||||
|
# The code a customer reads out (the id's first characters, see order_code).
|
||||||
|
code = q.strip().lstrip('#').lower()
|
||||||
|
if 6 <= len(code) <= 12 and re.fullmatch(r'[0-9a-f]+', code):
|
||||||
|
sql += " OR replace(id::text,'-','') LIKE %s"
|
||||||
|
params.append(code + '%')
|
||||||
|
quote_match, quote_params = customer_match('q.draft', q)
|
||||||
|
with db.connect() as c:
|
||||||
|
# Real orders: a proof card is found through its order (app/proof.py).
|
||||||
|
orders = c.execute(f'''SELECT * FROM dtf_local.orders WHERE ({sql}) AND parent_id IS NULL
|
||||||
|
ORDER BY created_at DESC LIMIT 8''', params).fetchall()
|
||||||
|
rows = c.execute(f'''SELECT q.* FROM dtf_local.quotes q
|
||||||
|
LEFT JOIN dtf_local.orders o ON o.quote_id=q.id
|
||||||
|
WHERE o.id IS NULL AND {LIVE_QUOTE} AND {quote_match}
|
||||||
|
ORDER BY q.created_at DESC LIMIT 8''', quote_params).fetchall()
|
||||||
|
orders = with_print_files(c, orders)
|
||||||
|
quotes = quote_views(c, rows)
|
||||||
|
return {'orders': orders, 'quotes': quotes, 'thumbnails': thumbnails(c, orders, quotes),
|
||||||
|
'names': company_names(c, orders, quotes)}
|
||||||
|
|
||||||
|
@router.post('/api/operator/quotes/{uid}/approve')
|
||||||
|
def approve(uid: UUID, body: Review, user=Depends(can('manage'))):
|
||||||
|
with db.connect() as c:
|
||||||
|
row = c.execute('SELECT * FROM dtf_local.quotes WHERE id=%s FOR UPDATE', (uid,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(404, 'Quote not found')
|
||||||
|
return quote_review.approve(c, row, body.items, user)
|
||||||
|
|
||||||
|
@router.post('/api/operator/quotes/{uid}/test-order')
|
||||||
|
def test_order(uid: UUID, user=Depends(can('manage'))):
|
||||||
|
"""An order for an approved quote without payment, to try the Kanban,
|
||||||
|
files and print flow in production. Marked TEST on the board, never sent
|
||||||
|
to Tiny or WhatsApp, and audited."""
|
||||||
|
with db.connect() as c:
|
||||||
|
try:
|
||||||
|
quote = payments.approved_quote(c, uid)
|
||||||
|
except payments.PaymentRefused as refusal:
|
||||||
|
raise HTTPException(404 if 'not found' in str(refusal) else 409, str(refusal))
|
||||||
|
receipt = {'provider': payments.TEST_PROVIDER, 'id': f'teste-{uid}', 'status': 'paid',
|
||||||
|
'total_cents': quote['approved']['total_cents'], 'operator': user}
|
||||||
|
order, created = payments.create_order(c, quote, receipt, 'site')
|
||||||
|
if created:
|
||||||
|
audit('test_order_created', order=str(order['id']), operator=user)
|
||||||
|
return order
|
||||||
|
|
||||||
|
|
||||||
|
class PaidOutside(StrictModel):
|
||||||
|
# No defaults (D-35): whoever registers the order says where it came from
|
||||||
|
# and how it was paid.
|
||||||
|
origin: Literal['site', 'dropflow', 'atendimento']
|
||||||
|
method: Literal[payments.OUTSIDE_METHODS]
|
||||||
|
note: str = Field(default='', max_length=300)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/quotes/{uid}/register')
|
||||||
|
def register_order(uid: UUID, body: PaidOutside, user=Depends(can('enter'))):
|
||||||
|
"""The order for an approved quote paid outside the system (Dropstar's
|
||||||
|
rule D-35): the team builds the cart on the Site, as a customer would, and
|
||||||
|
registers it here with its origin and how it was paid. The price is the
|
||||||
|
quote's, the Site's table price."""
|
||||||
|
with db.connect() as c:
|
||||||
|
try:
|
||||||
|
quote = payments.approved_quote(c, uid)
|
||||||
|
except payments.PaymentRefused as refusal:
|
||||||
|
raise HTTPException(404 if 'not found' in str(refusal) else 409, str(refusal))
|
||||||
|
receipt = {'provider': payments.MANUAL_PROVIDER, 'method': body.method, 'note': body.note.strip(),
|
||||||
|
'status': 'paid', 'total_cents': quote['approved']['total_cents'], 'operator': user}
|
||||||
|
order, created = payments.create_order(c, quote, receipt, body.origin)
|
||||||
|
if not created:
|
||||||
|
# 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
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/quotes/{uid}/discard')
|
||||||
|
def discard_quote(uid: UUID, user=Depends(can('manage'))):
|
||||||
|
"""An unpaid quote leaves the Kanban and can no longer be paid. Its files
|
||||||
|
keep their normal expiry; a payment that still arrives for it is refused
|
||||||
|
and listed under Pagamentos."""
|
||||||
|
with db.connect() as c:
|
||||||
|
# Locked like a payment locks it, so a discard and a payment never cross.
|
||||||
|
row = c.execute('SELECT id FROM dtf_local.quotes WHERE id=%s FOR UPDATE', (uid,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(404, 'Quote not found')
|
||||||
|
if c.execute('SELECT 1 FROM dtf_local.orders WHERE quote_id=%s', (uid,)).fetchone():
|
||||||
|
raise HTTPException(409, 'Esta cotação já virou pedido.')
|
||||||
|
c.execute('UPDATE dtf_local.quotes SET discarded_at=now(), discarded_by=%s WHERE id=%s AND discarded_at IS NULL',
|
||||||
|
(user, uid))
|
||||||
|
audit('quote_discarded', quote=str(uid), operator=user)
|
||||||
|
return {'ok': True}
|
||||||
73
app/api/operator/rework.py
Normal file
73
app/api/operator/rework.py
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
"""Rework: its causes, and opening and deciding one (D-02 to D-04)."""
|
||||||
|
from decimal import Decimal
|
||||||
|
from typing import Literal
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
|
from pydantic import Field
|
||||||
|
|
||||||
|
from ...core import db
|
||||||
|
from ...core.auth import audit, can
|
||||||
|
from ...core.models import StrictModel
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
# Rework (Dropstar's rules D-02 to D-04): four causes of the house, each with a
|
||||||
|
# goal of 0,4% of the film printed (1,6% in all), and the customer's approved
|
||||||
|
# bad art, recorded apart and outside the goal (D-04).
|
||||||
|
HOUSE_CAUSES = ('impressao', 'perfil_cor', 'tratamento', 'pedido')
|
||||||
|
CUSTOMER_CAUSE = 'arte_cliente'
|
||||||
|
REWORK_GOAL_PERCENT = Decimal('0.4')
|
||||||
|
|
||||||
|
|
||||||
|
class ReworkOpen(StrictModel):
|
||||||
|
cause: Literal[HOUSE_CAUSES + (CUSTOMER_CAUSE,)]
|
||||||
|
metres: Decimal = Field(gt=0, le=1000)
|
||||||
|
note: str = Field(default='', max_length=1000)
|
||||||
|
|
||||||
|
|
||||||
|
class ReworkDecision(StrictModel):
|
||||||
|
authorized: bool
|
||||||
|
reason: str = Field(default='', max_length=1000)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/orders/{uid}/reworks')
|
||||||
|
def open_rework(uid: UUID, body: ReworkOpen, user=Depends(can('rework'))):
|
||||||
|
"""Coordination opens a rework with its cause (D-02). There is no way to
|
||||||
|
change the cause afterwards (D-03)."""
|
||||||
|
with db.connect() as c:
|
||||||
|
order = c.execute('SELECT id,number,cancelled_at FROM dtf_local.orders WHERE id=%s', (uid,)).fetchone()
|
||||||
|
if not order:
|
||||||
|
raise HTTPException(404, 'Pedido não encontrado.')
|
||||||
|
if order['cancelled_at']:
|
||||||
|
raise HTTPException(409, 'Pedido cancelado não abre retrabalho.')
|
||||||
|
# Who printed the sheet: who last sent it to Revisão.
|
||||||
|
printed = c.execute('''SELECT operator FROM dtf_local.movements WHERE order_id=%s AND to_state='rev'
|
||||||
|
AND NOT back ORDER BY id DESC LIMIT 1''', (uid,)).fetchone()
|
||||||
|
row = c.execute('''INSERT INTO dtf_local.reworks(order_id,cause,metres,note,printed_by,opened_by)
|
||||||
|
VALUES(%s,%s,%s,%s,%s,%s) RETURNING *''',
|
||||||
|
(uid, body.cause, body.metres, body.note.strip(), printed['operator'] if printed else None,
|
||||||
|
user)).fetchone()
|
||||||
|
audit('rework_opened', order=order['number'], cause=body.cause, operator=user)
|
||||||
|
return row
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/reworks/{rid}/decision')
|
||||||
|
def decide_rework(rid: int, body: ReworkDecision, user=Depends(can('authorize'))):
|
||||||
|
"""An Administrador authorizes a rework, and only then it counts, or
|
||||||
|
declines it with a reason (D-02). Never one they opened themselves."""
|
||||||
|
reason = body.reason.strip()
|
||||||
|
if not body.authorized and len(reason) < 3:
|
||||||
|
raise HTTPException(422, 'Diga por que o retrabalho não foi autorizado.')
|
||||||
|
with db.connect() as c:
|
||||||
|
row = c.execute('SELECT * FROM dtf_local.reworks WHERE id=%s FOR UPDATE', (rid,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(404, 'Retrabalho não encontrado.')
|
||||||
|
if row['decided_at']:
|
||||||
|
raise HTTPException(409, 'Este retrabalho já foi decidido.')
|
||||||
|
if row['opened_by'] == user:
|
||||||
|
raise HTTPException(409, 'Quem abriu o retrabalho não pode autorizá-lo.')
|
||||||
|
row = c.execute('''UPDATE dtf_local.reworks SET authorized=%s, decided_by=%s, decided_at=now(), decline_reason=%s
|
||||||
|
WHERE id=%s RETURNING *''', (body.authorized, user, None if body.authorized else reason, rid)).fetchone()
|
||||||
|
audit('rework_decided', rework=rid, authorized=body.authorized, operator=user)
|
||||||
|
return row
|
||||||
49
app/api/operator/session.py
Normal file
49
app/api/operator/session.py
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
"""Kanban sign-in and sign-out."""
|
||||||
|
import hashlib
|
||||||
|
import secrets
|
||||||
|
|
||||||
|
from fastapi import APIRouter, HTTPException, Request, Response
|
||||||
|
|
||||||
|
from ...core import db
|
||||||
|
from ...core.auth import (COOKIE_SECURE, DUMMY_PASSWORD_HASH, audit, client_ip,
|
||||||
|
login_failed, password_matches, throttle)
|
||||||
|
from ...core.models import OperatorLogin
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
@router.post('/api/operator/login')
|
||||||
|
def operator_login(body: OperatorLogin, request: Request, response: Response):
|
||||||
|
email = body.email
|
||||||
|
throttle('operator:'+email, request)
|
||||||
|
with db.connect() as c:
|
||||||
|
account = c.execute('SELECT * FROM dtf_local.operators WHERE email=%s', (email,)).fetchone()
|
||||||
|
if not c.execute('SELECT 1 FROM dtf_local.operators WHERE active LIMIT 1').fetchone():
|
||||||
|
raise HTTPException(503, 'Nenhuma conta de operador configurada.')
|
||||||
|
# Comparable password work whether or not the account exists or is active.
|
||||||
|
stored = account['password_hash'] if account else DUMMY_PASSWORD_HASH
|
||||||
|
matches = password_matches(body.password, stored)
|
||||||
|
if not account or not account['active'] or not matches:
|
||||||
|
login_failed('operator:'+email)
|
||||||
|
audit('operator_login_failed', ip=client_ip(request), operator=email)
|
||||||
|
raise HTTPException(401, 'E-mail ou senha inválidos.')
|
||||||
|
token = secrets.token_urlsafe(32)
|
||||||
|
with db.connect() as c:
|
||||||
|
previous = hashlib.sha256(request.cookies.get('dtf_operator','').encode()).hexdigest()
|
||||||
|
c.execute('DELETE FROM dtf_local.operator_sessions WHERE token_hash=%s', (previous,))
|
||||||
|
c.execute('INSERT INTO dtf_local.operator_sessions(token_hash,username) VALUES(%s,%s)',
|
||||||
|
(hashlib.sha256(token.encode()).hexdigest(), email))
|
||||||
|
c.execute('UPDATE dtf_local.operators SET last_login_at=now() WHERE id=%s', (account['id'],))
|
||||||
|
response.set_cookie('dtf_operator', token, httponly=True, secure=COOKIE_SECURE,
|
||||||
|
samesite='strict', path='/api/operator', max_age=28800)
|
||||||
|
audit('operator_login_success', operator=email)
|
||||||
|
return {'ok': True}
|
||||||
|
|
||||||
|
@router.post('/api/operator/logout')
|
||||||
|
def operator_logout(request: Request, response: Response):
|
||||||
|
with db.connect() as c:
|
||||||
|
digest = hashlib.sha256(request.cookies.get('dtf_operator','').encode()).hexdigest()
|
||||||
|
c.execute('DELETE FROM dtf_local.operator_sessions WHERE token_hash=%s', (digest,))
|
||||||
|
response.delete_cookie('dtf_operator', path='/api/operator', httponly=True,
|
||||||
|
secure=COOKIE_SECURE, samesite='strict')
|
||||||
|
audit('operator_logout')
|
||||||
|
return {'ok': True}
|
||||||
361
app/api/operator/stats.py
Normal file
361
app/api/operator/stats.py
Normal file
@@ -0,0 +1,361 @@
|
|||||||
|
"""Números: the production figures and the SQL helpers they share."""
|
||||||
|
from datetime import date, datetime, timedelta, timezone
|
||||||
|
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
|
||||||
|
from .rework import CUSTOMER_CAUSE, HOUSE_CAUSES, REWORK_GOAL_PERCENT
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
LOCAL_DAY = "(o.created_at AT TIME ZONE 'America/Sao_Paulo')::date"
|
||||||
|
# A montador "Interno" or "faturado" order records the table price, not money
|
||||||
|
# received (Marcus, 2026-11-10): the cash figures leave it out and Números
|
||||||
|
# shows it in its own block.
|
||||||
|
NOT_CASH = ('COALESCE(o.payment->>\'method\',\'\') NOT IN '
|
||||||
|
f"('{payments.INTERNAL_METHOD}','{payments.INVOICED_METHOD}')")
|
||||||
|
|
||||||
|
|
||||||
|
def waited(order, start, end):
|
||||||
|
"""SQL: the seconds `order` spent in "Aguardando contato" between `start`
|
||||||
|
and `end`. Dropstar's rule D-38: that wait has no deadline and does not
|
||||||
|
count in the time figures."""
|
||||||
|
return f'''COALESCE((SELECT sum(extract(epoch FROM least({end}, COALESCE(w.ended_at, now()))
|
||||||
|
- greatest({start}, w.started_at))) FROM dtf_local.contact_waits w
|
||||||
|
WHERE w.order_id={order} AND w.started_at<{end} AND COALESCE(w.ended_at, now())>{start}), 0)'''
|
||||||
|
|
||||||
|
|
||||||
|
# Longest period one request may cover: a year and a day, for a year against the last.
|
||||||
|
STATS_MAX_DAYS = 366
|
||||||
|
|
||||||
|
|
||||||
|
def stats_period(days, start, end):
|
||||||
|
"""The local days a request covers: the last `days`, or start to end."""
|
||||||
|
today = datetime.now(timezone(timedelta(hours=-3))).date()
|
||||||
|
if start is None and end is None:
|
||||||
|
days = days or 30
|
||||||
|
return today - timedelta(days=days - 1), today
|
||||||
|
if start is None or end is None:
|
||||||
|
raise HTTPException(422, 'Informe a data inicial e a final.')
|
||||||
|
if start > end:
|
||||||
|
raise HTTPException(422, 'A data inicial é depois da final.')
|
||||||
|
if (end - start).days + 1 > STATS_MAX_DAYS:
|
||||||
|
raise HTTPException(422, f'O período vai até {STATS_MAX_DAYS} dias.')
|
||||||
|
return start, end
|
||||||
|
|
||||||
|
|
||||||
|
@router.get('/api/operator/stats')
|
||||||
|
def production_stats(days: int | None = Query(default=None, ge=7, le=365), start: date | None = None,
|
||||||
|
end: date | None = None, user=Depends(operator)):
|
||||||
|
"""Production numbers from what the board already records: orders paid in
|
||||||
|
the period, how long each stage holds an order, what each machine printed,
|
||||||
|
and what is waiting now. The period is the last `days`, or start to end."""
|
||||||
|
start, end = stats_period(days, start, end)
|
||||||
|
period = (start, end)
|
||||||
|
within = f"{LOCAL_DAY} BETWEEN %s AND %s"
|
||||||
|
metres = "(SELECT COALESCE(sum((i->>'billed_metres')::numeric),0) FROM jsonb_array_elements(o.snapshot->'items') i)"
|
||||||
|
with db.connect() as c:
|
||||||
|
limit_rows = c.execute('SELECT state,hours,responsible FROM dtf_local.stage_limits').fetchall()
|
||||||
|
limits = {row['state']: {'hours': float(row['hours']), 'responsible': row['responsible']}
|
||||||
|
for row in limit_rows}
|
||||||
|
total = c.execute(f'''SELECT count(*) AS orders,
|
||||||
|
COALESCE(sum((o.snapshot->>'total_cents')::bigint) FILTER (WHERE {NOT_CASH}),0) AS cents,
|
||||||
|
COALESCE(sum({metres}),0) AS metres,
|
||||||
|
count(*) FILTER (WHERE EXISTS (SELECT 1 FROM dtf_local.movements m WHERE m.order_id=o.id
|
||||||
|
AND m.to_state='cor' AND NOT m.back)) AS corrected
|
||||||
|
FROM dtf_local.orders o WHERE {REAL_ORDER} AND {within}''', period).fetchone()
|
||||||
|
# Approved quotes of the period nobody paid (front 9).
|
||||||
|
unpaid_figures = unpaid.figures(c, start, end)
|
||||||
|
daily = {row['day']: row for row in c.execute(f'''SELECT {LOCAL_DAY} AS day, count(*) AS orders,
|
||||||
|
COALESCE(sum({metres}),0) AS metres FROM dtf_local.orders o WHERE {REAL_ORDER} AND {within}
|
||||||
|
GROUP BY 1''', period).fetchall()}
|
||||||
|
# Each order's stages as spans: from entering a stage to the next move.
|
||||||
|
spans = f'''WITH events AS (
|
||||||
|
SELECT o.id, 'rec' AS state, o.created_at AS at FROM dtf_local.orders o WHERE {REAL_ORDER} AND {within}
|
||||||
|
UNION ALL
|
||||||
|
SELECT m.order_id, m.to_state, m.created_at FROM dtf_local.movements m
|
||||||
|
JOIN dtf_local.orders o ON o.id=m.order_id WHERE {REAL_ORDER} AND {within})
|
||||||
|
SELECT id, state, at, LEAD(at) OVER (PARTITION BY id ORDER BY at) AS until FROM events'''
|
||||||
|
# Orders, not passages: an order sent back counts once, its passages apart,
|
||||||
|
# and its time in a stage is the sum of its passages. Otherwise an order
|
||||||
|
# that came back twice reads as three quick passages, not one slow order.
|
||||||
|
stages = c.execute(f'''SELECT state, count(*) AS orders, sum(passages)::int AS passages,
|
||||||
|
avg(seconds) / 3600 AS average_hours
|
||||||
|
FROM (SELECT id, state, count(*) AS passages,
|
||||||
|
sum(extract(epoch FROM until-at) - {waited('s.id', 's.at', 's.until')}) AS seconds
|
||||||
|
FROM ({spans}) s WHERE until IS NOT NULL GROUP BY id, state) per_order
|
||||||
|
GROUP BY state''', period + period).fetchall()
|
||||||
|
lead = c.execute(f'''SELECT count(*) AS orders, percentile_cont(0.5) WITHIN GROUP (ORDER BY extract(epoch FROM
|
||||||
|
f.at - o.created_at) - {waited('o.id', 'o.created_at', 'f.at')}) / 3600 AS median_hours FROM dtf_local.orders o
|
||||||
|
JOIN LATERAL (SELECT min(created_at) AS at FROM dtf_local.movements m WHERE m.order_id=o.id AND m.to_state='fin') f
|
||||||
|
ON f.at IS NOT NULL
|
||||||
|
WHERE {REAL_ORDER} AND {within}''', period).fetchone()
|
||||||
|
# What waits now, however old, and since when in its stage.
|
||||||
|
waiting = c.execute(f'''SELECT o.state, count(*) AS orders, max(extract(epoch FROM now() - COALESCE(
|
||||||
|
(SELECT max(m.created_at) FROM dtf_local.movements m WHERE m.order_id=o.id AND m.to_state=o.state),
|
||||||
|
o.created_at))) / 3600 AS oldest_hours
|
||||||
|
FROM dtf_local.orders o WHERE {REAL_ORDER} AND o.state<>'fin' GROUP BY o.state''').fetchall()
|
||||||
|
# Passages past each stage's acceptable time (front 11), in the
|
||||||
|
# selected period and today.
|
||||||
|
# Each passage carries whether its order paid for treatment, which only
|
||||||
|
# Art received counts (front 5).
|
||||||
|
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->'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)
|
||||||
|
# Rework of the period (D-02 to D-04): the authorized ones, by the day
|
||||||
|
# they were opened, over the film the machines printed in it.
|
||||||
|
not_test = "COALESCE(o.payment->>'provider','') <> 'teste'"
|
||||||
|
opened = "(r.opened_at AT TIME ZONE 'America/Sao_Paulo')::date BETWEEN %s AND %s"
|
||||||
|
redone = {row['cause']: row for row in c.execute(f'''SELECT r.cause, sum(r.metres) AS metres,
|
||||||
|
count(DISTINCT r.order_id) AS orders FROM dtf_local.reworks r JOIN dtf_local.orders o ON o.id=r.order_id
|
||||||
|
WHERE r.authorized AND {not_test} AND {opened} GROUP BY r.cause''', period).fetchall()}
|
||||||
|
# The house's rework enters the pay of who printed it (D-02).
|
||||||
|
by_printer = c.execute(f'''SELECT COALESCE({person('r.printed_by')}, 'Sem registro') AS who,
|
||||||
|
sum(r.metres) AS metres FROM dtf_local.reworks r JOIN dtf_local.orders o ON o.id=r.order_id
|
||||||
|
WHERE r.authorized AND r.cause<>%s AND {not_test} AND {opened} GROUP BY 1 ORDER BY 2 DESC''',
|
||||||
|
(CUSTOMER_CAUSE,) + period).fetchall()
|
||||||
|
undecided = c.execute(f'''SELECT r.id, r.order_id, o.number, r.cause, r.metres, r.opened_at,
|
||||||
|
{person('r.opened_by')} AS opened_name FROM dtf_local.reworks r JOIN dtf_local.orders o ON o.id=r.order_id
|
||||||
|
WHERE r.decided_at IS NULL AND {not_test} ORDER BY r.opened_at''').fetchall()
|
||||||
|
# Arte tratada, for the designer's productivity: orders of the period
|
||||||
|
# whose final someone prepared, by who approved it (any version).
|
||||||
|
treated = c.execute(f'''SELECT COALESCE(op.name, f.created_by) AS who, count(DISTINCT f.order_id) AS orders
|
||||||
|
FROM dtf_local.order_files f JOIN dtf_local.orders o ON o.id=f.order_id
|
||||||
|
LEFT JOIN dtf_local.operators op ON op.email=f.created_by
|
||||||
|
WHERE {REAL_ORDER} AND {within} AND {TREATED} GROUP BY 1 ORDER BY 2 DESC, 1''', period).fetchall()
|
||||||
|
treated_orders = c.execute(f'''SELECT count(DISTINCT f.order_id) AS n FROM dtf_local.order_files f
|
||||||
|
JOIN dtf_local.orders o ON o.id=f.order_id WHERE {REAL_ORDER} AND {within} AND {TREATED}''',
|
||||||
|
period).fetchone()['n']
|
||||||
|
# Each way in apart (D-21): what came from where, and how long it took
|
||||||
|
# from payment to Finalizado, Aguardando contato left out as above.
|
||||||
|
origins = {row['origin']: row for row in c.execute(f'''SELECT o.origin, count(*) AS orders,
|
||||||
|
COALESCE(sum((o.snapshot->>'total_cents')::bigint) FILTER (WHERE {NOT_CASH}),0) AS cents,
|
||||||
|
COALESCE(sum({metres}),0) AS metres,
|
||||||
|
count(f.at) AS finished, percentile_cont(0.5) WITHIN GROUP (ORDER BY extract(epoch FROM
|
||||||
|
f.at - o.created_at) - {waited('o.id', 'o.created_at', 'f.at')}) / 3600 AS median_hours
|
||||||
|
FROM dtf_local.orders o
|
||||||
|
LEFT JOIN LATERAL (SELECT min(created_at) AS at FROM dtf_local.movements m
|
||||||
|
WHERE m.order_id=o.id AND m.to_state='fin') f ON true
|
||||||
|
WHERE {REAL_ORDER} AND {within} GROUP BY o.origin''', period).fetchall()}
|
||||||
|
# The table price of the montador's Interno and Venda orders, counted
|
||||||
|
# apart from the money received above (front 7a.3).
|
||||||
|
price_table = {row['method']: row for row in c.execute(f'''SELECT o.payment->>'method' AS method,
|
||||||
|
count(*) AS orders, COALESCE(sum({metres}),0) AS metres,
|
||||||
|
COALESCE(sum((o.snapshot->>'total_cents')::bigint),0) AS cents
|
||||||
|
FROM dtf_local.orders o WHERE {REAL_ORDER} AND {within}
|
||||||
|
AND o.payment->>'method' IN (%s,%s) GROUP BY 1''',
|
||||||
|
period + (payments.INTERNAL_METHOD, payments.INVOICED_METHOD)).fetchall()}
|
||||||
|
# Coupons used by the period's paid orders (front 8.3): what each code
|
||||||
|
# brought in orders, billed metres, discount and money received.
|
||||||
|
coupons_used = c.execute(f'''SELECT o.snapshot->'coupon'->>'id' AS id,
|
||||||
|
o.snapshot->'coupon'->>'code' AS code, count(*) AS orders,
|
||||||
|
COALESCE(sum({metres}),0) AS metres,
|
||||||
|
COALESCE(sum((o.snapshot->'coupon'->>'discount_cents')::bigint),0) AS discount_cents,
|
||||||
|
COALESCE(sum((o.snapshot->>'total_cents')::bigint) FILTER (WHERE {NOT_CASH}),0) AS cents
|
||||||
|
FROM dtf_local.orders o
|
||||||
|
WHERE {REAL_ORDER} AND {within} AND o.snapshot->'coupon'->>'id' IS NOT NULL
|
||||||
|
GROUP BY 1,2 ORDER BY orders DESC, code''', period).fetchall()
|
||||||
|
# Speed (item 0.12): the browser's marks on the way to a quote, the
|
||||||
|
# Prumo's print generation and the time from payment event to card.
|
||||||
|
site_speed = c.execute(f'''WITH samples AS (
|
||||||
|
SELECT (o.snapshot->'timings'->>'page_ms')::numeric AS page_ms,
|
||||||
|
(o.snapshot->'timings'->>'upload_ms')::numeric AS upload_ms,
|
||||||
|
(o.snapshot->'timings'->>'upload_bytes')::numeric AS upload_bytes,
|
||||||
|
(o.snapshot->'timings'->>'analysis_ms')::numeric AS analysis_ms,
|
||||||
|
(o.snapshot->'timings'->>'montage_ms')::numeric AS montage_ms
|
||||||
|
FROM dtf_local.orders o WHERE {REAL_ORDER} AND {within})
|
||||||
|
SELECT
|
||||||
|
avg(page_ms) AS page_avg,
|
||||||
|
percentile_cont(0.95) WITHIN GROUP (ORDER BY page_ms) AS page_p95, count(page_ms) AS page_n,
|
||||||
|
avg((upload_ms/1000.0)/(upload_bytes/1048576.0))
|
||||||
|
FILTER (WHERE upload_ms>0 AND upload_bytes>0) AS upload_avg,
|
||||||
|
percentile_cont(0.95) WITHIN GROUP (ORDER BY (upload_ms/1000.0)/(upload_bytes/1048576.0))
|
||||||
|
FILTER (WHERE upload_ms>0 AND upload_bytes>0) AS upload_p95,
|
||||||
|
count(*) FILTER (WHERE upload_ms>0 AND upload_bytes>0) AS upload_n,
|
||||||
|
avg(analysis_ms) AS analysis_avg,
|
||||||
|
percentile_cont(0.95) WITHIN GROUP (ORDER BY analysis_ms) AS analysis_p95, count(analysis_ms) AS analysis_n,
|
||||||
|
avg(montage_ms) AS montage_avg,
|
||||||
|
percentile_cont(0.95) WITHIN GROUP (ORDER BY montage_ms) AS montage_p95, count(montage_ms) AS montage_n
|
||||||
|
FROM samples''', period).fetchone()
|
||||||
|
print_speed = c.execute(f'''WITH samples AS (
|
||||||
|
SELECT extract(epoch FROM (p.finished_at-p.created_at)) AS seconds,
|
||||||
|
COALESCE((o.snapshot->'items'->p.item_index->>'metres')::numeric,
|
||||||
|
(o.snapshot->'items'->p.item_index->>'billed_metres')::numeric, 0) AS metres
|
||||||
|
FROM dtf_local.print_files p JOIN dtf_local.orders o ON o.id=p.order_id
|
||||||
|
WHERE {REAL_ORDER} AND {within} AND p.status='ready' AND p.finished_at IS NOT NULL
|
||||||
|
AND p.item_index < jsonb_array_length(o.snapshot->'items'))
|
||||||
|
SELECT avg(seconds) AS avg_s,
|
||||||
|
percentile_cont(0.95) WITHIN GROUP (ORDER BY seconds) AS p95_s, count(*) AS n,
|
||||||
|
avg(seconds/NULLIF(metres/10,0))
|
||||||
|
FILTER (WHERE metres>0) AS per10_avg,
|
||||||
|
percentile_cont(0.95) WITHIN GROUP (ORDER BY seconds/NULLIF(metres/10,0))
|
||||||
|
FILTER (WHERE metres>0) AS per10_p95,
|
||||||
|
count(*) FILTER (WHERE metres>0) AS per10_n
|
||||||
|
FROM samples''', period).fetchone()
|
||||||
|
card_speed = c.execute(f'''WITH samples AS (
|
||||||
|
SELECT extract(epoch FROM (o.created_at - min(e.received_at))) AS seconds
|
||||||
|
FROM dtf_local.orders o JOIN dtf_local.payment_events e ON e.reference=o.quote_id::text
|
||||||
|
WHERE {REAL_ORDER} AND {within} GROUP BY o.id)
|
||||||
|
SELECT avg(seconds) AS avg_s,
|
||||||
|
percentile_cont(0.95) WITHIN GROUP (ORDER BY seconds) AS p95_s, count(*) AS n
|
||||||
|
FROM samples WHERE seconds >= 0''', period).fetchone()
|
||||||
|
today = datetime.now(timezone(timedelta(hours=-3))).date()
|
||||||
|
late = {state: {'count': 0, 'today': 0} for state in ('rec', 'tra', 'imp', 'rev', 'fin')}
|
||||||
|
for row in late_rows:
|
||||||
|
limit = limits.get(row['state'])
|
||||||
|
if not limit:
|
||||||
|
continue
|
||||||
|
hours = float(limit['hours'])
|
||||||
|
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:
|
||||||
|
late[row['state']]['today'] += 1
|
||||||
|
series = []
|
||||||
|
for offset in range((end - start).days + 1):
|
||||||
|
day = start + timedelta(days=offset)
|
||||||
|
row = daily.get(day)
|
||||||
|
series.append({'day': day.isoformat(), 'orders': row['orders'] if row else 0,
|
||||||
|
'metres': float(row['metres']) if row else 0.0})
|
||||||
|
hours = lambda value: round(float(value), 1) if value is not None else None
|
||||||
|
return {'days': len(series), 'start': start.isoformat(), 'end': end.isoformat(),
|
||||||
|
'orders': total['orders'], 'cents': int(total['cents']), 'metres': float(total['metres']),
|
||||||
|
'corrected': total['corrected'], 'daily': series,
|
||||||
|
'treated': {'orders': treated_orders, 'by': [{'who': row['who'], 'orders': row['orders']} for row in treated]},
|
||||||
|
'origins': [{'origin': name, 'orders': origins[name]['orders'] if name in origins else 0,
|
||||||
|
'cents': int(origins[name]['cents']) if name in origins else 0,
|
||||||
|
'metres': float(origins[name]['metres']) if name in origins else 0.0,
|
||||||
|
'finished': origins[name]['finished'] if name in origins else 0,
|
||||||
|
'median_hours': hours(origins[name]['median_hours']) if name in origins else None}
|
||||||
|
for name in ORIGINS],
|
||||||
|
'unpaid': unpaid_figures,
|
||||||
|
'price_table': [{'method': method,
|
||||||
|
'orders': price_table[method]['orders'] if method in price_table else 0,
|
||||||
|
'metres': float(price_table[method]['metres']) if method in price_table else 0.0,
|
||||||
|
'cents': int(price_table[method]['cents']) if method in price_table else 0}
|
||||||
|
for method in (payments.INVOICED_METHOD, payments.INTERNAL_METHOD)],
|
||||||
|
'lead': {'orders': lead['orders'], 'median_hours': hours(lead['median_hours'])},
|
||||||
|
'stage_limits': limits, 'late': late,
|
||||||
|
'stages': {row['state']: {'orders': row['orders'], 'passages': row['passages'],
|
||||||
|
'average_hours': hours(row['average_hours'])} for row in stages},
|
||||||
|
'waiting': {row['state']: {'orders': row['orders'], 'oldest_hours': hours(row['oldest_hours'])} for row in waiting},
|
||||||
|
'speed': speed_figures(site_speed, print_speed, card_speed),
|
||||||
|
'machines': printed, 'rework': rework_figures(printed, redone, by_printer, undecided),
|
||||||
|
'coupons': [{'id': row['id'], 'code': row['code'], 'orders': row['orders'],
|
||||||
|
'metres': float(row['metres']), 'discount_cents': int(row['discount_cents']),
|
||||||
|
'cents': int(row['cents'])} for row in coupons_used]}
|
||||||
|
|
||||||
|
|
||||||
|
def speed_figures(site, generation, card):
|
||||||
|
"""Números' speed block: average and slow-case p95, in seconds per unit."""
|
||||||
|
def pair(avg, p95, n, scale=1):
|
||||||
|
return {'average': round(float(avg)/scale, 2) if avg is not None else None,
|
||||||
|
'p95': round(float(p95)/scale, 2) if p95 is not None else None,
|
||||||
|
'samples': int(n or 0)}
|
||||||
|
return [
|
||||||
|
{'key': 'page', 'label': 'Abrir o montador', 'unit': 's',
|
||||||
|
**pair(site['page_avg'], site['page_p95'], site['page_n'], 1000)},
|
||||||
|
{'key': 'upload', 'label': 'Subir o arquivo', 'unit': 's/MB',
|
||||||
|
**pair(site['upload_avg'], site['upload_p95'], site['upload_n'])},
|
||||||
|
{'key': 'analysis', 'label': 'Conferência do Prumo', 'unit': 's',
|
||||||
|
**pair(site['analysis_avg'], site['analysis_p95'], site['analysis_n'], 1000)},
|
||||||
|
{'key': 'montage', 'label': 'Montagem das avulsas', 'unit': 's',
|
||||||
|
**pair(site['montage_avg'], site['montage_p95'], site['montage_n'], 1000)},
|
||||||
|
{'key': 'print', 'label': 'Gerar arquivo final (10 m)', 'unit': 's',
|
||||||
|
**pair(generation['per10_avg'], generation['per10_p95'], generation['per10_n'])},
|
||||||
|
{'key': 'card', 'label': 'Card em Arte recebida', 'unit': 's',
|
||||||
|
**pair(card['avg_s'], card['p95_s'], card['n'])},
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def rework_figures(printed, redone, by_printer, undecided):
|
||||||
|
"""Números' rework: per cause, the metres redone over the film printed,
|
||||||
|
against the goal; the house's total against four times it."""
|
||||||
|
film = Decimal(str(sum(m['metres'] for m in printed)))
|
||||||
|
share = lambda metres: float(round(100 * metres / film, 2)) if film else None
|
||||||
|
causes = []
|
||||||
|
for cause in HOUSE_CAUSES + (CUSTOMER_CAUSE,):
|
||||||
|
row = redone.get(cause)
|
||||||
|
metres = Decimal(row['metres']) if row else Decimal(0)
|
||||||
|
causes.append({'cause': cause, 'metres': float(metres), 'orders': row['orders'] if row else 0,
|
||||||
|
'percent': share(metres)})
|
||||||
|
house = sum(Decimal(str(c['metres'])) for c in causes if c['cause'] != CUSTOMER_CAUSE)
|
||||||
|
return {'film_metres': float(film), 'goal_percent': float(REWORK_GOAL_PERCENT),
|
||||||
|
'house': {'metres': float(house), 'percent': share(house),
|
||||||
|
'goal_percent': float(REWORK_GOAL_PERCENT * len(HOUSE_CAUSES))},
|
||||||
|
'causes': causes,
|
||||||
|
'by_printer': [{'who': row['who'], 'metres': float(row['metres'])} for row in by_printer],
|
||||||
|
'pending': [{'id': row['id'], 'order_id': str(row['order_id']), 'number': row['number'],
|
||||||
|
'cause': row['cause'], 'metres': float(row['metres']), 'opened_at': row['opened_at'].isoformat(),
|
||||||
|
'opened_by': row['opened_name']} for row in undecided]}
|
||||||
|
|
||||||
|
|
||||||
|
def machine_output(c, start, end):
|
||||||
|
"""What each machine printed in the period: the orders that reached
|
||||||
|
Finalizado then, on the machine they were on, their metres, the hours they
|
||||||
|
spent in Imprimindo (so metres per hour is the machine's real pace, as the
|
||||||
|
room moves the cards), when it last finished one, and what it has now.
|
||||||
|
|
||||||
|
The metres are the film printed, not the metres billed: billing rounds up
|
||||||
|
to 10 cm and to one metre at least, and a 0,40 m order printed as 1 m would
|
||||||
|
make the machine look faster than it is. Orders in Imprimindo on the same
|
||||||
|
machine at the same time share that time: it counts once."""
|
||||||
|
metres = ("(SELECT COALESCE(sum(COALESCE(i->>'metres', i->>'billed_metres')::numeric),0)"
|
||||||
|
" FROM jsonb_array_elements(o.snapshot->'items') i)")
|
||||||
|
done = c.execute(f'''SELECT o.id, o.machine_id, {metres} AS metres, f.at
|
||||||
|
FROM dtf_local.orders o
|
||||||
|
JOIN LATERAL (SELECT min(created_at) AS at FROM dtf_local.movements m
|
||||||
|
WHERE m.order_id=o.id AND m.to_state='fin') f ON f.at IS NOT NULL
|
||||||
|
WHERE {REAL_ORDER} AND (f.at AT TIME ZONE 'America/Sao_Paulo')::date BETWEEN %s AND %s''',
|
||||||
|
(start, end)).fetchall()
|
||||||
|
ids = [row['id'] for row in done]
|
||||||
|
printing = {}
|
||||||
|
for row in c.execute('''WITH events AS (
|
||||||
|
SELECT m.order_id AS id, m.to_state AS state, m.created_at AS at FROM dtf_local.movements m
|
||||||
|
WHERE m.order_id=ANY(%s)),
|
||||||
|
spans AS (SELECT id, state, at, LEAD(at) OVER (PARTITION BY id ORDER BY at) AS until FROM events)
|
||||||
|
SELECT id, at, until FROM spans WHERE state='imp' AND until IS NOT NULL''', (ids,)).fetchall() if ids else []:
|
||||||
|
printing.setdefault(row['id'], []).append((row['at'], row['until']))
|
||||||
|
last = {str(row['machine_id']): row['at'] for row in c.execute(f'''SELECT o.machine_id, max(m.created_at) AS at
|
||||||
|
FROM dtf_local.orders o JOIN dtf_local.movements m ON m.order_id=o.id AND m.to_state='fin'
|
||||||
|
WHERE {REAL_ORDER} AND o.machine_id IS NOT NULL GROUP BY o.machine_id''').fetchall()}
|
||||||
|
result = []
|
||||||
|
for m in machines.rows(c):
|
||||||
|
mine = [row for row in done if str(row['machine_id'] or '') == m['id']]
|
||||||
|
hours_in = busy_hours([span for row in mine for span in printing.get(row['id'], [])])
|
||||||
|
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': 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]
|
||||||
|
if loose:
|
||||||
|
result.append({'id': None, 'name': 'Sem máquina', 'active': True, 'orders': len(loose),
|
||||||
|
'metres': float(sum(row['metres'] for row in loose)), 'printing_hours': None,
|
||||||
|
'metres_per_hour': None, 'last_finished': None, 'now': {}})
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def busy_hours(spans):
|
||||||
|
"""The hours the spans (start, end) cover, time shared by several counted once."""
|
||||||
|
seconds, reached = 0.0, None
|
||||||
|
for at, until in sorted(spans):
|
||||||
|
if reached is None or at >= reached:
|
||||||
|
seconds += (until - at).total_seconds()
|
||||||
|
reached = until
|
||||||
|
elif until > reached:
|
||||||
|
seconds += (until - reached).total_seconds()
|
||||||
|
reached = until
|
||||||
|
return seconds / 3600
|
||||||
@@ -11,7 +11,7 @@ import httpx
|
|||||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||||
from psycopg.types.json import Jsonb
|
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 import db
|
||||||
from ..core.auth import audit, client_ip, owner, rate_limit
|
from ..core.auth import audit, client_ip, owner, rate_limit
|
||||||
from ..core.models import PaymentIntent
|
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))
|
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():
|
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.')
|
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
|
# 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,
|
# removed after a while. A payment under way keeps them a day longer,
|
||||||
# time enough for the provider's notice to become the order.
|
# 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)):
|
if live != len(set(uploads)):
|
||||||
raise HTTPException(410, 'Os arquivos deste pedido expiraram porque ele não foi pago a tempo. '
|
raise HTTPException(410, 'Os arquivos deste pedido expiraram porque ele não foi pago a tempo. '
|
||||||
'Monte o pedido de novo para pagar.')
|
'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
|
# Never a second charge: an approved payment is waiting for its
|
||||||
# notification to become the order, and a card in review may still be.
|
# 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
|
# A card waiting for the bank's confirmation (3-D Secure) blocks only
|
||||||
|
|||||||
@@ -1,19 +1,19 @@
|
|||||||
"""Quotes: the customer's cart, approved at once when it can be (app/quote_review.py)."""
|
"""Quotes: the customer's cart, approved at once when it can be (app/quote_review.py)."""
|
||||||
import hashlib
|
import hashlib
|
||||||
import json
|
import json
|
||||||
|
from datetime import datetime, timezone
|
||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
from uuid import UUID, uuid4
|
from uuid import UUID, uuid4
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
from psycopg.types.json import Jsonb
|
from psycopg.types.json import Jsonb
|
||||||
|
|
||||||
from .. import payments
|
from .. import cart_pricing, payments
|
||||||
from ..core import db
|
from ..core import db
|
||||||
from ..core.auth import owner
|
from ..core.auth import owner
|
||||||
from ..core.models import QuoteRequest
|
from ..core.models import QuoteRequest
|
||||||
from ..core.pricing import price
|
|
||||||
from .. import quote_review
|
from .. import quote_review
|
||||||
from ..grade_check import Files, mismatch
|
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 ..runtime import freight, payment, quote_view, require_delivery_available, storage, upload_row
|
||||||
from ..scanning import require_clean
|
from ..scanning import require_clean
|
||||||
|
|
||||||
@@ -25,17 +25,19 @@ def create_quote(body: QuoteRequest, session_id=Depends(owner)):
|
|||||||
if abs(item.metres*100-item.production.height_cm) > Decimal('0.02'):
|
if abs(item.metres*100-item.production.height_cm) > Decimal('0.02'):
|
||||||
raise HTTPException(422, 'A metragem não confere com a montagem enviada. Monte o pedido de novo.')
|
raise HTTPException(422, 'A metragem não confere com a montagem enviada. Monte o pedido de novo.')
|
||||||
require_delivery_available(body.freight.service)
|
require_delivery_available(body.freight.service)
|
||||||
|
# The coupon code is stored normalized, so a quote waiting for review keeps
|
||||||
|
# the code the operator will see (front 8.3).
|
||||||
|
code = (body.coupon or '').strip().upper() or None
|
||||||
draft = body.model_dump(mode='json', exclude={'request_key'})
|
draft = body.model_dump(mode='json', exclude={'request_key'})
|
||||||
|
draft['coupon'] = code
|
||||||
digest = hashlib.sha256(json.dumps(draft, sort_keys=True).encode()).hexdigest()
|
digest = hashlib.sha256(json.dumps(draft, sort_keys=True).encode()).hexdigest()
|
||||||
|
accepted_at = datetime.now(timezone.utc).isoformat()
|
||||||
|
for item in draft['items']:
|
||||||
|
if item.get('residue_accepted'):
|
||||||
|
item['residue_accepted_at'] = accepted_at
|
||||||
|
if item.get('stroke_choice'):
|
||||||
|
item['stroke_choice_at'] = accepted_at
|
||||||
reason = quote_review.review_reason(draft)
|
reason = quote_review.review_reason(draft)
|
||||||
if reason is not None:
|
|
||||||
# Waits for review: check the delivery now, priced at approval.
|
|
||||||
try:
|
|
||||||
priced = [price(item.mode, str(item.metres), item.grade) for item in body.items]
|
|
||||||
freight.quote(body.freight.service, body.freight.postal_code,
|
|
||||||
sum(Decimal(i['billed_metres']) for i in priced), sum(i['total_cents'] for i in priced))
|
|
||||||
except ValueError as exc:
|
|
||||||
raise HTTPException(422, str(exc))
|
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
rows = {}
|
rows = {}
|
||||||
for item in body.items:
|
for item in body.items:
|
||||||
@@ -48,10 +50,39 @@ def create_quote(body: QuoteRequest, session_id=Depends(owner)):
|
|||||||
raise HTTPException(422, 'JPG não tem fundo transparente. Envie a arte em PNG ou PDF.')
|
raise HTTPException(422, 'JPG não tem fundo transparente. Envie a arte em PNG ou PDF.')
|
||||||
require_clean(row)
|
require_clean(row)
|
||||||
rows[str(uid)] = row
|
rows[str(uid)] = row
|
||||||
|
names = {uid: row['name'] for uid, row in rows.items()}
|
||||||
|
# One pricing module for the pre-check and the approval (plan 003). It
|
||||||
|
# also applies the grade rules and the coupon, as before.
|
||||||
|
try:
|
||||||
|
cart = cart_pricing.price_cart(
|
||||||
|
c, draft['items'], names, coupon_code=code,
|
||||||
|
customer_document=body.customer.cnpj,
|
||||||
|
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']),
|
||||||
|
cart['items_total'])
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(422, str(exc))
|
||||||
# The grade came from the browser and is shown with the order (it no
|
# The grade came from the browser and is shown with the order (it no
|
||||||
# longer sets the price): before a cart is approved at checkout, the
|
# longer sets the price): before a cart is approved at checkout, the
|
||||||
# server works it out from the files.
|
# server works it out from the files.
|
||||||
note = mismatch(Files(storage), draft['items'], rows) if reason is None else None
|
files = Files(storage)
|
||||||
|
# Record the lowest source resolution for the Prumo report (front 6).
|
||||||
|
for draft_item, item in zip(draft['items'], body.items):
|
||||||
|
dpis = []
|
||||||
|
for source in item.production.sources:
|
||||||
|
row = rows.get(str(source.upload_id))
|
||||||
|
dpi = source_dpi(files, row, source.model_dump(mode='json')) if row else None
|
||||||
|
if dpi:
|
||||||
|
dpis.append(dpi)
|
||||||
|
if dpis:
|
||||||
|
draft_item['source_dpi'] = round(min(dpis))
|
||||||
|
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
|
||||||
reason = reason or note
|
reason = reason or note
|
||||||
uid = uuid4()
|
uid = uuid4()
|
||||||
c.execute('INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,review_note) VALUES(%s,%s,%s,%s,%s,%s) ON CONFLICT(owner,request_key) DO NOTHING',
|
c.execute('INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,review_note) VALUES(%s,%s,%s,%s,%s,%s) ON CONFLICT(owner,request_key) DO NOTHING',
|
||||||
|
|||||||
98
app/api/reviews.py
Normal file
98
app/api/reviews.py
Normal file
@@ -0,0 +1,98 @@
|
|||||||
|
"""Routes of the review photo or video (Fase 2, front 2, app/reviews.py)."""
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
|
from pydantic import Field
|
||||||
|
|
||||||
|
from .. import reviews
|
||||||
|
from ..core import db
|
||||||
|
from ..core.auth import audit, can, operator, owner
|
||||||
|
from ..core.models import StrictModel
|
||||||
|
from ..runtime import operator_identity, owned_order, storage, upload_row
|
||||||
|
from ..scanning import require_clean
|
||||||
|
from .uploads import begin_upload
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
class ReviewUploadStart(StrictModel):
|
||||||
|
"""The same shape as UploadStart, without its artwork-extension rule: a
|
||||||
|
review carries a photo or a video, not an artwork."""
|
||||||
|
name: str = Field(min_length=1, max_length=200, pattern=r'^[^/\\\x00-\x1f]+$')
|
||||||
|
size: int = Field(gt=0, strict=True)
|
||||||
|
|
||||||
|
|
||||||
|
class ReviewAdd(StrictModel):
|
||||||
|
upload_id: UUID
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/orders/{uid}/reviews/uploads')
|
||||||
|
def start_review_upload(uid: UUID, body: ReviewUploadStart, user=Depends(can('inspect'))):
|
||||||
|
reviews.kind_of(body.name, body.size)
|
||||||
|
return begin_upload(body, session_id=operator_identity(user))
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/orders/{uid}/reviews')
|
||||||
|
def add_review(uid: UUID, body: ReviewAdd, user=Depends(can('inspect'))):
|
||||||
|
with db.connect() as c:
|
||||||
|
order = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s', (uid,)).fetchone()
|
||||||
|
if not order:
|
||||||
|
raise HTTPException(404, 'Pedido não encontrado.')
|
||||||
|
if order.get('cancelled_at'):
|
||||||
|
raise HTTPException(409, 'Pedido cancelado.')
|
||||||
|
if order['state'] != 'rev':
|
||||||
|
raise HTTPException(409, 'A revisão só entra com o pedido em Revisão.')
|
||||||
|
upload = upload_row(c, body.upload_id, operator_identity(user), lock=True)
|
||||||
|
if not upload['complete']:
|
||||||
|
raise HTTPException(409, 'Espere o envio terminar.')
|
||||||
|
require_clean(upload)
|
||||||
|
kind, ext, width, height = reviews.check(storage, upload)
|
||||||
|
row = reviews.attach(c, order, upload, kind, ext, width, height, user)
|
||||||
|
audit('order_review_added', order=str(uid), review=row['id'], kind=kind, operator=user)
|
||||||
|
return row
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/orders/{uid}/reviews/{rid}/remove')
|
||||||
|
def remove_review(uid: UUID, rid: int, user=Depends(can('inspect'))):
|
||||||
|
with db.connect() as c:
|
||||||
|
order = c.execute('SELECT state FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
|
||||||
|
if not order:
|
||||||
|
raise HTTPException(404, 'Pedido não encontrado.')
|
||||||
|
if order['state'] != 'rev':
|
||||||
|
raise HTTPException(409, 'A revisão só sai com o pedido ainda em Revisão.')
|
||||||
|
row = c.execute('DELETE FROM dtf_local.order_reviews WHERE id=%s AND order_id=%s RETURNING upload_id',
|
||||||
|
(rid, uid)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(404, 'Revisão não encontrada.')
|
||||||
|
c.execute('UPDATE dtf_local.uploads SET expires_at=now() WHERE id=%s', (row['upload_id'],))
|
||||||
|
audit('order_review_removed', order=str(uid), review=rid, operator=user)
|
||||||
|
return {'ok': True}
|
||||||
|
|
||||||
|
|
||||||
|
def _mime(name):
|
||||||
|
return reviews.FORMATS[name.rsplit('.', 1)[-1].lower()][1]
|
||||||
|
|
||||||
|
|
||||||
|
@router.get('/api/operator/orders/{uid}/reviews/{rid}/view')
|
||||||
|
def view_review(uid: UUID, rid: int, user=Depends(operator)):
|
||||||
|
with db.connect() as c:
|
||||||
|
row = c.execute('''SELECT r.kind,u.object_key,u.name FROM dtf_local.order_reviews r
|
||||||
|
JOIN dtf_local.uploads u ON u.id=r.upload_id WHERE r.id=%s AND r.order_id=%s''',
|
||||||
|
(rid, uid)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(404, 'Revisão não encontrada.')
|
||||||
|
return {'url': storage.view(row['object_key'], _mime(row['name'])), 'name': row['name'], 'kind': row['kind']}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get('/api/customer/orders/{oid}/reviews/{rid}/view')
|
||||||
|
def customer_view_review(oid: UUID, rid: int, identity=Depends(owner)):
|
||||||
|
with db.connect() as c:
|
||||||
|
owned_order(c, oid, identity)
|
||||||
|
row = c.execute('''SELECT u.object_key,u.name FROM dtf_local.order_reviews r
|
||||||
|
JOIN dtf_local.uploads u ON u.id=r.upload_id
|
||||||
|
JOIN dtf_local.orders o ON o.id=r.order_id
|
||||||
|
WHERE r.id=%s AND r.order_id=%s AND o.state='fin' AND r.kind='photo' ''',
|
||||||
|
(rid, oid)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(404, 'Foto não encontrada.')
|
||||||
|
return {'url': storage.view(row['object_key'], _mime(row['name'])), 'name': row['name'], 'kind': 'photo'}
|
||||||
264
app/api/site_admin.py
Normal file
264
app/api/site_admin.py
Normal file
@@ -0,0 +1,264 @@
|
|||||||
|
"""The Site tab: what the Site sells and at what price, edited by Gestão.
|
||||||
|
|
||||||
|
A product is switched on or off here. Prices carry a start date and become
|
||||||
|
history: a row that has started is never changed or deleted, so only a
|
||||||
|
scheduled (future) price may be cancelled. Approved quotes keep the price they
|
||||||
|
were approved with (app/quote_review.py); a switched-off product refuses new
|
||||||
|
quotes and approvals with 422.
|
||||||
|
"""
|
||||||
|
import re
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
from uuid import UUID, uuid4
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
|
from psycopg.errors import UniqueViolation
|
||||||
|
from psycopg.types.json import Jsonb
|
||||||
|
|
||||||
|
from .. import catalog, grade_rules
|
||||||
|
from ..core import db
|
||||||
|
from ..core.auth import audit, can
|
||||||
|
from ..core.models import CouponNew, CouponUpdate, GradeRules, SitePriceNew, SiteProductToggle
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
def price_row(row):
|
||||||
|
return {'id': row['id'], 'unit_cents': row['unit_cents'], 'bands': row['bands'] or [],
|
||||||
|
'starts_at': row['starts_at'].isoformat(), 'created_by': row['created_by'],
|
||||||
|
'created_at': row['created_at'].isoformat()}
|
||||||
|
|
||||||
|
|
||||||
|
def checked_bands(product, bands):
|
||||||
|
"""The bands the row will store; 422 in Portuguese for anything invalid.
|
||||||
|
Ajuste Fino counts its bands in arts; the other products in metres."""
|
||||||
|
if len(bands) > 5:
|
||||||
|
raise HTTPException(422, 'Um preço pode ter no máximo 5 faixas.')
|
||||||
|
checked, last = [], None
|
||||||
|
for band in bands:
|
||||||
|
if not band.from_metres.is_finite() or band.from_metres <= 0:
|
||||||
|
raise HTTPException(422, 'O início de cada faixa precisa ser maior que zero.')
|
||||||
|
if band.unit_cents <= 0:
|
||||||
|
raise HTTPException(422, 'O preço de cada faixa precisa ser maior que zero.')
|
||||||
|
if band.unit_cents > 10000000:
|
||||||
|
raise HTTPException(422, 'O preço de cada faixa é alto demais.')
|
||||||
|
if last is not None and band.from_metres <= last:
|
||||||
|
raise HTTPException(422, 'As faixas precisam estar em ordem crescente.')
|
||||||
|
last = band.from_metres
|
||||||
|
checked.append({'from_metres': str(band.from_metres), 'unit_cents': band.unit_cents})
|
||||||
|
return checked
|
||||||
|
|
||||||
|
|
||||||
|
@router.get('/api/operator/site/products')
|
||||||
|
def site_products(user=Depends(can('manage'))):
|
||||||
|
with db.connect() as c:
|
||||||
|
state = catalog.current(c)
|
||||||
|
now = c.execute('SELECT now() AS now').fetchone()['now']
|
||||||
|
started = {row['product']: row['unit_cents'] for row in c.execute('''
|
||||||
|
SELECT DISTINCT ON (product) product, unit_cents
|
||||||
|
FROM dtf_local.product_prices
|
||||||
|
WHERE starts_at <= now()
|
||||||
|
ORDER BY product, starts_at DESC, id DESC''').fetchall()}
|
||||||
|
rows = c.execute('''SELECT id, product, unit_cents, bands, starts_at, created_by, created_at
|
||||||
|
FROM dtf_local.product_prices ORDER BY product, created_at DESC, id DESC''').fetchall()
|
||||||
|
products = []
|
||||||
|
for product in catalog.PRODUCTS:
|
||||||
|
prices = [row for row in rows if row['product'] == product]
|
||||||
|
future = sorted((row for row in prices if row['starts_at'] > now),
|
||||||
|
key=lambda row: (row['starts_at'], row['id']))
|
||||||
|
products.append({
|
||||||
|
'id': product, 'title': catalog.TITLES[product], 'unit': catalog.UNITS[product],
|
||||||
|
'enabled': state[product]['enabled'],
|
||||||
|
'unit_cents': state[product]['unit_cents'],
|
||||||
|
'bands': state[product]['bands'],
|
||||||
|
'fallback': product not in started,
|
||||||
|
'scheduled': [price_row(row) for row in future],
|
||||||
|
'history': [price_row(row) for row in prices[:20]],
|
||||||
|
})
|
||||||
|
return {'products': products}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/site/products/{product}')
|
||||||
|
def toggle_product(product: str, body: SiteProductToggle, user=Depends(can('manage'))):
|
||||||
|
if product not in catalog.PRODUCTS:
|
||||||
|
raise HTTPException(404, 'Produto não encontrado.')
|
||||||
|
with db.connect() as c:
|
||||||
|
c.execute('''INSERT INTO dtf_local.products(id, enabled, updated_by, updated_at)
|
||||||
|
VALUES(%s,%s,%s,now())
|
||||||
|
ON CONFLICT (id) DO UPDATE SET enabled=EXCLUDED.enabled,
|
||||||
|
updated_by=EXCLUDED.updated_by, updated_at=now()''',
|
||||||
|
(product, body.enabled, user))
|
||||||
|
audit('site_product_changed', product=product, enabled=body.enabled, operator=user)
|
||||||
|
return {'ok': True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/site/products/{product}/prices')
|
||||||
|
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 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
|
||||||
|
if starts_at.tzinfo is None:
|
||||||
|
starts_at = starts_at.replace(tzinfo=timezone.utc)
|
||||||
|
if starts_at < now - timedelta(minutes=1):
|
||||||
|
raise HTTPException(422, 'A data de início não pode estar no passado.')
|
||||||
|
with db.connect() as c:
|
||||||
|
row = c.execute('''INSERT INTO dtf_local.product_prices(product, unit_cents, starts_at, created_by, bands)
|
||||||
|
VALUES(%s,%s,%s,%s,%s) RETURNING id''',
|
||||||
|
(product, body.unit_cents, starts_at, user, Jsonb(bands))).fetchone()
|
||||||
|
audit('site_price_changed', product=product, unit_cents=body.unit_cents, bands=bands,
|
||||||
|
starts_at=starts_at.isoformat(), operator=user)
|
||||||
|
return {'id': row['id']}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/site/prices/{price_id}/cancel')
|
||||||
|
def cancel_price(price_id: int, user=Depends(can('manage'))):
|
||||||
|
with db.connect() as c:
|
||||||
|
row = c.execute('''SELECT id, product, unit_cents, starts_at
|
||||||
|
FROM dtf_local.product_prices WHERE id=%s FOR UPDATE''', (price_id,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(404, 'Preço não encontrado.')
|
||||||
|
if row['starts_at'] <= datetime.now(timezone.utc):
|
||||||
|
raise HTTPException(409, 'Este preço já começou: o histórico não pode ser apagado.')
|
||||||
|
c.execute('DELETE FROM dtf_local.product_prices WHERE id=%s', (price_id,))
|
||||||
|
audit('site_price_cancelled', price=price_id, product=row['product'], operator=user)
|
||||||
|
return {'ok': True}
|
||||||
|
|
||||||
|
|
||||||
|
def as_utc(value):
|
||||||
|
if value is None:
|
||||||
|
return None
|
||||||
|
return value if value.tzinfo else value.replace(tzinfo=timezone.utc)
|
||||||
|
|
||||||
|
|
||||||
|
def coupon_code(value):
|
||||||
|
code = (value or '').strip().upper()
|
||||||
|
if not re.fullmatch(r'[A-Z0-9-]{3,30}', code):
|
||||||
|
raise HTTPException(422, 'O código precisa ter de 3 a 30 letras, números ou hífens.')
|
||||||
|
return code
|
||||||
|
|
||||||
|
|
||||||
|
def check_coupon(kind, value, valid_from, valid_until):
|
||||||
|
if kind == 'percent' and not 1 <= value <= 90:
|
||||||
|
raise HTTPException(422, 'A porcentagem do cupom precisa ser de 1 a 90.')
|
||||||
|
if valid_until is not None and valid_until <= valid_from:
|
||||||
|
raise HTTPException(422, 'A validade final precisa ser depois do início.')
|
||||||
|
|
||||||
|
|
||||||
|
@router.get('/api/operator/site/coupons')
|
||||||
|
def site_coupons(user=Depends(can('manage'))):
|
||||||
|
with db.connect() as c:
|
||||||
|
rows = c.execute('''SELECT c.*, (SELECT count(*) FROM dtf_local.orders o
|
||||||
|
WHERE o.snapshot->'coupon'->>'id'=c.id::text
|
||||||
|
AND o.cancelled_at IS NULL AND COALESCE(o.payment->>'provider','') <> 'teste'
|
||||||
|
AND o.parent_id IS NULL) AS uses
|
||||||
|
FROM dtf_local.coupons c WHERE c.deleted_at IS NULL
|
||||||
|
ORDER BY c.paused, c.created_at DESC''').fetchall()
|
||||||
|
return {'coupons': [{'id': str(row['id']), 'code': row['code'], 'kind': row['kind'],
|
||||||
|
'value': row['value'], 'valid_from': row['valid_from'].isoformat(),
|
||||||
|
'valid_until': row['valid_until'].isoformat() if row['valid_until'] else None,
|
||||||
|
'min_metres': float(row['min_metres']) if row['min_metres'] is not None else None,
|
||||||
|
'max_uses': row['max_uses'], 'max_uses_per_customer': row['max_uses_per_customer'],
|
||||||
|
'product': row['product'], 'note': row['note'], 'paused': row['paused'],
|
||||||
|
'created_by': row['created_by'], 'created_at': row['created_at'].isoformat(),
|
||||||
|
'uses': row['uses']} for row in rows]}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/site/coupons')
|
||||||
|
def create_coupon(body: CouponNew, user=Depends(can('manage'))):
|
||||||
|
code = coupon_code(body.code)
|
||||||
|
valid_from = as_utc(body.valid_from) or datetime.now(timezone.utc)
|
||||||
|
valid_until = as_utc(body.valid_until)
|
||||||
|
check_coupon(body.kind, body.value, valid_from, valid_until)
|
||||||
|
coupon_id = uuid4()
|
||||||
|
try:
|
||||||
|
with db.connect() as c:
|
||||||
|
if c.execute('SELECT 1 FROM dtf_local.coupons WHERE code=%s AND deleted_at IS NULL',
|
||||||
|
(code,)).fetchone():
|
||||||
|
raise HTTPException(409, 'Já existe um cupom com este código.')
|
||||||
|
c.execute('''INSERT INTO dtf_local.coupons(id,code,kind,value,valid_from,valid_until,
|
||||||
|
min_metres,max_uses,max_uses_per_customer,product,note,created_by)
|
||||||
|
VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)''',
|
||||||
|
(coupon_id, code, body.kind, body.value, valid_from, valid_until, body.min_metres,
|
||||||
|
body.max_uses, body.max_uses_per_customer, body.product, body.note.strip(), user))
|
||||||
|
except UniqueViolation:
|
||||||
|
# Two requests with the same new code at once: the partial index decides.
|
||||||
|
raise HTTPException(409, 'Já existe um cupom com este código.')
|
||||||
|
audit('site_coupon_created', coupon=str(coupon_id), code=code, operator=user)
|
||||||
|
return {'id': str(coupon_id)}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/site/coupons/{coupon_id}')
|
||||||
|
def update_coupon(coupon_id: UUID, body: CouponUpdate, user=Depends(can('manage'))):
|
||||||
|
fields = body.model_dump(exclude_unset=True)
|
||||||
|
# The form never sends null for these; a null would try to write NULL into
|
||||||
|
# a NOT NULL column, so an explicit null means "keep what is there".
|
||||||
|
for name in ('kind', 'value', 'paused'):
|
||||||
|
if name in fields and fields[name] is None:
|
||||||
|
fields.pop(name)
|
||||||
|
with db.connect() as c:
|
||||||
|
row = c.execute('''SELECT * FROM dtf_local.coupons
|
||||||
|
WHERE id=%s AND deleted_at IS NULL FOR UPDATE''', (coupon_id,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(404, 'Cupom não encontrado.')
|
||||||
|
kind = fields.get('kind', row['kind'])
|
||||||
|
value = fields.get('value', row['value'])
|
||||||
|
valid_from = as_utc(fields['valid_from']) if 'valid_from' in fields else row['valid_from']
|
||||||
|
valid_from = valid_from or row['valid_from']
|
||||||
|
valid_until = as_utc(fields['valid_until']) if 'valid_until' in fields else row['valid_until']
|
||||||
|
check_coupon(kind, value, valid_from, valid_until)
|
||||||
|
if 'valid_from' in fields:
|
||||||
|
fields['valid_from'] = valid_from
|
||||||
|
if 'valid_until' in fields:
|
||||||
|
fields['valid_until'] = valid_until
|
||||||
|
if 'note' in fields:
|
||||||
|
fields['note'] = (fields['note'] or '').strip()
|
||||||
|
if fields:
|
||||||
|
names = list(fields)
|
||||||
|
c.execute(f'''UPDATE dtf_local.coupons SET {', '.join(f'{name}=%s' for name in names)}
|
||||||
|
WHERE id=%s''', (*[fields[name] for name in names], coupon_id))
|
||||||
|
audit('site_coupon_updated', coupon=str(coupon_id), operator=user)
|
||||||
|
return {'ok': True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/site/coupons/{coupon_id}/delete')
|
||||||
|
def delete_coupon(coupon_id: UUID, user=Depends(can('manage'))):
|
||||||
|
with db.connect() as c:
|
||||||
|
row = c.execute('''UPDATE dtf_local.coupons SET deleted_at=now()
|
||||||
|
WHERE id=%s AND deleted_at IS NULL RETURNING code''', (coupon_id,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(404, 'Cupom não encontrado.')
|
||||||
|
audit('site_coupon_deleted', coupon=str(coupon_id), code=row['code'], operator=user)
|
||||||
|
return {'ok': True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get('/api/operator/site/grade-rules')
|
||||||
|
def site_grade_rules(user=Depends(can('manage'))):
|
||||||
|
with db.connect() as c:
|
||||||
|
rules = grade_rules.current_rules(c)
|
||||||
|
offered = catalog.treatment_offered(c)
|
||||||
|
return {'aviso': rules.get('aviso'), 'tratamento': rules.get('tratamento'),
|
||||||
|
'treatment_offered': offered}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/site/grade-rules')
|
||||||
|
def save_grade_rules(body: GradeRules, user=Depends(can('manage'))):
|
||||||
|
if body.aviso is not None and body.tratamento is not None and body.tratamento > body.aviso:
|
||||||
|
raise HTTPException(422, 'A regra do Ajuste Fino precisa ser menor ou igual à do aviso.')
|
||||||
|
with db.connect() as c:
|
||||||
|
for action, below in (('aviso', body.aviso), ('tratamento', body.tratamento)):
|
||||||
|
if below is None:
|
||||||
|
c.execute('DELETE FROM dtf_local.grade_rules WHERE action=%s', (action,))
|
||||||
|
else:
|
||||||
|
c.execute('''INSERT INTO dtf_local.grade_rules(action,below,updated_by,updated_at)
|
||||||
|
VALUES(%s,%s,%s,now())
|
||||||
|
ON CONFLICT (action) DO UPDATE SET below=EXCLUDED.below,
|
||||||
|
updated_by=EXCLUDED.updated_by, updated_at=now()''',
|
||||||
|
(action, below, user))
|
||||||
|
audit('site_grade_rules_changed', aviso=body.aviso, tratamento=body.tratamento, operator=user)
|
||||||
|
return {'ok': True}
|
||||||
164
app/api/site_videos.py
Normal file
164
app/api/site_videos.py
Normal file
@@ -0,0 +1,164 @@
|
|||||||
|
"""Six DTF videos, managed by Gestão and published only after virus scanning."""
|
||||||
|
from typing import Literal
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, Response
|
||||||
|
from pydantic import Field
|
||||||
|
|
||||||
|
from ..core import db
|
||||||
|
from ..core.auth import audit, can, operator
|
||||||
|
from ..core.models import StrictModel
|
||||||
|
from ..runtime import operator_identity, storage, upload_row
|
||||||
|
from ..scanning import require_clean
|
||||||
|
from .uploads import begin_upload
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
CATALOG = {
|
||||||
|
'subindo': 'Subindo a arte pelo celular',
|
||||||
|
'nota': 'O que é a nota da arte — e o que ela não é',
|
||||||
|
'png': 'Por que PNG com fundo transparente',
|
||||||
|
'avulsas': 'Montando artes avulsas e vendo a folha ao vivo',
|
||||||
|
'retirada': 'Retirada em Franca em 24 h',
|
||||||
|
'sala': 'A sala às 3 da manhã',
|
||||||
|
}
|
||||||
|
VIDEO_MAX = 500 * 1024 * 1024
|
||||||
|
CAPTIONS_MAX = 1024 * 1024
|
||||||
|
|
||||||
|
|
||||||
|
class VideoUpdate(StrictModel):
|
||||||
|
upload_id: UUID | None = None
|
||||||
|
captions_id: UUID | None = None
|
||||||
|
product: Literal['file', 'avulsa', 'uvfile', 'uv'] | None = None
|
||||||
|
enabled: bool = False
|
||||||
|
|
||||||
|
|
||||||
|
class VideoUploadStart(StrictModel):
|
||||||
|
name: str = Field(min_length=1, max_length=200, pattern=r'^[^/\\\x00-\x1f]+$')
|
||||||
|
size: int = Field(gt=0, strict=True)
|
||||||
|
|
||||||
|
|
||||||
|
def _kind(upload):
|
||||||
|
name = upload['name'].lower()
|
||||||
|
if name.endswith('.mp4') and upload['size'] <= VIDEO_MAX:
|
||||||
|
return 'video/mp4', b'ftyp', 4
|
||||||
|
if name.endswith('.webm') and upload['size'] <= VIDEO_MAX:
|
||||||
|
return 'video/webm', b'\x1a\x45\xdf\xa3', 0
|
||||||
|
if name.endswith('.vtt') and upload['size'] <= CAPTIONS_MAX:
|
||||||
|
return 'text/vtt', b'WEBVTT', 0
|
||||||
|
raise HTTPException(422, 'Use MP4/WebM de até 500 MB ou legenda VTT de até 1 MB.')
|
||||||
|
|
||||||
|
|
||||||
|
def _checked_upload(c, uid, identity, expected):
|
||||||
|
upload = upload_row(c, uid, identity, lock=True)
|
||||||
|
if not upload['complete']:
|
||||||
|
raise HTTPException(409, 'Espere o envio terminar.')
|
||||||
|
require_clean(upload)
|
||||||
|
mime, signature, offset = _kind(upload)
|
||||||
|
if mime not in expected:
|
||||||
|
raise HTTPException(422, 'Escolha um vídeo MP4/WebM e uma legenda VTT.')
|
||||||
|
response = storage.client.get_object(Bucket=storage.bucket, Key=upload['object_key'], Range='bytes=0-31')
|
||||||
|
head = response['Body'].read()
|
||||||
|
if not head[offset:].startswith(signature) and not (mime == 'text/vtt' and head.startswith(b'\xef\xbb\xbfWEBVTT')):
|
||||||
|
raise HTTPException(422, 'O conteúdo do arquivo não corresponde à extensão.')
|
||||||
|
return upload, mime
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/site-videos/uploads')
|
||||||
|
def start_video_upload(body: VideoUploadStart, user=Depends(can('manage'))):
|
||||||
|
_kind({'name': body.name, 'size': body.size})
|
||||||
|
return begin_upload(body, session_id=operator_identity(user))
|
||||||
|
|
||||||
|
|
||||||
|
@router.get('/api/operator/site-videos')
|
||||||
|
def manage_videos(user=Depends(operator)):
|
||||||
|
with db.connect() as c:
|
||||||
|
rows = {row['id']: row for row in c.execute('''SELECT v.*,
|
||||||
|
u.name AS video_name, t.name AS captions_name
|
||||||
|
FROM dtf_local.site_videos v
|
||||||
|
LEFT JOIN dtf_local.uploads u ON u.id=v.upload_id
|
||||||
|
LEFT JOIN dtf_local.uploads t ON t.id=v.captions_id''').fetchall()}
|
||||||
|
return {'videos': [dict(id=id, title=title,
|
||||||
|
product=rows[id]['product'] if id in rows else None,
|
||||||
|
upload_id=rows[id]['upload_id'] if id in rows else None,
|
||||||
|
captions_id=rows[id]['captions_id'] if id in rows else None,
|
||||||
|
video_name=rows[id]['video_name'] if id in rows else None,
|
||||||
|
captions_name=rows[id]['captions_name'] if id in rows else None,
|
||||||
|
enabled=rows[id]['enabled'] if id in rows else False)
|
||||||
|
for id, title in CATALOG.items()]}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/site-videos/{video_id}')
|
||||||
|
def update_video(video_id: str, body: VideoUpdate, user=Depends(can('manage'))):
|
||||||
|
if video_id not in CATALOG:
|
||||||
|
raise HTTPException(404, 'Vídeo não encontrado.')
|
||||||
|
if body.enabled and not body.upload_id:
|
||||||
|
raise HTTPException(422, 'Envie o vídeo antes de publicar.')
|
||||||
|
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 (
|
||||||
|
(body.upload_id, ('video/mp4','video/webm'), previous.get('upload_id'), previous.get('video_key')),
|
||||||
|
(body.captions_id, ('text/vtt',), previous.get('captions_id'), previous.get('captions_key'))):
|
||||||
|
if not uid:
|
||||||
|
keys.append(None)
|
||||||
|
elif uid == previous_id and previous_key:
|
||||||
|
keys.append(previous_key)
|
||||||
|
else:
|
||||||
|
upload, mime = _checked_upload(c, uid, identity, expected)
|
||||||
|
key = f'videos/{video_id}/{uid}{".vtt" if mime == "text/vtt" else ".webm" if mime == "video/webm" else ".mp4"}'
|
||||||
|
storage.client.copy_object(Bucket=storage.bucket,
|
||||||
|
CopySource={'Bucket': storage.bucket, 'Key': upload['object_key']},
|
||||||
|
Key=key, ContentType=mime, MetadataDirective='REPLACE')
|
||||||
|
keys.append(key)
|
||||||
|
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,
|
||||||
|
video_key=EXCLUDED.video_key,captions_key=EXCLUDED.captions_key,
|
||||||
|
product=EXCLUDED.product,enabled=EXCLUDED.enabled,updated_by=EXCLUDED.updated_by,updated_at=now()''',
|
||||||
|
(video_id, body.upload_id, body.captions_id, keys[0], keys[1], body.product, body.enabled, user))
|
||||||
|
ids = [uid for uid in (body.upload_id, body.captions_id) if uid]
|
||||||
|
if ids:
|
||||||
|
c.execute("UPDATE dtf_local.uploads SET expires_at=GREATEST(expires_at,now()+interval '30 days') WHERE id=ANY(%s)", (ids,))
|
||||||
|
audit('site_video_changed', video=video_id, operator=user, enabled=body.enabled)
|
||||||
|
return {'ok': True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get('/api/site/videos')
|
||||||
|
def published_videos():
|
||||||
|
with db.connect() as c:
|
||||||
|
rows = c.execute('''SELECT v.id,v.product,v.video_key,v.captions_key,u.name AS video_name
|
||||||
|
FROM dtf_local.site_videos v
|
||||||
|
JOIN dtf_local.uploads u ON u.id=v.upload_id
|
||||||
|
WHERE v.enabled AND v.video_key IS NOT NULL''').fetchall()
|
||||||
|
return {'videos': [dict(id=row['id'], product=row['product'],
|
||||||
|
src=storage.view(row['video_key'], _kind({'name':row['video_name'],'size':0})[0]),
|
||||||
|
captions=f"/api/site/videos/{row['id']}/captions" if row['captions_key'] else None)
|
||||||
|
for row in rows]}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get('/api/site/videos/{video_id}/captions')
|
||||||
|
def published_captions(video_id: str):
|
||||||
|
if video_id not in CATALOG:
|
||||||
|
raise HTTPException(404, 'Legenda não encontrada.')
|
||||||
|
with db.connect() as c:
|
||||||
|
row = c.execute('''SELECT captions_key FROM dtf_local.site_videos
|
||||||
|
WHERE id=%s AND enabled AND video_key IS NOT NULL AND captions_key IS NOT NULL''',
|
||||||
|
(video_id,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(404, 'Legenda não encontrada.')
|
||||||
|
obj = storage.client.get_object(Bucket=storage.bucket, Key=row['captions_key'])
|
||||||
|
body = obj['Body'].read(CAPTIONS_MAX + 1)
|
||||||
|
if len(body) > CAPTIONS_MAX:
|
||||||
|
raise HTTPException(500, 'Legenda inválida.')
|
||||||
|
return Response(body, media_type='text/vtt', headers={'Cache-Control': 'public, max-age=300'})
|
||||||
168
app/api/stamps.py
Normal file
168
app/api/stamps.py
Normal file
@@ -0,0 +1,168 @@
|
|||||||
|
"""The montador's stamp sizes, its brand per stamp, the internal customer and
|
||||||
|
the Interno and Venda orders a sheet becomes (Fase 2, fronts 7a to 7a.3)."""
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||||
|
from psycopg.types.json import Jsonb
|
||||||
|
|
||||||
|
from .. import payments, quote_review
|
||||||
|
from ..core import db
|
||||||
|
from ..core.auth import audit, can, roles_of
|
||||||
|
from ..core.models import (Customer, Freight, MontadorOrder, QuoteRequest, StampBrand,
|
||||||
|
StampSizeTable, UploadStart)
|
||||||
|
from ..runtime import operator_identity
|
||||||
|
from .uploads import begin_upload
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
# 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
|
||||||
|
# administrators both.
|
||||||
|
MONTADOR_KINDS = {'expedicao': {'interno'}, 'vendedor': {'venda'},
|
||||||
|
'superadmin': {'interno', 'venda'}, 'admin': {'interno', 'venda'},
|
||||||
|
'gestao': {'interno', 'venda'}}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get('/api/operator/stamp-sizes')
|
||||||
|
def stamp_sizes(user=Depends(can('assemble'))):
|
||||||
|
with db.connect() as c:
|
||||||
|
rows = c.execute('SELECT letter,width_cm FROM dtf_local.stamp_sizes ORDER BY width_cm, letter').fetchall()
|
||||||
|
return {'sizes': rows}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/stamp-sizes')
|
||||||
|
def save_stamp_sizes(body: StampSizeTable, user=Depends(can('manage'))):
|
||||||
|
with db.connect() as c:
|
||||||
|
c.execute('DELETE FROM dtf_local.stamp_sizes')
|
||||||
|
c.cursor().executemany('INSERT INTO dtf_local.stamp_sizes(letter,width_cm,updated_by) VALUES(%s,%s,%s)',
|
||||||
|
[(row.letter, row.width_cm, user) for row in body.sizes])
|
||||||
|
audit('stamp_sizes_changed', operator=user, sizes=len(body.sizes))
|
||||||
|
return {'ok': True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get('/api/operator/internal-customer')
|
||||||
|
def read_internal_customer(user=Depends(can('assemble'))):
|
||||||
|
"""The customer every Interno order belongs to; empty fields mean Gestão
|
||||||
|
still has to complete it."""
|
||||||
|
with db.connect() as c:
|
||||||
|
row = c.execute('SELECT name,cnpj,zap,mail FROM dtf_local.internal_customer').fetchone()
|
||||||
|
return row or {'name': '', 'cnpj': '', 'zap': '', 'mail': ''}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/internal-customer')
|
||||||
|
def save_internal_customer(body: Customer, user=Depends(can('manage'))):
|
||||||
|
with db.connect() as c:
|
||||||
|
c.execute('''INSERT INTO dtf_local.internal_customer(id,name,cnpj,zap,mail,updated_by,updated_at)
|
||||||
|
VALUES(1,%s,%s,%s,%s,%s,now()) ON CONFLICT(id) DO UPDATE SET name=EXCLUDED.name,
|
||||||
|
cnpj=EXCLUDED.cnpj, zap=EXCLUDED.zap, mail=EXCLUDED.mail,
|
||||||
|
updated_by=EXCLUDED.updated_by, updated_at=now()''',
|
||||||
|
(body.name, body.cnpj, body.zap, body.mail, user))
|
||||||
|
audit('internal_customer_changed', operator=user)
|
||||||
|
return {'ok': True}
|
||||||
|
|
||||||
|
|
||||||
|
def internal_customer(c):
|
||||||
|
"""The fixed Interno customer, ready to use, or the reason Gestão must
|
||||||
|
complete it first."""
|
||||||
|
row = c.execute('SELECT name,cnpj,zap,mail FROM dtf_local.internal_customer').fetchone()
|
||||||
|
if not row or not all(str(row[key] or '').strip() for key in ('name', 'cnpj', 'zap', 'mail')):
|
||||||
|
raise HTTPException(409, INTERNAL_MISSING)
|
||||||
|
try:
|
||||||
|
return Customer(**row)
|
||||||
|
except ValueError:
|
||||||
|
raise HTTPException(409, INTERNAL_MISSING) from None
|
||||||
|
|
||||||
|
|
||||||
|
@router.get('/api/operator/stamps/{code}')
|
||||||
|
def read_stamp(code: str, user=Depends(can('assemble'))):
|
||||||
|
"""The brand recorded for a stamp code; nothing else uses it yet."""
|
||||||
|
if not CODE.fullmatch(code):
|
||||||
|
raise HTTPException(422, 'Código inválido.')
|
||||||
|
with db.connect() as c:
|
||||||
|
row = c.execute('SELECT code,brand,public FROM dtf_local.stamps WHERE code=%s', (code,)).fetchone()
|
||||||
|
return row or {'code': code, 'brand': '', 'public': False}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/stamps/{code}')
|
||||||
|
def save_stamp(code: str, body: StampBrand, user=Depends(can('manage'))):
|
||||||
|
if not CODE.fullmatch(code):
|
||||||
|
raise HTTPException(422, 'Código inválido.')
|
||||||
|
brand = body.brand.strip()
|
||||||
|
with db.connect() as c:
|
||||||
|
c.execute('''INSERT INTO dtf_local.stamps(code,brand,public,updated_by,updated_at)
|
||||||
|
VALUES(%s,%s,%s,%s,now()) ON CONFLICT(code) DO UPDATE SET brand=EXCLUDED.brand,
|
||||||
|
public=EXCLUDED.public, updated_by=EXCLUDED.updated_by, updated_at=now()''',
|
||||||
|
(code, brand, body.public, user))
|
||||||
|
audit('stamp_brand_saved', code=code, operator=user, public=body.public)
|
||||||
|
return {'ok': True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/montador/uploads')
|
||||||
|
def montador_upload(body: UploadStart, user=Depends(can('assemble'))):
|
||||||
|
if not body.name.lower().endswith('.png'):
|
||||||
|
raise HTTPException(422, 'A estampa precisa ser um PNG.')
|
||||||
|
return begin_upload(body, session_id=operator_identity(user))
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/montador/orders')
|
||||||
|
def montador_order(body: MontadorOrder, request: Request, user=Depends(can('assemble'))):
|
||||||
|
"""The card a montador sheet becomes (fronts 7a.3 and 7a.4): Interno (the
|
||||||
|
fixed internal customer, origin dropflow, never Tiny) or Venda (a Tiny
|
||||||
|
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."""
|
||||||
|
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':
|
||||||
|
customer = internal_customer(c)
|
||||||
|
origin, method = 'dropflow', payments.INTERNAL_METHOD
|
||||||
|
else:
|
||||||
|
customer = body.customer
|
||||||
|
origin, method = 'atendimento', payments.INVOICED_METHOD
|
||||||
|
draft = QuoteRequest(request_key=body.request_key, customer=customer, items=body.items,
|
||||||
|
freight=body.freight or Freight(service='pickup'),
|
||||||
|
destination=body.destination).model_dump(mode='json', exclude={'request_key'})
|
||||||
|
draft['montador'] = True
|
||||||
|
draft['kind'] = body.kind
|
||||||
|
if body.with_order:
|
||||||
|
draft['with_order'] = body.with_order
|
||||||
|
digest = hashlib.sha256(json.dumps(draft, sort_keys=True).encode()).hexdigest()
|
||||||
|
owner = operator_identity(user)
|
||||||
|
c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft)
|
||||||
|
VALUES(%s,%s,%s,%s,%s) ON CONFLICT(owner,request_key) DO NOTHING''',
|
||||||
|
(uuid4(), owner, body.request_key, digest, Jsonb(draft)))
|
||||||
|
quote = c.execute('SELECT * FROM dtf_local.quotes WHERE owner=%s AND request_key=%s FOR UPDATE',
|
||||||
|
(owner, body.request_key)).fetchone()
|
||||||
|
if quote['request_hash'] != digest:
|
||||||
|
raise HTTPException(409, 'A montagem mudou durante o envio. Tente de novo.')
|
||||||
|
if not quote['approved']:
|
||||||
|
approved = quote_review.approve(c, quote, body.items, user)
|
||||||
|
# The order's kind and the clothing order it travels with, on the
|
||||||
|
# card and in Tiny's internal note.
|
||||||
|
approved = {**approved, 'kind': body.kind,
|
||||||
|
**({'with_order': body.with_order} if body.with_order else {})}
|
||||||
|
# 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()
|
||||||
|
receipt = {'provider': payments.MANUAL_PROVIDER, 'method': method, 'note': '',
|
||||||
|
'status': 'paid', 'total_cents': quote['approved']['total_cents'], 'operator': user}
|
||||||
|
order, created = payments.create_order(c, quote, receipt, origin)
|
||||||
|
if not created:
|
||||||
|
raise HTTPException(409, f"Esta montagem já virou o pedido #{order['number']}.")
|
||||||
|
audit('montador_order_created', order=str(order['id']), origin=origin, kind=body.kind, operator=user)
|
||||||
|
return order
|
||||||
@@ -12,7 +12,7 @@ from fastapi import APIRouter, Depends, HTTPException, Request
|
|||||||
from starlette.concurrency import run_in_threadpool
|
from starlette.concurrency import run_in_threadpool
|
||||||
|
|
||||||
from ..core import db
|
from ..core import db
|
||||||
from ..core.auth import audit, owner, rate_limit
|
from ..core.auth import audit, client_ip, owner, rate_limit
|
||||||
from ..core.limits import upload_limit_bytes
|
from ..core.limits import upload_limit_bytes
|
||||||
from ..core.models import UploadStart
|
from ..core.models import UploadStart
|
||||||
from ..payments import UNPAID_HOLD
|
from ..payments import UNPAID_HOLD
|
||||||
@@ -20,30 +20,53 @@ from ..runtime import PART_BYTES, storage, upload_row
|
|||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
|
|
||||||
|
# A cart of many files: 66 in Marcus's case (2026-11-11), and adding more or
|
||||||
|
# retrying must fit. The per-source bucket bounds abuse, not a real order.
|
||||||
|
UPLOAD_START_LIMIT = 1000
|
||||||
|
UPLOAD_START_IP_LIMIT = 3000
|
||||||
|
# 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):
|
||||||
|
"""The public upload route's per-source bucket. The operator upload routes
|
||||||
|
reuse begin_upload directly and stay bound by their own session bucket."""
|
||||||
|
rate_limit('upload-start-ip', client_ip(request), UPLOAD_START_IP_LIMIT, 900)
|
||||||
|
|
||||||
|
|
||||||
@router.post('/api/uploads')
|
@router.post('/api/uploads')
|
||||||
def begin_upload(body: UploadStart, session_id=Depends(owner)):
|
def begin_upload(body: UploadStart, session_id=Depends(owner), _source=Depends(upload_ip_limit)):
|
||||||
if body.size > upload_limit_bytes():
|
if body.size > upload_limit_bytes():
|
||||||
raise HTTPException(413, 'O arquivo passa do tamanho máximo aceito. Escolha um arquivo menor.')
|
raise HTTPException(413, 'O arquivo passa do tamanho máximo aceito. Escolha um arquivo menor.')
|
||||||
uid = uuid4()
|
uid = uuid4()
|
||||||
key = f'originals/{uid}'
|
key = f'originals/{uid}'
|
||||||
rate_limit('upload-start', str(session_id), 60, 900)
|
rate_limit('upload-start', str(session_id), UPLOAD_START_LIMIT, 900)
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
# Serialize reservations across API processes, including changing guest IDs.
|
# Serialize reservations across API processes, including changing guest IDs.
|
||||||
c.execute('SELECT pg_advisory_xact_lock(804208)')
|
c.execute('SELECT pg_advisory_xact_lock(804208)')
|
||||||
usage = c.execute('''SELECT COALESCE(sum(size),0) AS total,
|
usage = c.execute('''SELECT COALESCE(sum(size),0) AS total,
|
||||||
COALESCE(sum(size) FILTER(WHERE owner=%s),0) AS owned,
|
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''',
|
FROM dtf_local.uploads WHERE purged_at IS NULL''',
|
||||||
(session_id,session_id)).fetchone()
|
(session_id,session_id,PENDING_IDLE_MINUTES)).fetchone()
|
||||||
if (usage['total']+body.size > int(os.environ.get('STORAGE_QUOTA_BYTES','53687091200')) or
|
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')) or
|
usage['owned']+body.size > int(os.environ.get('OWNER_UPLOAD_QUOTA_BYTES','10737418240')))
|
||||||
usage['pending'] >= int(os.environ.get('MAX_PENDING_UPLOADS','10'))):
|
pending_full = usage['pending'] >= int(os.environ.get('MAX_PENDING_UPLOADS','30'))
|
||||||
|
if storage_full or pending_full:
|
||||||
audit('upload_quota_rejected')
|
audit('upload_quota_rejected')
|
||||||
|
if pending_full and not storage_full:
|
||||||
|
# A big cart goes 4 at a time now (web/upload.js); a burst may
|
||||||
|
# still meet the pending cap: ask the Site to wait and retry.
|
||||||
|
raise HTTPException(429, 'Muitos envios ao mesmo tempo. O site tenta de novo sozinho.',
|
||||||
|
headers={'Retry-After': '15'})
|
||||||
raise HTTPException(429, 'Limite de armazenamento ou de envios pendentes atingido. Tente de novo mais tarde.')
|
raise HTTPException(429, 'Limite de armazenamento ou de envios pendentes atingido. Tente de novo mais tarde.')
|
||||||
multipart = storage.begin(key)
|
multipart = storage.begin(key)
|
||||||
c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,expires_at)
|
c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,original_name,size,object_key,multipart_id,expires_at)
|
||||||
VALUES(%s,%s,%s,%s,%s,%s,now()+interval '1 hour')''',
|
VALUES(%s,%s,%s,%s,%s,%s,%s,now()+interval '1 hour')''',
|
||||||
(uid, session_id, body.name, body.size, key, multipart))
|
(uid, session_id, body.name, body.name, body.size, key, multipart))
|
||||||
return {'id': uid, 'part_bytes': PART_BYTES}
|
return {'id': uid, 'part_bytes': PART_BYTES}
|
||||||
|
|
||||||
@router.get('/api/uploads/{uid}')
|
@router.get('/api/uploads/{uid}')
|
||||||
|
|||||||
138
app/api/users.py
138
app/api/users.py
@@ -5,6 +5,7 @@ changes it in "Minha senha". The superadmin is the system's own account, set fro
|
|||||||
administrators manage everyone else. Nobody can remove, disable or demote
|
administrators manage everyone else. Nobody can remove, disable or demote
|
||||||
themselves, so the last administrator cannot lock the team out by accident.
|
themselves, so the last administrator cannot lock the team out by accident.
|
||||||
"""
|
"""
|
||||||
|
import os
|
||||||
import re
|
import re
|
||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
from typing import Literal
|
from typing import Literal
|
||||||
@@ -13,25 +14,39 @@ from uuid import UUID, uuid4
|
|||||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||||
from pydantic import Field, field_validator
|
from pydantic import Field, field_validator
|
||||||
|
|
||||||
from .. import machines, mail
|
from .. import machines, mail, observability
|
||||||
from ..core import db
|
from ..core import db
|
||||||
from ..core.auth import (CAPABILITIES, MACHINE_QUESTION, audit, can, may_move, may_reorder, password_hash,
|
from ..core.auth import (CAPABILITIES, audit, can, has, machine_bound, machine_question, may_move, may_reorder,
|
||||||
password_matches, signed_in)
|
password_hash, password_matches, roles_of, signed_in)
|
||||||
from ..core.models import StrictModel
|
from ..core.models import StrictModel
|
||||||
from ..runtime import BACK, STATES, TRANSITIONS
|
from ..runtime import BACK, ENVIRONMENT, STATES, TRANSITIONS
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
|
|
||||||
|
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):
|
class UserIn(StrictModel):
|
||||||
# The profiles an administrator may give; superadmin only comes from the console.
|
# The profiles an administrator may give; superadmin only comes from the console.
|
||||||
name: str = Field(min_length=1, max_length=80)
|
name: str = Field(min_length=1, max_length=80)
|
||||||
email: str = Field(min_length=3, max_length=254)
|
email: str = Field(min_length=3, max_length=254)
|
||||||
role: Literal['admin', 'gestao', 'designer', 'operador', 'revisor', 'vendedor', 'financeiro']
|
# 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)
|
password: str | None = Field(default=None, min_length=8, max_length=128)
|
||||||
active: bool = True
|
active: bool = True
|
||||||
# No longer used: an operator's machine is the one chosen after signing in
|
# No longer used: an operator's machine is the one chosen after signing in
|
||||||
# (item 12). Kept so a page loaded before still saves.
|
# (item 12). Kept so a page loaded before still saves.
|
||||||
machines: list[UUID] = Field(default_factory=list, max_length=50)
|
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')
|
@field_validator('email')
|
||||||
@classmethod
|
@classmethod
|
||||||
@@ -41,6 +56,10 @@ class UserIn(StrictModel):
|
|||||||
raise ValueError('Informe um e-mail válido.')
|
raise ValueError('Informe um e-mail válido.')
|
||||||
return value
|
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):
|
class MachineIn(StrictModel):
|
||||||
name: str = Field(min_length=1, max_length=60)
|
name: str = Field(min_length=1, max_length=60)
|
||||||
@@ -48,11 +67,18 @@ class MachineIn(StrictModel):
|
|||||||
active: bool = True
|
active: bool = True
|
||||||
# Metres open before the next order goes to another machine; None is no limit.
|
# 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)
|
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
|
# 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.
|
# signing in. Kept so a page loaded before still saves.
|
||||||
operators: list[UUID] | None = Field(default=None, max_length=200)
|
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):
|
class PasswordChange(StrictModel):
|
||||||
current: str = Field(min_length=1, max_length=128)
|
current: str = Field(min_length=1, max_length=128)
|
||||||
new: str = Field(min_length=8, max_length=128)
|
new: str = Field(min_length=8, max_length=128)
|
||||||
@@ -64,15 +90,22 @@ def me(request: Request):
|
|||||||
their profile makes (forward, and the step back) and the columns whose
|
their profile makes (forward, and the step back) and the columns whose
|
||||||
order they set."""
|
order they set."""
|
||||||
account = signed_in(request)
|
account = signed_in(request)
|
||||||
role = account['role']
|
role, roles = account['role'], roles_of(account)
|
||||||
moves = [[a, b] for a, nexts in TRANSITIONS.items() for b in nexts if may_move(role, a, b)]
|
moves = [[a, b] for a, nexts in TRANSITIONS.items() for b in nexts if may_move(roles, a, b)]
|
||||||
moves += [[a, b] for a, b in BACK.items() if may_move(role, a, b, back=True)]
|
moves += [[a, b] for a, b in BACK.items() if may_move(roles, a, b, back=True)]
|
||||||
return {'email': account['email'], 'name': account['name'], 'role': role,
|
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).
|
# 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'],
|
'machine_answered': account['machine_answered'],
|
||||||
'can': sorted(cap for cap, roles in CAPABILITIES.items() if role in roles),
|
'can': sorted(cap for cap in CAPABILITIES if has(account, cap)),
|
||||||
'moves': moves, 'reorder': [state for state in STATES if may_reorder(role, state)]}
|
'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):
|
class MachineAnswer(StrictModel):
|
||||||
@@ -89,7 +122,7 @@ def choose_session_machine(body: MachineAnswer, request: Request):
|
|||||||
person runs two machines from two computers. Someone else already on it is
|
person runs two machines from two computers. Someone else already on it is
|
||||||
a warning, not a refusal: shifts overlap for a few minutes."""
|
a warning, not a refusal: shifts overlap for a few minutes."""
|
||||||
account = signed_in(request)
|
account = signed_in(request)
|
||||||
question = MACHINE_QUESTION.get(account['role'])
|
question = machine_question(account)
|
||||||
if not question:
|
if not question:
|
||||||
raise HTTPException(403, 'Seu perfil não trabalha em máquina.')
|
raise HTTPException(403, 'Seu perfil não trabalha em máquina.')
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
@@ -128,13 +161,20 @@ def change_password(body: PasswordChange, request: Request):
|
|||||||
|
|
||||||
def user_rows(c):
|
def user_rows(c):
|
||||||
"""Every account, with the machines its open sessions are on now (item 12)."""
|
"""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,
|
||||||
COALESCE(array_agg(DISTINCT s.machine_id) FILTER (WHERE s.machine_id IS NOT NULL), '{}') AS machines
|
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
|
||||||
|
WHERE x.username=o.email AND x.expires_at>now()) AS seen_at
|
||||||
FROM dtf_local.operators o LEFT JOIN dtf_local.operator_sessions s
|
FROM dtf_local.operators o LEFT JOIN dtf_local.operator_sessions s
|
||||||
ON s.username=o.email AND s.expires_at>now() AND s.machine_id IS NOT NULL
|
ON s.username=o.email AND s.expires_at>now() AND s.machine_id IS NOT NULL
|
||||||
GROUP BY o.id ORDER BY o.active DESC, o.name, o.email''').fetchall()
|
GROUP BY o.id ORDER BY o.active DESC, o.name, o.email''').fetchall()
|
||||||
for row in rows:
|
for row in rows:
|
||||||
row['machines'] = [str(m) for m in row['machines']]
|
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
|
return rows
|
||||||
|
|
||||||
|
|
||||||
@@ -162,10 +202,12 @@ def create_user(body: UserIn, request: Request, user=Depends(can('users'))):
|
|||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
if c.execute('SELECT 1 FROM dtf_local.operators WHERE email=%s', (body.email,)).fetchone():
|
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.')
|
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)
|
seller = body.tiny_seller
|
||||||
VALUES(%s,%s,%s,%s,%s,%s)''', (uid, body.email, body.name.strip(), password_hash(body.password),
|
c.execute('''INSERT INTO dtf_local.operators(id,email,name,password_hash,role,roles,active,tiny_seller_id,tiny_seller_name)
|
||||||
body.role, body.active))
|
VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s)''', (uid, body.email, body.name.strip(), password_hash(body.password),
|
||||||
audit('operator_created', operator=user, account=body.email, role=body.role)
|
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)}
|
return {'id': str(uid)}
|
||||||
|
|
||||||
|
|
||||||
@@ -176,13 +218,16 @@ def update_user(uid: UUID, body: UserIn, request: Request, user=Depends(can('use
|
|||||||
row = target(c, uid, request)
|
row = target(c, uid, request)
|
||||||
# A superadmin keeps that profile: the form offers only the assignable ones.
|
# A superadmin keeps that profile: the form offers only the assignable ones.
|
||||||
role = row['role'] if row['role'] == 'superadmin' else body.role
|
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.')
|
raise HTTPException(409, 'Você não pode desativar a sua conta nem mudar o seu perfil.')
|
||||||
if body.email != row['email'] and c.execute(
|
if body.email != row['email'] and c.execute(
|
||||||
'SELECT 1 FROM dtf_local.operators WHERE email=%s AND id<>%s', (body.email, uid)).fetchone():
|
'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.')
|
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',
|
seller = body.tiny_seller
|
||||||
(body.name.strip(), body.email, role, body.active, uid))
|
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:
|
if body.password:
|
||||||
c.execute('UPDATE dtf_local.operators SET password_hash=%s WHERE id=%s', (password_hash(body.password), uid))
|
c.execute('UPDATE dtf_local.operators SET password_hash=%s WHERE id=%s', (password_hash(body.password), uid))
|
||||||
if body.email != row['email']:
|
if body.email != row['email']:
|
||||||
@@ -190,7 +235,7 @@ def update_user(uid: UUID, body: UserIn, request: Request, user=Depends(can('use
|
|||||||
if not body.active or body.password:
|
if not body.active or body.password:
|
||||||
# Disabled, or given a new password: whoever was signed in signs in again.
|
# 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,))
|
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))
|
password_reset=bool(body.password))
|
||||||
return {'ok': True}
|
return {'ok': True}
|
||||||
|
|
||||||
@@ -224,11 +269,14 @@ def list_machines(user=Depends(can('view'))):
|
|||||||
def create_machine(body: MachineIn, user=Depends(can('users'))):
|
def create_machine(body: MachineIn, user=Depends(can('users'))):
|
||||||
mid = uuid4()
|
mid = uuid4()
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
if c.execute('SELECT 1 FROM dtf_local.machines WHERE lower(name)=lower(%s)', (body.name.strip(),)).fetchone():
|
# A machine's hot folder is its first name, for good: no other machine
|
||||||
raise HTTPException(409, 'Já existe uma máquina com este nome.')
|
# may be called that, or two would share one folder.
|
||||||
c.execute('INSERT INTO dtf_local.machines(id,name,products,active,limit_metres) VALUES(%s,%s,%s,%s,%s)',
|
if c.execute('SELECT 1 FROM dtf_local.machines WHERE lower(name)=lower(%s) OR lower(folder)=lower(%s)',
|
||||||
(mid, body.name.strip(), sorted(set(body.products)), body.active, body.limit_metres))
|
(body.name.strip(), body.name.strip())).fetchone():
|
||||||
machines.route(c)
|
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)
|
audit('machine_created', operator=user, machine=body.name)
|
||||||
return {'id': str(mid)}
|
return {'id': str(mid)}
|
||||||
|
|
||||||
@@ -236,29 +284,45 @@ def create_machine(body: MachineIn, user=Depends(can('users'))):
|
|||||||
@router.post('/api/operator/machines/{mid}')
|
@router.post('/api/operator/machines/{mid}')
|
||||||
def update_machine(mid: UUID, body: MachineIn, user=Depends(can('users'))):
|
def update_machine(mid: UUID, body: MachineIn, user=Depends(can('users'))):
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
if c.execute('SELECT 1 FROM dtf_local.machines WHERE lower(name)=lower(%s) AND id<>%s',
|
if c.execute('''SELECT 1 FROM dtf_local.machines WHERE (lower(name)=lower(%s) OR lower(folder)=lower(%s))
|
||||||
(body.name.strip(), mid)).fetchone():
|
AND id<>%s''', (body.name.strip(), body.name.strip(), mid)).fetchone():
|
||||||
raise HTTPException(409, 'Já existe uma máquina com este nome.')
|
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
|
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,
|
places=COALESCE(%s,places) WHERE id=%s RETURNING id''',
|
||||||
body.limit_metres, mid)).fetchone():
|
(body.name.strip(), sorted(set(body.products)), body.active, body.limit_metres,
|
||||||
|
body.places, mid)).fetchone():
|
||||||
raise HTTPException(404, 'Máquina não encontrada.')
|
raise HTTPException(404, 'Máquina não encontrada.')
|
||||||
if not body.active:
|
if not body.active:
|
||||||
release_sessions(c, mid)
|
release_sessions(c, mid)
|
||||||
machines.route(c)
|
|
||||||
audit('machine_updated', operator=user, machine=body.name)
|
audit('machine_updated', operator=user, machine=body.name)
|
||||||
return {'ok': True}
|
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')
|
@router.post('/api/operator/machines/{mid}/delete')
|
||||||
def delete_machine(mid: UUID, user=Depends(can('users'))):
|
def delete_machine(mid: UUID, user=Depends(can('users'))):
|
||||||
"""Its orders go back to the automatic choice; its operators lose it."""
|
"""Its orders lose that machine; its operators lose the session choice."""
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
|
if c.execute("SELECT 1 FROM dtf_local.orders WHERE machine_id=%s AND state='imp' AND cancelled_at IS NULL LIMIT 1",
|
||||||
|
(mid,)).fetchone():
|
||||||
|
raise HTTPException(409, 'Há pedido imprimindo nesta máquina. Termine ou mova o pedido antes de excluí-la.')
|
||||||
release_sessions(c, mid)
|
release_sessions(c, mid)
|
||||||
row = c.execute('DELETE FROM dtf_local.machines WHERE id=%s RETURNING name', (mid,)).fetchone()
|
row = c.execute('DELETE FROM dtf_local.machines WHERE id=%s RETURNING name', (mid,)).fetchone()
|
||||||
if not row:
|
if not row:
|
||||||
raise HTTPException(404, 'Máquina não encontrada.')
|
raise HTTPException(404, 'Máquina não encontrada.')
|
||||||
machines.route(c)
|
|
||||||
audit('machine_deleted', operator=user, machine=row['name'])
|
audit('machine_deleted', operator=user, machine=row['name'])
|
||||||
return {'ok': True}
|
return {'ok': True}
|
||||||
|
|
||||||
|
|||||||
43
app/app.py
43
app/app.py
@@ -4,29 +4,66 @@ Configuration and shared helpers are in local.runtime; every route lives in a
|
|||||||
router under local.api. This module creates the application, applies the
|
router under local.api. This module creates the application, applies the
|
||||||
cross-cutting middleware, and includes them.
|
cross-cutting middleware, and includes them.
|
||||||
"""
|
"""
|
||||||
|
import asyncio
|
||||||
|
import logging
|
||||||
|
import time
|
||||||
from contextlib import asynccontextmanager
|
from contextlib import asynccontextmanager
|
||||||
|
|
||||||
from fastapi import FastAPI
|
import psycopg
|
||||||
|
from fastapi import FastAPI, Request
|
||||||
from fastapi.responses import JSONResponse
|
from fastapi.responses import JSONResponse
|
||||||
from starlette.middleware.trustedhost import TrustedHostMiddleware
|
from starlette.middleware.trustedhost import TrustedHostMiddleware
|
||||||
|
|
||||||
|
from . import observability
|
||||||
from .core import db
|
from .core import db
|
||||||
from .core.auth import audit, client_ip
|
from .core.auth import audit, client_ip
|
||||||
from .runtime import ALLOWED_HOSTS, ALLOWED_ORIGINS, storage
|
from .runtime import ALLOWED_HOSTS, ALLOWED_ORIGINS, storage
|
||||||
from .api import artwork, customer, health, operator, orders, payments, quotes, uploads, users
|
from .api import artwork, customer, health, machine_log, operator, orders, payments, quotes, reviews, site_admin, site_videos, stamps, uploads, users
|
||||||
|
|
||||||
|
observability.init('api')
|
||||||
|
|
||||||
|
|
||||||
|
RETRY_SECONDS = (1, 2, 4, 8, 15)
|
||||||
|
STARTUP_BUDGET_SECONDS = 90
|
||||||
|
|
||||||
|
|
||||||
@asynccontextmanager
|
@asynccontextmanager
|
||||||
async def lifespan(app):
|
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:
|
with db.connect() as c:
|
||||||
c.execute('SELECT 1 FROM dtf_local.operator_sessions LIMIT 1')
|
c.execute('SELECT 1 FROM dtf_local.operator_sessions LIMIT 1')
|
||||||
storage.health()
|
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
|
yield
|
||||||
|
|
||||||
|
|
||||||
app = FastAPI(title='DTF Portal/API', lifespan=lifespan, docs_url=None, redoc_url=None)
|
app = FastAPI(title='DTF Portal/API', lifespan=lifespan, docs_url=None, redoc_url=None)
|
||||||
app.add_middleware(TrustedHostMiddleware, allowed_hosts=ALLOWED_HOSTS)
|
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')
|
@app.middleware('http')
|
||||||
async def safe_headers(request, call_next):
|
async def safe_headers(request, call_next):
|
||||||
if request.method not in ('GET','HEAD','OPTIONS'):
|
if request.method not in ('GET','HEAD','OPTIONS'):
|
||||||
@@ -45,5 +82,5 @@ async def safe_headers(request, call_next):
|
|||||||
|
|
||||||
|
|
||||||
# Order is not significant: no two routers declare the same path.
|
# Order is not significant: no two routers declare the same path.
|
||||||
for module in (health, uploads, quotes, orders, payments, operator, customer, artwork, users):
|
for module in (health, uploads, quotes, orders, payments, operator, customer, artwork, users, site_videos, site_admin, reviews, machine_log, stamps):
|
||||||
app.include_router(module.router)
|
app.include_router(module.router)
|
||||||
|
|||||||
@@ -9,7 +9,8 @@ from uuid import UUID, uuid4
|
|||||||
|
|
||||||
from fastapi import HTTPException
|
from fastapi import HTTPException
|
||||||
|
|
||||||
from .runtime import upload_row
|
from .runtime import upload_row, storage
|
||||||
|
from .printpng_validate import require_final_png
|
||||||
from .scanning import require_clean
|
from .scanning import require_clean
|
||||||
|
|
||||||
|
|
||||||
@@ -20,8 +21,9 @@ def generated_owner(c, order, ref, kind):
|
|||||||
from, and only while that item still has its original artwork: after a
|
from, and only while that item still has its original artwork: after a
|
||||||
customer correction it reproduces a layout nobody wants printed.
|
customer correction it reproduces a layout nobody wants printed.
|
||||||
"""
|
"""
|
||||||
generated = c.execute('''SELECT item_index FROM dtf_local.print_files
|
generated = c.execute('''SELECT p.item_index FROM dtf_local.print_parts p JOIN dtf_local.print_files f
|
||||||
WHERE order_id=%s AND upload_id=%s AND status='ready' ''', (order['id'], ref.upload_id)).fetchone()
|
ON f.order_id=p.order_id AND f.item_index=p.item_index
|
||||||
|
WHERE p.order_id=%s AND p.upload_id=%s AND f.status='ready' ''', (order['id'], ref.upload_id)).fetchone()
|
||||||
if not generated:
|
if not generated:
|
||||||
return None
|
return None
|
||||||
if kind != 'final' or generated['item_index'] != ref.item_index:
|
if kind != 'final' or generated['item_index'] != ref.item_index:
|
||||||
@@ -29,7 +31,6 @@ def generated_owner(c, order, ref, kind):
|
|||||||
if c.execute("SELECT 1 FROM dtf_local.order_files WHERE order_id=%s AND kind='correction' LIMIT 1",
|
if c.execute("SELECT 1 FROM dtf_local.order_files WHERE order_id=%s AND kind='correction' LIMIT 1",
|
||||||
(order['id'],)).fetchone():
|
(order['id'],)).fetchone():
|
||||||
raise HTTPException(409, 'O cliente enviou uma correção depois que este arquivo foi gerado. Use a correção ou envie outro arquivo.')
|
raise HTTPException(409, 'O cliente enviou uma correção depois que este arquivo foi gerado. Use a correção ou envie outro arquivo.')
|
||||||
# A large sheet's print file is its original, owned by the customer.
|
|
||||||
return c.execute('SELECT owner FROM dtf_local.uploads WHERE id=%s', (ref.upload_id,)).fetchone()['owner']
|
return c.execute('SELECT owner FROM dtf_local.uploads WHERE id=%s', (ref.upload_id,)).fetchone()['owner']
|
||||||
|
|
||||||
|
|
||||||
@@ -73,20 +74,45 @@ def submit_files(c, order, body, identity, kind, actor):
|
|||||||
current = {(row['upload_id'], row['item_index']) for row in c.execute(
|
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",
|
"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()
|
(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}
|
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):
|
if kept and len(kept) == len(body.files):
|
||||||
raise HTTPException(409, 'Estes já são os arquivos finais. Envie o arquivo novo.')
|
raise HTTPException(409, 'Estes já são os arquivos finais. Envie o arquivo novo.')
|
||||||
|
revived = set()
|
||||||
for ref in body.files:
|
for ref in body.files:
|
||||||
if ref.upload_id in kept:
|
if ref.upload_id in kept:
|
||||||
continue
|
continue
|
||||||
corrected = correction_owner(c, order, ref, kind)
|
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']:
|
if not upload['complete']:
|
||||||
raise HTTPException(409, 'Espere o envio de todos os arquivos terminar.')
|
raise HTTPException(409, 'Espere o envio de todos os arquivos terminar.')
|
||||||
require_clean(upload)
|
require_clean(upload)
|
||||||
# Attached once, except a correction approved as its own final.
|
if kind == 'final':
|
||||||
if c.execute('SELECT id FROM dtf_local.order_files WHERE upload_id=%s'+(" AND kind<>'correction'" if corrected else ''),
|
require_final_png(storage, upload)
|
||||||
(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.')
|
raise HTTPException(409, 'Este arquivo já está no pedido. Envie uma nova versão.')
|
||||||
# A new customer correction supersedes every final prepared from earlier
|
# A new customer correction supersedes every final prepared from earlier
|
||||||
# artwork, including finals uploaded while this order was in correction.
|
# artwork, including finals uploaded while this order was in correction.
|
||||||
@@ -94,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'],))
|
c.execute("UPDATE dtf_local.order_files SET active=false WHERE order_id=%s AND kind IN ('correction','final')", (order['id'],))
|
||||||
else:
|
else:
|
||||||
c.execute('UPDATE dtf_local.order_files SET active=false WHERE order_id=%s AND kind=%s', (order['id'],kind))
|
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:
|
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'",
|
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))
|
(order['id'], ref.upload_id))
|
||||||
continue
|
continue
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ from pathlib import Path
|
|||||||
from urllib.parse import urlparse
|
from urllib.parse import urlparse
|
||||||
import psycopg
|
import psycopg
|
||||||
from psycopg import sql
|
from psycopg import sql
|
||||||
|
from . import migrate
|
||||||
from .core.secrets import load as load_secret_files
|
from .core.secrets import load as load_secret_files
|
||||||
from .operators import seed_from_environment
|
from .operators import seed_from_environment
|
||||||
|
|
||||||
@@ -41,22 +42,22 @@ def main():
|
|||||||
c.execute(sql.SQL('ALTER ROLE {} NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS PASSWORD {}').format(
|
c.execute(sql.SQL('ALTER ROLE {} NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS PASSWORD {}').format(
|
||||||
sql.Identifier(role), sql.Literal(password)))
|
sql.Identifier(role), sql.Literal(password)))
|
||||||
c.execute(Path(__file__).with_name('schema.sql').read_text())
|
c.execute(Path(__file__).with_name('schema.sql').read_text())
|
||||||
|
applied = migrate.apply(c)
|
||||||
c.execute(sql.SQL('REVOKE CREATE ON SCHEMA public FROM PUBLIC'))
|
c.execute(sql.SQL('REVOKE CREATE ON SCHEMA public FROM PUBLIC'))
|
||||||
c.execute(sql.SQL('GRANT CONNECT ON DATABASE {} TO {}').format(sql.Identifier(database),sql.Identifier(role)))
|
c.execute(sql.SQL('GRANT CONNECT ON DATABASE {} TO {}').format(sql.Identifier(database),sql.Identifier(role)))
|
||||||
c.execute(sql.SQL('GRANT USAGE ON SCHEMA dtf_local TO {}').format(sql.Identifier(role)))
|
c.execute(sql.SQL('GRANT USAGE ON SCHEMA dtf_local TO {}').format(sql.Identifier(role)))
|
||||||
c.execute(sql.SQL('GRANT SELECT,INSERT,UPDATE,DELETE ON ALL TABLES IN SCHEMA dtf_local TO {}').format(sql.Identifier(role)))
|
c.execute(sql.SQL('GRANT SELECT,INSERT,UPDATE,DELETE ON ALL TABLES IN SCHEMA dtf_local TO {}').format(sql.Identifier(role)))
|
||||||
c.execute(sql.SQL('GRANT USAGE,SELECT ON ALL SEQUENCES IN SCHEMA dtf_local TO {}').format(sql.Identifier(role)))
|
c.execute(sql.SQL('GRANT USAGE,SELECT ON ALL SEQUENCES IN SCHEMA dtf_local TO {}').format(sql.Identifier(role)))
|
||||||
# ops.launch_reset starts the order numbers again at #1 (setval), once
|
# The order identity sequence is never reset: DTF-1…DTF-15 already
|
||||||
# the test orders are gone; nothing else may change a sequence.
|
# exist as Tiny order numbers (Dropstar, 2026-11-05).
|
||||||
numbers = c.execute("SELECT pg_get_serial_sequence('dtf_local.orders','number')").fetchone()[0]
|
|
||||||
c.execute(sql.SQL('GRANT UPDATE ON SEQUENCE {} TO {}').format(
|
|
||||||
sql.Identifier(*numbers.split('.', 1)), sql.Identifier(role)))
|
|
||||||
# Turn the configured credential into a real account so an existing
|
# Turn the configured credential into a real account so an existing
|
||||||
# deployment keeps logging in exactly as before. Inserts only when that
|
# deployment keeps logging in exactly as before. Inserts only when that
|
||||||
# email is absent, so a password changed with local.operators is never
|
# email is absent, so a password changed with local.operators is never
|
||||||
# reverted by a stale environment variable on the next deploy.
|
# reverted by a stale environment variable on the next deploy.
|
||||||
seeded = seed_from_environment(c)
|
seeded = seed_from_environment(c)
|
||||||
print('Local schema migrated; runtime role has DML only.')
|
print('Local schema migrated; runtime role has DML only.')
|
||||||
|
if applied:
|
||||||
|
print(f'Schema migrations applied: {", ".join(applied)}')
|
||||||
if seeded:
|
if seeded:
|
||||||
print(f'Seeded operator account {seeded} from OPERATOR_EMAIL.')
|
print(f'Seeded operator account {seeded} from OPERATOR_EMAIL.')
|
||||||
|
|
||||||
|
|||||||
140
app/cart_pricing.py
Normal file
140
app/cart_pricing.py
Normal file
@@ -0,0 +1,140 @@
|
|||||||
|
"""One pricing module for every way a cart is priced (Critical Corrections 3).
|
||||||
|
|
||||||
|
The Site's pre-check and the approval used to repeat the same chain and had
|
||||||
|
already drifted: the pre-check ignored the manual-file extra. Everything that
|
||||||
|
turns items into money lives here now. The catalog is read once, the arithmetic
|
||||||
|
is pure, and a new price rule only has to be added in one place.
|
||||||
|
"""
|
||||||
|
from decimal import Decimal
|
||||||
|
|
||||||
|
from . import catalog, coupons, grade_rules
|
||||||
|
from .core import pricing
|
||||||
|
|
||||||
|
|
||||||
|
def art_pairs(items):
|
||||||
|
"""[item_index, source_index] for every art in the cart: one artwork of
|
||||||
|
loose art, or one sheet file of a ready sheet."""
|
||||||
|
return [[index, source] for index, item in enumerate(items)
|
||||||
|
for source in range(len((item.get('production') or {}).get('sources') or []))]
|
||||||
|
|
||||||
|
|
||||||
|
def chosen_arts(items, choice):
|
||||||
|
"""The arts the draft's treatment selects: all of them for True (old carts
|
||||||
|
and the grade rule), the valid pairs for a list."""
|
||||||
|
if choice is True:
|
||||||
|
return art_pairs(items)
|
||||||
|
if not isinstance(choice, (list, tuple)):
|
||||||
|
return []
|
||||||
|
valid = {tuple(pair) for pair in art_pairs(items)}
|
||||||
|
return [list(pair) for pair in choice
|
||||||
|
if isinstance(pair, (list, tuple)) and len(pair) == 2 and tuple(pair) in valid]
|
||||||
|
|
||||||
|
|
||||||
|
def treatment_price(items, choice, offer):
|
||||||
|
"""Ajuste Fino for the chosen arts, with the row's bands counted in arts.
|
||||||
|
{} when it is not offered or no art is chosen."""
|
||||||
|
if not offer or not offer.get('enabled') or offer.get('unit_cents', 0) <= 0:
|
||||||
|
return {}
|
||||||
|
arts = chosen_arts(items, choice)
|
||||||
|
if not arts:
|
||||||
|
return {}
|
||||||
|
count = len(arts)
|
||||||
|
unit = catalog.band_price(offer['unit_cents'], offer.get('bands') or [], count)
|
||||||
|
return {'cents': unit * count, 'hours': 24, 'arts': count, 'unit_cents': unit}
|
||||||
|
|
||||||
|
|
||||||
|
def 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
|
||||||
|
total, then apply_bands. Exactly as an order is charged."""
|
||||||
|
priced = []
|
||||||
|
for item in items:
|
||||||
|
extra = manual_extra if pricing.is_manual(item, names) else 0
|
||||||
|
product = catalog_now[item['mode']]
|
||||||
|
priced.append({**pricing.price(item['mode'], str(item['metres']), item['grade'], extra,
|
||||||
|
minimum=Decimal('0') if item.get('split') else Decimal('1'),
|
||||||
|
unit_cents=product['unit_cents']),
|
||||||
|
**({'split': item['split']} if item.get('split') else {})})
|
||||||
|
pricing.bill_splits(priced)
|
||||||
|
totals = {}
|
||||||
|
for item in priced:
|
||||||
|
totals[item['mode']] = totals.get(item['mode'], Decimal('0')) + Decimal(item['billed_metres'])
|
||||||
|
banded = {}
|
||||||
|
for mode, total in totals.items():
|
||||||
|
product = catalog_now[mode]
|
||||||
|
price_for_total = catalog.band_price(product['unit_cents'], product['bands'], total)
|
||||||
|
if price_for_total != product['unit_cents']:
|
||||||
|
banded[mode] = price_for_total
|
||||||
|
pricing.apply_bands(priced, banded)
|
||||||
|
return priced
|
||||||
|
|
||||||
|
|
||||||
|
def price_cart(c, items, names, *, coupon_code=None, customer_document=None,
|
||||||
|
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, '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:
|
||||||
|
if not catalog_now[item['mode']]['enabled']:
|
||||||
|
raise HTTPException(422, 'Este produto não está à venda agora.')
|
||||||
|
priced = price_items(items, names, catalog_now, pricing.manual_extra_cents())
|
||||||
|
offer = catalog_now['tratamento']
|
||||||
|
offered = bool(offer['enabled'] and offer['unit_cents'] > 0)
|
||||||
|
flags = grade_rules.triggered(grade_rules.current_rules(c), priced, offered)
|
||||||
|
if not treatment_rule:
|
||||||
|
flags.pop('tratamento', None)
|
||||||
|
treatment = treatment_price(items, wants_treatment, offer)
|
||||||
|
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:
|
||||||
|
coupon = coupons.check(c, coupon_code, customer_document, priced)
|
||||||
|
return {'items': priced,
|
||||||
|
'items_total': sum(i['total_cents'] for i in priced),
|
||||||
|
'coupon': coupon,
|
||||||
|
'treatment': treatment,
|
||||||
|
'treatment_cents': treatment.get('cents', 0),
|
||||||
|
'redesign': redesign,
|
||||||
|
'redesign_cents': redesign.get('cents', 0),
|
||||||
|
'grade_flags': flags}
|
||||||
113
app/catalog.py
Normal file
113
app/catalog.py
Normal file
@@ -0,0 +1,113 @@
|
|||||||
|
"""What the Site sells and at what price, edited in the Kanban's Site tab.
|
||||||
|
|
||||||
|
Dropstar, 2026-11-05 (Fase 2, front 8): the products and their prices leave the
|
||||||
|
code and live in the database, with a start date and a history. `PRICES` in
|
||||||
|
app/core/pricing.py stays as the seed and the fallback for the five modes;
|
||||||
|
`treatment_cents()` stays as the fallback for `tratamento`. A price row is never
|
||||||
|
changed or deleted once its start date has passed (the table is the history),
|
||||||
|
and an approved quote keeps the price it was approved with.
|
||||||
|
|
||||||
|
`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. `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
|
||||||
|
band reached wins and the whole quantity is charged at that one price. The
|
||||||
|
bands travel with the row, so they start and become history with it.
|
||||||
|
"""
|
||||||
|
from decimal import Decimal
|
||||||
|
|
||||||
|
from .core import pricing
|
||||||
|
|
||||||
|
# The modes sold by the metre, and the services sold per art.
|
||||||
|
MODES = ('file', 'avulsa', 'uvfile', 'uv', 'premium')
|
||||||
|
PRODUCTS = (*MODES, 'tratamento', 'redesenho')
|
||||||
|
|
||||||
|
TITLES = {
|
||||||
|
'file': 'Têxtil folha pronta',
|
||||||
|
'avulsa': 'Têxtil artes avulsas',
|
||||||
|
'uvfile': 'UV folha pronta',
|
||||||
|
'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', 'redesenho': 'arte'}
|
||||||
|
|
||||||
|
|
||||||
|
def fallback_cents(product: str) -> int:
|
||||||
|
"""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:
|
||||||
|
"""The unit price for this quantity: the base, or the highest band reached.
|
||||||
|
The quantity is metres for a product and arts for Ajuste Fino; the whole
|
||||||
|
quantity is charged at one price, not in steps."""
|
||||||
|
quantity = Decimal(str(quantity))
|
||||||
|
price = base_cents
|
||||||
|
best = None
|
||||||
|
for band in bands or []:
|
||||||
|
start = Decimal(str(band['from_metres']))
|
||||||
|
if quantity >= start and (best is None or start >= best):
|
||||||
|
best = start
|
||||||
|
price = band['unit_cents']
|
||||||
|
return price
|
||||||
|
|
||||||
|
|
||||||
|
def current(c) -> dict:
|
||||||
|
"""{'file': {'enabled': bool, 'unit_cents': int, 'bands': [...]}, ...}."""
|
||||||
|
enabled = {row['id']: row['enabled'] for row in
|
||||||
|
c.execute('SELECT id, enabled FROM dtf_local.products').fetchall()}
|
||||||
|
prices = {row['product']: row for row in c.execute('''
|
||||||
|
SELECT DISTINCT ON (product) product, unit_cents, bands
|
||||||
|
FROM dtf_local.product_prices
|
||||||
|
WHERE starts_at <= now()
|
||||||
|
ORDER BY product, starts_at DESC, id DESC''').fetchall()}
|
||||||
|
return {product: {'enabled': bool(enabled.get(product, True)),
|
||||||
|
'unit_cents': prices[product]['unit_cents'] if product in prices else fallback_cents(product),
|
||||||
|
'bands': prices[product]['bands'] if product in prices else []}
|
||||||
|
for product in PRODUCTS}
|
||||||
|
|
||||||
|
|
||||||
|
def unit_cents(c, product: str) -> int:
|
||||||
|
"""The current base price of one product, or the fallback."""
|
||||||
|
row = c.execute('''SELECT unit_cents FROM dtf_local.product_prices
|
||||||
|
WHERE product=%s AND starts_at <= now()
|
||||||
|
ORDER BY starts_at DESC, id DESC LIMIT 1''', (product,)).fetchone()
|
||||||
|
return row['unit_cents'] if row else fallback_cents(product)
|
||||||
|
|
||||||
|
|
||||||
|
def unit_cents_for(c, product: str, quantity: Decimal) -> int:
|
||||||
|
"""The current price of one product for this quantity, bands included."""
|
||||||
|
row = c.execute('''SELECT unit_cents, bands FROM dtf_local.product_prices
|
||||||
|
WHERE product=%s AND starts_at <= now()
|
||||||
|
ORDER BY starts_at DESC, id DESC LIMIT 1''', (product,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
return fallback_cents(product)
|
||||||
|
return band_price(row['unit_cents'], row['bands'], quantity)
|
||||||
|
|
||||||
|
|
||||||
|
def treatment_offered(c) -> bool:
|
||||||
|
"""Whether the designer's treatment is on the Site: enabled and priced."""
|
||||||
|
offer = current(c)['tratamento']
|
||||||
|
return bool(offer['enabled'] and offer['unit_cents'] > 0)
|
||||||
|
|
||||||
|
|
||||||
|
def require_enabled(c, product: str) -> None:
|
||||||
|
"""Refuse a product someone switched off in the Kanban's Site tab."""
|
||||||
|
# Imported here so the pure helpers above load without the web framework
|
||||||
|
# (tests/test_pricing.py runs on the host, where FastAPI is not installed).
|
||||||
|
from fastapi import HTTPException
|
||||||
|
row = c.execute('SELECT enabled FROM dtf_local.products WHERE id=%s', (product,)).fetchone()
|
||||||
|
if row and not row['enabled']:
|
||||||
|
raise HTTPException(422, 'Este produto não está à venda agora.')
|
||||||
124
app/core/auth.py
124
app/core/auth.py
@@ -4,6 +4,9 @@ import os
|
|||||||
import secrets
|
import secrets
|
||||||
import logging
|
import logging
|
||||||
import json
|
import json
|
||||||
|
import psycopg
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
from uuid import UUID, uuid4
|
from uuid import UUID, uuid4
|
||||||
from fastapi import HTTPException, Request
|
from fastapi import HTTPException, Request
|
||||||
from ..core.db import connect
|
from ..core.db import connect
|
||||||
@@ -71,16 +74,32 @@ def transfer_guest(c, previous, identity):
|
|||||||
c.execute(f'UPDATE dtf_local.{table} SET owner=%s WHERE owner=%s', (identity,previous['owner']))
|
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'],))
|
c.execute('DELETE FROM dtf_local.sessions WHERE owner=%s', (previous['owner'],))
|
||||||
|
|
||||||
def audit(event, **fields):
|
_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.
|
# Only explicit metadata: never cookies, passwords, signed URLs or request bodies.
|
||||||
logging.getLogger('dtf.security').warning(json.dumps({'event':event, **fields}, sort_keys=True))
|
logging.getLogger('dtf.security').warning(json.dumps({'event':event, **fields}, sort_keys=True))
|
||||||
try:
|
try:
|
||||||
from psycopg.types.json import Jsonb
|
from psycopg.types.json import Jsonb
|
||||||
|
if c is not None:
|
||||||
|
c.execute('INSERT INTO dtf_local.security_events(event,details) VALUES(%s,%s)',(event,Jsonb(fields)))
|
||||||
|
else:
|
||||||
with connect() as c:
|
with connect() as c:
|
||||||
c.execute('INSERT INTO dtf_local.security_events(event,details) VALUES(%s,%s)',(event,Jsonb(fields)))
|
c.execute('INSERT INTO dtf_local.security_events(event,details) VALUES(%s,%s)',(event,Jsonb(fields)))
|
||||||
except Exception:
|
except Exception:
|
||||||
# Logging must still work during a DB outage without recursively auditing itself.
|
# Logging must still work during a DB outage without recursively auditing
|
||||||
logging.getLogger('dtf.security').error('Security event persistence unavailable')
|
# 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):
|
def rate_limit(scope, identity, limit, seconds=900):
|
||||||
key = hashlib.sha256((scope+'|'+identity).encode()).hexdigest()
|
key = hashlib.sha256((scope+'|'+identity).encode()).hexdigest()
|
||||||
@@ -114,18 +133,21 @@ def login_failed(email):
|
|||||||
"""Count a failed sign-in (or registration attempt) against the account."""
|
"""Count a failed sign-in (or registration attempt) against the account."""
|
||||||
rate_limit('auth-account', email, 1_000_000)
|
rate_limit('auth-account', email, 1_000_000)
|
||||||
|
|
||||||
# What each Kanban profile may do. "view" is reading; "produce" moves cards and
|
# What each Kanban profile may do. "view" is reading; "produce" handles the
|
||||||
# handles artwork; "print" is the print room's side of it (the machine, the
|
# artwork: approving the final files, the contraction, "Tratar a arte", the
|
||||||
|
# contact wait. "The designer approves every file" (Dropstar's rule D-16), so
|
||||||
|
# the operator does not: they pull and print. "print" is the print room's side
|
||||||
|
# of it (the machine, the
|
||||||
# queue's order, its files and folder); "manage" covers quotes, cancellations
|
# queue's order, its files and folder); "manage" covers quotes, cancellations
|
||||||
# and payments; "users" is the Usuários page; "integrations" is everything in
|
# and payments; "users" is the Usuários page; "integrations" is everything in
|
||||||
# Integrações but the print room's folder (connecting Tiny, the checks, the
|
# Integrações but the print room's folder (connecting Tiny, the checks, the
|
||||||
# backup, the Tiny log): the others see there only what is on and off.
|
# backup, the Tiny log): the others see there only what is on and off.
|
||||||
# The designer approves and refuses artwork and asks for corrections, on every
|
# The designer approves and refuses artwork and asks for corrections, on every
|
||||||
# order whatever its machine. Which cards each profile moves is MOVES.
|
# order whatever its machine. Which cards each profile moves is MOVES.
|
||||||
ROLES = ('superadmin', 'admin', 'gestao', 'designer', 'operador', 'revisor', 'vendedor', 'financeiro')
|
ROLES = ('superadmin', 'admin', 'gestao', 'designer', 'operador', 'revisor', 'vendedor', 'financeiro', 'expedicao')
|
||||||
CAPABILITIES = {
|
CAPABILITIES = {
|
||||||
'view': set(ROLES),
|
'view': set(ROLES),
|
||||||
'produce': {'superadmin', 'admin', 'gestao', 'designer', 'operador'},
|
'produce': {'superadmin', 'admin', 'gestao', 'designer'},
|
||||||
'print': {'superadmin', 'admin', 'gestao', 'operador'},
|
'print': {'superadmin', 'admin', 'gestao', 'operador'},
|
||||||
'manage': {'superadmin', 'admin', 'gestao'},
|
'manage': {'superadmin', 'admin', 'gestao'},
|
||||||
# Registering an order paid outside the system, from its Site quote (D-35).
|
# Registering an order paid outside the system, from its Site quote (D-35).
|
||||||
@@ -142,10 +164,23 @@ CAPABILITIES = {
|
|||||||
# file. Resolving a payment stays with "manage".
|
# file. Resolving a payment stays with "manage".
|
||||||
'payments': {'superadmin', 'admin', 'gestao', 'financeiro'},
|
'payments': {'superadmin', 'admin', 'gestao', 'financeiro'},
|
||||||
'cancel': {'superadmin', 'admin', 'gestao', 'financeiro'},
|
'cancel': {'superadmin', 'admin', 'gestao', 'financeiro'},
|
||||||
|
# Prova OK or reprovada, on the proof card only (Dropstar, 2026-11-03): the
|
||||||
|
# seller, who otherwise only views, Gestão and the administrators.
|
||||||
|
'proof': {'superadmin', 'admin', 'gestao', 'vendedor'},
|
||||||
# "Retirado" at the counter (Dropstar's third round, item 14): everyone
|
# "Retirado" at the counter (Dropstar's third round, item 14): everyone
|
||||||
# but the seller, who only views (D-30). It includes everyone who produces,
|
# but the seller, who only views (D-30). It includes everyone who produces,
|
||||||
# so an operator upload (artwork.py) takes it for its parts.
|
# and the operator, so an operator upload (artwork.py) takes it for its parts.
|
||||||
'deliver': {'superadmin', 'admin', 'gestao', 'designer', 'operador', 'revisor'},
|
'deliver': {'superadmin', 'admin', 'gestao', 'designer', 'operador', 'revisor'},
|
||||||
|
# The photo or video of the printed sheet in Revisão (Fase 2, front 2): who
|
||||||
|
# releases to Finalizado, and Gestão, which may stand in for them.
|
||||||
|
'inspect': {'superadmin', 'admin', 'gestao', 'revisor'},
|
||||||
|
# Montar folha (Fase 2, front 7): the new Expedição profile and the seller,
|
||||||
|
# who gets this one action although otherwise view-only (D-30).
|
||||||
|
'assemble': {'superadmin', 'admin', 'gestao', 'vendedor', 'expedicao'},
|
||||||
|
# The 10x15 thermal label at Finalizado (Marcus, 2026-11-10, front 10): the
|
||||||
|
# Revisor who releases the card, the Expedição profile that ships it, and
|
||||||
|
# Gestão, which may stand in for either.
|
||||||
|
'label': {'superadmin', 'admin', 'gestao', 'revisor', 'expedicao'},
|
||||||
}
|
}
|
||||||
|
|
||||||
# Who moves which card (Dropstar's flow, 2026-10-23, and their rules of
|
# Who moves which card (Dropstar's flow, 2026-10-23, and their rules of
|
||||||
@@ -172,9 +207,19 @@ MACHINE_QUESTION = {'operador': 'required', 'gestao': 'optional', 'admin': 'opti
|
|||||||
MOVERS = MANAGERS + tuple(MOVES)
|
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):
|
def may_move(role, from_state, to_state, back=False):
|
||||||
"""Whether this profile may move a card; `back` is the step back that
|
"""Whether this profile (or any of these) may move a card; `back` is the
|
||||||
undoes the move to_state -> from_state."""
|
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:
|
if back:
|
||||||
return role in MANAGERS or (to_state, from_state) in MOVES.get(role, ())
|
return role in MANAGERS or (to_state, from_state) in MOVES.get(role, ())
|
||||||
if to_state == 'fin':
|
if to_state == 'fin':
|
||||||
@@ -187,7 +232,44 @@ def may_move(role, from_state, to_state, back=False):
|
|||||||
def may_reorder(role, state):
|
def may_reorder(role, state):
|
||||||
"""Changing a card's place in its column, the order it is worked in: for
|
"""Changing a card's place in its column, the order it is worked in: for
|
||||||
whoever takes cards forward out of it."""
|
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):
|
def signed_in(request: Request):
|
||||||
@@ -198,11 +280,16 @@ def signed_in(request: Request):
|
|||||||
raise HTTPException(401, 'Entre no Kanban.')
|
raise HTTPException(401, 'Entre no Kanban.')
|
||||||
digest = hashlib.sha256(token.encode()).hexdigest()
|
digest = hashlib.sha256(token.encode()).hexdigest()
|
||||||
with connect() as c:
|
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
|
FROM dtf_local.operator_sessions s
|
||||||
JOIN dtf_local.operators o ON o.email=s.username AND o.active
|
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
|
LEFT JOIN dtf_local.machines m ON m.id=s.machine_id
|
||||||
WHERE s.token_hash=%s AND s.expires_at>now()''', (digest,)).fetchone()
|
WHERE s.token_hash=%s AND s.expires_at>now()''', (digest,)).fetchone()
|
||||||
|
if row:
|
||||||
|
# When the session was last used, for "Ativo agora" in Usuários:
|
||||||
|
# written at most once a minute, not on every request.
|
||||||
|
c.execute('''UPDATE dtf_local.operator_sessions SET seen_at=now()
|
||||||
|
WHERE token_hash=%s AND (seen_at IS NULL OR seen_at<now()-interval '1 minute')''', (digest,))
|
||||||
if not row:
|
if not row:
|
||||||
raise HTTPException(401, 'Sua sessão expirou. Entre de novo.')
|
raise HTTPException(401, 'Sua sessão expirou. Entre de novo.')
|
||||||
# The machine this session works on (item 12), or None.
|
# The machine this session works on (item 12), or None.
|
||||||
@@ -218,7 +305,18 @@ def can(capability):
|
|||||||
returns the operator's e-mail, as the routes record it."""
|
returns the operator's e-mail, as the routes record it."""
|
||||||
def check(request: Request):
|
def check(request: Request):
|
||||||
account = signed_in(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
|
||||||
|
|
||||||
|
|
||||||
|
def can_any(*capabilities):
|
||||||
|
"""A dependency that lets through a profile with any of these capabilities,
|
||||||
|
and returns the operator's e-mail, as the routes record it."""
|
||||||
|
def check(request: Request):
|
||||||
|
account = signed_in(request)
|
||||||
|
if not any(has(account, capability) for capability in capabilities):
|
||||||
raise HTTPException(403, 'Seu perfil não permite esta ação.')
|
raise HTTPException(403, 'Seu perfil não permite esta ação.')
|
||||||
return account['email']
|
return account['email']
|
||||||
return check
|
return check
|
||||||
|
|||||||
@@ -1,9 +1,18 @@
|
|||||||
import os
|
import os
|
||||||
|
import threading
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
import psycopg
|
import psycopg
|
||||||
from psycopg.rows import dict_row
|
from psycopg.rows import dict_row
|
||||||
|
from psycopg_pool import ConnectionPool
|
||||||
|
|
||||||
def connect():
|
from .. import migrate
|
||||||
|
|
||||||
|
# One pool per process, created on first use when DB_POOL is on (default off).
|
||||||
|
_pool = None
|
||||||
|
_pool_lock = threading.Lock()
|
||||||
|
|
||||||
|
|
||||||
|
def _direct():
|
||||||
# Production passes credentials as discrete libpq fields. This avoids
|
# Production passes credentials as discrete libpq fields. This avoids
|
||||||
# treating characters in a generated password as URL syntax. Local and
|
# treating characters in a generated password as URL syntax. Local and
|
||||||
# test environments retain DATABASE_URL compatibility.
|
# test environments retain DATABASE_URL compatibility.
|
||||||
@@ -17,7 +26,44 @@ def connect():
|
|||||||
)
|
)
|
||||||
return psycopg.connect(os.environ['DATABASE_URL'], row_factory=dict_row)
|
return psycopg.connect(os.environ['DATABASE_URL'], row_factory=dict_row)
|
||||||
|
|
||||||
|
|
||||||
|
def _pool_arguments():
|
||||||
|
"""The conninfo and kwargs for the pool, matching _direct()'s settings."""
|
||||||
|
if os.environ.get('DATABASE_HOST'):
|
||||||
|
return '', {
|
||||||
|
'host': os.environ['DATABASE_HOST'],
|
||||||
|
'dbname': os.environ['DATABASE_NAME'],
|
||||||
|
'user': os.environ['DATABASE_USER'],
|
||||||
|
'password': os.environ['DATABASE_PASSWORD'],
|
||||||
|
'row_factory': dict_row,
|
||||||
|
}
|
||||||
|
return os.environ['DATABASE_URL'], {'row_factory': dict_row}
|
||||||
|
|
||||||
|
|
||||||
|
def _pool_instance():
|
||||||
|
global _pool
|
||||||
|
if _pool is None:
|
||||||
|
with _pool_lock:
|
||||||
|
if _pool is None:
|
||||||
|
conninfo, kwargs = _pool_arguments()
|
||||||
|
_pool = ConnectionPool(
|
||||||
|
conninfo, kwargs=kwargs, min_size=1,
|
||||||
|
max_size=int(os.environ.get('DB_POOL_SIZE') or 20),
|
||||||
|
open=True, timeout=10, check=ConnectionPool.check_connection)
|
||||||
|
return _pool
|
||||||
|
|
||||||
|
|
||||||
|
def connect():
|
||||||
|
"""A connection for one `with` block. Pooled when DB_POOL is on (default
|
||||||
|
off): the same commit/rollback contract, the connection goes back to the
|
||||||
|
pool instead of closing."""
|
||||||
|
if os.environ.get('DB_POOL', 'off').lower() != 'on':
|
||||||
|
return _direct()
|
||||||
|
return _pool_instance().connection()
|
||||||
|
|
||||||
|
|
||||||
def initialize():
|
def initialize():
|
||||||
with connect() as c:
|
with connect() as c:
|
||||||
# The schema lives at the package root, one level up from core/.
|
# The schema lives at the package root, one level up from core/.
|
||||||
c.execute((Path(__file__).resolve().parent.parent / 'schema.sql').read_text())
|
c.execute((Path(__file__).resolve().parent.parent / 'schema.sql').read_text())
|
||||||
|
migrate.apply(c)
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import re
|
import re
|
||||||
|
from datetime import date, datetime
|
||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
from typing import Literal
|
from typing import Literal
|
||||||
from uuid import UUID
|
from uuid import UUID
|
||||||
@@ -126,9 +127,14 @@ class ProductionSource(StrictModel):
|
|||||||
rotation_degrees: Literal[0, 90] = 0
|
rotation_degrees: Literal[0, 90] = 0
|
||||||
mirrored: bool = False
|
mirrored: bool = False
|
||||||
measurement: Literal['file', 'customer']
|
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)
|
||||||
|
|
||||||
class ProductionPlacement(StrictModel):
|
class ProductionPlacement(StrictModel):
|
||||||
source_index: int = Field(ge=0, le=19, strict=True)
|
source_index: int = Field(ge=0, le=199, strict=True)
|
||||||
copy_index: int = Field(ge=0, le=199, strict=True)
|
copy_index: int = Field(ge=0, le=199, strict=True)
|
||||||
x_cm: Decimal = Field(ge=0, le=57)
|
x_cm: Decimal = Field(ge=0, le=57)
|
||||||
y_cm: Decimal = Field(ge=0, le=1200000)
|
y_cm: Decimal = Field(ge=0, le=1200000)
|
||||||
@@ -147,26 +153,108 @@ class ProductionSpec(StrictModel):
|
|||||||
version: Literal[2, 3]
|
version: Literal[2, 3]
|
||||||
film_width_cm: Decimal
|
film_width_cm: Decimal
|
||||||
height_cm: Decimal = Field(gt=0, le=1200000)
|
height_cm: Decimal = Field(gt=0, le=1200000)
|
||||||
sources: list[ProductionSource] = Field(min_length=1, max_length=20)
|
sources: list[ProductionSource] = Field(min_length=1, max_length=200)
|
||||||
placements: list[ProductionPlacement] = Field(min_length=1, max_length=4000)
|
placements: list[ProductionPlacement] = Field(min_length=1, max_length=4000)
|
||||||
|
|
||||||
|
class Split(StrictModel):
|
||||||
|
"""One sheet of loose art the Site split by contraction class (item 17,
|
||||||
|
Dropstar 2026-10-30): fine lines (C1, C2) on one sheet, thick (C3) on
|
||||||
|
another, each its own item and print file, billed together."""
|
||||||
|
group: str = Field(pattern=r'^[a-z0-9]{1,16}$')
|
||||||
|
part: int = Field(ge=1, le=10, strict=True)
|
||||||
|
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 = {}
|
||||||
|
for item in items:
|
||||||
|
if item.split:
|
||||||
|
groups.setdefault(item.split.group, []).append(item)
|
||||||
|
for parts in groups.values():
|
||||||
|
of = parts[0].split.of
|
||||||
|
if sorted(item.split.part for item in parts) != list(range(1, of + 1)) or \
|
||||||
|
any(item.split.of != of or item.mode != parts[0].mode for item in parts):
|
||||||
|
raise ValueError('Split sheets must list each part once, of one product')
|
||||||
|
|
||||||
|
|
||||||
class Item(StrictModel):
|
class Item(StrictModel):
|
||||||
mode: Literal['file','avulsa','uvfile','uv']
|
mode: Literal['file','avulsa','uvfile','uv','premium']
|
||||||
metres: Decimal = Field(gt=0, le=12000)
|
metres: Decimal = Field(gt=0, le=12000)
|
||||||
grade: int = Field(ge=0, le=100, strict=True)
|
grade: int = Field(ge=0, le=100, strict=True)
|
||||||
uploads: list[UUID] = Field(min_length=1, max_length=20)
|
uploads: list[UUID] = Field(min_length=1, max_length=200)
|
||||||
production: ProductionSpec
|
production: ProductionSpec
|
||||||
quality_status: Literal['ok', 'warning', 'unverified']
|
quality_status: Literal['ok', 'warning', 'unverified']
|
||||||
quality_acknowledged: bool
|
quality_acknowledged: bool
|
||||||
# Residue dots under 2 mm the customer accepted printing on a ready sheet,
|
# Residue dots under 2 mm the customer accepted printing on a ready sheet,
|
||||||
# rather than erasing them (Dropstar, 2026-10-29): 0 when none.
|
# rather than erasing them (Dropstar, 2026-10-29): 0 when none.
|
||||||
residue_accepted: int = Field(default=0, ge=0, le=1000000, strict=True)
|
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)
|
||||||
|
stroke_class: Literal['C1', 'C2', 'C3'] | None = None
|
||||||
|
# A sheet with fine lines and solid areas (item 16): the customer kept the
|
||||||
|
# measure (protect the fine lines) or chose to protect the solid areas (C3).
|
||||||
|
stroke_choice: Literal['measured', 'client_c3'] | None = None
|
||||||
|
# Where the thinnest stroke sits in the assembled film, from 0 (top) to 1
|
||||||
|
# (bottom): the proof card crops a 15 cm window around it (Dropstar, 05/11).
|
||||||
|
proof_y_fraction: Decimal | None = Field(default=None, ge=0, le=1)
|
||||||
|
# The lowest source resolution the server measured, for the Prumo report
|
||||||
|
# (Dropstar, 05/11). None when the format cannot be measured.
|
||||||
|
source_dpi: int | None = Field(default=None, ge=0, le=1000000)
|
||||||
|
split: Split | None = None
|
||||||
|
|
||||||
|
@field_validator('uploads', mode='before')
|
||||||
|
@classmethod
|
||||||
|
def uploads_cap(cls, value):
|
||||||
|
# The Site shows a "Value error, ..." message as it is (web/checkout.js
|
||||||
|
# problem()); the Field cap alone would give the generic sentence.
|
||||||
|
if isinstance(value, list) and len(value) > 200:
|
||||||
|
raise ValueError('Este item tem mais de 200 arquivos. Divida em dois itens.')
|
||||||
|
return value
|
||||||
|
|
||||||
@model_validator(mode='after')
|
@model_validator(mode='after')
|
||||||
def production_matches_uploads(self):
|
def production_matches_uploads(self):
|
||||||
|
if self.split and (self.mode not in ('avulsa', 'uv') or self.split.part > self.split.of):
|
||||||
|
raise ValueError('Only loose artwork is split into sheets')
|
||||||
if [source.upload_id for source in self.production.sources] != self.uploads:
|
if [source.upload_id for source in self.production.sources] != self.uploads:
|
||||||
raise ValueError('Production sources must match uploaded files in order')
|
raise ValueError('Production sources must match uploaded files in order')
|
||||||
is_sheet = self.mode in ('file', 'uvfile')
|
is_sheet = self.mode in ('file', 'uvfile', 'premium')
|
||||||
# UV is 27 cm wide (Dropstar, 2026-10-28; it was 28,5).
|
# UV is 27 cm wide (Dropstar, 2026-10-28; it was 28,5).
|
||||||
film_width = Decimal('27') if self.mode in ('uvfile', 'uv') else Decimal('57')
|
film_width = Decimal('27') if self.mode in ('uvfile', 'uv') else Decimal('57')
|
||||||
if self.production.film_width_cm != film_width:
|
if self.production.film_width_cm != film_width:
|
||||||
@@ -176,6 +264,8 @@ class Item(StrictModel):
|
|||||||
raise ValueError('Production source does not fit the selected product')
|
raise ValueError('Production source does not fit the selected product')
|
||||||
if is_sheet and (source.rotation_degrees or source.mirrored):
|
if is_sheet and (source.rotation_degrees or source.mirrored):
|
||||||
raise ValueError('Finished sheets cannot be rotated or mirrored by the layout')
|
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.
|
# A textile transfer is pressed face down: mirrored, it prints backwards.
|
||||||
if self.mode == 'avulsa' and source.mirrored:
|
if self.mode == 'avulsa' and source.mirrored:
|
||||||
raise ValueError('Textile artwork cannot be mirrored')
|
raise ValueError('Textile artwork cannot be mirrored')
|
||||||
@@ -201,10 +291,48 @@ class Item(StrictModel):
|
|||||||
raise ValueError('Finished sheets must retain their original orientation')
|
raise ValueError('Finished sheets must retain their original orientation')
|
||||||
if placed != expected:
|
if placed != expected:
|
||||||
raise ValueError('Production layout does not cover every source copy')
|
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:
|
if self.quality_status == 'warning' and not self.quality_acknowledged:
|
||||||
raise ValueError('Resolution warning must be acknowledged')
|
raise ValueError('Resolution warning must be acknowledged')
|
||||||
return self
|
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: a value out of range
|
||||||
|
(a cart left open for hours, DTF-WEB-9) is dropped, never refused.
|
||||||
|
"""
|
||||||
|
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):
|
class QuoteRequest(StrictModel):
|
||||||
request_key: UUID
|
request_key: UUID
|
||||||
customer: Customer
|
customer: Customer
|
||||||
@@ -213,6 +341,54 @@ class QuoteRequest(StrictModel):
|
|||||||
destination: Destination | None = None
|
destination: Destination | None = None
|
||||||
# "Quero aprovar uma prova antes de imprimir": the order waits for the customer.
|
# "Quero aprovar uma prova antes de imprimir": the order waits for the customer.
|
||||||
proof: bool = False
|
proof: bool = False
|
||||||
|
# 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).
|
||||||
|
timings: ClientTimings | None = None
|
||||||
|
|
||||||
|
@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')
|
||||||
|
def treatment_arts_exist(self):
|
||||||
|
if isinstance(self.treatment, list):
|
||||||
|
seen = set()
|
||||||
|
for item_index, source_index in self.treatment:
|
||||||
|
if (item_index < 0 or source_index < 0 or item_index >= len(self.items)
|
||||||
|
or source_index >= len(self.items[item_index].production.sources)):
|
||||||
|
raise ValueError('Ajuste Fino: arte não encontrada no pedido.')
|
||||||
|
if (item_index, source_index) in seen:
|
||||||
|
raise ValueError('Ajuste Fino: cada arte aparece uma vez.')
|
||||||
|
seen.add((item_index, source_index))
|
||||||
|
return self
|
||||||
|
|
||||||
|
@model_validator(mode='after')
|
||||||
|
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')
|
@model_validator(mode='after')
|
||||||
def destination_matches_freight(self):
|
def destination_matches_freight(self):
|
||||||
@@ -225,9 +401,55 @@ class QuoteRequest(StrictModel):
|
|||||||
raise ValueError('The delivery address CEP must be the CEP freight was quoted for')
|
raise ValueError('The delivery address CEP must be the CEP freight was quoted for')
|
||||||
return self
|
return self
|
||||||
|
|
||||||
|
class MontadorOrder(StrictModel):
|
||||||
|
"""What the montador sends (fronts 7a.3 and 7a.4): Interno or Venda, loose
|
||||||
|
artwork only; the server prices and approves it as a quote. An Interno
|
||||||
|
order takes the fixed customer from the database, a Venda one the customer
|
||||||
|
picked from Tiny. A Venda ships with the Site's freight or travels with the
|
||||||
|
customer's clothing order; an Interno never ships."""
|
||||||
|
request_key: UUID
|
||||||
|
kind: Literal['interno', 'venda']
|
||||||
|
# Empty for an Interno order: the server reads the internal customer.
|
||||||
|
customer: Customer | None = None
|
||||||
|
items: list[Item] = Field(min_length=1, max_length=30)
|
||||||
|
# A Venda that travels with the customer's clothing order; pickup freight.
|
||||||
|
with_order: int | None = Field(default=None, ge=1, le=999999, strict=True)
|
||||||
|
# A Venda with "Envio": the chosen freight service and the full address.
|
||||||
|
freight: Freight | None = None
|
||||||
|
destination: Destination | None = None
|
||||||
|
|
||||||
|
@model_validator(mode='after')
|
||||||
|
def order_kind(self):
|
||||||
|
if any(item.mode != 'avulsa' for item in self.items):
|
||||||
|
raise ValueError('O montador só monta artes avulsas.')
|
||||||
|
if self.kind == 'venda' and self.customer is None:
|
||||||
|
raise ValueError('O pedido de venda precisa do cliente.')
|
||||||
|
delivery = bool(self.freight and self.freight.service != 'pickup')
|
||||||
|
if self.kind == 'interno':
|
||||||
|
if self.with_order is not None:
|
||||||
|
raise ValueError('O pedido interno não tem envio.')
|
||||||
|
if delivery or self.destination is not None:
|
||||||
|
raise ValueError('O pedido interno não tem envio.')
|
||||||
|
elif delivery:
|
||||||
|
if self.with_order is not None:
|
||||||
|
raise ValueError('Escolha retirada, envio ou junto com o pedido de roupa.')
|
||||||
|
if self.destination is None:
|
||||||
|
raise ValueError('O envio precisa do endereço completo.')
|
||||||
|
if self.destination.postal_code != self.freight.postal_code:
|
||||||
|
raise ValueError('O CEP do frete e o do endereço precisam ser o mesmo.')
|
||||||
|
elif self.destination is not None:
|
||||||
|
raise ValueError('Só o pedido com envio tem endereço de entrega.')
|
||||||
|
return self
|
||||||
|
|
||||||
class Review(StrictModel):
|
class Review(StrictModel):
|
||||||
items: list[Item] = Field(min_length=1, max_length=30)
|
items: list[Item] = Field(min_length=1, max_length=30)
|
||||||
|
|
||||||
|
@model_validator(mode='after')
|
||||||
|
def splits_complete(self):
|
||||||
|
check_splits(self.items)
|
||||||
|
check_one_machine(self.items)
|
||||||
|
return self
|
||||||
|
|
||||||
class Pay(StrictModel):
|
class Pay(StrictModel):
|
||||||
quote_id: UUID
|
quote_id: UUID
|
||||||
|
|
||||||
@@ -240,8 +462,8 @@ class PaymentMethod(StrictModel):
|
|||||||
# Up to 3, as Dropstar sells; the card form offers no more.
|
# Up to 3, as Dropstar sells; the card form offers no more.
|
||||||
installments: int = Field(default=1, ge=1, le=3, strict=True)
|
installments: int = Field(default=1, ge=1, le=3, strict=True)
|
||||||
issuer_id: str | None = Field(default=None, max_length=40)
|
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 document in the card form, which opens with the order's: the payer
|
||||||
# the cardholder, not necessarily the company on the invoice.
|
# when it is a valid CPF or CNPJ (app/mercadopago.py payer).
|
||||||
payer_document_type: Literal['CPF', 'CNPJ'] | None = None
|
payer_document_type: Literal['CPF', 'CNPJ'] | None = None
|
||||||
payer_document: str | None = Field(default=None, pattern=r'^[0-9]{11,14}$')
|
payer_document: str | None = Field(default=None, pattern=r'^[0-9]{11,14}$')
|
||||||
|
|
||||||
@@ -264,6 +486,85 @@ class Move(StrictModel):
|
|||||||
state: Literal['rec','tra','imp','cor','rev','fin']
|
state: Literal['rec','tra','imp','cor','rev','fin']
|
||||||
version: int = Field(ge=0)
|
version: int = Field(ge=0)
|
||||||
reason: str = Field(default='', max_length=1000)
|
reason: str = Field(default='', max_length=1000)
|
||||||
|
# Pulled into Imprimindo onto a machine's lane: the machine it prints on.
|
||||||
|
machine_id: UUID | None = None
|
||||||
|
|
||||||
|
class MachineEntry(StrictModel):
|
||||||
|
"""One thing entered into a machine (Fase 2, front 1a, app/machine_log.py)."""
|
||||||
|
kind: Literal['supply', 'part', 'event']
|
||||||
|
item: str = Field(min_length=1, max_length=40)
|
||||||
|
quantity: Decimal | None = Field(default=None, gt=0, le=999999, decimal_places=3)
|
||||||
|
cost_cents: int | None = Field(default=None, ge=0, le=10**12, strict=True)
|
||||||
|
serial: str | None = Field(default=None, max_length=200)
|
||||||
|
note: str | None = Field(default=None, max_length=1000)
|
||||||
|
stop_minutes: int | None = Field(default=None, gt=0, le=100000, strict=True)
|
||||||
|
from_alert: bool = False
|
||||||
|
|
||||||
|
|
||||||
|
class MachineSheet(StrictModel):
|
||||||
|
"""The machine's own data, typed by Gestão: cost, start and supply minimums."""
|
||||||
|
price_cents: int | None = Field(default=None, ge=0, le=10**12, strict=True)
|
||||||
|
installed_on: date | None = None
|
||||||
|
minimums: dict[str, Decimal | None] = Field(default_factory=dict)
|
||||||
|
|
||||||
|
|
||||||
|
class SiteProductToggle(StrictModel):
|
||||||
|
"""Ligar ou desligar um produto na aba Site (Fase 2, front 8)."""
|
||||||
|
enabled: bool
|
||||||
|
|
||||||
|
|
||||||
|
class PriceBand(StrictModel):
|
||||||
|
"""Uma faixa por metragem: a partir de X m, o metro passa a custar Y."""
|
||||||
|
from_metres: Decimal
|
||||||
|
unit_cents: int = Field(strict=True)
|
||||||
|
|
||||||
|
|
||||||
|
class SitePriceNew(StrictModel):
|
||||||
|
"""Um novo preço e a data em que começa; sem data, começa agora."""
|
||||||
|
unit_cents: int = Field(ge=0, le=10000000, strict=True)
|
||||||
|
starts_at: datetime | None = None
|
||||||
|
# As faixas viajam com o preço (front 8.2); vazio é o preço único.
|
||||||
|
bands: list[PriceBand] = Field(default_factory=list)
|
||||||
|
|
||||||
|
|
||||||
|
class CouponNew(StrictModel):
|
||||||
|
"""Um cupom novo, criado na aba Site (front 8.3)."""
|
||||||
|
code: str = Field(min_length=1, max_length=30)
|
||||||
|
kind: Literal['percent', 'per_metre']
|
||||||
|
value: int = Field(gt=0, le=10000000, strict=True)
|
||||||
|
valid_from: datetime | None = None
|
||||||
|
valid_until: datetime | None = None
|
||||||
|
min_metres: Decimal | None = Field(default=None, gt=0, decimal_places=1)
|
||||||
|
max_uses: int | None = Field(default=None, gt=0, strict=True)
|
||||||
|
max_uses_per_customer: int | None = Field(default=None, gt=0, strict=True)
|
||||||
|
product: Literal['file', 'avulsa', 'uvfile', 'uv', 'premium'] | None = None
|
||||||
|
note: str = Field(default='', max_length=1000)
|
||||||
|
|
||||||
|
|
||||||
|
class CouponUpdate(StrictModel):
|
||||||
|
"""Os campos de um cupom que podem mudar; o código fica como foi criado."""
|
||||||
|
kind: Literal['percent', 'per_metre'] | None = None
|
||||||
|
value: int | None = Field(default=None, gt=0, le=10000000, strict=True)
|
||||||
|
valid_from: datetime | None = None
|
||||||
|
valid_until: datetime | None = None
|
||||||
|
min_metres: Decimal | None = Field(default=None, gt=0, decimal_places=1)
|
||||||
|
max_uses: int | None = Field(default=None, gt=0, strict=True)
|
||||||
|
max_uses_per_customer: int | None = Field(default=None, gt=0, strict=True)
|
||||||
|
product: Literal['file', 'avulsa', 'uvfile', 'uv', 'premium'] | None = None
|
||||||
|
note: str | None = Field(default=None, max_length=1000)
|
||||||
|
paused: bool | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class GradeRules(StrictModel):
|
||||||
|
"""As regras da nota da arte: um limite por ação, ou nada (null)."""
|
||||||
|
aviso: int | None = Field(ge=1, le=100, strict=True)
|
||||||
|
tratamento: int | None = Field(ge=1, le=100, strict=True)
|
||||||
|
|
||||||
|
|
||||||
|
class Contraction(StrictModel):
|
||||||
|
item_index: int = Field(ge=0, le=100)
|
||||||
|
# None returns the item to the class the browser measured.
|
||||||
|
value: Literal['C1', 'C2', 'C3'] | None = None
|
||||||
|
|
||||||
class Resolution(StrictModel):
|
class Resolution(StrictModel):
|
||||||
note: str = Field(min_length=3, max_length=1000)
|
note: str = Field(min_length=3, max_length=1000)
|
||||||
@@ -352,3 +653,25 @@ class ArtworkSubmission(StrictModel):
|
|||||||
version: int = Field(ge=0, strict=True)
|
version: int = Field(ge=0, strict=True)
|
||||||
files: list[FileReference] = Field(min_length=1, max_length=60)
|
files: list[FileReference] = Field(min_length=1, max_length=60)
|
||||||
note: str = Field(min_length=1, max_length=1000)
|
note: str = Field(min_length=1, max_length=1000)
|
||||||
|
|
||||||
|
class StampSize(StrictModel):
|
||||||
|
"""One row of the montador's size table (Fase 2, front 7)."""
|
||||||
|
letter: str = Field(pattern=r'^[A-Z]{1,2}$')
|
||||||
|
width_cm: Decimal = Field(gt=0, le=56, decimal_places=2)
|
||||||
|
|
||||||
|
class StampSizeTable(StrictModel):
|
||||||
|
"""The whole table, replaced in one go by Gestão."""
|
||||||
|
sizes: list[StampSize] = Field(min_length=1, max_length=26)
|
||||||
|
|
||||||
|
@model_validator(mode='after')
|
||||||
|
def letters_unique(self):
|
||||||
|
letters = [row.letter for row in self.sizes]
|
||||||
|
if len(letters) != len(set(letters)):
|
||||||
|
raise ValueError('Cada tamanho tem uma letra própria.')
|
||||||
|
return self
|
||||||
|
|
||||||
|
|
||||||
|
class StampBrand(StrictModel):
|
||||||
|
"""The brand recorded per stamp code, for the future catalogue (front 7a.3)."""
|
||||||
|
brand: str = Field(default='', max_length=120)
|
||||||
|
public: bool = False
|
||||||
|
|||||||
@@ -8,7 +8,20 @@ import os
|
|||||||
import re
|
import re
|
||||||
from decimal import Decimal, ROUND_CEILING
|
from decimal import Decimal, ROUND_CEILING
|
||||||
|
|
||||||
PRICES = {'file': 1990, 'avulsa': 2190, 'uvfile': 7990, 'uv': 8990}
|
# 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
|
# A finished sheet the Site cannot open (CDR, AI, PSD, TIFF) is opened by a
|
||||||
# person before printing. It pays this per metre on top of the product's price
|
# person before printing. It pays this per metre on top of the product's price
|
||||||
@@ -24,6 +37,18 @@ def manual_extra_cents() -> int:
|
|||||||
return value
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def treatment_cents() -> int:
|
||||||
|
"""Ajuste Fino, a fixed amount per art (front 1a).
|
||||||
|
|
||||||
|
Zero keeps the option hidden: the price is the client's decision, and the
|
||||||
|
server and the Site read the same `TREATMENT_CENTS`.
|
||||||
|
"""
|
||||||
|
value = int(os.environ.get('TREATMENT_CENTS', '0') or 0)
|
||||||
|
if not 0 <= value <= 1000000:
|
||||||
|
raise ValueError('TREATMENT_CENTS must be between 0 and 1000000')
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
def is_manual(item, names) -> bool:
|
def is_manual(item, names) -> bool:
|
||||||
"""Whether a finished-sheet item has a file someone must open by hand: one
|
"""Whether a finished-sheet item has a file someone must open by hand: one
|
||||||
the customer measured, or one in a format the Site cannot read."""
|
the customer measured, or one in a format the Site cannot read."""
|
||||||
@@ -32,21 +57,55 @@ def is_manual(item, names) -> bool:
|
|||||||
for source in item['production']['sources'])
|
for source in item['production']['sources'])
|
||||||
|
|
||||||
|
|
||||||
def price(mode: str, metres: str, grade: int, extra_cents: int = 0) -> dict:
|
def price(mode: str, metres: str, grade: int, extra_cents: int = 0, minimum: Decimal = Decimal('1'),
|
||||||
|
unit_cents: int | None = None) -> dict:
|
||||||
"""The item's charge. The grade is validated and kept with the item; the
|
"""The item's charge. The grade is validated and kept with the item; the
|
||||||
price does not depend on it."""
|
price does not depend on it. A split sheet has no minimum of its own: its
|
||||||
|
group has one (bill_splits). `unit_cents` is the current price from the
|
||||||
|
database (app/catalog.py); without it, the table above."""
|
||||||
length = Decimal(str(metres))
|
length = Decimal(str(metres))
|
||||||
if mode not in PRICES or not length.is_finite() or not 0 < length <= 12000:
|
if mode not in PRICES or not length.is_finite() or not 0 < length <= 12000:
|
||||||
raise ValueError('Invalid product or length')
|
raise ValueError('Invalid product or length')
|
||||||
if isinstance(grade, bool) or not isinstance(grade, int) or not 0 <= grade <= 100:
|
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')
|
raise ValueError('Grade must be an integer between 0 and 100')
|
||||||
billed = max(Decimal('1'), (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:
|
if isinstance(extra_cents, bool) or not isinstance(extra_cents, int) or extra_cents < 0:
|
||||||
raise ValueError('Invalid extra charge')
|
raise ValueError('Invalid extra charge')
|
||||||
unit = PRICES[mode] + extra_cents
|
unit = (PRICES[mode] if unit_cents is None else unit_cents) + extra_cents
|
||||||
priced = {'mode': mode, 'metres': str(length), 'grade': grade,
|
priced = {'mode': mode, 'metres': str(length), 'grade': grade,
|
||||||
'billed_metres': str(billed), 'unit_cents': unit,
|
'billed_metres': str(billed), 'unit_cents': unit,
|
||||||
'total_cents': int(billed * unit)}
|
'total_cents': int(billed * unit)}
|
||||||
if extra_cents:
|
if extra_cents:
|
||||||
priced['manual_extra_cents'] = extra_cents
|
priced['manual_extra_cents'] = extra_cents
|
||||||
return priced
|
return priced
|
||||||
|
|
||||||
|
|
||||||
|
def bill_splits(priced: list) -> list:
|
||||||
|
"""The order minimum of 1 m once per split group, on its first sheet: the
|
||||||
|
customer did not choose the split (item 17), so it never costs a metre more."""
|
||||||
|
for group in dict.fromkeys(i['split']['group'] for i in priced if i.get('split')):
|
||||||
|
parts = [i for i in priced if (i.get('split') or {}).get('group') == group]
|
||||||
|
short = Decimal('1') - sum(Decimal(i['billed_metres']) for i in parts)
|
||||||
|
if short > 0:
|
||||||
|
first = min(parts, key=lambda i: i['split']['part'])
|
||||||
|
billed = Decimal(first['billed_metres']) + short
|
||||||
|
first.update(billed_metres=str(billed), total_cents=int(billed * first['unit_cents']))
|
||||||
|
return priced
|
||||||
|
|
||||||
|
|
||||||
|
def apply_bands(priced: list, unit_by_mode: dict) -> list:
|
||||||
|
"""Rewrite the items of each mode to the band price for the order's total
|
||||||
|
metres of that product (front 8.2). The manual-file extra stays on top of
|
||||||
|
each item; a mode absent from `unit_by_mode` is untouched."""
|
||||||
|
for item in priced:
|
||||||
|
if item['mode'] in unit_by_mode:
|
||||||
|
unit = unit_by_mode[item['mode']] + item.get('manual_extra_cents', 0)
|
||||||
|
item['unit_cents'] = unit
|
||||||
|
item['total_cents'] = int(Decimal(str(item['billed_metres'])) * unit)
|
||||||
|
return priced
|
||||||
|
|
||||||
|
|
||||||
|
def sheet_label(item: dict) -> str:
|
||||||
|
"""' · folha 1 de 2' on a split sheet (item 17), for the customer's lists."""
|
||||||
|
split = item.get('split')
|
||||||
|
return f" · folha {split['part']} de {split['of']}" if split else ''
|
||||||
|
|||||||
81
app/coupons.py
Normal file
81
app/coupons.py
Normal file
@@ -0,0 +1,81 @@
|
|||||||
|
"""Discount coupons typed by the customer at checkout (Fase 2, front 8.3).
|
||||||
|
|
||||||
|
One coupon per order. It is checked when the quote is created and again at
|
||||||
|
approval; only paid orders count against its limits, so a cart that waits or
|
||||||
|
expires never spends a use. The discount is computed on the server after the
|
||||||
|
bands of app/catalog.py, on the eligible items only, and never on freight or
|
||||||
|
the treatment. An approved quote keeps the coupon it was approved with.
|
||||||
|
"""
|
||||||
|
from decimal import Decimal, ROUND_FLOOR
|
||||||
|
|
||||||
|
from . import catalog
|
||||||
|
|
||||||
|
# A test order, a cancelled one and a proof card are not a sale (as the
|
||||||
|
# board's REAL_ORDER): they do not spend a coupon use.
|
||||||
|
PAID_ORDER = ("o.cancelled_at IS NULL AND COALESCE(o.payment->>'provider','') <> 'teste' "
|
||||||
|
"AND o.parent_id IS NULL")
|
||||||
|
|
||||||
|
|
||||||
|
def eligible_items(items, product):
|
||||||
|
"""The items a coupon applies to: all of them, or one product's."""
|
||||||
|
return [item for item in items if product is None or item.get('mode') == product]
|
||||||
|
|
||||||
|
|
||||||
|
def discount_cents(kind, value, items):
|
||||||
|
"""The discount on the eligible items, in cents. Percent: floor of the
|
||||||
|
items' total. Per metre: the value times their billed metres, floored.
|
||||||
|
Never more than the items' total."""
|
||||||
|
total = sum(int(item.get('total_cents') or 0) for item in items)
|
||||||
|
if kind == 'percent':
|
||||||
|
discount = int((Decimal(total) * value / 100).to_integral_value(rounding=ROUND_FLOOR))
|
||||||
|
elif kind == 'per_metre':
|
||||||
|
metres = sum(Decimal(str(item.get('billed_metres') or 0)) for item in items)
|
||||||
|
discount = int((metres * value).to_integral_value(rounding=ROUND_FLOOR))
|
||||||
|
else:
|
||||||
|
raise ValueError('Invalid coupon kind')
|
||||||
|
return max(0, min(discount, total))
|
||||||
|
|
||||||
|
|
||||||
|
def metres_label(value):
|
||||||
|
"""5,5 m: how a minimum reads on the Site."""
|
||||||
|
return f'{Decimal(value).normalize():f}'.replace('.', ',')
|
||||||
|
|
||||||
|
|
||||||
|
def check(c, code, customer_document, priced_items):
|
||||||
|
"""The coupon for this cart and customer, or a 422 saying why not.
|
||||||
|
Returns {'id', 'code', 'discount_cents'}."""
|
||||||
|
# Imported here so the pure helpers above load without the web framework
|
||||||
|
# (tests/test_coupons.py runs on the host, where FastAPI is not installed).
|
||||||
|
from fastapi import HTTPException
|
||||||
|
code = (code or '').strip().upper()
|
||||||
|
row = c.execute('''SELECT *, now() AS now FROM dtf_local.coupons
|
||||||
|
WHERE code=%s AND deleted_at IS NULL''', (code,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(422, 'Cupom não encontrado.')
|
||||||
|
if row['paused']:
|
||||||
|
raise HTTPException(422, 'Este cupom está pausado.')
|
||||||
|
if row['valid_from'] > row['now']:
|
||||||
|
raise HTTPException(422, 'Este cupom ainda não começou.')
|
||||||
|
if row['valid_until'] is not None and row['valid_until'] <= row['now']:
|
||||||
|
raise HTTPException(422, 'Este cupom expirou.')
|
||||||
|
eligible = eligible_items(priced_items, row['product'])
|
||||||
|
if row['product'] and not eligible:
|
||||||
|
raise HTTPException(422, f'Este cupom vale só para {catalog.TITLES[row["product"]]}.')
|
||||||
|
metres = sum(Decimal(str(item.get('billed_metres') or 0)) for item in eligible)
|
||||||
|
if row['min_metres'] is not None and metres < row['min_metres']:
|
||||||
|
raise HTTPException(422, f'Este cupom pede pelo menos {metres_label(row["min_metres"])} m.')
|
||||||
|
# Uses count only paid orders: the limit is spent at payment, not at the
|
||||||
|
# quote, and an order already paid is never refused afterwards.
|
||||||
|
used = c.execute(f'''SELECT count(*) AS n FROM dtf_local.orders o
|
||||||
|
WHERE o.snapshot->'coupon'->>'id'=%s AND {PAID_ORDER}''',
|
||||||
|
(str(row['id']),)).fetchone()['n']
|
||||||
|
if row['max_uses'] is not None and used >= row['max_uses']:
|
||||||
|
raise HTTPException(422, 'Este cupom já foi usado o máximo de vezes.')
|
||||||
|
if row['max_uses_per_customer'] is not None and customer_document:
|
||||||
|
mine = c.execute(f'''SELECT count(*) AS n FROM dtf_local.orders o
|
||||||
|
WHERE o.snapshot->'coupon'->>'id'=%s AND o.snapshot->'customer'->>'cnpj'=%s
|
||||||
|
AND {PAID_ORDER}''', (str(row['id']), str(customer_document))).fetchone()['n']
|
||||||
|
if mine >= row['max_uses_per_customer']:
|
||||||
|
raise HTTPException(422, 'Você já usou este cupom.')
|
||||||
|
return {'id': str(row['id']), 'code': row['code'],
|
||||||
|
'discount_cents': discount_cents(row['kind'], row['value'], eligible)}
|
||||||
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')"""
|
||||||
@@ -15,15 +15,19 @@ again, by the Site's own rules:
|
|||||||
is only vectors (web/site-pdf.js, dpiDasImagens and resumoDpi).
|
is only vectors (web/site-pdf.js, dpiDasImagens and resumoDpi).
|
||||||
|
|
||||||
Images are measured from their first bytes, never decoded. A PDF is opened
|
Images are measured from their first bytes, never decoded. A PDF is opened
|
||||||
only up to PDF_MAX_BYTES, the size the Site itself analyses. A grade that
|
only up to PDF_MAX_BYTES, the size the Site itself analyses. Its DPI is worked
|
||||||
cannot be recomputed is None; the caller decides what that means.
|
out when the scan finishes and stored on the upload row (pdf_checked), so
|
||||||
|
checkout uses the stored number and opens the file only when it is absent. A
|
||||||
|
grade that cannot be recomputed is None; the caller decides what that means.
|
||||||
"""
|
"""
|
||||||
import math
|
import math
|
||||||
import os
|
import os
|
||||||
import struct
|
import struct
|
||||||
import tempfile
|
import tempfile
|
||||||
|
|
||||||
DPI_IDEAL = 300
|
DPI_IDEAL = 200
|
||||||
|
DPI_REFUSE = 96
|
||||||
|
PDF_VECTOR_DPI = 300
|
||||||
# The Site analyses PDFs up to 150 MB (GRANDE_BYTES); above that it does not
|
# The Site analyses PDFs up to 150 MB (GRANDE_BYTES); above that it does not
|
||||||
# grade them, so neither does this.
|
# grade them, so neither does this.
|
||||||
PDF_MAX_BYTES = 150 * 1048576
|
PDF_MAX_BYTES = 150 * 1048576
|
||||||
@@ -123,28 +127,46 @@ def pdf_dpi(path):
|
|||||||
return None
|
return None
|
||||||
found = [(dpi, area) for dpi, area in found if dpi > 0]
|
found = [(dpi, area) for dpi, area in found if dpi > 0]
|
||||||
if not found:
|
if not found:
|
||||||
return DPI_IDEAL
|
return PDF_VECTOR_DPI
|
||||||
total = sum(area for _, area in found) or 1
|
total = sum(area for _, area in found) or 1
|
||||||
return js_round(sum(dpi * area for dpi, area in found) / total)
|
return js_round(sum(dpi * area for dpi, area in found) / total)
|
||||||
|
|
||||||
|
|
||||||
|
def stored_pdf_dpi(storage, row):
|
||||||
|
"""A stored PDF's DPI, read once; None when it is above PDF_MAX_BYTES."""
|
||||||
|
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)
|
||||||
|
|
||||||
|
|
||||||
class Files:
|
class Files:
|
||||||
"""The uploaded files, read from storage as little as needed."""
|
"""The uploaded files, read from storage as little as needed."""
|
||||||
|
|
||||||
def __init__(self, storage):
|
def __init__(self, storage):
|
||||||
self.storage = storage
|
self.storage = storage
|
||||||
|
# A PDF is read once per quote: source_dpi, resolution_issue and
|
||||||
|
# mismatch all ask for the same files.
|
||||||
|
self._heads = {}
|
||||||
|
self._dpis = {}
|
||||||
|
|
||||||
def head(self, row):
|
def head(self, row):
|
||||||
return self.storage.client.get_object(Bucket=self.storage.bucket, Key=row['object_key'],
|
key = row['object_key']
|
||||||
Range=f'bytes=0-{HEAD_BYTES - 1}')['Body'].read()
|
if key not in self._heads:
|
||||||
|
self._heads[key] = self.storage.client.get_object(
|
||||||
|
Bucket=self.storage.bucket, Key=key, Range=f'bytes=0-{HEAD_BYTES - 1}')['Body'].read()
|
||||||
|
return self._heads[key]
|
||||||
|
|
||||||
def pdf_dpi(self, row):
|
def pdf_dpi(self, row):
|
||||||
if row['size'] > PDF_MAX_BYTES:
|
key = row['object_key']
|
||||||
return None
|
if key not in self._dpis:
|
||||||
with tempfile.NamedTemporaryFile(suffix='.pdf') as handle:
|
if row.get('pdf_checked'):
|
||||||
self.storage.client.download_fileobj(self.storage.bucket, row['object_key'], handle)
|
self._dpis[key] = row['pdf_dpi']
|
||||||
handle.flush()
|
else:
|
||||||
return pdf_dpi(handle.name)
|
self._dpis[key] = stored_pdf_dpi(self.storage, row)
|
||||||
|
return self._dpis[key]
|
||||||
|
|
||||||
|
|
||||||
def source_dpi(files, row, source):
|
def source_dpi(files, row, source):
|
||||||
@@ -178,6 +200,62 @@ def item_grade(files, item, rows):
|
|||||||
return js_round(sum(grade_of(d) for d in dpis) / len(dpis))
|
return js_round(sum(grade_of(d) for d in dpis) / len(dpis))
|
||||||
|
|
||||||
|
|
||||||
|
def resolution_issue(files, items, rows):
|
||||||
|
"""Refuse sub-96 DPI and require recorded consent for measurable 96–199 DPI.
|
||||||
|
|
||||||
|
Unknown formats remain for manual review; they cannot be treated as a
|
||||||
|
measured zero DPI or silently called high-resolution artwork.
|
||||||
|
"""
|
||||||
|
for index, item in enumerate(items, 1):
|
||||||
|
dpis = []
|
||||||
|
for source in item['production']['sources']:
|
||||||
|
row = rows.get(str(source['upload_id']))
|
||||||
|
dpi = source_dpi(files, row, source) if row else None
|
||||||
|
if dpi is None:
|
||||||
|
dpis = []
|
||||||
|
break
|
||||||
|
dpis.append(dpi)
|
||||||
|
if not dpis:
|
||||||
|
continue
|
||||||
|
# The Site shows and compares the rounded DPI (web/site-quality.js,
|
||||||
|
# site-pdf.js): decide on the same whole number, not the raw fraction.
|
||||||
|
shown = js_round(min(dpis))
|
||||||
|
if shown < DPI_REFUSE:
|
||||||
|
return f'Item {index}: resolução de {shown} DPI abaixo do mínimo de {DPI_REFUSE} DPI.'
|
||||||
|
if shown < DPI_IDEAL and (item['quality_status'] != 'warning' or not item['quality_acknowledged']):
|
||||||
|
return f'Item {index}: confirme a ressalva de resolução entre {DPI_REFUSE} e {DPI_IDEAL - 1} DPI.'
|
||||||
|
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):
|
def mismatch(files, items, rows):
|
||||||
"""Why a cart's grades cannot be approved at checkout, or None."""
|
"""Why a cart's grades cannot be approved at checkout, or None."""
|
||||||
for item in items:
|
for item in items:
|
||||||
|
|||||||
34
app/grade_rules.py
Normal file
34
app/grade_rules.py
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
"""What the art grade decides, set in the Kanban's Site tab (Fase 2, front 8.5).
|
||||||
|
|
||||||
|
With no rule nothing changes anywhere. An item triggers a rule when its grade
|
||||||
|
is below the rule's `below`; the order's worst item decides. `aviso` flags the
|
||||||
|
order for the designer; `tratamento` makes Ajuste Fino required, but only while
|
||||||
|
it is offered (enabled and priced above zero).
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def current_rules(c) -> dict:
|
||||||
|
"""{'aviso': 70, 'tratamento': 50} for the rows that exist."""
|
||||||
|
return {row['action']: row['below'] for row in
|
||||||
|
c.execute('SELECT action, below FROM dtf_local.grade_rules').fetchall()}
|
||||||
|
|
||||||
|
|
||||||
|
def triggered(rules: dict, items, treatment_offered: bool) -> dict:
|
||||||
|
"""The rules the order's worst item triggers: {'aviso': N}, maybe with
|
||||||
|
'tratamento': N. N is the worst grade; empty when no rule applies."""
|
||||||
|
grades = [item.get('grade') for item in items if item.get('grade') is not None]
|
||||||
|
if not grades:
|
||||||
|
return {}
|
||||||
|
worst = min(grades)
|
||||||
|
flags = {}
|
||||||
|
if 'aviso' in rules and worst < rules['aviso']:
|
||||||
|
flags['aviso'] = worst
|
||||||
|
if treatment_offered and 'tratamento' in rules and worst < rules['tratamento']:
|
||||||
|
flags['tratamento'] = worst
|
||||||
|
return flags
|
||||||
|
|
||||||
|
|
||||||
|
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 '
|
||||||
|
'é obrigatório neste pedido.')
|
||||||
189
app/hotfolder.py
Normal file
189
app/hotfolder.py
Normal file
@@ -0,0 +1,189 @@
|
|||||||
|
"""Each machine's hot folders (Dropstar's third round, item 10, 2026-10-29/30).
|
||||||
|
|
||||||
|
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 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
|
||||||
|
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. 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.
|
||||||
|
"""
|
||||||
|
from datetime import timedelta
|
||||||
|
|
||||||
|
# The machines' folders, inside the Kanban's main folder (Dropstar, 2026-10-30).
|
||||||
|
PRINTING_FOLDER = '3. Imprimindo'
|
||||||
|
# A computer that claimed a part and never said it was written.
|
||||||
|
CLAIM_TIMEOUT = timedelta(minutes=10)
|
||||||
|
CLASSES = ('C1', 'C2', 'C3')
|
||||||
|
# The premium product's own folder (Dropstar, 2026-11-10, front 3).
|
||||||
|
PREMIUM = 'PREMIUM'
|
||||||
|
|
||||||
|
|
||||||
|
def contraction(order, index):
|
||||||
|
"""The item's class for the folder: the one chosen in the Kanban, or what
|
||||||
|
the Site measured (C3 when the customer protected the solid areas)."""
|
||||||
|
chosen = (order.get('contraction') or {}).get(str(index)) or {}
|
||||||
|
if chosen.get('class') in CLASSES:
|
||||||
|
return chosen['class']
|
||||||
|
item = order['snapshot']['items'][index]
|
||||||
|
if item.get('stroke_choice') == 'client_c3':
|
||||||
|
return 'C3'
|
||||||
|
return item.get('stroke_class') if item.get('stroke_class') in CLASSES else None
|
||||||
|
|
||||||
|
|
||||||
|
def folder_class(order, index):
|
||||||
|
"""The folder an item's parts go to: PREMIUM for the premium product,
|
||||||
|
whatever contraction class is recorded, else C1/C2/C3."""
|
||||||
|
item = order['snapshot']['items'][index]
|
||||||
|
return PREMIUM if item.get('mode') == 'premium' else contraction(order, index)
|
||||||
|
|
||||||
|
|
||||||
|
def start(c, order_id):
|
||||||
|
"""The order entered Imprimindo: its approved finals queue for its
|
||||||
|
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 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):
|
||||||
|
c.execute('''INSERT INTO dtf_local.hot_parts(order_id,round,seq,item_index,upload_id,name)
|
||||||
|
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."""
|
||||||
|
c.execute('''UPDATE dtf_local.hot_parts SET state=CASE WHEN state IN ('claimed','written') THEN 'withdraw' ELSE 'gone' END,
|
||||||
|
done_at=CASE WHEN state IN ('claimed','written') THEN NULL ELSE now() END
|
||||||
|
WHERE order_id=%s AND state IN ('queued','claimed','written')''', (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 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, 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.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']
|
||||||
|
if row['state'] != 'queued':
|
||||||
|
busy[machine] = busy.get(machine, 0) + 1
|
||||||
|
for row in rows:
|
||||||
|
machine, order = row['machine_id'], row['order_id']
|
||||||
|
if row['state'] != 'queued' or order in blocked:
|
||||||
|
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) >= row['places'] or not cls:
|
||||||
|
blocked.add(order)
|
||||||
|
continue
|
||||||
|
# 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
|
||||||
|
due.append({**row, 'folder': folder})
|
||||||
|
return due
|
||||||
|
|
||||||
|
|
||||||
|
def watched(c):
|
||||||
|
"""The parts written and not yet taken by Flexi, and those to delete."""
|
||||||
|
return c.execute('''SELECT id, order_id, name, folder, state FROM dtf_local.hot_parts
|
||||||
|
WHERE state IN ('written','withdraw') AND folder IS NOT NULL ORDER BY id''').fetchall()
|
||||||
|
|
||||||
|
|
||||||
|
# What a computer reports about a part, and from which states it may.
|
||||||
|
REPORTS = {'written': ('claimed',), 'released': ('claimed',), 'consumed': ('written',), 'gone': ('withdraw',)}
|
||||||
|
|
||||||
|
|
||||||
|
def report(c, part_id, what, user):
|
||||||
|
"""A computer wrote the part, could not, saw Flexi take it, or deleted a
|
||||||
|
withdrawn one. Returns whether the report applied."""
|
||||||
|
if what == 'written':
|
||||||
|
sql = '''UPDATE dtf_local.hot_parts SET state='written', written_at=now() WHERE id=%s AND state='claimed'
|
||||||
|
AND claimed_by=%s RETURNING id'''
|
||||||
|
return bool(c.execute(sql, (part_id, user)).fetchone())
|
||||||
|
if what == 'released':
|
||||||
|
sql = '''UPDATE dtf_local.hot_parts SET state='queued', claimed_at=NULL, claimed_by=NULL, folder=NULL
|
||||||
|
WHERE id=%s AND state='claimed' AND claimed_by=%s RETURNING id'''
|
||||||
|
return bool(c.execute(sql, (part_id, user)).fetchone())
|
||||||
|
new = {'consumed': 'consumed', 'gone': 'gone'}[what]
|
||||||
|
return bool(c.execute(f'''UPDATE dtf_local.hot_parts SET state='{new}', done_at=now() WHERE id=%s
|
||||||
|
AND state=ANY(%s) RETURNING id''', (part_id, list(REPORTS[what]))).fetchone())
|
||||||
|
|
||||||
|
|
||||||
|
def progress(c, order_ids):
|
||||||
|
"""For each order in parts, where its film is (Dropstar, 2026-10-30):
|
||||||
|
"parte 3/7 imprimindo · 4/7 ripando". Flexi rips the part it took last
|
||||||
|
while the one before it prints."""
|
||||||
|
rows = c.execute('''SELECT h.order_id, count(*) AS parts,
|
||||||
|
max(h.seq) FILTER (WHERE h.state='consumed') AS taken,
|
||||||
|
count(*) FILTER (WHERE h.state IN ('claimed','written')) AS waiting
|
||||||
|
FROM dtf_local.hot_parts h
|
||||||
|
WHERE h.order_id=ANY(%s) AND h.round=(SELECT max(round) FROM dtf_local.hot_parts x WHERE x.order_id=h.order_id)
|
||||||
|
GROUP BY h.order_id''', (order_ids,)).fetchall()
|
||||||
|
return {row['order_id']: {'parts': row['parts'], 'taken': row['taken'] or 0, 'waiting': row['waiting']}
|
||||||
|
for row in rows}
|
||||||
129
app/label.py
Normal file
129
app/label.py
Normal file
@@ -0,0 +1,129 @@
|
|||||||
|
"""The 10x15 cm thermal label printed at Finalizado (Fase 2, front 10).
|
||||||
|
|
||||||
|
Marcus, 2026-11-10: when a card reaches Finalizado the Kanban prints a label on
|
||||||
|
the Zebra ZD220: the Tiny order number, the customer, what the order is, pickup
|
||||||
|
or shipping, when it was released and by which Revisor, and a QR with the Tiny
|
||||||
|
order number only. The server renders the page so its content lives in one
|
||||||
|
place. The QR is an inline SVG from segno; nothing is loaded from outside.
|
||||||
|
|
||||||
|
`label_fields` is pure, for the tests; `label_html` only adds the markup and the
|
||||||
|
QR. Without a Tiny receipt the order keeps its own DTF-<number> as the number
|
||||||
|
and in the QR (an Interno order never reaches Tiny).
|
||||||
|
"""
|
||||||
|
import html
|
||||||
|
from datetime import timezone
|
||||||
|
from decimal import Decimal
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
|
LOCAL = ZoneInfo('America/Sao_Paulo')
|
||||||
|
|
||||||
|
SERVICE_NAMES = {'pac': 'Correios PAC', 'sedex': 'Correios SEDEX', 'jadlog': 'Jadlog'}
|
||||||
|
|
||||||
|
|
||||||
|
def _escape(value):
|
||||||
|
return html.escape(str(value if value is not None else ''), quote=True)
|
||||||
|
|
||||||
|
|
||||||
|
def _metres(items):
|
||||||
|
"""The order's billed metres with a comma and two decimals, as the card shows."""
|
||||||
|
total = sum((Decimal(str(item.get('billed_metres') or item.get('metres') or 0))
|
||||||
|
for item in items), Decimal(0))
|
||||||
|
return f'{total:.2f}'.replace('.', ',')
|
||||||
|
|
||||||
|
|
||||||
|
def _sheets(count):
|
||||||
|
return f'{count} folha' if count == 1 else f'{count} folhas'
|
||||||
|
|
||||||
|
|
||||||
|
def _delivery(snapshot):
|
||||||
|
"""Retirada, Envio with the carrier the card shows, junto com a roupa, or Interno."""
|
||||||
|
if snapshot.get('with_order'):
|
||||||
|
return f"Junto com pedido de roupa nº {snapshot['with_order']}"
|
||||||
|
if snapshot.get('kind') == 'interno':
|
||||||
|
return 'Interno'
|
||||||
|
if snapshot.get('destination'):
|
||||||
|
freight = snapshot.get('freight') or {}
|
||||||
|
service = freight.get('service')
|
||||||
|
return 'Envio · ' + (freight.get('description') or SERVICE_NAMES.get(service) or service or 'Frete')
|
||||||
|
return 'Retirada'
|
||||||
|
|
||||||
|
|
||||||
|
def _customer(snapshot):
|
||||||
|
customer = snapshot.get('customer') or {}
|
||||||
|
destination = snapshot.get('destination') or {}
|
||||||
|
return customer.get('name') or destination.get('recipient') or customer.get('mail') or '—'
|
||||||
|
|
||||||
|
|
||||||
|
def _finished_at(value):
|
||||||
|
if value is None:
|
||||||
|
return ''
|
||||||
|
if value.tzinfo is None:
|
||||||
|
value = value.replace(tzinfo=timezone.utc)
|
||||||
|
return value.astimezone(LOCAL).strftime('%d/%m/%Y %H:%M')
|
||||||
|
|
||||||
|
|
||||||
|
def label_fields(order, tiny_number, finished_at, revisor):
|
||||||
|
"""What the label says, from one order and its Tiny sale receipt."""
|
||||||
|
snapshot = order.get('snapshot') or {}
|
||||||
|
items = snapshot.get('items') or []
|
||||||
|
code = str(tiny_number) if tiny_number else f"DTF-{order['number']}"
|
||||||
|
return {'code': code, 'customer': _customer(snapshot), 'sheets': len(items),
|
||||||
|
'metres': _metres(items), 'delivery': _delivery(snapshot),
|
||||||
|
'finished_at': _finished_at(finished_at), 'revisor': revisor or '—',
|
||||||
|
'qr': code}
|
||||||
|
|
||||||
|
|
||||||
|
def qr_svg(text):
|
||||||
|
"""The QR as an inline SVG, dark on the label's white; segno is pure Python.
|
||||||
|
|
||||||
|
`omitsize` keeps a viewBox and drops the fixed width/height, so the CSS can
|
||||||
|
print it at the label's 30 mm without the modules staying pixel-sized.
|
||||||
|
"""
|
||||||
|
import segno
|
||||||
|
return segno.make_qr(text, error='m').svg_inline(border=1, omitsize=True)
|
||||||
|
|
||||||
|
|
||||||
|
def label_html(fields):
|
||||||
|
"""The printable page: 100 x 150 mm, black on white, no external resources."""
|
||||||
|
code = _escape(fields['code'])
|
||||||
|
# The number is as large as its length allows on the 88 mm of usable width.
|
||||||
|
code_size = 22 if len(str(fields['code'])) <= 7 else 18 if len(str(fields['code'])) <= 9 else 15
|
||||||
|
customer = _escape(fields['customer'])
|
||||||
|
sheets = _escape(_sheets(int(fields['sheets'])))
|
||||||
|
metres = _escape(fields['metres'])
|
||||||
|
delivery = _escape(fields['delivery'])
|
||||||
|
finished = _escape(fields['finished_at'])
|
||||||
|
revisor = _escape(fields['revisor'])
|
||||||
|
return f"""<!doctype html>
|
||||||
|
<html lang="pt-BR">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Etiqueta {code}</title>
|
||||||
|
<style>
|
||||||
|
@page {{ size: 100mm 150mm; margin: 0 }}
|
||||||
|
* {{ box-sizing: border-box }}
|
||||||
|
html, body {{ margin: 0; padding: 0; background: #fff; color: #000 }}
|
||||||
|
body {{ font-family: system-ui, -apple-system, "Segoe UI", Roboto, Arial, sans-serif }}
|
||||||
|
.label {{ width: 100mm; height: 150mm; padding: 6mm 6mm 5mm; display: flex;
|
||||||
|
flex-direction: column; gap: 2mm; overflow: hidden }}
|
||||||
|
.code {{ font-size: {code_size}mm; line-height: .95; font-weight: 800; letter-spacing: -.02em;
|
||||||
|
white-space: nowrap; overflow: hidden }}
|
||||||
|
.customer {{ font-size: 6mm; line-height: 1.15; font-weight: 700 }}
|
||||||
|
.line {{ font-size: 4.6mm; line-height: 1.2 }}
|
||||||
|
.foot {{ font-size: 3.6mm; line-height: 1.35; margin-top: 2mm }}
|
||||||
|
.qr {{ margin-top: auto; display: flex; justify-content: center }}
|
||||||
|
.qr svg {{ width: 30mm; height: 30mm; display: block }}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="label">
|
||||||
|
<div class="code">{code}</div>
|
||||||
|
<div class="customer">{customer}</div>
|
||||||
|
<div class="line">DTF · {sheets} · {metres} m</div>
|
||||||
|
<div class="line">{delivery}</div>
|
||||||
|
<div class="foot"><div>Finalizado em {finished}</div><div>Revisor: {revisor}</div></div>
|
||||||
|
<div class="qr">{qr_svg(fields['qr'])}</div>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
"""
|
||||||
292
app/machine_log.py
Normal file
292
app/machine_log.py
Normal file
@@ -0,0 +1,292 @@
|
|||||||
|
"""Each machine's sheet: supplies, parts, events, counters and alerts
|
||||||
|
(Fase 2, front 1, part a; the Números block per machine is part b).
|
||||||
|
|
||||||
|
The room enters what goes into a machine with one click on its card: a
|
||||||
|
supply (film roll, ink by colour, powder) with its quantity and lot cost,
|
||||||
|
a part (cap, damper, head, wiper, other) with its cost and serial, or an
|
||||||
|
event (cleaned, aligned the head, a stop with its reason and minutes). The
|
||||||
|
Kanban already knows what each machine printed; with what goes in, it knows
|
||||||
|
what it uses.
|
||||||
|
|
||||||
|
Alerts appear on the machine's computer between one file and the next,
|
||||||
|
never in the middle: when someone on that machine pulls the next card into
|
||||||
|
Imprimindo. They are marked done (which records the event) or postponed
|
||||||
|
once, which lets exactly one more card through.
|
||||||
|
|
||||||
|
clean CLEAN_EVERY_METRES printed since the last "clean" event.
|
||||||
|
align ALIGN_AFTER_FILM_METRES printed since the last film change (a
|
||||||
|
supply entry of "film") with no "align" event after it.
|
||||||
|
supply a supply whose estimated stock is at or below the machine's minimum:
|
||||||
|
the one Gestão typed, or Dropstar's default for that supply (1 roll
|
||||||
|
of film, 1 L of each ink, 5 kg of powder).
|
||||||
|
|
||||||
|
The supply estimate assumes each entry refills what was used since the one
|
||||||
|
before: the use per metre is the quantity entered over the metres printed in
|
||||||
|
that interval, averaged over the last SUPPLY_INTERVALS intervals; the stock is
|
||||||
|
the average refill minus that use times the metres printed since the last
|
||||||
|
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 for a proof card the length of each
|
||||||
|
proof sheet (film_metres).
|
||||||
|
"""
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from decimal import Decimal
|
||||||
|
|
||||||
|
CLEAN_EVERY_METRES = Decimal('10')
|
||||||
|
ALIGN_AFTER_FILM_METRES = Decimal('20')
|
||||||
|
SUPPLY_INTERVALS = 3
|
||||||
|
# item -> (Portuguese label, unit shown). Supplies are counted in rolls,
|
||||||
|
# litres and kilograms; Números shows ink per 100 m and powder in grams.
|
||||||
|
SUPPLIES = {'film': ('Filme', 'rolo'), 'ink_c': ('Tinta ciano', 'L'), 'ink_m': ('Tinta magenta', 'L'),
|
||||||
|
'ink_y': ('Tinta amarela', 'L'), 'ink_k': ('Tinta preta', 'L'), 'ink_w': ('Tinta branca', 'L'),
|
||||||
|
'powder': ('Poliamida', 'kg')}
|
||||||
|
# Dropstar's fixed minimums (2026-11-10): a machine with no minimum typed uses
|
||||||
|
# these. Units match the supplies: rolls, litres and kilograms.
|
||||||
|
DEFAULT_MINIMUMS = {'film': Decimal('1'), 'ink_c': Decimal('1'), 'ink_m': Decimal('1'),
|
||||||
|
'ink_y': Decimal('1'), 'ink_k': Decimal('1'), 'ink_w': Decimal('1'),
|
||||||
|
'powder': Decimal('5')}
|
||||||
|
PARTS = {'cap': 'Cap', 'damper': 'Damper', 'head': 'Cabeça de impressão', 'wiper': 'Wiper', 'other': 'Outra peça'}
|
||||||
|
EVENTS = {'clean': 'Limpeza', 'align': 'Alinhamento da cabeça', 'stop': 'Parada'}
|
||||||
|
|
||||||
|
# A cycle with no resetting event still needs a value the snooze row can key on.
|
||||||
|
_EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc)
|
||||||
|
|
||||||
|
|
||||||
|
def one_decimal(value):
|
||||||
|
"""One decimal place with the Brazilian comma, as the alert lines show it."""
|
||||||
|
return f'{Decimal(str(value)):.1f}'.replace('.', ',')
|
||||||
|
|
||||||
|
|
||||||
|
# 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
|
||||||
|
snapshot = snapshot or {}
|
||||||
|
proof = bool(snapshot.get('proof_of'))
|
||||||
|
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:
|
||||||
|
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:
|
||||||
|
value = item.get('billed_metres')
|
||||||
|
total += Decimal(str(value or 0))
|
||||||
|
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
|
||||||
|
ORDER BY created_at DESC, id DESC LIMIT 1''', (machine_id, kind, item)).fetchone()
|
||||||
|
|
||||||
|
|
||||||
|
def counters(c, machine_id):
|
||||||
|
"""{'clean': {'metres': Decimal, 'since': datetime|None},
|
||||||
|
'film': {'metres': Decimal, 'since': datetime|None, 'aligned': bool}}"""
|
||||||
|
clean = _last_entry(c, machine_id, 'event', 'clean')
|
||||||
|
film = _last_entry(c, machine_id, 'supply', 'film')
|
||||||
|
clean_since = clean['created_at'] if clean else None
|
||||||
|
# No cleaning on record yet: count from when the sheet started, or every
|
||||||
|
# machine would ask for one on the day this went live.
|
||||||
|
start = c.execute('SELECT log_since FROM dtf_local.machines WHERE id=%s', (machine_id,)).fetchone()
|
||||||
|
film_since = film['created_at'] if film else None
|
||||||
|
aligned = False
|
||||||
|
if film:
|
||||||
|
aligned = c.execute('''SELECT 1 FROM dtf_local.machine_entries
|
||||||
|
WHERE machine_id=%s AND kind='event' AND item='align' AND created_at>=%s LIMIT 1''',
|
||||||
|
(machine_id, film_since)).fetchone() is not None
|
||||||
|
return {'clean': {'metres': printed_since(c, machine_id, clean_since or (start or {}).get('log_since')),
|
||||||
|
'since': clean_since},
|
||||||
|
'film': {'metres': printed_since(c, machine_id, film_since or (start or {}).get('log_since')),
|
||||||
|
'since': film_since,
|
||||||
|
'aligned': aligned}}
|
||||||
|
|
||||||
|
|
||||||
|
def estimate(entries, metres_between, metres_since_last, minimum=None):
|
||||||
|
"""The supply estimate from simple lists, so it is tested without a database.
|
||||||
|
|
||||||
|
`entries` are the quantities entered, oldest first; `metres_between[i]` is
|
||||||
|
the film printed between entry i and entry i+1; `metres_since_last` is the
|
||||||
|
film printed since the last entry. None with fewer than two entries or when
|
||||||
|
no interval had film printed (nothing to divide by).
|
||||||
|
"""
|
||||||
|
quantities = [Decimal(str(value)) for value in entries]
|
||||||
|
if len(quantities) < 2:
|
||||||
|
return None
|
||||||
|
uses, refills = [], []
|
||||||
|
for quantity, metres in list(zip(quantities[1:], metres_between))[-SUPPLY_INTERVALS:]:
|
||||||
|
metres = Decimal(str(metres))
|
||||||
|
if metres <= 0:
|
||||||
|
continue
|
||||||
|
uses.append(quantity / metres)
|
||||||
|
refills.append(quantity)
|
||||||
|
if not uses:
|
||||||
|
return None
|
||||||
|
per_metre = sum(uses, Decimal(0)) / len(uses)
|
||||||
|
refill = sum(refills, Decimal(0)) / len(refills)
|
||||||
|
stock = refill - per_metre * Decimal(str(metres_since_last))
|
||||||
|
return {'per_metre': per_metre, 'stock': stock, 'metres_left': stock / per_metre,
|
||||||
|
'minimum': minimum}
|
||||||
|
|
||||||
|
|
||||||
|
def minimum_for(minimums, item):
|
||||||
|
"""The minimum typed for the machine, or Dropstar's default for that supply."""
|
||||||
|
return minimums.get(item, DEFAULT_MINIMUMS.get(item))
|
||||||
|
|
||||||
|
|
||||||
|
def supply_low(value):
|
||||||
|
"""Whether an estimate is at or below the machine's minimum (typed or default)."""
|
||||||
|
return bool(value) and value['minimum'] is not None and value['stock'] <= value['minimum']
|
||||||
|
|
||||||
|
|
||||||
|
def supply_estimates(c, machine_id):
|
||||||
|
"""{item: {'per_metre': Decimal, 'stock': Decimal, 'metres_left': Decimal,
|
||||||
|
'minimum': Decimal|None}} for the supplies with an estimate (see module doc)."""
|
||||||
|
minimums = {row['item']: row['minimum'] for row in c.execute(
|
||||||
|
'SELECT item,minimum FROM dtf_local.machine_minimums WHERE machine_id=%s', (machine_id,)).fetchall()}
|
||||||
|
result = {}
|
||||||
|
for item in SUPPLIES:
|
||||||
|
# Only the entries the estimate uses: the board asks for it on every refresh.
|
||||||
|
rows = c.execute('''SELECT quantity, created_at FROM (SELECT quantity, created_at, id
|
||||||
|
FROM dtf_local.machine_entries WHERE machine_id=%s AND kind='supply' AND item=%s
|
||||||
|
ORDER BY created_at DESC, id DESC LIMIT %s) last ORDER BY created_at, id''',
|
||||||
|
(machine_id, item, SUPPLY_INTERVALS + 1)).fetchall()
|
||||||
|
if len(rows) < 2:
|
||||||
|
continue
|
||||||
|
printed = [printed_since(c, machine_id, row['created_at']) for row in rows]
|
||||||
|
between = [printed[index - 1] - printed[index] for index in range(1, len(printed))]
|
||||||
|
value = estimate([row['quantity'] for row in rows], between, printed[-1],
|
||||||
|
minimum_for(minimums, item))
|
||||||
|
if value is not None:
|
||||||
|
result[item] = value
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def alerts(c, machine_id):
|
||||||
|
"""The alerts due on this machine now, each {'key': 'clean' | 'align' |
|
||||||
|
'supply:<item>', 'text': Portuguese line, 'cycle_from': datetime|None,
|
||||||
|
'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"
|
||||||
|
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")
|
||||||
|
"""
|
||||||
|
machine = c.execute('SELECT name FROM dtf_local.machines WHERE id=%s', (machine_id,)).fetchone()
|
||||||
|
if not machine:
|
||||||
|
return []
|
||||||
|
name = machine['name']
|
||||||
|
counts = counters(c, machine_id)
|
||||||
|
supplies = supply_estimates(c, machine_id)
|
||||||
|
result = []
|
||||||
|
|
||||||
|
def postponed(key, cycle):
|
||||||
|
return c.execute('''SELECT snoozed_at FROM dtf_local.machine_snoozes
|
||||||
|
WHERE machine_id=%s AND alert=%s AND cycle_from=%s''',
|
||||||
|
(machine_id, key, cycle or _EPOCH)).fetchone()
|
||||||
|
|
||||||
|
def pulled_since(moment):
|
||||||
|
return c.execute('''SELECT 1 FROM dtf_local.movements m
|
||||||
|
JOIN dtf_local.orders o ON o.id=m.order_id
|
||||||
|
WHERE o.machine_id=%s AND m.to_state='imp' AND NOT m.back AND m.created_at>%s LIMIT 1''',
|
||||||
|
(machine_id, moment)).fetchone() is not None
|
||||||
|
|
||||||
|
def due(key, text, cycle):
|
||||||
|
snooze = postponed(key, cycle)
|
||||||
|
blocking = not (snooze and not pulled_since(snooze['snoozed_at']))
|
||||||
|
result.append({'key': key, 'text': text, 'cycle_from': cycle,
|
||||||
|
'snoozable': snooze is None, 'blocking': blocking})
|
||||||
|
|
||||||
|
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'])
|
||||||
|
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'])
|
||||||
|
for item, value in supplies.items():
|
||||||
|
if not supply_low(value):
|
||||||
|
continue
|
||||||
|
last = _last_entry(c, machine_id, 'supply', item)
|
||||||
|
due('supply:' + item, f"{SUPPLIES[item][0].lower()} da {name} deve acabar em "
|
||||||
|
f"~{one_decimal(value['metres_left'])} m", last['created_at'] if last else None)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def _field(body, name, default=None):
|
||||||
|
return body.get(name, default) if isinstance(body, dict) else getattr(body, name, default)
|
||||||
|
|
||||||
|
|
||||||
|
def add_entry(c, machine_id, body, user, from_alert=False):
|
||||||
|
"""Record one entry. A supply without cost takes the cost of that item's
|
||||||
|
last entry on the machine. Returns the row."""
|
||||||
|
kind = _field(body, 'kind')
|
||||||
|
item = _field(body, 'item')
|
||||||
|
cost = _field(body, 'cost_cents')
|
||||||
|
if kind == 'supply' and cost is None:
|
||||||
|
last = c.execute('''SELECT cost_cents FROM dtf_local.machine_entries
|
||||||
|
WHERE machine_id=%s AND kind='supply' AND item=%s AND cost_cents IS NOT NULL
|
||||||
|
ORDER BY created_at DESC, id DESC LIMIT 1''', (machine_id, item)).fetchone()
|
||||||
|
if last:
|
||||||
|
cost = last['cost_cents']
|
||||||
|
quantity = _field(body, 'quantity') if kind == 'supply' else None
|
||||||
|
stop_minutes = _field(body, 'stop_minutes') if kind == 'event' and item == 'stop' else None
|
||||||
|
return c.execute('''INSERT INTO dtf_local.machine_entries
|
||||||
|
(machine_id,kind,item,quantity,cost_cents,serial,note,stop_minutes,from_alert,created_by)
|
||||||
|
VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) RETURNING *''',
|
||||||
|
(machine_id, kind, item, quantity, cost if kind in ('supply', 'part') else None,
|
||||||
|
_field(body, 'serial') if kind == 'part' else None, _field(body, 'note'),
|
||||||
|
stop_minutes, from_alert, user)).fetchone()
|
||||||
|
|
||||||
|
|
||||||
|
def snooze(c, machine_id, key, user):
|
||||||
|
"""Postpone an alert once per cycle; a second time in the same cycle is 409."""
|
||||||
|
from fastapi import HTTPException
|
||||||
|
current = next((alert for alert in alerts(c, machine_id) if alert['key'] == key), None)
|
||||||
|
if current is None:
|
||||||
|
raise HTTPException(409, 'Este aviso não está pendente.')
|
||||||
|
if not current['snoozable']:
|
||||||
|
raise HTTPException(409, 'Este aviso já foi adiado neste ciclo.')
|
||||||
|
row = c.execute('''INSERT INTO dtf_local.machine_snoozes(machine_id,alert,cycle_from,snoozed_by)
|
||||||
|
VALUES(%s,%s,%s,%s) ON CONFLICT (machine_id,alert,cycle_from) DO NOTHING RETURNING *''',
|
||||||
|
(machine_id, key, current['cycle_from'] or _EPOCH, user)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(409, 'Este aviso já foi adiado neste ciclo.')
|
||||||
|
return row
|
||||||
279
app/machine_stats.py
Normal file
279
app/machine_stats.py
Normal file
@@ -0,0 +1,279 @@
|
|||||||
|
"""Números per machine, month by month (Fase 2, front 1, part b).
|
||||||
|
|
||||||
|
From what the room enters on each machine's sheet (app/machine_log.py) and
|
||||||
|
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,
|
||||||
|
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
|
||||||
|
total and by reason (the note, as typed).
|
||||||
|
Consumo metres per film roll = printed / rolls entered in the month;
|
||||||
|
ink litres per 100 m, per colour = litres entered / printed * 100;
|
||||||
|
powder grams per 100 m = kg entered * 1000 / printed * 100.
|
||||||
|
Refills stand for what was used: an entry replaces what ran out.
|
||||||
|
Custo supplies per metre and parts per metre = their cost entered in
|
||||||
|
the month / printed; total per metre = the sum.
|
||||||
|
Resultado contribution = what the orders it printed in the month sold
|
||||||
|
(their items' total_cents, not freight or treatment; no proof
|
||||||
|
or test order) minus its supplies and parts of the month. Also
|
||||||
|
accumulated since installation (installed_on, else log_since).
|
||||||
|
ROI accumulated contribution / (price + parts since installation),
|
||||||
|
in %, and months to pay back = (price + parts since
|
||||||
|
installation - accumulated contribution) / the average monthly
|
||||||
|
contribution since installation (None when that average is not
|
||||||
|
positive or the price is unknown).
|
||||||
|
|
||||||
|
Every ratio is None when its divisor is zero or unknown: no number is
|
||||||
|
better than a made-up one.
|
||||||
|
"""
|
||||||
|
from datetime import datetime, time
|
||||||
|
from decimal import Decimal, ROUND_HALF_UP
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
|
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.
|
||||||
|
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
|
||||||
|
the next month) as timezone-aware datetimes at 00:00 America/Sao_Paulo.
|
||||||
|
A malformed month is ValueError."""
|
||||||
|
now = datetime.now(SAO_PAULO)
|
||||||
|
if month is None:
|
||||||
|
year, number = now.year, now.month
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
parsed = datetime.strptime(month, '%Y-%m')
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
raise ValueError('month must be YYYY-MM') from None
|
||||||
|
# strptime accepts a single digit; the board always sends two.
|
||||||
|
if month != f'{parsed.year:04d}-{parsed.month:02d}':
|
||||||
|
raise ValueError('month must be YYYY-MM')
|
||||||
|
year, number = parsed.year, parsed.month
|
||||||
|
start = datetime(year, number, 1, tzinfo=SAO_PAULO)
|
||||||
|
if number == 12:
|
||||||
|
end = datetime(year + 1, 1, 1, tzinfo=SAO_PAULO)
|
||||||
|
else:
|
||||||
|
end = datetime(year, number + 1, 1, tzinfo=SAO_PAULO)
|
||||||
|
return start, end
|
||||||
|
|
||||||
|
|
||||||
|
def ratios(printed, hours_running=None, supplies_cents=0, parts_cents=0, rolls=None,
|
||||||
|
inks=None, powder=None, price_cents=None, contribution_cents=0,
|
||||||
|
installed_parts_cents=0, months=None):
|
||||||
|
"""Every Números ratio from raw totals, so they are tested without a
|
||||||
|
database. A zero or unknown divisor gives None; cents are whole."""
|
||||||
|
printed = Decimal(str(printed or 0))
|
||||||
|
|
||||||
|
def per_metre(cents):
|
||||||
|
if printed == 0:
|
||||||
|
return None
|
||||||
|
return int((Decimal(cents) / printed).quantize(Decimal('1'), rounding=ROUND_HALF_UP))
|
||||||
|
|
||||||
|
result = {
|
||||||
|
'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
|
||||||
|
else round(float(Decimal(str(quantity)) / printed * 100), 1))
|
||||||
|
for item, quantity in (inks or {}).items()},
|
||||||
|
'powder_g_per_100m': (round(float(Decimal(str(powder)) * 1000 / printed * 100), 1)
|
||||||
|
if powder is not None and printed else None),
|
||||||
|
'supplies_per_metre_cents': per_metre(supplies_cents),
|
||||||
|
'parts_per_metre_cents': per_metre(parts_cents),
|
||||||
|
'total_per_metre_cents': per_metre(Decimal(supplies_cents) + Decimal(parts_cents)),
|
||||||
|
'roi_pct': None,
|
||||||
|
'payback_months': None,
|
||||||
|
}
|
||||||
|
# Without a price there is no investment to measure the return against.
|
||||||
|
invested = None if price_cents is None else Decimal(price_cents) + Decimal(installed_parts_cents)
|
||||||
|
if invested:
|
||||||
|
result['roi_pct'] = round(float(Decimal(contribution_cents) * 100 / invested), 1)
|
||||||
|
if price_cents is not None and months and months > 0:
|
||||||
|
average = Decimal(contribution_cents) / Decimal(str(months))
|
||||||
|
if average > 0:
|
||||||
|
result['payback_months'] = round(
|
||||||
|
float((invested - Decimal(contribution_cents)) / average), 1)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
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(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 AND {NOT_UNDONE}
|
||||||
|
AND m.created_at>=%s AND m.created_at<%s''', (machine_id, start, end)).fetchall()
|
||||||
|
|
||||||
|
|
||||||
|
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):
|
||||||
|
"""What the order's items sold; proof cards, tests and cancelled orders
|
||||||
|
are not sales (as REAL_ORDER in the board)."""
|
||||||
|
if (row['parent_id'] is not None or row['cancelled_at'] is not None
|
||||||
|
or (row['payment'] or {}).get('provider') == 'teste'):
|
||||||
|
return 0
|
||||||
|
return sum(int(item.get('total_cents') or 0)
|
||||||
|
for item in (row['snapshot'] or {}).get('items') or [])
|
||||||
|
|
||||||
|
|
||||||
|
def printed_between(c, machine_id, start, end):
|
||||||
|
"""Film metres the machine printed in [start, end), as Decimal."""
|
||||||
|
return sum((_film(row) for row in _printed_orders(c, machine_id, start, end)),
|
||||||
|
Decimal(0))
|
||||||
|
|
||||||
|
|
||||||
|
def _union_hours(spans, start, end):
|
||||||
|
"""The hours the spans (start, end) cover inside [start, end); time shared
|
||||||
|
by several orders is counted once."""
|
||||||
|
clipped = []
|
||||||
|
for at, until in spans:
|
||||||
|
first, last = max(at, start), min(until, end)
|
||||||
|
if last > first:
|
||||||
|
clipped.append((first, last))
|
||||||
|
seconds, reached = 0.0, None
|
||||||
|
for at, until in sorted(clipped):
|
||||||
|
if reached is None or at >= reached:
|
||||||
|
seconds += (until - at).total_seconds()
|
||||||
|
reached = until
|
||||||
|
elif until > reached:
|
||||||
|
seconds += (until - reached).total_seconds()
|
||||||
|
reached = until
|
||||||
|
return round(seconds / 3600, 1)
|
||||||
|
|
||||||
|
|
||||||
|
def machine_month(c, machine, start, end):
|
||||||
|
"""One machine's figures for [start, end): {'printed_metres', 'hours_running',
|
||||||
|
'metres_per_hour', 'stopped_hours', 'stops': [{'reason', 'hours'}],
|
||||||
|
'metres_per_roll', 'ink_per_100m': {item: litres}, 'powder_g_per_100m',
|
||||||
|
'supplies_cents', 'parts_cents', 'supplies_per_metre_cents',
|
||||||
|
'parts_per_metre_cents', 'total_per_metre_cents', 'sold_cents',
|
||||||
|
'contribution_cents'}. `machine` is its row from dtf_local.machines."""
|
||||||
|
mid = machine['id']
|
||||||
|
rows = _printed_orders(c, mid, start, end)
|
||||||
|
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 (
|
||||||
|
SELECT m.order_id AS id, m.to_state AS state, m.created_at AS at FROM dtf_local.movements m
|
||||||
|
WHERE m.order_id=ANY(%s)),
|
||||||
|
spans AS (SELECT id, state, at, LEAD(at) OVER (PARTITION BY id ORDER BY at) AS until FROM events)
|
||||||
|
SELECT at, until FROM spans WHERE state='imp' AND until IS NOT NULL''',
|
||||||
|
(ids,)).fetchall() if ids else []
|
||||||
|
hours = _union_hours([(row['at'], row['until']) for row in spans], start, end)
|
||||||
|
|
||||||
|
supplies = c.execute('''SELECT item, COALESCE(sum(quantity),0) AS quantity,
|
||||||
|
COALESCE(sum(cost_cents),0) AS cents FROM dtf_local.machine_entries
|
||||||
|
WHERE machine_id=%s AND kind='supply' AND created_at>=%s AND created_at<%s
|
||||||
|
GROUP BY item''', (mid, start, end)).fetchall()
|
||||||
|
quantities = {row['item']: row['quantity'] for row in supplies}
|
||||||
|
supplies_cents = int(sum((row['cents'] for row in supplies), 0))
|
||||||
|
parts_cents = int(c.execute('''SELECT COALESCE(sum(cost_cents),0) AS cents
|
||||||
|
FROM dtf_local.machine_entries WHERE machine_id=%s AND kind='part'
|
||||||
|
AND created_at>=%s AND created_at<%s''', (mid, start, end)).fetchone()['cents'])
|
||||||
|
stops = c.execute('''SELECT note, COALESCE(sum(stop_minutes),0) AS minutes
|
||||||
|
FROM dtf_local.machine_entries WHERE machine_id=%s AND kind='event' AND item='stop'
|
||||||
|
AND created_at>=%s AND created_at<%s GROUP BY note ORDER BY minutes DESC, note''',
|
||||||
|
(mid, start, end)).fetchall()
|
||||||
|
stop_list = [{'reason': row['note'] or '', 'hours': round(float(row['minutes']) / 60, 1)}
|
||||||
|
for row in stops if row['minutes']]
|
||||||
|
stopped = round(sum(float(row['minutes']) for row in stops) / 60, 1)
|
||||||
|
values = ratios(printed, hours_running=hours, supplies_cents=supplies_cents,
|
||||||
|
parts_cents=parts_cents, rolls=quantities.get('film'),
|
||||||
|
inks={item: quantities.get(item) for item in INK_ITEMS},
|
||||||
|
powder=quantities.get('powder'))
|
||||||
|
return {
|
||||||
|
'printed_metres': round(float(printed), 2),
|
||||||
|
'hours_running': hours,
|
||||||
|
'metres_per_hour': values['metres_per_hour'],
|
||||||
|
'stopped_hours': stopped,
|
||||||
|
'stops': stop_list,
|
||||||
|
'metres_per_roll': values['metres_per_roll'],
|
||||||
|
'ink_per_100m': values['ink_per_100m'],
|
||||||
|
'powder_g_per_100m': values['powder_g_per_100m'],
|
||||||
|
'supplies_cents': supplies_cents,
|
||||||
|
'parts_cents': parts_cents,
|
||||||
|
'supplies_per_metre_cents': values['supplies_per_metre_cents'],
|
||||||
|
'parts_per_metre_cents': values['parts_per_metre_cents'],
|
||||||
|
'total_per_metre_cents': values['total_per_metre_cents'],
|
||||||
|
'sold_cents': sold,
|
||||||
|
'contribution_cents': sold - supplies_cents - parts_cents,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def since_installation(c, machine, until):
|
||||||
|
"""{'from': date, 'contribution_cents', 'parts_cents', 'months': float,
|
||||||
|
'roi_pct': float|None, 'payback_months': float|None} from installed_on
|
||||||
|
(else log_since) to `until`."""
|
||||||
|
mid = machine['id']
|
||||||
|
if machine['installed_on'] is not None:
|
||||||
|
from_date = machine['installed_on']
|
||||||
|
start = datetime.combine(from_date, time.min, tzinfo=SAO_PAULO)
|
||||||
|
else:
|
||||||
|
start = machine['log_since'] or datetime.now(SAO_PAULO)
|
||||||
|
from_date = start.astimezone(SAO_PAULO).date()
|
||||||
|
sold = sum((_sold(row) for row in _printed_orders(c, mid, start, until)), 0)
|
||||||
|
cents = lambda kind: int(c.execute('''SELECT COALESCE(sum(cost_cents),0) AS cents
|
||||||
|
FROM dtf_local.machine_entries WHERE machine_id=%s AND kind=%s
|
||||||
|
AND created_at>=%s AND created_at<%s''', (mid, kind, start, until)).fetchone()['cents'])
|
||||||
|
supplies_cents, parts_cents = cents('supply'), cents('part')
|
||||||
|
contribution = sold - supplies_cents - parts_cents
|
||||||
|
seconds = (until - start).total_seconds()
|
||||||
|
months = round(float(Decimal(str(seconds)) / _MONTH_SECONDS), 1) if seconds > 0 else 0.0
|
||||||
|
values = ratios(0, price_cents=machine['price_cents'], contribution_cents=contribution,
|
||||||
|
installed_parts_cents=parts_cents, months=months)
|
||||||
|
return {'from': from_date, 'contribution_cents': contribution, 'parts_cents': parts_cents,
|
||||||
|
'months': months, 'roi_pct': values['roi_pct'],
|
||||||
|
'payback_months': values['payback_months']}
|
||||||
|
|
||||||
|
|
||||||
|
def report(c, month=None):
|
||||||
|
"""{'month': '2026-11', 'machines': [{'id', 'name', 'price_cents',
|
||||||
|
'installed_on', 'month': machine_month(...), 'total': since_installation(...)}]}
|
||||||
|
for every machine (active or not) that has entries or printed in the month,
|
||||||
|
plus every active one."""
|
||||||
|
start, end = month_bounds(month)
|
||||||
|
until = min(datetime.now(SAO_PAULO), end)
|
||||||
|
machines = c.execute('''SELECT id, name, price_cents, installed_on, log_since, active
|
||||||
|
FROM dtf_local.machines ORDER BY created_at, name''').fetchall()
|
||||||
|
entered = {str(row['machine_id']) for row in c.execute(
|
||||||
|
'''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(
|
||||||
|
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 AND {NOT_UNDONE}
|
||||||
|
AND m.created_at>=%s AND m.created_at<%s''', (start, end)).fetchall()}
|
||||||
|
result = []
|
||||||
|
for machine in machines:
|
||||||
|
key = str(machine['id'])
|
||||||
|
if not (machine['active'] or key in entered or key in printed):
|
||||||
|
continue
|
||||||
|
result.append({'id': key, 'name': machine['name'], 'price_cents': machine['price_cents'],
|
||||||
|
'installed_on': machine['installed_on'],
|
||||||
|
'month': machine_month(c, machine, start, end),
|
||||||
|
'total': since_installation(c, machine, until)})
|
||||||
|
return {'month': start.strftime('%Y-%m'), 'machines': result}
|
||||||
@@ -1,24 +1,17 @@
|
|||||||
"""The print machines: which one each order goes to, and how loaded each is.
|
"""The print machines, their load and the printing places on each one."""
|
||||||
|
|
||||||
An order gets its machine once, and keeps it: someone's choice in the order
|
|
||||||
panel, or else the active machine that prints its product with the fewest
|
|
||||||
metres still open, among those below their limit (or, all of them full, the
|
|
||||||
least loaded anyway; the machine then shows it is over its limit). A machine
|
|
||||||
switched off, deleted or no longer printing the product gives its automatic
|
|
||||||
orders back to that choice, unless they are already printing.
|
|
||||||
"""
|
|
||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
|
|
||||||
|
from . import machine_log
|
||||||
|
|
||||||
# Not finished: the work still ahead of a machine.
|
# Not finished: the work still ahead of a machine.
|
||||||
OPEN = ('rec', 'tra', 'imp', 'cor')
|
OPEN = ('rec', 'tra', 'imp', 'cor')
|
||||||
# Stages an automatic order may still move from: not once it is printing.
|
# Orders at most in Imprimindo per machine, and files in its hot folder at
|
||||||
MOVABLE = ('rec', 'tra', 'cor')
|
# once: dtf_local.machines.places, set per machine by Admin and Gestão
|
||||||
# One routing at a time, so two at once cannot both pick the same "least loaded".
|
# (Marcus, 2026-11-17). It was two for all (Dropstar, 2026-10-29): one
|
||||||
LOCK = 7_041_901
|
# printing, the next ripped by FlexiPRINT meanwhile; three keeps one more
|
||||||
# Two orders at most in Imprimindo per machine (Dropstar, 2026-10-29): one
|
# waiting in the folder. A new machine starts with DEFAULT_PLACES.
|
||||||
# printing, the next being ripped by FlexiPRINT meanwhile. A third would
|
DEFAULT_PLACES = 3
|
||||||
# make the RIP choke; two mean the next sheet is ready when one ends.
|
MAX_PLACES = 6
|
||||||
PRINTING_CAP = 2
|
|
||||||
|
|
||||||
|
|
||||||
def product_family(order):
|
def product_family(order):
|
||||||
@@ -44,52 +37,10 @@ def loads(c):
|
|||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
def pick(machines, load, order):
|
|
||||||
"""The machine for one order, or None when none prints its product."""
|
|
||||||
family, metres = product_family(order), order_metres(order)
|
|
||||||
able = [m for m in machines if m['active'] and family in m['products']]
|
|
||||||
if not able:
|
|
||||||
return None
|
|
||||||
used = lambda m: load.get(str(m['id']), Decimal(0))
|
|
||||||
room = [m for m in able if m['limit_metres'] is None or used(m) + metres <= m['limit_metres']]
|
|
||||||
# min() keeps the first of equals: the machine registered first.
|
|
||||||
return min(room or able, key=used)
|
|
||||||
|
|
||||||
|
|
||||||
def route(c):
|
|
||||||
"""Give every open order without a machine its automatic one."""
|
|
||||||
# A choice whose machine was deleted is no choice any more.
|
|
||||||
c.execute('UPDATE dtf_local.orders SET machine_chosen=false WHERE machine_id IS NULL AND machine_chosen')
|
|
||||||
# Automatic orders on a machine that can no longer take them, before printing.
|
|
||||||
c.execute('''UPDATE dtf_local.orders o SET machine_id=NULL FROM dtf_local.machines m
|
|
||||||
WHERE o.machine_id=m.id AND NOT o.machine_chosen AND o.state=ANY(%s) AND o.cancelled_at IS NULL
|
|
||||||
AND (NOT m.active OR NOT ((CASE WHEN o.snapshot->'items'->0->>'mode' IN ('uv','uvfile')
|
|
||||||
THEN 'uv' ELSE 'textil' END)=ANY(m.products)))''', (list(MOVABLE),))
|
|
||||||
waiting = c.execute('''SELECT id, snapshot FROM dtf_local.orders
|
|
||||||
WHERE machine_id IS NULL AND cancelled_at IS NULL AND state=ANY(%s)
|
|
||||||
ORDER BY created_at, number''', (list(OPEN),)).fetchall()
|
|
||||||
if not waiting:
|
|
||||||
return 0
|
|
||||||
c.execute('SELECT pg_advisory_xact_lock(%s)', (LOCK,))
|
|
||||||
machines = c.execute('''SELECT id, products, active, limit_metres FROM dtf_local.machines
|
|
||||||
ORDER BY created_at, name''').fetchall()
|
|
||||||
load = {k: v['metres'] for k, v in loads(c).items()}
|
|
||||||
routed = 0
|
|
||||||
for order in waiting:
|
|
||||||
machine = pick(machines, load, order)
|
|
||||||
if machine is None:
|
|
||||||
continue
|
|
||||||
if c.execute('''UPDATE dtf_local.orders SET machine_id=%s, machine_chosen=false
|
|
||||||
WHERE id=%s AND machine_id IS NULL RETURNING id''', (machine['id'], order['id'])).fetchone():
|
|
||||||
key = str(machine['id'])
|
|
||||||
load[key] = load.get(key, Decimal(0)) + order_metres(order)
|
|
||||||
routed += 1
|
|
||||||
return routed
|
|
||||||
|
|
||||||
|
|
||||||
def rows(c, with_operators=False):
|
def rows(c, with_operators=False):
|
||||||
"""Every machine with its load, for the Kanban."""
|
"""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()
|
ORDER BY created_at, name''').fetchall()
|
||||||
load = loads(c)
|
load = loads(c)
|
||||||
operators = {}
|
operators = {}
|
||||||
@@ -105,9 +56,11 @@ def rows(c, with_operators=False):
|
|||||||
for m in machines:
|
for m in machines:
|
||||||
key = str(m['id'])
|
key = str(m['id'])
|
||||||
used = load.get(key, {'metres': Decimal(0), 'orders': 0, 'states': {}})
|
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,
|
'limit_metres': float(m['limit_metres']) if m['limit_metres'] is not None else None,
|
||||||
'open_metres': float(used['metres']), 'open_orders': used['orders'], 'states': used['states']}
|
'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:
|
if with_operators:
|
||||||
row['operators'] = operators.get(key, [])
|
row['operators'] = operators.get(key, [])
|
||||||
result.append(row)
|
result.append(row)
|
||||||
@@ -115,22 +68,23 @@ def rows(c, with_operators=False):
|
|||||||
|
|
||||||
|
|
||||||
def full(c, machine_id, order_id):
|
def full(c, machine_id, order_id):
|
||||||
"""The machine's name when it already has PRINTING_CAP other orders in
|
"""(name, places) when the machine already has its places' worth of
|
||||||
Imprimindo, so this one cannot join them; None when it has room. The
|
other orders in Imprimindo, so this one cannot join them; None when it
|
||||||
machine's row is locked, so two pulls at once cannot both take the last
|
has room. The machine's row is locked, so two pulls at once cannot both
|
||||||
place."""
|
take the last place."""
|
||||||
if machine_id is None:
|
if machine_id is None:
|
||||||
return 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'
|
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']
|
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):
|
def printing_slots(c):
|
||||||
"""Per order in Imprimindo: 'imprimindo' for the first to enter it on its
|
"""Per order in Imprimindo: 'imprimindo' for the first to enter it on its
|
||||||
machine (ripped, running), 'ripando' for the one after it."""
|
machine (ripped, running), 'ripando' for the one after it, 'aguardando'
|
||||||
return {row['id']: 'imprimindo' if row['place'] == 1 else 'ripando' for row in c.execute('''
|
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
|
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
|
FROM dtf_local.orders o, LATERAL (SELECT max(created_at) AS at FROM dtf_local.movements
|
||||||
WHERE order_id=o.id AND to_state='imp') m
|
WHERE order_id=o.id AND to_state='imp') m
|
||||||
|
|||||||
38
app/mail.py
38
app/mail.py
@@ -23,6 +23,8 @@ import ssl
|
|||||||
from email.message import EmailMessage
|
from email.message import EmailMessage
|
||||||
from email.utils import formataddr, formatdate, make_msgid, parseaddr
|
from email.utils import formataddr, formatdate, make_msgid, parseaddr
|
||||||
|
|
||||||
|
from .core.pricing import sheet_label
|
||||||
|
|
||||||
ADAPTER = os.environ.get('MAIL_ADAPTER', 'off')
|
ADAPTER = os.environ.get('MAIL_ADAPTER', 'off')
|
||||||
RESET_MINUTES = 60
|
RESET_MINUTES = 60
|
||||||
CODE_MINUTES = 15
|
CODE_MINUTES = 15
|
||||||
@@ -70,11 +72,15 @@ def order_paid(c, order, origin):
|
|||||||
delivery = freight.get('description') or 'Entrega'
|
delivery = freight.get('description') or 'Entrega'
|
||||||
if freight.get('days'):
|
if freight.get('days'):
|
||||||
delivery += f" · até {freight['days']} dias úteis"
|
delivery += f" · até {freight['days']} dias úteis"
|
||||||
rows = [('Itens', '\n'.join(f"{PRODUCTS.get(i.get('mode'), i.get('mode'))} · "
|
rows = [('Itens', '\n'.join(f"{PRODUCTS.get(i.get('mode'), i.get('mode'))}{sheet_label(i)} · "
|
||||||
f"{str(i.get('billed_metres') or i.get('metres')).replace('.', ',')} m"
|
f"{str(i.get('billed_metres') or i.get('metres')).replace('.', ',')} m"
|
||||||
for i in snapshot.get('items', []))),
|
for i in snapshot.get('items', []))),
|
||||||
('Entrega', delivery),
|
('Entrega', delivery)]
|
||||||
('Total', money(snapshot.get('total_cents') or 0) + (f' · {paid}' if paid else ''))]
|
coupon = snapshot.get('coupon') or {}
|
||||||
|
if coupon:
|
||||||
|
rows.append((f"Cupom {coupon.get('code', '')}",
|
||||||
|
f"− {money(coupon.get('discount_cents') or 0)}"))
|
||||||
|
rows.append(('Total', money(snapshot.get('total_cents') or 0) + (f' · {paid}' if paid else '')))
|
||||||
number, link = order['number'], f"{origin}/conta/pedidos?order={order['id']}"
|
number, link = order['number'], f"{origin}/conta/pedidos?order={order['id']}"
|
||||||
text = '\n'.join([mail_html.greeting(customer.get('name')), '',
|
text = '\n'.join([mail_html.greeting(customer.get('name')), '',
|
||||||
f'Seu pagamento foi aprovado e o pedido #{number} já está com a nossa equipe. '
|
f'Seu pagamento foi aprovado e o pedido #{number} já está com a nossa equipe. '
|
||||||
@@ -87,7 +93,31 @@ def order_paid(c, order, origin):
|
|||||||
|
|
||||||
|
|
||||||
PRODUCTS = {'file': 'DTF Têxtil · folha montada', 'avulsa': 'DTF Têxtil · artes avulsas',
|
PRODUCTS = {'file': 'DTF Têxtil · folha montada', 'avulsa': 'DTF Têxtil · artes avulsas',
|
||||||
'uvfile': 'DTF UV · folha montada', 'uv': 'DTF UV · artes avulsas'}
|
'uvfile': 'DTF UV · folha montada', 'uv': 'DTF UV · artes avulsas',
|
||||||
|
'premium': 'DTF Têxtil Premium · folha montada'}
|
||||||
|
|
||||||
|
|
||||||
|
def quote_expired(c, quote, origin):
|
||||||
|
"""The customer's notice that an approved, unpaid order expired after 24 h
|
||||||
|
(Fase 2, front 9): its files were deleted and they can send it again on
|
||||||
|
the Site. Returns whether it was queued (False without an e-mail)."""
|
||||||
|
customer = (quote.get('draft') or {}).get('customer') or {}
|
||||||
|
if not customer.get('mail'):
|
||||||
|
return False
|
||||||
|
from . import mail_html
|
||||||
|
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}'])
|
||||||
|
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}'),
|
||||||
|
])
|
||||||
|
return queue(c, 'notice', customer['mail'], 'Seu pedido expirou · DTF Dropstar', text, html)
|
||||||
|
|
||||||
|
|
||||||
def money(cents):
|
def money(cents):
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ from typing import Mapping
|
|||||||
import httpx
|
import httpx
|
||||||
|
|
||||||
from .adapters import PaymentEvent
|
from .adapters import PaymentEvent
|
||||||
|
from .core.models import cnpj_ok, cpf_ok
|
||||||
|
|
||||||
API = 'https://api.mercadopago.com'
|
API = 'https://api.mercadopago.com'
|
||||||
# How old a signed timestamp may be. Mercado Pago retries a failed delivery
|
# 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))
|
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:
|
class MercadoPagoPayment:
|
||||||
name = 'mercadopago'
|
name = 'mercadopago'
|
||||||
|
|
||||||
@@ -76,9 +100,10 @@ class MercadoPagoPayment:
|
|||||||
body = {'transaction_amount': float(Decimal(total_cents) / 100),
|
body = {'transaction_amount': float(Decimal(total_cents) / 100),
|
||||||
'description': f'DTF - cotação {quote_id[:8]}',
|
'description': f'DTF - cotação {quote_id[:8]}',
|
||||||
'external_reference': quote_id,
|
'external_reference': quote_id,
|
||||||
'payer': {'email': customer['mail'],
|
'payer': payer(customer, method if method['type'] == 'card' else None),
|
||||||
'identification': {'type': 'CPF' if len(customer['cnpj']) == 11 else 'CNPJ',
|
# The order's own document, kept on the payment for finance
|
||||||
'number': customer['cnpj']}}}
|
# even when the card's holder is someone else.
|
||||||
|
'metadata': {'documento_pedido': customer['cnpj']}}
|
||||||
if self.notification_url:
|
if self.notification_url:
|
||||||
body['notification_url'] = self.notification_url
|
body['notification_url'] = self.notification_url
|
||||||
expires_at = None
|
expires_at = None
|
||||||
@@ -93,9 +118,6 @@ class MercadoPagoPayment:
|
|||||||
# it; asking it of every card was refused as a rule (10113).
|
# it; asking it of every card was refused as a rule (10113).
|
||||||
if method['payment_method_id'].startswith('deb'):
|
if method['payment_method_id'].startswith('deb'):
|
||||||
body['three_d_secure_mode'] = 'optional'
|
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.
|
# No issuer_id: Mercado Pago takes the issuer from the card number.
|
||||||
# The form's suggestion was refused for its own test cards
|
# The form's suggestion was refused for its own test cards
|
||||||
# (10111, "the issuer does not have the BIN configured").
|
# (10111, "the issuer does not have the BIN configured").
|
||||||
|
|||||||
34
app/migrate.py
Normal file
34
app/migrate.py
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
"""Timestamped schema migrations, applied once by the database initializer.
|
||||||
|
|
||||||
|
schema.sql is the frozen baseline and runs on every start; a change after it is
|
||||||
|
a file in app/migrations/, named YYYYMMDDHHMM_slug.sql. The name is the
|
||||||
|
migration's identity and is recorded in dtf_local.migrations, so a deploy never
|
||||||
|
applies one twice and an older image skips names it does not know.
|
||||||
|
"""
|
||||||
|
import re
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
MIGRATIONS = Path(__file__).resolve().with_name('migrations')
|
||||||
|
LOCK = 804209
|
||||||
|
NAME = re.compile(r'\d{12}_[a-z0-9-]+\.sql')
|
||||||
|
|
||||||
|
|
||||||
|
def apply(c, directory=MIGRATIONS) -> list[str]:
|
||||||
|
"""Run, in name order, every migration file not yet recorded in
|
||||||
|
dtf_local.migrations, each recorded in the same transaction. A name in
|
||||||
|
the table that has no file (written by a newer image) is ignored, so an
|
||||||
|
older image still starts."""
|
||||||
|
c.execute('SELECT pg_advisory_xact_lock(%s)', (LOCK,))
|
||||||
|
files = {}
|
||||||
|
for path in Path(directory).iterdir():
|
||||||
|
if not path.is_file() or not NAME.fullmatch(path.name):
|
||||||
|
raise ValueError(f'Unexpected file in {directory}: {path.name}')
|
||||||
|
files[path.name] = path
|
||||||
|
applied = []
|
||||||
|
for name in sorted(files):
|
||||||
|
if c.execute('SELECT 1 FROM dtf_local.migrations WHERE name=%s', (name,)).fetchone():
|
||||||
|
continue
|
||||||
|
c.execute(files[name].read_text())
|
||||||
|
c.execute('INSERT INTO dtf_local.migrations(name) VALUES(%s)', (name,))
|
||||||
|
applied.append(name)
|
||||||
|
return applied
|
||||||
14
app/migrations/202611091607_checks-current-lists.sql
Normal file
14
app/migrations/202611091607_checks-current-lists.sql
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
-- The current lists of the three CHECK constraints whose values have grown
|
||||||
|
-- over time, applied once to every database, including one whose copy is older
|
||||||
|
-- (an image before front 7a lacks 'expedicao', for example). From now on,
|
||||||
|
-- widening a list is a new migration that drops and adds that one constraint.
|
||||||
|
ALTER TABLE dtf_local.operators DROP CONSTRAINT IF EXISTS operators_role;
|
||||||
|
ALTER TABLE dtf_local.operators ADD CONSTRAINT operators_role
|
||||||
|
CHECK (role IN ('superadmin','admin','gestao','designer','operador','revisor','vendedor','financeiro','expedicao'));
|
||||||
|
|
||||||
|
ALTER TABLE dtf_local.mail_queue DROP CONSTRAINT IF EXISTS mail_queue_kind_check;
|
||||||
|
ALTER TABLE dtf_local.mail_queue ADD CONSTRAINT mail_queue_kind_check
|
||||||
|
CHECK(kind IN ('reset','code','account','notice','order','alert','test'));
|
||||||
|
|
||||||
|
ALTER TABLE dtf_local.orders DROP CONSTRAINT IF EXISTS orders_origin_check;
|
||||||
|
ALTER TABLE dtf_local.orders ADD CONSTRAINT orders_origin_check CHECK (origin IN ('site','dropflow','atendimento'));
|
||||||
7
app/migrations/202611092000_grade-rules.sql
Normal file
7
app/migrations/202611092000_grade-rules.sql
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
-- Front 8.5: what the art grade decides, set in the Kanban's Site tab. No row
|
||||||
|
-- means no rule, and nothing changes; each action has at most one threshold.
|
||||||
|
CREATE TABLE IF NOT EXISTS dtf_local.grade_rules (
|
||||||
|
action text PRIMARY KEY CHECK (action IN ('aviso','tratamento')),
|
||||||
|
below integer NOT NULL CHECK (below BETWEEN 1 AND 100),
|
||||||
|
updated_by text NOT NULL, updated_at timestamptz NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
4
app/migrations/202611101200_upload-pdf-dpi.sql
Normal file
4
app/migrations/202611101200_upload-pdf-dpi.sql
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
-- The PDF's resolution, worked out at the scan (Critical Corrections 2): pdf_checked
|
||||||
|
-- false = not worked out yet (checkout reads as before), NULL pdf_dpi with it true = unreadable.
|
||||||
|
ALTER TABLE dtf_local.uploads ADD COLUMN IF NOT EXISTS pdf_checked boolean NOT NULL DEFAULT false;
|
||||||
|
ALTER TABLE dtf_local.uploads ADD COLUMN IF NOT EXISTS pdf_dpi integer;
|
||||||
24
app/migrations/202611111200_montador-interno-stamps.sql
Normal file
24
app/migrations/202611111200_montador-interno-stamps.sql
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
-- Front 7a.3: a brand per stamp, for the future catalogue, and the montador's
|
||||||
|
-- fixed internal customer. The brand is only recorded here for now; nothing
|
||||||
|
-- else reads it yet (Marcus, 2026-11-10).
|
||||||
|
CREATE TABLE IF NOT EXISTS dtf_local.stamps (
|
||||||
|
code text PRIMARY KEY CHECK (code ~ '^[A-Za-z0-9_-]{1,40}$'),
|
||||||
|
brand text NOT NULL DEFAULT '',
|
||||||
|
public boolean NOT NULL DEFAULT false,
|
||||||
|
updated_by text NOT NULL,
|
||||||
|
updated_at timestamptz NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
-- The one customer every Interno order belongs to (the marketplace's own
|
||||||
|
-- sales). Gestão completes it; until then an Interno order is refused.
|
||||||
|
CREATE TABLE IF NOT EXISTS dtf_local.internal_customer (
|
||||||
|
id integer PRIMARY KEY DEFAULT 1 CHECK (id=1),
|
||||||
|
name text NOT NULL DEFAULT '',
|
||||||
|
cnpj text NOT NULL DEFAULT '',
|
||||||
|
zap text NOT NULL DEFAULT '',
|
||||||
|
mail text NOT NULL DEFAULT '',
|
||||||
|
updated_by text NOT NULL DEFAULT 'sistema',
|
||||||
|
updated_at timestamptz NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
INSERT INTO dtf_local.internal_customer(id,name) VALUES(1,'Nexstar · Marketplace')
|
||||||
|
ON CONFLICT (id) DO NOTHING;
|
||||||
17
app/migrations/202611111200_premium-product.sql
Normal file
17
app/migrations/202611111200_premium-product.sql
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
-- Front 3: the Premium product (Marcus, 2026-11-10), built and switched OFF
|
||||||
|
-- until Dropstar prints the three test sheets and says "testado". The products
|
||||||
|
-- CHECK is the inline constraint of dtf_local.products.id, which Postgres
|
||||||
|
-- named products_id_check; widening a list is a new migration that drops and
|
||||||
|
-- adds that one constraint (never schema.sql).
|
||||||
|
ALTER TABLE dtf_local.products DROP CONSTRAINT IF EXISTS products_id_check;
|
||||||
|
ALTER TABLE dtf_local.products ADD CONSTRAINT products_id_check
|
||||||
|
CHECK (id IN ('file','avulsa','uvfile','uv','premium','tratamento'));
|
||||||
|
|
||||||
|
INSERT INTO dtf_local.products(id, enabled) VALUES ('premium', false)
|
||||||
|
ON CONFLICT (id) DO NOTHING;
|
||||||
|
|
||||||
|
-- A coupon may also target the new product (the Site tab lists every mode).
|
||||||
|
ALTER TABLE dtf_local.coupons DROP CONSTRAINT IF EXISTS coupons_product_check;
|
||||||
|
ALTER TABLE dtf_local.coupons ADD CONSTRAINT coupons_product_check
|
||||||
|
CHECK (product IN ('file','avulsa','uvfile','uv','premium'));
|
||||||
|
|
||||||
12
app/migrations/202611111530_label-prints.sql
Normal file
12
app/migrations/202611111530_label-prints.sql
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
-- Front 10: the 10x15 cm label at Finalizado (Marcus, 2026-11-10). One 'auto'
|
||||||
|
-- print per order, decided by the unique partial index, so two computers
|
||||||
|
-- asking at once cannot both print it; a reprint is always another row.
|
||||||
|
CREATE TABLE IF NOT EXISTS dtf_local.label_prints (
|
||||||
|
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||||
|
order_id uuid NOT NULL REFERENCES dtf_local.orders(id) ON DELETE CASCADE,
|
||||||
|
reason text NOT NULL CHECK (reason IN ('auto','reprint')),
|
||||||
|
printed_by text NOT NULL,
|
||||||
|
printed_at timestamptz NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS label_prints_one_auto
|
||||||
|
ON dtf_local.label_prints(order_id) WHERE reason='auto';
|
||||||
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;
|
||||||
146
app/observability.py
Normal file
146
app/observability.py
Normal file
@@ -0,0 +1,146 @@
|
|||||||
|
"""Sentry for the API and the worker, off until a DSN arrives (note Sentry).
|
||||||
|
|
||||||
|
`init(component)` reads `SENTRY_DSN_API` and returns without importing the SDK
|
||||||
|
when it is empty, so local and CI runs carry no Sentry dependency or network
|
||||||
|
cost. When it is set, `scrub` keeps cookies, credentials, request bodies and
|
||||||
|
Brazilian personal data out of the events (LGPD).
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
|
||||||
|
|
||||||
|
EMAIL = re.compile(r'[^\s@]+@[^\s@]+\.[A-Za-z]{2,}')
|
||||||
|
# CPF (11 digits) or CNPJ (14), with or without punctuation.
|
||||||
|
DOCUMENT = re.compile(r'(?<!\d)(?:\d{2}\.?\d{3}\.?\d{3}/?\d{4}-?\d{2}'
|
||||||
|
r'|\d{3}\.?\d{3}\.?\d{3}-?\d{2})(?!\d)')
|
||||||
|
SENSITIVE_PARAM = re.compile(r'token|signature|x-amz', re.I)
|
||||||
|
SENSITIVE_HEADER = re.compile(r'^(cookie|authorization|x-.*token.*)$', re.I)
|
||||||
|
REDACTED = '[removido]'
|
||||||
|
|
||||||
|
|
||||||
|
def _clean(text):
|
||||||
|
"""Replace e-mail addresses and CPF/CNPJ in one string."""
|
||||||
|
if not isinstance(text, str):
|
||||||
|
return text
|
||||||
|
return DOCUMENT.sub(REDACTED, EMAIL.sub(REDACTED, text))
|
||||||
|
|
||||||
|
|
||||||
|
def _scrub_query(query):
|
||||||
|
"""A query string without token, signature and X-Amz parameters."""
|
||||||
|
if not isinstance(query, str) or not query:
|
||||||
|
return query
|
||||||
|
pairs = parse_qsl(query, keep_blank_values=True)
|
||||||
|
kept = [(key, value) for key, value in pairs if not SENSITIVE_PARAM.search(key)]
|
||||||
|
return query if len(kept) == len(pairs) else urlencode(kept, doseq=True)
|
||||||
|
|
||||||
|
|
||||||
|
def _scrub_url(url):
|
||||||
|
if not isinstance(url, str):
|
||||||
|
return url
|
||||||
|
parts = urlsplit(url)
|
||||||
|
if not parts.query:
|
||||||
|
return url
|
||||||
|
return urlunsplit(parts._replace(query=_scrub_query(parts.query)))
|
||||||
|
|
||||||
|
|
||||||
|
def _scrub_text(value):
|
||||||
|
"""Personal data and a URL query string inside a message or crumb."""
|
||||||
|
value = _clean(value)
|
||||||
|
if not isinstance(value, str) or '?' not in value:
|
||||||
|
return value
|
||||||
|
head, _, query = value.partition('?')
|
||||||
|
return head + '?' + _scrub_query(query)
|
||||||
|
|
||||||
|
|
||||||
|
def _scrub_value(value):
|
||||||
|
if isinstance(value, str):
|
||||||
|
return _scrub_text(value)
|
||||||
|
if isinstance(value, list):
|
||||||
|
return [_scrub_value(item) for item in value]
|
||||||
|
if isinstance(value, dict):
|
||||||
|
return {key: _scrub_value(item) for key, item in value.items()}
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def _scrub_request(request):
|
||||||
|
"""Cookies, credentials, query tokens and bodies never leave the server."""
|
||||||
|
if not isinstance(request, dict):
|
||||||
|
return
|
||||||
|
request.pop('cookies', None)
|
||||||
|
request.pop('data', None)
|
||||||
|
request.pop('body', None)
|
||||||
|
headers = request.get('headers')
|
||||||
|
if isinstance(headers, dict):
|
||||||
|
request['headers'] = {key: value for key, value in headers.items()
|
||||||
|
if not SENSITIVE_HEADER.match(str(key))}
|
||||||
|
if 'query_string' in request:
|
||||||
|
request['query_string'] = _scrub_query(request['query_string'])
|
||||||
|
if 'url' in request:
|
||||||
|
request['url'] = _scrub_url(request['url'])
|
||||||
|
|
||||||
|
|
||||||
|
def scrub(event, hint=None):
|
||||||
|
"""before_send: strip credentials, bodies and personal data from an event."""
|
||||||
|
if not isinstance(event, dict):
|
||||||
|
return event
|
||||||
|
_scrub_request(event.get('request'))
|
||||||
|
if 'message' in event:
|
||||||
|
event['message'] = _scrub_text(event['message'])
|
||||||
|
logentry = event.get('logentry')
|
||||||
|
if isinstance(logentry, dict) and 'message' in logentry:
|
||||||
|
logentry['message'] = _scrub_text(logentry['message'])
|
||||||
|
exception = event.get('exception')
|
||||||
|
if isinstance(exception, dict):
|
||||||
|
for value in exception.get('values') or []:
|
||||||
|
if isinstance(value, dict) and 'value' in value:
|
||||||
|
value['value'] = _scrub_text(value['value'])
|
||||||
|
breadcrumbs = event.get('breadcrumbs')
|
||||||
|
if isinstance(breadcrumbs, dict):
|
||||||
|
breadcrumbs = breadcrumbs.get('values') or []
|
||||||
|
if isinstance(breadcrumbs, list):
|
||||||
|
for crumb in breadcrumbs:
|
||||||
|
if not isinstance(crumb, dict):
|
||||||
|
continue
|
||||||
|
if 'message' in crumb:
|
||||||
|
crumb['message'] = _scrub_text(crumb['message'])
|
||||||
|
if 'data' in crumb:
|
||||||
|
crumb['data'] = _scrub_value(crumb['data'])
|
||||||
|
if 'extra' in event:
|
||||||
|
event['extra'] = _scrub_value(event['extra'])
|
||||||
|
return event
|
||||||
|
|
||||||
|
|
||||||
|
def _traces_rate():
|
||||||
|
try:
|
||||||
|
return float(os.environ.get('SENTRY_TRACES', '0') or 0)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return 0.0
|
||||||
|
|
||||||
|
|
||||||
|
def release():
|
||||||
|
"""The deploy this process runs: IMAGE_TAG when the stack sets one, else the
|
||||||
|
commit the image was built from (RELEASE, from deploy/Dockerfile.api)."""
|
||||||
|
value = os.environ.get('IMAGE_TAG') or os.environ.get('RELEASE') or ''
|
||||||
|
return None if value in ('', 'unknown', 'latest') else value
|
||||||
|
|
||||||
|
|
||||||
|
def init(component):
|
||||||
|
"""Start Sentry for this process; False (and no imports) without a DSN."""
|
||||||
|
dsn = os.environ.get('SENTRY_DSN_API', '').strip()
|
||||||
|
if not dsn:
|
||||||
|
return False
|
||||||
|
import sentry_sdk
|
||||||
|
environment = os.environ.get('SENTRY_ENVIRONMENT')
|
||||||
|
if not environment:
|
||||||
|
from .runtime import ENVIRONMENT
|
||||||
|
environment = ENVIRONMENT
|
||||||
|
sentry_sdk.init(
|
||||||
|
dsn=dsn,
|
||||||
|
environment=environment,
|
||||||
|
release=release(),
|
||||||
|
send_default_pii=False,
|
||||||
|
traces_sample_rate=_traces_rate(),
|
||||||
|
before_send=scrub,
|
||||||
|
)
|
||||||
|
sentry_sdk.set_tag('component', component)
|
||||||
|
return True
|
||||||
@@ -45,10 +45,10 @@ def seed_from_environment(cursor):
|
|||||||
'SELECT id FROM dtf_local.operators WHERE email=%s', (email,)).fetchone()
|
'SELECT id FROM dtf_local.operators WHERE email=%s', (email,)).fetchone()
|
||||||
if existing:
|
if existing:
|
||||||
# The configured account is the system's own: it stays superadmin.
|
# 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
|
return None
|
||||||
cursor.execute(
|
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)))
|
(uuid4(), email, 'Operador', password_hash(password)))
|
||||||
return email
|
return email
|
||||||
|
|
||||||
@@ -69,8 +69,8 @@ def add(email, name='', role='admin'):
|
|||||||
with connect() as c:
|
with connect() as c:
|
||||||
if c.execute('SELECT id FROM dtf_local.operators WHERE email=%s', (email,)).fetchone():
|
if c.execute('SELECT id FROM dtf_local.operators WHERE email=%s', (email,)).fetchone():
|
||||||
raise SystemExit(f'{email} already exists. Use "password" or "enable".')
|
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)',
|
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))
|
(uuid4(), email, name, password_hash(_ask_password(email)), role, [role]))
|
||||||
print(f'Added {email} as {role}.')
|
print(f'Added {email} as {role}.')
|
||||||
|
|
||||||
|
|
||||||
@@ -79,7 +79,8 @@ def set_role(email, role):
|
|||||||
if role not in ROLES:
|
if role not in ROLES:
|
||||||
raise SystemExit('Role must be one of: ' + ', '.join(ROLES))
|
raise SystemExit('Role must be one of: ' + ', '.join(ROLES))
|
||||||
with connect() as c:
|
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.')
|
raise SystemExit(f'{email} does not exist.')
|
||||||
print(f'{email} is now {role}.')
|
print(f'{email} is now {role}.')
|
||||||
|
|
||||||
|
|||||||
110
app/payments.py
110
app/payments.py
@@ -16,7 +16,7 @@ from uuid import UUID, uuid4
|
|||||||
|
|
||||||
from psycopg.types.json import Jsonb
|
from psycopg.types.json import Jsonb
|
||||||
|
|
||||||
from . import machines, mail, proof
|
from . import mail, proof
|
||||||
from .core.auth import audit
|
from .core.auth import audit
|
||||||
from .core.models import PRODUCTION_VERSIONS
|
from .core.models import PRODUCTION_VERSIONS
|
||||||
from .printjobs import queue as queue_print_files
|
from .printjobs import queue as queue_print_files
|
||||||
@@ -24,14 +24,20 @@ from .runtime import PUBLIC_ORIGIN, enqueue, upload_row
|
|||||||
from .scanning import require_clean
|
from .scanning import require_clean
|
||||||
|
|
||||||
QUOTE_VALID_HOURS = 24
|
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):
|
class PaymentRefused(Exception):
|
||||||
"""The payment cannot become an order, with a reason worth recording."""
|
"""The payment cannot become an order, with a reason worth recording."""
|
||||||
|
|
||||||
|
|
||||||
def approved_quote(c, quote_id, owner=None):
|
def approved_quote(c, quote_id, owner=None, payment_id=None):
|
||||||
"""The reviewed quote behind a payment, or a refusal explaining why not."""
|
"""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 '')
|
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()
|
row = c.execute(sql + ' FOR UPDATE', (quote_id, owner) if owner else (quote_id,)).fetchone()
|
||||||
if not row:
|
if not row:
|
||||||
@@ -42,7 +48,12 @@ def approved_quote(c, quote_id, owner=None):
|
|||||||
raise PaymentRefused('quote was discarded')
|
raise PaymentRefused('quote was discarded')
|
||||||
if any(item.get('production', {}).get('version') not in PRODUCTION_VERSIONS for item in row['approved']['items']):
|
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')
|
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')
|
raise PaymentRefused('quote expired before payment')
|
||||||
return row
|
return row
|
||||||
|
|
||||||
@@ -60,12 +71,49 @@ def is_test(order):
|
|||||||
# (Dropstar's rule D-35, 2026-10-26; the user's answers of 2026-10-27).
|
# (Dropstar's rule D-35, 2026-10-26; the user's answers of 2026-10-27).
|
||||||
MANUAL_PROVIDER = 'manual'
|
MANUAL_PROVIDER = 'manual'
|
||||||
OUTSIDE_METHODS = ('pix', 'card', 'cash', 'credit')
|
OUTSIDE_METHODS = ('pix', 'card', 'cash', 'credit')
|
||||||
|
# A montador Venda order is invoiced, not paid at the counter: it is not one of
|
||||||
|
# the Cotações "registrar" methods. It goes to Tiny as an approved quote does.
|
||||||
|
INVOICED_METHOD = 'faturado'
|
||||||
|
# A montador Interno order: the marketplace's own sale, already invoiced there.
|
||||||
|
# It stays in house and never reaches Tiny (Marcus, 2026-11-10).
|
||||||
|
INTERNAL_METHOD = 'interno'
|
||||||
|
|
||||||
|
|
||||||
def in_tiny(order):
|
def in_tiny(order):
|
||||||
"""Whether the order goes to Tiny: every order but a test. A Dropflow
|
"""Whether the order goes to Tiny: every order but an internal one, a test
|
||||||
order goes in its own revenue category (app/tiny.py, CATEGORIES)."""
|
or a proof card (app/proof.py), which is no sale. A Dropflow order goes in
|
||||||
return not is_test(order)
|
its own revenue category (app/tiny.py, CATEGORIES)."""
|
||||||
|
if (order.get('payment') or {}).get('method') == INTERNAL_METHOD:
|
||||||
|
return False
|
||||||
|
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
|
# How long a file is kept while nothing has been paid for it. A cart's files
|
||||||
@@ -88,6 +136,29 @@ def hold_uploads(c, upload_ids, interval):
|
|||||||
WHERE id=ANY(%s) AND purged_at IS NULL''', (interval, [str(u) for u in upload_ids]))
|
WHERE id=ANY(%s) AND purged_at IS NULL''', (interval, [str(u) for u in upload_ids]))
|
||||||
|
|
||||||
|
|
||||||
|
def release_files(c, uploads):
|
||||||
|
"""Expire these uploads now, except any another order or an open quote
|
||||||
|
still uses: a customer can buy the same file again. Returns how many."""
|
||||||
|
free = []
|
||||||
|
for upload in uploads:
|
||||||
|
used = c.execute('''SELECT 1 FROM dtf_local.order_files WHERE upload_id=%s
|
||||||
|
UNION ALL SELECT 1 FROM dtf_local.print_files WHERE upload_id=%s
|
||||||
|
UNION ALL SELECT 1 FROM dtf_local.print_parts WHERE upload_id=%s
|
||||||
|
UNION ALL SELECT 1 FROM dtf_local.orders o, jsonb_array_elements(o.snapshot->'items') i
|
||||||
|
WHERE i->'uploads' ? %s
|
||||||
|
UNION ALL SELECT 1 FROM dtf_local.quotes q, jsonb_array_elements(q.draft->'items') i
|
||||||
|
WHERE q.discarded_at IS NULL AND q.expired_at IS NULL
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM dtf_local.orders x WHERE x.quote_id=q.id)
|
||||||
|
AND i->'uploads' ? %s
|
||||||
|
LIMIT 1''', (upload,) * 5).fetchone()
|
||||||
|
if not used:
|
||||||
|
free.append(upload)
|
||||||
|
if free:
|
||||||
|
c.execute('''UPDATE dtf_local.uploads SET expires_at=now() WHERE id=ANY(%s::uuid[])
|
||||||
|
AND purged_at IS NULL''', (free,))
|
||||||
|
return len(free)
|
||||||
|
|
||||||
|
|
||||||
def create_order(c, quote, payment, origin):
|
def create_order(c, quote, payment, origin):
|
||||||
"""Create the order for a reviewed quote, or return the one already there.
|
"""Create the order for a reviewed quote, or return the one already there.
|
||||||
`origin` is where it came from (D-21): each way in names its own.
|
`origin` is where it came from (D-21): each way in names its own.
|
||||||
@@ -118,9 +189,13 @@ def create_order(c, quote, payment, origin):
|
|||||||
order = c.execute('''UPDATE dtf_local.orders SET contact_since=now(), contact_by='Site', contact_note=%s
|
order = c.execute('''UPDATE dtf_local.orders SET contact_since=now(), contact_by='Site', contact_note=%s
|
||||||
WHERE id=%s RETURNING *''', (proof.CUSTOMER_NOTE, order['id'])).fetchone()
|
WHERE id=%s RETURNING *''', (proof.CUSTOMER_NOTE, order['id'])).fetchone()
|
||||||
c.execute('INSERT INTO dtf_local.contact_waits(order_id, started_at) VALUES(%s, now())', (order['id'],))
|
c.execute('INSERT INTO dtf_local.contact_waits(order_id, started_at) VALUES(%s, now())', (order['id'],))
|
||||||
machines.route(c)
|
# An order with a proof gets its proof card (app/proof.py).
|
||||||
|
proof.create_child(c, order)
|
||||||
if is_test(order):
|
if is_test(order):
|
||||||
return order, True
|
return order, True
|
||||||
|
# An invoiced or internal montador order was not paid here: no "pedido
|
||||||
|
# pago" e-mail for either (front 7a.3).
|
||||||
|
if payment.get('method') not in (INVOICED_METHOD, INTERNAL_METHOD):
|
||||||
mail.order_paid(c, order, PUBLIC_ORIGIN)
|
mail.order_paid(c, order, PUBLIC_ORIGIN)
|
||||||
if not in_tiny(order):
|
if not in_tiny(order):
|
||||||
return order, True
|
return order, True
|
||||||
@@ -165,7 +240,7 @@ def apply(c, event):
|
|||||||
except (ValueError, AttributeError):
|
except (ValueError, AttributeError):
|
||||||
order = None
|
order = None
|
||||||
if order:
|
if order:
|
||||||
audit('payment_reversed', order=order['number'], status=event.status)
|
audit('payment_reversed', order=order['number'], status=event.status, c=c)
|
||||||
return f"attention: payment {event.status} for order {order['number']}"
|
return f"attention: payment {event.status} for order {order['number']}"
|
||||||
if event.status != 'approved':
|
if event.status != 'approved':
|
||||||
return f'ignored: {event.status}'
|
return f'ignored: {event.status}'
|
||||||
@@ -176,7 +251,7 @@ def apply(c, event):
|
|||||||
return 'refused: reference is not a quote id'
|
return 'refused: reference is not a quote id'
|
||||||
|
|
||||||
try:
|
try:
|
||||||
quote = approved_quote(c, quote_id)
|
quote = approved_quote(c, quote_id, payment_id=provider_id)
|
||||||
except PaymentRefused as refusal:
|
except PaymentRefused as refusal:
|
||||||
return f'refused: {refusal}'
|
return f'refused: {refusal}'
|
||||||
|
|
||||||
@@ -187,11 +262,20 @@ def apply(c, event):
|
|||||||
expected = quote['approved']['total_cents']
|
expected = quote['approved']['total_cents']
|
||||||
if type(event.amount_cents) is not int or event.amount_cents != expected:
|
if type(event.amount_cents) is not int or event.amount_cents != expected:
|
||||||
audit('payment_amount_mismatch', quote=str(quote_id),
|
audit('payment_amount_mismatch', quote=str(quote_id),
|
||||||
expected_cents=expected, paid_cents=event.amount_cents)
|
expected_cents=expected, paid_cents=event.amount_cents, c=c)
|
||||||
return f'refused: paid {event.amount_cents} but quote total is {expected}'
|
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')
|
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):
|
def reconcile(connect, provider, quote_id=None, limit=20):
|
||||||
@@ -209,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')
|
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.created_at > now() - make_interval(hours => %s)''' +
|
||||||
(' AND i.quote_id=%s' if quote_id else '') + ' ORDER BY i.created_at DESC LIMIT %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 = []
|
outcomes = []
|
||||||
for row in rows:
|
for row in rows:
|
||||||
# Asked outside any transaction: no lock is held while the provider answers.
|
# 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 PIL import Image, ImageOps
|
||||||
|
|
||||||
from .core.models import PRODUCTION_VERSIONS
|
from .core.models import PRODUCTION_VERSIONS
|
||||||
|
from .core.pricing import STEP_GRACE_M
|
||||||
|
|
||||||
PT_PER_CM = 72 / 2.54
|
PT_PER_CM = 72 / 2.54
|
||||||
# Acrobat's page limit, 200 inches (5,08 m). A longer sheet is written at its
|
# Acrobat's page limit, 200 inches (5,08 m). A longer sheet is written at its
|
||||||
@@ -380,13 +381,15 @@ def open_source(path, name):
|
|||||||
return SourceImage(path, name)
|
return SourceImage(path, name)
|
||||||
|
|
||||||
|
|
||||||
def check_layout(item, sizes, vector=()):
|
def check_layout(item, sizes, vector=(), proof=False):
|
||||||
"""Refuse a layout the file cannot reproduce faithfully. Returns the lowest
|
"""Refuse a layout the file cannot reproduce faithfully. Returns the lowest
|
||||||
DPI of the raster sources (vector pages have none)."""
|
DPI of the raster sources (vector pages have none). A proof is free of
|
||||||
|
charge, so its zero billed metres must not reject the item's full sheet."""
|
||||||
production = item['production']
|
production = item['production']
|
||||||
height = Decimal(str(production['height_cm']))
|
height = Decimal(str(production['height_cm']))
|
||||||
billed = Decimal(str(item['billed_metres'])) * 100
|
billed = Decimal(str(item['billed_metres'])) * 100
|
||||||
if 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')
|
raise Unsupported(f'a montagem tem {height} cm, mas só {billed} cm foram cobrados')
|
||||||
lowest = None
|
lowest = None
|
||||||
for placement in production['placements']:
|
for placement in production['placements']:
|
||||||
|
|||||||
398
app/printjobs.py
398
app/printjobs.py
@@ -2,68 +2,178 @@
|
|||||||
|
|
||||||
A paid order queues one job per item. The worker claims a job, commits the
|
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
|
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
|
lock or a database connection. A claim past its deadline (the render limit
|
||||||
belong to a worker that died and is taken again.
|
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 an ordinary upload row owned by an identity derived from the
|
The result is a 300 DPI PNG (item 13, app/printpng.py), or its parts for a
|
||||||
order, already marked clean: its only inputs are artwork that passed the
|
film longer than a part (10 m): ordinary upload rows owned by an identity derived from the
|
||||||
malware scan, and the bytes are written here. The operator still decides
|
order, already marked clean, since their only inputs are artwork that passed
|
||||||
whether it becomes the final file; generation never approves anything.
|
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
|
||||||
|
file; generation never approves anything.
|
||||||
|
|
||||||
Sheets of several GB are the normal order, and decoding one would take more
|
Sheets of several GB are the normal order: a PNG or a PDF is read band by
|
||||||
memory than the worker has. A source above LARGE_SOURCE_BYTES is never
|
band, so its size does not matter. Any other file above LARGE_SOURCE_BYTES
|
||||||
opened: a finished sheet placed whole on the film is already its own print
|
is prepared by hand from the original.
|
||||||
file, so the original becomes the print file; any other layout is prepared
|
|
||||||
by hand from the original.
|
|
||||||
"""
|
"""
|
||||||
|
import io
|
||||||
import logging
|
import logging
|
||||||
|
import multiprocessing
|
||||||
import os
|
import os
|
||||||
|
import shutil
|
||||||
import tempfile
|
import tempfile
|
||||||
import time
|
import time
|
||||||
|
from queue import Empty
|
||||||
from datetime import timedelta
|
from datetime import timedelta
|
||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
from zoneinfo import ZoneInfo
|
from zoneinfo import ZoneInfo
|
||||||
from uuid import NAMESPACE_URL, UUID, uuid4, uuid5
|
from uuid import NAMESPACE_URL, UUID, uuid4, uuid5
|
||||||
|
|
||||||
|
import psycopg
|
||||||
from psycopg.types.json import Jsonb
|
from psycopg.types.json import Jsonb
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
from .cart_pricing import needs_designer
|
||||||
from .core.auth import audit
|
from .core.auth import audit
|
||||||
from .core.db import connect
|
from .core.db import connect
|
||||||
from .printfile import Unsupported, render
|
from .printfile import Unsupported
|
||||||
|
from .printpng import part_cuts, render
|
||||||
|
from . import proof
|
||||||
|
from .proof import PROOF_SHEET_CM
|
||||||
from .tiny import purchase_order
|
from .tiny import purchase_order
|
||||||
|
|
||||||
LOCAL = ZoneInfo('America/Sao_Paulo')
|
LOCAL = ZoneInfo('America/Sao_Paulo')
|
||||||
|
|
||||||
CLAIM_TIMEOUT = timedelta(minutes=15)
|
# 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
|
MAX_ATTEMPTS = 3
|
||||||
LARGE_SOURCE_BYTES = int(os.environ.get('PRINT_DECODE_MAX_BYTES', str(300 * 1024 * 1024)))
|
LARGE_SOURCE_BYTES = int(os.environ.get('PRINT_DECODE_MAX_BYTES', str(300 * 1024 * 1024)))
|
||||||
# Formats the operator can import as they are.
|
# Read band by band, whatever their size.
|
||||||
PRINTABLE_ORIGINAL = ('.png', '.jpg', '.jpeg', '.tif', '.tiff', '.pdf')
|
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):
|
def generated_identity(order_id):
|
||||||
return uuid5(NAMESPACE_URL, f'dtf-print-file:{order_id}')
|
return uuid5(NAMESPACE_URL, f'dtf-print-file:{order_id}')
|
||||||
|
|
||||||
|
|
||||||
|
def proof_part(heights_cm, original_height_cm, fraction):
|
||||||
|
"""Which part of a split final holds the finest stroke, and where inside it.
|
||||||
|
|
||||||
|
`heights_cm` are the parts' heights in order, `fraction` the stroke's
|
||||||
|
position on the original film (0 at the top, 1 at the bottom). A single
|
||||||
|
part returns the same fraction, as before.
|
||||||
|
"""
|
||||||
|
heights = [float(height) for height in heights_cm]
|
||||||
|
if not heights:
|
||||||
|
return 0, 0.0
|
||||||
|
position = min(1.0, max(0.0, float(fraction or 0))) * float(original_height_cm)
|
||||||
|
start = 0.0
|
||||||
|
for index, height in enumerate(heights):
|
||||||
|
end = start + height
|
||||||
|
if position <= end or index == len(heights) - 1:
|
||||||
|
inside = (position - start) / height if height > 0 else 0.0
|
||||||
|
return index, min(1.0, max(0.0, inside))
|
||||||
|
start = end
|
||||||
|
return len(heights) - 1, 1.0
|
||||||
|
|
||||||
|
|
||||||
|
def png_height_cm(storage, row):
|
||||||
|
"""A PNG's height in cm at 300 DPI, from its header alone (a Range read)."""
|
||||||
|
head = storage.client.get_object(Bucket=storage.bucket, Key=row['object_key'],
|
||||||
|
Range='bytes=0-65535')['Body'].read()
|
||||||
|
with Image.open(io.BytesIO(head)) as image:
|
||||||
|
height_px = image.size[1]
|
||||||
|
return float(Decimal(height_px) * Decimal('2.54') / Decimal(300))
|
||||||
|
|
||||||
|
|
||||||
def queue(c, order_id, items, only_missing=False):
|
def queue(c, order_id, items, only_missing=False):
|
||||||
"""Queue (or re-queue) generation for every item of an order."""
|
"""Queue (or re-queue) generation for every item of an order."""
|
||||||
for index in range(items):
|
for index in range(items):
|
||||||
if only_missing:
|
if only_missing:
|
||||||
c.execute('''INSERT INTO dtf_local.print_files(id,order_id,item_index) VALUES(%s,%s,%s)
|
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,
|
ON CONFLICT(order_id,item_index) DO UPDATE SET status='pending', attempts=0,
|
||||||
claimed_at=NULL, finished_at=NULL, detail='{}'
|
claimed_at=NULL, claim_token=NULL, finished_at=NULL, upload_id=NULL, detail='{}'
|
||||||
WHERE dtf_local.print_files.status IN ('failed','manual')''',
|
WHERE dtf_local.print_files.status IN ('failed','manual') OR
|
||||||
(uuid4(), order_id, index))
|
(dtf_local.print_files.status='rendering' AND '''
|
||||||
|
+ STALE.format(p='dtf_local.print_files') + ')',
|
||||||
|
(uuid4(), order_id, index, CLAIM_TIMEOUT))
|
||||||
else:
|
else:
|
||||||
c.execute('''INSERT INTO dtf_local.print_files(id,order_id,item_index) VALUES(%s,%s,%s)
|
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))
|
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):
|
def claim(c):
|
||||||
return c.execute('''SELECT p.*, o.snapshot, o.number, o.created_at AS ordered_at FROM dtf_local.print_files p
|
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
|
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 p.created_at FOR UPDATE OF p SKIP LOCKED LIMIT 1''', (CLAIM_TIMEOUT,)).fetchone()
|
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()
|
||||||
|
|
||||||
|
|
||||||
|
def _render_child(result_queue, job, item, uploads):
|
||||||
|
"""Render in a killable process: a stuck image decoder cannot hold a card forever."""
|
||||||
|
from .adapters import LocalS3Storage
|
||||||
|
try:
|
||||||
|
result_queue.put(('ready', produce(LocalS3Storage(), job, item, uploads)))
|
||||||
|
except Unsupported as reason:
|
||||||
|
result_queue.put(('manual', str(reason)))
|
||||||
|
except BaseException as exc:
|
||||||
|
logging.exception('Print file generation failed')
|
||||||
|
result_queue.put(('error', type(exc).__name__))
|
||||||
|
|
||||||
|
|
||||||
|
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(seconds)
|
||||||
|
if process.is_alive():
|
||||||
|
process.terminate()
|
||||||
|
process.join(5)
|
||||||
|
if process.is_alive():
|
||||||
|
process.kill()
|
||||||
|
process.join()
|
||||||
|
return 'timeout', None
|
||||||
|
try:
|
||||||
|
return result_queue.get(timeout=5)
|
||||||
|
except Empty:
|
||||||
|
return 'error', f'processo encerrou com código {process.exitcode}'
|
||||||
|
finally:
|
||||||
|
result_queue.close()
|
||||||
|
result_queue.join_thread()
|
||||||
|
|
||||||
|
|
||||||
def render_one(storage):
|
def render_one(storage):
|
||||||
@@ -71,81 +181,159 @@ def render_one(storage):
|
|||||||
job = claim(c)
|
job = claim(c)
|
||||||
if not job:
|
if not job:
|
||||||
return False
|
return False
|
||||||
c.execute('''UPDATE dtf_local.print_files SET status='rendering', claimed_at=now(),
|
token = uuid4()
|
||||||
attempts=attempts+1 WHERE id=%s''', (job['id'],))
|
|
||||||
item = job['snapshot']['items'][job['item_index']]
|
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,
|
||||||
|
# or from the part of it that holds the finest stroke when the film was
|
||||||
|
# cut into parts (item 13).
|
||||||
|
if job['parent_id']:
|
||||||
|
finals = c.execute('''SELECT u.id,u.object_key FROM dtf_local.order_files f
|
||||||
|
JOIN dtf_local.uploads u ON u.id=f.upload_id
|
||||||
|
LEFT JOIN dtf_local.print_parts p ON p.order_id=f.order_id
|
||||||
|
AND p.item_index=f.item_index AND p.upload_id=f.upload_id
|
||||||
|
WHERE f.order_id=%s AND f.item_index=%s AND f.kind='final' AND f.active
|
||||||
|
AND u.purged_at IS NULL AND u.expires_at>now()
|
||||||
|
ORDER BY p.part NULLS LAST, f.created_at''',
|
||||||
|
(job['parent_id'], item['proof_parent_item_index'])).fetchall()
|
||||||
|
if finals:
|
||||||
|
source = finals[0]
|
||||||
|
if len(finals) > 1:
|
||||||
|
heights = [png_height_cm(storage, row) for row in finals]
|
||||||
|
index, fraction = proof_part(heights, item['production']['height_cm'],
|
||||||
|
item.get('proof_y_fraction'))
|
||||||
|
source = finals[index]
|
||||||
|
job['proof_fraction'] = fraction
|
||||||
|
source_ids = [source['id']]
|
||||||
|
item = {**item, 'uploads': [str(source['id'])]}
|
||||||
|
job['proof_fallback'] = True
|
||||||
|
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,
|
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)''',
|
(expires_at<=now()) AS expired FROM dtf_local.uploads WHERE id=ANY(%s)''',
|
||||||
([UUID(u) for u in item['uploads']],)).fetchall()
|
(source_ids,)).fetchall()
|
||||||
# Every generated file shares its order's artwork retention deadline.
|
# Every generated file shares its order's artwork retention deadline.
|
||||||
expiry = c.execute('SELECT min(created_at)+interval \'30 days\' AS e FROM dtf_local.uploads WHERE id=ANY(%s)',
|
expiry = c.execute('SELECT min(created_at)+interval \'30 days\' AS e FROM dtf_local.uploads WHERE id=ANY(%s)',
|
||||||
([UUID(u) for u in item['uploads']],)).fetchone()['e']
|
(source_ids,)).fetchone()['e']
|
||||||
by_id = {str(row['id']): row for row in uploads}
|
by_id = {str(row['id']): row for row in uploads}
|
||||||
if any(row['size'] > LARGE_SOURCE_BYTES for row in uploads):
|
if job.get('wait_for_treatment'):
|
||||||
original = whole_sheet(item, by_id)
|
finish(job, 'manual', {'reason': 'Ajuste Fino pago: prepare e aprove o PNG completo no pedido pai para gerar a prova.'})
|
||||||
if original:
|
return True
|
||||||
with connect() as c:
|
if any(row['size'] > LARGE_SOURCE_BYTES and not row['name'].lower().endswith(STREAMED) for row in uploads):
|
||||||
c.execute('''UPDATE dtf_local.print_files SET status='ready', upload_id=%s, detail=%s,
|
finish(job, 'manual', {'reason': f'arquivo acima de {LARGE_SOURCE_BYTES // 1048576} MB que não é PNG nem PDF: '
|
||||||
finished_at=now(), claimed_at=NULL WHERE id=%s''',
|
|
||||||
(original['id'], Jsonb({'source': 'original', 'name': original['name']}), job['id']))
|
|
||||||
audit('print_file_original', order=str(job['order_id']), item=job['item_index'])
|
|
||||||
else:
|
|
||||||
finish(job, 'manual', {'reason': f'arquivo acima de {LARGE_SOURCE_BYTES // 1048576} MB: '
|
|
||||||
'monte a folha a partir do original'})
|
'monte a folha a partir do original'})
|
||||||
audit('print_file_manual', order=str(job['order_id']), item=job['item_index'])
|
audit('print_file_manual', order=str(job['order_id']), item=job['item_index'])
|
||||||
return True
|
return True
|
||||||
try:
|
outcome, result = render_with_timeout(job, item, by_id, seconds)
|
||||||
result = produce(storage, job, item, by_id)
|
if outcome == 'manual':
|
||||||
except Unsupported as reason:
|
finish(job, 'manual', {'reason': result})
|
||||||
finish(job, 'manual', {'reason': str(reason)})
|
|
||||||
audit('print_file_manual', order=str(job['order_id']), item=job['item_index'])
|
audit('print_file_manual', order=str(job['order_id']), item=job['item_index'])
|
||||||
return True
|
return True
|
||||||
except Exception as exc:
|
if outcome == 'timeout':
|
||||||
logging.exception('Print file generation failed')
|
finish(job, 'failed', {'reason': f'Tempo limite de {seconds // 60} min excedido. Gere de novo.'})
|
||||||
final = job['attempts'] + 1 >= MAX_ATTEMPTS
|
audit('print_file_timeout', order=str(job['order_id']), item=job['item_index'])
|
||||||
finish(job, 'failed' if final else 'pending', {'error': type(exc).__name__})
|
# 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
|
return True
|
||||||
path, name, size, detail = result
|
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
|
||||||
|
scratch, parts, detail = result
|
||||||
|
stored = []
|
||||||
try:
|
try:
|
||||||
|
for path, name in parts:
|
||||||
uid = uuid4()
|
uid = uuid4()
|
||||||
key = f'originals/{uid}'
|
key = f'originals/{uid}'
|
||||||
storage.store(key, path, 'application/pdf')
|
storage.store(key, path, 'image/png')
|
||||||
|
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. 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:
|
finally:
|
||||||
os.unlink(path)
|
shutil.rmtree(scratch, ignore_errors=True)
|
||||||
|
for part, (uid, _, size, _) in zip(detail['parts'], stored):
|
||||||
|
part.update(upload_id=str(uid), size=size)
|
||||||
with connect() as c:
|
with connect() as c:
|
||||||
|
current = c.execute('''SELECT 1 FROM dtf_local.print_files WHERE id=%s AND claim_token=%s
|
||||||
|
AND status='rendering' FOR UPDATE''', (job['id'], job['claim_token'])).fetchone()
|
||||||
|
if not current:
|
||||||
|
return True
|
||||||
|
for uid, name, size, key in stored:
|
||||||
c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,complete,
|
c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,complete,
|
||||||
expires_at,scan_state,scan_reason,scanned_at)
|
expires_at,scan_state,scan_reason,scanned_at)
|
||||||
VALUES(%s,%s,%s,%s,%s,'',true,%s,'clean','generated from scanned artwork',now())''',
|
VALUES(%s,%s,%s,%s,%s,'',true,%s,'clean','generated from scanned artwork',now())''',
|
||||||
(uid, generated_identity(job['order_id']), name, size, key, expiry))
|
(uid, generated_identity(job['order_id']), name, size, key, expiry))
|
||||||
|
# claimed_at stays: the Prumo report measures generation from the claim.
|
||||||
c.execute('''UPDATE dtf_local.print_files SET status='ready', upload_id=%s, detail=%s,
|
c.execute('''UPDATE dtf_local.print_files SET status='ready', upload_id=%s, detail=%s,
|
||||||
finished_at=now() WHERE id=%s''', (uid, Jsonb(detail), job['id']))
|
finished_at=now(),claim_token=NULL WHERE id=%s''', (stored[0][0], Jsonb(detail), job['id']))
|
||||||
audit('print_file_ready', order=str(job['order_id']), item=job['item_index'])
|
c.execute('DELETE FROM dtf_local.print_parts WHERE order_id=%s AND item_index=%s',
|
||||||
|
(job['order_id'], job['item_index']))
|
||||||
|
for number, (uid, _, _, _) in enumerate(stored, 1):
|
||||||
|
c.execute('INSERT INTO dtf_local.print_parts(order_id,item_index,part,upload_id) VALUES(%s,%s,%s,%s)',
|
||||||
|
(job['order_id'], job['item_index'], number, uid))
|
||||||
|
if job['snapshot'].get('proof_of'):
|
||||||
|
c.execute('''UPDATE dtf_local.order_files SET active=false
|
||||||
|
WHERE order_id=%s AND item_index=%s AND kind='final' ''',
|
||||||
|
(job['order_id'], job['item_index']))
|
||||||
|
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','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
|
return True
|
||||||
|
|
||||||
|
|
||||||
def whole_sheet(item, uploads):
|
def store_tiles(storage, folder, upload_id):
|
||||||
"""The original, when the item is one finished sheet placed whole, once,
|
"""A part's pieces for the Kanban's viewer (item 7), beside the files the
|
||||||
unrotated and unmirrored, across the film: then it is the print file."""
|
storage policy lets the service write: originals/tiles/<upload>/<level>/<index>.png."""
|
||||||
spec = item.get('production') or {}
|
if not os.path.isdir(folder):
|
||||||
sources, placements = spec.get('sources') or [], spec.get('placements') or []
|
return
|
||||||
if len(item['uploads']) != 1 or len(sources) != 1 or len(placements) != 1:
|
for level in sorted(os.listdir(folder)):
|
||||||
return None
|
for strip in sorted(os.listdir(os.path.join(folder, level))):
|
||||||
source, place = sources[0], placements[0]
|
storage.store(f'originals/tiles/{upload_id}/{level}/{strip}', os.path.join(folder, level, strip), 'image/png')
|
||||||
row = uploads.get(item['uploads'][0])
|
|
||||||
if (not row or row['scan_state'] != 'clean' or row['purged_at'] or row['expired']
|
|
||||||
or source.get('kind') != 'sheet' or int(source.get('copies', 1)) != 1
|
|
||||||
or not row['name'].lower().endswith(PRINTABLE_ORIGINAL)):
|
|
||||||
return None
|
|
||||||
if (float(place['x_cm']) != 0 or float(place['y_cm']) != 0 or int(place['rotation_degrees']) != 0
|
|
||||||
or place['mirrored'] or abs(float(source['width_cm']) - float(spec['film_width_cm'])) > 0.5):
|
|
||||||
return None
|
|
||||||
return row
|
|
||||||
|
|
||||||
|
|
||||||
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
|
"""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)."""
|
copies, the footer prints and Tiny keeps (Dropstar, 2026-10-23); after
|
||||||
return f'DTF-{number}-item-{item_index + 1}'
|
"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(job, item):
|
def footer(job, item):
|
||||||
@@ -156,6 +344,10 @@ def footer(job, item):
|
|||||||
count = len(job['snapshot']['items'])
|
count = len(job['snapshot']['items'])
|
||||||
day = job['ordered_at'].astimezone(LOCAL).strftime('%d/%m/%Y')
|
day = job['ordered_at'].astimezone(LOCAL).strftime('%d/%m/%Y')
|
||||||
billed = f"{Decimal(str(item['billed_metres'])):.2f}".replace('.', ',')
|
billed = f"{Decimal(str(item['billed_metres'])):.2f}".replace('.', ',')
|
||||||
|
proof_of = job['snapshot'].get('proof_of')
|
||||||
|
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"])}',
|
fields = ['DROPSTAR', f'Pedido {purchase_order(job["number"])}',
|
||||||
f'Item {job["item_index"] + 1}/{count}', day, f'{billed} m']
|
f'Item {job["item_index"] + 1}/{count}', day, f'{billed} m']
|
||||||
# A mirrored artwork (UV only) is named on the sheet, for the room to see
|
# A mirrored artwork (UV only) is named on the sheet, for the room to see
|
||||||
@@ -165,45 +357,93 @@ def footer(job, item):
|
|||||||
return ' · '.join(fields)
|
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):
|
def produce(storage, job, item, uploads):
|
||||||
"""Fetch the item's artwork and render it. Returns (pdf path, name, size, evidence)."""
|
"""Fetch the item's artwork and render it. Returns (folder, [(png path,
|
||||||
|
name)], evidence); the caller removes the folder."""
|
||||||
|
if not (item.get('production') or {}).get('placements'):
|
||||||
|
raise Unsupported('o item não tem montagem: prepare o arquivo à mão')
|
||||||
for upload_id in item['uploads']:
|
for upload_id in item['uploads']:
|
||||||
row = uploads.get(upload_id)
|
row = uploads.get(upload_id)
|
||||||
if not row or row['scan_state'] != 'clean':
|
if not row or row['scan_state'] != 'clean':
|
||||||
raise Unsupported('um arquivo original está ausente ou não foi liberado pelo antivírus')
|
raise Unsupported('um arquivo original está ausente ou não foi liberado pelo antivírus')
|
||||||
if row['purged_at'] or row['expired']:
|
if row['purged_at'] or row['expired']:
|
||||||
raise Unsupported('um arquivo original passou do prazo de guarda')
|
raise Unsupported('um arquivo original passou do prazo de guarda')
|
||||||
number = job['number']
|
output = tempfile.mkdtemp(prefix='print-')
|
||||||
name = f'{file_prefix(number, job["item_index"])}.pdf'
|
try:
|
||||||
with tempfile.TemporaryDirectory(prefix='print-') as scratch:
|
with tempfile.TemporaryDirectory(prefix='print-') as scratch:
|
||||||
files = {}
|
files = {}
|
||||||
for index, upload_id in enumerate(item['uploads']):
|
for index, upload_id in enumerate(item['uploads']):
|
||||||
local = os.path.join(scratch, f'source-{index}')
|
local = os.path.join(scratch, f'source-{index}')
|
||||||
storage.fetch(uploads[upload_id]['object_key'], local)
|
storage.fetch(uploads[upload_id]['object_key'], local)
|
||||||
files[index] = (local, uploads[upload_id]['name'])
|
files[index] = (local, uploads[upload_id]['name'])
|
||||||
handle, output = tempfile.mkstemp(prefix='print-', suffix='.pdf')
|
if job.get('proof_fallback'):
|
||||||
try:
|
with Image.open(files[0][0]) as final:
|
||||||
with os.fdopen(handle, 'wb') as out:
|
width_px, height_px = final.size
|
||||||
detail = render(item, files, out, f'Pedido {number} - item {job["item_index"] + 1}',
|
width_cm = float(Decimal(width_px) * Decimal('2.54') / Decimal(300))
|
||||||
footer=footer(job, item))
|
height_cm = float(Decimal(height_px) * Decimal('2.54') / Decimal(300))
|
||||||
|
if job.get('proof_fraction') is not None:
|
||||||
|
# Already relative to the chosen part (proof_part).
|
||||||
|
fraction = float(job['proof_fraction'])
|
||||||
|
else:
|
||||||
|
original_height = float(item['production']['height_cm'])
|
||||||
|
fraction = min(1, float(item.get('proof_y_fraction') or 0) * original_height / height_cm)
|
||||||
|
source = {'kind': 'sheet', 'width_cm': width_cm, 'length_cm': height_cm,
|
||||||
|
'copies': 1, 'rotation_degrees': 0, 'mirrored': False, 'measurement': 'file'}
|
||||||
|
item = {**item, 'proof_y_fraction': fraction,
|
||||||
|
'production': {'version': 3, 'film_width_cm': width_cm,
|
||||||
|
'height_cm': height_cm, 'sources': [source],
|
||||||
|
'placements': [{'source_index': 0, 'copy_index': 0,
|
||||||
|
'x_cm': 0, 'y_cm': 0, 'width_cm': width_cm,
|
||||||
|
'length_cm': height_cm, 'rotation_degrees': 0,
|
||||||
|
'mirrored': False}]}}
|
||||||
|
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'], 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,
|
||||||
|
pictures=pictures_by_source(item, job.get('pictures')))
|
||||||
except BaseException:
|
except BaseException:
|
||||||
os.unlink(output)
|
shutil.rmtree(output, ignore_errors=True)
|
||||||
raise
|
raise
|
||||||
return output, name, os.path.getsize(output), detail
|
return output, parts, detail
|
||||||
|
|
||||||
|
|
||||||
def finish(job, status, detail):
|
def finish(job, status, detail):
|
||||||
with connect() as c:
|
with connect() as c:
|
||||||
c.execute('''UPDATE dtf_local.print_files SET status=%s, detail=%s,
|
c.execute('''UPDATE dtf_local.print_files SET status=%s, detail=%s,
|
||||||
finished_at=CASE WHEN %s='pending' THEN NULL ELSE now() END,
|
finished_at=CASE WHEN %s='pending' THEN NULL ELSE now() END,
|
||||||
claimed_at=NULL WHERE id=%s''', (status, Jsonb(detail), status, job['id']))
|
claimed_at=NULL,claim_token=NULL WHERE id=%s AND claim_token=%s AND status='rendering' ''',
|
||||||
|
(status, Jsonb(detail), status, job['id'], job['claim_token']))
|
||||||
|
|
||||||
|
|
||||||
def render_loop(storage):
|
def render_loop(storage):
|
||||||
|
down_since, delay = None, 2
|
||||||
while True:
|
while True:
|
||||||
try:
|
try:
|
||||||
if render_one(storage):
|
if render_one(storage):
|
||||||
continue
|
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:
|
except Exception:
|
||||||
logging.exception('Print render worker tick failed')
|
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)
|
time.sleep(2)
|
||||||
|
|||||||
791
app/printpng.py
Normal file
791
app/printpng.py
Normal file
@@ -0,0 +1,791 @@
|
|||||||
|
"""The print file as a PNG (Dropstar's third round, item 13, 2026-10-29).
|
||||||
|
|
||||||
|
FlexiPRINT's Spot OK 1 preset makes the white underbase from transparency, and
|
||||||
|
it reads that reliably only from a PNG: the montador writes each order item as
|
||||||
|
a 300 DPI PNG with an alpha channel on a transparent background, the same file
|
||||||
|
from payment to Finalizado. The customer may still send PNG or PDF; the output
|
||||||
|
is always PNG, and nothing converts it afterwards.
|
||||||
|
|
||||||
|
A 57 cm x 15 m sheet is 6732 x 177165 px, 4,7 GB as pixels, so nothing here
|
||||||
|
holds a whole sheet: the film is composed and written in bands of rows.
|
||||||
|
|
||||||
|
- Writing: each band is encoded by Pillow without compression, which still
|
||||||
|
chooses each row's PNG filter, and its filtered rows go into one zlib stream
|
||||||
|
for the whole file.
|
||||||
|
- A long PNG sheet is read band by band the same way backwards: the next
|
||||||
|
band's compressed rows, behind the last decoded row unfiltered, are wrapped
|
||||||
|
as a small PNG of their own that Pillow decodes.
|
||||||
|
- A PDF page is rendered band by band at 300 DPI by PDFium, vector all the way.
|
||||||
|
- 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 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
|
||||||
|
import os
|
||||||
|
import struct
|
||||||
|
import zlib
|
||||||
|
from decimal import Decimal
|
||||||
|
|
||||||
|
from PIL import Image, ImageDraw, ImageFont, ImageOps
|
||||||
|
|
||||||
|
from .core.models import PRODUCTION_VERSIONS
|
||||||
|
from .printfile import (FOOTER_CM, FOOTER_LOGO, FOOTER_LOGO_CM, MAX_DECODED_PIXELS, SUPPORTED_FORMATS,
|
||||||
|
Unsupported, check_layout)
|
||||||
|
from .printtiles import Pyramid
|
||||||
|
|
||||||
|
DPI = 300
|
||||||
|
PX_PER_CM = DPI / 2.54
|
||||||
|
# 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
|
||||||
|
Image.MAX_IMAGE_PIXELS = None
|
||||||
|
|
||||||
|
|
||||||
|
def px(cm):
|
||||||
|
return int(round(float(cm) * PX_PER_CM))
|
||||||
|
|
||||||
|
|
||||||
|
# ---- Writing ----------------------------------------------------------------
|
||||||
|
|
||||||
|
def _chunk(fp, kind, data):
|
||||||
|
fp.write(struct.pack('>I', len(data)) + kind + data)
|
||||||
|
fp.write(struct.pack('>I', zlib.crc32(kind + data) & 0xffffffff))
|
||||||
|
|
||||||
|
|
||||||
|
class PngWriter:
|
||||||
|
"""An RGBA PNG written band by band: only one band is ever in memory."""
|
||||||
|
|
||||||
|
def __init__(self, fp, width, height):
|
||||||
|
self.fp, self.width, self.height = fp, width, height
|
||||||
|
self.rows = 0
|
||||||
|
# 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))
|
||||||
|
per_metre = round(DPI / 0.0254)
|
||||||
|
_chunk(fp, b'pHYs', struct.pack('>IIB', per_metre, per_metre, 1))
|
||||||
|
|
||||||
|
def band(self, image):
|
||||||
|
"""Append `image` (RGBA, the film's width) below what is written."""
|
||||||
|
if image.mode != 'RGBA' or image.width != self.width:
|
||||||
|
raise ValueError('a band must be RGBA and as wide as the film')
|
||||||
|
rows = image.height
|
||||||
|
if self.rows + rows > self.height:
|
||||||
|
raise ValueError('more rows than the file has')
|
||||||
|
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):
|
||||||
|
out = self.z.compress(data)
|
||||||
|
if out:
|
||||||
|
self.pending.append(out)
|
||||||
|
if sum(map(len, self.pending)) >= 1 << 20:
|
||||||
|
self._flush()
|
||||||
|
|
||||||
|
def _flush(self):
|
||||||
|
if self.pending:
|
||||||
|
_chunk(self.fp, b'IDAT', b''.join(self.pending))
|
||||||
|
self.pending = []
|
||||||
|
|
||||||
|
def close(self):
|
||||||
|
if self.rows != self.height:
|
||||||
|
raise ValueError(f'{self.rows} of {self.height} rows written')
|
||||||
|
self.pending.append(self.z.flush())
|
||||||
|
self._flush()
|
||||||
|
_chunk(self.fp, b'IEND', b'')
|
||||||
|
|
||||||
|
|
||||||
|
# ---- Reading ----------------------------------------------------------------
|
||||||
|
|
||||||
|
class PngRows:
|
||||||
|
"""A PNG's rows in order, band by band, without decoding the whole image.
|
||||||
|
|
||||||
|
Only 8-bit, non-interlaced files: anything else is decoded whole.
|
||||||
|
"""
|
||||||
|
CHANNELS = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}
|
||||||
|
|
||||||
|
def __init__(self, path):
|
||||||
|
self.fp = open(path, 'rb')
|
||||||
|
if self.fp.read(8) != b'\x89PNG\r\n\x1a\n':
|
||||||
|
raise Unsupported('o PNG está corrompido')
|
||||||
|
self.extra = []
|
||||||
|
while True:
|
||||||
|
size, kind = struct.unpack('>I4s', self.fp.read(8))
|
||||||
|
if kind == b'IDAT':
|
||||||
|
self.idat_left = size
|
||||||
|
break
|
||||||
|
data = self.fp.read(size)
|
||||||
|
self.fp.read(4)
|
||||||
|
if kind == b'IHDR':
|
||||||
|
self.width, self.height, depth, color, _, _, interlace = struct.unpack('>IIBBBBB', data)
|
||||||
|
self.ihdr = data
|
||||||
|
if depth != 8 or interlace or color not in self.CHANNELS:
|
||||||
|
raise Unsupported('PNG de 16 bits ou entrelaçado')
|
||||||
|
self.row_bytes = 1 + self.width * self.CHANNELS[color]
|
||||||
|
elif kind in (b'PLTE', b'tRNS'):
|
||||||
|
self.extra.append((kind, data))
|
||||||
|
elif kind == b'IEND':
|
||||||
|
raise Unsupported('o PNG não tem imagem')
|
||||||
|
self.inflate = zlib.decompressobj()
|
||||||
|
self.buffer = b''
|
||||||
|
self.done = 0 # rows decoded so far
|
||||||
|
self.previous = None # the last decoded row, raw
|
||||||
|
|
||||||
|
def _compressed(self, want):
|
||||||
|
"""At least `want` bytes of filtered rows, unless the file ends first."""
|
||||||
|
parts, have = [self.buffer], len(self.buffer)
|
||||||
|
while have < want:
|
||||||
|
if not self.idat_left:
|
||||||
|
self.fp.read(4)
|
||||||
|
size, kind = struct.unpack('>I4s', self.fp.read(8))
|
||||||
|
if kind != b'IDAT':
|
||||||
|
break
|
||||||
|
self.idat_left = size
|
||||||
|
block = self.fp.read(min(self.idat_left, 1 << 20))
|
||||||
|
self.idat_left -= len(block)
|
||||||
|
out = self.inflate.decompress(block)
|
||||||
|
parts.append(out)
|
||||||
|
have += len(out)
|
||||||
|
data = b''.join(parts)
|
||||||
|
self.buffer = data[want:]
|
||||||
|
return data[:want]
|
||||||
|
|
||||||
|
def band(self, rows):
|
||||||
|
"""The next `rows` rows (fewer at the end) as an image in the file's mode."""
|
||||||
|
rows = min(rows, self.height - self.done)
|
||||||
|
if rows <= 0:
|
||||||
|
return None
|
||||||
|
filtered = self._compressed(rows * self.row_bytes)
|
||||||
|
if len(filtered) != rows * self.row_bytes:
|
||||||
|
raise Unsupported('o PNG terminou antes da última linha')
|
||||||
|
lead = 1 if self.previous is not None else 0
|
||||||
|
out = io.BytesIO()
|
||||||
|
out.write(b'\x89PNG\r\n\x1a\n')
|
||||||
|
_chunk(out, b'IHDR', struct.pack('>II', self.width, rows + lead) + self.ihdr[8:])
|
||||||
|
for kind, data in self.extra:
|
||||||
|
_chunk(out, kind, data)
|
||||||
|
body = (b'\x00' + self.previous if lead else b'') + filtered
|
||||||
|
_chunk(out, b'IDAT', zlib.compress(body, 0))
|
||||||
|
_chunk(out, b'IEND', b'')
|
||||||
|
out.seek(0)
|
||||||
|
image = Image.open(out)
|
||||||
|
image.load()
|
||||||
|
if lead:
|
||||||
|
image = image.crop((0, 1, self.width, rows + 1))
|
||||||
|
self.previous = image.crop((0, rows - 1, self.width, rows)).tobytes()
|
||||||
|
self.done += rows
|
||||||
|
return image
|
||||||
|
|
||||||
|
def close(self):
|
||||||
|
self.fp.close()
|
||||||
|
|
||||||
|
|
||||||
|
def rgba(image):
|
||||||
|
if image.mode == 'RGBA':
|
||||||
|
return image
|
||||||
|
if image.mode in ('I;16', 'I;16B', 'I;16L', 'I'):
|
||||||
|
image = image.convert('I').point(lambda value: value * (1 / 257)).convert('L')
|
||||||
|
return image.convert('RGBA')
|
||||||
|
|
||||||
|
|
||||||
|
class Source:
|
||||||
|
"""One customer file: its size as the Site measured it, and its pixels."""
|
||||||
|
|
||||||
|
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
|
||||||
|
if self.pdf:
|
||||||
|
import pypdfium2
|
||||||
|
try:
|
||||||
|
self.document = pypdfium2.PdfDocument(path)
|
||||||
|
except Exception as exc:
|
||||||
|
raise Unsupported(f'"{name}" não é um PDF que o gerador consiga ler') from exc
|
||||||
|
if len(self.document) != 1:
|
||||||
|
count = len(self.document)
|
||||||
|
self.document.close()
|
||||||
|
raise Unsupported(f'"{name}" tem {count} páginas; só PDFs de uma página são gerados automaticamente')
|
||||||
|
self.page = self.document[0]
|
||||||
|
self.size = self.page.get_size() # as displayed, /Rotate applied
|
||||||
|
self.streamable = True
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
image = Image.open(path)
|
||||||
|
except Exception as exc:
|
||||||
|
raise Unsupported(f'"{name}" não é uma imagem que o gerador consiga ler') from exc
|
||||||
|
if image.format not in SUPPORTED_FORMATS:
|
||||||
|
raise Unsupported(f'"{name}" está em {image.format or "formato desconhecido"}; '
|
||||||
|
'só JPEG, PNG, WebP, TIFF e PDF são gerados automaticamente')
|
||||||
|
# Pillow decodes a whole PNG to look for EXIF after the pixels; only
|
||||||
|
# an orientation ahead of them is read, as is a JPEG's.
|
||||||
|
try:
|
||||||
|
self.orientation = (image.getexif().get(0x0112, 1)
|
||||||
|
if image.format != 'PNG' or 'exif' in image.info else 1)
|
||||||
|
except Exception:
|
||||||
|
self.orientation = 1
|
||||||
|
width, height = image.size
|
||||||
|
self.size = (height, width) if self.orientation in (5, 6, 7, 8) else (width, height)
|
||||||
|
self.streamable = False
|
||||||
|
if image.format == 'PNG' and self.orientation == 1:
|
||||||
|
try:
|
||||||
|
PngRows(path).close()
|
||||||
|
self.streamable = True
|
||||||
|
except Unsupported:
|
||||||
|
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:
|
||||||
|
if width * height > MAX_DECODED_PIXELS:
|
||||||
|
raise Unsupported(f'"{self.name}" ficaria grande demais para montar; prepare este item à mão')
|
||||||
|
scale = width / self.size[0]
|
||||||
|
image = self.page.render(scale=scale, fill_color=(0, 0, 0, 0)).to_pil()
|
||||||
|
return rgba(image).resize((width, height), Image.LANCZOS) if image.size != (width, height) else rgba(image)
|
||||||
|
image = Image.open(self.path)
|
||||||
|
if image.width * image.height > MAX_DECODED_PIXELS:
|
||||||
|
raise Unsupported(f'"{self.name}" tem {image.width} × {image.height} px, mais do que o '
|
||||||
|
'gerador processa; prepare este item à mão')
|
||||||
|
image.load()
|
||||||
|
if self.orientation != 1:
|
||||||
|
image = ImageOps.exif_transpose(image)
|
||||||
|
image = rgba(image)
|
||||||
|
return image if image.size == (width, height) else image.resize((width, height), Image.LANCZOS)
|
||||||
|
|
||||||
|
def close(self):
|
||||||
|
if self.pdf:
|
||||||
|
self.document.close()
|
||||||
|
|
||||||
|
|
||||||
|
# ---- Pieces -----------------------------------------------------------------
|
||||||
|
|
||||||
|
class Piece:
|
||||||
|
"""One placement on the film, in pixels, able to give the rows of the film
|
||||||
|
it covers, in order."""
|
||||||
|
|
||||||
|
def __init__(self, placement, source):
|
||||||
|
self.source = source
|
||||||
|
self.x, self.y = px(placement['x_cm']), px(placement['y_cm'])
|
||||||
|
self.w = max(1, px(Decimal(str(placement['x_cm'])) + Decimal(str(placement['width_cm']))) - self.x)
|
||||||
|
self.h = max(1, px(Decimal(str(placement['y_cm'])) + Decimal(str(placement['length_cm']))) - self.y)
|
||||||
|
self.rotation = placement['rotation_degrees'] % 360
|
||||||
|
self.mirrored = placement['mirrored']
|
||||||
|
self.reader = None
|
||||||
|
|
||||||
|
@property
|
||||||
|
def streamed(self):
|
||||||
|
return (self.source.streamable and not self.rotation and not self.mirrored and
|
||||||
|
self.w * self.h > STREAM_ABOVE_PIXELS)
|
||||||
|
|
||||||
|
def rows(self, top, bottom, cache):
|
||||||
|
"""The piece's rows [top, bottom) in film coordinates, as RGBA."""
|
||||||
|
a, b = top - self.y, bottom - self.y
|
||||||
|
if not self.streamed:
|
||||||
|
return self._placed(cache).crop((0, a, self.w, b))
|
||||||
|
if self.source.pdf:
|
||||||
|
return self._pdf_rows(a, b)
|
||||||
|
return self._png_rows(a, b)
|
||||||
|
|
||||||
|
def _placed(self, cache):
|
||||||
|
"""The whole piece, turned and scaled, shared by every copy."""
|
||||||
|
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)
|
||||||
|
if self.rotation:
|
||||||
|
# Clockwise, as the Site turns it.
|
||||||
|
image = image.rotate(-self.rotation, expand=True)
|
||||||
|
cache[key] = image if image.size == (self.w, self.h) else image.resize((self.w, self.h), Image.LANCZOS)
|
||||||
|
return cache[key]
|
||||||
|
|
||||||
|
def _pdf_rows(self, a, b):
|
||||||
|
page_w, page_h = self.source.size
|
||||||
|
scale = self.w / page_w
|
||||||
|
top_pt, bottom_pt = a / scale, max(0.0, page_h - b / scale)
|
||||||
|
image = self.source.page.render(scale=scale, crop=(0, bottom_pt, 0, top_pt),
|
||||||
|
fill_color=(0, 0, 0, 0)).to_pil()
|
||||||
|
image = rgba(image)
|
||||||
|
return image if image.size == (self.w, b - a) else image.resize((self.w, b - a), Image.LANCZOS)
|
||||||
|
|
||||||
|
def _png_rows(self, a, b):
|
||||||
|
"""Rows [a, b) of the piece from a PNG read in order, scaled to the piece."""
|
||||||
|
if self.reader is None:
|
||||||
|
self.reader = PngRows(self.source.path)
|
||||||
|
self.buffer, self.buffer_top = None, 0
|
||||||
|
sw, sh = self.reader.width, self.reader.height
|
||||||
|
# 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 = 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:
|
||||||
|
self.buffer = band
|
||||||
|
else:
|
||||||
|
joined = Image.new('RGBA', (sw, self.buffer.height + band.height))
|
||||||
|
joined.paste(self.buffer, (0, 0))
|
||||||
|
joined.paste(band, (0, self.buffer.height))
|
||||||
|
self.buffer = joined
|
||||||
|
if want_top > self.buffer_top: # rows no band will need again
|
||||||
|
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 + 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):
|
||||||
|
if self.reader:
|
||||||
|
self.reader.close()
|
||||||
|
self.reader = None
|
||||||
|
|
||||||
|
|
||||||
|
# ---- Parts and footer -------------------------------------------------------
|
||||||
|
|
||||||
|
# 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'])))
|
||||||
|
for p in production['placements']]
|
||||||
|
cuts = [Decimal(0)]
|
||||||
|
while height - cuts[-1] > limit:
|
||||||
|
start = cuts[-1]
|
||||||
|
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)]
|
||||||
|
# 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
|
||||||
|
the film. Without a measured fraction it starts at the top, as before."""
|
||||||
|
height = Decimal(str(height_cm))
|
||||||
|
if height <= 0:
|
||||||
|
return [Decimal(0), Decimal(0)]
|
||||||
|
span = min(height, Decimal(str(limit_cm)))
|
||||||
|
if fraction is None:
|
||||||
|
return [Decimal(0), span]
|
||||||
|
center = min(Decimal(1), max(Decimal(0), Decimal(str(fraction)))) * height
|
||||||
|
start = min(height - span, max(Decimal(0), center - span / 2))
|
||||||
|
return [start, start + span]
|
||||||
|
|
||||||
|
|
||||||
|
def _font(size):
|
||||||
|
return ImageFont.load_default(size=size)
|
||||||
|
|
||||||
|
|
||||||
|
def footer_band(text, width):
|
||||||
|
"""The footer, 1,5 cm, black on transparent: the logo, then the line."""
|
||||||
|
height = px(FOOTER_CM)
|
||||||
|
band = Image.new('RGBA', (width, height))
|
||||||
|
draw = ImageDraw.Draw(band)
|
||||||
|
x = px(0.5)
|
||||||
|
if os.path.exists(FOOTER_LOGO):
|
||||||
|
logo = rgba(Image.open(FOOTER_LOGO))
|
||||||
|
logo_h = px(FOOTER_LOGO_CM)
|
||||||
|
logo = logo.resize((max(1, round(logo.width * logo_h / logo.height)), logo_h), Image.LANCZOS)
|
||||||
|
band.alpha_composite(logo, (x, (height - logo_h) // 2))
|
||||||
|
x += logo.width + px(0.4)
|
||||||
|
text = text.partition(' · ')[2]
|
||||||
|
room = width - x - px(0.5)
|
||||||
|
size = px(FOOTER_TEXT_CM)
|
||||||
|
while size > 10 and draw.textlength(text, font=_font(size)) > room:
|
||||||
|
size -= 4
|
||||||
|
font = _font(size)
|
||||||
|
top, bottom = font.getbbox(text)[1], font.getbbox(text)[3]
|
||||||
|
draw.text((x, (height - (bottom - top)) // 2 - top), text, font=font, fill=(0, 0, 0, 255),
|
||||||
|
stroke_width=max(1, size // 40), stroke_fill=(0, 0, 0, 255))
|
||||||
|
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, 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`,
|
||||||
|
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']
|
||||||
|
if production.get('version') not in PRODUCTION_VERSIONS:
|
||||||
|
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'])
|
||||||
|
|
||||||
|
def laid_out():
|
||||||
|
return sorted((Piece(placement, sources[placement['source_index']])
|
||||||
|
for placement in production['placements']), key=lambda piece: piece.y)
|
||||||
|
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, ranges, width, line,
|
||||||
|
tiles=os.path.join(out_dir, 'tiles', name) if tiles else None))
|
||||||
|
parts.append((path, name))
|
||||||
|
finally:
|
||||||
|
for source in sources:
|
||||||
|
source.close()
|
||||||
|
return parts, {'format': 'png', 'dpi': DPI,
|
||||||
|
'film_width_cm': str(production['film_width_cm']),
|
||||||
|
'height_cm': str(production['height_cm']),
|
||||||
|
'width_px': width,
|
||||||
|
'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']),
|
||||||
|
'sources': len(sources),
|
||||||
|
'vector_sources': len(vector),
|
||||||
|
'min_dpi': round(lowest) if lowest else None}
|
||||||
|
|
||||||
|
|
||||||
|
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)
|
||||||
|
band = Image.new('RGBA', (width, band_bottom - band_top))
|
||||||
|
for piece in pieces:
|
||||||
|
if piece.y >= band_bottom:
|
||||||
|
break
|
||||||
|
if piece.y + piece.h <= band_top:
|
||||||
|
continue
|
||||||
|
a, b = max(band_top, piece.y), min(band_bottom, piece.y + piece.h)
|
||||||
|
rows = piece.rows(a, b, cache)
|
||||||
|
left = max(0, -piece.x)
|
||||||
|
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))
|
||||||
|
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:
|
||||||
|
piece.close()
|
||||||
|
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]
|
||||||
|
|
||||||
|
|
||||||
|
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(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
|
||||||
64
app/printpng_validate.py
Normal file
64
app/printpng_validate.py
Normal file
@@ -0,0 +1,64 @@
|
|||||||
|
"""Small, bounded header check for the final file FlexiPRINT receives.
|
||||||
|
|
||||||
|
The original upload may be PNG or PDF. A *final* file is a transparent,
|
||||||
|
8-bit RGBA PNG tagged 300 DPI. Read only header chunks before IDAT, so even
|
||||||
|
a multi-gigabyte sheet is checked without decoding or downloading the film.
|
||||||
|
"""
|
||||||
|
import struct
|
||||||
|
|
||||||
|
PNG = b'\x89PNG\r\n\x1a\n'
|
||||||
|
HEADER_BYTES = 1 << 20
|
||||||
|
|
||||||
|
|
||||||
|
def final_png_issue(data):
|
||||||
|
if not data.startswith(PNG):
|
||||||
|
return 'O arquivo final precisa ser PNG transparente a 300 DPI. Converta PDF/TIFF antes de enviar.'
|
||||||
|
at = len(PNG)
|
||||||
|
rgba = False
|
||||||
|
dpi = None
|
||||||
|
image_data = False
|
||||||
|
while at + 12 <= len(data):
|
||||||
|
size = struct.unpack('>I', data[at:at + 4])[0]
|
||||||
|
kind = data[at + 4:at + 8]
|
||||||
|
end = at + 12 + size
|
||||||
|
if kind == b'IDAT':
|
||||||
|
image_data = True
|
||||||
|
break
|
||||||
|
if end > len(data):
|
||||||
|
return 'O cabeçalho do PNG final está incompleto ou inválido.'
|
||||||
|
body = data[at + 8:at + 8 + size]
|
||||||
|
if kind == b'IHDR':
|
||||||
|
if at != 8 or size != 13:
|
||||||
|
return 'O cabeçalho do PNG final está inválido.'
|
||||||
|
width, height, depth, color, compression, filtering, interlace = struct.unpack('>IIBBBBB', body)
|
||||||
|
rgba = bool(width and height and depth == 8 and color == 6 and
|
||||||
|
compression == 0 and filtering == 0 and interlace == 0)
|
||||||
|
elif kind == b'pHYs' and size == 9:
|
||||||
|
x, y, unit = struct.unpack('>IIB', body)
|
||||||
|
if unit == 1 and x and y:
|
||||||
|
dpi = (x * .0254, y * .0254)
|
||||||
|
at = end
|
||||||
|
if not rgba:
|
||||||
|
return 'O PNG final precisa ter transparência (canal alfa RGBA de 8 bits).'
|
||||||
|
if not dpi or any(abs(axis - 300) > 1 for axis in dpi):
|
||||||
|
return 'O PNG final precisa estar marcado como 300 DPI nos dois eixos.'
|
||||||
|
if not image_data:
|
||||||
|
return 'O PNG final está incompleto: faltam os dados da imagem.'
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
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'):
|
||||||
|
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}')
|
||||||
|
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)
|
||||||
107
app/printtiles.py
Normal file
107
app/printtiles.py
Normal file
@@ -0,0 +1,107 @@
|
|||||||
|
"""The print file in pieces, for the Kanban's viewer (Dropstar's third round, item 7).
|
||||||
|
|
||||||
|
"Abrir e conferir" shows the PNG at up to 100% (one file pixel, one screen
|
||||||
|
pixel). A 57 cm x 15 m film is 160 million pixels per 2 m: loaded whole it
|
||||||
|
freezes the designer's computer, so the viewer loads it in pieces, like a map.
|
||||||
|
|
||||||
|
The pieces are strips of the film's whole width, STRIP_ROWS tall, at 100%
|
||||||
|
and at each halving down to a few strips for the whole film: level 0 is the
|
||||||
|
file itself, level k is 1/2^k of it. They are written while the PNG is, from
|
||||||
|
the same bands, so the file is never read back.
|
||||||
|
"""
|
||||||
|
import io
|
||||||
|
import math
|
||||||
|
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
STRIP_ROWS = 512
|
||||||
|
# Levels stop when the whole film fits in about one screen.
|
||||||
|
SMALLEST_ROWS = 1024
|
||||||
|
|
||||||
|
|
||||||
|
def levels_for(height):
|
||||||
|
"""How many levels a film of `height` px gets: halving until it is short."""
|
||||||
|
count = 1
|
||||||
|
while math.ceil(height / 2 ** (count - 1)) > SMALLEST_ROWS and count < 12:
|
||||||
|
count += 1
|
||||||
|
return count
|
||||||
|
|
||||||
|
|
||||||
|
class Pyramid:
|
||||||
|
"""Fed the film's bands from the top, it hands each finished strip, as a
|
||||||
|
PNG, to `emit(level, index, png_bytes)`."""
|
||||||
|
|
||||||
|
def __init__(self, width, height, emit):
|
||||||
|
self.width, self.height, self.emit = width, height, emit
|
||||||
|
self.levels = levels_for(height)
|
||||||
|
self.pending = [None] * self.levels # rows of each level not yet a strip
|
||||||
|
self.count = [0] * self.levels # strips written per level
|
||||||
|
# A level's odd last row waits for its pair.
|
||||||
|
self.odd = [None] * self.levels
|
||||||
|
|
||||||
|
def band(self, image):
|
||||||
|
self._feed(0, image)
|
||||||
|
|
||||||
|
def _feed(self, level, image):
|
||||||
|
if level >= self.levels:
|
||||||
|
return
|
||||||
|
rows = self.pending[level]
|
||||||
|
if rows is None:
|
||||||
|
rows = image
|
||||||
|
else:
|
||||||
|
joined = Image.new('RGBA', (image.width, rows.height + image.height))
|
||||||
|
joined.paste(rows, (0, 0))
|
||||||
|
joined.paste(image, (0, rows.height))
|
||||||
|
rows = joined
|
||||||
|
while rows.height >= STRIP_ROWS:
|
||||||
|
self._strip(level, rows.crop((0, 0, rows.width, STRIP_ROWS)))
|
||||||
|
rows = rows.crop((0, STRIP_ROWS, rows.width, rows.height)) if rows.height > STRIP_ROWS else None
|
||||||
|
if rows is None:
|
||||||
|
break
|
||||||
|
self.pending[level] = rows
|
||||||
|
# The next level down, from these rows, two by two.
|
||||||
|
self._halve(level, image)
|
||||||
|
|
||||||
|
def _halve(self, level, image):
|
||||||
|
if level + 1 >= self.levels:
|
||||||
|
return
|
||||||
|
if self.odd[level] is not None:
|
||||||
|
joined = Image.new('RGBA', (image.width, image.height + 1))
|
||||||
|
joined.paste(self.odd[level], (0, 0))
|
||||||
|
joined.paste(image, (0, 1))
|
||||||
|
image, self.odd[level] = joined, None
|
||||||
|
if image.height % 2:
|
||||||
|
self.odd[level] = image.crop((0, image.height - 1, image.width, image.height))
|
||||||
|
image = image.crop((0, 0, image.width, image.height - 1))
|
||||||
|
if image.height:
|
||||||
|
small = image.resize((max(1, math.ceil(image.width / 2)), image.height // 2), Image.BOX)
|
||||||
|
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()
|
||||||
|
writer = PngWriter(out, image.width, image.height)
|
||||||
|
writer.band(image)
|
||||||
|
writer.close()
|
||||||
|
self.emit(level, self.count[level], out.getvalue())
|
||||||
|
self.count[level] += 1
|
||||||
|
|
||||||
|
def close(self):
|
||||||
|
"""Flush what is left at each level, from the top level down."""
|
||||||
|
for level in range(self.levels):
|
||||||
|
if self.odd[level] is not None and level + 1 < self.levels:
|
||||||
|
last = self.odd[level]
|
||||||
|
self.odd[level] = None
|
||||||
|
self._feed(level + 1, last.resize((max(1, math.ceil(last.width / 2)), 1), Image.BOX))
|
||||||
|
if self.pending[level] is not None and self.pending[level].height:
|
||||||
|
self._strip(level, self.pending[level])
|
||||||
|
self.pending[level] = None
|
||||||
|
return self.manifest()
|
||||||
|
|
||||||
|
def manifest(self):
|
||||||
|
return {'width': self.width, 'height': self.height, 'strip_rows': STRIP_ROWS,
|
||||||
|
'levels': [{'scale': 1 / 2 ** k, 'width': math.ceil(self.width / 2 ** k),
|
||||||
|
'height': math.ceil(self.height / 2 ** k), 'strips': self.count[k]}
|
||||||
|
for k in range(self.levels)]}
|
||||||
141
app/proof.py
141
app/proof.py
@@ -1,8 +1,9 @@
|
|||||||
"""The print proof (Dropstar, 2026-10-21).
|
"""The print proof (Dropstar, 2026-10-21).
|
||||||
|
|
||||||
An order above 10 m prints a proof before the rest, checked by the print room
|
An order above 10 m prints a proof before the rest, checked by the print room
|
||||||
without stopping the order. Dropstar's rule (2026-10-23): up to 30 cm, from
|
without stopping the order. Dropstar's current rule: 15 cm from the part
|
||||||
the part with the thinnest lines, a piece of each different artwork, at most
|
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
|
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
|
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
|
2026-10-28): that order waits for them, marked "Aguardando contato", until
|
||||||
@@ -11,6 +12,13 @@ marks "Prova OK" once the proof is checked, and without it the order does not
|
|||||||
reach Finalizado.
|
reach Finalizado.
|
||||||
"""
|
"""
|
||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
|
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')
|
PROOF_ABOVE_METRES = Decimal('10')
|
||||||
CUSTOMER_NOTE = ('O cliente pediu uma prova antes de imprimir: mande a foto da prova pelo WhatsApp '
|
CUSTOMER_NOTE = ('O cliente pediu uma prova antes de imprimir: mande a foto da prova pelo WhatsApp '
|
||||||
@@ -24,3 +32,132 @@ def billed_metres(snapshot):
|
|||||||
def needs_proof(snapshot):
|
def needs_proof(snapshot):
|
||||||
"""Whether the order prints a proof first: asked for, or above 10 m."""
|
"""Whether the order prints a proof first: asked for, or above 10 m."""
|
||||||
return bool(snapshot.get('proof')) or billed_metres(snapshot) > PROOF_ABOVE_METRES
|
return bool(snapshot.get('proof')) or billed_metres(snapshot) > PROOF_ABOVE_METRES
|
||||||
|
|
||||||
|
|
||||||
|
# ---- The proof card (Dropstar's third round, 2026-10-30 and 2026-11-03) -----
|
||||||
|
#
|
||||||
|
# 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 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
|
||||||
|
PROVIDER = 'prova'
|
||||||
|
|
||||||
|
|
||||||
|
def proof_identity(order_id):
|
||||||
|
return uuid5(NAMESPACE_URL, f'dtf-proof:{order_id}')
|
||||||
|
|
||||||
|
|
||||||
|
def create_child(c, parent):
|
||||||
|
"""The parent's proof card, in Arte recebida, its proof sheets queued to be
|
||||||
|
generated. Returns it, or None when the order needs no proof."""
|
||||||
|
if parent.get('parent_id') or not needs_proof(parent['snapshot']):
|
||||||
|
return None
|
||||||
|
from .printjobs import queue
|
||||||
|
# A class has one proof. When several items share it, use the one with the
|
||||||
|
# finest measured line; no metre or product value is sold on this card.
|
||||||
|
classes = {}
|
||||||
|
for index, item in enumerate(parent['snapshot']['items']):
|
||||||
|
kind = item.get('stroke_class') or 'C3'
|
||||||
|
width = item.get('stroke_px') or 10000
|
||||||
|
if kind not in classes or width < classes[kind][0]:
|
||||||
|
classes[kind] = (width, index, item)
|
||||||
|
selected = [classes[kind] for kind in ('C1', 'C2', 'C3') if kind in classes][:MAX_PROOFS]
|
||||||
|
proof_items = [{**item, 'billed_metres': '0', 'total_cents': 0, 'unit_cents': 0,
|
||||||
|
'proof_parent_item_index': index} for _, index, item in selected]
|
||||||
|
freight = {**parent['snapshot'].get('freight', {}), 'total_cents': 0}
|
||||||
|
snapshot = {**parent['snapshot'], 'items': proof_items, 'total_cents': 0,
|
||||||
|
'freight': freight, 'proof_of': parent['number']}
|
||||||
|
child = c.execute('''INSERT INTO dtf_local.orders(id,owner,snapshot,payment,origin,parent_id,machine_id,machine_chosen)
|
||||||
|
VALUES(%s,%s,%s,%s,%s,%s,%s,%s) RETURNING *''',
|
||||||
|
(uuid4(), proof_identity(parent['id']), Jsonb(snapshot), Jsonb({'provider': PROVIDER}),
|
||||||
|
parent['origin'], parent['id'], parent.get('machine_id'), parent.get('machine_chosen', False))).fetchone()
|
||||||
|
queue(c, child['id'], len(snapshot['items']))
|
||||||
|
return child
|
||||||
|
|
||||||
|
|
||||||
|
def open_child(c, parent_id):
|
||||||
|
"""The parent's proof card still waiting for its answer, if any."""
|
||||||
|
return c.execute('''SELECT * FROM dtf_local.orders WHERE parent_id=%s AND proof_result IS NULL
|
||||||
|
AND cancelled_at IS NULL ORDER BY created_at DESC LIMIT 1''', (parent_id,)).fetchone()
|
||||||
|
|
||||||
|
|
||||||
|
def waiting(c, order):
|
||||||
|
"""Whether the order waits for its proof: it has a proof card without an OK."""
|
||||||
|
return not order.get('parent_id') and not order.get('proof_ok_at') and bool(open_child(c, order['id']))
|
||||||
|
|
||||||
|
|
||||||
|
def manual_source_needed(c, order):
|
||||||
|
"""A proof child cannot decode an original; prepare the full parent PNG first."""
|
||||||
|
if order.get('parent_id') or order['state'] != 'rec':
|
||||||
|
return False
|
||||||
|
child = open_child(c, order['id'])
|
||||||
|
return bool(child and c.execute('''SELECT 1 FROM dtf_local.print_files
|
||||||
|
WHERE order_id=%s AND status='manual' LIMIT 1''', (child['id'],)).fetchone())
|
||||||
|
|
||||||
|
|
||||||
|
def require_unlocked(c, order):
|
||||||
|
"""A parent cannot enter production or have its final changed before the proof answer."""
|
||||||
|
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
|
||||||
|
|||||||
155
app/prumo.py
Normal file
155
app/prumo.py
Normal file
@@ -0,0 +1,155 @@
|
|||||||
|
"""What the Prumo did to an order, in the order it happened (front 6).
|
||||||
|
|
||||||
|
The Site and the browser already make every decision; this module only turns
|
||||||
|
the fields they left on the order into the short report the designer reads
|
||||||
|
before opening the file. Nothing here changes an order or a price.
|
||||||
|
"""
|
||||||
|
from datetime import datetime
|
||||||
|
from decimal import Decimal
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
|
LOCAL = ZoneInfo('America/Sao_Paulo')
|
||||||
|
MANUAL = {'cdr', 'psd', 'psb', 'tif', 'tiff'}
|
||||||
|
# The stroke class in the customer's words, without the internal C1/C2/C3 code.
|
||||||
|
STROKE_SUMMARY = {
|
||||||
|
'C1': 'Sua arte tem traços muito finos; a impressão foi ajustada para eles.',
|
||||||
|
'C2': 'Sua arte tem traços médios; a impressão foi ajustada para eles.',
|
||||||
|
'C3': 'Sua arte tem áreas cheias; a impressão foi ajustada para elas.',
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _ext(name):
|
||||||
|
return (str(name or '').rsplit('.', 1)[-1] if '.' in str(name or '') else '').lower()
|
||||||
|
|
||||||
|
|
||||||
|
def _m(value):
|
||||||
|
try:
|
||||||
|
return f'{Decimal(str(value)):.2f}'.replace('.', ',')
|
||||||
|
except Exception:
|
||||||
|
return str(value)
|
||||||
|
|
||||||
|
|
||||||
|
def _cm(value):
|
||||||
|
try:
|
||||||
|
return f'{Decimal(str(value)):.1f}'.replace('.', ',')
|
||||||
|
except Exception:
|
||||||
|
return str(value)
|
||||||
|
|
||||||
|
|
||||||
|
def _hora(value):
|
||||||
|
if not value:
|
||||||
|
return ''
|
||||||
|
try:
|
||||||
|
moment = value if isinstance(value, datetime) else datetime.fromisoformat(str(value).replace('Z', '+00:00'))
|
||||||
|
return ' às ' + moment.astimezone(LOCAL).strftime('%H:%M')
|
||||||
|
except Exception:
|
||||||
|
return ''
|
||||||
|
|
||||||
|
|
||||||
|
def report(order, uploads):
|
||||||
|
"""One line per action that happened, for the card and the customer.
|
||||||
|
|
||||||
|
`uploads` maps an upload id (as text) to a row with `name` and
|
||||||
|
`original_name`. `order` is the order row with its snapshot and generated
|
||||||
|
print files.
|
||||||
|
"""
|
||||||
|
snapshot = order.get('snapshot') or {}
|
||||||
|
items = snapshot.get('items') or []
|
||||||
|
generated = {row.get('item_index'): row for row in (order.get('print_files') or [])}
|
||||||
|
lines = []
|
||||||
|
if snapshot.get('proof_of'):
|
||||||
|
lines.append(f'Prova do pedido #{snapshot["proof_of"]}')
|
||||||
|
multi = len(items) > 1
|
||||||
|
for index, item in enumerate(items):
|
||||||
|
lead = f'Item {index + 1}: ' if multi else ''
|
||||||
|
names = []
|
||||||
|
for uid in item.get('uploads') or []:
|
||||||
|
row = uploads.get(str(uid)) or {}
|
||||||
|
original = row.get('original_name') or row.get('name') or ''
|
||||||
|
final = row.get('name') or original
|
||||||
|
names.append(final)
|
||||||
|
if original and final and _ext(original) != _ext(final):
|
||||||
|
lines.append(f'{lead}Chegou {_ext(original).upper()}, era {_ext(final).upper()} por dentro — tratado como {_ext(final).upper()}')
|
||||||
|
# One format line per item, not one per file: the designer reads what
|
||||||
|
# the item is, and only the files that changed are named above.
|
||||||
|
formats = sorted({_ext(name).upper() or 'desconhecido' for name in names})
|
||||||
|
if len(formats) == 1:
|
||||||
|
count = f' ({len(names)} arquivos)' if len(names) > 1 else ''
|
||||||
|
lines.append(f'{lead}Formato detectado: {formats[0]}{count}')
|
||||||
|
elif formats:
|
||||||
|
lines.append(f'{lead}Formatos detectados: {", ".join(formats)}')
|
||||||
|
exts = {_ext(name) for name in names}
|
||||||
|
row = generated.get(index)
|
||||||
|
ready = bool(row and row.get('status') == 'ready')
|
||||||
|
if row and row.get('status') == 'manual':
|
||||||
|
lines.append(f'{lead}Arquivo exige preparo manual')
|
||||||
|
dpi = item.get('source_dpi')
|
||||||
|
if dpi:
|
||||||
|
lines.append(f'{lead}Resolução detectada: {dpi} DPI')
|
||||||
|
if ready:
|
||||||
|
detail = row.get('detail') or {}
|
||||||
|
if exts & {'pdf', 'ai'} and detail.get('format') == 'png':
|
||||||
|
lines.append(f'{lead}PDF → PNG {detail.get("dpi", 300)} DPI')
|
||||||
|
elif detail.get('format'):
|
||||||
|
lines.append(f'{lead}Arquivo final em {detail["format"].upper()} {detail.get("dpi", 300)} DPI')
|
||||||
|
dots = int(item.get('residue_accepted') or 0)
|
||||||
|
if dots:
|
||||||
|
lines.append(f'{lead}{dots} ponto{"s" if dots > 1 else ""} < 2 mm — cliente aceitou' +
|
||||||
|
_hora(item.get('residue_accepted_at')))
|
||||||
|
production = item.get('production') or {}
|
||||||
|
placements = production.get('placements') or []
|
||||||
|
if item.get('mode') in ('avulsa', 'uv'):
|
||||||
|
rotated = sum(1 for p in placements if p.get('rotation_degrees') in (90, 270))
|
||||||
|
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 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)')
|
||||||
|
elif item.get('stroke_choice') == 'measured':
|
||||||
|
lines.append(f'{lead}Aviso de traço fino disparou — cliente escolheu imprimir em C1')
|
||||||
|
else:
|
||||||
|
lines.append(f'{lead}Aviso de traço fino não disparou')
|
||||||
|
if row:
|
||||||
|
detail = row.get('detail') or {}
|
||||||
|
parts = detail.get('parts') or []
|
||||||
|
if len(parts) > 1:
|
||||||
|
sizes = [Decimal(str(p.get('to_cm', 0))) - Decimal(str(p.get('from_cm', 0))) for p in parts]
|
||||||
|
lines.append(f'{lead}{_m(billed)} m → {len(parts)} partes (' +
|
||||||
|
' + '.join(_m(size) for size in sizes) + ')')
|
||||||
|
# From the claim, not from the queue: the customer waits for the
|
||||||
|
# generation, not for the file's turn.
|
||||||
|
if ready and row.get('finished_at') and row.get('claimed_at'):
|
||||||
|
seconds = (row['finished_at'] - row['claimed_at']).total_seconds()
|
||||||
|
lines.append(f'{lead}Prumo levou {max(1, round(seconds))} s')
|
||||||
|
return lines
|
||||||
|
|
||||||
|
|
||||||
|
def customer_summary(items):
|
||||||
|
"""The same facts in the customer's words, for the summary before paying."""
|
||||||
|
lines = []
|
||||||
|
for index, item in enumerate(items or []):
|
||||||
|
lead = f'Item {index + 1}: ' if len(items) > 1 else ''
|
||||||
|
dpi = item.get('source_dpi')
|
||||||
|
if dpi and dpi < 300:
|
||||||
|
lines.append(f'{lead}Sua arte foi medida em {dpi} DPI. O arquivo de impressão será preparado em 300 DPI após o pagamento.')
|
||||||
|
dots = int(item.get('residue_accepted') or 0)
|
||||||
|
if dots:
|
||||||
|
lines.append(f'{lead}Há {dots} pontinho{"s" if dots > 1 else ""} solto{"s" if dots > 1 else ""} '
|
||||||
|
'que você aceitou imprimir.')
|
||||||
|
if item.get('stroke_class') in STROKE_SUMMARY:
|
||||||
|
lines.append(f'{lead}{STROKE_SUMMARY[item["stroke_class"]]}')
|
||||||
|
if item.get('stroke_choice') == 'measured':
|
||||||
|
lines.append(f'{lead}Você escolheu imprimir o traço fino assim mesmo (C1).')
|
||||||
|
elif item.get('stroke_choice') == 'client_c3':
|
||||||
|
lines.append(f'{lead}Você escolheu proteger as áreas chapadas (C3).')
|
||||||
|
return lines
|
||||||
@@ -19,10 +19,9 @@ from decimal import Decimal
|
|||||||
from fastapi import HTTPException
|
from fastapi import HTTPException
|
||||||
from psycopg.types.json import Jsonb
|
from psycopg.types.json import Jsonb
|
||||||
|
|
||||||
from . import payments
|
from . import cart_pricing, payments
|
||||||
from .proof import PROOF_ABOVE_METRES
|
from .proof import PROOF_ABOVE_METRES
|
||||||
from .core.models import PRODUCTION_VERSIONS
|
from .core.models import PRODUCTION_VERSIONS
|
||||||
from .core.pricing import is_manual, manual_extra_cents, price
|
|
||||||
from .runtime import freight, upload_row
|
from .runtime import freight, upload_row
|
||||||
from .scanning import require_clean
|
from .scanning import require_clean
|
||||||
|
|
||||||
@@ -60,34 +59,72 @@ def approve(c, row, items, reviewer):
|
|||||||
raise HTTPException(409, 'A cotação usa uma montagem antiga: o cliente precisa montar o pedido de novo.')
|
raise HTTPException(409, 'A cotação usa uma montagem antiga: o cliente precisa montar o pedido de novo.')
|
||||||
if len(items) != len(draft['items']):
|
if len(items) != len(draft['items']):
|
||||||
raise HTTPException(422, 'Confira todos os itens da cotação.')
|
raise HTTPException(422, 'Confira todos os itens da cotação.')
|
||||||
priced = []
|
names = {}
|
||||||
for item, original in zip(items, draft['items']):
|
for item, original in zip(items, draft['items']):
|
||||||
if item.mode != original['mode'] or list(map(str, item.uploads)) != original['uploads']:
|
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.')
|
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):
|
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.')
|
raise HTTPException(422, 'A montagem e a confirmação do cliente não podem mudar na revisão.')
|
||||||
names = {}
|
|
||||||
for upload_id in item.uploads:
|
for upload_id in item.uploads:
|
||||||
upload = upload_row(c, upload_id, row['owner'])
|
upload = upload_row(c, upload_id, row['owner'])
|
||||||
require_clean(upload)
|
require_clean(upload)
|
||||||
names[str(upload_id)] = upload['name']
|
names[str(upload_id)] = upload['name']
|
||||||
extra = manual_extra_cents() if is_manual(original, names) else 0
|
# The montador assembles the sheet itself: the treatment rule does not apply.
|
||||||
priced.append({**price(item.mode, str(item.metres), item.grade, extra),
|
cart = cart_pricing.price_cart(
|
||||||
|
c, [item.model_dump(mode='json') for item in items], names,
|
||||||
|
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']
|
||||||
|
for priced_item, original in zip(priced, draft['items']):
|
||||||
|
priced_item.update({
|
||||||
'uploads': original['uploads'], 'production': original['production'],
|
'uploads': original['uploads'], 'production': original['production'],
|
||||||
'quality_status': original['quality_status'],
|
'quality_status': original['quality_status'],
|
||||||
'quality_acknowledged': original['quality_acknowledged'],
|
'quality_acknowledged': original['quality_acknowledged'],
|
||||||
'residue_accepted': original.get('residue_accepted', 0)})
|
'residue_accepted': original.get('residue_accepted', 0),
|
||||||
|
**({'residue_accepted_at': original['residue_accepted_at']}
|
||||||
|
if original.get('residue_accepted_at') else {}),
|
||||||
|
**({'stroke_px': original['stroke_px'], 'stroke_class': original['stroke_class']}
|
||||||
|
if original.get('stroke_class') else {}),
|
||||||
|
**({'stroke_choice': original['stroke_choice']} if original.get('stroke_choice') else {}),
|
||||||
|
**({'stroke_choice_at': original['stroke_choice_at']}
|
||||||
|
if original.get('stroke_choice_at') else {}),
|
||||||
|
**({'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)
|
metres = sum(Decimal(i['billed_metres']) for i in priced)
|
||||||
try:
|
try:
|
||||||
quoted_freight = freight.quote(draft['freight']['service'], draft['freight'].get('postal_code', ''),
|
quoted_freight = freight.quote(draft['freight']['service'], draft['freight'].get('postal_code', ''),
|
||||||
metres, sum(i['total_cents'] for i in priced))
|
metres, items_total)
|
||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
raise HTTPException(422, str(exc))
|
raise HTTPException(422, str(exc))
|
||||||
approved = {'customer': draft['customer'], 'items': priced, 'freight': quoted_freight,
|
approved = {'customer': draft['customer'], 'items': priced, 'freight': quoted_freight,
|
||||||
'destination': draft.get('destination'),
|
'destination': draft.get('destination'),
|
||||||
# The customer's proof only above 10 m (Dropstar, 2026-10-28).
|
# The customer's proof only above 10 m (Dropstar, 2026-10-28).
|
||||||
**({'proof': True} if draft.get('proof') and metres > PROOF_ABOVE_METRES else {}),
|
**({'proof': True} if draft.get('proof') and metres > PROOF_ABOVE_METRES else {}),
|
||||||
'total_cents': sum(i['total_cents'] for i in priced) + quoted_freight['total_cents']}
|
# 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).
|
||||||
|
**({'coupon': coupon} if coupon else {}),
|
||||||
|
# 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) + redesign.get('cents', 0)}
|
||||||
c.execute('UPDATE dtf_local.quotes SET approved=%s, reviewed_by=%s, approved_at=now() WHERE id=%s',
|
c.execute('UPDATE dtf_local.quotes SET approved=%s, reviewed_by=%s, approved_at=now() WHERE id=%s',
|
||||||
(Jsonb(approved), reviewer, row['id']))
|
(Jsonb(approved), reviewer, row['id']))
|
||||||
# Approved and payable now: the files wait for the payment, not for ever.
|
# Approved and payable now: the files wait for the payment, not for ever.
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import io
|
|||||||
import unicodedata
|
import unicodedata
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
|
from .core.pricing import sheet_label
|
||||||
from .printfile import Name, PdfWriter, deflate, serialize, _HELVETICA, _HELVETICA_BOLD
|
from .printfile import Name, PdfWriter, deflate, serialize, _HELVETICA, _HELVETICA_BOLD
|
||||||
from .printjobs import LOCAL, file_prefix
|
from .printjobs import LOCAL, file_prefix
|
||||||
|
|
||||||
@@ -20,7 +21,8 @@ MARGIN = 4 * MM
|
|||||||
ROOM = WIDTH - 2 * MARGIN
|
ROOM = WIDTH - 2 * MARGIN
|
||||||
FONTS = {'F1': 'Helvetica-Bold', 'F2': 'Helvetica'}
|
FONTS = {'F1': 'Helvetica-Bold', 'F2': 'Helvetica'}
|
||||||
PRODUCTS = {'file': 'DTF Têxtil · folha montada', 'avulsa': 'DTF Têxtil · artes avulsas',
|
PRODUCTS = {'file': 'DTF Têxtil · folha montada', 'avulsa': 'DTF Têxtil · artes avulsas',
|
||||||
'uvfile': 'DTF UV · folha montada', 'uv': 'DTF UV · artes avulsas'}
|
'uvfile': 'DTF UV · folha montada', 'uv': 'DTF UV · artes avulsas',
|
||||||
|
'premium': 'DTF Têxtil Premium · folha montada'}
|
||||||
METHODS = {'pix': 'Pix', 'card': 'Cartão', 'cash': 'Dinheiro', 'credit': 'Crédito do cliente'}
|
METHODS = {'pix': 'Pix', 'card': 'Cartão', 'cash': 'Dinheiro', 'credit': 'Crédito do cliente'}
|
||||||
# Helvetica's widths for what the tables in printfile.py leave out.
|
# Helvetica's widths for what the tables in printfile.py leave out.
|
||||||
EXTRA = {'$': 556, '(': 333, ')': 333, '_': 556, '#': 556, '—': 1000, '@': 1015, '&': 667, '+': 584, "'": 191}
|
EXTRA = {'$': 556, '(': 333, ')': 333, '_': 556, '#': 556, '—': 1000, '@': 1015, '&': 667, '+': 584, "'": 191}
|
||||||
@@ -95,7 +97,10 @@ def lines(order, paid_with, issued):
|
|||||||
out.append(('Produto', 7.5, False, 10))
|
out.append(('Produto', 7.5, False, 10))
|
||||||
for item in snapshot.get('items') or []:
|
for item in snapshot.get('items') or []:
|
||||||
metres = str(item.get('billed_metres') or item.get('metres') or '').replace('.', ',')
|
metres = str(item.get('billed_metres') or item.get('metres') or '').replace('.', ',')
|
||||||
out += [(part, 9.5, False, 2) for part in wrap(f"{PRODUCTS.get(item.get('mode'), item.get('mode'))} — {metres} m", 9.5)]
|
out += [(part, 9.5, False, 2) for part in wrap(f"{PRODUCTS.get(item.get('mode'), item.get('mode'))}{sheet_label(item)} — {metres} m", 9.5)]
|
||||||
|
coupon = snapshot.get('coupon') or {}
|
||||||
|
if coupon:
|
||||||
|
out.append((f"Cupom {coupon.get('code', '')}: - {money(coupon.get('discount_cents') or 0)}", 9, False, 4))
|
||||||
out += [('Valor', 7.5, False, 10), (money(snapshot.get('total_cents') or 0), 12, True, 1),
|
out += [('Valor', 7.5, False, 10), (money(snapshot.get('total_cents') or 0), 12, True, 1),
|
||||||
('Pagamento', 7.5, False, 6), (METHODS.get(paid_with, 'Teste' if paid_with == 'teste' else paid_with or '—'), 10, False, 1),
|
('Pagamento', 7.5, False, 6), (METHODS.get(paid_with, 'Teste' if paid_with == 'teste' else paid_with or '—'), 10, False, 1),
|
||||||
(f"Emitido em {issued.astimezone(LOCAL).strftime('%d/%m/%Y %H:%M')}", 8.5, False, 10),
|
(f"Emitido em {issued.astimezone(LOCAL).strftime('%d/%m/%Y %H:%M')}", 8.5, False, 10),
|
||||||
|
|||||||
131
app/reviews.py
Normal file
131
app/reviews.py
Normal file
@@ -0,0 +1,131 @@
|
|||||||
|
"""The review photo or video of the printed sheet (Fase 2, front 2).
|
||||||
|
|
||||||
|
In Revisão the card gets "Revisar": the Revisor takes a photo or a short video
|
||||||
|
(up to 30 s) of the sheet with the computer's or the phone's camera in the
|
||||||
|
browser, or sends one already recorded. It is attached to the order as
|
||||||
|
DTF-<n>-revisao-<seq>.<ext>, with when and who (dtf_local.order_reviews), and
|
||||||
|
the computers with the order folders turned on copy it to Kanban/Revisões/.
|
||||||
|
An order above 1 m cannot reach Finalizado without a photo; a smaller one may.
|
||||||
|
Once the order is in Finalizado, the customer's order page shows the photos
|
||||||
|
(the "ready" notice links to it). Videos stay on the card.
|
||||||
|
|
||||||
|
Kept for REVIEW_KEEP_DAYS, longer than artwork: it is the evidence when a
|
||||||
|
customer says the sheet came out wrong.
|
||||||
|
"""
|
||||||
|
from decimal import Decimal
|
||||||
|
|
||||||
|
from fastapi import HTTPException
|
||||||
|
|
||||||
|
from . import grade_check
|
||||||
|
from .proof import billed_metres
|
||||||
|
|
||||||
|
PHOTO_MIN_PX = 1600 # the longer side; enough to read the footer
|
||||||
|
VIDEO_MAX_SECONDS = 30 # enforced by the recorder and the file check in the browser
|
||||||
|
PHOTO_MAX_BYTES = 30 * 1048576
|
||||||
|
VIDEO_MAX_BYTES = 150 * 1048576
|
||||||
|
REQUIRED_ABOVE_METRES = Decimal('1')
|
||||||
|
REVIEW_KEEP_DAYS = 180
|
||||||
|
FOLDER = 'Revisões'
|
||||||
|
# Extension -> (kind, MIME). HEIC is left out: browsers cannot show it.
|
||||||
|
FORMATS = {'jpg': ('photo', 'image/jpeg'), 'jpeg': ('photo', 'image/jpeg'),
|
||||||
|
'png': ('photo', 'image/png'), 'webp': ('photo', 'image/webp'),
|
||||||
|
'mp4': ('video', 'video/mp4'), 'webm': ('video', 'video/webm'),
|
||||||
|
'mov': ('video', 'video/quicktime')}
|
||||||
|
|
||||||
|
|
||||||
|
def file_name(number, seq, ext):
|
||||||
|
"""DTF-13-revisao-1.jpg: the name in the folder and on the card."""
|
||||||
|
return f'DTF-{number}-revisao-{seq}.{ext}'
|
||||||
|
|
||||||
|
|
||||||
|
FORMAT_MESSAGE = ('Use foto JPG, PNG ou WebP de até 30 MB, ou vídeo MP4, WebM ou MOV de até 150 MB.')
|
||||||
|
# What each extension must start with. MP4 and MOV share the ISO container:
|
||||||
|
# the "ftyp" box sits at byte 4.
|
||||||
|
SIGNATURES = {'jpg': (b'\xff\xd8\xff', 0), 'jpeg': (b'\xff\xd8\xff', 0),
|
||||||
|
'png': (b'\x89PNG\r\n\x1a\n', 0),
|
||||||
|
'webp': (b'WEBP', 8),
|
||||||
|
'mp4': (b'ftyp', 4), 'mov': (b'ftyp', 4),
|
||||||
|
'webm': (b'\x1a\x45\xdf\xa3', 0)}
|
||||||
|
|
||||||
|
|
||||||
|
def kind_of(name, size):
|
||||||
|
"""('photo' | 'video', mime, ext) for an accepted file, or HTTPException 422
|
||||||
|
with a Portuguese message naming the accepted formats and size limits."""
|
||||||
|
ext = name.rsplit('.', 1)[-1].lower() if '.' in name else ''
|
||||||
|
if ext not in FORMATS:
|
||||||
|
raise HTTPException(422, FORMAT_MESSAGE)
|
||||||
|
kind, mime = FORMATS[ext]
|
||||||
|
limit = PHOTO_MAX_BYTES if kind == 'photo' else VIDEO_MAX_BYTES
|
||||||
|
if size > limit:
|
||||||
|
raise HTTPException(422, FORMAT_MESSAGE)
|
||||||
|
return kind, mime, ext
|
||||||
|
|
||||||
|
|
||||||
|
def check(storage, upload):
|
||||||
|
"""Read the start of the stored file (a Range read, as grade_check.Files.head)
|
||||||
|
and confirm its signature matches the extension. For a photo, return its
|
||||||
|
(width, height) and refuse (422) when the longer side is below PHOTO_MIN_PX;
|
||||||
|
for a video, return (None, None). Returns (kind, ext, width, height)."""
|
||||||
|
kind, mime, ext = kind_of(upload['name'], upload['size'])
|
||||||
|
head = storage.client.get_object(Bucket=storage.bucket, Key=upload['object_key'],
|
||||||
|
Range=f'bytes=0-{grade_check.HEAD_BYTES - 1}')['Body'].read()
|
||||||
|
# WebP is a RIFF container with its own form type, like the scanner's check.
|
||||||
|
if ext == 'webp':
|
||||||
|
matches = head[:4] == b'RIFF' and head[8:12] == b'WEBP'
|
||||||
|
else:
|
||||||
|
signature, offset = SIGNATURES[ext]
|
||||||
|
matches = head[offset:].startswith(signature)
|
||||||
|
if not matches:
|
||||||
|
raise HTTPException(422, 'O conteúdo do arquivo não corresponde à extensão.')
|
||||||
|
if kind == 'video':
|
||||||
|
return kind, ext, None, None
|
||||||
|
size = grade_check.image_size(head)
|
||||||
|
if not size or not all(size):
|
||||||
|
raise HTTPException(422, 'Não foi possível ler a foto.')
|
||||||
|
width, height = size
|
||||||
|
if max(width, height) < PHOTO_MIN_PX:
|
||||||
|
raise HTTPException(422, f'A foto precisa ter pelo menos {PHOTO_MIN_PX} px no lado maior para ler o rodapé.')
|
||||||
|
return kind, ext, width, height
|
||||||
|
|
||||||
|
|
||||||
|
def required(snapshot):
|
||||||
|
"""Whether finishing this order needs a review photo: billed metres above
|
||||||
|
REQUIRED_ABOVE_METRES (proof.billed_metres)."""
|
||||||
|
return billed_metres(snapshot) > REQUIRED_ABOVE_METRES
|
||||||
|
|
||||||
|
|
||||||
|
def has_photo(c, order_id):
|
||||||
|
return c.execute("SELECT 1 FROM dtf_local.order_reviews WHERE order_id=%s AND kind='photo' LIMIT 1",
|
||||||
|
(order_id,)).fetchone() is not None
|
||||||
|
|
||||||
|
|
||||||
|
def attach(c, order, upload, kind, ext, width, height, user):
|
||||||
|
"""Record the review: the next seq for the order, the upload renamed to
|
||||||
|
file_name(...) and kept REVIEW_KEEP_DAYS from now. Returns the new row."""
|
||||||
|
# The order's row is the lock: two reviewers adding at once take one seq
|
||||||
|
# each, never the same one.
|
||||||
|
c.execute('SELECT id FROM dtf_local.orders WHERE id=%s FOR UPDATE', (order['id'],))
|
||||||
|
seq = c.execute('SELECT COALESCE(max(seq),0)+1 AS seq FROM dtf_local.order_reviews WHERE order_id=%s',
|
||||||
|
(order['id'],)).fetchone()['seq']
|
||||||
|
name = file_name(order['number'], seq, ext)
|
||||||
|
c.execute("UPDATE dtf_local.uploads SET name=%s, expires_at=now()+make_interval(days => %s) WHERE id=%s",
|
||||||
|
(name, REVIEW_KEEP_DAYS, upload['id']))
|
||||||
|
row = c.execute('''INSERT INTO dtf_local.order_reviews(order_id,seq,upload_id,kind,width,height,created_by)
|
||||||
|
VALUES(%s,%s,%s,%s,%s,%s,%s) RETURNING *''',
|
||||||
|
(order['id'], seq, upload['id'], kind, width, height, user)).fetchone()
|
||||||
|
return {**row, 'name': name}
|
||||||
|
|
||||||
|
|
||||||
|
def by_order(c, order_ids):
|
||||||
|
"""{order_id (str): [ {id, seq, kind, name, width, height, created_by,
|
||||||
|
created_at}, ... ]} in seq order, for the board."""
|
||||||
|
if not order_ids:
|
||||||
|
return {}
|
||||||
|
rows = c.execute('''SELECT r.id,r.order_id,r.seq,r.kind,r.width,r.height,r.created_by,r.created_at,u.name
|
||||||
|
FROM dtf_local.order_reviews r JOIN dtf_local.uploads u ON u.id=r.upload_id
|
||||||
|
WHERE r.order_id=ANY(%s) ORDER BY r.order_id,r.seq''', (order_ids,)).fetchall()
|
||||||
|
out = {}
|
||||||
|
for row in rows:
|
||||||
|
out.setdefault(str(row['order_id']), []).append(
|
||||||
|
{key: row[key] for key in ('id', 'seq', 'kind', 'name', 'width', 'height', 'created_by', 'created_at')})
|
||||||
|
return out
|
||||||
@@ -12,6 +12,7 @@ from uuid import uuid5, NAMESPACE_URL
|
|||||||
from fastapi import HTTPException
|
from fastapi import HTTPException
|
||||||
from psycopg.types.json import Jsonb
|
from psycopg.types.json import Jsonb
|
||||||
|
|
||||||
|
from . import catalog
|
||||||
from .adapters import FakeFreight, FakePayment, LocalS3Storage, require_runtime
|
from .adapters import FakeFreight, FakePayment, LocalS3Storage, require_runtime
|
||||||
from .freight import FreightOptions
|
from .freight import FreightOptions
|
||||||
from .core.secrets import load as load_secret_files
|
from .core.secrets import load as load_secret_files
|
||||||
@@ -32,6 +33,7 @@ if os.environ.get('FREIGHT_ADAPTER') == 'jadlog':
|
|||||||
from .jadlog import JadlogFreight
|
from .jadlog import JadlogFreight
|
||||||
_carriers.append(JadlogFreight())
|
_carriers.append(JadlogFreight())
|
||||||
from . import correios as _correios
|
from . import correios as _correios
|
||||||
|
from . import prumo
|
||||||
if _correios.configured():
|
if _correios.configured():
|
||||||
_carriers.append(_correios.CorreiosFreight())
|
_carriers.append(_correios.CorreiosFreight())
|
||||||
freight = FreightOptions(_carriers or [FakeFreight()])
|
freight = FreightOptions(_carriers or [FakeFreight()])
|
||||||
@@ -103,8 +105,25 @@ def order_code(order_id):
|
|||||||
return str(order_id).replace('-', '')[:8].upper()
|
return str(order_id).replace('-', '')[:8].upper()
|
||||||
|
|
||||||
|
|
||||||
def quote_view(c, row):
|
def quote_views(c, rows):
|
||||||
|
"""quote_view for a list of quotes, in two queries whatever its length: the
|
||||||
|
board shows up to 240 quotes, and asking per quote made 480 queries."""
|
||||||
|
ids = [row['id'] for row in rows]
|
||||||
|
if not ids:
|
||||||
|
return []
|
||||||
|
orders = {r['quote_id']: {k: r[k] for k in ('id', 'number', 'state')} for r in c.execute(
|
||||||
|
'SELECT quote_id,id,number,state FROM dtf_local.orders WHERE quote_id=ANY(%s)', (ids,)).fetchall()}
|
||||||
|
attempts = {r['quote_id']: {k: r[k] for k in ('method', 'status', 'status_detail', 'expires_at', 'created_at')}
|
||||||
|
for r in c.execute('''SELECT DISTINCT ON (quote_id) quote_id,method,status,
|
||||||
|
response->>'status_detail' AS status_detail, response->>'expires_at' AS expires_at, created_at
|
||||||
|
FROM dtf_local.payment_intents WHERE quote_id=ANY(%s) ORDER BY quote_id, created_at DESC''', (ids,)).fetchall()}
|
||||||
|
return [quote_view(c, row, order=orders.get(row['id']), attempt=attempts.get(row['id']), known=True) for row in rows]
|
||||||
|
|
||||||
|
|
||||||
|
def quote_view(c, row, order=None, attempt=None, known=False):
|
||||||
from .quote_review import review_reason # it imports this module
|
from .quote_review import review_reason # it imports this module
|
||||||
|
from .payments import QUOTE_VALID_HOURS # it imports this module too
|
||||||
|
if not known:
|
||||||
order = c.execute('SELECT id,number,state FROM dtf_local.orders WHERE quote_id=%s', (row['id'],)).fetchone()
|
order = c.execute('SELECT id,number,state FROM dtf_local.orders WHERE quote_id=%s', (row['id'],)).fetchone()
|
||||||
# The latest payment attempt, so the payment page can tell a refused card
|
# The latest payment attempt, so the payment page can tell a refused card
|
||||||
# (the notification updates it) from one still waiting.
|
# (the notification updates it) from one still waiting.
|
||||||
@@ -115,9 +134,28 @@ def quote_view(c, row):
|
|||||||
if attempt and attempt['status'] == 'rejected':
|
if attempt and attempt['status'] == 'rejected':
|
||||||
from .payment_messages import rejection
|
from .payment_messages import rejection
|
||||||
attempt = {**attempt, 'message': rejection(attempt['status_detail'])}
|
attempt = {**attempt, 'message': rejection(attempt['status_detail'])}
|
||||||
expired = row['approved_at'] and row['approved_at'] < datetime.now(timezone.utc)-timedelta(hours=24)
|
expires_at = (row['approved_at'] + timedelta(hours=QUOTE_VALID_HOURS)
|
||||||
|
if row['approved_at'] else None)
|
||||||
|
expired = (bool(row.get('expired_at')) or
|
||||||
|
bool(row['approved_at'] and row['approved_at'] <
|
||||||
|
datetime.now(timezone.utc)-timedelta(hours=QUOTE_VALID_HOURS)))
|
||||||
|
items = (row['approved'] or row['draft']).get('items') or []
|
||||||
|
treatment = (row['approved'] or {}).get('treatment')
|
||||||
|
if not treatment and (row['draft'] or {}).get('treatment'):
|
||||||
|
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'],
|
return {'id': row['id'], 'created_at': row['created_at'],
|
||||||
'draft': row['draft'], 'approved': row['approved'],
|
'draft': row['draft'], 'approved': row['approved'],
|
||||||
|
'expires_at': expires_at.isoformat() if expires_at else None,
|
||||||
|
'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
|
'status': 'paid' if order else 'discarded' if row.get('discarded_at') else 'expired' if expired
|
||||||
else 'approved' if row['approved'] else 'pending_review',
|
else 'approved' if row['approved'] else 'pending_review',
|
||||||
'auto_approved': row.get('reviewed_by') == 'auto',
|
'auto_approved': row.get('reviewed_by') == 'auto',
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ are those of the format its name claims (a PNG that really is a PNG, not a
|
|||||||
program renamed .png). That is the check the client chose for large files; it
|
program renamed .png). That is the check the client chose for large files; it
|
||||||
does not look for malware inside a valid file.
|
does not look for malware inside a valid file.
|
||||||
"""
|
"""
|
||||||
|
import logging
|
||||||
import re
|
import re
|
||||||
import socket
|
import socket
|
||||||
import struct
|
import struct
|
||||||
@@ -16,6 +17,7 @@ from fastapi import HTTPException
|
|||||||
from .core.auth import audit
|
from .core.auth import audit
|
||||||
from .core.db import connect
|
from .core.db import connect
|
||||||
from .core.limits import scan_limit_bytes
|
from .core.limits import scan_limit_bytes
|
||||||
|
from .grade_check import stored_pdf_dpi
|
||||||
|
|
||||||
def require_clean(row):
|
def require_clean(row):
|
||||||
if not row['complete'] or row['scan_state'] != 'clean':
|
if not row['complete'] or row['scan_state'] != 'clean':
|
||||||
@@ -144,11 +146,22 @@ def scan_one(storage, scanner=None):
|
|||||||
finally:stream.close()
|
finally:stream.close()
|
||||||
except Exception:
|
except Exception:
|
||||||
state,reason='error','Malware scanner unavailable; file remains blocked'
|
state,reason='error','Malware scanner unavailable; file remains blocked'
|
||||||
|
# A PDF's resolution is worked out here, once, so checkout never reads
|
||||||
|
# it (Critical Corrections 2). A failure leaves it for the fallback.
|
||||||
|
checked,pdf_dpi_value=False,None
|
||||||
|
if state=='clean' and name.lower().endswith('.pdf'):
|
||||||
|
try:
|
||||||
|
pdf_dpi_value=stored_pdf_dpi(storage,row)
|
||||||
|
checked=True
|
||||||
|
except Exception:
|
||||||
|
logging.exception('Could not work out the PDF DPI of upload %s',row['id'])
|
||||||
c.execute("""UPDATE dtf_local.uploads SET name=%s,scan_state=%s,scan_reason=%s,scanned_at=now(),
|
c.execute("""UPDATE dtf_local.uploads SET name=%s,scan_state=%s,scan_reason=%s,scanned_at=now(),
|
||||||
scan_after=now()+interval '1 minute',
|
scan_after=now()+interval '1 minute',
|
||||||
|
pdf_checked=CASE WHEN %s THEN true ELSE pdf_checked END,
|
||||||
|
pdf_dpi=CASE WHEN %s THEN %s ELSE pdf_dpi END,
|
||||||
expires_at=CASE WHEN %s IN ('rejected','error') THEN LEAST(expires_at,now()+interval '3 days') ELSE expires_at END
|
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,state,row['id']))
|
WHERE id=%s""",(name,state,reason,checked,checked,pdf_dpi_value,state,row['id']))
|
||||||
audit('artwork_scan', upload=str(row['id']), result=state)
|
audit('artwork_scan', upload=str(row['id']), result=state, c=c)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def scan_loop(storage):
|
def scan_loop(storage):
|
||||||
|
|||||||
268
app/schema.sql
268
app/schema.sql
@@ -80,6 +80,8 @@ CREATE TABLE IF NOT EXISTS dtf_local.security_events (
|
|||||||
);
|
);
|
||||||
ALTER TABLE dtf_local.uploads ADD COLUMN IF NOT EXISTS expires_at timestamptz;
|
ALTER TABLE dtf_local.uploads ADD COLUMN IF NOT EXISTS expires_at timestamptz;
|
||||||
ALTER TABLE dtf_local.uploads ADD COLUMN IF NOT EXISTS purged_at timestamptz;
|
ALTER TABLE dtf_local.uploads ADD COLUMN IF NOT EXISTS purged_at timestamptz;
|
||||||
|
ALTER TABLE dtf_local.uploads ADD COLUMN IF NOT EXISTS original_name text;
|
||||||
|
UPDATE dtf_local.uploads SET original_name=name WHERE original_name IS NULL;
|
||||||
ALTER TABLE dtf_local.uploads ADD COLUMN IF NOT EXISTS scan_state text NOT NULL DEFAULT 'pending';
|
ALTER TABLE dtf_local.uploads ADD COLUMN IF NOT EXISTS scan_state text NOT NULL DEFAULT 'pending';
|
||||||
ALTER TABLE dtf_local.uploads ADD COLUMN IF NOT EXISTS scan_reason text;
|
ALTER TABLE dtf_local.uploads ADD COLUMN IF NOT EXISTS scan_reason text;
|
||||||
ALTER TABLE dtf_local.uploads ADD COLUMN IF NOT EXISTS scanned_at timestamptz;
|
ALTER TABLE dtf_local.uploads ADD COLUMN IF NOT EXISTS scanned_at timestamptz;
|
||||||
@@ -136,6 +138,7 @@ CREATE TABLE IF NOT EXISTS dtf_local.print_files (
|
|||||||
created_at timestamptz NOT NULL DEFAULT now(), finished_at timestamptz,
|
created_at timestamptz NOT NULL DEFAULT now(), finished_at timestamptz,
|
||||||
UNIQUE(order_id,item_index)
|
UNIQUE(order_id,item_index)
|
||||||
);
|
);
|
||||||
|
ALTER TABLE dtf_local.print_files ADD COLUMN IF NOT EXISTS claim_token uuid;
|
||||||
|
|
||||||
-- Each run of the off-server database backup (ops/db_backup.py), which the
|
-- Each run of the off-server database backup (ops/db_backup.py), which the
|
||||||
-- Kanban shows so a backup that stopped working does not go unnoticed.
|
-- Kanban shows so a backup that stopped working does not go unnoticed.
|
||||||
@@ -203,8 +206,40 @@ CREATE INDEX IF NOT EXISTS payment_events_unprocessed ON dtf_local.payment_event
|
|||||||
CREATE INDEX IF NOT EXISTS print_files_open ON dtf_local.print_files(created_at)
|
CREATE INDEX IF NOT EXISTS print_files_open ON dtf_local.print_files(created_at)
|
||||||
WHERE status IN ('pending','rendering');
|
WHERE status IN ('pending','rendering');
|
||||||
|
|
||||||
|
-- The generated files of each item (item 13, 2026-10-29): one PNG, or the parts
|
||||||
|
-- of a film over 15 m, in order. print_files.upload_id stays the first.
|
||||||
|
CREATE TABLE IF NOT EXISTS dtf_local.print_parts (
|
||||||
|
order_id uuid NOT NULL, item_index integer NOT NULL, part integer NOT NULL CHECK(part >= 1),
|
||||||
|
upload_id uuid NOT NULL REFERENCES dtf_local.uploads(id) ON DELETE CASCADE,
|
||||||
|
PRIMARY KEY(order_id,item_index,part),
|
||||||
|
FOREIGN KEY(order_id,item_index) REFERENCES dtf_local.print_files(order_id,item_index) ON DELETE CASCADE
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS print_parts_upload ON dtf_local.print_parts(upload_id);
|
||||||
|
|
||||||
|
-- What each machine's hot folder gets (item 10, app/hotfolder.py): one row per
|
||||||
|
-- file or part, per entry into Imprimindo (round), written by one computer.
|
||||||
|
CREATE TABLE IF NOT EXISTS dtf_local.hot_parts (
|
||||||
|
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||||
|
order_id uuid NOT NULL REFERENCES dtf_local.orders(id) ON DELETE CASCADE,
|
||||||
|
round integer NOT NULL, seq integer NOT NULL, item_index integer NOT NULL,
|
||||||
|
upload_id uuid NOT NULL REFERENCES dtf_local.uploads(id) ON DELETE CASCADE,
|
||||||
|
name text NOT NULL, folder text,
|
||||||
|
state text NOT NULL DEFAULT 'queued'
|
||||||
|
CHECK(state IN ('queued','claimed','written','consumed','withdraw','gone')),
|
||||||
|
claimed_at timestamptz, claimed_by text, written_at timestamptz, done_at timestamptz,
|
||||||
|
created_at timestamptz NOT NULL DEFAULT now(),
|
||||||
|
UNIQUE(order_id, round, seq)
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS hot_parts_open ON dtf_local.hot_parts(order_id)
|
||||||
|
WHERE state IN ('queued','claimed','written','withdraw');
|
||||||
|
INSERT INTO dtf_local.print_parts(order_id,item_index,part,upload_id)
|
||||||
|
SELECT order_id,item_index,1,upload_id FROM dtf_local.print_files WHERE upload_id IS NOT NULL
|
||||||
|
ON CONFLICT DO NOTHING;
|
||||||
|
|
||||||
-- A movement that undid an earlier one (a mistaken move), shown as such.
|
-- A movement that undid an earlier one (a mistaken move), shown as such.
|
||||||
ALTER TABLE dtf_local.movements ADD COLUMN IF NOT EXISTS back boolean NOT NULL DEFAULT false;
|
ALTER TABLE dtf_local.movements ADD COLUMN IF NOT EXISTS back boolean NOT NULL DEFAULT false;
|
||||||
|
CREATE INDEX IF NOT EXISTS movements_finished_latest ON dtf_local.movements(order_id, created_at DESC)
|
||||||
|
WHERE to_state='fin' AND NOT back;
|
||||||
|
|
||||||
-- The Kanban lists payment events a person must act on (money without an
|
-- The Kanban lists payment events a person must act on (money without an
|
||||||
-- order, or a reversed payment on an existing order) until resolved.
|
-- order, or a reversed payment on an existing order) until resolved.
|
||||||
@@ -249,16 +284,21 @@ CREATE TABLE IF NOT EXISTS dtf_local.cnpj_names (
|
|||||||
-- from the console); administrators manage users and machines; gestão runs
|
-- from the console); administrators manage users and machines; gestão runs
|
||||||
-- the business; designers approve artwork; operadores print; revisores check
|
-- the business; designers approve artwork; operadores print; revisores check
|
||||||
-- the printed sheet and are the only ones to release it to Finalizado;
|
-- the printed sheet and are the only ones to release it to Finalizado;
|
||||||
-- vendedores only read.
|
-- vendedores only read; expedição assembles sheets in the Kanban's montador.
|
||||||
ALTER TABLE dtf_local.operators ADD COLUMN IF NOT EXISTS role text NOT NULL DEFAULT 'admin';
|
ALTER TABLE dtf_local.operators ADD COLUMN IF NOT EXISTS role text NOT NULL DEFAULT 'admin';
|
||||||
ALTER TABLE dtf_local.operators DROP CONSTRAINT IF EXISTS operators_role;
|
-- Created once, and widened only by a migration: re-adding it on every start
|
||||||
|
-- would let an older image narrow the list and refuse rows written under a
|
||||||
|
-- later one, and the database would not finish starting.
|
||||||
|
DO $$ BEGIN
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname='operators_role'
|
||||||
|
AND conrelid='dtf_local.operators'::regclass) THEN
|
||||||
ALTER TABLE dtf_local.operators ADD CONSTRAINT operators_role
|
ALTER TABLE dtf_local.operators ADD CONSTRAINT operators_role
|
||||||
CHECK (role IN ('superadmin','admin','gestao','designer','operador','revisor','vendedor','financeiro'));
|
CHECK (role IN ('superadmin','admin','gestao','designer','operador','revisor','vendedor','financeiro','expedicao'));
|
||||||
-- The print machines, and which products each prints. An order keeps the
|
END IF;
|
||||||
-- machine someone chose (machine_chosen) or the one given automatically: the
|
END $$;
|
||||||
-- active machine of its product with the fewest metres open (app/machines.py).
|
-- Print machines and which products each prints. An order gets its machine
|
||||||
-- limit_metres: the metres open a machine takes before the next order goes to
|
-- when someone pulls it into Imprimindo; no machine is assigned at payment.
|
||||||
-- another one; NULL is no limit.
|
-- limit_metres remains the load shown for a machine.
|
||||||
CREATE TABLE IF NOT EXISTS dtf_local.machines (
|
CREATE TABLE IF NOT EXISTS dtf_local.machines (
|
||||||
id uuid PRIMARY KEY, name text UNIQUE NOT NULL, products text[] NOT NULL DEFAULT '{}',
|
id uuid PRIMARY KEY, name text UNIQUE NOT NULL, products text[] NOT NULL DEFAULT '{}',
|
||||||
active boolean NOT NULL DEFAULT true, created_at timestamptz NOT NULL DEFAULT now()
|
active boolean NOT NULL DEFAULT true, created_at timestamptz NOT NULL DEFAULT now()
|
||||||
@@ -273,6 +313,44 @@ DO $$ BEGIN
|
|||||||
INSERT INTO dtf_local.migrations VALUES('machine-chosen-v1');
|
INSERT INTO dtf_local.migrations VALUES('machine-chosen-v1');
|
||||||
END IF;
|
END IF;
|
||||||
END $$;
|
END $$;
|
||||||
|
-- Remove the old automatic suggestions before printing. Keep real choices
|
||||||
|
-- and machines already printing, whose hot-folder files may be in flight.
|
||||||
|
DO $$ BEGIN
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM dtf_local.migrations WHERE name='machine-pull-only-v1') THEN
|
||||||
|
UPDATE dtf_local.orders SET machine_id=NULL, machine_chosen=false
|
||||||
|
WHERE NOT machine_chosen AND state IN ('rec','tra','cor');
|
||||||
|
INSERT INTO dtf_local.migrations VALUES('machine-pull-only-v1');
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
-- Acceptable time per stage (front 11): Gestão edits these; a card past the
|
||||||
|
-- limit turns yellow, at twice the limit red. `responsible` is who the board
|
||||||
|
-- names for that column. The final stage counts days without pickup.
|
||||||
|
CREATE TABLE IF NOT EXISTS dtf_local.stage_limits (
|
||||||
|
state text PRIMARY KEY CHECK (state IN ('rec','tra','imp','rev','fin')),
|
||||||
|
hours numeric NOT NULL CHECK (hours > 0),
|
||||||
|
responsible text NOT NULL DEFAULT '',
|
||||||
|
updated_by text NOT NULL DEFAULT 'sistema',
|
||||||
|
updated_at timestamptz NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
-- Videos are uploaded by Gestão; the Site reads only enabled, scanned files.
|
||||||
|
CREATE TABLE IF NOT EXISTS dtf_local.site_videos (
|
||||||
|
id text PRIMARY KEY CHECK (id IN ('subindo','nota','png','avulsas','retirada','sala')),
|
||||||
|
upload_id uuid REFERENCES dtf_local.uploads(id),
|
||||||
|
captions_id uuid REFERENCES dtf_local.uploads(id),
|
||||||
|
video_key text,
|
||||||
|
captions_key text,
|
||||||
|
product text CHECK (product IN ('file','avulsa','uvfile','uv')),
|
||||||
|
enabled boolean NOT NULL DEFAULT false,
|
||||||
|
updated_by text NOT NULL DEFAULT 'sistema',
|
||||||
|
updated_at timestamptz NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
ALTER TABLE dtf_local.site_videos ADD COLUMN IF NOT EXISTS video_key text;
|
||||||
|
ALTER TABLE dtf_local.site_videos ADD COLUMN IF NOT EXISTS captions_key text;
|
||||||
|
INSERT INTO dtf_local.stage_limits(state,hours,responsible) VALUES
|
||||||
|
('rec',2,'Designer'), ('tra',6,'Operador'), ('imp',4,'Operador'),
|
||||||
|
('rev',2,'Revisor'), ('fin',72,'Atendimento')
|
||||||
|
ON CONFLICT (state) DO NOTHING;
|
||||||
|
|
||||||
-- The machines an operator works on; none means every machine.
|
-- The machines an operator works on; none means every machine.
|
||||||
CREATE TABLE IF NOT EXISTS dtf_local.operator_machines (
|
CREATE TABLE IF NOT EXISTS dtf_local.operator_machines (
|
||||||
operator_id uuid NOT NULL REFERENCES dtf_local.operators(id) ON DELETE CASCADE,
|
operator_id uuid NOT NULL REFERENCES dtf_local.operators(id) ON DELETE CASCADE,
|
||||||
@@ -339,11 +417,16 @@ UPDATE dtf_local.accounts a SET email_verified=true WHERE NOT a.email_verified A
|
|||||||
-- E-mail kinds: a password-recovery link, a code, the notice that an account
|
-- E-mail kinds: a password-recovery link, a code, the notice that an account
|
||||||
-- already exists, the notice of a changed e-mail, a customer's paid order,
|
-- already exists, the notice of a changed e-mail, a customer's paid order,
|
||||||
-- the team's alerts and a test.
|
-- the team's alerts and a test.
|
||||||
-- Defined once, here: the schema runs on every start, and an earlier, narrower
|
-- Created once, and widened only by a migration: the schema runs on every
|
||||||
-- copy would refuse the rows of the kinds added after it.
|
-- start, and re-adding an earlier, narrower copy would refuse the rows of the
|
||||||
ALTER TABLE dtf_local.mail_queue DROP CONSTRAINT IF EXISTS mail_queue_kind_check;
|
-- kinds added after it.
|
||||||
|
DO $$ BEGIN
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname='mail_queue_kind_check'
|
||||||
|
AND conrelid='dtf_local.mail_queue'::regclass) THEN
|
||||||
ALTER TABLE dtf_local.mail_queue ADD CONSTRAINT mail_queue_kind_check
|
ALTER TABLE dtf_local.mail_queue ADD CONSTRAINT mail_queue_kind_check
|
||||||
CHECK(kind IN ('reset','code','account','notice','order','alert','test'));
|
CHECK(kind IN ('reset','code','account','notice','order','alert','test'));
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
|
||||||
-- The print proof (Dropstar, 2026-10-21): an order above 10 m, or one whose
|
-- The print proof (Dropstar, 2026-10-21): an order above 10 m, or one whose
|
||||||
-- customer asked for a proof at checkout, prints 20 cm first; the room marks
|
-- customer asked for a proof at checkout, prints 20 cm first; the room marks
|
||||||
@@ -381,8 +464,13 @@ WHERE o.contact_since IS NOT NULL AND NOT EXISTS (SELECT 1 FROM dtf_local.contac
|
|||||||
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS origin text;
|
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS origin text;
|
||||||
UPDATE dtf_local.orders SET origin='site' WHERE origin IS NULL;
|
UPDATE dtf_local.orders SET origin='site' WHERE origin IS NULL;
|
||||||
ALTER TABLE dtf_local.orders ALTER COLUMN origin SET NOT NULL;
|
ALTER TABLE dtf_local.orders ALTER COLUMN origin SET NOT NULL;
|
||||||
ALTER TABLE dtf_local.orders DROP CONSTRAINT IF EXISTS orders_origin_check;
|
-- Created once, and widened only by a migration; never re-added on start.
|
||||||
|
DO $$ BEGIN
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname='orders_origin_check'
|
||||||
|
AND conrelid='dtf_local.orders'::regclass) THEN
|
||||||
ALTER TABLE dtf_local.orders ADD CONSTRAINT orders_origin_check CHECK (origin IN ('site','dropflow','atendimento'));
|
ALTER TABLE dtf_local.orders ADD CONSTRAINT orders_origin_check CHECK (origin IN ('site','dropflow','atendimento'));
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
|
||||||
-- Rework (Dropstar's rules D-02 to D-04, 2026-10-26; the user's answers of
|
-- Rework (Dropstar's rules D-02 to D-04, 2026-10-26; the user's answers of
|
||||||
-- 2026-10-27). Gestão opens it with its cause, and the cause never changes
|
-- 2026-10-27). Gestão opens it with its cause, and the cause never changes
|
||||||
@@ -423,6 +511,162 @@ ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS picked_up_photo uuid REFER
|
|||||||
ALTER TABLE dtf_local.operator_sessions ADD COLUMN IF NOT EXISTS machine_id uuid REFERENCES dtf_local.machines(id) ON DELETE SET NULL;
|
ALTER TABLE dtf_local.operator_sessions ADD COLUMN IF NOT EXISTS machine_id uuid REFERENCES dtf_local.machines(id) ON DELETE SET NULL;
|
||||||
ALTER TABLE dtf_local.operator_sessions ADD COLUMN IF NOT EXISTS machine_at timestamptz;
|
ALTER TABLE dtf_local.operator_sessions ADD COLUMN IF NOT EXISTS machine_at timestamptz;
|
||||||
ALTER TABLE dtf_local.operator_sessions ADD COLUMN IF NOT EXISTS machine_answered boolean NOT NULL DEFAULT false;
|
ALTER TABLE dtf_local.operator_sessions ADD COLUMN IF NOT EXISTS machine_answered boolean NOT NULL DEFAULT false;
|
||||||
|
-- The contraction class chosen per item (item 9), keyed by item index, with
|
||||||
|
-- who chose it and when; the measured class stays in the order's snapshot.
|
||||||
|
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS contraction jsonb NOT NULL DEFAULT '{}'::jsonb;
|
||||||
|
|
||||||
|
-- The proof card (Dropstar, 2026-10-30, app/proof.py): an order of its own,
|
||||||
|
-- child of the order it proves, with no quote of its own; its answer, Prova OK
|
||||||
|
-- or reprovada with its reason, by whom and when.
|
||||||
|
ALTER TABLE dtf_local.orders ALTER COLUMN quote_id DROP NOT NULL;
|
||||||
|
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS parent_id uuid REFERENCES dtf_local.orders(id) ON DELETE CASCADE;
|
||||||
|
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS proof_result text CHECK (proof_result IN ('ok','rejected'));
|
||||||
|
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS proof_decided_at timestamptz;
|
||||||
|
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS proof_decided_by text;
|
||||||
|
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS proof_reason text;
|
||||||
|
CREATE INDEX IF NOT EXISTS orders_parent ON dtf_local.orders(parent_id) WHERE parent_id IS NOT NULL;
|
||||||
|
-- An order's own rows go with it, so deleting an order takes its proof cards
|
||||||
|
-- and theirs too. Done once: a constraint already cascading is left alone.
|
||||||
|
DO $$
|
||||||
|
DECLARE r record;
|
||||||
|
BEGIN
|
||||||
|
FOR r IN SELECT c.conname, c.conrelid::regclass AS tbl FROM pg_constraint c
|
||||||
|
WHERE c.contype='f' AND c.confrelid='dtf_local.orders'::regclass AND c.confdeltype<>'c'
|
||||||
|
AND c.conrelid IN ('dtf_local.movements'::regclass, 'dtf_local.order_files'::regclass,
|
||||||
|
'dtf_local.print_files'::regclass)
|
||||||
|
LOOP
|
||||||
|
EXECUTE format('ALTER TABLE %s DROP CONSTRAINT %I', r.tbl, r.conname);
|
||||||
|
EXECUTE format('ALTER TABLE %s ADD CONSTRAINT %I FOREIGN KEY (order_id) REFERENCES dtf_local.orders(id) ON DELETE CASCADE',
|
||||||
|
r.tbl, r.conname);
|
||||||
|
END LOOP;
|
||||||
|
END $$;
|
||||||
|
-- When the session was last used (Usuários: who is on the system now).
|
||||||
|
ALTER TABLE dtf_local.operator_sessions ADD COLUMN IF NOT EXISTS seen_at timestamptz;
|
||||||
-- The machine of whoever moved a card, as it was named then: "Imprimindo ·
|
-- The machine of whoever moved a card, as it was named then: "Imprimindo ·
|
||||||
-- Thales · máquina2".
|
-- Thales · máquina2".
|
||||||
ALTER TABLE dtf_local.movements ADD COLUMN IF NOT EXISTS machine text;
|
ALTER TABLE dtf_local.movements ADD COLUMN IF NOT EXISTS machine text;
|
||||||
|
|
||||||
|
-- An approved quote nobody paid in 24 h expires (Fase 2, front 9, app/unpaid.py).
|
||||||
|
ALTER TABLE dtf_local.quotes ADD COLUMN IF NOT EXISTS expired_at timestamptz;
|
||||||
|
|
||||||
|
-- The Revisor's photo or short video of the printed sheet (Fase 2, front 2,
|
||||||
|
-- app/reviews.py): DTF-<n>-revisao-<seq>, the record of when and by whom it
|
||||||
|
-- was checked. A photo is required to finish an order above 1 m.
|
||||||
|
CREATE TABLE IF NOT EXISTS dtf_local.order_reviews (
|
||||||
|
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||||
|
order_id uuid NOT NULL REFERENCES dtf_local.orders(id) ON DELETE CASCADE,
|
||||||
|
seq integer NOT NULL CHECK(seq >= 1),
|
||||||
|
upload_id uuid NOT NULL REFERENCES dtf_local.uploads(id) ON DELETE CASCADE,
|
||||||
|
kind text NOT NULL CHECK(kind IN ('photo','video')),
|
||||||
|
width integer, height integer,
|
||||||
|
created_by text NOT NULL, created_at timestamptz NOT NULL DEFAULT now(),
|
||||||
|
UNIQUE(order_id, seq)
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS order_reviews_order ON dtf_local.order_reviews(order_id);
|
||||||
|
|
||||||
|
-- Each machine's sheet (Fase 2, front 1, app/machine_log.py): what it cost and
|
||||||
|
-- when it started, typed once by Gestão; what goes into it, entered by the
|
||||||
|
-- room; and the minimum of each supply that raises the alert.
|
||||||
|
ALTER TABLE dtf_local.machines ADD COLUMN IF NOT EXISTS price_cents bigint CHECK (price_cents >= 0);
|
||||||
|
ALTER TABLE dtf_local.machines ADD COLUMN IF NOT EXISTS installed_on date;
|
||||||
|
-- When the counters start: a machine with no cleaning on record counts from
|
||||||
|
-- here, not from everything it printed before the sheet existed.
|
||||||
|
ALTER TABLE dtf_local.machines ADD COLUMN IF NOT EXISTS log_since timestamptz NOT NULL DEFAULT now();
|
||||||
|
CREATE TABLE IF NOT EXISTS dtf_local.machine_entries (
|
||||||
|
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||||
|
machine_id uuid NOT NULL REFERENCES dtf_local.machines(id) ON DELETE CASCADE,
|
||||||
|
kind text NOT NULL CHECK(kind IN ('supply','part','event')),
|
||||||
|
item text NOT NULL,
|
||||||
|
quantity numeric(12,3) CHECK (quantity > 0),
|
||||||
|
cost_cents bigint CHECK (cost_cents >= 0),
|
||||||
|
serial text, note text,
|
||||||
|
stop_minutes integer CHECK (stop_minutes > 0),
|
||||||
|
from_alert boolean NOT NULL DEFAULT false,
|
||||||
|
created_by text NOT NULL, created_at timestamptz NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS machine_entries_machine ON dtf_local.machine_entries(machine_id, created_at);
|
||||||
|
CREATE TABLE IF NOT EXISTS dtf_local.machine_minimums (
|
||||||
|
machine_id uuid NOT NULL REFERENCES dtf_local.machines(id) ON DELETE CASCADE,
|
||||||
|
item text NOT NULL, minimum numeric(12,3) NOT NULL CHECK (minimum >= 0),
|
||||||
|
PRIMARY KEY(machine_id, item)
|
||||||
|
);
|
||||||
|
-- "Adiar uma vez": an alert postponed lets one more card be pulled, once per
|
||||||
|
-- cycle (the cycle starts at the event that resets its counter).
|
||||||
|
CREATE TABLE IF NOT EXISTS dtf_local.machine_snoozes (
|
||||||
|
machine_id uuid NOT NULL REFERENCES dtf_local.machines(id) ON DELETE CASCADE,
|
||||||
|
alert text NOT NULL, cycle_from timestamptz NOT NULL,
|
||||||
|
snoozed_by text NOT NULL, snoozed_at timestamptz NOT NULL DEFAULT now(),
|
||||||
|
PRIMARY KEY(machine_id, alert, cycle_from)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Orders generated before the print file was a PNG with its strips (item 13)
|
||||||
|
-- open blank in the 100% viewer. Those not approved yet are generated again,
|
||||||
|
-- once: the same layout, now as PNG with strips. An approved final, a
|
||||||
|
-- customer's correction or a cancelled order is left as it is.
|
||||||
|
DO $$ BEGIN
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM dtf_local.migrations WHERE name='png-regenerate-v1') THEN
|
||||||
|
UPDATE dtf_local.print_files p SET status='pending', attempts=0, claimed_at=NULL, claim_token=NULL,
|
||||||
|
finished_at=NULL, upload_id=NULL, detail='{}'
|
||||||
|
FROM dtf_local.orders o
|
||||||
|
WHERE o.id=p.order_id AND o.state='rec' AND o.cancelled_at IS NULL
|
||||||
|
AND p.status='ready' AND NOT (p.detail ? 'format')
|
||||||
|
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.active);
|
||||||
|
INSERT INTO dtf_local.migrations VALUES('png-regenerate-v1');
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
-- Front 8: what the Site sells and at what price, edited in the Kanban's Site tab.
|
||||||
|
CREATE TABLE IF NOT EXISTS dtf_local.products (
|
||||||
|
id text PRIMARY KEY CHECK (id IN ('file','avulsa','uvfile','uv','tratamento')),
|
||||||
|
enabled boolean NOT NULL DEFAULT true,
|
||||||
|
updated_by text NOT NULL DEFAULT 'sistema',
|
||||||
|
updated_at timestamptz NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
INSERT INTO dtf_local.products(id) VALUES ('file'),('avulsa'),('uvfile'),('uv'),('tratamento')
|
||||||
|
ON CONFLICT (id) DO NOTHING;
|
||||||
|
CREATE TABLE IF NOT EXISTS dtf_local.product_prices (
|
||||||
|
id bigserial PRIMARY KEY,
|
||||||
|
product text NOT NULL REFERENCES dtf_local.products(id),
|
||||||
|
unit_cents integer NOT NULL CHECK (unit_cents >= 0 AND unit_cents <= 10000000),
|
||||||
|
starts_at timestamptz NOT NULL,
|
||||||
|
created_by text NOT NULL,
|
||||||
|
created_at timestamptz NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS product_prices_current ON dtf_local.product_prices(product, starts_at DESC);
|
||||||
|
|
||||||
|
-- Front 7a: the stamp sizes of the Kanban's montador; Gestão edits them.
|
||||||
|
CREATE TABLE IF NOT EXISTS dtf_local.stamp_sizes (
|
||||||
|
letter text PRIMARY KEY CHECK (letter ~ '^[A-Z]{1,2}$'),
|
||||||
|
width_cm numeric(5,2) NOT NULL CHECK (width_cm > 0 AND width_cm <= 56),
|
||||||
|
updated_by text NOT NULL DEFAULT 'sistema',
|
||||||
|
updated_at timestamptz NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
INSERT INTO dtf_local.stamp_sizes(letter,width_cm) VALUES ('A',20),('B',24),('C',27),('D',30)
|
||||||
|
ON CONFLICT (letter) DO NOTHING;
|
||||||
|
-- Front 8.2: a price may also have bands by the order's total metres of that
|
||||||
|
-- product: base price, then "from 5 m R$ Y", "from 20 m R$ Z" (jsonb list of
|
||||||
|
-- {"from_metres": "5", "unit_cents": 1990}, strictly increasing, at most 5).
|
||||||
|
ALTER TABLE dtf_local.product_prices ADD COLUMN IF NOT EXISTS bands jsonb NOT NULL DEFAULT '[]';
|
||||||
|
|
||||||
|
-- Front 8.3: discount coupons, created in the Kanban's Site tab. The id is
|
||||||
|
-- generated in Python (schema.sql does not use gen_random_uuid). A deleted
|
||||||
|
-- code may be created again; the orders that used it keep its id and code.
|
||||||
|
CREATE TABLE IF NOT EXISTS dtf_local.coupons (
|
||||||
|
id uuid PRIMARY KEY,
|
||||||
|
code text NOT NULL CHECK (code ~ '^[A-Z0-9-]{3,30}$'),
|
||||||
|
kind text NOT NULL CHECK (kind IN ('percent','per_metre')),
|
||||||
|
value integer NOT NULL CHECK (value > 0), -- percent: 1..90; per_metre: cents per billed metre
|
||||||
|
valid_from timestamptz NOT NULL DEFAULT now(),
|
||||||
|
valid_until timestamptz,
|
||||||
|
min_metres numeric(8,1),
|
||||||
|
max_uses integer CHECK (max_uses > 0),
|
||||||
|
max_uses_per_customer integer CHECK (max_uses_per_customer > 0),
|
||||||
|
product text CHECK (product IN ('file','avulsa','uvfile','uv')), -- NULL = every product
|
||||||
|
note text NOT NULL DEFAULT '',
|
||||||
|
paused boolean NOT NULL DEFAULT false,
|
||||||
|
deleted_at timestamptz,
|
||||||
|
created_by text NOT NULL,
|
||||||
|
created_at timestamptz NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS coupons_live_code ON dtf_local.coupons(code) WHERE deleted_at IS NULL;
|
||||||
|
|||||||
266
app/tiny.py
266
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).
|
invoiced one is not cancelled here (its nota fiscal is cancelled in Tiny).
|
||||||
Pickup orders carry the client's "retirar pessoalmente" forma de envio.
|
Pickup orders carry the client's "retirar pessoalmente" forma de envio.
|
||||||
"""
|
"""
|
||||||
|
import logging
|
||||||
import os
|
import os
|
||||||
import secrets
|
import secrets
|
||||||
import time
|
import time
|
||||||
@@ -56,29 +57,41 @@ AUTH = 'https://accounts.tiny.com.br/realms/tiny/protocol/openid-connect'
|
|||||||
# Not TINY_PRODUCT_<MODE>: app/core/secrets.py reads any variable ending in
|
# Not TINY_PRODUCT_<MODE>: app/core/secrets.py reads any variable ending in
|
||||||
# _FILE as a path to a secret file, and one product mode is called "file".
|
# _FILE as a path to a secret file, and one product mode is called "file".
|
||||||
PRODUCT_SETTINGS = {'file': 'TINY_PRODUCT_TEXTIL_FOLHA', 'avulsa': 'TINY_PRODUCT_TEXTIL_AVULSA',
|
PRODUCT_SETTINGS = {'file': 'TINY_PRODUCT_TEXTIL_FOLHA', 'avulsa': 'TINY_PRODUCT_TEXTIL_AVULSA',
|
||||||
'uvfile': 'TINY_PRODUCT_UV_FOLHA', 'uv': 'TINY_PRODUCT_UV_AVULSA'}
|
'uvfile': 'TINY_PRODUCT_UV_FOLHA', 'uv': 'TINY_PRODUCT_UV_AVULSA',
|
||||||
|
'premium': 'TINY_PRODUCT_TEXTIL_PREMIUM'}
|
||||||
# The common code prefix of a mode's SKUs ("DTFIMP.TX" for DTFIMP.TX.100CM,
|
# The common code prefix of a mode's SKUs ("DTFIMP.TX" for DTFIMP.TX.100CM,
|
||||||
# the metre, and DTFIMP.TX.0010CM to DTFIMP.TX.0090CM). When set, it replaces
|
# the metre, and DTFIMP.TX.0010CM to DTFIMP.TX.0090CM). When set, it replaces
|
||||||
# the mode's product id.
|
# the mode's product id.
|
||||||
SKU_SETTINGS = {'file': 'TINY_SKU_TEXTIL_FOLHA', 'avulsa': 'TINY_SKU_TEXTIL_AVULSA',
|
SKU_SETTINGS = {'file': 'TINY_SKU_TEXTIL_FOLHA', 'avulsa': 'TINY_SKU_TEXTIL_AVULSA',
|
||||||
'uvfile': 'TINY_SKU_UV_FOLHA', 'uv': 'TINY_SKU_UV_AVULSA'}
|
'uvfile': 'TINY_SKU_UV_FOLHA', 'uv': 'TINY_SKU_UV_AVULSA',
|
||||||
|
'premium': 'TINY_SKU_TEXTIL_PREMIUM'}
|
||||||
# Or a SKU per 10 cm ("DTFIMP.UV.010CM"), alone (2,30 m is 23 of it) or after
|
# Or a SKU per 10 cm ("DTFIMP.UV.010CM"), alone (2,30 m is 23 of it) or after
|
||||||
# a metre SKU ("DTFIMP.UV.1MT"): 2,30 m is 2 metres and 3 of the 10 cm.
|
# a metre SKU ("DTFIMP.UV.1MT"): 2,30 m is 2 metres and 3 of the 10 cm.
|
||||||
STEP_SETTINGS = {'file': 'TINY_SKU10_TEXTIL_FOLHA', 'avulsa': 'TINY_SKU10_TEXTIL_AVULSA',
|
STEP_SETTINGS = {'file': 'TINY_SKU10_TEXTIL_FOLHA', 'avulsa': 'TINY_SKU10_TEXTIL_AVULSA',
|
||||||
'uvfile': 'TINY_SKU10_UV_FOLHA', 'uv': 'TINY_SKU10_UV_AVULSA'}
|
'uvfile': 'TINY_SKU10_UV_FOLHA', 'uv': 'TINY_SKU10_UV_AVULSA',
|
||||||
|
'premium': 'TINY_SKU10_TEXTIL_PREMIUM'}
|
||||||
METRE_SETTINGS = {'file': 'TINY_SKU_METRO_TEXTIL_FOLHA', 'avulsa': 'TINY_SKU_METRO_TEXTIL_AVULSA',
|
METRE_SETTINGS = {'file': 'TINY_SKU_METRO_TEXTIL_FOLHA', 'avulsa': 'TINY_SKU_METRO_TEXTIL_AVULSA',
|
||||||
'uvfile': 'TINY_SKU_METRO_UV_FOLHA', 'uv': 'TINY_SKU_METRO_UV_AVULSA'}
|
'uvfile': 'TINY_SKU_METRO_UV_FOLHA', 'uv': 'TINY_SKU_METRO_UV_AVULSA',
|
||||||
|
'premium': 'TINY_SKU_METRO_TEXTIL_PREMIUM'}
|
||||||
# Dropstar's own catalogue (checked against its Tiny export, 2026-10-14): Têxtil
|
# Dropstar's own catalogue (checked against its Tiny export, 2026-10-14): Têxtil
|
||||||
# as DTFIMP.TX.100CM per metre and DTFIMP.TX.0010CM to 0090CM for the rest, UV
|
# as DTFIMP.TX.100CM per metre and DTFIMP.TX.0010CM to 0090CM for the rest, UV
|
||||||
# as DTFIMP.UV.1MT per metre and DTFIMP.UV.010CM per 10 cm, the ready sheet and
|
# as DTFIMP.UV.1MT per metre and DTFIMP.UV.010CM per 10 cm, the ready sheet and
|
||||||
# loose artwork alike. The settings above only override these.
|
# loose artwork alike. The settings above only override these.
|
||||||
SKU_DEFAULTS = {'file': 'DTFIMP.TX', 'avulsa': 'DTFIMP.TX'}
|
SKU_DEFAULTS = {'file': 'DTFIMP.TX', 'avulsa': 'DTFIMP.TX', 'premium': 'DTFIMP.TXP'}
|
||||||
STEP_DEFAULTS = {'uvfile': 'DTFIMP.UV.010CM', 'uv': 'DTFIMP.UV.010CM'}
|
STEP_DEFAULTS = {'uvfile': 'DTFIMP.UV.010CM', 'uv': 'DTFIMP.UV.010CM'}
|
||||||
METRE_DEFAULTS = {'uvfile': 'DTFIMP.UV.1MT', 'uv': 'DTFIMP.UV.1MT'}
|
METRE_DEFAULTS = {'uvfile': 'DTFIMP.UV.1MT', 'uv': 'DTFIMP.UV.1MT'}
|
||||||
|
# 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',
|
PRODUCTS = {'file': 'DTF Têxtil 57 cm · folha montada',
|
||||||
'avulsa': 'DTF Têxtil 57 cm · artes avulsas',
|
'avulsa': 'DTF Têxtil 57 cm · artes avulsas',
|
||||||
'uvfile': 'DTF UV 27 cm · folha montada',
|
'uvfile': 'DTF UV 27 cm · folha montada',
|
||||||
'uv': 'DTF UV 27 cm · artes avulsas'}
|
'uv': 'DTF UV 27 cm · artes avulsas',
|
||||||
|
'premium': 'DTF Têxtil Premium 57 cm · folha montada'}
|
||||||
# How far back to look for an order a previous delivery may already have made.
|
# How far back to look for an order a previous delivery may already have made.
|
||||||
SEARCH_DAYS = 7
|
SEARCH_DAYS = 7
|
||||||
# A "ready" event can come after corrections; it normally knows the Tiny id.
|
# A "ready" event can come after corrections; it normally knows the Tiny id.
|
||||||
@@ -100,8 +113,19 @@ OUTSIDE_NOTES = {'pix': 'Pix', 'card': 'cartão', 'cash': 'dinheiro', 'credit':
|
|||||||
|
|
||||||
def internal_note(payload):
|
def internal_note(payload):
|
||||||
paid = payload.get('payment') or {}
|
paid = payload.get('payment') or {}
|
||||||
how = f"pago fora do site ({OUTSIDE_NOTES.get(paid.get('method'), paid.get('method'))})" if paid.get('outside') else 'pago'
|
method = paid.get('method')
|
||||||
return f"{ORIGIN_NOTES.get(payload.get('origin') or 'site')} · {how} · {payload['order_id']}"
|
if method == 'faturado':
|
||||||
|
# A montador Venda order is invoiced (front 7a.3): its forma de
|
||||||
|
# recebimento is "Boleto" when the client's id is configured.
|
||||||
|
boleto = os.environ.get('TINY_RECEIPT_BOLETO', '').strip()
|
||||||
|
how = 'faturado (Boleto)' if boleto.isdigit() else 'faturado: forma de recebimento a definir'
|
||||||
|
else:
|
||||||
|
how = f"pago fora do site ({OUTSIDE_NOTES.get(method, method)})" if paid.get('outside') else 'pago'
|
||||||
|
note = f"{ORIGIN_NOTES.get(payload.get('origin') or 'site')} · {how} · {payload['order_id']}"
|
||||||
|
with_order = (payload.get('order') or {}).get('with_order')
|
||||||
|
if with_order:
|
||||||
|
note += f' · junto com o pedido de roupa nº {with_order}'
|
||||||
|
return note
|
||||||
|
|
||||||
|
|
||||||
STATUS_UPDATES_SETTING = 'TINY_STATUS_UPDATES'
|
STATUS_UPDATES_SETTING = 'TINY_STATUS_UPDATES'
|
||||||
@@ -114,15 +138,20 @@ PICKUP_EXACT = 'retirar pessoalmente'
|
|||||||
# Dropstar's own ids, read from its store orders with app.tiny_probe exemplo
|
# 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
|
# (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
|
# looked up: Pix and credit card, as the store's orders are paid, and the
|
||||||
# DropStar carrier its pickup orders name. Dinheiro and, for the customer's
|
# DropStar carrier its pickup orders name. Dinheiro was sent by Marcus on
|
||||||
# credit, Dropstar's own "CORREÇÃO DTF" were sent by Marcus on 2026-10-27, for
|
# 2026-10-27, for the orders the team registers as paid outside the site
|
||||||
# the orders the team registers as paid outside the site (D-35).
|
# (D-35). The customer's credit is "CREDITO PRE-PAGO" (Marcus, 2026-11-18);
|
||||||
RECEIPT_METHODS = {'pix': 919478952, 'card': 977460722, 'cash': 919478944, 'credit': 977493654}
|
# "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': 987762591,
|
||||||
|
**({'faturado': int(_BOLETO)} if _BOLETO.isdigit() else {})}
|
||||||
PICKUP_CARRIER = 761565838
|
PICKUP_CARRIER = 761565838
|
||||||
# Dropstar's answers: the financial category "DTF SITE" (RECEITAS, id sent on
|
# Dropstar's answers: the financial category "DTF SITE" (RECEITAS, id sent on
|
||||||
# 2026-10-26; it goes in pagamento.categoria, and replaced the store's
|
# 2026-10-26; it goes in pagamento.categoria, and replaced the store's
|
||||||
# "DUPLICADO DROP", 965775137), no seller (Tiny sets it from the contact,
|
# "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
|
# POST /pedidos does not take marcadores. Capitals, no accent, no extra
|
||||||
# space: the string Kondado reads for Power BI.
|
# space: the string Kondado reads for Power BI.
|
||||||
CATEGORY = 986932924
|
CATEGORY = 986932924
|
||||||
@@ -130,6 +159,15 @@ CATEGORY = 986932924
|
|||||||
# the rules document (D-21) keeps the two channels apart in the financial.
|
# the rules document (D-21) keeps the two channels apart in the financial.
|
||||||
CATEGORIES = {'dropflow': 987032506}
|
CATEGORIES = {'dropflow': 987032506}
|
||||||
TAG = 'SITE DTF'
|
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 is the sender's (CIF), as on the store's orders.
|
||||||
FREIGHT_PAID_BY = 'R'
|
FREIGHT_PAID_BY = 'R'
|
||||||
# The forma de envio each delivery service uses, by name; a Correios service
|
# The forma de envio each delivery service uses, by name; a Correios service
|
||||||
@@ -151,6 +189,17 @@ class TinyError(Exception):
|
|||||||
pass
|
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):
|
class TinyNotConnected(TinyError):
|
||||||
"""No authorised connection yet: an operator must click "Conectar Tiny"."""
|
"""No authorised connection yet: an operator must click "Conectar Tiny"."""
|
||||||
|
|
||||||
@@ -191,6 +240,11 @@ def metre_sku(mode):
|
|||||||
return setting(METRE_SETTINGS[mode]) or ('' if setting(STEP_SETTINGS[mode]) else METRE_DEFAULTS.get(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):
|
def mode_codes(mode):
|
||||||
"""Every SKU code a mode sold by SKU uses, or [] for a mode sold by product id."""
|
"""Every SKU code a mode sold by SKU uses, or [] for a mode sold by product id."""
|
||||||
if step_sku(mode):
|
if step_sku(mode):
|
||||||
@@ -313,8 +367,10 @@ class TinyAuth:
|
|||||||
operator = self._claim(c, state)
|
operator = self._claim(c, state)
|
||||||
return self.authorize_url(operator, offline=False)
|
return self.authorize_url(operator, offline=False)
|
||||||
|
|
||||||
def status(self):
|
def status(self, c=None):
|
||||||
|
if c is None:
|
||||||
with self.connect() as c:
|
with self.connect() as c:
|
||||||
|
return self.status(c)
|
||||||
row = c.execute('''SELECT connected_by,connected_at,refresh_expires_at,updated_at,offline,
|
row = c.execute('''SELECT connected_by,connected_at,refresh_expires_at,updated_at,offline,
|
||||||
refresh_failed_at,refused_at FROM dtf_local.provider_tokens WHERE provider='tiny' ''').fetchone()
|
refresh_failed_at,refused_at FROM dtf_local.provider_tokens WHERE provider='tiny' ''').fetchone()
|
||||||
if not row:
|
if not row:
|
||||||
@@ -426,6 +482,48 @@ def search_forms(document):
|
|||||||
return list(dict.fromkeys((punctuated(d), d)))
|
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
|
||||||
|
name. Tiny's own search does the matching."""
|
||||||
|
text = str(query or '').strip()
|
||||||
|
digits = ''.join(ch for ch in text if ch.isdigit())
|
||||||
|
found = []
|
||||||
|
if digits and not any(ch.isalpha() for ch in text):
|
||||||
|
for form in search_forms(digits):
|
||||||
|
found += orders.request('GET', '/contatos', params={'cpfCnpj': form, 'limit': limit}).get('itens') or []
|
||||||
|
else:
|
||||||
|
found = orders.request('GET', '/contatos', params={'nome': text, 'limit': limit}).get('itens') or []
|
||||||
|
contacts, seen = [], set()
|
||||||
|
for entry in found:
|
||||||
|
if entry.get('id') in seen:
|
||||||
|
continue
|
||||||
|
seen.add(entry.get('id'))
|
||||||
|
contacts.append({'id': entry.get('id'), 'name': entry.get('nome') or '',
|
||||||
|
'document': entry.get('cpfCnpj') or '',
|
||||||
|
'email': entry.get('email') or '',
|
||||||
|
'phone': entry.get('telefone') or entry.get('celular') or ''})
|
||||||
|
return contacts[:limit]
|
||||||
|
|
||||||
|
|
||||||
def contact_payload(order, company=None):
|
def contact_payload(order, company=None):
|
||||||
"""A new contact, named after the company's razão social when the
|
"""A new contact, named after the company's razão social when the
|
||||||
registry gave it (app/cnpj.py), else the customer's name, else the
|
registry gave it (app/cnpj.py), else the customer's name, else the
|
||||||
@@ -461,7 +559,7 @@ def business_days_after(day, days):
|
|||||||
return day
|
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
|
"""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
|
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
|
a SKU's product id by its code; shipping(service) the forma de envio and de
|
||||||
@@ -481,14 +579,47 @@ def order_payload(payload, contact_id, today=None, product_id=None, shipping=Non
|
|||||||
line['infoAdicional'] = note + f" · {item['billed_metres']} m"
|
line['infoAdicional'] = note + f" · {item['billed_metres']} m"
|
||||||
items.append(line)
|
items.append(line)
|
||||||
continue
|
continue
|
||||||
setting = PRODUCT_SETTINGS[item['mode']]
|
product_setting = PRODUCT_SETTINGS[item['mode']]
|
||||||
product = os.environ.get(setting, '')
|
product = os.environ.get(product_setting, '')
|
||||||
if not product.isdigit():
|
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)},
|
items.append({'produto': {'id': int(product)},
|
||||||
'quantidade': float(Decimal(item['billed_metres'])),
|
'quantidade': float(Decimal(item['billed_metres'])),
|
||||||
'valorUnitario': money(item['unit_cents']),
|
'valorUnitario': money(item['unit_cents']),
|
||||||
'infoAdicional': note})
|
'infoAdicional': note})
|
||||||
|
treatment = order.get('treatment') or {}
|
||||||
|
if treatment.get('cents'):
|
||||||
|
# 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'])
|
||||||
|
# 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']
|
freight = order['freight']
|
||||||
service = freight.get('service')
|
service = freight.get('service')
|
||||||
pickup = service == 'pickup'
|
pickup = service == 'pickup'
|
||||||
@@ -500,21 +631,41 @@ def order_payload(payload, contact_id, today=None, product_id=None, shipping=Non
|
|||||||
'valorFrete': money(freight['total_cents']),
|
'valorFrete': money(freight['total_cents']),
|
||||||
'observacoes': f"Pedido DTF #{payload['number']}" + (' · retirada em Franca' if pickup else ''),
|
'observacoes': f"Pedido DTF #{payload['number']}" + (' · retirada em Franca' if pickup else ''),
|
||||||
'observacoesInternas': internal_note(payload)}
|
'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.
|
||||||
|
pedido['valorDesconto'] = money(coupon.get('discount_cents') or 0)
|
||||||
carrier = shipping(service) if shipping else None
|
carrier = shipping(service) if shipping else None
|
||||||
if carrier:
|
if carrier:
|
||||||
pedido['transportador'] = {'fretePorConta': FREIGHT_PAID_BY, **carrier}
|
pedido['transportador'] = {'fretePorConta': FREIGHT_PAID_BY, **carrier}
|
||||||
# The carrier's time already counts production; a pickup is ready after it.
|
# 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)
|
days = freight.get('days') if not pickup else int(os.environ.get('FREIGHT_PRODUCTION_DAYS') or 0)
|
||||||
if days is not None:
|
if days is not None:
|
||||||
pedido['dataPrevista'] = business_days_after(day, int(days)).isoformat()
|
# 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.
|
# 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)}}
|
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:
|
if received:
|
||||||
total = money(order['total_cents'])
|
total = money(order['total_cents'])
|
||||||
pedido['pagamento'].update({'formaRecebimento': {'id': received},
|
parcela = {'dias': 0, 'data': day.isoformat(), 'valor': total,
|
||||||
'parcelas': [{'dias': 0, 'data': day.isoformat(), 'valor': total,
|
'formaRecebimento': {'id': received}}
|
||||||
'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')
|
destination = order.get('destination')
|
||||||
if destination:
|
if destination:
|
||||||
pedido['enderecoEntrega'] = {**address(destination), 'enderecoNro': destination['number'],
|
pedido['enderecoEntrega'] = {**address(destination), 'enderecoNro': destination['number'],
|
||||||
@@ -551,6 +702,19 @@ def configured_skus(orders, mode):
|
|||||||
return 'ok' if not missing else 'SKU não encontrado entre os produtos ativos: ' + ', '.join(missing)
|
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):
|
def find_pickup(orders):
|
||||||
"""The forma de envio named "Retirar pessoalmente" (Dropstar's), else the one
|
"""The forma de envio named "Retirar pessoalmente" (Dropstar's), else the one
|
||||||
named like "retirar", or why there is not one."""
|
named like "retirar", or why there is not one."""
|
||||||
@@ -615,9 +779,9 @@ def configured_pickup(orders):
|
|||||||
|
|
||||||
def check(auth=None, transport=None, orders=None):
|
def check(auth=None, transport=None, orders=None):
|
||||||
"""Read-only proof that the connection and permissions work: one order and
|
"""Read-only proof that the connection and permissions work: one order and
|
||||||
one contact listed, each product's SKUs found active and the pickup
|
one contact listed, each product's SKUs (and Ajuste Fino) found active and
|
||||||
forma de envio found, nothing created. Raises TinyNotConnected when there is no usable connection;
|
the pickup forma de envio found, nothing created. Raises TinyNotConnected
|
||||||
otherwise reports each read separately."""
|
when there is no usable connection; otherwise reports each read separately."""
|
||||||
orders = orders or TinyOrders(auth=auth or TinyAuth(), transport=transport)
|
orders = orders or TinyOrders(auth=auth or TinyAuth(), transport=transport)
|
||||||
|
|
||||||
def listed(path, **filters):
|
def listed(path, **filters):
|
||||||
@@ -630,6 +794,7 @@ def check(auth=None, transport=None, orders=None):
|
|||||||
reads = [('pedidos', lambda: listed('/pedidos', dataInicial=since)), ('contatos', lambda: listed('/contatos'))]
|
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)
|
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]
|
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]))
|
reads.append(('forma de envio de retirada', lambda: configured_pickup(orders)[1]))
|
||||||
results = {}
|
results = {}
|
||||||
for name, read in reads:
|
for name, read in reads:
|
||||||
@@ -661,7 +826,9 @@ class TinyOrders:
|
|||||||
headers = {'Authorization': f'Bearer {self.auth.access_token()}'}
|
headers = {'Authorization': f'Bearer {self.auth.access_token()}'}
|
||||||
response = self.http.request(method, path, headers=headers, **kwargs)
|
response = self.http.request(method, path, headers=headers, **kwargs)
|
||||||
if response.status_code == 429:
|
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:
|
if response.status_code >= 400:
|
||||||
raise TinyError(f'{method} {path}: {response.status_code} {response.text[:300]}')
|
raise TinyError(f'{method} {path}: {response.status_code} {response.text[:300]}')
|
||||||
return response.json() if response.content else {}
|
return response.json() if response.content else {}
|
||||||
@@ -695,17 +862,34 @@ class TinyOrders:
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
def contact(self, order):
|
def contact(self, order):
|
||||||
|
"""The customer's contact id, and the seller of an existing one."""
|
||||||
cnpj = order['customer']['cnpj']
|
cnpj = order['customer']['cnpj']
|
||||||
known = self.find_contact(cnpj)
|
known = self.find_contact(cnpj)
|
||||||
if known:
|
if known:
|
||||||
return known
|
return known, self.contact_seller(known)
|
||||||
company = None
|
company = None
|
||||||
if self.names and len(cnpj) == 14:
|
if self.names and len(cnpj) == 14:
|
||||||
try:
|
try:
|
||||||
company = self.names(cnpj)
|
company = self.names(cnpj)
|
||||||
except Exception: # a name is a nicety; the order must still go
|
except Exception: # a name is a nicety; the order must still go
|
||||||
company = None
|
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):
|
def find(self, payload, days=SEARCH_DAYS):
|
||||||
"""An order a previous delivery already created, or None."""
|
"""An order a previous delivery already created, or None."""
|
||||||
@@ -723,15 +907,17 @@ class TinyOrders:
|
|||||||
return detail
|
return detail
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def tag(self, tiny_id, known=False):
|
def tag(self, tiny_id, tags, known=False):
|
||||||
"""The SITE DTF marcador on the order, once. A retry that finds the
|
"""The order's marcadores (order_tags), once each. A retry that finds
|
||||||
order already created checks first, since POST adds another."""
|
the order already created checks first, since POST adds another."""
|
||||||
|
missing = list(tags)
|
||||||
if known:
|
if known:
|
||||||
have = self.request('GET', f'/pedidos/{tiny_id}/marcadores')
|
have = self.request('GET', f'/pedidos/{tiny_id}/marcadores')
|
||||||
have = have if isinstance(have, list) else have.get('itens') or []
|
have = have if isinstance(have, list) else have.get('itens') or []
|
||||||
if any(str(m.get('descricao', '')).strip().upper() == TAG for m in have):
|
names = {str(m.get('descricao', '')).strip().upper() for m in have}
|
||||||
return
|
missing = [tag for tag in tags if tag not in names]
|
||||||
self.request('POST', f'/pedidos/{tiny_id}/marcadores', json=[{'descricao': TAG}])
|
if missing:
|
||||||
|
self.request('POST', f'/pedidos/{tiny_id}/marcadores', json=[{'descricao': tag} for tag in missing])
|
||||||
|
|
||||||
def set_situacao(self, tiny_id, situacao):
|
def set_situacao(self, tiny_id, situacao):
|
||||||
self.request('PUT', f'/pedidos/{tiny_id}/situacao', json={'situacao': situacao})
|
self.request('PUT', f'/pedidos/{tiny_id}/situacao', json={'situacao': situacao})
|
||||||
@@ -762,16 +948,18 @@ class TinyOrders:
|
|||||||
'tiny_id': str(existing.get('id')), 'tiny_number': str(existing.get('numeroPedido'))}
|
'tiny_id': str(existing.get('id')), 'tiny_number': str(existing.get('numeroPedido'))}
|
||||||
tiny_id, situacao = existing.get('id'), existing.get('situacao')
|
tiny_id, situacao = existing.get('id'), existing.get('situacao')
|
||||||
else:
|
else:
|
||||||
contact_id = self.contact(payload['order'])
|
contact_id, seller = self.contact(payload['order'])
|
||||||
created = self.request('POST', '/pedidos', json=order_payload(
|
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',
|
receipt = {'provider': 'tiny', 'event_key': event_key, 'status': 'created',
|
||||||
'tiny_id': str(created.get('id')), 'tiny_number': str(created.get('numeroPedido'))}
|
'tiny_id': str(created.get('id')), 'tiny_number': str(created.get('numeroPedido'))}
|
||||||
tiny_id, situacao = created.get('id'), ABERTA
|
tiny_id, situacao = created.get('id'), ABERTA
|
||||||
# Tagged before it is approved, so a failure here is retried while the order is still open.
|
# Tagged before it is approved, so a failure here is retried while the order is still open.
|
||||||
if situacao == ABERTA:
|
if situacao == ABERTA:
|
||||||
self.tag(tiny_id, known=bool(existing))
|
tags = order_tags(payload)
|
||||||
receipt['marcador'] = TAG
|
self.tag(tiny_id, tags, known=bool(existing))
|
||||||
|
receipt['marcador'] = ', '.join(tags)
|
||||||
if status_updates() and situacao == ABERTA:
|
if status_updates() and situacao == ABERTA:
|
||||||
self.set_situacao(tiny_id, APROVADA)
|
self.set_situacao(tiny_id, APROVADA)
|
||||||
receipt['situacao'] = SITUACOES[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 argparse
|
||||||
import base64
|
import base64
|
||||||
import json
|
import json
|
||||||
|
import os
|
||||||
import sys
|
import sys
|
||||||
import time
|
import time
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
@@ -165,6 +166,15 @@ def conferir(orders, out):
|
|||||||
method, result = tiny.configured_pickup(orders)
|
method, result = tiny.configured_pickup(orders)
|
||||||
ok &= result == 'ok'
|
ok &= result == 'ok'
|
||||||
out(f"{tiny.PICKUP_SETTING} (retirada): {result} {method.get('nome') if method else ''}".rstrip())
|
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'}")
|
out(f"{tiny.STATUS_UPDATES_SETTING}: {'ligado' if tiny.status_updates() else 'desligado'}")
|
||||||
for name, result in tiny.check(orders=orders).items():
|
for name, result in tiny.check(orders=orders).items():
|
||||||
if name in ('pedidos', 'contatos'):
|
if name in ('pedidos', 'contatos'):
|
||||||
|
|||||||
73
app/unpaid.py
Normal file
73
app/unpaid.py
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
"""Orders made on the Site and never paid (Dropstar's Fase 2, front 9, 05/11/2026).
|
||||||
|
|
||||||
|
An approved quote is an order the customer did not pay yet: Kanban's
|
||||||
|
Cotações › "Aguardando pagamento" lists it, with how long ago it came and
|
||||||
|
when it expires, so the seller can charge it by WhatsApp. After
|
||||||
|
QUOTE_VALID_HOURS (24 h) without payment it expires on its own: its files
|
||||||
|
are freed for deletion and the customer gets an e-mail ("seu pedido expirou,
|
||||||
|
suba de novo quando quiser"). Never while a payment attempt is still live
|
||||||
|
(a Pix not yet expired, a card being processed), so a late payment always
|
||||||
|
finds its files. Números counts orders made, paid and expired, and the
|
||||||
|
abandonment rate.
|
||||||
|
"""
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
|
||||||
|
from . import mail, payments
|
||||||
|
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).
|
||||||
|
FINAL_INTENT = ('approved', 'rejected', 'cancelled', 'expired', 'refunded')
|
||||||
|
|
||||||
|
|
||||||
|
def expire(c, origin):
|
||||||
|
"""Expire the approved, unpaid quotes past QUOTE_VALID_HOURS: set
|
||||||
|
quotes.expired_at, free their files (payments.release_files) and queue the
|
||||||
|
customer's e-mail (mail.quote_expired). Returns how many expired."""
|
||||||
|
rows = c.execute('''SELECT q.* FROM dtf_local.quotes q
|
||||||
|
WHERE q.approved IS NOT NULL AND q.discarded_at IS NULL AND q.expired_at IS NULL
|
||||||
|
AND q.approved_at <= now() - make_interval(hours => %s)
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM dtf_local.orders o WHERE o.quote_id=q.id)
|
||||||
|
AND NOT EXISTS (
|
||||||
|
SELECT 1 FROM dtf_local.payment_intents i
|
||||||
|
WHERE i.quote_id=q.id
|
||||||
|
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)
|
||||||
|
-- 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), 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
|
||||||
|
# as open, or its own files would stay held.
|
||||||
|
payments.release_files(c, payments.quote_uploads(row['approved']))
|
||||||
|
# Only a quote that just ran out is news to the customer: the backlog
|
||||||
|
# from before this front existed expires silently on the first pass.
|
||||||
|
if row['approved_at'] > datetime.now(timezone.utc) - timedelta(hours=2 * QUOTE_VALID_HOURS):
|
||||||
|
mail.quote_expired(c, row, origin)
|
||||||
|
return len(rows)
|
||||||
|
|
||||||
|
|
||||||
|
def figures(c, start, end):
|
||||||
|
"""Números, for quotes approved between the local days `start` and `end`
|
||||||
|
(inclusive): {'made': n, 'paid': n, 'expired': n, 'waiting': n,
|
||||||
|
'abandon_pct': float | None}. Paid has an order; expired has expired_at;
|
||||||
|
waiting is neither yet. abandon_pct is expired / (paid + expired) * 100,
|
||||||
|
one decimal, None when both are 0."""
|
||||||
|
row = c.execute('''SELECT count(*) AS made,
|
||||||
|
count(*) FILTER (WHERE EXISTS (SELECT 1 FROM dtf_local.orders o WHERE o.quote_id=q.id)) AS paid,
|
||||||
|
count(*) FILTER (WHERE q.expired_at IS NOT NULL) AS expired,
|
||||||
|
count(*) FILTER (WHERE q.expired_at IS NULL
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM dtf_local.orders o WHERE o.quote_id=q.id)) AS waiting
|
||||||
|
FROM dtf_local.quotes q
|
||||||
|
WHERE q.discarded_at IS NULL AND q.approved_at IS NOT NULL
|
||||||
|
AND (q.approved_at AT TIME ZONE 'America/Sao_Paulo')::date BETWEEN %s AND %s''',
|
||||||
|
(start, end)).fetchone()
|
||||||
|
paid, expired = row['paid'], row['expired']
|
||||||
|
decided = paid + expired
|
||||||
|
return {'made': row['made'], 'paid': paid, 'expired': expired, 'waiting': row['waiting'],
|
||||||
|
'abandon_pct': round(expired / decided * 100, 1) if decided else None}
|
||||||
101
app/worker.py
101
app/worker.py
@@ -5,8 +5,10 @@ import os
|
|||||||
import threading
|
import threading
|
||||||
import time
|
import time
|
||||||
from http.server import BaseHTTPRequestHandler, HTTPServer
|
from http.server import BaseHTTPRequestHandler, HTTPServer
|
||||||
|
import psycopg
|
||||||
|
from botocore.exceptions import ClientError
|
||||||
from psycopg.types.json import Jsonb
|
from psycopg.types.json import Jsonb
|
||||||
from . import mail
|
from . import mail, observability, unpaid
|
||||||
from .adapters import FakeTiny, LocalS3Storage, require_runtime
|
from .adapters import FakeTiny, LocalS3Storage, require_runtime
|
||||||
from .core.secrets import load as load_secret_files
|
from .core.secrets import load as load_secret_files
|
||||||
from .core.db import connect
|
from .core.db import connect
|
||||||
@@ -15,18 +17,44 @@ from .scanning import ClamAV, scan_loop
|
|||||||
|
|
||||||
load_secret_files()
|
load_secret_files()
|
||||||
require_runtime()
|
require_runtime()
|
||||||
adapters = {'tiny': FakeTiny()}
|
# Production without the real Tiny (TINY_ADAPTER missing from the stack):
|
||||||
# Not yet confirmed against the client's account; see app/tiny.py.
|
# the sends wait and Sentry is told, instead of the simulator marking real
|
||||||
if os.environ.get('TINY_ADAPTER') == 'tiny':
|
# 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 .tiny import TinyOrders
|
||||||
from .cnpj import company
|
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_tick = 0.0
|
||||||
last_cleanup = 0.0
|
last_cleanup = 0.0
|
||||||
last_reconcile = 0.0
|
last_reconcile = 0.0
|
||||||
last_names = 0.0
|
last_names = 0.0
|
||||||
names_thread = None
|
names_thread = None
|
||||||
last_tiny_keepalive = 0.0
|
last_tiny_keepalive = 0.0
|
||||||
|
db_down_since = None
|
||||||
storage = LocalS3Storage()
|
storage = LocalS3Storage()
|
||||||
scan_thread = None
|
scan_thread = None
|
||||||
render_thread = None
|
render_thread = None
|
||||||
@@ -38,7 +66,19 @@ def cleanup():
|
|||||||
AND (expires_at<=now() OR (NOT complete AND created_at<now()-interval '1 day'))
|
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()
|
ORDER BY created_at FOR UPDATE SKIP LOCKED LIMIT 50""").fetchall()
|
||||||
for row in rows:
|
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'])
|
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']}/")
|
||||||
c.execute('UPDATE dtf_local.uploads SET purged_at=now() WHERE id=%s', (row['id'],))
|
c.execute('UPDATE dtf_local.uploads SET purged_at=now() WHERE id=%s', (row['id'],))
|
||||||
c.execute('DELETE FROM dtf_local.upload_thumbnails WHERE upload_id=%s', (row['id'],))
|
c.execute('DELETE FROM dtf_local.upload_thumbnails WHERE upload_id=%s', (row['id'],))
|
||||||
c.execute('DELETE FROM dtf_local.sessions WHERE expires_at<=now()')
|
c.execute('DELETE FROM dtf_local.sessions WHERE expires_at<=now()')
|
||||||
@@ -50,17 +90,37 @@ def cleanup():
|
|||||||
c.execute("DELETE FROM dtf_local.security_events WHERE created_at<now()-interval '30 days'")
|
c.execute("DELETE FROM dtf_local.security_events WHERE created_at<now()-interval '30 days'")
|
||||||
|
|
||||||
def tick():
|
def tick():
|
||||||
|
"""Deliver at most one outbox job; True when there was one, False otherwise."""
|
||||||
global last_tick
|
global last_tick
|
||||||
|
processed = False
|
||||||
with connect() as c:
|
with connect() as c:
|
||||||
job = c.execute('SELECT * FROM dtf_local.outbox WHERE delivered_at IS NULL AND available_at <= now() ORDER BY id FOR UPDATE SKIP LOCKED LIMIT 1').fetchone()
|
job = c.execute('SELECT * FROM dtf_local.outbox WHERE delivered_at IS NULL AND available_at <= now() ORDER BY id FOR UPDATE SKIP LOCKED LIMIT 1').fetchone()
|
||||||
if job:
|
if job:
|
||||||
|
processed = True
|
||||||
try:
|
try:
|
||||||
receipt = adapters[job['provider']].deliver(job['event_key'], job['payload'])
|
receipt = adapters[job['provider']].deliver(job['event_key'], job['payload'])
|
||||||
c.execute('UPDATE dtf_local.outbox SET delivered_at=now(), receipt=%s, attempts=attempts+1, last_error=NULL WHERE id=%s', (Jsonb(receipt),job['id']))
|
c.execute('UPDATE dtf_local.outbox SET delivered_at=now(), receipt=%s, attempts=attempts+1, last_error=NULL WHERE id=%s', (Jsonb(receipt),job['id']))
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
delay = min(1800, 2**min(job['attempts']+1, 10))
|
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']))
|
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()
|
last_tick = time.monotonic()
|
||||||
|
return processed
|
||||||
|
|
||||||
|
def drain(limit=50):
|
||||||
|
"""Deliver up to `limit` outbox jobs in one pass, so a backlog leaves at
|
||||||
|
once instead of one job per second (Critical Corrections item 9)."""
|
||||||
|
for _ in range(limit):
|
||||||
|
if not tick():
|
||||||
|
return
|
||||||
|
|
||||||
def tiny_keepalive():
|
def tiny_keepalive():
|
||||||
"""Keep a connected Tiny authorised even while no orders are sent.
|
"""Keep a connected Tiny authorised even while no orders are sent.
|
||||||
@@ -112,19 +172,37 @@ def resolve_names():
|
|||||||
names_thread.start()
|
names_thread.start()
|
||||||
|
|
||||||
def loop():
|
def loop():
|
||||||
global last_cleanup
|
global last_cleanup, db_down_since
|
||||||
|
delay = 1
|
||||||
while True:
|
while True:
|
||||||
try:
|
try:
|
||||||
tick()
|
drain()
|
||||||
if time.monotonic()-last_cleanup > 60:
|
if time.monotonic()-last_cleanup > 60:
|
||||||
cleanup()
|
cleanup()
|
||||||
|
# Approved quotes unpaid for 24 h expire on their own (front 9).
|
||||||
|
with connect() as c:
|
||||||
|
unpaid.expire(c, os.environ.get('PUBLIC_ORIGIN', 'http://localhost'))
|
||||||
last_cleanup = time.monotonic()
|
last_cleanup = time.monotonic()
|
||||||
mail.send_pending(connect)
|
mail.send_pending(connect)
|
||||||
tiny_keepalive()
|
tiny_keepalive()
|
||||||
reconcile_payments()
|
reconcile_payments()
|
||||||
resolve_names()
|
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:
|
except Exception:
|
||||||
logging.exception('Local worker tick failed')
|
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)
|
time.sleep(1)
|
||||||
|
|
||||||
class Health(BaseHTTPRequestHandler):
|
class Health(BaseHTTPRequestHandler):
|
||||||
@@ -145,6 +223,15 @@ class Health(BaseHTTPRequestHandler):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
if __name__ == '__main__':
|
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 = threading.Thread(target=scan_loop,args=(storage,),daemon=True)
|
||||||
scan_thread.start()
|
scan_thread.start()
|
||||||
render_thread = threading.Thread(target=render_loop,args=(storage,),daemon=True)
|
render_thread = threading.Thread(target=render_loop,args=(storage,),daemon=True)
|
||||||
|
|||||||
@@ -27,6 +27,10 @@ x-app: &app
|
|||||||
ALLOWED_HOSTS: ${ALLOWED_HOSTS:-localhost,127.0.0.1}
|
ALLOWED_HOSTS: ${ALLOWED_HOSTS:-localhost,127.0.0.1}
|
||||||
ALLOWED_ORIGINS: ${ALLOWED_ORIGINS:-http://localhost:${SITE_PORT:-8080},http://localhost:${KANBAN_PORT:-8081},http://127.0.0.1:${SITE_PORT:-8080},http://127.0.0.1:${KANBAN_PORT:-8081}}
|
ALLOWED_ORIGINS: ${ALLOWED_ORIGINS:-http://localhost:${SITE_PORT:-8080},http://localhost:${KANBAN_PORT:-8081},http://127.0.0.1:${SITE_PORT:-8080},http://127.0.0.1:${KANBAN_PORT:-8081}}
|
||||||
COOKIE_SECURE: "false"
|
COOKIE_SECURE: "false"
|
||||||
|
# Sentry stays off locally unless real DSNs are set in .env.
|
||||||
|
SENTRY_DSN_API: ${SENTRY_DSN_API:-}
|
||||||
|
SENTRY_DSN_WEB: ${SENTRY_DSN_WEB:-}
|
||||||
|
SENTRY_ENVIRONMENT: ${SENTRY_ENVIRONMENT:-}
|
||||||
# Sandbox testing only: set PAYMENT_ADAPTER=mercadopago with the MP_* test
|
# Sandbox testing only: set PAYMENT_ADAPTER=mercadopago with the MP_* test
|
||||||
# credentials, or TINY_ADAPTER=tiny with a TINY_TOKEN, in .env. Never real
|
# credentials, or TINY_ADAPTER=tiny with a TINY_TOKEN, in .env. Never real
|
||||||
# production credentials on a developer machine.
|
# production credentials on a developer machine.
|
||||||
@@ -58,6 +62,8 @@ x-app: &app
|
|||||||
QUOTE_AUTO_APPROVE: ${QUOTE_AUTO_APPROVE:-true}
|
QUOTE_AUTO_APPROVE: ${QUOTE_AUTO_APPROVE:-true}
|
||||||
QUOTE_AUTO_MAX_METRES: ${QUOTE_AUTO_MAX_METRES:-50}
|
QUOTE_AUTO_MAX_METRES: ${QUOTE_AUTO_MAX_METRES:-50}
|
||||||
MANUAL_FILE_EXTRA_CENTS: ${MANUAL_FILE_EXTRA_CENTS:-0}
|
MANUAL_FILE_EXTRA_CENTS: ${MANUAL_FILE_EXTRA_CENTS:-0}
|
||||||
|
# Fixed price of the designer's treatment per order; 0 hides the option.
|
||||||
|
TREATMENT_CENTS: ${TREATMENT_CENTS:-0}
|
||||||
TINY_ADAPTER: ${TINY_ADAPTER:-fake}
|
TINY_ADAPTER: ${TINY_ADAPTER:-fake}
|
||||||
TINY_CLIENT_ID: ${TINY_CLIENT_ID:-}
|
TINY_CLIENT_ID: ${TINY_CLIENT_ID:-}
|
||||||
TINY_CLIENT_SECRET: ${TINY_CLIENT_SECRET:-}
|
TINY_CLIENT_SECRET: ${TINY_CLIENT_SECRET:-}
|
||||||
@@ -66,6 +72,7 @@ x-app: &app
|
|||||||
TINY_PRODUCT_TEXTIL_AVULSA: ${TINY_PRODUCT_TEXTIL_AVULSA:-}
|
TINY_PRODUCT_TEXTIL_AVULSA: ${TINY_PRODUCT_TEXTIL_AVULSA:-}
|
||||||
TINY_PRODUCT_UV_FOLHA: ${TINY_PRODUCT_UV_FOLHA:-}
|
TINY_PRODUCT_UV_FOLHA: ${TINY_PRODUCT_UV_FOLHA:-}
|
||||||
TINY_PRODUCT_UV_AVULSA: ${TINY_PRODUCT_UV_AVULSA:-}
|
TINY_PRODUCT_UV_AVULSA: ${TINY_PRODUCT_UV_AVULSA:-}
|
||||||
|
TINY_PRODUCT_TREATMENT: ${TINY_PRODUCT_TREATMENT:-}
|
||||||
TINY_SKU_TEXTIL_FOLHA: ${TINY_SKU_TEXTIL_FOLHA:-}
|
TINY_SKU_TEXTIL_FOLHA: ${TINY_SKU_TEXTIL_FOLHA:-}
|
||||||
TINY_SKU_TEXTIL_AVULSA: ${TINY_SKU_TEXTIL_AVULSA:-}
|
TINY_SKU_TEXTIL_AVULSA: ${TINY_SKU_TEXTIL_AVULSA:-}
|
||||||
TINY_SKU_UV_FOLHA: ${TINY_SKU_UV_FOLHA:-}
|
TINY_SKU_UV_FOLHA: ${TINY_SKU_UV_FOLHA:-}
|
||||||
@@ -95,7 +102,7 @@ x-app: &app
|
|||||||
UPLOAD_PART_BYTES: ${UPLOAD_PART_BYTES:-8388608}
|
UPLOAD_PART_BYTES: ${UPLOAD_PART_BYTES:-8388608}
|
||||||
STORAGE_QUOTA_BYTES: ${STORAGE_QUOTA_BYTES:-53687091200}
|
STORAGE_QUOTA_BYTES: ${STORAGE_QUOTA_BYTES:-53687091200}
|
||||||
OWNER_UPLOAD_QUOTA_BYTES: ${OWNER_UPLOAD_QUOTA_BYTES:-10737418240}
|
OWNER_UPLOAD_QUOTA_BYTES: ${OWNER_UPLOAD_QUOTA_BYTES:-10737418240}
|
||||||
MAX_PENDING_UPLOADS: ${MAX_PENDING_UPLOADS:-10}
|
MAX_PENDING_UPLOADS: ${MAX_PENDING_UPLOADS:-30}
|
||||||
SCAN_MAX_BYTES: ${SCAN_MAX_BYTES:-2097152000}
|
SCAN_MAX_BYTES: ${SCAN_MAX_BYTES:-2097152000}
|
||||||
networks: [local]
|
networks: [local]
|
||||||
init: true
|
init: true
|
||||||
@@ -210,6 +217,10 @@ services:
|
|||||||
|
|
||||||
api:
|
api:
|
||||||
<<: *app
|
<<: *app
|
||||||
|
environment:
|
||||||
|
<<: *environment
|
||||||
|
# CI and local tests exercise the pool (Critical Corrections item 4).
|
||||||
|
DB_POOL: "on"
|
||||||
command: uvicorn app.app:app --host 0.0.0.0 --port 8000 --no-access-log
|
command: uvicorn app.app:app --host 0.0.0.0 --port 8000 --no-access-log
|
||||||
depends_on:
|
depends_on:
|
||||||
db-init: {condition: service_completed_successfully}
|
db-init: {condition: service_completed_successfully}
|
||||||
@@ -222,6 +233,10 @@ services:
|
|||||||
|
|
||||||
worker:
|
worker:
|
||||||
<<: *app
|
<<: *app
|
||||||
|
environment:
|
||||||
|
<<: *environment
|
||||||
|
# CI and local tests exercise the pool (Critical Corrections item 4).
|
||||||
|
DB_POOL: "on"
|
||||||
command: python -m app.worker
|
command: python -m app.worker
|
||||||
depends_on:
|
depends_on:
|
||||||
api: {condition: service_healthy}
|
api: {condition: service_healthy}
|
||||||
@@ -263,6 +278,7 @@ services:
|
|||||||
# Empty unless testing Mercado Pago's card form; see docs/LOCAL_SETUP.md.
|
# Empty unless testing Mercado Pago's card form; see docs/LOCAL_SETUP.md.
|
||||||
PAYMENT_CSP_SOURCES: ${PAYMENT_CSP_SOURCES:-}
|
PAYMENT_CSP_SOURCES: ${PAYMENT_CSP_SOURCES:-}
|
||||||
PAYMENT_CHALLENGE_SOURCES: ${PAYMENT_CHALLENGE_SOURCES:-}
|
PAYMENT_CHALLENGE_SOURCES: ${PAYMENT_CHALLENGE_SOURCES:-}
|
||||||
|
SENTRY_CSP_SOURCES: ""
|
||||||
ports:
|
ports:
|
||||||
# Published ports are host-wide even bound to loopback, so on a shared
|
# Published ports are host-wide even bound to loopback, so on a shared
|
||||||
# machine any of them can collide with something unrelated. CI overrides
|
# machine any of them can collide with something unrelated. CI overrides
|
||||||
@@ -288,6 +304,7 @@ services:
|
|||||||
S3_PUBLIC_ENDPOINT: ${S3_PUBLIC_ENDPOINT:-http://localhost:${STORAGE_PORT:-9000}}
|
S3_PUBLIC_ENDPOINT: ${S3_PUBLIC_ENDPOINT:-http://localhost:${STORAGE_PORT:-9000}}
|
||||||
PAYMENT_CSP_SOURCES: ""
|
PAYMENT_CSP_SOURCES: ""
|
||||||
PAYMENT_CHALLENGE_SOURCES: ""
|
PAYMENT_CHALLENGE_SOURCES: ""
|
||||||
|
SENTRY_CSP_SOURCES: ""
|
||||||
ports: ["127.0.0.1:${KANBAN_PORT:-8081}:80"]
|
ports: ["127.0.0.1:${KANBAN_PORT:-8081}:80"]
|
||||||
networks: [local, edge]
|
networks: [local, edge]
|
||||||
depends_on:
|
depends_on:
|
||||||
|
|||||||
@@ -6,6 +6,8 @@ ARG PYTHON_BASE_IMAGE=python:3.12-slim@sha256:2f17fc044b579bab302c2e8054d3a686e2
|
|||||||
FROM ${PYTHON_BASE_IMAGE}
|
FROM ${PYTHON_BASE_IMAGE}
|
||||||
|
|
||||||
ARG VCS_REF=unknown
|
ARG VCS_REF=unknown
|
||||||
|
# The commit this image was built from, as the Sentry release (app/observability.py).
|
||||||
|
ENV RELEASE=$VCS_REF
|
||||||
LABEL org.opencontainers.image.title="DTF Portal/API" \
|
LABEL org.opencontainers.image.title="DTF Portal/API" \
|
||||||
org.opencontainers.image.revision="$VCS_REF" \
|
org.opencontainers.image.revision="$VCS_REF" \
|
||||||
org.opencontainers.image.source="DTF System repository"
|
org.opencontainers.image.source="DTF System repository"
|
||||||
|
|||||||
@@ -26,8 +26,8 @@ server {
|
|||||||
add_header X-Content-Type-Options nosniff always;
|
add_header X-Content-Type-Options nosniff always;
|
||||||
add_header Referrer-Policy no-referrer always;
|
add_header Referrer-Policy no-referrer always;
|
||||||
add_header X-Frame-Options DENY always;
|
add_header X-Frame-Options DENY always;
|
||||||
add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
|
add_header Permissions-Policy "camera=(self), microphone=(), geolocation=()" always;
|
||||||
add_header Content-Security-Policy "default-src 'self'; script-src 'self' @SCRIPT_HASHES@ ${PAYMENT_CSP_SOURCES}; script-src-attr 'none'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: blob: https://cdn.vnda.com.br ${PAYMENT_CSP_SOURCES}; connect-src 'self' ${S3_PUBLIC_ENDPOINT} https://cdn.vnda.com.br ${PAYMENT_CSP_SOURCES}; frame-src 'self' ${PAYMENT_CSP_SOURCES} ${PAYMENT_CHALLENGE_SOURCES}; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self' ${PAYMENT_CHALLENGE_SOURCES}" always;
|
add_header Content-Security-Policy "default-src 'self'; script-src 'self' @SCRIPT_HASHES@ ${PAYMENT_CSP_SOURCES}; script-src-attr 'none'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: blob: https://cdn.vnda.com.br ${S3_PUBLIC_ENDPOINT} ${PAYMENT_CSP_SOURCES}; media-src 'self' ${S3_PUBLIC_ENDPOINT}; connect-src 'self' ${S3_PUBLIC_ENDPOINT} https://cdn.vnda.com.br ${PAYMENT_CSP_SOURCES} ${SENTRY_CSP_SOURCES}; frame-src 'self' ${PAYMENT_CSP_SOURCES} ${PAYMENT_CHALLENGE_SOURCES}; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self' ${PAYMENT_CHALLENGE_SOURCES}" always;
|
||||||
|
|
||||||
location = /health { access_log off; return 200 'ok'; }
|
location = /health { access_log off; return 200 'ok'; }
|
||||||
location /api/ {
|
location /api/ {
|
||||||
@@ -49,7 +49,7 @@ server {
|
|||||||
# Always revalidate HTML/JS/CSS after a deployment. Without this, a browser
|
# Always revalidate HTML/JS/CSS after a deployment. Without this, a browser
|
||||||
# can pair a new Kanban page with a cached older script after a rollout.
|
# can pair a new Kanban page with a cached older script after a rollout.
|
||||||
# The Site's product pages and cart are addresses of the same page (web/site-pages.js).
|
# The Site's product pages and cart are addresses of the same page (web/site-pages.js).
|
||||||
location ~ ^/(arquivo-por-metro|artes-avulsas|uv-arquivo-por-metro|uv-artes-avulsas|carrinho|pagamento|pagamento/pix)/?$ {
|
location ~ ^/(arquivo-por-metro|artes-avulsas|uv-arquivo-por-metro|uv-artes-avulsas|premium|carrinho|pagamento|pagamento/pix)/?$ {
|
||||||
expires -1;
|
expires -1;
|
||||||
try_files /index.html =404;
|
try_files /index.html =404;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,6 +15,11 @@ PUBLIC_HOST=dtf.example.invalid
|
|||||||
KANBAN_HOST=kanban-dtf.example.invalid
|
KANBAN_HOST=kanban-dtf.example.invalid
|
||||||
SITE_PORT=8080
|
SITE_PORT=8080
|
||||||
KANBAN_PORT=8081
|
KANBAN_PORT=8081
|
||||||
|
# API processes: 2 by default; 1 runs one process, as before. API only.
|
||||||
|
API_WORKERS=2
|
||||||
|
# Database connection pool: off keeps one connection per block, as before.
|
||||||
|
DB_POOL=off
|
||||||
|
DB_POOL_SIZE=20
|
||||||
|
|
||||||
R2_ENDPOINT=TBD
|
R2_ENDPOINT=TBD
|
||||||
R2_PUBLIC_ENDPOINT=TBD
|
R2_PUBLIC_ENDPOINT=TBD
|
||||||
@@ -37,13 +42,19 @@ TINY_ADAPTER=TBD
|
|||||||
# redirect URL registered there must equal TINY_REDIRECT_URI.
|
# redirect URL registered there must equal TINY_REDIRECT_URI.
|
||||||
TINY_CLIENT_ID=TBD
|
TINY_CLIENT_ID=TBD
|
||||||
TINY_REDIRECT_URI=https://<KANBAN_DOMAIN>/api/operator/tiny/callback
|
TINY_REDIRECT_URI=https://<KANBAN_DOMAIN>/api/operator/tiny/callback
|
||||||
|
TREATMENT_CENTS=0
|
||||||
TINY_PRODUCT_TEXTIL_FOLHA=TBD
|
TINY_PRODUCT_TEXTIL_FOLHA=TBD
|
||||||
TINY_PRODUCT_TEXTIL_AVULSA=TBD
|
TINY_PRODUCT_TEXTIL_AVULSA=TBD
|
||||||
TINY_PRODUCT_UV_FOLHA=TBD
|
TINY_PRODUCT_UV_FOLHA=TBD
|
||||||
TINY_PRODUCT_UV_AVULSA=TBD
|
TINY_PRODUCT_UV_AVULSA=TBD
|
||||||
|
TINY_PRODUCT_TREATMENT=TBD
|
||||||
TINY_FORMA_ENVIO_RETIRADA=TBD
|
TINY_FORMA_ENVIO_RETIRADA=TBD
|
||||||
# true only at go-live, after the n8n DTFIMP designer branch is removed.
|
# true only at go-live, after the n8n DTFIMP designer branch is removed.
|
||||||
TINY_STATUS_UPDATES=false
|
TINY_STATUS_UPDATES=false
|
||||||
|
# Tiny id of the forma de recebimento "Boleto" (montador Venda orders).
|
||||||
|
TINY_RECEIPT_BOLETO=
|
||||||
|
# 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.
|
# E-mail (password recovery and team alerts). off until the SMTP account exists.
|
||||||
MAIL_ADAPTER=off
|
MAIL_ADAPTER=off
|
||||||
MAIL_FROM=DTF Dropstar <nao-responda@SITE_DOMAIN>
|
MAIL_FROM=DTF Dropstar <nao-responda@SITE_DOMAIN>
|
||||||
@@ -67,6 +78,11 @@ BACKUP_SECRET_ACCESS_KEY=TBD
|
|||||||
BACKUP_AGE_RECIPIENT=age1...
|
BACKUP_AGE_RECIPIENT=age1...
|
||||||
BACKUP_HOUR=3
|
BACKUP_HOUR=3
|
||||||
|
|
||||||
|
# Sentry: empty DSNs keep it off; the environment defaults to production.
|
||||||
|
SENTRY_DSN_API=
|
||||||
|
SENTRY_DSN_WEB=
|
||||||
|
SENTRY_ENVIRONMENT=
|
||||||
|
|
||||||
# Names of external Portainer/Docker Swarm secrets, never their values.
|
# Names of external Portainer/Docker Swarm secrets, never their values.
|
||||||
DATABASE_URL_SECRET=TBD
|
DATABASE_URL_SECRET=TBD
|
||||||
DATABASE_ADMIN_URL_SECRET=TBD
|
DATABASE_ADMIN_URL_SECRET=TBD
|
||||||
|
|||||||
@@ -41,9 +41,9 @@ SOURCE_BLOCKERS = {
|
|||||||
'app/runtime.py': (
|
'app/runtime.py': (
|
||||||
'payment = FakePayment()',
|
'payment = FakePayment()',
|
||||||
),
|
),
|
||||||
'app/worker.py': (
|
# app/worker.py's "adapters = {'tiny': FakeTiny()}" left on 2026-11-27: in
|
||||||
"adapters = {'tiny': FakeTiny()}",
|
# 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):
|
def test_fake_checkout_is_explicitly_blocked(self):
|
||||||
errors = source_errors()
|
errors = source_errors()
|
||||||
self.assertTrue(any('app/runtime.py remains local-only' in error for error in 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):
|
def test_secret_reuse_and_incoherent_limits_are_rejected(self):
|
||||||
values = valid_config()
|
values = valid_config()
|
||||||
|
|||||||
@@ -8,6 +8,14 @@ x-app-environment: &app-environment
|
|||||||
# Must differ from POSTGRES_PASSWORD: the runtime role is DML-only, and reusing
|
# Must differ from POSTGRES_PASSWORD: the runtime role is DML-only, and reusing
|
||||||
# the administrator credential would make that restriction meaningless.
|
# the administrator credential would make that restriction meaningless.
|
||||||
DATABASE_PASSWORD: ${APP_DB_PASSWORD:?set APP_DB_PASSWORD}
|
DATABASE_PASSWORD: ${APP_DB_PASSWORD:?set APP_DB_PASSWORD}
|
||||||
|
# Reuse database connections per API/worker process when on; off keeps one
|
||||||
|
# connection per `with` block, exactly as before (the production default).
|
||||||
|
DB_POOL: ${DB_POOL:-off}
|
||||||
|
DB_POOL_SIZE: ${DB_POOL_SIZE:-20}
|
||||||
|
# Sentry: empty DSNs leave it off; the environment defaults to production.
|
||||||
|
SENTRY_DSN_API: ${SENTRY_DSN_API:-}
|
||||||
|
SENTRY_DSN_WEB: ${SENTRY_DSN_WEB:-}
|
||||||
|
SENTRY_ENVIRONMENT: ${SENTRY_ENVIRONMENT:-production}
|
||||||
S3_ENDPOINT: ${R2_ENDPOINT:?set R2_ENDPOINT}
|
S3_ENDPOINT: ${R2_ENDPOINT:?set R2_ENDPOINT}
|
||||||
S3_PUBLIC_ENDPOINT: ${R2_ENDPOINT:?set R2_ENDPOINT}
|
S3_PUBLIC_ENDPOINT: ${R2_ENDPOINT:?set R2_ENDPOINT}
|
||||||
S3_BUCKET: ${R2_BUCKET:?set R2_BUCKET}
|
S3_BUCKET: ${R2_BUCKET:?set R2_BUCKET}
|
||||||
@@ -75,10 +83,16 @@ x-app-environment: &app-environment
|
|||||||
# (CDR, AI, PSD, TIFF, or a length the customer typed). Dropstar set R$ 2,00
|
# (CDR, AI, PSD, TIFF, or a length the customer typed). Dropstar set R$ 2,00
|
||||||
# a metro on 2026-10-23; 0 adds nothing. The Site shows it before payment.
|
# a metro on 2026-10-23; 0 adds nothing. The Site shows it before payment.
|
||||||
MANUAL_FILE_EXTRA_CENTS: ${MANUAL_FILE_EXTRA_CENTS:-200}
|
MANUAL_FILE_EXTRA_CENTS: ${MANUAL_FILE_EXTRA_CENTS:-200}
|
||||||
|
# Fixed price of the designer's treatment per order, in cents; 0 hides it.
|
||||||
|
TREATMENT_CENTS: ${TREATMENT_CENTS:-0}
|
||||||
# Print files longer than 5,08 m are written at their real size, which Corel
|
# Print files longer than 5,08 m are written at their real size, which Corel
|
||||||
# reads (2026-10-28). true goes back to PDF's /UserUnit scale, for a RIP that
|
# reads (2026-10-28). true goes back to PDF's /UserUnit scale, for a RIP that
|
||||||
# refuses pages over 5,08 m.
|
# refuses pages over 5,08 m.
|
||||||
PRINT_PAGE_SCALE: ${PRINT_PAGE_SCALE:-false}
|
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
|
# 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
|
# 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
|
# set now: they let an operator connect Tiny from the Kanban, and the worker
|
||||||
@@ -96,6 +110,11 @@ x-app-environment: &app-environment
|
|||||||
TINY_PRODUCT_TEXTIL_AVULSA: ${TINY_PRODUCT_TEXTIL_AVULSA:-}
|
TINY_PRODUCT_TEXTIL_AVULSA: ${TINY_PRODUCT_TEXTIL_AVULSA:-}
|
||||||
TINY_PRODUCT_UV_FOLHA: ${TINY_PRODUCT_UV_FOLHA:-}
|
TINY_PRODUCT_UV_FOLHA: ${TINY_PRODUCT_UV_FOLHA:-}
|
||||||
TINY_PRODUCT_UV_AVULSA: ${TINY_PRODUCT_UV_AVULSA:-}
|
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_FOLHA: ${TINY_SKU_TEXTIL_FOLHA:-}
|
||||||
TINY_SKU_TEXTIL_AVULSA: ${TINY_SKU_TEXTIL_AVULSA:-}
|
TINY_SKU_TEXTIL_AVULSA: ${TINY_SKU_TEXTIL_AVULSA:-}
|
||||||
TINY_SKU_UV_FOLHA: ${TINY_SKU_UV_FOLHA:-}
|
TINY_SKU_UV_FOLHA: ${TINY_SKU_UV_FOLHA:-}
|
||||||
@@ -113,6 +132,12 @@ x-app-environment: &app-environment
|
|||||||
# Optional e-commerce channel id for Site orders. Without it the order still
|
# Optional e-commerce channel id for Site orders. Without it the order still
|
||||||
# carries DTF-<n> as numeroPedidoEcommerce, with no channel.
|
# carries DTF-<n> as numeroPedidoEcommerce, with no channel.
|
||||||
TINY_ECOMMERCE_ID: ${TINY_ECOMMERCE_ID:-}
|
TINY_ECOMMERCE_ID: ${TINY_ECOMMERCE_ID:-}
|
||||||
|
# The Tiny forma de recebimento id of "Boleto", for invoiced montador Venda
|
||||||
|
# orders (front 7a.3). Empty: the order goes without one and its note says so.
|
||||||
|
TINY_RECEIPT_BOLETO: ${TINY_RECEIPT_BOLETO:-}
|
||||||
|
# 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
|
# Sets "Aprovada" on paid orders and "Pronto para envio" on finished pickup
|
||||||
# orders, which the client's Tiny -> n8n notices send to customers. Turn on
|
# orders, which the client's Tiny -> n8n notices send to customers. Turn on
|
||||||
# only together with TINY_ADAPTER=tiny and after n8n stops sending the
|
# only together with TINY_ADAPTER=tiny and after n8n stops sending the
|
||||||
@@ -142,7 +167,7 @@ x-app-environment: &app-environment
|
|||||||
# Sheets of several GB are the normal order, so room for many of them.
|
# Sheets of several GB are the normal order, so room for many of them.
|
||||||
STORAGE_QUOTA_BYTES: "${STORAGE_QUOTA_BYTES:-536870912000}"
|
STORAGE_QUOTA_BYTES: "${STORAGE_QUOTA_BYTES:-536870912000}"
|
||||||
OWNER_UPLOAD_QUOTA_BYTES: "${OWNER_UPLOAD_QUOTA_BYTES:-53687091200}"
|
OWNER_UPLOAD_QUOTA_BYTES: "${OWNER_UPLOAD_QUOTA_BYTES:-53687091200}"
|
||||||
MAX_PENDING_UPLOADS: "10"
|
MAX_PENDING_UPLOADS: "30"
|
||||||
# ClamAV scans up to its own limit, 2000 MiB (infra/clamd.conf); a larger
|
# ClamAV scans up to its own limit, 2000 MiB (infra/clamd.conf); a larger
|
||||||
# file, up to the 4 GB above, is released after the file-format check
|
# file, up to the 4 GB above, is released after the file-format check
|
||||||
# (app/scanning.py, check_large).
|
# (app/scanning.py, check_large).
|
||||||
@@ -210,13 +235,20 @@ services:
|
|||||||
|
|
||||||
api:
|
api:
|
||||||
image: ${API_IMAGE:-gitea.blyzer.com.br/blyzer/dtf-api}:${IMAGE_TAG:-latest}
|
image: ${API_IMAGE:-gitea.blyzer.com.br/blyzer/dtf-api}:${IMAGE_TAG:-latest}
|
||||||
environment: *app-environment
|
environment:
|
||||||
|
<<: *app-environment
|
||||||
|
# Two uvicorn processes by default (Critical Corrections item 2, step 1):
|
||||||
|
# a slow 150 MB PDF check no longer holds every request in the only one.
|
||||||
|
# API_WORKERS=1 restores one process without a new image.
|
||||||
|
WEB_CONCURRENCY: "${API_WORKERS:-2}"
|
||||||
networks: [backend, egress]
|
networks: [backend, egress]
|
||||||
read_only: true
|
read_only: true
|
||||||
# Swarm ignores the short `tmpfs:` key: a read-only container then has no
|
# Swarm ignores the short `tmpfs:` key: a read-only container then has no
|
||||||
# writable /tmp at all. The long volume syntax is what a stack honours.
|
# writable /tmp at all. The long volume syntax is what a stack honours.
|
||||||
|
# 512 MiB, not 256: with two processes each may write a 150 MB PDF from the
|
||||||
|
# grade check at the same time.
|
||||||
volumes:
|
volumes:
|
||||||
- {type: tmpfs, target: /tmp, tmpfs: {size: 268435456}}
|
- {type: tmpfs, target: /tmp, tmpfs: {size: 536870912}}
|
||||||
healthcheck:
|
healthcheck:
|
||||||
test: [CMD-SHELL, 'python -c "import os,urllib.request; r=urllib.request.Request(\"http://localhost:8000/health\",headers={\"Host\":os.environ[\"PUBLIC_HOST\"]}); urllib.request.urlopen(r,timeout=3)"']
|
test: [CMD-SHELL, 'python -c "import os,urllib.request; r=urllib.request.Request(\"http://localhost:8000/health\",headers={\"Host\":os.environ[\"PUBLIC_HOST\"]}); urllib.request.urlopen(r,timeout=3)"']
|
||||||
interval: 15s
|
interval: 15s
|
||||||
@@ -225,6 +257,7 @@ services:
|
|||||||
start_period: 30s
|
start_period: 30s
|
||||||
deploy:
|
deploy:
|
||||||
replicas: 1
|
replicas: 1
|
||||||
|
update_config: {order: start-first, failure_action: rollback}
|
||||||
restart_policy: {condition: on-failure, delay: 5s}
|
restart_policy: {condition: on-failure, delay: 5s}
|
||||||
|
|
||||||
worker:
|
worker:
|
||||||
@@ -284,6 +317,8 @@ services:
|
|||||||
# Mercado Pago's card form loads from these origins; empty keeps the
|
# Mercado Pago's card form loads from these origins; empty keeps the
|
||||||
# Site at script-src 'self'. Set together with the Mercado Pago adapter.
|
# Site at script-src 'self'. Set together with the Mercado Pago adapter.
|
||||||
PAYMENT_CSP_SOURCES: ${PAYMENT_CSP_SOURCES:-}
|
PAYMENT_CSP_SOURCES: ${PAYMENT_CSP_SOURCES:-}
|
||||||
|
# The Sentry ingest origin(s) for connect-src; empty until the DSN exists.
|
||||||
|
SENTRY_CSP_SOURCES: ${SENTRY_CSP_SOURCES:-https://o4510863040905216.ingest.us.sentry.io}
|
||||||
# The bank's confirmation page for debit and other 3-D Secure cards is
|
# The bank's confirmation page for debit and other 3-D Secure cards is
|
||||||
# on the issuer's own domain, so it cannot be listed: "https:" lets
|
# on the issuer's own domain, so it cannot be listed: "https:" lets
|
||||||
# frames and form posts reach it (never scripts). Empty turns it off.
|
# frames and form posts reach it (never scripts). Empty turns it off.
|
||||||
@@ -302,6 +337,7 @@ services:
|
|||||||
start_period: 15s
|
start_period: 15s
|
||||||
deploy:
|
deploy:
|
||||||
replicas: 1
|
replicas: 1
|
||||||
|
update_config: {order: start-first, failure_action: rollback}
|
||||||
restart_policy: {condition: on-failure, delay: 5s}
|
restart_policy: {condition: on-failure, delay: 5s}
|
||||||
|
|
||||||
kanban:
|
kanban:
|
||||||
@@ -312,6 +348,8 @@ services:
|
|||||||
S3_PUBLIC_ENDPOINT: ${R2_ENDPOINT:?set R2_ENDPOINT}
|
S3_PUBLIC_ENDPOINT: ${R2_ENDPOINT:?set R2_ENDPOINT}
|
||||||
PAYMENT_CSP_SOURCES: ""
|
PAYMENT_CSP_SOURCES: ""
|
||||||
PAYMENT_CHALLENGE_SOURCES: ""
|
PAYMENT_CHALLENGE_SOURCES: ""
|
||||||
|
# The Kanban reports to Sentry too; set from the browser DSN host.
|
||||||
|
SENTRY_CSP_SOURCES: ${SENTRY_CSP_SOURCES:-https://o4510863040905216.ingest.us.sentry.io}
|
||||||
networks: [backend]
|
networks: [backend]
|
||||||
ports:
|
ports:
|
||||||
- target: 8080
|
- target: 8080
|
||||||
@@ -326,6 +364,7 @@ services:
|
|||||||
start_period: 15s
|
start_period: 15s
|
||||||
deploy:
|
deploy:
|
||||||
replicas: 1
|
replicas: 1
|
||||||
|
update_config: {order: start-first, failure_action: rollback}
|
||||||
restart_policy: {condition: on-failure, delay: 5s}
|
restart_policy: {condition: on-failure, delay: 5s}
|
||||||
|
|
||||||
configs:
|
configs:
|
||||||
|
|||||||
@@ -238,6 +238,24 @@ storage permits; otherwise reselect them. Saved quote IDs also survive reloads.
|
|||||||
Clearing cookies loses a guest session, while registered customers can sign in
|
Clearing cookies loses a guest session, while registered customers can sign in
|
||||||
again. The operator can still inspect order records.
|
again. The operator can still inspect order records.
|
||||||
|
|
||||||
|
## Schema changes
|
||||||
|
|
||||||
|
`app/schema.sql` is the frozen baseline: every start runs it, and nothing new
|
||||||
|
is added to it. A schema change is a new file in `app/migrations/`, named with
|
||||||
|
a timestamp and a short slug, `YYYYMMDDHHMM_description.sql` (for example
|
||||||
|
`202611091607_checks-current-lists.sql`). `app/migrate.py` runs every file not
|
||||||
|
yet recorded in `dtf_local.migrations`, in name order, each recorded in the
|
||||||
|
same transaction and under an advisory lock; `app/bootstrap.py` and
|
||||||
|
`app/core/db.py` call it right after the schema and before the grants, so a
|
||||||
|
table a migration creates is granted to the runtime role. Never edit an applied
|
||||||
|
migration: add a new one instead. Any file in that folder whose name does not
|
||||||
|
match `^\d{12}_[a-z0-9-]+\.sql$` stops the start, so a typo is never skipped.
|
||||||
|
|
||||||
|
Widening a CHECK constraint is a DROP + ADD in a migration, with the full list;
|
||||||
|
`app/schema.sql` only creates the three initial ones when missing. A rollback
|
||||||
|
to an image at or after this change is safe: an older image ignores migration
|
||||||
|
names it does not know.
|
||||||
|
|
||||||
## Print files
|
## Print files
|
||||||
|
|
||||||
Every paid order queues one print-file job per item. The worker renders a PDF
|
Every paid order queues one print-file job per item. The worker renders a PDF
|
||||||
|
|||||||
@@ -173,7 +173,10 @@ affect stored data or retention.
|
|||||||
In the Portainer stack variables, change `IMAGE_TAG` from `latest` to the full
|
In the Portainer stack variables, change `IMAGE_TAG` from `latest` to the full
|
||||||
SHA of the last known-good Gitea commit and redeploy. This rolls back Site, API,
|
SHA of the last known-good Gitea commit and redeploy. This rolls back Site, API,
|
||||||
Kanban, and worker code; it does not undo database migrations or restore data.
|
Kanban, and worker code; it does not undo database migrations or restore data.
|
||||||
After recovery and a corrected release, return `IMAGE_TAG` to `latest`.
|
Rolling back to an image from before the timestamped migrations can still fail
|
||||||
|
if the data uses newer values; images from that change on ignore migration
|
||||||
|
names they do not know, so a rollback is safe. After recovery and a corrected
|
||||||
|
release, return `IMAGE_TAG` to `latest`.
|
||||||
|
|
||||||
## 6. Before opening to customers
|
## 6. Before opening to customers
|
||||||
|
|
||||||
@@ -207,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
|
Change it only on the client's instruction; the Site shows the new price after
|
||||||
the redeploy.
|
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
|
## 8. Correios
|
||||||
|
|
||||||
PAC and SEDEX appear in the cart once `CORREIOS_CODIGO_ACESSO` (the CWS access
|
PAC and SEDEX appear in the cart once `CORREIOS_CODIGO_ACESSO` (the CWS access
|
||||||
@@ -223,6 +229,36 @@ If a service is refused, the contract uses other codes: set `CORREIOS_COD_PAC`
|
|||||||
or `CORREIOS_COD_SEDEX`. Correios price by the box, so `JADLOG_CAIXA_CM` and the
|
or `CORREIOS_COD_SEDEX`. Correios price by the box, so `JADLOG_CAIXA_CM` and the
|
||||||
package weights must be set (they already are for Jadlog).
|
package weights must be set (they already are for Jadlog).
|
||||||
|
|
||||||
|
## 9. API processes
|
||||||
|
|
||||||
|
`API_WORKERS` is how many uvicorn processes the API container runs (default 2;
|
||||||
|
`1` runs one process, as before). More than one keeps a slow checkout, such as
|
||||||
|
a PDF of up to 150 MB being checked, from holding every other request in the
|
||||||
|
only process; the API's `/tmp` is sized for two such checks at once. It applies
|
||||||
|
to the API only, never to the worker. Set it in the stack's environment and
|
||||||
|
redeploy.
|
||||||
|
|
||||||
|
## 10. Database connection pool
|
||||||
|
|
||||||
|
`DB_POOL` reuses database connections inside each API process and the worker
|
||||||
|
instead of opening one per `with` block (default `off`, the previous
|
||||||
|
behaviour). Set it to `on` in the stack's environment and redeploy to keep
|
||||||
|
between 1 and `DB_POOL_SIZE` connections per process (`DB_POOL_SIZE` defaults
|
||||||
|
to 20); set it back to `off` to return to one connection per block.
|
||||||
|
|
||||||
|
## 11. Sentry
|
||||||
|
|
||||||
|
Sentry is built into the API, the worker, the Site and the Kanban, and stays
|
||||||
|
off while the DSNs are empty. Set `SENTRY_DSN_API` and `SENTRY_DSN_WEB` in the
|
||||||
|
stack's environment, and optionally `SENTRY_ENVIRONMENT` (defaults to
|
||||||
|
`production`). The API and worker initialise from `SENTRY_DSN_API`; the browser
|
||||||
|
reads `SENTRY_DSN_WEB` from `/api/session` on the Site and from
|
||||||
|
`/api/operator/me` on the Kanban. When the DSNs exist, also set
|
||||||
|
`SENTRY_CSP_SOURCES` to the Sentry ingest origin, such as
|
||||||
|
`https://o123.ingest.sentry.io` (or `https://*.ingest.sentry.io`), so the CSP
|
||||||
|
`connect-src` allows the browser to send events. No image change is needed to
|
||||||
|
switch it on: update the stack variables and redeploy.
|
||||||
|
|
||||||
## Current blocker
|
## Current blocker
|
||||||
|
|
||||||
This is the final deployment shape, but it is not authorized for production
|
This is the final deployment shape, but it is not authorized for production
|
||||||
|
|||||||
90
docs/ROADMAP-FASE-2-2026-11-06.md
Normal file
90
docs/ROADMAP-FASE-2-2026-11-06.md
Normal file
@@ -0,0 +1,90 @@
|
|||||||
|
# Roadmap da 3ª rodada e Fase 2 — Kanban turbinado
|
||||||
|
|
||||||
|
Base: PDF de Marcus Fernandes, 05/11/2026, versão 2; leitura do repositório em 06/11/2026. Este plano ordena **entregas por esforço crescente**, preservando duas travas do documento: a correção **0.1 começa imediatamente e bloqueia a divulgação do site**, e **nenhuma frente da Fase 2 entra em produção antes da bateria de testes da seção 0**. Horas são faixas preliminares de engenharia, incluindo implementação e validação local; não são prazo corrido nem promessa de implantação. Uma pessoa pode tocar itens rápidos enquanto a correção 0.1 avança.
|
||||||
|
|
||||||
|
**Execução em 06/11:** a Etapa 0 está implementada no código e validada localmente. A prova 0.1 passou a recortar os 15 cm no trecho de traço mais fino de cada classe, gera o PNG final do filho, limpa o contato ao responder a prova e mantém pai e filho na mesma máquina. A 0.11 foi ensaiada no reset local com o `ops.launch_reset` (sem reiniciar a numeração) e a 0.12 passou a registrar tempos do site/Prumo em Números. A bateria local passou: unitários (o de preços no host, porque o container da API não tem Node), smoke, workflow, pagamento, impressão/prova, usuários, Kanban, cotações, segurança, retenção, backup e os dois testes de navegador. Nada foi implantado em produção; a 0.11 em dados reais continua dependendo de autorização, backup e janela.
|
||||||
|
|
||||||
|
## O que o código já comprova
|
||||||
|
|
||||||
|
- O pagamento cria o pedido e dispara a geração do arquivo e o card de prova; há caminhos separados para pedido de teste e pagamento registrado pelo balcão ([`app/payments.py`](../app/payments.py), [`app/api/operator.py`](../app/api/operator.py)). A correção 0.10 exige teste de ponta a ponta em ambiente controlado para confirmar que **pedido real do site** não usa esses caminhos.
|
||||||
|
- O pagamento cria o pedido e o card de prova. O card filho gera seu próprio PNG final, o pai fica bloqueado até a resposta e os dois compartilham a máquina; a prova usa uma janela de 15 cm em volta do traço mais fino de cada classe ([`app/proof.py`](../app/proof.py), [`app/printjobs.py`](../app/printjobs.py), [`app/printpng.py`](../app/printpng.py)).
|
||||||
|
- A máquina não é mais atribuída ao pagamento: quem puxa o card escolhe a máquina da sessão, e o histórico guarda operador e hora ([`app/machines.py`](../app/machines.py), [`app/api/operator.py`](../app/api/operator.py)).
|
||||||
|
- A folha pronta aceita resíduo e traço fino com o mesmo aceite das avulsas; a régua é 96/200 DPI e 287–293 DPI passam como 300 ([`web/site-quality.js`](../web/site-quality.js), [`web/site-config.js`](../web/site-config.js), [`app/grade_check.py`](../app/grade_check.py)).
|
||||||
|
- A geração tem timeout de 15 minutos, aviso de falha com hora no card e “Gerar de novo” ([`app/printjobs.py`](../app/printjobs.py), [`app/api/operator.py`](../app/api/operator.py)).
|
||||||
|
- O download do original agora usa `DTF-<n>-original-<i>`, e o arquivo final só entra como PNG RGBA 8 bits a 300 DPI ([`app/api/operator.py`](../app/api/operator.py), [`app/printpng_validate.py`](../app/printpng_validate.py)).
|
||||||
|
- A 0.12 passou a registrar em Números a página, o upload (MB/s), a conferência do Prumo, a montagem, a geração por 10 m e o tempo do evento de pagamento até o card, com média e p95 ([`app/api/operator.py`](../app/api/operator.py), [`web/checkout.js`](../web/checkout.js), [`web/kanban.js`](../web/kanban.js)).
|
||||||
|
|
||||||
|
Esses achados são **verificação estática do repositório**, não prova de que a versão implantada tem exatamente o mesmo comportamento. O PDF traz evidências visuais dos pedidos #14 e #15; a confirmação de correção precisa repetir cenários equivalentes em homologação.
|
||||||
|
|
||||||
|
## Etapa 0 — correções antes da Fase 2
|
||||||
|
|
||||||
|
**Começar 0.1 no primeiro dia**, em paralelo aos primeiros itens abaixo. Os itens estão na ordem aproximada de menor esforço para entregar. A sequência de publicação deve preservar as dependências indicadas.
|
||||||
|
|
||||||
|
| Ordem de entrega | PDF | Trabalho e critério de aceite | Estimativa | Dependência |
|
||||||
|
|---|---|---|---:|---|
|
||||||
|
| 1 | 0.7 | Finalizados do mais novo ao mais antigo; colunas de trabalho continuam FIFO. | 2–4 h | Nenhuma. |
|
||||||
|
| 2 | 0.6 | “Abrir arquivo” na frente do card em todas as colunas, sem expandir. | 3–6 h | Nenhuma. |
|
||||||
|
| 3 | 0.10 | Provar que pedido real do site só nasce com pagamento confirmado; manter exceções explícitas de teste e balcão. Corrigir apenas se o teste achar furo. | 3–8 h | Acesso a homologação e um fluxo de pagamento de teste. |
|
||||||
|
| 4 | 0.8 | Nova régua: `<96` recusa; `96–199` exige ciência; `>=200` passa sem ressalva. Aplicar no navegador e na aprovação do servidor; conferir 287–293 DPI. | 6–12 h | Arquivos de amostra. |
|
||||||
|
| 5 | 0.9 | Arquivo final exclusivamente PNG 300 DPI transparente. Validar no servidor, no upload e na aprovação; mensagem clara para PDF/TIFF ou conversão definida. | 8–16 h | Decidir **rejeitar** PDF/TIFF ou convertê-los; sugerido rejeitar e orientar o designer, por ser a via menor e mais segura. |
|
||||||
|
| 6 | 0.5 + limpeza da máquina | Eliminar máquina automática na criação; atribuir a máquina da sessão que puxa; gravar operador/hora; contar o limite e mandar à pasta certa. Pai e filho não podem divergir. | 10–20 h | Regra de prova 0.1 para a vinculação pai/filho. |
|
||||||
|
| 7 | 0.4 | Timeout visível, horário da falha, recuperação de job preso e “Gerar de novo” funcional para falha/timeout. | 10–18 h | Definir timeout inicial por tamanho; medir com 0.12. |
|
||||||
|
| 8 | 0.3 | PNG alto: medir dimensões no servidor ou rejeitar com limite explícito **antes de cobrar**; `0 DPI` nunca passa como medida. Testar 57 × 1600 cm. | 12–24 h | Definir limite aceito para arquivo alto caso a análise no servidor não seja viável. |
|
||||||
|
| 9 | 0.2 | Aceite explícito e persistido de resíduo e traço fino na folha pronta **e** nas avulsas; sem aceite, trava; fundo chapado e `<96 DPI` continuam sem exceção. | 14–28 h | Texto final de aceite já está no PDF. |
|
||||||
|
| 10 | 0.1 **urgente** | Prova criada no pagamento: até 15 cm por classe do trecho de menor traço, PNG final aprovado no filho, custo/metragem zero, topo da fila, uma máquina para pai/filho, travas do pai até resposta do vendedor, motivo na reprovação. | 36–72 h | 0.5 integra a parte de máquina; usar amostras #14/#15. **Bloqueia divulgação.** |
|
||||||
|
| 11 | “O que tirar” | Remover “Contato feito”, agrupar Originais, mover Manifesto para Arquivos e ocultar nota do cliente. A remoção da máquina automática está em 0.5. | 6–12 h | “Contato feito” depende de 0.1; demais independentes. |
|
||||||
|
| 12 | 0.12 | Medir média e p95 das seis etapas no Números; ETA de upload e andamento legível das etapas no site; converter violações dos limites do PDF em correções com número. | 24–40 h | Instrumentar antes da bateria final para medir casos reais. |
|
||||||
|
| 13 | 0.11 | **Só depois de 0.1–0.10:** backup verificável, limpeza de pedidos/cards/histórico/pastas e recibos, preservar cadastros/integrações e sequência de números Tiny; repetir toda a bateria. | 8–16 h de operação | Autorização expressa do dono dos dados, janela, backup/restauração, lista de números já usados no Tiny; cliente cancela testes no Tiny. |
|
||||||
|
|
||||||
|
**Gate de saída da Etapa 0:** repetir no site e no Kanban os cenários do PDF, inclusive #14/#15 equivalentes, PNG alto, 96/199/200/293 DPI, resíduo/traço fino nos dois caminhos, timeout e retomada, máquina puxada, saída em PNG, pedido não pago, e medição de tempos. Divulgar o site somente após a prova 0.1 e os demais bloqueios comerciais estarem validados. O “zerar” é destrutivo: preparar e ensaiar restauração antes de executar em qualquer ambiente com dados reais.
|
||||||
|
|
||||||
|
## Fase 2 — entregas menores primeiro, respeitando dependências
|
||||||
|
|
||||||
|
O PDF numera as frentes pela prioridade do cliente; esta tabela muda **apenas a ordem de implementação sugerida por tempo**. A documentação da frente 12 acompanha cada entrega e fecha a rodada.
|
||||||
|
|
||||||
|
| Sequência | Frente | Entrega | Estimativa | Entrada necessária / dependência |
|
||||||
|
|---|---|---|---:|---|
|
||||||
|
| 1 | 6 | Nome Prumo e relatório ordenado das ações no card e no resumo antes do pagamento. | 12–24 h | Itens prévios 9/13/16 citados no PDF; persistir eventos reais, não inferir do resultado final. |
|
||||||
|
| 2 | 4 | Área de vídeos, player flutuante e vínculo por produto. | 12–24 h | Estrutura independe da gravação; **Dropstar fornece seis vídeos** para publicar. A edição pelo Kanban entra na frente 8. |
|
||||||
|
| 3 | 5 | Tratamento pelo designer como opcional, item pago, etiqueta e prazo adicional de 24 h. | 12–24 h | **Dropstar define R$ X** e confirma capacidade/SLA; reutilizar fluxo existente de envio do final. |
|
||||||
|
| 4 | 9 | Evoluir cotações/tentativas para aba “Aguardando pagamento”, idade, contato, expiração e abandono. | 16–32 h | Decisões de expiração, aviso, cancelamento e arquivo; vide quadro abaixo. Não tratar cotação pendente de revisão como pedido criado. |
|
||||||
|
| 5 | 11 | Limites editáveis por etapa, cores, lista Atrasados e comparação no Números. | 18–32 h | Limites iniciais no PDF: 2 h, 6 h, 4 h, 2 h, 3 dias; confirmar dono de cada etapa. |
|
||||||
|
| 6 | 3 | Premium: produto, preço, classe/pasta PREMIUM, SKU Tiny e comparação no site. | 28–52 h | **Bloqueado para publicação** até preset Spot OK Premium no Flexi, hot folder, contração e três folhas de teste aprovadas pela Dropstar; SKU Tiny. |
|
||||||
|
| 7 | 2 | Foto/vídeo da revisão, câmera/upload, pasta `Revisões/`, bloqueio de Finalizado acima de 1 m e foto no aviso. | 36–64 h | Dropstar instala pedestal/celular e aprova exemplo de foto; integrar ao fluxo de avisos do n8n/Tiny já usado pelo cliente. |
|
||||||
|
| 8 | 1 | Ficha de máquinas, insumos/peças/eventos, contadores, alertas e custo/ROI no Números. | 64–112 h | Hot folders existentes; **Dropstar fornece** preço/data de instalação, custos/lotes, mínimos e registro operacional. Confirmar como detectar “entre um arquivo e outro” sem sinal de impressão do Flexi. |
|
||||||
|
| 9 | 7a | Montador no Kanban com `Estampas/`, tabela de tamanhos, lista, montagem e card faturado. | 72–128 h | Prumo 6; **Dropstar fornece** PNGs/códigos, tabela de tamanhos e regra de faturamento/Tiny; criar perfil Expedição. |
|
||||||
|
| 10 | 7b | QR no impresso e preenchimento automático do lote. | 72–128 h | 7a em uso; **Dropstar fornece** origem e formato dos pedidos do lote e validação física do QR. |
|
||||||
|
| 11 | 8 | Aba Site administrável: produtos, preços/faixas, cupons, vídeos e nota da arte, com vigência e auditoria. | 96–160 h | Modelo comercial e permissões aprovados pela Gestão; frente 4 para vídeos; migrar preço autoritativo do código para banco sem alterar pedidos pagos. |
|
||||||
|
| 12 | 10 | Vetorizar/ampliar separado, lote, prévia, créditos/packs, cupom e chamada ao motor. | 120–220 h | Frente 8; **Wagner mede custo/qualidade por imagem e escolhe motor**, Dropstar aprova pack e política grátis. Fazer piloto antes de fixar preço. |
|
||||||
|
| Transversal | 12 | Documentação macro, por perfil e implantação; atualizar ao concluir cada rodada. | 16–32 h | Acesso aos fluxos reais de Flexi, Tiny, pagamento e n8n; revisão operacional da Dropstar. |
|
||||||
|
|
||||||
|
## Dependências que precisam vir deles
|
||||||
|
|
||||||
|
**Dropstar/Marcus (decisões e material):**
|
||||||
|
|
||||||
|
1. Autorizar e agendar o reset 0.11 **somente quando a correção estiver validada**; confirmar backup, dados a preservar, sequência dos números e cancelamento manual dos testes no Tiny.
|
||||||
|
2. Fornecer massa de homologação equivalente aos pedidos #14/#15 e aos arquivos de DPI, resíduo, traço e PNG alto; confirmar os tempos aceitáveis já propostos no PDF após a medição 0.12.
|
||||||
|
3. Informar preço do tratamento; preços de compra e datas das máquinas; lançamentos históricos, custos, mínimos e responsáveis por alimentar insumos/eventos.
|
||||||
|
4. Gravar/entregar seis vídeos; fornecer pedestal/celular para revisão e aprovar se foto pode seguir pelo fluxo de aviso existente.
|
||||||
|
5. Configurar e testar o Premium no Flexi (8 passadas, branco máximo, contração, hot folder), imprimir três folhas, dar o “ok, testado” e cadastrar/confirmar SKU no Tiny.
|
||||||
|
6. Entregar biblioteca `Estampas/` (PNG transparente 300 DPI por código), tabela de larguras, exceções por tamanho, regra de faturamento e origem dos lotes/QR.
|
||||||
|
7. Definir preços iniciais, faixas, cupons, responsáveis e vigência da aba Site; validar se a nota da arte deve sair da tela até ter ação definida.
|
||||||
|
8. Com Wagner, comparar motor próprio e API para vetorizar: custo real, fotos/degradês, volume esperado e política dos packs/grátis antes de ativar cobrança.
|
||||||
|
|
||||||
|
**Respostas operacionais necessárias, mas parcialmente verificadas no código:**
|
||||||
|
|
||||||
|
| Pergunta do PDF | Achado no repositório | Confirmação externa |
|
||||||
|
|---|---|---|
|
||||||
|
| Onde fica pedido criado e não pago? | Cotações sem pedido aparecem na aba Cotações; tentativas têm registros separados. O card de produção surge ao confirmar pagamento, teste ou pagamento de balcão. | Definir se a futura aba une cotação aprovada e tentativa pendente; manter cotações aguardando revisão separadas. |
|
||||||
|
| Quanto duram Pix/cartão e o arquivo? | Pix: 30 min configurados. Cotação aprovada: 24 h; arquivos têm retenção própria. Não há uma regra única de 24 h de pedido não pago. | Confirmar política de cartão pendente/3DS, contato, expiração de 24 h, mensagem e exclusão do arquivo em conformidade com pagamento tardio. |
|
||||||
|
| “Original 1” baixa com qual nome? | Hoje o download individual usa o nome do upload. | O PDF já decide: renomear para nome do pedido; não precisa de nova decisão. |
|
||||||
|
| Menor traço é medido quando? | Nas avulsas, a medida é recalculada para a largura escolhida em 300 DPI. | Validar a folha pronta com arquivo de teste; a regra final deve ser a dimensão impressa, não o original. |
|
||||||
|
| Tiny avisa a cada etapa? | O código envia eventos de pagamento, entrada na fila e Finalizado; atualização de status Tiny depende de configuração. | **Dropstar verifica n8n/Tiny real:** quais estados disparam WhatsApp e texto aprovado. |
|
||||||
|
| “Pedir novamente” reutiliza final? | Não foi localizada implementação dessa ação no site/portal do repositório. | Se existe fora deste código, demonstrar; se entrar no escopo, decidir reaproveitamento de PNG válido, retenção e nova conferência. |
|
||||||
|
|
||||||
|
## Decisões de interpretação do PDF
|
||||||
|
|
||||||
|
- Em 0.5, o texto diz que a máquina automática é sugestão; em “O que tirar”, Marcus manda retirar a atribuição automática e deixar toda a fila sem máquina até alguém puxar. **Adotar a segunda regra**, que é explícita e resolve a separação pai/filho. Se uma sugestão visual ainda for desejada, ela não pode gravar `machine_id` nem dividir a prova.
|
||||||
|
- O quadro “Ordem e dependências” chama a frente 9 de “Aba Cotações”; o texto da frente 9 pede **aba Aguardando pagamento**. Tratar como evolução da aba existente e mostrar apenas oportunidades realmente pagáveis, sem misturar revisão de orçamento.
|
||||||
|
- Na frente 5, “item 8 no ar” se refere ao envio de arquivo final da rodada anterior, não necessariamente à frente 8 da Fase 2. O fluxo já existe no código; o preço do serviço é o bloqueio principal.
|
||||||
|
- A proposta de 24 h para pedido não pago não substitui os 30 min do Pix. O sistema precisa distinguir vencimento da tentativa de pagamento, prazo de recuperação comercial e retenção do arquivo, para não apagar uma compra paga tardiamente.
|
||||||
@@ -8,8 +8,8 @@ server {
|
|||||||
add_header X-Content-Type-Options nosniff always;
|
add_header X-Content-Type-Options nosniff always;
|
||||||
add_header Referrer-Policy no-referrer always;
|
add_header Referrer-Policy no-referrer always;
|
||||||
add_header X-Frame-Options DENY always;
|
add_header X-Frame-Options DENY always;
|
||||||
add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
|
add_header Permissions-Policy "camera=(self), microphone=(), geolocation=()" always;
|
||||||
add_header Content-Security-Policy "default-src 'self'; script-src 'self' @SCRIPT_HASHES@ ${PAYMENT_CSP_SOURCES}; script-src-attr 'none'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: blob: https://cdn.vnda.com.br ${PAYMENT_CSP_SOURCES}; connect-src 'self' ${S3_PUBLIC_ENDPOINT} https://cdn.vnda.com.br ${PAYMENT_CSP_SOURCES}; frame-src 'self' ${PAYMENT_CSP_SOURCES} ${PAYMENT_CHALLENGE_SOURCES}; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self' ${PAYMENT_CHALLENGE_SOURCES}" always;
|
add_header Content-Security-Policy "default-src 'self'; script-src 'self' @SCRIPT_HASHES@ ${PAYMENT_CSP_SOURCES}; script-src-attr 'none'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: blob: https://cdn.vnda.com.br ${S3_PUBLIC_ENDPOINT} ${PAYMENT_CSP_SOURCES}; media-src 'self' ${S3_PUBLIC_ENDPOINT}; connect-src 'self' ${S3_PUBLIC_ENDPOINT} https://cdn.vnda.com.br ${PAYMENT_CSP_SOURCES} ${SENTRY_CSP_SOURCES}; frame-src 'self' ${PAYMENT_CSP_SOURCES} ${PAYMENT_CHALLENGE_SOURCES}; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self' ${PAYMENT_CHALLENGE_SOURCES}" always;
|
||||||
location = /health { access_log off; return 200 'ok'; }
|
location = /health { access_log off; return 200 'ok'; }
|
||||||
location /api/ {
|
location /api/ {
|
||||||
limit_req zone=api_limit burst=100 nodelay;
|
limit_req zone=api_limit burst=100 nodelay;
|
||||||
|
|||||||
@@ -34,6 +34,7 @@ certifi==2026.10.19 \
|
|||||||
# via
|
# via
|
||||||
# httpcore
|
# httpcore
|
||||||
# httpx
|
# httpx
|
||||||
|
# sentry-sdk
|
||||||
click==8.5.0 \
|
click==8.5.0 \
|
||||||
--hash=sha256:255bc9599cf7748b4b1a446ccc735421bd08a2ae529a8b88597d3de5664ee360 \
|
--hash=sha256:255bc9599cf7748b4b1a446ccc735421bd08a2ae529a8b88597d3de5664ee360 \
|
||||||
--hash=sha256:ba0d2089de75ea0310e2dde03160e6ca10009947fb95a182f9b54021bb272e34
|
--hash=sha256:ba0d2089de75ea0310e2dde03160e6ca10009947fb95a182f9b54021bb272e34
|
||||||
@@ -453,6 +454,10 @@ psycopg-binary==3.2.9 \
|
|||||||
--hash=sha256:fa5c80d8b4cbf23f338db88a7251cef8bb4b68e0f91cf8b6ddfa93884fdbb0c1 \
|
--hash=sha256:fa5c80d8b4cbf23f338db88a7251cef8bb4b68e0f91cf8b6ddfa93884fdbb0c1 \
|
||||||
--hash=sha256:fb7599e436b586e265bea956751453ad32eb98be6a6e694252f4691c31b16edb
|
--hash=sha256:fb7599e436b586e265bea956751453ad32eb98be6a6e694252f4691c31b16edb
|
||||||
# via psycopg
|
# via psycopg
|
||||||
|
psycopg-pool==3.2.8 \
|
||||||
|
--hash=sha256:5474137f3a58e697e0141d0311e70ec067fc4466031496d7f9ef3e2c28a1dc09 \
|
||||||
|
--hash=sha256:854e17c2a637c3b9f8d8b24faad57d4cf850baf3fc03ca56ef7e5b4998e391b9
|
||||||
|
# via -r infra/requirements.txt
|
||||||
pydantic==2.13.5 \
|
pydantic==2.13.5 \
|
||||||
--hash=sha256:346a034f080da3755d8e9cb5e00e8b07de1d39e4f6e2c87d8ab7cafa0b269a73 \
|
--hash=sha256:346a034f080da3755d8e9cb5e00e8b07de1d39e4f6e2c87d8ab7cafa0b269a73 \
|
||||||
--hash=sha256:51a9c5f7b2f8e636f04c6cada605d9b6a3bf1348fdf945a3d8869b19bba0ee08
|
--hash=sha256:51a9c5f7b2f8e636f04c6cada605d9b6a3bf1348fdf945a3d8869b19bba0ee08
|
||||||
@@ -579,6 +584,31 @@ pydantic-core==2.46.5 \
|
|||||||
--hash=sha256:fc8515076c11f3cfdf4fb142dcca0fe384b1230a3b5415458ac84f3e0903ec13 \
|
--hash=sha256:fc8515076c11f3cfdf4fb142dcca0fe384b1230a3b5415458ac84f3e0903ec13 \
|
||||||
--hash=sha256:ff218293c9c806138dca139765e3b067621be52bcd93cdc14c7711be7ddc90a9
|
--hash=sha256:ff218293c9c806138dca139765e3b067621be52bcd93cdc14c7711be7ddc90a9
|
||||||
# via pydantic
|
# via pydantic
|
||||||
|
pypdfium2==5.14.0 \
|
||||||
|
--hash=sha256:09b99c8f0cb427eb17fec13c0862ed598bba34b4843df153f70fff806a2820bc \
|
||||||
|
--hash=sha256:11f281613fa22313d9c7ab89947665e84eccf8ebe40e1198a84a88352305648d \
|
||||||
|
--hash=sha256:149fd5c6397b8df8bf7911a93506eff0be874f877afe7ac936cf5d37d21a6a06 \
|
||||||
|
--hash=sha256:1951f0aed469150b13c62eabd501a9839e608ab9983ca8579be9eb73213b72b6 \
|
||||||
|
--hash=sha256:2de384df66ba55fcaab0775f30f28ec1090af3dfa60276a07821efc96d993118 \
|
||||||
|
--hash=sha256:382de7fe20d32c42993a274d7b6c555a5623a97570dfc1d2f5e0a16fe0d5d482 \
|
||||||
|
--hash=sha256:51d9e9b64ebc34effaf57f9b6d4511b3f66ad3744bd1690d2cc6700853173dcf \
|
||||||
|
--hash=sha256:593f2c952ae3ffdca0efcbb3d9464fbccb876254386114ff900cabef21157c3f \
|
||||||
|
--hash=sha256:605ab9d0d4c5e223599c9065b88d16b2c1f131c807c80dea8adbb16f1433e95b \
|
||||||
|
--hash=sha256:790e2cac1641a65912b73bd7243f45195d36f1663c85a3e1a126a8f5867c82a3 \
|
||||||
|
--hash=sha256:9f4d77db5232826dd03a63481f32164331b96c21fd68f0667b2e43dbae141a93 \
|
||||||
|
--hash=sha256:9fd5cc94a389d50298e4d8cb79af6b9b8e0d785606e2a937725dc6e271c9c6e6 \
|
||||||
|
--hash=sha256:b40a0913196a1483f0fdc22a53f8719c3aef87f1c4d8d9c38d2ad4e207500fdf \
|
||||||
|
--hash=sha256:bed597b2cea3990164e43f9003f71db18959d0abd5d73adc9c176e7be2d84b98 \
|
||||||
|
--hash=sha256:c5f009b3157f10e97dceb55963f5910eff92feb00587ba10a76f12b87ce1a4b6 \
|
||||||
|
--hash=sha256:c73be14076bedebd9bcaf9b062579c95c668580043bccd29eb0db502101d5716 \
|
||||||
|
--hash=sha256:d436ee9e024f981e68f5775f5a9d115f93ea14ee6c2c6efd35dd17d83edf4942 \
|
||||||
|
--hash=sha256:dbfd6deff68cc46b134acd6be380d98d694a9f018fbb622c07229225c85db389 \
|
||||||
|
--hash=sha256:e4e203ea9710fd00e5448edb6f1615dc8587035357f75f40b432dde0c33e8da1 \
|
||||||
|
--hash=sha256:e70d87cb0577eab38f2106f9c9606b458930beef612a1b5f298772ed259f5ec0 \
|
||||||
|
--hash=sha256:eb8aeca157808f323e39ea298cc6d6c8e080c192ea2efb1ca81daa0f0ff4d095 \
|
||||||
|
--hash=sha256:f1b696e6901e16f114a2ec6332e5e3f8f5033a901614ead28499ab18ca6024f5 \
|
||||||
|
--hash=sha256:f6f13bbcc5f4adabc2676e52f662c6cb375de86b314790b0ae08f3ab62eb116a
|
||||||
|
# via -r infra/requirements.txt
|
||||||
python-dateutil==2.9.0.post0 \
|
python-dateutil==2.9.0.post0 \
|
||||||
--hash=sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3 \
|
--hash=sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3 \
|
||||||
--hash=sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427
|
--hash=sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427
|
||||||
@@ -587,6 +617,14 @@ s3transfer==0.13.1 \
|
|||||||
--hash=sha256:a981aa7429be23fe6dfc13e80e4020057cbab622b08c0315288758d67cabc724 \
|
--hash=sha256:a981aa7429be23fe6dfc13e80e4020057cbab622b08c0315288758d67cabc724 \
|
||||||
--hash=sha256:c3fdba22ba1bd367922f27ec8032d6a1cf5f10c934fb5d68cf60fd5a23d936cf
|
--hash=sha256:c3fdba22ba1bd367922f27ec8032d6a1cf5f10c934fb5d68cf60fd5a23d936cf
|
||||||
# via boto3
|
# via boto3
|
||||||
|
segno==1.6.6 \
|
||||||
|
--hash=sha256:28c7d081ed0cf935e0411293a465efd4d500704072cdb039778a2ab8736190c7 \
|
||||||
|
--hash=sha256:e60933afc4b52137d323a4434c8340e0ce1e58cec71439e46680d4db188f11b3
|
||||||
|
# via -r infra/requirements.txt
|
||||||
|
sentry-sdk==2.74.0 \
|
||||||
|
--hash=sha256:40b205af015649df3ec9986e057ce24ce85956bee3fb75efa72c93aa7036bdff \
|
||||||
|
--hash=sha256:dd91d75aacaef636006b579ac3ddb2fdbc9dce35f00f4b353b6b1b110c6b256a
|
||||||
|
# via -r infra/requirements.txt
|
||||||
six==1.17.0 \
|
six==1.17.0 \
|
||||||
--hash=sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274 \
|
--hash=sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274 \
|
||||||
--hash=sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81
|
--hash=sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81
|
||||||
@@ -604,6 +642,7 @@ typing-extensions==4.16.0 \
|
|||||||
# anyio
|
# anyio
|
||||||
# fastapi
|
# fastapi
|
||||||
# psycopg
|
# psycopg
|
||||||
|
# psycopg-pool
|
||||||
# pydantic
|
# pydantic
|
||||||
# pydantic-core
|
# pydantic-core
|
||||||
# starlette
|
# starlette
|
||||||
@@ -617,7 +656,9 @@ typing-inspection==0.4.4 \
|
|||||||
urllib3==2.7.0 \
|
urllib3==2.7.0 \
|
||||||
--hash=sha256:231e0ec3b63ceb14667c67be60f2f2c40a518cb38b03af60abc813da26505f4c \
|
--hash=sha256:231e0ec3b63ceb14667c67be60f2f2c40a518cb38b03af60abc813da26505f4c \
|
||||||
--hash=sha256:9fb4c81ebbb1ce9531cce37674bbc6f1360472bc18ca9a553ede278ef7276897
|
--hash=sha256:9fb4c81ebbb1ce9531cce37674bbc6f1360472bc18ca9a553ede278ef7276897
|
||||||
# via botocore
|
# via
|
||||||
|
# botocore
|
||||||
|
# sentry-sdk
|
||||||
uvicorn==0.34.2 \
|
uvicorn==0.34.2 \
|
||||||
--hash=sha256:0e929828f6186353a80b58ea719861d2629d766293b6d19baf086ba31d4f3328 \
|
--hash=sha256:0e929828f6186353a80b58ea719861d2629d766293b6d19baf086ba31d4f3328 \
|
||||||
--hash=sha256:deb49af569084536d269fe0a6d67e3754f104cf03aba7c11c40f01aadf33c403
|
--hash=sha256:deb49af569084536d269fe0a6d67e3754f104cf03aba7c11c40f01aadf33c403
|
||||||
|
|||||||
@@ -2,7 +2,11 @@ fastapi==0.141.1
|
|||||||
starlette==1.6.0
|
starlette==1.6.0
|
||||||
uvicorn==0.34.2
|
uvicorn==0.34.2
|
||||||
psycopg[binary]==3.2.9
|
psycopg[binary]==3.2.9
|
||||||
|
psycopg-pool==3.2.8
|
||||||
boto3==1.38.23
|
boto3==1.38.23
|
||||||
httpx==0.28.1
|
httpx==0.28.1
|
||||||
pillow==13.0.0
|
pillow==13.0.0
|
||||||
pikepdf==10.13.0.post1
|
pikepdf==10.13.0.post1
|
||||||
|
pypdfium2==5.14.0
|
||||||
|
segno==1.6.6
|
||||||
|
sentry-sdk==2.74.0
|
||||||
|
|||||||
@@ -1 +1 @@
|
|||||||
{"Rules":[{"ID":"local-artwork-retention","Status":"Enabled","Filter":{"Prefix":""},"Expiration":{"Days":30},"AbortIncompleteMultipartUpload":{"DaysAfterInitiation":1}}]}
|
{"Rules":[{"ID":"local-artwork-retention","Status":"Enabled","Filter":{"Prefix":"originals/"},"Expiration":{"Days":30},"AbortIncompleteMultipartUpload":{"DaysAfterInitiation":1}}]}
|
||||||
|
|||||||
@@ -2,6 +2,6 @@
|
|||||||
"Version": "2012-10-17",
|
"Version": "2012-10-17",
|
||||||
"Statement": [
|
"Statement": [
|
||||||
{"Effect":"Allow","Action":["s3:ListBucket","s3:ListBucketMultipartUploads","s3:GetBucketLocation"],"Resource":["arn:aws:s3:::dtf-local-artwork"]},
|
{"Effect":"Allow","Action":["s3:ListBucket","s3:ListBucketMultipartUploads","s3:GetBucketLocation"],"Resource":["arn:aws:s3:::dtf-local-artwork"]},
|
||||||
{"Effect":"Allow","Action":["s3:GetObject","s3:PutObject","s3:DeleteObject","s3:AbortMultipartUpload","s3:ListMultipartUploadParts"],"Resource":["arn:aws:s3:::dtf-local-artwork/originals/*"]}
|
{"Effect":"Allow","Action":["s3:GetObject","s3:PutObject","s3:DeleteObject","s3:AbortMultipartUpload","s3:ListMultipartUploadParts"],"Resource":["arn:aws:s3:::dtf-local-artwork/originals/*","arn:aws:s3:::dtf-local-artwork/videos/*"]}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,32 +1,44 @@
|
|||||||
"""Clear the test orders before the Site opens to customers, once, by hand.
|
"""Clear the test board before the Site opens to customers, once, by hand.
|
||||||
|
|
||||||
Run from the worker's console (Portainer > Containers > worker > Console):
|
Run from the worker's console (Portainer > Containers > worker > Console):
|
||||||
|
|
||||||
python -m ops.launch_reset shows what would be removed
|
python -m ops.launch_reset shows what would be removed
|
||||||
python -m ops.launch_reset --confirmar APAGAR removes it
|
python -m ops.launch_reset --confirmar APAGAR removes it
|
||||||
python -m ops.launch_reset --confirmar APAGAR --contas also customer accounts
|
python -m ops.launch_reset --confirmar APAGAR --contas also customer accounts
|
||||||
|
python -m ops.launch_reset --root /srv/Kanban --confirmar APAGAR
|
||||||
|
also empties the flow folders
|
||||||
|
|
||||||
Removes every order with its moves, files and notices, every quote, payment
|
Removes every order with its moves, files, notices and history, every quote,
|
||||||
attempt and payment notification, and the artwork pictures. The artwork
|
payment attempt and payment notification, and the artwork pictures. The
|
||||||
files are marked expired, so the worker deletes them from storage within a
|
artwork files are marked expired, so the worker deletes them from storage
|
||||||
minute. Operators, the Tiny connection and the backups are kept.
|
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
|
It refuses if any payment was made with real money (Mercado Pago's
|
||||||
live_mode): those are customers' orders, not tests.
|
live_mode): those are customers' orders, not tests.
|
||||||
|
|
||||||
Order numbers start again at #1. A database set up before the worker could
|
The order numbering is **not** reset (Dropstar, 2026-11-05): DTF-1…DTF-15
|
||||||
do that prints the one command to run in the database container's console.
|
already exist as Tiny order numbers. DELETE keeps the identity sequence, so
|
||||||
|
the next card continues from where it stopped.
|
||||||
"""
|
"""
|
||||||
import argparse
|
import argparse
|
||||||
|
import shutil
|
||||||
import sys
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
from app.core import db
|
from app.core import db
|
||||||
|
|
||||||
TABLES = [ # in an order the foreign keys allow
|
TABLES = [ # in an order the foreign keys allow
|
||||||
|
('hot_parts', 'peças nas pastas das máquinas'),
|
||||||
|
('print_parts', 'partes dos arquivos de impressão'),
|
||||||
|
('reworks', 'retrabalhos'),
|
||||||
|
('contact_waits', 'esperas de contato'),
|
||||||
('movements', 'movimentos de etapa'),
|
('movements', 'movimentos de etapa'),
|
||||||
('order_files', 'arquivos finais e correções'),
|
('order_files', 'arquivos finais e correções'),
|
||||||
('print_files', 'arquivos de impressão gerados'),
|
('print_files', 'arquivos de impressão gerados'),
|
||||||
('outbox', 'envios ao Tiny e avisos'),
|
('outbox', 'envios ao Tiny e avisos'),
|
||||||
|
('order_reviews', 'fotos e vídeos de revisão'),
|
||||||
('orders', 'pedidos'),
|
('orders', 'pedidos'),
|
||||||
('payment_intents', 'tentativas de pagamento'),
|
('payment_intents', 'tentativas de pagamento'),
|
||||||
('payment_events', 'avisos de pagamento'),
|
('payment_events', 'avisos de pagamento'),
|
||||||
@@ -34,20 +46,42 @@ TABLES = [ # in an order the foreign keys allow
|
|||||||
('upload_thumbnails', 'miniaturas das artes'),
|
('upload_thumbnails', 'miniaturas das artes'),
|
||||||
]
|
]
|
||||||
ACCOUNTS = [('sessions', 'sessões de clientes'), ('accounts', 'contas de clientes')]
|
ACCOUNTS = [('sessions', 'sessões de clientes'), ('accounts', 'contas de clientes')]
|
||||||
|
FLOW_FOLDERS = ('1. Arte recebida', '2. Arte conferida', '3. Imprimindo',
|
||||||
|
'4. Revisão', '5. Finalizado', 'Recibos', 'Revisões')
|
||||||
CONFIRM = 'APAGAR'
|
CONFIRM = 'APAGAR'
|
||||||
RESTART = 'ALTER TABLE dtf_local.orders ALTER COLUMN number RESTART WITH 1;'
|
# What stays points at some uploads: the Site's videos and captions (Marcus,
|
||||||
# What the worker's role may do itself (app/bootstrap.py grants it).
|
# 2026-11-16: the whole Site tab stays). Their files are left alone.
|
||||||
RENUMBER = "SELECT setval(pg_get_serial_sequence('dtf_local.orders','number'), 1, false)"
|
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):
|
def counts(c, tables):
|
||||||
return {table: c.execute(f'SELECT count(*) AS n FROM dtf_local.{table}').fetchone()['n'] for table, _ in tables}
|
return {table: c.execute(f'SELECT count(*) AS n FROM dtf_local.{table}').fetchone()['n'] for table, _ in tables}
|
||||||
|
|
||||||
|
|
||||||
|
def clean_folders(root, dry_run=True):
|
||||||
|
"""Empty the flow folders under `root`, recreating them; keep Estampas/."""
|
||||||
|
root = Path(root)
|
||||||
|
if not any((root / name).exists() for name in FLOW_FOLDERS):
|
||||||
|
raise SystemExit(f'{root} does not look like the Kanban root: no flow folders found.')
|
||||||
|
if dry_run:
|
||||||
|
return [str(root / name) for name in FLOW_FOLDERS if (root / name).exists()]
|
||||||
|
cleaned = []
|
||||||
|
for name in FLOW_FOLDERS:
|
||||||
|
path = root / name
|
||||||
|
if path.is_dir():
|
||||||
|
shutil.rmtree(path)
|
||||||
|
path.mkdir(parents=True, exist_ok=True)
|
||||||
|
cleaned.append(str(path))
|
||||||
|
return cleaned
|
||||||
|
|
||||||
|
|
||||||
def main(argv=None, out=print, connect=db.connect):
|
def main(argv=None, out=print, connect=db.connect):
|
||||||
parser = argparse.ArgumentParser(prog='python -m ops.launch_reset')
|
parser = argparse.ArgumentParser(prog='python -m ops.launch_reset')
|
||||||
parser.add_argument('--confirmar', default='', help=f'escreva {CONFIRM} para apagar')
|
parser.add_argument('--confirmar', default='', help=f'escreva {CONFIRM} para apagar')
|
||||||
parser.add_argument('--contas', action='store_true', help='apagar também as contas de clientes')
|
parser.add_argument('--contas', action='store_true', help='apagar também as contas de clientes')
|
||||||
|
parser.add_argument('--root', type=Path, help='raiz Kanban, a pasta com "1. Arte recebida"')
|
||||||
|
parser.add_argument('--keep-files', action='store_true', help='não mexer nas pastas do Kanban')
|
||||||
args = parser.parse_args(argv)
|
args = parser.parse_args(argv)
|
||||||
tables = TABLES + (ACCOUNTS if args.contas else [])
|
tables = TABLES + (ACCOUNTS if args.contas else [])
|
||||||
with connect() as c:
|
with connect() as c:
|
||||||
@@ -57,26 +91,24 @@ 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.')
|
out(f'Recusado: {live} pagamento(s) com dinheiro real (live_mode). Esses pedidos são de clientes.')
|
||||||
return 1
|
return 1
|
||||||
before = counts(c, tables)
|
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:
|
for table, label in tables:
|
||||||
out(f'{before[table]:>7} {label}')
|
out(f'{before[table]:>7} {label}')
|
||||||
out(f'{files:>7} arquivos de arte (o worker apaga do armazenamento)')
|
out(f'{files:>7} arquivos de arte (o worker apaga do armazenamento)')
|
||||||
|
if args.root and not args.keep_files:
|
||||||
|
out('Pastas que serão esvaziadas:')
|
||||||
|
for folder in clean_folders(args.root, dry_run=True):
|
||||||
|
out(f' {folder}')
|
||||||
if args.confirmar != CONFIRM:
|
if args.confirmar != CONFIRM:
|
||||||
out(f'Nada foi apagado. Repita com --confirmar {CONFIRM} para apagar.')
|
out(f'Nada foi apagado. Repita com --confirmar {CONFIRM} para apagar.')
|
||||||
return 0
|
return 0
|
||||||
for table, _ in tables:
|
for table, _ in tables:
|
||||||
c.execute(f'DELETE FROM dtf_local.{table}')
|
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}')
|
||||||
out('Apagado.')
|
if args.root and not args.keep_files:
|
||||||
try:
|
for folder in clean_folders(args.root, dry_run=False):
|
||||||
with connect() as c:
|
out(f'esvaziada {folder}')
|
||||||
c.execute(RENUMBER)
|
out('Apagado. A numeração dos pedidos continua de onde parou.')
|
||||||
out('A numeração dos pedidos recomeça em #1.')
|
|
||||||
except Exception as exc: # the application's role cannot alter the table
|
|
||||||
if 'permission' not in str(exc).lower() and 'owner' not in str(exc).lower():
|
|
||||||
raise
|
|
||||||
out('Para a numeração recomeçar em #1, rode no console do container do banco (db):')
|
|
||||||
out(f' psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -c "{RESTART}"')
|
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user