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>
138 lines
5.9 KiB
Python
138 lines
5.9 KiB
Python
"""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'
|