feat: the pickup receipt in Recibos/ and "Retirado" on the card (Dropstar's third round, item 14)
All checks were successful
Build and deploy / Validate source (push) Successful in 4s
Build and deploy / Integration suite on a real stack (push) Successful in 3m38s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 59s
All checks were successful
Build and deploy / Validate source (push) Successful in 4s
Build and deploy / Integration suite on a real stack (push) Successful in 3m38s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 59s
A pickup order reaching Finalizado has its receipt due: a PDF for the 80 mm roll with the order number large at the top, the customer and CPF/CNPJ, each product and its metres, the amount and how it was paid, the date issued, and the "Retirado em" and "Assinatura" lines (app/receipt.py). The Kanban's folder saves it in Recibos/, where the counter's print queue sends it to the Bematech. One computer claims each receipt on the server before writing it, so it is never printed twice, and gives it back if it could not save it. Orders sent by carrier have none. "Retirado" on a pickup in Finalizado records when and who handed it over, with an optional photo of the signed receipt (kept 30 days). Anyone but the seller may mark it (new "deliver" capability); the order panel also opens the receipt to print it again. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -28,16 +28,18 @@ def begin_final(oid: UUID, body: UploadStart, user=Depends(can('produce'))):
|
||||
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('produce'))):
|
||||
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('produce'))):
|
||||
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('produce'))):
|
||||
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')
|
||||
|
||||
@@ -15,12 +15,13 @@ from pydantic import Field
|
||||
from ..core import db
|
||||
from ..core.auth import (COOKIE_SECURE, DUMMY_PASSWORD_HASH, MOVERS, audit, can, client_ip, operator,
|
||||
login_failed, may_move, may_reorder, password_matches, throttle)
|
||||
from ..core.models import Move, OperatorLogin, Resolution, Review, StrictModel
|
||||
from ..core.models import Move, OperatorLogin, Resolution, Review, StrictModel, UploadStart
|
||||
from ..printjobs import file_prefix, queue as queue_print_files
|
||||
from .. import cnpj, machines, mail, payments, proof, quote_review
|
||||
from .. import cnpj, machines, mail, payments, proof, quote_review, receipt
|
||||
from .. import tiny
|
||||
from ..runtime import (BACK, BOARD_FINISHED_LIMIT, BOARD_QUOTE_LIMIT, ENVIRONMENT, PUBLIC_ORIGIN, STATES,
|
||||
TRANSITIONS, payment, enqueue, freight, quote_view, storage)
|
||||
TRANSITIONS, payment, enqueue, freight, operator_identity, quote_view, storage, upload_row)
|
||||
from .uploads import begin_upload
|
||||
from ..scanning import require_clean
|
||||
|
||||
router = APIRouter()
|
||||
@@ -694,6 +695,105 @@ def proof_ok(uid: UUID, user=Depends(can('print'))):
|
||||
return {'ok': True, 'version': row['version']}
|
||||
|
||||
|
||||
def paid_with(c, order):
|
||||
"""How the order was paid, for its receipt: pix, card, cash, credit, or
|
||||
'teste' for an operator's test order."""
|
||||
paid = order.get('payment') or {}
|
||||
if paid.get('provider') == 'teste':
|
||||
return 'teste'
|
||||
if paid.get('provider') == payments.MANUAL_PROVIDER:
|
||||
return paid.get('method')
|
||||
row = c.execute('''SELECT method FROM dtf_local.payment_intents WHERE quote_id=%s AND status='approved'
|
||||
ORDER BY created_at DESC LIMIT 1''', (order['quote_id'],)).fetchone()
|
||||
return row and row['method']
|
||||
|
||||
|
||||
@router.get('/api/operator/orders/{uid}/receipt')
|
||||
def pickup_receipt(uid: UUID, user=Depends(operator)):
|
||||
"""The pickup receipt's PDF (item 14), for the folder to save or someone
|
||||
to print again."""
|
||||
with db.connect() as c:
|
||||
order = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s', (uid,)).fetchone()
|
||||
if not order:
|
||||
raise HTTPException(404, 'Pedido não encontrado.')
|
||||
if not receipt.is_pickup(order['snapshot']):
|
||||
raise HTTPException(409, 'Só pedido de retirada tem recibo.')
|
||||
body = receipt.render(order, paid_with(c, order))
|
||||
return Response(body, media_type='application/pdf',
|
||||
headers={'Content-Disposition': f'inline; filename="{receipt.file_name(order)}"'})
|
||||
|
||||
|
||||
@router.post('/api/operator/orders/{uid}/receipt/claim')
|
||||
def claim_receipt(uid: UUID, user=Depends(can('print'))):
|
||||
"""One computer's folder takes the receipt to save: once, so the counter's
|
||||
queue never prints it twice."""
|
||||
with db.connect() as c:
|
||||
row = c.execute('''UPDATE dtf_local.orders SET receipt_saved_at=now(), receipt_saved_by=%s
|
||||
WHERE id=%s AND receipt_due_at IS NOT NULL AND receipt_saved_at IS NULL AND cancelled_at IS NULL
|
||||
RETURNING number''', (user, uid)).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(409, 'Este recibo já foi salvo.')
|
||||
audit('pickup_receipt_saved', order=row['number'], operator=user)
|
||||
return {'ok': True}
|
||||
|
||||
|
||||
@router.post('/api/operator/orders/{uid}/receipt/release')
|
||||
def release_receipt(uid: UUID, user=Depends(can('print'))):
|
||||
"""The folder could not save the receipt it took: another computer may."""
|
||||
with db.connect() as c:
|
||||
c.execute('''UPDATE dtf_local.orders SET receipt_saved_at=NULL, receipt_saved_by=NULL
|
||||
WHERE id=%s AND receipt_saved_by=%s''', (uid, user))
|
||||
return {'ok': True}
|
||||
|
||||
|
||||
def pickup_order(c, uid, lock=False):
|
||||
"""An order in Finalizado to be picked up, or why it cannot be marked."""
|
||||
order = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s' + (' FOR UPDATE' if lock else ''), (uid,)).fetchone()
|
||||
if not order:
|
||||
raise HTTPException(404, 'Pedido não encontrado.')
|
||||
if order['cancelled_at'] or order['state'] != 'fin' or not receipt.is_pickup(order['snapshot']):
|
||||
raise HTTPException(409, 'Só um pedido de retirada em Finalizado é marcado como retirado.')
|
||||
if order['picked_up_at']:
|
||||
raise HTTPException(409, 'Este pedido já foi marcado como retirado.')
|
||||
return order
|
||||
|
||||
|
||||
@router.post('/api/operator/orders/{uid}/pickup-uploads')
|
||||
def begin_pickup_photo(uid: UUID, body: UploadStart, user=Depends(can('deliver'))):
|
||||
"""The photo of the signed receipt, sent before marking the order."""
|
||||
with db.connect() as c:
|
||||
pickup_order(c, uid)
|
||||
return begin_upload(body, session_id=operator_identity(user))
|
||||
|
||||
|
||||
class PickedUp(StrictModel):
|
||||
photo: UUID | None = None
|
||||
|
||||
|
||||
PHOTO_TYPES = ('.jpg', '.jpeg', '.png', '.webp', '.heic', '.heif')
|
||||
|
||||
|
||||
@router.post('/api/operator/orders/{uid}/picked-up')
|
||||
def picked_up(uid: UUID, body: PickedUp, user=Depends(can('deliver'))):
|
||||
""""Retirado": when and who handed the order over, and the photo of the
|
||||
signed receipt when there is one (item 14). Finalizado means ready; this
|
||||
closes the cycle. The photo is kept 30 days, as the order's files are."""
|
||||
with db.connect() as c:
|
||||
order = pickup_order(c, uid, lock=True)
|
||||
if body.photo:
|
||||
photo = upload_row(c, body.photo, operator_identity(user), lock=True)
|
||||
if not photo['complete']:
|
||||
raise HTTPException(409, 'Espere a foto terminar de enviar.')
|
||||
if not photo['name'].lower().endswith(PHOTO_TYPES):
|
||||
raise HTTPException(422, 'A foto do recibo precisa ser uma imagem (JPG, PNG, WebP ou HEIC).')
|
||||
require_clean(photo)
|
||||
c.execute("UPDATE dtf_local.uploads SET expires_at=now()+interval '30 days' WHERE id=%s", (body.photo,))
|
||||
row = c.execute('''UPDATE dtf_local.orders SET picked_up_at=now(), picked_up_by=%s, picked_up_photo=%s
|
||||
WHERE id=%s RETURNING picked_up_at''', (user, body.photo, uid)).fetchone()
|
||||
audit('order_picked_up', order=order['number'], operator=user, photo=bool(body.photo))
|
||||
return {'ok': True, 'picked_up_at': row['picked_up_at']}
|
||||
|
||||
|
||||
class QueuePlace(StrictModel):
|
||||
"""Where a dragged card lands: between two orders of its column, either
|
||||
of them absent at the top or the bottom."""
|
||||
@@ -775,7 +875,11 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
|
||||
c.execute("UPDATE dtf_local.order_files SET active=false WHERE order_id=%s AND kind='final'", (uid,))
|
||||
c.execute('INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason,back) VALUES(%s,%s,%s,%s,%s,%s)',
|
||||
(uid,row['state'],body.state,user,body.reason,back))
|
||||
changed = c.execute('UPDATE dtf_local.orders SET state=%s, version=version+1, updated_at=now(), queue_key=NULL WHERE id=%s RETURNING *', (body.state,uid)).fetchone()
|
||||
# A pickup reaching Finalizado has its receipt due (item 14), once.
|
||||
due = body.state == 'fin' and not back and receipt.is_pickup(row['snapshot'])
|
||||
changed = c.execute('''UPDATE dtf_local.orders SET state=%s, version=version+1, updated_at=now(), queue_key=NULL,
|
||||
receipt_due_at=CASE WHEN %s THEN COALESCE(receipt_due_at, now()) ELSE receipt_due_at END
|
||||
WHERE id=%s RETURNING *''', (body.state, due, uid)).fetchone()
|
||||
# Entering the queue (Arte conferida) is Tiny's "Preparando envio";
|
||||
# Finalizado its "Pronto para envio" (Dropstar's flow, 2026-10-23).
|
||||
events = {'tra':'production_started','cor':'correction_needed','fin':'ready'}
|
||||
@@ -1244,8 +1348,14 @@ def queue_folder(body: FolderSync, request: Request, user=Depends(can('print')))
|
||||
files = named_files(rows)
|
||||
held = c.execute('SELECT id,state,cancelled_at FROM dtf_local.orders WHERE id=ANY(%s)',
|
||||
(body.held,)).fetchall() if body.held else []
|
||||
# The pickup receipts no computer saved yet (item 14), due since the
|
||||
# folders were chosen: one that was off catches up, like the files.
|
||||
due = c.execute('''SELECT id, number FROM dtf_local.orders WHERE receipt_due_at IS NOT NULL
|
||||
AND receipt_saved_at IS NULL AND cancelled_at IS NULL AND (%s::timestamptz IS NULL OR receipt_due_at>=%s)
|
||||
ORDER BY receipt_due_at''', (body.since, body.since)).fetchall() if body.early else []
|
||||
return {'files': files,
|
||||
'states': {str(o['id']): 'cancelled' if o['cancelled_at'] else o['state'] for o in held}}
|
||||
'states': {str(o['id']): 'cancelled' if o['cancelled_at'] else o['state'] for o in held},
|
||||
'receipts': [{'order': str(o['id']), 'number': o['number'], 'name': receipt.file_name(o)} for o in due]}
|
||||
|
||||
|
||||
@router.get('/api/operator/uploads/{uid}/download')
|
||||
|
||||
Reference in New Issue
Block a user