Compare commits
247 Commits
dbc9ba4dee
...
ui-v2
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ea3b2b29d1 | ||
|
|
db877c52e6 | ||
|
|
8c053596b7 | ||
|
|
6a312bec9c | ||
|
|
455c1a1fae | ||
|
|
c08136d87b | ||
|
|
d962865944 | ||
|
|
a5417d200e | ||
|
|
95e7c64501 | ||
|
|
7f2327aea9 | ||
|
|
9c44cdf2a1 | ||
|
|
757008566c | ||
|
|
35b7701664 | ||
|
|
636c27ee88 | ||
|
|
8257ac24ab | ||
|
|
ac22f9a2f6 | ||
|
|
ebe8b29db2 | ||
|
|
b08a258931 | ||
|
|
ee6344dc74 | ||
|
|
312e1e3aa3 | ||
|
|
874e53ae46 | ||
|
|
1ad761ec53 | ||
|
|
258128de9f | ||
|
|
5692804c6f | ||
|
|
babd9e327c | ||
|
|
c45e5f732b | ||
|
|
0319039328 | ||
|
|
bba55a83f3 | ||
|
|
494925dff4 | ||
|
|
6a921415ea | ||
|
|
35e64d77d7 | ||
|
|
f77de40b7f | ||
|
|
19b8b8c509 | ||
|
|
0088158dc0 | ||
|
|
ee1159065a | ||
|
|
b6f20733fa | ||
|
|
93cb289940 | ||
|
|
88819c3a5f | ||
|
|
629628a522 | ||
|
|
a9253d830a | ||
|
|
c21497d71b | ||
|
|
56e5462647 | ||
|
|
88181b755d | ||
|
|
1dc8cf1efb | ||
|
|
f6bdbe006e | ||
|
|
c8c49ed57e | ||
|
|
18120e686f | ||
|
|
e3c31e43e5 | ||
|
|
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 | ||
|
|
641dc6053b | ||
|
|
4c01e932c3 | ||
|
|
e3d5558198 | ||
|
|
c18b9e5b87 | ||
|
|
cfcbe545f1 | ||
|
|
24013458c9 | ||
|
|
ccc25a2d5d | ||
|
|
7386469404 | ||
|
|
b329f76378 | ||
|
|
c9f8122600 | ||
|
|
66ddb17f02 | ||
|
|
96f1d27221 | ||
|
|
ca698434a2 | ||
|
|
86b8199612 | ||
|
|
543a9a9fb4 | ||
|
|
91269ce414 | ||
|
|
a87403338d | ||
|
|
da903db32a | ||
|
|
9926d3ab55 | ||
|
|
e95a42dbed | ||
|
|
c1a07a75fa | ||
|
|
3b92813491 | ||
|
|
7cab210674 | ||
|
|
24cb52d992 | ||
|
|
6a50e6db4d |
33
.env.example
@@ -20,10 +20,39 @@ APP_ENV=local
|
||||
PAYMENT_ADAPTER=fake
|
||||
FREIGHT_ADAPTER=fake
|
||||
TINY_ADAPTER=fake
|
||||
WHATSAPP_ADAPTER=fake
|
||||
# Sandbox only (see docs/LOCAL_SETUP.md, "Provider sandboxes"):
|
||||
# PAYMENT_ADAPTER=mercadopago
|
||||
# MP_ACCESS_TOKEN=TEST-...
|
||||
# MP_WEBHOOK_SECRET=...
|
||||
# MP_NOTIFICATION_URL=https://<public tunnel>/api/payments/webhook
|
||||
# Tiny API v3: client ID/secret come from the "Aplicativo" created in Tiny
|
||||
# (Configurações > Geral > Aplicativos); the redirect URI registered there
|
||||
# must be exactly TINY_REDIRECT_URI. Product ids are the Tiny products each
|
||||
# Site product becomes. Tiny has no sandbox: orders created are real.
|
||||
# TINY_CLIENT_ID=...
|
||||
# TINY_CLIENT_SECRET=...
|
||||
# TINY_REDIRECT_URI=http://localhost:8081/api/operator/tiny/callback
|
||||
# TINY_PRODUCT_TEXTIL_FOLHA=...
|
||||
# TINY_PRODUCT_TEXTIL_AVULSA=...
|
||||
# TINY_PRODUCT_UV_FOLHA=...
|
||||
# TINY_PRODUCT_UV_AVULSA=...
|
||||
# TINY_ADAPTER=tiny # only once connected and tested: creates real orders
|
||||
# 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
|
||||
MOCK_FREIGHT_CENTS=1500
|
||||
MAX_UPLOAD_BYTES=5368709120
|
||||
MAX_UPLOAD_BYTES=4294967296
|
||||
UPLOAD_PART_BYTES=8388608
|
||||
STORAGE_QUOTA_BYTES=53687091200
|
||||
OWNER_UPLOAD_QUOTA_BYTES=10737418240
|
||||
|
||||
27
.env.exemplo
@@ -1,27 +0,0 @@
|
||||
# HISTORICAL PROTOTYPE ONLY. Do not use for the local stack; use .env.example.
|
||||
# ---- portal (nuvem) ----
|
||||
DATABASE_URL=postgresql+psycopg://dtf:senha@localhost/dtf
|
||||
S3_ENDPOINT=https://<conta>.r2.cloudflarestorage.com
|
||||
S3_BUCKET=dtf-artes
|
||||
AWS_ACCESS_KEY_ID=
|
||||
AWS_SECRET_ACCESS_KEY=
|
||||
BASE_PORTAL=https://arte.dropstaratacado.com.br
|
||||
BASE_KANBAN=http://servidor:8080
|
||||
WEBHOOK_TOKEN=troque-isto
|
||||
AGENTE_TOKEN=troque-isto-tambem
|
||||
AGENTE_WEBHOOK=http://ip-da-fabrica:8080/api/agente/acordar
|
||||
|
||||
# ---- Tiny ----
|
||||
TINY_CLIENT_ID=
|
||||
TINY_CLIENT_SECRET=
|
||||
TINY_TOKEN_URL=
|
||||
TINY_BASE=https://api.tiny.com.br/public-api/v3
|
||||
|
||||
# ---- WhatsApp ----
|
||||
WHATS_PROVEDOR=meta
|
||||
WHATS_TOKEN=
|
||||
WHATS_NUMERO_ID=
|
||||
|
||||
# ---- fábrica ----
|
||||
PASTA_DTF=\\servidor\DTF
|
||||
KANBAN_DB=C:\dtf\kanban.db
|
||||
@@ -16,14 +16,14 @@ jobs:
|
||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
|
||||
- name: Run fast regression checks
|
||||
run: |
|
||||
python3 -m py_compile local/*.py deploy/*.py
|
||||
python3 -m py_compile app/*.py app/**/*.py ops/*.py deploy/*.py
|
||||
python3 -m unittest \
|
||||
local.test_dependency_lock \
|
||||
local.test_staging_readiness \
|
||||
tests.test_dependency_lock \
|
||||
tests.test_staging_readiness \
|
||||
deploy.test_production_preflight \
|
||||
local.test_pricing \
|
||||
local.test_secrets -v
|
||||
sh -n local/lock_dependencies.sh
|
||||
tests.test_pricing \
|
||||
tests.test_secrets -v
|
||||
sh -n infra/lock_dependencies.sh
|
||||
|
||||
integration:
|
||||
name: Integration suite on a real stack
|
||||
@@ -31,9 +31,26 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 45
|
||||
env:
|
||||
SITE_PORT: "8080"
|
||||
KANBAN_PORT: "8081"
|
||||
API_PORT: "8000"
|
||||
# The runner shares the host's Docker daemon, so every published port is
|
||||
# taken on the machine itself. Known occupants of that host:
|
||||
# 8000, 9443 Portainer (the Edge tunnel and its UI)
|
||||
# 18080/18081 the production dtf-cloud stack (docker-compose.yml defaults)
|
||||
# 9000/9001 MinIO defaults elsewhere
|
||||
# This block avoids all of them. Ephemeral ports are not an option: the
|
||||
# published port is baked into PUBLIC_ORIGIN, ALLOWED_ORIGINS and the CSP
|
||||
# when the containers start, so it has to be known beforehand.
|
||||
SITE_PORT: "28080"
|
||||
KANBAN_PORT: "28081"
|
||||
API_PORT: "28000"
|
||||
STORAGE_PORT: "29000"
|
||||
STORAGE_CONSOLE_PORT: "29001"
|
||||
# Presigned URLs are signed against this endpoint, so it must be reachable
|
||||
# by whoever follows them. The suites run inside the network, so it has to
|
||||
# be the service name, not a published port on the host.
|
||||
S3_PUBLIC_ENDPOINT: http://storage:9000
|
||||
PUBLIC_ORIGIN: http://site
|
||||
ALLOWED_HOSTS: localhost,127.0.0.1,site,kanban
|
||||
ALLOWED_ORIGINS: http://site,http://kanban,http://localhost:28080,http://localhost:28081
|
||||
COMPOSE: docker compose -f compose.local.yaml
|
||||
steps:
|
||||
- name: Checkout
|
||||
@@ -49,45 +66,48 @@ jobs:
|
||||
$COMPOSE up --build -d --wait --wait-timeout 600
|
||||
$COMPOSE ps
|
||||
|
||||
# Run inside the stack's own network. The runner is itself a container, so
|
||||
# ports published on the host's loopback are in a different namespace and
|
||||
# unreachable from here. SITE_HOST_HEADER keeps the Host the gateway and
|
||||
# TrustedHostMiddleware expect, so the configuration under test is the same
|
||||
# one a developer exercises on localhost.
|
||||
- name: API and workflow regressions
|
||||
run: |
|
||||
python3 -m local.smoke_test
|
||||
python3 -m local.workflow_test
|
||||
python3 -m local.security_test
|
||||
python3 -m local.scanning_test
|
||||
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"
|
||||
$COMPOSE exec -T \
|
||||
-e SITE_BASE_URL=http://site \
|
||||
-e SITE_HOST_HEADER=localhost \
|
||||
api python -m "tests.$suite"
|
||||
done
|
||||
|
||||
# Need Pillow and httpx, which only the application image has. The raster
|
||||
# check needs PyMuPDF as well and skips here; run it locally when changing
|
||||
# the generator's geometry. The provider suites use a fake transport: they
|
||||
# prove the documented contract, not the integration.
|
||||
- name: Print-file geometry and provider adapters
|
||||
run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_payment_messages tests.test_jadlog tests.test_correios tests.test_quote_review tests.test_moves tests.test_large_files tests.test_grade_check tests.test_schema tests.test_customer_document tests.test_mail_html tests.test_layout_rules -v
|
||||
|
||||
- name: Runtime and retention regressions
|
||||
run: |
|
||||
$COMPOSE exec -T api python -m local.retention_test
|
||||
$COMPOSE exec -T api python -m local.runtime_security_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.tiny_oauth_test
|
||||
$COMPOSE exec -T backup python -m tests.backup_test
|
||||
|
||||
# These need a real Chrome. They are the only coverage for the artwork
|
||||
# editor and the full customer journey, so install google-chrome-stable
|
||||
# (or set CHROME_BIN) on the runner to make them gate deployments. The
|
||||
# suites above stay hard gates either way.
|
||||
# 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.
|
||||
- name: Browser regressions
|
||||
run: |
|
||||
for candidate in "$CHROME_BIN" /usr/bin/google-chrome-stable \
|
||||
/usr/bin/google-chrome /usr/bin/chromium /usr/bin/chromium-browser; do
|
||||
if [ -n "$candidate" ] && [ -x "$candidate" ]; then
|
||||
export CHROME_BIN="$candidate"
|
||||
break
|
||||
fi
|
||||
done
|
||||
if [ ! -x "${CHROME_BIN:-}" ]; then
|
||||
echo "::warning::No Chrome on this runner; browser regressions were NOT run."
|
||||
echo "Install google-chrome-stable or set CHROME_BIN to gate on them."
|
||||
exit 0
|
||||
fi
|
||||
echo "Using $CHROME_BIN"
|
||||
node local/artwork_browser_test.mjs
|
||||
node local/browser_test.mjs
|
||||
$COMPOSE build browser-tests
|
||||
$COMPOSE run --rm --no-deps browser-tests sh -ec \
|
||||
'node tests/artwork_browser_test.mjs && node tests/browser_test.mjs'
|
||||
|
||||
- name: Diagnostics on failure
|
||||
if: failure()
|
||||
run: |
|
||||
$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
|
||||
if: always()
|
||||
@@ -115,13 +135,9 @@ jobs:
|
||||
fs --scanners secret --exit-code 1 --severity HIGH,CRITICAL \
|
||||
--no-progress /src
|
||||
|
||||
# PORTAINER.md described this as blocking publication. It never ran at
|
||||
# all, and turning it on unconditionally would block every deploy: the
|
||||
# source preflight refuses a release while the payment and messaging
|
||||
# adapters are fake, which is the deliberate state the stack runs in
|
||||
# today. So its verdict is always printed, and enforcement is opt-in.
|
||||
# Set the repository variable ENFORCE_PRODUCTION_PREFLIGHT to "true" once
|
||||
# real adapters land, and this becomes the gate the documentation claims.
|
||||
# Advisory while the provider adapters are fake. This is the only copy of
|
||||
# the gate: set ENFORCE_PRODUCTION_PREFLIGHT=true and a blocked preflight
|
||||
# fails this job, which stops images from being published.
|
||||
- name: Production source preflight
|
||||
run: |
|
||||
set +e
|
||||
@@ -138,10 +154,14 @@ jobs:
|
||||
fi
|
||||
echo "::warning::Source preflight reports blockers (advisory; set ENFORCE_PRODUCTION_PREFLIGHT=true to gate)."
|
||||
|
||||
# Every push to main that passes validation, the integration suite and the
|
||||
# scans publishes images. Production changes only when someone pulls and
|
||||
# redeploys the stack in Portainer; a manual run of this workflow also calls
|
||||
# the Portainer webhook when one is configured.
|
||||
publish-and-deploy:
|
||||
name: Publish images and notify Portainer
|
||||
name: Publish images
|
||||
needs: [validate, integration, scan]
|
||||
if: gitea.event_name == 'push' && gitea.ref == 'refs/heads/main'
|
||||
if: gitea.ref == 'refs/heads/main' && (gitea.event_name == 'push' || gitea.event_name == 'workflow_dispatch')
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 45
|
||||
env:
|
||||
@@ -160,7 +180,7 @@ jobs:
|
||||
test -n "$REGISTRY_TOKEN"
|
||||
echo "$REGISTRY_TOKEN" | docker login gitea.blyzer.com.br \
|
||||
--username "$REGISTRY_USERNAME" --password-stdin
|
||||
- name: Build and publish API
|
||||
- name: Build API
|
||||
run: |
|
||||
image="gitea.blyzer.com.br/blyzer/dtf-api"
|
||||
# The Dockerfiles pin digests themselves; these variables let a base be
|
||||
@@ -169,21 +189,17 @@ jobs:
|
||||
set --
|
||||
[ -n "$PYTHON_BASE_IMAGE" ] && set -- --build-arg PYTHON_BASE_IMAGE="$PYTHON_BASE_IMAGE"
|
||||
docker build --file deploy/Dockerfile.api "$@" \
|
||||
--build-arg VCS_REF="${{ gitea.sha }}" \
|
||||
--build-arg VCS_REF="${{ gitea.sha }}" --build-arg PACKAGES_DAY="$(date -u +%F)" \
|
||||
--tag "$image:latest" --tag "$image:${{ gitea.sha }}" .
|
||||
docker push "$image:latest"
|
||||
docker push "$image:${{ gitea.sha }}"
|
||||
- name: Build and publish web
|
||||
- name: Build web
|
||||
run: |
|
||||
image="gitea.blyzer.com.br/blyzer/dtf-web"
|
||||
set --
|
||||
[ -n "$PYTHON_BASE_IMAGE" ] && set -- --build-arg PYTHON_BASE_IMAGE="$PYTHON_BASE_IMAGE"
|
||||
[ -n "$NGINX_BASE_IMAGE" ] && set -- "$@" --build-arg NGINX_BASE_IMAGE="$NGINX_BASE_IMAGE"
|
||||
docker build --file deploy/Dockerfile.web "$@" \
|
||||
--build-arg VCS_REF="${{ gitea.sha }}" \
|
||||
--build-arg VCS_REF="${{ gitea.sha }}" --build-arg PACKAGES_DAY="$(date -u +%F)" \
|
||||
--tag "$image:latest" --tag "$image:${{ gitea.sha }}" .
|
||||
docker push "$image:latest"
|
||||
docker push "$image:${{ gitea.sha }}"
|
||||
# CRITICAL blocks, HIGH is reported. Both images carry zero CRITICAL after
|
||||
# the base pinning and OS upgrades, so this gate holds the line already
|
||||
# reached. The remaining HIGH findings have no upstream fix, so failing on
|
||||
@@ -191,31 +207,63 @@ jobs:
|
||||
- name: Image vulnerabilities
|
||||
run: |
|
||||
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 \
|
||||
"gitea.blyzer.com.br/blyzer/dtf-api:${{ gitea.sha }}" \
|
||||
"gitea.blyzer.com.br/blyzer/dtf-web:${{ gitea.sha }}"; do
|
||||
echo "--- $target (HIGH, reported)"
|
||||
docker run --rm -v /var/run/docker.sock:/var/run/docker.sock "$image" \
|
||||
image --scanners vuln --severity HIGH --no-progress \
|
||||
trivy image --skip-db-update --image-src docker --scanners vuln --severity HIGH --no-progress \
|
||||
--format table --exit-code 0 "$target" ||
|
||||
echo "::warning::Could not scan $target for HIGH findings"
|
||||
echo "--- $target (CRITICAL, blocking)"
|
||||
docker run --rm -v /var/run/docker.sock:/var/run/docker.sock "$image" \
|
||||
image --scanners vuln --severity CRITICAL --no-progress \
|
||||
--format table --exit-code 1 "$target" || failed=1
|
||||
set +e
|
||||
trivy image --skip-db-update --image-src docker --scanners vuln --severity CRITICAL --no-progress \
|
||||
--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
|
||||
if [ "$failed" -ne 0 ]; then
|
||||
echo "::error::A CRITICAL vulnerability was found in a published image."
|
||||
if [ "$found" -ne 0 ]; then
|
||||
echo "::error::A CRITICAL vulnerability was found in a release image."
|
||||
exit 1
|
||||
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
|
||||
run: |
|
||||
for name in dtf-api dtf-web; do
|
||||
image="gitea.blyzer.com.br/blyzer/$name"
|
||||
docker push "$image:${{ gitea.sha }}"
|
||||
docker push "$image:latest"
|
||||
done
|
||||
|
||||
- name: Trigger Portainer redeployment
|
||||
if: gitea.event_name == 'workflow_dispatch'
|
||||
env:
|
||||
PORTAINER_WEBHOOK: ${{ secrets.PORTAINER_WEBHOOK }}
|
||||
run: |
|
||||
if [ -z "$PORTAINER_WEBHOOK" ]; then
|
||||
echo "PORTAINER_WEBHOOK is not configured; images were published but deployment was skipped."
|
||||
echo "No PORTAINER_WEBHOOK configured; redeploy the stack in Portainer."
|
||||
exit 0
|
||||
fi
|
||||
curl --fail --silent --show-error --max-time 30 --request POST "$PORTAINER_WEBHOOK"
|
||||
|
||||
14
.gitignore
vendored
@@ -35,8 +35,12 @@ deploy/portainer.env
|
||||
output/local/
|
||||
output/security/
|
||||
|
||||
# Keep the roadmap generator, not its extracted text or render-review scratch.
|
||||
tmp/*
|
||||
!tmp/pdfs/
|
||||
tmp/pdfs/*
|
||||
!tmp/pdfs/generate_dtf_report.py
|
||||
# Scratch only. The roadmap generator moved to tools/, the PDFs to docs/.
|
||||
tmp/
|
||||
|
||||
# Client deliverables and scratch inputs live here but are not the repository's
|
||||
# to version: they are produced for a specific week, or dropped in to test with.
|
||||
Relatorio-*.docx
|
||||
Relatorio-*.pdf
|
||||
imagem-teste.*
|
||||
output/documents/
|
||||
|
||||
403
CONTEXT.md
@@ -1,403 +0,0 @@
|
||||
# DTF System - Project Context for AI Agents
|
||||
|
||||
## Purpose of this document
|
||||
|
||||
Read this document before changing code, documentation, architecture, or scope.
|
||||
It is the current English source of truth for the project. It supersedes older
|
||||
decisions in `README.md`, `ESPECIFICACAO.md`, `schema.sql`, and the existing
|
||||
prototype code whenever they conflict.
|
||||
|
||||
Update this file whenever the team makes a material product, process, or
|
||||
architecture decision.
|
||||
|
||||
## Project goal
|
||||
|
||||
Build a DTF ordering and production-flow system for Dropstar/Altus.
|
||||
|
||||
The current process is slow and manual: customers send artwork through
|
||||
WhatsApp, staff forward files, designers discover problems late, and production
|
||||
status is not visible outside the factory. The business has substantially more
|
||||
machine capacity than it currently uses. The goal is to let customers place DTF
|
||||
orders online, pay, send artwork, and follow production without making
|
||||
WhatsApp, shared folders, or manual handoffs the bottleneck.
|
||||
|
||||
The customer-facing value is speed and clarity. The operations value is a
|
||||
traceable queue and fewer lost or manually handled orders.
|
||||
|
||||
## Current MVP scope
|
||||
|
||||
The MVP must be delivered in **at most three weeks**. The target is a working
|
||||
online system, not factory-machine automation.
|
||||
|
||||
### Included
|
||||
|
||||
- Dedicated DTF site/subdomain.
|
||||
- Existing Site DTF commercial rules and product experience.
|
||||
- Direct, resumable multipart file upload to Cloudflare R2.
|
||||
- Mercado Pago payment integration with signed and idempotent webhooks.
|
||||
- Freight quotation and charging at checkout.
|
||||
- Idempotent Tiny/Olist order integration and order traceability.
|
||||
- Online Kanban for production status and secure file download.
|
||||
- WhatsApp status notifications.
|
||||
- Private object storage, 30-day file retention, backups, and basic security.
|
||||
- Operator guidance for the factory team.
|
||||
|
||||
### Explicitly outside the three-week delivery
|
||||
|
||||
- Automatic pre-flight validation. It will be validated after delivery using
|
||||
real customer files and real printed output, then refined as support work.
|
||||
- Direct FlexiPRINT integration.
|
||||
- Factory-side agent, hot folder, internal file server automation, VPN, and
|
||||
heartbeat monitoring.
|
||||
- Production-room dashboard, printer/machine telemetry, and advanced reports.
|
||||
- Automated shipping-label purchase, shipping-label printing, and dispatch
|
||||
automation. The MVP freight scope is quote selection and charging only.
|
||||
- Personalized cart behaviour based on past orders, day, or time.
|
||||
|
||||
After delivery, the team provides support and evaluates requested changes. Do
|
||||
not turn post-delivery support into a new committed delivery phase without an
|
||||
explicit decision.
|
||||
|
||||
## Agreed production model
|
||||
|
||||
```text
|
||||
Customer browser
|
||||
-> Site DTF / API on VPS
|
||||
-> direct multipart upload to private Cloudflare R2
|
||||
-> Mercado Pago payment + freight selected at checkout
|
||||
-> Tiny/Olist order record
|
||||
-> online Kanban
|
||||
-> factory operator downloads final file and imports it manually into FlexiPRINT
|
||||
```
|
||||
|
||||
WhatsApp is a notification channel, not the artwork-upload channel. It is used
|
||||
for payment confirmation, correction requests, production status, and order
|
||||
completion.
|
||||
|
||||
The operator works through the browser. The factory does not need an installed
|
||||
agent or an internal server for the MVP.
|
||||
|
||||
If the factory internet connection fails, only the factory team temporarily
|
||||
loses access to the Kanban and secure downloads. The public portal, payments,
|
||||
uploads, R2 objects, queue, and cloud services remain online. Factory work
|
||||
resumes when local access returns.
|
||||
|
||||
## Infrastructure and deployment
|
||||
|
||||
- **VPS:** runs the website, API, worker, PostgreSQL, ClamAV, Kanban, and
|
||||
third-party integrations.
|
||||
- **Cloudflare R2:** private S3-compatible object storage for original uploads
|
||||
and final files. It does not run the application, database, worker, or
|
||||
antivirus.
|
||||
- **Upload path:** the browser uploads directly to R2 using short-lived,
|
||||
server-issued presigned multipart URLs. Large files must never be proxied
|
||||
through the VPS.
|
||||
- **Deployment:** one Portainer-owned `dtf-cloud` Docker Swarm stack. One Gitea
|
||||
Actions workflow tests/scans, publishes `latest` plus commit-SHA application
|
||||
images, and calls the Portainer webhook. Activation remains blocked pending
|
||||
the production work listed below.
|
||||
- **Kanban access:** configure `OPERATOR_EMAIL` and `OPERATOR_PASSWORD` as
|
||||
stack environment variables. If the email is absent, only Kanban login is
|
||||
blocked; the rest of the stack remains available.
|
||||
- **Recommended VPS baseline:** 4 vCPU, 16 GB RAM, and 200 GB NVMe. Existing
|
||||
VPS capacity may be used if it safely meets or exceeds this baseline.
|
||||
- **Backups:** PostgreSQL backups go to R2. Application secrets are never
|
||||
committed to Git.
|
||||
|
||||
## File retention
|
||||
|
||||
The business does not want an unlimited artwork library.
|
||||
|
||||
| Artifact | Retention |
|
||||
|---|---:|
|
||||
| Incomplete multipart upload | 1 day |
|
||||
| Rejected or infected upload | 3 days |
|
||||
| Customer original after approval | Up to 7 days |
|
||||
| Final print artwork | Maximum 30 days from the first upload |
|
||||
| Order history and metrics | Kept in the database without keeping the image |
|
||||
|
||||
The 30-day retention decision overrides older references to 90 days or
|
||||
12-month artwork reordering.
|
||||
|
||||
## R2 planning cost reference
|
||||
|
||||
R2 cost is driven primarily by the average number of gigabytes stored during a
|
||||
month; read/write operations are expected to be a much smaller cost at the
|
||||
project's scale. There is no egress charge in the current planning model.
|
||||
|
||||
The client-facing roadmap uses the following planning examples, based on
|
||||
standard R2 storage pricing, the included storage allowance, and an exchange
|
||||
rate reference of USD 1 = BRL 5.13:
|
||||
|
||||
| Average storage | Approx. R2/month | Approx. BRL/month |
|
||||
|---|---:|---:|
|
||||
| 100 GB | USD 1.35 | BRL 7 |
|
||||
| 500 GB | USD 7.35 | BRL 38 |
|
||||
| 1 TB | USD 14.85 | BRL 76 |
|
||||
| 3 TB | USD 44.85 | BRL 230 |
|
||||
|
||||
These are planning estimates only. Confirm Cloudflare pricing, exchange rates,
|
||||
taxes, and payment-provider fees before presenting a commercial quote.
|
||||
|
||||
## Commercial rules
|
||||
|
||||
The existing rules in `dtf-site.html` are approved as the current source of
|
||||
truth. Do **not** redesign, simplify, or change prices, discounts, minimums,
|
||||
rounding, or product modes without explicit approval.
|
||||
|
||||
The current site contains four product modes, quality-based price tiers,
|
||||
artwork-ready discounts, separate assembly charges for loose artwork, a
|
||||
one-metre minimum, and ten-centimetre billing rounding.
|
||||
|
||||
The browser may display the calculation, but production payment creation must
|
||||
recalculate and validate all price, quantity, freight, and discount values on
|
||||
the server. Client-provided totals are never authoritative.
|
||||
|
||||
Normal JPG/PNG uploads are individual artwork by default, including when uploaded
|
||||
from the by-metre panel. They use the existing loose-artwork editor, printed
|
||||
width, quantity, and live packing canvas; packed height determines metres.
|
||||
Customers uploading an already assembled film-width image must explicitly select
|
||||
the ready-sheet option before uploading. PDF and manual-format ready sheets keep
|
||||
their existing workflow. These models retain their separate approved price tiers;
|
||||
image dimensions alone must never classify a normal artwork as a finished sheet.
|
||||
|
||||
## Freight
|
||||
|
||||
The original visual freight flow in `dtf-site.html` was a stub with only pickup
|
||||
functional. The localhost bridge now supports pickup and backend fake freight
|
||||
quotes; there is still no real carrier quotation or production checkout.
|
||||
|
||||
The customer already uses Correios and other shipping platforms. Before freight
|
||||
can be completed, obtain:
|
||||
|
||||
- The platform(s) that should be used as the source of truth.
|
||||
- API credentials or delegated access for the selected platform.
|
||||
- Origin postal code/address.
|
||||
- Available services and carriers to offer.
|
||||
- Packaging weight and dimensions by DTF length/package.
|
||||
- Freight business policy: exact pass-through, subsidy, free-shipping rules,
|
||||
pickup, or other exceptions.
|
||||
|
||||
At checkout, the backend must quote freight from the selected source, store the
|
||||
chosen service and quoted amount, include the amount in the Mercado Pago
|
||||
payment, and persist it in the order. Do not create a payment before the freight
|
||||
amount is final.
|
||||
|
||||
## Integrations
|
||||
|
||||
### Mercado Pago
|
||||
|
||||
Required before production payment integration, not for the local mock milestone:
|
||||
|
||||
- Production credentials.
|
||||
- Webhook configuration/access.
|
||||
|
||||
Webhook processing must verify authenticity and be idempotent. A duplicate or
|
||||
late delivery must not create a duplicate payment, order, message, or queue
|
||||
card.
|
||||
|
||||
### Tiny/Olist
|
||||
|
||||
Tiny/Olist is already available. The implementation must create/update orders
|
||||
idempotently and use the order number for traceability. Confirm the actual API
|
||||
endpoints, marker/tag behaviour, and rate limits before production use.
|
||||
|
||||
### WhatsApp
|
||||
|
||||
WhatsApp is already available, but the technical provider still needs to be
|
||||
confirmed (official Meta Cloud API, Z-API, or another provider).
|
||||
|
||||
Implement only the required customer events:
|
||||
|
||||
1. Payment approved.
|
||||
2. Artwork correction needed, with a secure link back to the site.
|
||||
3. Order entered production.
|
||||
4. Order ready for collection or shipping.
|
||||
|
||||
Messages initiated by the business may require approved templates depending on
|
||||
the provider and conversation state. Use an outbox/job mechanism with retries,
|
||||
delivery status handling, and idempotency. Do not send artwork through
|
||||
WhatsApp.
|
||||
|
||||
## Factory responsibilities after delivery
|
||||
|
||||
The client/factory team is responsible for:
|
||||
|
||||
- Opening the Kanban, downloading final files, and importing them manually into
|
||||
the current FlexiPRINT setup.
|
||||
- Performing real print tests and reporting mismatches in the final file or
|
||||
printed result.
|
||||
- Maintaining PCs, printers, FlexiPRINT licences, printing profiles, internal
|
||||
folders, and the local factory network.
|
||||
- Informing the development team about changes to prices, freight, operational
|
||||
rules, or external platforms that need system changes.
|
||||
|
||||
The development team delivers the online system, provides usage guidance, and
|
||||
supports subsequent corrections or scoped enhancements.
|
||||
|
||||
## Three-week roadmap
|
||||
|
||||
| Week | Delivery | Result |
|
||||
|---|---|---|
|
||||
| 1 | Infrastructure and upload | VPS, domain, database, R2, multipart upload, antivirus, and service foundation. |
|
||||
| 2 | Payment, freight, and order | Mercado Pago, freight quotation, idempotent Tiny/Olist order creation, final file generation, and main Kanban states. |
|
||||
| 3 | Kanban and handover | Online Kanban, secure download, WhatsApp status messages, 30-day retention, and operational handover. |
|
||||
|
||||
## Known implementation status
|
||||
|
||||
### Active localhost milestone (2026-09-15)
|
||||
|
||||
The current implementation target is localhost before any production connection.
|
||||
Use `docker-compose.yml`, `.env.example`, and `LOCAL_SETUP.md`. The runtime is in
|
||||
`local/`; historical `portal/`, `kanban/`, `agente/`, and `schema.sql` are preserved
|
||||
as references and are not imported or started by Compose.
|
||||
|
||||
- One local `dtf-cloud` Compose project runs seven long-lived services: Site and
|
||||
Kanban web gateways, FastAPI Portal/API, PostgreSQL, MinIO, ClamAV, and a
|
||||
PostgreSQL outbox/scanning worker. Separate database and storage initialization
|
||||
jobs provision restricted runtime identities, for nine Compose services total.
|
||||
- MinIO implements the S3 storage boundary with direct multipart browser uploads,
|
||||
resumable parts, private objects, and short-lived signed operator downloads.
|
||||
- Payment, freight, Tiny/Olist, and WhatsApp use fake adapters only. No production
|
||||
credentials or integrations are configured. The API and worker have no external
|
||||
network route; only local web/storage gateways publish loopback ports.
|
||||
- The original Site commercial calculation and appearance remain the source of
|
||||
truth. Its existing browser artwork analysis is retained as prototype advice;
|
||||
no new automatic pre-flight, server artwork analysis, or print-file generation
|
||||
is implemented or invoked.
|
||||
- Since client length and grade could be tampered with and automatic pre-flight
|
||||
is deferred, a local operator manually confirms those commercial inputs before
|
||||
checkout. This is a development trust-boundary decision, not a new production
|
||||
promise. The backend calculates all tiers, discounts, assembly-inclusive rates,
|
||||
one-metre minimum, ten-centimetre rounding, freight, and final totals. Immutable
|
||||
approved quotes expire after 24 hours. A customer confirms the server total
|
||||
on the Site to create one idempotent local paid order.
|
||||
- Paid orders use `rec`, `tra`, `fil`, `imp`, `cor`, `fin`, with allowed transitions,
|
||||
operator authentication, concurrency checks, and durable movement history.
|
||||
Local mock integration receipts are visible in the Kanban.
|
||||
- The customer portal at `/portal.html` supports local registration/login,
|
||||
stronger scrypt password hashing with legacy-hash upgrade, revocable HttpOnly
|
||||
sessions, owned order history/status, secure active
|
||||
file downloads, and correction uploads. Registration/login can claim only the
|
||||
current guest session's records, never orders found by email or CNPJ. Email
|
||||
verification and password recovery are not implemented.
|
||||
- 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
|
||||
removed/replaced or joined by new items; in-place reconstruction of the artwork
|
||||
editor and cross-device cart synchronization are not implemented. Browser
|
||||
storage capacity limits apply. Payment clears the saved cart. Logout revokes
|
||||
the server session and clears local checkout metadata and saved File blobs
|
||||
across open Site tabs.
|
||||
- Operators manually upload and approve a complete final-file set, with one or
|
||||
more files per order item. Queue entry requires active final files for every
|
||||
item. Corrections invalidate the old set; customers submit corrections through
|
||||
their portal, and operators reapprove final files. No artwork transformation,
|
||||
automatic pre-flight, or machine control is performed.
|
||||
- Every completed upload is quarantined pending a local ClamAV scan. Only `clean`
|
||||
files can be quoted, commercially approved, paid, downloaded, attached as final
|
||||
files, or admitted to the print queue. Rejected/error files remain blocked and
|
||||
expire within three days. The isolated scanner uses signatures bundled in its
|
||||
pinned image and has no external network route. The transport accepts files up
|
||||
to 5 GiB, but the local scan/release limit is 128 MiB; larger files remain
|
||||
blocked. This malware gate is not print pre-flight or artwork validation.
|
||||
- A retention worker removes expired object bytes but keeps order/file metadata:
|
||||
incomplete uploads after one day, originals within seven days of manual final
|
||||
artwork approval, and attached final/correction files within 30 days of the
|
||||
order's first upload. Storage lifecycle is also a 30-day backstop.
|
||||
- Structured security events are written to logs and PostgreSQL. The local
|
||||
`security_status` command summarizes authentication, rate-limit, scan, and
|
||||
scanner/signature alerts without exposing secrets. Security regression tests,
|
||||
exact-runtime Python dependency auditing, and Trivy image reports live under
|
||||
`local/` and `output/security/`; open findings are documented in
|
||||
`SECURITY_REPORT.md` and are not a production-readiness claim.
|
||||
- All direct and transitive Python packages are pinned with artifact hashes in
|
||||
`local/requirements.lock`; the API image build requires those hashes. The lock
|
||||
is regenerated in a disposable Python 3.12 container by
|
||||
`local/lock_dependencies.sh`. A fresh exact-runtime audit found no known Python
|
||||
advisories on 2026-09-15; this does not cover OS/container findings.
|
||||
- `compose.staging.yaml` is a separate, network-disabled readiness gate only. It
|
||||
validates non-secret staging decisions and rejects placeholders, local endpoints,
|
||||
fake providers, embedded secret settings, and unsafe secret sources. It does not
|
||||
deploy the application, contain credentials, or contact any real provider.
|
||||
- A separate production delivery package now exists under `deploy/`, with
|
||||
non-root API/web image definitions, a single Portainer Docker Swarm stack,
|
||||
external secret/volume contracts, health-monitored rolling updates,
|
||||
commit-SHA rollback images, and one protected Gitea workflow under
|
||||
`.gitea/workflows/`. The package never contains provider credentials and has
|
||||
not been deployed. Its fail-closed preflight intentionally rejects the current
|
||||
source until production adapters, Docker-secret file loading, approved inputs,
|
||||
restore rehearsal, image scans, and human security approval are complete.
|
||||
- `python3 -m local.backup create-and-verify` creates a private, Git-ignored bundle
|
||||
containing a PostgreSQL dump plus every complete, unexpired object already marked
|
||||
`clean`. SHA-256 manifests protect both parts. Verification restores the database
|
||||
under a UUID name and the object bytes under a UUID MinIO prefix, hashes the
|
||||
restored bytes, then removes only those temporary targets. Active data is never
|
||||
overwritten; pending, rejected, errored, expired, and purged objects are excluded.
|
||||
Run this local snapshot while uploads and retention are idle. Scheduling, offsite
|
||||
copies, and production restore operations remain unfinished.
|
||||
- Real providers, production authentication hardening, email verification/recovery,
|
||||
automatic final-file generation, production backup operations, and production
|
||||
activation remain incomplete. Deployment plumbing exists but cannot pass its
|
||||
release gate yet. No factory automation or pre-flight is added.
|
||||
|
||||
See `IMPLEMENTATION_REPORT.md` for verification, `PRODUCTION_INPUTS.md` for the
|
||||
decisions and evidence required before staging or production connection, and
|
||||
`PORTAINER.md` for the production delivery contract.
|
||||
The client roadmap promises are unchanged, so its PDF source is not regenerated
|
||||
for this local implementation checkpoint.
|
||||
|
||||
### Existing assets
|
||||
|
||||
- `dtf-site.html`: rich static front-end prototype. It includes the current
|
||||
commercial rules, client-side artwork analysis, current-session cart, and
|
||||
delivery UI. The localhost checkout bridge connects it to the new local API.
|
||||
- `portal/`: early FastAPI prototype for the original Tiny-first, token-link
|
||||
upload flow.
|
||||
- `kanban/`: early FastAPI/SQLite Kanban prototype.
|
||||
- `agente/`: factory-side agent prototype; out of current MVP scope.
|
||||
- `tmp/pdfs/generate_dtf_report.py`: generator for the current client-facing
|
||||
roadmap PDF.
|
||||
- `output/pdf/dtf-plano-producao-e-roadmap.pdf`: current generated roadmap.
|
||||
- `Reunião iniciada às 2026_09_09 09_39 GMT-03_00 - Anotações do Gemini.pdf`:
|
||||
meeting notes that established the business direction. Treat it as context;
|
||||
the latest decisions in this document define the active scope.
|
||||
|
||||
### Important gaps and stale assumptions
|
||||
|
||||
- The original Site had no backend payment, freight quote, order persistence,
|
||||
authentication, purchase history, or real cart persistence. Local order
|
||||
persistence, reviewed quotes, mock freight and fake payment now work through
|
||||
`local/static/checkout.js`. The local customer portal now provides accounts and
|
||||
order history; cart recovery is browser-local. Production account verification,
|
||||
recovery, and cross-device cart editing are still absent.
|
||||
- Without the local bridge, the original freight fallback remains a stub.
|
||||
Real freight quotation remains unimplemented in all runtimes.
|
||||
- The existing `portal/whats.py` and `kanban/whats.py` are duplicated and send
|
||||
direct text messages. They are not production-ready notification modules.
|
||||
- Older documentation and code describe a Tiny webhook creating an upload link,
|
||||
a factory agent, local Kanban, FlexiPRINT automation, 90-day retention, and
|
||||
12-month artwork reuse. Those are not the current MVP model.
|
||||
|
||||
## Documentation synchronization
|
||||
|
||||
`context.md` is the compact operating context for agents. The current
|
||||
client-facing narrative, diagrams, and formatting live in
|
||||
`output/pdf/dtf-plano-producao-e-roadmap.pdf`, generated from
|
||||
`tmp/pdfs/generate_dtf_report.py`.
|
||||
|
||||
When a decision changes, update both the relevant implementation context here
|
||||
and the roadmap source when it changes what the client-facing plan promises.
|
||||
|
||||
## Change-control rules for agents
|
||||
|
||||
- Preserve the current Site DTF commercial rules unless explicitly asked to
|
||||
change them.
|
||||
- Do not add factory-side automation, a local agent, hot folders, FlexiPRINT
|
||||
control, machine dashboards, or a new post-MVP delivery commitment by
|
||||
inference.
|
||||
- Do not claim that R2 hosts or executes application services.
|
||||
- Keep all customer-facing and internal documentation in English only when this
|
||||
file is the requested artifact; otherwise follow the user's requested
|
||||
language.
|
||||
- When a requirement is unclear, distinguish between the MVP, a future
|
||||
enhancement, and an existing prototype assumption before changing code.
|
||||
22
README.md
@@ -1,12 +1,12 @@
|
||||
# Sistema DTF 24h — Altus Group
|
||||
|
||||
> **Active local milestone (2026-09-11):** Read [CONTEXT.md](CONTEXT.md) first.
|
||||
> Start with `docker compose up --build`, then open the [Site](http://localhost:8080)
|
||||
> **Active local milestone (2026-09-23):** Read [docs/CONTEXT.md](docs/CONTEXT.md) first.
|
||||
> Start with `docker compose -f compose.local.yaml up --build`, then open the [Site](http://localhost:8080)
|
||||
> and [Kanban](http://localhost:8081). Optional configuration: copy `.env.example`
|
||||
> to `.env`. Follow [LOCAL_SETUP.md](LOCAL_SETUP.md) for the complete test flow,
|
||||
> to `.env`. Follow [docs/LOCAL_SETUP.md](docs/LOCAL_SETUP.md) for the complete test flow,
|
||||
> local login, health checks, and troubleshooting. See
|
||||
> [IMPLEMENTATION_REPORT.md](IMPLEMENTATION_REPORT.md) for scope and reuse decisions.
|
||||
> Production delivery uses one Portainer stack; see [PORTAINER.md](PORTAINER.md).
|
||||
> [IMPLEMENTATION_REPORT.md](docs/historico/IMPLEMENTATION_REPORT.md) for scope and reuse decisions.
|
||||
> Production delivery uses one Portainer stack; see [docs/PORTAINER.md](docs/PORTAINER.md).
|
||||
> Everything below is preserved historical prototype documentation, not the active
|
||||
> setup or delivery specification. Do not run its production integrations or agent.
|
||||
|
||||
@@ -14,6 +14,16 @@
|
||||
> a arquitetura, o código e o que ainda depende de resposta.
|
||||
> Base: conversas de 29 e 30/08/2026 com Marcus.
|
||||
|
||||
|
||||
> **2026-09-21.** Everything below this line is the original prototype
|
||||
> documentation. The code it describes (`portal/`, `kanban/`, `agente/`, the root
|
||||
> `schema.sql`, `.env.exemplo`) no longer exists, and the model it describes is
|
||||
> not the one implemented. Kept for the business reasoning in it — the capacity
|
||||
> figures, the cost argument, the meeting decisions. For how the system actually
|
||||
> works read [docs/CONTEXT.md](docs/CONTEXT.md); for what is outstanding read
|
||||
> [docs/ROADMAP.md](docs/ROADMAP.md); for the original documents see
|
||||
> [docs/historico/](docs/historico/README.md).
|
||||
|
||||
---
|
||||
|
||||
## Por que este projeto existe
|
||||
@@ -418,7 +428,7 @@ depende de a pasta de rede funcionar.
|
||||
```bash
|
||||
apt install -y python3.12-venv libvips-tools postgresql nginx certbot
|
||||
python3 -m venv /opt/dtf/venv && source /opt/dtf/venv/bin/activate
|
||||
pip install -r requirements.txt
|
||||
pip install fastapi uvicorn sqlmodel 'psycopg[binary]' boto3 httpx # prototype only; no longer tracked
|
||||
cp .env.exemplo .env # preencher
|
||||
cd portal && uvicorn main:app --host 0.0.0.0 --port 8000
|
||||
```
|
||||
|
||||
470
ROADMAP.md
@@ -1,470 +0,0 @@
|
||||
# DTF System — Working Roadmap
|
||||
|
||||
> Internal engineering tracker. Not a client document, not a promise sheet.
|
||||
> The client-facing narrative lives in `output/pdf/dtf-plano-producao-e-roadmap.pdf`
|
||||
> and in the weekly report (`Relatorio-Semana-1-DTF.docx`).
|
||||
>
|
||||
> 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.
|
||||
|
||||
**Current step:** Block 0 closed, plus 2.1–2.6 and 5.1. Next: 2.7 (vendor or
|
||||
integrity-pin pdf.js), then 2.8–2.11. Block 1 still waits on client inputs for
|
||||
1.1/1.2.
|
||||
|
||||
**Last audit:** 2026-09-18, full read of `local/`, `dtf-site.html`, `deploy/`,
|
||||
`.gitea/`, docs and legacy prototypes. Findings below carry their audit IDs.
|
||||
|
||||
| Status | Meaning |
|
||||
|---|---|
|
||||
| `[ ]` | not started |
|
||||
| `[~]` | in progress |
|
||||
| `[x]` | done and verified |
|
||||
| `[?]` | blocked on a decision (product or client), not on code |
|
||||
|
||||
---
|
||||
|
||||
## Block 0 · Broken right now
|
||||
|
||||
Nothing in this block is optional. Until it is closed, the system cannot be
|
||||
demonstrated, and the week-1 claims cannot be defended.
|
||||
|
||||
### `[x]` 0.1 — API returns 500 on every session, login and registration `(F1)`
|
||||
|
||||
`local/auth.py:46` calls `os.environ` and the module never imports `os`.
|
||||
Reproduced: `NameError: name 'os' is not defined`. `/api/session` calls
|
||||
`new_session()` whenever there is no cookie, so the Site checkout bridge, cart
|
||||
recovery and the customer portal all fail on first visit. Introduced in `e3e37f6`.
|
||||
|
||||
- Add `import os` to `local/auth.py`.
|
||||
- Move the `COOKIE_SECURE` read to a module constant so it is evaluated once.
|
||||
- **Accept:** a fresh browser hits the Site and `/api/session` returns 200 with a
|
||||
`cart_scope`; `local/smoke_test.py` and `local/workflow_test.py` pass.
|
||||
|
||||
### `[x]` 0.2 — "Arquivo por metro" is unreachable in practice
|
||||
|
||||
Two independent causes, both from 2026-09-18 commits. Verified in a browser.
|
||||
|
||||
**a. Every entry point hard-routes to loose artwork** (`483a083`)
|
||||
|
||||
| Control | Currently opens |
|
||||
|---|---|
|
||||
| Nav "Impressão DTF" | `avulsa` |
|
||||
| "DTF Têxtil · 57 cm" | `avulsa` |
|
||||
| "DTF UV · 28,5 cm" | `uv` |
|
||||
| Hero "Enviar minha arte" | `avulsa` |
|
||||
|
||||
Only the price card reaches `file`. Revert the three `data-modo-cta` attributes
|
||||
so navigation links land on the product chooser, not on a product.
|
||||
|
||||
**b. Dropping a PNG/JPG in `file` mode silently switches the order** `(F25)`
|
||||
|
||||
`dtf-site.html` `sel()` — from `abrir('file')`, dropping `imagem-teste.jpg` gives
|
||||
`modo: "avulsa"`, header "Artes avulsas", price `R$ 29,90/m`. Meanwhile the same
|
||||
screen says *"Arraste suas folhas montadas · PNG, JPG ou PDF"*, marks
|
||||
*"PNG, JPG ou PDF · a partir de R$ 14,90"* as the recommended path, and sets
|
||||
`input.accept=".png,.jpg,.jpeg,.pdf"`. The page invites the drop and then
|
||||
reprices the order 50% higher.
|
||||
|
||||
The escape hatch `#imagemComoFolha` sits above the drop zone as small text inside
|
||||
an informational notice, defaults to unchecked, and must be ticked *before* the
|
||||
drop. After the switch fires, `pintaModo()` sets `trocarParaAvulsa.hidden = true`,
|
||||
so the checkbox disappears and there is no way back in place.
|
||||
|
||||
Net effect: the only formats that survive `file` mode are PDF/TIFF/PSD/AI/CDR —
|
||||
the path the UI itself marks as the worse option. A mixed drop (JPG + PDF) is
|
||||
rejected and accepts nothing.
|
||||
|
||||
- Make the ready-sheet choice an explicit two-option control **inside** the drop
|
||||
area, styled like the existing `.cam` selector — not a checkbox in a notice.
|
||||
- Stop advertising PNG/JPG in the by-metre drop zone while rejecting them.
|
||||
- When a switch does happen, show the price change and offer one-click undo.
|
||||
- **Accept:** a customer can complete a by-metre order with a PNG from any entry
|
||||
point, and no product/price change ever happens without a visible confirmation.
|
||||
|
||||
### `[x]` 0.3 — Ready-sheet declaration is unverified and worth money `(F22 related)`
|
||||
|
||||
Ticking `#imagemComoFolha` is an honour-system claim that moves the price from
|
||||
R$ 29,90/m to R$ 19,90/m (R$ 14,90 with a good grade). `medirFolha` then derives
|
||||
sheet height purely from aspect ratio × 57 cm — the original bug, now opt-in.
|
||||
|
||||
Measured with `imagem-teste.jpg` (466 × 659 px):
|
||||
|
||||
| Route | System behaviour | Billed |
|
||||
|---|---|---|
|
||||
| Ticked | treated as a 57 × 80,6 cm mounted sheet | 1 m × R$ 19,90 = **R$ 19,90** |
|
||||
| Not ticked | 20 cm wide, packs to 28,3 cm of film | 1 m × R$ 29,90 = **R$ 29,90** |
|
||||
|
||||
- Validate the claim: declared width must be ≈ film width (57 / 28,5 cm) at a
|
||||
plausible DPI before the sheet model is accepted.
|
||||
- Re-check server-side in `/api/operator/quotes/{id}/approve` before pricing.
|
||||
- **Accept:** a small single artwork declared as a ready sheet is rejected with a
|
||||
clear message; a genuine 57 cm sheet passes; the operator sees the verdict.
|
||||
|
||||
### `[x]` 0.4 — Documented local startup fails `(F2)`
|
||||
|
||||
`LOCAL_SETUP.md` says `docker compose up --build` with no `.env`.
|
||||
`docker compose --env-file .env.example config` exits 1: `R2_ENDPOINT`,
|
||||
`R2_ACCESS_KEY_ID`, `SITE_DOMAIN`, `KANBAN_DOMAIN` missing. `docker-compose.yml`
|
||||
became a production/R2 stack in `e3e37f6`; `.env.example` is still the MinIO one
|
||||
and there is no MinIO service left.
|
||||
|
||||
- Decide: keep one production compose and add `compose.local.yaml` with MinIO, or
|
||||
restore a local default. Recommend the former.
|
||||
- **Accept:** a clean clone reaches a working Site + Kanban with the documented
|
||||
command, and `LOCAL_SETUP.md` matches what actually runs.
|
||||
|
||||
### `[x]` 0.5 — App DB role shares the admin password `(F3)`
|
||||
|
||||
`docker-compose.yml:65` sets `APP_DB_PASSWORD: ${POSTGRES_PASSWORD}` — the same
|
||||
value as `dtf_admin`. `bootstrap.py` grants the app role DML-only and then hands
|
||||
it a credential that also logs in as the owner. Anyone reading the API container
|
||||
env has admin on the database.
|
||||
|
||||
- **Accept:** distinct secrets; connecting as `dtf_app` with the admin password fails.
|
||||
|
||||
### `[x]` 0.6 — A paid order showed the customer nothing (found while closing Block 0)
|
||||
|
||||
`#checkoutStatus` and `#checkoutActions` lived inside `#carr`, and the success path
|
||||
in `checkout.js` clears the cart (`pedido=[]; limpaPaineis()`) before writing the
|
||||
confirmation — `.carr{display:none}` then hid the panel holding it. Present since
|
||||
the first commit; it only surfaced once 0.1 made a payment reachable at all.
|
||||
Both elements now sit in their own always-visible `.checkout` container.
|
||||
|
||||
### How Block 0 was verified
|
||||
|
||||
A live stack (`compose.local.yaml`), then the full suite:
|
||||
|
||||
| Check | Result |
|
||||
|---|---|
|
||||
| `/api/session` on a cold browser | 200 with `cart_scope` + session cookie |
|
||||
| smoke · workflow · security · scanning | pass |
|
||||
| retention · runtime security (in-container) | pass |
|
||||
| `artwork_browser_test.mjs` | pass, updated to the new declared-product behaviour |
|
||||
| `browser_test.mjs` end-to-end | pass — upload → quote → operator approval → paid order → all Kanban states |
|
||||
| 4 CI unit tests | pass |
|
||||
|
||||
Ports 8090/8091/8010 were used; 8080 was held by an unrelated preview server.
|
||||
|
||||
---
|
||||
|
||||
## Block 1 · Week 2 — committed to the client
|
||||
|
||||
From the report already sent. These are dated promises, not backlog.
|
||||
|
||||
- `[ ]` 1.1 — Mercado Pago transparent checkout, signed and idempotent webhooks.
|
||||
Requires production credentials + webhook access. Payment must never be created
|
||||
before the freight amount is final.
|
||||
- `[ ]` 1.2 — Real freight quotation. **Blocked on client inputs** (see
|
||||
`PRODUCTION_INPUTS.md`): source platform, credentials, origin CEP, services,
|
||||
packaging weight/dimensions per length, subsidy policy.
|
||||
- `[ ]` 1.3 — Idempotent Tiny/Olist order creation with order-number traceability.
|
||||
Confirm endpoints, tag behaviour and rate limits first.
|
||||
- `[ ]` 1.4 — Final print-file generation (see 3.2 — this is the same problem).
|
||||
- `[ ]` 1.5 — Main Kanban production states consolidated.
|
||||
- `[ ]` 1.6 — **Block 0.2 + 0.3**, promised as "início da próxima semana".
|
||||
|
||||
`[!]` The production compose currently blocks `dev_paid` (`ENVIRONMENT != 'local'`)
|
||||
and ships only fake adapters, so the deployed system cannot take an order at all.
|
||||
1.1 is what unblocks it.
|
||||
|
||||
---
|
||||
|
||||
## Block 2 · Security — before any public exposure
|
||||
|
||||
### `[x]` 2.1 — Rate limiting and audit logs are blind to the client `(F5)`
|
||||
|
||||
uvicorn runs without trusted proxy headers (`forwarded_allow_ips` defaults to
|
||||
`127.0.0.1`; nginx is a different container IP), so `request.client.host` is nginx
|
||||
for every request. `rate_limit('auth-source', ...)` at 60/15min becomes a single
|
||||
global bucket — **60 failed logins lock out every customer** — and every `audit()`
|
||||
record has no attacker IP.
|
||||
|
||||
- Set `--proxy-headers` with `FORWARDED_ALLOW_IPS` scoped to the nginx service, or
|
||||
read `X-Forwarded-For` explicitly at the edge.
|
||||
- **Accept:** two clients on different IPs have independent buckets; audit rows
|
||||
carry the real IP.
|
||||
|
||||
### `[x]` 2.2 — The public site throttles itself `(F6)`
|
||||
|
||||
`local/app.py:115` — `rate_limit('guest-sessions', ENVIRONMENT, 120, 900)` is keyed
|
||||
on the environment name: 120 new visitors per 15 minutes **site-wide** (~8/min).
|
||||
Normal traffic 429s. Key per source IP (after 2.1) and raise the ceiling.
|
||||
|
||||
### `[x]` 2.3 — `deploy/stack.yaml` cannot boot `(F7)`
|
||||
|
||||
It passes `DATABASE_URL_FILE`, `AWS_ACCESS_KEY_ID_FILE`, `OPERATOR_PASSWORD_FILE`,
|
||||
`OPERATOR_USER`. The code reads `DATABASE_URL`, `AWS_ACCESS_KEY_ID`,
|
||||
`OPERATOR_PASSWORD`, `OPERATOR_EMAIL`, and no `_FILE` loader exists.
|
||||
`app.py:58` does `os.environ['OPERATOR_PASSWORD']` → `KeyError` → 500 instead of 503.
|
||||
|
||||
- Implement `local/secrets.py` (the preflight already expects it) reading `*_FILE`
|
||||
with env fallback. Reconcile `OPERATOR_USER` vs `OPERATOR_EMAIL`.
|
||||
- **Accept:** the stack renders and boots against Swarm secrets; missing operator
|
||||
config yields 503, not 500.
|
||||
|
||||
### `[x]` 2.4 — The documented release gate does not exist `(F8)`
|
||||
|
||||
`PORTAINER.md` and `SECURITY_REPORT.md` claim the workflow runs the full isolated
|
||||
suite, Trivy HIGH/CRITICAL image gates, secret scanning and the source preflight
|
||||
before calling Portainer. `.gitea/workflows/deploy.yml` runs `py_compile` plus four
|
||||
unit tests, then builds, pushes `latest` and calls the webhook **unconditionally**.
|
||||
`deploy/production_preflight.py` is never invoked — only its unit test runs.
|
||||
|
||||
- Either implement the gate or correct both documents. Do not leave the gap.
|
||||
|
||||
### `[x]` 2.5 — The preflight has silently decayed `(F9)`
|
||||
|
||||
It blocks by string-matching source. **4 of 6 markers are dead** after the R2
|
||||
refactor: `'This runtime only supports APP_ENV=local'`,
|
||||
`'Only local S3 storage is supported'`, `"allowed_hosts=['localhost', '127.0.0.1']"`,
|
||||
`"'environment': 'local'"`. String gates weaken without failing.
|
||||
|
||||
- Replace marker matching with behavioural assertions (import the module, assert
|
||||
the adapter classes in use).
|
||||
|
||||
### `[x]` 2.6 — Base images are not pinned `(F10)`
|
||||
|
||||
Dockerfiles default to mutable `python:3.12-slim` / `nginx:1.28-alpine`, the
|
||||
workflow passes no digest build-args, and `--pull` makes builds non-reproducible —
|
||||
while `PORTAINER.md` documents digest-pinned immutable bases.
|
||||
|
||||
### `[ ]` 2.7 — pdf.js loaded from CDN without integrity `(F11)`
|
||||
|
||||
3.11.174 from `cdnjs`, no SRI, and CSP allows the whole host for `script-src` **and**
|
||||
`worker-src`. Vendor the asset or pin `integrity` and narrow the CSP to the exact path.
|
||||
|
||||
### `[ ]` 2.8 — Single shared operator credential `(F12)`
|
||||
|
||||
One `OPERATOR_EMAIL`/`OPERATOR_PASSWORD` for the whole factory; `movements.operator`
|
||||
records the same name for everyone. The meeting asked for traceability, and the old
|
||||
`kanban/main.py` explicitly designed separation of duties (Mayana classifies,
|
||||
Thales/Alexandre authorise). Needs real per-person accounts with roles.
|
||||
|
||||
### `[ ]` 2.9 — No TLS in the stack `(F13)`
|
||||
|
||||
Ports publish plain HTTP on 18080/18081 while `COOKIE_SECURE: "true"` — cookies are
|
||||
silently dropped unless something external terminates TLS. Nothing in the repo
|
||||
provisions certificates; `TAREFAS.md` A2 still lists it as pending.
|
||||
|
||||
### `[ ]` 2.10 — No email verification, no password recovery `(F14)`
|
||||
|
||||
A locked-out customer has no path back, and registration accepts any CNPJ without
|
||||
proving control of the e-mail. Needs a transactional mail provider — **client input**.
|
||||
|
||||
### `[ ]` 2.11 — LGPD `(F15)`
|
||||
|
||||
CNPJ, phone and e-mail are kept indefinitely in `accounts.profile` and
|
||||
`orders.snapshot`. Artwork has a 30-day policy; personal data has none, and there is
|
||||
no privacy notice, consent record or deletion path.
|
||||
|
||||
---
|
||||
|
||||
## Block 3 · Architecture — needs a decision before code
|
||||
|
||||
### `[?]` 3.1 — Manual quote approval contradicts the 24h business case `(F16)`
|
||||
|
||||
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
|
||||
money. As built, a 2am order still waits for a person. `CONTEXT.md` frames this as a
|
||||
temporary development trust boundary — the risk is that it silently becomes the
|
||||
delivered model.
|
||||
|
||||
**Decide:** what makes a quote auto-approvable (mode, metre range, grade floor,
|
||||
returning customer), and what still routes to a human.
|
||||
|
||||
### `[?]` 3.2 — Billable metres are computed in the customer's browser `(F17, F18)`
|
||||
|
||||
For loose artwork, `metros` comes from `desenhaMontagem`/`encaixar` — a canvas
|
||||
alpha-mask packer running client-side. The server never recomputes it.
|
||||
`passoDe()`/`CELULAS_MAX` coarsen the grid for large sheets and image decoding
|
||||
differs by browser, so **the same cart can price differently on different devices**.
|
||||
The code comments reference "o motor do servidor"; that engine does not exist.
|
||||
|
||||
Worse, the layout the customer is quoted on is never produced — operators upload
|
||||
final files by hand, so billed metres ≠ printed metres and a designer redoes work
|
||||
the site already did.
|
||||
|
||||
**Decide:** port the packer to the server as the pricing authority and the print-file
|
||||
generator, with the browser as preview only. This is the single largest gap between
|
||||
what was promised in the meeting and what exists.
|
||||
|
||||
### `[?]` 3.3 — The 5 GB problem is unsolved `(F19)`
|
||||
|
||||
Transport accepts 5 GiB; `SCAN_MAX_BYTES` / ClamAV `StreamMaxLength` release only
|
||||
≤ 128 MiB. Files above that are quarantined permanently with no path forward. This
|
||||
is exactly the risk Jorge raised in the meeting.
|
||||
|
||||
**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).
|
||||
|
||||
### `[ ]` 3.4 — Upload throughput `(F20)`
|
||||
|
||||
8 MiB parts, strictly sequential in `local/static/upload.js:21`, one presign
|
||||
round-trip per part → ~640 sequential API calls for a 5 GB file, through an nginx
|
||||
`limit_req` of 20r/s. Add parallelism (4–6 in flight) and batch presigning.
|
||||
|
||||
### `[ ]` 3.5 — Payment ordering `(F27)`
|
||||
|
||||
`dev_paid` charges before persisting the order and passes no idempotency key.
|
||||
Harmless with `FakePayment`; with Mercado Pago that ordering is how you get double
|
||||
charges. Fix as part of 1.1.
|
||||
|
||||
---
|
||||
|
||||
## Block 4 · Scale and performance
|
||||
|
||||
- `[ ]` 4.1 — Missing indexes `(F23)`. `local/schema.sql` indexes only
|
||||
`uploads(owner)`. Add `orders(owner)`, `quotes(owner)`, `order_files(order_id)`,
|
||||
`movements(order_id)`, and a partial index on
|
||||
`outbox(available_at) WHERE delivered_at IS NULL` — the worker polls that table
|
||||
every second and it only grows.
|
||||
- `[ ]` 4.2 — `/api/operator/board` is unpaginated `(F24)`: every order ever, plus a
|
||||
per-quote subquery each. Fine at 10 orders, not at 200/day.
|
||||
- `[ ]` 4.3 — Scan throughput `(F21)`: one `scan_loop` thread, `worker` at
|
||||
`replicas: 1`, ClamAV `MaxThreads 2`, browser gives up after 150s.
|
||||
- `[ ]` 4.4 — Quality grade fallback `(F22)`: when `carregarImagem` fails,
|
||||
`px(f)=Math.sqrt(f.size/1024)*95` stands — a DPI inferred from **file size in
|
||||
bytes** — and it drives up to a 25% discount. Fail closed instead.
|
||||
- `[ ]` 4.5 — Dead config `(F28)`: `stack.yaml` sets `CLAMD_HOST: scanner`,
|
||||
`scanning.py` hardcodes `'scanner'`.
|
||||
|
||||
---
|
||||
|
||||
## Block 5 · Hygiene and maintenance
|
||||
|
||||
- `[x]` 5.1 — CI coverage `(F33)`. An `integration` job now builds the localhost
|
||||
stack and runs smoke, workflow, security, scanning, retention, runtime security
|
||||
and both browser suites; `publish-and-deploy` depends on it. Verified by
|
||||
reintroducing the 0.1 defect: `py_compile` and the unit tests still passed while
|
||||
`smoke_test` failed on `/session`, blocking the release. Browser tests skip with
|
||||
a warning when the runner has no Chrome — **install `google-chrome-stable` on the
|
||||
runner (or set `CHROME_BIN`) to make them gate as well.**
|
||||
- `[ ]` 5.2 — Remove or archive the dead prototypes `(F30)`: `portal/`, `kanban/`,
|
||||
`agente/`, root `schema.sql` (~1,500 lines describing an abandoned model). Several
|
||||
expose unauthenticated endpoints taking the acting user from the request body
|
||||
(`/api/puxar`, `/api/devolver`).
|
||||
- `[ ]` 5.3 — Root `requirements.txt` is the prototype's `(F31)`: wildcard pins,
|
||||
unused `sqlmodel`/`pyvips`/`qrcode`/`pillow`, next to the hash-locked
|
||||
`local/requirements.lock`.
|
||||
- `[ ]` 5.4 — `pip==26.2.1` pinned as a runtime dependency `(F32)` — pip ships inside
|
||||
the read-only production image.
|
||||
- `[ ]` 5.5 — Doc drift `(F34)`. `README.md`, `CONTEXT.md`, `LOCAL_SETUP.md` and
|
||||
`SECURITY_REPORT.md` describe a MinIO localhost stack, an API with "no external
|
||||
network route", a `operator` / `local-operator-only` login the email-validated
|
||||
model rejects, and a release gate — none match the current tree.
|
||||
- `[ ]` 5.6 — `dtf-site.html` is 2,889 lines with commercial rules, the packing
|
||||
engine, PDF analysis, UI and checkout inline `(F29)`. Split at least the pricing
|
||||
table and the packer so 3.2 has somewhere to land.
|
||||
- `[ ]` 5.7 — Commercial rules duplicated between `FAIXAS` (JS) and `TIERS` (Python)
|
||||
`(F26)`. `test_pricing` guards parity; generate one from the other instead.
|
||||
- `[ ]` 5.9 — `local/browser_test.mjs` failed once and passed on an immediate
|
||||
re-run, with no code change in between (2026-09-21). It is a deploy gate when the
|
||||
runner has Chrome, so an intermittent failure there blocks releases for no reason.
|
||||
Suspect Chrome startup timing or a race against stack readiness. Watch it, and if
|
||||
it recurs add an explicit readiness wait rather than a retry.
|
||||
- `[ ]` 5.8 — The Site promises retention the system does not honour. The cart aside
|
||||
still reads *"O arquivo fica guardado por 90 dias e o histórico do pedido por 12
|
||||
meses"*, while `CONTEXT.md` and the implemented retention are 30 days maximum.
|
||||
This is a customer-facing commercial promise, so correct the copy or the policy —
|
||||
do not leave them disagreeing. Found 2026-09-18 while closing Block 0.
|
||||
|
||||
---
|
||||
|
||||
## Done
|
||||
|
||||
### Week 1 — infrastructure, uploads, service base
|
||||
|
||||
- `[x]` Compose stack: Site, Kanban, API, PostgreSQL, worker, ClamAV, R2/MinIO storage.
|
||||
- `[x]` Gitea + Portainer publication path; web service startup and API rollout fixed.
|
||||
- `[x]` Database passwords with special characters handled via discrete libpq fields.
|
||||
- `[x]` Kanban e-mail/password login; missing operator config no longer breaks stack boot.
|
||||
- `[x]` Direct resumable multipart browser → private object storage.
|
||||
- `[x]` Quarantine + ClamAV gate: only `clean` files can be quoted, paid, downloaded or queued.
|
||||
- `[x]` Retention worker: incomplete 1d, rejected 3d, originals 7d after approval, finals 30d.
|
||||
- `[x]` Server-side pricing authority with parity test against the Site JavaScript (4,444 cases).
|
||||
- `[x]` Loose-artwork packing flow: per-file width, copies, rotate, mirror, live 57 cm preview,
|
||||
5 mm gap, ruler and watermark preserved; metres follow packed height.
|
||||
- `[x]` Rotation/mirror applied to packing masks; stale renders no longer overwrite a newer preview.
|
||||
- `[x]` Hash-locked Python dependencies; Trivy reports in `output/security/`.
|
||||
|
||||
### Block 0 — 2026-09-18
|
||||
|
||||
- `[x]` `import os` restored in `local/auth.py`; `COOKIE_SECURE` is now a single
|
||||
module constant shared with `local/app.py`.
|
||||
- `[x]` Navigation links no longer preselect a product (`data-modo-cta` removed).
|
||||
- `[x]` Ready sheet vs loose artwork is an explicit, priced, reversible selector
|
||||
(`#tipoEnvio`), shown in all four modes and locked once a file is attached.
|
||||
The product is the declaration; `sel()` no longer switches anything silently.
|
||||
- `[x]` `medirFolha` returns `dpiFolha`; an image that cannot span the film width
|
||||
at `DPI_RECUSA` is refused as a sheet, with one click to send it as loose artwork.
|
||||
- `[x]` `pintaCaminhos` scoped to `#caminhos .cam` — its global `.cam` selector was
|
||||
clobbering the new control.
|
||||
- `[x]` `compose.local.yaml` restored (MinIO, fake providers, builds from source).
|
||||
- `[x]` `APP_DB_PASSWORD` separated from `POSTGRES_PASSWORD`, with a `bootstrap.py`
|
||||
guard that refuses identical credentials in both configuration forms.
|
||||
- `[x]` Checkout confirmation moved out of the panel the success path hides.
|
||||
|
||||
### Block 2 and CI — 2026-09-18
|
||||
|
||||
- `[x]` The web gateway overwrites `X-Forwarded-For` with the peer address instead
|
||||
of appending to it, and `client_ip()` resolves the requester for rate-limit
|
||||
buckets and security events. Verified: a forged `203.0.113.99` never reaches the
|
||||
audit trail.
|
||||
- `[x]` Guest sessions are limited per source. The first attempt used 30/IP, which
|
||||
the new regression caught as too tight for shared NAT — recreating the original
|
||||
fault in a narrower form — so the ceiling is 240 per 15 minutes, overridable with
|
||||
`GUEST_SESSION_LIMIT`.
|
||||
- `[x]` Security events now carry the source address (`operator_login_failed`,
|
||||
`customer_login_failed`, `cross_origin_rejected`, `http_security_event`).
|
||||
- `[x]` CI runs the integration suites against a real stack before publishing.
|
||||
|
||||
### 2026-09-21
|
||||
|
||||
- `[x]` 2.3 — `local/secrets.py` resolves every `<NAME>_FILE` into `<NAME>` from the
|
||||
API, worker and bootstrap entrypoints, failing closed on an unreadable or empty
|
||||
secret and on a value supplied both ways. Verified by booting the API, the worker
|
||||
and bootstrap with credentials supplied only as mounted files, including a
|
||||
password containing `:/?#[]&=+$ ,%`. `OPERATOR_USER` in the stack became
|
||||
`OPERATOR_EMAIL`, which is what the runtime reads.
|
||||
- `[x]` 2.5 — The gate now loads `local/secrets.py` and makes it resolve every
|
||||
secret `deploy/stack.yaml` declares, plus asserts it fails closed. Verified
|
||||
against a no-op loader (11 blockers) and one that swallows a missing file
|
||||
(1 blocker); only the real implementation passes. The four marker strings that
|
||||
stopped matching when R2 support landed were removed; the two describing real
|
||||
blockers stay, so the gate still refuses a release while the payment and
|
||||
messaging adapters are fake.
|
||||
|
||||
- `[x]` 2.4 — A blocking Trivy secret scan was added and verified both ways: a
|
||||
planted AWS key pair, GitHub token and private key block the job; the repository
|
||||
passes clean. Worth knowing: Trivy allowlists documented example credentials, so
|
||||
my first probe passed with AWS's own sample keys — the gate is a backstop, not
|
||||
permission to commit secrets. The source preflight now runs and always prints its
|
||||
verdict, enforcing only when `ENFORCE_PRODUCTION_PREFLIGHT` is `true`; enforcing
|
||||
it today would block every deploy, since it refuses a release while the adapters
|
||||
are fake. Image vulnerabilities are reported after each build, not enforced —
|
||||
56 HIGH and 3 CRITICAL, only 15 with an upstream fix. `PORTAINER.md` and
|
||||
`SECURITY_REPORT.md` now carry a table of what gates and what does not, replacing
|
||||
descriptions of checks that never ran.
|
||||
|
||||
- `[x]` 2.6 — Both bases pinned by digest, OS packages upgraded in the production
|
||||
images, and the web image moved off the nginx 1.28 line.
|
||||
|
||||
| Image | Before | After |
|
||||
|---|---|---|
|
||||
| API | 56 HIGH, 3 CRITICAL (15 fixable) | 46 HIGH, 0 CRITICAL |
|
||||
| Web | 5 HIGH, all unfixable in place | 0 HIGH, 0 CRITICAL |
|
||||
|
||||
The 1.28 nginx pins `nginx=1.28.3-r1` in `/etc/apk/world`, so `apk upgrade`
|
||||
cannot patch it even though Alpine ships `-r7`; `nginx:alpine` (1.31.6) is clean
|
||||
while `1.29-alpine` scans worse at 37 HIGH. The two remaining "fixable" API
|
||||
findings are `msgpack` and `setuptools`, which I confirmed are absent from the
|
||||
built image rather than trusting the earlier report. Local images now share the
|
||||
pinned bases, so the integration suite exercises what ships; full suite passes on
|
||||
nginx 1.31.6. With both images at zero CRITICAL, the image scan now **gates on
|
||||
CRITICAL** and reports HIGH.
|
||||
|
||||
### Reporting
|
||||
|
||||
- `[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"
|
||||
claim and the internal commit reference.
|
||||
141
agente/agente.py
@@ -1,141 +0,0 @@
|
||||
"""
|
||||
Agente da fábrica — traz a arte aprovada do portal para o servidor local.
|
||||
|
||||
Roda como serviço:
|
||||
Windows: nssm install DtfAgente "C:\\Python312\\python.exe" "C:\\dtf\\agente.py"
|
||||
Linux: systemd (ver dtf-agente.service no repositório)
|
||||
|
||||
Duas fontes de trabalho:
|
||||
- webhook do portal (chega na hora)
|
||||
- polling a cada 60 s (rede de segurança se o webhook falhar)
|
||||
|
||||
Se a internet cair, o agente para e o portal continua recebendo.
|
||||
Quando voltar, ele baixa o acumulado. Nada se perde.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import logging
|
||||
import os
|
||||
import sqlite3
|
||||
import time
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
|
||||
PORTAL = os.environ["BASE_PORTAL"]
|
||||
TOKEN = os.environ["AGENTE_TOKEN"]
|
||||
RAIZ = Path(os.environ.get("PASTA_DTF", r"\\servidor\DTF"))
|
||||
BANCO = Path(os.environ.get("KANBAN_DB", r"C:\dtf\kanban.db"))
|
||||
INTERVALO = 60
|
||||
HEARTBEAT = 300
|
||||
|
||||
PASTA_ENTRADA = RAIZ / "00_ARTE_RECEBIDA"
|
||||
|
||||
logging.basicConfig(
|
||||
filename=RAIZ / "_log" / "agente.log",
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(message)s",
|
||||
)
|
||||
log = logging.getLogger("agente")
|
||||
|
||||
|
||||
def sha256(caminho: Path) -> str:
|
||||
h = hashlib.sha256()
|
||||
with open(caminho, "rb") as f:
|
||||
for bloco in iter(lambda: f.read(1 << 20), b""):
|
||||
h.update(bloco)
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def registrar_no_kanban(arte: dict, arquivos: list[Path]) -> None:
|
||||
"""Insere o card. Idempotente: a chave é o arte_id, não o nome do arquivo."""
|
||||
con = sqlite3.connect(BANCO)
|
||||
try:
|
||||
con.execute("""
|
||||
CREATE TABLE IF NOT EXISTS card(
|
||||
arte_id INTEGER PRIMARY KEY,
|
||||
pedido TEXT, cliente TEXT, metros REAL,
|
||||
coluna TEXT DEFAULT 'rec', desde TEXT,
|
||||
maquina TEXT, partes INTEGER
|
||||
)""")
|
||||
con.execute("""
|
||||
INSERT OR IGNORE INTO card(arte_id,pedido,cliente,metros,desde,partes)
|
||||
VALUES (?,?,?,?,?,?)""",
|
||||
(arte["arte_id"], arte["pedido"], arte["cliente"],
|
||||
arte["metros"], datetime.now().isoformat(timespec="seconds"),
|
||||
len(arquivos)))
|
||||
con.commit()
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
|
||||
def baixar(cliente: httpx.Client, arte: dict) -> bool:
|
||||
PASTA_ENTRADA.mkdir(parents=True, exist_ok=True)
|
||||
salvos: list[Path] = []
|
||||
|
||||
for parte in arte["partes"]:
|
||||
destino = PASTA_ENTRADA / f"{arte['pedido']}_{parte['nome']}"
|
||||
if destino.exists():
|
||||
salvos.append(destino)
|
||||
continue
|
||||
tmp = destino.with_suffix(".parcial")
|
||||
with cliente.stream("GET", parte["url"]) as r:
|
||||
r.raise_for_status()
|
||||
with open(tmp, "wb") as f:
|
||||
for bloco in r.iter_bytes(1 << 20):
|
||||
f.write(bloco)
|
||||
tmp.rename(destino) # só aparece na pasta quando está completo
|
||||
salvos.append(destino)
|
||||
log.info("baixado %s (%s) sha=%s", destino.name,
|
||||
f"{parte['metros']:.2f} m", sha256(destino)[:12])
|
||||
|
||||
registrar_no_kanban(arte, salvos)
|
||||
cliente.post(f"{PORTAL}/api/artes/{arte['arte_id']}/baixada",
|
||||
headers={"x-token": TOKEN}, timeout=15)
|
||||
return True
|
||||
|
||||
|
||||
def ciclo(cliente: httpx.Client) -> int:
|
||||
r = cliente.get(f"{PORTAL}/api/artes", headers={"x-token": TOKEN}, timeout=30)
|
||||
r.raise_for_status()
|
||||
artes = r.json()
|
||||
for arte in artes:
|
||||
try:
|
||||
baixar(cliente, arte)
|
||||
except Exception as e:
|
||||
log.error("falha na arte %s: %s", arte["arte_id"], e)
|
||||
return len(artes)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
log.info("agente iniciado · portal=%s · pasta=%s", PORTAL, RAIZ)
|
||||
ultimo_hb = 0.0
|
||||
with httpx.Client(follow_redirects=True) as cliente:
|
||||
while True:
|
||||
try:
|
||||
n = ciclo(cliente)
|
||||
if n:
|
||||
log.info("%d arte(s) processada(s)", n)
|
||||
except httpx.HTTPError as e:
|
||||
# internet caiu: não é erro fatal, o portal segue recebendo
|
||||
log.warning("sem conexão com o portal: %s", e)
|
||||
except Exception as e:
|
||||
log.exception("erro inesperado: %s", e)
|
||||
|
||||
agora = time.time()
|
||||
if agora - ultimo_hb > HEARTBEAT:
|
||||
try:
|
||||
cliente.post(f"{PORTAL}/api/agente/heartbeat",
|
||||
headers={"x-token": TOKEN}, timeout=10)
|
||||
ultimo_hb = agora
|
||||
except Exception:
|
||||
pass # sem sinal por 15 min, o portal alerta o TI
|
||||
|
||||
time.sleep(INTERVALO)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,14 +0,0 @@
|
||||
[Unit]
|
||||
Description=Agente DTF - baixa artes do portal
|
||||
After=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=dtf
|
||||
EnvironmentFile=/etc/dtf/.env
|
||||
ExecStart=/usr/bin/python3 /opt/dtf/agente.py
|
||||
Restart=always
|
||||
RestartSec=15
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
276
app/adapters.py
Normal file
@@ -0,0 +1,276 @@
|
||||
"""Local-only composition root. No production provider implementations/imports."""
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
from typing import Mapping, NamedTuple, Protocol
|
||||
from urllib.parse import urlparse
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
from botocore.exceptions import ClientError
|
||||
|
||||
def require_runtime():
|
||||
"""Validate the supported local and R2-backed deployment modes.
|
||||
|
||||
Each provider is fake until its settings are complete; a real one refuses
|
||||
to start without them.
|
||||
"""
|
||||
environment = os.environ.get('APP_ENV', 'local')
|
||||
freight = os.environ.get('FREIGHT_ADAPTER')
|
||||
if freight == 'jadlog':
|
||||
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')
|
||||
if tiny == 'tiny':
|
||||
from .tiny import required_settings
|
||||
for name in required_settings():
|
||||
if not os.environ.get(name):
|
||||
raise RuntimeError(f'{name} is required for the Tiny adapter')
|
||||
elif tiny != 'fake':
|
||||
raise RuntimeError('TINY must use the fake or tiny adapter')
|
||||
# Mercado Pago is selectable only with its credentials present; it has not
|
||||
# yet passed the sandbox flows, so production preflight still blocks it.
|
||||
payment = os.environ.get('PAYMENT_ADAPTER')
|
||||
if payment == 'mercadopago':
|
||||
for name in ('MP_ACCESS_TOKEN', 'MP_WEBHOOK_SECRET'):
|
||||
if not os.environ.get(name):
|
||||
raise RuntimeError(f'{name} is required for the Mercado Pago adapter')
|
||||
elif payment != 'fake':
|
||||
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 os.environ.get('STORAGE_ADAPTER') != 's3-local':
|
||||
raise RuntimeError('Local runtime requires local S3 storage')
|
||||
for name in ('S3_ENDPOINT', 'S3_PUBLIC_ENDPOINT'):
|
||||
endpoint = urlparse(os.environ[name])
|
||||
if endpoint.scheme != 'http' or endpoint.hostname not in ('storage', 'localhost', '127.0.0.1'):
|
||||
raise RuntimeError(f'{name} must point to local MinIO')
|
||||
return
|
||||
if environment != 'production':
|
||||
raise RuntimeError('APP_ENV must be local or production')
|
||||
if os.environ.get('STORAGE_ADAPTER') != 's3-r2':
|
||||
raise RuntimeError('Production runtime requires R2 storage')
|
||||
for name in ('S3_ENDPOINT', 'S3_PUBLIC_ENDPOINT'):
|
||||
endpoint = urlparse(os.environ[name])
|
||||
if endpoint.scheme != 'https' or not (endpoint.hostname or '').endswith('.r2.cloudflarestorage.com'):
|
||||
raise RuntimeError(f'{name} must be a Cloudflare R2 S3 API endpoint')
|
||||
for name in ('AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY'):
|
||||
if not os.environ.get(name):
|
||||
raise RuntimeError(f'{name} is required for R2')
|
||||
|
||||
|
||||
# Compatibility alias for local-only callers outside the active runtime.
|
||||
require_local = require_runtime
|
||||
|
||||
class PaymentEvent(NamedTuple):
|
||||
"""One provider notification, normalised.
|
||||
|
||||
`event_id` identifies the delivery and makes it idempotent. `reference` is
|
||||
our quote id, echoed back by the provider. `amount_cents` is what the
|
||||
provider says was actually paid, which the service compares against the
|
||||
approved total before it will create an order.
|
||||
"""
|
||||
event_id: str
|
||||
reference: str
|
||||
status: str # 'approved' | 'rejected' | 'pending' | 'refunded'
|
||||
amount_cents: int | None
|
||||
raw: dict
|
||||
|
||||
|
||||
class PaymentAdapter(Protocol):
|
||||
def create(self, quote_id: str, total_cents: int, customer: dict, method: dict | None = None) -> dict:
|
||||
"""Start a payment. Must be idempotent on quote_id: a retry after a
|
||||
timeout has to return the existing payment, never charge twice."""
|
||||
|
||||
def verify(self, headers: Mapping[str, str], body: bytes, query: Mapping[str, str] | None = None) -> bool:
|
||||
"""Whether this delivery genuinely came from the provider."""
|
||||
|
||||
def parse(self, body: bytes, query: Mapping[str, str] | None = None) -> PaymentEvent | None:
|
||||
"""Normalise a verified delivery, or None if it is not about a payment."""
|
||||
|
||||
|
||||
class FakePayment:
|
||||
"""Local stand-in with a real signature scheme, so the webhook path is
|
||||
exercised end to end rather than waiting for a provider account.
|
||||
|
||||
Signs the body with HMAC-SHA256 under PAYMENT_WEBHOOK_SECRET. A real adapter
|
||||
replaces verify() and parse() with the provider's own scheme; nothing else in
|
||||
the service changes.
|
||||
"""
|
||||
|
||||
name = 'fake'
|
||||
header = 'x-payment-signature'
|
||||
|
||||
def _secret(self) -> bytes | None:
|
||||
secret = os.environ.get('PAYMENT_WEBHOOK_SECRET', '')
|
||||
return secret.encode() if secret else None
|
||||
|
||||
def create(self, quote_id: str, total_cents: int, customer: dict, method: dict | None = None) -> dict:
|
||||
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}',
|
||||
'status': 'pending', 'total_cents': total_cents}
|
||||
|
||||
def sign(self, body: bytes) -> str:
|
||||
secret = self._secret()
|
||||
if secret is None:
|
||||
raise RuntimeError('PAYMENT_WEBHOOK_SECRET is not configured')
|
||||
return hmac.new(secret, body, hashlib.sha256).hexdigest()
|
||||
|
||||
def verify(self, headers, body: bytes, query=None) -> bool:
|
||||
# No configured secret means nothing can be verified, so nothing is
|
||||
# accepted. A guessable default would let anyone forge an approval and
|
||||
# create an order that was never paid for.
|
||||
if self._secret() is None:
|
||||
return False
|
||||
supplied = headers.get(self.header) or headers.get(self.header.title()) or ''
|
||||
return hmac.compare_digest(supplied, self.sign(body))
|
||||
|
||||
def parse(self, body: bytes, query=None):
|
||||
try:
|
||||
data = json.loads(body)
|
||||
except ValueError:
|
||||
return None
|
||||
if not isinstance(data, dict) or 'event_id' not in data:
|
||||
return None
|
||||
return PaymentEvent(event_id=str(data['event_id']),
|
||||
reference=str(data.get('reference', '')),
|
||||
status=str(data.get('status', 'pending')),
|
||||
amount_cents=data.get('amount_cents'),
|
||||
raw=data)
|
||||
|
||||
# The local development checkout still needs a direct "it is paid" path.
|
||||
def pay(self, quote_id: str, total_cents: int) -> dict:
|
||||
return {'provider': 'fake', 'id': f'local-{quote_id}',
|
||||
'status': 'paid', 'total_cents': total_cents}
|
||||
|
||||
class FreightAdapter(Protocol):
|
||||
def quote(self, service: str, postal_code: str, metres=None, declared_cents: int = 0) -> dict: ...
|
||||
|
||||
class FakeFreight:
|
||||
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':
|
||||
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():
|
||||
raise ValueError('Select pickup or a mock quote with an eight-digit CEP')
|
||||
cents = int(os.environ.get('MOCK_FREIGHT_CENTS', '1500'))
|
||||
if cents < 0:
|
||||
raise ValueError('Invalid mock freight configuration')
|
||||
return {'provider': 'fake', 'service': service, 'postal_code': postal_code,
|
||||
'total_cents': cents, 'description': 'Entrega simulada'}
|
||||
|
||||
class EventAdapter(Protocol):
|
||||
def deliver(self, event_key: str, payload: dict) -> dict: ...
|
||||
|
||||
class FakeTiny:
|
||||
def deliver(self, event_key: str, payload: dict) -> dict:
|
||||
return {'provider': 'fake-tiny', 'reference': f"LOCAL-{payload['number']}",
|
||||
'event_key': event_key, 'status': 'recorded-locally'}
|
||||
|
||||
class ObjectStorage(Protocol):
|
||||
def begin(self, key: str) -> str: ...
|
||||
def parts(self, key: str, upload_id: str) -> list: ...
|
||||
def part_url(self, key: str, upload_id: str, part: int, size: int) -> str: ...
|
||||
def complete(self, key: str, upload_id: str, parts: list): ...
|
||||
def size(self, key: str) -> int: ...
|
||||
def download(self, key: str, name: str) -> str: ...
|
||||
def fetch(self, key: str, path: str): ...
|
||||
def store(self, key: str, path: str, content_type: str): ...
|
||||
def health(self): ...
|
||||
def discard(self, key: str, upload_id: str, complete: bool): ...
|
||||
|
||||
class LocalS3Storage:
|
||||
def __init__(self):
|
||||
config = Config(signature_version='s3v4', s3={'addressing_style': 'path'},
|
||||
connect_timeout=3, read_timeout=10, retries={'max_attempts': 2})
|
||||
self.client = boto3.client('s3', endpoint_url=os.environ['S3_ENDPOINT'], config=config)
|
||||
self.public = boto3.client('s3', endpoint_url=os.environ['S3_PUBLIC_ENDPOINT'], config=config)
|
||||
self.bucket = os.environ['S3_BUCKET']
|
||||
|
||||
def initialize(self):
|
||||
try:
|
||||
self.client.head_bucket(Bucket=self.bucket)
|
||||
except ClientError as exc:
|
||||
if exc.response['ResponseMetadata']['HTTPStatusCode'] != 404:
|
||||
raise
|
||||
self.client.create_bucket(Bucket=self.bucket)
|
||||
self.client.put_bucket_lifecycle_configuration(Bucket=self.bucket, LifecycleConfiguration={
|
||||
'Rules': [{'ID': 'local-artwork-retention', 'Status': 'Enabled', 'Filter': {'Prefix': ''},
|
||||
'Expiration': {'Days': 30}, 'AbortIncompleteMultipartUpload': {'DaysAfterInitiation': 1}}]})
|
||||
|
||||
def health(self):
|
||||
self.client.head_bucket(Bucket=self.bucket)
|
||||
|
||||
def begin(self, key):
|
||||
return self.client.create_multipart_upload(Bucket=self.bucket, Key=key,
|
||||
ContentType='application/octet-stream')['UploadId']
|
||||
|
||||
def parts(self, key, upload_id):
|
||||
result = []
|
||||
for page in self.client.get_paginator('list_parts').paginate(
|
||||
Bucket=self.bucket, Key=key, UploadId=upload_id):
|
||||
result.extend(page.get('Parts', []))
|
||||
return result
|
||||
|
||||
def part_url(self, key, upload_id, part, size):
|
||||
return self.public.generate_presigned_url('upload_part', Params={
|
||||
'Bucket': self.bucket, 'Key': key, 'UploadId': upload_id, 'PartNumber': part,
|
||||
'ContentLength': size}, ExpiresIn=900)
|
||||
|
||||
def complete(self, key, upload_id, parts):
|
||||
self.client.complete_multipart_upload(Bucket=self.bucket, Key=key, UploadId=upload_id,
|
||||
MultipartUpload={'Parts': [{'PartNumber': p['PartNumber'], 'ETag': p['ETag']} for p in parts]})
|
||||
|
||||
def size(self, key):
|
||||
return self.client.head_object(Bucket=self.bucket, Key=key)['ContentLength']
|
||||
|
||||
def fetch(self, key, path):
|
||||
"""Copy a stored object to a local file (the worker's scratch space)."""
|
||||
self.client.download_file(self.bucket, key, path)
|
||||
|
||||
def store(self, key, path, content_type):
|
||||
"""Upload a file the service generated itself, such as a print file."""
|
||||
self.client.upload_file(path, self.bucket, key, ExtraArgs={'ContentType': content_type})
|
||||
|
||||
def download(self, key, name):
|
||||
from urllib.parse import quote
|
||||
return self.public.generate_presigned_url('get_object', Params={
|
||||
'Bucket': self.bucket, 'Key': key,
|
||||
'ResponseContentDisposition': "attachment; filename*=UTF-8''" + quote(name, safe=''),
|
||||
'ResponseContentType': 'application/octet-stream'}, ExpiresIn=300)
|
||||
|
||||
def discard(self, key, upload_id, complete):
|
||||
if not complete:
|
||||
try:
|
||||
self.client.abort_multipart_upload(Bucket=self.bucket, Key=key, UploadId=upload_id)
|
||||
except ClientError as exc:
|
||||
if exc.response['ResponseMetadata']['HTTPStatusCode'] != 404:
|
||||
raise
|
||||
self.client.delete_object(Bucket=self.bucket, Key=key)
|
||||
2
app/api/__init__.py
Normal file
@@ -0,0 +1,2 @@
|
||||
"""HTTP routers, one per resource. They import from local.runtime, never
|
||||
from each other or from local.app."""
|
||||
55
app/api/artwork.py
Normal file
@@ -0,0 +1,55 @@
|
||||
"""Operator artwork handling: final files, and the uploads that carry them.
|
||||
|
||||
These reuse the customer upload routes with the operator's derived identity, so
|
||||
one transport serves both and there is only one place where parts are signed.
|
||||
"""
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
|
||||
from ..core import db
|
||||
from ..artwork import submit_files
|
||||
from ..core.auth import can, operator
|
||||
from ..core.models import ArtworkSubmission, UploadStart
|
||||
from ..runtime import file_rows, operator_identity
|
||||
from .uploads import begin_upload, cancel_upload, complete_upload, part_url, upload_status
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.post('/api/operator/orders/{oid}/uploads')
|
||||
def begin_final(oid: UUID, body: UploadStart, user=Depends(can('produce'))):
|
||||
with db.connect() as c:
|
||||
row = c.execute('SELECT state FROM dtf_local.orders WHERE id=%s', (oid,)).fetchone()
|
||||
if not row: raise HTTPException(404, 'Order not found')
|
||||
if row['state'] not in ('rec','cor'): raise HTTPException(409, 'Order is not in artwork review')
|
||||
return begin_upload(body, session_id=operator_identity(user))
|
||||
|
||||
@router.get('/api/operator/uploads/{uid}')
|
||||
def final_status(uid: UUID, user=Depends(operator)):
|
||||
return upload_status(uid,session_id=operator_identity(user))
|
||||
|
||||
# The parts of an upload its operator started: a final (produce) or the
|
||||
# photo of a signed pickup receipt (deliver, which includes produce).
|
||||
@router.post('/api/operator/uploads/{uid}/parts/{number}')
|
||||
def final_part(uid: UUID, number: int, user=Depends(can('deliver'))):
|
||||
return part_url(uid,number,session_id=operator_identity(user))
|
||||
|
||||
@router.post('/api/operator/uploads/{uid}/complete')
|
||||
def final_complete(uid: UUID, user=Depends(can('deliver'))):
|
||||
return complete_upload(uid,session_id=operator_identity(user))
|
||||
|
||||
@router.delete('/api/operator/uploads/{uid}')
|
||||
def final_cancel(uid: UUID, user=Depends(can('deliver'))):
|
||||
return cancel_upload(uid,session_id=operator_identity(user))
|
||||
|
||||
@router.get('/api/operator/orders/{oid}/files')
|
||||
def operator_files(oid: UUID, user=Depends(operator)):
|
||||
with db.connect() as c:
|
||||
return file_rows(c,oid)
|
||||
|
||||
@router.post('/api/operator/orders/{oid}/final-files')
|
||||
def final_files(oid: UUID, body: ArtworkSubmission, user=Depends(can('produce'))):
|
||||
with db.connect() as c:
|
||||
order = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (oid,)).fetchone()
|
||||
if not order: raise HTTPException(404, 'Order not found')
|
||||
return submit_files(c,order,body,operator_identity(user),'final',user)
|
||||
523
app/api/customer.py
Normal file
@@ -0,0 +1,523 @@
|
||||
"""Customer accounts, their orders, and the corrections they submit."""
|
||||
import hashlib
|
||||
import secrets
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from typing import Literal
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response
|
||||
from psycopg.errors import UniqueViolation
|
||||
from psycopg.types.json import Jsonb
|
||||
|
||||
from ..core import db
|
||||
from ..artwork import submit_files
|
||||
from ..core.auth import (DUMMY_PASSWORD_HASH, audit, client_ip, new_session, owner, login_failed, password_hash,
|
||||
password_matches, rate_limit, session_row, throttle, transfer_guest)
|
||||
from ..core.models import (ArtworkSubmission, EmailChange, EmailCode, EmailResend, ForgotPassword, Login,
|
||||
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
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def current(request):
|
||||
try: return session_row(request)
|
||||
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')
|
||||
def register(body: Register, request: Request, response: Response):
|
||||
email = body.customer.mail.strip().lower()
|
||||
throttle(email, request)
|
||||
# Registration attempts keep counting against the email, as before.
|
||||
login_failed(email)
|
||||
previous = current(request)
|
||||
profile = body.customer.model_dump()
|
||||
profile['mail'] = email
|
||||
with db.connect() as c:
|
||||
if previous and c.execute('SELECT id FROM dtf_local.accounts WHERE id=%s', (previous['owner'],)).fetchone():
|
||||
raise HTTPException(409, 'Saia da conta atual antes de criar outra.')
|
||||
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 verified: claim_orders(c, identity, profile)
|
||||
new_session(c, response, identity)
|
||||
except UniqueViolation:
|
||||
raise HTTPException(409, 'Já existe uma conta com este e-mail. Entre com a sua senha.')
|
||||
audit('account_registered', account=str(identity))
|
||||
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')
|
||||
def login(body: Login, request: Request, response: Response):
|
||||
email = body.email.strip().lower()
|
||||
throttle(email, request)
|
||||
with db.connect() as c:
|
||||
account = c.execute('SELECT * FROM dtf_local.accounts WHERE email=%s', (email,)).fetchone()
|
||||
# Comparable password work even when the email is absent.
|
||||
stored = account['password_hash'] if account else DUMMY_PASSWORD_HASH
|
||||
matches = password_matches(body.password, stored)
|
||||
if not account or not matches:
|
||||
login_failed(email)
|
||||
audit('customer_login_failed', ip=client_ip(request))
|
||||
raise HTTPException(401, 'E-mail ou senha inválidos.')
|
||||
previous = current(request)
|
||||
with db.connect() as c:
|
||||
if not stored.startswith('scrypt-v2$'):
|
||||
c.execute('UPDATE dtf_local.accounts SET password_hash=%s WHERE id=%s', (password_hash(body.password),account['id']))
|
||||
if previous:
|
||||
transfer_guest(c, previous, account['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'])
|
||||
audit('customer_login_success', account=str(account['id']))
|
||||
return {'customer': account['profile']}
|
||||
|
||||
@router.post('/api/account/logout')
|
||||
def logout(request: Request, response: Response):
|
||||
previous = current(request)
|
||||
if previous:
|
||||
with db.connect() as c:
|
||||
c.execute('DELETE FROM dtf_local.sessions WHERE id=%s', (previous['id'],))
|
||||
response.delete_cookie('dtf_session', httponly=True, samesite='strict')
|
||||
response.headers['Clear-Site-Data'] = '"storage"'
|
||||
audit('customer_logout')
|
||||
return {'ok': True}
|
||||
|
||||
@router.get('/api/account/me')
|
||||
def me(identity=Depends(owner)):
|
||||
with db.connect() as c:
|
||||
row = c.execute('SELECT profile FROM dtf_local.accounts WHERE id=%s', (identity,)).fetchone()
|
||||
return {'customer': row['profile'] if row else None}
|
||||
|
||||
def account_row(c, identity, lock=False):
|
||||
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:
|
||||
row = account_row(c, identity, lock=True)
|
||||
profile = {**row['profile'], 'zap': body.zap,
|
||||
'address': body.address.model_dump() if body.address else None}
|
||||
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}')
|
||||
def detail(oid: UUID, identity=Depends(owner)):
|
||||
with db.connect() as c:
|
||||
row = owned_order(c, oid, identity)
|
||||
# A move back undoes an operator's mistake and its reason is internal;
|
||||
# only a correction's reason is written for the customer.
|
||||
history = c.execute('''SELECT from_state,to_state,CASE WHEN to_state='cor' THEN reason ELSE '' END AS reason,
|
||||
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')
|
||||
def correction(oid: UUID, body: ArtworkSubmission, identity=Depends(owner)):
|
||||
with db.connect() as c:
|
||||
order = owned_order(c, oid, identity, lock=True)
|
||||
return submit_files(c,order,body,identity,'correction','customer')
|
||||
|
||||
@router.get('/api/customer/orders/{oid}/files/{fid}/download')
|
||||
def customer_download(oid: UUID, fid: UUID, identity=Depends(owner)):
|
||||
with db.connect() as c:
|
||||
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()
|
||||
if not row: raise HTTPException(404, 'Arquivo não encontrado.')
|
||||
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)
|
||||
return {'url':storage.download(row['object_key'],row['name']), 'name':row['name']}
|
||||
90
app/api/health.py
Normal file
@@ -0,0 +1,90 @@
|
||||
"""Health, session bootstrap, freight quoting and the address of a CEP."""
|
||||
import os
|
||||
import re
|
||||
|
||||
import httpx
|
||||
from fastapi import APIRouter, HTTPException, Request, Response
|
||||
|
||||
from ..core import db
|
||||
from .. import mail
|
||||
from ..core.auth import client_ip, owner, new_session, rate_limit
|
||||
from ..core.limits import upload_limit_bytes
|
||||
from ..core.pricing import manual_extra_cents
|
||||
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.get('/health')
|
||||
@router.get('/api/health')
|
||||
def health():
|
||||
try:
|
||||
with db.connect() as c:
|
||||
c.execute('SELECT 1')
|
||||
storage.health()
|
||||
except Exception:
|
||||
raise HTTPException(503, 'Database or storage unavailable')
|
||||
return {'status': 'ok', 'environment': ENVIRONMENT,
|
||||
'storage': 'minio' if ENVIRONMENT == 'local' else 'r2', 'integrations': 'fake'}
|
||||
|
||||
@router.get('/api/session')
|
||||
def session(request: Request, response: Response):
|
||||
try:
|
||||
session_id = owner(request)
|
||||
except HTTPException:
|
||||
# Per source, not per deployment: keyed on the environment name this was a
|
||||
# single global bucket, so ~8 new visitors a minute exhausted it site-wide.
|
||||
rate_limit('guest-sessions', client_ip(request), GUEST_SESSION_LIMIT, 900)
|
||||
with db.connect() as c:
|
||||
session_id = new_session(c, response)
|
||||
return {'environment': ENVIRONMENT, 'cart_scope': str(session_id), 'part_bytes': PART_BYTES,
|
||||
'max_upload_bytes': upload_limit_bytes(), 'payment_provider': payment.name,
|
||||
'password_recovery': mail.configured(),
|
||||
# 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.
|
||||
'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')
|
||||
def quote_freight(body: FreightEstimate):
|
||||
require_delivery_available(body.service)
|
||||
try:
|
||||
return freight.quote(body.service, body.postal_code, body.metres, body.declared_cents)
|
||||
except ValueError as 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 ''}
|
||||
1388
app/api/operator.py
Normal file
38
app/api/orders.py
Normal file
@@ -0,0 +1,38 @@
|
||||
"""Local development checkout.
|
||||
|
||||
The real path is the provider webhook. This exists so the local stack can reach
|
||||
a paid order without a provider account, and it goes through the same service so
|
||||
the two cannot drift apart.
|
||||
"""
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
|
||||
from .. import payments
|
||||
from ..core import db
|
||||
from ..core.auth import owner
|
||||
from ..core.models import Pay
|
||||
from ..runtime import ENVIRONMENT, payment
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post('/api/orders/dev-paid')
|
||||
def dev_paid(body: Pay, session_id=Depends(owner)):
|
||||
if ENVIRONMENT != 'local':
|
||||
raise HTTPException(503, 'Checkout is not configured yet')
|
||||
with db.connect() as c:
|
||||
try:
|
||||
quote = payments.approved_quote(c, body.quote_id, session_id)
|
||||
except payments.PaymentRefused as refusal:
|
||||
# The quote may already be paid; that is not a refusal.
|
||||
existing = c.execute('SELECT * FROM dtf_local.orders WHERE quote_id=%s AND owner=%s',
|
||||
(body.quote_id, session_id)).fetchone()
|
||||
if existing:
|
||||
return existing
|
||||
raise HTTPException(404 if 'not found' in str(refusal) else 409, str(refusal))
|
||||
# The charge happens inside the transaction that persists the order, so a
|
||||
# failure to record it cannot leave a customer charged without an order.
|
||||
receipt = payment.pay(str(body.quote_id), quote['approved']['total_cents'])
|
||||
order, _ = payments.create_order(c, quote, receipt, 'site')
|
||||
return order
|
||||
174
app/api/payments.py
Normal file
@@ -0,0 +1,174 @@
|
||||
"""The provider's callback.
|
||||
|
||||
Unauthenticated by necessity — a payment provider has no session — so the
|
||||
signature is the only thing standing between this endpoint and an attacker
|
||||
creating orders. It is verified before the body is parsed, let alone acted on,
|
||||
and an unverified delivery is recorded and refused rather than retried.
|
||||
"""
|
||||
from uuid import uuid4
|
||||
|
||||
import httpx
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from psycopg.types.json import Jsonb
|
||||
|
||||
from .. import payment_messages as messages, payments
|
||||
from ..core import db
|
||||
from ..core.auth import audit, client_ip, owner, rate_limit
|
||||
from ..core.models import PaymentIntent
|
||||
from ..runtime import payment
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
# Generous: a provider legitimately retries, and a signature check is cheap.
|
||||
# This exists so an unsigned flood cannot keep the database busy.
|
||||
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')
|
||||
async def webhook(request: Request):
|
||||
rate_limit('payment-webhook', client_ip(request), WEBHOOK_LIMIT, 900)
|
||||
body = await request.body()
|
||||
|
||||
query = dict(request.query_params)
|
||||
if not payment.verify(request.headers, body, query):
|
||||
# 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')
|
||||
|
||||
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)
|
||||
if event is None:
|
||||
# Verified, so genuinely from the provider, but not about a payment.
|
||||
# Acknowledge it: refusing would make the provider retry for ever.
|
||||
return {'status': 'ignored'}
|
||||
|
||||
with db.connect() as c:
|
||||
stored = payments.record(c, event_provider(), event)
|
||||
if stored is None:
|
||||
# Already delivered. Acknowledge without acting again.
|
||||
return {'status': 'duplicate'}
|
||||
outcome = payments.apply(c, event)
|
||||
c.execute('UPDATE dtf_local.payment_events SET processed_at=now(), outcome=%s WHERE id=%s',
|
||||
(outcome, stored['id']))
|
||||
|
||||
# audit()'s own first parameter is named `event`, so the id goes under another key.
|
||||
audit('payment_webhook_applied', payment_event=event.event_id,
|
||||
status=event.status, outcome=outcome)
|
||||
return {'status': 'applied', 'outcome': outcome}
|
||||
|
||||
|
||||
def event_provider():
|
||||
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')
|
||||
def intent(body: PaymentIntent, session_id=Depends(owner)):
|
||||
"""Start paying an approved quote: a PIX code, or a card token from the
|
||||
provider's own form. Asking twice for the same method returns the same
|
||||
payment; a quote already paid returns 409."""
|
||||
rate_limit('payment-intent', str(session_id), 30, 900)
|
||||
with db.connect() as c:
|
||||
try:
|
||||
quote = payments.approved_quote(c, body.quote_id, session_id)
|
||||
except payments.PaymentRefused as 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():
|
||||
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
|
||||
# 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
|
||||
AND (status='approved' OR (method='card' AND status='pending'
|
||||
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':
|
||||
# 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()
|
||||
if existing and not existing['expired']:
|
||||
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:
|
||||
created = payment.create(str(body.quote_id), quote['approved']['total_cents'],
|
||||
quote['approved']['customer'], method)
|
||||
except ValueError:
|
||||
raise HTTPException(422, 'Esta forma de pagamento não é aceita. Pague com cartão de crédito ou PIX.')
|
||||
except httpx.HTTPStatusError as exc:
|
||||
# Mercado Pago's own reason (status, message and cause codes) goes to
|
||||
# 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,
|
||||
status,amount_cents,response) VALUES(%s,%s,%s,%s,%s,%s,%s,%s)
|
||||
ON CONFLICT(provider,provider_payment_id) DO NOTHING''',
|
||||
(uuid4(), body.quote_id, payment.name, created['id'], body.method.type,
|
||||
created['status'], quote['approved']['total_cents'], Jsonb(created)))
|
||||
return created
|
||||
84
app/api/quotes.py
Normal file
@@ -0,0 +1,84 @@
|
||||
"""Quotes: the customer's cart, approved at once when it can be (app/quote_review.py)."""
|
||||
import hashlib
|
||||
import json
|
||||
from decimal import Decimal
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from psycopg.types.json import Jsonb
|
||||
|
||||
from .. import payments
|
||||
from ..core import db
|
||||
from ..core.auth import owner
|
||||
from ..core.models import QuoteRequest
|
||||
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
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.post('/api/quotes')
|
||||
def create_quote(body: QuoteRequest, session_id=Depends(owner)):
|
||||
for item in body.items:
|
||||
if abs(item.metres*100-item.production.height_cm) > Decimal('0.02'):
|
||||
raise HTTPException(422, 'A metragem não confere com a montagem enviada. Monte o pedido de novo.')
|
||||
require_delivery_available(body.freight.service)
|
||||
draft = body.model_dump(mode='json', exclude={'request_key'})
|
||||
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:
|
||||
priced = [price(item.mode, str(item.metres), item.grade) for item in body.items]
|
||||
freight.quote(body.freight.service, body.freight.postal_code,
|
||||
sum(Decimal(i['billed_metres']) for i in priced), sum(i['total_cents'] for i in priced))
|
||||
except ValueError as exc:
|
||||
raise HTTPException(422, str(exc))
|
||||
with db.connect() as c:
|
||||
rows = {}
|
||||
for item in body.items:
|
||||
for uid in item.uploads:
|
||||
row = upload_row(c, uid, session_id)
|
||||
if not row['complete']:
|
||||
raise HTTPException(409, 'Espere o envio de todos os arquivos terminar antes de continuar.')
|
||||
# No transparency: the background prints, and loose art packs as a box (2026-10-23).
|
||||
if row['name'].lower().endswith(('.jpg', '.jpeg')):
|
||||
raise HTTPException(422, 'JPG não tem fundo transparente. Envie a arte em PNG ou PDF.')
|
||||
require_clean(row)
|
||||
rows[str(uid)] = row
|
||||
# The grade came from the browser and is shown with the order (it no
|
||||
# longer sets the price): before a cart is approved at checkout, the
|
||||
# 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()
|
||||
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), note))
|
||||
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:
|
||||
raise HTTPException(409, 'O carrinho mudou durante o envio. Tente de novo.')
|
||||
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}')
|
||||
def get_quote(uid: UUID, session_id=Depends(owner)):
|
||||
with db.connect() as c:
|
||||
row = c.execute('SELECT * FROM dtf_local.quotes WHERE id=%s AND owner=%s', (uid,session_id)).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(404, 'Pedido não encontrado.')
|
||||
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
|
||||
142
app/api/uploads.py
Normal file
@@ -0,0 +1,142 @@
|
||||
"""Customer uploads: reservation, signed parts, completion.
|
||||
|
||||
The operator artwork routes reuse these functions directly with a different
|
||||
identity, which is why they are plain functions with a session_id argument.
|
||||
"""
|
||||
import math
|
||||
import os
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from botocore.exceptions import ClientError
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
|
||||
from ..core import db
|
||||
from ..core.auth import audit, owner, rate_limit
|
||||
from ..core.limits import upload_limit_bytes
|
||||
from ..core.models import UploadStart
|
||||
from ..payments import UNPAID_HOLD
|
||||
from ..runtime import PART_BYTES, storage, upload_row
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.post('/api/uploads')
|
||||
def begin_upload(body: UploadStart, session_id=Depends(owner)):
|
||||
if body.size > upload_limit_bytes():
|
||||
raise HTTPException(413, 'O arquivo passa do tamanho máximo aceito. Escolha um arquivo menor.')
|
||||
uid = uuid4()
|
||||
key = f'originals/{uid}'
|
||||
rate_limit('upload-start', str(session_id), 60, 900)
|
||||
with db.connect() as c:
|
||||
# Serialize reservations across API processes, including changing guest IDs.
|
||||
c.execute('SELECT pg_advisory_xact_lock(804208)')
|
||||
usage = c.execute('''SELECT COALESCE(sum(size),0) AS total,
|
||||
COALESCE(sum(size) FILTER(WHERE owner=%s),0) AS owned,
|
||||
count(*) FILTER(WHERE owner=%s AND NOT complete) AS pending
|
||||
FROM dtf_local.uploads WHERE purged_at IS NULL''',
|
||||
(session_id,session_id)).fetchone()
|
||||
if (usage['total']+body.size > int(os.environ.get('STORAGE_QUOTA_BYTES','53687091200')) or
|
||||
usage['owned']+body.size > int(os.environ.get('OWNER_UPLOAD_QUOTA_BYTES','10737418240')) or
|
||||
usage['pending'] >= int(os.environ.get('MAX_PENDING_UPLOADS','10'))):
|
||||
audit('upload_quota_rejected')
|
||||
raise HTTPException(429, 'Limite de armazenamento ou de envios pendentes atingido. Tente de novo mais tarde.')
|
||||
multipart = storage.begin(key)
|
||||
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')''',
|
||||
(uid, session_id, body.name, body.size, key, multipart))
|
||||
return {'id': uid, 'part_bytes': PART_BYTES}
|
||||
|
||||
@router.get('/api/uploads/{uid}')
|
||||
def upload_status(uid: UUID, session_id=Depends(owner)):
|
||||
with db.connect() as c:
|
||||
row = upload_row(c, uid, session_id)
|
||||
parts = [] if row['complete'] else storage.parts(row['object_key'], row['multipart_id'])
|
||||
return {'id': uid, 'complete': row['complete'], 'part_bytes': PART_BYTES,
|
||||
'scan_state':row['scan_state'], 'scan_reason':row['scan_reason'],
|
||||
'parts': [p['PartNumber'] for p in parts]}
|
||||
|
||||
@router.post('/api/uploads/{uid}/parts/{part}')
|
||||
def part_url(uid: UUID, part: int, session_id=Depends(owner)):
|
||||
with db.connect() as c:
|
||||
row = upload_row(c, uid, session_id)
|
||||
if row['complete'] or not 1 <= part <= math.ceil(row['size'] / PART_BYTES):
|
||||
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)
|
||||
return {'url': storage.part_url(row['object_key'], row['multipart_id'], part, size)}
|
||||
|
||||
@router.post('/api/uploads/{uid}/complete')
|
||||
def complete_upload(uid: UUID, session_id=Depends(owner)):
|
||||
with db.connect() as c:
|
||||
row = upload_row(c, uid, session_id, lock=True)
|
||||
if row['complete']:
|
||||
return {'id': uid, 'complete': True}
|
||||
try:
|
||||
existing_size = storage.size(row['object_key'])
|
||||
except ClientError as exc:
|
||||
if exc.response['ResponseMetadata']['HTTPStatusCode'] != 404:
|
||||
raise
|
||||
existing_size = None
|
||||
if existing_size is None:
|
||||
parts = storage.parts(row['object_key'], row['multipart_id'])
|
||||
expected = math.ceil(row['size'] / PART_BYTES)
|
||||
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)):
|
||||
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)
|
||||
existing_size = storage.size(row['object_key'])
|
||||
if existing_size != row['size']:
|
||||
raise HTTPException(409, 'O envio do arquivo não chegou inteiro. Escolha o arquivo de novo.')
|
||||
# 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}
|
||||
|
||||
# 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}')
|
||||
def cancel_upload(uid: UUID, session_id=Depends(owner)):
|
||||
with db.connect() as c:
|
||||
row=upload_row(c,uid,session_id,lock=True)
|
||||
if row['complete']:
|
||||
raise HTTPException(409, 'Este arquivo já foi enviado e não pode ser cancelado.')
|
||||
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('DELETE FROM dtf_local.upload_thumbnails WHERE upload_id=%s',(uid,))
|
||||
audit('upload_cancelled', upload=str(uid))
|
||||
return {'id':uid,'cancelled':True}
|
||||
275
app/api/users.py
Normal file
@@ -0,0 +1,275 @@
|
||||
"""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, MACHINE_QUESTION, audit, can, may_move, may_reorder, password_hash,
|
||||
password_matches, signed_in)
|
||||
from ..core.models import StrictModel
|
||||
from ..runtime import BACK, STATES, TRANSITIONS
|
||||
|
||||
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', 'revisor', 'vendedor', 'financeiro']
|
||||
password: str | None = Field(default=None, min_length=8, max_length=128)
|
||||
active: bool = True
|
||||
# No longer used: an operator's machine is the one chosen after signing in
|
||||
# (item 12). Kept so a page loaded before still saves.
|
||||
machines: list[UUID] = Field(default_factory=list, max_length=50)
|
||||
|
||||
@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)
|
||||
# No longer used (item 12): who is on a machine is who chose it after
|
||||
# signing in. Kept so a page loaded before still saves.
|
||||
operators: list[UUID] | None = Field(default=None, max_length=200)
|
||||
|
||||
|
||||
class 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: the moves
|
||||
their profile makes (forward, and the step back) and the columns whose
|
||||
order they set."""
|
||||
account = signed_in(request)
|
||||
role = account['role']
|
||||
moves = [[a, b] for a, nexts in TRANSITIONS.items() for b in nexts if may_move(role, a, b)]
|
||||
moves += [[a, b] for a, b in BACK.items() if may_move(role, a, b, back=True)]
|
||||
return {'email': account['email'], 'name': account['name'], 'role': role,
|
||||
# The machine this session is on, and whether to ask (item 12).
|
||||
'machine': account['machine'], 'machine_question': MACHINE_QUESTION.get(role),
|
||||
'machine_answered': account['machine_answered'],
|
||||
'can': sorted(cap for cap, roles in CAPABILITIES.items() if role in roles),
|
||||
'moves': moves, 'reorder': [state for state in STATES if may_reorder(role, state)]}
|
||||
|
||||
|
||||
class MachineAnswer(StrictModel):
|
||||
# None: "Não estou em máquina", for the profiles that may say so.
|
||||
machine_id: UUID | None = None
|
||||
# Taken while someone else is on it: a shift change, not a mistake.
|
||||
confirm: bool = False
|
||||
|
||||
|
||||
@router.post('/api/operator/me/machine')
|
||||
def choose_session_machine(body: MachineAnswer, request: Request):
|
||||
"""The machine this session works on (Dropstar's third round, item 12):
|
||||
the operator's pulls go to it, and the history names it. Per session, so a
|
||||
person runs two machines from two computers. Someone else already on it is
|
||||
a warning, not a refusal: shifts overlap for a few minutes."""
|
||||
account = signed_in(request)
|
||||
question = MACHINE_QUESTION.get(account['role'])
|
||||
if not question:
|
||||
raise HTTPException(403, 'Seu perfil não trabalha em máquina.')
|
||||
with db.connect() as c:
|
||||
name = None
|
||||
if body.machine_id is None:
|
||||
if question == 'required':
|
||||
raise HTTPException(422, 'Escolha a máquina em que você está.')
|
||||
else:
|
||||
row = c.execute('SELECT name FROM dtf_local.machines WHERE id=%s AND active', (body.machine_id,)).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(404, 'Máquina não encontrada ou desligada.')
|
||||
name = row['name']
|
||||
others = [r['who'] for r in c.execute('''SELECT DISTINCT COALESCE(NULLIF(o.name,''), o.email) AS who
|
||||
FROM dtf_local.operator_sessions s JOIN dtf_local.operators o ON o.email=s.username AND o.active
|
||||
WHERE s.machine_id=%s AND s.expires_at>now() AND s.username<>%s ORDER BY 1''',
|
||||
(body.machine_id, account['email'])).fetchall()]
|
||||
if others and not body.confirm:
|
||||
raise HTTPException(409, f"{name} já tem {' e '.join(others)} ligado.")
|
||||
c.execute('''UPDATE dtf_local.operator_sessions SET machine_id=%s, machine_at=CASE WHEN %s THEN now() END,
|
||||
machine_answered=true WHERE token_hash=%s''', (body.machine_id, name is not None, account['session']))
|
||||
audit('operator_machine_chosen', operator=account['email'], machine=name or '')
|
||||
return {'machine': {'id': str(body.machine_id), 'name': name} if name else None}
|
||||
|
||||
|
||||
@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):
|
||||
"""Every account, with the machines its open sessions are on now (item 12)."""
|
||||
rows = c.execute('''SELECT o.id,o.email,o.name,o.role,o.active,o.last_login_at,o.created_at,
|
||||
COALESCE(array_agg(DISTINCT s.machine_id) FILTER (WHERE s.machine_id IS NOT NULL), '{}') AS machines
|
||||
FROM dtf_local.operators o LEFT JOIN dtf_local.operator_sessions s
|
||||
ON s.username=o.email AND s.expires_at>now() AND s.machine_id IS NOT NULL
|
||||
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
|
||||
|
||||
|
||||
@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))
|
||||
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,))
|
||||
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 release_sessions(c, mid):
|
||||
"""Whoever was on a machine switched off or deleted is asked again."""
|
||||
c.execute('''UPDATE dtf_local.operator_sessions SET machine_id=NULL, machine_at=NULL, machine_answered=false
|
||||
WHERE machine_id=%s''', (mid,))
|
||||
|
||||
|
||||
@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))
|
||||
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.')
|
||||
if not body.active:
|
||||
release_sessions(c, mid)
|
||||
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:
|
||||
release_sessions(c, mid)
|
||||
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}
|
||||
49
app/app.py
Normal file
@@ -0,0 +1,49 @@
|
||||
"""The DTF Portal/API service: assembly only.
|
||||
|
||||
Configuration and shared helpers are in local.runtime; every route lives in a
|
||||
router under local.api. This module creates the application, applies the
|
||||
cross-cutting middleware, and includes them.
|
||||
"""
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.responses import JSONResponse
|
||||
from starlette.middleware.trustedhost import TrustedHostMiddleware
|
||||
|
||||
from .core import db
|
||||
from .core.auth import audit, client_ip
|
||||
from .runtime import ALLOWED_HOSTS, ALLOWED_ORIGINS, storage
|
||||
from .api import artwork, customer, health, operator, orders, payments, quotes, uploads, users
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app):
|
||||
with db.connect() as c:
|
||||
c.execute('SELECT 1 FROM dtf_local.operator_sessions LIMIT 1')
|
||||
storage.health()
|
||||
yield
|
||||
|
||||
|
||||
app = FastAPI(title='DTF Portal/API', lifespan=lifespan, docs_url=None, redoc_url=None)
|
||||
app.add_middleware(TrustedHostMiddleware, allowed_hosts=ALLOWED_HOSTS)
|
||||
|
||||
@app.middleware('http')
|
||||
async def safe_headers(request, call_next):
|
||||
if request.method not in ('GET','HEAD','OPTIONS'):
|
||||
origin = request.headers.get('origin')
|
||||
if request.headers.get('sec-fetch-site') == 'cross-site' or (origin and origin not in ALLOWED_ORIGINS):
|
||||
audit('cross_origin_rejected', ip=client_ip(request))
|
||||
return JSONResponse({'detail':'Cross-origin request rejected'}, status_code=403)
|
||||
response = await call_next(request)
|
||||
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))
|
||||
# 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['Referrer-Policy'] = 'no-referrer'
|
||||
return response
|
||||
|
||||
|
||||
# Order is not significant: no two routers declare the same path.
|
||||
for module in (health, uploads, quotes, orders, payments, operator, customer, artwork, users):
|
||||
app.include_router(module.router)
|
||||
113
app/artwork.py
Normal file
@@ -0,0 +1,113 @@
|
||||
"""Attaching artwork to an order: the rules shared by customers and operators.
|
||||
|
||||
A customer submits a correction and an operator submits the final set; both go
|
||||
through the same checks, so the rule about what may be attached, when, and what
|
||||
it does to retention lives in one place.
|
||||
"""
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
from .runtime import upload_row
|
||||
from .scanning import require_clean
|
||||
|
||||
|
||||
def generated_owner(c, order, ref, kind):
|
||||
"""The owner to look a generated print file up under, or None if it is not one.
|
||||
|
||||
A generated file may be approved as the final for the item it was made
|
||||
from, and only while that item still has its original artwork: after a
|
||||
customer correction it reproduces a layout nobody wants printed.
|
||||
"""
|
||||
generated = c.execute('''SELECT item_index FROM dtf_local.print_files
|
||||
WHERE order_id=%s AND upload_id=%s AND status='ready' ''', (order['id'], ref.upload_id)).fetchone()
|
||||
if not generated:
|
||||
return None
|
||||
if kind != 'final' or generated['item_index'] != ref.item_index:
|
||||
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",
|
||||
(order['id'],)).fetchone():
|
||||
raise HTTPException(409, 'O cliente enviou uma correção depois que este arquivo foi gerado. Use a correção ou envie outro arquivo.')
|
||||
# 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):
|
||||
if order['version'] != body.version:
|
||||
raise HTTPException(409, 'O pedido mudou. Atualize a página e envie de novo.')
|
||||
# Arte conferida is the print queue (2026-10-23): what is in it keeps its finals.
|
||||
if kind == 'final' and order['state'] not in ('rec','cor'):
|
||||
raise HTTPException(409, 'O arquivo final só muda antes de Arte conferida, a fila. Volte o pedido para Arte recebida para trocar.')
|
||||
if kind == 'correction' and order['state'] != 'cor':
|
||||
raise HTTPException(409, 'Este pedido não está esperando correção.')
|
||||
if len({f.upload_id for f in body.files}) != len(body.files):
|
||||
raise HTTPException(422, 'O mesmo arquivo foi enviado duas vezes.')
|
||||
count = len(order['snapshot']['items'])
|
||||
if any(f.item_index >= count for f in body.files):
|
||||
raise HTTPException(422, 'Item do pedido inválido.')
|
||||
if kind == 'final' and {f.item_index for f in body.files} != set(range(count)):
|
||||
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']]
|
||||
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)
|
||||
if expiry <= datetime.now(timezone.utc):
|
||||
raise HTTPException(410, 'Os arquivos deste pedido expiraram (30 dias).')
|
||||
# A final already approved for its item may stay as it is beside a new
|
||||
# one for another item: "Tratar a arte" replaces only the item treated
|
||||
# (Dropstar, 2026-10-29). Something has to change, though.
|
||||
current = {(row['upload_id'], row['item_index']) for row in c.execute(
|
||||
"SELECT upload_id,item_index FROM dtf_local.order_files WHERE order_id=%s AND kind='final' AND active",
|
||||
(order['id'],)).fetchall()} if kind == 'final' else set()
|
||||
kept = {ref.upload_id for ref in body.files if (ref.upload_id, ref.item_index) in current}
|
||||
if kept and len(kept) == len(body.files):
|
||||
raise HTTPException(409, 'Estes já são os arquivos finais. Envie o arquivo novo.')
|
||||
for ref in body.files:
|
||||
if ref.upload_id in kept:
|
||||
continue
|
||||
corrected = correction_owner(c, order, ref, kind)
|
||||
upload = upload_row(c, ref.upload_id, corrected or generated_owner(c, order, ref, kind) or identity, lock=True)
|
||||
if not upload['complete']:
|
||||
raise HTTPException(409, 'Espere o envio de todos os arquivos terminar.')
|
||||
require_clean(upload)
|
||||
# Attached once, except a correction approved as its own final.
|
||||
if c.execute('SELECT id FROM dtf_local.order_files WHERE upload_id=%s'+(" AND kind<>'correction'" if corrected else ''),
|
||||
(ref.upload_id,)).fetchone():
|
||||
raise HTTPException(409, 'Este arquivo já está no pedido. Envie uma nova versão.')
|
||||
# A new customer correction supersedes every final prepared from earlier
|
||||
# artwork, including finals uploaded while this order was in correction.
|
||||
if kind == 'correction':
|
||||
c.execute("UPDATE dtf_local.order_files SET active=false WHERE order_id=%s AND kind IN ('correction','final')", (order['id'],))
|
||||
else:
|
||||
c.execute('UPDATE dtf_local.order_files SET active=false WHERE order_id=%s AND kind=%s', (order['id'],kind))
|
||||
for ref in body.files:
|
||||
if ref.upload_id in kept:
|
||||
c.execute("UPDATE dtf_local.order_files SET active=true WHERE order_id=%s AND upload_id=%s AND kind='final'",
|
||||
(order['id'], ref.upload_id))
|
||||
continue
|
||||
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))
|
||||
# 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'],))
|
||||
if kind == 'final':
|
||||
# Artwork approval, not commercial quote approval, starts original cleanup.
|
||||
# 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}
|
||||
BIN
app/assets/logo-dropstar.png
Normal file
|
After Width: | Height: | Size: 97 KiB |
@@ -4,7 +4,8 @@ from pathlib import Path
|
||||
from urllib.parse import urlparse
|
||||
import psycopg
|
||||
from psycopg import sql
|
||||
from .secrets import load as load_secret_files
|
||||
from .core.secrets import load as load_secret_files
|
||||
from .operators import seed_from_environment
|
||||
|
||||
|
||||
def admin_connect():
|
||||
@@ -45,6 +46,18 @@ def main():
|
||||
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 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
|
||||
# deployment keeps logging in exactly as before. Inserts only when that
|
||||
# email is absent, so a password changed with local.operators is never
|
||||
# reverted by a stale environment variable on the next deploy.
|
||||
seeded = seed_from_environment(c)
|
||||
print('Local schema migrated; runtime role has DML only.')
|
||||
if seeded:
|
||||
print(f'Seeded operator account {seeded} from OPERATOR_EMAIL.')
|
||||
|
||||
if __name__ == '__main__': main()
|
||||
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
|
||||
1
app/core/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
"""Shared foundations: identity, database, models, prices, secret loading."""
|
||||
227
app/core/auth.py
Normal file
@@ -0,0 +1,227 @@
|
||||
"""Local customer passwords and revocable database sessions. No email service."""
|
||||
import hashlib
|
||||
import os
|
||||
import secrets
|
||||
import logging
|
||||
import json
|
||||
from uuid import UUID, uuid4
|
||||
from fastapi import HTTPException, Request
|
||||
from ..core.db import connect
|
||||
|
||||
COOKIE_SECURE = os.environ.get('COOKIE_SECURE', 'false').lower() == 'true'
|
||||
|
||||
def client_ip(request: Request):
|
||||
"""The requester's address, for rate-limit buckets and security events.
|
||||
|
||||
The API is only reachable through the web gateway, which replaces
|
||||
X-Forwarded-For with the peer address it observed, so the header carries
|
||||
exactly one value the client could not choose. Without this every request
|
||||
looks like the gateway, which collapses per-source limits into one global
|
||||
bucket and strips the address from the audit trail.
|
||||
"""
|
||||
forwarded = request.headers.get('x-forwarded-for', '').split(',')[0].strip()
|
||||
if forwarded:
|
||||
return forwarded[:64]
|
||||
return request.client.host if request.client else 'unknown'
|
||||
|
||||
def password_hash(password, salt=None):
|
||||
salt = salt or secrets.token_hex(16)
|
||||
digest = hashlib.scrypt(password.encode(), salt=bytes.fromhex(salt), n=16384, r=8, p=5).hex()
|
||||
return f'scrypt-v2${salt}${digest}'
|
||||
|
||||
def password_matches(password, stored):
|
||||
try:
|
||||
version, salt, digest = stored.split('$')
|
||||
if version not in ('scrypt', 'scrypt-v2'): return False
|
||||
actual = hashlib.scrypt(password.encode(), salt=bytes.fromhex(salt), n=16384, r=8,
|
||||
p=1 if version == 'scrypt' else 5).hex()
|
||||
return secrets.compare_digest(actual, digest)
|
||||
except (ValueError, TypeError):
|
||||
return False
|
||||
|
||||
DUMMY_PASSWORD_HASH = password_hash('invalid-account-password', '00'*16)
|
||||
|
||||
def session_row(request):
|
||||
try:
|
||||
sid = UUID(request.cookies.get('dtf_session', ''))
|
||||
except ValueError:
|
||||
raise HTTPException(401, 'Sessão não iniciada. Recarregue a página.')
|
||||
with connect() as c:
|
||||
row = c.execute('SELECT * FROM dtf_local.sessions WHERE id=%s AND expires_at>now()', (sid,)).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(401, 'Session expired; sign in or start a new session')
|
||||
return row
|
||||
|
||||
def owner(request: Request):
|
||||
return session_row(request)['owner']
|
||||
|
||||
def new_session(c, response, identity=None):
|
||||
sid = uuid4()
|
||||
identity = identity or uuid4()
|
||||
c.execute('INSERT INTO dtf_local.sessions(id,owner) VALUES(%s,%s)', (sid,identity))
|
||||
response.set_cookie('dtf_session', str(sid), httponly=True, secure=COOKIE_SECURE,
|
||||
samesite='strict', max_age=86400*7)
|
||||
return identity
|
||||
|
||||
def transfer_guest(c, previous, identity):
|
||||
# Successful authentication can claim only the current guest browser's records.
|
||||
if c.execute('SELECT id FROM dtf_local.accounts WHERE id=%s', (previous['owner'],)).fetchone():
|
||||
return
|
||||
for table in ('uploads','quotes','orders'):
|
||||
c.execute(f'UPDATE dtf_local.{table} SET owner=%s WHERE owner=%s', (identity,previous['owner']))
|
||||
c.execute('DELETE FROM dtf_local.sessions WHERE owner=%s', (previous['owner'],))
|
||||
|
||||
def audit(event, **fields):
|
||||
# Only explicit metadata: never cookies, passwords, signed URLs or request bodies.
|
||||
logging.getLogger('dtf.security').warning(json.dumps({'event':event, **fields}, sort_keys=True))
|
||||
try:
|
||||
from psycopg.types.json import Jsonb
|
||||
with connect() as c:
|
||||
c.execute('INSERT INTO dtf_local.security_events(event,details) VALUES(%s,%s)',(event,Jsonb(fields)))
|
||||
except Exception:
|
||||
# Logging must still work during a DB outage without recursively auditing itself.
|
||||
logging.getLogger('dtf.security').error('Security event persistence unavailable')
|
||||
|
||||
def rate_limit(scope, identity, limit, seconds=900):
|
||||
key = hashlib.sha256((scope+'|'+identity).encode()).hexdigest()
|
||||
with connect() as c:
|
||||
row = c.execute("""INSERT INTO dtf_local.login_attempts(key,attempts) VALUES(%s,1)
|
||||
ON CONFLICT(key) DO UPDATE SET
|
||||
attempts=CASE WHEN dtf_local.login_attempts.started_at < now()-%s*interval '1 second' THEN 1 ELSE LEAST(dtf_local.login_attempts.attempts+1,1000000) END,
|
||||
started_at=CASE WHEN dtf_local.login_attempts.started_at < now()-%s*interval '1 second' THEN now() ELSE dtf_local.login_attempts.started_at END
|
||||
RETURNING attempts""", (key,seconds,seconds)).fetchone()
|
||||
if row['attempts'] > limit:
|
||||
audit('rate_limit', scope=scope)
|
||||
raise HTTPException(429, 'Muitas tentativas. Tente de novo mais tarde.', headers={'Retry-After':str(seconds)})
|
||||
|
||||
ACCOUNT_FAILURES = 10
|
||||
|
||||
def throttle(email, request):
|
||||
# Independent account and source buckets prevent bypass by rotating emails.
|
||||
# Every attempt counts against the source. Only failures count against the
|
||||
# account: guessing a password is what the account bucket stops, and
|
||||
# counting successful sign-ins too let ordinary use lock an operator out.
|
||||
rate_limit('auth-source', client_ip(request), 60)
|
||||
key = hashlib.sha256(('auth-account|'+email).encode()).hexdigest()
|
||||
with connect() as c:
|
||||
row = c.execute("""SELECT attempts FROM dtf_local.login_attempts
|
||||
WHERE key=%s AND started_at >= now()-interval '900 seconds'""", (key,)).fetchone()
|
||||
if row and row['attempts'] >= ACCOUNT_FAILURES:
|
||||
audit('rate_limit', scope='auth-account')
|
||||
raise HTTPException(429, 'Muitas tentativas. Tente de novo mais tarde.', headers={'Retry-After': '900'})
|
||||
|
||||
def login_failed(email):
|
||||
"""Count a failed sign-in (or registration attempt) against the account."""
|
||||
rate_limit('auth-account', email, 1_000_000)
|
||||
|
||||
# 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. Which cards each profile moves is MOVES.
|
||||
ROLES = ('superadmin', 'admin', 'gestao', 'designer', 'operador', 'revisor', 'vendedor', 'financeiro')
|
||||
CAPABILITIES = {
|
||||
'view': set(ROLES),
|
||||
'produce': {'superadmin', 'admin', 'gestao', 'designer', 'operador'},
|
||||
'print': {'superadmin', 'admin', 'gestao', 'operador'},
|
||||
'manage': {'superadmin', 'admin', 'gestao'},
|
||||
# Registering an order paid outside the system, from its Site quote (D-35).
|
||||
# Not the seller: Vendedor only views the board (D-30).
|
||||
'enter': {'superadmin', 'admin', 'gestao'},
|
||||
# Rework (D-02): coordination opens it with its cause, an Administrador
|
||||
# (Thales or Alexandre) authorizes it.
|
||||
'rework': {'superadmin', 'gestao'},
|
||||
'authorize': {'superadmin', 'admin'},
|
||||
'users': {'superadmin', 'admin'},
|
||||
'integrations': {'superadmin'},
|
||||
# Financeiro (Dropstar, 2026-10-30): sees the board, Pagamentos, Números and
|
||||
# Cotações, and cancels an order with its reason; moves no card, touches no
|
||||
# file. Resolving a payment stays with "manage".
|
||||
'payments': {'superadmin', 'admin', 'gestao', 'financeiro'},
|
||||
'cancel': {'superadmin', 'admin', 'gestao', 'financeiro'},
|
||||
# "Retirado" at the counter (Dropstar's third round, item 14): everyone
|
||||
# but the seller, who only views (D-30). It includes everyone who produces,
|
||||
# so an operator upload (artwork.py) takes it for its parts.
|
||||
'deliver': {'superadmin', 'admin', 'gestao', 'designer', 'operador', 'revisor'},
|
||||
}
|
||||
|
||||
# Who moves which card (Dropstar's flow, 2026-10-23, and their rules of
|
||||
# 2026-10-26): the designer the artwork, the operator the printing, and the
|
||||
# Revisor to Finalizado, so nobody in the room releases their own print (D-29);
|
||||
# Admin, Dropstar's own login, may release too (the user, 2026-10-28), and we,
|
||||
# the superadmin, for support. Gestão, the coordination, pulls back and
|
||||
# never forward, always with a reason (D-20): a step back, or Correção. Admin,
|
||||
# Dropstar's own login, makes every other move. A step back undoes a mistaken
|
||||
# move: open to whoever may make the move it undoes.
|
||||
MOVES = {
|
||||
'designer': {('rec', 'tra'), ('rec', 'cor'), ('tra', 'cor'), ('cor', 'rec'), ('cor', 'tra')},
|
||||
'operador': {('tra', 'imp'), ('imp', 'rev')},
|
||||
'revisor': {('rev', 'fin')},
|
||||
}
|
||||
ADMINS = ('superadmin', 'admin')
|
||||
COORDINATION = ('gestao',)
|
||||
MANAGERS = ADMINS + COORDINATION
|
||||
RELEASERS = ('revisor', 'admin', 'superadmin')
|
||||
# Who is asked "Em qual máquina você está?" after signing in (Dropstar, 2026-10-30):
|
||||
# the operator must answer; Gestão and the administrators may say they are on
|
||||
# none. The other profiles are never asked.
|
||||
MACHINE_QUESTION = {'operador': 'required', 'gestao': 'optional', 'admin': 'optional'}
|
||||
MOVERS = MANAGERS + tuple(MOVES)
|
||||
|
||||
|
||||
def may_move(role, from_state, to_state, back=False):
|
||||
"""Whether this profile may move a card; `back` is the step back that
|
||||
undoes the move to_state -> from_state."""
|
||||
if back:
|
||||
return role in MANAGERS or (to_state, from_state) in MOVES.get(role, ())
|
||||
if to_state == 'fin':
|
||||
return role in RELEASERS
|
||||
if to_state == 'cor' and role in COORDINATION:
|
||||
return True
|
||||
return role in ADMINS or (from_state, to_state) in MOVES.get(role, ())
|
||||
|
||||
|
||||
def may_reorder(role, state):
|
||||
"""Changing a card's place in its column, the order it is worked in: for
|
||||
whoever takes cards forward out of it."""
|
||||
return role in MANAGERS or any(a == state and b != 'cor' for a, b in MOVES.get(role, ()))
|
||||
|
||||
|
||||
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', '')
|
||||
if not token or len(token)>128:
|
||||
raise HTTPException(401, 'Entre no Kanban.')
|
||||
digest = hashlib.sha256(token.encode()).hexdigest()
|
||||
with connect() as c:
|
||||
row = c.execute('''SELECT o.id,o.email,o.name,o.role,s.machine_answered,m.id AS machine_id,m.name AS machine_name
|
||||
FROM dtf_local.operator_sessions s
|
||||
JOIN dtf_local.operators o ON o.email=s.username AND o.active
|
||||
LEFT JOIN dtf_local.machines m ON m.id=s.machine_id
|
||||
WHERE s.token_hash=%s AND s.expires_at>now()''', (digest,)).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(401, 'Sua sessão expirou. Entre de novo.')
|
||||
# The machine this session works on (item 12), or None.
|
||||
machine_id, machine_name = row.pop('machine_id'), row.pop('machine_name')
|
||||
row['machine'] = {'id': str(machine_id), 'name': machine_name} if machine_id else None
|
||||
row['session'] = digest
|
||||
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')
|
||||
@@ -19,4 +19,5 @@ def connect():
|
||||
|
||||
def initialize():
|
||||
with connect() as c:
|
||||
c.execute(Path(__file__).with_name('schema.sql').read_text())
|
||||
# The schema lives at the package root, one level up from core/.
|
||||
c.execute((Path(__file__).resolve().parent.parent / 'schema.sql').read_text())
|
||||
13
app/core/limits.py
Normal file
@@ -0,0 +1,13 @@
|
||||
"""Limits shared by upload admission and the malware scanner."""
|
||||
import os
|
||||
|
||||
CLAMAV_STREAM_MAX_BYTES = 2000 * 1024 * 1024 # infra/clamd.conf StreamMaxLength
|
||||
|
||||
|
||||
def scan_limit_bytes():
|
||||
"""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():
|
||||
return int(os.environ.get('MAX_UPLOAD_BYTES', str(4 * 1024 ** 3)))
|
||||
354
app/core/models.py
Normal file
@@ -0,0 +1,354 @@
|
||||
import re
|
||||
from decimal import Decimal
|
||||
from typing import Literal
|
||||
from uuid import UUID
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
||||
|
||||
class StrictModel(BaseModel):
|
||||
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):
|
||||
# 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
|
||||
zap: str
|
||||
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')
|
||||
@classmethod
|
||||
def document_valid(cls, value):
|
||||
digits = re.sub(r'\D', '', value)
|
||||
if not digits.isascii() or not (cpf_ok(digits) or cnpj_ok(digits)):
|
||||
raise ValueError('Invalid CPF or CNPJ')
|
||||
return digits
|
||||
|
||||
@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
|
||||
|
||||
@field_validator('mail')
|
||||
@classmethod
|
||||
def email_valid(cls, value):
|
||||
if not re.fullmatch(r'[^\s@]+@[^\s@]+\.[a-zA-Z]{2,}', value.strip()):
|
||||
raise ValueError('Invalid email')
|
||||
return value.strip()
|
||||
|
||||
class Freight(StrictModel):
|
||||
service: Literal['pickup','mock-standard','jadlog','pac','sedex'] = 'pickup'
|
||||
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',
|
||||
'PR','PE','PI','RJ','RN','RS','RO','RR','SC','SP','SE','TO']
|
||||
|
||||
class Destination(StrictModel):
|
||||
"""Where a shipped order goes. A CEP alone quotes freight; it does not deliver."""
|
||||
recipient: str = Field(min_length=2, max_length=120)
|
||||
street: str = Field(min_length=2, max_length=160)
|
||||
number: str = Field(min_length=1, max_length=20)
|
||||
complement: str = Field(default='', max_length=80)
|
||||
district: str = Field(min_length=2, max_length=80)
|
||||
city: str = Field(min_length=2, max_length=80)
|
||||
state: UF
|
||||
postal_code: str = Field(pattern=r'^[0-9]{8}$')
|
||||
|
||||
@field_validator('recipient', 'street', 'number', 'complement', 'district', 'city', mode='before')
|
||||
@classmethod
|
||||
def trimmed(cls, value):
|
||||
if isinstance(value, str):
|
||||
value = ' '.join(value.split())
|
||||
if any(ord(ch) < 32 for ch in value):
|
||||
raise ValueError('Invalid characters')
|
||||
return value
|
||||
|
||||
class UploadStart(StrictModel):
|
||||
name: str = Field(min_length=1, max_length=200, pattern=r'^[^/\\\x00-\x1f]+$')
|
||||
size: int = Field(gt=0, strict=True)
|
||||
|
||||
@field_validator('name')
|
||||
@classmethod
|
||||
def artwork_extension(cls, value):
|
||||
# Union of existing Site product formats; this is NOT malware/pre-flight validation.
|
||||
if not re.search(r'\.(png|jpe?g|webp|tiff?|pdf|psd|psb|ai|cdr)$', value, re.I):
|
||||
raise ValueError('Unsupported artwork file extension')
|
||||
return value
|
||||
|
||||
class ProductionSource(StrictModel):
|
||||
upload_id: UUID
|
||||
kind: Literal['sheet', 'artwork']
|
||||
width_cm: Decimal = Field(gt=0, le=57)
|
||||
length_cm: Decimal = Field(gt=0, le=6000)
|
||||
copies: int = Field(ge=1, le=200, strict=True)
|
||||
rotation_degrees: Literal[0, 90] = 0
|
||||
mirrored: bool = False
|
||||
measurement: Literal['file', 'customer']
|
||||
|
||||
class ProductionPlacement(StrictModel):
|
||||
source_index: int = Field(ge=0, le=19, strict=True)
|
||||
copy_index: int = Field(ge=0, le=199, strict=True)
|
||||
x_cm: Decimal = Field(ge=0, le=57)
|
||||
y_cm: Decimal = Field(ge=0, le=1200000)
|
||||
width_cm: Decimal = Field(gt=0, le=57)
|
||||
length_cm: Decimal = Field(gt=0, le=6000)
|
||||
rotation_degrees: Literal[0, 90, 180, 270]
|
||||
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):
|
||||
version: Literal[2, 3]
|
||||
film_width_cm: Decimal
|
||||
height_cm: Decimal = Field(gt=0, le=1200000)
|
||||
sources: list[ProductionSource] = Field(min_length=1, max_length=20)
|
||||
placements: list[ProductionPlacement] = Field(min_length=1, max_length=4000)
|
||||
|
||||
class Item(StrictModel):
|
||||
mode: Literal['file','avulsa','uvfile','uv']
|
||||
metres: Decimal = Field(gt=0, le=12000)
|
||||
grade: int = Field(ge=0, le=100, strict=True)
|
||||
uploads: list[UUID] = Field(min_length=1, max_length=20)
|
||||
production: ProductionSpec
|
||||
quality_status: Literal['ok', 'warning', 'unverified']
|
||||
quality_acknowledged: bool
|
||||
# Residue dots under 2 mm the customer accepted printing on a ready sheet,
|
||||
# rather than erasing them (Dropstar, 2026-10-29): 0 when none.
|
||||
residue_accepted: int = Field(default=0, ge=0, le=1000000, strict=True)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def production_matches_uploads(self):
|
||||
if [source.upload_id for source in self.production.sources] != self.uploads:
|
||||
raise ValueError('Production sources must match uploaded files in order')
|
||||
is_sheet = self.mode in ('file', 'uvfile')
|
||||
# UV is 27 cm wide (Dropstar, 2026-10-28; it was 28,5).
|
||||
film_width = Decimal('27') if self.mode in ('uvfile', 'uv') else Decimal('57')
|
||||
if self.production.film_width_cm != film_width:
|
||||
raise ValueError('Production film width does not match the product')
|
||||
for source in self.production.sources:
|
||||
if (source.kind == 'sheet') != is_sheet or source.width_cm > film_width:
|
||||
raise ValueError('Production source does not fit the selected product')
|
||||
if is_sheet and (source.rotation_degrees or source.mirrored):
|
||||
raise ValueError('Finished sheets cannot be rotated or mirrored by the layout')
|
||||
# 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)
|
||||
for copy in range(source.copies)}
|
||||
placed=set()
|
||||
tolerance=Decimal('0.02')
|
||||
for placement in self.production.placements:
|
||||
key=(placement.source_index,placement.copy_index)
|
||||
if key not in expected or key in placed:
|
||||
raise ValueError('Production placement has a missing or duplicate source copy')
|
||||
placed.add(key)
|
||||
source=self.production.sources[placement.source_index]
|
||||
auto_rotation=(placement.rotation_degrees-source.rotation_degrees)%360
|
||||
if auto_rotation not in (0,90) or placement.mirrored != source.mirrored:
|
||||
raise ValueError('Production placement changes the source transform')
|
||||
width,length=(source.width_cm,source.length_cm) if auto_rotation==0 else (source.length_cm,source.width_cm)
|
||||
if abs(placement.width_cm-width)>tolerance or abs(placement.length_cm-length)>tolerance:
|
||||
raise ValueError('Production placement changes the source size')
|
||||
if placement.x_cm+placement.width_cm>film_width+tolerance or placement.y_cm+placement.length_cm>self.production.height_cm+tolerance:
|
||||
raise ValueError('Production placement is outside the film')
|
||||
if is_sheet and (placement.x_cm or auto_rotation):
|
||||
raise ValueError('Finished sheets must retain their original orientation')
|
||||
if placed != expected:
|
||||
raise ValueError('Production layout does not cover every source copy')
|
||||
if self.quality_status == 'warning' and not self.quality_acknowledged:
|
||||
raise ValueError('Resolution warning must be acknowledged')
|
||||
return self
|
||||
|
||||
class QuoteRequest(StrictModel):
|
||||
request_key: UUID
|
||||
customer: Customer
|
||||
items: list[Item] = Field(min_length=1, max_length=30)
|
||||
freight: Freight
|
||||
destination: Destination | None = None
|
||||
# "Quero aprovar uma prova antes de imprimir": the order waits for the customer.
|
||||
proof: bool = False
|
||||
|
||||
@model_validator(mode='after')
|
||||
def destination_matches_freight(self):
|
||||
if self.freight.service == 'pickup':
|
||||
if self.destination is not None:
|
||||
raise ValueError('Pickup orders do not take a delivery address')
|
||||
elif self.destination is None:
|
||||
raise ValueError('Delivery requires the full address')
|
||||
elif self.destination.postal_code != self.freight.postal_code:
|
||||
raise ValueError('The delivery address CEP must be the CEP freight was quoted for')
|
||||
return self
|
||||
|
||||
class Review(StrictModel):
|
||||
items: list[Item] = Field(min_length=1, max_length=30)
|
||||
|
||||
class Pay(StrictModel):
|
||||
quote_id: UUID
|
||||
|
||||
class PaymentMethod(StrictModel):
|
||||
type: Literal['pix', 'card']
|
||||
# Card fields come from the provider's own form, which tokenises the card
|
||||
# in the browser; the number never reaches this server.
|
||||
token: str | None = Field(default=None, max_length=200)
|
||||
payment_method_id: str | None = Field(default=None, max_length=40, pattern=r'^[a-z_]+$')
|
||||
# Up to 3, as Dropstar sells; the card form offers no more.
|
||||
installments: int = Field(default=1, ge=1, le=3, strict=True)
|
||||
issuer_id: str | None = Field(default=None, max_length=40)
|
||||
# The cardholder's document from the card form: for a card, the payer is
|
||||
# the cardholder, not necessarily the company on the invoice.
|
||||
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')
|
||||
def card_needs_token(self):
|
||||
if self.type == 'card' and not (self.token and self.payment_method_id):
|
||||
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
|
||||
|
||||
class PaymentIntent(StrictModel):
|
||||
quote_id: UUID
|
||||
method: PaymentMethod
|
||||
|
||||
class Move(StrictModel):
|
||||
state: Literal['rec','tra','imp','cor','rev','fin']
|
||||
version: int = Field(ge=0)
|
||||
reason: str = Field(default='', max_length=1000)
|
||||
|
||||
class Resolution(StrictModel):
|
||||
note: str = Field(min_length=3, max_length=1000)
|
||||
|
||||
class Register(StrictModel):
|
||||
customer: Customer
|
||||
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):
|
||||
email: str = Field(min_length=3, max_length=254)
|
||||
password: str = Field(min_length=1, max_length=128)
|
||||
|
||||
class OperatorLogin(StrictModel):
|
||||
email: str = Field(min_length=3, max_length=254)
|
||||
password: str = Field(min_length=1, max_length=128)
|
||||
|
||||
@field_validator('email')
|
||||
@classmethod
|
||||
def operator_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 FileReference(StrictModel):
|
||||
upload_id: UUID
|
||||
item_index: int = Field(ge=0, strict=True)
|
||||
|
||||
class ArtworkSubmission(StrictModel):
|
||||
version: int = Field(ge=0, strict=True)
|
||||
files: list[FileReference] = Field(min_length=1, max_length=60)
|
||||
note: str = Field(min_length=1, max_length=1000)
|
||||
52
app/core/pricing.py
Normal file
@@ -0,0 +1,52 @@
|
||||
"""Dropstar's single price per metre for each product; integer BRL cents at the boundary.
|
||||
|
||||
One price per product (Dropstar, 2026-10-23). The grade is still recorded with
|
||||
each item, for the customer and the print room, but it no longer changes the
|
||||
price. This module does not inspect artwork or perform pre-flight.
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
from decimal import Decimal, ROUND_CEILING
|
||||
|
||||
PRICES = {'file': 1990, 'avulsa': 2190, 'uvfile': 7990, 'uv': 8990}
|
||||
|
||||
# A finished sheet the Site cannot open (CDR, AI, PSD, TIFF) is opened by a
|
||||
# person before printing. It pays this per metre on top of the product's price
|
||||
# when the business sets it, to make the formats the robot reads the cheaper
|
||||
# path. Zero 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:
|
||||
"""The item's charge. The grade is validated and kept with the item; the
|
||||
price does not depend on it."""
|
||||
length = Decimal(str(metres))
|
||||
if mode not in PRICES or not length.is_finite() or not 0 < length <= 12000:
|
||||
raise ValueError('Invalid product or length')
|
||||
if isinstance(grade, bool) or not isinstance(grade, int) or not 0 <= grade <= 100:
|
||||
raise ValueError('Grade must be an integer between 0 and 100')
|
||||
billed = max(Decimal('1'), (length * 10).to_integral_value(rounding=ROUND_CEILING) / 10)
|
||||
if isinstance(extra_cents, bool) or not isinstance(extra_cents, int) or extra_cents < 0:
|
||||
raise ValueError('Invalid extra charge')
|
||||
unit = PRICES[mode] + extra_cents
|
||||
priced = {'mode': mode, 'metres': str(length), 'grade': grade,
|
||||
'billed_metres': str(billed), 'unit_cents': unit,
|
||||
'total_cents': int(billed * unit)}
|
||||
if extra_cents:
|
||||
priced['manual_extra_cents'] = extra_cents
|
||||
return priced
|
||||
@@ -1,9 +1,9 @@
|
||||
"""Resolve Docker secret files into the environment before configuration is read.
|
||||
|
||||
Swarm mounts each secret as a file and the stack passes its path as `<NAME>_FILE`.
|
||||
Nothing read `_FILE` settings, so `deploy/stack.yaml` could not boot: the runtime
|
||||
looked for `DATABASE_URL`, `AWS_ACCESS_KEY_ID` and `OPERATOR_PASSWORD` while the
|
||||
stack supplied only the `_FILE` form.
|
||||
The deployed `docker-compose.yml` passes credentials as plain environment
|
||||
variables, so this module is inert there. It exists so a stack can supply them as
|
||||
Docker secrets instead without any code change; see `docs/ROADMAP.md` 2.12.
|
||||
|
||||
Call `load()` in every entrypoint before any configuration is read.
|
||||
|
||||
@@ -12,9 +12,9 @@ secrets` elsewhere in the package to the standard library, not to this file.
|
||||
"""
|
||||
import os
|
||||
|
||||
# The settings production supplies as secret files. Any other `*_FILE` variable is
|
||||
# The settings a stack may supply as secret files. Any other `*_FILE` variable is
|
||||
# resolved the same way; this list documents the contract and is what the release
|
||||
# gate checks against, so keep it in step with `deploy/stack.yaml`.
|
||||
# gate checks against.
|
||||
SECRET_FILE_SETTINGS = (
|
||||
'DATABASE_URL',
|
||||
'DATABASE_ADMIN_URL',
|
||||
@@ -27,7 +27,8 @@ SECRET_FILE_SETTINGS = (
|
||||
'PAYMENT_TOKEN',
|
||||
'PAYMENT_WEBHOOK_SECRET',
|
||||
'TINY_TOKEN',
|
||||
'WHATSAPP_TOKEN',
|
||||
'SMTP_PASSWORD',
|
||||
'CORREIOS_CODIGO_ACESSO',
|
||||
)
|
||||
|
||||
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}
|
||||
191
app/grade_check.py
Normal file
@@ -0,0 +1,191 @@
|
||||
"""The grade recomputed from the uploaded files.
|
||||
|
||||
The Site grades the art in the customer's browser and sends the grade with the
|
||||
cart. The price no longer depends on it (one price per product, 2026-10-23),
|
||||
but the grade is shown with the order on the Kanban and in Tiny. 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 # no grade claimed: 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())
|
||||
137
app/machines.py
Normal file
@@ -0,0 +1,137 @@
|
||||
"""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', 'imp', 'cor')
|
||||
# Stages an automatic order may still move from: not once it is printing.
|
||||
MOVABLE = ('rec', 'tra', 'cor')
|
||||
# One routing at a time, so two at once cannot both pick the same "least loaded".
|
||||
LOCK = 7_041_901
|
||||
# Two orders at most in Imprimindo per machine (Dropstar, 2026-10-29): one
|
||||
# printing, the next being ripped by FlexiPRINT meanwhile. A third would
|
||||
# make the RIP choke; two mean the next sheet is ready when one ends.
|
||||
PRINTING_CAP = 2
|
||||
|
||||
|
||||
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:
|
||||
# Who is on it now: the open sessions that chose it (item 12).
|
||||
for r in c.execute('''SELECT DISTINCT ON (s.machine_id, o.id) s.machine_id, o.id, o.name, o.email, s.machine_at
|
||||
FROM dtf_local.operator_sessions s JOIN dtf_local.operators o ON o.email=s.username AND o.active
|
||||
WHERE s.machine_id IS NOT NULL AND s.expires_at>now()
|
||||
ORDER BY s.machine_id, o.id, s.machine_at''').fetchall():
|
||||
operators.setdefault(str(r['machine_id']), []).append(
|
||||
{'id': str(r['id']), 'name': r['name'] or r['email'], 'since': r['machine_at']})
|
||||
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
|
||||
|
||||
|
||||
def full(c, machine_id, order_id):
|
||||
"""The machine's name when it already has PRINTING_CAP other orders in
|
||||
Imprimindo, so this one cannot join them; None when it has room. The
|
||||
machine's row is locked, so two pulls at once cannot both take the last
|
||||
place."""
|
||||
if machine_id is None:
|
||||
return None
|
||||
machine = c.execute('SELECT name FROM dtf_local.machines WHERE id=%s FOR UPDATE', (machine_id,)).fetchone()
|
||||
printing = c.execute('''SELECT count(*) AS n FROM dtf_local.orders WHERE machine_id=%s AND state='imp'
|
||||
AND cancelled_at IS NULL AND id<>%s''', (machine_id, order_id)).fetchone()['n']
|
||||
return machine['name'] if machine and printing >= PRINTING_CAP else None
|
||||
|
||||
|
||||
def printing_slots(c):
|
||||
"""Per order in Imprimindo: 'imprimindo' for the first to enter it on its
|
||||
machine (ripped, running), 'ripando' for the one after it."""
|
||||
return {row['id']: 'imprimindo' if row['place'] == 1 else 'ripando' for row in c.execute('''
|
||||
SELECT o.id, row_number() OVER (PARTITION BY o.machine_id ORDER BY m.at, o.number) AS place
|
||||
FROM dtf_local.orders o, LATERAL (SELECT max(created_at) AS at FROM dtf_local.movements
|
||||
WHERE order_id=o.id AND to_state='imp') m
|
||||
WHERE o.state='imp' AND o.cancelled_at IS NULL AND o.machine_id IS NOT NULL''').fetchall()}
|
||||
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.'),
|
||||
])
|
||||
219
app/mercadopago.py
Normal file
@@ -0,0 +1,219 @@
|
||||
"""Mercado Pago: payment creation, webhook verification and status lookup.
|
||||
|
||||
Written from the public API documentation and exercised only against a fake
|
||||
HTTP transport. It is not a verified integration until it has passed the
|
||||
sandbox flows in docs/PRODUCTION_INPUTS.md with the client's own account;
|
||||
until then the runtime refuses to select it without explicit credentials.
|
||||
|
||||
The notification is only a pointer. Its body says "payment 123 changed" and
|
||||
nothing about amount or status, so nothing in it is trusted beyond the id:
|
||||
the payment is fetched from the API with our access token, and that response
|
||||
is what the order service compares against the approved quote.
|
||||
|
||||
Signature (x-signature: "ts=<unix>,v1=<hex>"): HMAC-SHA256, keyed with the
|
||||
webhook secret from the integration panel, over the manifest
|
||||
"id:<data.id>;request-id:<x-request-id>;ts:<ts>;", where data.id comes from
|
||||
the notification URL's query string (lower-cased when alphanumeric). A part
|
||||
whose value is absent from the notification is left out of the manifest.
|
||||
"""
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from decimal import Decimal, InvalidOperation
|
||||
from typing import Mapping
|
||||
|
||||
import httpx
|
||||
|
||||
from .adapters import PaymentEvent
|
||||
|
||||
API = 'https://api.mercadopago.com'
|
||||
# How old a signed timestamp may be. Mercado Pago retries a failed delivery
|
||||
# every 15 minutes, re-signing each attempt, so a replayed old one is refused.
|
||||
MAX_SIGNATURE_AGE = 30 * 60
|
||||
STATUSES = {'approved': 'approved', 'pending': 'pending', 'in_process': 'pending',
|
||||
'authorized': 'pending', 'in_mediation': 'pending', 'rejected': 'rejected',
|
||||
'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:
|
||||
name = 'mercadopago'
|
||||
|
||||
def __init__(self, access_token=None, webhook_secret=None, notification_url=None,
|
||||
transport=None, clock=time.time):
|
||||
self.access_token = access_token or os.environ.get('MP_ACCESS_TOKEN', '')
|
||||
# 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', '')
|
||||
if not self.access_token or not self.webhook_secret:
|
||||
raise RuntimeError('Mercado Pago needs MP_ACCESS_TOKEN and MP_WEBHOOK_SECRET')
|
||||
self.http = httpx.Client(base_url=API, transport=transport, timeout=15,
|
||||
headers={'Authorization': f'Bearer {self.access_token}'})
|
||||
self.clock = clock
|
||||
|
||||
# Payments ------------------------------------------------------------
|
||||
|
||||
def create(self, quote_id: str, total_cents: int, customer: dict, method: dict | None = None) -> dict:
|
||||
"""Create a payment for an approved quote.
|
||||
|
||||
The quote id is the idempotency key, so a retry after a timeout returns
|
||||
the payment already created rather than charging again. `method` is
|
||||
{'type': 'pix'} or {'type': 'card', 'token', 'payment_method_id',
|
||||
'installments', 'issuer_id'} from Mercado Pago's card form: card data is
|
||||
tokenised in the customer's browser and never reaches this server.
|
||||
"""
|
||||
method = method or {'type': 'pix'}
|
||||
body = {'transaction_amount': float(Decimal(total_cents) / 100),
|
||||
'description': f'DTF - cotação {quote_id[:8]}',
|
||||
'external_reference': quote_id,
|
||||
'payer': {'email': customer['mail'],
|
||||
'identification': {'type': 'CPF' if len(customer['cnpj']) == 11 else 'CNPJ',
|
||||
'number': customer['cnpj']}}}
|
||||
if self.notification_url:
|
||||
body['notification_url'] = self.notification_url
|
||||
expires_at = None
|
||||
if method['type'] == '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':
|
||||
body.update(token=method['token'], payment_method_id=method['payment_method_id'],
|
||||
installments=int(method.get('installments', 1)))
|
||||
# 3-D Secure (the bank's confirmation) only for debit, which needs
|
||||
# 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:
|
||||
raise ValueError('Unsupported payment method')
|
||||
# A PIX retry must return the same code; a new one, after the last
|
||||
# expired, is the next attempt. A card retry after a decline is a new
|
||||
# attempt with a new token, so the token is part of the key; the intent
|
||||
# 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]}"
|
||||
response = self.http.post('/v1/payments', json=body, headers={'X-Idempotency-Key': key})
|
||||
response.raise_for_status()
|
||||
payment = response.json()
|
||||
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']),
|
||||
'status': STATUSES.get(payment.get('status'), 'pending'),
|
||||
'status_detail': payment.get('status_detail'),
|
||||
'total_cents': total_cents,
|
||||
'pix_qr_code': transaction.get('qr_code'),
|
||||
'pix_qr_code_base64': transaction.get('qr_code_base64'),
|
||||
'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:
|
||||
response = self.http.get(f'/v1/payments/{payment_id}')
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
# Webhooks ------------------------------------------------------------
|
||||
|
||||
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 ''
|
||||
parts = dict(part.strip().split('=', 1) for part in signature.split(',') if '=' in part)
|
||||
ts, supplied = parts.get('ts', ''), parts.get('v1', '')
|
||||
if not ts.isdigit() or not supplied:
|
||||
return False
|
||||
if abs(self.clock() - int(ts[:10])) > MAX_SIGNATURE_AGE:
|
||||
return False
|
||||
request_id = headers.get('x-request-id') or ''
|
||||
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};'
|
||||
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()
|
||||
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:
|
||||
try:
|
||||
data = json.loads(body)
|
||||
except ValueError:
|
||||
return None
|
||||
if not isinstance(data, dict) or data.get('type') != 'payment':
|
||||
return None
|
||||
payment_id = str((query or {}).get('data.id') or (data.get('data') or {}).get('id') or '')
|
||||
if not payment_id.isdigit():
|
||||
return None
|
||||
try:
|
||||
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', '')))
|
||||
|
||||
|
||||
def event_from_payment(payment: dict, notification_id: str = '') -> PaymentEvent:
|
||||
"""Normalise a payment fetched from the API. Amount is None unless it is BRL
|
||||
and a whole number of centavos, so a foreign or malformed amount is refused."""
|
||||
amount = None
|
||||
if payment.get('currency_id') == 'BRL':
|
||||
try:
|
||||
cents = Decimal(str(payment.get('transaction_amount'))) * 100
|
||||
if cents == cents.to_integral_value():
|
||||
amount = int(cents)
|
||||
except (InvalidOperation, TypeError, ValueError):
|
||||
amount = None
|
||||
status = STATUSES.get(payment.get('status'), 'pending')
|
||||
# One event per payment state: a notification id alone would let the same
|
||||
# approval be applied twice under two notifications, and would collapse a
|
||||
# later refund into the earlier approval.
|
||||
event_id = f"{payment.get('id')}:{payment.get('status')}"
|
||||
return PaymentEvent(event_id=event_id, reference=str(payment.get('external_reference') or ''),
|
||||
status=status, amount_cents=amount,
|
||||
raw={'provider': 'mercadopago', 'payment_id': str(payment.get('id')),
|
||||
'status': payment.get('status'), 'status_detail': payment.get('status_detail'),
|
||||
'currency_id': payment.get('currency_id'),
|
||||
'transaction_amount': payment.get('transaction_amount'),
|
||||
'date_approved': payment.get('date_approved'),
|
||||
'notification_id': notification_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())
|
||||
153
app/operators.py
Normal file
@@ -0,0 +1,153 @@
|
||||
"""Kanban operator accounts.
|
||||
|
||||
One shared login meant every card movement was attributed to the same name, so
|
||||
the movement history could not answer who did what. Accounts live in the
|
||||
database; `OPERATOR_EMAIL` and `OPERATOR_PASSWORD` seed the first one so an
|
||||
existing deployment keeps working unchanged.
|
||||
|
||||
Administered from the API container, the same way the schema is:
|
||||
|
||||
python -m app.operators list
|
||||
python -m app.operators add maria@example.com --name "Maria" [--role admin]
|
||||
python -m app.operators role maria@example.com superadmin
|
||||
python -m app.operators password 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
|
||||
reach shell history or the process list.
|
||||
"""
|
||||
import getpass
|
||||
import os
|
||||
import sys
|
||||
from uuid import uuid4
|
||||
|
||||
from .core.auth import ROLES, password_hash
|
||||
from .core.db import connect
|
||||
|
||||
MIN_PASSWORD = 8
|
||||
|
||||
|
||||
def seed_from_environment(cursor):
|
||||
"""Make the configured credential a real account, once.
|
||||
|
||||
Only inserts when that email is absent, so a password changed here is never
|
||||
reverted by a stale environment variable on the next deploy.
|
||||
"""
|
||||
email = os.environ.get('OPERATOR_EMAIL', '').strip().lower()
|
||||
password = os.environ.get('OPERATOR_PASSWORD', '')
|
||||
if not email or not password:
|
||||
return None
|
||||
existing = cursor.execute(
|
||||
'SELECT id FROM dtf_local.operators WHERE email=%s', (email,)).fetchone()
|
||||
if existing:
|
||||
# The configured account is the system's own: it stays superadmin.
|
||||
cursor.execute("UPDATE dtf_local.operators SET role='superadmin' WHERE email=%s", (email,))
|
||||
return None
|
||||
cursor.execute(
|
||||
"INSERT INTO dtf_local.operators(id,email,name,password_hash,role) VALUES(%s,%s,%s,%s,'superadmin')",
|
||||
(uuid4(), email, 'Operador', password_hash(password)))
|
||||
return email
|
||||
|
||||
|
||||
def _ask_password(email):
|
||||
first = getpass.getpass(f'New password for {email}: ')
|
||||
if len(first) < MIN_PASSWORD:
|
||||
raise SystemExit(f'Password must be at least {MIN_PASSWORD} characters.')
|
||||
if first != getpass.getpass('Repeat: '):
|
||||
raise SystemExit('Passwords did not match.')
|
||||
return first
|
||||
|
||||
|
||||
def add(email, name='', role='admin'):
|
||||
email = email.strip().lower()
|
||||
if role not in ROLES:
|
||||
raise SystemExit('Role must be one of: ' + ', '.join(ROLES))
|
||||
with connect() as c:
|
||||
if c.execute('SELECT id FROM dtf_local.operators WHERE email=%s', (email,)).fetchone():
|
||||
raise SystemExit(f'{email} already exists. Use "password" or "enable".')
|
||||
c.execute('INSERT INTO dtf_local.operators(id,email,name,password_hash,role) VALUES(%s,%s,%s,%s,%s)',
|
||||
(uuid4(), email, name, password_hash(_ask_password(email)), role))
|
||||
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):
|
||||
email = email.strip().lower()
|
||||
with connect() as c:
|
||||
if not c.execute('SELECT id FROM dtf_local.operators WHERE email=%s', (email,)).fetchone():
|
||||
raise SystemExit(f'{email} does not exist.')
|
||||
c.execute('UPDATE dtf_local.operators SET password_hash=%s WHERE email=%s',
|
||||
(password_hash(_ask_password(email)), email))
|
||||
print(f'Password changed for {email}. Existing sessions stay valid until they expire;'
|
||||
' run "disable" first if the account is compromised.')
|
||||
|
||||
|
||||
def set_active(email, active):
|
||||
email = email.strip().lower()
|
||||
with connect() as c:
|
||||
updated = c.execute(
|
||||
'UPDATE dtf_local.operators SET active=%s WHERE email=%s RETURNING email',
|
||||
(active, email)).fetchone()
|
||||
if not updated:
|
||||
raise SystemExit(f'{email} does not exist.')
|
||||
if not active:
|
||||
# Revoke immediately: disabling must end access now, not in eight hours.
|
||||
c.execute('DELETE FROM dtf_local.operator_sessions WHERE username=%s', (email,))
|
||||
print(f'{email} {"enabled" if active else "disabled; open sessions revoked"}.')
|
||||
|
||||
|
||||
def listing():
|
||||
with connect() as c:
|
||||
rows = c.execute('''SELECT email,name,role,active,last_login_at FROM dtf_local.operators
|
||||
ORDER BY email''').fetchall()
|
||||
if not rows:
|
||||
print('No operator accounts. Set OPERATOR_EMAIL and OPERATOR_PASSWORD and run'
|
||||
' "python -m local.bootstrap", or add one here.')
|
||||
return
|
||||
for row in rows:
|
||||
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'
|
||||
print(f"{state} {row['email']:<34} {row['name'][:20]:<20} {row['role']:<10} last login {seen}")
|
||||
|
||||
|
||||
def main(argv):
|
||||
if not argv:
|
||||
raise SystemExit(__doc__)
|
||||
command, rest = argv[0], argv[1:]
|
||||
if command == 'list':
|
||||
return listing()
|
||||
if not rest:
|
||||
raise SystemExit(f'usage: python -m local.operators {command} <email>')
|
||||
email = rest[0]
|
||||
if command == 'add':
|
||||
name = rest[rest.index('--name') + 1] if '--name' in rest else ''
|
||||
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':
|
||||
return password(email)
|
||||
if command == 'disable':
|
||||
return set_active(email, False)
|
||||
if command == 'enable':
|
||||
return set_active(email, True)
|
||||
raise SystemExit(__doc__)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main(sys.argv[1:])
|
||||
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.')
|
||||
230
app/payments.py
Normal file
@@ -0,0 +1,230 @@
|
||||
"""Turning a payment into an order, once.
|
||||
|
||||
A provider may deliver the same notification several times, out of order, or
|
||||
long after the fact. None of that may produce a second order, a second charge,
|
||||
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
|
||||
crash mid-way is retried rather than half-applied.
|
||||
|
||||
Order creation lives here rather than in a route because the paths that reach
|
||||
it must agree: the webhook, reconcile() (the provider asked directly) and the
|
||||
local development checkout.
|
||||
"""
|
||||
import logging
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from psycopg.types.json import Jsonb
|
||||
|
||||
from . import machines, mail, proof
|
||||
from .core.auth import audit
|
||||
from .core.models import PRODUCTION_VERSIONS
|
||||
from .printjobs import queue as queue_print_files
|
||||
from .runtime import PUBLIC_ORIGIN, enqueue, upload_row
|
||||
from .scanning import require_clean
|
||||
|
||||
QUOTE_VALID_HOURS = 24
|
||||
|
||||
|
||||
class PaymentRefused(Exception):
|
||||
"""The payment cannot become an order, with a reason worth recording."""
|
||||
|
||||
|
||||
def approved_quote(c, quote_id, owner=None):
|
||||
"""The reviewed quote behind a payment, or a refusal explaining why not."""
|
||||
sql = 'SELECT * FROM dtf_local.quotes WHERE id=%s' + (' AND owner=%s' if owner else '')
|
||||
row = c.execute(sql + ' FOR UPDATE', (quote_id, owner) if owner else (quote_id,)).fetchone()
|
||||
if not row:
|
||||
raise PaymentRefused('quote not found')
|
||||
if not row['approved']:
|
||||
raise PaymentRefused('quote was never reviewed')
|
||||
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')
|
||||
if row['approved_at'] < datetime.now(timezone.utc) - timedelta(hours=QUOTE_VALID_HOURS):
|
||||
raise PaymentRefused('quote expired before payment')
|
||||
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
|
||||
|
||||
|
||||
# An order paid outside the system (Pix or cash at the counter, a card machine,
|
||||
# the customer's credit) and registered by the team from its Site quote
|
||||
# (Dropstar's rule D-35, 2026-10-26; the user's answers of 2026-10-27).
|
||||
MANUAL_PROVIDER = 'manual'
|
||||
OUTSIDE_METHODS = ('pix', 'card', 'cash', 'credit')
|
||||
|
||||
|
||||
def in_tiny(order):
|
||||
"""Whether the order goes to Tiny: every order but a test. A Dropflow
|
||||
order goes in its own revenue category (app/tiny.py, CATEGORIES)."""
|
||||
return not is_test(order)
|
||||
|
||||
|
||||
# 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, origin):
|
||||
"""Create the order for a reviewed quote, or return the one already there.
|
||||
`origin` is where it came from (D-21): each way in names its own.
|
||||
|
||||
Returns (order, created). The caller decides what to do about a duplicate;
|
||||
the important part is that asking twice cannot produce two orders, because
|
||||
orders.quote_id is unique and this runs inside the caller's transaction.
|
||||
"""
|
||||
existing = c.execute('SELECT * FROM dtf_local.orders WHERE quote_id=%s', (quote['id'],)).fetchone()
|
||||
if existing:
|
||||
return existing, False
|
||||
|
||||
approved = quote['approved']
|
||||
for item in approved['items']:
|
||||
for upload_id in item['uploads']:
|
||||
require_clean(upload_row(c, UUID(upload_id), quote['owner']))
|
||||
|
||||
order = c.execute(
|
||||
'''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,origin)
|
||||
VALUES(%s,%s,%s,%s,%s,%s) RETURNING *''',
|
||||
(uuid4(), quote['id'], quote['owner'], Jsonb(approved), Jsonb(payment), origin)).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']))
|
||||
if approved.get('proof'):
|
||||
# The customer asked for a proof: the order waits for their word.
|
||||
order = c.execute('''UPDATE dtf_local.orders SET contact_since=now(), contact_by='Site', contact_note=%s
|
||||
WHERE id=%s RETURNING *''', (proof.CUSTOMER_NOTE, order['id'])).fetchone()
|
||||
c.execute('INSERT INTO dtf_local.contact_waits(order_id, started_at) VALUES(%s, now())', (order['id'],))
|
||||
machines.route(c)
|
||||
if is_test(order):
|
||||
return order, True
|
||||
mail.order_paid(c, order, PUBLIC_ORIGIN)
|
||||
if not in_tiny(order):
|
||||
return order, True
|
||||
# How it was paid, for the order's payment in Tiny.
|
||||
if payment.get('provider') == MANUAL_PROVIDER:
|
||||
paid = {'method': payment['method'], 'outside': True}
|
||||
else:
|
||||
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'],
|
||||
'event': 'payment_approved', 'order': approved, 'origin': origin,
|
||||
'payment': dict(paid) if paid else {}})
|
||||
return order, True
|
||||
|
||||
|
||||
def record(c, provider, event):
|
||||
"""Store a delivery. Returns None if this exact event was already seen."""
|
||||
inserted = c.execute(
|
||||
'''INSERT INTO dtf_local.payment_events(id,provider,event_id,reference,status,amount_cents,payload)
|
||||
VALUES(%s,%s,%s,%s,%s,%s,%s) ON CONFLICT(provider,event_id) DO NOTHING RETURNING *''',
|
||||
(uuid4(), provider, event.event_id, event.reference, event.status,
|
||||
event.amount_cents, Jsonb(event.raw))).fetchone()
|
||||
return inserted
|
||||
|
||||
|
||||
def apply(c, event):
|
||||
"""Act on a payment notification. Returns the outcome recorded against it.
|
||||
|
||||
Outcomes starting 'refused' (money arrived, no order) or 'attention' (an
|
||||
order exists but its payment was reversed) stay on the Kanban until an
|
||||
operator records a resolution.
|
||||
"""
|
||||
provider_id = event.raw.get('payment_id')
|
||||
if provider_id:
|
||||
c.execute('''UPDATE dtf_local.payment_intents SET status=%s, updated_at=now()
|
||||
WHERE provider_payment_id=%s''', (event.status, provider_id))
|
||||
if event.status in ('refunded', 'cancelled'):
|
||||
try:
|
||||
order = c.execute('SELECT number FROM dtf_local.orders WHERE quote_id=%s',
|
||||
(UUID(event.reference),)).fetchone()
|
||||
except (ValueError, AttributeError):
|
||||
order = None
|
||||
if order:
|
||||
audit('payment_reversed', order=order['number'], status=event.status)
|
||||
return f"attention: payment {event.status} for order {order['number']}"
|
||||
if event.status != 'approved':
|
||||
return f'ignored: {event.status}'
|
||||
|
||||
try:
|
||||
quote_id = UUID(event.reference)
|
||||
except (ValueError, AttributeError):
|
||||
return 'refused: reference is not a quote id'
|
||||
|
||||
try:
|
||||
quote = approved_quote(c, quote_id)
|
||||
except PaymentRefused as refusal:
|
||||
return f'refused: {refusal}'
|
||||
|
||||
# The provider is the authority on what was paid, and the reviewed quote is
|
||||
# the authority on what was owed. If they disagree, no order is created:
|
||||
# underpayment would ship artwork that was not paid for, and overpayment
|
||||
# means something is wrong that a person should look at.
|
||||
expected = quote['approved']['total_cents']
|
||||
if type(event.amount_cents) is not int or event.amount_cents != expected:
|
||||
audit('payment_amount_mismatch', quote=str(quote_id),
|
||||
expected_cents=expected, paid_cents=event.amount_cents)
|
||||
return f'refused: paid {event.amount_cents} but quote total is {expected}'
|
||||
|
||||
order, created = create_order(c, quote, {'provider': event.raw.get('provider', 'webhook'), **event.raw}, 'site')
|
||||
return f"order {order['number']}" + ('' if created else ' (already existed)')
|
||||
|
||||
|
||||
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
|
||||
581
app/printfile.py
Normal file
@@ -0,0 +1,581 @@
|
||||
"""The print file: the reviewed layout, reproduced exactly, at the film's size.
|
||||
|
||||
The customer is quoted on a layout the Site computes: each copy of each artwork
|
||||
at a width, rotation, mirror and position on the film. Production spec v2 keeps
|
||||
that layout through the approved order. This module turns it into one PDF per
|
||||
order item, with a page exactly as wide as the film and as long as the layout,
|
||||
so the operator imports what the customer approved instead of rebuilding it.
|
||||
|
||||
Each source image is embedded once, at its original resolution, and every copy
|
||||
is a placement of it. Nothing is resampled: a 300 DPI artwork is still 300 DPI
|
||||
in the file, a JPEG keeps its original bytes, and transparency survives as a
|
||||
soft mask. The output is therefore about the size of the artwork, not of a
|
||||
57 cm x 20 m raster, and it never needs that raster in memory.
|
||||
|
||||
Raster sources are JPEG, PNG, WebP and TIFF. A single-page PDF is placed as a
|
||||
vector form, never rasterised. Anything else (PSD, AI, CDR, multi-page or
|
||||
protected PDFs), or a file whose proportions do not match the size it was
|
||||
quoted at, is refused with a reason, and the operator prepares that item by
|
||||
hand exactly as before.
|
||||
"""
|
||||
import math
|
||||
import os
|
||||
import tempfile
|
||||
import zlib
|
||||
from decimal import Decimal
|
||||
|
||||
from PIL import Image, ImageOps
|
||||
|
||||
from .core.models import PRODUCTION_VERSIONS
|
||||
|
||||
PT_PER_CM = 72 / 2.54
|
||||
# Acrobat's page limit, 200 inches (5,08 m). A longer sheet is written at its
|
||||
# real size, on one page: CorelDRAW, where Dropstar checks the files, ignores
|
||||
# /UserUnit and showed a 12,8 m sheet at a third of its size (2026-10-28).
|
||||
# PRINT_PAGE_SCALE=true goes back to scaling user space with /UserUnit (PDF
|
||||
# 1.6), for software that refuses pages over the limit. Either way the film is
|
||||
# never cut into pages a RIP might print with gaps.
|
||||
MAX_PAGE_PT = 14400
|
||||
|
||||
|
||||
def page_unit(width_pt, height_pt):
|
||||
"""The page's /UserUnit: 1 (real size) unless PRINT_PAGE_SCALE is on."""
|
||||
if os.environ.get('PRINT_PAGE_SCALE', 'false').strip().lower() != 'true':
|
||||
return 1
|
||||
return max(1, math.ceil(max(width_pt, height_pt) / MAX_PAGE_PT))
|
||||
# How far a file's proportions may drift from the quoted size before the item
|
||||
# is refused: rounding in the Site keeps real files well inside this.
|
||||
ASPECT_TOLERANCE = 0.01
|
||||
# The quote may round up (10 cm steps, 1 m minimum) but never down.
|
||||
HEIGHT_TOLERANCE_CM = Decimal('0.05')
|
||||
SUPPORTED_FORMATS = {'JPEG', 'PNG', 'WEBP', 'TIFF'}
|
||||
STRIP_ROWS = 256
|
||||
# Decoding holds the whole image in memory (about 4 bytes a pixel). 57 cm x 3 m
|
||||
# at 300 DPI is 239 Mpx; above this the item goes to the operator instead.
|
||||
MAX_DECODED_PIXELS = int(os.environ.get('PRINT_MAX_PIXELS', '250000000'))
|
||||
# Pillow's own bomb guard would refuse a genuine long sheet before we can
|
||||
# decide; the explicit limit above is the one that applies.
|
||||
Image.MAX_IMAGE_PIXELS = None
|
||||
|
||||
|
||||
class Unsupported(Exception):
|
||||
"""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):
|
||||
pass
|
||||
|
||||
|
||||
class Ref(int):
|
||||
pass
|
||||
|
||||
|
||||
def serialize(value):
|
||||
if isinstance(value, Ref):
|
||||
return b'%d 0 R' % value
|
||||
if isinstance(value, Name):
|
||||
return b'/' + value.encode('ascii')
|
||||
if isinstance(value, bool):
|
||||
return b'true' if value else b'false'
|
||||
if isinstance(value, int):
|
||||
return b'%d' % value
|
||||
if isinstance(value, (float, Decimal)):
|
||||
text = f'{float(value):.4f}'.rstrip('0').rstrip('.')
|
||||
return (text if text not in ('', '-0') else '0').encode('ascii')
|
||||
if isinstance(value, dict):
|
||||
return b'<<' + b''.join(b'/' + k.encode('ascii') + b' ' + serialize(v)
|
||||
for k, v in value.items()) + b'>>'
|
||||
if isinstance(value, (list, tuple)):
|
||||
return b'[' + b' '.join(serialize(v) for v in value) + b']'
|
||||
if isinstance(value, str):
|
||||
escaped = value.replace('\\', '\\\\').replace('(', '\\(').replace(')', '\\)')
|
||||
return b'(' + escaped.encode('latin-1', 'replace') + b')'
|
||||
raise TypeError(f'Cannot serialize {type(value).__name__}')
|
||||
|
||||
|
||||
class PdfWriter:
|
||||
"""A sequential PDF writer: objects go straight to the file, streams included.
|
||||
|
||||
Stream lengths are indirect objects written after the data, so an image is
|
||||
compressed strip by strip into the output without being held in memory.
|
||||
"""
|
||||
|
||||
def __init__(self, fp):
|
||||
self.fp = fp
|
||||
self.offsets = {}
|
||||
self.next_id = 1
|
||||
self.write(b'%PDF-1.6\n%\xe2\xe3\xcf\xd3\n')
|
||||
|
||||
def write(self, data):
|
||||
self.fp.write(data)
|
||||
|
||||
def tell(self):
|
||||
return self.fp.tell()
|
||||
|
||||
def alloc(self):
|
||||
ref = Ref(self.next_id)
|
||||
self.next_id += 1
|
||||
return ref
|
||||
|
||||
def obj(self, value, ref=None):
|
||||
ref = ref or self.alloc()
|
||||
self.offsets[ref] = self.tell()
|
||||
self.write(b'%d 0 obj\n' % ref + serialize(value) + b'\nendobj\n')
|
||||
return ref
|
||||
|
||||
def stream(self, dictionary, chunks, ref=None):
|
||||
"""Write a stream from an iterable of already-encoded byte chunks."""
|
||||
ref = ref or self.alloc()
|
||||
length = self.alloc()
|
||||
self.offsets[ref] = self.tell()
|
||||
self.write(b'%d 0 obj\n' % ref + serialize({**dictionary, 'Length': length}) + b'\nstream\n')
|
||||
start = self.tell()
|
||||
for chunk in chunks:
|
||||
self.write(chunk)
|
||||
size = self.tell() - start
|
||||
self.write(b'\nendstream\nendobj\n')
|
||||
self.obj(size, length)
|
||||
return ref
|
||||
|
||||
def finish(self, root, info):
|
||||
xref = self.tell()
|
||||
count = self.next_id
|
||||
self.write(b'xref\n0 %d\n0000000000 65535 f \n' % count)
|
||||
for ref in range(1, count):
|
||||
self.write(b'%010d 00000 n \n' % self.offsets[ref])
|
||||
self.write(b'trailer\n' + serialize({'Size': count, 'Root': root, 'Info': info}) +
|
||||
b'\nstartxref\n%d\n%%%%EOF\n' % xref)
|
||||
|
||||
|
||||
def deflate(pieces):
|
||||
compressor = zlib.compressobj(6)
|
||||
for piece in pieces:
|
||||
out = compressor.compress(piece)
|
||||
if out:
|
||||
yield out
|
||||
yield compressor.flush()
|
||||
|
||||
|
||||
class SourceImage:
|
||||
"""One customer file, opened for reading pixels and measured as the browser sees it."""
|
||||
|
||||
def __init__(self, path, name):
|
||||
self.path = path
|
||||
self.name = name
|
||||
try:
|
||||
self.image = Image.open(path)
|
||||
self.format = self.image.format
|
||||
except Image.DecompressionBombError as exc:
|
||||
raise Unsupported(f'"{name}" é grande demais para gerar automaticamente') from exc
|
||||
except Exception as exc:
|
||||
raise Unsupported(f'"{name}" não é uma imagem que o gerador consiga ler') from exc
|
||||
if self.format not in SUPPORTED_FORMATS:
|
||||
raise Unsupported(f'"{name}" está em {self.format or "formato desconhecido"}; '
|
||||
'só JPEG, PNG, WebP, TIFF e PDF são gerados automaticamente')
|
||||
if getattr(self.image, 'n_frames', 1) > 1 and self.format != 'TIFF':
|
||||
raise Unsupported(f'"{name}" é animado ou tem vários quadros')
|
||||
# Browsers draw a photo upright according to its EXIF orientation, and
|
||||
# the Site measured it that way, so the print must too.
|
||||
try:
|
||||
self.orientation = self.image.getexif().get(0x0112, 1)
|
||||
except Exception:
|
||||
self.orientation = 1
|
||||
width, height = self.image.size
|
||||
self.size = (height, width) if self.orientation in (5, 6, 7, 8) else (width, height)
|
||||
|
||||
def passthrough(self):
|
||||
"""Whether the original JPEG bytes can go into the PDF unchanged."""
|
||||
return (self.format == 'JPEG' and self.orientation == 1 and
|
||||
self.image.mode in ('L', 'RGB', 'CMYK'))
|
||||
|
||||
def embed(self, pdf):
|
||||
"""Write this image (and its alpha) as XObjects; returns the image reference."""
|
||||
if self.passthrough():
|
||||
return self._embed_jpeg(pdf)
|
||||
width, height = self.image.size
|
||||
if width * height > MAX_DECODED_PIXELS:
|
||||
raise Unsupported(f'"{self.name}" tem {width} × {height} px, mais do que o '
|
||||
'gerador processa; prepare este item à mão')
|
||||
return self._embed_pixels(pdf)
|
||||
|
||||
def _colorspace(self, pdf, mode):
|
||||
components = {'L': 1, 'RGB': 3, 'CMYK': 4}[mode]
|
||||
device = Name({'L': 'DeviceGray', 'RGB': 'DeviceRGB', 'CMYK': 'DeviceCMYK'}[mode])
|
||||
profile = self.image.info.get('icc_profile')
|
||||
if not profile:
|
||||
return device
|
||||
icc = pdf.stream({'N': components, 'Alternate': device, 'Filter': Name('FlateDecode')},
|
||||
deflate([profile]))
|
||||
return [Name('ICCBased'), icc]
|
||||
|
||||
def _embed_jpeg(self, pdf):
|
||||
image = self.image
|
||||
extra = {}
|
||||
if image.mode == 'CMYK' and 'adobe' in image.info:
|
||||
# Adobe writes CMYK JPEGs inverted; PDF readers expect the Decode flip.
|
||||
extra['Decode'] = [1, 0, 1, 0, 1, 0, 1, 0]
|
||||
|
||||
def chunks():
|
||||
with open(self.path, 'rb') as source:
|
||||
while block := source.read(1 << 20):
|
||||
yield block
|
||||
return pdf.stream({'Type': Name('XObject'), 'Subtype': Name('Image'),
|
||||
'Width': image.width, 'Height': image.height,
|
||||
'ColorSpace': self._colorspace(pdf, image.mode),
|
||||
'BitsPerComponent': 8, 'Filter': Name('DCTDecode'), **extra},
|
||||
chunks())
|
||||
|
||||
def _upright(self):
|
||||
image = self.image
|
||||
image.load()
|
||||
if self.orientation != 1:
|
||||
image = ImageOps.exif_transpose(image)
|
||||
return image
|
||||
|
||||
def _embed_pixels(self, pdf):
|
||||
image = self._upright()
|
||||
mode = image.mode
|
||||
has_alpha = mode in ('RGBA', 'LA', 'PA', 'RGBa', 'La') or (
|
||||
mode == 'P' and 'transparency' in image.info) or (
|
||||
mode in ('L', 'RGB') and 'transparency' in image.info)
|
||||
if mode in ('I;16', 'I;16B', 'I;16L', 'I'):
|
||||
image = image.convert('I').point(lambda value: value * (1 / 257)).convert('L')
|
||||
mode = 'L'
|
||||
if mode == 'CMYK':
|
||||
color_mode = 'CMYK'
|
||||
elif mode in ('1', 'L', 'LA', 'La'):
|
||||
color_mode = 'L'
|
||||
elif mode in ('P', 'PA', 'RGB', 'RGBA', 'RGBa'):
|
||||
color_mode = 'RGB'
|
||||
else:
|
||||
raise Unsupported(f'"{self.name}" usa o modo de cor {mode}, que não é gerado automaticamente')
|
||||
if has_alpha:
|
||||
image = image.convert('RGBA' if color_mode == 'RGB' else 'LA')
|
||||
width, height = image.size
|
||||
|
||||
def strips(convert):
|
||||
for top in range(0, height, STRIP_ROWS):
|
||||
yield convert(image.crop((0, top, width, min(height, top + STRIP_ROWS)))).tobytes()
|
||||
|
||||
smask = None
|
||||
if has_alpha:
|
||||
smask = pdf.stream({'Type': Name('XObject'), 'Subtype': Name('Image'),
|
||||
'Width': width, 'Height': height,
|
||||
'ColorSpace': Name('DeviceGray'), 'BitsPerComponent': 8,
|
||||
'Filter': Name('FlateDecode')},
|
||||
deflate(strips(lambda strip: strip.getchannel('A'))))
|
||||
colorspace = self._colorspace(pdf, color_mode)
|
||||
dictionary = {'Type': Name('XObject'), 'Subtype': Name('Image'),
|
||||
'Width': width, 'Height': height, 'ColorSpace': colorspace,
|
||||
'BitsPerComponent': 8, 'Filter': Name('FlateDecode')}
|
||||
if smask:
|
||||
dictionary['SMask'] = smask
|
||||
return pdf.stream(dictionary, deflate(strips(lambda strip: strip.convert(color_mode))))
|
||||
|
||||
def close(self):
|
||||
self.image.close()
|
||||
|
||||
|
||||
def placement_matrix(placement, page_height_pt):
|
||||
"""Map the image's unit square onto its box on the film.
|
||||
|
||||
Matches the Site's canvas: the artwork is mirrored first, then turned
|
||||
clockwise about the centre of its box, and the turned image fills the box.
|
||||
"""
|
||||
x = float(placement['x_cm']) * PT_PER_CM
|
||||
top = page_height_pt - float(placement['y_cm']) * PT_PER_CM
|
||||
w = float(placement['width_cm']) * PT_PER_CM
|
||||
h = float(placement['length_cm']) * PT_PER_CM
|
||||
rotation = placement['rotation_degrees'] % 360
|
||||
mirrored = placement['mirrored']
|
||||
|
||||
def to_page(u, v):
|
||||
# Unit square (v up) -> image frame (s right, t down).
|
||||
s, t = u, 1 - v
|
||||
if mirrored:
|
||||
s = 1 - s
|
||||
s, t = {0: (s, t), 90: (1 - t, s), 180: (1 - s, 1 - t), 270: (t, 1 - s)}[rotation]
|
||||
return x + s * w, top - t * h
|
||||
|
||||
ox, oy = to_page(0, 0)
|
||||
ax, ay = to_page(1, 0)
|
||||
cx, cy = to_page(0, 1)
|
||||
return [ax - ox, ay - oy, cx - ox, cy - oy, ox, oy]
|
||||
|
||||
|
||||
class PdfPage:
|
||||
"""One page of a customer PDF, placed as a vector form: nothing is rasterised.
|
||||
|
||||
The box and orientation are the ones the Site measured with pdf.js: the
|
||||
CropBox (which pikepdf uses for the form's BBox), turned by the page's
|
||||
/Rotate, inherited or not.
|
||||
"""
|
||||
|
||||
def __init__(self, path, name):
|
||||
import pikepdf
|
||||
self.name = name
|
||||
try:
|
||||
self.pdf = pikepdf.open(path)
|
||||
except pikepdf.PasswordError as exc:
|
||||
raise Unsupported(f'"{name}" está protegido por senha') from exc
|
||||
except Exception as exc:
|
||||
raise Unsupported(f'"{name}" não é um PDF que o gerador consiga ler') from exc
|
||||
try:
|
||||
pages = len(self.pdf.pages)
|
||||
if pages != 1:
|
||||
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.rotation = int(self.page.rotation) % 360
|
||||
if self.rotation not in (0, 90, 180, 270):
|
||||
raise Unsupported(f'"{name}" tem uma rotação de página não suportada')
|
||||
box = [float(v) for v in self.page.cropbox]
|
||||
except Unsupported:
|
||||
self.pdf.close()
|
||||
raise
|
||||
except Exception as exc:
|
||||
self.pdf.close()
|
||||
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.w, self.h = abs(box[2] - box[0]), abs(box[3] - box[1])
|
||||
if self.w <= 0 or self.h <= 0:
|
||||
self.pdf.close()
|
||||
raise Unsupported(f'"{name}" tem uma página vazia')
|
||||
# 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)
|
||||
|
||||
def normalise(self):
|
||||
"""Matrix from the page's box, as displayed, onto the unit square."""
|
||||
a, d = 1 / self.w, 1 / self.h
|
||||
scale = [a, 0, 0, d, -self.x0 * a, -self.y0 * d]
|
||||
turn = {0: [1, 0, 0, 1, 0, 0], 90: [0, -1, 1, 0, 0, 1],
|
||||
180: [-1, 0, 0, -1, 1, 1], 270: [0, 1, -1, 0, 1, 0]}[self.rotation]
|
||||
return multiply(scale, turn)
|
||||
|
||||
def form(self, target):
|
||||
"""The page as a form XObject copied into the target document."""
|
||||
form = self.page.as_form_xobject(handle_transformations=False)
|
||||
group = self.page.obj.get('/Group')
|
||||
if group is not None and '/Group' not in form:
|
||||
form.Group = group
|
||||
return target.copy_foreign(form)
|
||||
|
||||
def close(self):
|
||||
self.pdf.close()
|
||||
|
||||
|
||||
def multiply(first, then):
|
||||
"""PDF matrices: a point transformed by `first`, then by `then`."""
|
||||
a1, b1, c1, d1, e1, f1 = first
|
||||
a2, b2, c2, d2, e2, f2 = then
|
||||
return [a1 * a2 + b1 * c2, a1 * b2 + b1 * d2, c1 * a2 + d1 * c2, c1 * b2 + d1 * d2,
|
||||
e1 * a2 + f1 * c2 + e2, e1 * b2 + f1 * d2 + f2]
|
||||
|
||||
|
||||
def open_source(path, name):
|
||||
with open(path, 'rb') as handle:
|
||||
head = handle.read(1024)
|
||||
if b'%PDF-' in head:
|
||||
return PdfPage(path, name)
|
||||
return SourceImage(path, name)
|
||||
|
||||
|
||||
def check_layout(item, sizes, vector=()):
|
||||
"""Refuse a layout the file cannot reproduce faithfully. Returns the lowest
|
||||
DPI of the raster sources (vector pages have none)."""
|
||||
production = item['production']
|
||||
height = Decimal(str(production['height_cm']))
|
||||
billed = Decimal(str(item['billed_metres'])) * 100
|
||||
if height > billed + HEIGHT_TOLERANCE_CM:
|
||||
raise Unsupported(f'a montagem tem {height} cm, mas só {billed} cm foram cobrados')
|
||||
lowest = None
|
||||
for placement in production['placements']:
|
||||
width_px, height_px = sizes[placement['source_index']]
|
||||
if placement['rotation_degrees'] % 180 == 90:
|
||||
width_px, height_px = height_px, width_px
|
||||
width_cm = float(placement['width_cm'])
|
||||
length_cm = float(placement['length_cm'])
|
||||
drift = abs((width_px / height_px) / (width_cm / length_cm) - 1)
|
||||
if drift > ASPECT_TOLERANCE:
|
||||
source = production['sources'][placement['source_index']]
|
||||
raise Unsupported(f'o arquivo {placement["source_index"] + 1} tem proporções diferentes '
|
||||
f'das cotadas ({source["width_cm"]} × {source["length_cm"]} cm)')
|
||||
if placement['source_index'] in vector:
|
||||
continue
|
||||
dpi = width_px / (width_cm / 2.54)
|
||||
lowest = dpi if lowest is None else min(lowest, dpi)
|
||||
return lowest
|
||||
|
||||
|
||||
# The footer (Dropstar, 2026-10-21): a 1,5 cm band after the last piece with one
|
||||
# line of black text on no background, saying which order, item, date and length
|
||||
# the sheet is, so a sheet cut off or dropped in the room is still known. The band
|
||||
# is outside the billed length: the page grows by it and never covers artwork.
|
||||
FOOTER_CM = Decimal('1.5')
|
||||
# The line about 1 cm tall, from the top of a "d" to the bottom of a "p"
|
||||
# (Dropstar, 2026-10-28; it was 18 pt, about 0,6 cm), smaller only when the
|
||||
# line would not fit the film's width (the 27 cm UV).
|
||||
FOOTER_PT = 31
|
||||
FOOTER_FONTS = {'F1': 'Helvetica-Bold', 'F2': 'Helvetica'}
|
||||
# Helvetica's widths (thousandths of the size), regular and bold, for the
|
||||
# characters the line uses; anything else counts as wide.
|
||||
_HELVETICA = dict(zip(' ,-./0123456789:ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\xb7',
|
||||
[278, 278, 333, 278, 278] + [556] * 10 + [278] +
|
||||
[667, 667, 722, 722, 667, 611, 778, 722, 278, 500, 667, 556, 833, 722, 778, 667, 778, 722, 667, 611,
|
||||
722, 667, 944, 667, 667, 611] +
|
||||
[556, 556, 500, 556, 556, 278, 556, 556, 222, 222, 500, 222, 833, 556, 556, 556, 556, 333, 500, 278,
|
||||
556, 500, 722, 500, 500, 500] + [278]))
|
||||
_HELVETICA_BOLD = dict(zip(' ,-./0123456789:ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\xb7',
|
||||
[278, 278, 333, 278, 278] + [556] * 10 + [333] +
|
||||
[722, 722, 722, 722, 667, 611, 778, 722, 278, 556, 722, 611, 833, 722, 778, 667, 778, 722, 667, 611,
|
||||
722, 667, 944, 667, 667, 611] +
|
||||
[556, 611, 556, 611, 556, 333, 611, 611, 278, 278, 556, 278, 889, 611, 611, 611, 611, 389, 556, 333,
|
||||
611, 556, 778, 556, 556, 500] + [278]))
|
||||
|
||||
|
||||
def text_width(text, bold=False):
|
||||
"""The width of `text` in Helvetica at size 1, in points."""
|
||||
widths = _HELVETICA_BOLD if bold else _HELVETICA
|
||||
return sum(widths.get(ch, 1000) for ch in text) / 1000
|
||||
# Dropstar's logo (sent 2026-10-23): black on transparent, so no white base is
|
||||
# printed around it. It takes the place of the brand's name at the line's start.
|
||||
FOOTER_LOGO = os.path.join(os.path.dirname(__file__), 'assets', 'logo-dropstar.png')
|
||||
FOOTER_LOGO_CM = 1.3
|
||||
|
||||
|
||||
def footer_commands(text, logo_size=None, width_pt=57 * PT_PER_CM):
|
||||
"""The footer's line, 0,5 cm from the left: the logo then the rest, or,
|
||||
without a logo, the line's first part (the brand) in bold. It is
|
||||
FOOTER_PT, or less when that would not fit `width_pt`, the film."""
|
||||
brand, _, rest = text.partition(' · ')
|
||||
# A warning closing the line (ESPELHADO) goes in bold.
|
||||
rest, mark, _ = rest.rpartition(' · ESPELHADO') if rest.endswith(' · ESPELHADO') else (rest, '', '')
|
||||
def literal(value):
|
||||
raw = value.encode('cp1252', 'replace')
|
||||
return b'(' + raw.replace(b'\\', b'\\\\').replace(b'(', b'\\(').replace(b')', b'\\)') + b')'
|
||||
def sized(room, line):
|
||||
fit = room / max(sum(text_width(part, bold) for part, bold in line), 1e-9)
|
||||
return int(min(FOOTER_PT, fit))
|
||||
x = 0.5 * PT_PER_CM
|
||||
if logo_size:
|
||||
height = FOOTER_LOGO_CM * PT_PER_CM
|
||||
width = height * logo_size[0] / logo_size[1]
|
||||
start = x + width + 0.4 * PT_PER_CM
|
||||
size = sized(width_pt - start - x, [(rest, False), (mark, True)])
|
||||
y = (float(FOOTER_CM) * PT_PER_CM - size * 0.7) / 2
|
||||
bottom = (float(FOOTER_CM) * PT_PER_CM - height) / 2
|
||||
return (b'q %s 0 0 %s %s %s cm /Logo Do Q\n' % (serialize(width), serialize(height), serialize(x), serialize(bottom))
|
||||
+ b'q 0 g BT /F2 %d Tf %s %s Td %s Tj /F1 %d Tf %s Tj ET Q\n'
|
||||
% (size, serialize(start), serialize(y), literal(rest), size, literal(mark)))
|
||||
middle = ' · ' + rest if rest else ''
|
||||
size = sized(width_pt - 2 * x, [(brand, True), (middle, False), (mark, True)])
|
||||
y = (float(FOOTER_CM) * PT_PER_CM - size * 0.7) / 2
|
||||
return (b'q 0 g BT /F1 %d Tf %s %s Td %s Tj /F2 %d Tf %s Tj /F1 %d Tf %s Tj ET Q\n'
|
||||
% (size, serialize(x), serialize(y), literal(brand), size, literal(middle), size, literal(mark)))
|
||||
|
||||
|
||||
def render(item, files, out, title, footer=None):
|
||||
"""Write the PDF for one approved order item.
|
||||
|
||||
`files` maps each source index to (local path, original name). With
|
||||
`footer`, the page gets the footer band and that line in it. Returns the
|
||||
evidence the Kanban shows: page size, what was billed, and the lowest DPI.
|
||||
|
||||
Raster sources are written by the streaming writer above. PDF sources are
|
||||
then added as vector forms by a second pass through pikepdf, so a sheet
|
||||
exported as PDF keeps its vectors, fonts and transparency.
|
||||
"""
|
||||
production = item['production']
|
||||
if production.get('version') not in PRODUCTION_VERSIONS:
|
||||
raise Unsupported('o item usa uma montagem antiga')
|
||||
sources = []
|
||||
try:
|
||||
for index in range(len(production['sources'])):
|
||||
path, name = files[index]
|
||||
sources.append(open_source(path, name))
|
||||
vector = {index for index, source in enumerate(sources) if isinstance(source, PdfPage)}
|
||||
lowest_dpi = check_layout(item, [source.size for source in sources], vector)
|
||||
|
||||
width_pt = float(production['film_width_cm']) * PT_PER_CM
|
||||
page_cm = Decimal(str(production['height_cm'])) + (FOOTER_CM if footer else 0)
|
||||
height_pt = float(page_cm) * PT_PER_CM
|
||||
unit = page_unit(width_pt, height_pt)
|
||||
|
||||
first = tempfile.TemporaryFile() if vector else out
|
||||
try:
|
||||
write_rasters(production, sources, first, title, width_pt, height_pt, unit, footer)
|
||||
if vector:
|
||||
first.seek(0)
|
||||
add_vector_pages(production, sources, first, out, height_pt)
|
||||
finally:
|
||||
if vector:
|
||||
first.close()
|
||||
finally:
|
||||
for source in sources:
|
||||
source.close()
|
||||
return {'film_width_cm': str(production['film_width_cm']),
|
||||
'height_cm': str(production['height_cm']),
|
||||
'page_height_cm': str(page_cm),
|
||||
'footer': footer,
|
||||
'billed_metres': str(item['billed_metres']),
|
||||
'placements': len(production['placements']),
|
||||
'sources': len(sources),
|
||||
'vector_sources': len(vector),
|
||||
'min_dpi': round(lowest_dpi) if lowest_dpi else None,
|
||||
'user_unit': unit}
|
||||
|
||||
|
||||
def write_rasters(production, sources, out, title, width_pt, height_pt, unit, footer=None):
|
||||
pdf = PdfWriter(out)
|
||||
images = {index: source.embed(pdf) for index, source in enumerate(sources)
|
||||
if isinstance(source, SourceImage)}
|
||||
# The user-space scale is not wrapped in q/Q, so it also applies to the
|
||||
# vector placements appended by the second pass.
|
||||
commands = [b'%s 0 0 %s 0 0 cm\n' % (serialize(1 / unit), serialize(1 / unit))] if unit > 1 else []
|
||||
for placement in production['placements']:
|
||||
if placement['source_index'] not in images:
|
||||
continue
|
||||
matrix = placement_matrix(placement, height_pt)
|
||||
commands.append(b'q ' + b' '.join(serialize(v) for v in matrix) +
|
||||
b' cm /Im%d Do Q\n' % placement['source_index'])
|
||||
resources = {'XObject': {f'Im{index}': ref for index, ref in images.items()}}
|
||||
if footer:
|
||||
logo = SourceImage(FOOTER_LOGO, 'logo') if os.path.exists(FOOTER_LOGO) else None
|
||||
if logo:
|
||||
resources['XObject']['Logo'] = logo.embed(pdf)
|
||||
logo.close()
|
||||
commands.append(footer_commands(footer, logo.size if logo else None, width_pt))
|
||||
resources['Font'] = {key: {'Type': Name('Font'), 'Subtype': Name('Type1'), 'BaseFont': Name(font),
|
||||
'Encoding': Name('WinAnsiEncoding')} for key, font in FOOTER_FONTS.items()}
|
||||
content = pdf.stream({'Filter': Name('FlateDecode')}, deflate(commands))
|
||||
pages = pdf.alloc()
|
||||
page_box = [0, 0, width_pt / unit, height_pt / unit]
|
||||
page = {'Type': Name('Page'), 'Parent': pages, 'MediaBox': page_box, 'TrimBox': page_box,
|
||||
'Resources': resources, 'Contents': content}
|
||||
if unit > 1:
|
||||
page['UserUnit'] = unit
|
||||
page_ref = pdf.obj(page)
|
||||
pdf.obj({'Type': Name('Pages'), 'Kids': [page_ref], 'Count': 1}, pages)
|
||||
root = pdf.obj({'Type': Name('Catalog'), 'Pages': pages})
|
||||
info = pdf.obj({'Title': title, 'Producer': 'DTF System print-file generator'})
|
||||
pdf.finish(root, info)
|
||||
|
||||
|
||||
def add_vector_pages(production, sources, first, out, height_pt):
|
||||
import pikepdf
|
||||
with pikepdf.open(first) as document:
|
||||
page = document.pages[0]
|
||||
xobjects = page.obj.Resources.XObject
|
||||
for index, source in enumerate(sources):
|
||||
if isinstance(source, PdfPage):
|
||||
xobjects[f'/Pdf{index}'] = source.form(document)
|
||||
commands = []
|
||||
for placement in production['placements']:
|
||||
source = sources[placement['source_index']]
|
||||
if not isinstance(source, PdfPage):
|
||||
continue
|
||||
matrix = multiply(source.normalise(), placement_matrix(placement, height_pt))
|
||||
commands.append(b'q ' + b' '.join(serialize(v) for v in matrix) +
|
||||
b' cm /Pdf%d Do Q\n' % placement['source_index'])
|
||||
page.contents_add(pikepdf.Stream(document, b''.join(commands)), prepend=False)
|
||||
document.save(out, min_version='1.6')
|
||||
209
app/printjobs.py
Normal file
@@ -0,0 +1,209 @@
|
||||
"""Generating print files in the background, one order item at a time.
|
||||
|
||||
A paid order queues one job per item. The worker claims a job, commits the
|
||||
claim, and renders outside any transaction, so a long render never holds a row
|
||||
lock or a database connection. A claim older than CLAIM_TIMEOUT is assumed to
|
||||
belong to a worker that died and is taken again.
|
||||
|
||||
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
|
||||
malware scan, and the bytes are written here. The operator still decides
|
||||
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 os
|
||||
import tempfile
|
||||
import time
|
||||
from datetime import timedelta
|
||||
from decimal import Decimal
|
||||
from zoneinfo import ZoneInfo
|
||||
from uuid import NAMESPACE_URL, UUID, uuid4, uuid5
|
||||
|
||||
from psycopg.types.json import Jsonb
|
||||
|
||||
from .core.auth import audit
|
||||
from .core.db import connect
|
||||
from .printfile import Unsupported, render
|
||||
from .tiny import purchase_order
|
||||
|
||||
LOCAL = ZoneInfo('America/Sao_Paulo')
|
||||
|
||||
CLAIM_TIMEOUT = timedelta(minutes=15)
|
||||
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):
|
||||
return uuid5(NAMESPACE_URL, f'dtf-print-file:{order_id}')
|
||||
|
||||
|
||||
def queue(c, order_id, items, only_missing=False):
|
||||
"""Queue (or re-queue) generation for every item of an order."""
|
||||
for index in range(items):
|
||||
if only_missing:
|
||||
c.execute('''INSERT INTO dtf_local.print_files(id,order_id,item_index) VALUES(%s,%s,%s)
|
||||
ON CONFLICT(order_id,item_index) DO UPDATE SET status='pending', attempts=0,
|
||||
claimed_at=NULL, finished_at=NULL, detail='{}'
|
||||
WHERE dtf_local.print_files.status IN ('failed','manual')''',
|
||||
(uuid4(), order_id, index))
|
||||
else:
|
||||
c.execute('''INSERT INTO dtf_local.print_files(id,order_id,item_index) VALUES(%s,%s,%s)
|
||||
ON CONFLICT(order_id,item_index) DO NOTHING''', (uuid4(), order_id, index))
|
||||
|
||||
|
||||
def claim(c):
|
||||
return c.execute('''SELECT p.*, o.snapshot, o.number, o.created_at AS ordered_at FROM dtf_local.print_files p
|
||||
JOIN dtf_local.orders o ON o.id=p.order_id
|
||||
WHERE p.status='pending' OR (p.status='rendering' AND p.claimed_at < now()-%s)
|
||||
ORDER BY p.created_at FOR UPDATE OF p SKIP LOCKED LIMIT 1''', (CLAIM_TIMEOUT,)).fetchone()
|
||||
|
||||
|
||||
def render_one(storage):
|
||||
with connect() as c:
|
||||
job = claim(c)
|
||||
if not job:
|
||||
return False
|
||||
c.execute('''UPDATE dtf_local.print_files SET status='rendering', claimed_at=now(),
|
||||
attempts=attempts+1 WHERE id=%s''', (job['id'],))
|
||||
item = job['snapshot']['items'][job['item_index']]
|
||||
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)''',
|
||||
([UUID(u) for u in item['uploads']],)).fetchall()
|
||||
# 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)',
|
||||
([UUID(u) for u in item['uploads']],)).fetchone()['e']
|
||||
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:
|
||||
result = produce(storage, job, item, by_id)
|
||||
except Unsupported as reason:
|
||||
finish(job, 'manual', {'reason': str(reason)})
|
||||
audit('print_file_manual', order=str(job['order_id']), item=job['item_index'])
|
||||
return True
|
||||
except Exception as exc:
|
||||
logging.exception('Print file generation failed')
|
||||
final = job['attempts'] + 1 >= MAX_ATTEMPTS
|
||||
finish(job, 'failed' if final else 'pending', {'error': type(exc).__name__})
|
||||
return True
|
||||
path, name, size, detail = result
|
||||
try:
|
||||
uid = uuid4()
|
||||
key = f'originals/{uid}'
|
||||
storage.store(key, path, 'application/pdf')
|
||||
finally:
|
||||
os.unlink(path)
|
||||
with connect() as c:
|
||||
c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,complete,
|
||||
expires_at,scan_state,scan_reason,scanned_at)
|
||||
VALUES(%s,%s,%s,%s,%s,'',true,%s,'clean','generated from scanned artwork',now())''',
|
||||
(uid, generated_identity(job['order_id']), name, size, key, expiry))
|
||||
c.execute('''UPDATE dtf_local.print_files SET status='ready', upload_id=%s, detail=%s,
|
||||
finished_at=now() WHERE id=%s''', (uid, Jsonb(detail), job['id']))
|
||||
audit('print_file_ready', order=str(job['order_id']), item=job['item_index'])
|
||||
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 file_prefix(number, item_index):
|
||||
"""How an order's files are named: DTF-23-item-1, the code the Kanban
|
||||
copies, the footer prints and Tiny keeps (Dropstar, 2026-10-23)."""
|
||||
return f'DTF-{number}-item-{item_index + 1}'
|
||||
|
||||
|
||||
def footer(job, item):
|
||||
"""The print file's footer line: DROPSTAR · Pedido DTF-123 · Item 1/2 ·
|
||||
21/10/2026 · 0,90 m, and · ESPELHADO when the artwork is mirrored. The
|
||||
order is named by its Kanban number, which Tiny keeps; the length is the
|
||||
one billed."""
|
||||
count = len(job['snapshot']['items'])
|
||||
day = job['ordered_at'].astimezone(LOCAL).strftime('%d/%m/%Y')
|
||||
billed = f"{Decimal(str(item['billed_metres'])):.2f}".replace('.', ',')
|
||||
fields = ['DROPSTAR', f'Pedido {purchase_order(job["number"])}',
|
||||
f'Item {job["item_index"] + 1}/{count}', day, f'{billed} m']
|
||||
# A mirrored artwork (UV only) is named on the sheet, for the room to see
|
||||
# before printing (Dropstar, 2026-10-23).
|
||||
if any(source.get('mirrored') for source in item['production']['sources']):
|
||||
fields.append('ESPELHADO')
|
||||
return ' · '.join(fields)
|
||||
|
||||
|
||||
def produce(storage, job, item, uploads):
|
||||
"""Fetch the item's artwork and render it. Returns (pdf path, name, size, evidence)."""
|
||||
for upload_id in item['uploads']:
|
||||
row = uploads.get(upload_id)
|
||||
if not row or row['scan_state'] != 'clean':
|
||||
raise Unsupported('um arquivo original está ausente ou não foi liberado pelo antivírus')
|
||||
if row['purged_at'] or row['expired']:
|
||||
raise Unsupported('um arquivo original passou do prazo de guarda')
|
||||
number = job['number']
|
||||
name = f'{file_prefix(number, job["item_index"])}.pdf'
|
||||
with tempfile.TemporaryDirectory(prefix='print-') as scratch:
|
||||
files = {}
|
||||
for index, upload_id in enumerate(item['uploads']):
|
||||
local = os.path.join(scratch, f'source-{index}')
|
||||
storage.fetch(uploads[upload_id]['object_key'], local)
|
||||
files[index] = (local, uploads[upload_id]['name'])
|
||||
handle, output = tempfile.mkstemp(prefix='print-', suffix='.pdf')
|
||||
try:
|
||||
with os.fdopen(handle, 'wb') as out:
|
||||
detail = render(item, files, out, f'Pedido {number} - item {job["item_index"] + 1}',
|
||||
footer=footer(job, item))
|
||||
except BaseException:
|
||||
os.unlink(output)
|
||||
raise
|
||||
return output, name, os.path.getsize(output), detail
|
||||
|
||||
|
||||
def finish(job, status, detail):
|
||||
with connect() as c:
|
||||
c.execute('''UPDATE dtf_local.print_files SET status=%s, detail=%s,
|
||||
finished_at=CASE WHEN %s='pending' THEN NULL ELSE now() END,
|
||||
claimed_at=NULL WHERE id=%s''', (status, Jsonb(detail), status, job['id']))
|
||||
|
||||
|
||||
def render_loop(storage):
|
||||
while True:
|
||||
try:
|
||||
if render_one(storage):
|
||||
continue
|
||||
except Exception:
|
||||
logging.exception('Print render worker tick failed')
|
||||
time.sleep(2)
|
||||
26
app/proof.py
Normal file
@@ -0,0 +1,26 @@
|
||||
"""The print proof (Dropstar, 2026-10-21).
|
||||
|
||||
An order above 10 m prints a proof before the rest, checked by the print room
|
||||
without stopping the order. Dropstar's rule (2026-10-23): up to 30 cm, from
|
||||
the part with the thinnest lines, a piece of each different artwork, at most
|
||||
three proofs per order, never billed. On an order above 10 m the customer
|
||||
may also ask for a proof at checkout (below 10 m there is none, Dropstar
|
||||
2026-10-28): that order waits for them, marked "Aguardando contato", until
|
||||
they approve the photo sent by WhatsApp. Either way the room
|
||||
marks "Prova OK" once the proof is checked, and without it the order does not
|
||||
reach Finalizado.
|
||||
"""
|
||||
from decimal import Decimal
|
||||
|
||||
PROOF_ABOVE_METRES = Decimal('10')
|
||||
CUSTOMER_NOTE = ('O cliente pediu uma prova antes de imprimir: mande a foto da prova pelo WhatsApp '
|
||||
'e espere o aceite.')
|
||||
|
||||
|
||||
def billed_metres(snapshot):
|
||||
return sum((Decimal(str(item.get('billed_metres') or 0)) for item in snapshot.get('items') or []), Decimal(0))
|
||||
|
||||
|
||||
def needs_proof(snapshot):
|
||||
"""Whether the order prints a proof first: asked for, or above 10 m."""
|
||||
return bool(snapshot.get('proof')) or billed_metres(snapshot) > PROOF_ABOVE_METRES
|
||||
95
app/quote_review.py
Normal file
@@ -0,0 +1,95 @@
|
||||
"""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 prices,
|
||||
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).
|
||||
|
||||
Each product has one price (Dropstar, 2026-10-23): the grade no longer changes
|
||||
what is charged. It is still worked out in the customer's browser and shown
|
||||
with the order, so it is 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 .proof import PROOF_ABOVE_METRES
|
||||
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'
|
||||
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'] or item.residue_accepted != original.get('residue_accepted', 0):
|
||||
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'],
|
||||
'residue_accepted': original.get('residue_accepted', 0)})
|
||||
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'),
|
||||
# The customer's proof only above 10 m (Dropstar, 2026-10-28).
|
||||
**({'proof': True} if draft.get('proof') and metres > PROOF_ABOVE_METRES else {}),
|
||||
'total_cents': sum(i['total_cents'] for i in priced) + quoted_freight['total_cents']}
|
||||
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
|
||||
137
app/receipt.py
Normal file
@@ -0,0 +1,137 @@
|
||||
"""The pickup receipt (Dropstar's third round, item 14, 2026-10-29).
|
||||
|
||||
A PDF for the counter's 80 mm thermal roll: the order number large at the
|
||||
top, the customer and their CPF or CNPJ, each product and its metres, the
|
||||
amount and how it was paid, when it was issued, and blank lines for the
|
||||
date of pickup and the signature. Only for orders picked up in Franca: one
|
||||
sent by a carrier has none. The Kanban's folder saves it in Recibos/, and the
|
||||
counter's print queue sends it to the Bematech.
|
||||
"""
|
||||
import io
|
||||
import unicodedata
|
||||
from datetime import datetime
|
||||
|
||||
from .printfile import Name, PdfWriter, deflate, serialize, _HELVETICA, _HELVETICA_BOLD
|
||||
from .printjobs import LOCAL, file_prefix
|
||||
|
||||
MM = 72 / 25.4
|
||||
WIDTH = 80 * MM
|
||||
MARGIN = 4 * MM
|
||||
ROOM = WIDTH - 2 * MARGIN
|
||||
FONTS = {'F1': 'Helvetica-Bold', 'F2': 'Helvetica'}
|
||||
PRODUCTS = {'file': 'DTF Têxtil · folha montada', 'avulsa': 'DTF Têxtil · artes avulsas',
|
||||
'uvfile': 'DTF UV · folha montada', 'uv': 'DTF UV · artes avulsas'}
|
||||
METHODS = {'pix': 'Pix', 'card': 'Cartão', 'cash': 'Dinheiro', 'credit': 'Crédito do cliente'}
|
||||
# Helvetica's widths for what the tables in printfile.py leave out.
|
||||
EXTRA = {'$': 556, '(': 333, ')': 333, '_': 556, '#': 556, '—': 1000, '@': 1015, '&': 667, '+': 584, "'": 191}
|
||||
|
||||
|
||||
def code(order):
|
||||
"""DTF-123: the order as the Kanban, the files and Tiny name it."""
|
||||
return file_prefix(order['number'], 0).rsplit('-item-', 1)[0]
|
||||
|
||||
|
||||
def is_pickup(snapshot):
|
||||
return ((snapshot or {}).get('freight') or {}).get('service') == 'pickup'
|
||||
|
||||
|
||||
def money(cents):
|
||||
whole, cents = divmod(int(cents), 100)
|
||||
return 'R$ ' + f'{whole:,}'.replace(',', '.') + f',{cents:02d}'
|
||||
|
||||
|
||||
def document(value):
|
||||
digits = ''.join(ch for ch in str(value or '') if ch.isdigit())
|
||||
if len(digits) == 14:
|
||||
return 'CNPJ', f'{digits[:2]}.{digits[2:5]}.{digits[5:8]}/{digits[8:12]}-{digits[12:]}'
|
||||
if len(digits) == 11:
|
||||
return 'CPF', f'{digits[:3]}.{digits[3:6]}.{digits[6:9]}-{digits[9:]}'
|
||||
return 'CPF/CNPJ', str(value or '')
|
||||
|
||||
|
||||
def width(text, bold=False):
|
||||
"""The width of `text` in Helvetica at size 1: an accented letter is as
|
||||
wide as its letter."""
|
||||
table = _HELVETICA_BOLD if bold else _HELVETICA
|
||||
total = 0
|
||||
for ch in text:
|
||||
base = unicodedata.normalize('NFD', ch)[0]
|
||||
total += table.get(ch) or table.get(base) or EXTRA.get(ch) or 600
|
||||
return total / 1000
|
||||
|
||||
|
||||
def wrap(text, size, bold=False):
|
||||
"""The text in lines that fit the roll, broken between words."""
|
||||
lines, line = [], ''
|
||||
for word in str(text).split():
|
||||
attempt = f'{line} {word}' if line else word
|
||||
if line and width(attempt, bold) * size > ROOM:
|
||||
lines.append(line)
|
||||
line = word
|
||||
else:
|
||||
line = attempt
|
||||
return lines + [line] if line else lines or ['']
|
||||
|
||||
|
||||
def literal(text):
|
||||
raw = text.encode('cp1252', 'replace')
|
||||
return b'(' + raw.replace(b'\\', b'\\\\').replace(b'(', b'\\(').replace(b')', b'\\)') + b')'
|
||||
|
||||
|
||||
def lines(order, paid_with, issued):
|
||||
"""What the receipt says, top to bottom: (text, size, bold, space before)."""
|
||||
snapshot = order['snapshot']
|
||||
customer = snapshot.get('customer') or {}
|
||||
kind, number = document(customer.get('cnpj'))
|
||||
name = code(order)
|
||||
# The number as large as the roll takes, up to 34 pt.
|
||||
big = min(34, int(ROOM / width(name, True)))
|
||||
out = [('DROPSTAR · Recibo de retirada', 9, True, 0), (name, big, True, 4)]
|
||||
if paid_with == 'teste':
|
||||
out.append(('PEDIDO DE TESTE', 10, True, 2))
|
||||
out.append(('Cliente', 7.5, False, 10))
|
||||
out += [(part, 10, True, 1) for part in wrap(customer.get('name') or customer.get('mail') or '', 10, True)]
|
||||
out += [(kind, 7.5, False, 6), (number, 10, False, 1)]
|
||||
out.append(('Produto', 7.5, False, 10))
|
||||
for item in snapshot.get('items') or []:
|
||||
metres = str(item.get('billed_metres') or item.get('metres') or '').replace('.', ',')
|
||||
out += [(part, 9.5, False, 2) for part in wrap(f"{PRODUCTS.get(item.get('mode'), item.get('mode'))} — {metres} m", 9.5)]
|
||||
out += [('Valor', 7.5, False, 10), (money(snapshot.get('total_cents') or 0), 12, True, 1),
|
||||
('Pagamento', 7.5, False, 6), (METHODS.get(paid_with, 'Teste' if paid_with == 'teste' else paid_with or '—'), 10, False, 1),
|
||||
(f"Emitido em {issued.astimezone(LOCAL).strftime('%d/%m/%Y %H:%M')}", 8.5, False, 10),
|
||||
('Retirado em ____/____/________', 10, False, 22),
|
||||
('Assinatura ______________________', 10, False, 26)]
|
||||
return out
|
||||
|
||||
|
||||
def render(order, paid_with, issued=None):
|
||||
"""The receipt's PDF bytes, 80 mm wide and as long as what it says."""
|
||||
rows = lines(order, paid_with, issued or datetime.now(LOCAL))
|
||||
height = MARGIN * 2 + sum(size * 1.2 + space for _, size, _, space in rows)
|
||||
y = height - MARGIN
|
||||
commands = [b'0 g\n']
|
||||
for text, size, bold, space in rows:
|
||||
y -= space + size
|
||||
commands.append(b'BT /%s %s Tf %s %s Td %s Tj ET\n' % (b'F1' if bold else b'F2', serialize(size),
|
||||
serialize(MARGIN), serialize(y), literal(text)))
|
||||
y -= size * 0.2
|
||||
out = io.BytesIO()
|
||||
pdf = PdfWriter(out)
|
||||
content = pdf.stream({'Filter': Name('FlateDecode')}, deflate(commands))
|
||||
pages = pdf.alloc()
|
||||
fonts = {key: {'Type': Name('Font'), 'Subtype': Name('Type1'), 'BaseFont': Name(font),
|
||||
'Encoding': Name('WinAnsiEncoding')} for key, font in FONTS.items()}
|
||||
box = [0, 0, WIDTH, height]
|
||||
page = pdf.obj({'Type': Name('Page'), 'Parent': pages, 'MediaBox': box, 'Resources': {'Font': fonts},
|
||||
'Contents': content})
|
||||
pdf.obj({'Type': Name('Pages'), 'Kids': [page], 'Count': 1}, pages)
|
||||
root = pdf.obj({'Type': Name('Catalog'), 'Pages': pages})
|
||||
info = pdf.obj({'Title': f'Recibo {code(order)}',
|
||||
'Producer': 'DTF System'})
|
||||
pdf.finish(root, info)
|
||||
return out.getvalue()
|
||||
|
||||
|
||||
def file_name(order):
|
||||
"""Recibo-DTF-123.pdf"""
|
||||
return f'Recibo-{code(order)}.pdf'
|
||||
148
app/runtime.py
Normal file
@@ -0,0 +1,148 @@
|
||||
"""Composition root, and the pieces every router needs.
|
||||
|
||||
app.py held the adapters, the configuration, the shared query helpers and all
|
||||
nineteen of its routes, so customer.py could not import from it without a cycle
|
||||
and was wired instead by passing nine callables into install_routes. Everything
|
||||
shared lives here: routers import downwards, never from each other.
|
||||
"""
|
||||
import os
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from uuid import uuid5, NAMESPACE_URL
|
||||
|
||||
from fastapi import HTTPException
|
||||
from psycopg.types.json import Jsonb
|
||||
|
||||
from .adapters import FakeFreight, FakePayment, LocalS3Storage, require_runtime
|
||||
from .freight import FreightOptions
|
||||
from .core.secrets import load as load_secret_files
|
||||
|
||||
# Secret files must resolve before any configuration below is read.
|
||||
load_secret_files()
|
||||
require_runtime()
|
||||
|
||||
storage = LocalS3Storage()
|
||||
if os.environ.get('PAYMENT_ADAPTER') == 'mercadopago':
|
||||
from .mercadopago import MercadoPagoPayment
|
||||
payment = MercadoPagoPayment()
|
||||
else:
|
||||
payment = FakePayment()
|
||||
# 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')
|
||||
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_ORIGINS = [origin for origin in os.environ.get('ALLOWED_ORIGINS', PUBLIC_ORIGIN).split(',') if origin]
|
||||
# Per source and generous: a browser needs one session and keeps the cookie, but
|
||||
# offices and mobile carriers put many real customers behind one address, so a
|
||||
# tight per-IP ceiling would lock out the same people the old global one did.
|
||||
GUEST_SESSION_LIMIT = int(os.environ.get('GUEST_SESSION_LIMIT', '240'))
|
||||
# The board returned every order ever created. Finished ones are terminal, so
|
||||
# they were pure growth: at a few hundred a day the response and the page both
|
||||
# degrade with no operator benefit.
|
||||
BOARD_FINISHED_LIMIT = int(os.environ.get('BOARD_FINISHED_LIMIT', '50'))
|
||||
BOARD_QUOTE_LIMIT = int(os.environ.get('BOARD_QUOTE_LIMIT', '100'))
|
||||
PART_BYTES = int(os.environ.get('UPLOAD_PART_BYTES', '8388608'))
|
||||
if not 5242880 <= PART_BYTES <= 67108864:
|
||||
raise RuntimeError('UPLOAD_PART_BYTES must be between 5 and 64 MiB')
|
||||
# Dropstar's flow of 2026-10-23: Arte conferida is the print queue (Fila de
|
||||
# impressão, 'fil', left the board), and Revisão checks the printed sheet
|
||||
# before Finalizado. After a correction the new art goes back through Arte
|
||||
# recebida or Arte conferida; Gestão may also take it straight to Revisão.
|
||||
# Who may make each move is app/core/auth.py's MOVES.
|
||||
STATES = {'rec': 'Arte recebida', 'tra': 'Arte conferida', 'imp': 'Imprimindo',
|
||||
'cor': 'Correção', 'rev': 'Revisão', 'fin': 'Finalizado'}
|
||||
TRANSITIONS = {'rec': ['tra','cor'], 'tra': ['imp','cor'], 'imp': ['rev','cor'],
|
||||
'rev': ['fin','cor'], 'cor': ['rec','tra','rev'], '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', 'imp': 'tra', 'rev': 'imp', 'fin': 'rev'}
|
||||
|
||||
|
||||
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):
|
||||
row = c.execute('SELECT * FROM dtf_local.uploads WHERE id=%s AND owner=%s' +
|
||||
(' FOR UPDATE' if lock else ''), (upload_id, session_id)).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(404, 'Arquivo não encontrado. Escolha o arquivo de novo.')
|
||||
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):
|
||||
raise HTTPException(410, 'Este arquivo expirou. Escolha o arquivo de novo.')
|
||||
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):
|
||||
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()
|
||||
# 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)
|
||||
return {'id': row['id'], 'created_at': row['created_at'],
|
||||
'draft': row['draft'], 'approved': row['approved'],
|
||||
'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}
|
||||
|
||||
|
||||
def enqueue(c, event_key, provider, payload):
|
||||
c.execute('INSERT INTO dtf_local.outbox(event_key,provider,payload) VALUES(%s,%s,%s) ON CONFLICT(event_key) DO NOTHING',
|
||||
(event_key, provider, Jsonb(payload)))
|
||||
|
||||
|
||||
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()
|
||||
if not row: raise HTTPException(404, 'Pedido não encontrado.')
|
||||
return row
|
||||
|
||||
|
||||
def file_rows(c, oid):
|
||||
return c.execute('''SELECT f.id,f.upload_id,f.item_index,f.kind,f.active,f.note,f.created_at,
|
||||
u.name,u.size,u.expires_at,(u.expires_at<=now()) AS expired
|
||||
FROM dtf_local.order_files f JOIN dtf_local.uploads u ON u.id=f.upload_id
|
||||
WHERE order_id=%s ORDER BY f.created_at''', (oid,)).fetchall()
|
||||
|
||||
|
||||
def operator_identity(user):
|
||||
return uuid5(NAMESPACE_URL, 'dtf-local-operator:'+user)
|
||||
160
app/scanning.py
Normal file
@@ -0,0 +1,160 @@
|
||||
"""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 struct
|
||||
import time
|
||||
from fastapi import HTTPException
|
||||
from .core.auth import audit
|
||||
from .core.db import connect
|
||||
from .core.limits import scan_limit_bytes
|
||||
|
||||
def require_clean(row):
|
||||
if not row['complete'] or row['scan_state'] != 'clean':
|
||||
raise HTTPException(409, 'Artwork is quarantined until the malware scan succeeds')
|
||||
|
||||
class ClamAV:
|
||||
def command(self, command, timeout=2):
|
||||
with socket.create_connection(('scanner',3310),timeout=timeout) as sock:
|
||||
sock.settimeout(timeout)
|
||||
sock.sendall(b'z'+command+b'\0')
|
||||
reply=b''
|
||||
while b'\0' not in reply and len(reply)<4096:
|
||||
block=sock.recv(4096)
|
||||
if not block:break
|
||||
reply+=block
|
||||
return reply.rstrip(b'\0\n')
|
||||
|
||||
def ping(self):
|
||||
return self.command(b'PING') == b'PONG'
|
||||
|
||||
def version(self):
|
||||
return self.command(b'VERSION').decode('utf-8','replace')
|
||||
|
||||
def scan(self, stream, size):
|
||||
with socket.create_connection(('scanner',3310),timeout=10) as sock:
|
||||
# A 2 GB file takes minutes to stream and scan.
|
||||
sock.settimeout(900)
|
||||
sock.sendall(b'zINSTREAM\0')
|
||||
sent=0
|
||||
for chunk in stream.iter_chunks(chunk_size=65536):
|
||||
sent+=len(chunk)
|
||||
if sent>size: return 'rejected','Stored file size changed'
|
||||
sock.sendall(struct.pack('!I',len(chunk))+chunk)
|
||||
if sent!=size:return 'rejected','Stored file size changed'
|
||||
sock.sendall(b'\0\0\0\0')
|
||||
reply=b''
|
||||
while b'\0' not in reply and len(reply)<4096:
|
||||
block=sock.recv(4096)
|
||||
if not block:break
|
||||
reply+=block
|
||||
result=reply.rstrip(b'\0\n')
|
||||
if result==b'stream: OK':return 'clean',None
|
||||
if result.endswith(b' FOUND'):return 'rejected','Malware or unsafe scan condition detected'
|
||||
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
|
||||
|
||||
|
||||
# Dropstar's rule D-13 (2026-10-26): the content decides a file's type, never
|
||||
# its extension. A third of their ".cdr" files are PDFs renamed.
|
||||
def detected_format(head):
|
||||
"""The format a file's first bytes show, as an extension, or None."""
|
||||
for ext in ('pdf', 'png', 'jpg', 'tif', 'psd'):
|
||||
if any(head.startswith(sig) for sig in SIGNATURES[ext]):
|
||||
return ext
|
||||
for ext, form in RIFF_FORMS.items():
|
||||
if form.match(head):
|
||||
return ext
|
||||
return None
|
||||
|
||||
|
||||
def real_name(name, head):
|
||||
"""The file's name with the extension of what it really is: a ".cdr" that
|
||||
is a PDF is "x.pdf", a JPG called ".png" is "x.jpg". A name its content
|
||||
agrees with stays, so an Illustrator file, which is a PDF inside, is still
|
||||
".ai" and handled by hand; unknown content keeps the name too."""
|
||||
found = detected_format(head)
|
||||
if not found or format_matches(name, head):
|
||||
return name
|
||||
stem, dot, _ = name.rpartition('.')
|
||||
return (stem if dot else name) + '.' + found
|
||||
|
||||
|
||||
def head_of(storage, row):
|
||||
"""A stored file's first bytes."""
|
||||
return storage.client.get_object(Bucket=storage.bucket, Key=row['object_key'],
|
||||
Range=f'bytes=0-{HEAD_BYTES - 1}')['Body'].read()
|
||||
|
||||
|
||||
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(head, row):
|
||||
"""Release decision for a file above the antivirus limit."""
|
||||
# The content decides (D-13): a ".cdr" that is a PDF is still a PDF.
|
||||
if format_matches(row['name'], head) or detected_format(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):
|
||||
scanner=scanner or ClamAV()
|
||||
with connect() as c:
|
||||
row=c.execute('''SELECT * FROM dtf_local.uploads WHERE complete AND purged_at IS NULL
|
||||
AND expires_at>now() AND scan_state IN ('pending','error') AND scan_after<=now()
|
||||
ORDER BY created_at FOR UPDATE SKIP LOCKED LIMIT 1''').fetchone()
|
||||
if not row:return False
|
||||
name=row['name']
|
||||
try:
|
||||
# Every later decision reads the stored name (the manual charge,
|
||||
# the JPG refusal, the grade, the print file, the folders), so the
|
||||
# name is made to say what the file is (D-13).
|
||||
head=head_of(storage,row)
|
||||
name=real_name(name,head)
|
||||
if row['size'] > scan_limit_bytes():
|
||||
state,reason=check_large(head,row)
|
||||
else:
|
||||
stream=storage.client.get_object(Bucket=storage.bucket,Key=row['object_key'])['Body']
|
||||
try:state,reason=scanner.scan(stream,row['size'])
|
||||
finally:stream.close()
|
||||
except Exception:
|
||||
state,reason='error','Malware scanner unavailable; file remains blocked'
|
||||
c.execute("""UPDATE dtf_local.uploads SET name=%s,scan_state=%s,scan_reason=%s,scanned_at=now(),
|
||||
scan_after=now()+interval '1 minute',
|
||||
expires_at=CASE WHEN %s IN ('rejected','error') THEN LEAST(expires_at,now()+interval '3 days') ELSE expires_at END
|
||||
WHERE id=%s""",(name,state,reason,state,row['id']))
|
||||
audit('artwork_scan', upload=str(row['id']), result=state)
|
||||
return True
|
||||
|
||||
def scan_loop(storage):
|
||||
while True:
|
||||
try:
|
||||
if scan_one(storage):continue
|
||||
except Exception:
|
||||
audit('scanner_worker_error')
|
||||
time.sleep(1)
|
||||
428
app/schema.sql
Normal file
@@ -0,0 +1,428 @@
|
||||
-- Separate schema: never imports/migrates the historical schema.sql or SQLite.
|
||||
CREATE SCHEMA IF NOT EXISTS dtf_local;
|
||||
CREATE TABLE IF NOT EXISTS dtf_local.uploads (
|
||||
id uuid PRIMARY KEY, owner uuid NOT NULL, name text NOT NULL,
|
||||
size bigint NOT NULL, object_key text UNIQUE NOT NULL, multipart_id text NOT NULL,
|
||||
complete boolean NOT NULL DEFAULT false,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS dtf_local.quotes (
|
||||
id uuid PRIMARY KEY, owner uuid NOT NULL, request_key uuid NOT NULL,
|
||||
request_hash text NOT NULL, draft jsonb NOT NULL, approved jsonb,
|
||||
reviewed_by text, approved_at timestamptz,
|
||||
created_at timestamptz NOT NULL DEFAULT now(), UNIQUE(owner, request_key)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS dtf_local.orders (
|
||||
id uuid PRIMARY KEY, number bigint GENERATED ALWAYS AS IDENTITY UNIQUE,
|
||||
quote_id uuid NOT NULL UNIQUE REFERENCES dtf_local.quotes(id), owner uuid NOT NULL,
|
||||
snapshot jsonb NOT NULL, payment jsonb NOT NULL, state text NOT NULL DEFAULT 'rec',
|
||||
version integer NOT NULL DEFAULT 0, created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS dtf_local.movements (
|
||||
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||
order_id uuid NOT NULL REFERENCES dtf_local.orders(id),
|
||||
from_state text NOT NULL, to_state text NOT NULL, operator text NOT NULL,
|
||||
reason text NOT NULL, created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS dtf_local.outbox (
|
||||
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, event_key text NOT NULL UNIQUE,
|
||||
provider text NOT NULL, payload jsonb NOT NULL, attempts integer NOT NULL DEFAULT 0,
|
||||
available_at timestamptz NOT NULL DEFAULT now(), delivered_at timestamptz,
|
||||
last_error text, receipt jsonb
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS dtf_local.accounts (
|
||||
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()
|
||||
);
|
||||
-- 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 (
|
||||
id uuid PRIMARY KEY, owner uuid NOT NULL,
|
||||
expires_at timestamptz NOT NULL DEFAULT now() + interval '7 days'
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS dtf_local.migrations (name text PRIMARY KEY);
|
||||
-- Preserve pre-account guest sessions once, without resurrecting logged-out sessions.
|
||||
DO $$ BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM dtf_local.migrations WHERE name='customer-sessions-v1') THEN
|
||||
INSERT INTO dtf_local.sessions(id,owner)
|
||||
SELECT owner,owner FROM (
|
||||
SELECT owner FROM dtf_local.orders UNION SELECT owner FROM dtf_local.quotes
|
||||
UNION SELECT owner FROM dtf_local.uploads
|
||||
) legacy ON CONFLICT DO NOTHING;
|
||||
INSERT INTO dtf_local.migrations VALUES('customer-sessions-v1');
|
||||
END IF;
|
||||
END $$;
|
||||
CREATE TABLE IF NOT EXISTS dtf_local.login_attempts (
|
||||
key text PRIMARY KEY, attempts integer NOT NULL DEFAULT 0,
|
||||
started_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS dtf_local.operator_sessions (
|
||||
token_hash text PRIMARY KEY, username text NOT NULL,
|
||||
expires_at timestamptz NOT NULL DEFAULT now() + interval '8 hours'
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS dtf_local.operators (
|
||||
id uuid PRIMARY KEY, email text UNIQUE NOT NULL, name text NOT NULL DEFAULT '',
|
||||
password_hash text NOT NULL, active boolean NOT NULL DEFAULT true,
|
||||
created_at timestamptz NOT NULL DEFAULT now(), last_login_at timestamptz
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS dtf_local.payment_events (
|
||||
id uuid PRIMARY KEY, provider text NOT NULL, event_id text NOT NULL,
|
||||
reference text, status text NOT NULL, amount_cents bigint,
|
||||
payload jsonb NOT NULL, received_at timestamptz NOT NULL DEFAULT now(),
|
||||
processed_at timestamptz, outcome text,
|
||||
UNIQUE(provider, event_id)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS dtf_local.security_events (
|
||||
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||
event text NOT NULL, details jsonb NOT NULL, created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
ALTER TABLE dtf_local.uploads ADD COLUMN IF NOT EXISTS expires_at timestamptz;
|
||||
ALTER TABLE dtf_local.uploads ADD COLUMN IF NOT EXISTS purged_at timestamptz;
|
||||
ALTER TABLE dtf_local.uploads ADD COLUMN IF NOT EXISTS scan_state text NOT NULL DEFAULT 'pending';
|
||||
ALTER TABLE dtf_local.uploads ADD COLUMN IF NOT EXISTS scan_reason text;
|
||||
ALTER TABLE dtf_local.uploads ADD COLUMN IF NOT EXISTS scanned_at timestamptz;
|
||||
ALTER TABLE dtf_local.uploads ADD COLUMN IF NOT EXISTS scan_after timestamptz NOT NULL DEFAULT now();
|
||||
UPDATE dtf_local.uploads SET expires_at=created_at + interval '30 days' WHERE expires_at IS NULL;
|
||||
ALTER TABLE dtf_local.uploads ALTER COLUMN expires_at SET DEFAULT now() + interval '30 days';
|
||||
CREATE TABLE IF NOT EXISTS dtf_local.order_files (
|
||||
id uuid PRIMARY KEY, order_id uuid NOT NULL REFERENCES dtf_local.orders(id),
|
||||
upload_id uuid NOT NULL REFERENCES dtf_local.uploads(id), item_index integer NOT NULL,
|
||||
kind text NOT NULL CHECK(kind IN ('final','correction')), active boolean NOT NULL DEFAULT true,
|
||||
note text NOT NULL, created_by text NOT NULL, created_at timestamptz NOT NULL DEFAULT now(),
|
||||
UNIQUE(order_id,upload_id,kind)
|
||||
);
|
||||
-- A payment started at the provider for an approved quote: which provider
|
||||
-- payment belongs to which quote, and its latest known status.
|
||||
CREATE TABLE IF NOT EXISTS dtf_local.payment_intents (
|
||||
id uuid PRIMARY KEY, quote_id uuid NOT NULL REFERENCES dtf_local.quotes(id),
|
||||
provider text NOT NULL, provider_payment_id text NOT NULL, method text NOT NULL,
|
||||
status text NOT NULL, amount_cents bigint NOT NULL, response jsonb NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
UNIQUE(provider, provider_payment_id)
|
||||
);
|
||||
-- OAuth connections to providers (Tiny). One row per provider; the refresh
|
||||
-- token rotates on use, so it lives here, never in configuration.
|
||||
CREATE TABLE IF NOT EXISTS dtf_local.provider_tokens (
|
||||
provider text PRIMARY KEY, access_token text NOT NULL, refresh_token text NOT NULL,
|
||||
access_expires_at timestamptz NOT NULL, refresh_expires_at timestamptz,
|
||||
connected_by text NOT NULL, connected_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
|
||||
-- callback, which arrives cross-site without the operator's cookie.
|
||||
CREATE TABLE IF NOT EXISTS dtf_local.oauth_states (
|
||||
state text PRIMARY KEY, provider text NOT NULL, operator text NOT NULL,
|
||||
expires_at timestamptz NOT NULL
|
||||
);
|
||||
-- The print file generated from each paid item's approved layout. One row per
|
||||
-- item: the worker claims it, renders, and records either the file or why the
|
||||
-- item has to be prepared by hand. Regenerating replaces the row's result.
|
||||
CREATE TABLE IF NOT EXISTS dtf_local.print_files (
|
||||
id uuid PRIMARY KEY, order_id uuid NOT NULL REFERENCES dtf_local.orders(id),
|
||||
item_index integer NOT NULL,
|
||||
status text NOT NULL DEFAULT 'pending'
|
||||
CHECK(status IN ('pending','rendering','ready','manual','failed')),
|
||||
upload_id uuid REFERENCES dtf_local.uploads(id), detail jsonb NOT NULL DEFAULT '{}',
|
||||
attempts integer NOT NULL DEFAULT 0, claimed_at timestamptz,
|
||||
created_at timestamptz NOT NULL DEFAULT now(), finished_at timestamptz,
|
||||
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);
|
||||
|
||||
-- Indexes follow the queries the application actually issues. Only these; every
|
||||
-- extra index is paid for on each write.
|
||||
|
||||
-- The customer portal lists a person's orders and open quotes, newest first.
|
||||
CREATE INDEX IF NOT EXISTS orders_owner ON dtf_local.orders(owner, created_at DESC);
|
||||
CREATE INDEX IF NOT EXISTS quotes_owner ON dtf_local.quotes(owner, created_at DESC);
|
||||
|
||||
-- Order detail and the movement history read by order.
|
||||
CREATE INDEX IF NOT EXISTS movements_order ON dtf_local.movements(order_id, id);
|
||||
CREATE INDEX IF NOT EXISTS order_files_order ON dtf_local.order_files(order_id);
|
||||
-- submit_files checks whether an upload is already attached, by upload.
|
||||
CREATE INDEX IF NOT EXISTS order_files_upload ON dtf_local.order_files(upload_id);
|
||||
|
||||
-- The worker polls this once a second, and the table only grows. Partial, so the
|
||||
-- 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)
|
||||
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.
|
||||
-- now() cannot appear in a partial index predicate, so the time comparisons stay
|
||||
-- in the query and the index narrows to rows still worth looking at.
|
||||
CREATE INDEX IF NOT EXISTS uploads_live ON dtf_local.uploads(created_at)
|
||||
WHERE purged_at IS NULL;
|
||||
|
||||
-- Sign-in transfers and logout delete a person's sessions by owner.
|
||||
CREATE INDEX IF NOT EXISTS sessions_owner ON dtf_local.sessions(owner);
|
||||
|
||||
-- Disabling an operator revokes their open sessions by name.
|
||||
CREATE INDEX IF NOT EXISTS operator_sessions_username ON dtf_local.operator_sessions(username);
|
||||
|
||||
-- security_status reads recent events; the worker prunes old ones by age.
|
||||
CREATE INDEX IF NOT EXISTS security_events_created ON dtf_local.security_events(created_at);
|
||||
|
||||
-- The webhook looks an event up by provider and id on every delivery, and the
|
||||
-- unique constraint already indexes that pair. Only the unprocessed sweep needs
|
||||
-- its own index, and it stays the size of the backlog.
|
||||
CREATE INDEX IF NOT EXISTS payment_events_unprocessed ON dtf_local.payment_events(received_at)
|
||||
WHERE processed_at IS NULL;
|
||||
|
||||
-- The render worker polls for unclaimed or abandoned jobs; the order view reads
|
||||
-- by order through the unique constraint.
|
||||
CREATE INDEX IF NOT EXISTS print_files_open ON dtf_local.print_files(created_at)
|
||||
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
|
||||
-- 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_by text;
|
||||
ALTER TABLE dtf_local.payment_events ADD COLUMN IF NOT EXISTS resolution text;
|
||||
CREATE INDEX IF NOT EXISTS payment_events_open_issues ON dtf_local.payment_events(received_at)
|
||||
WHERE (outcome LIKE 'refused%' OR outcome LIKE 'attention%') AND resolved_at IS NULL;
|
||||
|
||||
-- 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);
|
||||
|
||||
-- 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 print; revisores check
|
||||
-- the printed sheet and are the only ones to release it to Finalizado;
|
||||
-- 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','revisor','vendedor','financeiro'));
|
||||
-- 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'));
|
||||
|
||||
-- The print proof (Dropstar, 2026-10-21): an order above 10 m, or one whose
|
||||
-- customer asked for a proof at checkout, prints 20 cm first; the room marks
|
||||
-- "Prova OK" once it is checked, and without it the order does not reach
|
||||
-- Finalizado.
|
||||
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS proof_ok_at timestamptz;
|
||||
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS proof_ok_by text;
|
||||
|
||||
-- Fila de impressão left the board (Dropstar, 2026-10-23): Arte conferida is
|
||||
-- the queue. An order still in it moves there once, with a line in its history.
|
||||
WITH moved AS (UPDATE dtf_local.orders SET state='tra', version=version+1, updated_at=now()
|
||||
WHERE state='fil' RETURNING id)
|
||||
INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason)
|
||||
SELECT id,'fil','tra','sistema','A Fila de impressão saiu do quadro: Arte conferida é a fila.' FROM moved;
|
||||
|
||||
-- Each time an order waited for a word with the customer ("Aguardando
|
||||
-- contato"): that wait has no deadline and does not count in the time figures
|
||||
-- of Números (Dropstar's rule D-38, 2026-10-26). An open wait has no end. The
|
||||
-- waits already open when this table came are recorded from their start.
|
||||
CREATE TABLE IF NOT EXISTS dtf_local.contact_waits (
|
||||
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||
order_id uuid NOT NULL REFERENCES dtf_local.orders(id) ON DELETE CASCADE,
|
||||
started_at timestamptz NOT NULL, ended_at timestamptz
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS contact_waits_order ON dtf_local.contact_waits(order_id);
|
||||
INSERT INTO dtf_local.contact_waits(order_id, started_at)
|
||||
SELECT o.id, o.contact_since FROM dtf_local.orders o
|
||||
WHERE o.contact_since IS NOT NULL AND NOT EXISTS (SELECT 1 FROM dtf_local.contact_waits w WHERE w.order_id=o.id);
|
||||
|
||||
-- Every card is born with its origin (Dropstar's rules D-21 and D-35,
|
||||
-- 2026-10-26): site, dropflow (the montador's batches) or atendimento (an
|
||||
-- order the team enters). No order without one, and no default: a default
|
||||
-- would become the origin of almost everything, so each way in names its own.
|
||||
-- The orders from before this column all came from the Site.
|
||||
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS origin text;
|
||||
UPDATE dtf_local.orders SET origin='site' WHERE origin IS NULL;
|
||||
ALTER TABLE dtf_local.orders ALTER COLUMN origin SET NOT NULL;
|
||||
ALTER TABLE dtf_local.orders DROP CONSTRAINT IF EXISTS orders_origin_check;
|
||||
ALTER TABLE dtf_local.orders ADD CONSTRAINT orders_origin_check CHECK (origin IN ('site','dropflow','atendimento'));
|
||||
|
||||
-- Rework (Dropstar's rules D-02 to D-04, 2026-10-26; the user's answers of
|
||||
-- 2026-10-27). Gestão opens it with its cause, and the cause never changes
|
||||
-- after (D-03); an Administrador authorizes or declines it, never one they
|
||||
-- opened, and only an authorized rework counts. Bad art the customer approved
|
||||
-- is recorded apart, outside the goal (D-04). printed_by is who sent the
|
||||
-- sheet to Revisão, as the rework enters the printer's pay.
|
||||
CREATE TABLE IF NOT EXISTS dtf_local.reworks (
|
||||
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||
order_id uuid NOT NULL REFERENCES dtf_local.orders(id) ON DELETE CASCADE,
|
||||
cause text NOT NULL CHECK (cause IN ('impressao','perfil_cor','tratamento','pedido','arte_cliente')),
|
||||
metres numeric NOT NULL CHECK (metres > 0),
|
||||
note text NOT NULL DEFAULT '',
|
||||
printed_by text,
|
||||
opened_by text NOT NULL, opened_at timestamptz NOT NULL DEFAULT now(),
|
||||
authorized boolean, decided_by text, decided_at timestamptz, decline_reason text
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS reworks_order ON dtf_local.reworks(order_id);
|
||||
|
||||
-- The pickup receipt (Dropstar's third round, item 14, 2026-10-29): due when
|
||||
-- an order to be picked up reaches Finalizado; one computer's folder claims
|
||||
-- it and saves the PDF in Recibos/, where the counter's print queue sends it
|
||||
-- to the Bematech. Claimed once, so it is never printed twice.
|
||||
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS receipt_due_at timestamptz;
|
||||
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS receipt_saved_at timestamptz;
|
||||
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS receipt_saved_by text;
|
||||
-- "Retirado": when, who handed it over and, optionally, a photo of the
|
||||
-- signed receipt. Finalizado means ready; this means delivered.
|
||||
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS picked_up_at timestamptz;
|
||||
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS picked_up_by text;
|
||||
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS picked_up_photo uuid REFERENCES dtf_local.uploads(id) ON DELETE SET NULL;
|
||||
|
||||
-- The machine a session works on (Dropstar's third round, item 12, 2026-10-30):
|
||||
-- chosen after signing in, per session, so one person may be on two machines,
|
||||
-- one per computer. machine_answered: the question was answered, "Não estou em
|
||||
-- máquina" included. The links Usuários showed before (operator_machines)
|
||||
-- are no longer read.
|
||||
ALTER TABLE dtf_local.operator_sessions ADD COLUMN IF NOT EXISTS machine_id uuid REFERENCES dtf_local.machines(id) ON DELETE SET NULL;
|
||||
ALTER TABLE dtf_local.operator_sessions ADD COLUMN IF NOT EXISTS machine_at timestamptz;
|
||||
ALTER TABLE dtf_local.operator_sessions ADD COLUMN IF NOT EXISTS machine_answered boolean NOT NULL DEFAULT false;
|
||||
-- The machine of whoever moved a card, as it was named then: "Imprimindo ·
|
||||
-- Thales · máquina2".
|
||||
ALTER TABLE dtf_local.movements ADD COLUMN IF NOT EXISTS machine text;
|
||||
799
app/tiny.py
Normal file
@@ -0,0 +1,799 @@
|
||||
"""Tiny/Olist ERP (API v3): create the sales order once a payment is approved.
|
||||
|
||||
Written from the public API documentation and exercised only against a fake
|
||||
HTTP transport. Tiny has no sandbox: the first real test creates a real order
|
||||
in the client's ERP, so test with a marked order and cancel it afterwards.
|
||||
|
||||
Authentication is OAuth2 on Tiny's Keycloak. The client creates an
|
||||
"Aplicativo" in Tiny (Configurações > Geral > Aplicativos), which yields a
|
||||
client ID and secret and registers our callback URL. An operator then clicks
|
||||
"Conectar Tiny" on the Kanban once; the tokens are kept in the database and
|
||||
the refresh token is rotated on every refresh, under a row lock so two
|
||||
workers never spend the same one.
|
||||
|
||||
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
|
||||
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
|
||||
carries numeroOrdemCompra = "DTF-<order number>", and before creating one the
|
||||
customer's recent orders are searched for that number, so a second delivery
|
||||
finds the first order instead of creating another. The same number goes in
|
||||
numeroPedidoEcommerce (Dropstar, 2026-10-23), which n8n reads as
|
||||
numero_ecommerce.
|
||||
|
||||
Customer notices: the client sends WhatsApp messages from Tiny's order
|
||||
situação (Tiny webhook -> their middleware -> n8n), on Aprovado, Pronto para
|
||||
envio, Enviado and Entregue. With TINY_STATUS_UPDATES on, the Kanban moves
|
||||
the Tiny order along with it (Dropstar's flow, 2026-10-23: two changes of
|
||||
situação, none for Imprimindo, Correção or Revisão):
|
||||
|
||||
paid (Arte recebida) -> Aprovada (the "approved" notice)
|
||||
Arte conferida (queue) -> Preparando envio (no notice)
|
||||
Finalizado -> Pronto para envio (pickup or delivery)
|
||||
cancelled -> Cancelada (no notice)
|
||||
|
||||
After Pronto para envio the order goes on in Tiny like any other: Enviada,
|
||||
Entregue.
|
||||
|
||||
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 secrets
|
||||
import time
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from decimal import Decimal
|
||||
from urllib.parse import urlencode
|
||||
|
||||
import httpx
|
||||
|
||||
API = 'https://api.tiny.com.br/public-api/v3'
|
||||
AUTH = 'https://accounts.tiny.com.br/realms/tiny/protocol/openid-connect'
|
||||
# Not TINY_PRODUCT_<MODE>: app/core/secrets.py reads any variable ending in
|
||||
# _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',
|
||||
'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',
|
||||
'avulsa': 'DTF Têxtil 57 cm · artes avulsas',
|
||||
'uvfile': 'DTF UV 27 cm · folha montada',
|
||||
'uv': 'DTF UV 27 cm · artes avulsas'}
|
||||
# How far back to look for an order a previous delivery may already have made.
|
||||
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.
|
||||
# Where the order came from (D-21) and, when the team registered it, how it was
|
||||
# paid outside the system (D-35), for whoever reads the order in Tiny.
|
||||
ORIGIN_NOTES = {'site': 'Site DTF', 'atendimento': 'Atendimento DTF', 'dropflow': 'Dropflow DTF'}
|
||||
OUTSIDE_NOTES = {'pix': 'Pix', 'card': 'cartão', 'cash': 'dinheiro', 'credit': 'crédito do cliente'}
|
||||
|
||||
|
||||
def internal_note(payload):
|
||||
paid = payload.get('payment') or {}
|
||||
how = f"pago fora do site ({OUTSIDE_NOTES.get(paid.get('method'), paid.get('method'))})" if paid.get('outside') else 'pago'
|
||||
return f"{ORIGIN_NOTES.get(payload.get('origin') or 'site')} · {how} · {payload['order_id']}"
|
||||
|
||||
|
||||
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. Dinheiro and, for the customer's
|
||||
# credit, Dropstar's own "CORREÇÃO DTF" were sent by Marcus on 2026-10-27, for
|
||||
# the orders the team registers as paid outside the site (D-35).
|
||||
RECEIPT_METHODS = {'pix': 919478952, 'card': 977460722, 'cash': 919478944, 'credit': 977493654}
|
||||
PICKUP_CARRIER = 761565838
|
||||
# Dropstar's answers: the financial category "DTF SITE" (RECEITAS, id sent on
|
||||
# 2026-10-26; it goes in pagamento.categoria, and replaced the store's
|
||||
# "DUPLICADO DROP", 965775137), no seller (Tiny sets it from the contact,
|
||||
# 2026-10-23), and the marcador SITE DTF, added after the order is created:
|
||||
# POST /pedidos does not take marcadores. Capitals, no accent, no extra
|
||||
# space: the string Kondado reads for Power BI.
|
||||
CATEGORY = 986932924
|
||||
# Dropflow's orders in their own category, "DTF DROPFLOW" (sent 2026-10-27):
|
||||
# the rules document (D-21) keeps the two channels apart in the financial.
|
||||
CATEGORIES = {'dropflow': 987032506}
|
||||
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
|
||||
# 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.
|
||||
BRASILIA = timezone(timedelta(hours=-3))
|
||||
|
||||
|
||||
def local_today():
|
||||
return datetime.now(BRASILIA).date()
|
||||
|
||||
|
||||
class TinyError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class TinyNotConnected(TinyError):
|
||||
"""No authorised connection yet: an operator must click "Conectar Tiny"."""
|
||||
|
||||
|
||||
def purchase_order(number):
|
||||
return f'DTF-{number}'
|
||||
|
||||
|
||||
def configured():
|
||||
"""Whether the OAuth application is configured (orders may still be fake)."""
|
||||
return all(os.environ.get(name) for name in ('TINY_CLIENT_ID', 'TINY_CLIENT_SECRET', 'TINY_REDIRECT_URI'))
|
||||
|
||||
|
||||
def required_settings():
|
||||
"""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 -------------------------------------------------------------------
|
||||
|
||||
class TinyAuth:
|
||||
"""The OAuth application and the stored connection."""
|
||||
|
||||
def __init__(self, connect=None, transport=None, clock=time.time):
|
||||
self.client_id = os.environ.get('TINY_CLIENT_ID', '')
|
||||
self.client_secret = os.environ.get('TINY_CLIENT_SECRET', '')
|
||||
self.redirect_uri = os.environ.get('TINY_REDIRECT_URI', '')
|
||||
if connect is None:
|
||||
from .core.db import connect
|
||||
self.connect = connect
|
||||
self.http = httpx.Client(timeout=20, transport=transport)
|
||||
self.clock = clock
|
||||
|
||||
def authorize_url(self, operator, offline=True):
|
||||
"""Start a connection. The state is single-use, short-lived, and only an
|
||||
authenticated operator can create one, which is what protects the
|
||||
callback: Tiny's redirect back is cross-site, so the operator's
|
||||
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)
|
||||
with self.connect() as c:
|
||||
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)
|
||||
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,
|
||||
'redirect_uri': self.redirect_uri,
|
||||
'scope': 'openid offline_access' if offline else 'openid',
|
||||
'state': state})
|
||||
|
||||
def _claim(self, c, state):
|
||||
row = c.execute('''DELETE FROM dtf_local.oauth_states WHERE state=%s AND provider='tiny'
|
||||
AND expires_at>now() RETURNING operator''', (state,)).fetchone()
|
||||
if not row:
|
||||
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,
|
||||
'redirect_uri': self.redirect_uri})
|
||||
self._store(c, tokens, 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):
|
||||
with self.connect() as c:
|
||||
row = c.execute('''SELECT connected_by,connected_at,refresh_expires_at,updated_at,offline,
|
||||
refresh_failed_at,refused_at FROM dtf_local.provider_tokens WHERE provider='tiny' ''').fetchone()
|
||||
if not row:
|
||||
return {'connected': False}
|
||||
now = datetime.now(timezone.utc)
|
||||
expires = 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):
|
||||
"""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:
|
||||
row = c.execute('''SELECT * FROM dtf_local.provider_tokens WHERE provider='tiny'
|
||||
FOR UPDATE''').fetchone()
|
||||
if not row:
|
||||
raise TinyNotConnected('Tiny is not connected; use "Conectar Tiny" on the Kanban')
|
||||
now = datetime.now(timezone.utc)
|
||||
if row['access_expires_at'] > now + timedelta(seconds=60):
|
||||
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:
|
||||
raise TinyNotConnected('The Tiny connection expired; connect again on the Kanban')
|
||||
try:
|
||||
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)
|
||||
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):
|
||||
response = self.http.post(f'{AUTH}/token', data={**form, 'client_id': self.client_id,
|
||||
'client_secret': self.client_secret})
|
||||
if response.status_code == 400 and form['grant_type'] == 'refresh_token':
|
||||
raise TinyNotConnected('Tiny refused the stored refresh token; connect again on the Kanban')
|
||||
response.raise_for_status()
|
||||
tokens = response.json()
|
||||
if not tokens.get('access_token') or not tokens.get('refresh_token'):
|
||||
raise TinyError('Tiny token response is missing tokens')
|
||||
return tokens
|
||||
|
||||
def _store(self, c, tokens, operator, refreshed=False):
|
||||
now = datetime.now(timezone.utc)
|
||||
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_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,
|
||||
access_expires_at,refresh_expires_at,connected_by,connected_at,updated_at,offline)
|
||||
VALUES('tiny',%s,%s,%s,%s,%s,now(),now(),%s)
|
||||
ON CONFLICT(provider) DO UPDATE SET access_token=EXCLUDED.access_token,
|
||||
refresh_token=EXCLUDED.refresh_token, access_expires_at=EXCLUDED.access_expires_at,
|
||||
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_at=CASE WHEN %s THEN dtf_local.provider_tokens.connected_at ELSE now() END''',
|
||||
(tokens['access_token'], tokens['refresh_token'], access_expires, refresh_expires,
|
||||
operator, offline, refreshed, refreshed))
|
||||
|
||||
|
||||
# Orders ------------------------------------------------------------------
|
||||
|
||||
def money(cents):
|
||||
return float(Decimal(cents) / 100)
|
||||
|
||||
|
||||
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']
|
||||
destination = order.get('destination')
|
||||
company = company or {}
|
||||
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'}
|
||||
if company.get('trade'):
|
||||
contact['fantasia'] = company['trade']
|
||||
if destination:
|
||||
contact['endereco'] = address(destination)
|
||||
return contact
|
||||
|
||||
|
||||
def address(destination):
|
||||
return {'endereco': destination['street'], 'numero': destination['number'],
|
||||
'complemento': destination.get('complement', ''), 'bairro': destination['district'],
|
||||
'municipio': destination['city'], 'cep': destination['postal_code'],
|
||||
'uf': destination['state'], 'pais': 'Brasil'}
|
||||
|
||||
|
||||
def business_days_after(day, days):
|
||||
"""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']
|
||||
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']]
|
||||
product = os.environ.get(setting, '')
|
||||
if not product.isdigit():
|
||||
raise TinyError(f'{setting} must be the Tiny product id')
|
||||
items.append({'produto': {'id': int(product)},
|
||||
'quantidade': float(Decimal(item['billed_metres'])),
|
||||
'valorUnitario': money(item['unit_cents']),
|
||||
'infoAdicional': note})
|
||||
freight = order['freight']
|
||||
service = freight.get('service')
|
||||
pickup = service == 'pickup'
|
||||
day = today or local_today()
|
||||
pedido = {'data': day.isoformat(),
|
||||
'idContato': contact_id,
|
||||
'numeroOrdemCompra': purchase_order(payload['number']),
|
||||
'itens': items,
|
||||
'valorFrete': money(freight['total_cents']),
|
||||
'observacoes': f"Pedido DTF #{payload['number']}" + (' · retirada em Franca' if pickup else ''),
|
||||
'observacoesInternas': internal_note(payload)}
|
||||
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': CATEGORIES.get(payload.get('origin'), 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')
|
||||
if destination:
|
||||
pedido['enderecoEntrega'] = {**address(destination), 'enderecoNro': destination['number'],
|
||||
'nomeDestinatario': destination['recipient']}
|
||||
del pedido['enderecoEntrega']['numero']
|
||||
# The channel id is optional in Tiny's v3 model; TINY_ECOMMERCE_ID adds it.
|
||||
pedido['ecommerce'] = {'numeroPedidoEcommerce': purchase_order(payload['number'])}
|
||||
ecommerce = os.environ.get('TINY_ECOMMERCE_ID', '')
|
||||
if ecommerce.isdigit():
|
||||
pedido['ecommerce']['id'] = int(ecommerce)
|
||||
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:
|
||||
def __init__(self, auth=None, transport=None, today=None, names=None):
|
||||
missing = [name for name in required_settings() if not os.environ.get(name)]
|
||||
if auth is None and missing:
|
||||
raise RuntimeError('Tiny needs ' + ', '.join(missing))
|
||||
self.auth = auth or TinyAuth()
|
||||
self.http = httpx.Client(base_url=API, transport=transport, timeout=30)
|
||||
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):
|
||||
headers = {'Authorization': f'Bearer {self.auth.access_token()}'}
|
||||
response = self.http.request(method, path, headers=headers, **kwargs)
|
||||
if response.status_code == 429:
|
||||
raise TinyError('Tiny rate limit reached; the outbox will retry')
|
||||
if response.status_code >= 400:
|
||||
raise TinyError(f'{method} {path}: {response.status_code} {response.text[:300]}')
|
||||
return response.json() if response.content else {}
|
||||
|
||||
def shipping(self, service):
|
||||
"""The forma de envio and de frete of a service, looked up once."""
|
||||
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 []:
|
||||
if ''.join(ch for ch in str(entry.get('cpfCnpj') or '') if ch.isdigit()) == cnpj:
|
||||
return entry['id']
|
||||
return None
|
||||
|
||||
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."""
|
||||
wanted = purchase_order(payload['number'])
|
||||
since = ((self.today or local_today()) - timedelta(days=days)).isoformat()
|
||||
seen = set()
|
||||
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 []:
|
||||
if entry['id'] in seen:
|
||||
continue
|
||||
seen.add(entry['id'])
|
||||
detail = self.request('GET', f"/pedidos/{entry['id']}")
|
||||
if detail.get('numeroOrdemCompra') == wanted:
|
||||
return detail
|
||||
return None
|
||||
|
||||
def tag(self, tiny_id, known=False):
|
||||
"""The SITE DTF marcador on the order, once. A retry that finds the
|
||||
order already created checks first, since POST adds another."""
|
||||
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):
|
||||
event = payload.get('event')
|
||||
if event == 'payment_approved':
|
||||
return self.sale(event_key, payload)
|
||||
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)
|
||||
if existing:
|
||||
receipt = {'provider': 'tiny', 'event_key': event_key, 'status': 'already-created',
|
||||
'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'])
|
||||
created = self.request('POST', '/pedidos', json=order_payload(
|
||||
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, 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):
|
||||
"""The order reached Finalizado: "Pronto para envio", for pickup and
|
||||
delivery alike (Dropstar, 2026-10-23). From there the team ships it in
|
||||
Tiny as any other order."""
|
||||
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]}
|
||||
386
app/tiny_probe.py
Normal file
@@ -0,0 +1,386 @@
|
||||
"""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
|
||||
python -m app.tiny_probe usuarios the account's users and their type, and which one the
|
||||
integration is connected as (read-only; needs the app's
|
||||
Usuários (Leitura) and a reconnect)
|
||||
python -m app.tiny_probe diagnostico --cpf ... --email ... --celular ...
|
||||
when Tiny refuses the order: sends it again without one
|
||||
part at a time, stops at the first it accepts (cancelled)
|
||||
|
||||
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 base64
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
from datetime import datetime
|
||||
from decimal import Decimal, InvalidOperation
|
||||
|
||||
from .core.pricing import PRICES
|
||||
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 = PRICES[mode]
|
||||
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
|
||||
# What Tiny kept of the e-commerce number, read back from the order.
|
||||
wanted = tiny.purchase_order(payload['number'])
|
||||
shop = orders.request('GET', f"/pedidos/{first['tiny_id']}").get('ecommerce') or {}
|
||||
out(f"E-commerce no Tiny: numeroPedidoEcommerce {shop.get('numeroPedidoEcommerce') or '(vazio)'}" +
|
||||
(f" · canal {shop.get('nome') or '?'} (id {shop['id']})" if shop.get('id') else ' · sem canal'))
|
||||
numbered = shop.get('numeroPedidoEcommerce') == wanted
|
||||
if not numbered:
|
||||
out(f'FALHA: o Tiny não guardou {wanted} em numeroPedidoEcommerce.')
|
||||
second = orders.deliver('teste-integracao', payload)
|
||||
out(f"2º envio: {second['status']} · Tiny id {second['tiny_id']}")
|
||||
found_again = second['status'] == 'already-created' and second['tiny_id'] == first['tiny_id']
|
||||
out('OK: o reenvio encontrou o mesmo pedido.' if found_again else 'FALHA: o reenvio não devolveu o mesmo pedido.')
|
||||
return numbered and found_again
|
||||
finally:
|
||||
# Whatever happened above, the test order does not stay open.
|
||||
cancelar(orders, first['tiny_id'], out)
|
||||
|
||||
|
||||
def connected_as(orders):
|
||||
"""Who logged in when the integration was connected: the name and e-mail
|
||||
in the access token's claims (an OpenID token), never the token itself."""
|
||||
try:
|
||||
part = orders.auth.access_token().split('.')[1]
|
||||
claims = json.loads(base64.urlsafe_b64decode(part + '=' * (-len(part) % 4)))
|
||||
except Exception:
|
||||
return {}
|
||||
return {key: claims[key] for key in ('name', 'email', 'preferred_username') if claims.get(key)}
|
||||
|
||||
|
||||
def usuarios(orders, out):
|
||||
"""The account's users, with their type, and the one the integration
|
||||
acts as: the API does what that user may do (read-only)."""
|
||||
me = connected_as(orders)
|
||||
if me:
|
||||
out('Integração conectada como: ' + ' · '.join(str(v) for v in me.values()))
|
||||
try:
|
||||
found = orders.request('GET', '/usuarios', params={'limit': 100}).get('itens') or []
|
||||
except tiny.TinyError as exc:
|
||||
if ': 403 ' in str(exc) or ': 401 ' in str(exc):
|
||||
out(f'Tiny recusou a lista de usuários ({exc}). Marque Usuários (Leitura) nas permissões do '
|
||||
'aplicativo e conecte o Tiny de novo no Kanban (Integrações).')
|
||||
return False
|
||||
raise
|
||||
ours = {str(v).lower() for v in me.values()}
|
||||
for user in found:
|
||||
mine = str(user.get('email') or '').lower() in ours or str(user.get('emailComunicacao') or '').lower() in ours
|
||||
out(f"{user.get('id')}\t{user.get('tipo') or '-'}\t{user.get('nome')}\t{user.get('email')}"
|
||||
+ ('\t<- integração' if mine else ''))
|
||||
out(f'{len(found)} usuário(s).')
|
||||
return True
|
||||
|
||||
|
||||
def diagnostico(orders, payload, out):
|
||||
"""Which part of the order Tiny refuses, when it says only 403. The same
|
||||
test order is sent whole, then without one part at a time, then with only
|
||||
what an order cannot go without; the first version Tiny accepts names the
|
||||
part, and that order is cancelled at once. The contact must exist already:
|
||||
this never creates one."""
|
||||
cnpj = payload['order']['customer']['cnpj']
|
||||
known = orders.find_contact(cnpj)
|
||||
if not known:
|
||||
out(f'Contato {tiny.punctuated(cnpj)} não existe no Tiny; use o CPF de um contato que já existe.')
|
||||
return False
|
||||
out(f'Contato {tiny.punctuated(cnpj)}: já existe no Tiny (id {known})')
|
||||
full = tiny.order_payload(payload, known, product_id=orders.product_id, shipping=orders.shipping)
|
||||
without = lambda key: {k: v for k, v in full.items() if k != key}
|
||||
versions = [('completo', full)] + [(f'sem {key}', without(key)) for key in
|
||||
('ecommerce', 'pagamento', 'transportador', 'dataPrevista')
|
||||
if key in full]
|
||||
versions.append(('só o essencial (data, contato, itens, nº de compra)',
|
||||
{k: full[k] for k in ('data', 'idContato', 'numeroOrdemCompra', 'itens')}))
|
||||
for name, body in versions:
|
||||
try:
|
||||
created = orders.request('POST', '/pedidos', json=body)
|
||||
except tiny.TinyError as exc:
|
||||
out(f'{name}: recusado ({exc})')
|
||||
continue
|
||||
out(f"{name}: ACEITO (Tiny id {created.get('id')}). O que falta no completo é o que foi tirado aqui.")
|
||||
cancelar(orders, created.get('id'), out)
|
||||
return True
|
||||
out('Todas as versões foram recusadas, até a essencial: não é o conteúdo do pedido, é a permissão '
|
||||
'do usuário do Tiny para incluir pedidos de venda.')
|
||||
return False
|
||||
|
||||
|
||||
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')
|
||||
commands.add_parser('usuarios')
|
||||
probe = commands.add_parser('diagnostico')
|
||||
probe.add_argument('--cnpj', '--cpf', dest='cnpj', required=True, help='CNPJ ou CPF de um contato que já existe')
|
||||
probe.add_argument('--email', required=True)
|
||||
probe.add_argument('--celular', required=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
|
||||
if args.command == 'usuarios':
|
||||
return 0 if usuarios(orders, 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
|
||||
if args.command == 'diagnostico':
|
||||
return 0 if diagnostico(orders, test_order(cnpj, args.email, args.celular, 'file'), out) else 1
|
||||
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())
|
||||
@@ -1,22 +1,35 @@
|
||||
"""Transactional outbox worker. Fake receipts persist; no messages leave the stack."""
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from http.server import BaseHTTPRequestHandler, HTTPServer
|
||||
from psycopg.types.json import Jsonb
|
||||
from .adapters import FakeTiny, FakeWhatsApp, LocalS3Storage, require_runtime
|
||||
from .secrets import load as load_secret_files
|
||||
from .db import connect
|
||||
from . import mail
|
||||
from .adapters import FakeTiny, LocalS3Storage, require_runtime
|
||||
from .core.secrets import load as load_secret_files
|
||||
from .core.db import connect
|
||||
from .printjobs import render_loop
|
||||
from .scanning import ClamAV, scan_loop
|
||||
|
||||
load_secret_files()
|
||||
require_runtime()
|
||||
adapters = {'tiny': FakeTiny(), 'whatsapp': FakeWhatsApp()}
|
||||
adapters = {'tiny': FakeTiny()}
|
||||
# Not yet confirmed against the client's account; see app/tiny.py.
|
||||
if os.environ.get('TINY_ADAPTER') == 'tiny':
|
||||
from .tiny import TinyOrders
|
||||
from .cnpj import company
|
||||
adapters['tiny'] = TinyOrders(names=company)
|
||||
last_tick = 0.0
|
||||
last_cleanup = 0.0
|
||||
last_reconcile = 0.0
|
||||
last_names = 0.0
|
||||
names_thread = None
|
||||
last_tiny_keepalive = 0.0
|
||||
storage = LocalS3Storage()
|
||||
scan_thread = None
|
||||
render_thread = None
|
||||
|
||||
def cleanup():
|
||||
"""Delete only expired object bytes; retain order/file metadata and history."""
|
||||
@@ -27,7 +40,11 @@ def cleanup():
|
||||
for row in rows:
|
||||
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('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.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.login_attempts WHERE started_at<now()-interval '1 day'")
|
||||
c.execute("DELETE FROM dtf_local.security_events WHERE created_at<now()-interval '30 days'")
|
||||
@@ -45,6 +62,55 @@ def tick():
|
||||
c.execute("UPDATE dtf_local.outbox SET attempts=attempts+1, last_error=%s, available_at=now() + %s * interval '1 second' WHERE id=%s", (str(exc),delay,job['id']))
|
||||
last_tick = time.monotonic()
|
||||
|
||||
def tiny_keepalive():
|
||||
"""Keep a connected Tiny authorised even while no orders are sent.
|
||||
|
||||
The refresh token expires unless it is used; access_token() refreshes (and
|
||||
rotates) only when the access token is about to expire, so asking every few
|
||||
minutes renews the connection roughly once per access-token lifetime.
|
||||
"""
|
||||
global last_tiny_keepalive
|
||||
if time.monotonic()-last_tiny_keepalive < 600:
|
||||
return
|
||||
last_tiny_keepalive = time.monotonic()
|
||||
from . import tiny
|
||||
if not tiny.configured():
|
||||
return
|
||||
try:
|
||||
tiny.TinyAuth().access_token()
|
||||
except tiny.TinyNotConnected:
|
||||
pass
|
||||
except Exception:
|
||||
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():
|
||||
global last_cleanup
|
||||
while True:
|
||||
@@ -53,6 +119,10 @@ def loop():
|
||||
if time.monotonic()-last_cleanup > 60:
|
||||
cleanup()
|
||||
last_cleanup = time.monotonic()
|
||||
mail.send_pending(connect)
|
||||
tiny_keepalive()
|
||||
reconcile_payments()
|
||||
resolve_names()
|
||||
except Exception:
|
||||
logging.exception('Local worker tick failed')
|
||||
time.sleep(1)
|
||||
@@ -64,16 +134,20 @@ class Health(BaseHTTPRequestHandler):
|
||||
scanner = bool(scan_thread and scan_thread.is_alive() and ClamAV().ping())
|
||||
except Exception:
|
||||
pass
|
||||
healthy = time.monotonic()-last_tick < 15 and scanner
|
||||
renderer = bool(render_thread and render_thread.is_alive())
|
||||
healthy = time.monotonic()-last_tick < 15 and scanner and renderer
|
||||
self.send_response(200 if self.path == '/health' and healthy else 503)
|
||||
self.end_headers()
|
||||
self.wfile.write(json.dumps({'worker': 'ok' if healthy else 'unavailable',
|
||||
'scanner': 'ok' if scanner else 'unavailable'}).encode())
|
||||
'scanner': 'ok' if scanner else 'unavailable',
|
||||
'print_files': 'ok' if renderer else 'unavailable'}).encode())
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
if __name__ == '__main__':
|
||||
scan_thread = threading.Thread(target=scan_loop,args=(storage,),daemon=True)
|
||||
scan_thread.start()
|
||||
render_thread = threading.Thread(target=render_loop,args=(storage,),daemon=True)
|
||||
render_thread.start()
|
||||
threading.Thread(target=loop, daemon=True).start()
|
||||
HTTPServer(('0.0.0.0',8002),Health).serve_forever()
|
||||
@@ -9,12 +9,12 @@
|
||||
x-app: &app
|
||||
build:
|
||||
context: .
|
||||
dockerfile: local/Dockerfile
|
||||
dockerfile: infra/Dockerfile
|
||||
environment: &environment
|
||||
APP_ENV: local
|
||||
DATABASE_URL: postgresql://${APP_DB_USER:-dtf_app}:${APP_DB_PASSWORD:-local-app-database-only}@db:5432/${POSTGRES_DB:-dtf_local}
|
||||
S3_ENDPOINT: http://storage:9000
|
||||
S3_PUBLIC_ENDPOINT: ${S3_PUBLIC_ENDPOINT:-http://localhost:9000}
|
||||
S3_PUBLIC_ENDPOINT: ${S3_PUBLIC_ENDPOINT:-http://localhost:${STORAGE_PORT:-9000}}
|
||||
S3_BUCKET: ${S3_BUCKET:-dtf-local-artwork}
|
||||
AWS_ACCESS_KEY_ID: ${S3_APP_USER:-dtf_app}
|
||||
AWS_SECRET_ACCESS_KEY: ${S3_APP_PASSWORD:-local-app-storage-only}
|
||||
@@ -23,22 +23,80 @@ x-app: &app
|
||||
OPERATOR_PASSWORD: ${OPERATOR_PASSWORD:-local-operator-only}
|
||||
# The browser reaches the API through the Site gateway, so the published
|
||||
# Site/Kanban origins must be accepted or every write is rejected 403.
|
||||
PUBLIC_ORIGIN: http://localhost:${SITE_PORT:-8080}
|
||||
ALLOWED_HOSTS: localhost,127.0.0.1
|
||||
ALLOWED_ORIGINS: http://localhost:${SITE_PORT:-8080},http://localhost:${KANBAN_PORT:-8081},http://127.0.0.1:${SITE_PORT:-8080},http://127.0.0.1:${KANBAN_PORT:-8081}
|
||||
PUBLIC_ORIGIN: ${PUBLIC_ORIGIN:-http://localhost:${SITE_PORT:-8080}}
|
||||
ALLOWED_HOSTS: ${ALLOWED_HOSTS:-localhost,127.0.0.1}
|
||||
ALLOWED_ORIGINS: ${ALLOWED_ORIGINS:-http://localhost:${SITE_PORT:-8080},http://localhost:${KANBAN_PORT:-8081},http://127.0.0.1:${SITE_PORT:-8080},http://127.0.0.1:${KANBAN_PORT:-8081}}
|
||||
COOKIE_SECURE: "false"
|
||||
PAYMENT_ADAPTER: fake
|
||||
FREIGHT_ADAPTER: fake
|
||||
TINY_ADAPTER: fake
|
||||
WHATSAPP_ADAPTER: fake
|
||||
# Sandbox testing only: set PAYMENT_ADAPTER=mercadopago with the MP_* test
|
||||
# credentials, or TINY_ADAPTER=tiny with a TINY_TOKEN, in .env. Never real
|
||||
# production credentials on a developer machine.
|
||||
PAYMENT_ADAPTER: ${PAYMENT_ADAPTER:-fake}
|
||||
PAYMENT_WEBHOOK_SECRET: ${PAYMENT_WEBHOOK_SECRET:-local-webhook-secret}
|
||||
MP_ACCESS_TOKEN: ${MP_ACCESS_TOKEN:-}
|
||||
MP_WEBHOOK_SECRET: ${MP_WEBHOOK_SECRET:-}
|
||||
MP_NOTIFICATION_URL: ${MP_NOTIFICATION_URL:-}
|
||||
MP_PUBLIC_KEY: ${MP_PUBLIC_KEY:-}
|
||||
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_CLIENT_ID: ${TINY_CLIENT_ID:-}
|
||||
TINY_CLIENT_SECRET: ${TINY_CLIENT_SECRET:-}
|
||||
TINY_REDIRECT_URI: ${TINY_REDIRECT_URI:-}
|
||||
TINY_PRODUCT_TEXTIL_FOLHA: ${TINY_PRODUCT_TEXTIL_FOLHA:-}
|
||||
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: ${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:-}
|
||||
# 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
|
||||
MOCK_FREIGHT_CENTS: ${MOCK_FREIGHT_CENTS:-1500}
|
||||
MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-5368709120}
|
||||
MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-4294967296}
|
||||
UPLOAD_PART_BYTES: ${UPLOAD_PART_BYTES:-8388608}
|
||||
STORAGE_QUOTA_BYTES: ${STORAGE_QUOTA_BYTES:-53687091200}
|
||||
OWNER_UPLOAD_QUOTA_BYTES: ${OWNER_UPLOAD_QUOTA_BYTES:-10737418240}
|
||||
MAX_PENDING_UPLOADS: ${MAX_PENDING_UPLOADS:-10}
|
||||
SCAN_MAX_BYTES: ${SCAN_MAX_BYTES:-134217728}
|
||||
SCAN_MAX_BYTES: ${SCAN_MAX_BYTES:-2097152000}
|
||||
networks: [local]
|
||||
init: true
|
||||
security_opt: [no-new-privileges:true]
|
||||
@@ -65,16 +123,21 @@ services:
|
||||
retries: 30
|
||||
|
||||
storage:
|
||||
# quay.io, not Docker Hub: minio/minio there now answers anonymous pulls
|
||||
# with 401 authentication required, which breaks any runner that is not
|
||||
# logged in. Same image — identical image ID. Override MINIO_IMAGE to use
|
||||
# a mirror of your own.
|
||||
image: ${MINIO_IMAGE:-quay.io/minio/minio:RELEASE.2025-04-22T22-12-26Z}
|
||||
# MinIO stopped publishing public images: since September 2026 both
|
||||
# Docker Hub (minio/minio) and quay.io answer anonymous pulls with 401,
|
||||
# which breaks any machine or runner without a cached copy. Chainguard's
|
||||
# build still pulls anonymously, ships sh and mc (the healthcheck and
|
||||
# storage-init need both) and runs as a non-root user. Pinned by digest
|
||||
# because Chainguard's free tier only publishes :latest. Override
|
||||
# MINIO_IMAGE to use a mirror of your own.
|
||||
image: ${MINIO_IMAGE:-cgr.dev/chainguard/minio@sha256:bd014394a80898e68c149f2311fdf8d5a2c2f3bb2c33b9327ae6d02b4b065ae1}
|
||||
command: server /data --console-address :9001
|
||||
environment:
|
||||
MINIO_ROOT_USER: ${MINIO_ROOT_USER:-dtf_local}
|
||||
MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD:-local-storage-only}
|
||||
ports: ["127.0.0.1:9000:9000", "127.0.0.1:9001:9001"]
|
||||
ports:
|
||||
- "127.0.0.1:${STORAGE_PORT:-9000}:9000"
|
||||
- "127.0.0.1:${STORAGE_CONSOLE_PORT:-9001}:9001"
|
||||
volumes: [storage-data:/data]
|
||||
networks: [local, edge]
|
||||
healthcheck:
|
||||
@@ -86,20 +149,30 @@ services:
|
||||
db-init:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: local/Dockerfile
|
||||
command: python -m local.bootstrap
|
||||
dockerfile: infra/Dockerfile
|
||||
command: python -m app.bootstrap
|
||||
environment:
|
||||
# Local only: the app role keeps a password distinct from the administrator.
|
||||
DATABASE_ADMIN_URL: postgresql://${POSTGRES_USER:-dtf_local}:${POSTGRES_PASSWORD:-local-database-only}@db:5432/${POSTGRES_DB:-dtf_local}
|
||||
APP_DB_USER: ${APP_DB_USER:-dtf_app}
|
||||
APP_DB_PASSWORD: ${APP_DB_PASSWORD:-local-app-database-only}
|
||||
# The migration job seeds the first operator account from these, so an
|
||||
# existing deployment keeps its Kanban login after the accounts table
|
||||
# lands. Without them there would be no account at all and login would
|
||||
# fail closed with 503.
|
||||
OPERATOR_EMAIL: ${OPERATOR_EMAIL:-operator@example.test}
|
||||
OPERATOR_PASSWORD: ${OPERATOR_PASSWORD:-local-operator-only}
|
||||
networks: [local]
|
||||
depends_on:
|
||||
db: {condition: service_healthy}
|
||||
restart: on-failure
|
||||
|
||||
storage-init:
|
||||
image: ${MINIO_IMAGE:-quay.io/minio/minio:RELEASE.2025-04-22T22-12-26Z}
|
||||
build:
|
||||
context: .
|
||||
dockerfile: infra/Dockerfile.storage-init
|
||||
args:
|
||||
MINIO_IMAGE: ${MINIO_IMAGE:-cgr.dev/chainguard/minio@sha256:bd014394a80898e68c149f2311fdf8d5a2c2f3bb2c33b9327ae6d02b4b065ae1}
|
||||
entrypoint: [/bin/sh, /init.sh]
|
||||
environment:
|
||||
MINIO_ROOT_USER: ${MINIO_ROOT_USER:-dtf_local}
|
||||
@@ -107,19 +180,22 @@ services:
|
||||
S3_APP_USER: ${S3_APP_USER:-dtf_app}
|
||||
S3_APP_PASSWORD: ${S3_APP_PASSWORD:-local-app-storage-only}
|
||||
S3_BUCKET: ${S3_BUCKET:-dtf-local-artwork}
|
||||
volumes:
|
||||
- ./local/storage-init.sh:/init.sh:ro
|
||||
- ./local/storage-policy.json:/policy.json:ro
|
||||
- ./local/storage-lifecycle.json:/lifecycle.json:ro
|
||||
S3_BACKUP_BUCKET: dtf-local-backups
|
||||
S3_BACKUP_USER: dtf_backup
|
||||
S3_BACKUP_PASSWORD: local-backup-storage-only
|
||||
networks: [local]
|
||||
depends_on:
|
||||
storage: {condition: service_healthy}
|
||||
restart: on-failure
|
||||
|
||||
scanner:
|
||||
image: clamav/clamav@sha256:9cb27d7660bdf66e9878c832cb433dd8aa152cfbe16f3c2c0084c80b04ae22b4
|
||||
# Built, not bind-mounted: see local/Dockerfile.scanner.
|
||||
build:
|
||||
context: .
|
||||
dockerfile: infra/Dockerfile.scanner
|
||||
args:
|
||||
CLAMAV_IMAGE: ${CLAMAV_IMAGE:-clamav/clamav@sha256:9cb27d7660bdf66e9878c832cb433dd8aa152cfbe16f3c2c0084c80b04ae22b4}
|
||||
entrypoint: [clamd, --foreground=true, --config-file=/etc/clamav/clamd.conf]
|
||||
volumes: [./local/clamd.conf:/etc/clamav/clamd.conf:ro]
|
||||
networks: [local]
|
||||
security_opt: [no-new-privileges:true]
|
||||
healthcheck:
|
||||
@@ -134,7 +210,7 @@ services:
|
||||
|
||||
api:
|
||||
<<: *app
|
||||
command: uvicorn local.app:app --host 0.0.0.0 --port 8000 --no-access-log
|
||||
command: uvicorn app.app:app --host 0.0.0.0 --port 8000 --no-access-log
|
||||
depends_on:
|
||||
db-init: {condition: service_completed_successfully}
|
||||
storage-init: {condition: service_completed_successfully}
|
||||
@@ -146,7 +222,7 @@ services:
|
||||
|
||||
worker:
|
||||
<<: *app
|
||||
command: python -m local.worker
|
||||
command: python -m app.worker
|
||||
depends_on:
|
||||
api: {condition: service_healthy}
|
||||
scanner: {condition: service_healthy}
|
||||
@@ -156,14 +232,43 @@ services:
|
||||
timeout: 3s
|
||||
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:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: local/Dockerfile.web
|
||||
dockerfile: infra/Dockerfile.web
|
||||
environment:
|
||||
S3_PUBLIC_ENDPOINT: ${S3_PUBLIC_ENDPOINT:-http://localhost: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.
|
||||
PAYMENT_CSP_SOURCES: ${PAYMENT_CSP_SOURCES:-}
|
||||
PAYMENT_CHALLENGE_SOURCES: ${PAYMENT_CHALLENGE_SOURCES:-}
|
||||
ports:
|
||||
# Published ports are host-wide even bound to loopback, so on a shared
|
||||
# machine any of them can collide with something unrelated. CI overrides
|
||||
# every one; see .gitea/workflows/deploy.yml.
|
||||
- "127.0.0.1:${SITE_PORT:-8080}:80"
|
||||
# Convenience only: the API through its own gateway. No test uses it.
|
||||
- "127.0.0.1:${API_PORT:-8000}:81"
|
||||
networks: [local, edge]
|
||||
depends_on:
|
||||
@@ -177,10 +282,12 @@ services:
|
||||
kanban:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: local/Dockerfile.web
|
||||
dockerfile: infra/Dockerfile.web
|
||||
environment:
|
||||
WEB_INDEX: kanban.html
|
||||
S3_PUBLIC_ENDPOINT: ${S3_PUBLIC_ENDPOINT:-http://localhost:9000}
|
||||
S3_PUBLIC_ENDPOINT: ${S3_PUBLIC_ENDPOINT:-http://localhost:${STORAGE_PORT:-9000}}
|
||||
PAYMENT_CSP_SOURCES: ""
|
||||
PAYMENT_CHALLENGE_SOURCES: ""
|
||||
ports: ["127.0.0.1:${KANBAN_PORT:-8081}:80"]
|
||||
networks: [local, edge]
|
||||
depends_on:
|
||||
@@ -191,6 +298,28 @@ services:
|
||||
timeout: 3s
|
||||
retries: 12
|
||||
|
||||
browser-tests:
|
||||
profiles: [ci]
|
||||
build:
|
||||
context: .
|
||||
dockerfile: infra/Dockerfile.browser-tests
|
||||
environment:
|
||||
CHROME_BIN: /usr/bin/chromium
|
||||
CHROME_NO_SANDBOX: "1"
|
||||
CHROME_TRUST_TEST_ORIGINS: "1"
|
||||
SITE_BROWSER_ORIGIN: http://site
|
||||
KANBAN_BROWSER_ORIGIN: http://kanban
|
||||
OPERATOR_EMAIL: ${OPERATOR_EMAIL:-operator@example.test}
|
||||
OPERATOR_PASSWORD: ${OPERATOR_PASSWORD:-local-operator-only}
|
||||
shm_size: 1gb
|
||||
networks: [local]
|
||||
depends_on:
|
||||
site: {condition: service_healthy}
|
||||
kanban: {condition: service_healthy}
|
||||
storage: {condition: service_healthy}
|
||||
security_opt: [no-new-privileges:true]
|
||||
cap_drop: [ALL]
|
||||
|
||||
volumes:
|
||||
postgres-data:
|
||||
storage-data:
|
||||
|
||||
16
compose.providers.yaml
Normal file
@@ -0,0 +1,16 @@
|
||||
# Provider sandbox testing only: gives the API and worker a route to the
|
||||
# internet so they can reach Mercado Pago and Tiny. The default local stack
|
||||
# keeps them on an internal network with no external route, which is what
|
||||
# every other local run should keep doing.
|
||||
#
|
||||
# docker compose -f compose.local.yaml -f compose.providers.yaml up -d --wait
|
||||
#
|
||||
# Credentials go in .env (see .env.example); never production credentials.
|
||||
services:
|
||||
api:
|
||||
networks: [local, provider-egress]
|
||||
worker:
|
||||
networks: [local, provider-egress]
|
||||
|
||||
networks:
|
||||
provider-egress: {}
|
||||
@@ -7,8 +7,8 @@ services:
|
||||
readiness:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: local/Dockerfile
|
||||
command: python -m local.staging_readiness /config/staging.env
|
||||
dockerfile: infra/Dockerfile
|
||||
command: python -m ops.staging_readiness /config/staging.env
|
||||
volumes:
|
||||
- ./staging/staging.env:/config/staging.env:ro
|
||||
network_mode: none
|
||||
|
||||
@@ -13,16 +13,23 @@ LABEL org.opencontainers.image.title="DTF Portal/API" \
|
||||
# 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
|
||||
# is what the production image was doing while the local one already did this.
|
||||
RUN apt-get update \
|
||||
# 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.
|
||||
# The day (PACKAGES_DAY, set by CI) is part of this layer, so a cached build
|
||||
# still fetches the fixes published since.
|
||||
ARG PACKAGES_DAY=unset
|
||||
RUN echo "packages refreshed: $PACKAGES_DAY" && apt-get update \
|
||||
&& apt-get upgrade -y \
|
||||
&& apt-get install -y --no-install-recommends postgresql-client-17 age \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
WORKDIR /app
|
||||
COPY local/requirements.txt local/requirements.lock /app/local/
|
||||
RUN python -m pip install --no-cache-dir --require-hashes -r local/requirements.lock
|
||||
COPY local /app/local
|
||||
COPY infra/requirements.txt infra/requirements.lock /app/infra/
|
||||
RUN python -m pip install --no-cache-dir --require-hashes -r infra/requirements.lock
|
||||
COPY app /app/app
|
||||
COPY ops /app/ops
|
||||
RUN useradd --uid 10001 --create-home --shell /usr/sbin/nologin dtf
|
||||
USER 10001:10001
|
||||
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 PYTHONPATH=/app
|
||||
EXPOSE 8000
|
||||
CMD ["uvicorn", "local.app:app", "--host", "0.0.0.0", "--port", "8000", "--no-access-log"]
|
||||
CMD ["uvicorn", "app.app:app", "--host", "0.0.0.0", "--port", "8000", "--no-access-log"]
|
||||
|
||||
@@ -7,23 +7,28 @@ ARG PYTHON_BASE_IMAGE=python:3.12-slim@sha256:2f17fc044b579bab302c2e8054d3a686e2
|
||||
ARG NGINX_BASE_IMAGE=nginx:alpine@sha256:62ff2089abf5a9ed33bd232895bef5e22f7bb4b200675cec49a5ebc48e3d4ac8
|
||||
FROM ${PYTHON_BASE_IMAGE} AS policy
|
||||
WORKDIR /build
|
||||
COPY dtf-site.html /build/dtf-site.html
|
||||
COPY local /build/local
|
||||
COPY web /build/web
|
||||
COPY infra /build/infra
|
||||
COPY deploy /build/deploy
|
||||
ENV NGINX_TEMPLATE=/build/deploy/nginx.conf.template
|
||||
RUN python local/compile_web.py
|
||||
RUN python infra/compile_web.py
|
||||
|
||||
FROM ${NGINX_BASE_IMAGE}
|
||||
# Same reason as the API image: a pinned base freezes its packages.
|
||||
RUN apk upgrade --no-cache
|
||||
# Same reason as the API image: a pinned base freezes its packages. The day
|
||||
# (PACKAGES_DAY, set by CI) is part of this layer, so a cached build still
|
||||
# fetches the fixes published since: brotli-libs 1.2.1 on 2026-10-29 was
|
||||
# missed by a cached upgrade layer and blocked the release gate.
|
||||
ARG PACKAGES_DAY=unset
|
||||
RUN echo "packages refreshed: $PACKAGES_DAY" && apk upgrade --no-cache
|
||||
ARG VCS_REF=unknown
|
||||
LABEL org.opencontainers.image.title="DTF Site and Kanban" \
|
||||
org.opencontainers.image.revision="$VCS_REF" \
|
||||
org.opencontainers.image.source="DTF System repository"
|
||||
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 dtf-site.html /usr/share/nginx/html/index.html
|
||||
COPY local/static/ /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
|
||||
# writes its PID/cache files. Keep the service non-root while granting it
|
||||
# ownership of only those runtime locations. This works in Docker Swarm,
|
||||
|
||||
@@ -5,8 +5,8 @@ substitute for `production_preflight.py`, CI, staging acceptance, or change appr
|
||||
|
||||
## Application and external contracts
|
||||
|
||||
- [ ] `PRODUCTION_INPUTS.md` has owners, decisions, and evidence for every item.
|
||||
- [ ] Production R2, freight, Mercado Pago, Tiny/Olist, and WhatsApp adapters have
|
||||
- [ ] `docs/PRODUCTION_INPUTS.md` has owners, decisions, and evidence for every item.
|
||||
- [ ] Production R2, freight, Mercado Pago, and Tiny/Olist adapters have
|
||||
sandbox contract tests and least-privilege credentials.
|
||||
- [ ] Payment webhook authenticity, replay handling, and idempotency are tested.
|
||||
- [ ] Docker secret `*_FILE` loading is implemented and tested without logging values.
|
||||
|
||||
@@ -4,7 +4,7 @@ The DTF application is one Portainer-owned Docker Swarm stack. Gitea builds,
|
||||
tests, scans, and publishes the two application images, then calls the stack's
|
||||
Portainer webhook. Start with the short operator guide in `../PORTAINER.md`.
|
||||
|
||||
- `stack.yaml` — the single Portainer stack.
|
||||
- The deployed stack is the repository's `docker-compose.yml`, not a file here.
|
||||
- `Dockerfile.api` and `Dockerfile.web` — prebuilt registry images.
|
||||
- `portainer.env.example` — non-secret Portainer variables.
|
||||
- `production_preflight.py` — fail-closed application/configuration validator.
|
||||
|
||||
@@ -8,6 +8,17 @@ server {
|
||||
# unavailable or still creating its database schema.
|
||||
resolver 127.0.0.11 ipv6=off valid=10s;
|
||||
set $api_upstream api:8000;
|
||||
|
||||
# This gateway sits behind the host's reverse proxy, so $remote_addr is that
|
||||
# proxy, not the customer. Recover the real address from the header it sets,
|
||||
# and only when the connection comes from a private network: a request that
|
||||
# reaches the published port directly from the internet is not trusted, so
|
||||
# its X-Forwarded-For is ignored and $remote_addr stays the actual peer.
|
||||
set_real_ip_from 10.0.0.0/8;
|
||||
set_real_ip_from 172.16.0.0/12;
|
||||
set_real_ip_from 192.168.0.0/16;
|
||||
real_ip_header X-Forwarded-For;
|
||||
real_ip_recursive on;
|
||||
root /usr/share/nginx/html;
|
||||
index ${WEB_INDEX};
|
||||
|
||||
@@ -16,7 +27,7 @@ server {
|
||||
add_header Referrer-Policy no-referrer always;
|
||||
add_header X-Frame-Options DENY always;
|
||||
add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
|
||||
add_header Content-Security-Policy "default-src 'self'; script-src 'self' @SCRIPT_HASHES@ https://cdnjs.cloudflare.com; 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; connect-src 'self' ${S3_PUBLIC_ENDPOINT} https://cdn.vnda.com.br https://cdnjs.cloudflare.com; worker-src 'self' blob: https://cdnjs.cloudflare.com; 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 /api/ {
|
||||
@@ -29,6 +40,7 @@ server {
|
||||
proxy_set_header X-Forwarded-Proto https;
|
||||
# Overwrite, never append: $proxy_add_x_forwarded_for keeps any header the
|
||||
# client sent, and the leftmost value would then be attacker-controlled.
|
||||
# After real_ip above, $remote_addr is the customer even behind the proxy.
|
||||
proxy_set_header X-Forwarded-For $remote_addr;
|
||||
proxy_connect_timeout 5s;
|
||||
proxy_read_timeout 30s;
|
||||
@@ -36,6 +48,21 @@ server {
|
||||
}
|
||||
# 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.
|
||||
# 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;
|
||||
}
|
||||
# The DTF's own terms: exchanges, file keeping and privacy.
|
||||
location ~ ^/termos/?$ {
|
||||
expires -1;
|
||||
try_files /termos.html =404;
|
||||
}
|
||||
location / {
|
||||
expires -1;
|
||||
try_files $uri $uri/ =404;
|
||||
|
||||
@@ -27,15 +27,45 @@ POSTGRES_VOLUME=TBD
|
||||
OPERATOR_EMAIL=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
|
||||
TINY_ADAPTER=TBD
|
||||
WHATSAPP_ADAPTER=TBD
|
||||
# Tiny API v3 application (Configurações > Geral > Aplicativos in Tiny). The
|
||||
# redirect URL registered there must equal TINY_REDIRECT_URI.
|
||||
TINY_CLIENT_ID=TBD
|
||||
TINY_REDIRECT_URI=https://<KANBAN_DOMAIN>/api/operator/tiny/callback
|
||||
TINY_PRODUCT_TEXTIL_FOLHA=TBD
|
||||
TINY_PRODUCT_TEXTIL_AVULSA=TBD
|
||||
TINY_PRODUCT_UV_FOLHA=TBD
|
||||
TINY_PRODUCT_UV_AVULSA=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
|
||||
OWNER_UPLOAD_QUOTA_BYTES=TBD
|
||||
MAX_PENDING_UPLOADS=10
|
||||
MAX_UPLOAD_BYTES=5368709120
|
||||
MAX_UPLOAD_BYTES=4294967296
|
||||
UPLOAD_PART_BYTES=8388608
|
||||
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.
|
||||
DATABASE_URL_SECRET=TBD
|
||||
@@ -48,4 +78,3 @@ OPERATOR_PASSWORD_SECRET=TBD
|
||||
PAYMENT_TOKEN_SECRET=TBD
|
||||
PAYMENT_WEBHOOK_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',
|
||||
'STORAGE_QUOTA_BYTES', 'OWNER_UPLOAD_QUOTA_BYTES', 'MAX_UPLOAD_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',
|
||||
'DB_ADMIN_PASSWORD_SECRET', 'APP_DB_PASSWORD_SECRET',
|
||||
'R2_ACCESS_KEY_ID_SECRET', 'R2_SECRET_ACCESS_KEY_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})$')
|
||||
IMAGE_REPOSITORY = re.compile(
|
||||
@@ -38,11 +38,11 @@ SOURCE_BLOCKERS = {
|
||||
# matching when R2 support landed; they were removed rather than left to rot.
|
||||
# What remains is the real blocker: no production payment or messaging adapter
|
||||
# exists, so these lines must change before a release can be meaningful.
|
||||
'local/app.py': (
|
||||
'app/runtime.py': (
|
||||
'payment = FakePayment()',
|
||||
),
|
||||
'local/worker.py': (
|
||||
"adapters = {'tiny': FakeTiny(), 'whatsapp': FakeWhatsApp()}",
|
||||
'app/worker.py': (
|
||||
"adapters = {'tiny': FakeTiny()}",
|
||||
),
|
||||
}
|
||||
|
||||
@@ -68,7 +68,7 @@ def secret_loading_errors(root=ROOT):
|
||||
import importlib.util
|
||||
import tempfile
|
||||
|
||||
module_path = root / 'local' / 'secrets.py'
|
||||
module_path = root / 'app' / 'core' / 'secrets.py'
|
||||
if not module_path.exists():
|
||||
return ['local runtime does not load the production Docker secret *_FILE settings']
|
||||
try:
|
||||
@@ -76,7 +76,7 @@ def secret_loading_errors(root=ROOT):
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
except Exception as exc:
|
||||
return [f'local/secrets.py could not be loaded: {exc}']
|
||||
return [f'app/core/secrets.py could not be loaded: {exc}']
|
||||
|
||||
stack_names = set()
|
||||
stack = root / 'deploy' / 'stack.yaml'
|
||||
@@ -97,7 +97,7 @@ def secret_loading_errors(root=ROOT):
|
||||
try:
|
||||
module.load(environ)
|
||||
except Exception as exc:
|
||||
failures.append(f'{name}_FILE is not resolved by local/secrets.py: {exc}')
|
||||
failures.append(f'{name}_FILE is not resolved by app/core/secrets.py: {exc}')
|
||||
continue
|
||||
if environ.get(name) != 'resolved-value':
|
||||
failures.append(f'{name}_FILE did not produce {name}')
|
||||
@@ -107,7 +107,7 @@ def secret_loading_errors(root=ROOT):
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
failures.append('local/secrets.py does not fail closed on an unreadable secret')
|
||||
failures.append('app/core/secrets.py does not fail closed on an unreadable secret')
|
||||
return failures
|
||||
|
||||
|
||||
@@ -148,7 +148,7 @@ def config_errors(values):
|
||||
bucket = values.get('R2_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')
|
||||
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'}:
|
||||
errors.append(f'{name} must select an approved non-fake implementation')
|
||||
for name in REQUIRED:
|
||||
@@ -176,6 +176,8 @@ def config_errors(values):
|
||||
errors.append('OWNER_UPLOAD_QUOTA_BYTES cannot exceed STORAGE_QUOTA_BYTES')
|
||||
if numeric.get('SCAN_MAX_BYTES', 0) > numeric.get('MAX_UPLOAD_BYTES', 0):
|
||||
errors.append('SCAN_MAX_BYTES cannot exceed MAX_UPLOAD_BYTES')
|
||||
if numeric.get('SCAN_MAX_BYTES', 0) > 128 * 1024 * 1024:
|
||||
errors.append('SCAN_MAX_BYTES cannot exceed the configured ClamAV 128 MiB stream limit')
|
||||
ports = {}
|
||||
for name in ('SITE_PORT', 'KANBAN_PORT'):
|
||||
try:
|
||||
|
||||
@@ -1,310 +0,0 @@
|
||||
version: "3.8"
|
||||
|
||||
x-app-environment: &app-environment
|
||||
APP_ENV: production
|
||||
DATABASE_URL_FILE: /run/secrets/database_url
|
||||
S3_ENDPOINT: ${R2_ENDPOINT:?set R2_ENDPOINT}
|
||||
S3_PUBLIC_ENDPOINT: ${R2_PUBLIC_ENDPOINT:?set R2_PUBLIC_ENDPOINT}
|
||||
S3_BUCKET: ${R2_BUCKET:?set R2_BUCKET}
|
||||
AWS_ACCESS_KEY_ID_FILE: /run/secrets/r2_access_key_id
|
||||
AWS_SECRET_ACCESS_KEY_FILE: /run/secrets/r2_secret_access_key
|
||||
AWS_DEFAULT_REGION: auto
|
||||
# The Kanban authenticates by email; the runtime reads OPERATOR_EMAIL.
|
||||
OPERATOR_EMAIL: ${OPERATOR_EMAIL:?set OPERATOR_EMAIL}
|
||||
OPERATOR_PASSWORD_FILE: /run/secrets/operator_password
|
||||
PAYMENT_ADAPTER: ${PAYMENT_ADAPTER:?set PAYMENT_ADAPTER}
|
||||
FREIGHT_ADAPTER: ${FREIGHT_ADAPTER:?set FREIGHT_ADAPTER}
|
||||
TINY_ADAPTER: ${TINY_ADAPTER:?set TINY_ADAPTER}
|
||||
WHATSAPP_ADAPTER: ${WHATSAPP_ADAPTER:?set WHATSAPP_ADAPTER}
|
||||
STORAGE_ADAPTER: s3-r2
|
||||
PAYMENT_TOKEN_FILE: /run/secrets/payment_token
|
||||
PAYMENT_WEBHOOK_SECRET_FILE: /run/secrets/payment_webhook_secret
|
||||
TINY_TOKEN_FILE: /run/secrets/tiny_token
|
||||
WHATSAPP_TOKEN_FILE: /run/secrets/whatsapp_token
|
||||
PUBLIC_ORIGIN: ${PUBLIC_ORIGIN:?set PUBLIC_ORIGIN}
|
||||
PUBLIC_HOST: ${PUBLIC_HOST:?set PUBLIC_HOST}
|
||||
ALLOWED_HOSTS: ${PUBLIC_HOST:?set PUBLIC_HOST},${KANBAN_HOST:?set KANBAN_HOST}
|
||||
ALLOWED_ORIGINS: ${PUBLIC_ORIGIN:?set PUBLIC_ORIGIN},https://${KANBAN_HOST:?set KANBAN_HOST}
|
||||
COOKIE_SECURE: "true"
|
||||
MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-5368709120}
|
||||
UPLOAD_PART_BYTES: ${UPLOAD_PART_BYTES:-8388608}
|
||||
STORAGE_QUOTA_BYTES: ${STORAGE_QUOTA_BYTES:?set STORAGE_QUOTA_BYTES}
|
||||
OWNER_UPLOAD_QUOTA_BYTES: ${OWNER_UPLOAD_QUOTA_BYTES:?set OWNER_UPLOAD_QUOTA_BYTES}
|
||||
MAX_PENDING_UPLOADS: ${MAX_PENDING_UPLOADS:-10}
|
||||
SCAN_MAX_BYTES: ${SCAN_MAX_BYTES:-134217728}
|
||||
|
||||
x-app-secrets: &app-secrets
|
||||
- database_url
|
||||
- r2_access_key_id
|
||||
- r2_secret_access_key
|
||||
- operator_password
|
||||
- payment_token
|
||||
- payment_webhook_secret
|
||||
- tiny_token
|
||||
- whatsapp_token
|
||||
|
||||
x-rolling: &rolling
|
||||
update_config:
|
||||
parallelism: 1
|
||||
delay: 10s
|
||||
order: start-first
|
||||
failure_action: rollback
|
||||
monitor: 45s
|
||||
rollback_config:
|
||||
parallelism: 1
|
||||
delay: 5s
|
||||
order: start-first
|
||||
failure_action: pause
|
||||
monitor: 45s
|
||||
restart_policy:
|
||||
condition: on-failure
|
||||
delay: 5s
|
||||
max_attempts: 5
|
||||
window: 60s
|
||||
|
||||
services:
|
||||
db:
|
||||
image: ${POSTGRES_IMAGE:?set POSTGRES_IMAGE}
|
||||
environment:
|
||||
POSTGRES_DB: ${POSTGRES_DB:?set POSTGRES_DB}
|
||||
POSTGRES_USER: ${POSTGRES_USER:?set POSTGRES_USER}
|
||||
POSTGRES_PASSWORD_FILE: /run/secrets/db_admin_password
|
||||
secrets: [db_admin_password]
|
||||
volumes:
|
||||
- postgres-data:/var/lib/postgresql/data
|
||||
networks: [backend]
|
||||
healthcheck:
|
||||
test: [CMD-SHELL, 'pg_isready -U "$$POSTGRES_USER" -d "$$POSTGRES_DB"']
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 12
|
||||
start_period: 20s
|
||||
stop_grace_period: 60s
|
||||
deploy:
|
||||
replicas: 1
|
||||
placement:
|
||||
constraints: [node.labels.dtf_database == true]
|
||||
update_config:
|
||||
parallelism: 1
|
||||
order: stop-first
|
||||
failure_action: rollback
|
||||
monitor: 60s
|
||||
rollback_config:
|
||||
parallelism: 1
|
||||
order: stop-first
|
||||
failure_action: pause
|
||||
monitor: 60s
|
||||
restart_policy:
|
||||
condition: on-failure
|
||||
delay: 10s
|
||||
max_attempts: 5
|
||||
window: 120s
|
||||
resources:
|
||||
limits: {cpus: "2.0", memory: 4G}
|
||||
reservations: {cpus: "0.5", memory: 1G}
|
||||
|
||||
db-init:
|
||||
image: ${API_IMAGE:?set API_IMAGE}:${IMAGE_TAG:-latest}
|
||||
command: python -m local.bootstrap
|
||||
environment:
|
||||
APP_ENV: production
|
||||
DATABASE_ADMIN_URL_FILE: /run/secrets/database_admin_url
|
||||
APP_DB_USER: ${APP_DB_USER:?set APP_DB_USER}
|
||||
APP_DB_PASSWORD_FILE: /run/secrets/app_db_password
|
||||
secrets: [database_admin_url, app_db_password]
|
||||
networks: [backend]
|
||||
deploy:
|
||||
replicas: 1
|
||||
restart_policy: {condition: none}
|
||||
placement:
|
||||
constraints: [node.platform.os == linux]
|
||||
resources:
|
||||
limits: {cpus: "0.5", memory: 512M}
|
||||
|
||||
scanner:
|
||||
image: ${CLAMAV_IMAGE:?set CLAMAV_IMAGE}
|
||||
user: "100:101"
|
||||
entrypoint: [clamd, --foreground=true, --config-file=/etc/clamav/clamd.conf]
|
||||
configs:
|
||||
- source: clamd_config
|
||||
target: /etc/clamav/clamd.conf
|
||||
mode: 0444
|
||||
networks: [backend]
|
||||
read_only: true
|
||||
cap_drop: [ALL]
|
||||
security_opt: [no-new-privileges:true]
|
||||
tmpfs:
|
||||
- /tmp:uid=100,gid=101,mode=0750
|
||||
- /run/clamav:uid=100,gid=101,mode=0750
|
||||
- /var/log/clamav:uid=100,gid=101,mode=0750
|
||||
healthcheck:
|
||||
test: [CMD, clamdscan, --config-file=/etc/clamav/clamd.conf, --ping, "3"]
|
||||
interval: 15s
|
||||
timeout: 5s
|
||||
retries: 20
|
||||
start_period: 90s
|
||||
deploy:
|
||||
replicas: 1
|
||||
restart_policy: {condition: on-failure, delay: 10s}
|
||||
resources:
|
||||
limits: {cpus: "2.0", memory: 3G}
|
||||
reservations: {cpus: "0.5", memory: 1G}
|
||||
|
||||
api:
|
||||
image: ${API_IMAGE:?set API_IMAGE}:${IMAGE_TAG:-latest}
|
||||
environment: *app-environment
|
||||
secrets: *app-secrets
|
||||
networks: [backend, egress]
|
||||
read_only: true
|
||||
tmpfs: [/tmp]
|
||||
init: true
|
||||
cap_drop: [ALL]
|
||||
security_opt: [no-new-privileges:true]
|
||||
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)"
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 12
|
||||
start_period: 30s
|
||||
stop_grace_period: 30s
|
||||
deploy:
|
||||
<<: *rolling
|
||||
replicas: 2
|
||||
resources:
|
||||
limits: {cpus: "1.0", memory: 1G}
|
||||
reservations: {cpus: "0.25", memory: 256M}
|
||||
|
||||
worker:
|
||||
image: ${API_IMAGE:?set API_IMAGE}:${IMAGE_TAG:-latest}
|
||||
command: python -m local.worker
|
||||
environment:
|
||||
<<: *app-environment
|
||||
CLAMD_HOST: scanner
|
||||
secrets: *app-secrets
|
||||
networks: [backend, egress]
|
||||
read_only: true
|
||||
tmpfs: [/tmp]
|
||||
init: true
|
||||
cap_drop: [ALL]
|
||||
security_opt: [no-new-privileges:true]
|
||||
healthcheck:
|
||||
test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8002/health',timeout=3)"]
|
||||
interval: 15s
|
||||
timeout: 5s
|
||||
retries: 12
|
||||
start_period: 90s
|
||||
stop_grace_period: 60s
|
||||
deploy:
|
||||
<<: *rolling
|
||||
replicas: 1
|
||||
update_config:
|
||||
parallelism: 1
|
||||
order: stop-first
|
||||
failure_action: rollback
|
||||
monitor: 60s
|
||||
rollback_config:
|
||||
parallelism: 1
|
||||
order: stop-first
|
||||
failure_action: pause
|
||||
monitor: 60s
|
||||
resources:
|
||||
limits: {cpus: "1.5", memory: 2G}
|
||||
reservations: {cpus: "0.25", memory: 512M}
|
||||
|
||||
site:
|
||||
image: ${WEB_IMAGE:?set WEB_IMAGE}:${IMAGE_TAG:-latest}
|
||||
environment:
|
||||
WEB_INDEX: index.html
|
||||
PUBLIC_HOST: ${PUBLIC_HOST:?set PUBLIC_HOST}
|
||||
S3_PUBLIC_ENDPOINT: ${R2_PUBLIC_ENDPOINT:?set R2_PUBLIC_ENDPOINT}
|
||||
networks: [backend]
|
||||
ports:
|
||||
- target: 8080
|
||||
published: ${SITE_PORT:-8080}
|
||||
protocol: tcp
|
||||
mode: ingress
|
||||
read_only: true
|
||||
tmpfs:
|
||||
- /tmp:uid=101,gid=101,mode=0750
|
||||
- /var/cache/nginx:uid=101,gid=101,mode=0750
|
||||
- /var/run:uid=101,gid=101,mode=0750
|
||||
- /etc/nginx/conf.d:uid=101,gid=101,mode=0750
|
||||
cap_drop: [ALL]
|
||||
security_opt: [no-new-privileges:true]
|
||||
healthcheck:
|
||||
test: [CMD-SHELL, 'wget -q --header="Host: $$PUBLIC_HOST" -O /dev/null http://127.0.0.1:8080/health']
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 12
|
||||
start_period: 15s
|
||||
deploy:
|
||||
<<: *rolling
|
||||
replicas: 2
|
||||
resources:
|
||||
limits: {cpus: "0.5", memory: 256M}
|
||||
reservations: {cpus: "0.1", memory: 64M}
|
||||
|
||||
kanban:
|
||||
image: ${WEB_IMAGE:?set WEB_IMAGE}:${IMAGE_TAG:-latest}
|
||||
environment:
|
||||
WEB_INDEX: kanban.html
|
||||
PUBLIC_HOST: ${KANBAN_HOST:?set KANBAN_HOST}
|
||||
S3_PUBLIC_ENDPOINT: ${R2_PUBLIC_ENDPOINT:?set R2_PUBLIC_ENDPOINT}
|
||||
networks: [backend]
|
||||
ports:
|
||||
- target: 8080
|
||||
published: ${KANBAN_PORT:-8081}
|
||||
protocol: tcp
|
||||
mode: ingress
|
||||
read_only: true
|
||||
tmpfs:
|
||||
- /tmp:uid=101,gid=101,mode=0750
|
||||
- /var/cache/nginx:uid=101,gid=101,mode=0750
|
||||
- /var/run:uid=101,gid=101,mode=0750
|
||||
- /etc/nginx/conf.d:uid=101,gid=101,mode=0750
|
||||
cap_drop: [ALL]
|
||||
security_opt: [no-new-privileges:true]
|
||||
healthcheck:
|
||||
test: [CMD-SHELL, 'wget -q --header="Host: $$PUBLIC_HOST" -O /dev/null http://127.0.0.1:8080/health']
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 12
|
||||
start_period: 15s
|
||||
deploy:
|
||||
<<: *rolling
|
||||
replicas: 1
|
||||
resources:
|
||||
limits: {cpus: "0.5", memory: 256M}
|
||||
reservations: {cpus: "0.1", memory: 64M}
|
||||
|
||||
configs:
|
||||
clamd_config:
|
||||
file: ../local/clamd.conf
|
||||
|
||||
secrets:
|
||||
database_url: {external: true, name: "${DATABASE_URL_SECRET:?set DATABASE_URL_SECRET}"}
|
||||
database_admin_url: {external: true, name: "${DATABASE_ADMIN_URL_SECRET:?set DATABASE_ADMIN_URL_SECRET}"}
|
||||
db_admin_password: {external: true, name: "${DB_ADMIN_PASSWORD_SECRET:?set DB_ADMIN_PASSWORD_SECRET}"}
|
||||
app_db_password: {external: true, name: "${APP_DB_PASSWORD_SECRET:?set APP_DB_PASSWORD_SECRET}"}
|
||||
r2_access_key_id: {external: true, name: "${R2_ACCESS_KEY_ID_SECRET:?set R2_ACCESS_KEY_ID_SECRET}"}
|
||||
r2_secret_access_key: {external: true, name: "${R2_SECRET_ACCESS_KEY_SECRET:?set R2_SECRET_ACCESS_KEY_SECRET}"}
|
||||
operator_password: {external: true, name: "${OPERATOR_PASSWORD_SECRET:?set OPERATOR_PASSWORD_SECRET}"}
|
||||
payment_token: {external: true, name: "${PAYMENT_TOKEN_SECRET:?set PAYMENT_TOKEN_SECRET}"}
|
||||
payment_webhook_secret: {external: true, name: "${PAYMENT_WEBHOOK_SECRET:?set PAYMENT_WEBHOOK_SECRET}"}
|
||||
tiny_token: {external: true, name: "${TINY_TOKEN_SECRET:?set TINY_TOKEN_SECRET}"}
|
||||
whatsapp_token: {external: true, name: "${WHATSAPP_TOKEN_SECRET:?set WHATSAPP_TOKEN_SECRET}"}
|
||||
|
||||
volumes:
|
||||
postgres-data:
|
||||
external: true
|
||||
name: ${POSTGRES_VOLUME:?set POSTGRES_VOLUME}
|
||||
|
||||
networks:
|
||||
backend:
|
||||
driver: overlay
|
||||
internal: true
|
||||
egress:
|
||||
driver: overlay
|
||||
@@ -1,8 +1,30 @@
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from .production_preflight import config_errors, source_errors
|
||||
|
||||
|
||||
class ReleaseWorkflowTests(unittest.TestCase):
|
||||
def test_only_checked_main_publishes_and_pushes_never_deploy(self):
|
||||
workflow = (Path(__file__).resolve().parents[1] /
|
||||
'.gitea/workflows/deploy.yml').read_text()
|
||||
checks, release = workflow.split(' publish-and-deploy:\n', 1)
|
||||
# Publishing waits for every check, and only ever happens from main.
|
||||
self.assertIn('needs: [validate, integration, scan]', release)
|
||||
self.assertIn("if: gitea.ref == 'refs/heads/main' && ", release)
|
||||
# The source preflight lives in the scan job and can be made blocking.
|
||||
self.assertIn('python3 deploy/production_preflight.py --source-only', checks)
|
||||
self.assertIn('ENFORCE_PRODUCTION_PREFLIGHT', checks)
|
||||
# Images are scanned before they are pushed, and a push to main only
|
||||
# publishes: redeployment is Portainer's (or a manual run's) decision.
|
||||
scan = release.index('- name: Image vulnerabilities')
|
||||
publish = release.index('- name: Publish validated images')
|
||||
redeploy = release.index('- name: Trigger Portainer redeployment')
|
||||
self.assertLess(scan, publish)
|
||||
self.assertLess(publish, redeploy)
|
||||
self.assertIn("if: gitea.event_name == 'workflow_dispatch'", release[redeploy:])
|
||||
|
||||
|
||||
def valid_config():
|
||||
digest = '1' * 64
|
||||
values = {
|
||||
@@ -37,19 +59,38 @@ def valid_config():
|
||||
'PAYMENT_ADAPTER': 'mercado-pago',
|
||||
'FREIGHT_ADAPTER': 'approved-freight',
|
||||
'TINY_ADAPTER': 'tiny-olist',
|
||||
'WHATSAPP_ADAPTER': 'approved-whatsapp',
|
||||
}
|
||||
for name in (
|
||||
'DATABASE_URL_SECRET', 'DATABASE_ADMIN_URL_SECRET',
|
||||
'DB_ADMIN_PASSWORD_SECRET', 'APP_DB_PASSWORD_SECRET',
|
||||
'R2_ACCESS_KEY_ID_SECRET', 'R2_SECRET_ACCESS_KEY_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()
|
||||
return values
|
||||
|
||||
|
||||
class SourceMarkerTests(unittest.TestCase):
|
||||
"""A marker that stops matching weakens the gate without failing it.
|
||||
|
||||
This is how four markers silently died when the runtime gained R2 support,
|
||||
and how the payment one died again when it moved to runtime.py. Assert that
|
||||
every marker still points at something real.
|
||||
"""
|
||||
|
||||
def test_every_marker_is_found_in_its_file(self):
|
||||
from deploy.production_preflight import ROOT, SOURCE_BLOCKERS
|
||||
for relative, markers in SOURCE_BLOCKERS.items():
|
||||
path = ROOT / relative
|
||||
self.assertTrue(path.exists(), f'{relative} no longer exists')
|
||||
text = path.read_text()
|
||||
for marker in markers:
|
||||
self.assertIn(marker, text,
|
||||
f'{relative} no longer contains {marker!r}: the gate '
|
||||
'would pass without the condition being resolved')
|
||||
|
||||
|
||||
class ProductionPreflightTests(unittest.TestCase):
|
||||
def test_structurally_complete_metadata_passes(self):
|
||||
self.assertEqual(config_errors(valid_config()), [])
|
||||
@@ -80,8 +121,8 @@ class ProductionPreflightTests(unittest.TestCase):
|
||||
|
||||
def test_fake_checkout_is_explicitly_blocked(self):
|
||||
errors = source_errors()
|
||||
self.assertTrue(any('local/app.py remains local-only' in error for error in errors))
|
||||
self.assertTrue(any('local/worker.py remains local-only' in error for error in errors))
|
||||
self.assertTrue(any('app/runtime.py remains local-only' in error for error in errors))
|
||||
self.assertTrue(any('app/worker.py remains local-only' in error for error in errors))
|
||||
|
||||
def test_secret_reuse_and_incoherent_limits_are_rejected(self):
|
||||
values = valid_config()
|
||||
@@ -92,6 +133,7 @@ class ProductionPreflightTests(unittest.TestCase):
|
||||
self.assertTrue(any('distinct external Swarm secret' in error for error in errors))
|
||||
self.assertIn('OWNER_UPLOAD_QUOTA_BYTES cannot exceed STORAGE_QUOTA_BYTES', errors)
|
||||
self.assertIn('SCAN_MAX_BYTES cannot exceed MAX_UPLOAD_BYTES', errors)
|
||||
self.assertTrue(any('configured ClamAV 128 MiB stream limit' in error for error in errors))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@@ -19,22 +19,134 @@ x-app-environment: &app-environment
|
||||
# this value is configured.
|
||||
OPERATOR_EMAIL: ${OPERATOR_EMAIL:-}
|
||||
OPERATOR_PASSWORD: ${OPERATOR_PASSWORD:?set OPERATOR_PASSWORD}
|
||||
PAYMENT_ADAPTER: fake
|
||||
FREIGHT_ADAPTER: fake
|
||||
TINY_ADAPTER: fake
|
||||
WHATSAPP_ADAPTER: fake
|
||||
# fake until Mercado Pago is configured; mercadopago requires MP_ACCESS_TOKEN
|
||||
# and MP_WEBHOOK_SECRET or the API and worker refuse to start. Test
|
||||
# credentials (TEST-...) until the sandbox flows have passed. The card form
|
||||
# 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:-}
|
||||
# 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). Dropstar set R$ 2,00
|
||||
# a metro on 2026-10-23; 0 adds nothing. The Site shows it before payment.
|
||||
MANUAL_FILE_EXTRA_CENTS: ${MANUAL_FILE_EXTRA_CENTS:-200}
|
||||
# Print files longer than 5,08 m are written at their real size, which Corel
|
||||
# reads (2026-10-28). true goes back to PDF's /UserUnit scale, for a RIP that
|
||||
# refuses pages over 5,08 m.
|
||||
PRINT_PAGE_SCALE: ${PRINT_PAGE_SCALE:-false}
|
||||
# Order creation in Tiny stays off until it has been tested against the
|
||||
# client's account (Tiny has no sandbox). The application credentials can be
|
||||
# set now: they let an operator connect Tiny from the Kanban, and the worker
|
||||
# keeps that connection alive. Callback: https://<KANBAN_DOMAIN>/api/operator/tiny/callback
|
||||
# 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_SECRET: ${TINY_CLIENT_SECRET:-}
|
||||
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_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: ${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:-}
|
||||
# Optional e-commerce channel id for Site orders. Without it the order still
|
||||
# carries DTF-<n> as numeroPedidoEcommerce, with no channel.
|
||||
TINY_ECOMMERCE_ID: ${TINY_ECOMMERCE_ID:-}
|
||||
# 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
|
||||
PUBLIC_ORIGIN: https://${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_ORIGINS: https://${SITE_DOMAIN:?set SITE_DOMAIN},https://${KANBAN_DOMAIN:?set KANBAN_DOMAIN}
|
||||
COOKIE_SECURE: "true"
|
||||
MAX_UPLOAD_BYTES: "5368709120"
|
||||
# 4 GB per file (Dropstar, 2026-10-28; it was 5 GB, then 1 GB from 2026-10-21).
|
||||
MAX_UPLOAD_BYTES: "4294967296"
|
||||
UPLOAD_PART_BYTES: "8388608"
|
||||
STORAGE_QUOTA_BYTES: "53687091200"
|
||||
OWNER_UPLOAD_QUOTA_BYTES: "10737418240"
|
||||
# Sheets of several GB are the normal order, so room for many of them.
|
||||
STORAGE_QUOTA_BYTES: "${STORAGE_QUOTA_BYTES:-536870912000}"
|
||||
OWNER_UPLOAD_QUOTA_BYTES: "${OWNER_UPLOAD_QUOTA_BYTES:-53687091200}"
|
||||
MAX_PENDING_UPLOADS: "10"
|
||||
SCAN_MAX_BYTES: "134217728"
|
||||
# ClamAV scans up to its own limit, 2000 MiB (infra/clamd.conf); a larger
|
||||
# file, up to the 4 GB above, is released after the file-format check
|
||||
# (app/scanning.py, check_large).
|
||||
SCAN_MAX_BYTES: "2097152000"
|
||||
|
||||
services:
|
||||
db:
|
||||
@@ -57,7 +169,7 @@ services:
|
||||
|
||||
db-init:
|
||||
image: ${API_IMAGE:-gitea.blyzer.com.br/blyzer/dtf-api}:${IMAGE_TAG:-latest}
|
||||
command: python -m local.bootstrap
|
||||
command: python -m app.bootstrap
|
||||
environment:
|
||||
DATABASE_ADMIN_HOST: db
|
||||
DATABASE_ADMIN_NAME: dtf
|
||||
@@ -65,6 +177,12 @@ services:
|
||||
DATABASE_ADMIN_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD}
|
||||
APP_DB_USER: dtf_app
|
||||
APP_DB_PASSWORD: ${APP_DB_PASSWORD:?set APP_DB_PASSWORD}
|
||||
# The migration job seeds the first operator account from these, so an
|
||||
# existing deployment keeps its Kanban login after the accounts table
|
||||
# lands. Without them there would be no account at all and login would
|
||||
# fail closed with 503.
|
||||
OPERATOR_EMAIL: ${OPERATOR_EMAIL:-}
|
||||
OPERATOR_PASSWORD: ${OPERATOR_PASSWORD:?set OPERATOR_PASSWORD}
|
||||
networks: [backend]
|
||||
deploy:
|
||||
replicas: 1
|
||||
@@ -74,7 +192,7 @@ services:
|
||||
image: clamav/clamav@sha256:9cb27d7660bdf66e9878c832cb433dd8aa152cfbe16f3c2c0084c80b04ae22b4
|
||||
entrypoint: [clamd, --foreground=true, --config-file=/etc/clamav/clamd.conf]
|
||||
configs:
|
||||
- source: clamd_config
|
||||
- source: clamd_config_2gb
|
||||
target: /etc/clamav/clamd.conf
|
||||
mode: 0444
|
||||
networks: [backend]
|
||||
@@ -95,7 +213,10 @@ services:
|
||||
environment: *app-environment
|
||||
networks: [backend, egress]
|
||||
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:
|
||||
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
|
||||
@@ -108,11 +229,12 @@ services:
|
||||
|
||||
worker:
|
||||
image: ${API_IMAGE:-gitea.blyzer.com.br/blyzer/dtf-api}:${IMAGE_TAG:-latest}
|
||||
command: python -m local.worker
|
||||
command: python -m app.worker
|
||||
environment: *app-environment
|
||||
networks: [backend, egress]
|
||||
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:
|
||||
test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8002/health',timeout=3)"]
|
||||
interval: 15s
|
||||
@@ -123,12 +245,49 @@ services:
|
||||
replicas: 1
|
||||
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:
|
||||
image: ${WEB_IMAGE:-gitea.blyzer.com.br/blyzer/dtf-web}:${IMAGE_TAG:-latest}
|
||||
environment:
|
||||
WEB_INDEX: index.html
|
||||
PUBLIC_HOST: ${SITE_DOMAIN:?set SITE_DOMAIN}
|
||||
S3_PUBLIC_ENDPOINT: ${R2_ENDPOINT:?set R2_ENDPOINT}
|
||||
# Mercado Pago's card form loads from these origins; empty keeps the
|
||||
# Site at script-src 'self'. Set together with the Mercado Pago adapter.
|
||||
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]
|
||||
ports:
|
||||
- target: 8080
|
||||
@@ -151,6 +310,8 @@ services:
|
||||
WEB_INDEX: kanban.html
|
||||
PUBLIC_HOST: ${KANBAN_DOMAIN:?set KANBAN_DOMAIN}
|
||||
S3_PUBLIC_ENDPOINT: ${R2_ENDPOINT:?set R2_ENDPOINT}
|
||||
PAYMENT_CSP_SOURCES: ""
|
||||
PAYMENT_CHALLENGE_SOURCES: ""
|
||||
networks: [backend]
|
||||
ports:
|
||||
- target: 8080
|
||||
@@ -168,11 +329,14 @@ services:
|
||||
restart_policy: {condition: on-failure, delay: 5s}
|
||||
|
||||
configs:
|
||||
clamd_config:
|
||||
file: ./local/clamd.conf
|
||||
# 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
|
||||
|
||||
volumes:
|
||||
postgres-data:
|
||||
worker-tmp:
|
||||
|
||||
networks:
|
||||
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.
|
||||
691
docs/CONTEXT.md
Normal file
@@ -0,0 +1,691 @@
|
||||
# DTF System - Project Context for AI Agents
|
||||
|
||||
## Purpose of this document
|
||||
|
||||
Read this document before changing code, documentation, architecture, or scope.
|
||||
It is the current English source of truth for the project. It supersedes older
|
||||
decisions in `README.md`, `docs/historico/ESPECIFICACAO.md`, `schema.sql`, and the existing
|
||||
prototype code whenever they conflict.
|
||||
|
||||
Update this file whenever the team makes a material product, process, or
|
||||
architecture decision.
|
||||
|
||||
## Project goal
|
||||
|
||||
Build a DTF ordering and production-flow system for Dropstar/Altus.
|
||||
|
||||
The current process is slow and manual: customers send artwork through
|
||||
WhatsApp, staff forward files, designers discover problems late, and production
|
||||
status is not visible outside the factory. The business has substantially more
|
||||
machine capacity than it currently uses. The goal is to let customers place DTF
|
||||
orders online, pay, send artwork, and follow production without making
|
||||
WhatsApp, shared folders, or manual handoffs the bottleneck.
|
||||
|
||||
The customer-facing value is speed and clarity. The operations value is a
|
||||
traceable queue and fewer lost or manually handled orders.
|
||||
|
||||
## Current MVP scope
|
||||
|
||||
The MVP must be delivered in **at most three weeks**. The target is a working
|
||||
online system, not factory-machine automation.
|
||||
|
||||
### Included
|
||||
|
||||
- Dedicated DTF site/subdomain.
|
||||
- Existing Site DTF commercial rules and product experience.
|
||||
- Direct, resumable multipart file upload to Cloudflare R2.
|
||||
- Mercado Pago payment integration with signed and idempotent webhooks.
|
||||
- Freight quotation and charging at checkout.
|
||||
- Idempotent Tiny/Olist order integration and order traceability.
|
||||
- Online Kanban for production status and secure file download.
|
||||
- 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.
|
||||
- Operator guidance for the factory team.
|
||||
|
||||
### Explicitly outside the three-week delivery
|
||||
|
||||
- Automatic pre-flight validation. It will be validated after delivery using
|
||||
real customer files and real printed output, then refined as support work.
|
||||
- Direct FlexiPRINT integration.
|
||||
- Factory-side agent, hot folder, internal file server automation, VPN, and
|
||||
heartbeat monitoring.
|
||||
- Production-room dashboard, printer/machine telemetry, and advanced reports.
|
||||
- Automated shipping-label purchase, shipping-label printing, and dispatch
|
||||
automation. The MVP freight scope is quote selection and charging only.
|
||||
- Personalized cart behaviour based on past orders, day, or time.
|
||||
|
||||
After delivery, the team provides support and evaluates requested changes. Do
|
||||
not turn post-delivery support into a new committed delivery phase without an
|
||||
explicit decision.
|
||||
|
||||
## Agreed production model
|
||||
|
||||
```text
|
||||
Customer browser
|
||||
-> Site DTF / API on VPS
|
||||
-> direct multipart upload to private Cloudflare R2
|
||||
-> Mercado Pago payment + freight selected at checkout
|
||||
-> Tiny/Olist order record
|
||||
-> online Kanban
|
||||
-> factory operator downloads final file and imports it manually into FlexiPRINT
|
||||
```
|
||||
|
||||
WhatsApp is a notification channel, not the artwork-upload channel. It is used
|
||||
for payment confirmation, correction requests, production status, and order
|
||||
completion.
|
||||
|
||||
The operator works through the browser. The factory does not need an installed
|
||||
agent or an internal server for the MVP.
|
||||
|
||||
If the factory internet connection fails, only the factory team temporarily
|
||||
loses access to the Kanban and secure downloads. The public portal, payments,
|
||||
uploads, R2 objects, queue, and cloud services remain online. Factory work
|
||||
resumes when local access returns.
|
||||
|
||||
## Infrastructure and deployment
|
||||
|
||||
- **VPS:** runs the website, API, worker, PostgreSQL, ClamAV, Kanban, and
|
||||
third-party integrations.
|
||||
- **Cloudflare R2:** private S3-compatible object storage for original uploads
|
||||
and final files. It does not run the application, database, worker, or
|
||||
antivirus.
|
||||
- **Upload path:** the browser uploads directly to R2 using short-lived,
|
||||
server-issued presigned multipart URLs. Large files must never be proxied
|
||||
through the VPS.
|
||||
- **Deployment:** one Portainer-owned `dtf-cloud` Docker Swarm stack. One Gitea
|
||||
Actions workflow tests/scans, publishes `latest` plus commit-SHA application
|
||||
images, and calls the Portainer webhook. Activation remains blocked pending
|
||||
the production work listed below.
|
||||
- **Kanban access:** configure `OPERATOR_EMAIL` and `OPERATOR_PASSWORD` as
|
||||
stack environment variables. If the email is absent, only Kanban login is
|
||||
blocked; the rest of the stack remains available.
|
||||
- **Recommended VPS baseline:** 4 vCPU, 16 GB RAM, and 200 GB NVMe. Existing
|
||||
VPS capacity may be used if it safely meets or exceeds this baseline.
|
||||
- **Backups:** PostgreSQL backups go to R2. Application secrets are never
|
||||
committed to Git.
|
||||
|
||||
## File retention
|
||||
|
||||
The business does not want an unlimited artwork library.
|
||||
|
||||
| Artifact | Retention |
|
||||
|---|---:|
|
||||
| Incomplete multipart upload | 1 day |
|
||||
| Rejected or infected upload | 3 days |
|
||||
| Customer original after approval | Up to 7 days |
|
||||
| Final print artwork | Maximum 30 days from the first upload |
|
||||
| Order history and metrics | Kept in the database without keeping the image |
|
||||
|
||||
The 30-day retention decision overrides older references to 90 days or
|
||||
12-month artwork reordering.
|
||||
|
||||
## R2 planning cost reference
|
||||
|
||||
R2 cost is driven primarily by the average number of gigabytes stored during a
|
||||
month; read/write operations are expected to be a much smaller cost at the
|
||||
project's scale. There is no egress charge in the current planning model.
|
||||
|
||||
The client-facing roadmap uses the following planning examples, based on
|
||||
standard R2 storage pricing, the included storage allowance, and an exchange
|
||||
rate reference of USD 1 = BRL 5.13:
|
||||
|
||||
| Average storage | Approx. R2/month | Approx. BRL/month |
|
||||
|---|---:|---:|
|
||||
| 100 GB | USD 1.35 | BRL 7 |
|
||||
| 500 GB | USD 7.35 | BRL 38 |
|
||||
| 1 TB | USD 14.85 | BRL 76 |
|
||||
| 3 TB | USD 44.85 | BRL 230 |
|
||||
|
||||
These are planning estimates only. Confirm Cloudflare pricing, exchange rates,
|
||||
taxes, and payment-provider fees before presenting a commercial quote.
|
||||
|
||||
## Commercial rules
|
||||
|
||||
The rules in `web/index.html` and `app/core/pricing.py` are approved as the
|
||||
current source of truth. Do **not** redesign, simplify, or change prices,
|
||||
minimums, rounding, or product modes without explicit approval.
|
||||
|
||||
The Site has four product modes, each with one price per metre (Dropstar,
|
||||
2026-10-23, live in the code since 2026-10-26). It replaced the five-band
|
||||
ladder by grade, its "a partir de R$ 14,90" and the separate assembly charge
|
||||
for loose artwork:
|
||||
|
||||
| Product | Ready sheet | Loose artwork |
|
||||
|---|---:|---:|
|
||||
| DTF textile, 57 cm | R$ 19,90 | R$ 21,90 |
|
||||
| UV sticker, 27 cm (Dropstar, 2026-10-28; was 28,5) | R$ 79,90 | R$ 89,90 |
|
||||
|
||||
The grade (nota) is still computed and shown, to the customer, on the Kanban
|
||||
and in Tiny's item note: it explains the file and no longer changes the price.
|
||||
Artwork below 96 DPI is still refused, and a resolution warning must still be
|
||||
acknowledged. The server still recomputes the grade from the files at checkout
|
||||
(`app/grade_check.py`) and holds for review a cart whose grade the files do not
|
||||
support, so the grade shown stays honest; the review reason "Nota informada sem
|
||||
análise da arte" existed only to stop a discount and was removed. One-metre
|
||||
minimum and ten-centimetre billing rounding. The prices are `PRECO` in
|
||||
`web/site-config.js` and `PRICES` in `app/core/pricing.py`, and
|
||||
`tests/test_pricing.py` checks they agree; every price on the Site's pages (top
|
||||
chip, home example, product cards, product selector, price table) is filled
|
||||
from `PRECO` through `data-preco`.
|
||||
|
||||
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
|
||||
recalculate and validate all price, quantity, and freight values on
|
||||
the server. Client-provided totals are never authoritative.
|
||||
|
||||
Normal JPG/PNG uploads are individual artwork by default, including when uploaded
|
||||
from the by-metre panel. They use the existing loose-artwork editor, printed
|
||||
width, quantity, and live packing canvas; packed height determines metres.
|
||||
Customers uploading an already assembled film-width image must explicitly select
|
||||
the ready-sheet option before uploading. PDF and manual-format ready sheets keep
|
||||
their existing workflow. These models keep their separate prices;
|
||||
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 product's price plus `MANUAL_FILE_EXTRA_CENTS` per
|
||||
metre (2026-10-13, asked at the 7 October meeting to steer customers to PNG).
|
||||
The production stack sets it to 200, R$ 2,00 a metre (Dropstar, 2026-10-23);
|
||||
a value set in Portainer overrides it, and it is 0 locally and in CI. The
|
||||
amount is the client's to set. The Site reads it from `/api/session` and shows
|
||||
it before checkout (product page, help text, price table);
|
||||
`app/core/pricing.py` charges it.
|
||||
|
||||
What a file is comes from its first bytes, never from its name (Dropstar's
|
||||
rule D-13, 2026-10-26; a third of their ".cdr" files are PDFs). The Site reads
|
||||
the first bytes when a file is chosen and renames it to its real extension
|
||||
(`nomeReal` in web/site-upload.js): a ".cdr" that is a PDF becomes ".pdf" and
|
||||
is measured and checked as a PDF, without the manual charge; a JPG called
|
||||
".png" is refused as a JPG, naming the file. The server does the same when it
|
||||
scans an upload (`real_name` in app/scanning.py) and stores the real name, so
|
||||
every later decision that reads the name (the manual charge, the JPG refusal,
|
||||
the grade, the original used as its own print file, the folder file names)
|
||||
follows the content even if the browser was bypassed. A name its content
|
||||
agrees with stays: an Illustrator ".ai" is a PDF inside but is still handled
|
||||
by hand, since one saved without PDF content prints a placeholder page. A file
|
||||
too large for the antivirus passes when its content is any accepted format.
|
||||
|
||||
## 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
|
||||
functional. The localhost bridge now supports pickup and backend fake freight
|
||||
quotes; there is still no real carrier quotation or production checkout.
|
||||
|
||||
The customer already uses Correios and other shipping platforms. Before freight
|
||||
can be completed, obtain:
|
||||
|
||||
- The platform(s) that should be used as the source of truth.
|
||||
- API credentials or delegated access for the selected platform.
|
||||
- Origin postal code/address.
|
||||
- Available services and carriers to offer.
|
||||
- Packaging weight and dimensions by DTF length/package.
|
||||
- Freight business policy: exact pass-through, subsidy, free-shipping rules,
|
||||
pickup, or other exceptions.
|
||||
|
||||
At checkout, the backend must quote freight from the selected source, store the
|
||||
chosen service and quoted amount, include the amount in the Mercado Pago
|
||||
payment, and persist it in the order. Do not create a payment before the freight
|
||||
amount is final.
|
||||
|
||||
## Integrations
|
||||
|
||||
### 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:
|
||||
|
||||
- Production credentials.
|
||||
- Webhook configuration/access.
|
||||
|
||||
Webhook processing must verify authenticity and be idempotent. A duplicate or
|
||||
late delivery must not create a duplicate payment, order, message, or queue
|
||||
card.
|
||||
|
||||
### Tiny/Olist
|
||||
|
||||
Tiny/Olist is already available. The implementation must create/update orders
|
||||
idempotently and use the order number for traceability. Confirm the actual API
|
||||
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 is already available, but the technical provider still needs to be
|
||||
confirmed (official Meta Cloud API, Z-API, or another provider).
|
||||
|
||||
Implement only the required customer events:
|
||||
|
||||
1. Payment approved.
|
||||
2. Artwork correction needed, with a secure link back to the site.
|
||||
3. Order entered production.
|
||||
4. Order ready for collection or shipping.
|
||||
|
||||
Messages initiated by the business may require approved templates depending on
|
||||
the provider and conversation state. Use an outbox/job mechanism with retries,
|
||||
delivery status handling, and idempotency. Do not send artwork through
|
||||
WhatsApp.
|
||||
|
||||
## Factory responsibilities after delivery
|
||||
|
||||
The client/factory team is responsible for:
|
||||
|
||||
- Opening the Kanban, downloading final files, and importing them manually into
|
||||
the current FlexiPRINT setup.
|
||||
- Performing real print tests and reporting mismatches in the final file or
|
||||
printed result.
|
||||
- Maintaining PCs, printers, FlexiPRINT licences, printing profiles, internal
|
||||
folders, and the local factory network.
|
||||
- Informing the development team about changes to prices, freight, operational
|
||||
rules, or external platforms that need system changes.
|
||||
|
||||
The development team delivers the online system, provides usage guidance, and
|
||||
supports subsequent corrections or scoped enhancements.
|
||||
|
||||
## Three-week roadmap
|
||||
|
||||
| Week | Delivery | Result |
|
||||
|---|---|---|
|
||||
| 1 | Infrastructure and upload | VPS, domain, database, R2, multipart upload, antivirus, and service foundation. |
|
||||
| 2 | Payment, freight, and order | Mercado Pago, freight quotation, idempotent Tiny/Olist order creation, final file generation, and main Kanban states. |
|
||||
| 3 | Kanban and handover | Online Kanban, secure download, WhatsApp status messages, 30-day retention, and operational handover. |
|
||||
|
||||
## 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)
|
||||
|
||||
Dropstar's three folders (asked 2026-10-23, agreed 2026-10-26): the Kanban,
|
||||
open in Chrome or Edge on a factory computer that reaches the server's
|
||||
folder, signed in with a profile that sees every order (Gestão), keeps the
|
||||
orders' files in three folders it creates inside the one chosen in
|
||||
Integrações ("Pastas dos pedidos"), numbered to sort in the flow's order:
|
||||
"1. Arte recebida" (the file arrives when the order does), "2. Arte
|
||||
conferida" (the queue; the file moves there with the card and stays while it
|
||||
prints and is checked in Revisão) and "3. Finalizado" (when the order is
|
||||
released, kept 30 days there). They are created as soon as the main folder
|
||||
is chosen. Correção, a cancellation or a
|
||||
deletion takes the file out; a replaced final is swapped. Orders already
|
||||
printing when the folder is chosen are not downloaded; every order paid after
|
||||
it is, whatever its stage, so a computer that was off catches up when it
|
||||
comes back (Dropstar's rules, 2026-10-26: the folder must reproduce what
|
||||
passed, not only what sits in the columns). A file someone took
|
||||
out is fetched again only when its order moves on (`POST
|
||||
/api/operator/queue/folder`, which also returns the files of orders the
|
||||
folders hold once they print). Who opens each folder is set in the server's
|
||||
folder permissions. Firefox cannot write into folders: it only downloads the
|
||||
files entering Arte conferida.
|
||||
|
||||
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, 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; Dropstar moved it to 4 GB on 2026-10-28: ClamAV scans
|
||||
up to its 2000 MiB, a larger file passes by the format check); a Designer profile
|
||||
(artwork stages only, every order, no machine, queue or cancelling; MOVES
|
||||
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. A ready sheet with a
|
||||
residue (ink under 2 mm on both sides, measured in pixels from the ink map in
|
||||
web/site-sheet.js) or without transparency (under 1,5 % of transparent
|
||||
pixels; every JPG) cannot be paid for; the preview circles each dot. PDFs
|
||||
over 150 MB and CDR/AI/PSD/TIFF are not checked. The generated print PDF ends
|
||||
in a 1,5 cm footer band below the layout, outside the billed length: "DROPSTAR
|
||||
· Pedido DTF-<Kanban number> · Item 1/2 · date · billed metres" in black
|
||||
Helvetica, after Dropstar's logo (app/assets), about 1 cm tall (31 pt, Dropstar
|
||||
2026-10-28; smaller only when it would not fit the 27 cm UV film). A sheet
|
||||
longer than 5,08 m (Acrobat's page limit) is written at its real size on one
|
||||
page since 2026-10-28: with PDF's /UserUnit scale, CorelDRAW, where Dropstar
|
||||
checks files, showed a 12,8 m sheet as 18,9 x 425 cm. PRINT_PAGE_SCALE=true
|
||||
in the stack goes back to /UserUnit, for a RIP that refuses pages over 5,08 m. An original used whole as its
|
||||
own print file (over 300 MB) has no footer. The print proof (app/proof.py):
|
||||
an order above 10 m, or one whose customer ticked "quero aprovar uma prova" at
|
||||
checkout (that one arrives marked Aguardando contato; the box shows, and the
|
||||
server keeps it, only above 10 m since 2026-10-28), cannot reach Finalizado
|
||||
before the print room marks Prova OK; the proof is not billed (up to 30 cm,
|
||||
at most 3 per order). Dropstar's answers of 2026-10-23: JPG is refused in every
|
||||
product; a PDF over 150 MB is flagged before payment; any non-square piece is
|
||||
tried both ways; a mirrored (UV) order is flagged on the card and in the PDF
|
||||
footer; files are named DTF-<number>-item-<n>, the code the Kanban copies;
|
||||
manual files cost R$ 2,00 more a metre. Also settled by Dropstar on
|
||||
2026-10-23: no seller on Tiny orders (Tiny sets it from the contact; the
|
||||
marcador SITE DTF separates the channel), the DTF terms page approved, the UV
|
||||
mirror stays, the designer does not move to the print queue, and Aguardando
|
||||
contato has no deadline of its own. There is no videocall: open points are
|
||||
settled in writing.
|
||||
|
||||
Done on 2026-10-26: the single price per product Dropstar asked for on
|
||||
2026-10-23 (see Commercial rules), on the Site and the server.
|
||||
|
||||
Dropstar's flow of 2026-10-23, in the code since 2026-10-26 (app/runtime.py,
|
||||
app/core/auth.py): the board is Arte recebida, Arte conferida, Imprimindo,
|
||||
Correção, Revisão, Finalizado. Fila de impressão left: Arte conferida is the
|
||||
queue, entered only with every item's final file approved, kept as approved
|
||||
there (to change one, the order goes back to Arte recebida), with its card
|
||||
order as the print order and "Baixar" for the room; orders that were in the
|
||||
queue were moved to Arte conferida with a line in their history. Who moves
|
||||
what (MOVES): the Designer Arte recebida to Arte conferida, asks for
|
||||
corrections and brings the new art back to Arte recebida or Arte conferida;
|
||||
the Operador Arte conferida to Imprimindo to Revisão; the Revisor Revisão to
|
||||
Finalizado, so nobody in the room releases their own print, and the
|
||||
Administrador may release too (the user, 2026-10-28; the superadmin for
|
||||
support); Gestão, the coordination, only pulls back, always with a reason
|
||||
(rule D-20 of Dropstar's internal rules, 2026-10-26): Correção from any
|
||||
stage, or a step back; Admin, Dropstar's own login, every other move,
|
||||
including Correção straight to Revisão. A step back belongs to whoever makes
|
||||
the move it undoes, and to Admin and Gestão. Tiny: Arte
|
||||
conferida sets "Preparando envio" and Finalizado "Pronto para envio", for
|
||||
delivery orders too; nothing for Imprimindo, Correção or Revisão. Prova OK
|
||||
still comes before Finalizado. The customer's portal shows the same steps.
|
||||
|
||||
Still to do (2026-10-26):
|
||||
- The DTF number in Tiny's `numeroPedidoEcommerce`: sent since 2026-10-26,
|
||||
next to the purchase order `numeroOrdemCompra` (which the resend check
|
||||
searches). Tiny keeps it only with a channel: `TINY_ECOMMERCE_ID=9594`,
|
||||
Dropstar's "API do ERP" integration (installed 2026-10-27). The store's own
|
||||
channel (DROPSTAR, 9336) refuses orders sent through the API. Confirmed
|
||||
with test order 145329.
|
||||
- Before TINY_STATUS_UPDATES goes on: Finalizado now sets "Pronto para
|
||||
envio" on delivery orders too, so the client's n8n must not send them the
|
||||
pickup message it sends on that situação.
|
||||
- Dropstar creates the Revisor users right after the redeploy that brings the
|
||||
new flow (the profile exists only from then): until then orders wait in
|
||||
Revisão, and only the superadmin can release them.
|
||||
- Done 2026-10-27, from Dropstar's answers on their internal rules: "Arte
|
||||
tratada", an order whose approved final is not the customer's art (not the
|
||||
file generated from it, not an original, not a correction they sent), is
|
||||
flagged on the card and in the order, and Números counts those orders by who
|
||||
approved the final, for the designer's productivity; a cancelled order's
|
||||
money stays as the customer's credit in their financial control (D-15, the
|
||||
Kanban's cancel text says so, nothing on the Site); the Kanban keeps
|
||||
deleting Finalizado files after 30 days; the footer gets the white spot.
|
||||
- Every order has an origin (Dropstar's rules D-21 and D-35, 2026-10-26):
|
||||
`site`, `dropflow` or `atendimento`, in dtf_local.orders.origin, required
|
||||
and without a default (a default would become the origin of almost
|
||||
everything, the document says), limited to the three by a check. The Site's
|
||||
orders are marked `site` where they are created (app/payments.py); the
|
||||
orders from before the column became `site`. The Kanban shows it on every
|
||||
card and in the order panel, filters by it (Origem), and Números has a "Por
|
||||
origem" table: orders, metres, money received and the median time from
|
||||
payment to Finalizado for each way in, Aguardando contato left out.
|
||||
- An order paid outside the system is registered from its Site quote (D-35;
|
||||
the user's answers of 2026-10-27): the team builds the cart on the Site as
|
||||
a customer would (the art comes in through the Site, D-08), stops at the
|
||||
payment step, and in the Kanban's Cotações, on the approved quote, picks the
|
||||
origin and how it was paid (Pix, cartão, dinheiro, crédito do cliente),
|
||||
neither preselected, with an optional note. The price is the quote's, the
|
||||
Site's table price. Allowed to Administrador and Gestão (the "enter"
|
||||
capability); not Vendedor, who only views the board (D-30). The order's payment is `{'provider': 'manual',
|
||||
'method', 'note', 'operator'}`; it counts in Números like any paid order and
|
||||
the customer gets the usual paid e-mail. An Atendimento (or Site) order
|
||||
goes to Tiny like a Site one, its internal note saying "pago fora do site"
|
||||
and how, each way named as Tiny's forma de recebimento (Pix, cartão, and
|
||||
from Marcus on 2026-10-27 Dinheiro 919478944 and, for the customer's credit,
|
||||
their "CORREÇÃO DTF" 977493654; RECEIPT_METHODS in app/tiny.py). A Dropflow
|
||||
order goes to Tiny too, in its own revenue category "DTF DROPFLOW"
|
||||
(987032506, CATEGORIES in app/tiny.py), not DTF SITE (D-21).
|
||||
- Rework register (Dropstar's rules D-02 to D-04; the user's answers of
|
||||
2026-10-27), dtf_local.reworks. Gestão opens it from the order panel's menu
|
||||
("Abrir retrabalho") with its cause, the metres redone (the order's printed
|
||||
metres to start) and a note: falha de impressão, perfil de cor, erro de
|
||||
tratamento, erro de pedido, or arte aprovada pelo cliente (outside the
|
||||
goal, D-04). The cause never changes after (D-03: there is no route for it).
|
||||
An Administrador authorizes it or declines it with a reason, never one they
|
||||
opened; the reprint is never held up, and only an authorized rework counts.
|
||||
Who printed it (who last sent the order to Revisão) is kept, as the house's
|
||||
rework enters the printer's pay. Números, "Retrabalho": per cause, the
|
||||
metres redone over the film printed in the period (Por máquina), by the day
|
||||
the rework was opened, against 0,4% per cause and 1,6% for the house; the
|
||||
house's by who printed it; and the ones waiting for authorization. A card
|
||||
with a rework carries a "Retrabalho" badge.
|
||||
- Still open from the internal rules (docs received 2026-10-26): customer
|
||||
credit as a payment the system keeps track of (today "crédito do cliente"
|
||||
is only how a registered order was paid). Done 2026-10-27: the folders catch up on what passed while the Kanban
|
||||
computer was off, time in "Aguardando contato" no longer counts in Números'
|
||||
time figures (D-38; each wait is kept in dtf_local.contact_waits, from mark
|
||||
to clear), and a file's type comes from its first bytes (D-13, see the
|
||||
commercial rules).
|
||||
- Settled on 2026-10-26: the DTF SITE category (986932924, CATEGORY in app/tiny.py),
|
||||
the white spot also under the print PDF's footer (nothing to change here),
|
||||
and the montador's order format (customer, files, product, the batch with
|
||||
the customer's ERP sale numbers, labels or pickup) with a record of each
|
||||
batch, both for after launch.
|
||||
- The three folders, once deployed: Marcus sets the main folder on the
|
||||
factory computer (Chrome, Integrações > Pastas dos pedidos); check on the
|
||||
first print whether FlexiPRINT keeps reading the file in Arte conferida
|
||||
after import (the file only leaves that folder at Finalizado).
|
||||
- Anchor-customer orders from the montador: after the launch; the team's idea
|
||||
is that Graphs handles that side and sends the orders to this Kanban.
|
||||
|
||||
### Active localhost milestone (2026-09-15)
|
||||
|
||||
The current implementation target is localhost before any production connection.
|
||||
Use `docker-compose.yml`, `.env.example`, and `LOCAL_SETUP.md`. The runtime is in
|
||||
`app/`; historical `portal/`, `kanban/`, `agente/`, and `schema.sql` are preserved
|
||||
as references and are not imported or started by Compose.
|
||||
|
||||
- One local `dtf-cloud` Compose project runs seven long-lived services: Site and
|
||||
Kanban web gateways, FastAPI Portal/API, PostgreSQL, MinIO, ClamAV, and a
|
||||
PostgreSQL outbox/scanning worker. Separate database and storage initialization
|
||||
jobs provision restricted runtime identities, for nine Compose services total.
|
||||
- MinIO implements the S3 storage boundary with direct multipart browser uploads,
|
||||
resumable parts, private objects, and short-lived signed operator downloads.
|
||||
- Payment, freight, and Tiny/Olist use fake adapters only. No production
|
||||
credentials or integrations are configured. The API and worker have no external
|
||||
network route; only local web/storage gateways publish loopback ports.
|
||||
- The original Site commercial calculation and appearance remain the source of
|
||||
truth. Its existing browser artwork analysis is retained as prototype advice;
|
||||
no new automatic pre-flight, server artwork analysis, or print-file generation
|
||||
is implemented or invoked.
|
||||
- Since client length and grade could be tampered with and automatic pre-flight
|
||||
is deferred, a local operator manually confirms those commercial inputs before
|
||||
checkout. This is a development trust-boundary decision, not a new production
|
||||
promise. The backend calculates all tiers, discounts, assembly-inclusive rates,
|
||||
one-metre minimum, ten-centimetre rounding, freight, and final totals. Immutable
|
||||
approved quotes expire after 24 hours. A customer confirms the server total
|
||||
on the Site to create one idempotent local paid order.
|
||||
- Paid orders use `rec`, `tra`, `imp`, `cor`, `rev`, `fin` (`fil` until 2026-10-26), with allowed transitions,
|
||||
operator authentication, concurrency checks, and durable movement history.
|
||||
Local mock integration receipts are visible in the Kanban.
|
||||
- The customer portal at `/portal.html` supports local registration/login,
|
||||
stronger scrypt password hashing with legacy-hash upgrade, revocable HttpOnly
|
||||
sessions, owned order history/status, secure active
|
||||
file downloads, and correction uploads. Registration/login claims the current
|
||||
guest session's records and, once the account's e-mail is confirmed with a
|
||||
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
|
||||
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
|
||||
editor and cross-device cart synchronization are not implemented. Browser
|
||||
storage capacity limits apply. Payment clears the saved cart. Logout revokes
|
||||
the server session and clears local checkout metadata and saved File blobs
|
||||
across open Site tabs.
|
||||
- Operators manually upload and approve a complete final-file set, with one or
|
||||
more files per order item. Queue entry requires active final files for every
|
||||
item. Corrections invalidate the old set; customers submit corrections through
|
||||
their portal, and operators reapprove final files. No artwork transformation,
|
||||
automatic pre-flight, or machine control is performed.
|
||||
- Every completed upload is quarantined pending a local ClamAV scan. Only `clean`
|
||||
files can be quoted, commercially approved, paid, downloaded, attached as final
|
||||
files, or admitted to the print queue. Rejected/error files remain blocked and
|
||||
expire within three days. The isolated scanner uses signatures bundled in its
|
||||
pinned image and has no external network route. The multipart transport could
|
||||
carry 5 GiB, but API and customer admission stop at the effective 128 MiB
|
||||
scan/release limit by default. Larger files require a new scan/release design.
|
||||
This malware gate is not print pre-flight or artwork validation.
|
||||
- A retention worker removes expired object bytes but keeps order/file metadata:
|
||||
incomplete uploads after a one-hour reservation lease, originals within seven days of manual final
|
||||
artwork approval, and attached final/correction files within 30 days of the
|
||||
order's first upload. Storage lifecycle is also a 30-day backstop.
|
||||
- Structured security events are written to logs and PostgreSQL. The local
|
||||
`security_status` command summarizes authentication, rate-limit, scan, and
|
||||
scanner/signature alerts without exposing secrets. Security regression tests,
|
||||
exact-runtime Python dependency auditing, and Trivy image reports live under
|
||||
`app/` and `output/security/`; open findings are documented in
|
||||
`SECURITY_REPORT.md` and are not a production-readiness claim.
|
||||
- All direct and transitive Python packages are pinned with artifact hashes in
|
||||
`infra/requirements.lock`; the API image build requires those hashes. The lock
|
||||
is regenerated in a disposable Python 3.12 container by
|
||||
`infra/lock_dependencies.sh`. A fresh exact-runtime audit found no known Python
|
||||
advisories on 2026-09-15; this does not cover OS/container findings.
|
||||
- `compose.staging.yaml` is a separate, network-disabled readiness gate only. It
|
||||
validates non-secret staging decisions and rejects placeholders, local endpoints,
|
||||
fake providers, embedded secret settings, and unsafe secret sources. It does not
|
||||
deploy the application, contain credentials, or contact any real provider.
|
||||
- A separate production delivery package now exists under `deploy/`, with
|
||||
non-root API/web image definitions, a single Portainer Docker Swarm stack,
|
||||
external secret/volume contracts, health-monitored rolling updates,
|
||||
commit-SHA rollback images, and one protected Gitea workflow under
|
||||
`.gitea/workflows/`. The package never contains provider credentials and has
|
||||
not been deployed. Its fail-closed preflight intentionally rejects the current
|
||||
source until production adapters, Docker-secret file loading, approved inputs,
|
||||
restore rehearsal, image scans, and human security approval are complete.
|
||||
- `python3 -m ops.backup create-and-verify` creates a private, Git-ignored bundle
|
||||
containing a PostgreSQL dump plus every complete, unexpired object already marked
|
||||
`clean`. SHA-256 manifests protect both parts. Verification restores the database
|
||||
under a UUID name and the object bytes under a UUID MinIO prefix, hashes the
|
||||
restored bytes, then removes only those temporary targets. Active data is never
|
||||
overwritten; pending, rejected, errored, expired, and purged objects are excluded.
|
||||
Run this local snapshot while uploads and retention are idle. Scheduling, offsite
|
||||
copies, and production restore operations remain unfinished.
|
||||
- Real providers, production authentication hardening, email verification/recovery,
|
||||
automatic final-file generation, production backup operations, and production
|
||||
activation remain incomplete. Deployment plumbing exists but cannot pass its
|
||||
release gate yet. No factory automation or pre-flight is added.
|
||||
|
||||
See `docs/historico/IMPLEMENTATION_REPORT.md` for verification, `PRODUCTION_INPUTS.md` for the
|
||||
decisions and evidence required before staging or production connection, and
|
||||
`PORTAINER.md` for the production delivery contract.
|
||||
The client roadmap promises are unchanged, so its PDF source is not regenerated
|
||||
for this local implementation checkpoint.
|
||||
|
||||
### Existing assets
|
||||
|
||||
- `web/`: the Site (`index.html`), the Kanban and customer portal pages, and
|
||||
the scripts behind them. `web/site-*.js` holds the Site's behaviour.
|
||||
- `docs/historico/`: the original specification, endpoint sketch, task plan and
|
||||
status report. Background only — they describe a model this system does not
|
||||
implement.
|
||||
|
||||
The prototypes they describe (`portal/`, `kanban/`, `agente/`, the root
|
||||
`schema.sql` and `.env.exemplo`) were removed on 2026-09-21 once nothing
|
||||
referenced them; recover from Git history if ever needed.
|
||||
- `tools/generate_dtf_report.py`: generator for the client-facing roadmap PDF.
|
||||
- `docs/roadmap-cliente.pdf`: the generated roadmap, as last sent.
|
||||
- `docs/reuniao-2026-09-09-anotacoes.pdf`:
|
||||
meeting notes that established the business direction. Treat it as context;
|
||||
the latest decisions in this document define the active scope.
|
||||
|
||||
### Important gaps and stale assumptions
|
||||
|
||||
- The original Site had no backend payment, freight quote, order persistence,
|
||||
authentication, purchase history, or real cart persistence. Local order
|
||||
persistence, reviewed quotes, mock freight and fake payment now work through
|
||||
`web/checkout.js`. The local customer portal now provides accounts and
|
||||
order history; cart recovery is browser-local. Password recovery by e-mail
|
||||
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.
|
||||
Real freight quotation remains unimplemented in all runtimes.
|
||||
- The existing the removed prototypes duplicated WhatsApp senders and send
|
||||
direct text messages. They are not production-ready notification modules.
|
||||
- Older documentation and code describe a Tiny webhook creating an upload link,
|
||||
a factory agent, local Kanban, FlexiPRINT automation, 90-day retention, and
|
||||
12-month artwork reuse. Those are not the current MVP model.
|
||||
|
||||
## Documentation synchronization
|
||||
|
||||
`context.md` is the compact operating context for agents. The current
|
||||
client-facing narrative, diagrams, and formatting live in
|
||||
`docs/roadmap-cliente.pdf`, generated from `tools/generate_dtf_report.py`.
|
||||
|
||||
When a decision changes, update both the relevant implementation context here
|
||||
and the roadmap source when it changes what the client-facing plan promises.
|
||||
|
||||
## Change-control rules for agents
|
||||
|
||||
- Preserve the current Site DTF commercial rules unless explicitly asked to
|
||||
change them.
|
||||
- Do not add factory-side automation, a local agent, hot folders, FlexiPRINT
|
||||
control, machine dashboards, or a new post-MVP delivery commitment by
|
||||
inference.
|
||||
- Do not claim that R2 hosts or executes application services.
|
||||
- Keep all customer-facing and internal documentation in English only when this
|
||||
file is the requested artifact; otherwise follow the user's requested
|
||||
language.
|
||||
- When a requirement is unclear, distinguish between the MVP, a future
|
||||
enhancement, and an existing prototype assumption before changing code.
|
||||
@@ -1,6 +1,6 @@
|
||||
# DTF local development
|
||||
|
||||
Read `CONTEXT.md` first. The current runtime lives in `local/`; older portal,
|
||||
Read `CONTEXT.md` first. The service lives in `app/`; older portal,
|
||||
Kanban, agent, requirements, and SQL files are historical prototypes.
|
||||
|
||||
## Start
|
||||
@@ -51,7 +51,7 @@ operator interfaces.
|
||||
## Browser test order
|
||||
|
||||
1. Open the Site. Choose **Arquivo por metro** and the manual/table-price path
|
||||
(CDR/AI/PSD/TIFF). Select `local/fixtures/local-test.cdr`. This is deliberately
|
||||
(CDR/AI/PSD/TIFF). Select `tests/fixtures/local-test.cdr`. This is deliberately
|
||||
harmless text for upload testing, not a printable CDR file.
|
||||
2. Enter **1.01 metres**. The original calculation bills **1.10 m × R$19.90 =
|
||||
R$21.89**, with grade 0 and pickup. You can also use your own non-sensitive
|
||||
@@ -62,23 +62,35 @@ operator interfaces.
|
||||
4. Click the Site checkout button. Files upload directly to MinIO, remain
|
||||
quarantined until ClamAV returns `clean`, and then become eligible for a quote.
|
||||
The local banner displays a quote ID awaiting commercial review.
|
||||
5. Open Kanban and log in. In **Cotações**, download the original if needed,
|
||||
confirm/correct total metres and grade, tick the manual confirmation, and
|
||||
click **Aprovar cotação**. For the fixture keep 1.01 m and grade 0.
|
||||
5. Open Kanban and log in. Open the **Cotações** tab, pick the quote, download
|
||||
the original if needed, confirm/correct metres and grade, tick the
|
||||
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
|
||||
authoritative server total, then click **Criar pedido de teste**. No real
|
||||
payment occurs.
|
||||
7. Refresh Kanban. The paid order starts in **Arte recebida**. Move it using
|
||||
the buttons or drag and drop to **Arte tratada**. Open **Arquivos de produção**,
|
||||
select the manually prepared final files for every item, enter a review note,
|
||||
tick the confirmation and click **Aprovar arquivos finais**. Use the harmless
|
||||
fixture again only for this local test; no printable file is generated.
|
||||
Continue through **Fila de impressão →
|
||||
Imprimindo → Finalizado**. A move to **Correção** requires a reason; it can
|
||||
return to **Arte recebida** or **Arte tratada**. Finalizado is terminal locally.
|
||||
8. Inspect **Histórico** and **Eventos locais de integração**. Worker receipts
|
||||
should say recorded locally. Download links expire after five minutes;
|
||||
request another link from Kanban when needed.
|
||||
7. Click **Atualizar** on the Kanban. The paid order appears in **Arte
|
||||
recebida** on the **Produção** tab. Click its card to open the order panel,
|
||||
then **Mover para Arte conferida** (dragging the card to a column also works).
|
||||
In the panel's **Arquivos finais**, select the manually prepared final file
|
||||
for every item, enter a review note, tick the confirmation and click
|
||||
**Aprovar arquivos finais**. Use the harmless fixture again only for this
|
||||
local test. The text fixture is not an image, so its print file shows
|
||||
**Preparar à mão**; with a PNG, JPEG or PDF artwork the generated file is
|
||||
preselected instead (see "Print files"). Continue with the panel's main
|
||||
button through **Fila de impressão → Imprimindo → Finalizado**. **Pedir
|
||||
correção** asks for the reason the customer will see; from **Correção** the
|
||||
order returns to **Arte recebida** or **Arte conferida**. A move made by
|
||||
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
|
||||
automatic pre-flight is deferred. Browser measurements and grade are proposals.
|
||||
@@ -97,7 +109,7 @@ final files are separately labeled. Never print the local text fixture.
|
||||
## Customer accounts, corrections, and cart recovery
|
||||
|
||||
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
|
||||
on successful login. Sessions are stored in PostgreSQL, expire after
|
||||
seven days, and are revoked on logout. Login/registration attempts are limited.
|
||||
@@ -135,15 +147,15 @@ Pricing parity requires Python 3.10+ and Node 22+ on the host, no package instal
|
||||
python3 -m unittest local.test_pricing -v
|
||||
```
|
||||
|
||||
This executes the real pricing constants/functions extracted from `dtf-site.html`
|
||||
This executes the real pricing constants/functions extracted from `web/site-config.js`
|
||||
and compares all four modes, 101 grades, and 11 lengths (4,444 cases) to backend
|
||||
pricing, plus assembly and invalid-input checks.
|
||||
|
||||
With the stack healthy, run the integration test (Python standard library only):
|
||||
|
||||
```bash
|
||||
python3 -m local.smoke_test
|
||||
python3 -m local.workflow_test
|
||||
python3 -m tests.smoke_test
|
||||
python3 -m tests.workflow_test
|
||||
```
|
||||
|
||||
It checks direct two-part upload/resume, missing parts, session isolation,
|
||||
@@ -155,14 +167,22 @@ The workflow test also checks guest-to-account migration, cross-session login,
|
||||
revoked sessions, ownership isolation, correction submissions, final revision
|
||||
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
|
||||
test is unmistakable:
|
||||
|
||||
```bash
|
||||
python3 -m local.security_test
|
||||
python3 -m local.scanning_test
|
||||
docker compose exec -T api python -m local.runtime_security_test
|
||||
docker compose exec -T api python -m local.retention_test
|
||||
python3 -m tests.security_test
|
||||
python3 -m tests.scanning_test
|
||||
docker compose -f compose.local.yaml exec -T api python3 -m tests.runtime_security_test
|
||||
docker compose -f compose.local.yaml exec -T api python3 -m tests.retention_test
|
||||
```
|
||||
|
||||
`local.scanning_test` stores an EICAR fixture as `SECURITY-EICAR.cdr`; ClamAV
|
||||
@@ -172,7 +192,7 @@ is retained for at most three days, so it temporarily appears in alert summaries
|
||||
For an automated real-browser walkthrough, install Chrome and use Node 22+:
|
||||
|
||||
```bash
|
||||
node local/browser_test.mjs
|
||||
node tests/browser_test.mjs
|
||||
```
|
||||
|
||||
Set `CHROME_BIN` if Chrome is not at `/usr/bin/google-chrome-stable`. The test
|
||||
@@ -183,23 +203,27 @@ test order for inspection. Both integration scripts read `.env` automatically.
|
||||
## Configuration and storage
|
||||
|
||||
`.env.example` lists local ports, database/MinIO values, operator login, adapter
|
||||
selection, mock freight amount, maximum file size (5 GiB), and multipart size
|
||||
(8 MiB by default). The malware scanner releases only files up to 128 MiB by
|
||||
default (`SCAN_MAX_BYTES`); larger uploads remain blocked even though the
|
||||
multipart transport supports 5 GiB. `S3_ENDPOINT=http://storage:9000`, database
|
||||
selection, mock freight amount, transport ceiling (5 GiB), and multipart size
|
||||
(8 MiB by default). The API and customer picker admit only files within the
|
||||
malware scanner's effective 128 MiB limit by default (`SCAN_MAX_BYTES`); the
|
||||
larger-file path remains a Week 2 decision. `S3_ENDPOINT=http://storage:9000`, database
|
||||
hostname `db`,
|
||||
and the internal service ports are fixed Compose wiring. The public S3 endpoint
|
||||
must resolve from the browser; keep `http://localhost:9000` for this stack.
|
||||
Parts use 15-minute presigned URLs and uploads must finish within one day.
|
||||
Parts use 15-minute presigned URLs and unfinished reservations expire after
|
||||
one hour. Clients can cancel a reservation through the upload DELETE endpoint.
|
||||
|
||||
Only fake integration adapters and `s3-local` storage are accepted. Startup fails
|
||||
if a production adapter/environment or nonlocal S3 endpoint is selected.
|
||||
Fake integration adapters and `s3-local` storage are the default. Mercado Pago
|
||||
and Tiny can be selected for sandbox testing only (see "Provider sandboxes");
|
||||
startup fails if their credentials are missing, if any other adapter is
|
||||
selected, or if a production environment or nonlocal S3 endpoint is used.
|
||||
The API, worker, and database run on an internal Docker network; web gateways
|
||||
and MinIO also join a network that permits loopback port publishing.
|
||||
|
||||
Objects are private, use UUID keys rather than filenames, and persist in a named
|
||||
volume. MinIO lifecycle rules expire objects after 30 days and abandon incomplete
|
||||
multipart uploads after one day; the API also blocks expired downloads. Order
|
||||
multipart uploads after one day as a backstop; the API lease and worker release
|
||||
unfinished reservations after one hour. The API also blocks expired downloads. Order
|
||||
history remains in PostgreSQL. Completed files start in `pending`; unknown,
|
||||
scanner-error, over-limit, encrypted/unsafe, and malware results fail closed.
|
||||
Only `clean` files can cross quote, payment, download, final-approval, and queue
|
||||
@@ -214,10 +238,132 @@ storage permits; otherwise reselect them. Saved quote IDs also survive reloads.
|
||||
Clearing cookies loses a guest session, while registered customers can sign in
|
||||
again. The operator can still inspect order records.
|
||||
|
||||
## Print files
|
||||
|
||||
Every paid order queues one print-file job per item. The worker renders a PDF
|
||||
exactly as wide as the film and as long as the approved layout, placing each
|
||||
copy at the position, rotation and mirror the customer reviewed. Each source
|
||||
image is embedded once at its original resolution (JPEG bytes unchanged, PNG
|
||||
transparency kept as a soft mask), so nothing is resampled. The Kanban card
|
||||
shows the status per item, the page size and the lowest DPI, and offers
|
||||
**Baixar PDF**. In **Arquivos de produção** the generated file is preselected
|
||||
as the final file; untick it to upload one by hand instead.
|
||||
|
||||
JPEG, PNG, WebP and TIFF are embedded as images. A single-page PDF is placed
|
||||
as a vector form (never rasterised), using the page's CropBox and `/Rotate`
|
||||
exactly as the Site measured it with pdf.js; the card then shows **PDF
|
||||
vetorial**. PSD, AI and CDR artwork, multi-page or password-protected PDFs, a
|
||||
file whose proportions do not match the quoted size, a layout longer than was
|
||||
billed, or an image above `PRINT_MAX_PIXELS` (250 Mpx by default) goes to
|
||||
**preparar à mão** with the reason, and the operator prepares it as before.
|
||||
**Gerar arquivos de impressão** retries those items and generates files for
|
||||
orders paid before the generator existed. After a customer correction the
|
||||
generated file is no longer offered: it reproduces the replaced artwork.
|
||||
|
||||
Layouts longer than about 5 m use the PDF `UserUnit` page scale instead of
|
||||
being split into pages. Confirm on the factory's FlexiPRINT that such a file
|
||||
imports at full length before relying on it for long orders.
|
||||
|
||||
```bash
|
||||
docker compose -f compose.local.yaml exec -T api python -m unittest tests.test_printfile -v
|
||||
docker compose -f compose.local.yaml exec -T api python -m tests.print_file_test
|
||||
```
|
||||
|
||||
With PyMuPDF installed locally (`pip install pymupdf`), the unit suite also
|
||||
draws each page and checks where every quadrant of the artwork lands.
|
||||
|
||||
## Provider sandboxes
|
||||
|
||||
`app/mercadopago.py` and `app/tiny.py` follow the providers' public API
|
||||
documentation and pass their unit suites against a fake transport. They are not
|
||||
verified integrations until they pass with the client's accounts.
|
||||
|
||||
The default local stack gives the API and worker no route to the internet, so
|
||||
provider testing adds `compose.providers.yaml`, which does:
|
||||
|
||||
```bash
|
||||
docker compose -f compose.local.yaml -f compose.providers.yaml up -d --wait
|
||||
```
|
||||
|
||||
Put only **test** credentials in `.env`:
|
||||
|
||||
```bash
|
||||
PAYMENT_ADAPTER=mercadopago
|
||||
MP_ACCESS_TOKEN=TEST-...
|
||||
MP_WEBHOOK_SECRET=... # "Assinatura secreta" in the webhook settings
|
||||
MP_NOTIFICATION_URL=https://<public tunnel>/api/payments/webhook
|
||||
```
|
||||
|
||||
### Tiny (API v3)
|
||||
|
||||
Tiny uses OAuth2. In the client's Tiny (Construa plan or above, with the
|
||||
"Gestão de Aplicativos" extension): **Configurações → Geral → Aplicativos →
|
||||
+ novo aplicativo**, with the redirect URL set to this system's callback. That
|
||||
gives a client ID and secret:
|
||||
|
||||
```bash
|
||||
TINY_CLIENT_ID=...
|
||||
TINY_CLIENT_SECRET=...
|
||||
TINY_REDIRECT_URI=http://localhost:8081/api/operator/tiny/callback # exactly as registered in Tiny
|
||||
TINY_PRODUCT_TEXTIL_FOLHA=... # Tiny product id for each Site product
|
||||
TINY_PRODUCT_TEXTIL_AVULSA=...
|
||||
TINY_PRODUCT_UV_FOLHA=...
|
||||
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**.
|
||||
Someone with a Tiny login approves access once; the tokens are stored in the
|
||||
database (the refresh token rotates on every use) and the worker keeps the
|
||||
connection alive. Only then set `TINY_ADAPTER=tiny`, which starts creating an
|
||||
order in Tiny for every paid order: find or create the customer's contact by
|
||||
CNPJ, then `POST /pedidos` with `numeroOrdemCompra = DTF-<order number>`. A
|
||||
retry searches the customer's recent orders for that number first, so it does
|
||||
not create a second one. **Tiny has no sandbox**: every test order is real, so
|
||||
agree the test with the client and cancel the test orders afterwards.
|
||||
|
||||
`tests.tiny_oauth_test` checks the connection flow against the real database
|
||||
with a fake token server; it saves and restores any existing connection.
|
||||
|
||||
With Mercado Pago selected, an approved quote shows **Pagar com PIX** on the
|
||||
Site instead of the local test button, and **Pagar com cartão** when
|
||||
`MP_PUBLIC_KEY` is set. The card form is Mercado Pago's Card Payment Brick: the
|
||||
card is typed into Mercado Pago's secure fields and only a one-time token
|
||||
reaches the API. It loads from Mercado Pago, so the Site's CSP must allow it:
|
||||
|
||||
```bash
|
||||
MP_PUBLIC_KEY=TEST-...
|
||||
PAYMENT_CSP_SOURCES=https://sdk.mercadopago.com https://*.mercadopago.com https://*.mlstatic.com https://*.mercadolibre.com
|
||||
```
|
||||
|
||||
`PAYMENT_CSP_SOURCES` is empty by default, which keeps the Site at
|
||||
`script-src 'self'`. The payment page offers credit card (the default), debit
|
||||
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
|
||||
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
|
||||
notification that cannot become an order, or a refund on an existing order,
|
||||
appears under **Pagamentos que precisam de atenção** on the Kanban until an
|
||||
operator records the resolution.
|
||||
|
||||
## Local backup and restore check
|
||||
|
||||
```bash
|
||||
python3 -m local.backup create-and-verify
|
||||
python3 -m ops.backup create-and-verify
|
||||
```
|
||||
|
||||
This writes a private four-file bundle in `backups/` (ignored by Git and Docker
|
||||
@@ -234,7 +380,7 @@ checks database counts, bundle hashes, every archived object's hash, and the byt
|
||||
downloaded after restore, then removes only the temporary database and objects. It
|
||||
never restores over active data. Keep every bundle file private: it contains
|
||||
customer data, password hashes, and customer artwork. To verify it again, run
|
||||
`python3 -m local.backup verify` followed by the printed
|
||||
`python3 -m ops.backup verify` followed by the printed
|
||||
`backups/...manifest.json` path. Legacy database-only `.dump` backups remain
|
||||
verifiable. Scheduling, offsite copies, and a production restore runbook remain
|
||||
unfinished.
|
||||
@@ -242,7 +388,7 @@ unfinished.
|
||||
After building the current image, test retention with synthetic files:
|
||||
|
||||
```bash
|
||||
docker compose exec -T api python -m local.retention_test
|
||||
docker compose -f compose.local.yaml exec -T api python3 -m tests.retention_test
|
||||
```
|
||||
|
||||
This checks that expired bytes are removed while unexpired files survive. It
|
||||
@@ -251,14 +397,14 @@ cleans up its own synthetic object bytes and retains their metadata.
|
||||
## Operations and troubleshooting
|
||||
|
||||
```bash
|
||||
docker compose logs --tail=100 api worker scanner
|
||||
docker compose restart api worker
|
||||
docker compose ps
|
||||
docker compose down
|
||||
docker compose -f compose.local.yaml logs --tail=100 api worker scanner
|
||||
docker compose -f compose.local.yaml restart api worker
|
||||
docker compose -f compose.local.yaml ps
|
||||
docker compose -f compose.local.yaml down
|
||||
```
|
||||
|
||||
`down` stops the stack and preserves named database/storage volumes. Restart
|
||||
with `docker compose up -d --wait`. Do not add `--volumes` unless you intend to
|
||||
with `docker compose -f compose.local.yaml up -d --wait`. Do not add `--volumes` unless you intend to
|
||||
permanently erase all local orders and artwork. No reset is required for tests.
|
||||
|
||||
Seven long-running services have Docker health checks; the database and storage
|
||||
@@ -270,7 +416,7 @@ exposes `/minio/health/ready`.
|
||||
Run the redacted local alert summary inside the API network namespace:
|
||||
|
||||
```bash
|
||||
docker compose exec -T api python -m local.security_status
|
||||
docker compose -f compose.local.yaml exec -T api python3 -m ops.security_status
|
||||
```
|
||||
|
||||
Exit status 1 means attention is required. Review blocked artwork, rate limits,
|
||||
@@ -306,13 +452,13 @@ Offline PDF previews may fall back to the prototype's manual/table-price path.
|
||||
## Dependency lock
|
||||
|
||||
The API, worker, and database initializer install every Python dependency from
|
||||
`local/requirements.lock` with `--require-hashes`. `local/requirements.txt`
|
||||
`infra/requirements.lock` with `--require-hashes`. `infra/requirements.txt`
|
||||
remains the human-maintained direct dependency list. After deliberately changing
|
||||
a direct pin, regenerate the lock in the same Python 3.12 environment and rebuild:
|
||||
|
||||
```bash
|
||||
./local/lock_dependencies.sh
|
||||
docker compose up --build -d --wait
|
||||
./infra/lock_dependencies.sh
|
||||
docker compose -f compose.local.yaml up --build -d --wait
|
||||
```
|
||||
|
||||
The generator downloads public package metadata in a disposable container and
|
||||
@@ -339,7 +485,7 @@ contracts and owners. See `staging/README.md`.
|
||||
Keep this stack local. Before connecting real services, confirm the production
|
||||
checkout trust workflow, complete `PRODUCTION_INPUTS.md`, and pass the isolated
|
||||
staging-readiness gate. Then implement the actual staging composition using the adapter contracts in
|
||||
`local/adapters.py`: start with private S3 staging storage, CORS, signed multipart
|
||||
`app/adapters.py`: start with private S3 staging storage, CORS, signed multipart
|
||||
contract tests and scoped credentials injected outside Git. Add provider sandbox
|
||||
adapters one at a time. Mercado Pago requires authenticated, signed, idempotent
|
||||
webhook handling before real payment is allowed; Tiny/Olist and WhatsApp need
|
||||
@@ -363,7 +509,7 @@ Run the source-only gate without credentials:
|
||||
python3 deploy/production_preflight.py --source-only
|
||||
```
|
||||
|
||||
It must remain blocked while `local/` supports only local fake adapters and does
|
||||
It must remain blocked while `app/` supports only local fake adapters and does
|
||||
not load Docker secret `*_FILE` settings. Do not bypass or delete this check.
|
||||
After approved production implementations and inputs exist, follow
|
||||
`PORTAINER.md` and `deploy/PRODUCTION_CHECKLIST.md`; release and deployment
|
||||
@@ -4,7 +4,12 @@ DTF follows the same operating model as Graphs and ComporHUB: Gitea builds
|
||||
prebuilt images, pushes them to the Gitea registry, and calls one Portainer
|
||||
webhook. Portainer owns and redeploys one Docker Swarm stack named `dtf-cloud`.
|
||||
|
||||
The production stack is `deploy/stack.yaml`. It contains Site, Kanban, API,
|
||||
The deployed stack is the repository's `docker-compose.yml`, which the
|
||||
`dtf-cloud` Portainer stack points at. It was once accompanied by `deploy/stack.yaml`, a more hardened definition
|
||||
supplying credentials as Docker secrets; that file was removed in favour of one
|
||||
definition. See `ROADMAP.md` 2.12 for the reasoning and what remains open.
|
||||
|
||||
The stack contains Site, Kanban, API,
|
||||
worker, PostgreSQL, ClamAV, and a one-time database initializer. Production uses
|
||||
Cloudflare R2, so MinIO is not part of this stack.
|
||||
|
||||
@@ -12,8 +17,11 @@ Cloudflare R2, so MinIO is not part of this stack.
|
||||
|
||||
The single workflow is `.gitea/workflows/deploy.yml`. Every push and pull request
|
||||
runs static validation, the integration suite against a real stack, and a secret
|
||||
scan. A push to `main` then builds the production images, publishes both `latest`
|
||||
and the full commit SHA, reports their vulnerabilities, and calls Portainer.
|
||||
scan. When all of them pass on a push to `main`, the images are built, scanned
|
||||
and published as both `latest` and the full commit SHA. Nothing is deployed:
|
||||
production changes when someone pulls and redeploys the stack in Portainer. A
|
||||
manual workflow run on `main` does the same and also calls the Portainer
|
||||
webhook, if `PORTAINER_WEBHOOK` is configured.
|
||||
|
||||
What actually gates a deployment:
|
||||
|
||||
@@ -21,17 +29,21 @@ What actually gates a deployment:
|
||||
|---|---|
|
||||
| `py_compile` and the unit tests | yes |
|
||||
| Integration suite on a live stack (smoke, workflow, security, scanning, retention, runtime) | yes |
|
||||
| Browser suites | only when the runner has Chrome; otherwise warns and continues |
|
||||
| Browser suites | yes; Chrome runs in the Compose test container |
|
||||
| Trivy secret scan (HIGH/CRITICAL) | yes |
|
||||
| Source preflight (`deploy/production_preflight.py --source-only`) | only when `ENFORCE_PRODUCTION_PREFLIGHT` is `true` |
|
||||
| Source preflight (`deploy/production_preflight.py --source-only`) | advisory unless `ENFORCE_PRODUCTION_PREFLIGHT` is `true`, which blocks publishing |
|
||||
| Trivy image vulnerabilities, CRITICAL | yes |
|
||||
| Trivy image vulnerabilities, HIGH | no — reported after the build |
|
||||
| Trivy image vulnerabilities, HIGH | no — reported before publication |
|
||||
| Configured Portainer webhook | no — called on manual runs when present; otherwise redeploy in Portainer |
|
||||
|
||||
The source preflight is advisory by default because it refuses a release while
|
||||
the payment and messaging adapters are fake, which is the deliberate state the
|
||||
stack runs in today. Enforcing it now would block every deployment. Set the
|
||||
repository variable `ENFORCE_PRODUCTION_PREFLIGHT` to `true` once real adapters
|
||||
land, and it becomes a hard gate.
|
||||
The source preflight reports while the payment and messaging adapters are
|
||||
fake. From 2026-09-23 it was enforced on every manual release, and since the
|
||||
adapters are still fake no release could succeed: production kept running
|
||||
older images while `main` moved on. It is now advisory everywhere. Set the
|
||||
repository variable `ENFORCE_PRODUCTION_PREFLIGHT` to `true` once the real
|
||||
adapters are in place, and a blocked preflight then stops images from being
|
||||
published. Before a manual release, run the full configuration
|
||||
preflight below against the actual Portainer values; CI checks source only.
|
||||
|
||||
CRITICAL image findings block. Both images carry none: the bases are pinned by
|
||||
digest, both Dockerfiles upgrade their OS packages, and the web image moved off
|
||||
@@ -55,10 +67,10 @@ Repository secrets:
|
||||
- `REGISTRY_USERNAME` and `REGISTRY_TOKEN` — package write credentials.
|
||||
- `PORTAINER_WEBHOOK` — webhook generated by the `dtf-cloud` Portainer stack.
|
||||
|
||||
The webhook is called only after the gating checks in the table above pass.
|
||||
The webhook is called only after the release gates above pass.
|
||||
`ENFORCE_PRODUCTION_PREFLIGHT` and `TRIVY_IMAGE` are optional repository
|
||||
variables; without them the preflight is advisory and a pinned default scanner
|
||||
image is used.
|
||||
variables; the former affects push checks and the latter defaults to a pinned
|
||||
scanner image.
|
||||
|
||||
## 2. One-time Portainer resources
|
||||
|
||||
@@ -81,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
|
||||
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
|
||||
|
||||
In Portainer select **Stacks → Add stack → Git repository**:
|
||||
@@ -88,7 +118,8 @@ In Portainer select **Stacks → Add stack → Git repository**:
|
||||
- Name: `dtf-cloud`
|
||||
- Repository: this Gitea repository
|
||||
- Reference: `main`
|
||||
- Compose path: `deploy/stack.yaml`
|
||||
- Compose path: `docker-compose.yml` (the repository default, which is what the
|
||||
existing `dtf-cloud` stack uses; it must stay at the root for this reason)
|
||||
- Registry: the private `gitea.blyzer.com.br` registry
|
||||
- Re-pull image: enabled
|
||||
- Automatic update: webhook
|
||||
@@ -118,10 +149,13 @@ The `db-init` service completing and stopping is expected. The other six
|
||||
services must be healthy. A failed `db-init` task or an unhealthy service blocks
|
||||
acceptance.
|
||||
|
||||
## 4. Normal deployment
|
||||
## 4. Manual deployment
|
||||
|
||||
Push to `main`. Gitea validates, tests, scans, publishes these images, and calls
|
||||
the webhook:
|
||||
Push the reviewed commit to `main` and wait for its validation workflow to pass.
|
||||
After validating the actual Portainer configuration with the full preflight in
|
||||
section 3, use Gitea Actions to manually run **Build and deploy** on `main` at
|
||||
that commit. The workflow repeats validation, tests and scans, then publishes
|
||||
these images and calls the webhook:
|
||||
|
||||
```text
|
||||
gitea.blyzer.com.br/blyzer/dtf-api:latest
|
||||
@@ -141,6 +175,54 @@ 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.
|
||||
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). The default is 200, R$ 2,00 a metro
|
||||
(Dropstar, 2026-10-23); a value set in the stack's environment overrides it.
|
||||
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
|
||||
|
||||
This is the final deployment shape, but it is not authorized for production
|
||||
15
docs/README.md
Normal file
@@ -0,0 +1,15 @@
|
||||
# Documents
|
||||
|
||||
| File | What it is |
|
||||
|---|---|
|
||||
| `reuniao-2026-09-09-anotacoes.pdf` | Meeting notes that set the business direction: the bottleneck, the 24h goal, the automation and payment decisions. Still the record of what was asked for. |
|
||||
| `roadmap-cliente.pdf` | The client-facing plan, as last sent. Generated by `tools/generate_dtf_report.py`; regenerate rather than edit. |
|
||||
| `historico/` | The original specification and prototype documents. Background only — they describe a model this system does not implement. |
|
||||
|
||||
Current engineering documents live at the repository root: `CONTEXT.md` for how
|
||||
the system works, `ROADMAP.md` for what is outstanding, `LOCAL_SETUP.md` to run
|
||||
it, `PORTAINER.md` to deploy it, `SECURITY_REPORT.md` and `PRODUCTION_INPUTS.md`
|
||||
for the security position and the decisions still owed by the client.
|
||||
|
||||
Weekly client reports are deliverables, not repository content. They are produced
|
||||
for a specific week and are deliberately not versioned here.
|
||||
85
docs/REMEDIATION-2026-09-22.md
Normal file
@@ -0,0 +1,85 @@
|
||||
# DTF remediation register — 2026-09-22
|
||||
|
||||
This is the action list for all 37 findings in [the September 21 review](REVIEW-2026-09-21.md). That review contains the evidence and severity for each ID. This register includes the September 22 payment review. It is a plan, not evidence that a finding has been closed in production.
|
||||
|
||||
**Current position:** We are in Week 2. The local fixes for foreign-quote order disclosure and approval without a verified amount are implemented and tested, but are not committed or deployed. The first order-correctness slice now covers parts of findings 2, 5–8, and 11; see the progress note below. The remaining work and production verification stay open. Payment webhook work is partial progress on finding 31, not completion of real payments.
|
||||
|
||||
**Local progress, 2026-09-22:** Browser and API regressions covered stale editor items, DPI refusal and warning acknowledgement, changed-cart quote actions, oversized width, and finals invalidated by a later correction. A versioned per-file source specification survived quote review into the order snapshot. At that point exact placement coordinates and a generated print file were still missing. None of these changes is a production release.
|
||||
|
||||
**Local progress, 2026-09-23:** Specification v2 adds per-copy film coordinates, validates every copy and the quote height, and keeps a downloadable layout manifest in the approved order. The board now pages pending and approved unpaid quotes; a local regression reached all 105 pending and 22 approved fixture quotes. Final print-file generation, completed-order search, and quote cancellation/expiry lifecycle remain open.
|
||||
|
||||
**Operational progress, 2026-09-23:** Finding 23's entrypoints are repaired locally. The staging gate passed in a network-disabled image with non-secret fixture data; `ops.security_status` ran in the API image and correctly reported stale local signatures; `ops.backup create-and-verify` restored database counts and 78 clean objects in isolated temporary targets; the production API image built and imported `ops`. This verifies the commands, not production offsite recovery (finding 30) or a fresh scanner (finding 17).
|
||||
|
||||
**Quality progress, 2026-09-23:** Findings 9 and 10 are partly repaired: failed image decoding blocks checkout, mixed analyzed/manual sheets stay at table price, and rotated DPI uses the correct pixel axis. PDF measurement now uses the PDF.js page model with effective crop, rotation, UserUnit and page count; invalid or multi-page files block quoting. The same-origin PDF worker and isolated browser checks pass. Unsupported image operators, representative print-file evidence and final printability remain open.
|
||||
|
||||
**Upload progress, 2026-09-23:** The API and customer picker now reject files above the effective ClamAV stream limit before transfer, and the session advertises that limit. Unfinished reservations have a one-hour lease and a customer/operator cancel endpoint; owner-scoped cancellation has an integration check. Quota remains reserved until the object is actually purged, so a failed cleanup cannot admit unaccounted storage. PDF rendering now destroys the parser job when its timeout fires, covered by a browser check. This closes the misleading upload-then-quarantine path locally but does not satisfy the agreed large-file capability in finding 3. A tested large-file scan/release design, stronger anonymous admission controls (finding 16), and remaining browser resource bounds (finding 12) are still required.
|
||||
|
||||
## Gates
|
||||
|
||||
| Gate | Meaning |
|
||||
|---|---|
|
||||
| **W2** | Fix during Week 2 before calling the corresponding client workflow complete. These defects can be worked on while provider contracts are clarified. |
|
||||
| **Upload** | Resolve before inviting the public to upload customer artwork. |
|
||||
| **Paid** | Resolve before enabling live checkout or accepting a real paid order. |
|
||||
| **Release** | Resolve before declaring the deployed production system ready. |
|
||||
| **Incremental** | Improve alongside feature work; it does not justify a standalone rewrite. |
|
||||
|
||||
The gates are cumulative: a live release must pass W2, Upload, Paid, and Release checks. Decisions labelled **business** require an agreed product rule; engineering can build and test the surrounding flow in parallel. Where a deployment risk is conditional, verify the actual topology and document the result before closing it.
|
||||
|
||||
## Complete finding-to-action map
|
||||
|
||||
| Review ID | Gate | Required action and closure evidence |
|
||||
|---|---|---|
|
||||
| 1 | Paid | Implement real payment, freight, ERP, and notification adapters with sandbox acceptance and reconciliation; remove fake adapters from the live path. |
|
||||
| 2 | W2 | Store a versioned per-file production specification and approved layout on quote and order; prove the factory can reproduce the purchased job. |
|
||||
| 3 | Upload; business | Agree the advertised maximum and implement a scan/release path that actually supports it; reject unsupported sizes before transfer. |
|
||||
| 4 | W2 | Give quotes an explicit lifecycle and paginated/searchable operator view; verify the 101st actionable quote remains visible. |
|
||||
| 5 | W2 | Invalidate or revision-bind finals when a new correction arrives; test a correction submitted after a final was uploaded. |
|
||||
| 6 | W2 | Make quality eligibility a checkout gate and store any required acknowledgement against the artwork revision. |
|
||||
| 7 | W2 | Clear the current cart item immediately when artwork is removed or becomes invalid; test the submitted payload. |
|
||||
| 8 | W2 | Bind checkout to an immutable quoted cart snapshot; require re-quote after any material edit, including same-price edits. |
|
||||
| 9 | W2 | Measure PDF pages through the parser's page model; handle every supported page or reject multi-page/unsupported geometry explicitly. |
|
||||
| 10 | W2 | Require quality evidence per billable source; make undecodable/unknown sources explicit and correct rotation-sensitive DPI calculations. |
|
||||
| 11 | W2 | Validate physical dimensions before packing; never silently scale a requested print size. |
|
||||
| 12 | Upload | Bound browser decoding, copy count, PDF work, and preview size; cancel obsolete work and test representative large inputs. |
|
||||
| 13 | Paid | Capture and validate a full delivery-address snapshot, then connect it to freight quote and order fulfilment. |
|
||||
| 14 | Paid; business | Set written auto-approval rules and manual-exception criteria; prove eligible orders can complete after hours without an operator. |
|
||||
| 15 | W2; business | Define accepted print output, generate it from the approved versioned layout, and compare produced geometry/metres with the quote. If scope changes, update the client commitment and site claims explicitly. |
|
||||
| 16 | Upload | Limit anonymous reservation capacity and lifetime; add cancellation and cleanup, then test quota-exhaustion behavior. |
|
||||
| 17 | Upload | Update ClamAV signatures on a controlled schedule; surface signature age and fail the intake gate when stale. |
|
||||
| 18 | Release | Trust only the actual proxy hop, restrict origin access, and test real client IP/rate limits through the deployed Swarm topology. |
|
||||
| 19 | Release | Wire file-backed secrets into the active stack; give each service only necessary credentials and remove unused bootstrap secrets. |
|
||||
| 20 | Release | Recheck operator `active` atomically when issuing and using sessions; test disable-versus-login concurrency and document password-change session policy. |
|
||||
| 21 | Paid | Provide email verification and customer recovery/guest continuity, and make checkout's account-creation claim match reality. |
|
||||
| 22 | Release; business | Agree retention/export/deletion rules for profiles, quotes, orders, payloads, artwork, and backups; implement and verify them. |
|
||||
| 23 | W2 | Repair staging, backup, and security commands after the directory move; smoke-test them in the images and Compose files actually shipped. |
|
||||
| 24 | Release | Set and test PostgreSQL node placement/persistence for the intended Swarm size, plus recovery after host failure. |
|
||||
| 25 | Release | Scan before promotion, publish immutable paired API/web image identities, and deploy exactly the scanned release. |
|
||||
| 26 | Release | Make preflight enforce the active stack contract and provider behavior; verify Portainer/deployment convergence after promotion. |
|
||||
| 27 | Release | Run browser tests in a network where signed storage URLs work; fail CI when Chrome or the test endpoint is unavailable. |
|
||||
| 28 | Release | Isolate each CI Compose project, ports, networks, and volumes; serialize release promotion and test overlapping runs. |
|
||||
| 29 | Release | Separate liveness/readiness, monitor provider backlog, cleanup, scanner freshness and backup age; test alert routing and rollback acceptance. |
|
||||
| 30 | Release; business | Set recovery objectives, make consistent encrypted offsite backups, and rehearse restore of database plus required live artwork. |
|
||||
| 31 | Paid | Finish durable payment intent, idempotent webhook handling, status/refund rules, reconciliation, and ordered outbox/dead-letter recovery; test provider-success/database-failure cases. Signed event work is only partial progress. |
|
||||
| 32 | Upload | Bound upload concurrency, decouple upload from scan waiting, measure queue latency, and distinguish transient scan errors from rejected content. |
|
||||
| 33 | Release | Introduce ordered schema migrations and core constraints/relationships; test both clean install and upgrade from the existing schema. |
|
||||
| 34 | Incremental | Replace shared mutable browser cart state as part of IDs 2/7/8; then extract reusable business operations from routes and add bounded DB connection management where load measurements warrant it. |
|
||||
| 35 | Release | Add representative artwork, real PDF, failure/retry, migration, operational-command, and exact-release acceptance tests. |
|
||||
| 36 | W2 | Correct executable setup/Portainer/security instructions and PDF generator paths; check generated output against current scope. |
|
||||
| 37 | Release | Inventory and scan every deployed image and vendored asset, pin release dependencies, and set a controlled refresh process. Do not describe the existing PDF.js advisory as a proven exploit. |
|
||||
|
||||
## Execution order
|
||||
|
||||
1. **Correct the customer/order model now:** IDs 2, 4–11, 23, and 36. Keep an immutable quote revision through payment, production output, and correction approval. Close each defect with a focused regression test and a real artwork example where geometry matters.
|
||||
2. **Set the missing product rules while coding continues:** IDs 3, 14, 15, 22, and 30. Obtain representative files, accepted print format, auto-approval thresholds, retention rules, recovery objectives, and provider sandbox access. Do not collect credentials in this document.
|
||||
3. **Make public intake safe:** IDs 3, 12, 16, 17, and 32. Test the declared upload size end to end, including scan, release, quota, browser memory, and timeout behavior.
|
||||
4. **Complete live commerce:** IDs 1, 13, 14, 15, 21, and 31. Build freight/address, payment/reconciliation, ERP, and notification flows; test duplicates, outages, refunds, and human exceptions in provider sandboxes.
|
||||
5. **Prove the deployed system:** IDs 18–20, 22, 24–30, 33, 35, and 37. Run the exact images and stack, exercise migration, backup/restore, monitoring, secrets, CI and release rollback. Improve ID 34 as the affected areas are changed.
|
||||
|
||||
## Who supplies what
|
||||
|
||||
- **Engineering:** implement and test the code, schema, operational commands, CI gates, provider adapters, and recovery runbooks; gather evidence for each closure. This work can start with the order/cart defects without waiting for provider access.
|
||||
- **Business/client:** approve unattended-pricing exceptions, final print-file format and samples, the real maximum file size, shipping services and policy, privacy retention, and recovery objectives. The detailed worksheet is [production inputs](PRODUCTION_INPUTS.md).
|
||||
- **Provider/operations owners:** supply sandbox accounts and configuration through the approved secret channel, plus the real deployment topology, backup destination, alert recipients, and release/rollback ownership. No credentials belong in this register or the repository.
|
||||
|
||||
**Closure rule:** A checkbox or passing mocked flow is insufficient. For each ID, keep the original evidence, record the implemented change and test, then verify in the environment that carries the risk. The [working roadmap](ROADMAP.md) tracks Week 2 delivery status; this register tracks the full defect disposition.
|
||||
144
docs/REVIEW-2026-09-21.md
Normal file
@@ -0,0 +1,144 @@
|
||||
**DTF project review — September 21, 2026**
|
||||
|
||||
Reviewed revision: `7386469`. Commit window: September 21, 00:00–24:00, America/Sao_Paulo; 26 commits. This is a review, not an implementation change or production approval.
|
||||
|
||||
**Assessment**
|
||||
|
||||
The project has a useful local workflow and several sound controls, but it is not yet the automated ordering and production system described in the meeting. The largest risks are incomplete commercial integrations, loss of production instructions between the editor and API, incorrect cart/quote behavior, an upload limit that the scanner cannot support, and operational controls that are documented more strongly than they are implemented.
|
||||
|
||||
Today's restructuring improved navigation through the repository, but introduced broken operational entrypoints. Today's board limit also introduced a starvation bug. Passing the existing tests does not establish that the requested artwork can be reproduced correctly or that the production deployment is recoverable.
|
||||
|
||||
**Business baseline and scope**
|
||||
|
||||
I read [the September 9 meeting notes](/home/farelos/compor/dtf-sistema/docs/reuniao-2026-09-09-anotacoes.pdf) first, then compared the implementation with [the later project context](/home/farelos/compor/dtf-sistema/docs/CONTEXT.md:20) and [the client roadmap](/home/farelos/compor/dtf-sistema/docs/roadmap-cliente.pdf).
|
||||
|
||||
The meeting's core outcome is unattended order intake and payment, fewer designer handoffs, reliable large-file handling, a traceable queue, and separation of ready artwork from artwork needing assistance. Later decisions explicitly defer automatic print preflight, factory agents, FlexiPRINT integration, machine dashboards, and advanced reports. Their absence is not reported here as an accidental regression. The approved site pricing also supersedes the meeting's simplified 20% discount description; changing those prices would require a separate business decision.
|
||||
|
||||
The active layout is `web/` for browser code; `app/api/` for HTTP routes; `app/core/` for shared foundations; the remaining `app/` modules for storage, artwork, scanning, initialization, and background work; `infra/` for local images and configuration; `deploy/`, the root Swarm composition, and `.gitea/` for delivery; `ops/` for operational commands; and `tests/` for checks. Historical documents describe earlier models and should not define current acceptance criteria.
|
||||
|
||||
**Evidence and limits**
|
||||
|
||||
- Inspected the active first-party application, browser logic, schema, deployment definitions, operational scripts, tests, project documents, and today's commit history and relevant diffs. Vendored PDF.js was checked as a third-party dependency, not subjected to a line-by-line audit of its minified implementation. Historical material was used as background.
|
||||
- Ran the current fast suite: 29 tests executed, 28 passed, one skipped because it still looks for the deleted `deploy/stack.yaml`.
|
||||
- Parsed all first-party Python files and checked the syntax of all first-party browser JavaScript files successfully.
|
||||
- Ran the isolated artwork browser suite with additional review probes against synthetic files. The existing checks passed; the probes reproduced findings 6, 7, and 10 below.
|
||||
- Ran the production source preflight: it correctly reported the fake payment and messaging adapters as blockers. CI does not enforce that result by default.
|
||||
- Used read-only checks in the running local API container: `ops` is absent, `app.staging_readiness` is absent, a 128 MiB + 1 byte scan is rejected, and ClamAV reports `1.5.4/28122/Sun Sep 13 06:26:25 2026`.
|
||||
- Executed the actual `submit_files` function body against an in-memory connection double to confirm which file kinds it invalidates. Also reproduced the board query's 101st-quote omission against synthetic SQL data. These are targeted logic checks, not production database tests.
|
||||
- Did not change application code, production services, credentials, orders, or stored artwork. Did not rerun the full container integration suite, perform a current Trivy audit, test provider sandboxes, or inspect production firewall/Portainer settings. Deployment-dependent risks below are explicitly qualified.
|
||||
|
||||
P1 means a delivery blocker or a material correctness, security, or recovery risk that should be resolved before accepting real customer work. P2 means an important correctness, reliability, or maintenance issue. A finding labelled a gap or design risk is not presented as an observed production incident.
|
||||
|
||||
**Commercial flow and artwork correctness**
|
||||
|
||||
1. **P1 — Production cannot complete an order. Confirmed delivery gap.** `dev-paid` returns 503 outside local mode, while runtime configuration requires fake payment, freight, Tiny, and WhatsApp adapters. There is no real payment creation/webhook/reconciliation flow, carrier quote, ERP order, or notification delivery. R2 connectivity and a healthy public page therefore do not establish a usable sales system. Complete the provider contracts and implement their sandbox-tested flows before treating the deployment as live commerce. Evidence: [orders.py:17](/home/farelos/compor/dtf-sistema/app/api/orders.py:17), [adapters.py:9](/home/farelos/compor/dtf-sistema/app/adapters.py:9), [runtime.py:24](/home/farelos/compor/dtf-sistema/app/runtime.py:24).
|
||||
|
||||
2. **P1 — The customer's production instructions disappear at checkout. Confirmed defect.** The editor records width, copies, rotation, mirroring, and ready-sheet repetitions, but `itemAtual` retains only totals and original Files. The API receives only mode, aggregate metres, grade, and upload IDs. It cannot tell the factory whether one artwork should be printed six times at 20 cm or with a different combination producing the same length. Neither the saved cart nor the order contains the full reproducible layout. Persist a versioned per-file production specification and the approved layout/revision. Evidence: [site-cart.js:65](/home/farelos/compor/dtf-sistema/web/site-cart.js:65), [checkout.js:65](/home/farelos/compor/dtf-sistema/web/checkout.js:65), [models.py:59](/home/farelos/compor/dtf-sistema/app/core/models.py:59).
|
||||
|
||||
3. **P1 — The 5 GiB upload path cannot deliver files above 128 MiB. Reproduced.** The browser/API accept 5 GiB, but `ClamAV.scan` hard-caps acceptance at `min(128 MiB, SCAN_MAX_BYTES)`, and ClamAV has matching limits. Raising the environment variable alone cannot fix it. Oversized files are rejected, blocked from quote/download/production, and scheduled for deletion; the customer may upload gigabytes before discovering this. Expose the usable limit before transfer and implement a deliberate large-file scan/release design. Evidence: [scanning.py:32](/home/farelos/compor/dtf-sistema/app/scanning.py:32), [clamd.conf:8](/home/farelos/compor/dtf-sistema/infra/clamd.conf:8), [docker-compose.yml:31](/home/farelos/compor/dtf-sistema/docker-compose.yml:31).
|
||||
|
||||
4. **P1 — The oldest 100 unpaid quotes can permanently hide new work. Introduced today in `543a9a9`.** The board selects the oldest unpaid quotes with a limit, including approved, expired, and abandoned quotes. There is no pagination, archive/cancel action, or pending-quote expiry that frees this window. Approved quotes are immutable, and expired ones cannot be paid, so old entries can remain indefinitely. Quote 101 is invisible even while needing review. Finished-order trimming also has no operator search/archive view for older completed work. Paginate/search history and give quotes an explicit lifecycle; do not silently cap actionable work. Evidence: [operator.py:59](/home/farelos/compor/dtf-sistema/app/api/operator.py:59), [kanban.js:24](/home/farelos/compor/dtf-sistema/web/kanban.js:24).
|
||||
|
||||
5. **P1 — A new correction can leave an obsolete final approved. Targeted logic reproduction.** An operator may submit finals while the order is in `cor`. The customer may then submit another correction using the latest version. `submit_files` deactivates only files of the incoming kind, so the earlier final remains active. Moving `cor → tra → fil` checks final coverage, not whether those finals were approved after the latest correction, and can accept the stale set. Invalidate finals on every accepted customer correction, or bind final approval to the specific correction revision. Evidence: [artwork.py:15](/home/farelos/compor/dtf-sistema/app/artwork.py:15), [artwork.py:40](/home/farelos/compor/dtf-sistema/app/artwork.py:40), [operator.py:118](/home/farelos/compor/dtf-sistema/app/api/operator.py:118).
|
||||
|
||||
6. **P2 — The stated DPI rejection and customer acknowledgement do not gate checkout. Browser-reproduced.** With 25.4-DPI artwork, the quality button was disabled but the payment button remained enabled and a cart item existed. `pintaEntrega` checks only customer data and freight; `dtfCheckout` does not check the resolution gate. The warning acknowledgement is also never recorded in the order. Manual operator review currently provides a later checkpoint, but the UI's claim that these files cannot proceed is false. Use one eligibility state for cart submission and retain any required acknowledgement against the artwork revision. Evidence: [site-quality.js:158](/home/farelos/compor/dtf-sistema/web/site-quality.js:158), [site-flow.js:90](/home/farelos/compor/dtf-sistema/web/site-flow.js:90), [checkout.js:49](/home/farelos/compor/dtf-sistema/web/checkout.js:49).
|
||||
|
||||
7. **P1 — Removing artwork can leave it in the submitted cart. Browser-reproduced.** After deleting the only artwork, `artes.length` became zero while `itemAtual.localFiles` still contained the removed file and checkout stayed enabled. An incomplete evaluation hides panels without clearing `itemAtual`; other invalid edits can similarly leave old totals and Files alive. Clear or invalidate the current cart item immediately whenever its underlying artwork becomes incomplete. Evidence: [site-cart.js:7](/home/farelos/compor/dtf-sistema/web/site-cart.js:7), [site-quality.js:79](/home/farelos/compor/dtf-sistema/web/site-quality.js:79), [site-pdf.js:348](/home/farelos/compor/dtf-sistema/web/site-pdf.js:348).
|
||||
|
||||
8. **P1 — Editing the cart after requesting a quote can still purchase the old quote. Confirmed control-flow defect.** Once `draftId` exists, checkout returns early through `refresh()` and never compares the current cart with the stored quote. The editor remains usable. The confirmation displays a server total but no full immutable item comparison, so quantity/artwork edits can be silently ignored, especially when the one-metre minimum keeps the total unchanged. Bind the UI to the quoted snapshot and explicitly replace the quote on edits. Evidence: [checkout.js:51](/home/farelos/compor/dtf-sistema/web/checkout.js:51), [checkout.js:89](/home/farelos/compor/dtf-sistema/web/checkout.js:89).
|
||||
|
||||
9. **P2 — PDF quantity and geometry are not reliably measured. Confirmed algorithm limitation.** Measurement searches the first/last 4 MiB for the first textual `MediaBox` and an unrelated first `UserUnit`; rendering/quality checks only page 1. There is no multi-page rejection or sum across pages. A multi-page print file can therefore be quoted as one page. Compressed/inherited page dictionaries, rotation, and page-specific units are not handled by this textual search. Use the PDF parser's page model, and either support every page or explicitly reject unsupported documents. Evidence: [site-pdf.js:101](/home/farelos/compor/dtf-sistema/web/site-pdf.js:101), [site-pdf.js:132](/home/farelos/compor/dtf-sistema/web/site-pdf.js:132).
|
||||
|
||||
10. **P2 — Quality grades can be based on missing or incorrect evidence. Partly browser-reproduced.** A CDR with no analysis plus an analysed PNG received grade 50 and R$18.70/m for the entire item rather than the CDR's stated table rate of R$19.90/m. `filter(Boolean)` removes unanalysed files from grading while their metres remain billable. For loose artwork, failed image decoding leaves a pixel estimate derived from compressed file size. Rotation retains the original width for DPI even when the physical width now corresponds to image height. The PDF image walker also treats no recognized images as vector artwork, although unsupported image operators or failed object lookup can yield the same result. Track quality per source and fail explicitly when measurement is unknown. Evidence: [site-quality.js:19](/home/farelos/compor/dtf-sistema/web/site-quality.js:19), [site-config.js:107](/home/farelos/compor/dtf-sistema/web/site-config.js:107), [site-upload.js:96](/home/farelos/compor/dtf-sistema/web/site-upload.js:96), [site-pdf.js:46](/home/farelos/compor/dtf-sistema/web/site-pdf.js:46).
|
||||
|
||||
11. **P2 — Oversized artwork is silently shrunk by the packer. Confirmed code path.** Width inputs advertise a maximum, but their JavaScript handlers accept larger values without validating form constraints. When no orientation fits, `encaixar` scales the artwork down to film width. The requested dimension and actual preview geometry then disagree, without an explicit approval to resize. Reject impossible dimensions or offer a visible, accepted resize. Evidence: [site-pdf.js:349](/home/farelos/compor/dtf-sistema/web/site-pdf.js:349), [site-packing.js:175](/home/farelos/compor/dtf-sistema/web/site-packing.js:175).
|
||||
|
||||
12. **P2 — The browser processing path is not bounded for large artwork. Confirmed design risk.** Images are loaded as full data URLs and decoded repeatedly; PDFs use full-file `arrayBuffer`; copy count has no effective upper bound before `Array.from`; preview canvas height grows with the whole layout. PDF timeouts race a promise without cancelling parsing/rendering or destroying the document. Large files or copy counts can exhaust memory or freeze the main thread before resumable upload helps. Bound work, avoid repeated full decodes, tile previews, cancel obsolete parsing, and provide a path that does not require browser rasterization of huge files. Evidence: [site-packing.js:6](/home/farelos/compor/dtf-sistema/web/site-packing.js:6), [site-packing.js:204](/home/farelos/compor/dtf-sistema/web/site-packing.js:204), [site-pdf.js:97](/home/farelos/compor/dtf-sistema/web/site-pdf.js:97).
|
||||
|
||||
13. **P1 — Home-delivery orders cannot capture a deliverable address. Confirmed MVP gap.** Customer data contains CNPJ, phone, and email; freight contains only service and CEP. There is no recipient name, street, number, complement, city/state, or validated delivery snapshot. A CEP can support an estimate, but it does not identify the destination needed to fulfil the order. Add the delivery contract together with freight integration; automated label purchase can remain out of scope. Evidence: [models.py:10](/home/farelos/compor/dtf-sistema/app/core/models.py:10), [models.py:43](/home/farelos/compor/dtf-sistema/app/core/models.py:43), [index.html:1209](/home/farelos/compor/dtf-sistema/web/index.html:1209).
|
||||
|
||||
14. **P1 — Unattended sales still depend on a human commercial review. Product decision outstanding.** Server pricing safely recalculates prices, but metres and grade become trusted only when an operator approves every quote. This intentionally protects the local prototype; it does not solve the meeting's after-hours bottleneck. Decide which orders can be accepted automatically, what evidence supports their price, and what exceptions require a person. Automatic print preflight being deferred does not itself settle the pricing-authority question. Evidence: [orders.py:28](/home/farelos/compor/dtf-sistema/app/api/orders.py:28), [operator.py:78](/home/farelos/compor/dtf-sistema/app/api/operator.py:78), [CONTEXT.md:262](/home/farelos/compor/dtf-sistema/docs/CONTEXT.md:262).
|
||||
|
||||
15. **P1 — Final print-file generation remains missing from the promised delivery. Confirmed gap.** The server stores originals and manually uploaded finals; it never generates the layout shown in the browser, applies repetitions, splits output, or adds the promised order identification. Consequently the factory must reconstruct the job, and billed metres have no machine-verifiable connection to produced metres. The client roadmap includes final-file generation in week 2 even while deferring automatic preflight. Implement a reproducible output path and print acceptance checks, or explicitly renegotiate that deliverable and the site's promises. Evidence: [api/artwork.py:45](/home/farelos/compor/dtf-sistema/app/api/artwork.py:45), [site-packing.js:342](/home/farelos/compor/dtf-sistema/web/site-packing.js:342), [ROADMAP.md:171](/home/farelos/compor/dtf-sistema/docs/ROADMAP.md:171).
|
||||
|
||||
**Security and access**
|
||||
|
||||
16. **P1 — Anonymous reservations can exhaust the entire storage quota without uploading bytes. Confirmed arithmetic/control-flow risk; no attack run.** Quota accounting immediately reserves the declared file size. With current defaults, five guest identities can reserve two 5 GiB uploads each and occupy the global 50 GiB allowance. Guest sessions and per-owner limits do not prevent this; all reservations remain until incomplete-upload cleanup after one day, and no customer abort endpoint releases them. Add global admission safeguards, short idle reservation leases, explicit cancellation, and a suitable identity/abuse policy. Evidence: [uploads.py:21](/home/farelos/compor/dtf-sistema/app/api/uploads.py:21), [health.py:26](/home/farelos/compor/dtf-sistema/app/api/health.py:26), [worker.py:21](/home/farelos/compor/dtf-sistema/app/worker.py:21).
|
||||
|
||||
17. **P1 — Malware signatures are already stale in the inspected local runtime. Reproduced operational gap.** The scanner runs `clamd` directly from a pinned image on an internal network, with no updater or scheduled replacement. It reports September 13 signatures on September 21, exceeding the repository's own seven-day threshold. Worker health only requires a live thread and PING. A running scanner is therefore reported healthy despite stale detection data. Establish controlled signature updates and make signature freshness visible to operations. [ClamAV's signature-management documentation](https://docs.clamav.net/manual/Usage/SignatureManagement.html) describes the update mechanism. Evidence: [docker-compose.yml:79](/home/farelos/compor/dtf-sistema/docker-compose.yml:79), [worker.py:60](/home/farelos/compor/dtf-sistema/app/worker.py:60), [security_status.py:7](/home/farelos/compor/dtf-sistema/ops/security_status.py:7).
|
||||
|
||||
18. **P1 — The reverse-proxy trust boundary is broader than the claimed protection. Deployment-dependent security risk introduced in `3b92813`.** Nginx accepts forwarded client addresses from every RFC1918 network, rather than the actual trusted proxy. Any reachable private peer can supply that header. The web ports use Swarm ingress, so the assumption that a direct internet request necessarily arrives with a public socket peer also needs topology testing. If untrusted traffic arrives through a trusted internal peer, it can spoof audit addresses and rate-limit buckets. Restrict trusted proxy hops and firewall the origin ports; verify through the actual Swarm/reverse-proxy chain. I did not verify production exposure or demonstrate a public exploit. Evidence: [nginx.conf.template:17](/home/farelos/compor/dtf-sistema/deploy/nginx.conf.template:17), [docker-compose.yml:143](/home/farelos/compor/dtf-sistema/docker-compose.yml:143). References: [Nginx real-IP trust](https://nginx.org/en/docs/http/ngx_http_realip_module.html), [Docker ingress routing](https://docs.docker.com/engine/swarm/ingress/).
|
||||
|
||||
19. **P2 — Production credentials remain plain service environment values. Confirmed configuration risk.** The actual stack supplies DB, R2, and operator secrets directly, despite the new secret-file loader and documentation describing external secrets. API and worker both receive the bootstrap operator password even though runtime authentication now uses the database. Removing the unused second stack reduced drift, but did not remove this exposure from the active one. Use the implemented file loader in the real stack and restrict each service to the secrets it needs. This is metadata/operational exposure, not evidence of a public credential leak. Evidence: [docker-compose.yml:3](/home/farelos/compor/dtf-sistema/docker-compose.yml:3), [core/secrets.py:1](/home/farelos/compor/dtf-sistema/app/core/secrets.py:1).
|
||||
|
||||
20. **P2 — Operator disable can race with login. Introduced with accounts in `a874033`; static concurrency finding.** Login reads the active account, performs expensive password verification, then inserts a session in a separate transaction without rechecking `active`. Disabling between those steps deletes existing sessions, but the in-flight login can create a new one afterwards. The request guard checks only session existence/expiry, so that session can authorize a disabled account for eight hours. Recheck active status atomically when issuing sessions and in authorization. Password changes also intentionally retain current sessions; document or revise that recovery policy. Evidence: [operator.py:23](/home/farelos/compor/dtf-sistema/app/api/operator.py:23), [auth.py:102](/home/farelos/compor/dtf-sistema/app/core/auth.py:102), [operators.py:80](/home/farelos/compor/dtf-sistema/app/operators.py:80).
|
||||
|
||||
21. **P2 — Account recovery and guest continuity are incomplete. Confirmed gap.** There is no email verification, password recovery/change flow for customers, or durable guest recovery mechanism. A guest who loses the cookie or passes its seven-day expiry cannot prove ownership merely by knowing the order/CNPJ, correctly, but also has no supported way to regain access. The site incorrectly promises account creation at payment; the order route creates no account. Complete the identity/recovery journey without weakening the existing ownership checks. Evidence: [customer.py:25](/home/farelos/compor/dtf-sistema/app/api/customer.py:25), [auth.py:58](/home/farelos/compor/dtf-sistema/app/core/auth.py:58), [index.html:1190](/home/farelos/compor/dtf-sistema/web/index.html:1190).
|
||||
|
||||
22. **P2 — Personal-data lifecycle is undefined beyond artwork cleanup. Confirmed governance gap, not a legal conclusion.** Profiles, quote drafts, immutable order snapshots, and integration payloads duplicate contact data without an implemented deletion/anonymization/export policy. Artwork expiry does not cover those records or retained backups. The site does link an external privacy/terms page, so claiming there is no privacy link would be inaccurate; this review did not establish whether that notice covers this processing. Define retention and access requirements for each data class, then implement them consistently. Evidence: [schema.sql:9](/home/farelos/compor/dtf-sistema/app/schema.sql:9), [schema.sql:28](/home/farelos/compor/dtf-sistema/app/schema.sql:28), [index.html:1358](/home/farelos/compor/dtf-sistema/web/index.html:1358).
|
||||
|
||||
**Operations and release engineering**
|
||||
|
||||
23. **P1 — Today's directory move broke staging, backup, and security operations. Reproduced packaging failure in `b329f76`.** Staging runs `app.staging_readiness`, but the module now lives under `ops`. Neither API Dockerfile copies `ops`. Backup still calls `local.storage_backup` inside the API container and selects plain `docker compose`, which now means the production-oriented root file rather than `compose.local.yaml`. Documentation calls nonexistent `app.backup` and `app.security_status`. These are broken operational commands, not merely stale comments. Package a deliberate operational runtime, update every executable entrypoint, and smoke-test the shipped commands. Evidence: [compose.staging.yaml:11](/home/farelos/compor/dtf-sistema/compose.staging.yaml:11), [infra/Dockerfile:10](/home/farelos/compor/dtf-sistema/infra/Dockerfile:10), [backup.py:13](/home/farelos/compor/dtf-sistema/ops/backup.py:13), [backup.py:41](/home/farelos/compor/dtf-sistema/ops/backup.py:41).
|
||||
|
||||
24. **P1 — PostgreSQL has no Swarm data-placement contract. Conditional recovery risk.** The active stack uses a normal local named volume with no node constraint. On a multi-node Swarm, rescheduling can attach a same-named empty local volume on another node rather than the existing database. The documented `POSTGRES_VOLUME` and `dtf_database=true` placement contract is not implemented. A single-node VPS is also a single failure domain. Specify and test persistence, placement, and recovery instead of relying on the volume name alone. Evidence: [docker-compose.yml:40](/home/farelos/compor/dtf-sistema/docker-compose.yml:40), [docker-compose.yml:180](/home/farelos/compor/dtf-sistema/docker-compose.yml:180), [PORTAINER.md:73](/home/farelos/compor/dtf-sistema/docs/PORTAINER.md:73).
|
||||
|
||||
25. **P1 — `latest` is published before the release scan, and deployment is not tied to the scanned pair. Confirmed pipeline design defect.** API and web `latest` tags are pushed independently before vulnerability checks. A failed scan leaves the mutable deployment tags pointing at rejected images; a manual redeploy or another run can consume them. Concurrent runs can also overwrite each other's API/web tags, while the webhook carries no exact release identity. Build and scan first, then promote one immutable API/web release and deploy that release. Evidence: [deploy.yml:194](/home/farelos/compor/dtf-sistema/.gitea/workflows/deploy.yml:194), [deploy.yml:217](/home/farelos/compor/dtf-sistema/.gitea/workflows/deploy.yml:217), [deploy.yml:243](/home/farelos/compor/dtf-sistema/.gitea/workflows/deploy.yml:243).
|
||||
|
||||
26. **P1 — The production gate does not validate the deployed contract. Confirmed gap.** CI runs only `--source-only`, treats failure as advisory by default, and never validates the actual Portainer metadata or observes deployment convergence. Full config validation expects names/secrets/volumes from the removed stack, while the active stack uses different variables. Positive secret-loader checks also derive their cases from that deleted file, leaving the set empty; the associated unit test skips. The two remaining provider checks match literal source strings, not working provider behavior. Retarget validation to the actual deployment, retain positive loader tests independently of a file's existence, and add release acceptance against real capabilities. Evidence: [deploy.yml:155](/home/farelos/compor/dtf-sistema/.gitea/workflows/deploy.yml:155), [production_preflight.py:17](/home/farelos/compor/dtf-sistema/deploy/production_preflight.py:17), [production_preflight.py:81](/home/farelos/compor/dtf-sistema/deploy/production_preflight.py:81), [test_secrets.py:75](/home/farelos/compor/dtf-sistema/tests/test_secrets.py:75).
|
||||
|
||||
27. **P1 — Browser tests can be skipped on a green release, and their upload endpoint is incompatible with the runner topology. Confirmed CI gap.** Missing Chrome or inaccessible host loopback returns success. Meanwhile CI signs browser storage URLs for `http://storage:9000`, a Compose-only hostname; installing Chrome or making host ports reachable does not by itself give that browser access to storage. These are the only broad tests of the artwork/cart journey. Run Chrome and the tests in a compatible network, then make omission fail the release. Evidence: [deploy.yml:45](/home/farelos/compor/dtf-sistema/.gitea/workflows/deploy.yml:45), [deploy.yml:90](/home/farelos/compor/dtf-sistema/.gitea/workflows/deploy.yml:90), [browser_test.mjs:44](/home/farelos/compor/dtf-sistema/tests/browser_test.mjs:44).
|
||||
|
||||
28. **P2 — CI runs share fixed ports and lack enforced project isolation. Conditional concurrency risk.** The integration job uses the same five host ports, relies on the default Compose project name, and ends with `down -v`. Overlapping runs on the shared Docker daemon can collide; if their project names coincide, they can also operate on each other's containers and volumes. Selecting currently unused ports fixed one collision but not concurrency. Allocate a unique project/network per run, avoid unnecessary published ports, and serialize release promotion. Evidence: [deploy.yml:27](/home/farelos/compor/dtf-sistema/.gitea/workflows/deploy.yml:27), [deploy.yml:121](/home/farelos/compor/dtf-sistema/.gitea/workflows/deploy.yml:121).
|
||||
|
||||
29. **P1 — Health checks do not establish operational readiness or successful delivery. Confirmed monitoring gap.** Public `/health` always returns 200 from Nginx. API health checks DB/storage, while worker health can remain green during repeated provider failures, stale signatures, or failed cleanup. `last_tick` advances even after a delivery retry is scheduled. Cleanup handles a batch in one transaction; one consistently failing object can roll back progress and repeatedly block later expired objects. There is no implemented external alert routing or post-webhook application verification, and the stack lacks explicit rollback/update policies described in the docs. Separate liveness from readiness and alert on backlog age, cleanup progress, signatures, backup age, and deployment acceptance. Evidence: [nginx.conf.template:32](/home/farelos/compor/dtf-sistema/deploy/nginx.conf.template:32), [worker.py:21](/home/farelos/compor/dtf-sistema/app/worker.py:21), [worker.py:35](/home/farelos/compor/dtf-sistema/app/worker.py:35), [deploy.yml:243](/home/farelos/compor/dtf-sistema/.gitea/workflows/deploy.yml:243).
|
||||
|
||||
30. **P1 — Recoverability is not implemented as a production service. Confirmed gap beyond the broken commands.** There is no scheduled offsite encrypted backup, production restoration procedure, or tested recovery objective. The local backup dumps PostgreSQL and selects object bytes afterwards, without a shared snapshot or enforced pause; concurrent uploads/retention can produce mismatched state. Its restore check validates database counts and archived bytes separately, not that every required live order file is restorable. Define a consistent recovery boundary, required data classes, backup retention, and a rehearsed restoration procedure. Evidence: [backup.py:27](/home/farelos/compor/dtf-sistema/ops/backup.py:27), [storage_backup.py:46](/home/farelos/compor/dtf-sistema/ops/storage_backup.py:46), [LOCAL_SETUP.md:216](/home/farelos/compor/dtf-sistema/docs/LOCAL_SETUP.md:216).
|
||||
|
||||
31. **P1 — Real payment and integration failure semantics are not yet represented. Design gap before enabling providers.** The mock payment is called before the order transaction commits. A future provider success followed by a DB failure needs a durable payment intent, provider idempotency, and reconciliation. The outbox has a useful unique event key, but retries can let a later event for the same order overtake an earlier failed event; permanent failures retry forever without a dead-letter/operator resolution path. Provider-side success followed by a crash can also repeat delivery. There are no real pending/failed/refunded/cancelled payment states or corresponding production rules. Implement those contracts before substituting real network calls for fakes. Evidence: [orders.py:34](/home/farelos/compor/dtf-sistema/app/api/orders.py:34), [worker.py:35](/home/farelos/compor/dtf-sistema/app/worker.py:35), [runtime.py:43](/home/farelos/compor/dtf-sistema/app/runtime.py:43).
|
||||
|
||||
32. **P2 — Upload/scanning throughput and timeout behavior are poorly matched. Confirmed design limitation.** Files and their 8 MiB parts are uploaded sequentially, with one API presign round-trip per part; the browser then waits for scanning before uploading the next file. One scan thread handles all work, holds a DB transaction during the remote read/scan, and the browser gives up after roughly 150 polls. Scanner errors shorten retention to three days even if a later retry succeeds; success does not restore that deadline. Add bounded transfer concurrency, separate upload completion from scan waiting, measure queue latency, and distinguish transient scanner faults from rejected content. Evidence: [upload.js:9](/home/farelos/compor/dtf-sistema/web/upload.js:9), [checkout.js:60](/home/farelos/compor/dtf-sistema/web/checkout.js:60), [scanning.py:55](/home/farelos/compor/dtf-sistema/app/scanning.py:55).
|
||||
|
||||
**Architecture, verification, and maintenance**
|
||||
|
||||
33. **P2 — Database integrity and schema evolution rely too heavily on application convention. Confirmed design weakness.** Startup replays one growing SQL script without a general ordered migration/version contract. Orders reference artwork inside JSON instead of relational order-item/upload references; states and scan states lack checks, and upload expiry remains nullable. The database cannot enforce several invariants that the application assumes. Today's index-before-table regression, fixed in `86b8199`, demonstrates why clean initialization and upgrade paths both need testing. Use versioned migrations, explicit core relationships/constraints, and verify supported upgrades as well as empty installations. Evidence: [bootstrap.py:29](/home/farelos/compor/dtf-sistema/app/bootstrap.py:29), [schema.sql:14](/home/farelos/compor/dtf-sistema/app/schema.sql:14), [schema.sql:71](/home/farelos/compor/dtf-sistema/app/schema.sql:71).
|
||||
|
||||
34. **P2 — File separation has not yet produced clear internal boundaries. Confirmed maintenance risk.** The browser scripts share mutable globals and a required evaluation order; cart and editor state can diverge, as reproduced above. API routes still implement SQL/business transactions, and the operator artwork router imports and calls the customer upload route functions directly. `runtime.py` constructs environment-bound adapters at import time, making isolated business tests harder. Every database operation creates a new connection, and synchronous audit DB writes also run directly in async middleware. Keep the small deployment, but move reusable use cases behind explicit interfaces, use one cart state model, and introduce bounded connection management as load requires. Evidence: [index.html:1376](/home/farelos/compor/dtf-sistema/web/index.html:1376), [api/artwork.py:15](/home/farelos/compor/dtf-sistema/app/api/artwork.py:15), [runtime.py:21](/home/farelos/compor/dtf-sistema/app/runtime.py:21), [db.py:6](/home/farelos/compor/dtf-sistema/app/core/db.py:6), [app.py:30](/home/farelos/compor/dtf-sistema/app/app.py:30).
|
||||
|
||||
35. **P2 — Existing tests verify the mock workflow more strongly than the delivered product. Confirmed coverage gap.** Pricing parity is valuable, but uses only 11 lengths and shared tables; it cannot validate print geometry. Integration fixtures deliberately use plain text with a `.cdr` extension, which tests transport but proves no printability. The current isolated browser server does not serve `/vendor/...`, and its tests do not exercise real PDF parsing. Missing operational entrypoints and stale-cart behavior passed the suite. CI tests local images/configuration, not the final production images and Swarm proxy topology. Add targeted acceptance for the defects above, real representative artwork, fault/retry cases, clean/upgrade schema paths, operational command packaging, and the exact release artifacts. Evidence: [test_pricing.py:10](/home/farelos/compor/dtf-sistema/tests/test_pricing.py:10), [fixtures/local-test.cdr](/home/farelos/compor/dtf-sistema/tests/fixtures/local-test.cdr), [artwork_browser_test.mjs:26](/home/farelos/compor/dtf-sistema/tests/artwork_browser_test.mjs:26), [deploy.yml:59](/home/farelos/compor/dtf-sistema/.gitea/workflows/deploy.yml:59).
|
||||
|
||||
36. **P2 — Documentation and generated deliverables can send operators to the wrong system. Partly introduced today.** README's active quick start still selects the production Compose file. Portainer instructions tell users to populate secret/volume/host variables the actual stack does not consume. Security/context documents still claim absent rollback, secrets, blocked deployment, or obsolete CDN behavior. The historical index calls the local milestone report a different prototype. The client PDF's diagram still labels a worker preflight while its scope defers it. Moving the PDF generator in `66ddb17` left `parents[2]`, which now resolves to `/home/farelos/compor`, outside this repository, and its output path no longer matches the documented PDF. Correct executable instructions and current claims, and validate generated output paths. Evidence: [README.md:3](/home/farelos/compor/dtf-sistema/README.md:3), [PORTAINER.md:73](/home/farelos/compor/dtf-sistema/docs/PORTAINER.md:73), [SECURITY_REPORT.md:40](/home/farelos/compor/dtf-sistema/docs/SECURITY_REPORT.md:40), [generate_dtf_report.py:17](/home/farelos/compor/dtf-sistema/tools/generate_dtf_report.py:17).
|
||||
|
||||
37. **P2 — Dependency/rebuild claims exceed the enforced supply-chain contract. Confirmed maintenance gap.** Vendoring PDF.js removed the CDN dependency, but version 3.11.174 remains old and has no automated inventory/update check. Its known eval advisory is mitigated by the existing `isEvalSupported:false` and restrictive CSP; this is not reported as demonstrated arbitrary code execution. PostgreSQL remains a mutable tag; CI scans only the application images. Unversioned OS upgrades and optional base-image overrides also mean a pinned base alone does not guarantee identical rebuilt images. The pricing tables are still separately maintained in JS/Python, though parity tests help. Record complete dependency provenance, scan all deployed images and vendored assets, and maintain a controlled refresh process. Evidence: [vendor/README.md:7](/home/farelos/compor/dtf-sistema/web/vendor/README.md:7), [site-pdf.js:97](/home/farelos/compor/dtf-sistema/web/site-pdf.js:97), [docker-compose.yml:41](/home/farelos/compor/dtf-sistema/docker-compose.yml:41), [deploy/Dockerfile.api:16](/home/farelos/compor/dtf-sistema/deploy/Dockerfile.api:16). Reference: [Mozilla's advisory and workaround](https://github.com/mozilla/pdf.js/security/advisories/GHSA-wgrm-67xf-hhpq). No fresh vulnerability counts are asserted here.
|
||||
|
||||
**Today's commit assessment**
|
||||
|
||||
| Commits | Result at reviewed HEAD |
|
||||
|---|---|
|
||||
| `341f154`, `d2f7b2c` | Secret-file loader and tests are useful; active stack still does not use them. |
|
||||
| `9da2a7d`, `bbcc8ab` | Added real gates, but source readiness remains advisory and publication precedes image acceptance. |
|
||||
| `4c9fa24`, `010c2a1` | Pinned application bases and added CRITICAL scanning. Do not infer current zero findings for every deployed service. |
|
||||
| `6c52ad6`, `6a50e6d` | Fixed CI image retrieval/configuration packaging. |
|
||||
| `24cb52d`, `7cab210`, `c1a07a7`, `dbc9ba4` | Improved integration execution after port/network failures; browser/network coverage and run isolation remain incomplete. |
|
||||
| `3b92813` | Recovered proxy client headers but trusts overly broad private ranges; needs real-topology verification. |
|
||||
| `e95a42d`, `9926d3a`, `91269ce` | Removed duplicate stack definition; active hardening and documentation were not reconciled completely. |
|
||||
| `da903db` | Removed PDF.js CDN dependency; old dependency and PDF logic remain. |
|
||||
| `a874033` | Added useful per-operator attribution; session issuance has a disable/login race. |
|
||||
| `543a9a9`, `86b8199` | Added useful indexes and bounded finished history; fixed table/index ordering. Quote truncation creates starvation. |
|
||||
| `ca69843` | Removed inactive prototypes; this correctly reduces ambiguity and should not be counted as lost active functionality. |
|
||||
| `96f1d27`, `c9f8122` | Improved code navigation and router assembly. Global state and business boundaries remain coupled. |
|
||||
| `66ddb17` | Removed accidentally tracked deliverables from HEAD and relocated artifacts; generator root/output was not updated. Untracking does not remove historical Git objects. |
|
||||
| `b329f76` | Improved directory roles; broke staging/backup/security command packaging. |
|
||||
| `7386469` | Centralized engineering docs; several executable instructions and current-state claims still disagree with code. |
|
||||
|
||||
The overall problem with today's work is incomplete acceptance around operational entrypoints and domain behavior. The reorganizations themselves are reasonable. Neither a microservice rewrite nor returning to the deleted prototypes would address the findings above.
|
||||
|
||||
**Recommended order of work**
|
||||
|
||||
1. Fix confirmed data/work-loss defects: preserve production instructions; clear stale cart state; bind quotes to the displayed cart; remove quote starvation; invalidate finals after corrections.
|
||||
2. Repair operational command packaging and establish a real backup/restore path. Address stale signatures, anonymous quota exhaustion, and the actual proxy trust boundary before accepting public uploads.
|
||||
3. Resolve the two central product decisions: unattended price authority and supported large-file processing. Align the site promises with the chosen interim behavior.
|
||||
4. Complete the MVP contracts: destination address/freight, durable payment intents and webhooks, Tiny, final-file generation, and the four WhatsApp events. Test their failure/reconciliation paths in staging.
|
||||
5. Make release identity, exact-artifact testing, browser tests, production configuration checks, and post-deployment verification enforceable. Reconcile the documentation with that one implementation.
|
||||
|
||||
The current controls worth preserving are server-calculated prices, immutable approved quotes, owner-scoped access, parameterized SQL, password hashing, revocable HttpOnly sessions, strict script CSP, private signed storage access, malware quarantine, state/version checks, transactional outbox insertion, and dependency hashes. This review identifies material defects and gaps supported by the inspected code; it does not establish that every possible flaw has been found.
|
||||
1068
docs/ROADMAP.md
Normal file
@@ -77,14 +77,15 @@ the signatures bundled into that image. On closeout it reported ClamAV
|
||||
below the seven-day alert threshold.
|
||||
|
||||
The multipart transport supports uploads up to 5 GiB, but `SCAN_MAX_BYTES` and
|
||||
ClamAV stream limits release at most 128 MiB by default. Larger files remain
|
||||
blocked. Supporting larger files requires a deliberate resource/timeout design,
|
||||
not simply increasing the upload limit.
|
||||
ClamAV stream limits release at most 128 MiB by default. As of 2026-09-23 the
|
||||
API and customer picker reject larger files before transfer. Supporting them
|
||||
requires a deliberate resource/timeout design, not simply increasing the
|
||||
transport limit.
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
docker compose exec -T api python -m local.security_status
|
||||
docker compose -f compose.local.yaml exec -T api python3 -m ops.security_status
|
||||
```
|
||||
|
||||
An exit status of 1 requires review. At closeout, attention was expected because
|
||||
@@ -99,7 +100,7 @@ errors, unexplained authentication bursts, or stale signatures as incidents.
|
||||
|
||||
`pip-audit` inspected the exact packages installed in the hash-enforced rebuilt API
|
||||
and found no known Python advisories on 2026-09-15. All 26 direct and transitive
|
||||
runtime packages are pinned with artifact hashes in `local/requirements.lock`.
|
||||
runtime packages are pinned with artifact hashes in `infra/requirements.lock`.
|
||||
`local/lock_dependencies.sh` regenerates it in a disposable Python 3.12 container.
|
||||
This is a point-in-time package-database result, not proof that the dependencies
|
||||
or image are vulnerability-free. Scheduled lock refresh and audit automation remain
|
||||
@@ -131,15 +132,12 @@ change when the advisory database or selected base digest changes.
|
||||
The files in `deploy/` and `.gitea/workflows/` are a guarded delivery mechanism,
|
||||
not an approval to operate the current application on the public internet.
|
||||
|
||||
Corrected 2026-09-21: an earlier version of this section described gates the
|
||||
workflow did not contain. The workflow now runs static validation, the
|
||||
integration suite against a live stack, and a blocking Trivy secret scan before
|
||||
publishing. The source preflight is advisory unless
|
||||
`ENFORCE_PRODUCTION_PREFLIGHT` is set, and image vulnerabilities are reported
|
||||
rather than enforced, because the current bases carry HIGH/CRITICAL findings
|
||||
with no upstream fix. Base images are still mutable tags, not digests.
|
||||
`PORTAINER.md` holds the authoritative table of what gates and what does not.
|
||||
It publishes both `latest` and the full commit SHA, then calls the Portainer
|
||||
Updated 2026-09-23: pushes to `main` run checks only. A manual workflow run on
|
||||
`main` requires the source preflight and a configured Portainer webhook before
|
||||
building. It scans built images before publication; CRITICAL findings block and
|
||||
HIGH findings are reported. The browser suites run in a required Compose Chrome
|
||||
container. `PORTAINER.md` holds the authoritative gate table. A permitted release
|
||||
publishes both `latest` and the full commit SHA, then calls the Portainer
|
||||
webhook. Application/provider secrets are created directly as versioned external
|
||||
Swarm secrets and never cross the workflow. Rollback selects the prior commit SHA
|
||||
in Portainer and does not roll back the database.
|
||||
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 |