Merge main into front-8

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

# Conflicts:
#	.gitea/workflows/deploy.yml
This commit is contained in:
Cauê Faleiros
2026-11-09 16:47:28 -03:00
35 changed files with 1449 additions and 262 deletions

View File

@@ -10,7 +10,7 @@ from fastapi import APIRouter, Depends, HTTPException
from ..core import db
from .. import proof
from ..artwork import submit_files
from ..core.auth import can, operator
from ..core.auth import can, can_any, operator
from ..core.models import ArtworkSubmission, UploadStart
from ..runtime import file_rows, operator_identity
from .uploads import begin_upload, cancel_upload, complete_upload, part_url, upload_status
@@ -38,15 +38,15 @@ def final_status(uid: UUID, user=Depends(operator)):
# 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'))):
def final_part(uid: UUID, number: int, user=Depends(can_any('deliver', 'assemble'))):
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'))):
def final_complete(uid: UUID, user=Depends(can_any('deliver', 'assemble'))):
return complete_upload(uid,session_id=operator_identity(user))
@router.delete('/api/operator/uploads/{uid}')
def final_cancel(uid: UUID, user=Depends(can('deliver'))):
def final_cancel(uid: UUID, user=Depends(can_any('deliver', 'assemble'))):
return cancel_upload(uid,session_id=operator_identity(user))
@router.get('/api/operator/orders/{oid}/files')

View File

@@ -22,7 +22,7 @@ CATALOG = {
'retirada': 'Retirada em Franca em 24 h',
'sala': 'A sala às 3 da manhã',
}
VIDEO_MAX = 100 * 1024 * 1024
VIDEO_MAX = 500 * 1024 * 1024
CAPTIONS_MAX = 1024 * 1024
@@ -46,7 +46,7 @@ def _kind(upload):
return 'video/webm', b'\x1a\x45\xdf\xa3', 0
if name.endswith('.vtt') and upload['size'] <= CAPTIONS_MAX:
return 'text/vtt', b'WEBVTT', 0
raise HTTPException(422, 'Use MP4/WebM de até 100 MB ou legenda VTT de até 1 MB.')
raise HTTPException(422, 'Use MP4/WebM de até 500 MB ou legenda VTT de até 1 MB.')
def _checked_upload(c, uid, identity, expected):

71
app/api/stamps.py Normal file
View File

