feat: the proof card, a child order the seller answers (Dropstar, 30/10 and 03/11)
Some checks failed
Build and deploy / Validate source (push) Successful in 1m8s
Build and deploy / Integration suite on a real stack (push) Failing after 3m14s
Build and deploy / Publish images (push) Has been skipped
Build and deploy / Secret scan and release gate (push) Successful in 9s
Some checks failed
Build and deploy / Validate source (push) Successful in 1m8s
Build and deploy / Integration suite on a real stack (push) Failing after 3m14s
Build and deploy / Publish images (push) Has been skipped
Build and deploy / Secret scan and release gate (push) Successful in 9s
An order with a proof (asked for at checkout, or above 10 m) gets a child
card "Prova": an order of its own (orders.parent_id), no sale, with the
film's first 30 cm as DTF-N-item-1-prova.png ("Prova do pedido DTF-N" in its
footer), which follows the flow up to Revisão like any card, hot folder
included. The order waits outside the queue, "Aguardando prova": it is not
pulled to Imprimindo, nor counted in the queue's places.
In Revisão the card is answered by the Vendedor, Gestão or the
Administrador (capability "proof"): Prova OK records who and when and puts
the order in Arte conferida when its finals are approved; Prova reprovada,
with its reason, sends the order back to Arte recebida, its final to be
approved again, and offers "Nova prova". Either way the card closes and
leaves the board. An order from before the cards keeps the old Prova OK.
The card is kept out of Tiny, e-mails, Números, the search, Finalizado and
the customer's account. Deleting an order takes its cards and their rows:
movements, order files and print files now cascade with their order.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -111,9 +111,10 @@ def board(user=Depends(operator)):
|
||||
# card they can act on. Finished orders are terminal and only accumulate,
|
||||
# so the board carries a recent window of them and reports the true total.
|
||||
active = c.execute("SELECT * FROM dtf_local.orders WHERE state<>'fin' ORDER BY created_at").fetchall()
|
||||
finished = c.execute("SELECT * FROM dtf_local.orders WHERE state='fin' ORDER BY created_at DESC LIMIT %s",
|
||||
(BOARD_FINISHED_LIMIT,)).fetchall()
|
||||
finished_total = c.execute("SELECT count(*) AS n FROM dtf_local.orders WHERE state='fin'").fetchone()['n']
|
||||
# A proof card that got its answer is done with (app/proof.py).
|
||||
finished = c.execute("""SELECT * FROM dtf_local.orders WHERE state='fin' AND parent_id IS NULL
|
||||
ORDER BY created_at DESC LIMIT %s""", (BOARD_FINISHED_LIMIT,)).fetchall()
|
||||
finished_total = c.execute("SELECT count(*) AS n FROM dtf_local.orders WHERE state='fin' AND parent_id IS NULL").fetchone()['n']
|
||||
pending = c.execute(f'''SELECT q.* FROM dtf_local.quotes q
|
||||
LEFT JOIN dtf_local.orders o ON o.quote_id=q.id
|
||||
WHERE o.id IS NULL AND q.approved IS NULL AND {LIVE_QUOTE}
|
||||
@@ -238,8 +239,19 @@ def with_print_files(c, orders):
|
||||
FROM dtf_local.movements WHERE order_id=ANY(%s) AND to_state='cor' ORDER BY order_id,id DESC''', (ids,)).fetchall()}
|
||||
# Where a printing order's files are in its machine's hot folder (item 10).
|
||||
hot = hotfolder.progress(c, [o['id'] for o in orders if o['state'] == 'imp'])
|
||||
# Each parent's latest proof card, and each card's parent (app/proof.py).
|
||||
children = {r['parent_id']: r for r in c.execute('''SELECT DISTINCT ON (parent_id) parent_id,id,number,state,
|
||||
proof_result,proof_decided_at,proof_decided_by,proof_reason FROM dtf_local.orders
|
||||
WHERE parent_id=ANY(%s) AND cancelled_at IS NULL ORDER BY parent_id, created_at DESC''', (ids,)).fetchall()}
|
||||
parents = {r['id']: r for r in c.execute('SELECT id,number,state FROM dtf_local.orders WHERE id=ANY(%s)',
|
||||
([o['parent_id'] for o in orders if o.get('parent_id')],)).fetchall()}
|
||||
for order in orders:
|
||||
order['hot'] = hot.get(order['id'])
|
||||
child = children.get(order['id'])
|
||||
order['proof_card'] = child and {k: child[k] for k in ('id', 'number', 'state', 'proof_result',
|
||||
'proof_decided_at', 'proof_decided_by', 'proof_reason')}
|
||||
parent = parents.get(order.get('parent_id'))
|
||||
order['proof_parent'] = parent and {'id': parent['id'], 'number': parent['number'], 'state': parent['state']}
|
||||
order['correction_reason'] = reasons.get(order['id']) if order['state'] == 'cor' else None
|
||||
order['print_files'] = [row for row in generated if row['order_id'] == order['id']]
|
||||
approved = [row for row in finals if row['order_id'] == order['id']]
|
||||
@@ -271,7 +283,7 @@ def finished_page(before_created_at: datetime | None = None, before_id: UUID | N
|
||||
"""Older finished orders, newest first, beyond the board's recent window."""
|
||||
paged = cursor_pair(before_created_at, before_id)
|
||||
with db.connect() as c:
|
||||
rows = c.execute('''SELECT * FROM dtf_local.orders WHERE state='fin'
|
||||
rows = c.execute('''SELECT * FROM dtf_local.orders WHERE state='fin' AND parent_id IS NULL
|
||||
''' + ('AND (created_at,id)<(%s,%s) ' if paged else '') + '''
|
||||
ORDER BY created_at DESC,id DESC LIMIT %s''',
|
||||
((before_created_at, before_id) if paged else ()) + (limit + 1,)).fetchall()
|
||||
@@ -436,7 +448,8 @@ def search(q: str = Query(min_length=2, max_length=100), user=Depends(operator))
|
||||
params.append(code + '%')
|
||||
quote_match, quote_params = customer_match('q.draft', q)
|
||||
with db.connect() as c:
|
||||
orders = c.execute(f'''SELECT * FROM dtf_local.orders WHERE {sql}
|
||||
# Real orders: a proof card is found through its order (app/proof.py).
|
||||
orders = c.execute(f'''SELECT * FROM dtf_local.orders WHERE ({sql}) AND parent_id IS NULL
|
||||
ORDER BY created_at DESC LIMIT 8''', params).fetchall()
|
||||
rows = c.execute(f'''SELECT q.* FROM dtf_local.quotes q
|
||||
LEFT JOIN dtf_local.orders o ON o.quote_id=q.id
|
||||
@@ -603,8 +616,10 @@ def delete_order(uid: UUID, user=Depends(can('manage'))):
|
||||
UNION SELECT upload_id FROM dtf_local.print_parts WHERE order_id=%s''',
|
||||
(uid, uid, uid)).fetchall()}
|
||||
candidates = produced - originals if test else produced | originals
|
||||
# Its proof cards (app/proof.py) go with it.
|
||||
cards = [r['id'] for r in c.execute('SELECT id FROM dtf_local.orders WHERE parent_id=%s', (uid,)).fetchall()]
|
||||
for table in ('movements', 'order_files', 'print_files'):
|
||||
c.execute(f'DELETE FROM dtf_local.{table} WHERE order_id=%s', (uid,))
|
||||
c.execute(f'DELETE FROM dtf_local.{table} WHERE order_id=ANY(%s)', ([uid] + cards,))
|
||||
c.execute('DELETE FROM dtf_local.outbox WHERE event_key LIKE %s', (f'{uid}:%',))
|
||||
c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (uid,))
|
||||
if not test:
|
||||
@@ -744,10 +759,78 @@ def contact(uid: UUID, body: ContactWait, user=Depends(can('produce'))):
|
||||
return {'ok': True}
|
||||
|
||||
|
||||
class ProofAnswer(StrictModel):
|
||||
result: Literal['ok', 'rejected']
|
||||
reason: str = Field(default='', max_length=500)
|
||||
|
||||
|
||||
@router.post('/api/operator/orders/{uid}/proof-answer')
|
||||
def proof_answer(uid: UUID, body: ProofAnswer, user=Depends(can('proof'))):
|
||||
"""The answer to a proof card in Revisão (Dropstar, 2026-11-03): Prova OK
|
||||
puts its order in the queue; Prova reprovada, with its reason, sends the
|
||||
order back to Arte recebida. Either way the card closes."""
|
||||
reason = ' '.join(body.reason.split())
|
||||
if body.result == 'rejected' and len(reason) < 3:
|
||||
raise HTTPException(422, 'Diga por que a prova foi reprovada.')
|
||||
with db.connect() as c:
|
||||
card = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
|
||||
if not card or not card.get('parent_id'):
|
||||
raise HTTPException(404, 'Card de prova não encontrado.')
|
||||
if card['cancelled_at'] or card['proof_result'] or card['state'] != 'rev':
|
||||
raise HTTPException(409, 'A prova é respondida em Revisão, uma vez.')
|
||||
parent = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (card['parent_id'],)).fetchone()
|
||||
c.execute('''UPDATE dtf_local.orders SET proof_result=%s, proof_decided_at=now(), proof_decided_by=%s,
|
||||
proof_reason=%s, state='fin', version=version+1, updated_at=now() WHERE id=%s''',
|
||||
(body.result, user, reason or None, uid))
|
||||
label = 'Prova OK' if body.result == 'ok' else 'Prova reprovada: ' + reason
|
||||
c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason)
|
||||
VALUES(%s,'rev','fin',%s,%s)''', (uid, user, label))
|
||||
if body.result == 'ok':
|
||||
# The order enters the queue: Arte conferida, if its finals are approved.
|
||||
ready = parent['state'] == 'rec' and all(c.execute('''SELECT 1 FROM dtf_local.order_files
|
||||
WHERE order_id=%s AND kind='final' AND active AND item_index=%s LIMIT 1''', (parent['id'], i)).fetchone()
|
||||
for i in range(len(parent['snapshot']['items'])))
|
||||
c.execute('''UPDATE dtf_local.orders SET proof_ok_at=now(), proof_ok_by=%s, version=version+1, updated_at=now(),
|
||||
state=CASE WHEN %s THEN 'tra' ELSE state END WHERE id=%s''', (user, ready, parent['id']))
|
||||
if ready:
|
||||
c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason)
|
||||
VALUES(%s,'rec','tra',%s,'Prova OK')''', (parent['id'], user))
|
||||
elif parent['state'] in ('rec', 'tra') and not parent['cancelled_at']:
|
||||
# Back to Arte recebida with the reason; its final is approved again.
|
||||
c.execute("UPDATE dtf_local.order_files SET active=false WHERE order_id=%s AND kind='final'", (parent['id'],))
|
||||
c.execute('''UPDATE dtf_local.orders SET state='rec', proof_ok_at=NULL, proof_ok_by=NULL, queue_key=NULL,
|
||||
version=version+1, updated_at=now() WHERE id=%s''', (parent['id'],))
|
||||
c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason)
|
||||
VALUES(%s,%s,'rec',%s,%s)''', (parent['id'], parent['state'], user, label))
|
||||
audit('order_proof_answered', order=parent['number'], result=body.result, operator=user)
|
||||
return {'ok': True}
|
||||
|
||||
|
||||
@router.post('/api/operator/orders/{uid}/proof-card')
|
||||
def new_proof_card(uid: UUID, user=Depends(can('produce'))):
|
||||
"""A new proof card for an order whose proof was rejected, or that has
|
||||
none yet (an order from before the cards)."""
|
||||
with db.connect() as c:
|
||||
row = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
|
||||
if not row or row.get('parent_id'):
|
||||
raise HTTPException(404, 'Pedido não encontrado.')
|
||||
if row['cancelled_at'] or row['state'] not in ('rec', 'tra') or row['proof_ok_at'] or proof.open_child(c, uid):
|
||||
raise HTTPException(409, 'Este pedido já tem uma prova em andamento ou aprovada.')
|
||||
child = proof.create_child(c, row)
|
||||
if not child:
|
||||
raise HTTPException(409, 'Este pedido não leva prova.')
|
||||
machines.route(c)
|
||||
audit('order_proof_card', order=row['number'], operator=user)
|
||||
return {'ok': True, 'id': child['id'], 'number': child['number']}
|
||||
|
||||
|
||||
@router.post('/api/operator/orders/{uid}/proof')
|
||||
def proof_ok(uid: UUID, user=Depends(can('print'))):
|
||||
"""The print room checked the proof: the order may reach Finalizado."""
|
||||
"""An order from before the proof cards: the print room checked the
|
||||
proof, and the order may reach Finalizado."""
|
||||
with db.connect() as c:
|
||||
if proof.open_child(c, uid):
|
||||
raise HTTPException(409, 'Este pedido tem um card de prova: a resposta vai nele.')
|
||||
row = c.execute('''UPDATE dtf_local.orders SET proof_ok_at=now(), proof_ok_by=%s, version=version+1
|
||||
WHERE id=%s AND cancelled_at IS NULL AND state<>'fin' RETURNING number, version''', (user, uid)).fetchone()
|
||||
if not row:
|
||||
@@ -968,7 +1051,13 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
|
||||
# Two at most per machine in Imprimindo (app/machines.py).
|
||||
if body.state == 'imp' and (name := machines.full(c, row['machine_id'], uid)):
|
||||
raise HTTPException(409, f'{name} já tem {machines.PRINTING_CAP} em Imprimindo.')
|
||||
if body.state == 'fin' and proof.needs_proof(row['snapshot']) and not row['proof_ok_at']:
|
||||
# A proof card ends with its answer, not in Finalizado; its order waits
|
||||
# for that answer outside the queue (app/proof.py).
|
||||
if row.get('parent_id') and body.state == 'fin':
|
||||
raise HTTPException(409, 'A prova termina com Prova OK ou Prova reprovada, não em Finalizado.')
|
||||
if body.state == 'imp' and proof.waiting(c, row):
|
||||
raise HTTPException(409, 'Aguardando prova: o pedido entra na fila com Prova OK no card da prova.')
|
||||
if body.state == 'fin' and not row.get('parent_id') and proof.needs_proof(row['snapshot']) and not row['proof_ok_at']:
|
||||
raise HTTPException(409, 'Falta a prova: confira a prova impressa e marque Prova OK antes de finalizar.')
|
||||
if body.state == 'cor':
|
||||
c.execute("UPDATE dtf_local.order_files SET active=false WHERE order_id=%s AND kind='final'", (uid,))
|
||||
@@ -1124,7 +1213,8 @@ def thumbnail(uid: UUID, user=Depends(operator)):
|
||||
headers={'Cache-Control': 'private, max-age=86400', 'Content-Disposition': 'inline'})
|
||||
|
||||
# Real work only: an operator's test order and a cancelled one are not production.
|
||||
REAL_ORDER = "o.cancelled_at IS NULL AND COALESCE(o.payment->>'provider','') <> 'teste'"
|
||||
# A proof card (app/proof.py) is no sale either.
|
||||
REAL_ORDER = "o.cancelled_at IS NULL AND COALESCE(o.payment->>'provider','') <> 'teste' AND o.parent_id IS NULL"
|
||||
# Where orders come from (D-21), in the order Números lists them.
|
||||
ORIGINS = ('site', 'dropflow', 'atendimento')
|
||||
LOCAL_DAY = "(o.created_at AT TIME ZONE 'America/Sao_Paulo')::date"
|
||||
|
||||
@@ -145,6 +145,9 @@ CAPABILITIES = {
|
||||
# file. Resolving a payment stays with "manage".
|
||||
'payments': {'superadmin', 'admin', 'gestao', 'financeiro'},
|
||||
'cancel': {'superadmin', 'admin', 'gestao', 'financeiro'},
|
||||
# Prova OK or reprovada, on the proof card only (Dropstar, 2026-11-03): the
|
||||
# seller, who otherwise only views, Gestão and the administrators.
|
||||
'proof': {'superadmin', 'admin', 'gestao', 'vendedor'},
|
||||
# "Retirado" at the counter (Dropstar's third round, item 14): everyone
|
||||
# but the seller, who only views (D-30). It includes everyone who produces,
|
||||
# and the operator, so an operator upload (artwork.py) takes it for its parts.
|
||||
|
||||
@@ -63,9 +63,10 @@ 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)
|
||||
"""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)."""
|
||||
return not is_test(order) and not order.get('parent_id')
|
||||
|
||||
|
||||
# How long a file is kept while nothing has been paid for it. A cart's files
|
||||
@@ -118,6 +119,8 @@ def create_order(c, quote, payment, origin):
|
||||
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'],))
|
||||
# An order with a proof gets its proof card (app/proof.py).
|
||||
proof.create_child(c, order)
|
||||
machines.route(c)
|
||||
if is_test(order):
|
||||
return order, True
|
||||
|
||||
@@ -32,6 +32,7 @@ from .core.auth import audit
|
||||
from .core.db import connect
|
||||
from .printfile import Unsupported
|
||||
from .printpng import render
|
||||
from .proof import PROOF_SHEET_CM
|
||||
from .tiny import purchase_order
|
||||
|
||||
LOCAL = ZoneInfo('America/Sao_Paulo')
|
||||
@@ -159,6 +160,10 @@ def footer(job, item):
|
||||
count = len(job['snapshot']['items'])
|
||||
day = job['ordered_at'].astimezone(LOCAL).strftime('%d/%m/%Y')
|
||||
billed = f"{Decimal(str(item['billed_metres'])):.2f}".replace('.', ',')
|
||||
proof_of = job['snapshot'].get('proof_of')
|
||||
if proof_of:
|
||||
return ' · '.join(['DROPSTAR', f'Prova do pedido {purchase_order(proof_of)}',
|
||||
f'Item {job["item_index"] + 1}/{count}', day])
|
||||
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
|
||||
@@ -185,8 +190,12 @@ def produce(storage, job, 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'])
|
||||
parts, detail = render(item, files, output, file_prefix(job['number'], job['item_index']),
|
||||
footer=footer(job, item), tiles=True)
|
||||
proof_of = job['snapshot'].get('proof_of')
|
||||
# A proof card's file: the first 30 cm, DTF-N-item-1-prova.png (app/proof.py).
|
||||
prefix = (file_prefix(proof_of, job['item_index']) + '-prova' if proof_of
|
||||
else file_prefix(job['number'], job['item_index']))
|
||||
parts, detail = render(item, files, output, prefix, footer=footer(job, item), tiles=True,
|
||||
limit_cm=PROOF_SHEET_CM if proof_of else None)
|
||||
except BaseException:
|
||||
shutil.rmtree(output, ignore_errors=True)
|
||||
raise
|
||||
|
||||
@@ -425,7 +425,7 @@ def footer_band(text, width):
|
||||
|
||||
# ---- The file ---------------------------------------------------------------
|
||||
|
||||
def render(item, files, out_dir, prefix, footer=None, part_cm=None, tiles=False):
|
||||
def render(item, files, out_dir, prefix, footer=None, part_cm=None, tiles=False, limit_cm=None):
|
||||
"""Write the PNG part(s) of one approved order item into `out_dir`.
|
||||
|
||||
`files` maps each source index to (local path, original name). With
|
||||
@@ -443,7 +443,9 @@ def render(item, files, out_dir, prefix, footer=None, part_cm=None, tiles=False)
|
||||
width = px(production['film_width_cm'])
|
||||
pieces = sorted((Piece(placement, sources[placement['source_index']])
|
||||
for placement in production['placements']), key=lambda piece: piece.y)
|
||||
cuts = part_cuts(production, part_cm)
|
||||
# A proof sheet is the film's first `limit_cm` (app/proof.py).
|
||||
cuts = ([Decimal(0), min(Decimal(str(production['height_cm'])), Decimal(str(limit_cm)))] if limit_cm
|
||||
else part_cuts(production, part_cm))
|
||||
count = len(cuts) - 1
|
||||
parts, manifests = [], []
|
||||
for number in range(count):
|
||||
|
||||
50
app/proof.py
50
app/proof.py
@@ -11,6 +11,9 @@ marks "Prova OK" once the proof is checked, and without it the order does not
|
||||
reach Finalizado.
|
||||
"""
|
||||
from decimal import Decimal
|
||||
from uuid import NAMESPACE_URL, uuid4, uuid5
|
||||
|
||||
from psycopg.types.json import Jsonb
|
||||
|
||||
PROOF_ABOVE_METRES = Decimal('10')
|
||||
CUSTOMER_NOTE = ('O cliente pediu uma prova antes de imprimir: mande a foto da prova pelo WhatsApp '
|
||||
@@ -24,3 +27,50 @@ def billed_metres(snapshot):
|
||||
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
|
||||
|
||||
|
||||
# ---- The proof card (Dropstar's third round, 2026-10-30 and 2026-11-03) -----
|
||||
#
|
||||
# An order with a proof becomes a parent and a child. The child, the card
|
||||
# "Prova", is an order of its own (orders.parent_id) with a pre-built proof
|
||||
# sheet of up to 30 cm, DTF-N-item-1-prova.png, and follows the normal flow up
|
||||
# to Revisão. The parent waits outside the queue, "Aguardando prova". On the
|
||||
# child, the Vendedor (Gestão and the Administrador too) marks Prova OK, and
|
||||
# the parent enters the queue; or Prova reprovada, with its reason, and the
|
||||
# parent goes back to Arte recebida and the child closes. The child is no
|
||||
# sale: it is not in Tiny, Números, the customer's account or their e-mails.
|
||||
PROOF_SHEET_CM = Decimal('30')
|
||||
# Three proofs at most per order, one per item (Dropstar, 2026-10-23).
|
||||
MAX_PROOFS = 3
|
||||
PROVIDER = 'prova'
|
||||
|
||||
|
||||
def proof_identity(order_id):
|
||||
return uuid5(NAMESPACE_URL, f'dtf-proof:{order_id}')
|
||||
|
||||
|
||||
def create_child(c, parent):
|
||||
"""The parent's proof card, in Arte recebida, its proof sheets queued to be
|
||||
generated. Returns it, or None when the order needs no proof."""
|
||||
if parent.get('parent_id') or not needs_proof(parent['snapshot']):
|
||||
return None
|
||||
from .printjobs import queue
|
||||
snapshot = {**parent['snapshot'], 'items': parent['snapshot']['items'][:MAX_PROOFS],
|
||||
'proof_of': parent['number']}
|
||||
child = c.execute('''INSERT INTO dtf_local.orders(id,owner,snapshot,payment,origin,parent_id,machine_id,machine_chosen)
|
||||
VALUES(%s,%s,%s,%s,%s,%s,%s,%s) RETURNING *''',
|
||||
(uuid4(), proof_identity(parent['id']), Jsonb(snapshot), Jsonb({'provider': PROVIDER}),
|
||||
parent['origin'], parent['id'], parent.get('machine_id'), parent.get('machine_chosen', False))).fetchone()
|
||||
queue(c, child['id'], len(snapshot['items']))
|
||||
return child
|
||||
|
||||
|
||||
def open_child(c, parent_id):
|
||||
"""The parent's proof card still waiting for its answer, if any."""
|
||||
return c.execute('''SELECT * FROM dtf_local.orders WHERE parent_id=%s AND proof_result IS NULL
|
||||
AND cancelled_at IS NULL ORDER BY created_at DESC LIMIT 1''', (parent_id,)).fetchone()
|
||||
|
||||
|
||||
def waiting(c, order):
|
||||
"""Whether the order waits for its proof: it has a proof card without an OK."""
|
||||
return not order.get('parent_id') and not order.get('proof_ok_at') and bool(open_child(c, order['id']))
|
||||
|
||||
@@ -456,6 +456,32 @@ ALTER TABLE dtf_local.operator_sessions ADD COLUMN IF NOT EXISTS machine_answere
|
||||
-- The contraction class chosen per item (item 9), keyed by item index, with
|
||||
-- who chose it and when; the measured class stays in the order's snapshot.
|
||||
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS contraction jsonb NOT NULL DEFAULT '{}'::jsonb;
|
||||
|
||||
-- The proof card (Dropstar, 2026-10-30, app/proof.py): an order of its own,
|
||||
-- child of the order it proves, with no quote of its own; its answer, Prova OK
|
||||
-- or reprovada with its reason, by whom and when.
|
||||
ALTER TABLE dtf_local.orders ALTER COLUMN quote_id DROP NOT NULL;
|
||||
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS parent_id uuid REFERENCES dtf_local.orders(id) ON DELETE CASCADE;
|
||||
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS proof_result text CHECK (proof_result IN ('ok','rejected'));
|
||||
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS proof_decided_at timestamptz;
|
||||
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS proof_decided_by text;
|
||||
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS proof_reason text;
|
||||
CREATE INDEX IF NOT EXISTS orders_parent ON dtf_local.orders(parent_id) WHERE parent_id IS NOT NULL;
|
||||
-- An order's own rows go with it, so deleting an order takes its proof cards
|
||||
-- and theirs too. Done once: a constraint already cascading is left alone.
|
||||
DO $$
|
||||
DECLARE r record;
|
||||
BEGIN
|
||||
FOR r IN SELECT c.conname, c.conrelid::regclass AS tbl FROM pg_constraint c
|
||||
WHERE c.contype='f' AND c.confrelid='dtf_local.orders'::regclass AND c.confdeltype<>'c'
|
||||
AND c.conrelid IN ('dtf_local.movements'::regclass, 'dtf_local.order_files'::regclass,
|
||||
'dtf_local.print_files'::regclass)
|
||||
LOOP
|
||||
EXECUTE format('ALTER TABLE %s DROP CONSTRAINT %I', r.tbl, r.conname);
|
||||
EXECUTE format('ALTER TABLE %s ADD CONSTRAINT %I FOREIGN KEY (order_id) REFERENCES dtf_local.orders(id) ON DELETE CASCADE',
|
||||
r.tbl, r.conname);
|
||||
END LOOP;
|
||||
END $$;
|
||||
-- When the session was last used (Usuários: who is on the system now).
|
||||
ALTER TABLE dtf_local.operator_sessions ADD COLUMN IF NOT EXISTS seen_at timestamptz;
|
||||
-- The machine of whoever moved a card, as it was named then: "Imprimindo ·
|
||||
|
||||
Reference in New Issue
Block a user