Compare commits
174 Commits
ui-v1
...
fe7bf4ef07
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fe7bf4ef07 | ||
|
|
289151214b | ||
|
|
9849ae5c14 | ||
|
|
fc3c08aced | ||
|
|
3ae453f47a | ||
|
|
80975b9424 | ||
|
|
d4494a0654 | ||
|
|
a2382f4834 | ||
|
|
c266bea684 | ||
|
|
a093b7d82a | ||
|
|
578a90bcc9 | ||
|
|
abae1c29a1 | ||
|
|
53c6234feb | ||
|
|
df30046027 | ||
|
|
c8857a5bf5 | ||
|
|
14a43f2ada | ||
|
|
12d5ba8d15 | ||
|
|
ea3c20ba1e | ||
|
|
b2e718449b | ||
|
|
7f7b684dbd | ||
|
|
f8cd6c148f | ||
|
|
3879754397 | ||
|
|
5910d3161f | ||
|
|
dbf1efc112 | ||
|
|
1f2358c8b5 | ||
|
|
7eb7d90f8b | ||
|
|
fb576e52d7 | ||
|
|
6919383d37 | ||
|
|
bd718796c5 | ||
|
|
8df35049f7 | ||
|
|
4f49ace867 | ||
|
|
1a7736dc8b | ||
|
|
4a2ce72764 | ||
|
|
b83e60ef0c | ||
|
|
37246917b9 | ||
|
|
a747d9a968 | ||
|
|
90e3126075 | ||
|
|
69997f4598 | ||
|
|
7383e44ff4 | ||
|
|
95be624cca | ||
|
|
5a431f8422 | ||
|
|
5a2e2db49a | ||
|
|
f8d76ed27d | ||
|
|
44458aea3e | ||
|
|
3c9f05041e | ||
|
|
914c55c329 | ||
|
|
8387d7ef3a | ||
|
|
cf12566e86 | ||
|
|
bcce64fff8 | ||
|
|
3664fe827e | ||
|
|
86507ed7b5 | ||
|
|
58ce0a4166 | ||
|
|
87cd7d77fb | ||
|
|
1216998914 | ||
|
|
2a2a783ff7 | ||
|
|
3db528a373 | ||
|
|
44cb6ccc16 | ||
|
|
c75c40ff28 | ||
|
|
6c2dcc77b0 | ||
|
|
5063c152c2 | ||
|
|
959ed37b15 | ||
|
|
172544b173 | ||
|
|
43d9a3c637 | ||
|
|
ac1d8743b1 | ||
|
|
545a8c0f2d | ||
|
|
8997e22f5e | ||
|
|
b3c5f63553 | ||
|
|
581fbe6be4 | ||
|
|
b1fbaad2bd | ||
|
|
1b445f0459 | ||
|
|
f567e6da89 | ||
|
|
c5b1bd37a6 | ||
|
|
e81b2b1681 | ||
|
|
a5c1ca53c0 | ||
|
|
4b804a2c85 | ||
|
|
c3c56a7f21 | ||
|
|
bc1fb60468 | ||
|
|
894e75fd94 | ||
|
|
d7b1eaae6d | ||
|
|
c19941555e | ||
|
|
8236ad8f0a | ||
|
|
dfa297d9b5 | ||
|
|
05da6d78ad | ||
|
|
7877489563 | ||
|
|
0218f119aa | ||
|
|
ca7cf7f701 | ||
|
|
67825a983d | ||
|
|
90c574a673 | ||
|
|
5616db1345 | ||
|
|
1fb2e5d55a | ||
|
|
7a908060fc | ||
|
|
b7abd401ec | ||
|
|
4b8b00443e | ||
|
|
26c46ccc1d | ||
|
|
b9ebdc0fdb | ||
|
|
2c664a1cc8 | ||
|
|
352590e63a | ||
|
|
b54c635cfc | ||
|
|
f6ce624b29 | ||
|
|
ef95dcc327 | ||
|
|
0b86fe79fc | ||
|
|
24ee4e9eab | ||
|
|
223854e392 | ||
|
|
0b55ebce7f | ||
|
|
bee7f8f245 | ||
|
|
c5db1375de | ||
|
|
3d8bca3af7 | ||
|
|
f3fc733352 | ||
|
|
4ce44feb70 | ||
|
|
01b94da36d | ||
|
|
25fa890e92 | ||
|
|
4386fc0737 | ||
|
|
70a76feb23 | ||
|
|
20982a945f | ||
|
|
37715ef223 | ||
|
|
b7e2ea12d0 | ||
|
|
933bd30cbd | ||
|
|
eb254da501 | ||
|
|
8786a33c8d | ||
|
|
20403c5132 | ||
|
|
1b57313496 | ||
|
|
a02711ef2b | ||
|
|
8dddf0fa25 | ||
|
|
f4aacb5776 | ||
|
|
64e47ee481 | ||
|
|
2b313a1cc8 | ||
|
|
7116ebe50a | ||
|
|
9e69c48d2d | ||
|
|
64c1260a9f | ||
|
|
b5bb03cbb4 | ||
|
|
2495edf188 | ||
|
|
f5fed013ab | ||
|
|
593ddf82c8 | ||
|
|
8b5aafa299 | ||
|
|
e47f88a6d6 | ||
|
|
5f2be7ea20 | ||
|
|
4437232d27 | ||
|
|
8bc57195e8 | ||
|
|
0a575a3be7 | ||
|
|
15abd589a8 | ||
|
|
32c060e1b0 | ||
|
|
6f5d183365 | ||
|
|
2215da8d5e | ||
|
|
88e65290e1 | ||
|
|
690b15ece1 | ||
|
|
e20c8673bb | ||
|
|
4de2151e9a | ||
|
|
641aafc87d | ||
|
|
875a7ef9c7 | ||
|
|
c436936fed | ||
|
|
0ed6de4bd5 | ||
|
|
eae3dad306 | ||
|
|
7b6675d4d4 | ||
|
|
4df74221d2 | ||
|
|
43043c361c | ||
|
|
536510b148 | ||
|
|
a1877bdf0a | ||
|
|
275ebf72c4 | ||
|
|
9bea187ea4 | ||
|
|
bd56170248 | ||
|
|
60b7336b37 | ||
|
|
04e4cbc953 | ||
|
|
aec5b1d054 | ||
|
|
8b42e684ca | ||
|
|
e768dcb489 | ||
|
|
122c645f72 | ||
|
|
988b252f9d | ||
|
|
56021d8451 | ||
|
|
b6a90411f1 | ||
|
|
cbbbdb351a | ||
|
|
b81ff8d03d | ||
|
|
177882e77b | ||
|
|
2e03b0362b | ||
|
|
99a558ddd9 |
16
.env.example
@@ -37,10 +37,22 @@ TINY_ADAPTER=fake
|
|||||||
# TINY_PRODUCT_UV_FOLHA=...
|
# TINY_PRODUCT_UV_FOLHA=...
|
||||||
# TINY_PRODUCT_UV_AVULSA=...
|
# TINY_PRODUCT_UV_AVULSA=...
|
||||||
# TINY_ADAPTER=tiny # only once connected and tested: creates real orders
|
# TINY_ADAPTER=tiny # only once connected and tested: creates real orders
|
||||||
WHATSAPP_ADAPTER=fake
|
# Jadlog price quotes go in jadlog.env, not here (see app/jadlog_probe.py):
|
||||||
|
# JADLOG_TOKEN=...
|
||||||
|
# JADLOG_CNPJ=... # the "Usuário" Jadlog issued, the CNPJ that contracts freight
|
||||||
|
# JADLOG_CONTA=... # conta corrente
|
||||||
|
# JADLOG_CONTRATO= # only if Jadlog issued a contract number
|
||||||
|
# E-mail stays in the database and the worker log (MAIL_ADAPTER=log). To send
|
||||||
|
# through a real server: MAIL_ADAPTER=smtp with the settings below.
|
||||||
|
# MAIL_FROM=DTF Dropstar <nao-responda@exemplo.com.br>
|
||||||
|
# SMTP_HOST=smtp.exemplo.com.br
|
||||||
|
# SMTP_PORT=587
|
||||||
|
# SMTP_SECURITY=starttls
|
||||||
|
# SMTP_USER=...
|
||||||
|
# SMTP_PASSWORD=...
|
||||||
STORAGE_ADAPTER=s3-local
|
STORAGE_ADAPTER=s3-local
|
||||||
MOCK_FREIGHT_CENTS=1500
|
MOCK_FREIGHT_CENTS=1500
|
||||||
MAX_UPLOAD_BYTES=5368709120
|
MAX_UPLOAD_BYTES=1073741824
|
||||||
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
|
||||||
|
|||||||
@@ -73,7 +73,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 print_file_test; do
|
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
|
||||||
echo "--- $suite"
|
echo "--- $suite"
|
||||||
$COMPOSE exec -T \
|
$COMPOSE exec -T \
|
||||||
-e SITE_BASE_URL=http://site \
|
-e SITE_BASE_URL=http://site \
|
||||||
@@ -86,13 +86,14 @@ 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 -v
|
run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_payment_messages tests.test_jadlog tests.test_correios tests.test_quote_review tests.test_large_files tests.test_grade_check tests.test_schema tests.test_customer_document tests.test_mail_html tests.test_layout_rules -v
|
||||||
|
|
||||||
- name: Runtime and retention regressions
|
- name: Runtime and retention regressions
|
||||||
run: |
|
run: |
|
||||||
$COMPOSE exec -T api python -m tests.retention_test
|
$COMPOSE exec -T api python -m tests.retention_test
|
||||||
$COMPOSE exec -T api python -m tests.runtime_security_test
|
$COMPOSE exec -T api python -m tests.runtime_security_test
|
||||||
$COMPOSE exec -T api python -m tests.tiny_oauth_test
|
$COMPOSE exec -T api python -m tests.tiny_oauth_test
|
||||||
|
$COMPOSE exec -T backup python -m tests.backup_test
|
||||||
|
|
||||||
# Run Chrome on the Compose network. It must resolve the same storage:9000
|
# Run Chrome on the Compose network. It must resolve the same storage:9000
|
||||||
# hostname used in presigned URLs, and absence of Chrome must fail CI.
|
# hostname used in presigned URLs, and absence of Chrome must fail CI.
|
||||||
@@ -106,7 +107,7 @@ jobs:
|
|||||||
if: failure()
|
if: failure()
|
||||||
run: |
|
run: |
|
||||||
$COMPOSE ps || true
|
$COMPOSE ps || true
|
||||||
$COMPOSE logs --tail 200 api worker site kanban || true
|
$COMPOSE logs --tail 200 api worker backup site kanban || true
|
||||||
|
|
||||||
- name: Tear down
|
- name: Tear down
|
||||||
if: always()
|
if: always()
|
||||||
@@ -206,24 +207,47 @@ jobs:
|
|||||||
- name: Image vulnerabilities
|
- name: Image vulnerabilities
|
||||||
run: |
|
run: |
|
||||||
image="${TRIVY_IMAGE:-aquasec/trivy:0.58.1}"
|
image="${TRIVY_IMAGE:-aquasec/trivy:0.58.1}"
|
||||||
failed=0
|
# One database download for the four scans, kept in a volume between
|
||||||
|
# runs and retried: a failed download from the mirror used to fail
|
||||||
|
# the gate as if a CRITICAL vulnerability had been found.
|
||||||
|
trivy() { docker run --rm -v /var/run/docker.sock:/var/run/docker.sock \
|
||||||
|
-v dtf-trivy-cache:/root/.cache/trivy "$image" "$@"; }
|
||||||
|
for attempt in 1 2 3; do
|
||||||
|
trivy image --download-db-only --no-progress && break
|
||||||
|
if [ "$attempt" -eq 3 ]; then
|
||||||
|
echo "::error::The vulnerability database could not be downloaded; the release images were not scanned."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "Database download failed (attempt $attempt); retrying in 30 s."
|
||||||
|
sleep 30
|
||||||
|
done
|
||||||
|
# Findings exit 5; any other failure means the scan did not run.
|
||||||
|
found=0; broken=0
|
||||||
for target in \
|
for target in \
|
||||||
"gitea.blyzer.com.br/blyzer/dtf-api:${{ gitea.sha }}" \
|
"gitea.blyzer.com.br/blyzer/dtf-api:${{ gitea.sha }}" \
|
||||||
"gitea.blyzer.com.br/blyzer/dtf-web:${{ gitea.sha }}"; do
|
"gitea.blyzer.com.br/blyzer/dtf-web:${{ gitea.sha }}"; do
|
||||||
echo "--- $target (HIGH, reported)"
|
echo "--- $target (HIGH, reported)"
|
||||||
docker run --rm -v /var/run/docker.sock:/var/run/docker.sock "$image" \
|
trivy image --skip-db-update --image-src docker --scanners vuln --severity HIGH --no-progress \
|
||||||
image --image-src docker --scanners vuln --severity HIGH --no-progress \
|
|
||||||
--format table --exit-code 0 "$target" ||
|
--format table --exit-code 0 "$target" ||
|
||||||
echo "::warning::Could not scan $target for HIGH findings"
|
echo "::warning::Could not scan $target for HIGH findings"
|
||||||
echo "--- $target (CRITICAL, blocking)"
|
echo "--- $target (CRITICAL, blocking)"
|
||||||
docker run --rm -v /var/run/docker.sock:/var/run/docker.sock "$image" \
|
set +e
|
||||||
image --image-src docker --scanners vuln --severity CRITICAL --no-progress \
|
trivy image --skip-db-update --image-src docker --scanners vuln --severity CRITICAL --no-progress \
|
||||||
--format table --exit-code 1 "$target" || failed=1
|
--format table --exit-code 5 "$target"
|
||||||
|
verdict=$?
|
||||||
|
set -e
|
||||||
|
if [ "$verdict" -eq 5 ]; then found=1
|
||||||
|
elif [ "$verdict" -ne 0 ]; then broken=1; echo "::error::The CRITICAL scan of $target did not run (exit $verdict)."
|
||||||
|
fi
|
||||||
done
|
done
|
||||||
if [ "$failed" -ne 0 ]; then
|
if [ "$found" -ne 0 ]; then
|
||||||
echo "::error::A CRITICAL vulnerability was found in a release image."
|
echo "::error::A CRITICAL vulnerability was found in a release image."
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
if [ "$broken" -ne 0 ]; then
|
||||||
|
echo "::error::A release image could not be scanned; nothing is published unscanned."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
- name: Publish validated images
|
- name: Publish validated images
|
||||||
run: |
|
run: |
|
||||||
|
|||||||
@@ -12,14 +12,25 @@ from botocore.exceptions import ClientError
|
|||||||
def require_runtime():
|
def require_runtime():
|
||||||
"""Validate the supported local and R2-backed deployment modes.
|
"""Validate the supported local and R2-backed deployment modes.
|
||||||
|
|
||||||
Real payment, freight, ERP, and WhatsApp providers are deliberately not
|
Each provider is fake until its settings are complete; a real one refuses
|
||||||
enabled yet. A non-local deployment keeps those adapters fake and disables
|
to start without them.
|
||||||
checkout until their audited implementations are added.
|
|
||||||
"""
|
"""
|
||||||
environment = os.environ.get('APP_ENV', 'local')
|
environment = os.environ.get('APP_ENV', 'local')
|
||||||
for name in ('FREIGHT', 'WHATSAPP'):
|
freight = os.environ.get('FREIGHT_ADAPTER')
|
||||||
if os.environ.get(f'{name}_ADAPTER') != 'fake':
|
if freight == 'jadlog':
|
||||||
raise RuntimeError(f'{name} must use the currently supported fake adapter')
|
from .jadlog import required_settings as jadlog_settings
|
||||||
|
for name in jadlog_settings():
|
||||||
|
if not os.environ.get(name):
|
||||||
|
raise RuntimeError(f'{name} is required for the Jadlog adapter')
|
||||||
|
elif freight != 'fake':
|
||||||
|
raise RuntimeError('FREIGHT must use the fake or jadlog adapter')
|
||||||
|
# Correios is on when its access code is set; it prices the same package.
|
||||||
|
if os.environ.get('CORREIOS_CODIGO_ACESSO', '').strip():
|
||||||
|
from .correios import required_settings as correios_settings
|
||||||
|
from .package import WEIGHT_SETTINGS
|
||||||
|
for name in (*correios_settings(), *WEIGHT_SETTINGS, 'JADLOG_CAIXA_CM'):
|
||||||
|
if not os.environ.get(name):
|
||||||
|
raise RuntimeError(f'{name} is required for Correios freight')
|
||||||
tiny = os.environ.get('TINY_ADAPTER')
|
tiny = os.environ.get('TINY_ADAPTER')
|
||||||
if tiny == 'tiny':
|
if tiny == 'tiny':
|
||||||
from .tiny import required_settings
|
from .tiny import required_settings
|
||||||
@@ -37,6 +48,16 @@ def require_runtime():
|
|||||||
raise RuntimeError(f'{name} is required for the Mercado Pago adapter')
|
raise RuntimeError(f'{name} is required for the Mercado Pago adapter')
|
||||||
elif payment != 'fake':
|
elif payment != 'fake':
|
||||||
raise RuntimeError('PAYMENT must use the fake or mercadopago adapter')
|
raise RuntimeError('PAYMENT must use the fake or mercadopago adapter')
|
||||||
|
mail = os.environ.get('MAIL_ADAPTER', 'off')
|
||||||
|
if mail == 'smtp':
|
||||||
|
from .mail import required_settings as mail_settings
|
||||||
|
for name in mail_settings():
|
||||||
|
if not os.environ.get(name):
|
||||||
|
raise RuntimeError(f'{name} is required for e-mail by SMTP')
|
||||||
|
if os.environ.get('SMTP_SECURITY', 'starttls') not in ('starttls', 'ssl', 'none'):
|
||||||
|
raise RuntimeError('SMTP_SECURITY must be starttls, ssl or none')
|
||||||
|
elif mail not in ('off', 'log'):
|
||||||
|
raise RuntimeError('MAIL_ADAPTER must be off, log or smtp')
|
||||||
if environment == 'local':
|
if environment == 'local':
|
||||||
if os.environ.get('STORAGE_ADAPTER') != 's3-local':
|
if os.environ.get('STORAGE_ADAPTER') != 's3-local':
|
||||||
raise RuntimeError('Local runtime requires local S3 storage')
|
raise RuntimeError('Local runtime requires local S3 storage')
|
||||||
@@ -106,6 +127,11 @@ class FakePayment:
|
|||||||
|
|
||||||
def create(self, quote_id: str, total_cents: int, customer: dict, method: dict | None = None) -> dict:
|
def create(self, quote_id: str, total_cents: int, customer: dict, method: dict | None = None) -> dict:
|
||||||
kind = (method or {}).get('type', 'pix')
|
kind = (method or {}).get('type', 'pix')
|
||||||
|
if kind == 'pix':
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
expires = (datetime.now(timezone.utc) + timedelta(minutes=30)).isoformat(timespec='milliseconds')
|
||||||
|
return {'provider': 'fake', 'id': f"local-{quote_id}-pix-{(method or {}).get('attempt', 1)}",
|
||||||
|
'status': 'pending', 'total_cents': total_cents, 'expires_at': expires}
|
||||||
return {'provider': 'fake', 'id': f'local-{quote_id}-{kind}',
|
return {'provider': 'fake', 'id': f'local-{quote_id}-{kind}',
|
||||||
'status': 'pending', 'total_cents': total_cents}
|
'status': 'pending', 'total_cents': total_cents}
|
||||||
|
|
||||||
@@ -143,10 +169,13 @@ class FakePayment:
|
|||||||
'status': 'paid', 'total_cents': total_cents}
|
'status': 'paid', 'total_cents': total_cents}
|
||||||
|
|
||||||
class FreightAdapter(Protocol):
|
class FreightAdapter(Protocol):
|
||||||
def quote(self, service: str, postal_code: str) -> dict: ...
|
def quote(self, service: str, postal_code: str, metres=None, declared_cents: int = 0) -> dict: ...
|
||||||
|
|
||||||
class FakeFreight:
|
class FakeFreight:
|
||||||
def quote(self, service: str, postal_code: str) -> dict:
|
name = 'fake'
|
||||||
|
services = {'mock-standard': 'Entrega simulada'}
|
||||||
|
|
||||||
|
def quote(self, service: str, postal_code: str, metres=None, declared_cents: int = 0) -> dict:
|
||||||
if service == 'pickup':
|
if service == 'pickup':
|
||||||
return {'provider': 'fake', 'service': 'pickup', 'total_cents': 0, 'postal_code': ''}
|
return {'provider': 'fake', 'service': 'pickup', 'total_cents': 0, 'postal_code': ''}
|
||||||
if service != 'mock-standard' or len(postal_code) != 8 or not postal_code.isascii() or not postal_code.isdigit():
|
if service != 'mock-standard' or len(postal_code) != 8 or not postal_code.isascii() or not postal_code.isdigit():
|
||||||
@@ -155,7 +184,7 @@ class FakeFreight:
|
|||||||
if cents < 0:
|
if cents < 0:
|
||||||
raise ValueError('Invalid mock freight configuration')
|
raise ValueError('Invalid mock freight configuration')
|
||||||
return {'provider': 'fake', 'service': service, 'postal_code': postal_code,
|
return {'provider': 'fake', 'service': service, 'postal_code': postal_code,
|
||||||
'total_cents': cents, 'description': 'Local simulated freight'}
|
'total_cents': cents, 'description': 'Entrega simulada'}
|
||||||
|
|
||||||
class EventAdapter(Protocol):
|
class EventAdapter(Protocol):
|
||||||
def deliver(self, event_key: str, payload: dict) -> dict: ...
|
def deliver(self, event_key: str, payload: dict) -> dict: ...
|
||||||
@@ -165,11 +194,6 @@ class FakeTiny:
|
|||||||
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'}
|
||||||
|
|
||||||
class FakeWhatsApp:
|
|
||||||
def deliver(self, event_key: str, payload: dict) -> dict:
|
|
||||||
return {'provider': 'fake-whatsapp', 'event_key': event_key,
|
|
||||||
'event': payload['event'], 'status': 'recorded-locally'}
|
|
||||||
|
|
||||||
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: ...
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ from fastapi import APIRouter, Depends, HTTPException
|
|||||||
|
|
||||||
from ..core import db
|
from ..core import db
|
||||||
from ..artwork import submit_files
|
from ..artwork import submit_files
|
||||||
from ..core.auth import operator
|
from ..core.auth import can, operator
|
||||||
from ..core.models import ArtworkSubmission, UploadStart
|
from ..core.models import ArtworkSubmission, UploadStart
|
||||||
from ..runtime import file_rows, operator_identity
|
from ..runtime import file_rows, operator_identity
|
||||||
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
|
||||||
@@ -17,7 +17,7 @@ from .uploads import begin_upload, cancel_upload, complete_upload, part_url, upl
|
|||||||
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(operator)):
|
def begin_final(oid: UUID, body: UploadStart, user=Depends(can('produce'))):
|
||||||
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 state 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')
|
||||||
@@ -29,15 +29,15 @@ def final_status(uid: UUID, user=Depends(operator)):
|
|||||||
return upload_status(uid,session_id=operator_identity(user))
|
return upload_status(uid,session_id=operator_identity(user))
|
||||||
|
|
||||||
@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(operator)):
|
def final_part(uid: UUID, number: int, user=Depends(can('produce'))):
|
||||||
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(operator)):
|
def final_complete(uid: UUID, user=Depends(can('produce'))):
|
||||||
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(operator)):
|
def final_cancel(uid: UUID, user=Depends(can('produce'))):
|
||||||
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')
|
||||||
@@ -46,7 +46,7 @@ def operator_files(oid: UUID, user=Depends(operator)):
|
|||||||
return file_rows(c,oid)
|
return file_rows(c,oid)
|
||||||
|
|
||||||
@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(operator)):
|
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')
|
||||||
|
|||||||
@@ -1,17 +1,23 @@
|
|||||||
"""Customer accounts, their orders, and the corrections they submit."""
|
"""Customer accounts, their orders, and the corrections they submit."""
|
||||||
|
import hashlib
|
||||||
|
import secrets
|
||||||
from datetime import datetime, timedelta, timezone
|
from datetime import datetime, timedelta, timezone
|
||||||
from uuid import UUID, uuid4
|
from uuid import UUID, uuid4
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Request, Response
|
from typing import Literal
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response
|
||||||
from psycopg.errors import UniqueViolation
|
from psycopg.errors import UniqueViolation
|
||||||
from psycopg.types.json import Jsonb
|
from psycopg.types.json import Jsonb
|
||||||
|
|
||||||
from ..core import db
|
from ..core import db
|
||||||
from ..artwork import submit_files
|
from ..artwork import submit_files
|
||||||
from ..core.auth import (DUMMY_PASSWORD_HASH, audit, client_ip, new_session, owner,
|
from ..core.auth import (DUMMY_PASSWORD_HASH, audit, client_ip, new_session, owner, login_failed, password_hash,
|
||||||
login_failed, password_hash, password_matches, session_row, throttle, transfer_guest)
|
password_matches, rate_limit, session_row, throttle, transfer_guest)
|
||||||
from ..core.models import ArtworkSubmission, Login, Register
|
from ..core.models import (ArtworkSubmission, EmailChange, EmailCode, EmailResend, ForgotPassword, Login,
|
||||||
from ..runtime import STATES, file_rows, owned_order, storage
|
PasswordChange, PasswordReset, ProfileUpdate, Register, SignupCode, SignupResend)
|
||||||
|
from .. import mail, mail_html
|
||||||
|
from ..runtime import ENVIRONMENT, PUBLIC_ORIGIN, STATES, file_rows, order_code, owned_order, storage
|
||||||
from ..scanning import require_clean
|
from ..scanning import require_clean
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
@@ -22,6 +28,87 @@ def current(request):
|
|||||||
except HTTPException: return None
|
except HTTPException: return None
|
||||||
|
|
||||||
|
|
||||||
|
# Signup: with e-mail on, the account exists only once the code sent to the
|
||||||
|
# address is entered, so nobody opens an account on someone else's e-mail. The
|
||||||
|
# answer is the same whether or not the address already has an account: that
|
||||||
|
# address gets a notice to sign in instead of a code, and no code works.
|
||||||
|
CODE_ATTEMPTS = 5
|
||||||
|
CODE_SENDS = 5
|
||||||
|
RESEND_SECONDS = 60
|
||||||
|
|
||||||
|
|
||||||
|
def signup_code(c, signup_id, email, name):
|
||||||
|
"""A fresh code for a signup (or the notice for an address that already has
|
||||||
|
an account, greeting that account's owner), queued by e-mail. Returns the
|
||||||
|
code's hash, None for the notice."""
|
||||||
|
existing = c.execute('SELECT profile FROM dtf_local.accounts WHERE email=%s', (email,)).fetchone()
|
||||||
|
if existing:
|
||||||
|
owner = existing['profile'].get('name')
|
||||||
|
login = f'{PUBLIC_ORIGIN}/conta/entrar'
|
||||||
|
mail.queue(c, 'account', email, 'Você já tem conta · DTF Dropstar',
|
||||||
|
f'{mail_html.greeting(owner)}\n\nAlguém tentou criar uma conta no DTF Dropstar com este e-mail, '
|
||||||
|
'mas ele já tem conta.\n\n'
|
||||||
|
f'Para entrar: {login}\n'
|
||||||
|
'Esqueceu a senha? Na mesma página, clique em “Esqueci minha senha”.\n\n'
|
||||||
|
'Se não foi você, ignore este e-mail: nada muda na sua conta.',
|
||||||
|
mail_html.account_exists(owner, login))
|
||||||
|
return None
|
||||||
|
return send_code(c, signup_id, email, 'signup', name)
|
||||||
|
|
||||||
|
|
||||||
|
# What a code is for: the text, the e-mail's heading, and what stays the same
|
||||||
|
# if it was not the customer who asked.
|
||||||
|
CODE_PURPOSES = {
|
||||||
|
'signup': ('criar a sua conta no DTF Dropstar', 'Confirme seu e-mail', 'nenhuma conta é criada sem ele.'),
|
||||||
|
'email': ('trocar o e-mail da sua conta no DTF Dropstar', 'Confirme seu novo e-mail',
|
||||||
|
'o e-mail da conta continua o mesmo.'),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def send_code(c, key, email, purpose, name=''):
|
||||||
|
"""A fresh 6-digit code by e-mail for `purpose` (CODE_PURPOSES); returns its hash."""
|
||||||
|
text, heading, unchanged = CODE_PURPOSES[purpose]
|
||||||
|
code = f'{secrets.randbelow(10 ** 6):06d}'
|
||||||
|
mail.queue(c, 'code', email, f'{code} é o seu código · DTF Dropstar',
|
||||||
|
f'{mail_html.greeting(name)}\n\nO seu código para {text} é:\n\n{code}\n\n'
|
||||||
|
f'Ele vale por {mail.CODE_MINUTES} minutos. Se não foi você, ignore este e-mail: {unchanged}',
|
||||||
|
mail_html.code(name, heading, text, code, mail.CODE_MINUTES, unchanged))
|
||||||
|
return code_digest(key, code)
|
||||||
|
|
||||||
|
|
||||||
|
def checked_code(c, table, key, code, request, extra=''):
|
||||||
|
"""The pending row a code confirms, locked, or the refusal to raise. A wrong
|
||||||
|
code counts against the row; the caller raises after its block commits."""
|
||||||
|
row = c.execute(f'SELECT * FROM dtf_local.{table} WHERE id=%s AND done_at IS NULL {extra} FOR UPDATE',
|
||||||
|
key).fetchone()
|
||||||
|
if not row or row['expires_at'] <= datetime.now(timezone.utc):
|
||||||
|
return None, HTTPException(410, 'Este código venceu. Clique em “Reenviar código”.')
|
||||||
|
if row['attempts'] >= CODE_ATTEMPTS:
|
||||||
|
return None, HTTPException(429, 'Muitas tentativas com este código. Clique em “Reenviar código”.')
|
||||||
|
if row['code_hash'] and secrets.compare_digest(row['code_hash'], code_digest(row['id'], code)):
|
||||||
|
c.execute(f'UPDATE dtf_local.{table} SET done_at=now() WHERE id=%s', (row['id'],))
|
||||||
|
return row, None
|
||||||
|
c.execute(f'UPDATE dtf_local.{table} SET attempts=attempts+1 WHERE id=%s', (row['id'],))
|
||||||
|
left = CODE_ATTEMPTS - row['attempts'] - 1
|
||||||
|
audit('code_wrong', kind=table, ip=client_ip(request))
|
||||||
|
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”.'))
|
||||||
|
|
||||||
|
|
||||||
|
def resend_wait(row):
|
||||||
|
"""Why another code cannot go yet, or None."""
|
||||||
|
wait = RESEND_SECONDS - (datetime.now(timezone.utc) - row['sent_at']).total_seconds()
|
||||||
|
if wait > 0:
|
||||||
|
return HTTPException(429, f'Aguarde {int(wait) + 1} s para pedir outro código.')
|
||||||
|
if row['sends'] >= CODE_SENDS:
|
||||||
|
return HTTPException(429, 'Limite de códigos atingido. Comece de novo em alguns minutos.')
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def code_digest(signup_id, code):
|
||||||
|
return hashlib.sha256(f'{signup_id}:{code}'.encode()).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
@router.post('/api/account/register')
|
@router.post('/api/account/register')
|
||||||
def register(body: Register, request: Request, response: Response):
|
def register(body: Register, request: Request, response: Response):
|
||||||
email = body.customer.mail.strip().lower()
|
email = body.customer.mail.strip().lower()
|
||||||
@@ -29,22 +116,109 @@ def register(body: Register, request: Request, response: Response):
|
|||||||
# Registration attempts keep counting against the email, as before.
|
# Registration attempts keep counting against the email, as before.
|
||||||
login_failed(email)
|
login_failed(email)
|
||||||
previous = current(request)
|
previous = current(request)
|
||||||
encoded = password_hash(body.password)
|
|
||||||
identity = uuid4()
|
|
||||||
profile = body.customer.model_dump()
|
profile = body.customer.model_dump()
|
||||||
profile['mail'] = email
|
profile['mail'] = email
|
||||||
try:
|
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
if previous and c.execute('SELECT id FROM dtf_local.accounts WHERE id=%s', (previous['owner'],)).fetchone():
|
if previous and c.execute('SELECT id FROM dtf_local.accounts WHERE id=%s', (previous['owner'],)).fetchone():
|
||||||
raise HTTPException(409, 'Sign out before registering another account')
|
raise HTTPException(409, 'Saia da conta atual antes de criar outra.')
|
||||||
c.execute('INSERT INTO dtf_local.accounts(id,email,password_hash,profile) VALUES(%s,%s,%s,%s)', (identity,email,encoded,Jsonb(profile)))
|
if mail.configured():
|
||||||
|
rate_limit('signup-account', email, CODE_SENDS, 3600)
|
||||||
|
signup_id = uuid4()
|
||||||
|
with db.connect() as c:
|
||||||
|
digest = signup_code(c, signup_id, email, profile.get('name'))
|
||||||
|
c.execute('''INSERT INTO dtf_local.account_signups(id,email,profile,password_hash,code_hash,expires_at)
|
||||||
|
VALUES(%s,%s,%s,%s,%s,now() + %s * interval '1 minute')''',
|
||||||
|
(signup_id, email, Jsonb(profile), password_hash(body.password), digest, mail.CODE_MINUTES))
|
||||||
|
audit('account_signup_started', ip=client_ip(request))
|
||||||
|
return {'verify': str(signup_id), 'email': email, 'minutes': mail.CODE_MINUTES, 'resend_seconds': RESEND_SECONDS}
|
||||||
|
# Without e-mail there is no code to send: the account is created at once.
|
||||||
|
return create_account(profile=profile, password=password_hash(body.password), previous=previous, response=response)
|
||||||
|
|
||||||
|
|
||||||
|
def claim_orders(c, identity, profile):
|
||||||
|
"""Orders bought without an account with this account's CPF/CNPJ and
|
||||||
|
e-mail, from any browser. Only for an e-mail confirmed with a code: a
|
||||||
|
CPF or CNPJ alone, which others may know, never brings anyone's orders.
|
||||||
|
Each order comes with its cart and the customer's files."""
|
||||||
|
document = ''.join(ch for ch in str(profile.get('cnpj') or '') if ch.isdigit())
|
||||||
|
if not document:
|
||||||
|
return 0
|
||||||
|
orders = c.execute('''SELECT o.id,o.owner,o.quote_id,o.snapshot FROM dtf_local.orders o
|
||||||
|
WHERE o.owner<>%s AND NOT EXISTS (SELECT 1 FROM dtf_local.accounts a WHERE a.id=o.owner)
|
||||||
|
AND regexp_replace(coalesce(o.snapshot->'customer'->>'cnpj',''),'\\D','','g')=%s
|
||||||
|
AND lower(trim(o.snapshot->'customer'->>'mail'))=%s
|
||||||
|
FOR UPDATE''', (identity, document, profile['mail'].strip().lower())).fetchall()
|
||||||
|
for order in orders:
|
||||||
|
uploads = [uid for item in order['snapshot'].get('items') or [] for uid in item.get('uploads') or []]
|
||||||
|
uploads += [row['upload_id'] for row in c.execute(
|
||||||
|
'SELECT upload_id FROM dtf_local.order_files WHERE order_id=%s', (order['id'],)).fetchall()]
|
||||||
|
c.execute('UPDATE dtf_local.orders SET owner=%s WHERE id=%s', (identity, order['id']))
|
||||||
|
c.execute('UPDATE dtf_local.quotes SET owner=%s WHERE id=%s AND owner=%s', (identity, order['quote_id'], order['owner']))
|
||||||
|
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']))
|
||||||
|
if orders:
|
||||||
|
audit('account_orders_claimed', account=str(identity), orders=len(orders))
|
||||||
|
return len(orders)
|
||||||
|
|
||||||
|
|
||||||
|
def create_account(profile, password, previous, response, verified=False):
|
||||||
|
identity = uuid4()
|
||||||
|
try:
|
||||||
|
with db.connect() as c:
|
||||||
|
c.execute('INSERT INTO dtf_local.accounts(id,email,password_hash,profile,email_verified) VALUES(%s,%s,%s,%s,%s)',
|
||||||
|
(identity, profile['mail'], password, Jsonb(profile), verified))
|
||||||
if previous: transfer_guest(c, previous, identity)
|
if previous: transfer_guest(c, previous, identity)
|
||||||
|
if verified: claim_orders(c, identity, profile)
|
||||||
new_session(c, response, identity)
|
new_session(c, response, identity)
|
||||||
except UniqueViolation:
|
except UniqueViolation:
|
||||||
raise HTTPException(409, 'An account already exists; sign in')
|
raise HTTPException(409, 'Já existe uma conta com este e-mail. Entre com a sua senha.')
|
||||||
audit('account_registered', account=str(identity))
|
audit('account_registered', account=str(identity))
|
||||||
return {'customer': profile}
|
return {'customer': profile}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/account/register/verify')
|
||||||
|
def register_verify(body: SignupCode, request: Request, response: Response):
|
||||||
|
rate_limit('code-verify', client_ip(request), 30)
|
||||||
|
with db.connect() as c:
|
||||||
|
signup, refusal = checked_code(c, 'account_signups', (body.signup,), body.code, request)
|
||||||
|
# Raised outside the block, so a wrong attempt is counted, not rolled back.
|
||||||
|
if refusal:
|
||||||
|
raise refusal
|
||||||
|
return create_account(profile=signup['profile'], password=signup['password_hash'],
|
||||||
|
previous=current(request), response=response, verified=True)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get('/api/account/register/dev-code')
|
||||||
|
def register_dev_code(signup: UUID):
|
||||||
|
"""The local stack's last code for a signup, for the browser test, which
|
||||||
|
cannot read the database. Only where e-mail stays in the log; elsewhere
|
||||||
|
the code exists only in the customer's inbox."""
|
||||||
|
if ENVIRONMENT != 'local' or mail.ADAPTER != 'log':
|
||||||
|
raise HTTPException(404, 'Not found')
|
||||||
|
with db.connect() as c:
|
||||||
|
row = c.execute('''SELECT m.body FROM dtf_local.account_signups s JOIN dtf_local.mail_queue m
|
||||||
|
ON m.to_addr=s.email AND m.kind='code' WHERE s.id=%s ORDER BY m.id DESC LIMIT 1''', (signup,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(404, 'Not found')
|
||||||
|
return {'code': next(word for word in row['body'].split() if word.isdigit() and len(word) == 6)}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/account/register/resend')
|
||||||
|
def register_resend(body: SignupResend, request: Request):
|
||||||
|
rate_limit('code-verify', client_ip(request), 30)
|
||||||
|
with db.connect() as c:
|
||||||
|
signup = c.execute('SELECT * FROM dtf_local.account_signups WHERE id=%s AND done_at IS NULL FOR UPDATE',
|
||||||
|
(body.signup,)).fetchone()
|
||||||
|
if not signup:
|
||||||
|
raise HTTPException(410, 'Este cadastro venceu. Preencha os dados de novo.')
|
||||||
|
if refusal := resend_wait(signup):
|
||||||
|
raise refusal
|
||||||
|
digest = signup_code(c, signup['id'], signup['email'], signup['profile'].get('name'))
|
||||||
|
c.execute('''UPDATE dtf_local.account_signups SET code_hash=%s, attempts=0, sends=sends+1, sent_at=now(),
|
||||||
|
expires_at=now() + %s * interval '1 minute' WHERE id=%s''', (digest, mail.CODE_MINUTES, signup['id']))
|
||||||
|
audit('account_signup_code_resent', ip=client_ip(request))
|
||||||
|
return {'ok': True, 'minutes': mail.CODE_MINUTES, 'resend_seconds': RESEND_SECONDS}
|
||||||
|
|
||||||
@router.post('/api/account/login')
|
@router.post('/api/account/login')
|
||||||
def login(body: Login, request: Request, response: Response):
|
def login(body: Login, request: Request, response: Response):
|
||||||
email = body.email.strip().lower()
|
email = body.email.strip().lower()
|
||||||
@@ -57,7 +231,7 @@ def login(body: Login, request: Request, response: Response):
|
|||||||
if not account or not matches:
|
if not account or not matches:
|
||||||
login_failed(email)
|
login_failed(email)
|
||||||
audit('customer_login_failed', ip=client_ip(request))
|
audit('customer_login_failed', ip=client_ip(request))
|
||||||
raise HTTPException(401, 'Invalid email or password')
|
raise HTTPException(401, 'E-mail ou senha inválidos.')
|
||||||
previous = current(request)
|
previous = current(request)
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
if not stored.startswith('scrypt-v2$'):
|
if not stored.startswith('scrypt-v2$'):
|
||||||
@@ -65,6 +239,9 @@ def login(body: Login, request: Request, response: Response):
|
|||||||
if previous:
|
if previous:
|
||||||
transfer_guest(c, previous, account['id'])
|
transfer_guest(c, previous, account['id'])
|
||||||
c.execute('DELETE FROM dtf_local.sessions WHERE id=%s', (previous['id'],))
|
c.execute('DELETE FROM dtf_local.sessions WHERE id=%s', (previous['id'],))
|
||||||
|
# Orders bought without the account since, on any device.
|
||||||
|
if account['email_verified']:
|
||||||
|
claim_orders(c, account['id'], account['profile'])
|
||||||
new_session(c, response, account['id'])
|
new_session(c, response, account['id'])
|
||||||
audit('customer_login_success', account=str(account['id']))
|
audit('customer_login_success', account=str(account['id']))
|
||||||
return {'customer': account['profile']}
|
return {'customer': account['profile']}
|
||||||
@@ -86,21 +263,248 @@ def me(identity=Depends(owner)):
|
|||||||
row = c.execute('SELECT profile FROM dtf_local.accounts WHERE id=%s', (identity,)).fetchone()
|
row = c.execute('SELECT profile FROM dtf_local.accounts WHERE id=%s', (identity,)).fetchone()
|
||||||
return {'customer': row['profile'] if row else None}
|
return {'customer': row['profile'] if row else None}
|
||||||
|
|
||||||
@router.get('/api/customer/orders')
|
def account_row(c, identity, lock=False):
|
||||||
def orders(identity=Depends(owner)):
|
row = c.execute('SELECT * FROM dtf_local.accounts WHERE id=%s' + (' FOR UPDATE' if lock else ''), (identity,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(401, 'Entre na sua conta.')
|
||||||
|
return row
|
||||||
|
|
||||||
|
@router.post('/api/account/profile')
|
||||||
|
def update_profile(body: ProfileUpdate, identity=Depends(owner)):
|
||||||
|
"""Name, WhatsApp and the saved delivery address. The CPF or CNPJ is the account's and
|
||||||
|
does not change; the e-mail is the login and changes on its own route."""
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
rows = c.execute('SELECT id,number,state,version,snapshot,created_at,updated_at FROM dtf_local.orders WHERE owner=%s ORDER BY created_at DESC', (identity,)).fetchall()
|
row = account_row(c, identity, lock=True)
|
||||||
quotes = c.execute('''SELECT q.id,q.approved,q.approved_at,q.created_at FROM dtf_local.quotes q
|
profile = {**row['profile'], 'zap': body.zap,
|
||||||
LEFT JOIN dtf_local.orders o ON o.quote_id=q.id WHERE q.owner=%s AND o.id IS NULL ORDER BY q.created_at DESC''', (identity,)).fetchall()
|
'address': body.address.model_dump() if body.address else None}
|
||||||
return {'orders': rows, 'quotes': quotes, 'states': STATES}
|
if body.name is not None:
|
||||||
|
profile['name'] = body.name
|
||||||
|
c.execute('UPDATE dtf_local.accounts SET profile=%s WHERE id=%s', (Jsonb(profile), identity))
|
||||||
|
audit('account_profile_updated', account=str(identity))
|
||||||
|
return {'customer': profile}
|
||||||
|
|
||||||
|
@router.post('/api/account/email')
|
||||||
|
def change_email(body: EmailChange, request: Request, identity=Depends(owner)):
|
||||||
|
with db.connect() as c:
|
||||||
|
row = account_row(c, identity)
|
||||||
|
throttle(row['email'], request)
|
||||||
|
if not password_matches(body.password, row['password_hash']):
|
||||||
|
login_failed(row['email'])
|
||||||
|
raise HTTPException(401, 'Senha incorreta.')
|
||||||
|
if body.email == row['email']:
|
||||||
|
raise HTTPException(422, 'Este já é o e-mail da sua conta.')
|
||||||
|
if not mail.configured():
|
||||||
|
return apply_email(identity, row, body.email)
|
||||||
|
# With e-mail on, the change waits for the code sent to the new address.
|
||||||
|
rate_limit('email-change', str(identity), CODE_SENDS, 3600)
|
||||||
|
change = uuid4()
|
||||||
|
with db.connect() as c:
|
||||||
|
if c.execute('SELECT 1 FROM dtf_local.accounts WHERE email=%s', (body.email,)).fetchone():
|
||||||
|
raise HTTPException(409, 'Este e-mail já é de outra conta.')
|
||||||
|
digest = send_code(c, change, body.email, 'email', row['profile'].get('name'))
|
||||||
|
c.execute('''INSERT INTO dtf_local.email_changes(id,account_id,new_email,code_hash,expires_at)
|
||||||
|
VALUES(%s,%s,%s,%s,now() + %s * interval '1 minute')''', (change, identity, body.email, digest, mail.CODE_MINUTES))
|
||||||
|
audit('account_email_change_started', account=str(identity))
|
||||||
|
return {'verify': str(change), 'email': body.email, 'minutes': mail.CODE_MINUTES, 'resend_seconds': RESEND_SECONDS}
|
||||||
|
|
||||||
|
|
||||||
|
def apply_email(identity, row, email):
|
||||||
|
"""Switch the account to the new e-mail and tell the old address."""
|
||||||
|
profile = {**row['profile'], 'mail': email}
|
||||||
|
try:
|
||||||
|
with db.connect() as c:
|
||||||
|
c.execute('UPDATE dtf_local.accounts SET email=%s, profile=%s, email_verified=true WHERE id=%s',
|
||||||
|
(email, Jsonb(profile), identity))
|
||||||
|
claim_orders(c, identity, profile)
|
||||||
|
name = row['profile'].get('name')
|
||||||
|
mail.queue(c, 'notice', row['email'], 'O e-mail da sua conta foi trocado · DTF Dropstar',
|
||||||
|
f'{mail_html.greeting(name)}\n\nO e-mail da sua conta no DTF Dropstar foi trocado para {email}. '
|
||||||
|
'A partir de agora, entre com ele.\n\n'
|
||||||
|
'Se não foi você, fale com a Dropstar pelo WhatsApp 16 99428-0056.',
|
||||||
|
mail_html.email_changed(name, row['email'], email))
|
||||||
|
except UniqueViolation:
|
||||||
|
raise HTTPException(409, 'Este e-mail já é de outra conta.')
|
||||||
|
audit('account_email_changed', account=str(identity))
|
||||||
|
return {'customer': profile}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/account/email/verify')
|
||||||
|
def change_email_verify(body: EmailCode, request: Request, identity=Depends(owner)):
|
||||||
|
rate_limit('code-verify', client_ip(request), 30)
|
||||||
|
with db.connect() as c:
|
||||||
|
change, refusal = checked_code(c, 'email_changes', (body.change, identity), body.code, request,
|
||||||
|
extra='AND account_id=%s')
|
||||||
|
row = account_row(c, identity) if change else None
|
||||||
|
if refusal:
|
||||||
|
raise refusal
|
||||||
|
return apply_email(identity, row, change['new_email'])
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/account/email/resend')
|
||||||
|
def change_email_resend(body: EmailResend, request: Request, identity=Depends(owner)):
|
||||||
|
rate_limit('code-verify', client_ip(request), 30)
|
||||||
|
with db.connect() as c:
|
||||||
|
change = c.execute('''SELECT * FROM dtf_local.email_changes WHERE id=%s AND account_id=%s AND done_at IS NULL
|
||||||
|
FOR UPDATE''', (body.change, identity)).fetchone()
|
||||||
|
if not change:
|
||||||
|
raise HTTPException(410, 'Esta troca venceu. Comece de novo.')
|
||||||
|
if refusal := resend_wait(change):
|
||||||
|
raise refusal
|
||||||
|
name = c.execute('SELECT profile FROM dtf_local.accounts WHERE id=%s', (identity,)).fetchone()['profile'].get('name')
|
||||||
|
digest = send_code(c, change['id'], change['new_email'], 'email', name)
|
||||||
|
c.execute('''UPDATE dtf_local.email_changes SET code_hash=%s, attempts=0, sends=sends+1, sent_at=now(),
|
||||||
|
expires_at=now() + %s * interval '1 minute' WHERE id=%s''', (digest, mail.CODE_MINUTES, change['id']))
|
||||||
|
return {'ok': True, 'minutes': mail.CODE_MINUTES, 'resend_seconds': RESEND_SECONDS}
|
||||||
|
|
||||||
|
@router.post('/api/account/password')
|
||||||
|
def change_password(body: PasswordChange, request: Request, identity=Depends(owner)):
|
||||||
|
with db.connect() as c:
|
||||||
|
row = account_row(c, identity)
|
||||||
|
throttle(row['email'], request)
|
||||||
|
if not password_matches(body.current, row['password_hash']):
|
||||||
|
login_failed(row['email'])
|
||||||
|
raise HTTPException(401, 'Senha atual incorreta.')
|
||||||
|
session = current(request)
|
||||||
|
with db.connect() as c:
|
||||||
|
c.execute('UPDATE dtf_local.accounts SET password_hash=%s WHERE id=%s', (password_hash(body.new), identity))
|
||||||
|
# Other devices signed in with the old password are signed out.
|
||||||
|
c.execute('DELETE FROM dtf_local.sessions WHERE owner=%s AND id<>%s', (identity, session['id']))
|
||||||
|
audit('account_password_changed', account=str(identity))
|
||||||
|
return {'ok': True}
|
||||||
|
|
||||||
|
# Password recovery: a link by e-mail that works once, for an hour. The answer
|
||||||
|
# never says whether the e-mail has an account.
|
||||||
|
RESET_SENT = 'Se houver uma conta com este e-mail, enviamos um link para criar uma nova senha. Ele vale por 1 hora.'
|
||||||
|
|
||||||
|
@router.post('/api/account/forgot')
|
||||||
|
def forgot_password(body: ForgotPassword, request: Request):
|
||||||
|
if not mail.configured():
|
||||||
|
raise HTTPException(503, 'A recuperação por e-mail ainda não está disponível. Fale com a Dropstar pelo WhatsApp.')
|
||||||
|
email = body.email.strip().lower()
|
||||||
|
rate_limit('reset-source', client_ip(request), 10)
|
||||||
|
# Per address: a few links an hour, so nobody fills someone's inbox.
|
||||||
|
rate_limit('reset-account', email, 3, 3600)
|
||||||
|
token = secrets.token_urlsafe(32)
|
||||||
|
with db.connect() as c:
|
||||||
|
account = c.execute('SELECT id,profile FROM dtf_local.accounts WHERE email=%s', (email,)).fetchone()
|
||||||
|
if account:
|
||||||
|
c.execute('''INSERT INTO dtf_local.password_resets(token_hash,account_id,expires_at)
|
||||||
|
VALUES(%s,%s,now() + %s * interval '1 minute')''',
|
||||||
|
(hashlib.sha256(token.encode()).hexdigest(), account['id'], mail.RESET_MINUTES))
|
||||||
|
# In the fragment, not the query: it is never sent to a server,
|
||||||
|
# nor in the Referer of the fonts and the logo the page loads.
|
||||||
|
link = f'{PUBLIC_ORIGIN}/conta/redefinir#{token}'
|
||||||
|
name = account['profile'].get('name')
|
||||||
|
mail.queue(c, 'reset', email, 'Crie uma nova senha · DTF Dropstar',
|
||||||
|
f'{mail_html.greeting(name)}\n\nAlguém pediu para criar uma nova senha na sua conta do DTF Dropstar. '
|
||||||
|
f'Para criar, abra o link abaixo. Ele vale por 1 hora e funciona uma vez só.\n\n{link}\n\n'
|
||||||
|
'Se não foi você, ignore este e-mail: a sua senha continua a mesma.',
|
||||||
|
mail_html.reset(name, link, mail.RESET_MINUTES))
|
||||||
|
audit('password_reset_requested', account=str(account['id']) if account else None, ip=client_ip(request))
|
||||||
|
return {'ok': True, 'message': RESET_SENT}
|
||||||
|
|
||||||
|
@router.post('/api/account/reset')
|
||||||
|
def reset_password(body: PasswordReset, request: Request, response: Response):
|
||||||
|
rate_limit('reset-source', client_ip(request), 10)
|
||||||
|
digest = hashlib.sha256(body.token.encode()).hexdigest()
|
||||||
|
previous = current(request)
|
||||||
|
with db.connect() as c:
|
||||||
|
reset = c.execute('''SELECT * FROM dtf_local.password_resets WHERE token_hash=%s
|
||||||
|
AND used_at IS NULL AND expires_at>now() FOR UPDATE''', (digest,)).fetchone()
|
||||||
|
if not reset:
|
||||||
|
audit('password_reset_refused', ip=client_ip(request))
|
||||||
|
raise HTTPException(400, 'Este link venceu ou já foi usado. Peça outro em “Esqueci minha senha”.')
|
||||||
|
identity = reset['account_id']
|
||||||
|
account = account_row(c, identity, lock=True)
|
||||||
|
# The link came by e-mail, so the address is confirmed too.
|
||||||
|
c.execute('UPDATE dtf_local.accounts SET password_hash=%s, email_verified=true WHERE id=%s',
|
||||||
|
(password_hash(body.password), identity))
|
||||||
|
c.execute('UPDATE dtf_local.password_resets SET used_at=now() WHERE token_hash=%s', (digest,))
|
||||||
|
# Every other link to this account stops working, and so does every
|
||||||
|
# session signed in with the old password.
|
||||||
|
c.execute('DELETE FROM dtf_local.password_resets WHERE account_id=%s AND used_at IS NULL', (identity,))
|
||||||
|
if previous:
|
||||||
|
transfer_guest(c, previous, identity)
|
||||||
|
claim_orders(c, identity, account['profile'])
|
||||||
|
c.execute('DELETE FROM dtf_local.sessions WHERE owner=%s', (identity,))
|
||||||
|
if previous:
|
||||||
|
c.execute('DELETE FROM dtf_local.sessions WHERE id=%s', (previous['id'],))
|
||||||
|
new_session(c, response, identity)
|
||||||
|
audit('password_reset', account=str(identity))
|
||||||
|
return {'customer': account['profile']}
|
||||||
|
|
||||||
|
# The order list's groups, as the customer filters them.
|
||||||
|
GROUPS = {'pay': 'Aguardando pagamento', 'prod': 'Em produção', 'cor': 'Correção', 'fin': 'Finalizados'}
|
||||||
|
ENTRIES = '''WITH live_quote AS (
|
||||||
|
-- The cart waiting for payment: the newest unpaid quote whose files still
|
||||||
|
-- exist. An older one was replaced when the cart changed, and one whose
|
||||||
|
-- files are gone can no longer be paid.
|
||||||
|
SELECT q.id, q.created_at, q.approved FROM dtf_local.quotes q
|
||||||
|
LEFT JOIN dtf_local.orders o ON o.quote_id=q.id
|
||||||
|
WHERE q.owner=%(me)s AND o.id IS NULL AND q.discarded_at IS NULL
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM jsonb_array_elements(q.draft->'items') i
|
||||||
|
CROSS JOIN LATERAL jsonb_array_elements_text(i->'uploads') u(uid)
|
||||||
|
JOIN dtf_local.uploads up ON up.id=u.uid::uuid
|
||||||
|
WHERE up.purged_at IS NOT NULL OR up.expires_at<=now())
|
||||||
|
ORDER BY q.created_at DESC LIMIT 1
|
||||||
|
), entries AS (
|
||||||
|
SELECT 'order' AS kind, o.id, o.number, CASE WHEN o.cancelled_at IS NOT NULL THEN 'cancelled' ELSE o.state END,
|
||||||
|
CASE WHEN o.cancelled_at IS NOT NULL OR o.state='fin' THEN 'fin' WHEN o.state='cor' THEN 'cor' ELSE 'prod' END AS grp,
|
||||||
|
(o.snapshot->>'total_cents')::bigint AS total_cents, o.created_at, o.snapshot->'items' AS items
|
||||||
|
FROM dtf_local.orders o WHERE o.owner=%(me)s
|
||||||
|
UNION ALL
|
||||||
|
SELECT 'quote', q.id, NULL, CASE WHEN q.approved IS NULL THEN 'review' ELSE 'pay' END, 'pay',
|
||||||
|
(q.approved->>'total_cents')::bigint, q.created_at, COALESCE(q.approved->'items','[]'::jsonb)
|
||||||
|
FROM live_quote q
|
||||||
|
)'''
|
||||||
|
|
||||||
|
@router.get('/api/customer/orders')
|
||||||
|
def orders(identity=Depends(owner), status: Literal['all','pay','prod','cor','fin'] = 'all',
|
||||||
|
number: int | None = Query(None, ge=1), code: str | None = Query(None, max_length=12, pattern=r'^[0-9A-Fa-f]+$'),
|
||||||
|
days: int = Query(0, ge=0, le=3650),
|
||||||
|
page: int = Query(1, ge=1, le=10000), size: int = Query(10, ge=1, le=50)):
|
||||||
|
"""The customer's orders and the cart waiting for payment, newest first,
|
||||||
|
filtered and a page at a time, with how many there are in each group."""
|
||||||
|
params = {'me': identity, 'grp': None if status == 'all' else status, 'number': number,
|
||||||
|
'code': code.lower() + '%' if code else None,
|
||||||
|
'since': datetime.now(timezone.utc) - timedelta(days=days) if days else None,
|
||||||
|
'size': size, 'offset': (page - 1) * size}
|
||||||
|
where = '''WHERE (%(grp)s::text IS NULL OR grp=%(grp)s) AND (%(number)s::int IS NULL OR number=%(number)s)
|
||||||
|
AND (%(code)s::text IS NULL OR (kind='order' AND replace(id::text,'-','') LIKE %(code)s))
|
||||||
|
AND (%(since)s::timestamptz IS NULL OR created_at>=%(since)s)'''
|
||||||
|
with db.connect() as c:
|
||||||
|
counts = {r['grp']: r['n'] for r in c.execute(ENTRIES + ' SELECT grp, count(*) AS n FROM entries GROUP BY grp', params).fetchall()}
|
||||||
|
total = c.execute(ENTRIES + ' SELECT count(*) AS n FROM entries ' + where, params).fetchone()['n']
|
||||||
|
rows = c.execute(ENTRIES + ' SELECT * FROM entries ' + where +
|
||||||
|
' ORDER BY created_at DESC LIMIT %(size)s OFFSET %(offset)s', params).fetchall()
|
||||||
|
items = []
|
||||||
|
for r in rows:
|
||||||
|
entry = {'kind': r['kind'], 'id': r['id'], 'number': r['number'], 'state': r['state'],
|
||||||
|
'code': order_code(r['id']) if r['kind'] == 'order' else None,
|
||||||
|
'group': r['grp'], 'total_cents': r['total_cents'], 'created_at': r['created_at'],
|
||||||
|
'items': [{'mode': i['mode'], 'billed_metres': i.get('billed_metres')} for i in r['items']]}
|
||||||
|
if r['kind'] == 'quote':
|
||||||
|
# A PIX code still open is paid on its own page.
|
||||||
|
pix = c.execute('''SELECT 1 FROM dtf_local.payment_intents WHERE quote_id=%s AND method='pix'
|
||||||
|
AND status='pending' AND COALESCE((response->>'expires_at')::timestamptz > now(), false)''',
|
||||||
|
(r['id'],)).fetchone()
|
||||||
|
entry['pay_with'] = 'pix' if pix else 'page'
|
||||||
|
items.append(entry)
|
||||||
|
return {'items': items, 'total': total, 'page': page, 'size': size,
|
||||||
|
'counts': {g: counts.get(g, 0) for g in GROUPS}, 'groups': GROUPS, 'states': STATES}
|
||||||
|
|
||||||
@router.get('/api/customer/orders/{oid}')
|
@router.get('/api/customer/orders/{oid}')
|
||||||
def detail(oid: UUID, identity=Depends(owner)):
|
def detail(oid: UUID, identity=Depends(owner)):
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
row = owned_order(c, oid, identity)
|
row = owned_order(c, oid, identity)
|
||||||
history = c.execute('SELECT from_state,to_state,reason,created_at FROM dtf_local.movements WHERE order_id=%s ORDER BY id', (oid,)).fetchall()
|
# A move back undoes an operator's mistake and its reason is internal;
|
||||||
return {'id': row['id'], 'number': row['number'], 'state': row['state'], 'version': row['version'],
|
# only a correction's reason is written for the customer.
|
||||||
'snapshot': row['snapshot'], 'history': history, 'files': file_rows(c,oid)}
|
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()
|
||||||
|
return {'id': row['id'], 'number': row['number'], 'code': order_code(row['id']),
|
||||||
|
'state': row['state'], 'version': row['version'],
|
||||||
|
'created_at': row['created_at'], 'snapshot': row['snapshot'], 'history': history,
|
||||||
|
'files': file_rows(c,oid)}
|
||||||
|
|
||||||
@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)):
|
||||||
@@ -113,7 +517,7 @@ def customer_download(oid: UUID, fid: UUID, identity=Depends(owner)):
|
|||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
owned_order(c,oid,identity)
|
owned_order(c,oid,identity)
|
||||||
row = c.execute('SELECT u.* FROM dtf_local.order_files f JOIN dtf_local.uploads u ON u.id=f.upload_id WHERE f.id=%s AND f.order_id=%s AND f.active', (fid,oid)).fetchone()
|
row = c.execute('SELECT u.* FROM dtf_local.order_files f JOIN dtf_local.uploads u ON u.id=f.upload_id WHERE f.id=%s AND f.order_id=%s AND f.active', (fid,oid)).fetchone()
|
||||||
if not row: raise HTTPException(404, 'Active file not found')
|
if not row: raise HTTPException(404, 'Arquivo não encontrado.')
|
||||||
if row['expires_at'] <= datetime.now(timezone.utc): raise HTTPException(410, 'File expired')
|
if row['expires_at'] <= datetime.now(timezone.utc): raise HTTPException(410, 'Este arquivo não está mais disponível: os arquivos ficam guardados por 30 dias.')
|
||||||
require_clean(row)
|
require_clean(row)
|
||||||
return {'url':storage.download(row['object_key'],row['name']), 'name':row['name']}
|
return {'url':storage.download(row['object_key'],row['name']), 'name':row['name']}
|
||||||
|
|||||||
@@ -1,13 +1,18 @@
|
|||||||
"""Health, session bootstrap and freight quoting."""
|
"""Health, session bootstrap, freight quoting and the address of a CEP."""
|
||||||
import os
|
import os
|
||||||
|
import re
|
||||||
|
|
||||||
|
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 ..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.models import Freight
|
from ..core.pricing import manual_extra_cents
|
||||||
from ..runtime import ENVIRONMENT, GUEST_SESSION_LIMIT, PART_BYTES, freight, payment, storage
|
from ..core.models import FreightAsk, FreightEstimate
|
||||||
|
from ..runtime import (ENVIRONMENT, GUEST_SESSION_LIMIT, PART_BYTES, delivery_services, freight, payment,
|
||||||
|
require_delivery_available, storage)
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
|
|
||||||
@@ -35,12 +40,51 @@ def session(request: Request, response: Response):
|
|||||||
session_id = new_session(c, response)
|
session_id = new_session(c, response)
|
||||||
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(),
|
||||||
|
# Per metre on a finished sheet someone opens by hand (app/core/pricing.py).
|
||||||
|
'manual_extra_cents': manual_extra_cents(),
|
||||||
# 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.
|
||||||
|
'freight_services': delivery_services()}
|
||||||
|
|
||||||
@router.post('/api/freight')
|
@router.post('/api/freight')
|
||||||
def quote_freight(body: Freight):
|
def quote_freight(body: FreightEstimate):
|
||||||
|
require_delivery_available(body.service)
|
||||||
try:
|
try:
|
||||||
return freight.quote(body.service, body.postal_code)
|
return freight.quote(body.service, body.postal_code, body.metres, body.declared_cents)
|
||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
raise HTTPException(422, str(exc))
|
raise HTTPException(422, str(exc))
|
||||||
|
|
||||||
|
@router.post('/api/freight/options')
|
||||||
|
def freight_options(body: FreightAsk, request: Request):
|
||||||
|
"""Every delivery option for the cart, cheapest first. Each asks a carrier,
|
||||||
|
so a source asking too often is held back."""
|
||||||
|
rate_limit('freight-options', client_ip(request), 120, 900)
|
||||||
|
if not delivery_services():
|
||||||
|
raise HTTPException(503, 'A entrega ainda não está disponível. Escolha a retirada em Franca.')
|
||||||
|
found = freight.options(body.postal_code, body.metres, body.declared_cents)
|
||||||
|
if not found['options']:
|
||||||
|
reasons = '; '.join(item['error'] for item in found['unavailable'])
|
||||||
|
raise HTTPException(422, 'Não foi possível cotar a entrega para este CEP agora.' + (f' ({reasons})' if reasons else ''))
|
||||||
|
return found
|
||||||
|
|
||||||
|
# The address of a CEP, so the cart fills it in. Looked up here rather than in
|
||||||
|
# the browser, which keeps the Site's CSP to its own origin.
|
||||||
|
VIACEP = 'https://viacep.com.br/ws/{}/json/'
|
||||||
|
CEP_LIMIT = 120
|
||||||
|
|
||||||
|
@router.get('/api/cep/{cep}')
|
||||||
|
def cep_address(cep: str, request: Request):
|
||||||
|
if not re.fullmatch(r'[0-9]{8}', cep):
|
||||||
|
raise HTTPException(422, 'CEP must have eight digits')
|
||||||
|
rate_limit('cep-lookup', client_ip(request), CEP_LIMIT, 900)
|
||||||
|
try:
|
||||||
|
response = httpx.get(VIACEP.format(cep), timeout=5)
|
||||||
|
data = response.json() if response.status_code == 200 else {}
|
||||||
|
except (httpx.HTTPError, ValueError):
|
||||||
|
raise HTTPException(503, 'Consulta de CEP indisponível')
|
||||||
|
if not data or data.get('erro'):
|
||||||
|
raise HTTPException(404, 'CEP não encontrado')
|
||||||
|
return {'street': data.get('logradouro') or '', 'district': data.get('bairro') or '',
|
||||||
|
'city': data.get('localidade') or '', 'state': data.get('uf') or ''}
|
||||||
|
|||||||
@@ -7,10 +7,11 @@ and an unverified delivery is recorded and refused rather than retried.
|
|||||||
"""
|
"""
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
||||||
|
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 payments
|
from .. import 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
|
||||||
@@ -21,6 +22,8 @@ router = APIRouter()
|
|||||||
# Generous: a provider legitimately retries, and a signature check is cheap.
|
# Generous: a provider legitimately retries, and a signature check is cheap.
|
||||||
# This exists so an unsigned flood cannot keep the database busy.
|
# This exists so an unsigned flood cannot keep the database busy.
|
||||||
WEBHOOK_LIMIT = 600
|
WEBHOOK_LIMIT = 600
|
||||||
|
# How long a card waiting for the bank's confirmation holds off a new attempt.
|
||||||
|
CHALLENGE_MINUTES = 10
|
||||||
|
|
||||||
|
|
||||||
@router.post('/api/payments/webhook')
|
@router.post('/api/payments/webhook')
|
||||||
@@ -30,9 +33,20 @@ async def webhook(request: Request):
|
|||||||
|
|
||||||
query = dict(request.query_params)
|
query = dict(request.query_params)
|
||||||
if not payment.verify(request.headers, body, query):
|
if not payment.verify(request.headers, body, query):
|
||||||
audit('payment_webhook_rejected', ip=client_ip(request), reason='signature')
|
# What arrived, never what it carried: which query parameters (Mercado
|
||||||
|
# Pago's current webhook sends data.id/type, its old IPN topic/id and
|
||||||
|
# often no signature), whether the signature and request id headers came,
|
||||||
|
# and how old the signature's timestamp is.
|
||||||
|
audit('payment_webhook_rejected', ip=client_ip(request), reason='signature',
|
||||||
|
params=','.join(sorted(query))[:200], source=query.get('source_news', '')[:20],
|
||||||
|
signed='x-signature' in request.headers, request_id='x-request-id' in request.headers,
|
||||||
|
age=signature_age(request.headers.get('x-signature', '')))
|
||||||
raise HTTPException(403, 'Invalid signature')
|
raise HTTPException(403, 'Invalid signature')
|
||||||
|
|
||||||
|
if getattr(payment, 'last_signature', 'documentado') not in (None, 'documentado') or getattr(payment, 'secret_was_trimmed', False):
|
||||||
|
# Genuine, but not quite as documented: say how, so it can be settled.
|
||||||
|
audit('payment_webhook_signature', variant=payment.last_signature,
|
||||||
|
secret_trimmed=getattr(payment, 'secret_was_trimmed', False))
|
||||||
event = payment.parse(body, query)
|
event = payment.parse(body, query)
|
||||||
if event is None:
|
if event is None:
|
||||||
# Verified, so genuinely from the provider, but not about a payment.
|
# Verified, so genuinely from the provider, but not about a payment.
|
||||||
@@ -58,6 +72,25 @@ def event_provider():
|
|||||||
return payment.name
|
return payment.name
|
||||||
|
|
||||||
|
|
||||||
|
def signature_age(signature):
|
||||||
|
"""Seconds since the signature's ts (ts=<unix>,v1=<hex>), or '' without one."""
|
||||||
|
import time
|
||||||
|
parts = dict(part.strip().split('=', 1) for part in signature.split(',') if '=' in part)
|
||||||
|
ts = parts.get('ts', '')
|
||||||
|
return int(time.time() - int(ts[:10])) if ts[:10].isdigit() else ''
|
||||||
|
|
||||||
|
|
||||||
|
def provider_reason(response):
|
||||||
|
"""A short, loggable reason from a refused provider call."""
|
||||||
|
try:
|
||||||
|
data = response.json()
|
||||||
|
except ValueError:
|
||||||
|
return f'HTTP {response.status_code}'
|
||||||
|
causes = '; '.join(f"{c.get('code')}: {c.get('description')}" for c in data.get('cause') or []
|
||||||
|
if isinstance(c, dict))
|
||||||
|
return (causes or data.get('message') or data.get('error') or f'HTTP {response.status_code}')[:300]
|
||||||
|
|
||||||
|
|
||||||
@router.post('/api/payments/intent')
|
@router.post('/api/payments/intent')
|
||||||
def intent(body: PaymentIntent, session_id=Depends(owner)):
|
def intent(body: PaymentIntent, session_id=Depends(owner)):
|
||||||
"""Start paying an approved quote: a PIX code, or a card token from the
|
"""Start paying an approved quote: a PIX code, or a card token from the
|
||||||
@@ -68,27 +101,71 @@ def intent(body: PaymentIntent, session_id=Depends(owner)):
|
|||||||
try:
|
try:
|
||||||
quote = payments.approved_quote(c, body.quote_id, session_id)
|
quote = payments.approved_quote(c, body.quote_id, session_id)
|
||||||
except payments.PaymentRefused as refusal:
|
except payments.PaymentRefused as refusal:
|
||||||
raise HTTPException(404 if 'not found' in str(refusal) else 409, str(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, 'Quote is already paid')
|
raise HTTPException(409, 'Este pedido já foi pago.')
|
||||||
|
# Never charge for files that are gone: an unpaid cart's files are
|
||||||
|
# removed after a while. A payment under way keeps them a day longer,
|
||||||
|
# time enough for the provider's notice to become the order.
|
||||||
|
uploads = payments.quote_uploads(quote['approved'])
|
||||||
|
live = c.execute('''SELECT count(*) AS n FROM dtf_local.uploads WHERE id=ANY(%s)
|
||||||
|
AND purged_at IS NULL AND expires_at>now()''', (uploads,)).fetchone()['n']
|
||||||
|
if live != len(set(uploads)):
|
||||||
|
raise HTTPException(410, 'Os arquivos deste pedido expiraram porque ele não foi pago a tempo. '
|
||||||
|
'Monte o pedido de novo para pagar.')
|
||||||
|
payments.hold_uploads(c, uploads, '1 day')
|
||||||
# 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
|
||||||
|
# for CHALLENGE_MINUTES: a customer who gave up on it must still be able
|
||||||
|
# to pay, and an unanswered challenge is not charged.
|
||||||
if c.execute('''SELECT 1 FROM dtf_local.payment_intents WHERE quote_id=%s
|
if c.execute('''SELECT 1 FROM dtf_local.payment_intents WHERE quote_id=%s
|
||||||
AND (status='approved' OR (method='card' AND status='pending'))''', (body.quote_id,)).fetchone():
|
AND (status='approved' OR (method='card' AND status='pending'
|
||||||
raise HTTPException(409, 'A payment for this quote is already approved or in review')
|
AND NOT (jsonb_typeof(response->'challenge')='object'
|
||||||
|
AND created_at < now() - make_interval(mins => %s))))''',
|
||||||
|
(body.quote_id, CHALLENGE_MINUTES)).fetchone():
|
||||||
|
raise HTTPException(409, 'Já existe um pagamento aprovado ou em análise para este pedido. '
|
||||||
|
'Aguarde a confirmação nesta página.')
|
||||||
|
method = body.method.model_dump()
|
||||||
if body.method.type == 'pix':
|
if body.method.type == 'pix':
|
||||||
existing = c.execute('''SELECT * FROM dtf_local.payment_intents WHERE quote_id=%s AND method='pix'
|
# One open PIX per quote: the same code until it expires, and a new
|
||||||
|
# one only after that, when the old code can no longer be paid.
|
||||||
|
# Serialised per quote, so two clicks never open two codes.
|
||||||
|
c.execute('SELECT pg_advisory_xact_lock(hashtext(%s))', ('pix:'+str(body.quote_id),))
|
||||||
|
existing = c.execute('''SELECT *, COALESCE((response->>'expires_at')::timestamptz <= now(), false) AS expired
|
||||||
|
FROM dtf_local.payment_intents WHERE quote_id=%s AND method='pix'
|
||||||
AND status='pending' ORDER BY created_at DESC LIMIT 1''', (body.quote_id,)).fetchone()
|
AND status='pending' ORDER BY created_at DESC LIMIT 1''', (body.quote_id,)).fetchone()
|
||||||
if existing:
|
if existing and not existing['expired']:
|
||||||
return existing['response']
|
return existing['response']
|
||||||
|
if existing:
|
||||||
|
c.execute("UPDATE dtf_local.payment_intents SET status='expired', updated_at=now() WHERE id=%s",
|
||||||
|
(existing['id'],))
|
||||||
|
method['attempt'] = c.execute('''SELECT count(*) AS n FROM dtf_local.payment_intents
|
||||||
|
WHERE quote_id=%s AND method='pix' ''', (body.quote_id,)).fetchone()['n'] + 1
|
||||||
try:
|
try:
|
||||||
created = payment.create(str(body.quote_id), quote['approved']['total_cents'],
|
created = payment.create(str(body.quote_id), quote['approved']['total_cents'],
|
||||||
quote['approved']['customer'], body.method.model_dump())
|
quote['approved']['customer'], method)
|
||||||
except ValueError as exc:
|
except ValueError:
|
||||||
raise HTTPException(422, str(exc))
|
raise HTTPException(422, 'Esta forma de pagamento não é aceita. Pague com cartão de crédito ou PIX.')
|
||||||
except Exception:
|
except httpx.HTTPStatusError as exc:
|
||||||
audit('payment_intent_failed', quote=str(body.quote_id))
|
# Mercado Pago's own reason (status, message and cause codes) goes to
|
||||||
raise HTTPException(502, 'Payment provider unavailable; try again')
|
# the log; it never contains card data, only what was refused.
|
||||||
|
reason = provider_reason(exc.response)
|
||||||
|
audit('payment_intent_refused', quote=str(body.quote_id), method=body.method.type,
|
||||||
|
status=exc.response.status_code, reason=reason)
|
||||||
|
if exc.response.status_code < 500:
|
||||||
|
try:
|
||||||
|
data = exc.response.json()
|
||||||
|
except ValueError:
|
||||||
|
data = {}
|
||||||
|
raise HTTPException(422, messages.refusal(data))
|
||||||
|
raise HTTPException(502, messages.UNAVAILABLE)
|
||||||
|
except Exception as exc:
|
||||||
|
audit('payment_intent_failed', quote=str(body.quote_id), error=type(exc).__name__)
|
||||||
|
raise HTTPException(502, messages.UNAVAILABLE)
|
||||||
|
if created.get('status') == 'rejected':
|
||||||
|
# What to tell the customer; the code stays in status_detail for the team.
|
||||||
|
created['message'] = messages.rejection(created.get('status_detail'))
|
||||||
c.execute('''INSERT INTO dtf_local.payment_intents(id,quote_id,provider,provider_payment_id,method,
|
c.execute('''INSERT INTO dtf_local.payment_intents(id,quote_id,provider,provider_payment_id,method,
|
||||||
status,amount_cents,response) VALUES(%s,%s,%s,%s,%s,%s,%s,%s)
|
status,amount_cents,response) VALUES(%s,%s,%s,%s,%s,%s,%s,%s)
|
||||||
ON CONFLICT(provider,provider_payment_id) DO NOTHING''',
|
ON CONFLICT(provider,provider_payment_id) DO NOTHING''',
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
"""Quotes: the customer's cart, and the operator-reviewed version of it."""
|
"""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 decimal import Decimal
|
from decimal import Decimal
|
||||||
@@ -7,10 +7,14 @@ 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 ..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 ..runtime import freight, quote_view, upload_row
|
from ..core.pricing import price
|
||||||
|
from .. import quote_review
|
||||||
|
from ..grade_check import Files, mismatch
|
||||||
|
from ..runtime import freight, payment, quote_view, require_delivery_available, storage, upload_row
|
||||||
from ..scanning import require_clean
|
from ..scanning import require_clean
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
@@ -19,32 +23,58 @@ router = APIRouter()
|
|||||||
def create_quote(body: QuoteRequest, session_id=Depends(owner)):
|
def create_quote(body: QuoteRequest, session_id=Depends(owner)):
|
||||||
for item in body.items:
|
for item in body.items:
|
||||||
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, 'Quoted metres do not match the submitted layout height')
|
raise HTTPException(422, 'A metragem não confere com a montagem enviada. Monte o pedido de novo.')
|
||||||
|
require_delivery_available(body.freight.service)
|
||||||
draft = body.model_dump(mode='json', exclude={'request_key'})
|
draft = body.model_dump(mode='json', exclude={'request_key'})
|
||||||
digest = hashlib.sha256(json.dumps(draft, sort_keys=True).encode()).hexdigest()
|
digest = hashlib.sha256(json.dumps(draft, sort_keys=True).encode()).hexdigest()
|
||||||
|
reason = quote_review.review_reason(draft)
|
||||||
|
if reason is not None:
|
||||||
|
# Waits for review: check the delivery now, priced at approval.
|
||||||
try:
|
try:
|
||||||
freight.quote(body.freight.service, body.freight.postal_code)
|
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:
|
except ValueError as exc:
|
||||||
raise HTTPException(422, str(exc))
|
raise HTTPException(422, str(exc))
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
|
rows = {}
|
||||||
for item in body.items:
|
for item in body.items:
|
||||||
for uid in item.uploads:
|
for uid in item.uploads:
|
||||||
row = upload_row(c, uid, session_id)
|
row = upload_row(c, uid, session_id)
|
||||||
if not row['complete']:
|
if not row['complete']:
|
||||||
raise HTTPException(409, 'Complete every upload before requesting a quote')
|
raise HTTPException(409, 'Espere o envio de todos os arquivos terminar antes de continuar.')
|
||||||
require_clean(row)
|
require_clean(row)
|
||||||
|
rows[str(uid)] = row
|
||||||
|
# The grade sets the price and came from the browser: before a cart is
|
||||||
|
# approved at checkout, the server works it out from the files.
|
||||||
|
note = mismatch(Files(storage), draft['items'], rows) if reason is None else None
|
||||||
|
reason = reason or note
|
||||||
uid = uuid4()
|
uid = uuid4()
|
||||||
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',
|
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',
|
||||||
(uid, session_id, body.request_key, digest, Jsonb(draft)))
|
(uid, session_id, body.request_key, digest, Jsonb(draft), note))
|
||||||
row = c.execute('SELECT * FROM dtf_local.quotes WHERE owner=%s AND request_key=%s', (session_id, body.request_key)).fetchone()
|
row = c.execute('SELECT * FROM dtf_local.quotes WHERE owner=%s AND request_key=%s FOR UPDATE', (session_id, body.request_key)).fetchone()
|
||||||
if row['request_hash'] != digest:
|
if row['request_hash'] != digest:
|
||||||
raise HTTPException(409, 'Request key already used for a different cart')
|
raise HTTPException(409, 'O carrinho mudou durante o envio. Tente de novo.')
|
||||||
return {'id': row['id'], 'status': 'pending_review'}
|
if row['id'] == uid and reason is None:
|
||||||
|
quote_review.approve(c, row, body.items, quote_review.AUTO)
|
||||||
|
return {'id': row['id'], 'status': 'approved'}
|
||||||
|
if row['id'] == uid:
|
||||||
|
# An operator reviews it first; the files wait for that review.
|
||||||
|
payments.hold_uploads(c, payments.quote_uploads(draft), payments.REVIEW_HOLD)
|
||||||
|
return {'id': row['id'], 'status': 'approved' if row['approved'] else 'pending_review'}
|
||||||
|
|
||||||
@router.get('/api/quotes/{uid}')
|
@router.get('/api/quotes/{uid}')
|
||||||
def get_quote(uid: UUID, session_id=Depends(owner)):
|
def get_quote(uid: UUID, session_id=Depends(owner)):
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
row = c.execute('SELECT * FROM dtf_local.quotes WHERE id=%s AND owner=%s', (uid,session_id)).fetchone()
|
row = c.execute('SELECT * FROM dtf_local.quotes WHERE id=%s AND owner=%s', (uid,session_id)).fetchone()
|
||||||
if not row:
|
if not row:
|
||||||
raise HTTPException(404, 'Quote not found')
|
raise HTTPException(404, 'Pedido não encontrado.')
|
||||||
return quote_view(c, row)
|
view = quote_view(c, row)
|
||||||
|
# The payment page asks every few seconds while it waits for the order. An
|
||||||
|
# approved card with no order yet is checked with the provider now, rather
|
||||||
|
# than waiting for its notification.
|
||||||
|
if view['status'] == 'approved' and (view['payment'] or {}).get('status') == 'approved':
|
||||||
|
if payments.reconcile(db.connect, payment, quote_id=uid, limit=3):
|
||||||
|
with db.connect() as c:
|
||||||
|
view = quote_view(c, c.execute('SELECT * FROM dtf_local.quotes WHERE id=%s', (uid,)).fetchone())
|
||||||
|
return view
|
||||||
|
|||||||
@@ -8,12 +8,14 @@ import os
|
|||||||
from uuid import UUID, uuid4
|
from uuid import UUID, uuid4
|
||||||
|
|
||||||
from botocore.exceptions import ClientError
|
from botocore.exceptions import ClientError
|
||||||
from fastapi import APIRouter, Depends, HTTPException
|
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||||
|
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, 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 ..runtime import PART_BYTES, storage, upload_row
|
from ..runtime import PART_BYTES, storage, upload_row
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
@@ -21,7 +23,7 @@ router = APIRouter()
|
|||||||
@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)):
|
||||||
if body.size > upload_limit_bytes():
|
if body.size > upload_limit_bytes():
|
||||||
raise HTTPException(413, 'File exceeds the malware scan limit; select a smaller file')
|
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), 60, 900)
|
||||||
@@ -37,7 +39,7 @@ def begin_upload(body: UploadStart, session_id=Depends(owner)):
|
|||||||
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')) or
|
||||||
usage['pending'] >= int(os.environ.get('MAX_PENDING_UPLOADS','10'))):
|
usage['pending'] >= int(os.environ.get('MAX_PENDING_UPLOADS','10'))):
|
||||||
audit('upload_quota_rejected')
|
audit('upload_quota_rejected')
|
||||||
raise HTTPException(429, 'Local storage quota or pending upload limit reached')
|
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,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,now()+interval '1 hour')''',
|
||||||
@@ -58,7 +60,10 @@ def part_url(uid: UUID, part: int, session_id=Depends(owner)):
|
|||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
row = upload_row(c, uid, session_id)
|
row = upload_row(c, uid, session_id)
|
||||||
if row['complete'] or not 1 <= part <= math.ceil(row['size'] / PART_BYTES):
|
if row['complete'] or not 1 <= part <= math.ceil(row['size'] / PART_BYTES):
|
||||||
raise HTTPException(409, 'Invalid part or completed upload')
|
raise HTTPException(409, 'O envio deste arquivo já terminou ou foi interrompido. Escolha o arquivo de novo.')
|
||||||
|
# The reservation lease is an hour; a multi-GB upload on a slow line
|
||||||
|
# takes longer, so each part it asks for keeps it alive.
|
||||||
|
c.execute("UPDATE dtf_local.uploads SET expires_at=GREATEST(expires_at,now()+interval '1 hour') WHERE id=%s", (uid,))
|
||||||
size = min(PART_BYTES, row['size']-(part-1)*PART_BYTES)
|
size = min(PART_BYTES, row['size']-(part-1)*PART_BYTES)
|
||||||
return {'url': storage.part_url(row['object_key'], row['multipart_id'], part, size)}
|
return {'url': storage.part_url(row['object_key'], row['multipart_id'], part, size)}
|
||||||
|
|
||||||
@@ -79,21 +84,59 @@ def complete_upload(uid: UUID, session_id=Depends(owner)):
|
|||||||
expected = math.ceil(row['size'] / PART_BYTES)
|
expected = math.ceil(row['size'] / PART_BYTES)
|
||||||
if [p['PartNumber'] for p in parts] != list(range(1, expected+1)) or any(
|
if [p['PartNumber'] for p in parts] != list(range(1, expected+1)) or any(
|
||||||
p['Size'] != min(PART_BYTES, row['size'] - i*PART_BYTES) for i,p in enumerate(parts)):
|
p['Size'] != min(PART_BYTES, row['size'] - i*PART_BYTES) for i,p in enumerate(parts)):
|
||||||
raise HTTPException(409, 'Parts are missing or their sizes do not match')
|
raise HTTPException(409, 'O envio do arquivo não chegou inteiro. Escolha o arquivo de novo.')
|
||||||
storage.complete(row['object_key'], row['multipart_id'], parts)
|
storage.complete(row['object_key'], row['multipart_id'], parts)
|
||||||
existing_size = storage.size(row['object_key'])
|
existing_size = storage.size(row['object_key'])
|
||||||
if existing_size != row['size']:
|
if existing_size != row['size']:
|
||||||
raise HTTPException(409, 'Stored size differs from declared size')
|
raise HTTPException(409, 'O envio do arquivo não chegou inteiro. Escolha o arquivo de novo.')
|
||||||
c.execute("UPDATE dtf_local.uploads SET complete=true,expires_at=now()+interval '30 days' WHERE id=%s", (uid,))
|
# Held while the cart is unpaid: an abandoned cart's files go after
|
||||||
|
# UNPAID_HOLD; a paid order keeps them for its 30 days (app/payments.py).
|
||||||
|
c.execute('UPDATE dtf_local.uploads SET complete=true,expires_at=now()+%s::interval WHERE id=%s',
|
||||||
|
(UNPAID_HOLD, uid))
|
||||||
return {'id': uid, 'complete': True}
|
return {'id': uid, 'complete': True}
|
||||||
|
|
||||||
|
# The browser's small picture of the artwork, for the Kanban. Only an image, and
|
||||||
|
# only a small one: the type is read from the bytes, never from the header.
|
||||||
|
THUMBNAIL_BYTES = 300_000
|
||||||
|
|
||||||
|
def thumbnail_type(data):
|
||||||
|
if data[:4] == b'RIFF' and data[8:12] == b'WEBP':
|
||||||
|
return 'image/webp'
|
||||||
|
if data[:3] == b'\xff\xd8\xff':
|
||||||
|
return 'image/jpeg'
|
||||||
|
if data[:8] == b'\x89PNG\r\n\x1a\n':
|
||||||
|
return 'image/png'
|
||||||
|
return None
|
||||||
|
|
||||||
|
def store_thumbnail(uid, session_id, mime, data):
|
||||||
|
rate_limit('upload-thumbnail', str(session_id), 120, 900)
|
||||||
|
with db.connect() as c:
|
||||||
|
upload_row(c, uid, session_id)
|
||||||
|
c.execute('''INSERT INTO dtf_local.upload_thumbnails(upload_id,mime,data) VALUES(%s,%s,%s)
|
||||||
|
ON CONFLICT(upload_id) DO UPDATE SET mime=EXCLUDED.mime, data=EXCLUDED.data, created_at=now()''',
|
||||||
|
(uid, mime, data))
|
||||||
|
|
||||||
|
@router.put('/api/uploads/{uid}/thumbnail')
|
||||||
|
async def put_thumbnail(uid: UUID, request: Request, session_id=Depends(owner)):
|
||||||
|
if int(request.headers.get('content-length') or 0) > THUMBNAIL_BYTES:
|
||||||
|
raise HTTPException(413, 'Thumbnail too large')
|
||||||
|
data = await request.body()
|
||||||
|
if len(data) > THUMBNAIL_BYTES:
|
||||||
|
raise HTTPException(413, 'Thumbnail too large')
|
||||||
|
mime = thumbnail_type(data)
|
||||||
|
if not mime:
|
||||||
|
raise HTTPException(415, 'Thumbnail must be a WebP, JPEG or PNG image')
|
||||||
|
await run_in_threadpool(store_thumbnail, uid, session_id, mime, data)
|
||||||
|
return {'id': uid}
|
||||||
|
|
||||||
@router.delete('/api/uploads/{uid}')
|
@router.delete('/api/uploads/{uid}')
|
||||||
def cancel_upload(uid: UUID, session_id=Depends(owner)):
|
def cancel_upload(uid: UUID, session_id=Depends(owner)):
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
row=upload_row(c,uid,session_id,lock=True)
|
row=upload_row(c,uid,session_id,lock=True)
|
||||||
if row['complete']:
|
if row['complete']:
|
||||||
raise HTTPException(409, 'Completed upload cannot be cancelled')
|
raise HTTPException(409, 'Este arquivo já foi enviado e não pode ser cancelado.')
|
||||||
storage.discard(row['object_key'],row['multipart_id'],False)
|
storage.discard(row['object_key'],row['multipart_id'],False)
|
||||||
c.execute('UPDATE dtf_local.uploads SET purged_at=now() WHERE id=%s',(uid,))
|
c.execute('UPDATE dtf_local.uploads SET purged_at=now() WHERE id=%s',(uid,))
|
||||||
|
c.execute('DELETE FROM dtf_local.upload_thumbnails WHERE upload_id=%s',(uid,))
|
||||||
audit('upload_cancelled', upload=str(uid))
|
audit('upload_cancelled', upload=str(uid))
|
||||||
return {'id':uid,'cancelled':True}
|
return {'id':uid,'cancelled':True}
|
||||||
|
|||||||
240
app/api/users.py
Normal file
@@ -0,0 +1,240 @@
|
|||||||
|
"""Kanban users and print machines, managed by the administrators.
|
||||||
|
|
||||||
|
An administrator creates each account with a first password and the person
|
||||||
|
changes it in "Minha senha". The superadmin is the system's own account, set from the console (python -m app.operators);
|
||||||
|
administrators manage everyone else. Nobody can remove, disable or demote
|
||||||
|
themselves, so the last administrator cannot lock the team out by accident.
|
||||||
|
"""
|
||||||
|
import re
|
||||||
|
from decimal import Decimal
|
||||||
|
from typing import Literal
|
||||||
|
from uuid import UUID, uuid4
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||||
|
from pydantic import Field, field_validator
|
||||||
|
|
||||||
|
from .. import machines, mail
|
||||||
|
from ..core import db
|
||||||
|
from ..core.auth import CAPABILITIES, audit, can, password_hash, password_matches, signed_in
|
||||||
|
from ..core.models import StrictModel
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
class UserIn(StrictModel):
|
||||||
|
# The profiles an administrator may give; superadmin only comes from the console.
|
||||||
|
name: str = Field(min_length=1, max_length=80)
|
||||||
|
email: str = Field(min_length=3, max_length=254)
|
||||||
|
role: Literal['admin', 'gestao', 'designer', 'operador', 'vendedor']
|
||||||
|
password: str | None = Field(default=None, min_length=8, max_length=128)
|
||||||
|
active: bool = True
|
||||||
|
machines: list[UUID] = Field(default_factory=list, max_length=50)
|
||||||
|
|
||||||
|
@field_validator('email')
|
||||||
|
@classmethod
|
||||||
|
def email_valid(cls, value):
|
||||||
|
value = value.strip().lower()
|
||||||
|
if not re.fullmatch(r'[^\s@]+@[^\s@]+\.[a-zA-Z]{2,}', value):
|
||||||
|
raise ValueError('Informe um e-mail válido.')
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
class MachineIn(StrictModel):
|
||||||
|
name: str = Field(min_length=1, max_length=60)
|
||||||
|
products: list[Literal['textil', 'uv']] = Field(default_factory=list, max_length=2)
|
||||||
|
active: bool = True
|
||||||
|
# Metres open before the next order goes to another machine; None is no limit.
|
||||||
|
limit_metres: Decimal | None = Field(default=None, gt=0, le=99999, decimal_places=1)
|
||||||
|
# The operators who work on it; None leaves them as they are.
|
||||||
|
operators: list[UUID] | None = Field(default=None, max_length=200)
|
||||||
|
|
||||||
|
|
||||||
|
class PasswordChange(StrictModel):
|
||||||
|
current: str = Field(min_length=1, max_length=128)
|
||||||
|
new: str = Field(min_length=8, max_length=128)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get('/api/operator/me')
|
||||||
|
def me(request: Request):
|
||||||
|
"""Who is signed in, and what the Kanban should offer them."""
|
||||||
|
account = signed_in(request)
|
||||||
|
return {'email': account['email'], 'name': account['name'], 'role': account['role'],
|
||||||
|
'machines': account['machines'],
|
||||||
|
'can': sorted(cap for cap, roles in CAPABILITIES.items() if account['role'] in roles)}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/me/password')
|
||||||
|
def change_password(body: PasswordChange, request: Request):
|
||||||
|
account = signed_in(request)
|
||||||
|
with db.connect() as c:
|
||||||
|
row = c.execute('SELECT password_hash FROM dtf_local.operators WHERE id=%s', (account['id'],)).fetchone()
|
||||||
|
if not password_matches(body.current, row['password_hash']):
|
||||||
|
raise HTTPException(403, 'A senha atual não confere.')
|
||||||
|
c.execute('UPDATE dtf_local.operators SET password_hash=%s WHERE id=%s', (password_hash(body.new), account['id']))
|
||||||
|
audit('operator_password_changed', operator=account['email'])
|
||||||
|
return {'ok': True}
|
||||||
|
|
||||||
|
|
||||||
|
def user_rows(c):
|
||||||
|
rows = c.execute('''SELECT o.id,o.email,o.name,o.role,o.active,o.last_login_at,o.created_at,
|
||||||
|
COALESCE(array_agg(m.machine_id) FILTER (WHERE m.machine_id IS NOT NULL), '{}') AS machines
|
||||||
|
FROM dtf_local.operators o LEFT JOIN dtf_local.operator_machines m ON m.operator_id=o.id
|
||||||
|
GROUP BY o.id ORDER BY o.active DESC, o.name, o.email''').fetchall()
|
||||||
|
for row in rows:
|
||||||
|
row['machines'] = [str(m) for m in row['machines']]
|
||||||
|
return rows
|
||||||
|
|
||||||
|
|
||||||
|
@router.get('/api/operator/users')
|
||||||
|
def list_users(user=Depends(can('users'))):
|
||||||
|
with db.connect() as c:
|
||||||
|
return {'users': user_rows(c), 'machines': machines.rows(c, with_operators=True)}
|
||||||
|
|
||||||
|
|
||||||
|
def target(c, uid, request):
|
||||||
|
"""The account to change, refusing a superadmin unless one is asking."""
|
||||||
|
row = c.execute('SELECT * FROM dtf_local.operators WHERE id=%s FOR UPDATE', (uid,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(404, 'Usuário não encontrado.')
|
||||||
|
if row['role'] == 'superadmin' and request.state.operator['role'] != 'superadmin':
|
||||||
|
raise HTTPException(403, 'Só o superadmin altera esta conta.')
|
||||||
|
return row
|
||||||
|
|
||||||
|
|
||||||
|
def set_machines(c, uid, chosen, role):
|
||||||
|
"""An operator's machines. Only operators have them: they limit what an
|
||||||
|
operator sees, and every other profile sees every order."""
|
||||||
|
if role != 'operador':
|
||||||
|
chosen = []
|
||||||
|
known = {str(r['id']) for r in c.execute('SELECT id FROM dtf_local.machines WHERE id=ANY(%s)',
|
||||||
|
([str(m) for m in chosen],)).fetchall()}
|
||||||
|
if len(known) != len(set(map(str, chosen))):
|
||||||
|
raise HTTPException(422, 'Uma das máquinas escolhidas não existe mais.')
|
||||||
|
c.execute('DELETE FROM dtf_local.operator_machines WHERE operator_id=%s', (uid,))
|
||||||
|
for machine in known:
|
||||||
|
c.execute('INSERT INTO dtf_local.operator_machines(operator_id,machine_id) VALUES(%s,%s)', (uid, machine))
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/users')
|
||||||
|
def create_user(body: UserIn, request: Request, user=Depends(can('users'))):
|
||||||
|
if not body.password:
|
||||||
|
raise HTTPException(422, 'Defina uma senha inicial com 8 caracteres ou mais.')
|
||||||
|
uid = uuid4()
|
||||||
|
with db.connect() as c:
|
||||||
|
if c.execute('SELECT 1 FROM dtf_local.operators WHERE email=%s', (body.email,)).fetchone():
|
||||||
|
raise HTTPException(409, 'Já existe um usuário com este e-mail.')
|
||||||
|
c.execute('''INSERT INTO dtf_local.operators(id,email,name,password_hash,role,active)
|
||||||
|
VALUES(%s,%s,%s,%s,%s,%s)''', (uid, body.email, body.name.strip(), password_hash(body.password),
|
||||||
|
body.role, body.active))
|
||||||
|
set_machines(c, uid, body.machines, body.role)
|
||||||
|
audit('operator_created', operator=user, account=body.email, role=body.role)
|
||||||
|
return {'id': str(uid)}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/users/{uid}')
|
||||||
|
def update_user(uid: UUID, body: UserIn, request: Request, user=Depends(can('users'))):
|
||||||
|
me_ = request.state.operator
|
||||||
|
with db.connect() as c:
|
||||||
|
row = target(c, uid, request)
|
||||||
|
# A superadmin keeps that profile: the form offers only the assignable ones.
|
||||||
|
role = row['role'] if row['role'] == 'superadmin' else body.role
|
||||||
|
if str(row['id']) == str(me_['id']) and (not body.active or role != row['role']):
|
||||||
|
raise HTTPException(409, 'Você não pode desativar a sua conta nem mudar o seu perfil.')
|
||||||
|
if body.email != row['email'] and c.execute(
|
||||||
|
'SELECT 1 FROM dtf_local.operators WHERE email=%s AND id<>%s', (body.email, uid)).fetchone():
|
||||||
|
raise HTTPException(409, 'Já existe um usuário com este e-mail.')
|
||||||
|
c.execute('UPDATE dtf_local.operators SET name=%s,email=%s,role=%s,active=%s WHERE id=%s',
|
||||||
|
(body.name.strip(), body.email, role, body.active, uid))
|
||||||
|
if body.password:
|
||||||
|
c.execute('UPDATE dtf_local.operators SET password_hash=%s WHERE id=%s', (password_hash(body.password), uid))
|
||||||
|
if body.email != row['email']:
|
||||||
|
c.execute('UPDATE dtf_local.operator_sessions SET username=%s WHERE username=%s', (body.email, row['email']))
|
||||||
|
if not body.active or body.password:
|
||||||
|
# Disabled, or given a new password: whoever was signed in signs in again.
|
||||||
|
c.execute('DELETE FROM dtf_local.operator_sessions WHERE username=%s', (body.email,))
|
||||||
|
set_machines(c, uid, body.machines, role)
|
||||||
|
audit('operator_updated', operator=user, account=body.email, role=role, active=body.active,
|
||||||
|
password_reset=bool(body.password))
|
||||||
|
return {'ok': True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/users/{uid}/delete')
|
||||||
|
def delete_user(uid: UUID, request: Request, user=Depends(can('users'))):
|
||||||
|
with db.connect() as c:
|
||||||
|
row = target(c, uid, request)
|
||||||
|
if str(row['id']) == str(request.state.operator['id']):
|
||||||
|
raise HTTPException(409, 'Você não pode excluir a sua própria conta.')
|
||||||
|
c.execute('DELETE FROM dtf_local.operator_sessions WHERE username=%s', (row['email'],))
|
||||||
|
c.execute('DELETE FROM dtf_local.operators WHERE id=%s', (uid,))
|
||||||
|
# The movement history keeps the e-mail of whoever moved each card.
|
||||||
|
audit('operator_deleted', operator=user, account=row['email'])
|
||||||
|
return {'ok': True}
|
||||||
|
|
||||||
|
|
||||||
|
def set_operators(c, mid, operators):
|
||||||
|
"""The machine's operators, from its own form. Other profiles are ignored."""
|
||||||
|
if operators is None:
|
||||||
|
return
|
||||||
|
ids = [str(o) for o in operators]
|
||||||
|
c.execute('DELETE FROM dtf_local.operator_machines WHERE machine_id=%s', (mid,))
|
||||||
|
c.execute("""INSERT INTO dtf_local.operator_machines(operator_id,machine_id)
|
||||||
|
SELECT id,%s FROM dtf_local.operators WHERE id=ANY(%s::uuid[]) AND role='operador'""", (mid, ids))
|
||||||
|
|
||||||
|
|
||||||
|
@router.get('/api/operator/machines')
|
||||||
|
def list_machines(user=Depends(can('view'))):
|
||||||
|
with db.connect() as c:
|
||||||
|
return {'machines': machines.rows(c, with_operators=True)}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/machines')
|
||||||
|
def create_machine(body: MachineIn, user=Depends(can('users'))):
|
||||||
|
mid = uuid4()
|
||||||
|
with db.connect() as c:
|
||||||
|
if c.execute('SELECT 1 FROM dtf_local.machines WHERE lower(name)=lower(%s)', (body.name.strip(),)).fetchone():
|
||||||
|
raise HTTPException(409, 'Já existe uma máquina com este nome.')
|
||||||
|
c.execute('INSERT INTO dtf_local.machines(id,name,products,active,limit_metres) VALUES(%s,%s,%s,%s,%s)',
|
||||||
|
(mid, body.name.strip(), sorted(set(body.products)), body.active, body.limit_metres))
|
||||||
|
set_operators(c, mid, body.operators)
|
||||||
|
machines.route(c)
|
||||||
|
audit('machine_created', operator=user, machine=body.name)
|
||||||
|
return {'id': str(mid)}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/machines/{mid}')
|
||||||
|
def update_machine(mid: UUID, body: MachineIn, user=Depends(can('users'))):
|
||||||
|
with db.connect() as c:
|
||||||
|
if c.execute('SELECT 1 FROM dtf_local.machines WHERE lower(name)=lower(%s) AND id<>%s',
|
||||||
|
(body.name.strip(), mid)).fetchone():
|
||||||
|
raise HTTPException(409, 'Já existe uma máquina com este nome.')
|
||||||
|
if not c.execute('''UPDATE dtf_local.machines SET name=%s,products=%s,active=%s,limit_metres=%s
|
||||||
|
WHERE id=%s RETURNING id''', (body.name.strip(), sorted(set(body.products)), body.active,
|
||||||
|
body.limit_metres, mid)).fetchone():
|
||||||
|
raise HTTPException(404, 'Máquina não encontrada.')
|
||||||
|
set_operators(c, mid, body.operators)
|
||||||
|
machines.route(c)
|
||||||
|
audit('machine_updated', operator=user, machine=body.name)
|
||||||
|
return {'ok': True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/machines/{mid}/delete')
|
||||||
|
def delete_machine(mid: UUID, user=Depends(can('users'))):
|
||||||
|
"""Its orders go back to the automatic choice; its operators lose it."""
|
||||||
|
with db.connect() as c:
|
||||||
|
row = c.execute('DELETE FROM dtf_local.machines WHERE id=%s RETURNING name', (mid,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(404, 'Máquina não encontrada.')
|
||||||
|
machines.route(c)
|
||||||
|
audit('machine_deleted', operator=user, machine=row['name'])
|
||||||
|
return {'ok': True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/mail/test')
|
||||||
|
def test_mail(request: Request, user=Depends(can('integrations'))):
|
||||||
|
"""A message to whoever asked, to prove the mail server works."""
|
||||||
|
with db.connect() as c:
|
||||||
|
if not mail.queue(c, 'test', user, 'Teste de e-mail · Kanban DTF',
|
||||||
|
'Este é um teste do Kanban DTF. Se chegou, o envio de e-mails está funcionando: '
|
||||||
|
'os e-mails dos clientes.'):
|
||||||
|
raise HTTPException(409, 'O envio de e-mails não está configurado no servidor.')
|
||||||
|
audit('mail_test_queued', operator=user)
|
||||||
|
return {'ok': True, 'to': user}
|
||||||
@@ -13,7 +13,7 @@ from starlette.middleware.trustedhost import TrustedHostMiddleware
|
|||||||
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
|
from .api import artwork, customer, health, operator, orders, payments, quotes, uploads, users
|
||||||
|
|
||||||
|
|
||||||
@asynccontextmanager
|
@asynccontextmanager
|
||||||
@@ -37,12 +37,13 @@ async def safe_headers(request, call_next):
|
|||||||
response = await call_next(request)
|
response = await call_next(request)
|
||||||
if response.status_code in (401,403,429) or response.status_code>=500:
|
if response.status_code in (401,403,429) or response.status_code>=500:
|
||||||
audit('http_security_event', method=request.method, status=response.status_code, ip=client_ip(request))
|
audit('http_security_event', method=request.method, status=response.status_code, ip=client_ip(request))
|
||||||
response.headers['Cache-Control'] = 'no-store'
|
# Nothing is cached unless a route says so (the Kanban's artwork pictures).
|
||||||
|
response.headers.setdefault('Cache-Control', 'no-store')
|
||||||
response.headers['X-Content-Type-Options'] = 'nosniff'
|
response.headers['X-Content-Type-Options'] = 'nosniff'
|
||||||
response.headers['Referrer-Policy'] = 'no-referrer'
|
response.headers['Referrer-Policy'] = 'no-referrer'
|
||||||
return response
|
return response
|
||||||
|
|
||||||
|
|
||||||
# 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):
|
for module in (health, uploads, quotes, orders, payments, operator, customer, artwork, users):
|
||||||
app.include_router(module.router)
|
app.include_router(module.router)
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ from uuid import UUID, uuid4
|
|||||||
|
|
||||||
from fastapi import HTTPException
|
from fastapi import HTTPException
|
||||||
|
|
||||||
from .printjobs import generated_identity
|
|
||||||
from .runtime import upload_row
|
from .runtime import upload_row
|
||||||
from .scanning import require_clean
|
from .scanning import require_clean
|
||||||
|
|
||||||
@@ -26,38 +25,57 @@ def generated_owner(c, order, ref, kind):
|
|||||||
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:
|
||||||
raise HTTPException(422, 'A generated print file can only be the final file of its own item')
|
raise HTTPException(422, 'O arquivo gerado só pode ser o final do próprio item.')
|
||||||
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, 'A customer correction replaced the artwork this file was generated from')
|
raise HTTPException(409, 'O cliente enviou uma correção depois que este arquivo foi gerado. Use a correção ou envie outro arquivo.')
|
||||||
return generated_identity(order['id'])
|
# 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']
|
||||||
|
|
||||||
|
|
||||||
|
def correction_owner(c, order, ref, kind):
|
||||||
|
"""The owner of a customer correction approved as it is, or None if it is not one.
|
||||||
|
|
||||||
|
A corrected file is often ready to print: the operator approves it as the
|
||||||
|
final of the item it corrects, without downloading and sending it back.
|
||||||
|
"""
|
||||||
|
if kind != 'final':
|
||||||
|
return None
|
||||||
|
row = c.execute('''SELECT u.owner FROM dtf_local.order_files f JOIN dtf_local.uploads u ON u.id=f.upload_id
|
||||||
|
WHERE f.order_id=%s AND f.upload_id=%s AND f.kind='correction' AND f.active AND f.item_index=%s''',
|
||||||
|
(order['id'], ref.upload_id, ref.item_index)).fetchone()
|
||||||
|
return row and row['owner']
|
||||||
|
|
||||||
|
|
||||||
def submit_files(c, order, body, identity, kind, actor):
|
def submit_files(c, order, body, identity, kind, actor):
|
||||||
if order['version'] != body.version:
|
if order['version'] != body.version:
|
||||||
raise HTTPException(409, 'Order changed. Refresh before submitting files.')
|
raise HTTPException(409, 'O pedido mudou. Atualize a página e envie de novo.')
|
||||||
if kind == 'final' and order['state'] not in ('rec','tra','cor'):
|
if kind == 'final' and order['state'] not in ('rec','tra','cor'):
|
||||||
raise HTTPException(409, 'Final files can only change during artwork review')
|
raise HTTPException(409, 'O arquivo final só pode mudar antes da fila de impressão.')
|
||||||
if kind == 'correction' and order['state'] != 'cor':
|
if kind == 'correction' and order['state'] != 'cor':
|
||||||
raise HTTPException(409, 'This order is not awaiting artwork correction')
|
raise HTTPException(409, 'Este pedido não está esperando correção.')
|
||||||
if len({f.upload_id for f in body.files}) != len(body.files):
|
if len({f.upload_id for f in body.files}) != len(body.files):
|
||||||
raise HTTPException(422, 'Each uploaded file must appear once')
|
raise HTTPException(422, 'O mesmo arquivo foi enviado duas vezes.')
|
||||||
count = len(order['snapshot']['items'])
|
count = len(order['snapshot']['items'])
|
||||||
if any(f.item_index >= count for f in body.files):
|
if any(f.item_index >= count for f in body.files):
|
||||||
raise HTTPException(422, 'Invalid order item')
|
raise HTTPException(422, 'Item do pedido inválido.')
|
||||||
if kind == 'final' and {f.item_index for f in body.files} != set(range(count)):
|
if kind == 'final' and {f.item_index for f in body.files} != set(range(count)):
|
||||||
raise HTTPException(422, 'Final-file set must cover every order item')
|
raise HTTPException(422, 'Envie um arquivo final para cada item do pedido.')
|
||||||
original_ids = [UUID(uid) for item in order['snapshot']['items'] for uid in item['uploads']]
|
original_ids = [UUID(uid) for item in order['snapshot']['items'] for uid in item['uploads']]
|
||||||
first = c.execute('SELECT min(created_at) AS first FROM dtf_local.uploads WHERE id=ANY(%s)', (original_ids,)).fetchone()['first']
|
first = c.execute('SELECT min(created_at) AS first FROM dtf_local.uploads WHERE id=ANY(%s)', (original_ids,)).fetchone()['first']
|
||||||
expiry = first + timedelta(days=30)
|
expiry = first + timedelta(days=30)
|
||||||
if expiry <= datetime.now(timezone.utc):
|
if expiry <= datetime.now(timezone.utc):
|
||||||
raise HTTPException(410, 'Order artwork retention has expired')
|
raise HTTPException(410, 'Os arquivos deste pedido expiraram (30 dias).')
|
||||||
for ref in body.files:
|
for ref in body.files:
|
||||||
upload = upload_row(c, ref.upload_id, generated_owner(c, order, ref, kind) or identity, lock=True)
|
corrected = correction_owner(c, order, ref, kind)
|
||||||
|
upload = upload_row(c, ref.upload_id, corrected or generated_owner(c, order, ref, kind) or identity, lock=True)
|
||||||
if not upload['complete']:
|
if not upload['complete']:
|
||||||
raise HTTPException(409, 'Complete all uploads first')
|
raise HTTPException(409, 'Espere o envio de todos os arquivos terminar.')
|
||||||
require_clean(upload)
|
require_clean(upload)
|
||||||
if c.execute('SELECT id FROM dtf_local.order_files WHERE upload_id=%s', (ref.upload_id,)).fetchone():
|
# Attached once, except a correction approved as its own final.
|
||||||
raise HTTPException(409, 'File is already attached. Upload a new revision.')
|
if c.execute('SELECT id FROM dtf_local.order_files WHERE upload_id=%s'+(" AND kind<>'correction'" if corrected else ''),
|
||||||
|
(ref.upload_id,)).fetchone():
|
||||||
|
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.
|
||||||
if kind == 'correction':
|
if kind == 'correction':
|
||||||
@@ -67,9 +85,13 @@ def submit_files(c, order, body, identity, kind, actor):
|
|||||||
for ref in body.files:
|
for ref in body.files:
|
||||||
c.execute('INSERT INTO dtf_local.order_files(id,order_id,upload_id,item_index,kind,note,created_by) VALUES(%s,%s,%s,%s,%s,%s,%s)',
|
c.execute('INSERT INTO dtf_local.order_files(id,order_id,upload_id,item_index,kind,note,created_by) VALUES(%s,%s,%s,%s,%s,%s,%s)',
|
||||||
(uuid4(),order['id'],ref.upload_id,ref.item_index,kind,body.note,actor))
|
(uuid4(),order['id'],ref.upload_id,ref.item_index,kind,body.note,actor))
|
||||||
c.execute('UPDATE dtf_local.uploads SET expires_at=LEAST(expires_at,%s) WHERE id=%s', (expiry,ref.upload_id))
|
# The order's window, whatever the upload's own hold was.
|
||||||
|
c.execute('UPDATE dtf_local.uploads SET expires_at=%s WHERE id=%s', (expiry,ref.upload_id))
|
||||||
c.execute('UPDATE dtf_local.orders SET version=version+1,updated_at=now() WHERE id=%s', (order['id'],))
|
c.execute('UPDATE dtf_local.orders SET version=version+1,updated_at=now() WHERE id=%s', (order['id'],))
|
||||||
if kind == 'final':
|
if kind == 'final':
|
||||||
# Artwork approval, not commercial quote approval, starts original cleanup.
|
# Artwork approval, not commercial quote approval, starts original cleanup.
|
||||||
c.execute("UPDATE dtf_local.uploads SET expires_at=LEAST(expires_at,now()+interval '7 days') WHERE id=ANY(%s)", (original_ids,))
|
# An original approved as its own print file is kept as the final.
|
||||||
|
finals = [ref.upload_id for ref in body.files]
|
||||||
|
c.execute("UPDATE dtf_local.uploads SET expires_at=LEAST(expires_at,now()+interval '7 days') WHERE id=ANY(%s) AND NOT id=ANY(%s)",
|
||||||
|
(original_ids, finals))
|
||||||
return {'ok': True, 'version': order['version']+1, 'expires_at': expiry}
|
return {'ok': True, 'version': order['version']+1, 'expires_at': expiry}
|
||||||
|
|||||||
@@ -46,6 +46,11 @@ def main():
|
|||||||
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 test orders are gone; nothing else may change a sequence.
|
||||||
|
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
|
||||||
|
|||||||
102
app/cnpj.py
Normal file
@@ -0,0 +1,102 @@
|
|||||||
|
"""The company name behind a customer's CNPJ, from the public registry.
|
||||||
|
|
||||||
|
The Site asks for e-mail, CNPJ and WhatsApp only, so the Kanban showed an
|
||||||
|
e-mail where a name belongs, and a new Tiny contact was named after it. The
|
||||||
|
Receita's CNPJ registry is public, and BrasilAPI serves it without a key.
|
||||||
|
Names are looked up by the worker, never while a customer waits, and kept in
|
||||||
|
dtf_local.cnpj_names; a lookup that fails is tried again a day later.
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
API = os.environ.get('CNPJ_LOOKUP_URL', 'https://brasilapi.com.br/api/cnpj/v1/')
|
||||||
|
# A few per minute of the worker's time is plenty: customers repeat.
|
||||||
|
PER_RUN = 5
|
||||||
|
|
||||||
|
|
||||||
|
def digits(value):
|
||||||
|
return ''.join(ch for ch in str(value or '') if ch.isdigit())
|
||||||
|
|
||||||
|
|
||||||
|
def fetch(cnpj, transport=None):
|
||||||
|
"""The registry's names for one CNPJ. An unknown CNPJ has none, and is not asked again."""
|
||||||
|
with httpx.Client(timeout=8, transport=transport) as http:
|
||||||
|
response = http.get(API + cnpj, headers={'Accept': 'application/json', 'User-Agent': 'dtf-sistema'})
|
||||||
|
if response.status_code == 404:
|
||||||
|
return {'legal_name': None, 'trade_name': None}
|
||||||
|
response.raise_for_status()
|
||||||
|
data = response.json()
|
||||||
|
clean = lambda value: ' '.join(str(value).split()) or None if value else None
|
||||||
|
return {'legal_name': clean(data.get('razao_social')), 'trade_name': clean(data.get('nome_fantasia'))}
|
||||||
|
|
||||||
|
|
||||||
|
def pending(c, limit):
|
||||||
|
"""CNPJs of orders and recent quotes never looked up, or whose lookup failed a day ago."""
|
||||||
|
return [row['cnpj'] for row in c.execute('''WITH seen AS (
|
||||||
|
SELECT regexp_replace(snapshot->'customer'->>'cnpj', '\\D', '', 'g') AS cnpj, created_at FROM dtf_local.orders
|
||||||
|
UNION ALL
|
||||||
|
SELECT regexp_replace(draft->'customer'->>'cnpj', '\\D', '', 'g'), created_at FROM dtf_local.quotes
|
||||||
|
WHERE created_at > now() - interval '3 days')
|
||||||
|
SELECT s.cnpj FROM seen s LEFT JOIN dtf_local.cnpj_names n ON n.cnpj=s.cnpj
|
||||||
|
WHERE length(s.cnpj)=14 AND (n.cnpj IS NULL OR (n.fetched_at IS NULL AND n.failed_at < now() - interval '1 day'))
|
||||||
|
GROUP BY s.cnpj ORDER BY max(s.created_at) DESC LIMIT %s''', (limit,)).fetchall()]
|
||||||
|
|
||||||
|
|
||||||
|
def store(c, cnpj, found):
|
||||||
|
c.execute('''INSERT INTO dtf_local.cnpj_names(cnpj,legal_name,trade_name,fetched_at) VALUES(%s,%s,%s,now())
|
||||||
|
ON CONFLICT (cnpj) DO UPDATE SET legal_name=EXCLUDED.legal_name, trade_name=EXCLUDED.trade_name,
|
||||||
|
fetched_at=now(), failed_at=NULL''', (cnpj, found['legal_name'], found['trade_name']))
|
||||||
|
|
||||||
|
|
||||||
|
def failed(c, cnpj):
|
||||||
|
c.execute('''INSERT INTO dtf_local.cnpj_names(cnpj,failed_at) VALUES(%s,now())
|
||||||
|
ON CONFLICT (cnpj) DO UPDATE SET failed_at=now()''', (cnpj,))
|
||||||
|
|
||||||
|
|
||||||
|
def resolve(connect, limit=PER_RUN, transport=None):
|
||||||
|
"""Look up the next few CNPJs; returns how many were found."""
|
||||||
|
with connect() as c:
|
||||||
|
cnpjs = pending(c, limit)
|
||||||
|
found = 0
|
||||||
|
for cnpj in cnpjs:
|
||||||
|
try:
|
||||||
|
names = fetch(cnpj, transport)
|
||||||
|
except (httpx.HTTPError, ValueError):
|
||||||
|
with connect() as c:
|
||||||
|
failed(c, cnpj)
|
||||||
|
continue
|
||||||
|
with connect() as c:
|
||||||
|
store(c, cnpj, names)
|
||||||
|
found += 1
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
def names(c, cnpjs):
|
||||||
|
"""{cnpj: {'legal': ..., 'trade': ...}} for the CNPJs already found."""
|
||||||
|
wanted = sorted({digits(value) for value in cnpjs} - {''})
|
||||||
|
if not wanted:
|
||||||
|
return {}
|
||||||
|
rows = c.execute('''SELECT cnpj,legal_name,trade_name FROM dtf_local.cnpj_names
|
||||||
|
WHERE cnpj=ANY(%s) AND (legal_name IS NOT NULL OR trade_name IS NOT NULL)''', (wanted,)).fetchall()
|
||||||
|
return {row['cnpj']: {'legal': row['legal_name'], 'trade': row['trade_name']} for row in rows}
|
||||||
|
|
||||||
|
|
||||||
|
def company(cnpj, connect=None, transport=None):
|
||||||
|
"""One CNPJ's names for a Tiny contact: stored, or looked up now. None if unavailable."""
|
||||||
|
if connect is None:
|
||||||
|
from .core.db import connect
|
||||||
|
cnpj = digits(cnpj)
|
||||||
|
if len(cnpj) != 14: # a CPF: a person, not in the company registry
|
||||||
|
return None
|
||||||
|
with connect() as c:
|
||||||
|
known = names(c, [cnpj]).get(cnpj)
|
||||||
|
if known:
|
||||||
|
return known
|
||||||
|
try:
|
||||||
|
found = fetch(cnpj, transport)
|
||||||
|
except (httpx.HTTPError, ValueError):
|
||||||
|
return None
|
||||||
|
with connect() as c:
|
||||||
|
store(c, cnpj, found)
|
||||||
|
return {'legal': found['legal_name'], 'trade': found['trade_name']} if any(found.values()) else None
|
||||||
@@ -45,7 +45,7 @@ def session_row(request):
|
|||||||
try:
|
try:
|
||||||
sid = UUID(request.cookies.get('dtf_session', ''))
|
sid = UUID(request.cookies.get('dtf_session', ''))
|
||||||
except ValueError:
|
except ValueError:
|
||||||
raise HTTPException(401, 'Start a local session first')
|
raise HTTPException(401, 'Sessão não iniciada. Recarregue a página.')
|
||||||
with connect() as c:
|
with connect() as c:
|
||||||
row = c.execute('SELECT * FROM dtf_local.sessions WHERE id=%s AND expires_at>now()', (sid,)).fetchone()
|
row = c.execute('SELECT * FROM dtf_local.sessions WHERE id=%s AND expires_at>now()', (sid,)).fetchone()
|
||||||
if not row:
|
if not row:
|
||||||
@@ -92,7 +92,7 @@ def rate_limit(scope, identity, limit, seconds=900):
|
|||||||
RETURNING attempts""", (key,seconds,seconds)).fetchone()
|
RETURNING attempts""", (key,seconds,seconds)).fetchone()
|
||||||
if row['attempts'] > limit:
|
if row['attempts'] > limit:
|
||||||
audit('rate_limit', scope=scope)
|
audit('rate_limit', scope=scope)
|
||||||
raise HTTPException(429, 'Too many requests. Try again later.', headers={'Retry-After':str(seconds)})
|
raise HTTPException(429, 'Muitas tentativas. Tente de novo mais tarde.', headers={'Retry-After':str(seconds)})
|
||||||
|
|
||||||
ACCOUNT_FAILURES = 10
|
ACCOUNT_FAILURES = 10
|
||||||
|
|
||||||
@@ -108,19 +108,61 @@ def throttle(email, request):
|
|||||||
WHERE key=%s AND started_at >= now()-interval '900 seconds'""", (key,)).fetchone()
|
WHERE key=%s AND started_at >= now()-interval '900 seconds'""", (key,)).fetchone()
|
||||||
if row and row['attempts'] >= ACCOUNT_FAILURES:
|
if row and row['attempts'] >= ACCOUNT_FAILURES:
|
||||||
audit('rate_limit', scope='auth-account')
|
audit('rate_limit', scope='auth-account')
|
||||||
raise HTTPException(429, 'Too many requests. Try again later.', headers={'Retry-After': '900'})
|
raise HTTPException(429, 'Muitas tentativas. Tente de novo mais tarde.', headers={'Retry-After': '900'})
|
||||||
|
|
||||||
def login_failed(email):
|
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)
|
||||||
|
|
||||||
def operator(request: Request):
|
# What each Kanban profile may do. "view" is reading; "produce" moves cards and
|
||||||
|
# handles artwork; "print" is the print room's side of it (the machine, the
|
||||||
|
# queue's order, its files and folder); "manage" covers quotes, cancellations
|
||||||
|
# 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
|
||||||
|
# backup, the Tiny log): the others see there only what is on and off.
|
||||||
|
# The designer approves and refuses artwork and asks for corrections, on every
|
||||||
|
# order whatever its machine, and moves cards only among DESIGNER_STATES.
|
||||||
|
ROLES = ('superadmin', 'admin', 'gestao', 'designer', 'operador', 'vendedor')
|
||||||
|
DESIGNER_STATES = ('rec', 'tra', 'cor')
|
||||||
|
CAPABILITIES = {
|
||||||
|
'view': set(ROLES),
|
||||||
|
'produce': {'superadmin', 'admin', 'gestao', 'designer', 'operador'},
|
||||||
|
'print': {'superadmin', 'admin', 'gestao', 'operador'},
|
||||||
|
'manage': {'superadmin', 'admin', 'gestao'},
|
||||||
|
'users': {'superadmin', 'admin'},
|
||||||
|
'integrations': {'superadmin'},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def signed_in(request: Request):
|
||||||
|
"""The operator behind this session, active, with the profile read now: a
|
||||||
|
role changed or an account disabled takes effect on the next request."""
|
||||||
token = request.cookies.get('dtf_operator', '')
|
token = request.cookies.get('dtf_operator', '')
|
||||||
if not token or len(token)>128:
|
if not token or len(token)>128:
|
||||||
raise HTTPException(401, 'Sign in to the local 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 username FROM dtf_local.operator_sessions WHERE token_hash=%s AND expires_at>now()', (digest,)).fetchone()
|
row = c.execute('''SELECT o.id,o.email,o.name,o.role FROM dtf_local.operator_sessions s
|
||||||
|
JOIN dtf_local.operators o ON o.email=s.username AND o.active
|
||||||
|
WHERE s.token_hash=%s AND s.expires_at>now()''', (digest,)).fetchone()
|
||||||
|
if row:
|
||||||
|
row['machines'] = [str(r['machine_id']) for r in c.execute(
|
||||||
|
'SELECT machine_id FROM dtf_local.operator_machines WHERE operator_id=%s', (row['id'],)).fetchall()]
|
||||||
if not row:
|
if not row:
|
||||||
raise HTTPException(401, 'Operator session expired')
|
raise HTTPException(401, 'Sua sessão expirou. Entre de novo.')
|
||||||
return row['username']
|
request.state.operator = row
|
||||||
|
return row
|
||||||
|
|
||||||
|
|
||||||
|
def can(capability):
|
||||||
|
"""A dependency that lets through the profiles allowed to do this, and
|
||||||
|
returns the operator's e-mail, as the routes record it."""
|
||||||
|
def check(request: Request):
|
||||||
|
account = signed_in(request)
|
||||||
|
if account['role'] not in CAPABILITIES[capability]:
|
||||||
|
raise HTTPException(403, 'Seu perfil não permite esta ação.')
|
||||||
|
return account['email']
|
||||||
|
return check
|
||||||
|
|
||||||
|
|
||||||
|
operator = can('view')
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
"""Limits shared by upload admission and the malware scanner."""
|
"""Limits shared by upload admission and the malware scanner."""
|
||||||
import os
|
import os
|
||||||
|
|
||||||
CLAMAV_STREAM_MAX_BYTES = 128 * 1024 * 1024 # infra/clamd.conf
|
CLAMAV_STREAM_MAX_BYTES = 2000 * 1024 * 1024 # infra/clamd.conf StreamMaxLength
|
||||||
|
|
||||||
|
|
||||||
def scan_limit_bytes():
|
def scan_limit_bytes():
|
||||||
return min(CLAMAV_STREAM_MAX_BYTES, int(os.environ.get('SCAN_MAX_BYTES', '134217728')))
|
"""The largest file ClamAV scans; above it the format check releases it."""
|
||||||
|
return min(CLAMAV_STREAM_MAX_BYTES, int(os.environ.get('SCAN_MAX_BYTES', str(CLAMAV_STREAM_MAX_BYTES))))
|
||||||
|
|
||||||
|
|
||||||
def upload_limit_bytes():
|
def upload_limit_bytes():
|
||||||
transport = int(os.environ.get('MAX_UPLOAD_BYTES', '5368709120'))
|
return int(os.environ.get('MAX_UPLOAD_BYTES', '1073741824'))
|
||||||
return min(transport, scan_limit_bytes())
|
|
||||||
|
|||||||
@@ -7,22 +7,48 @@ from pydantic import BaseModel, ConfigDict, Field, field_validator, model_valida
|
|||||||
class StrictModel(BaseModel):
|
class StrictModel(BaseModel):
|
||||||
model_config = ConfigDict(extra='forbid', allow_inf_nan=False)
|
model_config = ConfigDict(extra='forbid', allow_inf_nan=False)
|
||||||
|
|
||||||
|
def check_digit(base, weights):
|
||||||
|
rem = sum(int(n) * w for n, w in zip(base, weights)) % 11
|
||||||
|
return 0 if rem < 2 else 11 - rem
|
||||||
|
|
||||||
|
def cpf_ok(digits):
|
||||||
|
return (len(digits) == 11 and len(set(digits)) > 1
|
||||||
|
and check_digit(digits[:9], range(10, 1, -1)) == int(digits[9])
|
||||||
|
and check_digit(digits[:10], range(11, 1, -1)) == int(digits[10]))
|
||||||
|
|
||||||
|
def cnpj_ok(digits):
|
||||||
|
return (len(digits) == 14 and len(set(digits)) > 1
|
||||||
|
and check_digit(digits[:12], [5,4,3,2,9,8,7,6,5,4,3,2]) == int(digits[12])
|
||||||
|
and check_digit(digits[:13], [6,5,4,3,2,9,8,7,6,5,4,3,2]) == int(digits[13]))
|
||||||
|
|
||||||
|
def person_name(value):
|
||||||
|
"""A name as typed, with its spaces tidied; at least two letters when given."""
|
||||||
|
name = ' '.join(str(value or '').split())
|
||||||
|
if name and sum(ch.isalpha() for ch in name) < 2:
|
||||||
|
raise ValueError('Invalid name')
|
||||||
|
return name
|
||||||
|
|
||||||
class Customer(StrictModel):
|
class Customer(StrictModel):
|
||||||
|
# The customer's CPF or CNPJ, digits only. The key keeps the name it had
|
||||||
|
# when only companies bought, as stored orders, quotes and accounts use it.
|
||||||
cnpj: str
|
cnpj: str
|
||||||
zap: str
|
zap: str
|
||||||
mail: str = Field(max_length=254)
|
mail: str = Field(max_length=254)
|
||||||
|
# Who to greet: the Tiny contact and the WhatsApp notices use it. Empty in
|
||||||
|
# orders placed before the Site asked for it.
|
||||||
|
name: str = Field(default='', max_length=80)
|
||||||
|
|
||||||
|
@field_validator('name')
|
||||||
|
@classmethod
|
||||||
|
def name_valid(cls, value):
|
||||||
|
return person_name(value)
|
||||||
|
|
||||||
@field_validator('cnpj')
|
@field_validator('cnpj')
|
||||||
@classmethod
|
@classmethod
|
||||||
def cnpj_valid(cls, value):
|
def document_valid(cls, value):
|
||||||
digits = re.sub(r'\D', '', value)
|
digits = re.sub(r'\D', '', value)
|
||||||
if len(digits) != 14 or len(set(digits)) == 1 or not digits.isascii():
|
if not digits.isascii() or not (cpf_ok(digits) or cnpj_ok(digits)):
|
||||||
raise ValueError('Invalid CNPJ')
|
raise ValueError('Invalid CPF or CNPJ')
|
||||||
def check(base, weights):
|
|
||||||
rem = sum(int(n) * w for n,w in zip(base, weights)) % 11
|
|
||||||
return 0 if rem < 2 else 11-rem
|
|
||||||
if check(digits[:12], [5,4,3,2,9,8,7,6,5,4,3,2]) != int(digits[12]) or check(digits[:13], [6,5,4,3,2,9,8,7,6,5,4,3,2]) != int(digits[13]):
|
|
||||||
raise ValueError('Invalid CNPJ')
|
|
||||||
return digits
|
return digits
|
||||||
|
|
||||||
@field_validator('zap')
|
@field_validator('zap')
|
||||||
@@ -41,9 +67,21 @@ class Customer(StrictModel):
|
|||||||
return value.strip()
|
return value.strip()
|
||||||
|
|
||||||
class Freight(StrictModel):
|
class Freight(StrictModel):
|
||||||
service: Literal['pickup','mock-standard'] = 'pickup'
|
service: Literal['pickup','mock-standard','jadlog','pac','sedex'] = 'pickup'
|
||||||
postal_code: str = Field(default='', max_length=8)
|
postal_code: str = Field(default='', max_length=8)
|
||||||
|
|
||||||
|
class FreightEstimate(Freight):
|
||||||
|
"""The cart's estimate. The charged freight is quoted again by the server
|
||||||
|
from the approved items, never from these numbers."""
|
||||||
|
metres: Decimal | None = Field(default=None, gt=0, le=12000)
|
||||||
|
declared_cents: int = Field(default=0, ge=0, le=100_000_000, strict=True)
|
||||||
|
|
||||||
|
class FreightAsk(StrictModel):
|
||||||
|
"""Every delivery option for the cart's package to a CEP."""
|
||||||
|
postal_code: str = Field(pattern=r'^[0-9]{8}$')
|
||||||
|
metres: Decimal = Field(gt=0, le=12000)
|
||||||
|
declared_cents: int = Field(default=0, ge=0, le=100_000_000, strict=True)
|
||||||
|
|
||||||
UF = Literal['AC','AL','AP','AM','BA','CE','DF','ES','GO','MA','MT','MS','MG','PA','PB',
|
UF = Literal['AC','AL','AP','AM','BA','CE','DF','ES','GO','MA','MT','MS','MG','PA','PB',
|
||||||
'PR','PE','PI','RJ','RN','RS','RO','RR','SC','SP','SE','TO']
|
'PR','PE','PI','RJ','RN','RS','RO','RR','SC','SP','SE','TO']
|
||||||
|
|
||||||
@@ -99,8 +137,14 @@ class ProductionPlacement(StrictModel):
|
|||||||
rotation_degrees: Literal[0, 90, 180, 270]
|
rotation_degrees: Literal[0, 90, 180, 270]
|
||||||
mirrored: bool
|
mirrored: bool
|
||||||
|
|
||||||
|
# The layout rule an order was packed with. 2: pieces 5 mm apart on a 5 mm grid,
|
||||||
|
# no margins. 3 (Dropstar, 2026-10-21): 5 mm margins top and bottom and between
|
||||||
|
# rows, and across the width 5 mm or the space left shared out equally.
|
||||||
|
PRODUCTION_VERSIONS = (2, 3)
|
||||||
|
|
||||||
|
|
||||||
class ProductionSpec(StrictModel):
|
class ProductionSpec(StrictModel):
|
||||||
version: Literal[2]
|
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=20)
|
||||||
@@ -128,6 +172,9 @@ 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')
|
||||||
|
# A textile transfer is pressed face down: mirrored, it prints backwards.
|
||||||
|
if self.mode == 'avulsa' and source.mirrored:
|
||||||
|
raise ValueError('Textile artwork cannot be mirrored')
|
||||||
expected={(index,copy) for index,source in enumerate(self.production.sources)
|
expected={(index,copy) for index,source in enumerate(self.production.sources)
|
||||||
for copy in range(source.copies)}
|
for copy in range(source.copies)}
|
||||||
placed=set()
|
placed=set()
|
||||||
@@ -184,13 +231,23 @@ class PaymentMethod(StrictModel):
|
|||||||
# in the browser; the number never reaches this server.
|
# in the browser; the number never reaches this server.
|
||||||
token: str | None = Field(default=None, max_length=200)
|
token: str | None = Field(default=None, max_length=200)
|
||||||
payment_method_id: str | None = Field(default=None, max_length=40, pattern=r'^[a-z_]+$')
|
payment_method_id: str | None = Field(default=None, max_length=40, pattern=r'^[a-z_]+$')
|
||||||
installments: int = Field(default=1, ge=1, le=12, strict=True)
|
# Up to 3, as Dropstar sells; the card form offers no more.
|
||||||
|
installments: int = Field(default=1, ge=1, le=3, strict=True)
|
||||||
issuer_id: str | None = Field(default=None, max_length=40)
|
issuer_id: str | None = Field(default=None, max_length=40)
|
||||||
|
# The cardholder's document from the card form: for a card, the payer is
|
||||||
|
# the cardholder, not necessarily the company on the invoice.
|
||||||
|
payer_document_type: Literal['CPF', 'CNPJ'] | None = None
|
||||||
|
payer_document: str | None = Field(default=None, pattern=r'^[0-9]{11,14}$')
|
||||||
|
|
||||||
@model_validator(mode='after')
|
@model_validator(mode='after')
|
||||||
def card_needs_token(self):
|
def card_needs_token(self):
|
||||||
if self.type == 'card' and not (self.token and self.payment_method_id):
|
if self.type == 'card' and not (self.token and self.payment_method_id):
|
||||||
raise ValueError('Card payment requires the provider token and method')
|
raise ValueError('Card payment requires the provider token and method')
|
||||||
|
# The store takes credit cards and PIX only. Mercado Pago's debit
|
||||||
|
# methods are debvisa, debmaster, debelo...; the adapter still knows
|
||||||
|
# how to pay one, should debit be offered again.
|
||||||
|
if self.type == 'card' and self.payment_method_id.startswith('deb'):
|
||||||
|
raise ValueError('Só aceitamos cartão de crédito ou PIX.')
|
||||||
return self
|
return self
|
||||||
|
|
||||||
class PaymentIntent(StrictModel):
|
class PaymentIntent(StrictModel):
|
||||||
@@ -207,7 +264,63 @@ class Resolution(StrictModel):
|
|||||||
|
|
||||||
class Register(StrictModel):
|
class Register(StrictModel):
|
||||||
customer: Customer
|
customer: Customer
|
||||||
password: str = Field(min_length=12, max_length=128)
|
password: str = Field(min_length=8, max_length=128)
|
||||||
|
|
||||||
|
class ProfileUpdate(StrictModel):
|
||||||
|
"""What a customer may change about their account; the CPF/CNPJ is not among it."""
|
||||||
|
zap: str
|
||||||
|
address: Destination | None = None
|
||||||
|
name: str | None = Field(default=None, max_length=80)
|
||||||
|
|
||||||
|
@field_validator('name')
|
||||||
|
@classmethod
|
||||||
|
def name_valid(cls, value):
|
||||||
|
return None if value is None else person_name(value)
|
||||||
|
|
||||||
|
@field_validator('zap')
|
||||||
|
@classmethod
|
||||||
|
def phone_valid(cls, value):
|
||||||
|
digits = re.sub(r'\D', '', value)
|
||||||
|
if len(digits) not in (10,11) or not digits.isascii():
|
||||||
|
raise ValueError('Invalid phone')
|
||||||
|
return digits
|
||||||
|
|
||||||
|
class EmailChange(StrictModel):
|
||||||
|
email: str = Field(max_length=254)
|
||||||
|
password: str = Field(min_length=1, max_length=128)
|
||||||
|
|
||||||
|
@field_validator('email')
|
||||||
|
@classmethod
|
||||||
|
def email_valid(cls, value):
|
||||||
|
value = value.strip().lower()
|
||||||
|
if not re.fullmatch(r'[^\s@]+@[^\s@]+\.[a-zA-Z]{2,}', value):
|
||||||
|
raise ValueError('Invalid email')
|
||||||
|
return value
|
||||||
|
|
||||||
|
class PasswordChange(StrictModel):
|
||||||
|
current: str = Field(min_length=1, max_length=128)
|
||||||
|
new: str = Field(min_length=8, max_length=128)
|
||||||
|
|
||||||
|
class SignupCode(StrictModel):
|
||||||
|
signup: UUID
|
||||||
|
code: str = Field(pattern=r'^[0-9]{6}$')
|
||||||
|
|
||||||
|
class SignupResend(StrictModel):
|
||||||
|
signup: UUID
|
||||||
|
|
||||||
|
class EmailCode(StrictModel):
|
||||||
|
change: UUID
|
||||||
|
code: str = Field(pattern=r'^[0-9]{6}$')
|
||||||
|
|
||||||
|
class EmailResend(StrictModel):
|
||||||
|
change: UUID
|
||||||
|
|
||||||
|
class ForgotPassword(StrictModel):
|
||||||
|
email: str = Field(min_length=3, max_length=254)
|
||||||
|
|
||||||
|
class PasswordReset(StrictModel):
|
||||||
|
token: str = Field(min_length=20, max_length=100, pattern=r'^[A-Za-z0-9_-]+$')
|
||||||
|
password: str = Field(min_length=8, max_length=128)
|
||||||
|
|
||||||
class Login(StrictModel):
|
class Login(StrictModel):
|
||||||
email: str = Field(min_length=3, max_length=254)
|
email: str = Field(min_length=3, max_length=254)
|
||||||
|
|||||||
@@ -3,6 +3,8 @@
|
|||||||
Quantity/grade must be supplied by an authenticated commercial reviewer.
|
Quantity/grade must be supplied by an authenticated commercial reviewer.
|
||||||
This module does not inspect artwork or perform pre-flight.
|
This module does not inspect artwork or perform pre-flight.
|
||||||
"""
|
"""
|
||||||
|
import os
|
||||||
|
import re
|
||||||
from decimal import Decimal, ROUND_CEILING
|
from decimal import Decimal, ROUND_CEILING
|
||||||
|
|
||||||
TIERS = {
|
TIERS = {
|
||||||
@@ -12,16 +14,44 @@ TIERS = {
|
|||||||
'uv': [(90,8390),(75,8790),(60,9190),(40,9590),(0,9990)],
|
'uv': [(90,8390),(75,8790),(60,9190),(40,9590),(0,9990)],
|
||||||
}
|
}
|
||||||
|
|
||||||
def price(mode: str, metres: str, grade: int) -> dict:
|
# A finished sheet the Site cannot open (CDR, AI, PSD, TIFF) is opened by a
|
||||||
|
# person before printing. It is priced at the top of the ladder, plus this per
|
||||||
|
# metre when the business sets it, to make the formats the robot reads the
|
||||||
|
# cheaper path. Zero (the default) adds nothing.
|
||||||
|
MANUAL_FORMATS = re.compile(r'\.(cdr|ai|psd|psb|tiff?)$', re.I)
|
||||||
|
|
||||||
|
|
||||||
|
def manual_extra_cents() -> int:
|
||||||
|
value = int(os.environ.get('MANUAL_FILE_EXTRA_CENTS', '0') or 0)
|
||||||
|
if not 0 <= value <= 100000:
|
||||||
|
raise ValueError('MANUAL_FILE_EXTRA_CENTS must be between 0 and 100000')
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def is_manual(item, names) -> bool:
|
||||||
|
"""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."""
|
||||||
|
return any(source['kind'] == 'sheet' and (source['measurement'] == 'customer' or
|
||||||
|
MANUAL_FORMATS.search(names.get(str(source['upload_id']), '')))
|
||||||
|
for source in item['production']['sources'])
|
||||||
|
|
||||||
|
|
||||||
|
def price(mode: str, metres: str, grade: int, extra_cents: int = 0) -> dict:
|
||||||
length = Decimal(str(metres))
|
length = Decimal(str(metres))
|
||||||
if mode not in TIERS or not length.is_finite() or not 0 < length <= 12000:
|
if mode not in TIERS 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(Decimal('1'), (length * 10).to_integral_value(rounding=ROUND_CEILING) / 10)
|
||||||
unit = next(cents for minimum, cents in TIERS[mode] if grade >= minimum)
|
if isinstance(extra_cents, bool) or not isinstance(extra_cents, int) or extra_cents < 0:
|
||||||
return {'mode': mode, 'metres': str(length), 'grade': grade,
|
raise ValueError('Invalid extra charge')
|
||||||
|
tier = next(cents for minimum, cents in TIERS[mode] if grade >= minimum)
|
||||||
|
unit = tier + extra_cents
|
||||||
|
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),
|
||||||
'discount_cents': int(billed * (TIERS[mode][-1][1] - unit))}
|
'discount_cents': int(billed * (TIERS[mode][-1][1] - tier))}
|
||||||
|
if extra_cents:
|
||||||
|
priced['manual_extra_cents'] = extra_cents
|
||||||
|
return priced
|
||||||
|
|
||||||
|
|||||||
@@ -27,7 +27,8 @@ SECRET_FILE_SETTINGS = (
|
|||||||
'PAYMENT_TOKEN',
|
'PAYMENT_TOKEN',
|
||||||
'PAYMENT_WEBHOOK_SECRET',
|
'PAYMENT_WEBHOOK_SECRET',
|
||||||
'TINY_TOKEN',
|
'TINY_TOKEN',
|
||||||
'WHATSAPP_TOKEN',
|
'SMTP_PASSWORD',
|
||||||
|
'CORREIOS_CODIGO_ACESSO',
|
||||||
)
|
)
|
||||||
|
|
||||||
SUFFIX = '_FILE'
|
SUFFIX = '_FILE'
|
||||||
|
|||||||
184
app/correios.py
Normal file
@@ -0,0 +1,184 @@
|
|||||||
|
"""Correios freight quotes (CWS API: Token, Preço and Prazo), PAC and SEDEX.
|
||||||
|
|
||||||
|
Written from the Correios manuals (API Preço, API Prazo) and exercised against
|
||||||
|
a fake HTTP transport until app.correios_probe has run on Dropstar's contract.
|
||||||
|
A quote is read-only: it creates no shipment and costs nothing.
|
||||||
|
|
||||||
|
The token comes from the posting card (cartão de postagem) with the CWS user
|
||||||
|
and its access code, lasts about a day and is reused until shortly before it
|
||||||
|
expires. It also says the contract and its regional office (DR), which price
|
||||||
|
the contract's own rates. Each box of the order (app/package.py) is one
|
||||||
|
object: Correios price the larger of its real and cubic weight themselves,
|
||||||
|
from the box's sides, so only the real weight is sent.
|
||||||
|
"""
|
||||||
|
import base64
|
||||||
|
import os
|
||||||
|
import threading
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal, InvalidOperation
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
from .package import Package
|
||||||
|
|
||||||
|
API = 'https://api.correios.com.br'
|
||||||
|
ORIGIN = '14402310'
|
||||||
|
# The contract's service codes ("contrato agência"); a setting overrides each.
|
||||||
|
SERVICES = {'pac': ('CORREIOS_COD_PAC', '03298', 'Correios PAC'),
|
||||||
|
'sedex': ('CORREIOS_COD_SEDEX', '03220', 'Correios SEDEX')}
|
||||||
|
PACKAGE = '2'
|
||||||
|
MAX_KG = Decimal(30)
|
||||||
|
BRASILIA = timezone(timedelta(hours=-3))
|
||||||
|
|
||||||
|
|
||||||
|
class CorreiosError(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def digits(value):
|
||||||
|
return ''.join(ch for ch in str(value or '') if ch.isdigit())
|
||||||
|
|
||||||
|
|
||||||
|
def required_settings():
|
||||||
|
return ('CORREIOS_USUARIO', 'CORREIOS_CODIGO_ACESSO', 'CORREIOS_CARTAO')
|
||||||
|
|
||||||
|
|
||||||
|
def configured():
|
||||||
|
return bool(os.environ.get('CORREIOS_CODIGO_ACESSO', '').strip())
|
||||||
|
|
||||||
|
|
||||||
|
def problem(response):
|
||||||
|
"""The Correios' own words for a refusal: txErro, or the gateway's msgs."""
|
||||||
|
try:
|
||||||
|
data = response.json()
|
||||||
|
except ValueError:
|
||||||
|
return f'HTTP {response.status_code}'
|
||||||
|
if isinstance(data, list):
|
||||||
|
data = data[0] if data else {}
|
||||||
|
if isinstance(data, dict):
|
||||||
|
if data.get('txErro'):
|
||||||
|
return data['txErro']
|
||||||
|
if data.get('msgs'):
|
||||||
|
return '; '.join(map(str, data['msgs']))
|
||||||
|
return f'HTTP {response.status_code}'
|
||||||
|
|
||||||
|
|
||||||
|
def cents(text):
|
||||||
|
"""'11,64' (or 11.64) in centavos."""
|
||||||
|
try:
|
||||||
|
value = Decimal(str(text).replace('.', '').replace(',', '.')) if ',' in str(text) else Decimal(str(text))
|
||||||
|
except InvalidOperation:
|
||||||
|
raise CorreiosError(f'preço ilegível: {text!r}') from None
|
||||||
|
return int((value * 100).quantize(Decimal('1'), ROUND_HALF_UP))
|
||||||
|
|
||||||
|
|
||||||
|
class CorreiosQuotes:
|
||||||
|
def __init__(self, user=None, access_code=None, card=None, origin=None, transport=None, clock=None):
|
||||||
|
self.user = (user or os.environ.get('CORREIOS_USUARIO', '')).strip()
|
||||||
|
self.access_code = (access_code or os.environ.get('CORREIOS_CODIGO_ACESSO', '')).strip()
|
||||||
|
self.card = digits(card or os.environ.get('CORREIOS_CARTAO'))
|
||||||
|
self.origin = digits(origin or os.environ.get('CORREIOS_ORIGEM_CEP') or ORIGIN)
|
||||||
|
if not (self.user and self.access_code and self.card):
|
||||||
|
raise RuntimeError('Correios needs ' + ', '.join(required_settings()))
|
||||||
|
self.http = httpx.Client(base_url=API, timeout=15, transport=transport)
|
||||||
|
self.clock = clock or (lambda: datetime.now(timezone.utc))
|
||||||
|
self.lock = threading.Lock()
|
||||||
|
self.token = None
|
||||||
|
self.expires = None
|
||||||
|
self.contract = None
|
||||||
|
self.dr = None
|
||||||
|
|
||||||
|
def authenticate(self):
|
||||||
|
basic = base64.b64encode(f'{self.user}:{self.access_code}'.encode()).decode()
|
||||||
|
response = self.http.post('/token/v1/autentica/cartaopostagem', json={'numero': self.card},
|
||||||
|
headers={'Authorization': f'Basic {basic}'})
|
||||||
|
if response.status_code >= 400:
|
||||||
|
raise CorreiosError(f'token recusado: {problem(response)}')
|
||||||
|
data = response.json()
|
||||||
|
card = data.get('cartaoPostagem') or {}
|
||||||
|
self.token = data['token']
|
||||||
|
self.contract = card.get('contrato') or os.environ.get('CORREIOS_CONTRATO') or None
|
||||||
|
self.dr = card.get('dr') or os.environ.get('CORREIOS_DR') or None
|
||||||
|
try:
|
||||||
|
# "2026-10-16T10:00:00", Brasília time unless it says otherwise.
|
||||||
|
expires = datetime.fromisoformat(data['expiraEm'])
|
||||||
|
self.expires = expires if expires.tzinfo else expires.replace(tzinfo=BRASILIA)
|
||||||
|
except (KeyError, TypeError, ValueError):
|
||||||
|
self.expires = self.clock() + timedelta(hours=23)
|
||||||
|
|
||||||
|
def bearer(self, fresh=False):
|
||||||
|
with self.lock:
|
||||||
|
if fresh or not self.token or self.clock() >= self.expires - timedelta(minutes=10):
|
||||||
|
self.authenticate()
|
||||||
|
return self.token
|
||||||
|
|
||||||
|
def get(self, path, params):
|
||||||
|
"""A GET with the token, renewed once if the Correios refuse it."""
|
||||||
|
for fresh in (False, True):
|
||||||
|
response = self.http.get(path, params=params, headers={'Authorization': f'Bearer {self.bearer(fresh)}',
|
||||||
|
'Accept': 'application/json'})
|
||||||
|
if response.status_code != 401:
|
||||||
|
break
|
||||||
|
if response.status_code >= 400:
|
||||||
|
raise CorreiosError(problem(response))
|
||||||
|
return response.json()
|
||||||
|
|
||||||
|
def price(self, code, postal_code, grams, sides):
|
||||||
|
"""The contract's price in centavos for one package."""
|
||||||
|
length, width, height = (int(side.to_integral_value(ROUND_CEILING)) for side in sides)
|
||||||
|
params = {'cepOrigem': self.origin, 'cepDestino': postal_code, 'psObjeto': str(grams),
|
||||||
|
'tpObjeto': PACKAGE, 'comprimento': str(length), 'largura': str(width), 'altura': str(height)}
|
||||||
|
self.bearer()
|
||||||
|
if self.contract and self.dr:
|
||||||
|
params.update(nuContrato=str(self.contract), nuDR=str(self.dr))
|
||||||
|
data = self.get(f'/preco/v1/nacional/{code}', params)
|
||||||
|
if data.get('txErro'):
|
||||||
|
raise CorreiosError(data['txErro'])
|
||||||
|
if data.get('pcFinal') in (None, ''):
|
||||||
|
raise CorreiosError('sem preço na resposta')
|
||||||
|
return cents(data['pcFinal'])
|
||||||
|
|
||||||
|
def days(self, code, postal_code):
|
||||||
|
"""Delivery time in working days from posting, or None."""
|
||||||
|
data = self.get(f'/prazo/v1/nacional/{code}', {'cepOrigem': self.origin, 'cepDestino': postal_code})
|
||||||
|
if data.get('txErro'):
|
||||||
|
raise CorreiosError(data['txErro'])
|
||||||
|
return data.get('prazoEntrega')
|
||||||
|
|
||||||
|
|
||||||
|
class CorreiosFreight(Package):
|
||||||
|
"""The Site's PAC and SEDEX options for the order's package."""
|
||||||
|
name = 'correios'
|
||||||
|
|
||||||
|
def __init__(self, quotes=None):
|
||||||
|
super().__init__()
|
||||||
|
if not self.box_cm:
|
||||||
|
raise RuntimeError('Correios price by the box: set JADLOG_CAIXA_CM')
|
||||||
|
self.quotes = quotes or CorreiosQuotes()
|
||||||
|
self.codes = {service: (os.environ.get(setting) or code).strip()
|
||||||
|
for service, (setting, code, _) in SERVICES.items()}
|
||||||
|
self.services = {service: label for service, (_, _, label) in SERVICES.items()}
|
||||||
|
|
||||||
|
def quote(self, service, postal_code, metres=None, declared_cents=0):
|
||||||
|
if service == 'pickup':
|
||||||
|
return {'provider': self.name, 'service': 'pickup', 'total_cents': 0, 'postal_code': ''}
|
||||||
|
if service not in self.codes or len(postal_code) != 8 or not postal_code.isascii() or not postal_code.isdigit():
|
||||||
|
raise ValueError('Select pickup or Correios delivery with an eight-digit CEP')
|
||||||
|
if metres is None or Decimal(str(metres)) <= 0:
|
||||||
|
raise ValueError('The order length is required to quote freight')
|
||||||
|
weights = self.box_weights_kg(metres)
|
||||||
|
if max(weights) > MAX_KG:
|
||||||
|
raise ValueError('Uma caixa passa de 30 kg, o limite dos Correios.')
|
||||||
|
code = self.codes[service]
|
||||||
|
try:
|
||||||
|
# Boxes of the same weight cost the same: one price per weight.
|
||||||
|
prices = {weight: self.quotes.price(code, postal_code, int(weight * 1000), self.box_cm)
|
||||||
|
for weight in set(weights)}
|
||||||
|
days = self.quotes.days(code, postal_code)
|
||||||
|
except (CorreiosError, httpx.HTTPError) as error:
|
||||||
|
raise ValueError(f'Não foi possível cotar o {self.services[service]} agora: {error}') from None
|
||||||
|
return {'provider': self.name, 'service': service, 'postal_code': postal_code,
|
||||||
|
'total_cents': sum(prices[weight] for weight in weights),
|
||||||
|
'real_kg': str(sum(weights)), 'boxes': len(weights),
|
||||||
|
'days': None if days is None else int(days) + self.production_days,
|
||||||
|
'description': self.services[service]}
|
||||||
70
app/correios_probe.py
Normal file
@@ -0,0 +1,70 @@
|
|||||||
|
"""Read-only check against Dropstar's real Correios contract, run by hand.
|
||||||
|
A quote creates no shipment and costs nothing.
|
||||||
|
|
||||||
|
python -m app.correios_probe [--cep 01310100 ...] [--peso 0.5 ...]
|
||||||
|
|
||||||
|
It answers whether the user, access code and posting card are accepted (and
|
||||||
|
which contract and DR the token carries), whether the contract prices PAC and
|
||||||
|
SEDEX with the codes in use, and what they cost and take for one box (the
|
||||||
|
JADLOG_CAIXA_CM sides) to a few regions. The first failure stops the run: an
|
||||||
|
account problem would repeat on every line.
|
||||||
|
|
||||||
|
In production, from the worker's console (Portainer > Containers > worker >
|
||||||
|
Console), with CORREIOS_CODIGO_ACESSO in the stack:
|
||||||
|
|
||||||
|
python -m app.correios_probe
|
||||||
|
"""
|
||||||
|
import argparse
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
from decimal import Decimal
|
||||||
|
|
||||||
|
from .core.secrets import load as load_secret_files
|
||||||
|
from .correios import SERVICES, CorreiosError, CorreiosQuotes
|
||||||
|
from .package import box_cm
|
||||||
|
|
||||||
|
DESTINATIONS = {'01310100': 'São Paulo', '20040002': 'Rio de Janeiro', '80010000': 'Curitiba',
|
||||||
|
'50030230': 'Recife', '69005010': 'Manaus'}
|
||||||
|
WEIGHTS = ['0.5', '2', '5']
|
||||||
|
|
||||||
|
|
||||||
|
def money(cents):
|
||||||
|
return f'R$ {cents / 100:.2f}'.replace('.', ',')
|
||||||
|
|
||||||
|
|
||||||
|
def run(quotes, sides, ceps, weights, out):
|
||||||
|
try:
|
||||||
|
quotes.bearer()
|
||||||
|
except CorreiosError as error:
|
||||||
|
out(f'ERRO no token: {error}')
|
||||||
|
return 1
|
||||||
|
out(f'Token ok · cartão {quotes.card} · contrato {quotes.contract or "-"} · DR {quotes.dr or "-"} '
|
||||||
|
f'· válido até {quotes.expires:%d/%m %H:%M}')
|
||||||
|
out(f"Origem {quotes.origin} · caixa {' × '.join(str(side) for side in sides)} cm")
|
||||||
|
for service, (setting, default, label) in SERVICES.items():
|
||||||
|
code = (os.environ.get(setting) or default).strip()
|
||||||
|
for cep in ceps:
|
||||||
|
try:
|
||||||
|
days = quotes.days(code, cep)
|
||||||
|
for weight in weights:
|
||||||
|
cents = quotes.price(code, cep, int(Decimal(weight) * 1000), sides)
|
||||||
|
out(f"{label} ({code})\t{weight} kg\t{cep}\t{DESTINATIONS.get(cep, '')}\t{money(cents)}\t"
|
||||||
|
f"{days if days is not None else '?'} dia(s)")
|
||||||
|
except CorreiosError as error:
|
||||||
|
out(f'ERRO {label} ({code}) para {cep}: {error}')
|
||||||
|
return 1
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv=None):
|
||||||
|
parser = argparse.ArgumentParser(prog='python -m app.correios_probe')
|
||||||
|
parser.add_argument('--cep', action='append', help='destination CEP (repeatable)')
|
||||||
|
parser.add_argument('--peso', action='append', help='weight in kg (repeatable)')
|
||||||
|
args = parser.parse_args(argv)
|
||||||
|
load_secret_files()
|
||||||
|
sides = box_cm(os.environ.get('JADLOG_CAIXA_CM') or '63x15.5x15.5')
|
||||||
|
return run(CorreiosQuotes(), sides, args.cep or list(DESTINATIONS), args.peso or WEIGHTS, print)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
sys.exit(main())
|
||||||
46
app/freight.py
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
"""Every delivery option the Site offers, from every carrier configured.
|
||||||
|
|
||||||
|
The cart asks for all options at once and shows them cheapest first; the
|
||||||
|
customer's choice is quoted again by the server when the cart is approved.
|
||||||
|
A carrier that does not answer leaves its options out instead of blocking the
|
||||||
|
others.
|
||||||
|
"""
|
||||||
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
|
|
||||||
|
|
||||||
|
class FreightOptions:
|
||||||
|
name = 'carriers'
|
||||||
|
|
||||||
|
def __init__(self, carriers):
|
||||||
|
self.carriers = carriers
|
||||||
|
self.by_service = {service: carrier for carrier in carriers for service in carrier.services}
|
||||||
|
|
||||||
|
@property
|
||||||
|
def services(self):
|
||||||
|
return {service: carrier.services[service] for service, carrier in self.by_service.items()}
|
||||||
|
|
||||||
|
def carrier(self, name):
|
||||||
|
return next((c for c in self.carriers if c.name == name), None)
|
||||||
|
|
||||||
|
def quote(self, service, postal_code, metres=None, declared_cents=0):
|
||||||
|
if service == 'pickup':
|
||||||
|
return {'provider': self.name, 'service': 'pickup', 'total_cents': 0, 'postal_code': ''}
|
||||||
|
carrier = self.by_service.get(service)
|
||||||
|
if not carrier:
|
||||||
|
raise ValueError('Esta forma de entrega não está disponível. Escolha outra.')
|
||||||
|
return carrier.quote(service, postal_code, metres, declared_cents)
|
||||||
|
|
||||||
|
def options(self, postal_code, metres=None, declared_cents=0):
|
||||||
|
"""Each service's quote, cheapest first, and why any could not be quoted."""
|
||||||
|
services = list(self.by_service)
|
||||||
|
with ThreadPoolExecutor(max_workers=max(1, len(services))) as pool:
|
||||||
|
futures = {service: pool.submit(self.quote, service, postal_code, metres, declared_cents)
|
||||||
|
for service in services}
|
||||||
|
found, missing = [], []
|
||||||
|
for service, future in futures.items():
|
||||||
|
try:
|
||||||
|
found.append(future.result())
|
||||||
|
except ValueError as error:
|
||||||
|
missing.append({'service': service, 'description': self.services[service], 'error': str(error)})
|
||||||
|
found.sort(key=lambda option: (option['total_cents'], option.get('days') or 99))
|
||||||
|
return {'options': found, 'unavailable': missing}
|
||||||
189
app/grade_check.py
Normal file
@@ -0,0 +1,189 @@
|
|||||||
|
"""The grade (the resolution discount) recomputed from the uploaded files.
|
||||||
|
|
||||||
|
The Site grades the art in the customer's browser and sends the grade with the
|
||||||
|
cart, and the price depends on it. A customer who edits the page could claim a
|
||||||
|
better grade, so before a cart is approved at checkout the server reads the
|
||||||
|
files it already has and works the grade out again, by the Site's own rules:
|
||||||
|
|
||||||
|
- a finished sheet: its pixel width over the sheet width is its DPI, and the
|
||||||
|
item's grade comes from the worst sheet (web/site-quality.js);
|
||||||
|
- artworks: each one's DPI along the width it is printed at, rotation
|
||||||
|
included; the item's grade is the average of the artworks' grades;
|
||||||
|
- a PDF: the area-weighted DPI of the images drawn on its page, 300 when it
|
||||||
|
is only vectors (web/site-pdf.js, dpiDasImagens and resumoDpi).
|
||||||
|
|
||||||
|
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
|
||||||
|
cannot be recomputed is None; the caller decides what that means.
|
||||||
|
"""
|
||||||
|
import math
|
||||||
|
import os
|
||||||
|
import struct
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
DPI_IDEAL = 300
|
||||||
|
# The Site analyses PDFs up to 150 MB (GRANDE_BYTES); above that it does not
|
||||||
|
# grade them, so neither does this.
|
||||||
|
PDF_MAX_BYTES = 150 * 1048576
|
||||||
|
HEAD_BYTES = 1048576
|
||||||
|
# Rounding in the browser and here can differ by a point on the same file.
|
||||||
|
TOLERANCE = 2
|
||||||
|
|
||||||
|
|
||||||
|
def js_round(value):
|
||||||
|
"""Math.round, which rounds halves up; Python's round() does not."""
|
||||||
|
return math.floor(value + 0.5)
|
||||||
|
|
||||||
|
|
||||||
|
def grade_of(dpi):
|
||||||
|
return max(6, min(100, js_round(dpi / DPI_IDEAL * 100)))
|
||||||
|
|
||||||
|
|
||||||
|
def image_size(head):
|
||||||
|
"""(width, height) in pixels from a PNG, JPEG or WebP's first bytes."""
|
||||||
|
if head[:8] == b'\x89PNG\r\n\x1a\n' and head[12:16] == b'IHDR':
|
||||||
|
return struct.unpack('>II', head[16:24])
|
||||||
|
if head[:2] == b'\xff\xd8':
|
||||||
|
i = 2
|
||||||
|
while i + 9 < len(head):
|
||||||
|
if head[i] != 0xFF:
|
||||||
|
i += 1
|
||||||
|
continue
|
||||||
|
marker = head[i + 1]
|
||||||
|
if marker in (0xD8, 0x01) or 0xD0 <= marker <= 0xD7 or marker == 0xFF:
|
||||||
|
i += 1 if marker == 0xFF else 2
|
||||||
|
continue
|
||||||
|
length = struct.unpack('>H', head[i + 2:i + 4])[0]
|
||||||
|
if 0xC0 <= marker <= 0xCF and marker not in (0xC4, 0xC8, 0xCC):
|
||||||
|
h, w = struct.unpack('>HH', head[i + 5:i + 9])
|
||||||
|
return w, h
|
||||||
|
i += 2 + length
|
||||||
|
return None
|
||||||
|
if head[:4] == b'RIFF' and head[8:12] == b'WEBP':
|
||||||
|
chunk = head[12:16]
|
||||||
|
if chunk == b'VP8X':
|
||||||
|
return (int.from_bytes(head[24:27], 'little') + 1, int.from_bytes(head[27:30], 'little') + 1)
|
||||||
|
if chunk == b'VP8L' and head[20] == 0x2F:
|
||||||
|
bits = int.from_bytes(head[21:25], 'little')
|
||||||
|
return (bits & 0x3FFF) + 1, ((bits >> 14) & 0x3FFF) + 1
|
||||||
|
if chunk == b'VP8 ' and head[23:26] == b'\x9d\x01\x2a':
|
||||||
|
w, h = struct.unpack('<HH', head[26:30])
|
||||||
|
return w & 0x3FFF, h & 0x3FFF
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _multiply(a, b):
|
||||||
|
return [a[0] * b[0] + a[2] * b[1], a[1] * b[0] + a[3] * b[1],
|
||||||
|
a[0] * b[2] + a[2] * b[3], a[1] * b[2] + a[3] * b[3],
|
||||||
|
a[0] * b[4] + a[2] * b[5] + a[4], a[1] * b[4] + a[3] * b[5] + a[5]]
|
||||||
|
|
||||||
|
|
||||||
|
def pdf_dpi(path):
|
||||||
|
"""The page's area-weighted image DPI, 300 for vectors only, None if the
|
||||||
|
file is not a one-page PDF this can read."""
|
||||||
|
import pikepdf
|
||||||
|
try:
|
||||||
|
with pikepdf.open(path) as pdf:
|
||||||
|
if len(pdf.pages) != 1:
|
||||||
|
return None
|
||||||
|
page = pdf.pages[0]
|
||||||
|
unit = float(page.obj.get('/UserUnit', 1))
|
||||||
|
found = []
|
||||||
|
|
||||||
|
def walk(resources, instructions, ctm, depth):
|
||||||
|
stack = []
|
||||||
|
xobjects = resources.get('/XObject', {}) if resources is not None else {}
|
||||||
|
for operands, operator in instructions:
|
||||||
|
op = str(operator)
|
||||||
|
if op == 'q':
|
||||||
|
stack.append(ctm)
|
||||||
|
elif op == 'Q':
|
||||||
|
ctm = stack.pop() if stack else [1, 0, 0, 1, 0, 0]
|
||||||
|
elif op == 'cm':
|
||||||
|
ctm = _multiply(ctm, [float(v) for v in operands])
|
||||||
|
elif op == 'Do' and operands:
|
||||||
|
xobject = xobjects.get(str(operands[0]))
|
||||||
|
if xobject is None:
|
||||||
|
continue
|
||||||
|
subtype = xobject.get('/Subtype')
|
||||||
|
if subtype == '/Image':
|
||||||
|
width_pt = math.hypot(ctm[0], ctm[1])
|
||||||
|
if width_pt >= 1:
|
||||||
|
found.append((int(xobject.get('/Width', 0)) / (width_pt * unit / 72),
|
||||||
|
abs(ctm[0] * ctm[3] - ctm[1] * ctm[2])))
|
||||||
|
elif subtype == '/Form' and depth < 8:
|
||||||
|
matrix = [float(v) for v in xobject.get('/Matrix', [1, 0, 0, 1, 0, 0])]
|
||||||
|
walk(xobject.get('/Resources', resources),
|
||||||
|
pikepdf.parse_content_stream(xobject), _multiply(ctm, matrix), depth + 1)
|
||||||
|
|
||||||
|
walk(page.obj.get('/Resources'), pikepdf.parse_content_stream(page), [1, 0, 0, 1, 0, 0], 0)
|
||||||
|
except Exception:
|
||||||
|
return None
|
||||||
|
found = [(dpi, area) for dpi, area in found if dpi > 0]
|
||||||
|
if not found:
|
||||||
|
return DPI_IDEAL
|
||||||
|
total = sum(area for _, area in found) or 1
|
||||||
|
return js_round(sum(dpi * area for dpi, area in found) / total)
|
||||||
|
|
||||||
|
|
||||||
|
class Files:
|
||||||
|
"""The uploaded files, read from storage as little as needed."""
|
||||||
|
|
||||||
|
def __init__(self, storage):
|
||||||
|
self.storage = storage
|
||||||
|
|
||||||
|
def head(self, row):
|
||||||
|
return self.storage.client.get_object(Bucket=self.storage.bucket, Key=row['object_key'],
|
||||||
|
Range=f'bytes=0-{HEAD_BYTES - 1}')['Body'].read()
|
||||||
|
|
||||||
|
def pdf_dpi(self, row):
|
||||||
|
if row['size'] > PDF_MAX_BYTES:
|
||||||
|
return None
|
||||||
|
with tempfile.NamedTemporaryFile(suffix='.pdf') as handle:
|
||||||
|
self.storage.client.download_fileobj(self.storage.bucket, row['object_key'], handle)
|
||||||
|
handle.flush()
|
||||||
|
return pdf_dpi(handle.name)
|
||||||
|
|
||||||
|
|
||||||
|
def source_dpi(files, row, source):
|
||||||
|
"""One source's DPI across the width it is printed at, or None."""
|
||||||
|
name = row['name'].lower()
|
||||||
|
width_in = float(source['width_cm']) / 2.54
|
||||||
|
if name.endswith('.pdf'):
|
||||||
|
return files.pdf_dpi(row) if source['kind'] == 'sheet' else None
|
||||||
|
if not name.endswith(('.png', '.jpg', '.jpeg', '.webp')):
|
||||||
|
return None
|
||||||
|
size = image_size(files.head(row))
|
||||||
|
if not size or not all(size):
|
||||||
|
return None
|
||||||
|
across = size[1] if source['rotation_degrees'] in (90, 270) else size[0]
|
||||||
|
return across / width_in
|
||||||
|
|
||||||
|
|
||||||
|
def item_grade(files, item, rows):
|
||||||
|
"""The grade the Site gives this item, recomputed; None if it cannot be."""
|
||||||
|
sources = item['production']['sources']
|
||||||
|
dpis = []
|
||||||
|
for source in sources:
|
||||||
|
row = rows.get(str(source['upload_id']))
|
||||||
|
dpi = source_dpi(files, row, source) if row else None
|
||||||
|
if dpi is None:
|
||||||
|
return None
|
||||||
|
dpis.append(dpi)
|
||||||
|
if all(source['kind'] == 'sheet' for source in sources):
|
||||||
|
# A sheet's DPI is shown and compared as a whole number.
|
||||||
|
return grade_of(min(js_round(d) for d in dpis))
|
||||||
|
return js_round(sum(grade_of(d) for d in dpis) / len(dpis))
|
||||||
|
|
||||||
|
|
||||||
|
def mismatch(files, items, rows):
|
||||||
|
"""Why a cart's grades cannot be approved at checkout, or None."""
|
||||||
|
for item in items:
|
||||||
|
if item['grade'] == 0:
|
||||||
|
continue # full price: nothing to verify
|
||||||
|
verified = item_grade(files, item, rows)
|
||||||
|
if verified is None:
|
||||||
|
return 'Nota não conferida no servidor'
|
||||||
|
if item['grade'] > verified + TOLERANCE:
|
||||||
|
return f"Nota {item['grade']} maior que a do arquivo ({verified})"
|
||||||
|
return None
|
||||||
109
app/jadlog.py
Normal file
@@ -0,0 +1,109 @@
|
|||||||
|
"""Jadlog freight quotes (Embarcador API, "Simulador de Frete").
|
||||||
|
|
||||||
|
Written from Jadlog's API manual v2.3 (August 2025) and exercised only
|
||||||
|
against a fake HTTP transport until app.jadlog_probe has run on the client's
|
||||||
|
account. A quote is read-only: it creates no shipment and costs nothing, so
|
||||||
|
unlike Tiny it can be tried on the real account as often as needed.
|
||||||
|
|
||||||
|
The client's contract: origin CEP 14402-310, service .PACKAGE (modalidade 3),
|
||||||
|
home delivery. Jadlog prices by weight in kg and expects the larger of the
|
||||||
|
real and the cubed weight, both from the order's package (app/package.py).
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
from decimal import ROUND_HALF_UP, Decimal
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
from .package import WEIGHT_SETTINGS, Package
|
||||||
|
|
||||||
|
QUOTE_URL = 'https://www.jadlog.com.br/embarcador/api/frete/valor'
|
||||||
|
PACKAGE = 3
|
||||||
|
ORIGIN = '14402310'
|
||||||
|
SERVICE = 'jadlog'
|
||||||
|
class JadlogError(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def digits(value):
|
||||||
|
return ''.join(ch for ch in str(value or '') if ch.isdigit())
|
||||||
|
|
||||||
|
|
||||||
|
class JadlogQuotes:
|
||||||
|
def __init__(self, token=None, cnpj=None, conta=None, contrato=None, origin=None,
|
||||||
|
modalidade=None, transport=None):
|
||||||
|
self.token = (token or os.environ.get('JADLOG_TOKEN', '')).strip()
|
||||||
|
self.cnpj = digits(cnpj or os.environ.get('JADLOG_CNPJ'))
|
||||||
|
# Sent as configured: Jadlog issues it as 000000-0 and documents six
|
||||||
|
# characters, so which form it accepts is only known on the account.
|
||||||
|
self.conta = (conta if conta is not None else os.environ.get('JADLOG_CONTA', '')).strip()
|
||||||
|
# Only when Jadlog issued one; the manual says to send null otherwise.
|
||||||
|
self.contrato = (contrato if contrato is not None else os.environ.get('JADLOG_CONTRATO', '')).strip() or None
|
||||||
|
self.origin = digits(origin or os.environ.get('JADLOG_ORIGEM_CEP') or ORIGIN)
|
||||||
|
self.modalidade = int(modalidade or os.environ.get('JADLOG_MODALIDADE') or PACKAGE)
|
||||||
|
if not self.token or len(self.cnpj) != 14:
|
||||||
|
raise RuntimeError('Jadlog needs JADLOG_TOKEN and a 14-digit JADLOG_CNPJ')
|
||||||
|
self.http = httpx.Client(timeout=20, transport=transport)
|
||||||
|
|
||||||
|
def item(self, postal_code, weight_kg, declared_cents):
|
||||||
|
return {'cepori': self.origin, 'cepdes': digits(postal_code), 'frap': 'N',
|
||||||
|
'peso': float(weight_kg), 'cnpj': self.cnpj, 'conta': self.conta,
|
||||||
|
'contrato': self.contrato, 'modalidade': self.modalidade,
|
||||||
|
'tpentrega': 'D', 'tpseguro': 'N',
|
||||||
|
'vldeclarado': declared_cents / 100, 'vlcoleta': 0}
|
||||||
|
|
||||||
|
def quote(self, postal_code, weight_kg, declared_cents):
|
||||||
|
"""Price in centavos and delivery days for one package to one CEP."""
|
||||||
|
response = self.http.post(QUOTE_URL, json={'frete': [self.item(postal_code, weight_kg, declared_cents)]},
|
||||||
|
headers={'Authorization': self.token})
|
||||||
|
if response.status_code == 401:
|
||||||
|
raise JadlogError('Jadlog refused the token (HTTP 401)')
|
||||||
|
try:
|
||||||
|
data = response.json()
|
||||||
|
except ValueError:
|
||||||
|
raise JadlogError(f'HTTP {response.status_code}: the response is not JSON') from None
|
||||||
|
items = data.get('frete') or []
|
||||||
|
# The manual names the group "erro" in its tables and "error" in its
|
||||||
|
# examples, at the top level and per item.
|
||||||
|
problem = data.get('error') or data.get('erro')
|
||||||
|
if not problem and items:
|
||||||
|
problem = items[0].get('erro') or items[0].get('error')
|
||||||
|
if problem:
|
||||||
|
raise JadlogError(problem.get('descricao') or str(problem) if isinstance(problem, dict) else str(problem))
|
||||||
|
if response.status_code >= 400 or not items or items[0].get('vltotal') is None:
|
||||||
|
raise JadlogError(f'HTTP {response.status_code}: no freight value in the response')
|
||||||
|
total = Decimal(str(items[0]['vltotal']))
|
||||||
|
return {'total_cents': int((total * 100).quantize(Decimal('1'), ROUND_HALF_UP)),
|
||||||
|
'days': items[0].get('prazo'), 'raw': items[0]}
|
||||||
|
|
||||||
|
|
||||||
|
def required_settings():
|
||||||
|
return ('JADLOG_TOKEN', 'JADLOG_CNPJ') + WEIGHT_SETTINGS
|
||||||
|
|
||||||
|
|
||||||
|
class JadlogFreight(Package):
|
||||||
|
"""The Site's Jadlog option: Jadlog's price for the order's package."""
|
||||||
|
name = 'jadlog'
|
||||||
|
services = {SERVICE: 'Jadlog'}
|
||||||
|
|
||||||
|
def __init__(self, quotes=None):
|
||||||
|
super().__init__()
|
||||||
|
self.quotes = quotes or JadlogQuotes()
|
||||||
|
|
||||||
|
def quote(self, service, postal_code, metres=None, declared_cents=0):
|
||||||
|
if service == 'pickup':
|
||||||
|
return {'provider': self.name, 'service': 'pickup', 'total_cents': 0, 'postal_code': ''}
|
||||||
|
if service != SERVICE or len(postal_code) != 8 or not postal_code.isascii() or not postal_code.isdigit():
|
||||||
|
raise ValueError('Select pickup or Jadlog delivery with an eight-digit CEP')
|
||||||
|
if metres is None or Decimal(str(metres)) <= 0:
|
||||||
|
raise ValueError('The order length is required to quote freight')
|
||||||
|
weight, real = self.weight_kg(metres), self.real_kg(metres)
|
||||||
|
try:
|
||||||
|
result = self.quotes.quote(postal_code, weight, int(declared_cents))
|
||||||
|
except (JadlogError, httpx.HTTPError) as error:
|
||||||
|
raise ValueError(f'Não foi possível cotar o frete na Jadlog agora: {error}') from None
|
||||||
|
days = result['days']
|
||||||
|
return {'provider': self.name, 'service': SERVICE, 'postal_code': postal_code,
|
||||||
|
'total_cents': result['total_cents'], 'weight_kg': str(weight), 'real_kg': str(real),
|
||||||
|
'boxes': self.boxes(metres),
|
||||||
|
'days': None if days is None else int(days) + self.production_days,
|
||||||
|
'description': self.services[SERVICE]}
|
||||||
80
app/jadlog_probe.py
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
"""Read-only price check against the client's real Jadlog account, run by hand.
|
||||||
|
A quote creates no shipment and costs nothing.
|
||||||
|
|
||||||
|
python -m app.jadlog_probe [--cep 01310100 ...] [--peso 0.5 ...] [--valor 100]
|
||||||
|
|
||||||
|
Without --cep and --peso it prices a few test weights to a few regions. It
|
||||||
|
answers whether the token, CNPJ and account are accepted, whether a contract
|
||||||
|
number is required (Jadlog names it in the error), and what the contract
|
||||||
|
prices and delivery times are. The first failure stops the run: an account
|
||||||
|
problem would repeat on every line.
|
||||||
|
|
||||||
|
In production, from the worker's console (Portainer > Containers > worker >
|
||||||
|
Console), with JADLOG_TOKEN, JADLOG_CNPJ and JADLOG_CONTA in the stack:
|
||||||
|
|
||||||
|
python -m app.jadlog_probe
|
||||||
|
|
||||||
|
Locally, with the credentials in jadlog.env (ignored by git):
|
||||||
|
|
||||||
|
docker compose -f compose.local.yaml -f compose.providers.yaml run --rm --no-deps --build \\
|
||||||
|
--env-from-file jadlog.env worker python -m app.jadlog_probe
|
||||||
|
"""
|
||||||
|
import argparse
|
||||||
|
import sys
|
||||||
|
from decimal import Decimal
|
||||||
|
|
||||||
|
from .core.secrets import load as load_secret_files
|
||||||
|
from .jadlog import JadlogError, JadlogQuotes
|
||||||
|
|
||||||
|
DESTINATIONS = {'14402310': 'Franca (origem)', '01310100': 'São Paulo', '20040002': 'Rio de Janeiro',
|
||||||
|
'80010000': 'Curitiba', '50030230': 'Recife', '69005010': 'Manaus'}
|
||||||
|
WEIGHTS = ['0.3', '0.5', '1', '2', '5']
|
||||||
|
|
||||||
|
|
||||||
|
def money(cents):
|
||||||
|
return f'R$ {cents / 100:.2f}'.replace('.', ',')
|
||||||
|
|
||||||
|
|
||||||
|
def run(quotes, ceps, weights, declared_cents, out):
|
||||||
|
header = quotes.token
|
||||||
|
for weight in weights:
|
||||||
|
for cep in ceps:
|
||||||
|
try:
|
||||||
|
result = quotes.quote(cep, Decimal(weight), declared_cents)
|
||||||
|
except JadlogError as error:
|
||||||
|
# The manual shows the header as the bare token; some accounts
|
||||||
|
# are issued one that expects the Bearer scheme.
|
||||||
|
if '401' in str(error) and not header.lower().startswith('bearer '):
|
||||||
|
quotes.token = 'Bearer ' + header
|
||||||
|
header = quotes.token
|
||||||
|
try:
|
||||||
|
result = quotes.quote(cep, Decimal(weight), declared_cents)
|
||||||
|
except JadlogError as retry:
|
||||||
|
out(f'ERRO {cep} {weight} kg: {retry} (also with "Bearer ")')
|
||||||
|
return 1
|
||||||
|
out('Note: the token only works with the "Bearer " prefix.')
|
||||||
|
else:
|
||||||
|
out(f'ERRO {cep} {weight} kg: {error}')
|
||||||
|
return 1
|
||||||
|
days = result['days']
|
||||||
|
out(f"{weight} kg\t{cep}\t{DESTINATIONS.get(cep, '')}\t{money(result['total_cents'])}\t"
|
||||||
|
f"{days if days is not None else '?'} dia(s)")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv=None):
|
||||||
|
parser = argparse.ArgumentParser(prog='python -m app.jadlog_probe')
|
||||||
|
parser.add_argument('--cep', action='append', help='destination CEP (repeatable)')
|
||||||
|
parser.add_argument('--peso', action='append', help='weight in kg (repeatable)')
|
||||||
|
parser.add_argument('--valor', default='100', help='declared value in reais (default 100)')
|
||||||
|
args = parser.parse_args(argv)
|
||||||
|
load_secret_files()
|
||||||
|
quotes = JadlogQuotes()
|
||||||
|
declared = int(Decimal(args.valor) * 100)
|
||||||
|
print(f'Origem {quotes.origin}, modalidade {quotes.modalidade}, contrato {quotes.contrato or "-"}, '
|
||||||
|
f'valor declarado {money(declared)}')
|
||||||
|
return run(quotes, args.cep or list(DESTINATIONS), args.peso or WEIGHTS, declared, print)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
sys.exit(main())
|
||||||
106
app/machines.py
Normal file
@@ -0,0 +1,106 @@
|
|||||||
|
"""The print machines: which one each order goes to, and how loaded each is.
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
# Not finished: the work still ahead of a machine.
|
||||||
|
OPEN = ('rec', 'tra', 'fil', 'imp', 'cor')
|
||||||
|
# Stages an automatic order may still move from: not once it is printing.
|
||||||
|
MOVABLE = ('rec', 'tra', 'fil', 'cor')
|
||||||
|
# One routing at a time, so two at once cannot both pick the same "least loaded".
|
||||||
|
LOCK = 7_041_901
|
||||||
|
|
||||||
|
|
||||||
|
def product_family(order):
|
||||||
|
"""Têxtil or UV, by the order's first item: what a machine prints."""
|
||||||
|
items = (order.get('snapshot') or {}).get('items') or [{}]
|
||||||
|
return 'uv' if items[0].get('mode') in ('uvfile', 'uv') else 'textil'
|
||||||
|
|
||||||
|
|
||||||
|
def order_metres(order):
|
||||||
|
return sum((Decimal(str(i.get('billed_metres') or 0)) for i in (order.get('snapshot') or {}).get('items') or []),
|
||||||
|
Decimal(0))
|
||||||
|
|
||||||
|
|
||||||
|
def loads(c):
|
||||||
|
"""Per machine id: metres and orders still open, and orders per stage."""
|
||||||
|
result = {}
|
||||||
|
for row in c.execute('''SELECT machine_id, state, snapshot FROM dtf_local.orders
|
||||||
|
WHERE machine_id IS NOT NULL AND cancelled_at IS NULL AND state=ANY(%s)''', (list(OPEN),)).fetchall():
|
||||||
|
load = result.setdefault(str(row['machine_id']), {'metres': Decimal(0), 'orders': 0, 'states': {}})
|
||||||
|
load['metres'] += order_metres(row)
|
||||||
|
load['orders'] += 1
|
||||||
|
load['states'][row['state']] = load['states'].get(row['state'], 0) + 1
|
||||||
|
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):
|
||||||
|
"""Every machine with its load, for the Kanban."""
|
||||||
|
machines = c.execute('''SELECT id, name, products, active, limit_metres FROM dtf_local.machines
|
||||||
|
ORDER BY created_at, name''').fetchall()
|
||||||
|
load = loads(c)
|
||||||
|
operators = {}
|
||||||
|
if with_operators:
|
||||||
|
for r in c.execute('''SELECT om.machine_id, o.id, o.name, o.email FROM dtf_local.operator_machines om
|
||||||
|
JOIN dtf_local.operators o ON o.id=om.operator_id ORDER BY o.name, o.email''').fetchall():
|
||||||
|
operators.setdefault(str(r['machine_id']), []).append({'id': str(r['id']), 'name': r['name'] or r['email']})
|
||||||
|
result = []
|
||||||
|
for m in machines:
|
||||||
|
key = str(m['id'])
|
||||||
|
used = load.get(key, {'metres': Decimal(0), 'orders': 0, 'states': {}})
|
||||||
|
row = {'id': key, 'name': m['name'], 'products': m['products'], 'active': m['active'],
|
||||||
|
'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']}
|
||||||
|
if with_operators:
|
||||||
|
row['operators'] = operators.get(key, [])
|
||||||
|
result.append(row)
|
||||||
|
return result
|
||||||
185
app/mail.py
Normal file
@@ -0,0 +1,185 @@
|
|||||||
|
"""E-mail: the customers' account messages and order confirmation.
|
||||||
|
|
||||||
|
Messages are queued in the database inside the transaction that caused them
|
||||||
|
(an order paid, a password to recover) and sent by the worker, so a slow
|
||||||
|
or unreachable mail server never holds up a request and a failed send is
|
||||||
|
retried. MAIL_ADAPTER chooses where they go:
|
||||||
|
|
||||||
|
off nothing is queued and recovery offers WhatsApp instead (the default,
|
||||||
|
until the client's SMTP details arrive);
|
||||||
|
log kept in the database and written to the worker's log, for the local
|
||||||
|
stack, where there is no mail server;
|
||||||
|
smtp sent through SMTP_HOST as MAIL_FROM.
|
||||||
|
|
||||||
|
A recovery link or a signup code lets someone in, so its text is erased once
|
||||||
|
it is sent (or once it expired unsent); only its subject stays as a record.
|
||||||
|
Customer messages carry an HTML version (app/mail_html.py) beside the plain
|
||||||
|
text.
|
||||||
|
"""
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import smtplib
|
||||||
|
import ssl
|
||||||
|
from email.message import EmailMessage
|
||||||
|
from email.utils import formataddr, formatdate, make_msgid, parseaddr
|
||||||
|
|
||||||
|
ADAPTER = os.environ.get('MAIL_ADAPTER', 'off')
|
||||||
|
RESET_MINUTES = 60
|
||||||
|
CODE_MINUTES = 15
|
||||||
|
# Messages that let someone in: their text is erased once sent, or once they
|
||||||
|
# expired unsent (minutes).
|
||||||
|
SECRET_KINDS = {'reset': RESET_MINUTES, 'code': CODE_MINUTES}
|
||||||
|
MAX_ATTEMPTS = 12
|
||||||
|
|
||||||
|
log = logging.getLogger('dtf.mail')
|
||||||
|
|
||||||
|
|
||||||
|
def configured():
|
||||||
|
return ADAPTER in ('log', 'smtp')
|
||||||
|
|
||||||
|
|
||||||
|
def required_settings():
|
||||||
|
return ('SMTP_HOST', 'MAIL_FROM')
|
||||||
|
|
||||||
|
|
||||||
|
def queue(c, kind, to, subject, body, html=None):
|
||||||
|
"""Queue one message in the caller's transaction. Returns False when e-mail
|
||||||
|
is off, so the caller can say so instead of promising a message."""
|
||||||
|
if not configured():
|
||||||
|
return False
|
||||||
|
c.execute('INSERT INTO dtf_local.mail_queue(kind,to_addr,subject,body,html) VALUES(%s,%s,%s,%s,%s)',
|
||||||
|
(kind, to, subject, body, html))
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def order_paid(c, order, origin):
|
||||||
|
"""The customer's confirmation of a paid order, with a link to it in the
|
||||||
|
account. Not for an operator's test order."""
|
||||||
|
snapshot = order['snapshot']
|
||||||
|
customer = snapshot.get('customer') or {}
|
||||||
|
if not customer.get('mail'):
|
||||||
|
return False
|
||||||
|
from . import mail_html
|
||||||
|
method = 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()
|
||||||
|
paid = {'pix': 'Pix', 'card': 'cartão'}.get((method or {}).get('method'), '')
|
||||||
|
freight = snapshot.get('freight') or {}
|
||||||
|
if freight.get('service') == 'pickup':
|
||||||
|
delivery = 'Retirada em Franca-SP'
|
||||||
|
else:
|
||||||
|
delivery = freight.get('description') or 'Entrega'
|
||||||
|
if freight.get('days'):
|
||||||
|
delivery += f" · até {freight['days']} dias úteis"
|
||||||
|
rows = [('Itens', '\n'.join(f"{PRODUCTS.get(i.get('mode'), i.get('mode'))} · "
|
||||||
|
f"{str(i.get('billed_metres') or i.get('metres')).replace('.', ',')} m"
|
||||||
|
for i in snapshot.get('items', []))),
|
||||||
|
('Entrega', delivery),
|
||||||
|
('Total', money(snapshot.get('total_cents') or 0) + (f' · {paid}' if paid else ''))]
|
||||||
|
number, link = order['number'], f"{origin}/conta/pedidos?order={order['id']}"
|
||||||
|
text = '\n'.join([mail_html.greeting(customer.get('name')), '',
|
||||||
|
f'Seu pagamento foi aprovado e o pedido #{number} já está com a nossa equipe. '
|
||||||
|
'Agora a gente confere a arte e coloca na fila de impressão.', '',
|
||||||
|
*(f'{key}: {value}' for key, value in rows), '',
|
||||||
|
f'Acompanhe cada etapa em Minha conta: {link}', '',
|
||||||
|
'Ainda não tem conta? Crie com este e-mail e o mesmo CPF/CNPJ do pedido: ele aparece lá na hora.'])
|
||||||
|
return queue(c, 'order', customer['mail'], f'Recebemos seu pedido #{number} · DTF Dropstar', text,
|
||||||
|
mail_html.order_paid(customer.get('name'), number, rows, link))
|
||||||
|
|
||||||
|
|
||||||
|
PRODUCTS = {'file': 'DTF Têxtil · folha montada', 'avulsa': 'DTF Têxtil · artes avulsas',
|
||||||
|
'uvfile': 'DTF UV · folha montada', 'uv': 'DTF UV · artes avulsas'}
|
||||||
|
|
||||||
|
|
||||||
|
def money(cents):
|
||||||
|
whole, cents = divmod(int(cents), 100)
|
||||||
|
return 'R$ ' + f'{whole:,}'.replace(',', '.') + f',{cents:02d}'
|
||||||
|
|
||||||
|
|
||||||
|
def message(to, subject, body, html=None):
|
||||||
|
sender = os.environ.get('MAIL_FROM', 'DTF Dropstar <nao-responda@localhost>')
|
||||||
|
name, address = parseaddr(sender)
|
||||||
|
msg = EmailMessage()
|
||||||
|
msg['From'] = formataddr((name or 'DTF Dropstar', address))
|
||||||
|
msg['To'] = to
|
||||||
|
msg['Subject'] = subject
|
||||||
|
# Neither EmailMessage nor smtplib adds it, and filters (Outlook's among them) count it missing.
|
||||||
|
msg['Date'] = formatdate(localtime=True)
|
||||||
|
msg['Message-ID'] = make_msgid(domain=address.split('@')[-1] or None)
|
||||||
|
reply = os.environ.get('MAIL_REPLY_TO', '')
|
||||||
|
if reply:
|
||||||
|
msg['Reply-To'] = reply
|
||||||
|
msg.set_content(body)
|
||||||
|
if html:
|
||||||
|
msg.add_alternative(html, subtype='html')
|
||||||
|
return msg
|
||||||
|
|
||||||
|
|
||||||
|
def send_smtp(msg):
|
||||||
|
host = os.environ['SMTP_HOST']
|
||||||
|
security = os.environ.get('SMTP_SECURITY', 'starttls')
|
||||||
|
port = int(os.environ.get('SMTP_PORT') or (465 if security == 'ssl' else 587))
|
||||||
|
user, password = os.environ.get('SMTP_USER', ''), os.environ.get('SMTP_PASSWORD', '')
|
||||||
|
context = ssl.create_default_context()
|
||||||
|
if security == 'ssl':
|
||||||
|
server = smtplib.SMTP_SSL(host, port, timeout=20, context=context)
|
||||||
|
else:
|
||||||
|
server = smtplib.SMTP(host, port, timeout=20)
|
||||||
|
with server:
|
||||||
|
if security == 'starttls':
|
||||||
|
server.starttls(context=context)
|
||||||
|
if user:
|
||||||
|
server.login(user, password)
|
||||||
|
server.send_message(msg)
|
||||||
|
|
||||||
|
|
||||||
|
def deliver(row):
|
||||||
|
msg = message(row['to_addr'], row['subject'], row['body'], row.get('html'))
|
||||||
|
if ADAPTER == 'smtp':
|
||||||
|
send_smtp(msg)
|
||||||
|
else:
|
||||||
|
log.warning('mail (%s) to %s: %s', ADAPTER, row['to_addr'], row['subject'])
|
||||||
|
|
||||||
|
|
||||||
|
def send_pending(connect, limit=5, ids=None):
|
||||||
|
"""Send what is due, a few at a time. Called by the worker every second;
|
||||||
|
`ids` sends just those messages, due or not (the tests use it)."""
|
||||||
|
if not configured():
|
||||||
|
return
|
||||||
|
with connect() as c:
|
||||||
|
# A link or a code that expired before it could be sent is useless.
|
||||||
|
for kind, minutes in SECRET_KINDS.items():
|
||||||
|
c.execute("""UPDATE dtf_local.mail_queue SET body='', html=NULL, last_error='expirou sem ser enviado', failed_at=now()
|
||||||
|
WHERE kind=%s AND sent_at IS NULL AND failed_at IS NULL
|
||||||
|
AND created_at < now() - %s * interval '1 minute'""", (kind, minutes))
|
||||||
|
rows = c.execute('''SELECT * FROM dtf_local.mail_queue WHERE sent_at IS NULL AND failed_at IS NULL
|
||||||
|
AND (id = ANY(%s) OR (%s::bigint[] IS NULL AND available_at <= now()))
|
||||||
|
ORDER BY id FOR UPDATE SKIP LOCKED LIMIT %s''', (ids or [], ids, limit)).fetchall()
|
||||||
|
for row in rows:
|
||||||
|
try:
|
||||||
|
deliver(row)
|
||||||
|
except Exception as exc:
|
||||||
|
attempts = row['attempts'] + 1
|
||||||
|
gave_up = attempts >= MAX_ATTEMPTS
|
||||||
|
c.execute('''UPDATE dtf_local.mail_queue SET attempts=%s, last_error=%s,
|
||||||
|
available_at=now() + %s * interval '1 second',
|
||||||
|
failed_at=CASE WHEN %s THEN now() END WHERE id=%s''',
|
||||||
|
(attempts, str(exc)[:500], min(3600, 2 ** min(attempts + 3, 12)), gave_up, row['id']))
|
||||||
|
log.warning('mail to %s failed (attempt %s): %s', row['to_addr'], attempts, exc)
|
||||||
|
continue
|
||||||
|
# The local log keeps the text so the link can be followed by hand.
|
||||||
|
erase = row['kind'] in SECRET_KINDS and ADAPTER != 'log'
|
||||||
|
c.execute('''UPDATE dtf_local.mail_queue SET sent_at=now(), attempts=attempts+1, last_error=NULL,
|
||||||
|
body=CASE WHEN %s THEN '' ELSE body END, html=CASE WHEN %s THEN NULL ELSE html END
|
||||||
|
WHERE id=%s''', (erase, erase, row['id']))
|
||||||
|
|
||||||
|
|
||||||
|
def status(c):
|
||||||
|
"""What the Kanban's Integrações shows about e-mail."""
|
||||||
|
last = c.execute('SELECT max(sent_at) AS at FROM dtf_local.mail_queue').fetchone()['at']
|
||||||
|
failing = c.execute('''SELECT to_addr, last_error, created_at FROM dtf_local.mail_queue
|
||||||
|
WHERE sent_at IS NULL AND last_error IS NOT NULL ORDER BY id DESC LIMIT 1''').fetchone()
|
||||||
|
pending = c.execute('SELECT count(*) AS n FROM dtf_local.mail_queue WHERE sent_at IS NULL AND failed_at IS NULL').fetchone()['n']
|
||||||
|
return {'adapter': ADAPTER, 'from': os.environ.get('MAIL_FROM', '') if configured() else '',
|
||||||
|
'host': os.environ.get('SMTP_HOST', '') if ADAPTER == 'smtp' else '',
|
||||||
|
'last_sent': last, 'pending': pending,
|
||||||
|
'error': {'to': failing['to_addr'], 'error': failing['last_error'], 'at': failing['created_at']} if failing else None}
|
||||||
203
app/mail_html.py
Normal file
@@ -0,0 +1,203 @@
|
|||||||
|
"""The customer e-mails' HTML, next to the plain text every message keeps.
|
||||||
|
|
||||||
|
Built for mail clients, not browsers: tables for layout, every style inline,
|
||||||
|
no web fonts or images (Outlook ignores flex, many clients block images until
|
||||||
|
asked), so it reads the same in Gmail, Outlook and phone apps. The look is
|
||||||
|
the Site's: the DROPSTAR wordmark in orange on black, a white card, orange
|
||||||
|
buttons. Every value put in is escaped here; callers pass plain text.
|
||||||
|
"""
|
||||||
|
from html import escape
|
||||||
|
|
||||||
|
ORANGE, INK, DARK_ORANGE = '#FFA81A', '#03060B', '#C25E00'
|
||||||
|
TEXT, MUTED, LINE = '#3A3733', '#5E5A54', '#ECE8E2'
|
||||||
|
FONT = "Inter, 'Helvetica Neue', Helvetica, Arial, sans-serif"
|
||||||
|
WHATSAPP = 'https://wa.me/5516994280056'
|
||||||
|
|
||||||
|
|
||||||
|
def greeting(name):
|
||||||
|
first = (name or '').split()
|
||||||
|
return f'Olá, {first[0]}!' if first else 'Olá!'
|
||||||
|
|
||||||
|
|
||||||
|
def layout(preheader, label, blocks):
|
||||||
|
"""The whole message: the dark header, the card holding `blocks` (already
|
||||||
|
HTML), and the footer. The preheader is the line inboxes show after the
|
||||||
|
subject."""
|
||||||
|
rows = ''.join(f'<tr><td style="padding:0 0 20px 0">{block}</td></tr>' for block in blocks)
|
||||||
|
return f'''<!doctype html>
|
||||||
|
<html lang="pt-BR">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||||
|
<meta name="color-scheme" content="light">
|
||||||
|
<title>DTF Dropstar</title>
|
||||||
|
</head>
|
||||||
|
<body style="margin:0;padding:0;background:#EEEBE6">
|
||||||
|
<div style="display:none;max-height:0;overflow:hidden;opacity:0">{escape(preheader)}</div>
|
||||||
|
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background:#EEEBE6">
|
||||||
|
<tr><td align="center" style="padding:32px 12px">
|
||||||
|
<table role="presentation" width="600" cellpadding="0" cellspacing="0" border="0" style="width:100%;max-width:600px;font-family:{FONT}">
|
||||||
|
<tr><td style="background:{INK};border-radius:16px 16px 0 0;padding:22px 32px">
|
||||||
|
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"><tr>
|
||||||
|
<td style="font-family:{FONT};font-size:24px;font-weight:800;font-style:italic;letter-spacing:-0.5px;color:{ORANGE}">DROPSTAR
|
||||||
|
<span style="font-size:12px;font-style:normal;letter-spacing:1px;color:{INK};background:{ORANGE};border-radius:6px;padding:3px 7px;vertical-align:middle">DTF</span></td>
|
||||||
|
<td align="right" style="font-family:{FONT};font-size:12px;font-weight:600;letter-spacing:0.7px;text-transform:uppercase;color:#B9B4AC">{escape(label)}</td>
|
||||||
|
</tr></table>
|
||||||
|
</td></tr>
|
||||||
|
<tr><td style="background:#FFFFFF;border-radius:0 0 16px 16px;padding:36px 36px 16px 36px">
|
||||||
|
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">{rows}</table>
|
||||||
|
</td></tr>
|
||||||
|
<tr><td align="center" style="padding:22px 8px 0 8px;font-family:{FONT};font-size:12.5px;line-height:19px;color:{MUTED}">
|
||||||
|
DTF Dropstar · Franca-SP · WhatsApp <a href="{WHATSAPP}" style="color:{MUTED}">16 99428-0056</a><br>
|
||||||
|
E-mail automático, não precisa responder.
|
||||||
|
</td></tr>
|
||||||
|
</table>
|
||||||
|
</td></tr>
|
||||||
|
</table>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
def title(text):
|
||||||
|
return (f'<h1 style="margin:0;font-family:{FONT};font-size:26px;line-height:32px;font-weight:800;'
|
||||||
|
f'color:{INK}">{escape(text)}</h1>')
|
||||||
|
|
||||||
|
|
||||||
|
def para(text):
|
||||||
|
return f'<p style="margin:0;font-family:{FONT};font-size:16px;line-height:25px;color:{TEXT}">{escape(text)}</p>'
|
||||||
|
|
||||||
|
|
||||||
|
def small(text, html=''):
|
||||||
|
return (f'<p style="margin:0;font-family:{FONT};font-size:13.5px;line-height:21px;color:{MUTED}">'
|
||||||
|
f'{escape(text)}{html}</p>')
|
||||||
|
|
||||||
|
|
||||||
|
def pill(text, tone='ok'):
|
||||||
|
background, color = {'ok': ('#E7F4EA', '#1E6B34'), 'info': ('#FFF4E0', DARK_ORANGE)}[tone]
|
||||||
|
return (f'<span style="display:inline-block;font-family:{FONT};font-size:12.5px;font-weight:700;'
|
||||||
|
f'letter-spacing:0.7px;text-transform:uppercase;background:{background};color:{color};'
|
||||||
|
f'border-radius:999px;padding:5px 11px">{escape(text)}</span>')
|
||||||
|
|
||||||
|
|
||||||
|
def code_box(code):
|
||||||
|
spaced = ' '.join(escape(code))
|
||||||
|
return (f'<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">'
|
||||||
|
f'<tr><td align="center" style="background:#FFF4E0;border:1px solid #F5D9A8;border-radius:12px;padding:22px">'
|
||||||
|
f'<div style="font-family:{FONT};font-size:12px;font-weight:700;letter-spacing:1.2px;'
|
||||||
|
f'text-transform:uppercase;color:{DARK_ORANGE}">Seu código</div>'
|
||||||
|
f'<div style="font-family:{FONT};font-size:38px;line-height:48px;font-weight:800;letter-spacing:6px;'
|
||||||
|
f'color:{INK}">{spaced}</div></td></tr></table>')
|
||||||
|
|
||||||
|
|
||||||
|
def button(text, url, dark=False):
|
||||||
|
background, color = (INK, ORANGE) if dark else (ORANGE, '#241703')
|
||||||
|
return (f'<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td align="center">'
|
||||||
|
f'<a href="{escape(url, quote=True)}" style="display:inline-block;background:{background};color:{color};'
|
||||||
|
f'font-family:{FONT};font-size:16px;font-weight:800;text-decoration:none;border-radius:10px;'
|
||||||
|
f'padding:15px 30px">{escape(text)}</a></td></tr></table>')
|
||||||
|
|
||||||
|
|
||||||
|
def facts(rows):
|
||||||
|
cells = ''.join(
|
||||||
|
f'<tr><td style="{"" if i == 0 else f"border-top:1px solid {LINE};"}padding:12px 16px;width:92px;'
|
||||||
|
f'vertical-align:top;font-family:{FONT};font-size:15px;font-weight:600;color:{MUTED}">{escape(key)}</td>'
|
||||||
|
f'<td style="{"" if i == 0 else f"border-top:1px solid {LINE};"}padding:12px 16px 12px 0;'
|
||||||
|
f'font-family:{FONT};font-size:15px;line-height:22px;font-weight:500;color:{INK};white-space:pre-line">{escape(value)}</td></tr>'
|
||||||
|
for i, (key, value) in enumerate(rows))
|
||||||
|
return (f'<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" '
|
||||||
|
f'style="border:1px solid {LINE};border-radius:12px;border-collapse:separate">{cells}</table>')
|
||||||
|
|
||||||
|
|
||||||
|
def callout(heading, text, warn=False):
|
||||||
|
background, border, color = ('#FFF1EC', '#F4C7B6', '#8A2A0A') if warn else ('#F4F2EE', '#E4DFD8', TEXT)
|
||||||
|
return (f'<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"><tr>'
|
||||||
|
f'<td style="background:{background};border:1px solid {border};border-radius:12px;padding:16px 18px">'
|
||||||
|
f'<div style="font-family:{FONT};font-size:15px;font-weight:700;color:{color}">{escape(heading)}</div>'
|
||||||
|
f'<div style="font-family:{FONT};font-size:14.5px;line-height:22px;color:{TEXT};padding-top:4px">'
|
||||||
|
f'{escape(text)}</div></td></tr></table>')
|
||||||
|
|
||||||
|
|
||||||
|
def steps(items):
|
||||||
|
"""The order's stages: (label, hint, done)."""
|
||||||
|
rows = []
|
||||||
|
for i, (label, hint, done) in enumerate(items):
|
||||||
|
top = '' if i == 0 else 'border-top:1px solid #F1EDE7;'
|
||||||
|
mark = (f'<div style="width:24px;height:24px;line-height:24px;border-radius:12px;background:{ORANGE};'
|
||||||
|
f'color:#241703;font-family:{FONT};font-size:14px;font-weight:800;text-align:center">✓</div>'
|
||||||
|
if done else
|
||||||
|
'<div style="width:20px;height:20px;border-radius:12px;border:2px solid #D9D3CB;background:#FFFFFF"></div>')
|
||||||
|
rows.append(f'<tr><td style="{top}padding:11px 14px 11px 0;width:24px;vertical-align:middle">{mark}</td>'
|
||||||
|
f'<td style="{top}padding:11px 0;font-family:{FONT}">'
|
||||||
|
f'<div style="font-size:15px;font-weight:{700 if done else 500};color:{INK if done else MUTED}">'
|
||||||
|
f'{escape(label)}</div><div style="font-size:13px;line-height:19px;color:{MUTED}">{escape(hint)}</div>'
|
||||||
|
f'</td></tr>')
|
||||||
|
return (f'<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" '
|
||||||
|
f'style="border:1px solid {LINE};border-radius:12px;border-collapse:separate;padding:4px 16px">'
|
||||||
|
f'{"".join(rows)}</table>')
|
||||||
|
|
||||||
|
|
||||||
|
# The messages ---------------------------------------------------------------
|
||||||
|
|
||||||
|
def code(name, heading, purpose, digits, minutes, ignore):
|
||||||
|
return layout(f'{digits} é o seu código', 'Sua conta', [
|
||||||
|
title(heading),
|
||||||
|
para(f'{greeting(name)} Use o código abaixo para {purpose}.'),
|
||||||
|
code_box(digits),
|
||||||
|
small(f'O código vale por {minutes} minutos. Se não foi você que pediu, ignore este e-mail: {ignore}'),
|
||||||
|
])
|
||||||
|
|
||||||
|
|
||||||
|
def reset(name, link, minutes):
|
||||||
|
hours = 'por 1 hora' if minutes == 60 else f'por {minutes} minutos'
|
||||||
|
return layout('Clique no botão para criar uma nova senha.', 'Sua conta', [
|
||||||
|
title('Crie uma nova senha'),
|
||||||
|
para(f'{greeting(name)} Recebemos um pedido para criar uma nova senha na sua conta. '
|
||||||
|
'É só clicar no botão abaixo.'),
|
||||||
|
button('Criar nova senha', link),
|
||||||
|
small(f'O link vale {hours} e funciona uma vez só. Se não foi você, ignore este e-mail: '
|
||||||
|
'sua senha continua a mesma.'),
|
||||||
|
small('O botão não abriu? Copie este endereço no navegador: ',
|
||||||
|
f'<br><a href="{escape(link, quote=True)}" style="color:{DARK_ORANGE};word-break:break-all">'
|
||||||
|
f'{escape(link)}</a>'),
|
||||||
|
])
|
||||||
|
|
||||||
|
|
||||||
|
def account_exists(name, login_link):
|
||||||
|
return layout('Este e-mail já tem conta no DTF Dropstar.', 'Sua conta', [
|
||||||
|
title('Este e-mail já tem uma conta'),
|
||||||
|
para(f'{greeting(name)} Alguém tentou criar uma conta no DTF Dropstar com este e-mail, mas ele já está '
|
||||||
|
'cadastrado. Para ver seus pedidos, é só entrar.'),
|
||||||
|
button('Entrar na minha conta', login_link),
|
||||||
|
callout('Esqueceu a senha?', 'Na página de entrada, clique em “Esqueci minha senha” e enviamos um link '
|
||||||
|
'para criar outra.'),
|
||||||
|
small('Se não foi você, ignore este e-mail: nada muda na sua conta.'),
|
||||||
|
])
|
||||||
|
|
||||||
|
|
||||||
|
def email_changed(name, old, new):
|
||||||
|
return layout('O e-mail da sua conta foi trocado.', 'Sua conta', [
|
||||||
|
title('O e-mail da sua conta foi trocado'),
|
||||||
|
para(f'{greeting(name)} A partir de agora, sua conta no DTF Dropstar entra com outro e-mail:'),
|
||||||
|
facts([('Antes', old), ('Agora', new)]),
|
||||||
|
callout('Não foi você?', 'Fale com a Dropstar agora pelo WhatsApp: a gente ajuda a recuperar a conta.',
|
||||||
|
warn=True),
|
||||||
|
button('Falar no WhatsApp', WHATSAPP, dark=True),
|
||||||
|
])
|
||||||
|
|
||||||
|
|
||||||
|
def order_paid(name, number, rows, link):
|
||||||
|
return layout(f'Pagamento aprovado. O pedido #{number} já está com a nossa equipe.', 'Seu pedido', [
|
||||||
|
pill('Pagamento aprovado'),
|
||||||
|
title(f'Recebemos seu pedido #{number}'),
|
||||||
|
para(f'{greeting(name)} Seu pagamento foi aprovado e o pedido já está com a nossa equipe. Agora a gente '
|
||||||
|
'confere a arte e coloca na fila de impressão.'),
|
||||||
|
facts(rows),
|
||||||
|
steps([('Pagamento aprovado', 'Pedido recebido pela equipe', True),
|
||||||
|
('Arte conferida', 'A equipe confere se está tudo certo para imprimir', False),
|
||||||
|
('Impressão', 'Seu filme entra na máquina', False),
|
||||||
|
('Pronto', 'Você recebe o aviso pelo WhatsApp', False)]),
|
||||||
|
button('Ver meu pedido', link),
|
||||||
|
small('Acompanhe cada etapa em Minha conta. Ainda não tem conta? Crie com este e-mail e o mesmo CPF/CNPJ '
|
||||||
|
'do pedido: ele aparece lá na hora.'),
|
||||||
|
])
|
||||||
@@ -21,6 +21,7 @@ import hmac
|
|||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
import time
|
import time
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
from decimal import Decimal, InvalidOperation
|
from decimal import Decimal, InvalidOperation
|
||||||
from typing import Mapping
|
from typing import Mapping
|
||||||
|
|
||||||
@@ -35,6 +36,9 @@ MAX_SIGNATURE_AGE = 30 * 60
|
|||||||
STATUSES = {'approved': 'approved', 'pending': 'pending', 'in_process': 'pending',
|
STATUSES = {'approved': 'approved', 'pending': 'pending', 'in_process': 'pending',
|
||||||
'authorized': 'pending', 'in_mediation': 'pending', 'rejected': 'rejected',
|
'authorized': 'pending', 'in_mediation': 'pending', 'rejected': 'rejected',
|
||||||
'cancelled': 'cancelled', 'refunded': 'refunded', 'charged_back': 'refunded'}
|
'cancelled': 'cancelled', 'refunded': 'refunded', 'charged_back': 'refunded'}
|
||||||
|
# A PIX code stops working after this; Mercado Pago then cancels the payment.
|
||||||
|
PIX_MINUTES = 30
|
||||||
|
BRASILIA = timezone(timedelta(hours=-3))
|
||||||
|
|
||||||
|
|
||||||
class MercadoPagoPayment:
|
class MercadoPagoPayment:
|
||||||
@@ -43,7 +47,13 @@ class MercadoPagoPayment:
|
|||||||
def __init__(self, access_token=None, webhook_secret=None, notification_url=None,
|
def __init__(self, access_token=None, webhook_secret=None, notification_url=None,
|
||||||
transport=None, clock=time.time):
|
transport=None, clock=time.time):
|
||||||
self.access_token = access_token or os.environ.get('MP_ACCESS_TOKEN', '')
|
self.access_token = access_token or os.environ.get('MP_ACCESS_TOKEN', '')
|
||||||
self.webhook_secret = (webhook_secret or os.environ.get('MP_WEBHOOK_SECRET', '')).encode()
|
# Trimmed: a space or line break pasted with the secret into the stack
|
||||||
|
# changes every HMAC, and Mercado Pago's own secret has none.
|
||||||
|
raw_secret = webhook_secret or os.environ.get('MP_WEBHOOK_SECRET', '')
|
||||||
|
self.webhook_secret = raw_secret.strip().encode()
|
||||||
|
self.secret_was_trimmed = raw_secret != raw_secret.strip()
|
||||||
|
# Which signed text matched the last notification verified (see verify).
|
||||||
|
self.last_signature = None
|
||||||
self.notification_url = notification_url or os.environ.get('MP_NOTIFICATION_URL', '')
|
self.notification_url = notification_url or os.environ.get('MP_NOTIFICATION_URL', '')
|
||||||
if not self.access_token or not self.webhook_secret:
|
if not self.access_token or not self.webhook_secret:
|
||||||
raise RuntimeError('Mercado Pago needs MP_ACCESS_TOKEN and MP_WEBHOOK_SECRET')
|
raise RuntimeError('Mercado Pago needs MP_ACCESS_TOKEN and MP_WEBHOOK_SECRET')
|
||||||
@@ -67,34 +77,55 @@ class MercadoPagoPayment:
|
|||||||
'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': {'email': customer['mail'],
|
||||||
'identification': {'type': 'CNPJ', 'number': customer['cnpj']}}}
|
'identification': {'type': 'CPF' if len(customer['cnpj']) == 11 else 'CNPJ',
|
||||||
|
'number': 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
|
||||||
if method['type'] == 'pix':
|
if method['type'] == 'pix':
|
||||||
body['payment_method_id'] = 'pix'
|
body['payment_method_id'] = 'pix'
|
||||||
|
expires_at = (datetime.now(BRASILIA) + timedelta(minutes=PIX_MINUTES)).isoformat(timespec='milliseconds')
|
||||||
|
body['date_of_expiration'] = expires_at
|
||||||
elif method['type'] == 'card':
|
elif method['type'] == 'card':
|
||||||
body.update(token=method['token'], payment_method_id=method['payment_method_id'],
|
body.update(token=method['token'], payment_method_id=method['payment_method_id'],
|
||||||
installments=int(method.get('installments', 1)))
|
installments=int(method.get('installments', 1)))
|
||||||
if method.get('issuer_id'):
|
# 3-D Secure (the bank's confirmation) only for debit, which needs
|
||||||
body['issuer_id'] = method['issuer_id']
|
# it; asking it of every card was refused as a rule (10113).
|
||||||
|
if method['payment_method_id'].startswith('deb'):
|
||||||
|
body['three_d_secure_mode'] = 'optional'
|
||||||
|
if method.get('payer_document_type') and method.get('payer_document'):
|
||||||
|
body['payer']['identification'] = {'type': method['payer_document_type'],
|
||||||
|
'number': method['payer_document']}
|
||||||
|
# No issuer_id: Mercado Pago takes the issuer from the card number.
|
||||||
|
# The form's suggestion was refused for its own test cards
|
||||||
|
# (10111, "the issuer does not have the BIN configured").
|
||||||
else:
|
else:
|
||||||
raise ValueError('Unsupported payment method')
|
raise ValueError('Unsupported payment method')
|
||||||
# A PIX retry must return the same code. A card retry after a decline
|
# A PIX retry must return the same code; a new one, after the last
|
||||||
# is a new attempt with a new token, so the token is part of the key;
|
# expired, is the next attempt. A card retry after a decline is a new
|
||||||
# the intent route refuses new attempts once one is approved or in review.
|
# attempt with a new token, so the token is part of the key; the intent
|
||||||
key = f'dtf-quote-{quote_id}-pix' if method['type'] == 'pix' else \
|
# route refuses new attempts once one is approved or in review.
|
||||||
|
key = f"dtf-quote-{quote_id}-pix-{int(method.get('attempt', 1))}" if method['type'] == 'pix' else \
|
||||||
f"dtf-quote-{quote_id}-card-{hashlib.sha256(method['token'].encode()).hexdigest()[:24]}"
|
f"dtf-quote-{quote_id}-card-{hashlib.sha256(method['token'].encode()).hexdigest()[:24]}"
|
||||||
response = self.http.post('/v1/payments', json=body, headers={'X-Idempotency-Key': key})
|
response = self.http.post('/v1/payments', json=body, headers={'X-Idempotency-Key': key})
|
||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
payment = response.json()
|
payment = response.json()
|
||||||
transaction = (payment.get('point_of_interaction') or {}).get('transaction_data') or {}
|
transaction = (payment.get('point_of_interaction') or {}).get('transaction_data') or {}
|
||||||
|
# A payment waiting for 3-D Secure carries the bank's challenge page,
|
||||||
|
# which the Site shows in a frame by posting `creq` to that address.
|
||||||
|
three_ds = payment.get('three_ds_info') or {}
|
||||||
|
challenge = ({'url': three_ds['external_resource_url'], 'creq': three_ds['creq']}
|
||||||
|
if payment.get('status_detail') == 'pending_challenge'
|
||||||
|
and three_ds.get('external_resource_url') and three_ds.get('creq') else None)
|
||||||
return {'provider': self.name, 'id': str(payment['id']),
|
return {'provider': self.name, 'id': str(payment['id']),
|
||||||
'status': STATUSES.get(payment.get('status'), 'pending'),
|
'status': STATUSES.get(payment.get('status'), 'pending'),
|
||||||
'status_detail': payment.get('status_detail'),
|
'status_detail': payment.get('status_detail'),
|
||||||
'total_cents': total_cents,
|
'total_cents': total_cents,
|
||||||
'pix_qr_code': transaction.get('qr_code'),
|
'pix_qr_code': transaction.get('qr_code'),
|
||||||
'pix_qr_code_base64': transaction.get('qr_code_base64'),
|
'pix_qr_code_base64': transaction.get('qr_code_base64'),
|
||||||
'ticket_url': transaction.get('ticket_url')}
|
'ticket_url': transaction.get('ticket_url'),
|
||||||
|
'expires_at': payment.get('date_of_expiration') or expires_at,
|
||||||
|
'challenge': challenge}
|
||||||
|
|
||||||
def lookup(self, payment_id: str) -> dict:
|
def lookup(self, payment_id: str) -> dict:
|
||||||
response = self.http.get(f'/v1/payments/{payment_id}')
|
response = self.http.get(f'/v1/payments/{payment_id}')
|
||||||
@@ -104,6 +135,12 @@ class MercadoPagoPayment:
|
|||||||
# Webhooks ------------------------------------------------------------
|
# Webhooks ------------------------------------------------------------
|
||||||
|
|
||||||
def verify(self, headers: Mapping[str, str], body: bytes, query: Mapping[str, str] | None = None) -> bool:
|
def verify(self, headers: Mapping[str, str], body: bytes, query: Mapping[str, str] | None = None) -> bool:
|
||||||
|
"""The notification is Mercado Pago's when its x-signature is the HMAC of
|
||||||
|
the documented text (id, request-id, ts) under our secret. A few close
|
||||||
|
variants of that text are also tried, each still needing the secret, so
|
||||||
|
a format that differs from the documentation is accepted and named in
|
||||||
|
self.last_signature rather than silently refused."""
|
||||||
|
self.last_signature = None
|
||||||
signature = headers.get('x-signature') or ''
|
signature = headers.get('x-signature') or ''
|
||||||
parts = dict(part.strip().split('=', 1) for part in signature.split(',') if '=' in part)
|
parts = dict(part.strip().split('=', 1) for part in signature.split(',') if '=' in part)
|
||||||
ts, supplied = parts.get('ts', ''), parts.get('v1', '')
|
ts, supplied = parts.get('ts', ''), parts.get('v1', '')
|
||||||
@@ -111,18 +148,28 @@ class MercadoPagoPayment:
|
|||||||
return False
|
return False
|
||||||
if abs(self.clock() - int(ts[:10])) > MAX_SIGNATURE_AGE:
|
if abs(self.clock() - int(ts[:10])) > MAX_SIGNATURE_AGE:
|
||||||
return False
|
return False
|
||||||
data_id = (query or {}).get('data.id', '')
|
|
||||||
if data_id.isalnum():
|
|
||||||
data_id = data_id.lower()
|
|
||||||
manifest = ''
|
|
||||||
if data_id:
|
|
||||||
manifest += f'id:{data_id};'
|
|
||||||
request_id = headers.get('x-request-id') or ''
|
request_id = headers.get('x-request-id') or ''
|
||||||
if request_id:
|
query_id = (query or {}).get('data.id', '')
|
||||||
|
try:
|
||||||
|
body_id = str(((json.loads(body) or {}).get('data') or {}).get('id') or '')
|
||||||
|
except (ValueError, AttributeError):
|
||||||
|
body_id = ''
|
||||||
|
|
||||||
|
def text(data_id, with_request=True):
|
||||||
|
manifest = f'id:{data_id};' if data_id else ''
|
||||||
|
if with_request and request_id:
|
||||||
manifest += f'request-id:{request_id};'
|
manifest += f'request-id:{request_id};'
|
||||||
manifest += f'ts:{ts};'
|
return manifest + f'ts:{ts};'
|
||||||
|
|
||||||
|
lowered = query_id.lower() if query_id.isalnum() else query_id
|
||||||
|
variants = [('documentado', text(lowered)), ('sem request-id', text(lowered, False)),
|
||||||
|
('id sem minúsculas', text(query_id)), ('id do corpo', text(body_id))]
|
||||||
|
for name, manifest in variants:
|
||||||
expected = hmac.new(self.webhook_secret, manifest.encode(), hashlib.sha256).hexdigest()
|
expected = hmac.new(self.webhook_secret, manifest.encode(), hashlib.sha256).hexdigest()
|
||||||
return hmac.compare_digest(expected, supplied.lower())
|
if hmac.compare_digest(expected, supplied.lower()):
|
||||||
|
self.last_signature = name
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
def parse(self, body: bytes, query: Mapping[str, str] | None = None) -> PaymentEvent | None:
|
def parse(self, body: bytes, query: Mapping[str, str] | None = None) -> PaymentEvent | None:
|
||||||
try:
|
try:
|
||||||
@@ -134,7 +181,15 @@ class MercadoPagoPayment:
|
|||||||
payment_id = str((query or {}).get('data.id') or (data.get('data') or {}).get('id') or '')
|
payment_id = str((query or {}).get('data.id') or (data.get('data') or {}).get('id') or '')
|
||||||
if not payment_id.isdigit():
|
if not payment_id.isdigit():
|
||||||
return None
|
return None
|
||||||
|
try:
|
||||||
payment = self.lookup(payment_id)
|
payment = self.lookup(payment_id)
|
||||||
|
except httpx.HTTPStatusError as error:
|
||||||
|
# Signed by Mercado Pago but about no payment of ours, such as the
|
||||||
|
# panel's "Simular notificação". Anything else is raised so that a
|
||||||
|
# real notification is retried.
|
||||||
|
if error.response.status_code == 404:
|
||||||
|
return None
|
||||||
|
raise
|
||||||
return event_from_payment(payment, notification_id=str(data.get('id', '')))
|
return event_from_payment(payment, notification_id=str(data.get('id', '')))
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
65
app/mercadopago_probe.py
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
"""Read-only look at the Mercado Pago account behind MP_ACCESS_TOKEN.
|
||||||
|
|
||||||
|
python -m app.mercadopago_probe [--bin 503143] [--valor 50]
|
||||||
|
|
||||||
|
Run from the api container's console (Portainer > Containers > api >
|
||||||
|
Console), or with "Verificar conta" on the Kanban's Integrations tab. It creates nothing and charges nothing: it asks Mercado Pago which
|
||||||
|
account the token belongs to, which card methods the account accepts, and how
|
||||||
|
it classifies a card number's first digits (type, issuer, instalments). That
|
||||||
|
is what payment errors such as 10111 (issuer) and 10113 (method excluded by a
|
||||||
|
rule) depend on.
|
||||||
|
"""
|
||||||
|
import argparse
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
from .core.secrets import load as load_secret_files
|
||||||
|
|
||||||
|
API = 'https://api.mercadopago.com'
|
||||||
|
|
||||||
|
|
||||||
|
def check(token, bin_='548083', amount='50', transport=None):
|
||||||
|
"""The account, its card methods and how a card's first digits are read."""
|
||||||
|
http = httpx.Client(base_url=API, timeout=15, transport=transport,
|
||||||
|
headers={'Authorization': f'Bearer {token}'})
|
||||||
|
result = {'token': 'test' if token.startswith('TEST-') else 'production'}
|
||||||
|
me = http.get('/users/me')
|
||||||
|
if me.status_code == 200:
|
||||||
|
user = me.json()
|
||||||
|
tags = user.get('tags') or []
|
||||||
|
result['account'] = {'id': user.get('id'), 'nickname': user.get('nickname'),
|
||||||
|
'site': user.get('site_id'), 'test_user': 'test_user' in tags, 'tags': tags}
|
||||||
|
else:
|
||||||
|
result['account'] = {'error': f'HTTP {me.status_code}'}
|
||||||
|
methods = http.get('/v1/payment_methods')
|
||||||
|
result['cards'] = ([{'id': m.get('id'), 'type': m.get('payment_type_id'), 'status': m.get('status')}
|
||||||
|
for m in methods.json() if m.get('payment_type_id') in ('credit_card', 'debit_card')]
|
||||||
|
if methods.status_code == 200 else {'error': f'HTTP {methods.status_code}'})
|
||||||
|
options = http.get('/v1/payment_methods/installments', params={'bin': bin_, 'amount': amount})
|
||||||
|
result['bin'] = ([{'method': o.get('payment_method_id'), 'type': o.get('payment_type_id'),
|
||||||
|
'issuer': (o.get('issuer') or {}).get('name'),
|
||||||
|
'installments': [c.get('installments') for c in o.get('payer_costs') or []]}
|
||||||
|
for o in options.json()]
|
||||||
|
if options.status_code == 200 else {'error': f'HTTP {options.status_code} {options.text[:200]}'})
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv=None):
|
||||||
|
parser = argparse.ArgumentParser(prog='python -m app.mercadopago_probe')
|
||||||
|
parser.add_argument('--bin', default='548083', help="the card's first six digits")
|
||||||
|
parser.add_argument('--valor', default='50', help='amount in reais for the instalment lookup')
|
||||||
|
args = parser.parse_args(argv)
|
||||||
|
load_secret_files()
|
||||||
|
token = os.environ.get('MP_ACCESS_TOKEN', '')
|
||||||
|
if not token:
|
||||||
|
print('MP_ACCESS_TOKEN is not set in this container.')
|
||||||
|
return 1
|
||||||
|
import json
|
||||||
|
print(json.dumps(check(token, args.bin, args.valor), indent=2, ensure_ascii=False))
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
sys.exit(main())
|
||||||
@@ -7,11 +7,15 @@ existing deployment keeps working unchanged.
|
|||||||
|
|
||||||
Administered from the API container, the same way the schema is:
|
Administered from the API container, the same way the schema is:
|
||||||
|
|
||||||
python -m local.operators list
|
python -m app.operators list
|
||||||
python -m local.operators add maria@example.com --name "Maria"
|
python -m app.operators add maria@example.com --name "Maria" [--role admin]
|
||||||
python -m local.operators password maria@example.com
|
python -m app.operators role maria@example.com superadmin
|
||||||
python -m local.operators disable maria@example.com
|
python -m app.operators password maria@example.com
|
||||||
python -m local.operators enable maria@example.com
|
python -m app.operators disable maria@example.com
|
||||||
|
python -m app.operators enable maria@example.com
|
||||||
|
|
||||||
|
The superadmin is the system's own account and is only set here; the
|
||||||
|
administrators manage everyone else on the Kanban's Usuários page.
|
||||||
|
|
||||||
Passwords are read from the terminal, never from an argument, so they do not
|
Passwords are read from the terminal, never from an argument, so they do not
|
||||||
reach shell history or the process list.
|
reach shell history or the process list.
|
||||||
@@ -21,10 +25,10 @@ import os
|
|||||||
import sys
|
import sys
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
||||||
from .core.auth import password_hash
|
from .core.auth import ROLES, password_hash
|
||||||
from .core.db import connect
|
from .core.db import connect
|
||||||
|
|
||||||
MIN_PASSWORD = 12
|
MIN_PASSWORD = 8
|
||||||
|
|
||||||
|
|
||||||
def seed_from_environment(cursor):
|
def seed_from_environment(cursor):
|
||||||
@@ -40,9 +44,11 @@ def seed_from_environment(cursor):
|
|||||||
existing = cursor.execute(
|
existing = cursor.execute(
|
||||||
'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.
|
||||||
|
cursor.execute("UPDATE dtf_local.operators SET role='superadmin' WHERE email=%s", (email,))
|
||||||
return None
|
return None
|
||||||
cursor.execute(
|
cursor.execute(
|
||||||
'INSERT INTO dtf_local.operators(id,email,name,password_hash) VALUES(%s,%s,%s,%s)',
|
"INSERT INTO dtf_local.operators(id,email,name,password_hash,role) VALUES(%s,%s,%s,%s,'superadmin')",
|
||||||
(uuid4(), email, 'Operador', password_hash(password)))
|
(uuid4(), email, 'Operador', password_hash(password)))
|
||||||
return email
|
return email
|
||||||
|
|
||||||
@@ -56,14 +62,26 @@ def _ask_password(email):
|
|||||||
return first
|
return first
|
||||||
|
|
||||||
|
|
||||||
def add(email, name=''):
|
def add(email, name='', role='admin'):
|
||||||
email = email.strip().lower()
|
email = email.strip().lower()
|
||||||
|
if role not in ROLES:
|
||||||
|
raise SystemExit('Role must be one of: ' + ', '.join(ROLES))
|
||||||
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) VALUES(%s,%s,%s,%s)',
|
c.execute('INSERT INTO dtf_local.operators(id,email,name,password_hash,role) VALUES(%s,%s,%s,%s,%s)',
|
||||||
(uuid4(), email, name, password_hash(_ask_password(email))))
|
(uuid4(), email, name, password_hash(_ask_password(email)), role))
|
||||||
print(f'Added {email}.')
|
print(f'Added {email} as {role}.')
|
||||||
|
|
||||||
|
|
||||||
|
def set_role(email, role):
|
||||||
|
email = email.strip().lower()
|
||||||
|
if role not in ROLES:
|
||||||
|
raise SystemExit('Role must be one of: ' + ', '.join(ROLES))
|
||||||
|
with connect() as c:
|
||||||
|
if not c.execute('UPDATE dtf_local.operators SET role=%s WHERE email=%s RETURNING id', (role, email)).fetchone():
|
||||||
|
raise SystemExit(f'{email} does not exist.')
|
||||||
|
print(f'{email} is now {role}.')
|
||||||
|
|
||||||
|
|
||||||
def password(email):
|
def password(email):
|
||||||
@@ -93,7 +111,7 @@ def set_active(email, active):
|
|||||||
|
|
||||||
def listing():
|
def listing():
|
||||||
with connect() as c:
|
with connect() as c:
|
||||||
rows = c.execute('''SELECT email,name,active,last_login_at FROM dtf_local.operators
|
rows = c.execute('''SELECT email,name,role,active,last_login_at FROM dtf_local.operators
|
||||||
ORDER BY email''').fetchall()
|
ORDER BY email''').fetchall()
|
||||||
if not rows:
|
if not rows:
|
||||||
print('No operator accounts. Set OPERATOR_EMAIL and OPERATOR_PASSWORD and run'
|
print('No operator accounts. Set OPERATOR_EMAIL and OPERATOR_PASSWORD and run'
|
||||||
@@ -102,7 +120,7 @@ def listing():
|
|||||||
for row in rows:
|
for row in rows:
|
||||||
seen = row['last_login_at'].strftime('%Y-%m-%d %H:%M') if row['last_login_at'] else 'never'
|
seen = row['last_login_at'].strftime('%Y-%m-%d %H:%M') if row['last_login_at'] else 'never'
|
||||||
state = 'active ' if row['active'] else 'DISABLED'
|
state = 'active ' if row['active'] else 'DISABLED'
|
||||||
print(f"{state} {row['email']:<34} {row['name'][:20]:<20} last login {seen}")
|
print(f"{state} {row['email']:<34} {row['name'][:20]:<20} {row['role']:<10} last login {seen}")
|
||||||
|
|
||||||
|
|
||||||
def main(argv):
|
def main(argv):
|
||||||
@@ -116,7 +134,12 @@ def main(argv):
|
|||||||
email = rest[0]
|
email = rest[0]
|
||||||
if command == 'add':
|
if command == 'add':
|
||||||
name = rest[rest.index('--name') + 1] if '--name' in rest else ''
|
name = rest[rest.index('--name') + 1] if '--name' in rest else ''
|
||||||
return add(email, name)
|
role = rest[rest.index('--role') + 1] if '--role' in rest else 'admin'
|
||||||
|
return add(email, name, role)
|
||||||
|
if command == 'role':
|
||||||
|
if len(rest) < 2:
|
||||||
|
raise SystemExit('usage: python -m app.operators role <email> <role>')
|
||||||
|
return set_role(email, rest[1])
|
||||||
if command == 'password':
|
if command == 'password':
|
||||||
return password(email)
|
return password(email)
|
||||||
if command == 'disable':
|
if command == 'disable':
|
||||||
|
|||||||
91
app/package.py
Normal file
@@ -0,0 +1,91 @@
|
|||||||
|
"""The package an order ships in, as every carrier is quoted for it.
|
||||||
|
|
||||||
|
The weight comes from the client (a base per box plus a weight per billed
|
||||||
|
metre of film) and has no default: a carrier refuses to start without it, so
|
||||||
|
a guessed weight never prices a customer's freight. A box holds
|
||||||
|
JADLOG_METROS_POR_CAIXA metres; a longer order ships in as many boxes as it
|
||||||
|
needs, each with its own packaging weight. The box's sides (JADLOG_CAIXA_CM)
|
||||||
|
are what the Correios price by, and with the contract's factor
|
||||||
|
(JADLOG_CUBAGEM_KG_M3) what Jadlog's cubed weight is. The settings keep the
|
||||||
|
Jadlog names they had when Jadlog was the only carrier.
|
||||||
|
"""
|
||||||
|
import math
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
from decimal import Decimal
|
||||||
|
|
||||||
|
WEIGHT_SETTINGS = ('JADLOG_PESO_BASE_KG', 'JADLOG_PESO_POR_METRO_KG')
|
||||||
|
GRAMS = Decimal('0.001')
|
||||||
|
|
||||||
|
|
||||||
|
def box_cm(text):
|
||||||
|
"""The box's three sides in cm from "56x14x14" ("56 × 14 × 14", "56,5x14x14")."""
|
||||||
|
sides = [Decimal(side.strip().replace(',', '.')) for side in re.split(r'[x×*]', text.lower())]
|
||||||
|
if len(sides) != 3 or any(side <= 0 for side in sides):
|
||||||
|
raise RuntimeError('JADLOG_CAIXA_CM takes three sides in cm, such as 56x14x14')
|
||||||
|
return sides
|
||||||
|
|
||||||
|
|
||||||
|
class Package:
|
||||||
|
def __init__(self):
|
||||||
|
self.base_kg = Decimal(os.environ['JADLOG_PESO_BASE_KG'])
|
||||||
|
self.per_metre_kg = Decimal(os.environ['JADLOG_PESO_POR_METRO_KG'])
|
||||||
|
# A carrier's time counts from collection; the order is printed first.
|
||||||
|
self.production_days = int(os.environ.get('FREIGHT_PRODUCTION_DAYS') or 0)
|
||||||
|
if self.base_kg < 0 or self.per_metre_kg <= 0 or self.production_days < 0:
|
||||||
|
raise RuntimeError('Package weight and production days must be positive')
|
||||||
|
# A box without its factor (or a factor without a box) would price by a guess.
|
||||||
|
box = (os.environ.get('JADLOG_CAIXA_CM') or '').strip()
|
||||||
|
factor = (os.environ.get('JADLOG_CUBAGEM_KG_M3') or '').strip()
|
||||||
|
if bool(box) != bool(factor):
|
||||||
|
raise RuntimeError('Set JADLOG_CAIXA_CM and JADLOG_CUBAGEM_KG_M3 together, or neither')
|
||||||
|
self.box_cm = box_cm(box) if box else None
|
||||||
|
self.cubage_kg_m3 = Decimal(factor.replace(',', '.')) if factor else None
|
||||||
|
if self.cubage_kg_m3 is not None and self.cubage_kg_m3 <= 0:
|
||||||
|
raise RuntimeError('JADLOG_CUBAGEM_KG_M3 must be positive')
|
||||||
|
per_box = (os.environ.get('JADLOG_METROS_POR_CAIXA') or '').strip()
|
||||||
|
self.metres_per_box = Decimal(per_box.replace(',', '.')) if per_box else None
|
||||||
|
if self.metres_per_box is not None and self.metres_per_box <= 0:
|
||||||
|
raise RuntimeError('JADLOG_METROS_POR_CAIXA must be positive')
|
||||||
|
|
||||||
|
def boxes(self, metres=None):
|
||||||
|
"""How many boxes the order fills; one when the capacity is not set."""
|
||||||
|
if metres is None or self.metres_per_box is None:
|
||||||
|
return 1
|
||||||
|
return max(1, math.ceil(Decimal(str(metres)) / self.metres_per_box))
|
||||||
|
|
||||||
|
def real_kg(self, metres):
|
||||||
|
return (self.boxes(metres) * self.base_kg + self.per_metre_kg * Decimal(str(metres))).quantize(GRAMS)
|
||||||
|
|
||||||
|
def box_weights_kg(self, metres):
|
||||||
|
"""Each box's real weight: full boxes first, the rest in the last one."""
|
||||||
|
metres = Decimal(str(metres))
|
||||||
|
count = self.boxes(metres)
|
||||||
|
if count == 1:
|
||||||
|
return [self.real_kg(metres)]
|
||||||
|
full = (self.base_kg + self.per_metre_kg * self.metres_per_box).quantize(GRAMS)
|
||||||
|
rest = metres - self.metres_per_box * (count - 1)
|
||||||
|
return [full] * (count - 1) + [(self.base_kg + self.per_metre_kg * rest).quantize(GRAMS)]
|
||||||
|
|
||||||
|
def cubed_kg(self, metres=None):
|
||||||
|
"""The boxes' volume in m³ times the contract's factor (one box without a
|
||||||
|
length); None without a box."""
|
||||||
|
if not self.box_cm:
|
||||||
|
return None
|
||||||
|
a, b, c = self.box_cm
|
||||||
|
return (self.boxes(metres) * a * b * c / Decimal(1_000_000) * self.cubage_kg_m3).quantize(GRAMS)
|
||||||
|
|
||||||
|
def weight_kg(self, metres):
|
||||||
|
"""What Jadlog charges by: the larger of the real and the cubed weight."""
|
||||||
|
real, cubed = self.real_kg(metres), self.cubed_kg(metres)
|
||||||
|
return max(real, cubed) if cubed is not None else real
|
||||||
|
|
||||||
|
def status(self):
|
||||||
|
"""The package rule, as the Kanban's Integrações shows it."""
|
||||||
|
cubed = self.cubed_kg()
|
||||||
|
return {'base_kg': str(self.base_kg), 'per_metre_kg': str(self.per_metre_kg),
|
||||||
|
'production_days': self.production_days,
|
||||||
|
'box_cm': [str(side) for side in self.box_cm] if self.box_cm else None,
|
||||||
|
'cubage_kg_m3': str(self.cubage_kg_m3) if self.cubage_kg_m3 else None,
|
||||||
|
'cubed_kg': str(cubed) if cubed is not None else None,
|
||||||
|
'metres_per_box': str(self.metres_per_box) if self.metres_per_box else None}
|
||||||
94
app/payment_messages.py
Normal file
@@ -0,0 +1,94 @@
|
|||||||
|
"""What to tell a customer when a payment does not go through.
|
||||||
|
|
||||||
|
Mercado Pago answers with codes: a refused card has a status_detail
|
||||||
|
("cc_rejected_insufficient_amount"), a request it cannot process has cause
|
||||||
|
codes (324, "invalid identification number"). Shown as they come, they read
|
||||||
|
like a crash. Each becomes one plain sentence that says what happened and
|
||||||
|
what the customer can do; the code itself goes to the log and, for the team,
|
||||||
|
stays on the Kanban.
|
||||||
|
"""
|
||||||
|
|
||||||
|
TRY_OTHER = 'Use outro cartão ou pague com PIX.'
|
||||||
|
|
||||||
|
# Mercado Pago's status_detail for a card payment it refused.
|
||||||
|
REJECTIONS = {
|
||||||
|
'cc_rejected_bad_filled_card_number': 'O número do cartão está incorreto. Confira e tente de novo.',
|
||||||
|
'cc_rejected_bad_filled_date': 'A data de validade do cartão está incorreta. Confira e tente de novo.',
|
||||||
|
'cc_rejected_bad_filled_security_code': 'O código de segurança (CVV) está incorreto. Confira e tente de novo.',
|
||||||
|
'cc_rejected_bad_filled_other': 'Algum dado do cartão está incorreto. Confira o nome, o CPF e a validade e tente de novo.',
|
||||||
|
'cc_rejected_insufficient_amount': 'O cartão não tem limite suficiente para este valor. ' + TRY_OTHER,
|
||||||
|
'cc_amount_rate_limit_exceeded': 'O cartão atingiu o limite de valor permitido. ' + TRY_OTHER,
|
||||||
|
'cc_rejected_call_for_authorize': 'O banco precisa autorizar este pagamento. Ligue para o banco emissor e '
|
||||||
|
'tente de novo, ou use outro cartão.',
|
||||||
|
'cc_rejected_card_disabled': 'O cartão está bloqueado ou ainda não foi ativado. Fale com o banco emissor '
|
||||||
|
'ou use outro cartão.',
|
||||||
|
'cc_rejected_invalid_installments': 'O cartão não aceita esse número de parcelas. Escolha outro número de parcelas.',
|
||||||
|
'cc_rejected_duplicated_payment': 'Um pagamento igual acabou de ser feito com este cartão. Se precisar pagar '
|
||||||
|
'de novo, use outro cartão ou PIX.',
|
||||||
|
'cc_rejected_max_attempts': 'O cartão atingiu o limite de tentativas. ' + TRY_OTHER,
|
||||||
|
'cc_rejected_high_risk': 'O pagamento foi recusado pela análise de segurança. ' + TRY_OTHER,
|
||||||
|
'rejected_high_risk': 'O pagamento foi recusado pela análise de segurança. ' + TRY_OTHER,
|
||||||
|
'cc_rejected_blacklist': 'Não foi possível pagar com este cartão. ' + TRY_OTHER,
|
||||||
|
'cc_rejected_card_type_not_allowed': 'Este tipo de cartão não é aceito. Use um cartão de crédito ou pague com PIX.',
|
||||||
|
'cc_rejected_3ds_challenge': 'O banco não confirmou o pagamento. Tente de novo ou use outro cartão.',
|
||||||
|
'cc_rejected_3ds_mandatory': 'O banco não confirmou o pagamento. Tente de novo ou use outro cartão.',
|
||||||
|
'cc_rejected_card_error': 'Não foi possível processar o cartão. Tente de novo ou use outro cartão.',
|
||||||
|
'cc_rejected_other_reason': 'O banco emissor recusou o pagamento. ' + TRY_OTHER,
|
||||||
|
'rejected_insufficient_data': 'Faltaram dados para processar o pagamento. Confira os dados e tente de novo.',
|
||||||
|
'rejected_by_regulations': 'Não foi possível pagar com este cartão. ' + TRY_OTHER,
|
||||||
|
}
|
||||||
|
REJECTED = 'O pagamento foi recusado. Confira os dados ou ' + TRY_OTHER[0].lower() + TRY_OTHER[1:]
|
||||||
|
|
||||||
|
# Mercado Pago's cause codes for a request it refused before charging.
|
||||||
|
CAUSES = {
|
||||||
|
'205': 'Informe o número do cartão.',
|
||||||
|
'208': 'Informe o mês de validade do cartão.',
|
||||||
|
'209': 'Informe o ano de validade do cartão.',
|
||||||
|
'212': 'Informe o CPF ou CNPJ do titular do cartão.',
|
||||||
|
'213': 'Informe o CPF ou CNPJ do titular do cartão.',
|
||||||
|
'214': 'Informe o CPF ou CNPJ do titular do cartão.',
|
||||||
|
'221': 'Informe o nome do titular como está no cartão.',
|
||||||
|
'224': 'Informe o código de segurança (CVV).',
|
||||||
|
'E301': 'O número do cartão está incorreto. Confira e tente de novo.',
|
||||||
|
'E302': 'O código de segurança (CVV) está incorreto. Confira e tente de novo.',
|
||||||
|
'316': 'O nome do titular está incorreto. Digite como está no cartão.',
|
||||||
|
'322': 'O CPF ou CNPJ do titular está incorreto. Confira e tente de novo.',
|
||||||
|
'323': 'O CPF ou CNPJ do titular está incorreto. Confira e tente de novo.',
|
||||||
|
'324': 'O CPF ou CNPJ do titular está incorreto. Confira e tente de novo.',
|
||||||
|
'325': 'A data de validade do cartão está incorreta. Confira e tente de novo.',
|
||||||
|
'326': 'A data de validade do cartão está incorreta. Confira e tente de novo.',
|
||||||
|
'2067': 'O CPF ou CNPJ do titular está incorreto. Confira e tente de novo.',
|
||||||
|
'3034': 'O número do cartão está incorreto. Confira e tente de novo.',
|
||||||
|
'4033': 'O cartão não aceita esse número de parcelas. Escolha outro número de parcelas.',
|
||||||
|
}
|
||||||
|
NOT_PROCESSED = 'Não foi possível processar o pagamento com este cartão. Confira os dados ou ' + \
|
||||||
|
TRY_OTHER[0].lower() + TRY_OTHER[1:]
|
||||||
|
UNAVAILABLE = 'O Mercado Pago não respondeu agora. Tente de novo em alguns instantes.'
|
||||||
|
|
||||||
|
|
||||||
|
def rejection(status_detail):
|
||||||
|
"""The sentence for a refused card payment."""
|
||||||
|
return REJECTIONS.get(status_detail or '', REJECTED)
|
||||||
|
|
||||||
|
|
||||||
|
def refusal(data):
|
||||||
|
"""The sentence for a request Mercado Pago refused (its JSON error body)."""
|
||||||
|
for cause in (data or {}).get('cause') or []:
|
||||||
|
if isinstance(cause, dict) and str(cause.get('code')) in CAUSES:
|
||||||
|
return CAUSES[str(cause.get('code'))]
|
||||||
|
return NOT_PROCESSED
|
||||||
|
|
||||||
|
|
||||||
|
# The reasons a quote cannot be paid (app.payments.PaymentRefused), as the customer reads them.
|
||||||
|
QUOTE_REFUSALS = {
|
||||||
|
'quote not found': 'Não encontramos este pedido. Monte o pedido de novo.',
|
||||||
|
'quote was never reviewed': 'Este pedido ainda está sendo conferido pela equipe. Você poderá pagar assim que for aprovado.',
|
||||||
|
'quote was discarded': 'Esta cotação foi cancelada. Monte o pedido de novo para pagar.',
|
||||||
|
'quote uses an obsolete production layout; request a new quote':
|
||||||
|
'Este pedido foi montado numa versão anterior do Site. Monte o pedido de novo para pagar.',
|
||||||
|
'quote expired before payment': 'O prazo de 24 horas para pagar este pedido acabou. Monte o pedido de novo para pagar.',
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def quote_refusal(reason):
|
||||||
|
return QUOTE_REFUSALS.get(str(reason), 'Não foi possível pagar este pedido. Monte o pedido de novo.')
|
||||||
@@ -6,17 +6,21 @@ or a second WhatsApp message. Every delivery is recorded under the provider's
|
|||||||
own event id and applied inside one transaction, so a duplicate is a no-op and a
|
own event id and applied inside one transaction, so a duplicate is a no-op and a
|
||||||
crash mid-way is retried rather than half-applied.
|
crash mid-way is retried rather than half-applied.
|
||||||
|
|
||||||
Order creation lives here rather than in a route because two paths reach it: the
|
Order creation lives here rather than in a route because the paths that reach
|
||||||
webhook, and the local development checkout. They must agree.
|
it must agree: the webhook, reconcile() (the provider asked directly) and the
|
||||||
|
local development checkout.
|
||||||
"""
|
"""
|
||||||
|
import logging
|
||||||
from datetime import datetime, timedelta, timezone
|
from datetime import datetime, timedelta, timezone
|
||||||
from uuid import UUID, uuid4
|
from uuid import UUID, uuid4
|
||||||
|
|
||||||
from psycopg.types.json import Jsonb
|
from psycopg.types.json import Jsonb
|
||||||
|
|
||||||
|
from . import machines, mail
|
||||||
from .core.auth import audit
|
from .core.auth import audit
|
||||||
|
from .core.models import PRODUCTION_VERSIONS
|
||||||
from .printjobs import queue as queue_print_files
|
from .printjobs import queue as queue_print_files
|
||||||
from .runtime import enqueue, upload_row
|
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
|
||||||
@@ -34,13 +38,43 @@ def approved_quote(c, quote_id, owner=None):
|
|||||||
raise PaymentRefused('quote not found')
|
raise PaymentRefused('quote not found')
|
||||||
if not row['approved']:
|
if not row['approved']:
|
||||||
raise PaymentRefused('quote was never reviewed')
|
raise PaymentRefused('quote was never reviewed')
|
||||||
if any(item.get('production', {}).get('version') != 2 for item in row['approved']['items']):
|
if row.get('discarded_at'):
|
||||||
|
raise PaymentRefused('quote was discarded')
|
||||||
|
if any(item.get('production', {}).get('version') not in PRODUCTION_VERSIONS for item in row['approved']['items']):
|
||||||
raise PaymentRefused('quote uses an obsolete production layout; request a new quote')
|
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):
|
if row['approved_at'] < datetime.now(timezone.utc) - timedelta(hours=QUOTE_VALID_HOURS):
|
||||||
raise PaymentRefused('quote expired before payment')
|
raise PaymentRefused('quote expired before payment')
|
||||||
return row
|
return row
|
||||||
|
|
||||||
|
|
||||||
|
TEST_PROVIDER = 'teste'
|
||||||
|
|
||||||
|
|
||||||
|
def is_test(order):
|
||||||
|
"""An operator's test order: it goes through production and notifies no one."""
|
||||||
|
return (order.get('payment') or {}).get('provider') == TEST_PROVIDER
|
||||||
|
|
||||||
|
|
||||||
|
# How long a file is kept while nothing has been paid for it. A cart's files
|
||||||
|
# are uploaded before payment, so the price and the security check are done on
|
||||||
|
# the file itself; a cart that is never paid must not keep them for 30 days.
|
||||||
|
UNPAID_HOLD = '2 days'
|
||||||
|
# A quote waiting for an operator's review keeps its files this long.
|
||||||
|
REVIEW_HOLD = '7 days'
|
||||||
|
# Once paid, the order keeps its originals for this long from the upload.
|
||||||
|
ORDER_RETENTION = '30 days'
|
||||||
|
|
||||||
|
|
||||||
|
def quote_uploads(quote_or_draft):
|
||||||
|
return [uid for item in quote_or_draft['items'] for uid in item['uploads']]
|
||||||
|
|
||||||
|
|
||||||
|
def hold_uploads(c, upload_ids, interval):
|
||||||
|
"""Keep these files at least `interval` from now; never shortens a hold."""
|
||||||
|
c.execute('''UPDATE dtf_local.uploads SET expires_at=GREATEST(expires_at, now()+%s::interval)
|
||||||
|
WHERE id=ANY(%s) AND purged_at IS NULL''', (interval, [str(u) for u in upload_ids]))
|
||||||
|
|
||||||
|
|
||||||
def create_order(c, quote, payment):
|
def create_order(c, quote, payment):
|
||||||
"""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.
|
||||||
|
|
||||||
@@ -60,11 +94,21 @@ def create_order(c, quote, payment):
|
|||||||
order = c.execute(
|
order = c.execute(
|
||||||
'INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment) VALUES(%s,%s,%s,%s,%s) RETURNING *',
|
'INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment) VALUES(%s,%s,%s,%s,%s) RETURNING *',
|
||||||
(uuid4(), quote['id'], quote['owner'], Jsonb(approved), Jsonb(payment))).fetchone()
|
(uuid4(), quote['id'], quote['owner'], Jsonb(approved), Jsonb(payment))).fetchone()
|
||||||
|
# Paid: the files are kept for the order's retention, counted from upload.
|
||||||
|
c.execute('''UPDATE dtf_local.uploads SET expires_at=GREATEST(expires_at, created_at+%s::interval)
|
||||||
|
WHERE id=ANY(%s) AND purged_at IS NULL''', (ORDER_RETENTION, quote_uploads(approved)))
|
||||||
queue_print_files(c, order['id'], len(approved['items']))
|
queue_print_files(c, order['id'], len(approved['items']))
|
||||||
for provider in ('tiny', 'whatsapp'):
|
machines.route(c)
|
||||||
enqueue(c, f"{order['id']}:paid:{provider}", provider,
|
if is_test(order):
|
||||||
|
return order, True
|
||||||
|
mail.order_paid(c, order, PUBLIC_ORIGIN)
|
||||||
|
# How it was paid, for the order's payment in Tiny.
|
||||||
|
paid = c.execute('''SELECT method FROM dtf_local.payment_intents WHERE quote_id=%s AND status='approved'
|
||||||
|
ORDER BY created_at DESC LIMIT 1''', (quote['id'],)).fetchone()
|
||||||
|
enqueue(c, f"{order['id']}:paid:tiny", 'tiny',
|
||||||
{'order_id': str(order['id']), 'number': order['number'],
|
{'order_id': str(order['id']), 'number': order['number'],
|
||||||
'event': 'payment_approved', 'order': approved})
|
'event': 'payment_approved', 'order': approved,
|
||||||
|
'payment': {'method': paid['method']} if paid else {}})
|
||||||
return order, True
|
return order, True
|
||||||
|
|
||||||
|
|
||||||
@@ -123,3 +167,39 @@ def apply(c, event):
|
|||||||
|
|
||||||
order, created = create_order(c, quote, {'provider': event.raw.get('provider', 'webhook'), **event.raw})
|
order, created = create_order(c, quote, {'provider': event.raw.get('provider', 'webhook'), **event.raw})
|
||||||
return f"order {order['number']}" + ('' if created else ' (already existed)')
|
return f"order {order['number']}" + ('' if created else ' (already existed)')
|
||||||
|
|
||||||
|
|
||||||
|
def reconcile(connect, provider, quote_id=None, limit=20):
|
||||||
|
"""Ask the provider about the payments of quotes that have no order yet and
|
||||||
|
apply what it says, exactly as a notification would. A notification can be
|
||||||
|
refused, lost or late; the provider's API is the authority either way, and
|
||||||
|
the event id (payment id and status) makes a webhook and this the same
|
||||||
|
delivery, applied once. Returns the outcomes of what was new."""
|
||||||
|
if not hasattr(provider, 'lookup'):
|
||||||
|
return []
|
||||||
|
from .mercadopago import event_from_payment
|
||||||
|
with connect() as c:
|
||||||
|
rows = c.execute('''SELECT i.provider_payment_id FROM dtf_local.payment_intents i
|
||||||
|
LEFT JOIN dtf_local.orders o ON o.quote_id=i.quote_id
|
||||||
|
WHERE o.id IS NULL AND i.provider=%s AND i.status IN ('pending','approved')
|
||||||
|
AND i.created_at > now() - make_interval(hours => %s)''' +
|
||||||
|
(' AND i.quote_id=%s' if quote_id else '') + ' ORDER BY i.created_at DESC LIMIT %s',
|
||||||
|
(provider.name, QUOTE_VALID_HOURS + 1, *([quote_id] if quote_id else []), limit)).fetchall()
|
||||||
|
outcomes = []
|
||||||
|
for row in rows:
|
||||||
|
# Asked outside any transaction: no lock is held while the provider answers.
|
||||||
|
try:
|
||||||
|
event = event_from_payment(provider.lookup(row['provider_payment_id']))
|
||||||
|
except Exception:
|
||||||
|
logging.exception('Payment reconciliation lookup failed')
|
||||||
|
continue
|
||||||
|
with connect() as c:
|
||||||
|
stored = record(c, provider.name, event)
|
||||||
|
if stored is None:
|
||||||
|
continue
|
||||||
|
outcome = apply(c, event)
|
||||||
|
c.execute('UPDATE dtf_local.payment_events SET processed_at=now(), outcome=%s WHERE id=%s',
|
||||||
|
(outcome, stored['id']))
|
||||||
|
audit('payment_reconciled', payment_event=event.event_id, status=event.status, outcome=outcome)
|
||||||
|
outcomes.append(outcome)
|
||||||
|
return outcomes
|
||||||
|
|||||||
@@ -26,6 +26,8 @@ from decimal import Decimal
|
|||||||
|
|
||||||
from PIL import Image, ImageOps
|
from PIL import Image, ImageOps
|
||||||
|
|
||||||
|
from .core.models import PRODUCTION_VERSIONS
|
||||||
|
|
||||||
PT_PER_CM = 72 / 2.54
|
PT_PER_CM = 72 / 2.54
|
||||||
# Acrobat's page limit. Longer layouts scale user space with /UserUnit (PDF 1.6)
|
# Acrobat's page limit. Longer layouts scale user space with /UserUnit (PDF 1.6)
|
||||||
# rather than cutting the film into pages a RIP might print with gaps.
|
# rather than cutting the film into pages a RIP might print with gaps.
|
||||||
@@ -46,7 +48,8 @@ Image.MAX_IMAGE_PIXELS = None
|
|||||||
|
|
||||||
|
|
||||||
class Unsupported(Exception):
|
class Unsupported(Exception):
|
||||||
"""This item cannot be generated automatically; the reason is for the operator."""
|
"""This item cannot be generated automatically. The reason is shown to the
|
||||||
|
operator on the Kanban, so it is written in Portuguese."""
|
||||||
|
|
||||||
|
|
||||||
class Name(str):
|
class Name(str):
|
||||||
@@ -153,14 +156,14 @@ class SourceImage:
|
|||||||
self.image = Image.open(path)
|
self.image = Image.open(path)
|
||||||
self.format = self.image.format
|
self.format = self.image.format
|
||||||
except Image.DecompressionBombError as exc:
|
except Image.DecompressionBombError as exc:
|
||||||
raise Unsupported(f'"{name}" is too large to generate automatically') from exc
|
raise Unsupported(f'"{name}" é grande demais para gerar automaticamente') from exc
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
raise Unsupported(f'"{name}" is not an image this generator can read') from exc
|
raise Unsupported(f'"{name}" não é uma imagem que o gerador consiga ler') from exc
|
||||||
if self.format not in SUPPORTED_FORMATS:
|
if self.format not in SUPPORTED_FORMATS:
|
||||||
raise Unsupported(f'"{name}" is {self.format or "an unknown format"}; '
|
raise Unsupported(f'"{name}" está em {self.format or "formato desconhecido"}; '
|
||||||
'only JPEG, PNG, WebP and TIFF are generated automatically')
|
'só JPEG, PNG, WebP, TIFF e PDF são gerados automaticamente')
|
||||||
if getattr(self.image, 'n_frames', 1) > 1 and self.format != 'TIFF':
|
if getattr(self.image, 'n_frames', 1) > 1 and self.format != 'TIFF':
|
||||||
raise Unsupported(f'"{name}" is animated or has several frames')
|
raise Unsupported(f'"{name}" é animado ou tem vários quadros')
|
||||||
# Browsers draw a photo upright according to its EXIF orientation, and
|
# Browsers draw a photo upright according to its EXIF orientation, and
|
||||||
# the Site measured it that way, so the print must too.
|
# the Site measured it that way, so the print must too.
|
||||||
try:
|
try:
|
||||||
@@ -181,8 +184,8 @@ class SourceImage:
|
|||||||
return self._embed_jpeg(pdf)
|
return self._embed_jpeg(pdf)
|
||||||
width, height = self.image.size
|
width, height = self.image.size
|
||||||
if width * height > MAX_DECODED_PIXELS:
|
if width * height > MAX_DECODED_PIXELS:
|
||||||
raise Unsupported(f'"{self.name}" has {width} x {height} px, more than the '
|
raise Unsupported(f'"{self.name}" tem {width} × {height} px, mais do que o '
|
||||||
'generator decodes; prepare this item by hand')
|
'gerador processa; prepare este item à mão')
|
||||||
return self._embed_pixels(pdf)
|
return self._embed_pixels(pdf)
|
||||||
|
|
||||||
def _colorspace(self, pdf, mode):
|
def _colorspace(self, pdf, mode):
|
||||||
@@ -235,7 +238,7 @@ class SourceImage:
|
|||||||
elif mode in ('P', 'PA', 'RGB', 'RGBA', 'RGBa'):
|
elif mode in ('P', 'PA', 'RGB', 'RGBA', 'RGBa'):
|
||||||
color_mode = 'RGB'
|
color_mode = 'RGB'
|
||||||
else:
|
else:
|
||||||
raise Unsupported(f'"{self.name}" uses the {mode} colour mode, which is not generated automatically')
|
raise Unsupported(f'"{self.name}" usa o modo de cor {mode}, que não é gerado automaticamente')
|
||||||
if has_alpha:
|
if has_alpha:
|
||||||
image = image.convert('RGBA' if color_mode == 'RGB' else 'LA')
|
image = image.convert('RGBA' if color_mode == 'RGB' else 'LA')
|
||||||
width, height = image.size
|
width, height = image.size
|
||||||
@@ -304,29 +307,29 @@ class PdfPage:
|
|||||||
try:
|
try:
|
||||||
self.pdf = pikepdf.open(path)
|
self.pdf = pikepdf.open(path)
|
||||||
except pikepdf.PasswordError as exc:
|
except pikepdf.PasswordError as exc:
|
||||||
raise Unsupported(f'"{name}" is password-protected') from exc
|
raise Unsupported(f'"{name}" está protegido por senha') from exc
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
raise Unsupported(f'"{name}" is not a PDF this generator can read') from exc
|
raise Unsupported(f'"{name}" não é um PDF que o gerador consiga ler') from exc
|
||||||
try:
|
try:
|
||||||
pages = len(self.pdf.pages)
|
pages = len(self.pdf.pages)
|
||||||
if pages != 1:
|
if pages != 1:
|
||||||
raise Unsupported(f'"{name}" has {pages} pages; only single-page PDFs are generated automatically')
|
raise Unsupported(f'"{name}" tem {pages} páginas; só PDFs de uma página são gerados automaticamente')
|
||||||
self.page = self.pdf.pages[0]
|
self.page = self.pdf.pages[0]
|
||||||
self.rotation = int(self.page.rotation) % 360
|
self.rotation = int(self.page.rotation) % 360
|
||||||
if self.rotation not in (0, 90, 180, 270):
|
if self.rotation not in (0, 90, 180, 270):
|
||||||
raise Unsupported(f'"{name}" has an unsupported page rotation')
|
raise Unsupported(f'"{name}" tem uma rotação de página não suportada')
|
||||||
box = [float(v) for v in self.page.cropbox]
|
box = [float(v) for v in self.page.cropbox]
|
||||||
except Unsupported:
|
except Unsupported:
|
||||||
self.pdf.close()
|
self.pdf.close()
|
||||||
raise
|
raise
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
self.pdf.close()
|
self.pdf.close()
|
||||||
raise Unsupported(f'"{name}" has a page this generator cannot read') from exc
|
raise Unsupported(f'"{name}" tem uma página que o gerador não consegue ler') from exc
|
||||||
self.x0, self.y0 = min(box[0], box[2]), min(box[1], box[3])
|
self.x0, self.y0 = min(box[0], box[2]), min(box[1], box[3])
|
||||||
self.w, self.h = abs(box[2] - box[0]), abs(box[3] - box[1])
|
self.w, self.h = abs(box[2] - box[0]), abs(box[3] - box[1])
|
||||||
if self.w <= 0 or self.h <= 0:
|
if self.w <= 0 or self.h <= 0:
|
||||||
self.pdf.close()
|
self.pdf.close()
|
||||||
raise Unsupported(f'"{name}" has an empty page')
|
raise Unsupported(f'"{name}" tem uma página vazia')
|
||||||
# As displayed, which is what the proportions are checked against.
|
# As displayed, which is what the proportions are checked against.
|
||||||
self.size = (self.h, self.w) if self.rotation in (90, 270) else (self.w, self.h)
|
self.size = (self.h, self.w) if self.rotation in (90, 270) else (self.w, self.h)
|
||||||
|
|
||||||
@@ -373,7 +376,7 @@ def check_layout(item, sizes, vector=()):
|
|||||||
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:
|
if height > billed + HEIGHT_TOLERANCE_CM:
|
||||||
raise Unsupported(f'layout is {height} cm long but only {billed} cm were billed')
|
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']:
|
||||||
width_px, height_px = sizes[placement['source_index']]
|
width_px, height_px = sizes[placement['source_index']]
|
||||||
@@ -384,8 +387,8 @@ def check_layout(item, sizes, vector=()):
|
|||||||
drift = abs((width_px / height_px) / (width_cm / length_cm) - 1)
|
drift = abs((width_px / height_px) / (width_cm / length_cm) - 1)
|
||||||
if drift > ASPECT_TOLERANCE:
|
if drift > ASPECT_TOLERANCE:
|
||||||
source = production['sources'][placement['source_index']]
|
source = production['sources'][placement['source_index']]
|
||||||
raise Unsupported(f'file {placement["source_index"] + 1} has proportions that do not match '
|
raise Unsupported(f'o arquivo {placement["source_index"] + 1} tem proporções diferentes '
|
||||||
f'the quoted {source["width_cm"]} x {source["length_cm"]} cm')
|
f'das cotadas ({source["width_cm"]} × {source["length_cm"]} cm)')
|
||||||
if placement['source_index'] in vector:
|
if placement['source_index'] in vector:
|
||||||
continue
|
continue
|
||||||
dpi = width_px / (width_cm / 2.54)
|
dpi = width_px / (width_cm / 2.54)
|
||||||
@@ -404,8 +407,8 @@ def render(item, files, out, title):
|
|||||||
exported as PDF keeps its vectors, fonts and transparency.
|
exported as PDF keeps its vectors, fonts and transparency.
|
||||||
"""
|
"""
|
||||||
production = item['production']
|
production = item['production']
|
||||||
if production.get('version') != 2:
|
if production.get('version') not in PRODUCTION_VERSIONS:
|
||||||
raise Unsupported('item uses an obsolete production layout')
|
raise Unsupported('o item usa uma montagem antiga')
|
||||||
sources = []
|
sources = []
|
||||||
try:
|
try:
|
||||||
for index in range(len(production['sources'])):
|
for index in range(len(production['sources'])):
|
||||||
|
|||||||
@@ -9,6 +9,12 @@ The result is an ordinary upload row owned by an identity derived from the
|
|||||||
order, already marked clean: its only inputs are artwork that passed the
|
order, already marked clean: its only inputs are artwork that passed the
|
||||||
malware scan, and the bytes are written here. The operator still decides
|
malware scan, and the bytes are written here. The operator still decides
|
||||||
whether it becomes the final file; generation never approves anything.
|
whether it becomes the final file; generation never approves anything.
|
||||||
|
|
||||||
|
Sheets of several GB are the normal order, and decoding one would take more
|
||||||
|
memory than the worker has. A source above LARGE_SOURCE_BYTES is never
|
||||||
|
opened: a finished sheet placed whole on the film is already its own print
|
||||||
|
file, so the original becomes the print file; any other layout is prepared
|
||||||
|
by hand from the original.
|
||||||
"""
|
"""
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
@@ -25,6 +31,9 @@ from .printfile import Unsupported, render
|
|||||||
|
|
||||||
CLAIM_TIMEOUT = timedelta(minutes=15)
|
CLAIM_TIMEOUT = timedelta(minutes=15)
|
||||||
MAX_ATTEMPTS = 3
|
MAX_ATTEMPTS = 3
|
||||||
|
LARGE_SOURCE_BYTES = int(os.environ.get('PRINT_DECODE_MAX_BYTES', str(300 * 1024 * 1024)))
|
||||||
|
# Formats the operator can import as they are.
|
||||||
|
PRINTABLE_ORIGINAL = ('.png', '.jpg', '.jpeg', '.tif', '.tiff', '.pdf')
|
||||||
|
|
||||||
|
|
||||||
def generated_identity(order_id):
|
def generated_identity(order_id):
|
||||||
@@ -60,13 +69,26 @@ def render_one(storage):
|
|||||||
c.execute('''UPDATE dtf_local.print_files SET status='rendering', claimed_at=now(),
|
c.execute('''UPDATE dtf_local.print_files SET status='rendering', claimed_at=now(),
|
||||||
attempts=attempts+1 WHERE id=%s''', (job['id'],))
|
attempts=attempts+1 WHERE id=%s''', (job['id'],))
|
||||||
item = job['snapshot']['items'][job['item_index']]
|
item = job['snapshot']['items'][job['item_index']]
|
||||||
uploads = c.execute('''SELECT id,name,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()
|
([UUID(u) for u in item['uploads']],)).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']
|
([UUID(u) for u in item['uploads']],)).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):
|
||||||
|
original = whole_sheet(item, by_id)
|
||||||
|
if original:
|
||||||
|
with connect() as c:
|
||||||
|
c.execute('''UPDATE dtf_local.print_files SET status='ready', upload_id=%s, detail=%s,
|
||||||
|
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'})
|
||||||
|
audit('print_file_manual', order=str(job['order_id']), item=job['item_index'])
|
||||||
|
return True
|
||||||
try:
|
try:
|
||||||
result = produce(storage, job, item, by_id)
|
result = produce(storage, job, item, by_id)
|
||||||
except Unsupported as reason:
|
except Unsupported as reason:
|
||||||
@@ -96,14 +118,33 @@ def render_one(storage):
|
|||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def whole_sheet(item, uploads):
|
||||||
|
"""The original, when the item is one finished sheet placed whole, once,
|
||||||
|
unrotated and unmirrored, across the film: then it is the print file."""
|
||||||
|
spec = item.get('production') or {}
|
||||||
|
sources, placements = spec.get('sources') or [], spec.get('placements') or []
|
||||||
|
if len(item['uploads']) != 1 or len(sources) != 1 or len(placements) != 1:
|
||||||
|
return None
|
||||||
|
source, place = sources[0], placements[0]
|
||||||
|
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 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 (pdf path, name, size, evidence)."""
|
||||||
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('an original file is missing or not cleared by the malware scan')
|
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('an original file has passed its retention period')
|
raise Unsupported('um arquivo original passou do prazo de guarda')
|
||||||
number = job['number']
|
number = job['number']
|
||||||
name = f'pedido-{number}-item-{job["item_index"] + 1}.pdf'
|
name = f'pedido-{number}-item-{job["item_index"] + 1}.pdf'
|
||||||
with tempfile.TemporaryDirectory(prefix='print-') as scratch:
|
with tempfile.TemporaryDirectory(prefix='print-') as scratch:
|
||||||
|
|||||||
94
app/quote_review.py
Normal file
@@ -0,0 +1,94 @@
|
|||||||
|
"""Quote approval: automatic at checkout, by an operator for the exceptions.
|
||||||
|
|
||||||
|
A quote the customer can pay is priced here from the server's own ladders,
|
||||||
|
whether an operator approved it on the Kanban or the Site approved it the
|
||||||
|
moment it was created. The Site is a shop: a customer who can price the order
|
||||||
|
should be able to pay for it straight away, at any hour, so only orders a
|
||||||
|
person must look at before charging wait for the Kanban (review_reason).
|
||||||
|
|
||||||
|
The grade (and so the discount) is worked out in the customer's browser and
|
||||||
|
checked against the files before an automatic approval (app/grade_check.py);
|
||||||
|
a grade the files do not support waits for review. The layout is still the
|
||||||
|
browser's (roadmap 3.9): the API checks its geometry. Operators see every
|
||||||
|
order's grade and artwork at Arte recebida.
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
from decimal import Decimal
|
||||||
|
|
||||||
|
from fastapi import HTTPException
|
||||||
|
from psycopg.types.json import Jsonb
|
||||||
|
|
||||||
|
from . import payments
|
||||||
|
from .core.models import PRODUCTION_VERSIONS
|
||||||
|
from .core.pricing import is_manual, manual_extra_cents, price
|
||||||
|
from .runtime import freight, upload_row
|
||||||
|
from .scanning import require_clean
|
||||||
|
|
||||||
|
AUTO = 'auto'
|
||||||
|
|
||||||
|
|
||||||
|
def auto_approve_enabled():
|
||||||
|
return os.environ.get('QUOTE_AUTO_APPROVE', 'true').lower() == 'true'
|
||||||
|
|
||||||
|
|
||||||
|
def max_auto_metres():
|
||||||
|
return Decimal(os.environ.get('QUOTE_AUTO_MAX_METRES', '50'))
|
||||||
|
|
||||||
|
|
||||||
|
def review_reason(draft):
|
||||||
|
"""Why this quote needs a person before it can be paid, or None."""
|
||||||
|
if not auto_approve_enabled():
|
||||||
|
return 'Aprovação automática desligada'
|
||||||
|
total = sum(Decimal(str(item['metres'])) for item in draft['items'])
|
||||||
|
if total > max_auto_metres():
|
||||||
|
return f'Pedido acima de {max_auto_metres():g} m'
|
||||||
|
for item in draft['items']:
|
||||||
|
if item.get('production', {}).get('version') not in PRODUCTION_VERSIONS:
|
||||||
|
return 'Montagem antiga'
|
||||||
|
# The Site grades only the art it could analyse; anything else is
|
||||||
|
# priced at the full rate. A discount on it did not come from the Site.
|
||||||
|
if item['quality_status'] == 'unverified' and item['grade'] != 0:
|
||||||
|
return 'Nota informada sem análise da arte'
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def approve(c, row, items, reviewer):
|
||||||
|
"""Price the reviewed items and bind them to the quote; returns the approval.
|
||||||
|
`row` must be locked by the caller."""
|
||||||
|
draft = row['draft']
|
||||||
|
if row['approved']:
|
||||||
|
raise HTTPException(409, 'Esta cotação já foi aprovada e não pode mudar.')
|
||||||
|
if any(item.get('production', {}).get('version') not in PRODUCTION_VERSIONS for item in draft['items']):
|
||||||
|
raise HTTPException(409, 'A cotação usa uma montagem antiga: o cliente precisa montar o pedido de novo.')
|
||||||
|
if len(items) != len(draft['items']):
|
||||||
|
raise HTTPException(422, 'Confira todos os itens da cotação.')
|
||||||
|
priced = []
|
||||||
|
for item, original in zip(items, draft['items']):
|
||||||
|
if item.mode != original['mode'] or list(map(str, item.uploads)) != original['uploads']:
|
||||||
|
raise HTTPException(422, 'O produto e os arquivos não podem mudar na revisão.')
|
||||||
|
if item.production.model_dump(mode='json') != original['production'] or item.quality_status != original['quality_status'] or item.quality_acknowledged != original['quality_acknowledged']:
|
||||||
|
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:
|
||||||
|
upload = upload_row(c, upload_id, row['owner'])
|
||||||
|
require_clean(upload)
|
||||||
|
names[str(upload_id)] = upload['name']
|
||||||
|
extra = manual_extra_cents() if is_manual(original, names) else 0
|
||||||
|
priced.append({**price(item.mode, str(item.metres), item.grade, extra),
|
||||||
|
'uploads': original['uploads'], 'production': original['production'],
|
||||||
|
'quality_status': original['quality_status'],
|
||||||
|
'quality_acknowledged': original['quality_acknowledged']})
|
||||||
|
metres = sum(Decimal(i['billed_metres']) for i in priced)
|
||||||
|
try:
|
||||||
|
quoted_freight = freight.quote(draft['freight']['service'], draft['freight'].get('postal_code', ''),
|
||||||
|
metres, sum(i['total_cents'] for i in priced))
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(422, str(exc))
|
||||||
|
approved = {'customer': draft['customer'], 'items': priced, 'freight': quoted_freight,
|
||||||
|
'destination': draft.get('destination'),
|
||||||
|
'total_cents': sum(i['total_cents'] for i in priced) + quoted_freight['total_cents']}
|
||||||
|
c.execute('UPDATE dtf_local.quotes SET approved=%s, reviewed_by=%s, approved_at=now() WHERE id=%s',
|
||||||
|
(Jsonb(approved), reviewer, row['id']))
|
||||||
|
# Approved and payable now: the files wait for the payment, not for ever.
|
||||||
|
payments.hold_uploads(c, payments.quote_uploads(approved), payments.UNPAID_HOLD)
|
||||||
|
return approved
|
||||||
@@ -13,6 +13,7 @@ from fastapi import HTTPException
|
|||||||
from psycopg.types.json import Jsonb
|
from psycopg.types.json import Jsonb
|
||||||
|
|
||||||
from .adapters import FakeFreight, FakePayment, LocalS3Storage, require_runtime
|
from .adapters import FakeFreight, FakePayment, LocalS3Storage, require_runtime
|
||||||
|
from .freight import FreightOptions
|
||||||
from .core.secrets import load as load_secret_files
|
from .core.secrets import load as load_secret_files
|
||||||
|
|
||||||
# Secret files must resolve before any configuration below is read.
|
# Secret files must resolve before any configuration below is read.
|
||||||
@@ -25,7 +26,15 @@ if os.environ.get('PAYMENT_ADAPTER') == 'mercadopago':
|
|||||||
payment = MercadoPagoPayment()
|
payment = MercadoPagoPayment()
|
||||||
else:
|
else:
|
||||||
payment = FakePayment()
|
payment = FakePayment()
|
||||||
freight = FakeFreight()
|
# Every carrier configured; the simulated one only where there is none.
|
||||||
|
_carriers = []
|
||||||
|
if os.environ.get('FREIGHT_ADAPTER') == 'jadlog':
|
||||||
|
from .jadlog import JadlogFreight
|
||||||
|
_carriers.append(JadlogFreight())
|
||||||
|
from . import correios as _correios
|
||||||
|
if _correios.configured():
|
||||||
|
_carriers.append(_correios.CorreiosFreight())
|
||||||
|
freight = FreightOptions(_carriers or [FakeFreight()])
|
||||||
ENVIRONMENT = os.environ.get('APP_ENV', 'local')
|
ENVIRONMENT = os.environ.get('APP_ENV', 'local')
|
||||||
PUBLIC_ORIGIN = os.environ.get('PUBLIC_ORIGIN', 'http://localhost')
|
PUBLIC_ORIGIN = os.environ.get('PUBLIC_ORIGIN', 'http://localhost')
|
||||||
ALLOWED_HOSTS = [host for host in os.environ.get('ALLOWED_HOSTS', 'localhost,127.0.0.1').split(',') if host]
|
ALLOWED_HOSTS = [host for host in os.environ.get('ALLOWED_HOSTS', 'localhost,127.0.0.1').split(',') if host]
|
||||||
@@ -42,29 +51,73 @@ BOARD_QUOTE_LIMIT = int(os.environ.get('BOARD_QUOTE_LIMIT', '100'))
|
|||||||
PART_BYTES = int(os.environ.get('UPLOAD_PART_BYTES', '8388608'))
|
PART_BYTES = int(os.environ.get('UPLOAD_PART_BYTES', '8388608'))
|
||||||
if not 5242880 <= PART_BYTES <= 67108864:
|
if not 5242880 <= PART_BYTES <= 67108864:
|
||||||
raise RuntimeError('UPLOAD_PART_BYTES must be between 5 and 64 MiB')
|
raise RuntimeError('UPLOAD_PART_BYTES must be between 5 and 64 MiB')
|
||||||
STATES = {'rec': 'Arte recebida', 'tra': 'Arte tratada', 'fil': 'Fila de impressão',
|
STATES = {'rec': 'Arte recebida', 'tra': 'Arte conferida', 'fil': 'Fila de impressão',
|
||||||
'imp': 'Imprimindo', 'cor': 'Correção', 'fin': 'Finalizado'}
|
'imp': 'Imprimindo', 'cor': 'Correção', 'fin': 'Finalizado'}
|
||||||
TRANSITIONS = {'rec': ['tra','cor'], 'tra': ['fil','cor'], 'fil': ['imp','cor'],
|
TRANSITIONS = {'rec': ['tra','cor'], 'tra': ['fil','cor'], 'fil': ['imp','cor'],
|
||||||
'imp': ['fin','cor'], 'cor': ['rec','tra'], 'fin': []}
|
'imp': ['fin','cor'], 'cor': ['rec','tra'], 'fin': []}
|
||||||
|
# Undoing a move made by mistake: one stage back, with an internal reason. It
|
||||||
|
# is not a correction: the customer is not told and approved finals stay.
|
||||||
|
BACK = {'tra': 'rec', 'fil': 'tra', 'imp': 'fil', 'fin': 'imp'}
|
||||||
|
|
||||||
|
|
||||||
|
def real_delivery():
|
||||||
|
"""Whether a real carrier is configured; a simulated price is local only."""
|
||||||
|
return any(carrier.name != 'fake' for carrier in freight.carriers)
|
||||||
|
|
||||||
|
|
||||||
|
def delivery_services():
|
||||||
|
"""The delivery options the cart may offer: none outside the local stack
|
||||||
|
without a real carrier, so a customer sees only pickup."""
|
||||||
|
if ENVIRONMENT != 'local' and not real_delivery():
|
||||||
|
return []
|
||||||
|
return [{'service': service, 'description': label} for service, label in freight.services.items()]
|
||||||
|
|
||||||
|
|
||||||
|
def require_delivery_available(service):
|
||||||
|
"""Outside the local stack, a simulated freight price must never reach a
|
||||||
|
customer: until a real freight provider exists, only pickup is offered."""
|
||||||
|
if service != 'pickup' and ENVIRONMENT != 'local' and not real_delivery():
|
||||||
|
raise HTTPException(503, 'A entrega ainda não está disponível. Escolha a retirada em Franca.')
|
||||||
|
|
||||||
|
|
||||||
def upload_row(c, upload_id, session_id, lock=False):
|
def upload_row(c, upload_id, session_id, lock=False):
|
||||||
row = c.execute('SELECT * FROM dtf_local.uploads WHERE id=%s AND owner=%s' +
|
row = c.execute('SELECT * FROM dtf_local.uploads WHERE id=%s AND owner=%s' +
|
||||||
(' FOR UPDATE' if lock else ''), (upload_id, session_id)).fetchone()
|
(' FOR UPDATE' if lock else ''), (upload_id, session_id)).fetchone()
|
||||||
if not row:
|
if not row:
|
||||||
raise HTTPException(404, 'Upload not found')
|
raise HTTPException(404, 'Arquivo não encontrado. Escolha o arquivo de novo.')
|
||||||
days = 30 if row['complete'] else 1
|
days = 30 if row['complete'] else 1
|
||||||
if row['purged_at'] or row['expires_at'] <= datetime.now(timezone.utc) or row['created_at'] < datetime.now(timezone.utc) - timedelta(days=days):
|
if row['purged_at'] or row['expires_at'] <= datetime.now(timezone.utc) or row['created_at'] < datetime.now(timezone.utc) - timedelta(days=days):
|
||||||
raise HTTPException(410, 'Upload expired; select the file again')
|
raise HTTPException(410, 'Este arquivo expirou. Escolha o arquivo de novo.')
|
||||||
return row
|
return row
|
||||||
|
|
||||||
|
|
||||||
|
def order_code(order_id):
|
||||||
|
"""What a customer calls an order: the first 8 characters of its id, in
|
||||||
|
capitals ("F6B9CDBC"). It is stable and says nothing about how many orders
|
||||||
|
the store has, unlike the sequential number the operators work with."""
|
||||||
|
return str(order_id).replace('-', '')[:8].upper()
|
||||||
|
|
||||||
|
|
||||||
def quote_view(c, row):
|
def quote_view(c, row):
|
||||||
|
from .quote_review import review_reason # it imports this module
|
||||||
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 notification updates it) from one still waiting.
|
||||||
|
# Its PIX expiry and time let the Kanban tell "tried to pay" from "never tried".
|
||||||
|
attempt = c.execute('''SELECT method,status,response->>'status_detail' AS status_detail,
|
||||||
|
response->>'expires_at' AS expires_at, created_at
|
||||||
|
FROM dtf_local.payment_intents WHERE quote_id=%s ORDER BY created_at DESC LIMIT 1''', (row['id'],)).fetchone()
|
||||||
|
if attempt and attempt['status'] == 'rejected':
|
||||||
|
from .payment_messages import rejection
|
||||||
|
attempt = {**attempt, 'message': rejection(attempt['status_detail'])}
|
||||||
expired = row['approved_at'] and row['approved_at'] < datetime.now(timezone.utc)-timedelta(hours=24)
|
expired = row['approved_at'] and row['approved_at'] < datetime.now(timezone.utc)-timedelta(hours=24)
|
||||||
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'],
|
||||||
'status': 'paid' if order else 'expired' if expired else 'approved' if row['approved'] else 'pending_review',
|
'status': 'paid' if order else 'discarded' if row.get('discarded_at') else 'expired' if expired
|
||||||
|
else 'approved' if row['approved'] else 'pending_review',
|
||||||
|
'auto_approved': row.get('reviewed_by') == 'auto',
|
||||||
|
'review_reason': None if row['approved'] else (row.get('review_note') or review_reason(row['draft'])),
|
||||||
|
'payment': attempt,
|
||||||
'order': order}
|
'order': order}
|
||||||
|
|
||||||
|
|
||||||
@@ -75,7 +128,7 @@ def enqueue(c, event_key, provider, payload):
|
|||||||
|
|
||||||
def owned_order(c, oid, identity, lock=False):
|
def owned_order(c, oid, identity, lock=False):
|
||||||
row = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s AND owner=%s'+(' FOR UPDATE' if lock else ''), (oid,identity)).fetchone()
|
row = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s AND owner=%s'+(' FOR UPDATE' if lock else ''), (oid,identity)).fetchone()
|
||||||
if not row: raise HTTPException(404, 'Order not found')
|
if not row: raise HTTPException(404, 'Pedido não encontrado.')
|
||||||
return row
|
return row
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,14 @@
|
|||||||
"""Local ClamAV boundary. Unknown/error/over-limit results NEVER release artwork."""
|
"""Releasing artwork: ClamAV up to its size limit, a format check above it.
|
||||||
|
|
||||||
|
Unknown or error results NEVER release artwork. ClamAV scans files up to
|
||||||
|
scan_limit_bytes() (at most 2 GB). Since 2026-10-21 a file is at most 1 GB and
|
||||||
|
the scan limit is the same, so every file is scanned. Were the upload limit
|
||||||
|
raised above it again, a larger file would be released only if its first bytes
|
||||||
|
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
|
||||||
|
does not look for malware inside a valid file.
|
||||||
|
"""
|
||||||
|
import re
|
||||||
import socket
|
import socket
|
||||||
import struct
|
import struct
|
||||||
import time
|
import time
|
||||||
@@ -30,10 +40,9 @@ class ClamAV:
|
|||||||
return self.command(b'VERSION').decode('utf-8','replace')
|
return self.command(b'VERSION').decode('utf-8','replace')
|
||||||
|
|
||||||
def scan(self, stream, size):
|
def scan(self, stream, size):
|
||||||
if size > scan_limit_bytes():
|
|
||||||
return 'rejected', 'File exceeds the malware scan limit'
|
|
||||||
with socket.create_connection(('scanner',3310),timeout=10) as sock:
|
with socket.create_connection(('scanner',3310),timeout=10) as sock:
|
||||||
sock.settimeout(150)
|
# A 2 GB file takes minutes to stream and scan.
|
||||||
|
sock.settimeout(900)
|
||||||
sock.sendall(b'zINSTREAM\0')
|
sock.sendall(b'zINSTREAM\0')
|
||||||
sent=0
|
sent=0
|
||||||
for chunk in stream.iter_chunks(chunk_size=65536):
|
for chunk in stream.iter_chunks(chunk_size=65536):
|
||||||
@@ -52,6 +61,37 @@ class ClamAV:
|
|||||||
if result.endswith(b' FOUND'):return 'rejected','Malware or unsafe scan condition detected'
|
if result.endswith(b' FOUND'):return 'rejected','Malware or unsafe scan condition detected'
|
||||||
return 'error','Scanner could not verify this file'
|
return 'error','Scanner could not verify this file'
|
||||||
|
|
||||||
|
# What each accepted extension must start with. AI files are PDF or PostScript;
|
||||||
|
# CDR and WebP are RIFF containers with their own form type.
|
||||||
|
TIFF = (b'II*\x00', b'MM\x00*', b'II+\x00', b'MM\x00+')
|
||||||
|
SIGNATURES = {
|
||||||
|
'png': (b'\x89PNG\r\n\x1a\n',),
|
||||||
|
'jpg': (b'\xff\xd8\xff',), 'jpeg': (b'\xff\xd8\xff',),
|
||||||
|
'tif': TIFF, 'tiff': TIFF,
|
||||||
|
'pdf': (b'%PDF-',), 'ai': (b'%PDF-', b'%!PS'),
|
||||||
|
'psd': (b'8BPS',), 'psb': (b'8BPS',),
|
||||||
|
}
|
||||||
|
RIFF_FORMS = {'cdr': re.compile(rb'^RIFF....CDR', re.S), 'webp': re.compile(rb'^RIFF....WEBP', re.S)}
|
||||||
|
HEAD_BYTES = 64
|
||||||
|
|
||||||
|
|
||||||
|
def format_matches(name, head):
|
||||||
|
"""Whether a file's first bytes are those of the format its name claims."""
|
||||||
|
ext = name.rsplit('.', 1)[-1].lower() if '.' in name else ''
|
||||||
|
if ext in RIFF_FORMS:
|
||||||
|
return bool(RIFF_FORMS[ext].match(head))
|
||||||
|
return any(head.startswith(sig) for sig in SIGNATURES.get(ext, ()))
|
||||||
|
|
||||||
|
|
||||||
|
def check_large(storage, row):
|
||||||
|
"""Release decision for a file above the antivirus limit."""
|
||||||
|
head = storage.client.get_object(Bucket=storage.bucket, Key=row['object_key'],
|
||||||
|
Range=f'bytes=0-{HEAD_BYTES - 1}')['Body'].read()
|
||||||
|
if format_matches(row['name'], head):
|
||||||
|
return 'clean', 'Acima do limite do antivírus; formato do arquivo conferido'
|
||||||
|
return 'rejected', 'O conteúdo do arquivo não corresponde ao formato do nome'
|
||||||
|
|
||||||
|
|
||||||
def scan_one(storage, scanner=None):
|
def scan_one(storage, scanner=None):
|
||||||
scanner=scanner or ClamAV()
|
scanner=scanner or ClamAV()
|
||||||
with connect() as c:
|
with connect() as c:
|
||||||
@@ -60,6 +100,9 @@ def scan_one(storage, scanner=None):
|
|||||||
ORDER BY created_at FOR UPDATE SKIP LOCKED LIMIT 1''').fetchone()
|
ORDER BY created_at FOR UPDATE SKIP LOCKED LIMIT 1''').fetchone()
|
||||||
if not row:return False
|
if not row:return False
|
||||||
try:
|
try:
|
||||||
|
if row['size'] > scan_limit_bytes():
|
||||||
|
state,reason=check_large(storage,row)
|
||||||
|
else:
|
||||||
stream=storage.client.get_object(Bucket=storage.bucket,Key=row['object_key'])['Body']
|
stream=storage.client.get_object(Bucket=storage.bucket,Key=row['object_key'])['Body']
|
||||||
try:state,reason=scanner.scan(stream,row['size'])
|
try:state,reason=scanner.scan(stream,row['size'])
|
||||||
finally:stream.close()
|
finally:stream.close()
|
||||||
|
|||||||
159
app/schema.sql
@@ -35,6 +35,9 @@ CREATE TABLE IF NOT EXISTS dtf_local.accounts (
|
|||||||
id uuid PRIMARY KEY, email text UNIQUE NOT NULL, password_hash text NOT NULL,
|
id uuid PRIMARY KEY, email text UNIQUE NOT NULL, password_hash text NOT NULL,
|
||||||
profile jsonb NOT NULL, created_at timestamptz NOT NULL DEFAULT now()
|
profile jsonb NOT NULL, created_at timestamptz NOT NULL DEFAULT now()
|
||||||
);
|
);
|
||||||
|
-- Confirmed with an e-mailed code (at signup or on a change): only then does
|
||||||
|
-- the account bring guest orders placed with its CPF/CNPJ and e-mail.
|
||||||
|
ALTER TABLE dtf_local.accounts ADD COLUMN IF NOT EXISTS email_verified boolean NOT NULL DEFAULT false;
|
||||||
CREATE TABLE IF NOT EXISTS dtf_local.sessions (
|
CREATE TABLE IF NOT EXISTS dtf_local.sessions (
|
||||||
id uuid PRIMARY KEY, owner uuid NOT NULL,
|
id uuid PRIMARY KEY, owner uuid NOT NULL,
|
||||||
expires_at timestamptz NOT NULL DEFAULT now() + interval '7 days'
|
expires_at timestamptz NOT NULL DEFAULT now() + interval '7 days'
|
||||||
@@ -107,6 +110,13 @@ CREATE TABLE IF NOT EXISTS dtf_local.provider_tokens (
|
|||||||
connected_by text NOT NULL, connected_at timestamptz NOT NULL DEFAULT now(),
|
connected_by text NOT NULL, connected_at timestamptz NOT NULL DEFAULT now(),
|
||||||
updated_at timestamptz NOT NULL DEFAULT now()
|
updated_at timestamptz NOT NULL DEFAULT now()
|
||||||
);
|
);
|
||||||
|
-- Renewal health, cleared by the next successful renewal or connection.
|
||||||
|
-- refused_at: the provider rejected the refresh token, so only a new
|
||||||
|
-- connection helps. offline: the grant is not bound to a login session.
|
||||||
|
ALTER TABLE dtf_local.provider_tokens ADD COLUMN IF NOT EXISTS refresh_failed_at timestamptz;
|
||||||
|
ALTER TABLE dtf_local.provider_tokens ADD COLUMN IF NOT EXISTS refresh_error text;
|
||||||
|
ALTER TABLE dtf_local.provider_tokens ADD COLUMN IF NOT EXISTS refused_at timestamptz;
|
||||||
|
ALTER TABLE dtf_local.provider_tokens ADD COLUMN IF NOT EXISTS offline boolean NOT NULL DEFAULT false;
|
||||||
-- Single-use states for an operator-started OAuth connection. They protect the
|
-- Single-use states for an operator-started OAuth connection. They protect the
|
||||||
-- callback, which arrives cross-site without the operator's cookie.
|
-- callback, which arrives cross-site without the operator's cookie.
|
||||||
CREATE TABLE IF NOT EXISTS dtf_local.oauth_states (
|
CREATE TABLE IF NOT EXISTS dtf_local.oauth_states (
|
||||||
@@ -127,6 +137,23 @@ CREATE TABLE IF NOT EXISTS dtf_local.print_files (
|
|||||||
UNIQUE(order_id,item_index)
|
UNIQUE(order_id,item_index)
|
||||||
);
|
);
|
||||||
|
|
||||||
|
-- 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.
|
||||||
|
CREATE TABLE IF NOT EXISTS dtf_local.backups (
|
||||||
|
id uuid PRIMARY KEY, started_at timestamptz NOT NULL, finished_at timestamptz NOT NULL,
|
||||||
|
status text NOT NULL CHECK(status IN ('ok','failed')), object_key text, bytes bigint, detail text
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS backups_finished ON dtf_local.backups(finished_at DESC);
|
||||||
|
-- "Fazer backup agora" in the Kanban; the backup service looks every minute.
|
||||||
|
CREATE TABLE IF NOT EXISTS dtf_local.backup_requests (
|
||||||
|
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, requested_at timestamptz NOT NULL DEFAULT now(),
|
||||||
|
requested_by text NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Why a quote waits for review, when the reason came from its files (the grade
|
||||||
|
-- the server recomputed) and cannot be worked out again from the draft alone.
|
||||||
|
ALTER TABLE dtf_local.quotes ADD COLUMN IF NOT EXISTS review_note text;
|
||||||
|
|
||||||
CREATE INDEX IF NOT EXISTS uploads_owner ON dtf_local.uploads(owner);
|
CREATE INDEX IF NOT EXISTS uploads_owner ON dtf_local.uploads(owner);
|
||||||
|
|
||||||
-- Indexes follow the queries the application actually issues. Only these; every
|
-- Indexes follow the queries the application actually issues. Only these; every
|
||||||
@@ -146,6 +173,9 @@ CREATE INDEX IF NOT EXISTS order_files_upload ON dtf_local.order_files(upload_id
|
|||||||
-- index stays the size of the backlog rather than of all history.
|
-- index stays the size of the backlog rather than of all history.
|
||||||
CREATE INDEX IF NOT EXISTS outbox_pending ON dtf_local.outbox(available_at, id)
|
CREATE INDEX IF NOT EXISTS outbox_pending ON dtf_local.outbox(available_at, id)
|
||||||
WHERE delivered_at IS NULL;
|
WHERE delivered_at IS NULL;
|
||||||
|
-- The system sends no WhatsApp messages (the client's own n8n does, from Tiny):
|
||||||
|
-- its old log rows would wait for an adapter that no longer exists.
|
||||||
|
DELETE FROM dtf_local.outbox WHERE provider='whatsapp';
|
||||||
|
|
||||||
-- The scanner and the retention sweep both walk live uploads in arrival order.
|
-- The scanner and the retention sweep both walk live uploads in arrival order.
|
||||||
-- now() cannot appear in a partial index predicate, so the time comparisons stay
|
-- now() cannot appear in a partial index predicate, so the time comparisons stay
|
||||||
@@ -173,6 +203,9 @@ 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');
|
||||||
|
|
||||||
|
-- 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;
|
||||||
|
|
||||||
-- 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.
|
||||||
ALTER TABLE dtf_local.payment_events ADD COLUMN IF NOT EXISTS resolved_at timestamptz;
|
ALTER TABLE dtf_local.payment_events ADD COLUMN IF NOT EXISTS resolved_at timestamptz;
|
||||||
@@ -183,3 +216,129 @@ CREATE INDEX IF NOT EXISTS payment_events_open_issues ON dtf_local.payment_event
|
|||||||
|
|
||||||
-- Payment intents look up by quote (customer retry) and by provider id (webhook).
|
-- Payment intents look up by quote (customer retry) and by provider id (webhook).
|
||||||
CREATE INDEX IF NOT EXISTS payment_intents_quote ON dtf_local.payment_intents(quote_id, created_at DESC);
|
CREATE INDEX IF NOT EXISTS payment_intents_quote ON dtf_local.payment_intents(quote_id, created_at DESC);
|
||||||
|
|
||||||
|
-- A small picture of each artwork (about 480 px), made by the customer's
|
||||||
|
-- browser from the file it already read, so the Kanban shows what an order is
|
||||||
|
-- without opening the original. It goes when the file's bytes go.
|
||||||
|
CREATE TABLE IF NOT EXISTS dtf_local.upload_thumbnails (
|
||||||
|
upload_id uuid PRIMARY KEY REFERENCES dtf_local.uploads(id),
|
||||||
|
mime text NOT NULL, data bytea NOT NULL, created_at timestamptz NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
-- An operator may discard an unpaid quote (it leaves the Kanban and can no
|
||||||
|
-- longer be paid) and cancel a paid order (it leaves the board but keeps its
|
||||||
|
-- payment and history; a refund is made at the provider).
|
||||||
|
ALTER TABLE dtf_local.quotes ADD COLUMN IF NOT EXISTS discarded_at timestamptz;
|
||||||
|
ALTER TABLE dtf_local.quotes ADD COLUMN IF NOT EXISTS discarded_by text;
|
||||||
|
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS cancelled_at timestamptz;
|
||||||
|
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS cancelled_by text;
|
||||||
|
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS cancel_reason text;
|
||||||
|
|
||||||
|
-- An order's place in its column's queue, when an operator dragged it up or
|
||||||
|
-- down. Empty means "by payment time"; it is cleared when the order moves on.
|
||||||
|
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS queue_key double precision;
|
||||||
|
|
||||||
|
-- The company name behind each customer's CNPJ, from the public registry
|
||||||
|
-- (app/cnpj.py). failed_at alone: the lookup failed and is retried later.
|
||||||
|
CREATE TABLE IF NOT EXISTS dtf_local.cnpj_names (
|
||||||
|
cnpj text PRIMARY KEY, legal_name text, trade_name text,
|
||||||
|
fetched_at timestamptz, failed_at timestamptz
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Who may do what on the Kanban. superadmin is the system's own account (set
|
||||||
|
-- from the console); administrators manage users and machines; gestão runs
|
||||||
|
-- the business; designers approve artwork; operadores produce; vendedores only read.
|
||||||
|
ALTER TABLE dtf_local.operators ADD COLUMN IF NOT EXISTS role text NOT NULL DEFAULT 'admin';
|
||||||
|
ALTER TABLE dtf_local.operators DROP CONSTRAINT IF EXISTS operators_role;
|
||||||
|
ALTER TABLE dtf_local.operators ADD CONSTRAINT operators_role
|
||||||
|
CHECK (role IN ('superadmin','admin','gestao','designer','operador','vendedor'));
|
||||||
|
-- The print machines, and which products each prints. An order keeps the
|
||||||
|
-- machine someone chose (machine_chosen) or the one given automatically: the
|
||||||
|
-- active machine of its product with the fewest metres open (app/machines.py).
|
||||||
|
-- limit_metres: the metres open a machine takes before the next order goes to
|
||||||
|
-- another one; NULL is no limit.
|
||||||
|
CREATE TABLE IF NOT EXISTS dtf_local.machines (
|
||||||
|
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()
|
||||||
|
);
|
||||||
|
ALTER TABLE dtf_local.machines ADD COLUMN IF NOT EXISTS limit_metres numeric(8,1) CHECK (limit_metres > 0);
|
||||||
|
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS machine_id uuid REFERENCES dtf_local.machines(id) ON DELETE SET NULL;
|
||||||
|
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS machine_chosen boolean NOT NULL DEFAULT false;
|
||||||
|
-- Until now only a person's choice was stored.
|
||||||
|
DO $$ BEGIN
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM dtf_local.migrations WHERE name='machine-chosen-v1') THEN
|
||||||
|
UPDATE dtf_local.orders SET machine_chosen=true WHERE machine_id IS NOT NULL;
|
||||||
|
INSERT INTO dtf_local.migrations VALUES('machine-chosen-v1');
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
-- The machines an operator works on; none means every machine.
|
||||||
|
CREATE TABLE IF NOT EXISTS dtf_local.operator_machines (
|
||||||
|
operator_id uuid NOT NULL REFERENCES dtf_local.operators(id) ON DELETE CASCADE,
|
||||||
|
machine_id uuid NOT NULL REFERENCES dtf_local.machines(id) ON DELETE CASCADE,
|
||||||
|
PRIMARY KEY (operator_id, machine_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
|
||||||
|
-- E-mail (app/mail.py): queued in the transaction that caused it, sent by the
|
||||||
|
-- worker. A recovery message's text is erased once sent; the subject stays.
|
||||||
|
CREATE TABLE IF NOT EXISTS dtf_local.mail_queue (
|
||||||
|
id bigserial PRIMARY KEY, kind text NOT NULL,
|
||||||
|
to_addr text NOT NULL, subject text NOT NULL, body text NOT NULL,
|
||||||
|
created_at timestamptz NOT NULL DEFAULT now(), available_at timestamptz NOT NULL DEFAULT now(),
|
||||||
|
attempts int NOT NULL DEFAULT 0, last_error text, sent_at timestamptz, failed_at timestamptz
|
||||||
|
);
|
||||||
|
-- The HTML version of a customer message (app/mail_html.py); erased with the
|
||||||
|
-- text for a code or a recovery link.
|
||||||
|
ALTER TABLE dtf_local.mail_queue ADD COLUMN IF NOT EXISTS html text;
|
||||||
|
CREATE INDEX IF NOT EXISTS mail_queue_pending ON dtf_local.mail_queue(available_at, id)
|
||||||
|
WHERE sent_at IS NULL AND failed_at IS NULL;
|
||||||
|
-- A customer's password recovery: only the token's hash is kept, for an hour,
|
||||||
|
-- and it works once.
|
||||||
|
CREATE TABLE IF NOT EXISTS dtf_local.password_resets (
|
||||||
|
token_hash text PRIMARY KEY, account_id uuid NOT NULL REFERENCES dtf_local.accounts(id) ON DELETE CASCADE,
|
||||||
|
created_at timestamptz NOT NULL DEFAULT now(), expires_at timestamptz NOT NULL, used_at timestamptz
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS password_resets_account ON dtf_local.password_resets(account_id);
|
||||||
|
-- Kanban users who get the team's alerts by e-mail.
|
||||||
|
ALTER TABLE dtf_local.operators ADD COLUMN IF NOT EXISTS alerts boolean NOT NULL DEFAULT false;
|
||||||
|
|
||||||
|
-- "Aguardando contato": an order whose file needs a word with the customer
|
||||||
|
-- before printing. A mark on the card, not a stage: the order stays where it is.
|
||||||
|
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS contact_since timestamptz;
|
||||||
|
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS contact_by text;
|
||||||
|
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS contact_note text;
|
||||||
|
|
||||||
|
-- A signup waiting for its e-mail code. The account is created only when the
|
||||||
|
-- code is entered; the password is already hashed and the code only hashed.
|
||||||
|
CREATE TABLE IF NOT EXISTS dtf_local.account_signups (
|
||||||
|
id uuid PRIMARY KEY, email text NOT NULL, profile jsonb NOT NULL, password_hash text NOT NULL,
|
||||||
|
code_hash text, created_at timestamptz NOT NULL DEFAULT now(), sent_at timestamptz NOT NULL DEFAULT now(),
|
||||||
|
expires_at timestamptz NOT NULL, sends int NOT NULL DEFAULT 1, attempts int NOT NULL DEFAULT 0,
|
||||||
|
done_at timestamptz
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS account_signups_created ON dtf_local.account_signups(created_at);
|
||||||
|
|
||||||
|
-- A customer changing the account's e-mail: the change waits for the code sent
|
||||||
|
-- to the new address, as a signup does, and the old address is told.
|
||||||
|
CREATE TABLE IF NOT EXISTS dtf_local.email_changes (
|
||||||
|
id uuid PRIMARY KEY, account_id uuid NOT NULL REFERENCES dtf_local.accounts(id) ON DELETE CASCADE,
|
||||||
|
new_email text NOT NULL, code_hash text NOT NULL, created_at timestamptz NOT NULL DEFAULT now(),
|
||||||
|
sent_at timestamptz NOT NULL DEFAULT now(), expires_at timestamptz NOT NULL,
|
||||||
|
sends int NOT NULL DEFAULT 1, attempts int NOT NULL DEFAULT 0, done_at timestamptz
|
||||||
|
);
|
||||||
|
-- Accounts confirmed by a code before email_verified existed. The signups
|
||||||
|
-- are deleted after a day; the code e-mail sent before the account existed
|
||||||
|
-- stays in the queue.
|
||||||
|
UPDATE dtf_local.accounts a SET email_verified=true WHERE NOT a.email_verified AND (
|
||||||
|
EXISTS (SELECT 1 FROM dtf_local.account_signups s WHERE s.email=a.email AND s.done_at IS NOT NULL)
|
||||||
|
OR EXISTS (SELECT 1 FROM dtf_local.email_changes e WHERE e.account_id=a.id AND e.new_email=a.email AND e.done_at IS NOT NULL)
|
||||||
|
OR EXISTS (SELECT 1 FROM dtf_local.mail_queue m WHERE m.kind='code' AND lower(m.to_addr)=a.email
|
||||||
|
AND m.created_at<=a.created_at));
|
||||||
|
-- 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,
|
||||||
|
-- the team's alerts and a test.
|
||||||
|
-- Defined once, here: the schema runs on every start, and an earlier, narrower
|
||||||
|
-- copy would refuse the rows of the kinds added after it.
|
||||||
|
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'));
|
||||||
|
|||||||
592
app/tiny.py
@@ -13,12 +13,29 @@ workers never spend the same one.
|
|||||||
|
|
||||||
Orders are created by contact and product id: the customer's contact is found
|
Orders are created by contact and product id: the customer's contact is found
|
||||||
by CNPJ or created, and each product mode maps to a product that must already
|
by CNPJ or created, and each product mode maps to a product that must already
|
||||||
exist in Tiny (PRODUCT_SETTINGS).
|
exist in Tiny (PRODUCT_SETTINGS), sold by the metre. A mode can instead be
|
||||||
|
sold as the client's own SKUs per length (SKU_SETTINGS): the order is then a
|
||||||
|
sum, 1,30 m = 1 × "1 metro" + 1 × "30 cm", at the price the customer paid.
|
||||||
|
|
||||||
Idempotency: the outbox may deliver the same event more than once. Every order
|
Idempotency: the outbox may deliver the same event more than once. Every order
|
||||||
carries numeroOrdemCompra = "DTF-<order number>", and before creating one the
|
carries numeroOrdemCompra = "DTF-<order number>", and before creating one the
|
||||||
customer's recent orders are searched for that number, so a second delivery
|
customer's recent orders are searched for that number, so a second delivery
|
||||||
finds the first order instead of creating another.
|
finds the first order instead of creating another.
|
||||||
|
|
||||||
|
Customer notices: the client sends WhatsApp messages from Tiny's order
|
||||||
|
situação (Tiny webhook -> their middleware -> n8n), on Aprovado, Pronto para
|
||||||
|
envio (pickup only), Enviado and Entregue. With TINY_STATUS_UPDATES on, the
|
||||||
|
Kanban moves the Tiny order along with it:
|
||||||
|
|
||||||
|
paid (Arte recebida) -> Aprovada (the "approved" notice)
|
||||||
|
Imprimindo -> Preparando envio (no notice)
|
||||||
|
Finalizado, pickup -> Pronto para envio (the pickup notice)
|
||||||
|
Finalizado, delivery -> unchanged: the team invoices and ships in Tiny
|
||||||
|
cancelled -> Cancelada (no notice)
|
||||||
|
|
||||||
|
An order someone already moved further in Tiny is never moved back, and an
|
||||||
|
invoiced one is not cancelled here (its nota fiscal is cancelled in Tiny).
|
||||||
|
Pickup orders carry the client's "retirar pessoalmente" forma de envio.
|
||||||
"""
|
"""
|
||||||
import os
|
import os
|
||||||
import secrets
|
import secrets
|
||||||
@@ -35,13 +52,72 @@ AUTH = 'https://accounts.tiny.com.br/realms/tiny/protocol/openid-connect'
|
|||||||
# _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'}
|
||||||
|
# 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 mode's product id.
|
||||||
|
SKU_SETTINGS = {'file': 'TINY_SKU_TEXTIL_FOLHA', 'avulsa': 'TINY_SKU_TEXTIL_AVULSA',
|
||||||
|
'uvfile': 'TINY_SKU_UV_FOLHA', 'uv': 'TINY_SKU_UV_AVULSA'}
|
||||||
|
# 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.
|
||||||
|
STEP_SETTINGS = {'file': 'TINY_SKU10_TEXTIL_FOLHA', 'avulsa': 'TINY_SKU10_TEXTIL_AVULSA',
|
||||||
|
'uvfile': 'TINY_SKU10_UV_FOLHA', 'uv': 'TINY_SKU10_UV_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'}
|
||||||
|
# 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.UV.1MT per metre and DTFIMP.UV.010CM per 10 cm, the ready sheet and
|
||||||
|
# loose artwork alike. The settings above only override these.
|
||||||
|
SKU_DEFAULTS = {'file': 'DTFIMP.TX', 'avulsa': 'DTFIMP.TX'}
|
||||||
|
STEP_DEFAULTS = {'uvfile': 'DTFIMP.UV.010CM', 'uv': 'DTFIMP.UV.010CM'}
|
||||||
|
METRE_DEFAULTS = {'uvfile': 'DTFIMP.UV.1MT', 'uv': 'DTFIMP.UV.1MT'}
|
||||||
PRODUCTS = {'file': 'DTF Têxtil 57 cm · folha montada',
|
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 28,5 cm · folha montada',
|
'uvfile': 'DTF UV 28,5 cm · folha montada',
|
||||||
'uv': 'DTF UV 28,5 cm · artes avulsas'}
|
'uv': 'DTF UV 28,5 cm · artes avulsas'}
|
||||||
# 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.
|
||||||
|
READY_SEARCH_DAYS = 45
|
||||||
|
# Tiny v3 order situações (PUT /pedidos/{id}/situacao).
|
||||||
|
ABERTA, APROVADA, PRONTO_ENVIO, ENVIADA, ENTREGUE, CANCELADA, NAO_ENTREGUE = 0, 3, 7, 5, 6, 2, 9
|
||||||
|
PREPARANDO, FATURADA, INCOMPLETA = 4, 1, 8
|
||||||
|
SITUACOES = {0: 'Aberta', 3: 'Aprovada', 4: 'Preparando envio', 1: 'Faturada', 7: 'Pronto para envio',
|
||||||
|
5: 'Enviada', 6: 'Entregue', 2: 'Cancelada', 8: 'Dados incompletos', 9: 'Não entregue'}
|
||||||
|
# The client's customer notices (Tiny webhook -> middleware -> n8n -> WhatsApp)
|
||||||
|
# react to these situações. Off until go-live: while n8n still sends the
|
||||||
|
# designer message for DTFIMP products on "Aprovado", setting it would reach
|
||||||
|
# Site customers.
|
||||||
|
STATUS_UPDATES_SETTING = 'TINY_STATUS_UPDATES'
|
||||||
|
# The client's custom "retirar pessoalmente" forma de envio (v2 code X), which
|
||||||
|
# the pickup notice is keyed on. Found in Tiny by name; this setting, an id,
|
||||||
|
# only overrides that.
|
||||||
|
PICKUP_SETTING = 'TINY_FORMA_ENVIO_RETIRADA'
|
||||||
|
PICKUP_NAME = 'retir'
|
||||||
|
PICKUP_EXACT = 'retirar pessoalmente'
|
||||||
|
# Dropstar's own ids, read from its store orders with app.tiny_probe exemplo
|
||||||
|
# (2026-10-19). The app may not list formas de recebimento, so these are not
|
||||||
|
# looked up: Pix and credit card, as the store's orders are paid, and the
|
||||||
|
# DropStar carrier its pickup orders name.
|
||||||
|
RECEIPT_METHODS = {'pix': 919478952, 'card': 977460722}
|
||||||
|
PICKUP_CARRIER = 761565838
|
||||||
|
# Dropstar's answers (2026-10-21): the store's financial category "DUPLICADO
|
||||||
|
# DROP" (it goes in pagamento.categoria), no seller (the team links one in
|
||||||
|
# Tiny), and the marcador, added after the order is created: POST /pedidos
|
||||||
|
# does not take marcadores. Their corrections of the same day replace the
|
||||||
|
# category and the seller with new ones (DTF SITE, SITE DTF), sent by id once
|
||||||
|
# Dropstar creates them, and the marcador with SITE DTF: capitals, no accent,
|
||||||
|
# no extra space, the string Kondado reads for Power BI.
|
||||||
|
CATEGORY = 965775137
|
||||||
|
TAG = 'SITE DTF'
|
||||||
|
# Freight is the sender's (CIF), as on the store's orders.
|
||||||
|
FREIGHT_PAID_BY = 'R'
|
||||||
|
# The forma de envio each delivery service uses, by name; a Correios service
|
||||||
|
# is the forma de frete with its contract code (app/correios.py).
|
||||||
|
CARRIERS = {'pac': 'correios', 'sedex': 'correios', 'jadlog': 'jadlog'}
|
||||||
STATE_MINUTES = 10
|
STATE_MINUTES = 10
|
||||||
|
# Renewal runs about every four hours against a one-day refresh token, so
|
||||||
|
# less than this left means renewals have been failing for hours.
|
||||||
|
EXPIRY_WARNING = timedelta(hours=12)
|
||||||
# Brazil has had no daylight saving since 2019; the order date is the local day.
|
# Brazil has had no daylight saving since 2019; the order date is the local day.
|
||||||
BRASILIA = timezone(timedelta(hours=-3))
|
BRASILIA = timezone(timedelta(hours=-3))
|
||||||
|
|
||||||
@@ -68,7 +144,95 @@ def configured():
|
|||||||
|
|
||||||
|
|
||||||
def required_settings():
|
def required_settings():
|
||||||
return ['TINY_CLIENT_ID', 'TINY_CLIENT_SECRET', 'TINY_REDIRECT_URI'] + list(PRODUCT_SETTINGS.values())
|
"""The OAuth application, and a product id for each mode not sold by SKU."""
|
||||||
|
return ['TINY_CLIENT_ID', 'TINY_CLIENT_SECRET', 'TINY_REDIRECT_URI'] + [
|
||||||
|
setting for mode, setting in PRODUCT_SETTINGS.items() if not (sku_prefix(mode) or step_sku(mode))]
|
||||||
|
|
||||||
|
|
||||||
|
# The stack passes every setting, empty when unset, so empty means "the
|
||||||
|
# default". A setting given for a mode replaces its default, in either form.
|
||||||
|
def setting(name):
|
||||||
|
return os.environ.get(name, '').strip()
|
||||||
|
|
||||||
|
|
||||||
|
def sku_prefix(mode):
|
||||||
|
return setting(SKU_SETTINGS[mode]) or ('' if setting(STEP_SETTINGS[mode]) else SKU_DEFAULTS.get(mode, ''))
|
||||||
|
|
||||||
|
|
||||||
|
def step_sku(mode):
|
||||||
|
return setting(STEP_SETTINGS[mode]) or ('' if setting(SKU_SETTINGS[mode]) else STEP_DEFAULTS.get(mode, ''))
|
||||||
|
|
||||||
|
|
||||||
|
def metre_sku(mode):
|
||||||
|
"""The metre SKU paired with a 10 cm SKU, or '' when the 10 cm one goes alone."""
|
||||||
|
if not step_sku(mode):
|
||||||
|
return ''
|
||||||
|
return setting(METRE_SETTINGS[mode]) or ('' if setting(STEP_SETTINGS[mode]) else METRE_DEFAULTS.get(mode, ''))
|
||||||
|
|
||||||
|
|
||||||
|
def mode_codes(mode):
|
||||||
|
"""Every SKU code a mode sold by SKU uses, or [] for a mode sold by product id."""
|
||||||
|
if step_sku(mode):
|
||||||
|
return [code for code in (metre_sku(mode), step_sku(mode)) if code]
|
||||||
|
return sku_codes(sku_prefix(mode)) if sku_prefix(mode) else []
|
||||||
|
|
||||||
|
|
||||||
|
def sku_codes(prefix):
|
||||||
|
"""The metre SKU and the nine of 10 to 90 cm, as the client's catalogue names them."""
|
||||||
|
return [f'{prefix}.100CM'] + [f'{prefix}.{cm:04d}CM' for cm in range(10, 100, 10)]
|
||||||
|
|
||||||
|
|
||||||
|
def tenths(item):
|
||||||
|
"""The billed length in 10 cm steps; the Site bills in them."""
|
||||||
|
billed = Decimal(item['billed_metres'])
|
||||||
|
steps = billed * 10
|
||||||
|
if steps != steps.to_integral_value():
|
||||||
|
raise TinyError(f'{billed} m is not a whole number of 10 cm steps')
|
||||||
|
return int(steps), int(billed * int(item['unit_cents']))
|
||||||
|
|
||||||
|
|
||||||
|
def step_lines(item, code, metre=''):
|
||||||
|
"""(code, quantity, cents each) for a 10 cm SKU, after whole metres of the
|
||||||
|
metre SKU when there is one, adding up to the item's total; a rest that
|
||||||
|
does not divide goes on one line of its own."""
|
||||||
|
steps, total = tenths(item)
|
||||||
|
lines = []
|
||||||
|
if metre and steps >= 10:
|
||||||
|
metres, steps = divmod(steps, 10)
|
||||||
|
unit = int(item['unit_cents'])
|
||||||
|
lines.append((metre, metres, unit))
|
||||||
|
total -= metres * unit
|
||||||
|
if not steps:
|
||||||
|
return lines
|
||||||
|
return lines + split_steps(code, steps, total)
|
||||||
|
|
||||||
|
|
||||||
|
def split_steps(code, steps, total):
|
||||||
|
each, rest = divmod(total, steps)
|
||||||
|
if not rest:
|
||||||
|
return [(code, steps, each)]
|
||||||
|
return [(code, steps - 1, each), (code, 1, each + rest)] if steps > 1 else [(code, 1, total)]
|
||||||
|
|
||||||
|
|
||||||
|
def sku_lines(item, prefix):
|
||||||
|
"""(code, quantity, cents each) adding up to the item: whole metres as the
|
||||||
|
metre SKU, the rest as one 10 cm SKU. The Site bills in 10 cm steps, so
|
||||||
|
the rest always has a SKU; the lines carry the price the customer paid."""
|
||||||
|
billed = Decimal(item['billed_metres'])
|
||||||
|
centimetres = billed * 100
|
||||||
|
if centimetres != centimetres.to_integral_value() or int(centimetres) % 10:
|
||||||
|
raise TinyError(f'{billed} m is not a whole number of 10 cm steps')
|
||||||
|
metres, rest = divmod(int(centimetres), 100)
|
||||||
|
unit = int(item['unit_cents'])
|
||||||
|
lines = [(f'{prefix}.100CM', metres, unit)] if metres else []
|
||||||
|
if rest:
|
||||||
|
# What is left of the item's total, so the order adds up to the cent.
|
||||||
|
lines.append((f'{prefix}.{rest:04d}CM', 1, int(billed * unit) - metres * unit))
|
||||||
|
return lines
|
||||||
|
|
||||||
|
|
||||||
|
def status_updates():
|
||||||
|
return os.environ.get(STATUS_UPDATES_SETTING, '').lower() == 'true'
|
||||||
|
|
||||||
|
|
||||||
# OAuth -------------------------------------------------------------------
|
# OAuth -------------------------------------------------------------------
|
||||||
@@ -86,44 +250,78 @@ class TinyAuth:
|
|||||||
self.http = httpx.Client(timeout=20, transport=transport)
|
self.http = httpx.Client(timeout=20, transport=transport)
|
||||||
self.clock = clock
|
self.clock = clock
|
||||||
|
|
||||||
def authorize_url(self, operator):
|
def authorize_url(self, operator, offline=True):
|
||||||
"""Start a connection. The state is single-use, short-lived, and only an
|
"""Start a connection. The state is single-use, short-lived, and only an
|
||||||
authenticated operator can create one, which is what protects the
|
authenticated operator can create one, which is what protects the
|
||||||
callback: Tiny's redirect back is cross-site, so the operator's
|
callback: Tiny's redirect back is cross-site, so the operator's
|
||||||
SameSite=Strict cookie does not travel with it."""
|
SameSite=Strict cookie does not travel with it.
|
||||||
|
|
||||||
|
offline_access asks for a grant that is not bound to a login session,
|
||||||
|
so the connection lasts as long as it keeps being renewed. Tiny's
|
||||||
|
documented refresh token otherwise lasts one day."""
|
||||||
state = secrets.token_urlsafe(32)
|
state = secrets.token_urlsafe(32)
|
||||||
with self.connect() as c:
|
with self.connect() as c:
|
||||||
c.execute("DELETE FROM dtf_local.oauth_states WHERE expires_at<now()")
|
c.execute("DELETE FROM dtf_local.oauth_states WHERE expires_at<now()")
|
||||||
c.execute('''INSERT INTO dtf_local.oauth_states(state,provider,operator,expires_at)
|
c.execute('''INSERT INTO dtf_local.oauth_states(state,provider,operator,expires_at)
|
||||||
VALUES(%s,'tiny',%s,now()+%s)''', (state, operator, timedelta(minutes=STATE_MINUTES)))
|
VALUES(%s,'tiny',%s,now()+%s)''', (state, operator, timedelta(minutes=STATE_MINUTES)))
|
||||||
return f'{AUTH}/auth?' + urlencode({'response_type': 'code', 'client_id': self.client_id,
|
return f'{AUTH}/auth?' + urlencode({'response_type': 'code', 'client_id': self.client_id,
|
||||||
'redirect_uri': self.redirect_uri, 'scope': 'openid',
|
'redirect_uri': self.redirect_uri,
|
||||||
|
'scope': 'openid offline_access' if offline else 'openid',
|
||||||
'state': state})
|
'state': state})
|
||||||
|
|
||||||
def complete(self, code, state):
|
def _claim(self, c, state):
|
||||||
"""Exchange the authorisation code; returns the operator who started it."""
|
|
||||||
with self.connect() as c:
|
|
||||||
row = c.execute('''DELETE FROM dtf_local.oauth_states WHERE state=%s AND provider='tiny'
|
row = c.execute('''DELETE FROM dtf_local.oauth_states WHERE state=%s AND provider='tiny'
|
||||||
AND expires_at>now() RETURNING operator''', (state,)).fetchone()
|
AND expires_at>now() RETURNING operator''', (state,)).fetchone()
|
||||||
if not row:
|
if not row:
|
||||||
raise TinyError('Unknown or expired authorisation state')
|
raise TinyError('Unknown or expired authorisation state')
|
||||||
|
return row['operator']
|
||||||
|
|
||||||
|
def complete(self, code, state):
|
||||||
|
"""Exchange the authorisation code; returns the operator who started it."""
|
||||||
|
with self.connect() as c:
|
||||||
|
operator = self._claim(c, state)
|
||||||
tokens = self._token({'grant_type': 'authorization_code', 'code': code,
|
tokens = self._token({'grant_type': 'authorization_code', 'code': code,
|
||||||
'redirect_uri': self.redirect_uri})
|
'redirect_uri': self.redirect_uri})
|
||||||
self._store(c, tokens, row['operator'])
|
self._store(c, tokens, operator)
|
||||||
return row['operator']
|
return operator
|
||||||
|
|
||||||
|
def without_offline(self, state):
|
||||||
|
"""Tiny refused the offline_access scope for this application: spend the
|
||||||
|
operator's state and start again with a session-bound grant."""
|
||||||
|
with self.connect() as c:
|
||||||
|
operator = self._claim(c, state)
|
||||||
|
return self.authorize_url(operator, offline=False)
|
||||||
|
|
||||||
def status(self):
|
def status(self):
|
||||||
with self.connect() as c:
|
with self.connect() as c:
|
||||||
row = c.execute('''SELECT connected_by,connected_at,refresh_expires_at
|
row = c.execute('''SELECT connected_by,connected_at,refresh_expires_at,updated_at,offline,
|
||||||
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:
|
||||||
return {'connected': False}
|
return {'connected': False}
|
||||||
expired = row['refresh_expires_at'] and row['refresh_expires_at'] <= datetime.now(timezone.utc)
|
now = datetime.now(timezone.utc)
|
||||||
return {'connected': not expired, 'connected_by': row['connected_by'],
|
expires = row['refresh_expires_at']
|
||||||
'connected_at': row['connected_at'], 'expires_at': row['refresh_expires_at']}
|
expired = bool(expires and expires <= now)
|
||||||
|
if row['refused_at']:
|
||||||
|
problem = 'refused'
|
||||||
|
elif expired:
|
||||||
|
problem = 'expired'
|
||||||
|
elif row['refresh_failed_at']:
|
||||||
|
problem = 'renewal-failing'
|
||||||
|
elif expires and expires - now < EXPIRY_WARNING:
|
||||||
|
problem = 'expiring'
|
||||||
|
else:
|
||||||
|
problem = None
|
||||||
|
return {'connected': not expired and not row['refused_at'], 'problem': problem,
|
||||||
|
'connected_by': row['connected_by'], 'connected_at': row['connected_at'],
|
||||||
|
'renewed_at': row['updated_at'], 'expires_at': expires, 'offline': row['offline'],
|
||||||
|
'failed_at': row['refresh_failed_at']}
|
||||||
|
|
||||||
def access_token(self):
|
def access_token(self):
|
||||||
"""A valid access token, refreshing (and rotating) under a row lock."""
|
"""A valid access token, refreshing (and rotating) under a row lock.
|
||||||
|
|
||||||
|
A failed renewal is recorded after the lock is released, so the Kanban
|
||||||
|
can show it. A refused refresh token is never tried again: only a new
|
||||||
|
connection helps, and retrying it would only repeat the refusal."""
|
||||||
with self.connect() as c:
|
with self.connect() as c:
|
||||||
row = c.execute('''SELECT * FROM dtf_local.provider_tokens WHERE provider='tiny'
|
row = c.execute('''SELECT * FROM dtf_local.provider_tokens WHERE provider='tiny'
|
||||||
FOR UPDATE''').fetchone()
|
FOR UPDATE''').fetchone()
|
||||||
@@ -132,11 +330,25 @@ class TinyAuth:
|
|||||||
now = datetime.now(timezone.utc)
|
now = datetime.now(timezone.utc)
|
||||||
if row['access_expires_at'] > now + timedelta(seconds=60):
|
if row['access_expires_at'] > now + timedelta(seconds=60):
|
||||||
return row['access_token']
|
return row['access_token']
|
||||||
|
if row['refused_at']:
|
||||||
|
raise TinyNotConnected('Tiny refused the stored refresh token; connect again on the Kanban')
|
||||||
if row['refresh_expires_at'] and row['refresh_expires_at'] <= now:
|
if row['refresh_expires_at'] and row['refresh_expires_at'] <= now:
|
||||||
raise TinyNotConnected('The Tiny connection expired; connect again on the Kanban')
|
raise TinyNotConnected('The Tiny connection expired; connect again on the Kanban')
|
||||||
|
try:
|
||||||
tokens = self._token({'grant_type': 'refresh_token', 'refresh_token': row['refresh_token']})
|
tokens = self._token({'grant_type': 'refresh_token', 'refresh_token': row['refresh_token']})
|
||||||
|
except (TinyError, httpx.HTTPError, ValueError) as exc:
|
||||||
|
failure = exc
|
||||||
|
else:
|
||||||
self._store(c, tokens, row['connected_by'], refreshed=True)
|
self._store(c, tokens, row['connected_by'], refreshed=True)
|
||||||
return tokens['access_token']
|
return tokens['access_token']
|
||||||
|
# Only against the token that failed: another worker may have renewed since.
|
||||||
|
with self.connect() as c:
|
||||||
|
c.execute('''UPDATE dtf_local.provider_tokens SET refresh_failed_at=now(), refresh_error=%s,
|
||||||
|
refused_at=CASE WHEN %s THEN now() ELSE refused_at END
|
||||||
|
WHERE provider='tiny' AND refresh_token=%s''',
|
||||||
|
(str(failure)[:300] or type(failure).__name__, isinstance(failure, TinyNotConnected),
|
||||||
|
row['refresh_token']))
|
||||||
|
raise failure
|
||||||
|
|
||||||
def _token(self, form):
|
def _token(self, form):
|
||||||
response = self.http.post(f'{AUTH}/token', data={**form, 'client_id': self.client_id,
|
response = self.http.post(f'{AUTH}/token', data={**form, 'client_id': self.client_id,
|
||||||
@@ -152,18 +364,21 @@ class TinyAuth:
|
|||||||
def _store(self, c, tokens, operator, refreshed=False):
|
def _store(self, c, tokens, operator, refreshed=False):
|
||||||
now = datetime.now(timezone.utc)
|
now = datetime.now(timezone.utc)
|
||||||
access_expires = now + timedelta(seconds=int(tokens.get('expires_in', 300)))
|
access_expires = now + timedelta(seconds=int(tokens.get('expires_in', 300)))
|
||||||
|
# An offline grant reports refresh_expires_in 0: no fixed end.
|
||||||
refresh_in = tokens.get('refresh_expires_in')
|
refresh_in = tokens.get('refresh_expires_in')
|
||||||
refresh_expires = now + timedelta(seconds=int(refresh_in)) if refresh_in else None
|
refresh_expires = now + timedelta(seconds=int(refresh_in)) if refresh_in else None
|
||||||
|
offline = 'offline_access' in str(tokens.get('scope') or '').split()
|
||||||
c.execute('''INSERT INTO dtf_local.provider_tokens(provider,access_token,refresh_token,
|
c.execute('''INSERT INTO dtf_local.provider_tokens(provider,access_token,refresh_token,
|
||||||
access_expires_at,refresh_expires_at,connected_by,connected_at,updated_at)
|
access_expires_at,refresh_expires_at,connected_by,connected_at,updated_at,offline)
|
||||||
VALUES('tiny',%s,%s,%s,%s,%s,now(),now())
|
VALUES('tiny',%s,%s,%s,%s,%s,now(),now(),%s)
|
||||||
ON CONFLICT(provider) DO UPDATE SET access_token=EXCLUDED.access_token,
|
ON CONFLICT(provider) DO UPDATE SET access_token=EXCLUDED.access_token,
|
||||||
refresh_token=EXCLUDED.refresh_token, access_expires_at=EXCLUDED.access_expires_at,
|
refresh_token=EXCLUDED.refresh_token, access_expires_at=EXCLUDED.access_expires_at,
|
||||||
refresh_expires_at=EXCLUDED.refresh_expires_at, updated_at=now(),
|
refresh_expires_at=EXCLUDED.refresh_expires_at, updated_at=now(), offline=EXCLUDED.offline,
|
||||||
|
refresh_failed_at=NULL, refresh_error=NULL, refused_at=NULL,
|
||||||
connected_by=CASE WHEN %s THEN dtf_local.provider_tokens.connected_by ELSE EXCLUDED.connected_by END,
|
connected_by=CASE WHEN %s THEN dtf_local.provider_tokens.connected_by ELSE EXCLUDED.connected_by END,
|
||||||
connected_at=CASE WHEN %s THEN dtf_local.provider_tokens.connected_at ELSE now() END''',
|
connected_at=CASE WHEN %s THEN dtf_local.provider_tokens.connected_at ELSE now() END''',
|
||||||
(tokens['access_token'], tokens['refresh_token'], access_expires, refresh_expires,
|
(tokens['access_token'], tokens['refresh_token'], access_expires, refresh_expires,
|
||||||
operator, refreshed, refreshed))
|
operator, offline, refreshed, refreshed))
|
||||||
|
|
||||||
|
|
||||||
# Orders ------------------------------------------------------------------
|
# Orders ------------------------------------------------------------------
|
||||||
@@ -172,12 +387,38 @@ def money(cents):
|
|||||||
return float(Decimal(cents) / 100)
|
return float(Decimal(cents) / 100)
|
||||||
|
|
||||||
|
|
||||||
def contact_payload(order):
|
def punctuated(document):
|
||||||
|
"""A CPF or CNPJ as Tiny keeps it, 130.323.978-71 or 11.222.333/0001-81:
|
||||||
|
its searches match that exact text, so the bare digits find nothing."""
|
||||||
|
d = ''.join(ch for ch in str(document) if ch.isdigit())
|
||||||
|
if len(d) == 11:
|
||||||
|
return f'{d[:3]}.{d[3:6]}.{d[6:9]}-{d[9:]}'
|
||||||
|
if len(d) == 14:
|
||||||
|
return f'{d[:2]}.{d[2:5]}.{d[5:8]}/{d[8:12]}-{d[12:]}'
|
||||||
|
return d
|
||||||
|
|
||||||
|
|
||||||
|
def search_forms(document):
|
||||||
|
"""Punctuated first, as Tiny keeps it; then the bare digits, for a contact
|
||||||
|
someone typed in without punctuation."""
|
||||||
|
d = ''.join(ch for ch in str(document) if ch.isdigit())
|
||||||
|
return list(dict.fromkeys((punctuated(d), d)))
|
||||||
|
|
||||||
|
|
||||||
|
def contact_payload(order, company=None):
|
||||||
|
"""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
|
||||||
|
recipient or the e-mail. A CPF (11 digits) is a person (F), a CNPJ a
|
||||||
|
company (J)."""
|
||||||
customer = order['customer']
|
customer = order['customer']
|
||||||
destination = order.get('destination')
|
destination = order.get('destination')
|
||||||
contact = {'nome': (destination or {}).get('recipient') or customer['mail'],
|
company = company or {}
|
||||||
'tipoPessoa': 'J', 'cpfCnpj': customer['cnpj'], 'email': customer['mail'],
|
contact = {'nome': (company.get('legal') or customer.get('name') or (destination or {}).get('recipient')
|
||||||
|
or customer['mail']),
|
||||||
|
'tipoPessoa': 'F' if len(customer['cnpj']) == 11 else 'J', 'cpfCnpj': punctuated(customer['cnpj']), 'email': customer['mail'],
|
||||||
'celular': customer['zap'], 'situacao': 'A'}
|
'celular': customer['zap'], 'situacao': 'A'}
|
||||||
|
if company.get('trade'):
|
||||||
|
contact['fantasia'] = company['trade']
|
||||||
if destination:
|
if destination:
|
||||||
contact['endereco'] = address(destination)
|
contact['endereco'] = address(destination)
|
||||||
return contact
|
return contact
|
||||||
@@ -190,11 +431,35 @@ def address(destination):
|
|||||||
'uf': destination['state'], 'pais': 'Brasil'}
|
'uf': destination['state'], 'pais': 'Brasil'}
|
||||||
|
|
||||||
|
|
||||||
def order_payload(payload, contact_id, today=None):
|
def business_days_after(day, days):
|
||||||
"""The v3 'pedido' for a paid order's approved snapshot."""
|
"""The day `days` working days (Monday to Friday) after `day`."""
|
||||||
|
while days > 0:
|
||||||
|
day += timedelta(days=1)
|
||||||
|
if day.weekday() < 5:
|
||||||
|
days -= 1
|
||||||
|
return day
|
||||||
|
|
||||||
|
|
||||||
|
def order_payload(payload, contact_id, today=None, product_id=None, shipping=None):
|
||||||
|
"""The v3 'pedido' for a paid order's approved snapshot, filled in as the
|
||||||
|
store's own orders are: payment, carrier and expected date. product_id finds
|
||||||
|
a SKU's product id by its code; shipping(service) the forma de envio and de
|
||||||
|
frete of a delivery service or pickup."""
|
||||||
order = payload['order']
|
order = payload['order']
|
||||||
items = []
|
items = []
|
||||||
for item in order['items']:
|
for item in order['items']:
|
||||||
|
note = PRODUCTS[item['mode']] + f" · nota {item['grade']}"
|
||||||
|
prefix, step = sku_prefix(item['mode']), step_sku(item['mode'])
|
||||||
|
if step or prefix:
|
||||||
|
if product_id is None:
|
||||||
|
raise TinyError(f"{SKU_SETTINGS[item['mode']]} needs the SKUs looked up in Tiny")
|
||||||
|
lines = step_lines(item, step, metre_sku(item['mode'])) if step else sku_lines(item, prefix)
|
||||||
|
for index, (code, quantity, cents) in enumerate(lines):
|
||||||
|
line = {'produto': {'id': product_id(code)}, 'quantidade': quantity, 'valorUnitario': money(cents)}
|
||||||
|
if index == 0:
|
||||||
|
line['infoAdicional'] = note + f" · {item['billed_metres']} m"
|
||||||
|
items.append(line)
|
||||||
|
continue
|
||||||
setting = PRODUCT_SETTINGS[item['mode']]
|
setting = PRODUCT_SETTINGS[item['mode']]
|
||||||
product = os.environ.get(setting, '')
|
product = os.environ.get(setting, '')
|
||||||
if not product.isdigit():
|
if not product.isdigit():
|
||||||
@@ -202,16 +467,33 @@ def order_payload(payload, contact_id, today=None):
|
|||||||
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': PRODUCTS[item['mode']] + f" · nota {item['grade']}"})
|
'infoAdicional': note})
|
||||||
freight = order['freight']
|
freight = order['freight']
|
||||||
pickup = freight.get('service') == 'pickup'
|
service = freight.get('service')
|
||||||
pedido = {'data': (today or local_today()).isoformat(),
|
pickup = service == 'pickup'
|
||||||
|
day = today or local_today()
|
||||||
|
pedido = {'data': day.isoformat(),
|
||||||
'idContato': contact_id,
|
'idContato': contact_id,
|
||||||
'numeroOrdemCompra': purchase_order(payload['number']),
|
'numeroOrdemCompra': purchase_order(payload['number']),
|
||||||
'itens': items,
|
'itens': items,
|
||||||
'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': f"Site DTF · pago · {payload['order_id']}"}
|
'observacoesInternas': f"Site DTF · pago · {payload['order_id']}"}
|
||||||
|
carrier = shipping(service) if shipping else None
|
||||||
|
if carrier:
|
||||||
|
pedido['transportador'] = {'fretePorConta': FREIGHT_PAID_BY, **carrier}
|
||||||
|
# The carrier's time already counts production; a pickup is ready after it.
|
||||||
|
days = freight.get('days') if not pickup else int(os.environ.get('FREIGHT_PRODUCTION_DAYS') or 0)
|
||||||
|
if days is not None:
|
||||||
|
pedido['dataPrevista'] = business_days_after(day, int(days)).isoformat()
|
||||||
|
# Paid at once, in full, as the store's orders: one parcel on the day.
|
||||||
|
pedido['pagamento'] = {'categoria': {'id': CATEGORY}}
|
||||||
|
received = RECEIPT_METHODS.get((payload.get('payment') or {}).get('method'))
|
||||||
|
if received:
|
||||||
|
total = money(order['total_cents'])
|
||||||
|
pedido['pagamento'].update({'formaRecebimento': {'id': received},
|
||||||
|
'parcelas': [{'dias': 0, 'data': day.isoformat(), 'valor': total,
|
||||||
|
'formaRecebimento': {'id': received}}]})
|
||||||
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'],
|
||||||
@@ -223,14 +505,134 @@ def order_payload(payload, contact_id, today=None):
|
|||||||
return pedido
|
return pedido
|
||||||
|
|
||||||
|
|
||||||
|
def configured_product(orders, mode):
|
||||||
|
"""The Tiny product a mode's setting points at, or a reason it cannot be used."""
|
||||||
|
setting = PRODUCT_SETTINGS[mode]
|
||||||
|
value = os.environ.get(setting, '')
|
||||||
|
if not value.isdigit():
|
||||||
|
return None, f'{setting} sem id'
|
||||||
|
found = orders.request('GET', f'/produtos/{value}')
|
||||||
|
if found.get('situacao') != 'A':
|
||||||
|
return found, f"produto {value} não está ativo no Tiny ({found.get('situacao')})"
|
||||||
|
return found, 'ok'
|
||||||
|
|
||||||
|
|
||||||
|
def configured_skus(orders, mode):
|
||||||
|
"""Whether every SKU of a mode sold by SKU is an active product in Tiny."""
|
||||||
|
missing = []
|
||||||
|
for code in mode_codes(mode):
|
||||||
|
try:
|
||||||
|
orders.product_id(code)
|
||||||
|
except TinyError:
|
||||||
|
missing.append(code)
|
||||||
|
return 'ok' if not missing else 'SKU não encontrado entre os produtos ativos: ' + ', '.join(missing)
|
||||||
|
|
||||||
|
|
||||||
|
def find_pickup(orders):
|
||||||
|
"""The forma de envio named "Retirar pessoalmente" (Dropstar's), else the one
|
||||||
|
named like "retirar", or why there is not one."""
|
||||||
|
found = orders.request('GET', '/formas-envio', params={'nome': PICKUP_NAME, 'limit': 100}).get('itens') or []
|
||||||
|
named = [f for f in found if PICKUP_NAME in str(f.get('nome', '')).lower()]
|
||||||
|
# The account also has "Retirar na loja", unused: the exact name decides.
|
||||||
|
exact = [f for f in named if ' '.join(str(f.get('nome', '')).lower().split()) == PICKUP_EXACT]
|
||||||
|
if len(exact) == 1:
|
||||||
|
return exact[0], 'ok'
|
||||||
|
if len(named) == 1:
|
||||||
|
return named[0], 'ok'
|
||||||
|
if not named:
|
||||||
|
return None, 'nenhuma forma de envio com "retir" no nome no Tiny'
|
||||||
|
return None, 'mais de uma forma de envio com "retir" no nome: ' + ', '.join(
|
||||||
|
f"{f.get('nome')} ({f.get('id')})" for f in named) + f'; escolha uma em {PICKUP_SETTING}'
|
||||||
|
|
||||||
|
|
||||||
|
def find_shipping(orders, service):
|
||||||
|
"""The forma de envio and de frete for a service, as {'formaEnvio': ...,
|
||||||
|
'formaFrete': ...} (and the DropStar carrier for pickup), or None when Tiny
|
||||||
|
has no such forma de envio: the order then goes without it."""
|
||||||
|
if service == 'pickup':
|
||||||
|
method, _ = configured_pickup(orders)
|
||||||
|
if not method:
|
||||||
|
return None
|
||||||
|
detail = orders.request('GET', f"/formas-envio/{method['id']}")
|
||||||
|
options = detail.get('formasFrete') or []
|
||||||
|
# "Retirar em loja", as the store's pickup orders.
|
||||||
|
frete = next((f for f in options if PICKUP_NAME in str(f.get('nome', '')).lower()), options[0] if options else None)
|
||||||
|
found = {'id': PICKUP_CARRIER, 'formaEnvio': {'id': int(method['id'])}}
|
||||||
|
if frete:
|
||||||
|
found['formaFrete'] = {'id': int(frete['id'])}
|
||||||
|
return found
|
||||||
|
name = CARRIERS.get(service)
|
||||||
|
if not name:
|
||||||
|
return None
|
||||||
|
listed = orders.request('GET', '/formas-envio', params={'nome': name, 'limit': 100}).get('itens') or []
|
||||||
|
method = next((f for f in listed if str(f.get('nome', '')).strip().lower() == name), None)
|
||||||
|
if not method:
|
||||||
|
return None
|
||||||
|
options = orders.request('GET', f"/formas-envio/{method['id']}").get('formasFrete') or []
|
||||||
|
if name == 'correios':
|
||||||
|
from .correios import SERVICES
|
||||||
|
setting, default, _ = SERVICES[service]
|
||||||
|
code = (os.environ.get(setting) or default).strip()
|
||||||
|
frete = next((f for f in options if str(f.get('codigo', '')).strip() == code), None)
|
||||||
|
else:
|
||||||
|
frete = options[0] if options else None
|
||||||
|
found = {'formaEnvio': {'id': int(method['id'])}}
|
||||||
|
if frete:
|
||||||
|
found['formaFrete'] = {'id': int(frete['id'])}
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
def configured_pickup(orders):
|
||||||
|
"""The forma de envio used for pickup orders, or why there is none."""
|
||||||
|
value = os.environ.get(PICKUP_SETTING, '')
|
||||||
|
if value.isdigit():
|
||||||
|
return orders.request('GET', f'/formas-envio/{value}'), 'ok'
|
||||||
|
return find_pickup(orders)
|
||||||
|
|
||||||
|
|
||||||
|
def check(auth=None, transport=None, orders=None):
|
||||||
|
"""Read-only proof that the connection and permissions work: one order and
|
||||||
|
one contact listed, each product's SKUs found active and the pickup
|
||||||
|
forma de envio found, nothing created. Raises TinyNotConnected when there is no usable connection;
|
||||||
|
otherwise reports each read separately."""
|
||||||
|
orders = orders or TinyOrders(auth=auth or TinyAuth(), transport=transport)
|
||||||
|
|
||||||
|
def listed(path, **filters):
|
||||||
|
orders.request('GET', path, params={'limit': 1, **filters})
|
||||||
|
return 'ok'
|
||||||
|
|
||||||
|
# Unfiltered, a large account's order list times out ("Sua consulta levou
|
||||||
|
# muito tempo"): yesterday's orders prove the same permission.
|
||||||
|
since = (local_today() - timedelta(days=1)).isoformat()
|
||||||
|
reads = [('pedidos', lambda: listed('/pedidos', dataInicial=since)), ('contatos', lambda: listed('/contatos'))]
|
||||||
|
reads += [(PRODUCTS[mode], lambda mode=mode: configured_skus(orders, mode) if mode_codes(mode)
|
||||||
|
else configured_product(orders, mode)[1]) for mode in PRODUCT_SETTINGS]
|
||||||
|
reads.append(('forma de envio de retirada', lambda: configured_pickup(orders)[1]))
|
||||||
|
results = {}
|
||||||
|
for name, read in reads:
|
||||||
|
try:
|
||||||
|
results[name] = read()
|
||||||
|
except TinyNotConnected:
|
||||||
|
raise
|
||||||
|
except TinyError as exc:
|
||||||
|
results[name] = str(exc)[:200]
|
||||||
|
except httpx.HTTPError:
|
||||||
|
results[name] = 'sem resposta do Tiny'
|
||||||
|
return results
|
||||||
|
|
||||||
|
|
||||||
class TinyOrders:
|
class TinyOrders:
|
||||||
def __init__(self, auth=None, transport=None, today=None):
|
def __init__(self, auth=None, transport=None, today=None, names=None):
|
||||||
missing = [name for name in required_settings() if not os.environ.get(name)]
|
missing = [name for name in required_settings() if not os.environ.get(name)]
|
||||||
if auth is None and missing:
|
if auth is None and missing:
|
||||||
raise RuntimeError('Tiny needs ' + ', '.join(missing))
|
raise RuntimeError('Tiny needs ' + ', '.join(missing))
|
||||||
self.auth = auth or TinyAuth()
|
self.auth = auth or TinyAuth()
|
||||||
self.http = httpx.Client(base_url=API, transport=transport, timeout=30)
|
self.http = httpx.Client(base_url=API, transport=transport, timeout=30)
|
||||||
self.today = today
|
self.today = today
|
||||||
|
self.skus = {}
|
||||||
|
self.carriers = {}
|
||||||
|
# The company's names by CNPJ, for new contacts (app.cnpj.company).
|
||||||
|
self.names = names
|
||||||
|
|
||||||
def request(self, method, path, **kwargs):
|
def request(self, method, path, **kwargs):
|
||||||
headers = {'Authorization': f'Bearer {self.auth.access_token()}'}
|
headers = {'Authorization': f'Bearer {self.auth.access_token()}'}
|
||||||
@@ -241,36 +643,138 @@ class TinyOrders:
|
|||||||
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 {}
|
||||||
|
|
||||||
def contact(self, order):
|
def shipping(self, service):
|
||||||
cnpj = order['customer']['cnpj']
|
"""The forma de envio and de frete of a service, looked up once."""
|
||||||
found = self.request('GET', '/contatos', params={'cpfCnpj': cnpj, 'limit': 5})
|
if service not in self.carriers:
|
||||||
|
self.carriers[service] = find_shipping(self, service)
|
||||||
|
return self.carriers[service]
|
||||||
|
|
||||||
|
def product_id(self, code):
|
||||||
|
"""The id of the active product with this SKU code, remembered once found."""
|
||||||
|
if code not in self.skus:
|
||||||
|
found = self.request('GET', '/produtos', params={'codigo': code, 'situacao': 'A', 'limit': 10})
|
||||||
|
# The filter may match more than the exact code: DTFIMP.TX.010CM is
|
||||||
|
# a different product from DTFIMP.TX.0010CM.
|
||||||
|
match = [p for p in found.get('itens') or []
|
||||||
|
if str(p.get('sku') or p.get('codigo') or '') == code and p.get('situacao', 'A') == 'A']
|
||||||
|
if not match:
|
||||||
|
raise TinyError(f'SKU {code} não encontrado entre os produtos ativos do Tiny')
|
||||||
|
self.skus[code] = int(match[0]['id'])
|
||||||
|
return self.skus[code]
|
||||||
|
|
||||||
|
def find_contact(self, cnpj):
|
||||||
|
"""The id of the customer's existing contact, or None."""
|
||||||
|
for form in search_forms(cnpj):
|
||||||
|
found = self.request('GET', '/contatos', params={'cpfCnpj': form, 'limit': 5})
|
||||||
for entry in found.get('itens') or []:
|
for entry in found.get('itens') or []:
|
||||||
if ''.join(ch for ch in str(entry.get('cpfCnpj') or '') if ch.isdigit()) == cnpj:
|
if ''.join(ch for ch in str(entry.get('cpfCnpj') or '') if ch.isdigit()) == cnpj:
|
||||||
return entry['id']
|
return entry['id']
|
||||||
return self.request('POST', '/contatos', json=contact_payload(order))['id']
|
return None
|
||||||
|
|
||||||
def find(self, payload):
|
def contact(self, order):
|
||||||
|
cnpj = order['customer']['cnpj']
|
||||||
|
known = self.find_contact(cnpj)
|
||||||
|
if known:
|
||||||
|
return known
|
||||||
|
company = None
|
||||||
|
if self.names and len(cnpj) == 14:
|
||||||
|
try:
|
||||||
|
company = self.names(cnpj)
|
||||||
|
except Exception: # a name is a nicety; the order must still go
|
||||||
|
company = None
|
||||||
|
return self.request('POST', '/contatos', json=contact_payload(order, company))['id']
|
||||||
|
|
||||||
|
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."""
|
||||||
wanted = purchase_order(payload['number'])
|
wanted = purchase_order(payload['number'])
|
||||||
since = ((self.today or local_today()) - timedelta(days=SEARCH_DAYS)).isoformat()
|
since = ((self.today or local_today()) - timedelta(days=days)).isoformat()
|
||||||
found = self.request('GET', '/pedidos', params={'cpfCnpj': payload['order']['customer']['cnpj'],
|
seen = set()
|
||||||
'dataInicial': since, 'limit': 100})
|
for form in search_forms(payload['order']['customer']['cnpj']):
|
||||||
|
found = self.request('GET', '/pedidos', params={'cpfCnpj': form, 'dataInicial': since, 'limit': 100})
|
||||||
for entry in found.get('itens') or []:
|
for entry in found.get('itens') or []:
|
||||||
|
if entry['id'] in seen:
|
||||||
|
continue
|
||||||
|
seen.add(entry['id'])
|
||||||
detail = self.request('GET', f"/pedidos/{entry['id']}")
|
detail = self.request('GET', f"/pedidos/{entry['id']}")
|
||||||
if detail.get('numeroOrdemCompra') == wanted:
|
if detail.get('numeroOrdemCompra') == wanted:
|
||||||
return detail
|
return detail
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
def tag(self, tiny_id, known=False):
|
||||||
|
"""The SITE DTF marcador on the order, once. A retry that finds the
|
||||||
|
order already created checks first, since POST adds another."""
|
||||||
|
if known:
|
||||||
|
have = self.request('GET', f'/pedidos/{tiny_id}/marcadores')
|
||||||
|
have = have if isinstance(have, list) else have.get('itens') or []
|
||||||
|
if any(str(m.get('descricao', '')).strip().upper() == TAG for m in have):
|
||||||
|
return
|
||||||
|
self.request('POST', f'/pedidos/{tiny_id}/marcadores', json=[{'descricao': TAG}])
|
||||||
|
|
||||||
|
def set_situacao(self, tiny_id, situacao):
|
||||||
|
self.request('PUT', f'/pedidos/{tiny_id}/situacao', json={'situacao': situacao})
|
||||||
|
|
||||||
def deliver(self, event_key, payload):
|
def deliver(self, event_key, payload):
|
||||||
if payload.get('event') != 'payment_approved':
|
event = payload.get('event')
|
||||||
# Production progress is not written to Tiny; only the sale is.
|
if event == 'payment_approved':
|
||||||
return {'provider': 'tiny', 'event_key': event_key, 'status': 'not-applicable',
|
return self.sale(event_key, payload)
|
||||||
'event': payload.get('event')}
|
if event == 'ready' and status_updates():
|
||||||
|
return self.ready(event_key, payload)
|
||||||
|
if event == 'production_started' and status_updates():
|
||||||
|
# Not past it: an order the team already invoiced stays where it is.
|
||||||
|
return self.move(event_key, payload, PREPARANDO, (ABERTA, APROVADA))
|
||||||
|
if event == 'cancelled' and status_updates():
|
||||||
|
return self.move(event_key, payload, CANCELADA, (ABERTA, APROVADA, PREPARANDO, INCOMPLETA))
|
||||||
|
# Other production events have no Tiny situação and are not written.
|
||||||
|
return {'provider': 'tiny', 'event_key': event_key, 'status': 'not-applicable', 'event': event}
|
||||||
|
|
||||||
|
def sale(self, event_key, payload):
|
||||||
|
"""Create the order once; with status updates on, approve it once.
|
||||||
|
|
||||||
|
An order is created "Aberta" and then set to "Aprovada", so a retry
|
||||||
|
after a failure between the two finds it still open and finishes the
|
||||||
|
job, and an order someone has already moved on is left alone."""
|
||||||
existing = self.find(payload)
|
existing = self.find(payload)
|
||||||
if existing:
|
if existing:
|
||||||
return {'provider': 'tiny', 'event_key': event_key, 'status': 'already-created',
|
receipt = {'provider': 'tiny', 'event_key': event_key, 'status': 'already-created',
|
||||||
'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')
|
||||||
|
else:
|
||||||
contact_id = self.contact(payload['order'])
|
contact_id = self.contact(payload['order'])
|
||||||
created = self.request('POST', '/pedidos', json=order_payload(payload, contact_id, self.today))
|
created = self.request('POST', '/pedidos', json=order_payload(
|
||||||
return {'provider': 'tiny', 'event_key': event_key, 'status': 'created',
|
payload, contact_id, self.today, product_id=self.product_id, shipping=self.shipping))
|
||||||
|
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
|
||||||
|
# Tagged before it is approved, so a failure here is retried while the order is still open.
|
||||||
|
if situacao == ABERTA:
|
||||||
|
self.tag(tiny_id, known=bool(existing))
|
||||||
|
receipt['marcador'] = TAG
|
||||||
|
if status_updates() and situacao == ABERTA:
|
||||||
|
self.set_situacao(tiny_id, APROVADA)
|
||||||
|
receipt['situacao'] = SITUACOES[APROVADA]
|
||||||
|
return receipt
|
||||||
|
|
||||||
|
def ready(self, event_key, payload):
|
||||||
|
"""A pickup order became ready: "Pronto para envio", which the client's
|
||||||
|
notices turn into the pickup message. Shipped orders get "Enviada"
|
||||||
|
once freight exists (1.2)."""
|
||||||
|
base = {'provider': 'tiny', 'event_key': event_key}
|
||||||
|
order = payload.get('order') or {}
|
||||||
|
if (order.get('freight') or {}).get('service') != 'pickup':
|
||||||
|
return {**base, 'status': 'not-applicable', 'event': 'ready'}
|
||||||
|
return self.move(event_key, payload, PRONTO_ENVIO, (ABERTA, APROVADA, PREPARANDO, FATURADA, INCOMPLETA))
|
||||||
|
|
||||||
|
def move(self, event_key, payload, target, from_situacoes):
|
||||||
|
"""Set the order's situação to `target` when it is still in one of
|
||||||
|
`from_situacoes`; anywhere else it was moved on in Tiny and stays."""
|
||||||
|
base = {'provider': 'tiny', 'event_key': event_key}
|
||||||
|
tiny_id = payload.get('tiny_id')
|
||||||
|
detail = self.request('GET', f'/pedidos/{tiny_id}') if tiny_id else self.find(payload, READY_SEARCH_DAYS)
|
||||||
|
if not detail:
|
||||||
|
raise TinyError(f"{purchase_order(payload['number'])} is not in Tiny yet; the outbox will retry")
|
||||||
|
base.update(tiny_id=str(detail.get('id')), tiny_number=str(detail.get('numeroPedido')))
|
||||||
|
situacao = detail.get('situacao')
|
||||||
|
if situacao not in from_situacoes:
|
||||||
|
return {**base, 'status': 'status-unchanged', 'situacao': SITUACOES.get(situacao, str(situacao))}
|
||||||
|
self.set_situacao(detail['id'], target)
|
||||||
|
return {**base, 'status': 'status-updated', 'situacao': SITUACOES[target]}
|
||||||
|
|||||||
295
app/tiny_probe.py
Normal file
@@ -0,0 +1,295 @@
|
|||||||
|
"""Supervised checks against the client's real Tiny, run by hand from a
|
||||||
|
container console (docker exec, or Portainer > Containers > worker > Console).
|
||||||
|
Tiny has no sandbox, so this is how the adapter is proven on the real account.
|
||||||
|
|
||||||
|
python -m app.tiny_probe produtos [termo] list active products (read-only)
|
||||||
|
python -m app.tiny_probe formas-envio [termo] list formas de envio, to find pickup (read-only)
|
||||||
|
python -m app.tiny_probe conferir connection, the products or SKUs and pickup (read-only)
|
||||||
|
python -m app.tiny_probe campos what a complete order needs from Tiny: payment methods,
|
||||||
|
categories, sellers, Correios/Jadlog freight (read-only)
|
||||||
|
python -m app.tiny_probe exemplo NUMERO the structure of an existing order, without the
|
||||||
|
customer's details, to copy in Site orders (read-only)
|
||||||
|
python -m app.tiny_probe pedido --cnpj ... --email ... --celular ... [--modo file] [--metros 1.3]
|
||||||
|
show the test order; --confirmar creates it, then cancels it
|
||||||
|
python -m app.tiny_probe cancelar TINY_ID cancel a test order (DTF-TESTE-...) left open; nothing else
|
||||||
|
|
||||||
|
The test order goes through TinyOrders.deliver, exactly as the worker sends a
|
||||||
|
paid order. The duplicate guard is then proven read-only first (the order must
|
||||||
|
be found by its purchase-order number) and only then by a second delivery,
|
||||||
|
which must return the existing order. If the search cannot find the order, the
|
||||||
|
second delivery is not attempted: it would create a duplicate. Either way the
|
||||||
|
test order is then cancelled through the API (Tiny has no delete, and the
|
||||||
|
team's users may not cancel by hand), and read back to show it is.
|
||||||
|
"""
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
from datetime import datetime
|
||||||
|
from decimal import Decimal, InvalidOperation
|
||||||
|
|
||||||
|
from .core.pricing import TIERS
|
||||||
|
from .core.secrets import load as load_secret_files
|
||||||
|
from . import tiny
|
||||||
|
|
||||||
|
FIND_ATTEMPTS = 4
|
||||||
|
FIND_WAIT_SECONDS = 5
|
||||||
|
|
||||||
|
|
||||||
|
def test_order(cnpj, email, celular, mode, now=None, metres='1'):
|
||||||
|
number = 'TESTE-' + (now or datetime.now(tiny.BRASILIA)).strftime('%Y%m%d%H%M')
|
||||||
|
unit = TIERS[mode][0][1]
|
||||||
|
total = int(Decimal(metres) * unit)
|
||||||
|
return {'order_id': 'teste-integracao', 'number': number, 'event': 'payment_approved',
|
||||||
|
'order': {'customer': {'cnpj': cnpj, 'mail': email, 'zap': celular},
|
||||||
|
'items': [{'mode': mode, 'grade': 100, 'billed_metres': metres, 'unit_cents': unit,
|
||||||
|
'total_cents': total}],
|
||||||
|
'freight': {'service': 'pickup', 'total_cents': 0},
|
||||||
|
'destination': None, 'total_cents': total}}
|
||||||
|
|
||||||
|
|
||||||
|
def produtos(orders, termo, out):
|
||||||
|
params = {'situacao': 'A', 'limit': 100}
|
||||||
|
if termo:
|
||||||
|
params['nome'] = termo
|
||||||
|
found = orders.request('GET', '/produtos', params=params).get('itens') or []
|
||||||
|
for item in found:
|
||||||
|
preco = (item.get('precos') or {}).get('preco')
|
||||||
|
out(f"{item['id']}\t{item.get('sku') or '-'}\t{item.get('descricao')}\tR$ {preco}")
|
||||||
|
out(f'{len(found)} produto(s) ativo(s)' + (f' com "{termo}"' if termo else '') + '.')
|
||||||
|
|
||||||
|
|
||||||
|
def formas_envio(orders, termo, out):
|
||||||
|
params = {'limit': 100}
|
||||||
|
if termo:
|
||||||
|
params['nome'] = termo
|
||||||
|
found = orders.request('GET', '/formas-envio', params=params).get('itens') or []
|
||||||
|
for item in found:
|
||||||
|
out(f"{item.get('id')}\t{item.get('tipo')}\t{item.get('nome')}")
|
||||||
|
out(f'{len(found)} forma(s) de envio' + (f' com "{termo}"' if termo else '') +
|
||||||
|
'. A retirada é a do tipo 6 (Customizado) que a equipe usa para retirar pessoalmente.')
|
||||||
|
|
||||||
|
|
||||||
|
# What a complete order (as the store's own orders reach Tiny) looks up, each
|
||||||
|
# with the app permission it needs in Tiny's Aplicativos screen.
|
||||||
|
LOOKUPS = (('Formas de recebimento', '/formas-recebimento', 'Forma de Recebimento (Leitura)'),
|
||||||
|
('Categorias de receita e despesa', '/categorias-receita-despesa', 'Contas Receber (Leitura)'),
|
||||||
|
('Vendedores', '/vendedores', 'Contatos (Leitura)'),
|
||||||
|
('Intermediadores', '/intermediadores', 'Intermediadores (Leitura)'))
|
||||||
|
# The parts of an existing order worth copying; the customer and the address
|
||||||
|
# are left out. Every other field is listed by name only.
|
||||||
|
EXAMPLE_FIELDS = ('situacao', 'data', 'dataPrevista', 'naturezaOperacao', 'vendedor', 'transportador',
|
||||||
|
'pagamento', 'categoria', 'ecommerce', 'intermediador', 'listaPreco', 'deposito',
|
||||||
|
'numeroOrdemCompra', 'valorFrete', 'origemPedido', 'marcadores')
|
||||||
|
|
||||||
|
|
||||||
|
def short(item):
|
||||||
|
return json.dumps(item, ensure_ascii=False, separators=(', ', ': '))[:240]
|
||||||
|
|
||||||
|
|
||||||
|
def listed(found):
|
||||||
|
return found if isinstance(found, list) else (found.get('itens') or [])
|
||||||
|
|
||||||
|
|
||||||
|
def campos(orders, out):
|
||||||
|
ok = True
|
||||||
|
for label, path, permission in LOOKUPS:
|
||||||
|
try:
|
||||||
|
found = listed(orders.request('GET', path, params={'limit': 100}))
|
||||||
|
except tiny.TinyError as exc:
|
||||||
|
ok = False
|
||||||
|
denied = ': 403 ' in str(exc) or ': 401 ' in str(exc)
|
||||||
|
out(f'{label}: ' + (f'sem permissão. Libere "{permission}" no aplicativo e reconecte. ({exc})' if denied
|
||||||
|
else str(exc)))
|
||||||
|
continue
|
||||||
|
out(f'{label}: {len(found)}')
|
||||||
|
for item in found:
|
||||||
|
out(' ' + short(item))
|
||||||
|
# Correios and Jadlog, with whatever freight options Tiny keeps for them.
|
||||||
|
methods = listed(orders.request('GET', '/formas-envio', params={'limit': 100}))
|
||||||
|
for method in methods:
|
||||||
|
if not any(word in str(method.get('nome', '')).lower() for word in ('correio', 'jadlog')):
|
||||||
|
continue
|
||||||
|
out(f"Forma de envio {method.get('id')} · tipo {method.get('tipo')} · {method.get('nome')}")
|
||||||
|
try:
|
||||||
|
out(' ' + short(orders.request('GET', f"/formas-envio/{method['id']}")))
|
||||||
|
except tiny.TinyError as exc:
|
||||||
|
out(f' {exc}')
|
||||||
|
return ok
|
||||||
|
|
||||||
|
|
||||||
|
def exemplo(orders, numero, out):
|
||||||
|
found = listed(orders.request('GET', '/pedidos', params={'numero': numero, 'limit': 5}))
|
||||||
|
match = [p for p in found if str(p.get('numeroPedido') or p.get('numero') or '') == str(numero)]
|
||||||
|
if not match:
|
||||||
|
out(f'Pedido {numero} não encontrado.')
|
||||||
|
return False
|
||||||
|
detail = orders.request('GET', f"/pedidos/{match[0]['id']}")
|
||||||
|
try:
|
||||||
|
detail['marcadores'] = orders.request('GET', f"/pedidos/{match[0]['id']}/marcadores")
|
||||||
|
except tiny.TinyError as exc:
|
||||||
|
detail['marcadores'] = f'não lidos: {exc}'
|
||||||
|
out(json.dumps({k: detail[k] for k in EXAMPLE_FIELDS if k in detail}, ensure_ascii=False, indent=2))
|
||||||
|
out('Outros campos (sem valores): ' + ', '.join(sorted(k for k in detail if k not in EXAMPLE_FIELDS)))
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def conferir(orders, out):
|
||||||
|
ok = True
|
||||||
|
for mode, setting in tiny.PRODUCT_SETTINGS.items():
|
||||||
|
prefix, step = tiny.sku_prefix(mode), tiny.step_sku(mode)
|
||||||
|
if step:
|
||||||
|
result = tiny.configured_skus(orders, mode)
|
||||||
|
ok &= result == 'ok'
|
||||||
|
metre = tiny.metre_sku(mode)
|
||||||
|
out(f'{tiny.STEP_SETTINGS[mode]} ({tiny.PRODUCTS[mode]}): {result} '
|
||||||
|
f'({metre + " por metro e " if metre else ""}{step} a cada 10 cm)')
|
||||||
|
continue
|
||||||
|
if prefix:
|
||||||
|
result = tiny.configured_skus(orders, mode)
|
||||||
|
ok &= result == 'ok'
|
||||||
|
out(f'{tiny.SKU_SETTINGS[mode]} ({tiny.PRODUCTS[mode]}): {result} '
|
||||||
|
f'({prefix}.100CM e {prefix}.0010CM a {prefix}.0090CM)')
|
||||||
|
continue
|
||||||
|
product, result = tiny.configured_product(orders, mode)
|
||||||
|
ok &= result == 'ok'
|
||||||
|
described = f"{product.get('sku') or '-'} · {product.get('descricao')}" if product else ''
|
||||||
|
out(f'{setting} ({tiny.PRODUCTS[mode]}): {result} {described}'.rstrip())
|
||||||
|
method, result = tiny.configured_pickup(orders)
|
||||||
|
ok &= result == 'ok'
|
||||||
|
out(f"{tiny.PICKUP_SETTING} (retirada): {result} {method.get('nome') if method else ''}".rstrip())
|
||||||
|
out(f"{tiny.STATUS_UPDATES_SETTING}: {'ligado' if tiny.status_updates() else 'desligado'}")
|
||||||
|
for name, result in tiny.check(orders=orders).items():
|
||||||
|
if name in ('pedidos', 'contatos'):
|
||||||
|
ok &= result == 'ok'
|
||||||
|
out(f'{name}: {result}')
|
||||||
|
out('Tudo conferido.' if ok else 'Há pendências acima.')
|
||||||
|
return ok
|
||||||
|
|
||||||
|
|
||||||
|
def pedido(orders, payload, confirm, out, wait=time.sleep):
|
||||||
|
cnpj = payload['order']['customer']['cnpj']
|
||||||
|
known = orders.find_contact(cnpj)
|
||||||
|
if known:
|
||||||
|
out(f"Contato {tiny.punctuated(cnpj)}: já existe no Tiny (id {known})")
|
||||||
|
else:
|
||||||
|
# Named as the worker names a new customer: the company in the CNPJ registry.
|
||||||
|
company = orders.names(cnpj) if orders.names else None
|
||||||
|
name = tiny.contact_payload(payload['order'], company)['nome']
|
||||||
|
out(f'Contato {tiny.punctuated(cnpj)}: não existe; será criado como "{name}"')
|
||||||
|
out('Pedido que será enviado:')
|
||||||
|
out(json.dumps(tiny.order_payload(payload, known or 0, product_id=orders.product_id,
|
||||||
|
shipping=orders.shipping),
|
||||||
|
ensure_ascii=False, indent=2))
|
||||||
|
out(f'Marcador: {tiny.TAG} (incluído logo depois de criar o pedido)')
|
||||||
|
if not confirm:
|
||||||
|
out('Nada foi criado. Repita com --confirmar para criar este pedido no Tiny.')
|
||||||
|
return None
|
||||||
|
first = orders.deliver('teste-integracao', payload)
|
||||||
|
out(f"1º envio: {first['status']} · Tiny id {first['tiny_id']} · nº {first['tiny_number']}")
|
||||||
|
try:
|
||||||
|
for attempt in range(FIND_ATTEMPTS):
|
||||||
|
found = orders.find(payload)
|
||||||
|
if found:
|
||||||
|
break
|
||||||
|
if attempt < FIND_ATTEMPTS - 1:
|
||||||
|
wait(FIND_WAIT_SECONDS)
|
||||||
|
else:
|
||||||
|
out(f'FALHA: a busca por {tiny.purchase_order(payload["number"])} não encontrou o pedido. '
|
||||||
|
'Um reenvio criaria um duplicado; o 2º envio não foi feito.')
|
||||||
|
return False
|
||||||
|
second = orders.deliver('teste-integracao', payload)
|
||||||
|
out(f"2º envio: {second['status']} · Tiny id {second['tiny_id']}")
|
||||||
|
passed = second['status'] == 'already-created' and second['tiny_id'] == first['tiny_id']
|
||||||
|
out('OK: o reenvio encontrou o mesmo pedido.' if passed else 'FALHA: o reenvio não devolveu o mesmo pedido.')
|
||||||
|
return passed
|
||||||
|
finally:
|
||||||
|
# Whatever happened above, the test order does not stay open.
|
||||||
|
cancelar(orders, first['tiny_id'], out)
|
||||||
|
|
||||||
|
|
||||||
|
def cancelar(orders, tiny_id, out):
|
||||||
|
"""Cancel a test order through the API and read it back. Only orders
|
||||||
|
this probe made (purchase order DTF-TESTE-...) are touched."""
|
||||||
|
try:
|
||||||
|
detail = orders.request('GET', f'/pedidos/{tiny_id}')
|
||||||
|
number = detail.get('numeroPedido')
|
||||||
|
if not str(detail.get('numeroOrdemCompra') or '').startswith(tiny.purchase_order('TESTE-')):
|
||||||
|
out(f'Recusado: o pedido {tiny_id} não é um pedido de teste (DTF-TESTE-...); nada foi alterado.')
|
||||||
|
return False
|
||||||
|
if detail.get('situacao') != tiny.CANCELADA:
|
||||||
|
orders.set_situacao(tiny_id, tiny.CANCELADA)
|
||||||
|
detail = orders.request('GET', f'/pedidos/{tiny_id}')
|
||||||
|
except tiny.TinyError as exc:
|
||||||
|
out(f'FALHA ao cancelar o pedido {tiny_id}: {exc}. Rode: python -m app.tiny_probe cancelar {tiny_id}')
|
||||||
|
return False
|
||||||
|
situacao = detail.get('situacao')
|
||||||
|
if situacao == tiny.CANCELADA:
|
||||||
|
out(f'Pedido nº {number} cancelado no Tiny.')
|
||||||
|
return True
|
||||||
|
out(f'FALHA: o pedido nº {number} ficou em {tiny.SITUACOES.get(situacao, situacao)}. '
|
||||||
|
f'Rode: python -m app.tiny_probe cancelar {tiny_id}')
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv=None, orders=None, out=print):
|
||||||
|
parser = argparse.ArgumentParser(prog='python -m app.tiny_probe')
|
||||||
|
commands = parser.add_subparsers(dest='command', required=True)
|
||||||
|
listing = commands.add_parser('produtos')
|
||||||
|
listing.add_argument('termo', nargs='?', default='')
|
||||||
|
methods = commands.add_parser('formas-envio')
|
||||||
|
methods.add_argument('termo', nargs='?', default='')
|
||||||
|
commands.add_parser('conferir')
|
||||||
|
commands.add_parser('campos')
|
||||||
|
example = commands.add_parser('exemplo')
|
||||||
|
example.add_argument('numero')
|
||||||
|
cancel = commands.add_parser('cancelar')
|
||||||
|
cancel.add_argument('tiny_id', type=int)
|
||||||
|
order = commands.add_parser('pedido')
|
||||||
|
order.add_argument('--cnpj', '--cpf', dest='cnpj', required=True, help='CNPJ ou CPF do cliente')
|
||||||
|
order.add_argument('--email', required=True)
|
||||||
|
order.add_argument('--celular', required=True)
|
||||||
|
order.add_argument('--modo', choices=sorted(tiny.PRODUCT_SETTINGS), default='file')
|
||||||
|
order.add_argument('--metros', default='1', help='metragem cobrada, em passos de 10 cm (ex.: 1.3)')
|
||||||
|
order.add_argument('--confirmar', action='store_true')
|
||||||
|
args = parser.parse_args(argv)
|
||||||
|
if orders is None:
|
||||||
|
load_secret_files()
|
||||||
|
from .cnpj import company
|
||||||
|
# The same names for new contacts as the worker uses (app/worker.py).
|
||||||
|
orders = tiny.TinyOrders(auth=tiny.TinyAuth(), names=company)
|
||||||
|
try:
|
||||||
|
if args.command == 'produtos':
|
||||||
|
produtos(orders, args.termo, out)
|
||||||
|
return 0
|
||||||
|
if args.command == 'formas-envio':
|
||||||
|
formas_envio(orders, args.termo, out)
|
||||||
|
return 0
|
||||||
|
if args.command == 'conferir':
|
||||||
|
return 0 if conferir(orders, out) else 1
|
||||||
|
if args.command == 'campos':
|
||||||
|
return 0 if campos(orders, out) else 1
|
||||||
|
if args.command == 'exemplo':
|
||||||
|
return 0 if exemplo(orders, args.numero, out) else 1
|
||||||
|
if args.command == 'cancelar':
|
||||||
|
return 0 if cancelar(orders, args.tiny_id, out) else 1
|
||||||
|
cnpj = ''.join(ch for ch in args.cnpj if ch.isdigit())
|
||||||
|
if len(cnpj) not in (11, 14):
|
||||||
|
out('Informe um CPF (11 dígitos) ou um CNPJ (14 dígitos).')
|
||||||
|
return 2
|
||||||
|
try:
|
||||||
|
metres = Decimal(args.metros.replace(',', '.'))
|
||||||
|
except InvalidOperation:
|
||||||
|
metres = Decimal(0)
|
||||||
|
if metres < 1 or (metres * 10) % 1:
|
||||||
|
out('Informe a metragem a partir de 1 m, em passos de 10 cm (ex.: 1.3).')
|
||||||
|
return 2
|
||||||
|
payload = test_order(cnpj, args.email, args.celular, args.modo, metres=str(metres))
|
||||||
|
return 0 if pedido(orders, payload, args.confirmar, out) is not False else 1
|
||||||
|
except tiny.TinyError as exc:
|
||||||
|
out(f'Tiny: {exc}')
|
||||||
|
return 1
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
sys.exit(main())
|
||||||
@@ -6,7 +6,8 @@ import threading
|
|||||||
import time
|
import time
|
||||||
from http.server import BaseHTTPRequestHandler, HTTPServer
|
from http.server import BaseHTTPRequestHandler, HTTPServer
|
||||||
from psycopg.types.json import Jsonb
|
from psycopg.types.json import Jsonb
|
||||||
from .adapters import FakeTiny, FakeWhatsApp, LocalS3Storage, require_runtime
|
from . import mail
|
||||||
|
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
|
||||||
from .printjobs import render_loop
|
from .printjobs import render_loop
|
||||||
@@ -14,13 +15,17 @@ from .scanning import ClamAV, scan_loop
|
|||||||
|
|
||||||
load_secret_files()
|
load_secret_files()
|
||||||
require_runtime()
|
require_runtime()
|
||||||
adapters = {'tiny': FakeTiny(), 'whatsapp': FakeWhatsApp()}
|
adapters = {'tiny': FakeTiny()}
|
||||||
# Not yet confirmed against the client's account; see app/tiny.py.
|
# Not yet confirmed against the client's account; see app/tiny.py.
|
||||||
if os.environ.get('TINY_ADAPTER') == 'tiny':
|
if os.environ.get('TINY_ADAPTER') == 'tiny':
|
||||||
from .tiny import TinyOrders
|
from .tiny import TinyOrders
|
||||||
adapters['tiny'] = TinyOrders()
|
from .cnpj import company
|
||||||
|
adapters['tiny'] = TinyOrders(names=company)
|
||||||
last_tick = 0.0
|
last_tick = 0.0
|
||||||
last_cleanup = 0.0
|
last_cleanup = 0.0
|
||||||
|
last_reconcile = 0.0
|
||||||
|
last_names = 0.0
|
||||||
|
names_thread = None
|
||||||
last_tiny_keepalive = 0.0
|
last_tiny_keepalive = 0.0
|
||||||
storage = LocalS3Storage()
|
storage = LocalS3Storage()
|
||||||
scan_thread = None
|
scan_thread = None
|
||||||
@@ -35,7 +40,11 @@ def cleanup():
|
|||||||
for row in rows:
|
for row in rows:
|
||||||
storage.discard(row['object_key'],row['multipart_id'],row['complete'])
|
storage.discard(row['object_key'],row['multipart_id'],row['complete'])
|
||||||
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.sessions WHERE expires_at<=now()')
|
c.execute('DELETE FROM dtf_local.sessions WHERE expires_at<=now()')
|
||||||
|
c.execute("DELETE FROM dtf_local.account_signups WHERE created_at<now()-interval '1 day'")
|
||||||
|
c.execute("DELETE FROM dtf_local.email_changes WHERE created_at<now()-interval '1 day'")
|
||||||
|
c.execute("DELETE FROM dtf_local.password_resets WHERE expires_at<now()-interval '1 day'")
|
||||||
c.execute('DELETE FROM dtf_local.operator_sessions WHERE expires_at<=now()')
|
c.execute('DELETE FROM dtf_local.operator_sessions WHERE expires_at<=now()')
|
||||||
c.execute("DELETE FROM dtf_local.login_attempts WHERE started_at<now()-interval '1 day'")
|
c.execute("DELETE FROM dtf_local.login_attempts WHERE started_at<now()-interval '1 day'")
|
||||||
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'")
|
||||||
@@ -74,6 +83,34 @@ def tiny_keepalive():
|
|||||||
except Exception:
|
except Exception:
|
||||||
logging.exception('Tiny connection refresh failed')
|
logging.exception('Tiny connection refresh failed')
|
||||||
|
|
||||||
|
def reconcile_payments():
|
||||||
|
"""Every minute: the payments of open quotes, asked of the provider, so an
|
||||||
|
approval becomes the order even when its notification never arrives."""
|
||||||
|
global last_reconcile
|
||||||
|
if time.monotonic()-last_reconcile < 60:
|
||||||
|
return
|
||||||
|
last_reconcile = time.monotonic()
|
||||||
|
from . import payments
|
||||||
|
from .runtime import payment
|
||||||
|
payments.reconcile(connect, payment)
|
||||||
|
|
||||||
|
def resolve_names():
|
||||||
|
"""Every minute: the company names of a few new customers' CNPJs, on a
|
||||||
|
thread of their own, so a slow registry never holds up orders."""
|
||||||
|
global last_names, names_thread
|
||||||
|
if time.monotonic()-last_names < 60 or (names_thread and names_thread.is_alive()):
|
||||||
|
return
|
||||||
|
last_names = time.monotonic()
|
||||||
|
from . import cnpj
|
||||||
|
|
||||||
|
def run():
|
||||||
|
try:
|
||||||
|
cnpj.resolve(connect)
|
||||||
|
except Exception:
|
||||||
|
logging.exception('CNPJ name lookup failed')
|
||||||
|
names_thread = threading.Thread(target=run, daemon=True)
|
||||||
|
names_thread.start()
|
||||||
|
|
||||||
def loop():
|
def loop():
|
||||||
global last_cleanup
|
global last_cleanup
|
||||||
while True:
|
while True:
|
||||||
@@ -82,7 +119,10 @@ def loop():
|
|||||||
if time.monotonic()-last_cleanup > 60:
|
if time.monotonic()-last_cleanup > 60:
|
||||||
cleanup()
|
cleanup()
|
||||||
last_cleanup = time.monotonic()
|
last_cleanup = time.monotonic()
|
||||||
|
mail.send_pending(connect)
|
||||||
tiny_keepalive()
|
tiny_keepalive()
|
||||||
|
reconcile_payments()
|
||||||
|
resolve_names()
|
||||||
except Exception:
|
except Exception:
|
||||||
logging.exception('Local worker tick failed')
|
logging.exception('Local worker tick failed')
|
||||||
time.sleep(1)
|
time.sleep(1)
|
||||||
|
|||||||
@@ -36,7 +36,28 @@ x-app: &app
|
|||||||
MP_WEBHOOK_SECRET: ${MP_WEBHOOK_SECRET:-}
|
MP_WEBHOOK_SECRET: ${MP_WEBHOOK_SECRET:-}
|
||||||
MP_NOTIFICATION_URL: ${MP_NOTIFICATION_URL:-}
|
MP_NOTIFICATION_URL: ${MP_NOTIFICATION_URL:-}
|
||||||
MP_PUBLIC_KEY: ${MP_PUBLIC_KEY:-}
|
MP_PUBLIC_KEY: ${MP_PUBLIC_KEY:-}
|
||||||
FREIGHT_ADAPTER: fake
|
FREIGHT_ADAPTER: ${FREIGHT_ADAPTER:-fake}
|
||||||
|
JADLOG_TOKEN: ${JADLOG_TOKEN:-}
|
||||||
|
JADLOG_CNPJ: ${JADLOG_CNPJ:-}
|
||||||
|
JADLOG_CONTA: ${JADLOG_CONTA:-}
|
||||||
|
JADLOG_CONTRATO: ${JADLOG_CONTRATO:-}
|
||||||
|
JADLOG_PESO_BASE_KG: ${JADLOG_PESO_BASE_KG:-}
|
||||||
|
JADLOG_PESO_POR_METRO_KG: ${JADLOG_PESO_POR_METRO_KG:-}
|
||||||
|
JADLOG_CAIXA_CM: ${JADLOG_CAIXA_CM:-}
|
||||||
|
JADLOG_CUBAGEM_KG_M3: ${JADLOG_CUBAGEM_KG_M3:-}
|
||||||
|
JADLOG_METROS_POR_CAIXA: ${JADLOG_METROS_POR_CAIXA:-}
|
||||||
|
FREIGHT_PRODUCTION_DAYS: ${FREIGHT_PRODUCTION_DAYS:-0}
|
||||||
|
# Correios: off locally unless an access code is set in .env.
|
||||||
|
CORREIOS_CODIGO_ACESSO: ${CORREIOS_CODIGO_ACESSO:-}
|
||||||
|
CORREIOS_USUARIO: ${CORREIOS_USUARIO:-}
|
||||||
|
CORREIOS_CARTAO: ${CORREIOS_CARTAO:-}
|
||||||
|
CORREIOS_CONTRATO: ${CORREIOS_CONTRATO:-}
|
||||||
|
CORREIOS_COD_PAC: ${CORREIOS_COD_PAC:-}
|
||||||
|
CORREIOS_COD_SEDEX: ${CORREIOS_COD_SEDEX:-}
|
||||||
|
# Carts the Site priced are approved at checkout; larger ones wait for review.
|
||||||
|
QUOTE_AUTO_APPROVE: ${QUOTE_AUTO_APPROVE:-true}
|
||||||
|
QUOTE_AUTO_MAX_METRES: ${QUOTE_AUTO_MAX_METRES:-50}
|
||||||
|
MANUAL_FILE_EXTRA_CENTS: ${MANUAL_FILE_EXTRA_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:-}
|
||||||
@@ -45,16 +66,37 @@ 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_SKU_TEXTIL_FOLHA: ${TINY_SKU_TEXTIL_FOLHA:-}
|
||||||
|
TINY_SKU_TEXTIL_AVULSA: ${TINY_SKU_TEXTIL_AVULSA:-}
|
||||||
|
TINY_SKU_UV_FOLHA: ${TINY_SKU_UV_FOLHA:-}
|
||||||
|
TINY_SKU_UV_AVULSA: ${TINY_SKU_UV_AVULSA:-}
|
||||||
|
TINY_SKU10_TEXTIL_FOLHA: ${TINY_SKU10_TEXTIL_FOLHA:-}
|
||||||
|
TINY_SKU10_TEXTIL_AVULSA: ${TINY_SKU10_TEXTIL_AVULSA:-}
|
||||||
|
TINY_SKU10_UV_FOLHA: ${TINY_SKU10_UV_FOLHA:-}
|
||||||
|
TINY_SKU10_UV_AVULSA: ${TINY_SKU10_UV_AVULSA:-}
|
||||||
|
TINY_SKU_METRO_TEXTIL_FOLHA: ${TINY_SKU_METRO_TEXTIL_FOLHA:-}
|
||||||
|
TINY_SKU_METRO_TEXTIL_AVULSA: ${TINY_SKU_METRO_TEXTIL_AVULSA:-}
|
||||||
|
TINY_SKU_METRO_UV_FOLHA: ${TINY_SKU_METRO_UV_FOLHA:-}
|
||||||
|
TINY_SKU_METRO_UV_AVULSA: ${TINY_SKU_METRO_UV_AVULSA:-}
|
||||||
TINY_ECOMMERCE_ID: ${TINY_ECOMMERCE_ID:-}
|
TINY_ECOMMERCE_ID: ${TINY_ECOMMERCE_ID:-}
|
||||||
WHATSAPP_ADAPTER: fake
|
# log keeps each e-mail in the database and the worker's log, with the
|
||||||
|
# recovery link readable there; smtp with the SMTP_* settings in .env.
|
||||||
|
MAIL_ADAPTER: ${MAIL_ADAPTER:-log}
|
||||||
|
MAIL_FROM: ${MAIL_FROM:-DTF Dropstar <nao-responda@localhost>}
|
||||||
|
MAIL_REPLY_TO: ${MAIL_REPLY_TO:-}
|
||||||
|
SMTP_HOST: ${SMTP_HOST:-}
|
||||||
|
SMTP_PORT: ${SMTP_PORT:-}
|
||||||
|
SMTP_SECURITY: ${SMTP_SECURITY:-starttls}
|
||||||
|
SMTP_USER: ${SMTP_USER:-}
|
||||||
|
SMTP_PASSWORD: ${SMTP_PASSWORD:-}
|
||||||
STORAGE_ADAPTER: s3-local
|
STORAGE_ADAPTER: s3-local
|
||||||
MOCK_FREIGHT_CENTS: ${MOCK_FREIGHT_CENTS:-1500}
|
MOCK_FREIGHT_CENTS: ${MOCK_FREIGHT_CENTS:-1500}
|
||||||
MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-5368709120}
|
MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-1073741824}
|
||||||
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:-10}
|
||||||
SCAN_MAX_BYTES: ${SCAN_MAX_BYTES:-134217728}
|
SCAN_MAX_BYTES: ${SCAN_MAX_BYTES:-1073741824}
|
||||||
networks: [local]
|
networks: [local]
|
||||||
init: true
|
init: true
|
||||||
security_opt: [no-new-privileges:true]
|
security_opt: [no-new-privileges:true]
|
||||||
@@ -138,6 +180,9 @@ services:
|
|||||||
S3_APP_USER: ${S3_APP_USER:-dtf_app}
|
S3_APP_USER: ${S3_APP_USER:-dtf_app}
|
||||||
S3_APP_PASSWORD: ${S3_APP_PASSWORD:-local-app-storage-only}
|
S3_APP_PASSWORD: ${S3_APP_PASSWORD:-local-app-storage-only}
|
||||||
S3_BUCKET: ${S3_BUCKET:-dtf-local-artwork}
|
S3_BUCKET: ${S3_BUCKET:-dtf-local-artwork}
|
||||||
|
S3_BACKUP_BUCKET: dtf-local-backups
|
||||||
|
S3_BACKUP_USER: dtf_backup
|
||||||
|
S3_BACKUP_PASSWORD: local-backup-storage-only
|
||||||
networks: [local]
|
networks: [local]
|
||||||
depends_on:
|
depends_on:
|
||||||
storage: {condition: service_healthy}
|
storage: {condition: service_healthy}
|
||||||
@@ -187,6 +232,28 @@ services:
|
|||||||
timeout: 3s
|
timeout: 3s
|
||||||
retries: 12
|
retries: 12
|
||||||
|
|
||||||
|
# The daily database backup, against the local backup bucket. Idle until
|
||||||
|
# BACKUP_AGE_RECIPIENT is set; tests/backup_test.py runs it with a throwaway key.
|
||||||
|
backup:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: infra/Dockerfile
|
||||||
|
command: python -m ops.db_backup serve
|
||||||
|
environment:
|
||||||
|
DATABASE_ADMIN_URL: postgresql://${POSTGRES_USER:-dtf_local}:${POSTGRES_PASSWORD:-local-database-only}@db:5432/${POSTGRES_DB:-dtf_local}
|
||||||
|
BACKUP_S3_ENDPOINT: http://storage:9000
|
||||||
|
BACKUP_BUCKET: dtf-local-backups
|
||||||
|
BACKUP_ACCESS_KEY_ID: dtf_backup
|
||||||
|
BACKUP_SECRET_ACCESS_KEY: local-backup-storage-only
|
||||||
|
BACKUP_REGION: us-east-1
|
||||||
|
BACKUP_AGE_RECIPIENT: ${BACKUP_AGE_RECIPIENT:-}
|
||||||
|
networks: [local]
|
||||||
|
read_only: true
|
||||||
|
tmpfs: [/tmp]
|
||||||
|
depends_on:
|
||||||
|
db-init: {condition: service_completed_successfully}
|
||||||
|
storage-init: {condition: service_completed_successfully}
|
||||||
|
|
||||||
site:
|
site:
|
||||||
build:
|
build:
|
||||||
context: .
|
context: .
|
||||||
@@ -195,6 +262,7 @@ services:
|
|||||||
S3_PUBLIC_ENDPOINT: ${S3_PUBLIC_ENDPOINT:-http://localhost:${STORAGE_PORT:-9000}}
|
S3_PUBLIC_ENDPOINT: ${S3_PUBLIC_ENDPOINT:-http://localhost:${STORAGE_PORT:-9000}}
|
||||||
# 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:-}
|
||||||
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
|
||||||
@@ -219,6 +287,7 @@ services:
|
|||||||
WEB_INDEX: kanban.html
|
WEB_INDEX: kanban.html
|
||||||
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: ""
|
||||||
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:
|
||||||
|
|||||||
@@ -13,8 +13,11 @@ LABEL org.opencontainers.image.title="DTF Portal/API" \
|
|||||||
# The base is pinned, so its OS packages are frozen at the digest's build date.
|
# The base is pinned, so its OS packages are frozen at the digest's build date.
|
||||||
# Upgrade them here or the image ships known-fixed Debian vulnerabilities, which
|
# Upgrade them here or the image ships known-fixed Debian vulnerabilities, which
|
||||||
# is what the production image was doing while the local one already did this.
|
# is what the production image was doing while the local one already did this.
|
||||||
|
# pg_dump and age are for the database backup (ops/db_backup.py). Debian 13
|
||||||
|
# ships PostgreSQL 17, the server's major version, which pg_dump must match.
|
||||||
RUN apt-get update \
|
RUN apt-get update \
|
||||||
&& apt-get upgrade -y \
|
&& apt-get upgrade -y \
|
||||||
|
&& apt-get install -y --no-install-recommends postgresql-client-17 age \
|
||||||
&& rm -rf /var/lib/apt/lists/*
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|||||||
@@ -22,7 +22,8 @@ LABEL org.opencontainers.image.title="DTF Site and Kanban" \
|
|||||||
org.opencontainers.image.source="DTF System repository"
|
org.opencontainers.image.source="DTF System repository"
|
||||||
ENV WEB_INDEX=index.html PUBLIC_HOST=invalid.example S3_PUBLIC_ENDPOINT=https://invalid.example
|
ENV WEB_INDEX=index.html PUBLIC_HOST=invalid.example S3_PUBLIC_ENDPOINT=https://invalid.example
|
||||||
COPY --from=policy /build/default.conf.template /etc/nginx/templates/default.conf.template
|
COPY --from=policy /build/default.conf.template /etc/nginx/templates/default.conf.template
|
||||||
COPY web/ /usr/share/nginx/html/
|
# The HTML from the policy stage, with every asset address versioned.
|
||||||
|
COPY --from=policy /build/web/ /usr/share/nginx/html/
|
||||||
|
|
||||||
# The official entrypoint renders the server configuration at startup and Nginx
|
# The official entrypoint renders the server configuration at startup and Nginx
|
||||||
# writes its PID/cache files. Keep the service non-root while granting it
|
# writes its PID/cache files. Keep the service non-root while granting it
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ substitute for `production_preflight.py`, CI, staging acceptance, or change appr
|
|||||||
## Application and external contracts
|
## Application and external contracts
|
||||||
|
|
||||||
- [ ] `docs/PRODUCTION_INPUTS.md` has owners, decisions, and evidence for every item.
|
- [ ] `docs/PRODUCTION_INPUTS.md` has owners, decisions, and evidence for every item.
|
||||||
- [ ] Production R2, freight, Mercado Pago, Tiny/Olist, and WhatsApp adapters have
|
- [ ] Production R2, freight, Mercado Pago, and Tiny/Olist adapters have
|
||||||
sandbox contract tests and least-privilege credentials.
|
sandbox contract tests and least-privilege credentials.
|
||||||
- [ ] Payment webhook authenticity, replay handling, and idempotency are tested.
|
- [ ] Payment webhook authenticity, replay handling, and idempotency are tested.
|
||||||
- [ ] Docker secret `*_FILE` loading is implemented and tested without logging values.
|
- [ ] Docker secret `*_FILE` loading is implemented and tested without logging values.
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ server {
|
|||||||
add_header Referrer-Policy no-referrer always;
|
add_header Referrer-Policy no-referrer always;
|
||||||
add_header X-Frame-Options DENY always;
|
add_header X-Frame-Options DENY always;
|
||||||
add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
|
add_header Permissions-Policy "camera=(), 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}; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'" 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;
|
||||||
|
|
||||||
location = /health { access_log off; return 200 'ok'; }
|
location = /health { access_log off; return 200 'ok'; }
|
||||||
location /api/ {
|
location /api/ {
|
||||||
@@ -48,6 +48,16 @@ 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).
|
||||||
|
location ~ ^/(arquivo-por-metro|artes-avulsas|uv-arquivo-por-metro|uv-artes-avulsas|carrinho|pagamento|pagamento/pix)/?$ {
|
||||||
|
expires -1;
|
||||||
|
try_files /index.html =404;
|
||||||
|
}
|
||||||
|
# The customer's area: one page, which shows the right part for each address.
|
||||||
|
location ~ ^/conta(/(entrar|pedidos|dados|redefinir))?/?$ {
|
||||||
|
expires -1;
|
||||||
|
try_files /portal.html =404;
|
||||||
|
}
|
||||||
location / {
|
location / {
|
||||||
expires -1;
|
expires -1;
|
||||||
try_files $uri $uri/ =404;
|
try_files $uri $uri/ =404;
|
||||||
|
|||||||
@@ -27,6 +27,10 @@ POSTGRES_VOLUME=TBD
|
|||||||
OPERATOR_EMAIL=TBD
|
OPERATOR_EMAIL=TBD
|
||||||
|
|
||||||
PAYMENT_ADAPTER=TBD
|
PAYMENT_ADAPTER=TBD
|
||||||
|
# With PAYMENT_ADAPTER=mercadopago. MP_ACCESS_TOKEN and MP_WEBHOOK_SECRET are
|
||||||
|
# secrets: enter them in Portainer only, never in this file.
|
||||||
|
MP_NOTIFICATION_URL=https://<SITE_DOMAIN>/api/payments/webhook
|
||||||
|
MP_PUBLIC_KEY=
|
||||||
FREIGHT_ADAPTER=TBD
|
FREIGHT_ADAPTER=TBD
|
||||||
TINY_ADAPTER=TBD
|
TINY_ADAPTER=TBD
|
||||||
# Tiny API v3 application (Configurações > Geral > Aplicativos in Tiny). The
|
# Tiny API v3 application (Configurações > Geral > Aplicativos in Tiny). The
|
||||||
@@ -37,13 +41,31 @@ 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
|
||||||
WHATSAPP_ADAPTER=TBD
|
TINY_FORMA_ENVIO_RETIRADA=TBD
|
||||||
|
# true only at go-live, after the n8n DTFIMP designer branch is removed.
|
||||||
|
TINY_STATUS_UPDATES=false
|
||||||
|
# E-mail (password recovery and team alerts). off until the SMTP account exists.
|
||||||
|
MAIL_ADAPTER=off
|
||||||
|
MAIL_FROM=DTF Dropstar <nao-responda@SITE_DOMAIN>
|
||||||
|
MAIL_REPLY_TO=
|
||||||
|
SMTP_HOST=TBD
|
||||||
|
SMTP_PORT=587
|
||||||
|
SMTP_SECURITY=starttls
|
||||||
|
SMTP_USER=TBD
|
||||||
|
SMTP_PASSWORD=TBD
|
||||||
STORAGE_QUOTA_BYTES=TBD
|
STORAGE_QUOTA_BYTES=TBD
|
||||||
OWNER_UPLOAD_QUOTA_BYTES=TBD
|
OWNER_UPLOAD_QUOTA_BYTES=TBD
|
||||||
MAX_PENDING_UPLOADS=10
|
MAX_PENDING_UPLOADS=10
|
||||||
MAX_UPLOAD_BYTES=5368709120
|
MAX_UPLOAD_BYTES=1073741824
|
||||||
UPLOAD_PART_BYTES=8388608
|
UPLOAD_PART_BYTES=8388608
|
||||||
SCAN_MAX_BYTES=134217728
|
SCAN_MAX_BYTES=134217728
|
||||||
|
# Daily encrypted database backup to its own bucket (docs/BACKUP.md).
|
||||||
|
BACKUP_S3_ENDPOINT=https://<account>.r2.cloudflarestorage.com
|
||||||
|
BACKUP_BUCKET=dtf-backups
|
||||||
|
BACKUP_ACCESS_KEY_ID=TBD
|
||||||
|
BACKUP_SECRET_ACCESS_KEY=TBD
|
||||||
|
BACKUP_AGE_RECIPIENT=age1...
|
||||||
|
BACKUP_HOUR=3
|
||||||
|
|
||||||
# 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
|
||||||
@@ -56,4 +78,3 @@ OPERATOR_PASSWORD_SECRET=TBD
|
|||||||
PAYMENT_TOKEN_SECRET=TBD
|
PAYMENT_TOKEN_SECRET=TBD
|
||||||
PAYMENT_WEBHOOK_SECRET=TBD
|
PAYMENT_WEBHOOK_SECRET=TBD
|
||||||
TINY_TOKEN_SECRET=TBD
|
TINY_TOKEN_SECRET=TBD
|
||||||
WHATSAPP_TOKEN_SECRET=TBD
|
|
||||||
|
|||||||
@@ -20,12 +20,12 @@ REQUIRED = (
|
|||||||
'POSTGRES_DB', 'POSTGRES_USER', 'APP_DB_USER', 'POSTGRES_VOLUME', 'OPERATOR_EMAIL',
|
'POSTGRES_DB', 'POSTGRES_USER', 'APP_DB_USER', 'POSTGRES_VOLUME', 'OPERATOR_EMAIL',
|
||||||
'STORAGE_QUOTA_BYTES', 'OWNER_UPLOAD_QUOTA_BYTES', 'MAX_UPLOAD_BYTES',
|
'STORAGE_QUOTA_BYTES', 'OWNER_UPLOAD_QUOTA_BYTES', 'MAX_UPLOAD_BYTES',
|
||||||
'UPLOAD_PART_BYTES', 'MAX_PENDING_UPLOADS', 'SCAN_MAX_BYTES',
|
'UPLOAD_PART_BYTES', 'MAX_PENDING_UPLOADS', 'SCAN_MAX_BYTES',
|
||||||
'PAYMENT_ADAPTER', 'FREIGHT_ADAPTER', 'TINY_ADAPTER', 'WHATSAPP_ADAPTER',
|
'PAYMENT_ADAPTER', 'FREIGHT_ADAPTER', 'TINY_ADAPTER',
|
||||||
'DATABASE_URL_SECRET', 'DATABASE_ADMIN_URL_SECRET',
|
'DATABASE_URL_SECRET', 'DATABASE_ADMIN_URL_SECRET',
|
||||||
'DB_ADMIN_PASSWORD_SECRET', 'APP_DB_PASSWORD_SECRET',
|
'DB_ADMIN_PASSWORD_SECRET', 'APP_DB_PASSWORD_SECRET',
|
||||||
'R2_ACCESS_KEY_ID_SECRET', 'R2_SECRET_ACCESS_KEY_SECRET',
|
'R2_ACCESS_KEY_ID_SECRET', 'R2_SECRET_ACCESS_KEY_SECRET',
|
||||||
'OPERATOR_PASSWORD_SECRET', 'PAYMENT_TOKEN_SECRET',
|
'OPERATOR_PASSWORD_SECRET', 'PAYMENT_TOKEN_SECRET',
|
||||||
'PAYMENT_WEBHOOK_SECRET', 'TINY_TOKEN_SECRET', 'WHATSAPP_TOKEN_SECRET',
|
'PAYMENT_WEBHOOK_SECRET', 'TINY_TOKEN_SECRET',
|
||||||
)
|
)
|
||||||
IMMUTABLE_IMAGE = re.compile(r'^[a-z0-9][a-z0-9._:/-]*@sha256:([0-9a-f]{64})$')
|
IMMUTABLE_IMAGE = re.compile(r'^[a-z0-9][a-z0-9._:/-]*@sha256:([0-9a-f]{64})$')
|
||||||
IMAGE_REPOSITORY = re.compile(
|
IMAGE_REPOSITORY = re.compile(
|
||||||
@@ -42,7 +42,7 @@ SOURCE_BLOCKERS = {
|
|||||||
'payment = FakePayment()',
|
'payment = FakePayment()',
|
||||||
),
|
),
|
||||||
'app/worker.py': (
|
'app/worker.py': (
|
||||||
"adapters = {'tiny': FakeTiny(), 'whatsapp': FakeWhatsApp()}",
|
"adapters = {'tiny': FakeTiny()}",
|
||||||
),
|
),
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -148,7 +148,7 @@ def config_errors(values):
|
|||||||
bucket = values.get('R2_BUCKET', '')
|
bucket = values.get('R2_BUCKET', '')
|
||||||
if bucket and not re.fullmatch(r'[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]', bucket):
|
if bucket and not re.fullmatch(r'[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]', bucket):
|
||||||
errors.append('R2_BUCKET must be a valid S3 bucket name')
|
errors.append('R2_BUCKET must be a valid S3 bucket name')
|
||||||
for name in ('PAYMENT_ADAPTER', 'FREIGHT_ADAPTER', 'TINY_ADAPTER', 'WHATSAPP_ADAPTER'):
|
for name in ('PAYMENT_ADAPTER', 'FREIGHT_ADAPTER', 'TINY_ADAPTER'):
|
||||||
if values.get(name, '').lower() in {'', 'fake', 'mock', 'local'}:
|
if values.get(name, '').lower() in {'', 'fake', 'mock', 'local'}:
|
||||||
errors.append(f'{name} must select an approved non-fake implementation')
|
errors.append(f'{name} must select an approved non-fake implementation')
|
||||||
for name in REQUIRED:
|
for name in REQUIRED:
|
||||||
|
|||||||
@@ -59,14 +59,13 @@ def valid_config():
|
|||||||
'PAYMENT_ADAPTER': 'mercado-pago',
|
'PAYMENT_ADAPTER': 'mercado-pago',
|
||||||
'FREIGHT_ADAPTER': 'approved-freight',
|
'FREIGHT_ADAPTER': 'approved-freight',
|
||||||
'TINY_ADAPTER': 'tiny-olist',
|
'TINY_ADAPTER': 'tiny-olist',
|
||||||
'WHATSAPP_ADAPTER': 'approved-whatsapp',
|
|
||||||
}
|
}
|
||||||
for name in (
|
for name in (
|
||||||
'DATABASE_URL_SECRET', 'DATABASE_ADMIN_URL_SECRET',
|
'DATABASE_URL_SECRET', 'DATABASE_ADMIN_URL_SECRET',
|
||||||
'DB_ADMIN_PASSWORD_SECRET', 'APP_DB_PASSWORD_SECRET',
|
'DB_ADMIN_PASSWORD_SECRET', 'APP_DB_PASSWORD_SECRET',
|
||||||
'R2_ACCESS_KEY_ID_SECRET', 'R2_SECRET_ACCESS_KEY_SECRET',
|
'R2_ACCESS_KEY_ID_SECRET', 'R2_SECRET_ACCESS_KEY_SECRET',
|
||||||
'OPERATOR_PASSWORD_SECRET', 'PAYMENT_TOKEN_SECRET',
|
'OPERATOR_PASSWORD_SECRET', 'PAYMENT_TOKEN_SECRET',
|
||||||
'PAYMENT_WEBHOOK_SECRET', 'TINY_TOKEN_SECRET', 'WHATSAPP_TOKEN_SECRET',
|
'PAYMENT_WEBHOOK_SECRET', 'TINY_TOKEN_SECRET',
|
||||||
):
|
):
|
||||||
values[name] = 'dtf_prod_' + name.lower()
|
values[name] = 'dtf_prod_' + name.lower()
|
||||||
return values
|
return values
|
||||||
|
|||||||
@@ -19,37 +19,127 @@ x-app-environment: &app-environment
|
|||||||
# this value is configured.
|
# this value is configured.
|
||||||
OPERATOR_EMAIL: ${OPERATOR_EMAIL:-}
|
OPERATOR_EMAIL: ${OPERATOR_EMAIL:-}
|
||||||
OPERATOR_PASSWORD: ${OPERATOR_PASSWORD:?set OPERATOR_PASSWORD}
|
OPERATOR_PASSWORD: ${OPERATOR_PASSWORD:?set OPERATOR_PASSWORD}
|
||||||
PAYMENT_ADAPTER: fake
|
# fake until Mercado Pago is configured; mercadopago requires MP_ACCESS_TOKEN
|
||||||
# Optional: without it the webhook verifies nothing and therefore accepts
|
# and MP_WEBHOOK_SECRET or the API and worker refuse to start. Test
|
||||||
# nothing, which is the correct state until a provider is connected. Set it
|
# credentials (TEST-...) until the sandbox flows have passed. The card form
|
||||||
# when the provider is configured, never to a value anyone could guess.
|
# appears only with MP_PUBLIC_KEY, and then needs PAYMENT_CSP_SOURCES too.
|
||||||
|
PAYMENT_ADAPTER: ${PAYMENT_ADAPTER:-fake}
|
||||||
|
MP_ACCESS_TOKEN: ${MP_ACCESS_TOKEN:-}
|
||||||
|
# The "assinatura secreta" from the webhook settings in Mercado Pago.
|
||||||
|
MP_WEBHOOK_SECRET: ${MP_WEBHOOK_SECRET:-}
|
||||||
|
# https://<SITE_DOMAIN>/api/payments/webhook, sent with every payment.
|
||||||
|
MP_NOTIFICATION_URL: ${MP_NOTIFICATION_URL:-}
|
||||||
|
MP_PUBLIC_KEY: ${MP_PUBLIC_KEY:-}
|
||||||
|
# The fake adapter's secret. Optional: without it the webhook verifies
|
||||||
|
# nothing and therefore accepts nothing, which is the correct state until a
|
||||||
|
# provider is connected. Never set it to a value anyone could guess.
|
||||||
PAYMENT_WEBHOOK_SECRET: ${PAYMENT_WEBHOOK_SECRET:-}
|
PAYMENT_WEBHOOK_SECRET: ${PAYMENT_WEBHOOK_SECRET:-}
|
||||||
FREIGHT_ADAPTER: fake
|
# fake offers pickup only. jadlog prices delivery with Jadlog and needs the
|
||||||
|
# credentials below and the package weight from the client; it refuses to
|
||||||
|
# start without them. The credentials alone are enough for the console
|
||||||
|
# check, python -m app.jadlog_probe, on the worker.
|
||||||
|
FREIGHT_ADAPTER: ${FREIGHT_ADAPTER:-fake}
|
||||||
|
JADLOG_TOKEN: ${JADLOG_TOKEN:-}
|
||||||
|
# The "Usuário" Jadlog issued: the CNPJ that contracts the freight.
|
||||||
|
JADLOG_CNPJ: ${JADLOG_CNPJ:-}
|
||||||
|
JADLOG_CONTA: ${JADLOG_CONTA:-}
|
||||||
|
JADLOG_CONTRATO: ${JADLOG_CONTRATO:-}
|
||||||
|
# Package weight in kg: a base plus each billed metre of film.
|
||||||
|
JADLOG_PESO_BASE_KG: ${JADLOG_PESO_BASE_KG:-}
|
||||||
|
JADLOG_PESO_POR_METRO_KG: ${JADLOG_PESO_POR_METRO_KG:-}
|
||||||
|
# The box (cm, "56x14x14") and the contract's cubage factor (kg/m³): Jadlog
|
||||||
|
# charges the larger of the real and the cubed weight. Both or neither.
|
||||||
|
JADLOG_CAIXA_CM: ${JADLOG_CAIXA_CM:-}
|
||||||
|
JADLOG_CUBAGEM_KG_M3: ${JADLOG_CUBAGEM_KG_M3:-}
|
||||||
|
# Metres of film one box holds; a longer order ships in more boxes.
|
||||||
|
JADLOG_METROS_POR_CAIXA: ${JADLOG_METROS_POR_CAIXA:-}
|
||||||
|
# Working days of production added to Jadlog's delivery time.
|
||||||
|
FREIGHT_PRODUCTION_DAYS: ${FREIGHT_PRODUCTION_DAYS:-0}
|
||||||
|
# Correios PAC and SEDEX, on when CORREIOS_CODIGO_ACESSO (the CWS access
|
||||||
|
# code, a secret: set it in the stack) is set. They price the package above
|
||||||
|
# (weights and JADLOG_CAIXA_CM). The rest is Dropstar's contract, not secret.
|
||||||
|
CORREIOS_CODIGO_ACESSO: ${CORREIOS_CODIGO_ACESSO:-}
|
||||||
|
CORREIOS_USUARIO: ${CORREIOS_USUARIO:-8825364223}
|
||||||
|
CORREIOS_CARTAO: ${CORREIOS_CARTAO:-0076691373}
|
||||||
|
CORREIOS_CONTRATO: ${CORREIOS_CONTRATO:-9912551407}
|
||||||
|
# Only if the contract's codes differ from 03298 (PAC) and 03220 (SEDEX);
|
||||||
|
# python -m app.correios_probe shows whether they price.
|
||||||
|
CORREIOS_COD_PAC: ${CORREIOS_COD_PAC:-}
|
||||||
|
CORREIOS_COD_SEDEX: ${CORREIOS_COD_SEDEX:-}
|
||||||
|
# A cart the Site priced is approved at checkout and can be paid at once;
|
||||||
|
# orders above QUOTE_AUTO_MAX_METRES, or with a grade the Site did not
|
||||||
|
# compute, wait for an operator on the Kanban (app/quote_review.py).
|
||||||
|
QUOTE_AUTO_APPROVE: ${QUOTE_AUTO_APPROVE:-true}
|
||||||
|
QUOTE_AUTO_MAX_METRES: ${QUOTE_AUTO_MAX_METRES:-50}
|
||||||
|
# Cents added to each metre of a finished sheet someone has to open by hand
|
||||||
|
# (CDR, AI, PSD, TIFF, or a length the customer typed). 0 adds nothing; 500
|
||||||
|
# is R$ 5,00 a metro. The Site shows it before the customer pays.
|
||||||
|
MANUAL_FILE_EXTRA_CENTS: ${MANUAL_FILE_EXTRA_CENTS:-0}
|
||||||
# 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
|
||||||
# keeps that connection alive. Callback: https://<KANBAN_DOMAIN>/api/operator/tiny/callback
|
# keeps that connection alive. Callback: https://<KANBAN_DOMAIN>/api/operator/tiny/callback
|
||||||
TINY_ADAPTER: fake
|
# fake until the supervised test order (python -m app.tiny_probe pedido) has
|
||||||
|
# passed on the client's account; then tiny, set in the stack.
|
||||||
|
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:-}
|
||||||
TINY_REDIRECT_URI: ${TINY_REDIRECT_URI:-}
|
TINY_REDIRECT_URI: ${TINY_REDIRECT_URI:-}
|
||||||
|
# Products, SKUs and the pickup forma de envio need no settings: the SKUs are
|
||||||
|
# Dropstar's catalogue (DTFIMP.TX…, DTFIMP.UV.1MT, DTFIMP.UV.010CM) and the
|
||||||
|
# pickup is found in Tiny by its name. These only override them.
|
||||||
TINY_PRODUCT_TEXTIL_FOLHA: ${TINY_PRODUCT_TEXTIL_FOLHA:-}
|
TINY_PRODUCT_TEXTIL_FOLHA: ${TINY_PRODUCT_TEXTIL_FOLHA:-}
|
||||||
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:-}
|
||||||
WHATSAPP_ADAPTER: fake
|
TINY_SKU_TEXTIL_FOLHA: ${TINY_SKU_TEXTIL_FOLHA:-}
|
||||||
|
TINY_SKU_TEXTIL_AVULSA: ${TINY_SKU_TEXTIL_AVULSA:-}
|
||||||
|
TINY_SKU_UV_FOLHA: ${TINY_SKU_UV_FOLHA:-}
|
||||||
|
TINY_SKU_UV_AVULSA: ${TINY_SKU_UV_AVULSA:-}
|
||||||
|
TINY_SKU10_TEXTIL_FOLHA: ${TINY_SKU10_TEXTIL_FOLHA:-}
|
||||||
|
TINY_SKU10_TEXTIL_AVULSA: ${TINY_SKU10_TEXTIL_AVULSA:-}
|
||||||
|
TINY_SKU10_UV_FOLHA: ${TINY_SKU10_UV_FOLHA:-}
|
||||||
|
TINY_SKU10_UV_AVULSA: ${TINY_SKU10_UV_AVULSA:-}
|
||||||
|
TINY_SKU_METRO_TEXTIL_FOLHA: ${TINY_SKU_METRO_TEXTIL_FOLHA:-}
|
||||||
|
TINY_SKU_METRO_TEXTIL_AVULSA: ${TINY_SKU_METRO_TEXTIL_AVULSA:-}
|
||||||
|
TINY_SKU_METRO_UV_FOLHA: ${TINY_SKU_METRO_UV_FOLHA:-}
|
||||||
|
TINY_SKU_METRO_UV_AVULSA: ${TINY_SKU_METRO_UV_AVULSA:-}
|
||||||
|
# The client's "retirar pessoalmente" forma de envio id, on pickup orders.
|
||||||
|
TINY_FORMA_ENVIO_RETIRADA: ${TINY_FORMA_ENVIO_RETIRADA:-}
|
||||||
|
# Sets "Aprovada" on paid orders and "Pronto para envio" on finished pickup
|
||||||
|
# orders, which the client's Tiny -> n8n notices send to customers. Turn on
|
||||||
|
# only together with TINY_ADAPTER=tiny and after n8n stops sending the
|
||||||
|
# designer message for DTFIMP products.
|
||||||
|
TINY_STATUS_UPDATES: ${TINY_STATUS_UPDATES:-false}
|
||||||
|
# E-mail: customers' password recovery and the team's alerts (app/mail.py).
|
||||||
|
# off until the client's SMTP account exists; then smtp with the settings
|
||||||
|
# below, or the API and worker refuse to start. SMTP_SECURITY is starttls
|
||||||
|
# (port 587), ssl (465) or none.
|
||||||
|
MAIL_ADAPTER: ${MAIL_ADAPTER:-off}
|
||||||
|
MAIL_FROM: ${MAIL_FROM:-}
|
||||||
|
MAIL_REPLY_TO: ${MAIL_REPLY_TO:-}
|
||||||
|
SMTP_HOST: ${SMTP_HOST:-}
|
||||||
|
SMTP_PORT: ${SMTP_PORT:-}
|
||||||
|
SMTP_SECURITY: ${SMTP_SECURITY:-starttls}
|
||||||
|
SMTP_USER: ${SMTP_USER:-}
|
||||||
|
SMTP_PASSWORD: ${SMTP_PASSWORD:-}
|
||||||
STORAGE_ADAPTER: s3-r2
|
STORAGE_ADAPTER: s3-r2
|
||||||
PUBLIC_ORIGIN: https://${SITE_DOMAIN:?set SITE_DOMAIN}
|
PUBLIC_ORIGIN: https://${SITE_DOMAIN:?set SITE_DOMAIN}
|
||||||
PUBLIC_HOST: ${SITE_DOMAIN:?set SITE_DOMAIN}
|
PUBLIC_HOST: ${SITE_DOMAIN:?set SITE_DOMAIN}
|
||||||
ALLOWED_HOSTS: ${SITE_DOMAIN:?set SITE_DOMAIN},${KANBAN_DOMAIN:?set KANBAN_DOMAIN}
|
ALLOWED_HOSTS: ${SITE_DOMAIN:?set SITE_DOMAIN},${KANBAN_DOMAIN:?set KANBAN_DOMAIN}
|
||||||
ALLOWED_ORIGINS: https://${SITE_DOMAIN:?set SITE_DOMAIN},https://${KANBAN_DOMAIN:?set KANBAN_DOMAIN}
|
ALLOWED_ORIGINS: https://${SITE_DOMAIN:?set SITE_DOMAIN},https://${KANBAN_DOMAIN:?set KANBAN_DOMAIN}
|
||||||
COOKIE_SECURE: "true"
|
COOKIE_SECURE: "true"
|
||||||
MAX_UPLOAD_BYTES: "5368709120"
|
# 1 GB per file (Dropstar, 2026-10-21): a 57 cm x 5 m sheet at 300 DPI is
|
||||||
|
# 200 to 300 MB, and much more takes an hour to send on a common connection.
|
||||||
|
MAX_UPLOAD_BYTES: "1073741824"
|
||||||
UPLOAD_PART_BYTES: "8388608"
|
UPLOAD_PART_BYTES: "8388608"
|
||||||
STORAGE_QUOTA_BYTES: "53687091200"
|
# Sheets of several GB are the normal order, so room for many of them.
|
||||||
OWNER_UPLOAD_QUOTA_BYTES: "10737418240"
|
STORAGE_QUOTA_BYTES: "${STORAGE_QUOTA_BYTES:-536870912000}"
|
||||||
|
OWNER_UPLOAD_QUOTA_BYTES: "${OWNER_UPLOAD_QUOTA_BYTES:-53687091200}"
|
||||||
MAX_PENDING_UPLOADS: "10"
|
MAX_PENDING_UPLOADS: "10"
|
||||||
SCAN_MAX_BYTES: "134217728"
|
# ClamAV scans up to this, so every file up to MAX_UPLOAD_BYTES is scanned;
|
||||||
|
# a larger one would be released after a file-format check (app/scanning.py).
|
||||||
|
SCAN_MAX_BYTES: "1073741824"
|
||||||
|
|
||||||
services:
|
services:
|
||||||
db:
|
db:
|
||||||
@@ -95,7 +185,7 @@ services:
|
|||||||
image: clamav/clamav@sha256:9cb27d7660bdf66e9878c832cb433dd8aa152cfbe16f3c2c0084c80b04ae22b4
|
image: clamav/clamav@sha256:9cb27d7660bdf66e9878c832cb433dd8aa152cfbe16f3c2c0084c80b04ae22b4
|
||||||
entrypoint: [clamd, --foreground=true, --config-file=/etc/clamav/clamd.conf]
|
entrypoint: [clamd, --foreground=true, --config-file=/etc/clamav/clamd.conf]
|
||||||
configs:
|
configs:
|
||||||
- source: clamd_config
|
- source: clamd_config_2gb
|
||||||
target: /etc/clamav/clamd.conf
|
target: /etc/clamav/clamd.conf
|
||||||
mode: 0444
|
mode: 0444
|
||||||
networks: [backend]
|
networks: [backend]
|
||||||
@@ -116,7 +206,10 @@ services:
|
|||||||
environment: *app-environment
|
environment: *app-environment
|
||||||
networks: [backend, egress]
|
networks: [backend, egress]
|
||||||
read_only: true
|
read_only: true
|
||||||
tmpfs: [/tmp]
|
# 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.
|
||||||
|
volumes:
|
||||||
|
- {type: tmpfs, target: /tmp, tmpfs: {size: 268435456}}
|
||||||
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
|
||||||
@@ -133,7 +226,8 @@ services:
|
|||||||
environment: *app-environment
|
environment: *app-environment
|
||||||
networks: [backend, egress]
|
networks: [backend, egress]
|
||||||
read_only: true
|
read_only: true
|
||||||
tmpfs: [/tmp]
|
# Print files are rendered here and can be hundreds of MB: on disk, not in memory.
|
||||||
|
volumes: [worker-tmp:/tmp]
|
||||||
healthcheck:
|
healthcheck:
|
||||||
test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8002/health',timeout=3)"]
|
test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8002/health',timeout=3)"]
|
||||||
interval: 15s
|
interval: 15s
|
||||||
@@ -144,6 +238,36 @@ services:
|
|||||||
replicas: 1
|
replicas: 1
|
||||||
restart_policy: {condition: on-failure, delay: 5s}
|
restart_policy: {condition: on-failure, delay: 5s}
|
||||||
|
|
||||||
|
# Daily encrypted copy of the database to a bucket of its own, off this
|
||||||
|
# server (ops/db_backup.py). Idle until the BACKUP_* settings are set. The
|
||||||
|
# bucket's lifecycle rule removes old copies; this credential never deletes.
|
||||||
|
backup:
|
||||||
|
image: ${API_IMAGE:-gitea.blyzer.com.br/blyzer/dtf-api}:${IMAGE_TAG:-latest}
|
||||||
|
command: python -m ops.db_backup serve
|
||||||
|
environment:
|
||||||
|
DATABASE_ADMIN_HOST: db
|
||||||
|
DATABASE_ADMIN_NAME: dtf
|
||||||
|
DATABASE_ADMIN_USER: dtf_admin
|
||||||
|
DATABASE_ADMIN_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD}
|
||||||
|
# The R2 account endpoint (the same as R2_ENDPOINT) and a bucket and API
|
||||||
|
# token for backups only, never the artwork bucket's.
|
||||||
|
BACKUP_S3_ENDPOINT: ${BACKUP_S3_ENDPOINT:-}
|
||||||
|
BACKUP_BUCKET: ${BACKUP_BUCKET:-}
|
||||||
|
BACKUP_ACCESS_KEY_ID: ${BACKUP_ACCESS_KEY_ID:-}
|
||||||
|
BACKUP_SECRET_ACCESS_KEY: ${BACKUP_SECRET_ACCESS_KEY:-}
|
||||||
|
# The public key (age1...). Its private key stays off this server.
|
||||||
|
BACKUP_AGE_RECIPIENT: ${BACKUP_AGE_RECIPIENT:-}
|
||||||
|
# Hour of day in Brasília.
|
||||||
|
BACKUP_HOUR: ${BACKUP_HOUR:-3}
|
||||||
|
networks: [backend, egress]
|
||||||
|
read_only: true
|
||||||
|
# In memory: a restore's private key is written here while it runs.
|
||||||
|
volumes:
|
||||||
|
- {type: tmpfs, target: /tmp, tmpfs: {size: 1073741824}}
|
||||||
|
deploy:
|
||||||
|
replicas: 1
|
||||||
|
restart_policy: {condition: on-failure, delay: 30s}
|
||||||
|
|
||||||
site:
|
site:
|
||||||
image: ${WEB_IMAGE:-gitea.blyzer.com.br/blyzer/dtf-web}:${IMAGE_TAG:-latest}
|
image: ${WEB_IMAGE:-gitea.blyzer.com.br/blyzer/dtf-web}:${IMAGE_TAG:-latest}
|
||||||
environment:
|
environment:
|
||||||
@@ -153,6 +277,10 @@ 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 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
|
||||||
|
# frames and form posts reach it (never scripts). Empty turns it off.
|
||||||
|
PAYMENT_CHALLENGE_SOURCES: ${PAYMENT_CHALLENGE_SOURCES:-}
|
||||||
networks: [backend]
|
networks: [backend]
|
||||||
ports:
|
ports:
|
||||||
- target: 8080
|
- target: 8080
|
||||||
@@ -176,6 +304,7 @@ services:
|
|||||||
PUBLIC_HOST: ${KANBAN_DOMAIN:?set KANBAN_DOMAIN}
|
PUBLIC_HOST: ${KANBAN_DOMAIN:?set KANBAN_DOMAIN}
|
||||||
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: ""
|
||||||
networks: [backend]
|
networks: [backend]
|
||||||
ports:
|
ports:
|
||||||
- target: 8080
|
- target: 8080
|
||||||
@@ -193,11 +322,14 @@ services:
|
|||||||
restart_policy: {condition: on-failure, delay: 5s}
|
restart_policy: {condition: on-failure, delay: 5s}
|
||||||
|
|
||||||
configs:
|
configs:
|
||||||
clamd_config:
|
# Renamed whenever infra/clamd.conf changes: Swarm cannot update a deployed
|
||||||
|
# config in place, and a redeploy with new content under the old name fails.
|
||||||
|
clamd_config_2gb:
|
||||||
file: ./infra/clamd.conf
|
file: ./infra/clamd.conf
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
postgres-data:
|
postgres-data:
|
||||||
|
worker-tmp:
|
||||||
|
|
||||||
networks:
|
networks:
|
||||||
backend:
|
backend:
|
||||||
|
|||||||
87
docs/BACKUP.md
Normal file
@@ -0,0 +1,87 @@
|
|||||||
|
# Database backup
|
||||||
|
|
||||||
|
The `backup` service copies the database off the server once a day
|
||||||
|
(`ops/db_backup.py`). It runs `pg_dump`, checks the archive, encrypts it with
|
||||||
|
[age](https://age-encryption.org) and uploads it to an R2 bucket used for
|
||||||
|
nothing else. Each run is recorded, and the Kanban shows the latest one under
|
||||||
|
Integrações → "Backup do banco" ("Em dia", "Verificar" or "Não configurado").
|
||||||
|
|
||||||
|
The artwork is not backed up. Originals and print files are temporary (7 to 30
|
||||||
|
days) and already stored on R2. The database holds what cannot be recreated:
|
||||||
|
orders, customers, quotes, payments, the Tiny connection and the operators.
|
||||||
|
|
||||||
|
## Why the backup cannot be read or deleted from the server
|
||||||
|
|
||||||
|
- **The server only encrypts.** It holds the public key (`age1…`). The private
|
||||||
|
key, which is the only way to open a backup, stays with the owner.
|
||||||
|
- **Its own bucket and token.** The backup token reaches the backup bucket
|
||||||
|
only, and the artwork token cannot reach it.
|
||||||
|
- **Nothing is deleted by the job.** The bucket's lifecycle rule removes old
|
||||||
|
copies. The bucket lock keeps anyone, including someone holding the token,
|
||||||
|
from deleting or overwriting a copy before its time.
|
||||||
|
|
||||||
|
## Setup (once)
|
||||||
|
|
||||||
|
1. **Key pair.** Generate it on your own computer, not on the server:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker run --rm gitea.blyzer.com.br/blyzer/dtf-api:latest age-keygen
|
||||||
|
```
|
||||||
|
|
||||||
|
Or, with age installed (`sudo pacman -S age`, `apt install age`), just
|
||||||
|
run `age-keygen`.
|
||||||
|
|
||||||
|
Save the whole output (the `AGE-SECRET-KEY-1…` line is the private key) in
|
||||||
|
the password manager. Only the `public key: age1…` value goes to Portainer.
|
||||||
|
Without the private key, no backup can ever be restored.
|
||||||
|
2. **Cloudflare R2 → Create bucket.** Use a name such as `dtf-backups`.
|
||||||
|
3. **Settings on that bucket:**
|
||||||
|
- Object lifecycle rules: delete objects after 35 days.
|
||||||
|
- Bucket lock rules: retain for 30 days, prefix `db/`.
|
||||||
|
4. **R2 → Manage API tokens → Create API token.**
|
||||||
|
- Permission: Object Read & Write.
|
||||||
|
- Scope: the `dtf-backups` bucket only.
|
||||||
|
5. **Portainer.** Add these to the stack's environment, then redeploy:
|
||||||
|
|
||||||
|
| Variable | Value |
|
||||||
|
|---|---|
|
||||||
|
| `BACKUP_S3_ENDPOINT` | same as `R2_ENDPOINT` |
|
||||||
|
| `BACKUP_BUCKET` | `dtf-backups` |
|
||||||
|
| `BACKUP_ACCESS_KEY_ID` | the new token's Access Key ID |
|
||||||
|
| `BACKUP_SECRET_ACCESS_KEY` | the new token's Secret Access Key |
|
||||||
|
| `BACKUP_AGE_RECIPIENT` | the public key, `age1…` |
|
||||||
|
| `BACKUP_HOUR` | optional, default `3` (03:00 Brasília) |
|
||||||
|
|
||||||
|
The first backup runs as soon as the service starts. After that it runs daily,
|
||||||
|
and a failed run is retried an hour later.
|
||||||
|
|
||||||
|
## Restore test
|
||||||
|
|
||||||
|
Do this after setup, and then once a month. Open the console of the `backup`
|
||||||
|
container in Portainer (Containers → `…_backup…` → Console) and run:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python -m ops.db_backup list
|
||||||
|
python -m ops.db_backup verify --identity -
|
||||||
|
```
|
||||||
|
|
||||||
|
`--identity -` asks for the private key to be pasted. It is kept only in the
|
||||||
|
container's memory while the command runs. `verify` restores the latest backup
|
||||||
|
into a scratch database, prints its row counts and drops it. The live database
|
||||||
|
is not touched.
|
||||||
|
|
||||||
|
## Restoring for real
|
||||||
|
|
||||||
|
From the `backup` container's console:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python -m ops.db_backup restore db/2026/10/dtf-20261001T060000Z.dump.age --into dtf_restored --identity -
|
||||||
|
```
|
||||||
|
|
||||||
|
This restores into a new database (or an empty one), never over the running
|
||||||
|
one. Then do one of these:
|
||||||
|
|
||||||
|
- **Check the restored data**, then point the stack at it.
|
||||||
|
- **On a new server**, deploy only the `db` service first. Restore into `dtf`
|
||||||
|
while it is still empty, then deploy the rest. `db-init` then applies the
|
||||||
|
schema and grants on top.
|
||||||
126
docs/CONTEXT.md
@@ -38,7 +38,9 @@ online system, not factory-machine automation.
|
|||||||
- Freight quotation and charging at checkout.
|
- Freight quotation and charging at checkout.
|
||||||
- Idempotent Tiny/Olist order integration and order traceability.
|
- Idempotent Tiny/Olist order integration and order traceability.
|
||||||
- Online Kanban for production status and secure file download.
|
- Online Kanban for production status and secure file download.
|
||||||
- WhatsApp status notifications.
|
- Customer status notices: not sent by this system. The client's own n8n sends
|
||||||
|
WhatsApp messages from Tiny's status changes (decided 2026-10-16); the Kanban
|
||||||
|
only offers a one-click WhatsApp link for a correction.
|
||||||
- Private object storage, 30-day file retention, backups, and basic security.
|
- Private object storage, 30-day file retention, backups, and basic security.
|
||||||
- Operator guidance for the factory team.
|
- Operator guidance for the factory team.
|
||||||
|
|
||||||
@@ -149,6 +151,11 @@ The current site contains four product modes, quality-based price tiers,
|
|||||||
artwork-ready discounts, separate assembly charges for loose artwork, a
|
artwork-ready discounts, separate assembly charges for loose artwork, a
|
||||||
one-metre minimum, and ten-centimetre billing rounding.
|
one-metre minimum, and ten-centimetre billing rounding.
|
||||||
|
|
||||||
|
Customers buy with a CPF (a person) or a CNPJ (a company), check digits
|
||||||
|
validated on both sides. The value keeps the `cnpj` key in orders, quotes and
|
||||||
|
accounts; Tiny gets a CPF contact as `tipoPessoa` F, Mercado Pago the matching
|
||||||
|
identification type, and only CNPJs are looked up in the company registry.
|
||||||
|
|
||||||
The browser may display the calculation, but production payment creation must
|
The browser may display the calculation, but production payment creation must
|
||||||
recalculate and validate all price, quantity, freight, and discount values on
|
recalculate and validate all price, quantity, freight, and discount values on
|
||||||
the server. Client-provided totals are never authoritative.
|
the server. Client-provided totals are never authoritative.
|
||||||
@@ -161,8 +168,25 @@ the ready-sheet option before uploading. PDF and manual-format ready sheets keep
|
|||||||
their existing workflow. These models retain their separate approved price tiers;
|
their existing workflow. These models retain their separate approved price tiers;
|
||||||
image dimensions alone must never classify a normal artwork as a finished sheet.
|
image dimensions alone must never classify a normal artwork as a finished sheet.
|
||||||
|
|
||||||
|
A finished sheet someone must open by hand (CDR, AI, PSD, TIFF, or a length the
|
||||||
|
customer typed) pays the top of the ladder plus `MANUAL_FILE_EXTRA_CENTS` per
|
||||||
|
metre (2026-10-13, asked at the 7 October meeting to steer customers to PNG).
|
||||||
|
It defaults to 0; the amount is the client's to set. The Site reads it from
|
||||||
|
`/api/session` and shows it before checkout; `app/core/pricing.py` charges it.
|
||||||
|
|
||||||
## Freight
|
## Freight
|
||||||
|
|
||||||
|
**Current (2026-10-15):** the cart quotes every carrier configured at once and
|
||||||
|
lists the options cheapest first, with the delivery time: Jadlog .PACKAGE
|
||||||
|
(`app/jadlog.py`) and Correios PAC and SEDEX (`app/correios.py`, Dropstar's
|
||||||
|
contract 9912551407, card 0076691373), plus pickup in Franca. A carrier that
|
||||||
|
does not answer is left out; the customer's choice is quoted again by the
|
||||||
|
server at approval. All carriers price the same package (`app/package.py`: a
|
||||||
|
base weight per box, a weight per metre, the box's sides, metres per box).
|
||||||
|
Correios is on when `CORREIOS_CODIGO_ACESSO` is set; `python -m
|
||||||
|
app.correios_probe` checks the contract's token, codes (03298 PAC, 03220
|
||||||
|
SEDEX by default), prices and times. The history below is kept as recorded.
|
||||||
|
|
||||||
The original visual freight flow in `web/index.html` was a stub with only pickup
|
The original visual freight flow in `web/index.html` was a stub with only pickup
|
||||||
functional. The localhost bridge now supports pickup and backend fake freight
|
functional. The localhost bridge now supports pickup and backend fake freight
|
||||||
quotes; there is still no real carrier quotation or production checkout.
|
quotes; there is still no real carrier quotation or production checkout.
|
||||||
@@ -187,6 +211,12 @@ amount is final.
|
|||||||
|
|
||||||
### Mercado Pago
|
### Mercado Pago
|
||||||
|
|
||||||
|
Card payments: up to 3 installments **with interest paid by the customer**;
|
||||||
|
1x has no interest (Wagner, 2026-10-14). Interest is Mercado Pago's: its card
|
||||||
|
form shows each option with the rate, and the order checks
|
||||||
|
`transaction_amount` (the price), not the total with interest. Keep "parcelamento
|
||||||
|
sem juros" off in the Mercado Pago account, or Dropstar pays the interest.
|
||||||
|
|
||||||
Required before production payment integration, not for the local mock milestone:
|
Required before production payment integration, not for the local mock milestone:
|
||||||
|
|
||||||
- Production credentials.
|
- Production credentials.
|
||||||
@@ -202,6 +232,26 @@ Tiny/Olist is already available. The implementation must create/update orders
|
|||||||
idempotently and use the order number for traceability. Confirm the actual API
|
idempotently and use the order number for traceability. Confirm the actual API
|
||||||
endpoints, marker/tag behaviour, and rate limits before production use.
|
endpoints, marker/tag behaviour, and rate limits before production use.
|
||||||
|
|
||||||
|
### E-mail
|
||||||
|
|
||||||
|
`app/mail.py` (2026-10-13): customers' password recovery (a one-time link,
|
||||||
|
valid one hour, sent to `/conta/redefinir#token`; only the token's hash is
|
||||||
|
stored and the message text is erased once sent). Since 2026-10-20 the team
|
||||||
|
gets no alert e-mails: the Kanban and Tiny are where orders are followed.
|
||||||
|
Messages are queued in the transaction that caused them and
|
||||||
|
sent by the worker with retries. `MAIL_ADAPTER` is `off` in production until
|
||||||
|
the client's SMTP account exists (recovery then offers WhatsApp), `log` on the
|
||||||
|
local stack, `smtp` with `SMTP_*` and `MAIL_FROM`.
|
||||||
|
|
||||||
|
Signup (2026-10-14): with e-mail on, an account is created only after the
|
||||||
|
6-digit code e-mailed to the address is entered (15 minutes, 5 wrong attempts,
|
||||||
|
a new code after 60 s, at most 5). The password is hashed at the first step
|
||||||
|
and the code stored only as a hash. The answer is the same for an address that
|
||||||
|
already has an account: it gets a "você já tem conta" notice instead of a code.
|
||||||
|
Changing the account's e-mail works the same way: the code goes to the new
|
||||||
|
address, the e-mail changes only once it is entered, and the old address is
|
||||||
|
told. Production sends through the client's Locaweb SMTP (set in the stack).
|
||||||
|
|
||||||
### WhatsApp
|
### WhatsApp
|
||||||
|
|
||||||
WhatsApp is already available, but the technical provider still needs to be
|
WhatsApp is already available, but the technical provider still needs to be
|
||||||
@@ -245,6 +295,65 @@ supports subsequent corrections or scoped enhancements.
|
|||||||
|
|
||||||
## Known implementation status
|
## Known implementation status
|
||||||
|
|
||||||
|
### Launch status (2026-10-19)
|
||||||
|
|
||||||
|
Live on dropstardtf.com.br (Site) and kanban.dropstardtf.com.br (Kanban), with
|
||||||
|
Mercado Pago in production, Correios PAC/SEDEX and Jadlog, SMTP e-mail and the
|
||||||
|
daily R2 backup. The system sends no WhatsApp: the client's n8n does, from
|
||||||
|
Tiny's situação (middleware in the separate api-tiny-n8n project). Tiny orders
|
||||||
|
are filled in as the store's own (app/tiny.py: payment, carrier, expected
|
||||||
|
date), with Dropstar's ids where the app may not list them.
|
||||||
|
|
||||||
|
Before go-live: Dropstar's category, seller and tag for Site orders in Tiny; a
|
||||||
|
supervised test order (`python -m app.tiny_probe pedido ... --confirmar`); the
|
||||||
|
n8n "isDTFIMP" node skipping orders whose numero_ecommerce starts with "DTF-";
|
||||||
|
then TINY_STATUS_UPDATES=true and TINY_ADAPTER=tiny, a backup,
|
||||||
|
`ops.launch_reset`, a real Pix and card payment refunded, and the pilot with
|
||||||
|
5 to 10 customers. The guides' screenshots are reproducible from
|
||||||
|
docs/guias/telas/.
|
||||||
|
|
||||||
|
### Kanban automatic folder (agreed in the 2026-10-07 meeting)
|
||||||
|
|
||||||
|
The Kanban, open on the print room's computer, saves the files to a folder
|
||||||
|
chosen in Integrações (Chrome or Edge; Firefox only downloads). Per computer,
|
||||||
|
it downloads as soon as the order arrives in Arte recebida (the default since
|
||||||
|
2026-10-20), into a `Recebidos` folder inside the chosen one, moved up when
|
||||||
|
the order enters the queue; or only when the order enters the print queue.
|
||||||
|
Files of orders cancelled, deleted or sent back for correction, and files
|
||||||
|
replaced by another final, are removed from the folder
|
||||||
|
(`POST /api/operator/queue/folder`).
|
||||||
|
|
||||||
|
Integrações (2026-10-20): only the superadmin (us) has the buttons, the
|
||||||
|
details and the Tiny log there (`integrations` capability, app/core/auth.py).
|
||||||
|
Admins and gestão see each integration's state and summary; anyone who
|
||||||
|
produces also gets the folder's row with its buttons.
|
||||||
|
|
||||||
|
Machines (2026-10-20, app/machines.py): each order keeps one machine, either
|
||||||
|
chosen in the order panel or given on arrival: the active machine of its
|
||||||
|
product with the fewest metres open (rec, tra, fil, imp, cor), preferring
|
||||||
|
those below their optional limit in metres, else the least loaded anyway (the
|
||||||
|
Usuários page shows it over the limit). A machine switched off, deleted or no
|
||||||
|
longer printing the product hands its automatic orders, not yet printing, to
|
||||||
|
that choice again. Only operators are linked to machines (from the user or
|
||||||
|
the machine form); a linked operator sees only those machines' orders.
|
||||||
|
|
||||||
|
Dropstar's corrections of 2026-10-21 already done: the home example priced as
|
||||||
|
a ready sheet; opening hours 7h to 18h with "send your art any time"; uploads
|
||||||
|
up to 1 GB (MAX_UPLOAD_BYTES, scanned whole by ClamAV); a Designer profile
|
||||||
|
(artwork stages only, every order, no machine, queue or cancelling;
|
||||||
|
DESIGNER_STATES in app/core/auth.py, the "print" capability for the room's
|
||||||
|
side); Números by date range, per machine (metres finished, metres per hour
|
||||||
|
in Imprimindo, last finished, now) and orders apart from passages. A machine's
|
||||||
|
metres are the film printed (item `metres`), never the billed ones, and time
|
||||||
|
two orders spent in Imprimindo together counts once; a stage's median is per
|
||||||
|
order, the sum of its passages. Layout version 3 (web/site-packing.js): rows
|
||||||
|
with exact sizes, 5 mm margins top and bottom and between rows, and across
|
||||||
|
the width 5 mm or the space left shared out equally (1,5 mm at least); the
|
||||||
|
shape packing is used only when it saves 1 cm or more. Waiting on
|
||||||
|
Dropstar: the Tiny category/seller/tag conflict, residue and opaque background
|
||||||
|
blocking, the print-file footer, the packing margins, the DTF terms, the
|
||||||
|
manual-file value, the proof print, and mirroring.
|
||||||
|
|
||||||
### Active localhost milestone (2026-09-15)
|
### Active localhost milestone (2026-09-15)
|
||||||
|
|
||||||
The current implementation target is localhost before any production connection.
|
The current implementation target is localhost before any production connection.
|
||||||
@@ -258,7 +367,7 @@ as references and are not imported or started by Compose.
|
|||||||
jobs provision restricted runtime identities, for nine Compose services total.
|
jobs provision restricted runtime identities, for nine Compose services total.
|
||||||
- MinIO implements the S3 storage boundary with direct multipart browser uploads,
|
- MinIO implements the S3 storage boundary with direct multipart browser uploads,
|
||||||
resumable parts, private objects, and short-lived signed operator downloads.
|
resumable parts, private objects, and short-lived signed operator downloads.
|
||||||
- Payment, freight, Tiny/Olist, and WhatsApp use fake adapters only. No production
|
- Payment, freight, and Tiny/Olist use fake adapters only. No production
|
||||||
credentials or integrations are configured. The API and worker have no external
|
credentials or integrations are configured. The API and worker have no external
|
||||||
network route; only local web/storage gateways publish loopback ports.
|
network route; only local web/storage gateways publish loopback ports.
|
||||||
- The original Site commercial calculation and appearance remain the source of
|
- The original Site commercial calculation and appearance remain the source of
|
||||||
@@ -278,9 +387,11 @@ as references and are not imported or started by Compose.
|
|||||||
- The customer portal at `/portal.html` supports local registration/login,
|
- The customer portal at `/portal.html` supports local registration/login,
|
||||||
stronger scrypt password hashing with legacy-hash upgrade, revocable HttpOnly
|
stronger scrypt password hashing with legacy-hash upgrade, revocable HttpOnly
|
||||||
sessions, owned order history/status, secure active
|
sessions, owned order history/status, secure active
|
||||||
file downloads, and correction uploads. Registration/login can claim only the
|
file downloads, and correction uploads. Registration/login claims the current
|
||||||
current guest session's records, never orders found by email or CNPJ. Email
|
guest session's records and, once the account's e-mail is confirmed with a
|
||||||
verification and password recovery are not implemented.
|
code, every guest order placed with the account's CPF/CNPJ and e-mail
|
||||||
|
together, from any browser; never by CPF/CNPJ alone. Signup and e-mail
|
||||||
|
changes are confirmed by an e-mailed code; password recovery by a link.
|
||||||
- Unfinished carts (including File blobs) recover from IndexedDB for 24 hours in
|
- Unfinished carts (including File blobs) recover from IndexedDB for 24 hours in
|
||||||
the same browser, scoped to the guest/account identity. Recovered items can be
|
the same browser, scoped to the guest/account identity. Recovered items can be
|
||||||
removed/replaced or joined by new items; in-place reconstruction of the artwork
|
removed/replaced or joined by new items; in-place reconstruction of the artwork
|
||||||
@@ -370,8 +481,9 @@ referenced them; recover from Git history if ever needed.
|
|||||||
authentication, purchase history, or real cart persistence. Local order
|
authentication, purchase history, or real cart persistence. Local order
|
||||||
persistence, reviewed quotes, mock freight and fake payment now work through
|
persistence, reviewed quotes, mock freight and fake payment now work through
|
||||||
`web/checkout.js`. The local customer portal now provides accounts and
|
`web/checkout.js`. The local customer portal now provides accounts and
|
||||||
order history; cart recovery is browser-local. Production account verification,
|
order history; cart recovery is browser-local. Password recovery by e-mail
|
||||||
recovery, and cross-device cart editing are still absent.
|
exists (see E-mail) but waits for the client's SMTP account; account e-mail
|
||||||
|
verification and cross-device cart editing are still absent.
|
||||||
- Without the local bridge, the original freight fallback remains a stub.
|
- Without the local bridge, the original freight fallback remains a stub.
|
||||||
Real freight quotation remains unimplemented in all runtimes.
|
Real freight quotation remains unimplemented in all runtimes.
|
||||||
- The existing the removed prototypes duplicated WhatsApp senders and send
|
- The existing the removed prototypes duplicated WhatsApp senders and send
|
||||||
|
|||||||
@@ -62,25 +62,35 @@ operator interfaces.
|
|||||||
4. Click the Site checkout button. Files upload directly to MinIO, remain
|
4. Click the Site checkout button. Files upload directly to MinIO, remain
|
||||||
quarantined until ClamAV returns `clean`, and then become eligible for a quote.
|
quarantined until ClamAV returns `clean`, and then become eligible for a quote.
|
||||||
The local banner displays a quote ID awaiting commercial review.
|
The local banner displays a quote ID awaiting commercial review.
|
||||||
5. Open Kanban and log in. In **Cotações**, download the original if needed,
|
5. Open Kanban and log in. Open the **Cotações** tab, pick the quote, download
|
||||||
confirm/correct total metres and grade, tick the manual confirmation, and
|
the original if needed, confirm/correct metres and grade, tick the
|
||||||
click **Aprovar cotação**. For the fixture keep 1.01 m and grade 0.
|
confirmation at the bottom and click **Aprovar cotação**. For the fixture
|
||||||
|
keep 1.01 m and grade 0.
|
||||||
6. Return to the Site and click its checkout action again. Inspect the
|
6. Return to the Site and click its checkout action again. Inspect the
|
||||||
authoritative server total, then click **Criar pedido de teste**. No real
|
authoritative server total, then click **Criar pedido de teste**. No real
|
||||||
payment occurs.
|
payment occurs.
|
||||||
7. Refresh Kanban. The paid order starts in **Arte recebida**. Move it using
|
7. Click **Atualizar** on the Kanban. The paid order appears in **Arte
|
||||||
the buttons or drag and drop to **Arte tratada**. Open **Arquivos de produção**,
|
recebida** on the **Produção** tab. Click its card to open the order panel,
|
||||||
select the manually prepared final files for every item, enter a review note,
|
then **Mover para Arte conferida** (dragging the card to a column also works).
|
||||||
tick the confirmation and click **Aprovar arquivos finais**. Use the harmless
|
In the panel's **Arquivos finais**, select the manually prepared final file
|
||||||
fixture again only for this local test. The text fixture is not an image, so
|
for every item, enter a review note, tick the confirmation and click
|
||||||
its print file shows **preparar à mão**; with a PNG or JPEG artwork the
|
**Aprovar arquivos finais**. Use the harmless fixture again only for this
|
||||||
generated PDF is preselected instead (see "Print files").
|
local test. The text fixture is not an image, so its print file shows
|
||||||
Continue through **Fila de impressão →
|
**Preparar à mão**; with a PNG, JPEG or PDF artwork the generated file is
|
||||||
Imprimindo → Finalizado**. A move to **Correção** requires a reason; it can
|
preselected instead (see "Print files"). Continue with the panel's main
|
||||||
return to **Arte recebida** or **Arte tratada**. Finalizado is terminal locally.
|
button through **Fila de impressão → Imprimindo → Finalizado**. **Pedir
|
||||||
8. Inspect **Histórico** and **Eventos locais de integração**. Worker receipts
|
correção** asks for the reason the customer will see; from **Correção** the
|
||||||
should say recorded locally. Download links expire after five minutes;
|
order returns to **Arte recebida** or **Arte conferida**. A move made by
|
||||||
request another link from Kanban when needed.
|
mistake is undone with **Voltar para …**: one stage back, with an internal
|
||||||
|
reason recorded in the history. The customer is not notified, approved
|
||||||
|
finals stay, and "produção iniciada"/"pedido pronto" are sent only once per
|
||||||
|
order even if the stage is entered again. Dragging a card only goes forward;
|
||||||
|
the columns it can be dropped on are highlighted.
|
||||||
|
8. The panel's **Histórico** lists every move. The **Pagamentos** tab lists
|
||||||
|
payments that need a person; **Integrações** shows the Tiny connection and
|
||||||
|
the send log; with the fake adapters every send reads "Registrado
|
||||||
|
(simulado)". Download links expire after five minutes; click again for a new
|
||||||
|
one. The previous Kanban is kept in git tag `ui-v1`.
|
||||||
|
|
||||||
The manual quote step is necessary to enforce the backend trust boundary while
|
The manual quote step is necessary to enforce the backend trust boundary while
|
||||||
automatic pre-flight is deferred. Browser measurements and grade are proposals.
|
automatic pre-flight is deferred. Browser measurements and grade are proposals.
|
||||||
@@ -99,7 +109,7 @@ final files are separately labeled. Never print the local text fixture.
|
|||||||
## Customer accounts, corrections, and cart recovery
|
## Customer accounts, corrections, and cart recovery
|
||||||
|
|
||||||
Open **Minha conta** on the Site, or `/portal.html`. Create a local account with
|
Open **Minha conta** on the Site, or `/portal.html`. Create a local account with
|
||||||
a test CNPJ, phone, email and password of at least 12 characters. Passwords use
|
a test CNPJ, phone, email and password of at least 8 characters. Passwords use
|
||||||
the current stronger scrypt format; legacy local hashes are verified and upgraded
|
the current stronger scrypt format; legacy local hashes are verified and upgraded
|
||||||
on successful login. Sessions are stored in PostgreSQL, expire after
|
on successful login. Sessions are stored in PostgreSQL, expire after
|
||||||
seven days, and are revoked on logout. Login/registration attempts are limited.
|
seven days, and are revoked on logout. Login/registration attempts are limited.
|
||||||
@@ -157,6 +167,14 @@ The workflow test also checks guest-to-account migration, cross-session login,
|
|||||||
revoked sessions, ownership isolation, correction submissions, final revision
|
revoked sessions, ownership isolation, correction submissions, final revision
|
||||||
invalidation, secure downloads, and mandatory final-file approval before queueing.
|
invalidation, secure downloads, and mandatory final-file approval before queueing.
|
||||||
|
|
||||||
|
The Kanban's artwork pictures, quote filters and order/quote search have their
|
||||||
|
own check, run inside the API container because it writes fixtures to the
|
||||||
|
database (and removes them):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose -f compose.local.yaml exec -T -e SITE_BASE_URL=http://site -e SITE_HOST_HEADER=localhost api python -m tests.kanban_test
|
||||||
|
```
|
||||||
|
|
||||||
Security and malware regressions are separate so an authorized harmless EICAR
|
Security and malware regressions are separate so an authorized harmless EICAR
|
||||||
test is unmistakable:
|
test is unmistakable:
|
||||||
|
|
||||||
@@ -291,6 +309,15 @@ TINY_PRODUCT_TEXTIL_FOLHA=... # Tiny product id for each Site product
|
|||||||
TINY_PRODUCT_TEXTIL_AVULSA=...
|
TINY_PRODUCT_TEXTIL_AVULSA=...
|
||||||
TINY_PRODUCT_UV_FOLHA=...
|
TINY_PRODUCT_UV_FOLHA=...
|
||||||
TINY_PRODUCT_UV_AVULSA=...
|
TINY_PRODUCT_UV_AVULSA=...
|
||||||
|
TINY_SKU_TEXTIL_FOLHA=DTFIMP.TX # optional, instead of the product id: sell by the client's
|
||||||
|
# SKUs (<prefix>.100CM per metre + <prefix>.0010CM … .0090CM)
|
||||||
|
TINY_SKU_TEXTIL_AVULSA= # same, for the other modes, once their SKUs are confirmed
|
||||||
|
TINY_SKU_UV_FOLHA=
|
||||||
|
TINY_SKU_UV_AVULSA=
|
||||||
|
TINY_SKU10_UV_FOLHA=DTFIMP.UV.010CM # or one SKU per 10 cm: 2,30 m = 23 of it (the client's UV)
|
||||||
|
TINY_SKU10_UV_AVULSA=DTFIMP.UV.010CM
|
||||||
|
TINY_SKU_METRO_UV_FOLHA=DTFIMP.UV.1MT # with a 10 cm SKU: whole metres first (2,30 m = 2 × 1MT + 3 × 010CM)
|
||||||
|
TINY_SKU_METRO_UV_AVULSA=DTFIMP.UV.1MT
|
||||||
```
|
```
|
||||||
|
|
||||||
With the client ID and secret set, the Kanban header shows **Conectar Tiny**.
|
With the client ID and secret set, the Kanban header shows **Conectar Tiny**.
|
||||||
@@ -318,8 +345,14 @@ PAYMENT_CSP_SOURCES=https://sdk.mercadopago.com https://*.mercadopago.com https:
|
|||||||
```
|
```
|
||||||
|
|
||||||
`PAYMENT_CSP_SOURCES` is empty by default, which keeps the Site at
|
`PAYMENT_CSP_SOURCES` is empty by default, which keeps the Site at
|
||||||
`script-src 'self'`. Once a payment for a quote is approved, or a card payment
|
`script-src 'self'`. The payment page offers credit card (the default), debit
|
||||||
is in review, the API refuses any further attempt for that quote. The order is created only by the signed
|
card and PIX. Card payments ask for 3-D Secure when the issuer requires it,
|
||||||
|
which debit cards usually do: the bank's confirmation page opens in a frame on
|
||||||
|
the issuer's own domain, so it needs `PAYMENT_CHALLENGE_SOURCES=https:` (frames
|
||||||
|
and form posts only, never scripts; empty by default). Once a payment for a
|
||||||
|
quote is approved, or a card payment is in review, the API refuses any further
|
||||||
|
attempt for that quote; a card left waiting for the bank's confirmation stops
|
||||||
|
blocking after ten minutes. The order is created only by the signed
|
||||||
notification, after the payment is fetched from the Mercado Pago API and its
|
notification, after the payment is fetched from the Mercado Pago API and its
|
||||||
BRL amount matches the approved total. Mercado Pago must be able to reach the
|
BRL amount matches the approved total. Mercado Pago must be able to reach the
|
||||||
webhook, so a local run needs a public HTTPS tunnel to the Site port. A paid
|
webhook, so a local run needs a public HTTPS tunnel to the Site port. A paid
|
||||||
|
|||||||
@@ -93,6 +93,24 @@ as `dtf_prod_database_url_v1`, then place only those names in the corresponding
|
|||||||
Credential values must never be entered into Git, `portainer.env`, or Gitea
|
Credential values must never be entered into Git, `portainer.env`, or Gitea
|
||||||
workflow variables.
|
workflow variables.
|
||||||
|
|
||||||
|
**R2 CORS.** The Site uploads artwork straight from the browser to the bucket
|
||||||
|
with presigned `PUT` requests, so the bucket must allow the Site's origin.
|
||||||
|
Without it the preflight is refused (403) and the Site shows "NetworkError
|
||||||
|
when attempting to fetch resource" at checkout (found 2026-09-28). In the
|
||||||
|
Cloudflare dashboard, R2 → the bucket → Settings → CORS policy:
|
||||||
|
|
||||||
|
```json
|
||||||
|
[
|
||||||
|
{
|
||||||
|
"AllowedOrigins": ["https://<SITE_DOMAIN>", "https://<KANBAN_DOMAIN>"],
|
||||||
|
"AllowedMethods": ["PUT", "GET", "HEAD"],
|
||||||
|
"AllowedHeaders": ["content-type"],
|
||||||
|
"ExposeHeaders": ["ETag"],
|
||||||
|
"MaxAgeSeconds": 3600
|
||||||
|
}
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
## 3. Create the stack once
|
## 3. Create the stack once
|
||||||
|
|
||||||
In Portainer select **Stacks → Add stack → Git repository**:
|
In Portainer select **Stacks → Add stack → Git repository**:
|
||||||
@@ -157,6 +175,52 @@ 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`.
|
After recovery and a corrected release, return `IMAGE_TAG` to `latest`.
|
||||||
|
|
||||||
|
## 6. Before opening to customers
|
||||||
|
|
||||||
|
Once, right before launch, clear the test orders from the worker's console
|
||||||
|
(Containers > worker > Console):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python -m ops.launch_reset # only counts
|
||||||
|
python -m ops.launch_reset --confirmar APAGAR # removes orders, quotes and payments
|
||||||
|
```
|
||||||
|
|
||||||
|
It refuses if any payment was made with real money. Order numbers restart at
|
||||||
|
#1 only with the database administrator: the script prints the `psql` line to
|
||||||
|
run in the `db` container's console. Add `--contas` to remove the test
|
||||||
|
customer accounts too.
|
||||||
|
|
||||||
|
## 7. E-mail and prices set in the stack
|
||||||
|
|
||||||
|
E-mail stays off (`MAIL_ADAPTER=off`) until the client's SMTP account exists.
|
||||||
|
Then set, in the stack's environment, `MAIL_ADAPTER=smtp`, `MAIL_FROM` (for
|
||||||
|
example `DTF Dropstar <nao-responda@SITE_DOMAIN>`), `SMTP_HOST`, `SMTP_PORT`,
|
||||||
|
`SMTP_SECURITY` (`starttls` on 587, `ssl` on 465), `SMTP_USER` and
|
||||||
|
`SMTP_PASSWORD`, and redeploy; the API and worker refuse to start if a required
|
||||||
|
one is missing. Check it with **Integrações → E-mail → Enviar teste** on the
|
||||||
|
Kanban, then switch on "Receber alertas por e-mail" for whoever wants alerts in
|
||||||
|
Usuários. Use a sending domain with SPF and DKIM, or the messages land in spam.
|
||||||
|
|
||||||
|
`MANUAL_FILE_EXTRA_CENTS` is the per-metre charge on finished sheets someone
|
||||||
|
opens by hand (CDR, AI, PSD, TIFF); 500 is R$ 5,00 a metro. Change it only on
|
||||||
|
the client's instruction; the Site shows the new price after the redeploy.
|
||||||
|
|
||||||
|
## 8. Correios
|
||||||
|
|
||||||
|
PAC and SEDEX appear in the cart once `CORREIOS_CODIGO_ACESSO` (the CWS access
|
||||||
|
code, a secret) is set in the stack and the stack redeployed. The user, posting
|
||||||
|
card and contract are Dropstar's and already the stack's defaults. Then, from
|
||||||
|
the worker's console:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python -m app.correios_probe
|
||||||
|
```
|
||||||
|
|
||||||
|
It shows the token's contract and DR and prices PAC and SEDEX to a few CEPs.
|
||||||
|
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
|
||||||
|
package weights must be set (they already are for Jadlog).
|
||||||
|
|
||||||
## 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
|
||||||
|
|||||||
254
docs/ROADMAP.md
@@ -7,16 +7,24 @@
|
|||||||
> Update the **Current step** line and the item status every time something moves.
|
> Update the **Current step** line and the item status every time something moves.
|
||||||
> Add new findings at the bottom of the relevant block rather than rewriting history.
|
> Add new findings at the bottom of the relevant block rather than rewriting history.
|
||||||
|
|
||||||
**Current step (2026-09-24, Week 2):** Client inputs for Mercado Pago and
|
**Current step (2026-09-25, last day of Week 2):** Still waiting on the client
|
||||||
freight were requested on 2026-09-24; Tiny access is already with the client.
|
for Mercado Pago credentials and webhook access (1.1) and freight data (1.2).
|
||||||
Built without them: server-side print-file generation (1.4), the delivery
|
Tiny is connected in production and reads orders, but the connected user
|
||||||
address (3.8), the Kanban's payment-issue and print-file views (1.5), and
|
cannot read contacts (403) and the client's catalogue has no per-metre UV
|
||||||
Mercado Pago and Tiny adapters written from the public API documentation and
|
product; both wait on the client (1.3). Built and deployed without them: server-side print-file
|
||||||
tested against fake transports (1.1, 1.3). None of the provider work is a
|
generation (1.4), the delivery address (3.8), the Kanban's payment-issue and
|
||||||
verified integration. The complete CI integration sequence passed locally on
|
print-file views and its redesign (1.5), the Site redesign (5.17), and Mercado
|
||||||
2026-09-24 (all API suites including the new `print_file_test`, adapter and
|
Pago and Tiny adapters written from the public API documentation and tested
|
||||||
generator unit suites, retention, runtime security, and both browser suites),
|
against fake transports. None of the provider work is a verified integration.
|
||||||
run with Docker Engine in WSL against a fresh build; pending a Gitea runner run.
|
Every change passed the full integration sequence locally (Docker Engine in
|
||||||
|
WSL) and on the Gitea runner, which publishes images on green pushes to `main`;
|
||||||
|
the user verified each release in production after redeploying in Portainer.
|
||||||
|
Operator and Site guides are in `docs/` (see Reporting).
|
||||||
|
**Left for today:** the Week 2 client report. Waiting on the client: the
|
||||||
|
Contatos permission and the product decision, then product ids and one
|
||||||
|
supervised real order (1.3); Mercado Pago credentials for the sandbox PIX and
|
||||||
|
card payments (1.1); freight data (1.2, the one Week 2 item that slips, on
|
||||||
|
client inputs).
|
||||||
|
|
||||||
**Previous step (2026-09-23):** Payment safety fixes 2.13 and 2.14 and
|
**Previous step (2026-09-23):** Payment safety fixes 2.13 and 2.14 and
|
||||||
the local order-correctness work in 3.6/3.9 have passed integration checks.
|
the local order-correctness work in 3.6/3.9 have passed integration checks.
|
||||||
@@ -239,9 +247,53 @@ From the report already sent. These are dated promises, not backlog.
|
|||||||
quote cannot be charged twice. The Site CSP gains the Mercado Pago origins
|
quote cannot be charged twice. The Site CSP gains the Mercado Pago origins
|
||||||
only through `PAYMENT_CSP_SOURCES`, empty by default. Not yet rendered
|
only through `PAYMENT_CSP_SOURCES`, empty by default. Not yet rendered
|
||||||
against a real public key; sandbox run and refund policy remain.
|
against a real public key; sandbox run and refund policy remain.
|
||||||
|
**Account setup (2026-09-28):** the client's application is Checkout
|
||||||
|
Transparente on the Payments API, webhook event "Pagamentos (legacy)" only,
|
||||||
|
URL `https://dtf.agenciacompor.com.br/api/payments/webhook`. The production
|
||||||
|
compose now takes `PAYMENT_ADAPTER` and `MP_*` from Portainer (it hard-coded
|
||||||
|
the fake adapter), so the sandbox runs on production with test credentials;
|
||||||
|
the Site has no real customers yet. A verified notification whose payment
|
||||||
|
does not exist (the panel's "Simular notificação") is acknowledged instead
|
||||||
|
of answering 500, which would have made Mercado Pago retry it.
|
||||||
- `[ ]` 1.2 — Real freight quotation. **Blocked on client inputs** (see
|
- `[ ]` 1.2 — Real freight quotation. **Blocked on client inputs** (see
|
||||||
`PRODUCTION_INPUTS.md`): source platform, credentials, origin CEP, services,
|
`PRODUCTION_INPUTS.md`): source platform, credentials, origin CEP, services,
|
||||||
packaging weight/dimensions per length, subsidy policy.
|
packaging weight/dimensions per length, subsidy policy.
|
||||||
|
**Received (2026-09-25):** Jadlog, API access (user/CNPJ, client code,
|
||||||
|
token, account), origin CEP 14402-310, service .PACKAGE (modalidade 3),
|
||||||
|
home delivery, billed by contract. Still missing: packaging weight and
|
||||||
|
dimensions per length and how freight is charged to the customer (asked
|
||||||
|
2026-09-28). `app/jadlog.py` prices one package from the manual (v2.3);
|
||||||
|
`python -m app.jadlog_probe` prices test weights to six regions, read-only,
|
||||||
|
to confirm token, account and contract on the client's account. Not yet run.
|
||||||
|
**Adapter (2026-09-29):** `FREIGHT_ADAPTER=jadlog` prices "Receber em casa"
|
||||||
|
with Jadlog from the order's billed metres (`JADLOG_PESO_BASE_KG` plus
|
||||||
|
`JADLOG_PESO_POR_METRO_KG` per metre) and value, adds
|
||||||
|
`FREIGHT_PRODUCTION_DAYS` to Jadlog's time, re-quotes the cart when it
|
||||||
|
changes, and quotes again at approval from the priced items. It refuses to
|
||||||
|
start without the credentials and the weights, which have no default. The
|
||||||
|
production stack now takes the Jadlog settings, so the probe runs from the
|
||||||
|
worker's console. Cubed weight is not computed: the client's box sizes will
|
||||||
|
tell whether it is needed.
|
||||||
|
**Packaging received (2026-10-01):** one box, 56 × 14 × 14 cm, 0.30 kg; film
|
||||||
|
1.50 kg per 20 m (0.075 kg/m); shipped with Jadlog's own insurance, which is
|
||||||
|
what `tpseguro: "N"` (normal) already quotes on the order's value. The box is
|
||||||
|
large for its weight, so the cubed weight matters: `JADLOG_CAIXA_CM` and
|
||||||
|
`JADLOG_CUBAGEM_KG_M3` make the quote send the larger of the real and the
|
||||||
|
cubed weight. The contract's factor is still unknown; until it is set the
|
||||||
|
Kanban's Frete card says the quote uses the real weight only.
|
||||||
|
**Corrected (2026-10-02):** the box is 63 × 15.5 × 15.5 cm (0.30 kg) and holds
|
||||||
|
about 60 m; UV ships in the same box at the same weight.
|
||||||
|
`JADLOG_METROS_POR_CAIXA` quotes a longer order as several boxes. Jadlog's
|
||||||
|
public .PACKAGE factor is 300 kg/m³ between states (167 within SP): 300 is
|
||||||
|
set, so in-state orders are quoted a little high, never low.
|
||||||
|
**Checked against Jadlog (2026-10-02):** `app.jadlog_probe` to Ribeirão
|
||||||
|
Preto/SP, R$ 34,27 declared: 0.47 kg R$ 13,77 · 1.68 kg R$ 17,65 · 2.52 kg
|
||||||
|
R$ 21,10 · 4.54 kg R$ 27,93. The old Olist site's R$ 17,65 is the 20 × 10 ×
|
||||||
|
28 cm box at 300 kg/m³ (1.68 kg); the client confirmed that Olist listing is
|
||||||
|
wrong and every order ships in the 63 × 15.5 × 15.5 cm box, so the new site's
|
||||||
|
4.54 kg is right. The declared value raises the price by about 0.65–0.75% of
|
||||||
|
it (R$ 500: R$ 30,93; R$ 5000: R$ 64,68): Jadlog's insurance, already in the
|
||||||
|
quote.
|
||||||
- `[~]` 1.3 — Idempotent Tiny/Olist order creation with order-number traceability.
|
- `[~]` 1.3 — Idempotent Tiny/Olist order creation with order-number traceability.
|
||||||
Confirm endpoints, tag behaviour and rate limits first.
|
Confirm endpoints, tag behaviour and rate limits first.
|
||||||
**Groundwork (2026-09-24), API v3 by decision:** OAuth2 against Tiny's
|
**Groundwork (2026-09-24), API v3 by decision:** OAuth2 against Tiny's
|
||||||
@@ -261,6 +313,85 @@ From the report already sent. These are dated promises, not backlog.
|
|||||||
real orders. Still to confirm on the client's account: plan (Construa+),
|
real orders. Still to confirm on the client's account: plan (Construa+),
|
||||||
product ids, token lifetimes, whether pickup needs a transportador, and
|
product ids, token lifetimes, whether pickup needs a transportador, and
|
||||||
rate limits.
|
rate limits.
|
||||||
|
**Supervised run (2026-09-25):** the payload and query parameters were
|
||||||
|
checked against Tiny's published v3 OpenAPI spec (`GET /pedidos` accepts
|
||||||
|
`cpfCnpj` and `dataInicial`; `GET /pedidos/{id}` returns
|
||||||
|
`numeroOrdemCompra`). "Testar conexão" on the Kanban now also reads the four
|
||||||
|
configured products and requires each to be active. `python -m
|
||||||
|
app.tiny_probe` runs from the worker console: `produtos` and `conferir` are
|
||||||
|
read-only; `pedido` shows the test order and creates it only with
|
||||||
|
`--confirmar`, through the worker's own `deliver`, then proves the duplicate
|
||||||
|
guard by search first and only then by a second delivery. Not yet run
|
||||||
|
against the client's account.
|
||||||
|
**Staying connected (2026-09-25):** Tiny documents a 4-hour access token and
|
||||||
|
a 1-day refresh token; the worker renews about every 4 hours. The connection
|
||||||
|
now asks for `offline_access` (listed by Tiny's Keycloak; if refused for this
|
||||||
|
application the callback retries once without it). Renewal failures are
|
||||||
|
stored: a refused refresh token marks the connection lost and is not retried,
|
||||||
|
a transient failure shows as a warning until the next success, and a
|
||||||
|
session grant with under 12 hours left is flagged. Previously a refused
|
||||||
|
refresh still showed "Tiny conectado". Whether Tiny grants offline access,
|
||||||
|
and whether a session grant has an undocumented maximum, is only known on
|
||||||
|
the client's account. There is no alert channel yet (no e-mail; WhatsApp
|
||||||
|
is fake): problems show on the Kanban only.
|
||||||
|
**Client account (2026-09-25):** connected in production with the
|
||||||
|
developer user the client provided. "Testar conexão": `pedidos` ok,
|
||||||
|
`contatos` 403, unchanged after reconnecting. The application's permissions
|
||||||
|
are correct (Contatos, Pedidos: read and include/edit; Produtos: read);
|
||||||
|
Olist documents that v3 calls also depend on the logged-in user's module
|
||||||
|
permissions, and that user's Cadastros menu shows only Produtos. Orders
|
||||||
|
need Contatos (search by CNPJ, create when new; delete never). **Client
|
||||||
|
to decide:** grant that user Clientes e Fornecedores, or reconnect with a
|
||||||
|
user that has it (a dedicated integration user is recommended).
|
||||||
|
**Products (2026-09-25),** from the client's product export: none of the
|
||||||
|
36 "DTF" products matches the four Site products. `951438842` "IMPRESSÃO
|
||||||
|
DTF PERSONALIZADO 57X100 (1 METRO)" (MT, R$ 19,90, active) fits Têxtil;
|
||||||
|
there is no per-metre UV product (the UV one is 27 cm, per 10 cm), and no
|
||||||
|
separate "artes avulsas" product. **Client to decide:** create four per-metre
|
||||||
|
products (recommended, copying `951438842`), or share `951438842` between
|
||||||
|
the two Têxtil modes; UV needs a product either way. The item note already
|
||||||
|
carries the Site mode and grade. No product ids are set in production yet;
|
||||||
|
both questions go to the client with the Mercado Pago credentials request.
|
||||||
|
**SKUs (2026-10-05):** the client answered that the products already exist
|
||||||
|
and an order is a sum of SKUs (1,30 m = `DTFIMP.TX.100CM` + `DTFIMP.TX.0030CM`);
|
||||||
|
the contact permission is no longer an issue (the user, 2026-09-28).
|
||||||
|
`TINY_SKU_<MODE>` (e.g. `TINY_SKU_TEXTIL_FOLHA=DTFIMP.TX`) sells a mode as
|
||||||
|
N × `<prefix>.100CM` plus one `<prefix>.00X0CM`, at the price the customer
|
||||||
|
paid (the client agreed), the last line taking what is left of the item's
|
||||||
|
total so the order adds up to the cent. Codes are looked up by `codigo`
|
||||||
|
(exact match on `sku`, active only) and remembered; "Testar conexão" and
|
||||||
|
`tiny_probe conferir` check all ten. Assumed, to confirm with the client:
|
||||||
|
above 1 m it is always N × "1 metro", not the 2–10 m SKUs. UV (only
|
||||||
|
`DTFIMP.UV.010CM` seen) and artes avulsas stay on a product id per metre
|
||||||
|
until their SKUs are confirmed. Fake transport only; whether v3's `/produtos`
|
||||||
|
filters by `codigo` is checked by `conferir` on the account.
|
||||||
|
**UV (2026-10-05):** the client sells UV only as `DTFIMP.UV.010CM`, per 10 cm.
|
||||||
|
`TINY_SKU10_<MODE>` names such a SKU: 2,30 m goes as 23 of it, at the price
|
||||||
|
paid (a rest that does not divide gets a line of its own).
|
||||||
|
**Customer notices through Tiny (2026-09-25, Week 3 head start):** the client
|
||||||
|
already sends WhatsApp notices from Tiny's order situação (Tiny webhook ->
|
||||||
|
the `api-tiny-n8n` middleware, which reads the order through API v2 -> n8n
|
||||||
|
-> WhatsApp templates): Aprovado, Pronto para envio with forma de envio `X`
|
||||||
|
(v2 "Customizada", their pickup), Enviado, Entregue. So the system's own
|
||||||
|
WhatsApp sender stays off and Tiny drives the notices. With
|
||||||
|
`TINY_STATUS_UPDATES=true` a paid order is created "Aberta" and set to
|
||||||
|
"Aprovada" (a retry finishes a half-done approval; an order already moved on
|
||||||
|
is left alone), and moving a pickup order to Finalizado sets "Pronto para
|
||||||
|
envio" by the Tiny id from the sale's receipt, searching only when it is
|
||||||
|
missing and retrying while the sale has not reached Tiny. Pickup orders
|
||||||
|
carry `TINY_FORMA_ENVIO_RETIRADA` (`tiny_probe formas-envio` lists the ids;
|
||||||
|
"Testar conexão" now checks it). Delivery orders get "Enviada" with 1.2.
|
||||||
|
Off by default: while n8n's `isDTFIMP` branch exists, "Aprovado" on a
|
||||||
|
`DTFIMP` product sends the designer message, and the Site's Têxtil product
|
||||||
|
code starts with `DTFIMP`. **Go-live together:** `TINY_ADAPTER=tiny`,
|
||||||
|
`TINY_STATUS_UPDATES=true`, n8n's `isDTFIMP`/"DTF Aprovado - Designer"
|
||||||
|
removed with "Mapear Whatsapp do Vendedor" connected to `If6`, and the
|
||||||
|
middleware's `numero_ecommerce` falling back to the purchase order so the
|
||||||
|
message shows `DTF-<n>`. **Unverified on the account:** that an API status
|
||||||
|
change fires Tiny's webhook, that Tiny accepts Aprovada -> Pronto para envio
|
||||||
|
without Faturada, and the v2 field name for the purchase order. Correção
|
||||||
|
necessária and Produção iniciada have no Tiny situação; client to decide
|
||||||
|
whether they need messages.
|
||||||
- `[~]` 1.4 — Final print-file generation (see 3.2 and 3.6: production instructions
|
- `[~]` 1.4 — Final print-file generation (see 3.2 and 3.6: production instructions
|
||||||
must survive checkout before an output engine can reproduce the approved job).
|
must survive checkout before an output engine can reproduce the approved job).
|
||||||
**Built (2026-09-24):** each paid item gets a PDF the width of the film and
|
**Built (2026-09-24):** each paid item gets a PDF the width of the film and
|
||||||
@@ -287,6 +418,17 @@ download, approve as final, queue; hand-preparation routing and retry).
|
|||||||
print-file status per item, and a panel lists payments that need a person
|
print-file status per item, and a panel lists payments that need a person
|
||||||
(money without an order, refunds after an order) until resolved. Confirm
|
(money without an order, refunds after an order) until resolved. Confirm
|
||||||
with the operation that these are the main states before closing.
|
with the operation that these are the main states before closing.
|
||||||
|
**2026-09-24:** a mistaken move can be undone one stage back (`BACK` in
|
||||||
|
`app/runtime.py`) with an internal reason, flagged in the history
|
||||||
|
(`movements.back`), without notifying the customer; "production started" and
|
||||||
|
"ready" are enqueued once per order. Previously the only way back was
|
||||||
|
Correção, which messages the customer and invalidates approved finals.
|
||||||
|
**Redesign (2026-09-24):** tabs for Produção, Cotações, Pagamentos and
|
||||||
|
Integrações; an order panel with stages, items, print files, final files and
|
||||||
|
history; numbered pagination (20 per page) on quotes, payment issues and the
|
||||||
|
integration log, which also has filters; messages dismiss themselves. The
|
||||||
|
operator guide (`docs/guia-operador-kanban.pdf`) documents the flow for the
|
||||||
|
operation to confirm.
|
||||||
- `[x]` 1.6 — **Block 0.2 + 0.3** were completed and verified on 2026-09-18.
|
- `[x]` 1.6 — **Block 0.2 + 0.3** were completed and verified on 2026-09-18.
|
||||||
|
|
||||||
`[!]` The production compose currently blocks `dev_paid` (`ENVIRONMENT != 'local'`)
|
`[!]` The production compose currently blocks `dev_paid` (`ENVIRONMENT != 'local'`)
|
||||||
@@ -482,7 +624,19 @@ The production topology has not been verified by the repository review.
|
|||||||
|
|
||||||
## Block 3 · Architecture — needs a decision before code
|
## Block 3 · Architecture — needs a decision before code
|
||||||
|
|
||||||
### `[?]` 3.1 — Manual quote approval contradicts the 24h business case `(F16)`
|
### `[~]` 3.1 — Manual quote approval contradicts the 24h business case `(F16)`
|
||||||
|
|
||||||
|
**Decided 2026-09-28 (the user: "we are an e-commerce"):** a cart the Site
|
||||||
|
priced is approved when the quote is created and can be paid at once
|
||||||
|
(`app/quote_review.py`, the same pricing the operator's approval uses). A
|
||||||
|
person reviews only orders above `QUOTE_AUTO_MAX_METRES` (50 m) and items
|
||||||
|
that claim a grade the Site could not have computed (unanalysed art with a
|
||||||
|
discount). The Kanban lists automatic approvals and the reason for each
|
||||||
|
manual one. **Still open:** the grade and layout are the browser's (3.2,
|
||||||
|
3.9), so a customer who edits the page can claim a better grade, up to the
|
||||||
|
top tier's discount; the server must compute the grade before this closes.
|
||||||
|
|
||||||
|
Previously:
|
||||||
|
|
||||||
Payment requires `quotes.approved`, set only by an authenticated operator. The
|
Payment requires `quotes.approved`, set only by an authenticated operator. The
|
||||||
meeting's premise was that the 17h30 order waiting until 5am is what costs the
|
meeting's premise was that the 17h30 order waiting until 5am is what costs the
|
||||||
@@ -509,7 +663,14 @@ the site already did.
|
|||||||
generator, with the browser as preview only. This is the single largest gap between
|
generator, with the browser as preview only. This is the single largest gap between
|
||||||
what was promised in the meeting and what exists.
|
what was promised in the meeting and what exists.
|
||||||
|
|
||||||
### `[?]` 3.3 — The 5 GB problem is unsolved `(F19)`
|
**2026-09-30:** the grade (the resolution discount) is no longer taken on trust.
|
||||||
|
Before an automatic approval the API recomputes it from the uploaded files by the
|
||||||
|
Site's rules (`app/grade_check.py`): image headers for PNG/JPG/WebP, the placed
|
||||||
|
images of a PDF up to 150 MB. A claim more than 2 points above the file's grade,
|
||||||
|
or a discount on a file the server cannot grade, waits for review with the reason
|
||||||
|
on the Kanban. The metres (the packing) are still the browser's.
|
||||||
|
|
||||||
|
### `[~]` 3.3 — The 5 GB problem is unsolved `(F19)`
|
||||||
|
|
||||||
Transport accepts 5 GiB; `SCAN_MAX_BYTES` / ClamAV `StreamMaxLength` release only
|
Transport accepts 5 GiB; `SCAN_MAX_BYTES` / ClamAV `StreamMaxLength` release only
|
||||||
≤ 128 MiB. As of 2026-09-23, customer selection and API reservation reject files
|
≤ 128 MiB. As of 2026-09-23, customer selection and API reservation reject files
|
||||||
@@ -520,6 +681,23 @@ This is exactly the risk Jorge raised in the meeting.
|
|||||||
**Decide:** raise the scan ceiling with a resource/timeout design, or define an
|
**Decide:** raise the scan ceiling with a resource/timeout design, or define an
|
||||||
explicit large-file path (staged scan, sampled scan, operator override with audit).
|
explicit large-file path (staged scan, sampled scan, operator override with audit).
|
||||||
|
|
||||||
|
**Built 2026-09-29 (sheets of several GB are the normal order, not the
|
||||||
|
exception):** files up to 5 GB. ClamAV scans up to 2 GB (`StreamMaxLength
|
||||||
|
2000M`); above that a file is released only when its first bytes match the
|
||||||
|
format its name claims (option A, the user's choice). The Site grades a sheet
|
||||||
|
over 150 MB from the pixel size in the PNG/JPEG/WebP header without decoding
|
||||||
|
it, and measures large PDFs through ranged reads; the worker never opens a
|
||||||
|
source over 300 MB: a single finished sheet placed whole becomes its own print
|
||||||
|
file, anything else goes to hand preparation. Uploads start as items enter the
|
||||||
|
cart and the lease renews with each part. Verified on the local stack: 386 MB
|
||||||
|
(ClamAV 78 s), 1.8 GB (ClamAV 6 min 18 s, scanner under 430 MB of memory, the
|
||||||
|
original as print file), 2.3 GB PNG released by the format check and a
|
||||||
|
disguised 2.3 GB file refused, and the header grade of a 200 MB file in 0.5 s.
|
||||||
|
**Open:** large PDFs get no automatic grade (the DPI of images inside is not
|
||||||
|
read without rendering); the scanner takes one file at a time, so several
|
||||||
|
multi-GB uploads queue; pieces, residue and background of a large sheet are
|
||||||
|
not checked automatically.
|
||||||
|
|
||||||
### `[ ]` 3.4 — Upload throughput `(F20)`
|
### `[ ]` 3.4 — Upload throughput `(F20)`
|
||||||
|
|
||||||
8 MiB parts, strictly sequential in `local/static/upload.js:21`, one presign
|
8 MiB parts, strictly sequential in `local/static/upload.js:21`, one presign
|
||||||
@@ -710,9 +888,31 @@ print-file evidence still need correction before this item can close.
|
|||||||
attempt counts against the source address and only failures count against
|
attempt counts against the source address and only failures count against
|
||||||
the account; registration still counts every attempt. The security suite's
|
the account; registration still counts every attempt. The security suite's
|
||||||
lockout check (ten failures, then 429) is unchanged and passes.
|
lockout check (ten failures, then 429) is unchanged and passes.
|
||||||
|
- `[x]` 5.17 — Site redesign (2026-09-24), Dropstar brand kept; the previous
|
||||||
|
look is tag `ui-v1`. The home, one page per product (`/arquivo-por-metro`,
|
||||||
|
`/artes-avulsas`, `/uv-arquivo-por-metro`, `/uv-artes-avulsas`) and
|
||||||
|
`/carrinho` have their own addresses but stay one document, so artwork held in
|
||||||
|
the browser survives moving between them (`web/site-pages.js`,
|
||||||
|
`web/site-steps.js`; nginx serves `index.html` for those paths). The product
|
||||||
|
page is built around a buy box (`web/site-compra.js`) that shows the item the
|
||||||
|
flow already priced (grade, price per metre, metres charged, total,
|
||||||
|
resolution acknowledgement and "Adicionar ao carrinho"); the duplicated
|
||||||
|
quality and preview panels are hidden. The cart has "Remover" per item,
|
||||||
|
"Esvaziar carrinho" and an 8-second undo. Fixed on the way, all already in
|
||||||
|
production before: the saved-cart note took a grid column and pushed the
|
||||||
|
order into a narrow strip, the panels outside `.w` ran edge to edge, and
|
||||||
|
"57 cm" wrapped on the ready-sheet option. The browser suite covers product
|
||||||
|
and cart addresses, reload on a product page, and remove/undo; the security
|
||||||
|
suite checks the new addresses carry the same CSP.
|
||||||
- `[ ]` 5.13 — Define production recovery: scheduled encrypted offsite database
|
- `[ ]` 5.13 — Define production recovery: scheduled encrypted offsite database
|
||||||
and object backups, a consistent snapshot boundary, Swarm data placement and
|
and object backups, a consistent snapshot boundary, Swarm data placement and
|
||||||
a restore rehearsal that opens every required live order file.
|
a restore rehearsal that opens every required live order file.
|
||||||
|
**2026-09-29:** database part built. The `backup` service dumps daily,
|
||||||
|
encrypts with age (the server holds only the public key) and uploads to a
|
||||||
|
bucket of its own, whose lifecycle rule expires copies and whose lock keeps
|
||||||
|
them from being deleted early. The Kanban shows the latest run, and
|
||||||
|
`tests/backup_test.py` restores a copy in CI. Setup and restore:
|
||||||
|
docs/BACKUP.md. Artwork is not copied: it is temporary and already on R2.
|
||||||
- `[ ]` 5.14 — Promote and verify one immutable release. **2026-09-24:** green
|
- `[ ]` 5.14 — Promote and verify one immutable release. **2026-09-24:** green
|
||||||
pushes to `main` now publish images and Portainer's pull-and-redeploy is the
|
pushes to `main` now publish images and Portainer's pull-and-redeploy is the
|
||||||
release gate; the source preflight is advisory unless enforced by variable,
|
release gate; the source preflight is advisory unless enforced by variable,
|
||||||
@@ -831,6 +1031,36 @@ print-file evidence still need correction before this item can close.
|
|||||||
|
|
||||||
### Reporting
|
### Reporting
|
||||||
|
|
||||||
|
- `[x]` Operator guide (`docs/guia-operador-kanban.pdf`) and Site guide
|
||||||
|
(`docs/guia-site-dtf.pdf`), 2026-09-24, with screenshots of a throwaway stack
|
||||||
|
and fictional orders. The payment step has no screenshot until Mercado Pago
|
||||||
|
is configured, and the guides name the provisional Kanban domain; regenerate
|
||||||
|
them when either changes. Early work toward Week 3's "orientação à operação".
|
||||||
|
- `[x]` Operator guide rebuilt from a committed source (2026-09-25):
|
||||||
|
`docs/guias/operador/` (HTML and the original screenshots, cropped as
|
||||||
|
before), printed by `docs/guias/imprimir.sh`. The source of the 09-24 PDF
|
||||||
|
was never committed. Corrected: stage moves do not update Tiny (only
|
||||||
|
"Aprovada" and, for pickup, "Pronto para envio", once enabled); WhatsApp
|
||||||
|
notices go through the client's Tiny -> n8n flow; the correction notice is
|
||||||
|
not automatic, the reason is in Minha conta; the Tiny card's renewal,
|
||||||
|
"Verificar" and "Testar conexão" checks. Found while writing it: the
|
||||||
|
customer's order history showed operators' internal reasons for moving an
|
||||||
|
order back; it now omits back moves and shows reasons only for corrections.
|
||||||
|
The Site guide's source is also not in the repository.
|
||||||
|
- `[x]` Operator guide rewritten for the Kanban of 2026-10-05 (11 pages): automatic
|
||||||
|
quote approval, the next-step box for the final file (one click for a correction
|
||||||
|
or the generated PDF), the queue and "Baixar", the WhatsApp correction notice,
|
||||||
|
cancel and delete, Números and auto-refresh. Screenshots from a throwaway stack
|
||||||
|
(compose project `dtfguide`) with four fictional companies; printed with
|
||||||
|
`docs/guias/imprimir.sh`.
|
||||||
|
- `[x]` Week-2 client report (`Relatorio-Semana-2-DTF.docx`), written 2026-09-25,
|
||||||
|
sent 2026-09-28. Before sending, the FlexiPRINT import was taken out of
|
||||||
|
"O que falta" (it is done this week) and the print-file paragraph no longer
|
||||||
|
names PSD, AI, CDR or multi-page PDFs as hand-preparation cases. **Reversed
|
||||||
|
2026-09-29:** those formats stay as built: no automatic check, the full rate
|
||||||
|
per metre, and the operator prepares them by hand. Automatic generation is
|
||||||
|
not planned; the sent report omits them from its list of exceptions. Freight is reported as Jadlog data received,
|
||||||
|
waiting on packaging weight and dimensions and the charging policy.
|
||||||
- `[x]` Week-1 client report (`Relatorio-Semana-1-DTF.docx`), corrected 2026-09-18 to
|
- `[x]` Week-1 client report (`Relatorio-Semana-1-DTF.docx`), corrected 2026-09-18 to
|
||||||
remove the inaccurate "Arquivo por metro permanece separado, com seleção explícita"
|
remove the inaccurate "Arquivo por metro permanece separado, com seleção explícita"
|
||||||
claim and the internal commit reference.
|
claim and the internal commit reference.
|
||||||
|
|||||||
BIN
docs/guia-operador-kanban.pdf
Normal file
BIN
docs/guia-site-dtf.pdf
Normal file
10
docs/guias/imprimir.sh
Executable file
@@ -0,0 +1,10 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# Print the guide sources in docs/guias/ to the PDFs in docs/ with headless
|
||||||
|
# Chrome (A4, no browser header or footer). Needs Chrome and the DejaVu fonts.
|
||||||
|
set -eu
|
||||||
|
cd "$(dirname "$0")"
|
||||||
|
CHROME=${CHROME:-$(command -v google-chrome-stable || command -v google-chrome || command -v chromium)}
|
||||||
|
"$CHROME" --headless --disable-gpu --no-pdf-header-footer --run-all-compositor-stages-before-draw \
|
||||||
|
--print-to-pdf="$PWD/../guia-operador-kanban.pdf" "file://$PWD/operador/guia-operador-kanban.html"
|
||||||
|
"$CHROME" --headless --disable-gpu --no-pdf-header-footer --run-all-compositor-stages-before-draw \
|
||||||
|
--print-to-pdf="$PWD/../guia-site-dtf.pdf" "file://$PWD/site/guia-site-dtf.html"
|
||||||
466
docs/guias/operador/guia-operador-kanban.html
Normal file
@@ -0,0 +1,466 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<!-- Source of docs/guia-operador-kanban.pdf. Print with docs/guias/imprimir.sh.
|
||||||
|
Screenshots in img/ come from a throwaway stack with fictional orders. -->
|
||||||
|
<html lang="pt-BR">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Kanban DTF · Guia do operador</title>
|
||||||
|
<style>
|
||||||
|
@page { size: A4; margin: 0; }
|
||||||
|
:root {
|
||||||
|
--navy: #0B1320; --orange: #F08A24; --ink: #1B2331; --muted: #6B7280;
|
||||||
|
--line: #D6DCE4; --head: #EAF0F8; --note: #FFF5E8; --note-line: #F4C58E;
|
||||||
|
}
|
||||||
|
* { box-sizing: border-box; }
|
||||||
|
html, body { margin: 0; padding: 0; }
|
||||||
|
body { font-family: 'DejaVu Sans', sans-serif; color: var(--ink); font-size: 9.7pt; line-height: 1.55;
|
||||||
|
-webkit-print-color-adjust: exact; print-color-adjust: exact; }
|
||||||
|
.page { width: 210mm; height: 297mm; position: relative; padding: 26mm 18mm 20mm; overflow: hidden;
|
||||||
|
page-break-after: always; break-after: page; }
|
||||||
|
.page:last-child { page-break-after: auto; break-after: auto; }
|
||||||
|
.running { position: absolute; top: 9mm; left: 18mm; right: 18mm; font-size: 7.4pt; color: var(--muted);
|
||||||
|
border-bottom: 0.6pt solid #E3E7ED; padding-bottom: 2.4mm; }
|
||||||
|
.folio { position: absolute; bottom: 9mm; right: 18mm; font-size: 7.4pt; color: var(--muted); }
|
||||||
|
.kicker { color: var(--orange); font-weight: bold; font-size: 7.6pt; letter-spacing: 0.04em; margin: 0 0 1mm; }
|
||||||
|
h1 { font-size: 20.5pt; line-height: 1.2; margin: 0 0 2mm; color: #101826; }
|
||||||
|
h1::after { content: ""; display: block; width: 18mm; height: 1.4mm; background: var(--orange); margin-top: 3mm; }
|
||||||
|
h2 { font-size: 11.5pt; margin: 7mm 0 2.5mm; color: #101826; }
|
||||||
|
p { margin: 0 0 2.6mm; }
|
||||||
|
b { font-weight: bold; }
|
||||||
|
table { width: 100%; border-collapse: collapse; margin: 2mm 0 3mm; font-size: 8.6pt; line-height: 1.45; }
|
||||||
|
th, td { border: 0.6pt solid var(--line); padding: 2mm 2.4mm; vertical-align: top; text-align: left; }
|
||||||
|
th { background: var(--head); font-weight: bold; }
|
||||||
|
td.n { color: var(--orange); font-weight: bold; font-size: 11pt; width: 7mm; text-align: center; }
|
||||||
|
td.k { font-weight: bold; }
|
||||||
|
.note { background: var(--note); border: 0.6pt solid var(--note-line); border-radius: 2mm; padding: 3mm 3.6mm;
|
||||||
|
font-size: 8.6pt; margin: 3mm 0; }
|
||||||
|
ul { margin: 0 0 3mm; padding-left: 4.5mm; }
|
||||||
|
ul li { margin-bottom: 1.1mm; }
|
||||||
|
ul li::marker { color: var(--orange); }
|
||||||
|
ol { margin: 0 0 3mm; padding-left: 5mm; }
|
||||||
|
ol li { margin-bottom: 1.3mm; }
|
||||||
|
ol li::marker { color: var(--orange); font-weight: bold; }
|
||||||
|
.chip { display: inline-block; border: 0.6pt solid #C9D0DA; background: #F4F6F9; border-radius: 1.2mm;
|
||||||
|
padding: 0 1.6mm; font-size: 7.6pt; line-height: 1.6; white-space: nowrap; }
|
||||||
|
.shot { display: block; width: 100%; border-radius: 1.6mm; margin: 2mm 0 1mm; }
|
||||||
|
.caption { font-size: 7.2pt; color: var(--muted); margin: 0 0 3mm; }
|
||||||
|
.split { display: flex; gap: 6mm; align-items: flex-start; }
|
||||||
|
.split > div { flex: 1; }
|
||||||
|
.split > .side { flex: 0 0 79.5mm; }
|
||||||
|
.quote { font-style: normal; }
|
||||||
|
.shot.half { width: 62%; }
|
||||||
|
.shot.narrow { width: 78%; }
|
||||||
|
|
||||||
|
/* Cover */
|
||||||
|
.cover { background: var(--navy); color: #F3F5F8; padding: 0 18mm; }
|
||||||
|
.cover .block { position: absolute; left: 18mm; right: 18mm; top: 158mm; }
|
||||||
|
.cover .kicker { margin-bottom: 4mm; }
|
||||||
|
.cover .title { font-size: 27pt; font-weight: bold; line-height: 1.25; margin: 0 0 4mm; color: #fff; }
|
||||||
|
.cover .lead { font-size: 9.6pt; color: #C8CFDA; margin: 0 0 8mm; }
|
||||||
|
.cover table { font-size: 8pt; margin: 0 0 8mm; }
|
||||||
|
.cover th, .cover td { border-color: #2A3547; background: transparent; color: #E6EAF0; padding: 3mm 3.6mm; }
|
||||||
|
.cover th { color: var(--orange); }
|
||||||
|
.cover .version { font-size: 8pt; color: #A9B2C0; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
|
||||||
|
<!-- 1 · Capa -->
|
||||||
|
<section class="page cover">
|
||||||
|
<div class="block">
|
||||||
|
<p class="kicker">GUIA DE OPERAÇÃO</p>
|
||||||
|
<p class="title">Kanban DTF<br>Guia do operador</p>
|
||||||
|
<p class="lead">Como conferir, produzir e entregar os pedidos que chegam pelo Site DTF.</p>
|
||||||
|
<table>
|
||||||
|
<tr><th style="width:50%">Acesso</th><th>Quem usa</th></tr>
|
||||||
|
<tr><td>kanban.dropstardtf.com.br<br>e-mail e senha do operador</td>
|
||||||
|
<td>Equipe da sala de DTF e atendimento</td></tr>
|
||||||
|
</table>
|
||||||
|
<p class="version">Versão de 19 de outubro de 2026</p>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- 2 · Visão geral -->
|
||||||
|
<section class="page">
|
||||||
|
<div class="running">DTF Dropstar - guia do operador</div>
|
||||||
|
<p class="kicker">VISÃO GERAL</p>
|
||||||
|
<h1>O caminho de um pedido</h1>
|
||||||
|
<p>O cliente monta a folha e envia as artes pelo Site DTF, vê o preço e paga na hora. Daí em diante, tudo acontece
|
||||||
|
no Kanban: o pedido percorre as etapas de produção até ficar pronto para retirada ou envio.</p>
|
||||||
|
<table>
|
||||||
|
<tr><td class="n">1</td><td class="k" style="width:31mm">Cliente envia</td>
|
||||||
|
<td>Monta a folha no Site, vê a nota da arte e o preço por metro.</td></tr>
|
||||||
|
<tr><td class="n">2</td><td class="k">Site aprova a cotação</td>
|
||||||
|
<td>O Site confere a nota pelos próprios arquivos e aprova na hora. Só vão para a equipe os pedidos acima de
|
||||||
|
50 m ou com nota que não confere (aba <b>Cotações</b>).</td></tr>
|
||||||
|
<tr><td class="n">3</td><td class="k">Cliente paga</td>
|
||||||
|
<td>Pelo Mercado Pago, com PIX ou cartão de crédito (à vista ou em até 3 vezes), na própria página do Site.</td></tr>
|
||||||
|
<tr><td class="n">4</td><td class="k">Pedido entra na produção</td>
|
||||||
|
<td>Com o pagamento aprovado, o pedido aparece em <b>Arte recebida</b>, com o arquivo de impressão já gerado, e é
|
||||||
|
lançado no Tiny. O cliente recebe a confirmação por e-mail e por WhatsApp.</td></tr>
|
||||||
|
<tr><td class="n">5</td><td class="k">Equipe produz</td>
|
||||||
|
<td>Confere e aprova o arquivo final, baixa, importa no FlexiPRINT e move o card a cada etapa.</td></tr>
|
||||||
|
<tr><td class="n">6</td><td class="k">Pedido pronto</td>
|
||||||
|
<td>Em <b>Finalizado</b>: na retirada, o cliente é avisado; na entrega, a equipe fatura e despacha pelo Tiny, como
|
||||||
|
nos outros pedidos (página 7).</td></tr>
|
||||||
|
</table>
|
||||||
|
<h2>As seis abas</h2>
|
||||||
|
<table>
|
||||||
|
<tr><th style="width:31mm">Aba</th><th>Para que serve</th></tr>
|
||||||
|
<tr><td class="k">Produção</td><td>O quadro com os pedidos pagos, uma coluna por etapa.</td></tr>
|
||||||
|
<tr><td class="k">Cotações</td><td>Carrinhos que ainda não foram pagos: os que esperam a equipe conferir e os aprovados
|
||||||
|
esperando o pagamento. O número ao lado indica quantos faltam revisar.</td></tr>
|
||||||
|
<tr><td class="k">Pagamentos</td><td>Pagamentos que o sistema não conseguiu ligar a um pedido. Normalmente fica vazia.</td></tr>
|
||||||
|
<tr><td class="k">Números</td><td>Pedidos, metros, valores e o tempo de cada etapa no período (página 10).</td></tr>
|
||||||
|
<tr><td class="k">Integrações</td><td>A pasta automática da Fila de impressão (página 9) e a situação do Tiny, Mercado Pago,
|
||||||
|
frete, e-mail e cópia de segurança (página 12).</td></tr>
|
||||||
|
<tr><td class="k">Usuários</td><td>Quem entra no Kanban, o perfil de cada um e as máquinas (página 11).</td></tr>
|
||||||
|
</table>
|
||||||
|
<p>Cada pessoa vê as abas do seu perfil: o operador, por exemplo, vê <b>Produção</b> e, em <b>Integrações</b>, só a pasta automática.</p>
|
||||||
|
<div class="note">O quadro se atualiza sozinho, de 30 em 30 segundos. No canto superior direito, ao lado de
|
||||||
|
<b>Atualizar</b>, dá para escolher outro intervalo (de 10 segundos a 15 minutos) ou desligar. Quando chega um pedido
|
||||||
|
novo, aparece o aviso <b>Novo pedido #</b> e o título da aba mostra quantos chegaram.</div>
|
||||||
|
<div class="folio">Página 2</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- 3 · Entrar e ler o quadro -->
|
||||||
|
<section class="page">
|
||||||
|
<div class="running">DTF Dropstar - guia do operador</div>
|
||||||
|
<p class="kicker">PRODUÇÃO</p>
|
||||||
|
<h1>Entrar e ler o quadro</h1>
|
||||||
|
<div class="split">
|
||||||
|
<div>
|
||||||
|
<p>Acesse <b>kanban.dropstardtf.com.br</b> e entre com seu e-mail e senha. Cada operador tem o próprio
|
||||||
|
acesso: é o nome dele que fica registrado em cada movimento do pedido.</p>
|
||||||
|
<p>Depois de várias senhas erradas seguidas, o acesso fica bloqueado por 15 minutos.</p>
|
||||||
|
<p>Para trocar a sua senha, clique nas suas iniciais, no canto superior direito, e em <b>Minha senha</b>. Esqueceu?
|
||||||
|
Peça a um administrador uma senha nova (página 11).</p>
|
||||||
|
</div>
|
||||||
|
<div class="side"><img class="shot" src="img/login.png" alt="Tela de entrada do Kanban"></div>
|
||||||
|
</div>
|
||||||
|
<img class="shot" src="img/quadro.png" alt="Quadro de produção">
|
||||||
|
<p class="caption">Quadro de produção. Cada coluna é uma fila: o pedido pago primeiro fica em cima.</p>
|
||||||
|
<h2>O que cada card mostra</h2>
|
||||||
|
<ul>
|
||||||
|
<li>A arte, o <b>#número</b> do pedido e há quanto tempo ele mudou de etapa.</li>
|
||||||
|
<li>O nome do cliente e o e-mail; a nota da arte, o produto e os metros cobrados.</li>
|
||||||
|
<li><span class="chip">Retirada em Franca</span> ou a cidade da entrega, e a máquina que vai imprimir.</li>
|
||||||
|
<li>O que falta: <span class="chip">Falta aprovar o final</span>, <span class="chip">Correção recebida</span>,
|
||||||
|
<span class="chip">Preparar à mão</span> ou, quando está tudo certo, <span class="chip">Final aprovado</span>.
|
||||||
|
<span class="chip">Parado</span> aparece quando o pedido fica mais de 4 h na mesma etapa, e
|
||||||
|
<span class="chip">☎ Aguardando contato</span> quando a equipe precisa falar com o cliente antes de imprimir (página 8).</li>
|
||||||
|
</ul>
|
||||||
|
<p>Os filtros mostram só <b>Têxtil</b>, <b>UV</b>, <b>Entrega</b>, <b>Retirada</b>, <b>Parados</b>, <b>Aguardando contato</b>,
|
||||||
|
<b>Preparar à mão</b> ou <b>Cancelados</b>. A busca (atalho <b>/</b>) encontra pedidos e cotações pelo nome, e-mail,
|
||||||
|
CPF ou CNPJ, WhatsApp, número ou código do pedido.</p>
|
||||||
|
<div class="folio">Página 3</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- 4 · Cotações -->
|
||||||
|
<section class="page">
|
||||||
|
<div class="running">DTF Dropstar - guia do operador</div>
|
||||||
|
<p class="kicker">COTAÇÕES</p>
|
||||||
|
<h1>Cotações que esperam a equipe</h1>
|
||||||
|
<p>Quase todo carrinho é aprovado pelo próprio Site, e o cliente paga em seguida. Ficam em <b>A revisar</b> só os
|
||||||
|
pedidos acima de <b>50 m</b> e os que pedem uma nota que não confere com os arquivos. O motivo aparece na cotação.</p>
|
||||||
|
<img class="shot" src="img/cotacoes.png" alt="Aba Cotações">
|
||||||
|
<p class="caption">À esquerda, a lista com filtros e busca; à direita, a cotação selecionada.</p>
|
||||||
|
<ol>
|
||||||
|
<li>Abra a aba <b>Cotações</b> e clique na cotação em <b>A revisar</b>.</li>
|
||||||
|
<li>Confira a arte e a montagem. Se precisar, abra os arquivos em <b>Original</b> ou a lista de peças em <b>Manifesto</b>.</li>
|
||||||
|
<li>Confira <b>Metros conferidos</b> e <b>Nota conferida</b>. Os valores do cliente já vêm preenchidos; mude só se
|
||||||
|
estiverem errados. A nota define o preço do metro.</li>
|
||||||
|
<li>Marque <b>Arquivos, metragem e nota conferidos</b> e clique em <b>Aprovar cotação</b>.</li>
|
||||||
|
</ol>
|
||||||
|
<p>O cliente tem <b>24 horas</b> para pagar; depois disso a cotação vence e sai da lista. Em <b>Aprovadas, aguardando
|
||||||
|
pagamento</b>, a etiqueta mostra se o cliente já tentou pagar (por exemplo, <span class="chip">Cartão recusado</span>
|
||||||
|
ou <span class="chip">PIX gerado · expira …</span>). Uma cotação que não vai ser paga pode sair da lista em
|
||||||
|
<b>Descartar cotação</b>.</p>
|
||||||
|
<div class="folio">Página 4</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- 5 · Abrir um pedido -->
|
||||||
|
<section class="page">
|
||||||
|
<div class="running">DTF Dropstar - guia do operador</div>
|
||||||
|
<p class="kicker">PRODUÇÃO</p>
|
||||||
|
<h1>Abrir um pedido</h1>
|
||||||
|
<div class="split">
|
||||||
|
<div>
|
||||||
|
<p>Clique em qualquer card para abrir o painel do pedido. O topo sempre mostra o próximo passo, e o botão
|
||||||
|
laranja é o que faz o pedido andar.</p>
|
||||||
|
<table>
|
||||||
|
<tr><th style="width:27mm">Parte</th><th>O que tem</th></tr>
|
||||||
|
<tr><td class="k">Topo</td><td>Número, etapa, código do pedido (o que o cliente vê), valor e data do pagamento,
|
||||||
|
o próximo passo e os botões. Em <b>⋯</b> ficam ações raras, como cancelar o pedido.</td></tr>
|
||||||
|
<tr><td class="k">Cliente e Entrega</td><td>Nome, e-mail, CPF ou CNPJ e <b>Abrir conversa</b> no WhatsApp;
|
||||||
|
endereço, transportadora e valor do frete, ou <b>Retirada em Franca</b>.</td></tr>
|
||||||
|
<tr><td class="k">Máquina</td><td>A máquina que vai imprimir, escolhida pelo produto. Dá para trocar por outra.</td></tr>
|
||||||
|
<tr><td class="k">Item</td><td>A arte e a montagem no filme, folha, peças e preço do metro. <b>PDF</b> ou
|
||||||
|
<b>Original</b> baixam os arquivos; <b>Manifesto</b> lista as peças e suas posições.</td></tr>
|
||||||
|
<tr><td class="k">Arquivos finais</td><td>As versões do arquivo que vai ser impresso, com quem aprovou e quando.</td></tr>
|
||||||
|
<tr><td class="k">Histórico</td><td>Cada movimento do pedido, com hora, operador e motivo.</td></tr>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
<div class="side"><img class="shot" src="img/painel.png" alt="Painel do pedido"></div>
|
||||||
|
</div>
|
||||||
|
<div class="folio">Página 5</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- 6 · Arquivo final -->
|
||||||
|
<section class="page">
|
||||||
|
<div class="running">DTF Dropstar - guia do operador</div>
|
||||||
|
<p class="kicker">PRODUÇÃO</p>
|
||||||
|
<h1>Aprovar o arquivo final</h1>
|
||||||
|
<p>Antes de ir para a <b>Fila de impressão</b>, cada item precisa de um arquivo final aprovado. Em <b>Arte conferida</b>,
|
||||||
|
enquanto falta, o topo do pedido mostra <b>Próximo passo: aprovar o arquivo final</b>, com o arquivo que vai ser impresso.</p>
|
||||||
|
<img class="shot narrow" src="img/arquivo-final.png" alt="Próximo passo: aprovar o arquivo final">
|
||||||
|
<ol>
|
||||||
|
<li>Clique em <b>Baixar</b> e confira o arquivo.</li>
|
||||||
|
<li>Clique em <b>Aprovar arquivo final</b> e confirme. Pronto: o botão laranja vira <b>Mover para Fila de impressão</b>.</li>
|
||||||
|
</ol>
|
||||||
|
<p>Quer imprimir outro arquivo? Clique em <b>Enviar outro arquivo</b>, escolha o arquivo, escreva uma nota, marque
|
||||||
|
<b>Arquivos conferidos</b> e aprove. Quando o cliente manda uma correção, ela é o arquivo sugerido:</p>
|
||||||
|
<img class="shot narrow" src="img/correcao-recebida.png" alt="Correção do cliente pronta para aprovar">
|
||||||
|
<h2>Quando não há arquivo pronto</h2>
|
||||||
|
<table>
|
||||||
|
<tr><th style="width:40mm">No card ou no item</th><th>O que fazer</th></tr>
|
||||||
|
<tr><td><span class="chip">Gerando arquivo…</span></td><td>Aguarde alguns segundos: o quadro se atualiza sozinho.</td></tr>
|
||||||
|
<tr><td><span class="chip">Preparar à mão</span></td><td>O cliente enviou um formato que o gerador não lê (CDR, AI, PSD)
|
||||||
|
ou um arquivo muito grande para montar. O botão laranja vira <b>Enviar arquivo final</b>: baixe o <b>Original</b>,
|
||||||
|
prepare o arquivo no seu programa e envie por ali. Quando a Dropstar cobra a abertura manual, o <b>Metro</b> do item
|
||||||
|
mostra o valor (ex.: <span class="chip">R$ 24,90 (com R$ 5,00 de arquivo manual)</span>).</td></tr>
|
||||||
|
<tr><td><span class="chip">Falhou ao gerar</span></td><td>Clique em <b>Gerar de novo</b>. Se falhar de novo, prepare à mão.</td></tr>
|
||||||
|
</table>
|
||||||
|
<div class="folio">Página 6</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- 7 · Mover pelas etapas -->
|
||||||
|
<section class="page">
|
||||||
|
<div class="running">DTF Dropstar - guia do operador</div>
|
||||||
|
<p class="kicker">PRODUÇÃO</p>
|
||||||
|
<h1>Mover o pedido pelas etapas</h1>
|
||||||
|
<p>Use o botão laranja <b>Mover para…</b> no topo do painel ou arraste o card para a coluna seguinte. Dentro da
|
||||||
|
mesma coluna, arraste o card para cima ou para baixo para mudar a prioridade na fila.</p>
|
||||||
|
<table>
|
||||||
|
<tr><th style="width:27mm">Etapa</th><th>Significa</th><th style="width:30mm">No Tiny</th><th style="width:40mm">Aviso ao cliente</th></tr>
|
||||||
|
<tr><td class="k">Arte recebida</td><td>Pedido pago, arquivo gerado. Ainda não conferido.</td><td>Aprovado</td><td>E-mail e WhatsApp de pedido aprovado</td></tr>
|
||||||
|
<tr><td class="k">Arte conferida</td><td>Arquivo conferido e ajustado, se preciso.</td><td>—</td><td>—</td></tr>
|
||||||
|
<tr><td class="k">Fila de impressão</td><td>Pronto para imprimir. Exige o arquivo final aprovado.</td><td>—</td><td>—</td></tr>
|
||||||
|
<tr><td class="k">Imprimindo</td><td>Na máquina.</td><td>Preparando envio</td><td>—</td></tr>
|
||||||
|
<tr><td class="k">Finalizado</td><td>Impresso. Retirada: pronto para buscar. Entrega: a equipe fatura e despacha no Tiny.</td>
|
||||||
|
<td>Retirada: Pronto para envio</td><td>Retirada: pronto para retirar. Entrega: ao ser enviado e entregue</td></tr>
|
||||||
|
<tr><td class="k">Correção</td><td>Algo no arquivo precisa ser resolvido pelo cliente.</td><td>—</td><td>Pela equipe, no WhatsApp (página 8)</td></tr>
|
||||||
|
</table>
|
||||||
|
<div class="note">Os avisos por WhatsApp saem pelo número e pelas mensagens que a Dropstar já usa, a partir da situação
|
||||||
|
do pedido no Tiny. Cada aviso sai <b>uma vez só</b>, mesmo que o pedido volte uma etapa e avance de novo. Um pedido
|
||||||
|
cancelado no Kanban é cancelado também no Tiny, se ainda não foi faturado.</div>
|
||||||
|
<div class="split">
|
||||||
|
<div>
|
||||||
|
<h2 style="margin-top:2mm">Baixar a fila de uma vez</h2>
|
||||||
|
<p>Na coluna <b>Fila de impressão</b>, o botão <b>Baixar</b> baixa o arquivo final de todos os pedidos da fila, na
|
||||||
|
ordem da fila, com o número do pedido no nome (ex.: <span class="chip">pedido-246-item-1-…</span>). Se o navegador
|
||||||
|
perguntar, permita vários downloads. Na sala de impressão, a <b>pasta automática</b> faz isso sozinha (página 9).</p>
|
||||||
|
<h2>Moveu errado? Volte uma etapa</h2>
|
||||||
|
<p>Clique em <b>← Voltar para [etapa anterior]</b>, embaixo dos botões, escreva o motivo (ex.: “movi por engano”) e
|
||||||
|
confirme. O retorno fica no histórico; o cliente não vê esse retorno nem o motivo.</p>
|
||||||
|
</div>
|
||||||
|
<div class="side" style="flex-basis:58mm"><img class="shot" src="img/fila.png" alt="Coluna Fila de impressão com o botão Baixar"></div>
|
||||||
|
</div>
|
||||||
|
<div class="folio">Página 7</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- 8 · Correção -->
|
||||||
|
<section class="page">
|
||||||
|
<div class="running">DTF Dropstar - guia do operador</div>
|
||||||
|
<p class="kicker">PRODUÇÃO</p>
|
||||||
|
<h1>Pedir correção ao cliente</h1>
|
||||||
|
<ol>
|
||||||
|
<li>No painel do pedido, clique em <b>Pedir correção</b>.</li>
|
||||||
|
<li>Escreva o motivo de forma clara para o cliente (ex.: “A arte escudo.png está com fundo branco. Envie com fundo transparente.”).</li>
|
||||||
|
<li>Clique em <b>Enviar para correção</b>. O pedido vai para a coluna <b>Correção</b>.</li>
|
||||||
|
<li>No topo do pedido, clique em <b>Avisar no WhatsApp</b>. Abre a conversa com o cliente com a mensagem pronta: o
|
||||||
|
código do pedido, o motivo e o link para enviar o arquivo corrigido. É só enviar.</li>
|
||||||
|
</ol>
|
||||||
|
<img class="shot" src="img/correcao.png" alt="Pedido em correção com Avisar no WhatsApp">
|
||||||
|
<p class="caption">Sem WhatsApp no pedido, use <b>Copiar mensagem</b> e envie por e-mail.</p>
|
||||||
|
<p>O cliente envia o arquivo corrigido em <b>Minha conta</b>, no Site. O card mostra
|
||||||
|
<span class="chip">Correção recebida</span>: mova o pedido para <b>Arte recebida</b> ou <b>Arte conferida</b>, confira a
|
||||||
|
correção e aprove como arquivo final (página 6).</p>
|
||||||
|
<div class="note">Correção é para problemas que só o cliente resolve (resolução, fundo, arte errada). Ajustes que a equipe
|
||||||
|
faz sozinha não precisam de correção: trate o arquivo em <b>Arte conferida</b>.</div>
|
||||||
|
<h2>Precisa falar com o cliente antes de imprimir?</h2>
|
||||||
|
<div class="split">
|
||||||
|
<div><p>No painel do pedido, clique em <b>☎ Aguardando contato</b> e escreva o que precisa ser combinado. O pedido fica na
|
||||||
|
mesma etapa, com a marca no card e no filtro <b>Aguardando contato</b>. Depois de falar com o cliente, clique em
|
||||||
|
<b>Contato feito</b>.</p></div>
|
||||||
|
<div class="side"><img class="shot" src="img/contato.png" alt="Pedido aguardando contato com o cliente"></div>
|
||||||
|
</div>
|
||||||
|
<div class="folio">Página 8</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- 9 · Pasta automática -->
|
||||||
|
<section class="page">
|
||||||
|
<div class="running">DTF Dropstar - guia do operador</div>
|
||||||
|
<p class="kicker">SALA DE IMPRESSÃO</p>
|
||||||
|
<h1>Pasta automática da Fila de impressão</h1>
|
||||||
|
<p>O Kanban salva os arquivos dos pedidos numa pasta do computador: a que o FlexiPRINT lê, ou a pasta da rede do
|
||||||
|
servidor. Ninguém precisa baixar à mão. Na linha da pasta, escolha <b>quando baixar</b>:</p>
|
||||||
|
<ul>
|
||||||
|
<li><b>Baixar ao chegar</b>: o arquivo é baixado assim que o pedido chega, na subpasta <b>Recebidos</b>, e passa para a
|
||||||
|
pasta principal quando o pedido entra na <b>Fila de impressão</b>. Arquivos grandes já estão no computador na hora de imprimir.</li>
|
||||||
|
<li><b>Baixar na Fila</b>: o arquivo é baixado quando o pedido entra na <b>Fila de impressão</b>.</li>
|
||||||
|
</ul>
|
||||||
|
<h2>Ligar (uma vez, no computador da sala de impressão)</h2>
|
||||||
|
<ol>
|
||||||
|
<li>Abra o Kanban no <b>Google Chrome</b> (ou no Microsoft Edge) e entre com o seu acesso.</li>
|
||||||
|
<li>Abra <b>Integrações</b>. Na linha <b>Pasta da Fila de impressão</b>, clique em <b>Escolher pasta</b>.</li>
|
||||||
|
<li>Escolha a pasta e permita que o Kanban altere os arquivos dela.</li>
|
||||||
|
<li>Pronto: a linha mostra <span class="chip">Ligada</span>. Escolha <b>Baixar ao chegar</b> ou <b>Baixar na Fila</b>.</li>
|
||||||
|
</ol>
|
||||||
|
<img class="shot" src="img/pasta.png" alt="Pasta da Fila de impressão ligada, com os detalhes abertos">
|
||||||
|
<p class="caption">Em <b>Detalhes</b>: a pasta, quantos arquivos foram salvos, e os botões <b>Trocar pasta</b> e <b>Desligar</b>.</p>
|
||||||
|
<ul>
|
||||||
|
<li>Os arquivos levam o número do pedido no nome (ex.: <span class="chip">pedido-246-item-1-…</span>). Enquanto baixa, o
|
||||||
|
arquivo termina em <span class="chip">.baixando</span>: o FlexiPRINT só vê o arquivo inteiro.</li>
|
||||||
|
<li>Pedido cancelado, excluído ou devolvido para correção: o arquivo sai da pasta. Arquivo trocado: a versão antiga sai.
|
||||||
|
Um arquivo que o FlexiPRINT tirar da pasta não é baixado de novo.</li>
|
||||||
|
<li>O Kanban precisa ficar <b>aberto</b> nesse computador. Ele confere a fila a cada 30 segundos, mesmo com a
|
||||||
|
atualização do quadro desligada, e pega também os pedidos movidos em outros computadores.</li>
|
||||||
|
<li>Um operador ligado a uma máquina recebe só os arquivos dos pedidos dela.</li>
|
||||||
|
</ul>
|
||||||
|
<h2>Depois de reiniciar o navegador</h2>
|
||||||
|
<div class="split">
|
||||||
|
<div><p>O navegador pede uma confirmação. A aba <b>Integrações</b> mostra um <b>!</b> laranja e a linha fica
|
||||||
|
<span class="chip">Liberar</span>: clique em <b>Liberar pasta</b> e confirme.</p></div>
|
||||||
|
<div class="side" style="flex-basis:30mm"><img class="shot" src="img/aba-aviso.png" alt="Aba Integrações com aviso"></div>
|
||||||
|
</div>
|
||||||
|
<img class="shot" src="img/pasta-liberar.png" alt="Pasta esperando o clique para liberar">
|
||||||
|
<div class="note">Use o <b>Chrome</b> na sala de impressão. O <b>Brave</b> vem com o acesso a pastas desligado (a linha
|
||||||
|
mostra como ligar). O <b>Firefox</b> não salva em pastas: nele, os arquivos da fila só são baixados para a pasta de
|
||||||
|
downloads, sem <b>Recebidos</b> e sem apagar os de pedidos cancelados.</div>
|
||||||
|
<div class="folio">Página 9</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- 10 · Cancelar e Números -->
|
||||||
|
<section class="page">
|
||||||
|
<div class="running">DTF Dropstar - guia do operador</div>
|
||||||
|
<p class="kicker">PEDIDOS E NÚMEROS</p>
|
||||||
|
<h1>Cancelar um pedido e ver os números</h1>
|
||||||
|
<div class="split">
|
||||||
|
<div>
|
||||||
|
<p>Em <b>⋯</b>, no topo do pedido, <b>Cancelar pedido</b> pede um motivo. O pedido sai do quadro e fica no filtro
|
||||||
|
<b>Cancelados</b>, com o pagamento e o histórico. O estorno, se houver, é feito no Mercado Pago. No Tiny, o pedido é
|
||||||
|
cancelado sozinho se ainda não foi faturado; se já foi, cancele a nota no Tiny. Um pedido cancelado pode ser
|
||||||
|
excluído de vez em <b>Excluir pedido</b>.</p>
|
||||||
|
<p>Pedidos de teste, criados pela equipe, aparecem com a etiqueta <span class="chip">TESTE</span> e são excluídos em
|
||||||
|
<b>⋯ → Excluir pedido de teste</b>.</p>
|
||||||
|
</div>
|
||||||
|
<div class="side"><img class="shot" src="img/menu.png" alt="Menu de ações do pedido"></div>
|
||||||
|
</div>
|
||||||
|
<h2>Números</h2>
|
||||||
|
<img class="shot" src="img/numeros.png" alt="Aba Números">
|
||||||
|
<p>A aba <b>Números</b> mostra, nos últimos 7, 30 ou 90 dias: pedidos pagos, metros vendidos, valor recebido, ticket
|
||||||
|
médio, quantos pedidos precisaram de correção e o tempo do pagamento até <b>Finalizado</b>. O gráfico mostra os metros
|
||||||
|
de cada dia (passe o mouse para ver os valores), e a tabela, quanto tempo cada etapa segura um pedido e o que está
|
||||||
|
esperando agora. Pedidos de teste e cancelados ficam de fora.</p>
|
||||||
|
<div class="folio">Página 10</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- 11 · Usuários -->
|
||||||
|
<section class="page">
|
||||||
|
<div class="running">DTF Dropstar - guia do operador</div>
|
||||||
|
<p class="kicker">EQUIPE</p>
|
||||||
|
<h1>Usuários, perfis e máquinas</h1>
|
||||||
|
<p>A aba <b>Usuários</b> aparece para os administradores. Cada pessoa tem o próprio acesso e um perfil:</p>
|
||||||
|
<table>
|
||||||
|
<tr><th style="width:31mm">Perfil</th><th>Pode</th></tr>
|
||||||
|
<tr><td class="k">Administrador</td><td>Tudo, inclusive usuários e máquinas.</td></tr>
|
||||||
|
<tr><td class="k">Gestão</td><td>Tudo, menos usuários e máquinas.</td></tr>
|
||||||
|
<tr><td class="k">Operador</td><td>Move pedidos, aprova arquivos e usa a pasta automática.</td></tr>
|
||||||
|
<tr><td class="k">Vendedor</td><td>Consulta pedidos, cotações e números. Não muda nada.</td></tr>
|
||||||
|
</table>
|
||||||
|
<img class="shot" style="width:68%" src="img/usuarios.png" alt="Aba Usuários">
|
||||||
|
<div class="split">
|
||||||
|
<div>
|
||||||
|
<h2 style="margin-top:2mm">Criar ou editar um usuário</h2>
|
||||||
|
<p>Clique em <b>Novo usuário</b> e preencha nome, e-mail, perfil e uma senha inicial (8 caracteres ou mais). Passe o
|
||||||
|
e-mail e a senha para a pessoa; ela troca em <b>Minha senha</b>. Se esquecer, defina uma senha nova em <b>Editar</b>.
|
||||||
|
<b>Ativo</b> desmarcado bloqueia o acesso na hora.</p>
|
||||||
|
<h2>Máquinas</h2>
|
||||||
|
<p>Em <b>Nova máquina</b>, informe o nome e se imprime Têxtil, UV ou os dois. O pedido vai para a primeira máquina
|
||||||
|
ativa que imprime o produto; no painel do pedido dá para escolher outra. O operador marcado em máquinas vê só os
|
||||||
|
pedidos delas; sem nenhuma marcada, vê todos.</p>
|
||||||
|
<h2>Alertas por e-mail</h2>
|
||||||
|
<p>Marque <b>Receber alertas por e-mail</b> para quem deve saber na hora de um pedido pago, de uma cotação esperando
|
||||||
|
revisão e de um pagamento com problema. Precisa do e-mail ativo em <b>Integrações</b>.</p>
|
||||||
|
</div>
|
||||||
|
<div class="side" style="flex-basis:62mm"><img class="shot" src="img/usuario-editar.png" alt="Editar usuário"></div>
|
||||||
|
</div>
|
||||||
|
<div class="folio">Página 11</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- 12 · Pagamentos e integrações -->
|
||||||
|
<section class="page">
|
||||||
|
<div class="running">DTF Dropstar - guia do operador</div>
|
||||||
|
<p class="kicker">PAGAMENTOS E INTEGRAÇÕES</p>
|
||||||
|
<h1>Pagamentos com problema e integrações</h1>
|
||||||
|
<p>A aba <b>Pagamentos</b> lista os pagamentos que chegaram mas não puderam virar pedido sozinhos. Exemplos:</p>
|
||||||
|
<ul>
|
||||||
|
<li>valor pago diferente do total da cotação;</li>
|
||||||
|
<li>cotação vencida antes do pagamento (passou das 24 h);</li>
|
||||||
|
<li>pagamento estornado ou cancelado depois que o pedido já existia.</li>
|
||||||
|
</ul>
|
||||||
|
<p>Resolva com o cliente ou no Mercado Pago e clique em <b>Registrar resolução</b>, descrevendo o que foi feito.
|
||||||
|
O item passa para <b>Resolvidos</b>.</p>
|
||||||
|
<img class="shot" src="img/pagamentos.png" alt="Aba Pagamentos">
|
||||||
|
<h2>Integrações</h2>
|
||||||
|
<img class="shot" src="img/integracoes.png" alt="Aba Integrações">
|
||||||
|
<p class="caption">Imagem de um ambiente de teste. Cada linha mostra a situação e um resumo; <b>Detalhes</b> abre as datas,
|
||||||
|
os números e os botões menos usados, embaixo da própria linha.</p>
|
||||||
|
<ul>
|
||||||
|
<li><b>Tiny</b>: quem conectou e se o envio de pedidos está ativo; o sistema renova a conexão sozinho. Se aparecer
|
||||||
|
<b>Não conectado</b> ou <b>Verificar</b>, clique em <b>Conectar Tiny</b> (ou <b>Reconectar</b>, em Detalhes) e entre
|
||||||
|
com o usuário do Tiny indicado pela Dropstar. <b>Testar conexão</b> confere pedidos, contatos, os produtos e a forma
|
||||||
|
de envio de retirada, sem criar nada.</li>
|
||||||
|
<li><b>Mercado Pago</b>: <b>Verificar conta</b> mostra, em Detalhes, a conta, a credencial e os avisos recebidos.</li>
|
||||||
|
<li><b>Frete</b>: as opções do carrinho (Jadlog, Correios PAC e SEDEX), a caixa e o peso usados na cotação.</li>
|
||||||
|
<li><b>E-mail</b>: os e-mails dos clientes e os alertas da equipe. <b>Enviar teste</b> manda um e-mail para você.</li>
|
||||||
|
<li><b>Backup do banco</b>: uma cópia por dia, às 3h, criptografada e fora do servidor. <b>Fazer backup agora</b> faz
|
||||||
|
uma cópia na hora (por exemplo, antes de uma mudança grande).</li>
|
||||||
|
<li><b>Envios ao Tiny</b>: tudo o que o sistema mandou ao Tiny, com filtros por situação, evento e pedido.
|
||||||
|
<b>Com erro</b> indica um envio que falhou; o sistema tenta de novo sozinho, mas o erro precisa de atenção.</li>
|
||||||
|
</ul>
|
||||||
|
<div class="folio">Página 12</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- 13 · Dúvidas -->
|
||||||
|
<section class="page">
|
||||||
|
<div class="running">DTF Dropstar - guia do operador</div>
|
||||||
|
<p class="kicker">DÚVIDAS FREQUENTES</p>
|
||||||
|
<h1>Mensagens e o que fazer</h1>
|
||||||
|
<table>
|
||||||
|
<tr><th style="width:62mm">Mensagem ou situação</th><th>O que fazer</th></tr>
|
||||||
|
<tr><td>“O pedido mudou. Clique em Atualizar.”</td><td>Outra pessoa mexeu no pedido ao mesmo tempo. Clique em <b>Atualizar</b> e repita a ação.</td></tr>
|
||||||
|
<tr><td>“Informe o motivo da correção.” / “Informe por que o pedido está voltando de etapa.”</td><td>Preencha o motivo antes de confirmar.</td></tr>
|
||||||
|
<tr><td>Card com <b>Parado</b></td><td>Veja se o pedido está esperando alguém ou se esqueceram de movê-lo.</td></tr>
|
||||||
|
<tr><td>Card com <b>Correção recebida</b></td><td>O cliente enviou o arquivo corrigido. Mova o pedido e aprove a correção (página 6).</td></tr>
|
||||||
|
<tr><td>Arquivo aparece como <b>expirado</b></td><td>Os arquivos ficam guardados por 30 dias. Depois disso, o cliente precisa enviar de novo.</td></tr>
|
||||||
|
<tr><td>No topo, <b>Tiny: verificar conexão</b> ou <b>Tiny não conectado</b></td><td>Abra <b>Integrações</b> e siga a mensagem do cartão do Tiny. Se pedir, clique em <b>Reconectar</b>.</td></tr>
|
||||||
|
<tr><td>O cliente comprou sem conta e não vê o pedido em Minha conta</td><td>Ele cria a conta (ou entra) com o mesmo CPF ou CNPJ e o mesmo e-mail do pedido: os pedidos aparecem sozinhos.</td></tr>
|
||||||
|
<tr><td>A internet da fábrica caiu</td><td>O Site continua recebendo pedidos e pagamentos. Quando a conexão voltar, o quadro se atualiza sozinho.</td></tr>
|
||||||
|
<tr><td><b>!</b> laranja na aba Integrações</td><td>A pasta automática espera um clique: <b>Liberar pasta</b> (página 9).</td></tr>
|
||||||
|
<tr><td>Esqueci a senha do Kanban</td><td>Peça a um administrador: <b>Usuários → Editar → Nova senha</b>.</td></tr>
|
||||||
|
<tr><td>O cliente esqueceu a senha do Site</td><td>Em <b>Minha conta → Esqueci minha senha</b>, ele recebe um link por e-mail que vale 1 hora.</td></tr>
|
||||||
|
</table>
|
||||||
|
<h2>Boas práticas</h2>
|
||||||
|
<ul>
|
||||||
|
<li>Mova o card assim que a etapa mudar: é o que atualiza o Tiny, avisa o cliente e mede o tempo de produção na aba <b>Números</b>.</li>
|
||||||
|
<li>Escreva motivos que outra pessoa entenda sem perguntar.</li>
|
||||||
|
<li>Use sempre o seu acesso: o histórico mostra quem fez cada movimento.</li>
|
||||||
|
<li>Clique em <b>Sair</b> ao deixar o computador.</li>
|
||||||
|
</ul>
|
||||||
|
<div class="folio">Página 13</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
BIN
docs/guias/operador/img/aba-aviso.png
Normal file
|
After Width: | Height: | Size: 5.5 KiB |
BIN
docs/guias/operador/img/arquivo-final.png
Normal file
|
After Width: | Height: | Size: 44 KiB |
BIN
docs/guias/operador/img/contato.png
Normal file
|
After Width: | Height: | Size: 34 KiB |
BIN
docs/guias/operador/img/correcao-recebida.png
Normal file
|
After Width: | Height: | Size: 47 KiB |
BIN
docs/guias/operador/img/correcao.png
Normal file
|
After Width: | Height: | Size: 81 KiB |
BIN
docs/guias/operador/img/cotacoes.png
Normal file
|
After Width: | Height: | Size: 360 KiB |
BIN
docs/guias/operador/img/fila.png
Normal file
|
After Width: | Height: | Size: 61 KiB |
BIN
docs/guias/operador/img/integracoes.png
Normal file
|
After Width: | Height: | Size: 154 KiB |
BIN
docs/guias/operador/img/login.png
Normal file
|
After Width: | Height: | Size: 16 KiB |
BIN
docs/guias/operador/img/menu.png
Normal file
|
After Width: | Height: | Size: 114 KiB |
BIN
docs/guias/operador/img/numeros.png
Normal file
|
After Width: | Height: | Size: 207 KiB |
BIN
docs/guias/operador/img/pagamentos.png
Normal file
|
After Width: | Height: | Size: 118 KiB |
BIN
docs/guias/operador/img/painel.png
Normal file
|
After Width: | Height: | Size: 190 KiB |
BIN
docs/guias/operador/img/pasta-liberar.png
Normal file
|
After Width: | Height: | Size: 31 KiB |
BIN
docs/guias/operador/img/pasta.png
Normal file
|
After Width: | Height: | Size: 110 KiB |
BIN
docs/guias/operador/img/quadro.png
Normal file
|
After Width: | Height: | Size: 442 KiB |
BIN
docs/guias/operador/img/usuario-editar.png
Normal file
|
After Width: | Height: | Size: 89 KiB |
BIN
docs/guias/operador/img/usuarios.png
Normal file
|
After Width: | Height: | Size: 208 KiB |
320
docs/guias/site/guia-site-dtf.html
Normal file
@@ -0,0 +1,320 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<!-- Source of docs/guia-site-dtf.pdf. Print with docs/guias/imprimir.sh.
|
||||||
|
Screenshots in img/ come from the local stack with fictional customers. -->
|
||||||
|
<html lang="pt-BR">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Site DTF · Como funciona</title>
|
||||||
|
<style>
|
||||||
|
@page { size: A4; margin: 0; }
|
||||||
|
:root {
|
||||||
|
--navy: #0B1320; --orange: #F08A24; --ink: #1B2331; --muted: #6B7280;
|
||||||
|
--line: #D6DCE4; --head: #EAF0F8; --note: #FFF5E8; --note-line: #F4C58E;
|
||||||
|
}
|
||||||
|
* { box-sizing: border-box; }
|
||||||
|
html, body { margin: 0; padding: 0; }
|
||||||
|
body { font-family: 'DejaVu Sans', sans-serif; color: var(--ink); font-size: 9.7pt; line-height: 1.55;
|
||||||
|
-webkit-print-color-adjust: exact; print-color-adjust: exact; }
|
||||||
|
.page { width: 210mm; height: 297mm; position: relative; padding: 26mm 18mm 20mm; overflow: hidden;
|
||||||
|
page-break-after: always; break-after: page; }
|
||||||
|
.page:last-child { page-break-after: auto; break-after: auto; }
|
||||||
|
.running { position: absolute; top: 9mm; left: 18mm; right: 18mm; font-size: 7.4pt; color: var(--muted);
|
||||||
|
border-bottom: 0.6pt solid #E3E7ED; padding-bottom: 2.4mm; }
|
||||||
|
.folio { position: absolute; bottom: 9mm; right: 18mm; font-size: 7.4pt; color: var(--muted); }
|
||||||
|
.kicker { color: var(--orange); font-weight: bold; font-size: 7.6pt; letter-spacing: 0.04em; margin: 0 0 1mm; }
|
||||||
|
h1 { font-size: 20.5pt; line-height: 1.2; margin: 0 0 2mm; color: #101826; }
|
||||||
|
h1::after { content: ""; display: block; width: 18mm; height: 1.4mm; background: var(--orange); margin-top: 3mm; }
|
||||||
|
h2 { font-size: 11.5pt; margin: 7mm 0 2.5mm; color: #101826; }
|
||||||
|
p { margin: 0 0 2.6mm; }
|
||||||
|
b { font-weight: bold; }
|
||||||
|
table { width: 100%; border-collapse: collapse; margin: 2mm 0 3mm; font-size: 8.6pt; line-height: 1.45; }
|
||||||
|
th, td { border: 0.6pt solid var(--line); padding: 2mm 2.4mm; vertical-align: top; text-align: left; }
|
||||||
|
th { background: var(--head); font-weight: bold; }
|
||||||
|
td.n { color: var(--orange); font-weight: bold; font-size: 11pt; width: 7mm; text-align: center; }
|
||||||
|
td.k { font-weight: bold; }
|
||||||
|
.note { background: var(--note); border: 0.6pt solid var(--note-line); border-radius: 2mm; padding: 3mm 3.6mm;
|
||||||
|
font-size: 8.6pt; margin: 3mm 0; }
|
||||||
|
ul { margin: 0 0 3mm; padding-left: 4.5mm; }
|
||||||
|
ul li { margin-bottom: 1.1mm; }
|
||||||
|
ul li::marker { color: var(--orange); }
|
||||||
|
ol { margin: 0 0 3mm; padding-left: 5mm; }
|
||||||
|
ol li { margin-bottom: 1.3mm; }
|
||||||
|
ol li::marker { color: var(--orange); font-weight: bold; }
|
||||||
|
.chip { display: inline-block; border: 0.6pt solid #C9D0DA; background: #F4F6F9; border-radius: 1.2mm;
|
||||||
|
padding: 0 1.6mm; font-size: 7.6pt; line-height: 1.6; white-space: nowrap; }
|
||||||
|
.shot { display: block; width: 100%; border-radius: 1.6mm; margin: 2mm 0 1mm; }
|
||||||
|
.caption { font-size: 7.2pt; color: var(--muted); margin: 0 0 3mm; }
|
||||||
|
.split { display: flex; gap: 6mm; align-items: flex-start; }
|
||||||
|
.split > div { flex: 1; }
|
||||||
|
.split > .side { flex: 0 0 79.5mm; }
|
||||||
|
.quote { font-style: normal; }
|
||||||
|
.shot.half { width: 62%; }
|
||||||
|
.shot.narrow { width: 78%; }
|
||||||
|
|
||||||
|
/* Cover */
|
||||||
|
.cover { background: var(--navy); color: #F3F5F8; padding: 0 18mm; }
|
||||||
|
.cover .block { position: absolute; left: 18mm; right: 18mm; top: 158mm; }
|
||||||
|
.cover .kicker { margin-bottom: 4mm; }
|
||||||
|
.cover .title { font-size: 27pt; font-weight: bold; line-height: 1.25; margin: 0 0 4mm; color: #fff; }
|
||||||
|
.cover .lead { font-size: 9.6pt; color: #C8CFDA; margin: 0 0 8mm; }
|
||||||
|
.cover table { font-size: 8pt; margin: 0 0 8mm; }
|
||||||
|
.cover th, .cover td { border-color: #2A3547; background: transparent; color: #E6EAF0; padding: 3mm 3.6mm; }
|
||||||
|
.cover th { color: var(--orange); }
|
||||||
|
.cover .version { font-size: 8pt; color: #A9B2C0; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
|
||||||
|
<!-- 1 · Capa -->
|
||||||
|
<section class="page cover">
|
||||||
|
<div class="block">
|
||||||
|
<p class="kicker">GUIA DO SITE</p>
|
||||||
|
<p class="title">Site DTF<br>Como funciona</p>
|
||||||
|
<p class="lead">Do envio da arte ao pedido pronto: o que o cliente vê e o que acontece em cada etapa.</p>
|
||||||
|
<table>
|
||||||
|
<tr><th style="width:50%">Endereço</th><th>Para quem</th></tr>
|
||||||
|
<tr><td>dropstardtf.com.br</td><td>Equipe Dropstar e atendimento</td></tr>
|
||||||
|
</table>
|
||||||
|
<p class="version">Versão de 19 de outubro de 2026</p>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- 2 · Jornada -->
|
||||||
|
<section class="page">
|
||||||
|
<div class="running">DTF Dropstar - como funciona o Site DTF</div>
|
||||||
|
<p class="kicker">VISÃO GERAL</p>
|
||||||
|
<h1>A jornada do cliente</h1>
|
||||||
|
<p>O cliente escolhe o produto, envia as artes e vê a nota e o preço na hora, sem cadastro. Fecha o carrinho e paga
|
||||||
|
em seguida: o Site confere o pedido sozinho.</p>
|
||||||
|
<table>
|
||||||
|
<tr><td class="n">1</td><td class="k" style="width:34mm">Escolhe o produto</td>
|
||||||
|
<td>Quatro opções: DTF Têxtil ou DTF UV, com folha já montada ou artes avulsas.</td></tr>
|
||||||
|
<tr><td class="n">2</td><td class="k">Monta a folha</td>
|
||||||
|
<td>Envia as artes, informa tamanho e quantidade e vê a folha, a nota e o total.</td></tr>
|
||||||
|
<tr><td class="n">3</td><td class="k">Carrinho</td>
|
||||||
|
<td>Escolhe os itens que vai pagar, informa nome, CPF ou CNPJ, WhatsApp e e-mail e escolhe retirada ou entrega.</td></tr>
|
||||||
|
<tr><td class="n">4</td><td class="k">Pagamento</td>
|
||||||
|
<td>PIX ou cartão de crédito (à vista ou em até 3 vezes) pelo Mercado Pago, na própria página. Os dados do cartão não passam pelo nosso servidor.</td></tr>
|
||||||
|
<tr><td class="n">5</td><td class="k">Produção</td>
|
||||||
|
<td>Com o pagamento aprovado, o pedido aparece no Kanban da equipe e é lançado no Tiny.</td></tr>
|
||||||
|
<tr><td class="n">6</td><td class="k">Acompanhamento</td>
|
||||||
|
<td>E-mail de confirmação, <b>Minha conta</b> com o andamento de cada pedido, e WhatsApp quando o pedido é aprovado, fica pronto para retirada ou é enviado.</td></tr>
|
||||||
|
</table>
|
||||||
|
<img class="shot" src="img/inicio.png" alt="Página inicial do Site DTF">
|
||||||
|
<p class="caption">Página inicial do Site DTF.</p>
|
||||||
|
<div class="folio">Página 2</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- 3 · Produtos e preços -->
|
||||||
|
<section class="page">
|
||||||
|
<div class="running">DTF Dropstar - como funciona o Site DTF</div>
|
||||||
|
<p class="kicker">PRODUTOS E PREÇOS</p>
|
||||||
|
<h1>Quatro produtos, um preço por nota</h1>
|
||||||
|
<img class="shot" src="img/produtos.png" alt="Escolha do produto">
|
||||||
|
<p>O preço do metro depende da <b>nota da arte</b>, calculada pela resolução no tamanho em que vai ser impressa.
|
||||||
|
Quanto melhor o arquivo, menor o preço.</p>
|
||||||
|
<table>
|
||||||
|
<tr><th>Nota da arte</th><th>Têxtil 57 cm<br>folha montada</th><th>Têxtil 57 cm<br>artes avulsas</th><th>UV 28,5 cm<br>folha montada</th><th>UV 28,5 cm<br>artes avulsas</th></tr>
|
||||||
|
<tr><td>90 a 100</td><td>R$ 14,90</td><td>R$ 24,90</td><td>R$ 69,90</td><td>R$ 83,90</td></tr>
|
||||||
|
<tr><td>75 a 89</td><td>R$ 16,20</td><td>R$ 26,20</td><td>R$ 73,90</td><td>R$ 87,90</td></tr>
|
||||||
|
<tr><td>60 a 74</td><td>R$ 17,50</td><td>R$ 27,50</td><td>R$ 77,90</td><td>R$ 91,90</td></tr>
|
||||||
|
<tr><td>40 a 59</td><td>R$ 18,70</td><td>R$ 28,70</td><td>R$ 81,90</td><td>R$ 95,90</td></tr>
|
||||||
|
<tr><td>abaixo de 40</td><td>R$ 19,90</td><td>R$ 29,90</td><td>R$ 85,90</td><td>R$ 99,90</td></tr>
|
||||||
|
</table>
|
||||||
|
<ul>
|
||||||
|
<li><b>Artes avulsas</b> incluem a montagem da folha: R$ 10,00 a mais por metro no têxtil e R$ 14,00 no UV, em qualquer nota.</li>
|
||||||
|
<li>A cobrança é a cada <b>10 cm</b> (uma folha de 2,75 m custa 2,80 m) e o pedido mínimo é de <b>1 metro</b>.</li>
|
||||||
|
<li>Folhas em CDR, AI, PSD ou TIFF não têm conferência automática: o metro vai pela tabela cheia e a equipe prepara o
|
||||||
|
arquivo à mão. Quando a Dropstar define um valor para essa preparação, ele aparece no preço do item antes do pagamento.</li>
|
||||||
|
</ul>
|
||||||
|
<div class="folio">Página 3</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- 4 · Montar a folha -->
|
||||||
|
<section class="page">
|
||||||
|
<div class="running">DTF Dropstar - como funciona o Site DTF</div>
|
||||||
|
<p class="kicker">PASSO 1</p>
|
||||||
|
<h1>Montar a folha</h1>
|
||||||
|
<img class="shot" src="img/montagem.png" alt="Página de um produto">
|
||||||
|
<p class="caption">Página de um produto: as artes à esquerda e, à direita, a folha montada ao vivo.</p>
|
||||||
|
<ul>
|
||||||
|
<li><b>Enviar as artes</b>: arrastar para a área de envio ou clicar para escolher. Artes avulsas aceitam PNG, JPG ou
|
||||||
|
WEBP; a folha montada aceita PNG, JPG ou PDF (e CDR, AI, PSD e TIFF pela tabela cheia).</li>
|
||||||
|
<li><b>Arquivos de até 5 GB</b>. O envio começa assim que a arte entra, com uma barra que mostra quanto tempo falta.
|
||||||
|
Todo arquivo passa por antivírus (até 2 GB) ou pela conferência do formato (acima disso) antes de chegar à equipe.</li>
|
||||||
|
<li><b>Tamanho e quantidade</b>: o cliente informa a largura de cada arte na peça e quantas cópias quer. Botões com
|
||||||
|
medidas comuns agilizam, e cada arte pode ser girada ou espelhada.</li>
|
||||||
|
<li><b>Dicas na própria arte</b>: se uma arte está pequena para o tamanho pedido, o Site diz até que medida ela sai em
|
||||||
|
300 DPI. Se uma largura um pouco menor economiza filme, aparece o botão para usar essa medida.</li>
|
||||||
|
<li><b>Folha já montada / Artes separadas</b>: a opção no topo troca entre enviar a folha pronta e mandar as artes
|
||||||
|
para a equipe montar, com a diferença de preço à vista.</li>
|
||||||
|
</ul>
|
||||||
|
<div class="folio">Página 4</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- 5 · A folha, a nota e o total -->
|
||||||
|
<section class="page">
|
||||||
|
<div class="running">DTF Dropstar - como funciona o Site DTF</div>
|
||||||
|
<p class="kicker">PASSO 1</p>
|
||||||
|
<h1>A folha, a nota e o total</h1>
|
||||||
|
<div class="split">
|
||||||
|
<div class="side" style="flex-basis:72mm"><img class="shot" src="img/painel.png" alt="Quadro da folha, nota e total"></div>
|
||||||
|
<div>
|
||||||
|
<p>O quadro da direita acompanha o cliente enquanto ele monta:</p>
|
||||||
|
<ul>
|
||||||
|
<li><b>Montagem ao vivo</b>: como as artes vão ficar no filme de 57 cm, e quanto da folha virou arte. O arquivo de
|
||||||
|
impressão é gerado com exatamente essa montagem.</li>
|
||||||
|
<li><b>Preço do metro pela resolução</b>: a escala mostra em que faixa a arte está e quanto custaria em cada uma.</li>
|
||||||
|
<li><b>Metragem</b> cobrada a cada 10 cm. Quando a folha tem menos de 1 m, o Site mostra quantos centímetros de
|
||||||
|
artes ainda cabem sem custo.</li>
|
||||||
|
<li><b>Total</b> do item e quanto o cliente economizou pela resolução.</li>
|
||||||
|
<li><b>Ressalva de resolução</b>: se alguma arte fica abaixo de 300 DPI, o cliente precisa marcar que leu e quer
|
||||||
|
imprimir assim. Abaixo de 96 DPI o Site não aceita a arte.</li>
|
||||||
|
<li><b>Adicionar ao carrinho</b> leva o item para o carrinho; dá para montar outros itens e pagar tudo junto.</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="folio">Página 5</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- 6 · Carrinho -->
|
||||||
|
<section class="page">
|
||||||
|
<div class="running">DTF Dropstar - como funciona o Site DTF</div>
|
||||||
|
<p class="kicker">PASSO 2</p>
|
||||||
|
<h1>Carrinho, dados e entrega</h1>
|
||||||
|
<img class="shot" src="img/carrinho.png" alt="Carrinho com dados e entrega">
|
||||||
|
<ul>
|
||||||
|
<li><b>Itens</b>: cada item aparece com a miniatura da arte. O cliente marca quais quer pagar agora; os outros ficam no
|
||||||
|
carrinho. <b>Remover</b> e <b>Esvaziar carrinho</b> podem ser desfeitos na hora.</li>
|
||||||
|
<li><b>Seus dados</b>: nome, CPF ou CNPJ (o mesmo da nota fiscal), WhatsApp e e-mail. Quem já tem conta entra com os
|
||||||
|
dados preenchidos.</li>
|
||||||
|
<li><b>Forma de entrega</b>: <b>Retirar em Franca</b> (Av. Major Elias Motta, 1281, Jardim São Luís, de segunda a
|
||||||
|
sexta, das 7h às 17h) ou <b>Receber em casa</b>. Na entrega, o CEP preenche o endereço e aparecem as opções
|
||||||
|
<b>Jadlog</b>, <b>Correios PAC</b> e <b>Correios SEDEX</b>, da mais barata para a mais cara, com o prazo já contando o
|
||||||
|
dia de produção.</li>
|
||||||
|
<li><b>Arquivos enviados</b> confirma que as artes já chegaram. Os arquivos de um carrinho não pago ficam guardados
|
||||||
|
por 2 dias.</li>
|
||||||
|
</ul>
|
||||||
|
<div class="folio">Página 6</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- 7 · Pagamento -->
|
||||||
|
<section class="page">
|
||||||
|
<div class="running">DTF Dropstar - como funciona o Site DTF</div>
|
||||||
|
<p class="kicker">PASSO 3</p>
|
||||||
|
<h1>Pagamento</h1>
|
||||||
|
<p>Em <b>Ir para o pagamento</b>, o Site confere o carrinho no servidor (preço, metragem e a nota pelos próprios
|
||||||
|
arquivos) e libera o pagamento na hora. Só esperam a equipe os pedidos acima de <b>50 m</b> e os que pedem uma nota
|
||||||
|
que não confere com os arquivos. Depois da aprovação, o cliente tem <b>24 horas</b> para pagar.</p>
|
||||||
|
<table>
|
||||||
|
<tr><th style="width:38mm">Forma</th><th>Como funciona</th></tr>
|
||||||
|
<tr><td class="k">Cartão de crédito</td><td>No formulário seguro do Mercado Pago, dentro da página: à vista sem juros,
|
||||||
|
ou em 2 ou 3 parcelas com juros. Os dados do cartão não passam pelo nosso servidor.</td></tr>
|
||||||
|
<tr><td class="k">PIX</td><td>QR Code e código copia e cola na própria página, válidos por 30 minutos, com contagem.
|
||||||
|
A página confirma sozinha quando o pagamento cai.</td></tr>
|
||||||
|
</table>
|
||||||
|
<h2>Quando o cartão é recusado</h2>
|
||||||
|
<p>O cliente vê o motivo em uma frase e o que fazer, por exemplo:</p>
|
||||||
|
<ul>
|
||||||
|
<li>“O cartão não tem limite suficiente para este valor. Use outro cartão ou pague com PIX.”</li>
|
||||||
|
<li>“O código de segurança (CVV) está incorreto. Confira e tente de novo.”</li>
|
||||||
|
<li>“O banco precisa autorizar este pagamento. Ligue para o banco emissor e tente de novo, ou use outro cartão.”</li>
|
||||||
|
</ul>
|
||||||
|
<h2>Pagamento aprovado</h2>
|
||||||
|
<p>A página mostra <b>Pagamento confirmado</b> e o botão <b>Ver meus pedidos</b>, e o cliente recebe o e-mail
|
||||||
|
<b>Recebemos seu pedido</b> (página 10). O pedido entra na produção e aparece no Kanban. Para o cliente, o pedido tem um <b>código</b> (ex.: <span class="chip">3F0CB7C2</span>); o número
|
||||||
|
sequencial fica só com a equipe.</p>
|
||||||
|
<div class="folio">Página 7</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- 8 · Minha conta -->
|
||||||
|
<section class="page">
|
||||||
|
<div class="running">DTF Dropstar - como funciona o Site DTF</div>
|
||||||
|
<p class="kicker">ACOMPANHAMENTO</p>
|
||||||
|
<h1>Minha conta</h1>
|
||||||
|
<p>O cliente entra com e-mail e senha, ou cria a conta com nome, CPF ou CNPJ, WhatsApp, e-mail e uma senha de 12
|
||||||
|
caracteres ou mais. Para criar, ele confirma o e-mail com um <b>código de 6 números</b> enviado na hora. Os pedidos
|
||||||
|
feitos sem conta com o mesmo CPF/CNPJ e e-mail aparecem na conta sozinhos, de qualquer navegador.</p>
|
||||||
|
<img class="shot narrow" src="img/conta.png" alt="Visão geral de Minha conta">
|
||||||
|
<ul>
|
||||||
|
<li><b>Visão geral</b>: quantos pedidos aguardam pagamento, estão em produção, em correção ou finalizados.</li>
|
||||||
|
<li><b>Pedidos</b>: a lista com código, produto, metragem, situação e valor, com filtros e busca pelo código. Cada
|
||||||
|
pedido mostra as etapas e o andamento, com data e hora.</li>
|
||||||
|
<li><b>Dados da conta</b>: nome, WhatsApp e endereço de entrega salvo; a troca de e-mail, confirmada por um código
|
||||||
|
enviado ao novo endereço (o antigo recebe um aviso); e a troca de senha. O CPF ou CNPJ não muda.</li>
|
||||||
|
</ul>
|
||||||
|
<div class="note"><b>Esqueci minha senha</b>: o cliente recebe por e-mail um link para criar uma nova senha, que vale
|
||||||
|
1 hora e funciona uma vez só.</div>
|
||||||
|
<div class="folio">Página 8</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- 9 · Correção -->
|
||||||
|
<section class="page">
|
||||||
|
<div class="running">DTF Dropstar - como funciona o Site DTF</div>
|
||||||
|
<p class="kicker">ACOMPANHAMENTO</p>
|
||||||
|
<h1>Correção e avisos</h1>
|
||||||
|
<img class="shot" src="img/pedido-correcao.png" alt="Pedido em correção em Minha conta">
|
||||||
|
<p class="caption">Pedido em correção: o motivo escrito pela equipe e o envio do arquivo corrigido.</p>
|
||||||
|
<p>Quando a equipe pede uma correção, o pedido aparece em <b>Correção</b> em Minha conta, com o motivo. O cliente envia
|
||||||
|
a arte corrigida ali mesmo, com uma nota do que mudou, e a equipe segue com o pedido. A equipe avisa o cliente pelo
|
||||||
|
WhatsApp, com a mensagem pronta no Kanban.</p>
|
||||||
|
<ul>
|
||||||
|
<li>As artes ficam guardadas por <b>30 dias</b>. Depois disso, para repetir o pedido, o cliente envia os arquivos de novo.</li>
|
||||||
|
</ul>
|
||||||
|
<div class="folio">Página 9</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- 10 · Avisos -->
|
||||||
|
<section class="page">
|
||||||
|
<div class="running">DTF Dropstar - como funciona o Site DTF</div>
|
||||||
|
<p class="kicker">ACOMPANHAMENTO</p>
|
||||||
|
<h1>Avisos ao cliente</h1>
|
||||||
|
<div class="split">
|
||||||
|
<div>
|
||||||
|
<h2 style="margin-top:0">Por e-mail</h2>
|
||||||
|
<p>Saem de <b>dropstardtf.com.br</b>, no visual do Site, com o nome do cliente:</p>
|
||||||
|
<ul>
|
||||||
|
<li><b>Recebemos seu pedido</b>: quando o pagamento é aprovado, com os itens, a entrega, o total, as próximas etapas e
|
||||||
|
o botão <b>Ver meu pedido</b>.</li>
|
||||||
|
<li><b>Código de confirmação</b>: para criar a conta e para trocar o e-mail. Vale 15 minutos.</li>
|
||||||
|
<li><b>Criar nova senha</b>: o link de <b>Esqueci minha senha</b>, que vale 1 hora.</li>
|
||||||
|
<li><b>E-mail trocado</b>: aviso ao endereço antigo, com o WhatsApp da Dropstar se não foi o cliente.</li>
|
||||||
|
<li><b>Você já tem conta</b>: quando alguém tenta criar uma conta com um e-mail já cadastrado.</li>
|
||||||
|
</ul>
|
||||||
|
<h2>Por WhatsApp</h2>
|
||||||
|
<p>Pelo número e pelas mensagens que a Dropstar já usa, a partir da situação do pedido no Tiny:</p>
|
||||||
|
<ul>
|
||||||
|
<li><b>Pedido aprovado</b>, quando o pagamento é aprovado;</li>
|
||||||
|
<li><b>Pronto para retirada</b>, quando o pedido de retirada é finalizado;</li>
|
||||||
|
<li><b>Pedido enviado</b> e <b>entregue</b>, nos pedidos com entrega.</li>
|
||||||
|
</ul>
|
||||||
|
<p>Na correção, a equipe avisa pelo WhatsApp com a mensagem pronta no Kanban.</p>
|
||||||
|
</div>
|
||||||
|
<div class="side" style="flex-basis:70mm"><img class="shot" src="img/email-pedido.png" alt="E-mail Recebemos seu pedido"></div>
|
||||||
|
</div>
|
||||||
|
<div class="folio">Página 10</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- 11 · Situação atual -->
|
||||||
|
<section class="page">
|
||||||
|
<div class="running">DTF Dropstar - como funciona o Site DTF</div>
|
||||||
|
<p class="kicker">SITUAÇÃO ATUAL</p>
|
||||||
|
<h1>O que já funciona e o que falta para o lançamento</h1>
|
||||||
|
<table>
|
||||||
|
<tr><th style="width:44mm">Parte</th><th style="width:36mm">Situação</th><th>Observação</th></tr>
|
||||||
|
<tr><td class="k">Site: produtos, montagem, nota e preço</td><td>Funcionando</td><td>Tabela e regras comerciais do Site DTF mantidas.</td></tr>
|
||||||
|
<tr><td class="k">Arquivos de até 5 GB</td><td>Funcionando</td><td>Antivírus até 2 GB; acima disso, conferência do formato.</td></tr>
|
||||||
|
<tr><td class="k">Frete (receber em casa)</td><td>Funcionando</td><td>Jadlog, Correios PAC e Correios SEDEX, com a caixa e o peso informados pela Dropstar.</td></tr>
|
||||||
|
<tr><td class="k">Pagamento</td><td>Funcionando</td><td>PIX e cartão de crédito (à vista ou em até 3 vezes), com as credenciais de produção do Mercado Pago.</td></tr>
|
||||||
|
<tr><td class="k">Minha conta e e-mails</td><td>Funcionando</td><td>Cadastro com código, recuperação de senha, troca de e-mail e confirmação do pedido.</td></tr>
|
||||||
|
<tr><td class="k">Kanban de produção</td><td>Funcionando</td><td>Veja o guia do operador.</td></tr>
|
||||||
|
<tr><td class="k">Cópia de segurança</td><td>Funcionando</td><td>Uma por dia, criptografada e fora do servidor.</td></tr>
|
||||||
|
<tr><td class="k">Domínio</td><td>Definitivo</td><td>dropstardtf.com.br (Site) e kanban.dropstardtf.com.br (Kanban).</td></tr>
|
||||||
|
<tr><td class="k">Pedido no Tiny e avisos por WhatsApp</td><td>Pronto, falta ativar</td><td>Ativados no lançamento, depois de definir a categoria, o vendedor e o marcador dos pedidos do DTF no Tiny.</td></tr>
|
||||||
|
<tr><td class="k">Lançamento</td><td>Próximo passo</td><td>Teste com um grupo de 5 a 10 clientes antes de abrir para todos.</td></tr>
|
||||||
|
</table>
|
||||||
|
<div class="folio">Página 11</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
BIN
docs/guias/site/img/carrinho.png
Normal file
|
After Width: | Height: | Size: 310 KiB |
BIN
docs/guias/site/img/conta.png
Normal file
|
After Width: | Height: | Size: 126 KiB |
BIN
docs/guias/site/img/email-pedido.png
Normal file
|
After Width: | Height: | Size: 195 KiB |
BIN
docs/guias/site/img/entrega.png
Normal file
|
After Width: | Height: | Size: 83 KiB |
BIN
docs/guias/site/img/inicio.png
Normal file
|
After Width: | Height: | Size: 234 KiB |
BIN
docs/guias/site/img/montagem.png
Normal file
|
After Width: | Height: | Size: 410 KiB |
BIN
docs/guias/site/img/painel.png
Normal file
|
After Width: | Height: | Size: 283 KiB |
BIN
docs/guias/site/img/pedido-correcao.png
Normal file
|
After Width: | Height: | Size: 234 KiB |
BIN
docs/guias/site/img/pedidos.png
Normal file
|
After Width: | Height: | Size: 320 KiB |
BIN
docs/guias/site/img/produtos.png
Normal file
|
After Width: | Height: | Size: 222 KiB |
27
docs/guias/telas/README.md
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
# Screenshots for the guides
|
||||||
|
|
||||||
|
The images in `operador/img/` and `site/img/` come from the local stack seeded
|
||||||
|
with fictional customers. To take them again:
|
||||||
|
|
||||||
|
1. Start the local stack with the CI settings (`docs/LOCAL_SETUP.md`), clear it as
|
||||||
|
`seed.py` says, and run `seed.py` in the api container.
|
||||||
|
2. Start a container from the browser-tests image on the stack's network and
|
||||||
|
give it internet too, so Google Fonts load (the stack's network is internal):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker run -d --name dtf-shots --network dtf-sistema_local \
|
||||||
|
-v "$PWD/docs/guias/telas:/g" -v /tmp/telas:/shots -e CHROME_BIN=/usr/bin/chromium \
|
||||||
|
dtf-sistema-browser-tests sleep 1800
|
||||||
|
docker network connect bridge dtf-shots
|
||||||
|
docker exec dtf-shots node /g/shots.mjs kanban
|
||||||
|
docker exec dtf-shots node /g/shots.mjs site
|
||||||
|
```
|
||||||
|
|
||||||
|
`site` also needs `/g/email-pedido.html`, the order e-mail rendered with
|
||||||
|
`app.mail_html.order_paid`.
|
||||||
|
3. Copy what changed from `/tmp/telas` into the `img/` folders (the print queue
|
||||||
|
column is cropped to 444x700 px), print with `../imprimir.sh` and check every
|
||||||
|
page: a page is fixed at A4 and cuts what does not fit.
|
||||||
|
|
||||||
|
Integrações is shown in its production state with fictional values set in the
|
||||||
|
page (shots.mjs), since the local stack has no Tiny or Mercado Pago.
|
||||||
295
docs/guias/telas/seed.py
Normal file
@@ -0,0 +1,295 @@
|
|||||||
|
"""Fictional orders for the guides' screenshots, on the LOCAL stack only.
|
||||||
|
|
||||||
|
Before: python -m ops.launch_reset --confirmar APAGAR --contas (worker), and in
|
||||||
|
the db container delete every operator but operator@example.test, the
|
||||||
|
machines, payment_events, mail_queue and cnpj_names. Then, from the repo:
|
||||||
|
|
||||||
|
docker compose -f compose.local.yaml exec -T -e SITE_BASE_URL=http://site -e SITE_HOST_HEADER=localhost -e PYTHONPATH=/app api python - < docs/guias/telas/seed.py
|
||||||
|
|
||||||
|
It makes orders #1-#11 in every Kanban stage, a quote above 50 m, a refused
|
||||||
|
payment, users and machines, and Pedro's account; see telas/README.md.
|
||||||
|
"""
|
||||||
|
import io
|
||||||
|
import math
|
||||||
|
import random
|
||||||
|
import time
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
from PIL import Image, ImageDraw
|
||||||
|
from psycopg.types.json import Jsonb
|
||||||
|
|
||||||
|
from app.core import db
|
||||||
|
from tests.smoke_test import Client, approved_quote, item_spec, upload_bytes
|
||||||
|
|
||||||
|
random.seed(7)
|
||||||
|
PALETTES = {
|
||||||
|
'aurora': [(255, 122, 89), (255, 196, 61), (61, 64, 91), (129, 178, 154)],
|
||||||
|
'ipe': [(244, 196, 48), (232, 93, 117), (45, 49, 66), (255, 255, 255)],
|
||||||
|
'mare': [(0, 119, 182), (0, 180, 216), (144, 224, 239), (3, 4, 94)],
|
||||||
|
'rocha': [(214, 40, 40), (247, 127, 0), (252, 191, 73), (0, 48, 73)],
|
||||||
|
'norte': [(46, 196, 182), (231, 29, 54), (255, 159, 28), (1, 22, 39)],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def check(base, weights):
|
||||||
|
rem = sum(int(n) * w for n, w in zip(base, weights)) % 11
|
||||||
|
return 0 if rem < 2 else 11 - rem
|
||||||
|
|
||||||
|
|
||||||
|
def cnpj(seed):
|
||||||
|
base = f'{seed:08d}0001'
|
||||||
|
d1 = check(base, [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2])
|
||||||
|
d2 = check(base + str(d1), [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2])
|
||||||
|
return base + f'{d1}{d2}'
|
||||||
|
|
||||||
|
|
||||||
|
def cpf(seed):
|
||||||
|
base = f'{seed:09d}'
|
||||||
|
d1 = check(base, range(10, 1, -1))
|
||||||
|
d2 = check(base + str(d1), range(11, 1, -1))
|
||||||
|
return base + f'{d1}{d2}'
|
||||||
|
|
||||||
|
|
||||||
|
def star(draw, cx, cy, r, color):
|
||||||
|
points = []
|
||||||
|
for i in range(10):
|
||||||
|
angle = math.pi / 2 + i * math.pi / 5
|
||||||
|
radius = r if i % 2 == 0 else r * 0.45
|
||||||
|
points.append((cx + radius * math.cos(angle), cy - radius * math.sin(angle)))
|
||||||
|
draw.polygon(points, fill=color)
|
||||||
|
|
||||||
|
|
||||||
|
def sticker(draw, x, y, size, palette, kind):
|
||||||
|
a, b, c, d = palette
|
||||||
|
if kind == 0:
|
||||||
|
draw.ellipse((x, y, x + size, y + size), fill=a)
|
||||||
|
draw.ellipse((x + size * .14, y + size * .14, x + size * .86, y + size * .86), fill=c)
|
||||||
|
star(draw, x + size / 2, y + size / 2, size * .28, b)
|
||||||
|
elif kind == 1:
|
||||||
|
draw.rounded_rectangle((x, y + size * .15, x + size, y + size * .85), radius=size * .18, fill=b)
|
||||||
|
for i in range(4):
|
||||||
|
draw.rectangle((x + size * (.12 + i * .2), y + size * .3, x + size * (.2 + i * .2), y + size * .7), fill=c)
|
||||||
|
elif kind == 2:
|
||||||
|
draw.polygon([(x + size / 2, y), (x + size, y + size / 2), (x + size / 2, y + size), (x, y + size / 2)], fill=d)
|
||||||
|
draw.ellipse((x + size * .3, y + size * .3, x + size * .7, y + size * .7), fill=a)
|
||||||
|
else:
|
||||||
|
draw.ellipse((x, y, x + size, y + size), fill=b)
|
||||||
|
draw.pieslice((x + size * .1, y + size * .1, x + size * .9, y + size * .9), 200, 340, fill=a)
|
||||||
|
draw.ellipse((x + size * .35, y + size * .55, x + size * .65, y + size * .85), fill=c)
|
||||||
|
|
||||||
|
|
||||||
|
def sheet(palette, width_cm, length_cm, px_per_cm=12):
|
||||||
|
"""A transparent finished sheet of stickers, as customers send."""
|
||||||
|
w, h = int(width_cm * px_per_cm), int(length_cm * px_per_cm)
|
||||||
|
image = Image.new('RGBA', (w, h), (0, 0, 0, 0))
|
||||||
|
draw = ImageDraw.Draw(image)
|
||||||
|
size = int(9 * px_per_cm)
|
||||||
|
gap = int(1.2 * px_per_cm)
|
||||||
|
cols = max(1, (w - gap) // (size + gap))
|
||||||
|
margin = (w - cols * size - (cols - 1) * gap) // 2
|
||||||
|
y, row = gap, 0
|
||||||
|
while y + size <= h - gap:
|
||||||
|
for col in range(cols):
|
||||||
|
sticker(draw, margin + col * (size + gap), y, size, palette, (row + col) % 4)
|
||||||
|
y += size + gap
|
||||||
|
row += 1
|
||||||
|
return image
|
||||||
|
|
||||||
|
|
||||||
|
def png(image, max_side=None):
|
||||||
|
if max_side:
|
||||||
|
image = image.copy()
|
||||||
|
image.thumbnail((max_side, max_side))
|
||||||
|
out = io.BytesIO()
|
||||||
|
image.save(out, 'PNG', optimize=True)
|
||||||
|
return out.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
def put_thumbnail(client, uid, data):
|
||||||
|
from urllib.request import Request
|
||||||
|
from tests.smoke_test import BASE, with_host
|
||||||
|
request = Request(BASE + f'/api/uploads/{uid}/thumbnail', data=data, method='PUT',
|
||||||
|
headers=with_host({'Content-Type': 'image/png'}))
|
||||||
|
with client.opener.open(request, timeout=30) as response:
|
||||||
|
assert response.status == 200
|
||||||
|
|
||||||
|
|
||||||
|
def order(customer, palette, mode, metres, grade, delivery=None):
|
||||||
|
client = Client()
|
||||||
|
client.call('/session')
|
||||||
|
film = 28.5 if mode in ('uv', 'uvfile') else 57
|
||||||
|
art = sheet(PALETTES[palette], film, float(metres) * 100)
|
||||||
|
uid = upload_bytes(client, png(art), name=f'{palette}-folha.png')
|
||||||
|
put_thumbnail(client, uid, png(art, 520))
|
||||||
|
item = item_spec(mode, metres, grade, uid)
|
||||||
|
draft = {'request_key': str(uuid4()), 'items': [item], 'customer': customer,
|
||||||
|
'freight': {'service': 'pickup'}}
|
||||||
|
if delivery:
|
||||||
|
draft['freight'] = {'service': 'mock-standard', 'postal_code': delivery['postal_code']}
|
||||||
|
draft['destination'] = delivery
|
||||||
|
quote = client.call('/quotes', draft)
|
||||||
|
approved_quote(client, quote, [item])
|
||||||
|
paid = client.call('/orders/dev-paid', {'quote_id': quote['id']})
|
||||||
|
return client, paid
|
||||||
|
|
||||||
|
|
||||||
|
def board_order(client, oid):
|
||||||
|
return next(o for o in client.call('/operator/board', operator=True)['orders'] if o['id'] == oid)
|
||||||
|
|
||||||
|
|
||||||
|
def wait_print(client, oid):
|
||||||
|
deadline = time.monotonic() + 120
|
||||||
|
while time.monotonic() < deadline:
|
||||||
|
found = board_order(client, oid)
|
||||||
|
files = found.get('print_files') or []
|
||||||
|
if files and files[0]['status'] in ('ready', 'manual', 'failed'):
|
||||||
|
return found, files[0]
|
||||||
|
time.sleep(1)
|
||||||
|
raise AssertionError('no print file')
|
||||||
|
|
||||||
|
|
||||||
|
def approve_final(client, oid):
|
||||||
|
found, row = wait_print(client, oid)
|
||||||
|
return client.call(f'/operator/orders/{oid}/final-files',
|
||||||
|
{'version': found['version'], 'files': [{'item_index': 0, 'upload_id': str(row['upload_id'])}],
|
||||||
|
'note': 'Arquivo gerado conferido'}, operator=True)['version']
|
||||||
|
|
||||||
|
|
||||||
|
def move(client, oid, version, state, reason=''):
|
||||||
|
return client.call(f'/operator/orders/{oid}/move', {'state': state, 'version': version, 'reason': reason},
|
||||||
|
operator=True)['version']
|
||||||
|
|
||||||
|
|
||||||
|
def to(client, paid, stages, correction=None):
|
||||||
|
oid = paid['id']
|
||||||
|
version = paid.get('version', 0)
|
||||||
|
for stage in stages:
|
||||||
|
if stage == 'final':
|
||||||
|
version = approve_final(client, oid)
|
||||||
|
elif stage == 'cor':
|
||||||
|
version = move(client, oid, version, 'cor', correction)
|
||||||
|
else:
|
||||||
|
version = move(client, oid, version, stage)
|
||||||
|
return oid, version
|
||||||
|
|
||||||
|
|
||||||
|
AURORA = {'name': 'Juliana Martins', 'cnpj': cnpj(31920485), 'zap': '16991234567', 'mail': 'contato@estampariaaurora.com.br'}
|
||||||
|
IPE = {'name': 'Pedro Alves', 'cnpj': cnpj(27450318), 'zap': '16992345678', 'mail': 'pedidos@camisetasipe.com.br'}
|
||||||
|
MARE = {'name': 'Rafael Costa', 'cnpj': cnpj(40871236), 'zap': '16993456789', 'mail': 'studio@maremoda.com.br'}
|
||||||
|
MARIA = {'name': 'Maria Oliveira', 'cnpj': cpf(529982247), 'zap': '16994567890', 'mail': 'maria.oliveira@email.com'}
|
||||||
|
BIANCA = {'name': 'Bianca Rocha', 'cnpj': cpf(318507264), 'zap': '16995678901', 'mail': 'bianca.rocha@email.com'}
|
||||||
|
NORTE = {'name': 'Lucas Ferreira', 'cnpj': cnpj(52640197), 'zap': '16996789012', 'mail': 'compras@graficanorte.com.br'}
|
||||||
|
RIBEIRAO = {'recipient': 'Maria Oliveira', 'street': 'Rua São Sebastião', 'number': '820', 'complement': 'Sala 4',
|
||||||
|
'district': 'Centro', 'city': 'Ribeirão Preto', 'state': 'SP', 'postal_code': '14015040'}
|
||||||
|
|
||||||
|
def order300(customer, palette, metres, delivery):
|
||||||
|
client = Client()
|
||||||
|
client.call('/session')
|
||||||
|
art = sheet(PALETTES[palette], 57, float(metres) * 100, px_per_cm=118)
|
||||||
|
uid = upload_bytes(client, png(art), name='aurora-folha-300dpi.png')
|
||||||
|
put_thumbnail(client, uid, png(art, 520))
|
||||||
|
item = item_spec('file', metres, 100, uid)
|
||||||
|
draft = {'request_key': str(uuid4()), 'items': [item], 'customer': customer,
|
||||||
|
'freight': {'service': 'mock-standard', 'postal_code': delivery['postal_code']}, 'destination': delivery}
|
||||||
|
quote = client.call('/quotes', draft)
|
||||||
|
approved_quote(client, quote, [item])
|
||||||
|
return client, client.call('/orders/dev-paid', {'quote_id': quote['id']})
|
||||||
|
|
||||||
|
# Finalizado, Imprimindo, Fila, Arte conferida, Correção, Arte recebida.
|
||||||
|
client, paid = order(BIANCA, 'rocha', 'file', '1.20', 100)
|
||||||
|
to(client, paid, ['final', 'tra', 'fil', 'imp', 'fin'])
|
||||||
|
client, paid = order(AURORA, 'aurora', 'file', '2.10', 100)
|
||||||
|
to(client, paid, ['final', 'tra', 'fil', 'imp', 'fin'])
|
||||||
|
client, paid = order(MARE, 'mare', 'uvfile', '1.00', 92)
|
||||||
|
to(client, paid, ['final', 'tra', 'fil', 'imp'])
|
||||||
|
client, paid = order(IPE, 'ipe', 'file', '1.60', 100)
|
||||||
|
to(client, paid, ['final', 'tra', 'fil'])
|
||||||
|
client, paid = order(AURORA, 'aurora', 'file', '1.30', 100)
|
||||||
|
to(client, paid, ['final', 'tra', 'fil'])
|
||||||
|
client, paid = order(MARIA, 'mare', 'file', '1.40', 85, RIBEIRAO)
|
||||||
|
to(client, paid, ['tra'])
|
||||||
|
client, paid = order(IPE, 'ipe', 'file', '2.30', 78)
|
||||||
|
to(client, paid, ['cor'], 'A arte ipe-folha.png está com fundo branco. Envie com fundo transparente.')
|
||||||
|
client, paid = order(MARE, 'mare', 'uvfile', '1.10', 92)
|
||||||
|
oid, version = to(client, paid, ['cor'], 'A arte está com 96 DPI. Envie em 300 DPI para não perder nitidez.')
|
||||||
|
fixed = sheet(PALETTES['mare'], 28.5, 110)
|
||||||
|
correction = upload_bytes(client, png(fixed), name='mare-folha-300dpi.png')
|
||||||
|
put_thumbnail(client, correction, png(fixed, 520))
|
||||||
|
client.call(f'/customer/orders/{oid}/corrections',
|
||||||
|
{'version': version, 'files': [{'item_index': 0, 'upload_id': correction}],
|
||||||
|
'note': 'Mandei de novo em 300 DPI.'})
|
||||||
|
client, paid = order(AURORA, 'aurora', 'file', '1.80', 100)
|
||||||
|
wait_print(client, paid['id'])
|
||||||
|
client, paid = order(BIANCA, 'rocha', 'file', '1.00', 100)
|
||||||
|
wait_print(client, paid['id'])
|
||||||
|
client.call(f"/operator/orders/{paid['id']}/contact",
|
||||||
|
{'waiting': True, 'note': 'Confirmar se quer a arte espelhada'}, operator=True)
|
||||||
|
|
||||||
|
# A quote above 50 m waits for the team.
|
||||||
|
client = Client()
|
||||||
|
client.call('/session')
|
||||||
|
art = sheet(PALETTES['norte'], 57, 400)
|
||||||
|
uid = upload_bytes(client, png(art), name='norte-folha.png')
|
||||||
|
put_thumbnail(client, uid, png(art, 520))
|
||||||
|
item = item_spec('file', '55.00', 100, uid)
|
||||||
|
client.call('/quotes', {'request_key': str(uuid4()), 'items': [item], 'customer': NORTE,
|
||||||
|
'freight': {'service': 'pickup'}})
|
||||||
|
|
||||||
|
# A payment that could not become an order, for the Pagamentos tab.
|
||||||
|
with db.connect() as c:
|
||||||
|
c.execute('''INSERT INTO dtf_local.payment_events(id,provider,event_id,reference,status,amount_cents,payload,
|
||||||
|
processed_at,outcome) VALUES(%s,'mercadopago',%s,%s,'approved',4590,%s,now(),%s)''',
|
||||||
|
(uuid4(), f'{random.randint(10**10, 10**11)}:approved', str(uuid4()),
|
||||||
|
Jsonb({'provider': 'mercadopago', 'status': 'approved'}),
|
||||||
|
'refused: amount 4590 does not match the quote total 5190'))
|
||||||
|
c.execute("UPDATE dtf_local.operators SET name='Equipe Compor' WHERE email='operator@example.test'")
|
||||||
|
|
||||||
|
|
||||||
|
# Order #11: a 300 DPI sheet in Arte conferida, delivered by Correios PAC,
|
||||||
|
# for the panel shots (the "approve the final file" step).
|
||||||
|
client, paid = order300(MARIA, 'aurora', '1.00', RIBEIRAO)
|
||||||
|
wait_print(client, paid['id'])
|
||||||
|
to(client, paid, ['tra'])
|
||||||
|
|
||||||
|
# The corrected order back in Arte conferida, where the correction is approved.
|
||||||
|
client = Client()
|
||||||
|
o8 = next(o for o in client.call('/operator/board', operator=True)['orders'] if o['number'] == 8)
|
||||||
|
client.call(f"/operator/orders/{o8['id']}/move", {'state': 'tra', 'version': o8['version'], 'reason': ''}, operator=True)
|
||||||
|
|
||||||
|
# Delivery orders show a real carrier, not the local simulated one.
|
||||||
|
with db.connect() as c:
|
||||||
|
c.execute("""UPDATE dtf_local.orders SET snapshot=jsonb_set(snapshot,'{freight,description}','"Correios PAC"')
|
||||||
|
WHERE jsonb_typeof(snapshot->'destination')='object'""")
|
||||||
|
|
||||||
|
# Users and machines for the Usuários tab (all fictional).
|
||||||
|
admin = Client()
|
||||||
|
textil = admin.call('/operator/machines', {'name': 'Têxtil 1', 'products': ['textil']}, operator=True)['id']
|
||||||
|
admin.call('/operator/machines', {'name': 'UV 1', 'products': ['uv']}, operator=True)
|
||||||
|
for name, email, role, machines in (
|
||||||
|
('Ana Souza', 'ana@dropstar.test', 'admin', []), ('Diego Ramos', 'diego@dropstar.test', 'gestao', []),
|
||||||
|
('Bruno Souza', 'bruno@dropstar.test', 'operador', [textil]), ('Carla Dias', 'carla@dropstar.test', 'vendedor', [])):
|
||||||
|
admin.call('/operator/users', {'name': name, 'email': email, 'role': role, 'password': 'senha-de-exemplo-123',
|
||||||
|
'machines': machines}, operator=True)
|
||||||
|
|
||||||
|
# Pedro's account (Camisetas Ipê): it brings his orders, one in correction, for Minha conta.
|
||||||
|
from tests.smoke_test import register
|
||||||
|
with db.connect() as c:
|
||||||
|
doc = c.execute("SELECT snapshot->'customer'->>'cnpj' AS d FROM dtf_local.orders WHERE number=7").fetchone()['d']
|
||||||
|
pedro = Client(); pedro.call('/session')
|
||||||
|
register(pedro, {**IPE, 'cnpj': doc}, 'senha-de-exemplo-123')
|
||||||
|
|
||||||
|
# Spread the orders over recent days, so Números and the cards look lived-in.
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
now = datetime.now(timezone.utc)
|
||||||
|
plan = {1: (timedelta(days=6), 3), 2: (timedelta(days=4), 4), 3: (timedelta(hours=7), 1), 4: (timedelta(hours=3), 1),
|
||||||
|
5: (timedelta(hours=3.5), 1), 6: (timedelta(hours=2), 1), 7: (timedelta(hours=2.5), 1), 8: (timedelta(hours=3), 1),
|
||||||
|
9: (timedelta(hours=1), 1), 10: (timedelta(minutes=40), 1), 11: (timedelta(hours=2), 1)}
|
||||||
|
with db.connect() as c:
|
||||||
|
for number, (ago, gap) in plan.items():
|
||||||
|
oid = c.execute('SELECT id FROM dtf_local.orders WHERE number=%s', (number,)).fetchone()['id']
|
||||||
|
base = last = now - ago
|
||||||
|
for i, m in enumerate(c.execute('SELECT id FROM dtf_local.movements WHERE order_id=%s ORDER BY id', (oid,)).fetchall()):
|
||||||
|
last = base + timedelta(hours=gap * (i + 1))
|
||||||
|
c.execute('UPDATE dtf_local.movements SET created_at=%s WHERE id=%s', (last, m['id']))
|
||||||
|
c.execute('UPDATE dtf_local.orders SET created_at=%s, updated_at=%s WHERE id=%s', (base, last, oid))
|
||||||
|
print('seeded for the screenshots')
|
||||||
170
docs/guias/telas/shots.mjs
Normal file
@@ -0,0 +1,170 @@
|
|||||||
|
// Screenshots for the guides, from the local stack seeded with fictional
|
||||||
|
// orders (seed.py). Runs in the browser-tests image: node shots.mjs <which>.
|
||||||
|
import {spawn} from 'node:child_process';
|
||||||
|
import {mkdtemp,readFile,writeFile,mkdir} from 'node:fs/promises';
|
||||||
|
import {tmpdir} from 'node:os';
|
||||||
|
|
||||||
|
const OUT='/shots';
|
||||||
|
const which=process.argv[2]||'kanban';
|
||||||
|
const profile=await mkdtemp(tmpdir()+'/dtf-shots-');
|
||||||
|
const chrome=spawn(process.env.CHROME_BIN||'/usr/bin/chromium',[
|
||||||
|
'--headless=new','--lang=pt-BR','--disable-gpu','--no-first-run','--no-sandbox','--hide-scrollbars','--font-render-hinting=none',
|
||||||
|
'--unsafely-treat-insecure-origin-as-secure=http://site,http://kanban',
|
||||||
|
'--remote-debugging-port=0','--user-data-dir='+profile,'about:blank'],{stdio:['ignore','ignore','pipe']});
|
||||||
|
const pause=ms=>new Promise(r=>setTimeout(r,ms));
|
||||||
|
async function waitFor(fn,what,timeout=30000){const end=Date.now()+timeout;while(Date.now()<end){try{if(await fn())return;}catch{}await pause(200);}throw new Error('Timeout: '+what);}
|
||||||
|
class Page{
|
||||||
|
constructor(ws){this.ws=ws;this.n=0;this.p=new Map();ws.onmessage=e=>{const d=JSON.parse(e.data);if(d.id&&this.p.has(d.id)){const x=this.p.get(d.id);this.p.delete(d.id);d.error?x.j(d.error):x.r(d.result);}};}
|
||||||
|
call(m,params={}){return new Promise((r,j)=>{const id=++this.n;this.p.set(id,{r,j});this.ws.send(JSON.stringify({id,method:m,params}));});}
|
||||||
|
async eval(e){const res=await this.call('Runtime.evaluate',{expression:e,awaitPromise:true,returnByValue:true});if(res.exceptionDetails)throw new Error(JSON.stringify(res.exceptionDetails).slice(0,400));return res.result.value;}
|
||||||
|
async size(w,h){await this.call('Emulation.setDeviceMetricsOverride',{width:w,height:h,deviceScaleFactor:2,mobile:false});await pause(300);}
|
||||||
|
async rect(selector,pad=0){return this.eval(`(()=>{const el=${selector.startsWith('(')?selector:`document.querySelector(${JSON.stringify(selector)})`};
|
||||||
|
const r=el.getBoundingClientRect();return {x:Math.max(0,r.left-${pad})+scrollX,y:Math.max(0,r.top-${pad})+scrollY,width:r.width+2*${pad},height:r.height+2*${pad}};})()`);}
|
||||||
|
async shot(name,clip){
|
||||||
|
const res=await this.call('Page.captureScreenshot',{format:'png',captureBeyondViewport:true,...(clip?{clip:{...clip,scale:1}}:{})});
|
||||||
|
await writeFile(`${OUT}/${name}.png`,Buffer.from(res.data,'base64'));console.log('shot',name,clip?Math.round(clip.width)+'x'+Math.round(clip.height):'page');
|
||||||
|
}
|
||||||
|
async el(name,selector,pad=0){await pause(250);await this.shot(name,await this.rect(selector,pad));}
|
||||||
|
}
|
||||||
|
let port;
|
||||||
|
await waitFor(async()=>{port=Number((await readFile(profile+'/DevToolsActivePort','utf8')).split('\n')[0]);return port;},'chrome');
|
||||||
|
async function open(url,w=1440,h=1000){
|
||||||
|
const tab=await (await fetch(`http://localhost:${port}/json/new?about:blank`,{method:'PUT'})).json();
|
||||||
|
const ws=new WebSocket(tab.webSocketDebuggerUrl);await new Promise((r,j)=>{ws.onopen=r;ws.onerror=j;});
|
||||||
|
const p=new Page(ws);await p.call('Runtime.enable');await p.call('Page.enable');await p.size(w,h);
|
||||||
|
await p.call('Emulation.setLocaleOverride',{locale:'pt-BR'}).catch(()=>{});
|
||||||
|
await p.call('Network.enable').catch(()=>{});await p.call('Network.setUserAgentOverride',{userAgent:'Mozilla/5.0 Chrome/130 Safari/537.36',acceptLanguage:'pt-BR'}).catch(()=>{});
|
||||||
|
await p.call('Page.navigate',{url});await waitFor(()=>p.eval('document.readyState==="complete"'),'load '+url);await pause(800);return p;
|
||||||
|
}
|
||||||
|
await mkdir(OUT,{recursive:true});
|
||||||
|
|
||||||
|
try{
|
||||||
|
if(which==='kanban'){
|
||||||
|
const k=await open('http://kanban/',1440,1000);
|
||||||
|
await waitFor(()=>k.eval('!document.getElementById("login").hidden'),'login form');
|
||||||
|
await k.el('login','#login',24);
|
||||||
|
await k.eval(`(()=>{email.value=${JSON.stringify(process.env.OPERATOR_EMAIL||'operator@example.test')};password.value=${JSON.stringify(process.env.OPERATOR_PASSWORD||'local-operator-only')};
|
||||||
|
document.getElementById('login').requestSubmit();})()`);
|
||||||
|
await waitFor(()=>k.eval('typeof board!=="undefined"&&!!board&&board.orders.length>0'),'board');
|
||||||
|
// No refresh while shooting: the timer would repaint over the shots.
|
||||||
|
// No refresh while shooting: the timer would repaint over the shots.
|
||||||
|
await k.eval(`(()=>{window.load=async()=>{};})()`);
|
||||||
|
await pause(1500);
|
||||||
|
await k.shot('quadro',{x:0,y:0,width:1440,height:700});
|
||||||
|
const id=n=>`board.orders.find(o=>o.number===${n}).id`;
|
||||||
|
// The print queue column, top part.
|
||||||
|
await k.el('fila','(document.querySelector(\'section.col[data-state="fil"]\'))',0).catch(e=>console.log('fila',e.message));
|
||||||
|
// Panel of an order waiting for its final file.
|
||||||
|
await k.size(1440,1900);
|
||||||
|
await k.eval(`document.querySelector('[data-card="'+${id(11)}+'"]').click()`);
|
||||||
|
await waitFor(()=>k.eval(`!!document.querySelector('[data-order="'+${id(11)}+'"]')`),'panel');await pause(1200);
|
||||||
|
await k.shot('painel',{...(await k.rect('#panel')),height:900});
|
||||||
|
await k.el('arquivo-final','#panel .nextstep.lead',0);
|
||||||
|
await k.eval(`document.querySelector('#panel .more').click()`);await pause(300);
|
||||||
|
await k.shot('menu',{...(await k.rect('#panel')),height:520});
|
||||||
|
await k.eval(`document.body.click()`);
|
||||||
|
// An order in correction, and one whose correction came back.
|
||||||
|
for(const [n,name] of [[7,'correcao'],[8,'correcao-recebida'],[10,'contato']]){
|
||||||
|
await k.eval(`closePanel&&closePanel()`).catch(()=>{});await pause(300);
|
||||||
|
await k.eval(`document.querySelector('[data-card="'+${id(n)}+'"]').click()`);
|
||||||
|
await waitFor(()=>k.eval(`!!document.querySelector('[data-order="'+${id(n)}+'"]')`),'panel '+n);await pause(1200);
|
||||||
|
if(name==='correcao-recebida')await k.el(name,'#panel .nextstep.lead',0);
|
||||||
|
else if(name==='contato')await k.el(name,'#panel .callout.contact',0);
|
||||||
|
else await k.shot(name,{...(await k.rect('#panel')),height:350});
|
||||||
|
}
|
||||||
|
await k.eval(`closePanel&&closePanel()`).catch(()=>{});
|
||||||
|
await k.size(1440,1000);
|
||||||
|
// Quotes, payments, numbers.
|
||||||
|
await k.eval(`document.querySelector('[data-tab="quotes"]').click()`);await pause(1500);
|
||||||
|
await k.eval(`document.querySelector('#quote-list button, #quote-list [data-quote], #quote-list li')?.click()`).catch(()=>{});await pause(1500);
|
||||||
|
await k.shot('cotacoes',{x:0,y:0,width:1440,height:1000});
|
||||||
|
await k.eval(`document.querySelector('[data-tab="payments"]').click()`);await pause(1500);
|
||||||
|
await k.shot('pagamentos',{x:0,y:0,width:1440,height:300});
|
||||||
|
await k.eval(`document.querySelector('[data-tab="stats"]').click()`);await pause(2000);
|
||||||
|
await k.shot('numeros',{x:0,y:0,width:1440,height:900});
|
||||||
|
// Users and the edit dialog.
|
||||||
|
await k.eval(`document.querySelector('[data-tab="users"]').click()`);await pause(1500);
|
||||||
|
await k.el('usuarios','#tab-users',0);
|
||||||
|
await k.eval(`[...document.querySelectorAll('#users-list tr')].find(tr=>tr.textContent.includes('Bruno')).querySelector('button').click()`);await pause(600);
|
||||||
|
await k.el('usuario-editar','.modal-box',0);
|
||||||
|
await k.eval(`document.querySelector('.modal').remove()`);
|
||||||
|
// Integrações as in production, with fictional values; the folder as on the print room's computer.
|
||||||
|
await k.eval(`document.querySelector('[data-tab="integrations"]').click()`);await pause(1200);
|
||||||
|
await k.eval(`(()=>{window.syncFolder=async()=>{};window.load=async()=>{};
|
||||||
|
const now=new Date(),at=h=>new Date(now-h*3600e3).toISOString();
|
||||||
|
board.tiny={configured:true,connected:true,connected_by:'tiny@dropstar.test',orders_enabled:true,offline:true,connected_at:at(72),renewed_at:at(2)};
|
||||||
|
board.providers={...board.providers,payment:'mercadopago',
|
||||||
|
freight:{services:{jadlog:'Jadlog',pac:'Correios PAC',sedex:'Correios SEDEX'},box_cm:['63','15.5','15.5'],production_days:1,
|
||||||
|
base_kg:'0.3',per_metre_kg:'0.075',cubage_kg_m3:'300',cubed_kg:'4.541',metres_per_box:'60'},
|
||||||
|
mail:{adapter:'smtp',pending:0,last_sent:at(1),from:'nao-responda@dropstardtf.com.br'},
|
||||||
|
backup:{last_ok:new Date(now.getFullYear(),now.getMonth(),now.getDate(),3,0).toISOString(),bytes:418000,failed:null,requested:false}};
|
||||||
|
FOLDER.mode='folder';FOLDER.handle={name:'FlexiPRINT'};FOLDER.granted=true;FOLDER.when='rec';FOLDER.error='';FOLDER.status='';
|
||||||
|
FOLDER.saved=new Map(Array.from({length:12},(_,i)=>['u'+i,{place:'queue'}]));FOLDER.last=new Date(now-25*60e3);
|
||||||
|
renderIntegrations();})()`);
|
||||||
|
await pause(600);
|
||||||
|
await k.el('integracoes','#integrations',0);
|
||||||
|
await k.eval(`document.querySelector('#folder-card .integ-more').click()`);await pause(400);
|
||||||
|
await k.el('pasta','#folder-card',0);
|
||||||
|
await k.eval(`(()=>{FOLDER.granted=false;OPEN_INTEG.clear();paintFolder();})()`);await pause(400);
|
||||||
|
await k.el('pasta-liberar','#folder-card',0);
|
||||||
|
await k.el('aba-aviso','[data-tab="integrations"]',10);
|
||||||
|
}
|
||||||
|
if(which==='site'){
|
||||||
|
// Minha conta: the overview, and an order waiting for a correction.
|
||||||
|
if(process.argv[3]!=='cart'){const c=await open('http://site/conta/entrar',1440,1000);
|
||||||
|
await waitFor(()=>c.eval('!!document.getElementById("login")'),'portal');
|
||||||
|
await c.eval(`(()=>{document.getElementById('email').value='pedidos@camisetasipe.com.br';
|
||||||
|
document.getElementById('password').value='senha-de-exemplo-123';document.getElementById('login').requestSubmit();})()`);
|
||||||
|
await pause(2500);
|
||||||
|
await c.call('Page.navigate',{url:'http://site/conta'});await pause(2500);
|
||||||
|
await c.eval(`(()=>{for(const el of document.querySelectorAll('body *'))if(el.children.length===0&&el.textContent.includes('Ambiente de desenvolvimento local'))el.closest('div,p,section').style.display='none';window.scrollTo(0,0);})()`);await pause(400);
|
||||||
|
await c.shot('conta',{x:0,y:0,width:1440,height:540});
|
||||||
|
const seven=await c.eval(`fetch('/api/customer/orders?page=1&size=10').then(r=>r.json()).then(d=>(d.items.find(i=>i.number===7)||d.items.find(i=>i.state==='cor')).id)`);
|
||||||
|
await c.call('Page.navigate',{url:'http://site/conta/pedidos?order='+seven});await pause(2500);
|
||||||
|
await c.eval(`(()=>{for(const el of document.querySelectorAll('body *'))if(el.children.length===0&&el.textContent.includes('Ambiente de desenvolvimento local'))el.closest('div,p,section').style.display='none';window.scrollTo(0,0);})()`);await pause(400);
|
||||||
|
await c.shot('pedido-correcao',{x:0,y:0,width:1440,height:960});}
|
||||||
|
// The cart: artworks added for real, then the customer's details and the delivery options.
|
||||||
|
const s=await open('http://site/',1440,1000);
|
||||||
|
await waitFor(()=>s.eval(`typeof window.dtfCheckout==="function"&&!!document.querySelector('[data-modo="avulsa"]')`),'site');
|
||||||
|
await s.eval(`document.querySelector('[data-modo="avulsa"]').click()`);await pause(800);
|
||||||
|
await s.eval(`(async()=>{
|
||||||
|
const make=async(name,w,h,draw)=>{const c=document.createElement('canvas');c.width=w;c.height=h;const x=c.getContext('2d');draw(x,w,h);
|
||||||
|
return new File([await new Promise(r=>c.toBlob(r,'image/png'))],name,{type:'image/png'});};
|
||||||
|
const files=[await make('logo-frente.png',2362,1417,(x,w,h)=>{x.fillStyle='#F26B1D';x.beginPath();x.roundRect(0,0,w,h,120);x.fill();
|
||||||
|
x.fillStyle='#FFD23F';x.beginPath();x.arc(w*.24,h/2,h*.32,0,7);x.fill();x.fillStyle='#fff';x.font='bold '+(h*.26)+'px sans-serif';x.fillText('AURORA',w*.44,h*.6);}),
|
||||||
|
await make('escudo.png',1181,1181,(x,w,h)=>{x.fillStyle='#1B998B';x.beginPath();x.arc(w/2,h/2,w/2,0,7);x.fill();x.fillStyle='#fff';
|
||||||
|
x.font='bold '+(h*.2)+'px sans-serif';x.textAlign='center';x.fillText('ESCUDO',w/2,h*.57);}),
|
||||||
|
await make('patrocinio.png',2835,472,(x,w,h)=>{x.fillStyle='#E84855';x.fillRect(0,0,w,h);x.fillStyle='#fff';x.font='bold '+(h*.5)+'px sans-serif';
|
||||||
|
x.textAlign='center';x.fillText('PATROCÍNIO',w/2,h*.68);})];
|
||||||
|
const dt=new DataTransfer();files.forEach(f=>dt.items.add(f));
|
||||||
|
const inp=document.getElementById('inp');inp.files=dt.files;inp.dispatchEvent(new Event('change',{bubbles:true}));})()`);
|
||||||
|
await waitFor(()=>s.eval('artes.length===3&&artes.every(a=>a.src)'),'artworks measured',30000);
|
||||||
|
for(const [i,cm,q] of [[0,20,4],[1,10,8],[2,24,3]]){
|
||||||
|
await s.eval(`(()=>{const set=(sel,v)=>{const el=document.querySelectorAll(sel)[${i}];el.value=v;el.dispatchEvent(new Event('change',{bubbles:true}));};
|
||||||
|
set('[data-cm]',${cm});set('[data-q]',${q});})()`);await pause(500);
|
||||||
|
}
|
||||||
|
await pause(1200);
|
||||||
|
await s.eval(`(()=>{const c=document.getElementById('cienteOk');if(c&&!c.checked){c.checked=true;c.dispatchEvent(new Event('change',{bubbles:true}));}})()`);
|
||||||
|
await waitFor(()=>s.eval('!!itemAtual&&itemPodeEnviar(itemAtual)'),'item ready for the cart',60000);
|
||||||
|
await s.eval(`document.getElementById('bAdd').click()`);
|
||||||
|
await waitFor(()=>s.eval('location.pathname==="/carrinho"'),'cart page',20000);
|
||||||
|
await waitFor(()=>s.eval(`document.getElementById('carr').innerText.includes('Arquivos enviados')&&!document.getElementById('carr').innerText.includes('verificando')`),'uploads done',180000);
|
||||||
|
await s.eval(`(()=>{const g=id=>document.getElementById(id);const fill=(id,v)=>{const el=g(id);el.value=v;el.dispatchEvent(new Event('input',{bubbles:true}));};
|
||||||
|
fill('fNome','Juliana Martins');fill('fCnpj','31920485000165');fill('fZap','16991234567');fill('fMail','contato@estampariaaurora.com.br');
|
||||||
|
entrega.tipo='frete';entrega.cep='14015040';g('cepIn').value='14015-040';
|
||||||
|
entrega.opcoes=[{service:'pac',description:'Correios PAC',days:7,total_cents:2183},{service:'jadlog',description:'Jadlog',days:5,total_cents:2690},
|
||||||
|
{service:'sedex',description:'Correios SEDEX',days:3,total_cents:4417}];
|
||||||
|
entrega.servico='pac';entrega.valor=21.83;entrega.dias=7;entrega.cotado=true;
|
||||||
|
entrega.end={nome:'Juliana Martins',rua:'Rua São Sebastião',num:'820',comp:'Sala 4',bairro:'Centro',cidade:'Ribeirão Preto',uf:'SP'};
|
||||||
|
for(const [id,k] of [['eNome','nome'],['eRua','rua'],['eNum','num'],['eComp','comp'],['eBairro','bairro'],['eCidade','cidade'],['eUf','uf']])g(id).value=entrega.end[k];
|
||||||
|
pintaFretes();pintaEntrega();if(typeof pintaPedido==='function')pintaPedido();window.scrollTo(0,0);})()`);
|
||||||
|
await pause(800);
|
||||||
|
const h=await s.eval(`Math.ceil(document.getElementById('fretes').getBoundingClientRect().bottom+28)`);
|
||||||
|
await s.shot('carrinho',{x:0,y:0,width:1440,height:h});
|
||||||
|
// The order confirmation e-mail, as the customer's mail app shows it.
|
||||||
|
const m=await open('file:///g/email-pedido.html',720,1000);
|
||||||
|
const mh=await m.eval('Math.ceil(document.body.scrollHeight)');
|
||||||
|
await m.shot('email-pedido',{x:0,y:0,width:720,height:mh});
|
||||||
|
}
|
||||||
|
}catch(e){console.error(e);process.exitCode=1;}
|
||||||
|
finally{chrome.kill();}
|
||||||
@@ -1,8 +1,11 @@
|
|||||||
# Same pinned base as deploy/Dockerfile.api, so the integration suite exercises
|
# Same pinned base as deploy/Dockerfile.api, so the integration suite exercises
|
||||||
# the image that ships rather than a different one.
|
# the image that ships rather than a different one.
|
||||||
FROM python:3.12-slim@sha256:2f17fc044b579bab302c2e8054d3a686e2cb9a83de48e70534b94cd8ebbe06a9
|
FROM python:3.12-slim@sha256:2f17fc044b579bab302c2e8054d3a686e2cb9a83de48e70534b94cd8ebbe06a9
|
||||||
|
# pg_dump and age are for the database backup (ops/db_backup.py). Debian 13
|
||||||
|
# ships PostgreSQL 17, the server's major version, which pg_dump must match.
|
||||||
RUN apt-get update \
|
RUN apt-get update \
|
||||||
&& apt-get upgrade -y \
|
&& apt-get upgrade -y \
|
||||||
|
&& apt-get install -y --no-install-recommends postgresql-client-17 age \
|
||||||
&& rm -rf /var/lib/apt/lists/*
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
COPY infra/requirements.txt infra/requirements.lock /app/infra/
|
COPY infra/requirements.txt infra/requirements.lock /app/infra/
|
||||||
|
|||||||
@@ -10,5 +10,6 @@ RUN apk upgrade --no-cache
|
|||||||
ENV WEB_INDEX=index.html
|
ENV WEB_INDEX=index.html
|
||||||
COPY --from=policy /build/default.conf.template /etc/nginx/templates/default.conf.template
|
COPY --from=policy /build/default.conf.template /etc/nginx/templates/default.conf.template
|
||||||
ENV S3_PUBLIC_ENDPOINT=http://localhost:9000
|
ENV S3_PUBLIC_ENDPOINT=http://localhost:9000
|
||||||
COPY web/ /usr/share/nginx/html/
|
# The HTML from the policy stage, with every asset address versioned.
|
||||||
|
COPY --from=policy /build/web/ /usr/share/nginx/html/
|
||||||
|
|
||||||
|
|||||||
@@ -5,10 +5,12 @@ TCPSocket 3310
|
|||||||
TCPAddr 0.0.0.0
|
TCPAddr 0.0.0.0
|
||||||
MaxThreads 2
|
MaxThreads 2
|
||||||
MaxQueue 8
|
MaxQueue 8
|
||||||
StreamMaxLength 128M
|
StreamMaxLength 2000M
|
||||||
MaxFileSize 128M
|
MaxFileSize 2000M
|
||||||
MaxScanSize 256M
|
MaxScanSize 4000M
|
||||||
MaxScanTime 120000
|
MaxScanTime 900000
|
||||||
|
ReadTimeout 900
|
||||||
|
CommandReadTimeout 900
|
||||||
AlertExceedsMax yes
|
AlertExceedsMax yes
|
||||||
AlertEncrypted yes
|
AlertEncrypted yes
|
||||||
ScanPDF yes
|
ScanPDF yes
|
||||||
|
|||||||
@@ -1,4 +1,7 @@
|
|||||||
"""Compile the gateway configuration: hash any trusted inline script for the CSP.
|
"""Compile the gateway configuration and version the Site's assets.
|
||||||
|
|
||||||
|
Inline scripts are hashed for the CSP; local scripts and stylesheets get a
|
||||||
|
content hash in their address.
|
||||||
|
|
||||||
The Site's behaviour now lives in separate files, so normally there is nothing to
|
The Site's behaviour now lives in separate files, so normally there is nothing to
|
||||||
hash and the policy is simply script-src 'self' — no allowlist to get wrong. The
|
hash and the policy is simply script-src 'self' — no allowlist to get wrong. The
|
||||||
@@ -12,6 +15,20 @@ from pathlib import Path
|
|||||||
import re
|
import re
|
||||||
|
|
||||||
root = Path('/build')
|
root = Path('/build')
|
||||||
|
|
||||||
|
# Every local script and stylesheet is addressed by its content, so a release
|
||||||
|
# can never pair new HTML with an old cached file: the proxy in front of the
|
||||||
|
# stack caches assets for hours, and a new index.html calling an old script
|
||||||
|
# broke the Site (2026-09-28). The HTML itself is served no-cache.
|
||||||
|
def versioned(match):
|
||||||
|
attribute, path = match.group(1), match.group(2)
|
||||||
|
digest = hashlib.sha256((root / 'web' / path.lstrip('/')).read_bytes()).hexdigest()[:12]
|
||||||
|
return f'{attribute}="{path}?v={digest}"'
|
||||||
|
|
||||||
|
for html in (root / 'web').glob('*.html'):
|
||||||
|
text = re.sub(r'\b(src|href)="(/[\w./-]+\.(?:js|css))(?:\?[^"]*)?"', versioned, html.read_text())
|
||||||
|
html.write_text(text)
|
||||||
|
|
||||||
hashes = []
|
hashes = []
|
||||||
for html in (root / 'web').glob('*.html'):
|
for html in (root / 'web').glob('*.html'):
|
||||||
for attributes, script in re.findall(r'<script\b([^>]*)>(.*?)</script>', html.read_text(), re.S | re.I):
|
for attributes, script in re.findall(r'<script\b([^>]*)>(.*?)</script>', html.read_text(), re.S | re.I):
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ server {
|
|||||||
add_header Referrer-Policy no-referrer always;
|
add_header Referrer-Policy no-referrer always;
|
||||||
add_header X-Frame-Options DENY always;
|
add_header X-Frame-Options DENY always;
|
||||||
add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
|
add_header Permissions-Policy "camera=(), 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}; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'" 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;
|
||||||
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;
|
||||||
@@ -19,6 +19,14 @@ server {
|
|||||||
proxy_set_header X-Forwarded-For $remote_addr;
|
proxy_set_header X-Forwarded-For $remote_addr;
|
||||||
client_max_body_size 2m;
|
client_max_body_size 2m;
|
||||||
}
|
}
|
||||||
|
# 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)/?$ {
|
||||||
|
try_files /index.html =404;
|
||||||
|
}
|
||||||
|
# The customer's area: one page, which shows the right part for each address.
|
||||||
|
location ~ ^/conta(/(entrar|pedidos|dados|redefinir))?/?$ {
|
||||||
|
try_files /portal.html =404;
|
||||||
|
}
|
||||||
location / { try_files $uri $uri/ =404; }
|
location / { try_files $uri $uri/ =404; }
|
||||||
}
|
}
|
||||||
server {
|
server {
|
||||||
|
|||||||
@@ -28,9 +28,9 @@ botocore==1.38.46 \
|
|||||||
# via
|
# via
|
||||||
# boto3
|
# boto3
|
||||||
# s3transfer
|
# s3transfer
|
||||||
certifi==2026.7.22 \
|
certifi==2026.10.19 \
|
||||||
--hash=sha256:62f22742b58a1a33014a2b6b706588a8d7e2a88ae7bd1a6ebe8c992928483775 \
|
--hash=sha256:035c1e85572b141bf1c3a3eff0e33a8eb74917522f2559075ff8d2fea780a1ae \
|
||||||
--hash=sha256:741e2c3b351ddf169a738da9f2c048608ff7f2c5cc02f1ebc6b118bb090d5d55
|
--hash=sha256:42d35340cc5b9ba78e818ddbff0c5b1c2b779de448a340fd1b989f5fa8670e1b
|
||||||
# via
|
# via
|
||||||
# httpcore
|
# httpcore
|
||||||
# httpx
|
# httpx
|
||||||
@@ -295,94 +295,90 @@ pikepdf==10.13.0.post1 \
|
|||||||
--hash=sha256:f7962a75cf22d0d683b49ab19b8966e94dc7014d9aa6806f3c0d2b37fb9ae607 \
|
--hash=sha256:f7962a75cf22d0d683b49ab19b8966e94dc7014d9aa6806f3c0d2b37fb9ae607 \
|
||||||
--hash=sha256:fb05fb7b42d85754219b55111aa61beff4e48da56069e971de1e5aca380c0ac1
|
--hash=sha256:fb05fb7b42d85754219b55111aa61beff4e48da56069e971de1e5aca380c0ac1
|
||||||
# via -r infra/requirements.txt
|
# via -r infra/requirements.txt
|
||||||
pillow==12.3.0 \
|
pillow==13.0.0 \
|
||||||
--hash=sha256:00808c5e14ef63ac5161091d242999076604ff74b883423a11e5d7bbb38bf756 \
|
--hash=sha256:02464da86f561f410e13b061ec37c3068a9cb557a095494157742d07b3c24a27 \
|
||||||
--hash=sha256:04f01d28a6aaff387bf842a13be313df23ba0597a44f1a976c9feb3c6ff4711a \
|
--hash=sha256:04a63720f79e22fd54d897c233a68314c50ca0603360f54ce2bd5db8f0f43782 \
|
||||||
--hash=sha256:06ff022112bc9cbf83b60f8e028d94ad87b60621706487e65f673de61610ab59 \
|
--hash=sha256:05cd2cd39055d0b9650060e4513ef4a9a0aea870083950bd046a0d6490f93a22 \
|
||||||
--hash=sha256:0740a512dc522224c77d9aa5a8d70d8b7d73fb91f2c21125d8d025d3b8990e45 \
|
--hash=sha256:06903aac074d00c988e77a1fc435286dc498506d4ca8d6f69df9babddf4ecc15 \
|
||||||
--hash=sha256:0847a763afefb695bc912d7c131e7e0632d4edc1d8698f58ddabec8e46b8b6d3 \
|
--hash=sha256:08b826a9bf1265c76de04a42061d61ea6b109418b7826f28ff1ecdfaa26c5502 \
|
||||||
--hash=sha256:0dd2064cbc55aaec028ef5fbb60fa47bb6c3e7918e07ff17935284b227a9d2df \
|
--hash=sha256:0d1a9cf7bc6917538b20f8d06b9ab2147e542f68849e96fc58eb66bdf6acc692 \
|
||||||
--hash=sha256:0feb2e9d6ad6c9e3c06effe9d00f3f1e618a6643273576b016f591e9315a7139 \
|
--hash=sha256:10b5019883c98f1dd819ca48ffc6f33a91cee04948fe637c605f4345c7cafd6f \
|
||||||
--hash=sha256:10e41f0fbf1eec8cfd234b8fe17a4caac7c9d0db4c204d3c173a8f9f6ef3232b \
|
--hash=sha256:12b0fa15879fe5a9d9eebe66e4e2d74128a773b1a4448010c9c714f45e04b9d8 \
|
||||||
--hash=sha256:1182d52bc2d5e5d7d0949503aa7e36d12f42205dc287e4883f407b1988820d39 \
|
--hash=sha256:12fbb851cf323cc19aac3eea1df5ad17b57e91e9fe3cfd06100dba7bb8208c13 \
|
||||||
--hash=sha256:164b31cd1a0490ab6efae01aa5df49da7061be0af1b30e035b6e9a1bfe34ee6e \
|
--hash=sha256:149a1c323ba366f90b48e6f1a6db6582eb50512df374588de56fc909abc0f0f3 \
|
||||||
--hash=sha256:1657923d2d45afb66526e5b933e5b3052e6bdea196c90d3abb2424e18c77dae8 \
|
--hash=sha256:19b66ca0a4d25cc0200b381ce824c7ea090db61427315e73cfb05dbf1b35c369 \
|
||||||
--hash=sha256:186941b6aef820ad110fb01fb06eb925374dc3a21b17e37ec9a53b250c6fe2d1 \
|
--hash=sha256:1c774b9c0ba0d0b356f71530677b39028878a2cae5a93e0a13779cfd17120f88 \
|
||||||
--hash=sha256:1cca606cd25738df4ed873d5ad46bbdb3d83b5cbca291f6b4ff13a4df6b0bbe8 \
|
--hash=sha256:20722cd5375533ad754053363a80b8fb30c79d37930a6f7228030e237ce3bd5d \
|
||||||
--hash=sha256:21900ce7ba264168cd50defae43cd75d25c833ad4ad6e73ffc5596d12e25ac89 \
|
--hash=sha256:20822140c9a2ba9c5e42df342b0a892ab2e102fc0e3db967a133bb9ce3f898bb \
|
||||||
--hash=sha256:236ff70b9312fb68943c703aa842ca6a758abfa45ac187a5e7c1452e96ef72b5 \
|
--hash=sha256:21c32061a5512dc13f87cc7303e120e4d77c2f70df89a35af0e3ce246e5ac57f \
|
||||||
--hash=sha256:23aceaa007d6172b02c277f0cd359c79492bbb14f7072b4ede9fbcaf20648130 \
|
--hash=sha256:2310e2adfc13c6d457d7d0f2ffdd5c56a74a317650cf765887df8d515a647ac0 \
|
||||||
--hash=sha256:23d27a3e0307ec2244cc51e7287b919aa68d097504ebe19df4e76a98a3eea5bd \
|
--hash=sha256:23edf4ec4b6f4f240e8df6e4985e9ee2ced86474632433e55fb1e2548744bf40 \
|
||||||
--hash=sha256:24870b09b224f7ae3c39ed07d10e819d06f8720bc551847b1d623832b5b0e28d \
|
--hash=sha256:2d50500a4a3bc6469adcdb319cf05d688b08ca3bf0f22a05339f3b25b433a599 \
|
||||||
--hash=sha256:251bf95b67017e27b13d82f5b326234ca62d70f9cf4c2b9032de2358a3b12c7b \
|
--hash=sha256:2e31c4e68cffd7b1f116127626813b82fcba19edf6b940a7b0c266d6484d0055 \
|
||||||
--hash=sha256:25b9b82bb22e6e2b3cd07b39c68b7b862001226cb3dff7130d1cb914121b39ed \
|
--hash=sha256:34fb3db1149c879343861831728c243c432d4a5afc8f1878ca7612ef8de2a033 \
|
||||||
--hash=sha256:28ce87c5ab450a9dd970b52e5aca5fe63ed432d18a2eaddd1979a00a1ba24ace \
|
--hash=sha256:37290fbef0c73e2d51d594eb78fded7dc7170d1c3ad0a890269e6fd8c8c4e061 \
|
||||||
--hash=sha256:300557495eb45ebb8aec96c2da9c4be642fbf7cd937278b4013ba894ea8eb0eb \
|
--hash=sha256:405be6058e206a86fedce2f715ecc2343f94072d7925251632dffa2c05f70dca \
|
||||||
--hash=sha256:30f2aa603c41533cc25c05acd0da21636e84a315768feb631c937177db558931 \
|
--hash=sha256:40a266371ece581e5de13b6635ef78d7487824af80561b6ca27694a88c19bc0f \
|
||||||
--hash=sha256:331b624368d4f1d069149002f25f44bc61c8919ce8ddb3c45bdad8f6e2d89510 \
|
--hash=sha256:42d63be3af4f9b951b199b0a9d23365d37ab14687e6d77b74940432c8515c4ca \
|
||||||
--hash=sha256:37d6d0a00072fd2948eb22bce7e1475f34569d90c87c59f7a2ec59541b77f7a6 \
|
--hash=sha256:44629d4498c9cb6b2051806155f22141df0d8a929c56134b166655232dfb2f8c \
|
||||||
--hash=sha256:37dc8f7bbb66efe481bb60defacef820c950c24713fb44962ed6aa2a50966de1 \
|
--hash=sha256:49c12af515073e9bf511e4ef736743bf70d531a643668722279314b937742ba4 \
|
||||||
--hash=sha256:3b8182a766685eaa002637e28b4ec8d6b18819a0c71f579bf0dbaa5830297cce \
|
--hash=sha256:4a25756244bdcce3b50580baadf320fa48297f0eeb8e114ba64139a40d4d0fc8 \
|
||||||
--hash=sha256:3edce1d53195db527e0191f84b71d02022de0540bf43a16ed734ed7537b07385 \
|
--hash=sha256:4bd024d567eca931b668978d672dba914d4b8e2628e2c3073a2ad178de8a2620 \
|
||||||
--hash=sha256:446c34dcc4324b084a53b705127dc15717b22c5e140ae0a3c38349d4efec071e \
|
--hash=sha256:4f8db54177035a2b5f717f94475b74907e12a96dc74f6d487f3966b0a4694071 \
|
||||||
--hash=sha256:4998562bf62a445225f22e07c896bb04b35b1b1f2eb6d760584c9c51d7a5f78c \
|
--hash=sha256:51ebb529fc5e8abdd55302f6c3f8943037348ec2384329a3e55677f69ae2fdfc \
|
||||||
--hash=sha256:4b0a7fe987b14c31ebda6083f74f22b561fd3739bc0ac51e019622e3d72668c7 \
|
--hash=sha256:567f20f1c75897d7663830da6ea8af719e03d712b1d9ee7f813319f9ece42e5a \
|
||||||
--hash=sha256:4e8c2a84d977f50b9daed6eeaf3baef67d00d5d74d932288f02cb94518ee3ace \
|
--hash=sha256:5933fcea5a5ba64c686f55c886a115cbfd92f2900460784a1e79909fdbafd7b6 \
|
||||||
--hash=sha256:4f883547d4b7f0495ebe7056b0cc2aea76094e7a4abc8e933540f3271df27d9c \
|
--hash=sha256:5bdb38ba220b61b4ec31dd1046dea6b016d3c6850a23f43ed8b58332b2fc668e \
|
||||||
--hash=sha256:514435a37670e3e5e08f3945b68718b6ed329bb84367777e16f9f4dfe1e61a0f \
|
--hash=sha256:5f56499c1a74d2b862beb0c33b8016f99d095858455df9d21583bbbc1c15b582 \
|
||||||
--hash=sha256:53aa02d20d10c3d814d536aa4e5ac9b84ca0ff5a88377963b085ad6822f93e64 \
|
--hash=sha256:67871a13cf47275201553b536c025da777f997fa562a19eb798af4ad4b97c18f \
|
||||||
--hash=sha256:5594fc43d548a7ed94949d139aa1341b270f1863f11cfd37f5a6c8b778a6b67f \
|
--hash=sha256:67c8d44ad89fa7eb88de5d6ef6199b1e03dd24974f85a67639fc8badb801fe79 \
|
||||||
--hash=sha256:571b9fcb07b97ef3a492028fb3d2dc0993ca23a06138b0315286566d29ef718a \
|
--hash=sha256:6a0920cb55df5a4d3f6862964908078c0bd59332bdd1bcd20d14e8c70ef27cc5 \
|
||||||
--hash=sha256:57b3d78c95ba9059768b10e28b813002261d3f3dfc55cc48b0c988f625175827 \
|
--hash=sha256:6bce6a29c3898191f4c9998e4d4e8f69790caeabde46e54da4bc235ce5bde683 \
|
||||||
--hash=sha256:5afb51d599ea772b8365ae807ae557f18bccfe46ab261fd1c2a9ed700fc6eb17 \
|
--hash=sha256:6f38f3f885a09cafc93fd667b1173a92f379e43785d635e7983c893f0da319fb \
|
||||||
--hash=sha256:6b02afb9b97f65fbca5f31db6a2a3ba21aa93030225f150fa3f249717e938fb4 \
|
--hash=sha256:73ee25cf8cf8b75d5a5aeed7cb6588f5e5dbfbb0fde51707b630bbb23897645c \
|
||||||
--hash=sha256:6c0016e7b354317c4e9e525b937ac8596c38d2d232b419529b9cd7a1cd46e39a \
|
--hash=sha256:7b999816b5850a35ada08443e6e03945f1f6488144a83afe2d37b240a552aafa \
|
||||||
--hash=sha256:71d6097b330eea8fd15097780c8e89cb1a8ce7838669f48c5bacd6f663dd4701 \
|
--hash=sha256:7c88c10dd432f3b39ccdafc9ed81d0c21b8fd634502574da76d1bfa4fe2c76d0 \
|
||||||
--hash=sha256:756c768d0c9c2955feb7a56c37ea24aea2e369f8d36a88da270b6a9f19e62b5e \
|
--hash=sha256:7d5e097eabd5d4915c27ac9f6e9325bb1e01a7c94d7348b5c4451d3fc30e8521 \
|
||||||
--hash=sha256:78cb2c6865a35ab8ff8b75fd122f6033b92a62c82801110e48ddd6c936a45d91 \
|
--hash=sha256:7e91e97a929232cdb828889ee6ad0e48d7f40f4ec38818f4e4a8968b2b1af22e \
|
||||||
--hash=sha256:7a743ff716f746fc19a9557f60dab1600d4613255f8a7aeb3cdde4db7eb15a66 \
|
--hash=sha256:7f6299e494e46253d40c34653cac369412f44ca53b5f85d848d3f95b1ed0546c \
|
||||||
--hash=sha256:85f998ea1848bc6757289e739cfbdda3a04adfd58b02fc018ce54d754a5ce468 \
|
--hash=sha256:816752a5ef76a80484c8c441c85593b7ea9304f6231fc5776ad1fbff7e773058 \
|
||||||
--hash=sha256:8728f216dcdb6e6d555cf971cb34076139ad74b31fc2c14da4fafc741c5f6217 \
|
--hash=sha256:83b37abd87b590acd8f47ca8a61f70893322b11834d36e07c2298dacad4d14d2 \
|
||||||
--hash=sha256:877c3f311ff35410f690861c4409e7ccbf0cd2f878e50628a28e5a0bb689e658 \
|
--hash=sha256:8619685cad8efc4c38c66d3b36aad854523297c43d748b3b6f0cc03c90ba3463 \
|
||||||
--hash=sha256:8cd2f7bdda092d99c9fc2fb7391354f306d01443d22785d0cbfafa2e2c8bb418 \
|
--hash=sha256:8bf295fe459343bc6093c8e5e0df60bfa189e0fcb775a22e2c2488fdeccc6c0d \
|
||||||
--hash=sha256:8e95e1385e4998ae9694eeaa4730ba5457ff61185b3a55e2e7bea0880aef452a \
|
--hash=sha256:8e459b613cf31f8980f584387b4fe47bf08e076e288d61aa8eba1f7fd4ddbb81 \
|
||||||
--hash=sha256:962864dc93511324d51ddbb5b9f8731bf71675b93ca612a07441896f4688fb8c \
|
--hash=sha256:8f36aa77f74b14a2103622b196402c71330e4e7cf4122ee45c854e9a01e0eecf \
|
||||||
--hash=sha256:9cf95fe4d0f84c82d282745d9bb08ad9f926efa00be4697e767b814ce40d4330 \
|
--hash=sha256:93ff9c9c3663ce23aaa5d0b6b6abac55359e2a0c06c7e30f3771829af816be63 \
|
||||||
--hash=sha256:9e881fca225083806662a5c43d627d215f258ff43c890f831966c7d7ba9c7402 \
|
--hash=sha256:9a635068d9793c7f0d929f39f18b58f1bd86c236e8e7b64167b86af9232ebca0 \
|
||||||
--hash=sha256:a2b55dd6b2a4c4b7d87ffa56bdb33fdc5fdb9a462173861a7bc097f17d91cb09 \
|
--hash=sha256:9dda0788a9932776a75d8bcc020076edc308ce2508b51f6739a45e3158b3fc42 \
|
||||||
--hash=sha256:a45650e8ce7fafffd731db8550230db6b0d306d181a90b67d3e6bca2f1990930 \
|
--hash=sha256:a192360d512305fe92d3053e4f7627bbad1f7708f1f4ad38cccd9336acabe9ad \
|
||||||
--hash=sha256:a876864214e136f0eb367788dbd7df045f4806801518e2cfe9e13229cfe06d8f \
|
--hash=sha256:a2a14cd73d5e6c927f644b0110ee81f59c4ef506259ec9183904747f2caacc81 \
|
||||||
--hash=sha256:ae26d61dfa7a47befdc7572b521024e8745f3d809bd95ca9505a7bba9ef849ec \
|
--hash=sha256:a625df9a2a5597fa5e5266e01aefc82604bb85d291e3547981e863560d75da6c \
|
||||||
--hash=sha256:af8d94b0db561cf68b88a267c5c44b49e134f525d0dc2cb7ed413a66bc23559a \
|
--hash=sha256:a6aaa7871aebca081eb5c45f83e845bbd9712ae99fa9286dbfdcee835e63f4b4 \
|
||||||
--hash=sha256:b343699e8308bdc51978310e1c959c584e7869cc8c40780058c87da7781a1e94 \
|
--hash=sha256:aa694c49787040943570d61c9b8fc01271bd2a2cfdd55f0d896f8aecdce1a981 \
|
||||||
--hash=sha256:b3c777e849237620b022f7f297dd67705f9f5cf1685f09f02e46f93e92725468 \
|
--hash=sha256:adb3c2124c68e480f4632d06cb7caa3b48a51678475f483b4edb1c6dee29ea43 \
|
||||||
--hash=sha256:b629de27fda84b42cde7edef0d85f13b958b47f6e9bbcbba9b673c562a89bd8b \
|
--hash=sha256:b84be41387fc00db28c13c02e30d42b02d8d8f6a4a741a1aee6012ca7f1f6039 \
|
||||||
--hash=sha256:ba09209fbe443b4acccebe845d8a138b89a8f4fbaeedd44953490b5315d5e965 \
|
--hash=sha256:bf97ba1b5542050e9b0c74e632323b6d8136cc99d64e193abebee22fe6013c76 \
|
||||||
--hash=sha256:ba54cfebe86920a559a7c4d6b9050791c20513650a1952ebe3368c7dc70306f8 \
|
--hash=sha256:c3bc8ee0271387e0b1e3ad0ff893645990a656e79bf9c42f4f734a3642b11d51 \
|
||||||
--hash=sha256:bcb46e2f9feff8d06323983bd83ed00c201fdcab3d74973e7072a889b3979fcd \
|
--hash=sha256:c50c80e3591e5cf9a8dfa6007d4f10732f02e32263850999286e56ccd650cfb2 \
|
||||||
--hash=sha256:bcc33feacfaefce60c12fd500a277533bdc02b10a19f7f6d348763d8140bbba7 \
|
--hash=sha256:c6fd031333dedcad7ce3e03d244093f43504f209e86925ebdb2b868fa4037630 \
|
||||||
--hash=sha256:bf16ba1b4d0b6b7c8e534936632270cf70eb00dbe09005bc345b2677b726855c \
|
--hash=sha256:c87a04e7f152ee4db5dbe15f0bfa3fe628a1aeedbe66b81c43b87f52c813f9ac \
|
||||||
--hash=sha256:cf1845d02ad822a369a49f2bb9345b1614744267682e7a03527dc3bf6eea1777 \
|
--hash=sha256:cdcd1ba258178f7356d74170c9a81ba4eab6a5d55748bc402a5a2a6fe6be3510 \
|
||||||
--hash=sha256:d69141514cc30b774ceea5e3ed3a6635c8d8a96edf664689b890f4089111fb35 \
|
--hash=sha256:d4737f50d23ddd11d6685faacbb9252887dde0bc7997127757247983d74399d6 \
|
||||||
--hash=sha256:d9c7f76c0673154f044e9d78c8655fb4213f6ca31a836df48b40fe5d187717b9 \
|
--hash=sha256:d7710eb676e9bb68965cb045be0d333b4c0d7f9dfbaa7fbf121385b1588683d3 \
|
||||||
--hash=sha256:dbce0b29841537a2fa4a214c2bbf14de3587c9680caa9b4e217568472490b28f \
|
--hash=sha256:d9b0a2bee3f3e03e9f29057aedb807dbf1e1d96ee1b9d0f422d9db6c8583271d \
|
||||||
--hash=sha256:dc624f6bc473dacdf7ef7eb8678d0d08edf15cd94fad6ae5c7d6cc67a4e4902f \
|
--hash=sha256:e65dd6e75de67b2362a4fa3e16aa627595f65054dc4ec73d64680c84d592fa61 \
|
||||||
--hash=sha256:e158cb00350dc278f3b91551101aa7d12415a66ebf2c91d8d5ac14e56ddd3ad0 \
|
--hash=sha256:e892354a424b1e82a78ba16785822bdd40de06f19446a3d4a28047df1a4f8932 \
|
||||||
--hash=sha256:e491916b378fba47242221bb9ead245211b70d504f495d105d17b14a24b4907c \
|
--hash=sha256:e8ca8f69b7c77fa96dad99f8638c1fc4f1c0bed4acaa1baf7a3c31bdb80a0ab1 \
|
||||||
--hash=sha256:e795b7eb908249c4e43c7c99fac7c2c75dab0c43566e37db472a355f63693d71 \
|
--hash=sha256:e91c2b1cbeae768c98752e67e717e283d68dae45717b41f2d91eaee648e37b7d \
|
||||||
--hash=sha256:e7e480451b9fa137494bccd3a7d69adbe8ac65a87d97be61e11f1b1050a5bac3 \
|
--hash=sha256:e98b4f91f99b24b1da72e10621ba181f7281922384a7403094debb4199de6c00 \
|
||||||
--hash=sha256:e91206ee562682b51b98ef4b26a6ef48fd84e15fd4c4bc5ec768eb641d206838 \
|
--hash=sha256:ef5fe6b7db3f501c56000ba8fe7c7e1a35ca1d45824fbeb95a67daa85cff4dbe \
|
||||||
--hash=sha256:e9871b1ffbfa9656b60aeee92ed5136a5742696006fa322b29ea3d8da0ecc9cf \
|
--hash=sha256:f11a3c1358bb3c68012a7b1f41b223c3db9f7bfde90b481df028cfe1c3363313 \
|
||||||
--hash=sha256:e9aeb04d6aef139de265b29683e119b638208f88cf73cdd1658aa07221165321 \
|
--hash=sha256:f391dc92a015c478745192fe4f2e120c2af2aba18d9fe0616341cbf537599806 \
|
||||||
--hash=sha256:ebaea975e03d3141d9d3a507df75c9b3ec90fa9d2ffd07567b3a978d9d790b26 \
|
--hash=sha256:f7cbb7a64e7ec664775195e4f81923bc8a93d9451b963f844e59118f63147a7a \
|
||||||
--hash=sha256:f0606c8bf2cdefea14a43530f7657cbbb7ecf1c4222512492ef4a4434a9501ec \
|
--hash=sha256:f9bd7d260d986f3553518c5d723544346fa48031f8aef3265d786aeb59845bc0 \
|
||||||
--hash=sha256:f13c32a3abd6079a66d9526e18dad9b6d280384d49d7c54040cd57b6424041d9 \
|
--hash=sha256:fc481f742ccda20e9ed760b8f978dff50f2a4e9bc253ac167fb0a05b0783ef52 \
|
||||||
--hash=sha256:f7401aebd7f581d7f83a439d87d474999317ee099218e5ad25d125290990ba65 \
|
--hash=sha256:ff3fe9eb621fbb9db4c4be33ab946f6bac5f98ab50ca8d3260503653656c961b \
|
||||||
--hash=sha256:fa4ecea169a355be7a3ade2c783e2ed12f0e40d2c5621cda8b3297faf7fbb9f5 \
|
--hash=sha256:ffea6b2986a797c84b6d1d27d4f43e0b83c73fc16281a930891cd237cf0d08fe
|
||||||
--hash=sha256:fbd139c8447d25dd750ab79ee274cc5e1fe80fc56340ab10b18a195e1b6eca3e \
|
|
||||||
--hash=sha256:fdafc9cce40277e0f7a0feabce0ee50dd2fa1800f3b38015e51296b5e814048d \
|
|
||||||
--hash=sha256:fe3cca2e4e8a592be0f269a1ca4835c25199d9f3ce815c8491048f785b0a0198 \
|
|
||||||
--hash=sha256:ffd0c5368496f41b0944be820fcb7a838aa6e623d250b01acf2643939c3f99d7
|
|
||||||
# via
|
# via
|
||||||
# -r infra/requirements.txt
|
# -r infra/requirements.txt
|
||||||
# pikepdf
|
# pikepdf
|
||||||
|
|||||||