fix: review of phase-2 stage 0 and fronts 5, 6 and 11
All checks were successful
Build and deploy / Publish images (push) Successful in 1m5s
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Successful in 5m7s
Build and deploy / Secret scan and release gate (push) Successful in 6s
All checks were successful
Build and deploy / Publish images (push) Successful in 1m5s
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Successful in 5m7s
Build and deploy / Secret scan and release gate (push) Successful in 6s
- A paid treatment adds its 24 h to Arte recebida's acceptable time, on the card and in Números (fronts 5 and 11). - TINY_PRODUCT_TREATMENT is a required Tiny setting once the treatment has a price, instead of every treated order failing at the Tiny. - A quote reads each PDF once: Files caches the header and the DPI. - A proof made from the parent's final split into parts uses the part that holds the finest stroke, not the last one (0.1). - Prumo report: one format line per item, the time from the claim (kept on the finished print file), and the stroke class in customer words. - The Site says the Prumo checks the art, and a too-tall PNG no longer says "Este PDF". Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -262,6 +262,10 @@ def assign_late(c, orders, limits):
|
||||
since = since or order['created_at']
|
||||
hours = max(0.0, (now - since).total_seconds() / 3600)
|
||||
limit_hours = float(limit['hours'])
|
||||
# A paid treatment gives Art received its extra hours to prepare the art.
|
||||
treatment = (order.get('snapshot') or {}).get('treatment') or {}
|
||||
if order['state'] == 'rec' and treatment:
|
||||
limit_hours += float(treatment.get('hours', 24))
|
||||
order['state_hours'] = round(hours, 2)
|
||||
order['limit_hours'] = limit_hours
|
||||
order['limit_by'] = limit['responsible']
|
||||
@@ -1426,10 +1430,14 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start
|
||||
FROM dtf_local.orders o WHERE {REAL_ORDER} AND o.state<>'fin' GROUP BY o.state''').fetchall()
|
||||
# Passages past each stage's acceptable time (front 11), in the
|
||||
# selected period and today.
|
||||
late_rows = c.execute(f'''SELECT state,
|
||||
extract(epoch FROM until-at) - {waited('s.id', 's.at', 's.until')} AS seconds,
|
||||
(until AT TIME ZONE 'America/Sao_Paulo')::date AS day
|
||||
FROM ({spans}) s WHERE until IS NOT NULL''', period + period).fetchall()
|
||||
# Each passage carries whether its order paid for treatment, which only
|
||||
# Art received counts (front 5).
|
||||
late_rows = c.execute(f'''SELECT s.state,
|
||||
extract(epoch FROM s.until-s.at) - {waited('s.id', 's.at', 's.until')} AS seconds,
|
||||
(s.until AT TIME ZONE 'America/Sao_Paulo')::date AS day,
|
||||
o.snapshot->'treatment' AS treatment
|
||||
FROM ({spans}) s LEFT JOIN dtf_local.orders o ON o.id=s.id WHERE s.until IS NOT NULL''',
|
||||
period + period).fetchall()
|
||||
printed = machine_output(c, start, end)
|
||||
# Rework of the period (D-02 to D-04): the authorized ones, by the day
|
||||
# they were opened, over the film the machines printed in it.
|
||||
@@ -1513,7 +1521,13 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start
|
||||
late = {state: {'count': 0, 'today': 0} for state in ('rec', 'tra', 'imp', 'rev', 'fin')}
|
||||
for row in late_rows:
|
||||
limit = limits.get(row['state'])
|
||||
if limit and row['seconds'] > limit['hours'] * 3600:
|
||||
if not limit:
|
||||
continue
|
||||
hours = float(limit['hours'])
|
||||
treatment = row.get('treatment') or {}
|
||||
if row['state'] == 'rec' and treatment:
|
||||
hours += float(treatment.get('hours', 24))
|
||||
if row['seconds'] > hours * 3600:
|
||||
late[row['state']]['count'] += 1
|
||||
if row['day'] == today:
|
||||
late[row['state']]['today'] += 1
|
||||
|
||||
@@ -135,18 +135,29 @@ class Files:
|
||||
|
||||
def __init__(self, storage):
|
||||
self.storage = storage
|
||||
# A PDF is read once per quote: source_dpi, resolution_issue and
|
||||
# mismatch all ask for the same files.
|
||||
self._heads = {}
|
||||
self._dpis = {}
|
||||
|
||||
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()
|
||||
key = row['object_key']
|
||||
if key not in self._heads:
|
||||
self._heads[key] = self.storage.client.get_object(
|
||||
Bucket=self.storage.bucket, Key=key, Range=f'bytes=0-{HEAD_BYTES - 1}')['Body'].read()
|
||||
return self._heads[key]
|
||||
|
||||
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)
|
||||
key = row['object_key']
|
||||
if key not in self._dpis:
|
||||
if row['size'] > PDF_MAX_BYTES:
|
||||
self._dpis[key] = None
|
||||
else:
|
||||
with tempfile.NamedTemporaryFile(suffix='.pdf') as handle:
|
||||
self.storage.client.download_fileobj(self.storage.bucket, key, handle)
|
||||
handle.flush()
|
||||
self._dpis[key] = pdf_dpi(handle.name)
|
||||
return self._dpis[key]
|
||||
|
||||
|
||||
def source_dpi(files, row, source):
|
||||
|
||||
@@ -16,6 +16,7 @@ Sheets of several GB are the normal order: a PNG or a PDF is read band by
|
||||
band, so its size does not matter. Any other file above LARGE_SOURCE_BYTES
|
||||
is prepared by hand from the original.
|
||||
"""
|
||||
import io
|
||||
import logging
|
||||
import multiprocessing
|
||||
import os
|
||||
@@ -53,6 +54,36 @@ def generated_identity(order_id):
|
||||
return uuid5(NAMESPACE_URL, f'dtf-print-file:{order_id}')
|
||||
|
||||
|
||||
def proof_part(heights_cm, original_height_cm, fraction):
|
||||
"""Which part of a split final holds the finest stroke, and where inside it.
|
||||
|
||||
`heights_cm` are the parts' heights in order, `fraction` the stroke's
|
||||
position on the original film (0 at the top, 1 at the bottom). A single
|
||||
part returns the same fraction, as before.
|
||||
"""
|
||||
heights = [float(height) for height in heights_cm]
|
||||
if not heights:
|
||||
return 0, 0.0
|
||||
position = min(1.0, max(0.0, float(fraction or 0))) * float(original_height_cm)
|
||||
start = 0.0
|
||||
for index, height in enumerate(heights):
|
||||
end = start + height
|
||||
if position <= end or index == len(heights) - 1:
|
||||
inside = (position - start) / height if height > 0 else 0.0
|
||||
return index, min(1.0, max(0.0, inside))
|
||||
start = end
|
||||
return len(heights) - 1, 1.0
|
||||
|
||||
|
||||
def png_height_cm(storage, row):
|
||||
"""A PNG's height in cm at 300 DPI, from its header alone (a Range read)."""
|
||||
head = storage.client.get_object(Bucket=storage.bucket, Key=row['object_key'],
|
||||
Range='bytes=0-65535')['Body'].read()
|
||||
with Image.open(io.BytesIO(head)) as image:
|
||||
height_px = image.size[1]
|
||||
return float(Decimal(height_px) * Decimal('2.54') / Decimal(300))
|
||||
|
||||
|
||||
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):
|
||||
@@ -123,15 +154,26 @@ def render_one(storage):
|
||||
item = job['snapshot']['items'][job['item_index']]
|
||||
source_ids = [UUID(u) for u in item['uploads']]
|
||||
# A format such as CDR needs a human to prepare the full-size final on
|
||||
# the parent. The child still generates its own 15 cm proof from that PNG.
|
||||
# the parent. The child still generates its own 15 cm proof from that PNG,
|
||||
# or from the part of it that holds the finest stroke when the film was
|
||||
# cut into parts (item 13).
|
||||
if job['parent_id']:
|
||||
source = c.execute('''SELECT u.id FROM dtf_local.order_files f
|
||||
finals = c.execute('''SELECT u.id,u.object_key FROM dtf_local.order_files f
|
||||
JOIN dtf_local.uploads u ON u.id=f.upload_id
|
||||
LEFT JOIN dtf_local.print_parts p ON p.order_id=f.order_id
|
||||
AND p.item_index=f.item_index AND p.upload_id=f.upload_id
|
||||
WHERE f.order_id=%s AND f.item_index=%s AND f.kind='final' AND f.active
|
||||
AND u.purged_at IS NULL AND u.expires_at>now()
|
||||
ORDER BY f.created_at DESC LIMIT 1''',
|
||||
(job['parent_id'], item['proof_parent_item_index'])).fetchone()
|
||||
if source:
|
||||
ORDER BY p.part NULLS LAST, f.created_at''',
|
||||
(job['parent_id'], item['proof_parent_item_index'])).fetchall()
|
||||
if finals:
|
||||
source = finals[0]
|
||||
if len(finals) > 1:
|
||||
heights = [png_height_cm(storage, row) for row in finals]
|
||||
index, fraction = proof_part(heights, item['production']['height_cm'],
|
||||
item.get('proof_y_fraction'))
|
||||
source = finals[index]
|
||||
job['proof_fraction'] = fraction
|
||||
source_ids = [source['id']]
|
||||
item = {**item, 'uploads': [str(source['id'])]}
|
||||
job['proof_fallback'] = True
|
||||
@@ -194,8 +236,9 @@ def render_one(storage):
|
||||
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))
|
||||
# claimed_at stays: the Prumo report measures generation from the claim.
|
||||
c.execute('''UPDATE dtf_local.print_files SET status='ready', upload_id=%s, detail=%s,
|
||||
finished_at=now(),claim_token=NULL,claimed_at=NULL WHERE id=%s''', (stored[0][0], Jsonb(detail), job['id']))
|
||||
finished_at=now(),claim_token=NULL WHERE id=%s''', (stored[0][0], Jsonb(detail), job['id']))
|
||||
c.execute('DELETE FROM dtf_local.print_parts WHERE order_id=%s AND item_index=%s',
|
||||
(job['order_id'], job['item_index']))
|
||||
for number, (uid, _, _, _) in enumerate(stored, 1):
|
||||
@@ -274,11 +317,15 @@ def produce(storage, job, item, uploads):
|
||||
width_px, height_px = final.size
|
||||
width_cm = float(Decimal(width_px) * Decimal('2.54') / Decimal(300))
|
||||
height_cm = float(Decimal(height_px) * Decimal('2.54') / Decimal(300))
|
||||
original_height = float(item['production']['height_cm'])
|
||||
fraction = float(item.get('proof_y_fraction') or 0)
|
||||
if job.get('proof_fraction') is not None:
|
||||
# Already relative to the chosen part (proof_part).
|
||||
fraction = float(job['proof_fraction'])
|
||||
else:
|
||||
original_height = float(item['production']['height_cm'])
|
||||
fraction = min(1, float(item.get('proof_y_fraction') or 0) * original_height / height_cm)
|
||||
source = {'kind': 'sheet', 'width_cm': width_cm, 'length_cm': height_cm,
|
||||
'copies': 1, 'rotation_degrees': 0, 'mirrored': False, 'measurement': 'file'}
|
||||
item = {**item, 'proof_y_fraction': min(1, fraction * original_height / height_cm),
|
||||
item = {**item, 'proof_y_fraction': fraction,
|
||||
'production': {'version': 3, 'film_width_cm': width_cm,
|
||||
'height_cm': height_cm, 'sources': [source],
|
||||
'placements': [{'source_index': 0, 'copy_index': 0,
|
||||
|
||||
26
app/prumo.py
26
app/prumo.py
@@ -10,6 +10,12 @@ from zoneinfo import ZoneInfo
|
||||
|
||||
LOCAL = ZoneInfo('America/Sao_Paulo')
|
||||
MANUAL = {'cdr', 'psd', 'psb', 'tif', 'tiff'}
|
||||
# The stroke class in the customer's words, without the internal C1/C2/C3 code.
|
||||
STROKE_SUMMARY = {
|
||||
'C1': 'Sua arte tem traços muito finos; a impressão foi ajustada para eles.',
|
||||
'C2': 'Sua arte tem traços médios; a impressão foi ajustada para eles.',
|
||||
'C3': 'Sua arte tem áreas cheias; a impressão foi ajustada para elas.',
|
||||
}
|
||||
|
||||
|
||||
def _ext(name):
|
||||
@@ -64,8 +70,14 @@ def report(order, uploads):
|
||||
names.append(final)
|
||||
if original and final and _ext(original) != _ext(final):
|
||||
lines.append(f'{lead}Chegou {_ext(original).upper()}, era {_ext(final).upper()} por dentro — tratado como {_ext(final).upper()}')
|
||||
else:
|
||||
lines.append(f'{lead}Formato detectado: {_ext(final).upper() or "desconhecido"}')
|
||||
# One format line per item, not one per file: the designer reads what
|
||||
# the item is, and only the files that changed are named above.
|
||||
formats = sorted({_ext(name).upper() or 'desconhecido' for name in names})
|
||||
if len(formats) == 1:
|
||||
count = f' ({len(names)} arquivos)' if len(names) > 1 else ''
|
||||
lines.append(f'{lead}Formato detectado: {formats[0]}{count}')
|
||||
elif formats:
|
||||
lines.append(f'{lead}Formatos detectados: {", ".join(formats)}')
|
||||
exts = {_ext(name) for name in names}
|
||||
row = generated.get(index)
|
||||
ready = bool(row and row.get('status') == 'ready')
|
||||
@@ -109,8 +121,10 @@ def report(order, uploads):
|
||||
sizes = [Decimal(str(p.get('to_cm', 0))) - Decimal(str(p.get('from_cm', 0))) for p in parts]
|
||||
lines.append(f'{lead}{_m(billed)} m → {len(parts)} partes (' +
|
||||
' + '.join(_m(size) for size in sizes) + ')')
|
||||
if ready and row.get('finished_at') and row.get('created_at'):
|
||||
seconds = (row['finished_at'] - row['created_at']).total_seconds()
|
||||
# From the claim, not from the queue: the customer waits for the
|
||||
# generation, not for the file's turn.
|
||||
if ready and row.get('finished_at') and row.get('claimed_at'):
|
||||
seconds = (row['finished_at'] - row['claimed_at']).total_seconds()
|
||||
lines.append(f'{lead}Prumo levou {max(1, round(seconds))} s')
|
||||
return lines
|
||||
|
||||
@@ -127,8 +141,8 @@ def customer_summary(items):
|
||||
if dots:
|
||||
lines.append(f'{lead}Há {dots} pontinho{"s" if dots > 1 else ""} solto{"s" if dots > 1 else ""} '
|
||||
'que você aceitou imprimir.')
|
||||
if item.get('stroke_class'):
|
||||
lines.append(f'{lead}O traço mais fino foi medido em {item["stroke_class"]}.')
|
||||
if item.get('stroke_class') in STROKE_SUMMARY:
|
||||
lines.append(f'{lead}{STROKE_SUMMARY[item["stroke_class"]]}')
|
||||
if item.get('stroke_choice') == 'measured':
|
||||
lines.append(f'{lead}Você escolheu imprimir o traço fino assim mesmo (C1).')
|
||||
elif item.get('stroke_choice') == 'client_c3':
|
||||
|
||||
@@ -51,6 +51,8 @@ from urllib.parse import urlencode
|
||||
|
||||
import httpx
|
||||
|
||||
from .core.pricing import treatment_cents
|
||||
|
||||
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
|
||||
@@ -166,8 +168,13 @@ def configured():
|
||||
|
||||
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'] + [
|
||||
required = ['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))]
|
||||
# A paid treatment is a line of its own: missing, every treated order would
|
||||
# fail at the Tiny, so ask for it with the rest of the settings.
|
||||
if treatment_cents() > 0:
|
||||
required.append('TINY_PRODUCT_TREATMENT')
|
||||
return required
|
||||
|
||||
|
||||
# The stack passes every setting, empty when unset, so empty means "the
|
||||
|
||||
Reference in New Issue
Block a user