@@ -0,0 +1,71 @@
"""The montador's stamp sizes and its invoiced orders (Fase 2, front 7)."""
import hashlib
import json
from uuid import uuid4
from fastapi import APIRouter, Depends, HTTPException, Request
from psycopg.types.json import Jsonb
from .. import payments, quote_review
from ..core import db
from ..core.auth import audit, can
from ..core.models import Freight, MontadorOrder, QuoteRequest, StampSizeTable, UploadStart
from ..runtime import operator_identity
from .uploads import begin_upload
router = APIRouter()
@router.get('/api/operator/stamp-sizes')
def stamp_sizes(user=Depends(can('assemble'))):
with db.connect() as c:
rows = c.execute('SELECT letter,width_cm FROM dtf_local.stamp_sizes ORDER BY width_cm, letter').fetchall()
return {'sizes': rows}
@router.post('/api/operator/stamp-sizes')
def save_stamp_sizes(body: StampSizeTable, user=Depends(can('manage'))):
with db.connect() as c:
c.execute('DELETE FROM dtf_local.stamp_sizes')
c.cursor().executemany('INSERT INTO dtf_local.stamp_sizes(letter,width_cm,updated_by) VALUES(%s,%s,%s)',
[(row.letter, row.width_cm, user) for row in body.sizes])
audit('stamp_sizes_changed', operator=user, sizes=len(body.sizes))
return {'ok': True}
@router.post('/api/operator/montador/uploads')
def montador_upload(body: UploadStart, user=Depends(can('assemble'))):
if not body.name.lower().endswith('.png'):
raise HTTPException(422, 'A estampa precisa ser um PNG.')
return begin_upload(body, session_id=operator_identity(user))
@router.post('/api/operator/montador/orders')
def montador_order(body: MontadorOrder, request: Request, user=Depends(can('assemble'))):
"""The order a montador sheet becomes, already invoiced (front 7a.2b):
typed customer, pickup, the Site's table price, and held out of Tiny until
Dropstar decides how it is invoiced there."""
origin = 'dropflow' if request.state.operator['role'] == 'expedicao' else 'atendimento'
draft = QuoteRequest(request_key=body.request_key, customer=body.customer, items=body.items,
freight=Freight(service='pickup')).model_dump(mode='json', exclude={'request_key'})
draft['montador'] = True
digest = hashlib.sha256(json.dumps(draft, sort_keys=True).encode()).hexdigest()
owner = operator_identity(user)
with db.connect() as c:
c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft)
VALUES(%s,%s,%s,%s,%s) ON CONFLICT(owner,request_key) DO NOTHING''',
(uuid4(), owner, body.request_key, digest, Jsonb(draft)))
quote = c.execute('SELECT * FROM dtf_local.quotes WHERE owner=%s AND request_key=%s FOR UPDATE',
(owner, body.request_key)).fetchone()
if quote['request_hash'] != digest:
raise HTTPException(409, 'A montagem mudou durante o envio. Tente de novo.')
if not quote['approved']:
quote_review.approve(c, quote, body.items, user)
quote = c.execute('SELECT * FROM dtf_local.quotes WHERE id=%s', (quote['id'],)).fetchone()
receipt = {'provider': payments.MANUAL_PROVIDER, 'method': payments.INVOICED_METHOD, 'note': '',
'status': 'paid', 'total_cents': quote['approved']['total_cents'], 'operator': user}
order, created = payments.create_order(c, quote, receipt, origin)
if not created:
raise HTTPException(409, f"Esta montagem já virou o pedido #{order['number']}.")
audit('montador_order_created', order=str(order['id']), origin=origin, operator=user)
return order

View File

@@ -26,7 +26,7 @@ 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']
role: Literal['admin', 'gestao', 'designer', 'operador', 'revisor', 'vendedor', 'financeiro', 'expedicao']
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

View File

@@ -13,7 +13,7 @@ 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, machine_log, operator, orders, payments, quotes, reviews, site_admin, site_videos, uploads, users
from .api import artwork, customer, health, machine_log, operator, orders, payments, quotes, reviews, site_admin, site_videos, stamps, uploads, users
@asynccontextmanager
@@ -45,5 +45,5 @@ async def safe_headers(request, call_next):
# Order is not significant: no two routers declare the same path.
for module in (health, uploads, quotes, orders, payments, operator, customer, artwork, users, site_videos, site_admin, reviews, machine_log):
for module in (health, uploads, quotes, orders, payments, operator, customer, artwork, users, site_videos, site_admin, reviews, machine_log, stamps):
app.include_router(module.router)

View File

@@ -4,6 +4,7 @@ from pathlib import Path
from urllib.parse import urlparse
import psycopg
from psycopg import sql
from . import migrate
from .core.secrets import load as load_secret_files
from .operators import seed_from_environment
@@ -41,6 +42,7 @@ def main():
c.execute(sql.SQL('ALTER ROLE {} NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS PASSWORD {}').format(
sql.Identifier(role), sql.Literal(password)))
c.execute(Path(__file__).with_name('schema.sql').read_text())
applied = migrate.apply(c)
c.execute(sql.SQL('REVOKE CREATE ON SCHEMA public FROM PUBLIC'))
c.execute(sql.SQL('GRANT CONNECT ON DATABASE {} TO {}').format(sql.Identifier(database),sql.Identifier(role)))
c.execute(sql.SQL('GRANT USAGE ON SCHEMA dtf_local TO {}').format(sql.Identifier(role)))
@@ -54,6 +56,8 @@ def main():
# 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 applied:
print(f'Schema migrations applied: {", ".join(applied)}')
if seeded:
print(f'Seeded operator account {seeded} from OPERATOR_EMAIL.')

View File

@@ -125,7 +125,7 @@ def login_failed(email):
# 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')
ROLES = ('superadmin', 'admin', 'gestao', 'designer', 'operador', 'revisor', 'vendedor', 'financeiro', 'expedicao')
CAPABILITIES = {
'view': set(ROLES),
'produce': {'superadmin', 'admin', 'gestao', 'designer'},
@@ -155,6 +155,9 @@ CAPABILITIES = {
# The photo or video of the printed sheet in Revisão (Fase 2, front 2): who
# releases to Finalizado, and Gestão, which may stand in for them.
'inspect': {'superadmin', 'admin', 'gestao', 'revisor'},
# Montar folha (Fase 2, front 7): the new Expedição profile and the seller,
# who gets this one action although otherwise view-only (D-30).
'assemble': {'superadmin', 'admin', 'gestao', 'vendedor', 'expedicao'},
}
# Who moves which card (Dropstar's flow, 2026-10-23, and their rules of
@@ -238,4 +241,15 @@ def can(capability):
return check
def can_any(*capabilities):
"""A dependency that lets through a profile with any of these capabilities,
and returns the operator's e-mail, as the routes record it."""
def check(request: Request):
account = signed_in(request)
if not any(account['role'] in CAPABILITIES[capability] for capability in capabilities):
raise HTTPException(403, 'Seu perfil não permite esta ação.')
return account['email']
return check
operator = can('view')

View File

@@ -3,6 +3,8 @@ from pathlib import Path
import psycopg
from psycopg.rows import dict_row
from .. import migrate
def connect():
# Production passes credentials as discrete libpq fields. This avoids
# treating characters in a generated password as URL syntax. Local and
@@ -21,3 +23,4 @@ def initialize():
with connect() as c:
# The schema lives at the package root, one level up from core/.
c.execute((Path(__file__).resolve().parent.parent / 'schema.sql').read_text())
migrate.apply(c)

View File

@@ -288,6 +288,19 @@ class QuoteRequest(StrictModel):
raise ValueError('The delivery address CEP must be the CEP freight was quoted for')
return self
class MontadorOrder(StrictModel):
"""What the montador sends (front 7a.2b): the typed customer, pickup only
and loose artwork only; the server prices and approves it as a quote."""
request_key: UUID
customer: Customer
items: list[Item] = Field(min_length=1, max_length=30)
@model_validator(mode='after')
def loose_art_only(self):
if any(item.mode != 'avulsa' for item in self.items):
raise ValueError('O montador só monta artes avulsas.')
return self
class Review(StrictModel):
items: list[Item] = Field(min_length=1, max_length=30)
@@ -499,3 +512,19 @@ 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)
class StampSize(StrictModel):
"""One row of the montador's size table (Fase 2, front 7)."""
letter: str = Field(pattern=r'^[A-Z]{1,2}$')
width_cm: Decimal = Field(gt=0, le=56, decimal_places=2)
class StampSizeTable(StrictModel):
"""The whole table, replaced in one go by Gestão."""
sizes: list[StampSize] = Field(min_length=1, max_length=26)
@model_validator(mode='after')
def letters_unique(self):
letters = [row.letter for row in self.sizes]
if len(letters) != len(set(letters)):
raise ValueError('Cada tamanho tem uma letra própria.')
return self

34
app/migrate.py Normal file
View File

@@ -0,0 +1,34 @@
"""Timestamped schema migrations, applied once by the database initializer.
schema.sql is the frozen baseline and runs on every start; a change after it is
a file in app/migrations/, named YYYYMMDDHHMM_slug.sql. The name is the
migration's identity and is recorded in dtf_local.migrations, so a deploy never
applies one twice and an older image skips names it does not know.
"""
import re
from pathlib import Path
MIGRATIONS = Path(__file__).resolve().with_name('migrations')
LOCK = 804209
NAME = re.compile(r'\d{12}_[a-z0-9-]+\.sql')
def apply(c, directory=MIGRATIONS) -> list[str]:
"""Run, in name order, every migration file not yet recorded in
dtf_local.migrations, each recorded in the same transaction. A name in
the table that has no file (written by a newer image) is ignored, so an
older image still starts."""
c.execute('SELECT pg_advisory_xact_lock(%s)', (LOCK,))
files = {}
for path in Path(directory).iterdir():
if not path.is_file() or not NAME.fullmatch(path.name):
raise ValueError(f'Unexpected file in {directory}: {path.name}')
files[path.name] = path
applied = []
for name in sorted(files):
if c.execute('SELECT 1 FROM dtf_local.migrations WHERE name=%s', (name,)).fetchone():
continue
c.execute(files[name].read_text())
c.execute('INSERT INTO dtf_local.migrations(name) VALUES(%s)', (name,))
applied.append(name)
return applied

View File

@@ -0,0 +1,14 @@
-- The current lists of the three CHECK constraints whose values have grown
-- over time, applied once to every database, including one whose copy is older
-- (an image before front 7a lacks 'expedicao', for example). From now on,
-- widening a list is a new migration that drops and adds that one constraint.
ALTER TABLE dtf_local.operators DROP CONSTRAINT IF EXISTS operators_role;
ALTER TABLE dtf_local.operators ADD CONSTRAINT operators_role
CHECK (role IN ('superadmin','admin','gestao','designer','operador','revisor','vendedor','financeiro','expedicao'));
ALTER TABLE dtf_local.mail_queue DROP CONSTRAINT IF EXISTS mail_queue_kind_check;
ALTER TABLE dtf_local.mail_queue ADD CONSTRAINT mail_queue_kind_check
CHECK(kind IN ('reset','code','account','notice','order','alert','test'));
ALTER TABLE dtf_local.orders DROP CONSTRAINT IF EXISTS orders_origin_check;
ALTER TABLE dtf_local.orders ADD CONSTRAINT orders_origin_check CHECK (origin IN ('site','dropflow','atendimento'));

View File

@@ -0,0 +1,7 @@
-- Front 8.5: what the art grade decides, set in the Kanban's Site tab. No row
-- means no rule, and nothing changes; each action has at most one threshold.
CREATE TABLE IF NOT EXISTS dtf_local.grade_rules (
action text PRIMARY KEY CHECK (action IN ('aviso','tratamento')),
below integer NOT NULL CHECK (below BETWEEN 1 AND 100),
updated_by text NOT NULL, updated_at timestamptz NOT NULL DEFAULT now()
);

View File

@@ -60,12 +60,19 @@ def is_test(order):
# (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')
# A montador order is invoiced, not paid at the counter: it is not one of the
# Cotações "registrar" methods.
INVOICED_METHOD = 'faturado'
def in_tiny(order):
"""Whether the order goes to Tiny: every order but a test or a proof card
(app/proof.py), which is no sale. A Dropflow order goes in its own revenue
category (app/tiny.py, CATEGORIES)."""
if (order.get('payment') or {}).get('method') == INVOICED_METHOD:
# Held until Dropstar decides how invoiced montador orders reach Tiny
# (asked 2026-11-09).
return False
return not is_test(order) and not order.get('parent_id')
@@ -146,7 +153,10 @@ def create_order(c, quote, payment, origin):
proof.create_child(c, order)
if is_test(order):
return order, True
mail.order_paid(c, order, PUBLIC_ORIGIN)
# An invoiced montador order was not paid: no "pedido pago" e-mail until
# Dropstar says what the customer hears (asked 2026-11-09).
if payment.get('method') != INVOICED_METHOD:
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.

View File

@@ -108,6 +108,10 @@ def approve(c, row, items, reviewer):
offer = catalog.current(c)['tratamento']
offered = bool(offer['enabled'] and offer['unit_cents'] > 0)
flags = grade_rules.triggered(grade_rules.current_rules(c), priced, offered)
# A montador sheet (front 7a) is assembled by the team from Estampas/, not
# sent by a customer: the treatment rule does not apply to it.
if draft.get('montador'):
flags.pop('tratamento', None)
if 'tratamento' in flags and not draft.get('treatment'):
raise HTTPException(422, grade_rules.treatment_message(flags['tratamento']))
items_total = sum(i['total_cents'] for i in priced)

View File

@@ -284,11 +284,18 @@ CREATE TABLE IF NOT EXISTS dtf_local.cnpj_names (
-- 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.
-- vendedores only read; expedição assembles sheets in the Kanban's montador.
ALTER TABLE dtf_local.operators ADD COLUMN IF NOT EXISTS role text NOT NULL DEFAULT 'admin';
ALTER TABLE dtf_local.operators 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'));
-- Created once, and widened only by a migration: re-adding it on every start
-- would let an older image narrow the list and refuse rows written under a
-- later one, and the database would not finish starting.
DO $$ BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname='operators_role'
AND conrelid='dtf_local.operators'::regclass) THEN
ALTER TABLE dtf_local.operators ADD CONSTRAINT operators_role
CHECK (role IN ('superadmin','admin','gestao','designer','operador','revisor','vendedor','financeiro','expedicao'));
END IF;
END $$;
-- Print machines and which products each prints. An order gets its machine
-- when someone pulls it into Imprimindo; no machine is assigned at payment.
-- limit_metres remains the load shown for a machine.
@@ -410,11 +417,16 @@ UPDATE dtf_local.accounts a SET email_verified=true WHERE NOT a.email_verified A
-- E-mail kinds: a password-recovery link, a code, the notice that an account
-- 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'));
-- Created once, and widened only by a migration: the schema runs on every
-- start, and re-adding an earlier, narrower copy would refuse the rows of the
-- kinds added after it.
DO $$ BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname='mail_queue_kind_check'
AND conrelid='dtf_local.mail_queue'::regclass) THEN
ALTER TABLE dtf_local.mail_queue ADD CONSTRAINT mail_queue_kind_check
CHECK(kind IN ('reset','code','account','notice','order','alert','test'));
END IF;
END $$;
-- The print proof (Dropstar, 2026-10-21): an order above 10 m, or one whose
-- customer asked for a proof at checkout, prints 20 cm first; the room marks
@@ -452,8 +464,13 @@ WHERE o.contact_since IS NOT NULL AND NOT EXISTS (SELECT 1 FROM dtf_local.contac
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS origin text;
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'));
-- Created once, and widened only by a migration; never re-added on start.
DO $$ BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname='orders_origin_check'
AND conrelid='dtf_local.orders'::regclass) THEN
ALTER TABLE dtf_local.orders ADD CONSTRAINT orders_origin_check CHECK (origin IN ('site','dropflow','atendimento'));
END IF;
END $$;
-- 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
@@ -618,6 +635,15 @@ CREATE TABLE IF NOT EXISTS dtf_local.product_prices (
);
CREATE INDEX IF NOT EXISTS product_prices_current ON dtf_local.product_prices(product, starts_at DESC);
-- Front 7a: the stamp sizes of the Kanban's montador; Gestão edits them.
CREATE TABLE IF NOT EXISTS dtf_local.stamp_sizes (
letter text PRIMARY KEY CHECK (letter ~ '^[A-Z]{1,2}$'),
width_cm numeric(5,2) NOT NULL CHECK (width_cm > 0 AND width_cm <= 56),
updated_by text NOT NULL DEFAULT 'sistema',
updated_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO dtf_local.stamp_sizes(letter,width_cm) VALUES ('A',20),('B',24),('C',27),('D',30)
ON CONFLICT (letter) DO NOTHING;
-- Front 8.2: a price may also have bands by the order's total metres of that
-- product: base price, then "from 5 m R$ Y", "from 20 m R$ Z" (jsonb list of
-- {"from_metres": "5", "unit_cents": 1990}, strictly increasing, at most 5).
@@ -644,11 +670,3 @@ CREATE TABLE IF NOT EXISTS dtf_local.coupons (
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE UNIQUE INDEX IF NOT EXISTS coupons_live_code ON dtf_local.coupons(code) WHERE deleted_at IS NULL;
-- Front 8.5: what the art grade decides, set in the Kanban's Site tab. No row
-- means no rule, and nothing changes; each action has at most one threshold.
CREATE TABLE IF NOT EXISTS dtf_local.grade_rules (
action text PRIMARY KEY CHECK (action IN ('aviso','tratamento')),
below integer NOT NULL CHECK (below BETWEEN 1 AND 100),
updated_by text NOT NULL, updated_at timestamptz NOT NULL DEFAULT now()
);

View File

@@ -53,10 +53,13 @@ def cleanup():
c.execute("DELETE FROM dtf_local.security_events WHERE created_at<now()-interval '30 days'")
def tick():
"""Deliver at most one outbox job; True when there was one, False otherwise."""
global last_tick
processed = False
with connect() as c:
job = c.execute('SELECT * FROM dtf_local.outbox WHERE delivered_at IS NULL AND available_at <= now() ORDER BY id FOR UPDATE SKIP LOCKED LIMIT 1').fetchone()
if job:
processed = True
try:
receipt = adapters[job['provider']].deliver(job['event_key'], job['payload'])
c.execute('UPDATE dtf_local.outbox SET delivered_at=now(), receipt=%s, attempts=attempts+1, last_error=NULL WHERE id=%s', (Jsonb(receipt),job['id']))
@@ -64,6 +67,14 @@ def tick():
delay = min(1800, 2**min(job['attempts']+1, 10))
c.execute("UPDATE dtf_local.outbox SET attempts=attempts+1, last_error=%s, available_at=now() + %s * interval '1 second' WHERE id=%s", (str(exc),delay,job['id']))
last_tick = time.monotonic()
return processed
def drain(limit=50):
"""Deliver up to `limit` outbox jobs in one pass, so a backlog leaves at
once instead of one job per second (Critical Corrections item 9)."""
for _ in range(limit):
if not tick():
return
def tiny_keepalive():
"""Keep a connected Tiny authorised even while no orders are sent.
@@ -118,7 +129,7 @@ def loop():
global last_cleanup
while True:
try:
tick()
drain()
if time.monotonic()-last_cleanup > 60:
cleanup()
# Approved quotes unpaid for 24 h expire on their own (front 9).