Compare commits
19 Commits
742ea5f5bd
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7e33e6fb1d | ||
|
|
37d747697a | ||
|
|
c4f8ba1b70 | ||
|
|
4283c93526 | ||
|
|
eb7a92bb89 | ||
|
|
9fc4d4e906 | ||
|
|
6ec0ea31a6 | ||
|
|
5f84db708c | ||
|
|
2ff11688bc | ||
|
|
a652d734ea | ||
|
|
48d8b2f434 | ||
|
|
4a1994bd06 | ||
|
|
bb6fb14b1a | ||
|
|
6970434e5d | ||
|
|
7454f6b840 | ||
|
|
ba85168c09 | ||
|
|
b64947eb76 | ||
|
|
f35a347a28 | ||
|
|
194797c412 |
@@ -232,7 +232,7 @@ class ObjectStorage(Protocol):
|
||||
def part_url(self, key: str, upload_id: str, part: int, size: int) -> str: ...
|
||||
def complete(self, key: str, upload_id: str, parts: list): ...
|
||||
def size(self, key: str) -> int: ...
|
||||
def download(self, key: str, name: str) -> str: ...
|
||||
def download(self, key: str, name: str, expires: int = 300) -> str: ...
|
||||
def fetch(self, key: str, path: str): ...
|
||||
def store(self, key: str, path: str, content_type: str): ...
|
||||
def health(self): ...
|
||||
@@ -299,12 +299,12 @@ class LocalS3Storage:
|
||||
"""Upload a file the service generated itself, such as a print file."""
|
||||
self.patient.upload_file(path, self.bucket, key, ExtraArgs={'ContentType': content_type})
|
||||
|
||||
def download(self, key, name):
|
||||
def download(self, key, name, expires=300):
|
||||
from urllib.parse import quote
|
||||
return self.public.generate_presigned_url('get_object', Params={
|
||||
'Bucket': self.bucket, 'Key': key,
|
||||
'ResponseContentDisposition': "attachment; filename*=UTF-8''" + quote(name, safe=''),
|
||||
'ResponseContentType': 'application/octet-stream'}, ExpiresIn=300)
|
||||
'ResponseContentType': 'application/octet-stream'}, ExpiresIn=expires)
|
||||
|
||||
def view(self, key, content_type, expires=3600):
|
||||
"""A link to show an object in the page, not download it: the Kanban's
|
||||
|
||||
@@ -16,6 +16,10 @@ from ...scanning import require_clean
|
||||
from .common import FINAL_OK
|
||||
|
||||
router = APIRouter()
|
||||
# The folders download a whole list of files, one after another, from links
|
||||
# made when the list was asked for: with films of 10 m, 5 minutes ran out
|
||||
# before the last ones began (erro 403). Only the team's computers see them.
|
||||
FOLDER_LINK_SECONDS = 3600
|
||||
|
||||
def named_files(rows):
|
||||
"""Each file named after its order and item, so a folder of them stays
|
||||
@@ -39,7 +43,7 @@ def named_files(rows):
|
||||
names.add(name)
|
||||
files.append({'order': str(row['order_id']), 'state': row['state'], 'number': row['number'],
|
||||
'item': row['item_index'] + 1, 'name': name, 'upload_id': str(row['upload_id']),
|
||||
'url': storage.download(row['object_key'], name)})
|
||||
'url': storage.download(row['object_key'], name, FOLDER_LINK_SECONDS)})
|
||||
return files
|
||||
|
||||
|
||||
@@ -163,7 +167,7 @@ def queue_hot(user=Depends(can('print'))):
|
||||
watched = hotfolder.watched(c)
|
||||
return {'folder': hotfolder.PRINTING_FOLDER,
|
||||
'write': [{'id': r['id'], 'order': str(r['order_id']), 'folder': r['folder'], 'name': r['name'],
|
||||
'url': storage.download(keys[str(r['upload_id'])], r['name'])} for r in due],
|
||||
'url': storage.download(keys[str(r['upload_id'])], r['name'], FOLDER_LINK_SECONDS)} for r in due],
|
||||
'watch': [{'id': r['id'], 'order': str(r['order_id']), 'folder': r['folder'], 'name': r['name']}
|
||||
for r in watched if r['state'] == 'written'],
|
||||
'withdraw': [{'id': r['id'], 'order': str(r['order_id']), 'folder': r['folder'], 'name': r['name']}
|
||||
|
||||
@@ -50,6 +50,10 @@ def delete_order(uid: UUID, user=Depends(can('manage'))):
|
||||
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=ANY(%s)', ([uid] + cards,))
|
||||
# A real order's Tiny events stay: its cancellation may not have
|
||||
# reached Tiny yet (Tiny down, or deleted at once), and what was sent
|
||||
# stays on record. A test order never goes to Tiny.
|
||||
if test:
|
||||
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:
|
||||
@@ -73,6 +77,14 @@ def cancel_order(uid: UUID, body: Resolution, user=Depends(can('cancel'))):
|
||||
if not row:
|
||||
raise HTTPException(404, 'Pedido não encontrado ou já cancelado.')
|
||||
hotfolder.stop(c, uid)
|
||||
# Its proof card not yet answered goes with it: left on the board, it
|
||||
# could still be pulled and printed for an order no one will take.
|
||||
cards = c.execute('''UPDATE dtf_local.orders SET cancelled_at=now(), cancelled_by=%s, cancel_reason=%s,
|
||||
version=version+1, updated_at=now()
|
||||
WHERE parent_id=%s AND cancelled_at IS NULL AND proof_result IS NULL RETURNING id''',
|
||||
(user, f"Pedido #{row['number']} cancelado: {body.note}", uid)).fetchall()
|
||||
for card in cards:
|
||||
hotfolder.stop(c, card['id'])
|
||||
if payments.in_tiny(row):
|
||||
sale = c.execute("SELECT receipt FROM dtf_local.outbox WHERE event_key=%s AND delivered_at IS NOT NULL",
|
||||
(f'{uid}:paid:tiny',)).fetchone()
|
||||
@@ -524,12 +536,20 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
|
||||
# again from what changed since.
|
||||
if printed_items is not None or (body.state == 'fin' and not back):
|
||||
c.execute('UPDATE dtf_local.orders SET print_items=NULL WHERE id=%s', (uid,))
|
||||
# Back to Imprimindo from Revisão (a mistaken move undone): the items
|
||||
# that pass printed are the choice again, and only what Flexi had not
|
||||
# taken goes back to the folder, never the whole order.
|
||||
if body.state == 'imp' and back:
|
||||
undone = c.execute('''SELECT items FROM dtf_local.movements WHERE order_id=%s
|
||||
AND from_state='imp' AND to_state='rev' AND NOT back ORDER BY id DESC LIMIT 1''', (uid,)).fetchone()
|
||||
if undone and undone['items'] is not None:
|
||||
c.execute('UPDATE dtf_local.orders SET print_items=%s WHERE id=%s', (undone['items'], uid))
|
||||
# Pulled to Imprimindo, its files go to its machine's hot folder; out
|
||||
# of it, what Flexi did not take leaves (item 10).
|
||||
if row['state'] == 'imp':
|
||||
hotfolder.stop(c, uid)
|
||||
if body.state == 'imp':
|
||||
hotfolder.start(c, uid)
|
||||
(hotfolder.resume if back else hotfolder.start)(c, uid)
|
||||
# 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(),
|
||||
@@ -538,21 +558,8 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
|
||||
WHERE id=%s RETURNING *''', (body.state, 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'}
|
||||
if body.state in events and not back and payments.in_tiny(row):
|
||||
# "Production started" and "ready" reach the customer once per order,
|
||||
# even if a mistaken move is undone and made again. Each correction
|
||||
# is a new request, so it keeps one message per movement.
|
||||
once = body.state in ('tra','fin')
|
||||
event = {'order_id':str(uid), 'number':row['number'], 'event':events[body.state], 'reason':body.reason,
|
||||
'customer_path': f'/portal.html?order={uid}'}
|
||||
# Tiny needs the order (customer, pickup or delivery) and, once the
|
||||
# sale reached it, its id, to set the situação without a search.
|
||||
sale = c.execute("SELECT receipt FROM dtf_local.outbox WHERE event_key=%s AND delivered_at IS NOT NULL",
|
||||
(f'{uid}:paid:tiny',)).fetchone()
|
||||
tiny = {**event, 'order': row['snapshot'], 'tiny_id': ((sale or {}).get('receipt') or {}).get('tiny_id')}
|
||||
key = f'{uid}:{events[body.state]}:tiny' if once else f'{uid}:{changed["version"]}:tiny'
|
||||
enqueue(c, key, 'tiny', tiny)
|
||||
if not back:
|
||||
payments.stage_event(c, row, body.state, body.reason, changed['version'])
|
||||
return changed
|
||||
|
||||
class PrintItems(StrictModel):
|
||||
@@ -574,7 +581,9 @@ def choose_print_items(uid: UUID, body: PrintItems, user=Depends(can('produce'))
|
||||
items = sorted(set(body.items))
|
||||
if any(i < 0 or i >= count for i in items):
|
||||
raise HTTPException(422, 'Item do pedido inválido.')
|
||||
chosen = None if len(items) == count else items
|
||||
# Every item is kept as the whole list, not NULL: NULL is "not chosen
|
||||
# yet", which the pass to the queue would replace with the suggestion.
|
||||
chosen = items
|
||||
c.execute('UPDATE dtf_local.orders SET print_items=%s, version=version+1, updated_at=now() WHERE id=%s',
|
||||
(chosen, uid))
|
||||
audit('order_print_items', order=row['number'], items=','.join(str(i + 1) for i in items), operator=user)
|
||||
|
||||
@@ -11,7 +11,7 @@ import httpx
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from psycopg.types.json import Jsonb
|
||||
|
||||
from .. import payment_messages as messages, payments
|
||||
from .. import coupons, payment_messages as messages, payments
|
||||
from ..core import db
|
||||
from ..core.auth import audit, client_ip, owner, rate_limit
|
||||
from ..core.models import PaymentIntent
|
||||
@@ -104,6 +104,15 @@ def intent(body: PaymentIntent, session_id=Depends(owner)):
|
||||
raise HTTPException(404 if 'not found' in str(refusal) else 409, messages.quote_refusal(refusal))
|
||||
if c.execute('SELECT 1 FROM dtf_local.orders WHERE quote_id=%s', (body.quote_id,)).fetchone():
|
||||
raise HTTPException(409, 'Este pedido já foi pago.')
|
||||
# A coupon's limits are spent at payment (app/coupons.py): one used up,
|
||||
# paused or ended since the cart was made no longer gives its discount.
|
||||
coupon = quote['approved'].get('coupon')
|
||||
if coupon:
|
||||
try:
|
||||
coupons.check(c, coupon['code'], (quote['approved'].get('customer') or {}).get('cnpj'),
|
||||
quote['approved']['items'])
|
||||
except HTTPException as refusal:
|
||||
raise HTTPException(409, f'{refusal.detail} Monte o carrinho de novo, sem o cupom, para pagar.')
|
||||
# Never charge for files that are gone: an unpaid cart's files are
|
||||
# removed after a while. A payment under way keeps them a day longer,
|
||||
# time enough for the provider's notice to become the order.
|
||||
@@ -113,7 +122,8 @@ def intent(body: PaymentIntent, session_id=Depends(owner)):
|
||||
if live != len(set(uploads)):
|
||||
raise HTTPException(410, 'Os arquivos deste pedido expiraram porque ele não foi pago a tempo. '
|
||||
'Monte o pedido de novo para pagar.')
|
||||
payments.hold_uploads(c, uploads, '1 day')
|
||||
# A card may sit in review for days (payments.CARD_REVIEW_HOURS).
|
||||
payments.hold_uploads(c, uploads, f'{payments.CARD_REVIEW_HOURS} hours' if body.method.type == 'card' else '1 day')
|
||||
# Never a second charge: an approved payment is waiting for its
|
||||
# notification to become the order, and a card in review may still be.
|
||||
# A card waiting for the bank's confirmation (3-D Secure) blocks only
|
||||
|
||||
@@ -13,7 +13,7 @@ from ..core import db
|
||||
from ..core.auth import owner
|
||||
from ..core.models import QuoteRequest
|
||||
from .. import quote_review
|
||||
from ..grade_check import Files, mismatch, resolution_issue, source_dpi
|
||||
from ..grade_check import Files, mismatch, proportion_issue, resolution_issue, source_dpi
|
||||
from ..runtime import freight, payment, quote_view, require_delivery_available, storage, upload_row
|
||||
from ..scanning import require_clean
|
||||
|
||||
@@ -79,7 +79,7 @@ def create_quote(body: QuoteRequest, session_id=Depends(owner)):
|
||||
dpis.append(dpi)
|
||||
if dpis:
|
||||
draft_item['source_dpi'] = round(min(dpis))
|
||||
issue = resolution_issue(files, draft['items'], rows)
|
||||
issue = proportion_issue(files, draft['items'], rows) or resolution_issue(files, draft['items'], rows)
|
||||
if issue:
|
||||
raise HTTPException(422, issue)
|
||||
note = mismatch(files, draft['items'], rows) if reason is None else None
|
||||
|
||||
@@ -16,7 +16,7 @@ router = APIRouter()
|
||||
|
||||
CATALOG = {
|
||||
'subindo': 'Subindo a arte pelo celular',
|
||||
'nota': 'O que é a nota da arte — e o que ela não é',
|
||||
'nota': 'O que a nota da arte mostra',
|
||||
'png': 'Por que PNG com fundo transparente',
|
||||
'avulsas': 'Montando artes avulsas e vendo a folha ao vivo',
|
||||
'retirada': 'Retirada em Franca em 24 h',
|
||||
|
||||
@@ -269,11 +269,14 @@ def list_machines(user=Depends(can('view'))):
|
||||
def create_machine(body: MachineIn, user=Depends(can('users'))):
|
||||
mid = uuid4()
|
||||
with db.connect() as c:
|
||||
if c.execute('SELECT 1 FROM dtf_local.machines WHERE lower(name)=lower(%s)', (body.name.strip(),)).fetchone():
|
||||
raise HTTPException(409, 'Já existe uma máquina com este nome.')
|
||||
c.execute('''INSERT INTO dtf_local.machines(id,name,products,active,limit_metres,places)
|
||||
VALUES(%s,%s,%s,%s,%s,%s)''', (mid, body.name.strip(), sorted(set(body.products)), body.active,
|
||||
body.limit_metres, body.places or machines.DEFAULT_PLACES))
|
||||
# A machine's hot folder is its first name, for good: no other machine
|
||||
# may be called that, or two would share one folder.
|
||||
if c.execute('SELECT 1 FROM dtf_local.machines WHERE lower(name)=lower(%s) OR lower(folder)=lower(%s)',
|
||||
(body.name.strip(), body.name.strip())).fetchone():
|
||||
raise HTTPException(409, 'Já existe uma máquina, ou a pasta de uma máquina, com este nome.')
|
||||
c.execute('''INSERT INTO dtf_local.machines(id,name,folder,products,active,limit_metres,places)
|
||||
VALUES(%s,%s,%s,%s,%s,%s,%s)''', (mid, body.name.strip(), body.name.strip(), sorted(set(body.products)),
|
||||
body.active, body.limit_metres, body.places or machines.DEFAULT_PLACES))
|
||||
audit('machine_created', operator=user, machine=body.name)
|
||||
return {'id': str(mid)}
|
||||
|
||||
@@ -281,9 +284,9 @@ def create_machine(body: MachineIn, user=Depends(can('users'))):
|
||||
@router.post('/api/operator/machines/{mid}')
|
||||
def update_machine(mid: UUID, body: MachineIn, user=Depends(can('users'))):
|
||||
with db.connect() as c:
|
||||
if c.execute('SELECT 1 FROM dtf_local.machines WHERE lower(name)=lower(%s) AND id<>%s',
|
||||
(body.name.strip(), mid)).fetchone():
|
||||
raise HTTPException(409, 'Já existe uma máquina com este nome.')
|
||||
if c.execute('''SELECT 1 FROM dtf_local.machines WHERE (lower(name)=lower(%s) OR lower(folder)=lower(%s))
|
||||
AND id<>%s''', (body.name.strip(), body.name.strip(), mid)).fetchone():
|
||||
raise HTTPException(409, 'Já existe uma máquina, ou a pasta de uma máquina, com este nome.')
|
||||
if not c.execute('''UPDATE dtf_local.machines SET name=%s,products=%s,active=%s,limit_metres=%s,
|
||||
places=COALESCE(%s,places) WHERE id=%s RETURNING id''',
|
||||
(body.name.strip(), sorted(set(body.products)), body.active, body.limit_metres,
|
||||
@@ -329,8 +332,8 @@ def test_mail(request: Request, user=Depends(can('integrations'))):
|
||||
"""A message to whoever asked, to prove the mail server works."""
|
||||
with db.connect() as c:
|
||||
if not mail.queue(c, 'test', user, 'Teste de e-mail · Kanban DTF',
|
||||
'Este é um teste do Kanban DTF. Se chegou, o envio de e-mails está funcionando: '
|
||||
'os e-mails dos clientes.'):
|
||||
'Este é um teste do Kanban DTF. Se chegou, o envio de e-mails aos clientes '
|
||||
'está funcionando.'):
|
||||
raise HTTPException(409, 'O envio de e-mails não está configurado no servidor.')
|
||||
audit('mail_test_queued', operator=user)
|
||||
return {'ok': True, 'to': user}
|
||||
|
||||
@@ -74,6 +74,20 @@ def submit_files(c, order, body, identity, kind, actor):
|
||||
current = {(row['upload_id'], row['item_index']) for row in c.execute(
|
||||
"SELECT upload_id,item_index FROM dtf_local.order_files WHERE order_id=%s AND kind='final' AND active",
|
||||
(order['id'],)).fetchall()} if kind == 'final' else set()
|
||||
# A film in parts is approved whole: with only some of its parts, the
|
||||
# others never reach the folders or the machine (#114, #128, #130).
|
||||
if kind == 'final':
|
||||
sent = {}
|
||||
for ref in body.files:
|
||||
sent.setdefault(ref.item_index, set()).add(str(ref.upload_id))
|
||||
for row in c.execute('''SELECT item_index, array_agg(upload_id::text ORDER BY part) AS uploads,
|
||||
array_agg(part ORDER BY part) AS numbers FROM dtf_local.print_parts WHERE order_id=%s
|
||||
GROUP BY item_index HAVING count(*) > 1''', (order['id'],)).fetchall():
|
||||
mine = sent.get(row['item_index'], set())
|
||||
missing = [n for n, u in zip(row['numbers'], row['uploads']) if u not in mine]
|
||||
if mine & set(row['uploads']) and missing:
|
||||
raise HTTPException(422, f"O filme do item {row['item_index'] + 1} tem {len(row['uploads'])} partes: "
|
||||
f"envie todas (faltam {', '.join('p' + str(n) for n in missing)}).")
|
||||
kept = {ref.upload_id for ref in body.files if (ref.upload_id, ref.item_index) in current}
|
||||
if kept and len(kept) == len(body.files):
|
||||
raise HTTPException(409, 'Estes já são os arquivos finais. Envie o arquivo novo.')
|
||||
|
||||
@@ -291,6 +291,17 @@ class Item(StrictModel):
|
||||
raise ValueError('Finished sheets must retain their original orientation')
|
||||
if placed != expected:
|
||||
raise ValueError('Production layout does not cover every source copy')
|
||||
# No piece on top of another: stacked pieces bill less film than they
|
||||
# print on, and print over each other. Swept down the film, so only
|
||||
# the pieces still open at each row are compared.
|
||||
boxes = sorted((p.y_cm, p.y_cm + p.length_cm, p.x_cm, p.x_cm + p.width_cm)
|
||||
for p in self.production.placements)
|
||||
open_boxes = []
|
||||
for top, bottom, left, right in boxes:
|
||||
open_boxes = [b for b in open_boxes if b[0] > top + tolerance]
|
||||
if any(l < right - tolerance and left < r - tolerance for _, l, r in open_boxes):
|
||||
raise ValueError('Duas peças da montagem ficaram uma sobre a outra. Monte o pedido de novo.')
|
||||
open_boxes.append((bottom, left, right))
|
||||
if self.quality_status == 'warning' and not self.quality_acknowledged:
|
||||
raise ValueError('Resolution warning must be acknowledged')
|
||||
return self
|
||||
|
||||
@@ -8,6 +8,19 @@ import os
|
||||
import re
|
||||
from decimal import Decimal, ROUND_CEILING
|
||||
|
||||
# Billed in steps of 10 cm, with 8 mm of grace for the customer (Marcus,
|
||||
# 2026-11-27): a length that passes a step by up to 8 mm is billed at that
|
||||
# step, by more at the next one. The Site rounds the same (web/site-config.js).
|
||||
STEP_GRACE_M = Decimal('0.008')
|
||||
|
||||
|
||||
def billed_length(length):
|
||||
"""The metres billed for `length` metres, before any minimum; never 0 for
|
||||
a sheet that has a length."""
|
||||
steps = ((Decimal(str(length)) - STEP_GRACE_M) * 10).to_integral_value(rounding=ROUND_CEILING)
|
||||
return max(Decimal('0.1'), steps / 10)
|
||||
|
||||
|
||||
PRICES = {'file': 1990, 'avulsa': 2190, 'uvfile': 7990, 'uv': 8990, 'premium': 3990}
|
||||
|
||||
# A finished sheet the Site cannot open (CDR, AI, PSD, TIFF) is opened by a
|
||||
@@ -55,7 +68,7 @@ def price(mode: str, metres: str, grade: int, extra_cents: int = 0, minimum: Dec
|
||||
raise ValueError('Invalid product or length')
|
||||
if isinstance(grade, bool) or not isinstance(grade, int) or not 0 <= grade <= 100:
|
||||
raise ValueError('Grade must be an integer between 0 and 100')
|
||||
billed = max(minimum, (length * 10).to_integral_value(rounding=ROUND_CEILING) / 10)
|
||||
billed = max(minimum, billed_length(length))
|
||||
if isinstance(extra_cents, bool) or not isinstance(extra_cents, int) or extra_cents < 0:
|
||||
raise ValueError('Invalid extra charge')
|
||||
unit = (PRICES[mode] if unit_cents is None else unit_cents) + extra_cents
|
||||
|
||||
@@ -32,6 +32,14 @@ PDF_VECTOR_DPI = 300
|
||||
# grade them, so neither does this.
|
||||
PDF_MAX_BYTES = 150 * 1048576
|
||||
HEAD_BYTES = 1048576
|
||||
# How much of a PDF's drawing is walked for its DPI: images and forms drawn
|
||||
# (Do), however many paths a vector page has. A page whose forms draw other
|
||||
# forms, ten times each, eight deep, is 10^8 draws in a 2 KB file: it
|
||||
# held the scanner's one thread for hours and every upload behind it
|
||||
# (security review, 2026-11-27). Past either limit the DPI is unknown, as for
|
||||
# a format this cannot read, and the order is reviewed by a person.
|
||||
PDF_MAX_DRAWS = 5000
|
||||
PDF_MAX_SECONDS = 10
|
||||
# Rounding in the browser and here can differ by a point on the same file.
|
||||
TOLERANCE = 2
|
||||
|
||||
@@ -84,10 +92,27 @@ def _multiply(a, b):
|
||||
a[0] * b[4] + a[2] * b[5] + a[4], a[1] * b[4] + a[3] * b[5] + a[5]]
|
||||
|
||||
|
||||
class _TooMuch(Exception):
|
||||
"""The PDF's drawing is larger than PDF_MAX_DRAWS or PDF_MAX_SECONDS."""
|
||||
|
||||
|
||||
def pdf_dpi(path):
|
||||
"""The page's area-weighted image DPI, 300 for vectors only, None if the
|
||||
file is not a one-page PDF this can read."""
|
||||
file is not a one-page PDF this can read, or draws more than it is worth
|
||||
walking (PDF_MAX_DRAWS, PDF_MAX_SECONDS)."""
|
||||
import time
|
||||
import pikepdf
|
||||
deadline = time.monotonic() + PDF_MAX_SECONDS
|
||||
steps = [0]
|
||||
parsed = {}
|
||||
|
||||
def instructions_of(stream):
|
||||
# A form drawn many times is read once.
|
||||
key = stream.objgen if stream.objgen != (0, 0) else id(stream)
|
||||
if key not in parsed:
|
||||
parsed[key] = pikepdf.parse_content_stream(stream)
|
||||
return parsed[key]
|
||||
|
||||
try:
|
||||
with pikepdf.open(path) as pdf:
|
||||
if len(pdf.pages) != 1:
|
||||
@@ -99,7 +124,9 @@ def pdf_dpi(path):
|
||||
def walk(resources, instructions, ctm, depth):
|
||||
stack = []
|
||||
xobjects = resources.get('/XObject', {}) if resources is not None else {}
|
||||
for operands, operator in instructions:
|
||||
for count, (operands, operator) in enumerate(instructions):
|
||||
if count % 1000 == 0 and time.monotonic() > deadline:
|
||||
raise _TooMuch
|
||||
op = str(operator)
|
||||
if op == 'q':
|
||||
stack.append(ctm)
|
||||
@@ -108,6 +135,9 @@ def pdf_dpi(path):
|
||||
elif op == 'cm':
|
||||
ctm = _multiply(ctm, [float(v) for v in operands])
|
||||
elif op == 'Do' and operands:
|
||||
steps[0] += 1
|
||||
if steps[0] > PDF_MAX_DRAWS or time.monotonic() > deadline:
|
||||
raise _TooMuch
|
||||
xobject = xobjects.get(str(operands[0]))
|
||||
if xobject is None:
|
||||
continue
|
||||
@@ -120,9 +150,14 @@ def pdf_dpi(path):
|
||||
elif subtype == '/Form' and depth < 8:
|
||||
matrix = [float(v) for v in xobject.get('/Matrix', [1, 0, 0, 1, 0, 0])]
|
||||
walk(xobject.get('/Resources', resources),
|
||||
pikepdf.parse_content_stream(xobject), _multiply(ctm, matrix), depth + 1)
|
||||
instructions_of(xobject), _multiply(ctm, matrix), depth + 1)
|
||||
|
||||
walk(page.obj.get('/Resources'), pikepdf.parse_content_stream(page), [1, 0, 0, 1, 0, 0], 0)
|
||||
except _TooMuch:
|
||||
import logging
|
||||
logging.warning('PDF %s draws more than %s images and forms, or takes over %s s: its DPI is left unknown',
|
||||
os.path.basename(path), PDF_MAX_DRAWS, PDF_MAX_SECONDS)
|
||||
return None
|
||||
except Exception:
|
||||
return None
|
||||
found = [(dpi, area) for dpi, area in found if dpi > 0]
|
||||
@@ -132,14 +167,47 @@ def pdf_dpi(path):
|
||||
return js_round(sum(dpi * area for dpi, area in found) / total)
|
||||
|
||||
|
||||
def _pdf_dpi_child(result, path):
|
||||
result.put(pdf_dpi(path))
|
||||
|
||||
|
||||
def bounded_pdf_dpi(path):
|
||||
"""pdf_dpi in a process of its own, ended past PDF_MAX_SECONDS: the PDF
|
||||
library itself can be held by a file (a huge compressed stream), where
|
||||
pdf_dpi's own limits cannot reach. None when it did not finish."""
|
||||
import multiprocessing
|
||||
from queue import Empty
|
||||
context = multiprocessing.get_context('spawn')
|
||||
result = context.Queue()
|
||||
process = context.Process(target=_pdf_dpi_child, args=(result, path))
|
||||
process.start()
|
||||
try:
|
||||
process.join(PDF_MAX_SECONDS + 5)
|
||||
if process.is_alive():
|
||||
process.kill()
|
||||
process.join()
|
||||
import logging
|
||||
logging.warning('PDF %s took over %s s to read: its DPI is left unknown',
|
||||
os.path.basename(path), PDF_MAX_SECONDS + 5)
|
||||
return None
|
||||
try:
|
||||
return result.get(timeout=5)
|
||||
except Empty:
|
||||
return None
|
||||
finally:
|
||||
result.close()
|
||||
result.join_thread()
|
||||
|
||||
|
||||
def stored_pdf_dpi(storage, row):
|
||||
"""A stored PDF's DPI, read once; None when it is above PDF_MAX_BYTES."""
|
||||
"""A stored PDF's DPI, read once; None when it is above PDF_MAX_BYTES or
|
||||
takes too long to read (bounded_pdf_dpi)."""
|
||||
if row['size'] > PDF_MAX_BYTES:
|
||||
return None
|
||||
with tempfile.NamedTemporaryFile(suffix='.pdf') as handle:
|
||||
storage.client.download_fileobj(storage.bucket, row['object_key'], handle)
|
||||
handle.flush()
|
||||
return pdf_dpi(handle.name)
|
||||
return bounded_pdf_dpi(handle.name)
|
||||
|
||||
|
||||
class Files:
|
||||
@@ -227,6 +295,35 @@ def resolution_issue(files, items, rows):
|
||||
return None
|
||||
|
||||
|
||||
def proportion_issue(files, items, rows):
|
||||
"""Why a cart's layout cannot be priced, or None: a raster file laid out
|
||||
at proportions it does not have (a 5 m sheet sent as 10 cm, say). The
|
||||
print file refuses the same thing (app/printfile.py check_layout), but
|
||||
only after payment; here it is refused before. A PDF, or a file whose
|
||||
size the first bytes do not tell, is left to that later check."""
|
||||
from .printfile import ASPECT_TOLERANCE
|
||||
for index, item in enumerate(items, 1):
|
||||
for number, source in enumerate(item['production']['sources'], 1):
|
||||
row = rows.get(str(source['upload_id']))
|
||||
if not row or row['name'].lower().endswith('.pdf'):
|
||||
continue
|
||||
size = image_size(files.head(row))
|
||||
if not size or not all(size):
|
||||
continue
|
||||
width_px, height_px = size
|
||||
if source.get('rotation_degrees') in (90, 270):
|
||||
width_px, height_px = height_px, width_px
|
||||
# A ready sheet's empty strips were cut from its length: the file
|
||||
# is the length plus both strips (app/core/models.py).
|
||||
length = (float(source['length_cm']) + float(source.get('trim_top_cm') or 0)
|
||||
+ float(source.get('trim_bottom_cm') or 0))
|
||||
drift = abs((width_px / height_px) / (float(source['width_cm']) / length) - 1)
|
||||
if drift > ASPECT_TOLERANCE:
|
||||
return (f'Item {index}: o arquivo {number} foi montado com {source["width_cm"]} × '
|
||||
f'{source["length_cm"]} cm, que não são as proporções dele. Monte o pedido de novo.')
|
||||
return None
|
||||
|
||||
|
||||
def mismatch(files, items, rows):
|
||||
"""Why a cart's grades cannot be approved at checkout, or None."""
|
||||
for item in items:
|
||||
|
||||
@@ -4,8 +4,8 @@ FlexiPRINT watches 3. Imprimindo/<máquina>/<C1|C2|C3|PREMIUM>/ and takes a
|
||||
file out of it when it rips. When the operator pulls a card to Imprimindo, its
|
||||
files go, as a copy, into its machine's folder for the item's contraction
|
||||
class; a premium item always goes to PREMIUM, whichever class it carries;
|
||||
the order's own file stays in its stage folder. A film over 15 m is several
|
||||
parts (item 13): all on the same machine, in order. A machine's folder holds
|
||||
the order's own file stays in its stage folder. A film longer than a part
|
||||
(10 m) is several parts (item 13): all on the same machine, in order. A machine's folder holds
|
||||
as many files at once as it has places in Imprimindo (machines.places, three
|
||||
since 2026-11-17); the next is written when Flexi takes one.
|
||||
|
||||
@@ -15,7 +15,8 @@ the same file and Flexi never prints it twice. A claim that did not finish
|
||||
goes back to the queue. A written part that is gone from its folder was
|
||||
taken by Flexi, and is never written again. A card that leaves Imprimindo
|
||||
(Revisão, Correção, a step back, a cancellation) withdraws what Flexi has not
|
||||
taken yet, and its computer deletes it.
|
||||
taken yet, and its computer deletes it. A step back from Revisão to
|
||||
Imprimindo writes again only what Flexi had not taken (resume()).
|
||||
|
||||
Each part's life is one row of dtf_local.hot_parts:
|
||||
queued -> claimed -> written -> consumed, or withdraw -> gone.
|
||||
@@ -70,6 +71,19 @@ def start(c, order_id):
|
||||
VALUES(%s,%s,%s,%s,%s,%s)''', (order_id, round_, seq, row['item_index'], row['upload_id'], row['name']))
|
||||
|
||||
|
||||
def resume(c, order_id):
|
||||
"""A step back from Revisão to Imprimindo, undoing a move made by
|
||||
mistake: the parts of the last round Flexi had not taken go back to the
|
||||
folder, in their order; what it took was printed and is never written
|
||||
again (start() would send the whole order to the machine once more)."""
|
||||
last = c.execute('SELECT max(round) AS r FROM dtf_local.hot_parts WHERE order_id=%s', (order_id,)).fetchone()['r']
|
||||
if last is None:
|
||||
return
|
||||
c.execute('''INSERT INTO dtf_local.hot_parts(order_id,round,seq,item_index,upload_id,name)
|
||||
SELECT order_id, round + 1, row_number() OVER (ORDER BY seq), item_index, upload_id, name
|
||||
FROM dtf_local.hot_parts WHERE order_id=%s AND round=%s AND state<>'consumed' ''', (order_id, last))
|
||||
|
||||
|
||||
def printed(c, order_ids):
|
||||
"""The files each order's machine has already taken, {order id: {upload
|
||||
ids}}: an order in it was printed before."""
|
||||
@@ -105,12 +119,12 @@ def claim(c, user):
|
||||
they entered it, until the machine has its places' worth in its folder."""
|
||||
c.execute('''UPDATE dtf_local.hot_parts SET state='queued', claimed_at=NULL, claimed_by=NULL
|
||||
WHERE state='claimed' AND claimed_at < now() - %s''', (CLAIM_TIMEOUT,))
|
||||
rows = c.execute('''SELECT h.*, o.machine_id, o.contraction, o.snapshot, m.name AS machine_name, m.places,
|
||||
rows = c.execute('''SELECT h.*, o.machine_id, o.contraction, o.snapshot, COALESCE(m.folder, m.name) AS machine_folder, m.places,
|
||||
(SELECT max(v.id) FROM dtf_local.movements v WHERE v.order_id=o.id AND v.to_state='imp') AS entered
|
||||
FROM dtf_local.hot_parts h JOIN dtf_local.orders o ON o.id=h.order_id
|
||||
JOIN dtf_local.machines m ON m.id=o.machine_id
|
||||
WHERE h.state IN ('queued','claimed','written') AND o.state='imp' AND o.cancelled_at IS NULL
|
||||
ORDER BY m.name, entered, h.order_id, h.seq FOR UPDATE OF h''').fetchall()
|
||||
ORDER BY m.created_at, m.id, entered, h.order_id, h.seq FOR UPDATE OF h''').fetchall()
|
||||
due, busy, blocked = [], {}, set()
|
||||
for row in rows:
|
||||
machine = row['machine_id']
|
||||
@@ -125,7 +139,9 @@ def claim(c, user):
|
||||
if busy.get(machine, 0) >= row['places'] or not cls:
|
||||
blocked.add(order)
|
||||
continue
|
||||
folder = f"{row['machine_name']}/{cls}"
|
||||
# The machine's folder, fixed at its creation: a renamed machine keeps
|
||||
# the path FlexiPRINT watches.
|
||||
folder = f"{row['machine_folder']}/{cls}"
|
||||
c.execute('''UPDATE dtf_local.hot_parts SET state='claimed', claimed_at=now(), claimed_by=%s, folder=%s
|
||||
WHERE id=%s''', (user, folder, row['id']))
|
||||
busy[machine] = busy.get(machine, 0) + 1
|
||||
|
||||
@@ -28,7 +28,8 @@ entry. Fewer than two entries, no estimate.
|
||||
|
||||
"Printed" is what left Imprimindo for Revisão on the machine (orders.machine_id,
|
||||
the movement imp -> rev not back): the film metres of the items
|
||||
(COALESCE(metres, billed_metres)), and PROOF_SHEET_CM per item for a proof card.
|
||||
(COALESCE(metres, billed_metres)), and for a proof card the length of each
|
||||
proof sheet (film_metres).
|
||||
"""
|
||||
from datetime import datetime, timezone
|
||||
from decimal import Decimal
|
||||
@@ -58,24 +59,40 @@ def one_decimal(value):
|
||||
return f'{Decimal(str(value)):.1f}'.replace('.', ',')
|
||||
|
||||
|
||||
def printed_since(c, machine_id, since):
|
||||
"""Film metres the machine printed after `since` (None: ever), as Decimal."""
|
||||
# A pass to Revisão undone at once (a mistaken move, back to Imprimindo):
|
||||
# the pass after the undo counts the film, so this one must not, or the
|
||||
# machine's metres count it twice. `m` is the pass in dtf_local.movements.
|
||||
NOT_UNDONE = """NOT EXISTS (SELECT 1 FROM dtf_local.movements u WHERE u.order_id=m.order_id AND u.back
|
||||
AND u.from_state='rev' AND u.to_state='imp'
|
||||
AND u.id=(SELECT min(n.id) FROM dtf_local.movements n WHERE n.order_id=m.order_id AND n.id>m.id))"""
|
||||
|
||||
|
||||
# Each proof sheet's stretches of film, {item index: [[top, bottom], ...]},
|
||||
# from its print file (app/printpng.py); `o` is the order.
|
||||
PROOF_WINDOWS = """(SELECT jsonb_object_agg(p.item_index::text, p.detail->'proof_windows')
|
||||
FROM dtf_local.print_files p WHERE p.order_id=o.id AND p.detail ? 'proof_windows') AS windows"""
|
||||
|
||||
|
||||
def film_metres(snapshot, items=None, windows=None):
|
||||
"""The film one pass to Revisão printed, in metres, as Decimal: each
|
||||
item's metres, on a reprint only the `items` that went again (#105). A
|
||||
proof card's item is its sheet: the finest stroke's window and the colour
|
||||
samples with the clear film between them, up to 30 cm (Marcus,
|
||||
2026-11-26), from `windows` ({item index: [[top, bottom], ...]} in cm);
|
||||
PROOF_SHEET_CM for a sheet made before the samples."""
|
||||
from .printpng import PROOF_GAP_CM
|
||||
from .proof import PROOF_SHEET_CM
|
||||
rows = c.execute('''SELECT o.snapshot, m.items FROM dtf_local.movements m
|
||||
JOIN dtf_local.orders o ON o.id=m.order_id
|
||||
WHERE o.machine_id=%s AND m.from_state='imp' AND m.to_state='rev' AND NOT m.back
|
||||
AND (%s::timestamptz IS NULL OR m.created_at > %s::timestamptz)''',
|
||||
(machine_id, since, since)).fetchall()
|
||||
total = Decimal(0)
|
||||
for row in rows:
|
||||
snapshot = row['snapshot'] or {}
|
||||
snapshot = snapshot or {}
|
||||
proof = bool(snapshot.get('proof_of'))
|
||||
total = Decimal(0)
|
||||
for index, item in enumerate(snapshot.get('items') or []):
|
||||
# A reprint counts only the items that went again (#105).
|
||||
if row.get('items') is not None and index not in row['items']:
|
||||
if items is not None and index not in items:
|
||||
continue
|
||||
if proof:
|
||||
total += PROOF_SHEET_CM
|
||||
stretches = (windows or {}).get(str(index)) or []
|
||||
cm = (sum((Decimal(str(b)) - Decimal(str(a)) for a, b in stretches), Decimal(0))
|
||||
+ PROOF_GAP_CM * (len(stretches) - 1)) if stretches else PROOF_SHEET_CM
|
||||
total += cm / 100
|
||||
else:
|
||||
value = item.get('metres')
|
||||
if value is None:
|
||||
@@ -84,6 +101,16 @@ def printed_since(c, machine_id, since):
|
||||
return total
|
||||
|
||||
|
||||
def printed_since(c, machine_id, since):
|
||||
"""Film metres the machine printed after `since` (None: ever), as Decimal."""
|
||||
rows = c.execute(f'''SELECT o.snapshot, m.items, {PROOF_WINDOWS} FROM dtf_local.movements m
|
||||
JOIN dtf_local.orders o ON o.id=m.order_id
|
||||
WHERE o.machine_id=%s AND m.from_state='imp' AND m.to_state='rev' AND NOT m.back AND {NOT_UNDONE}
|
||||
AND (%s::timestamptz IS NULL OR m.created_at > %s::timestamptz)''',
|
||||
(machine_id, since, since)).fetchall()
|
||||
return sum((film_metres(row['snapshot'], row.get('items'), row.get('windows')) for row in rows), Decimal(0))
|
||||
|
||||
|
||||
def _last_entry(c, machine_id, kind, item):
|
||||
return c.execute('''SELECT * FROM dtf_local.machine_entries
|
||||
WHERE machine_id=%s AND kind=%s AND item=%s
|
||||
@@ -178,7 +205,7 @@ def alerts(c, machine_id):
|
||||
'snoozable': bool, 'blocking': bool}. blocking is False when it was
|
||||
postponed this cycle and no card was pulled on the machine since.
|
||||
Texts, with metres in one decimal and a comma:
|
||||
clean "<máquina>: 10,4 m desde a última limpeza — limpe antes do próximo arquivo"
|
||||
clean "<máquina>: 10,4 m desde a última limpeza: limpe antes do próximo arquivo"
|
||||
align "<máquina>: 19,8 m desde a troca de filme — alinhe a cabeça antes do próximo"
|
||||
supply "<label minúsculo> da <máquina> deve acabar em ~3 m" (e.g. "tinta branca da máquina2 deve acabar em ~3,0 m")
|
||||
"""
|
||||
@@ -209,11 +236,11 @@ def alerts(c, machine_id):
|
||||
|
||||
if counts['clean']['metres'] >= CLEAN_EVERY_METRES:
|
||||
due('clean', f"{name}: {one_decimal(counts['clean']['metres'])} m desde a última limpeza "
|
||||
'— limpe antes do próximo arquivo', counts['clean']['since'])
|
||||
': limpe antes do próximo arquivo', counts['clean']['since'])
|
||||
if (counts['film']['since'] is not None and not counts['film']['aligned']
|
||||
and counts['film']['metres'] >= ALIGN_AFTER_FILM_METRES):
|
||||
due('align', f"{name}: {one_decimal(counts['film']['metres'])} m desde a troca de filme "
|
||||
'— alinhe a cabeça antes do próximo', counts['film']['since'])
|
||||
': alinhe a cabeça antes do próximo', counts['film']['since'])
|
||||
for item, value in supplies.items():
|
||||
if not supply_low(value):
|
||||
continue
|
||||
|
||||
@@ -5,7 +5,7 @@ what the board already knows it printed, per machine and calendar month
|
||||
(America/Sao_Paulo):
|
||||
|
||||
Produção printed metres (machine_log rule: imp -> rev, film metres,
|
||||
PROOF_SHEET_CM per proof item); hours running = the union of the
|
||||
a proof sheet its real length); hours running = the union of the
|
||||
time its orders spent in Imprimindo, clipped to the month (two
|
||||
orders printing together count once); metres per hour = printed
|
||||
/ hours running; hours stopped = the "stop" events' minutes, in
|
||||
@@ -33,7 +33,7 @@ from datetime import datetime, time
|
||||
from decimal import Decimal, ROUND_HALF_UP
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from .machine_log import SUPPLIES
|
||||
from .machine_log import NOT_UNDONE, PROOF_WINDOWS, SUPPLIES, film_metres
|
||||
|
||||
SAO_PAULO = ZoneInfo('America/Sao_Paulo')
|
||||
# The five inks Números lists, in the order the sheet knows them.
|
||||
@@ -119,30 +119,15 @@ def ratios(printed, hours_running=None, supplies_cents=0, parts_cents=0, rolls=N
|
||||
def _printed_orders(c, machine_id, start, end):
|
||||
"""The orders that left Imprimindo for Revisão on the machine in the
|
||||
period, with what is needed to count film and what they sold."""
|
||||
return c.execute('''SELECT o.id, o.snapshot, o.parent_id, o.cancelled_at, o.payment, m.items
|
||||
return c.execute(f'''SELECT o.id, o.snapshot, o.parent_id, o.cancelled_at, o.payment, m.items, {PROOF_WINDOWS}
|
||||
FROM dtf_local.movements m JOIN dtf_local.orders o ON o.id=m.order_id
|
||||
WHERE o.machine_id=%s AND m.from_state='imp' AND m.to_state='rev' AND NOT m.back
|
||||
WHERE o.machine_id=%s AND m.from_state='imp' AND m.to_state='rev' AND NOT m.back AND {NOT_UNDONE}
|
||||
AND m.created_at>=%s AND m.created_at<%s''', (machine_id, start, end)).fetchall()
|
||||
|
||||
|
||||
def _film(snapshot, items=None):
|
||||
"""The film printed for one order (machine_log's rule), as Decimal; on a
|
||||
reprint only the `items` that went again."""
|
||||
from .proof import PROOF_SHEET_CM
|
||||
snapshot = snapshot or {}
|
||||
proof = bool(snapshot.get('proof_of'))
|
||||
total = Decimal(0)
|
||||
for index, item in enumerate(snapshot.get('items') or []):
|
||||
if items is not None and index not in items:
|
||||
continue
|
||||
if proof:
|
||||
total += PROOF_SHEET_CM
|
||||
else:
|
||||
value = item.get('metres')
|
||||
if value is None:
|
||||
value = item.get('billed_metres')
|
||||
total += Decimal(str(value or 0))
|
||||
return total
|
||||
def _film(row):
|
||||
"""The film one printed order took (machine_log's rule), as Decimal."""
|
||||
return film_metres(row['snapshot'], row.get('items'), row.get('windows'))
|
||||
|
||||
|
||||
def _sold(row):
|
||||
@@ -157,7 +142,7 @@ def _sold(row):
|
||||
|
||||
def printed_between(c, machine_id, start, end):
|
||||
"""Film metres the machine printed in [start, end), as Decimal."""
|
||||
return sum((_film(row['snapshot'], row.get('items')) for row in _printed_orders(c, machine_id, start, end)),
|
||||
return sum((_film(row) for row in _printed_orders(c, machine_id, start, end)),
|
||||
Decimal(0))
|
||||
|
||||
|
||||
@@ -189,7 +174,7 @@ def machine_month(c, machine, start, end):
|
||||
'contribution_cents'}. `machine` is its row from dtf_local.machines."""
|
||||
mid = machine['id']
|
||||
rows = _printed_orders(c, mid, start, end)
|
||||
printed = sum((_film(row['snapshot'], row.get('items')) for row in rows), Decimal(0))
|
||||
printed = sum((_film(row) for row in rows), Decimal(0))
|
||||
sold = sum((_sold(row) for row in rows), 0)
|
||||
ids = [row['id'] for row in rows]
|
||||
spans = c.execute('''WITH events AS (
|
||||
@@ -278,9 +263,9 @@ def report(c, month=None):
|
||||
'''SELECT DISTINCT machine_id FROM dtf_local.machine_entries
|
||||
WHERE created_at>=%s AND created_at<%s''', (start, end)).fetchall()}
|
||||
printed = {str(row['machine_id']) for row in c.execute(
|
||||
'''SELECT DISTINCT o.machine_id FROM dtf_local.movements m
|
||||
f'''SELECT DISTINCT o.machine_id FROM dtf_local.movements m
|
||||
JOIN dtf_local.orders o ON o.id=m.order_id
|
||||
WHERE m.from_state='imp' AND m.to_state='rev' AND NOT m.back
|
||||
WHERE m.from_state='imp' AND m.to_state='rev' AND NOT m.back AND {NOT_UNDONE}
|
||||
AND m.created_at>=%s AND m.created_at<%s''', (start, end)).fetchall()}
|
||||
result = []
|
||||
for machine in machines:
|
||||
|
||||
@@ -39,7 +39,8 @@ def loads(c):
|
||||
|
||||
def rows(c, with_operators=False):
|
||||
"""Every machine with its load, for the Kanban."""
|
||||
machines = c.execute('''SELECT id, name, products, active, limit_metres, places FROM dtf_local.machines
|
||||
machines = c.execute('''SELECT id, name, COALESCE(folder, name) AS folder, products, active, limit_metres, places
|
||||
FROM dtf_local.machines
|
||||
ORDER BY created_at, name''').fetchall()
|
||||
load = loads(c)
|
||||
operators = {}
|
||||
@@ -55,7 +56,7 @@ def rows(c, with_operators=False):
|
||||
for m in machines:
|
||||
key = str(m['id'])
|
||||
used = load.get(key, {'metres': Decimal(0), 'orders': 0, 'states': {}})
|
||||
row = {'id': key, 'name': m['name'], 'products': m['products'], 'active': m['active'],
|
||||
row = {'id': key, 'name': m['name'], 'folder': m['folder'], 'products': m['products'], 'active': m['active'],
|
||||
'limit_metres': float(m['limit_metres']) if m['limit_metres'] is not None else None,
|
||||
'places': m['places'],
|
||||
'open_metres': float(used['metres']), 'open_orders': used['orders'], 'states': used['states'],
|
||||
|
||||
@@ -84,10 +84,10 @@ def order_paid(c, order, origin):
|
||||
number, link = order['number'], f"{origin}/conta/pedidos?order={order['id']}"
|
||||
text = '\n'.join([mail_html.greeting(customer.get('name')), '',
|
||||
f'Seu pagamento foi aprovado e o pedido #{number} já está com a nossa equipe. '
|
||||
'Agora a gente confere a arte e coloca na fila de impressão.', '',
|
||||
'Conferimos a arte e colocamos na fila de impressão.', '',
|
||||
*(f'{key}: {value}' for key, value in rows), '',
|
||||
f'Acompanhe cada etapa em Minha conta: {link}', '',
|
||||
'Ainda não tem conta? Crie com este e-mail e o mesmo CPF/CNPJ do pedido: ele aparece lá na hora.'])
|
||||
'Se ainda não tem conta, crie com este e-mail e o mesmo CPF/CNPJ do pedido: ele aparece lá na hora.'])
|
||||
return queue(c, 'order', customer['mail'], f'Recebemos seu pedido #{number} · DTF Dropstar', text,
|
||||
mail_html.order_paid(customer.get('name'), number, rows, link))
|
||||
|
||||
@@ -108,14 +108,14 @@ def quote_expired(c, quote, origin):
|
||||
link = f'{origin}/'
|
||||
text = '\n'.join([mail_html.greeting(customer.get('name')), '',
|
||||
'Seu pedido não foi pago em 24 horas e expirou. Os arquivos que você enviou foram apagados.', '',
|
||||
f'Quando quiser, é só montar de novo no site: {link}'])
|
||||
f'Para pedir de novo, monte no site: {link}'])
|
||||
html = mail_html.layout('Seu pedido não foi pago em 24 horas e expirou.', 'Seu pedido', [
|
||||
mail_html.pill('Pedido expirado', 'info'),
|
||||
mail_html.title('Seu pedido expirou'),
|
||||
mail_html.para(f'{mail_html.greeting(customer.get("name"))} Seu pedido não foi pago em 24 horas e '
|
||||
'expirou. Os arquivos que você enviou foram apagados.'),
|
||||
mail_html.button('Montar de novo', link),
|
||||
mail_html.small(f'Quando quiser, é só montar de novo no site: {link}'),
|
||||
mail_html.small(f'Para pedir de novo, monte no site: {link}'),
|
||||
])
|
||||
return queue(c, 'notice', customer['mail'], 'Seu pedido expirou · DTF Dropstar', text, html)
|
||||
|
||||
|
||||
@@ -152,12 +152,11 @@ def reset(name, link, minutes):
|
||||
hours = 'por 1 hora' if minutes == 60 else f'por {minutes} minutos'
|
||||
return layout('Clique no botão para criar uma nova senha.', 'Sua conta', [
|
||||
title('Crie uma nova senha'),
|
||||
para(f'{greeting(name)} Recebemos um pedido para criar uma nova senha na sua conta. '
|
||||
'É só clicar no botão abaixo.'),
|
||||
para(f'{greeting(name)} Recebemos um pedido de nova senha para a sua conta.'),
|
||||
button('Criar nova senha', link),
|
||||
small(f'O link vale {hours} e funciona uma vez só. Se não foi você, ignore este e-mail: '
|
||||
'sua senha continua a mesma.'),
|
||||
small('O botão não abriu? Copie este endereço no navegador: ',
|
||||
small('Se o botão não abrir, copie este endereço no navegador: ',
|
||||
f'<br><a href="{escape(link, quote=True)}" style="color:{DARK_ORANGE};word-break:break-all">'
|
||||
f'{escape(link)}</a>'),
|
||||
])
|
||||
@@ -167,7 +166,7 @@ def account_exists(name, login_link):
|
||||
return layout('Este e-mail já tem conta no DTF Dropstar.', 'Sua conta', [
|
||||
title('Este e-mail já tem uma conta'),
|
||||
para(f'{greeting(name)} Alguém tentou criar uma conta no DTF Dropstar com este e-mail, mas ele já está '
|
||||
'cadastrado. Para ver seus pedidos, é só entrar.'),
|
||||
'cadastrado. Entre para ver seus pedidos.'),
|
||||
button('Entrar na minha conta', login_link),
|
||||
callout('Esqueceu a senha?', 'Na página de entrada, clique em “Esqueci minha senha” e enviamos um link '
|
||||
'para criar outra.'),
|
||||
@@ -180,7 +179,7 @@ def email_changed(name, old, new):
|
||||
title('O e-mail da sua conta foi trocado'),
|
||||
para(f'{greeting(name)} A partir de agora, sua conta no DTF Dropstar entra com outro e-mail:'),
|
||||
facts([('Antes', old), ('Agora', new)]),
|
||||
callout('Não foi você?', 'Fale com a Dropstar agora pelo WhatsApp: a gente ajuda a recuperar a conta.',
|
||||
callout('Não foi você?', 'Fale com a Dropstar pelo WhatsApp para recuperar a conta.',
|
||||
warn=True),
|
||||
button('Falar no WhatsApp', WHATSAPP, dark=True),
|
||||
])
|
||||
@@ -190,14 +189,14 @@ def order_paid(name, number, rows, link):
|
||||
return layout(f'Pagamento aprovado. O pedido #{number} já está com a nossa equipe.', 'Seu pedido', [
|
||||
pill('Pagamento aprovado'),
|
||||
title(f'Recebemos seu pedido #{number}'),
|
||||
para(f'{greeting(name)} Seu pagamento foi aprovado e o pedido já está com a nossa equipe. Agora a gente '
|
||||
'confere a arte e coloca na fila de impressão.'),
|
||||
para(f'{greeting(name)} Seu pagamento foi aprovado e o pedido já está com a nossa equipe. '
|
||||
'Conferimos a arte e colocamos na fila de impressão.'),
|
||||
facts(rows),
|
||||
steps([('Pagamento aprovado', 'Pedido recebido pela equipe', True),
|
||||
('Arte conferida', 'A equipe confere se está tudo certo para imprimir', False),
|
||||
('Impressão', 'Seu filme entra na máquina', False),
|
||||
('Pronto', 'Você recebe o aviso pelo WhatsApp', False)]),
|
||||
button('Ver meu pedido', link),
|
||||
small('Acompanhe cada etapa em Minha conta. Ainda não tem conta? Crie com este e-mail e o mesmo CPF/CNPJ '
|
||||
'do pedido: ele aparece lá na hora.'),
|
||||
small('Acompanhe cada etapa em Minha conta. Se ainda não tem conta, crie com este e-mail e o mesmo '
|
||||
'CPF/CNPJ do pedido: ele aparece lá na hora.'),
|
||||
])
|
||||
|
||||
5
app/migrations/202611272000_machine-folder.sql
Normal file
5
app/migrations/202611272000_machine-folder.sql
Normal file
@@ -0,0 +1,5 @@
|
||||
-- Each machine's hot folder (3. Imprimindo/<folder>/C1..) is fixed when the
|
||||
-- machine is created: FlexiPRINT watches that path, so renaming the machine
|
||||
-- must not send its files to a folder nobody watches (2026-11-27).
|
||||
ALTER TABLE dtf_local.machines ADD COLUMN IF NOT EXISTS folder text;
|
||||
UPDATE dtf_local.machines SET folder=name WHERE folder IS NULL;
|
||||
@@ -24,14 +24,20 @@ from .runtime import PUBLIC_ORIGIN, enqueue, upload_row
|
||||
from .scanning import require_clean
|
||||
|
||||
QUOTE_VALID_HOURS = 24
|
||||
# A card the provider holds "em análise" may be approved hours or days later:
|
||||
# its quote stays open, its files kept and the provider asked this long.
|
||||
CARD_REVIEW_HOURS = 72
|
||||
|
||||
|
||||
class PaymentRefused(Exception):
|
||||
"""The payment cannot become an order, with a reason worth recording."""
|
||||
|
||||
|
||||
def approved_quote(c, quote_id, owner=None):
|
||||
"""The reviewed quote behind a payment, or a refusal explaining why not."""
|
||||
def approved_quote(c, quote_id, owner=None, payment_id=None):
|
||||
"""The reviewed quote behind a payment, or a refusal explaining why not.
|
||||
`payment_id`, from a provider's notice: a payment started while the quote
|
||||
was valid is honoured whenever its approval arrives (a PIX paid in its
|
||||
last minutes, a card approved after review)."""
|
||||
sql = 'SELECT * FROM dtf_local.quotes WHERE id=%s' + (' AND owner=%s' if owner else '')
|
||||
row = c.execute(sql + ' FOR UPDATE', (quote_id, owner) if owner else (quote_id,)).fetchone()
|
||||
if not row:
|
||||
@@ -42,7 +48,12 @@ def approved_quote(c, quote_id, owner=None):
|
||||
raise PaymentRefused('quote was discarded')
|
||||
if any(item.get('production', {}).get('version') not in PRODUCTION_VERSIONS for item in row['approved']['items']):
|
||||
raise PaymentRefused('quote uses an obsolete production layout; request a new quote')
|
||||
if row['approved_at'] < datetime.now(timezone.utc) - timedelta(hours=QUOTE_VALID_HOURS):
|
||||
deadline = row['approved_at'] + timedelta(hours=QUOTE_VALID_HOURS)
|
||||
if deadline < datetime.now(timezone.utc):
|
||||
started = payment_id and c.execute('''SELECT 1 FROM dtf_local.payment_intents
|
||||
WHERE quote_id=%s AND provider_payment_id=%s AND created_at <= %s''',
|
||||
(quote_id, str(payment_id), deadline)).fetchone()
|
||||
if not started:
|
||||
raise PaymentRefused('quote expired before payment')
|
||||
return row
|
||||
|
||||
@@ -77,6 +88,34 @@ def in_tiny(order):
|
||||
return not is_test(order) and not order.get('parent_id')
|
||||
|
||||
|
||||
# What a stage tells Tiny: entering the queue (Arte conferida) is its
|
||||
# "Preparando envio", Finalizado its "Pronto para envio" (Dropstar's flow,
|
||||
# 2026-10-23); a correction has no situação and is only recorded.
|
||||
STAGE_EVENTS = {'tra': 'production_started', 'cor': 'correction_needed', 'fin': 'ready'}
|
||||
|
||||
|
||||
def stage_event(c, order, state, reason, version):
|
||||
"""Queue Tiny's event for an order that entered `state` (not by a step
|
||||
back), whoever moved it: a card dragged, or the Prova OK that puts the
|
||||
order in the queue (app/proof.py). `order` is its row before the move,
|
||||
`version` its version after."""
|
||||
if state not in STAGE_EVENTS or not in_tiny(order):
|
||||
return
|
||||
# "Production started" and "ready" reach the customer once per order,
|
||||
# even if a mistaken move is undone and made again. Each correction is a
|
||||
# new request, so it keeps one message per movement.
|
||||
once = state in ('tra', 'fin')
|
||||
event = {'order_id': str(order['id']), 'number': order['number'], 'event': STAGE_EVENTS[state],
|
||||
'reason': reason, 'customer_path': f"/portal.html?order={order['id']}"}
|
||||
# Tiny needs the order (customer, pickup or delivery) and, once the sale
|
||||
# reached it, its id, to set the situação without a search.
|
||||
sale = c.execute("SELECT receipt FROM dtf_local.outbox WHERE event_key=%s AND delivered_at IS NOT NULL",
|
||||
(f"{order['id']}:paid:tiny",)).fetchone()
|
||||
tiny = {**event, 'order': order['snapshot'], 'tiny_id': ((sale or {}).get('receipt') or {}).get('tiny_id')}
|
||||
key = f"{order['id']}:{STAGE_EVENTS[state]}:tiny" if once else f"{order['id']}:{version}:tiny"
|
||||
enqueue(c, key, 'tiny', tiny)
|
||||
|
||||
|
||||
# How long a file is kept while nothing has been paid for it. A cart's files
|
||||
# are uploaded before payment, so the price and the security check are done on
|
||||
# the file itself; a cart that is never paid must not keep them for 30 days.
|
||||
@@ -212,7 +251,7 @@ def apply(c, event):
|
||||
return 'refused: reference is not a quote id'
|
||||
|
||||
try:
|
||||
quote = approved_quote(c, quote_id)
|
||||
quote = approved_quote(c, quote_id, payment_id=provider_id)
|
||||
except PaymentRefused as refusal:
|
||||
return f'refused: {refusal}'
|
||||
|
||||
@@ -227,7 +266,16 @@ def apply(c, event):
|
||||
return f'refused: paid {event.amount_cents} but quote total is {expected}'
|
||||
|
||||
order, created = create_order(c, quote, {'provider': event.raw.get('provider', 'webhook'), **event.raw}, 'site')
|
||||
return f"order {order['number']}" + ('' if created else ' (already existed)')
|
||||
if created:
|
||||
return f"order {order['number']}"
|
||||
# The order exists, paid by another payment (a PIX and a card for the same
|
||||
# cart, or paid outside the site too): the customer paid twice. Listed on
|
||||
# the Kanban until someone refunds one, like a reversal.
|
||||
first = str((order.get('payment') or {}).get('payment_id') or '')
|
||||
if provider_id and str(provider_id) != first:
|
||||
audit('payment_duplicate', order=order['number'], payment=str(provider_id), c=c)
|
||||
return f"attention: second payment {provider_id} for order {order['number']}; refund one"
|
||||
return f"order {order['number']} (already existed)"
|
||||
|
||||
|
||||
def reconcile(connect, provider, quote_id=None, limit=20):
|
||||
@@ -245,7 +293,7 @@ def reconcile(connect, provider, quote_id=None, limit=20):
|
||||
WHERE o.id IS NULL AND i.provider=%s AND i.status IN ('pending','approved')
|
||||
AND i.created_at > now() - make_interval(hours => %s)''' +
|
||||
(' AND i.quote_id=%s' if quote_id else '') + ' ORDER BY i.created_at DESC LIMIT %s',
|
||||
(provider.name, QUOTE_VALID_HOURS + 1, *([quote_id] if quote_id else []), limit)).fetchall()
|
||||
(provider.name, CARD_REVIEW_HOURS + 1, *([quote_id] if quote_id else []), limit)).fetchall()
|
||||
outcomes = []
|
||||
for row in rows:
|
||||
# Asked outside any transaction: no lock is held while the provider answers.
|
||||
|
||||
@@ -27,6 +27,7 @@ from decimal import Decimal
|
||||
from PIL import Image, ImageOps
|
||||
|
||||
from .core.models import PRODUCTION_VERSIONS
|
||||
from .core.pricing import STEP_GRACE_M
|
||||
|
||||
PT_PER_CM = 72 / 2.54
|
||||
# Acrobat's page limit, 200 inches (5,08 m). A longer sheet is written at its
|
||||
@@ -387,7 +388,8 @@ def check_layout(item, sizes, vector=(), proof=False):
|
||||
production = item['production']
|
||||
height = Decimal(str(production['height_cm']))
|
||||
billed = Decimal(str(item['billed_metres'])) * 100
|
||||
if not proof and height > billed + HEIGHT_TOLERANCE_CM:
|
||||
# Up to 8 mm past the billed length is the customer's grace (app/core/pricing.py).
|
||||
if not proof and height > billed + STEP_GRACE_M * 100 + HEIGHT_TOLERANCE_CM:
|
||||
raise Unsupported(f'a montagem tem {height} cm, mas só {billed} cm foram cobrados')
|
||||
lowest = None
|
||||
for placement in production['placements']:
|
||||
|
||||
@@ -7,7 +7,7 @@ plus a margin; CLAIM_TIMEOUT for a claim made before deadlines existed) is
|
||||
assumed to belong to a worker that died and is taken again.
|
||||
|
||||
The result is a 300 DPI PNG (item 13, app/printpng.py), or its parts for a
|
||||
film over 15 m: ordinary upload rows owned by an identity derived from the
|
||||
film longer than a part (10 m): ordinary upload rows owned by an identity derived from the
|
||||
order, already marked clean, since their only inputs are artwork that passed
|
||||
the malware scan and the bytes are written here. dtf_local.print_parts lists
|
||||
them in order. The operator still decides whether they become the final
|
||||
|
||||
@@ -19,8 +19,9 @@ holds a whole sheet: the film is composed and written in bands of rows.
|
||||
- Loose artwork is small: each file is decoded, turned and scaled to its place
|
||||
once, and copied into every band it crosses.
|
||||
|
||||
A layout longer than 15 m leaves as parts of up to 15 m (Dropstar,
|
||||
2026-10-30), DTF-7-item-1-p3.png, each with its footer saying which part it
|
||||
A layout longer than a part leaves as parts of up to PART_CM, 10 m since
|
||||
Marcus's 18/11 answer (Flexi opens up to 4 GB per image; Dropstar,
|
||||
2026-10-30, was 15 m), DTF-7-item-1-p3.png, each with its footer saying which part it
|
||||
is. Loose artwork is cut where no piece crosses; a finished sheet between
|
||||
copies, or else in a clear band of its own pixels, and through the artwork
|
||||
only when it has none (#136).
|
||||
@@ -41,11 +42,14 @@ from .printtiles import Pyramid
|
||||
|
||||
DPI = 300
|
||||
PX_PER_CM = DPI / 2.54
|
||||
# Parts of up to 15 m, 6732 x 177165 px (Dropstar, 2026-10-30).
|
||||
PART_CM = Decimal(os.environ.get('PRINT_PART_CM', '1500'))
|
||||
# Parts of up to 10 m (Marcus, 2026-11-18): a 15 m part, 6732 x 177165 px, is
|
||||
# 4,8 GB decoded and FlexiPRINT refuses it. PRINT_PART_CM overrides it.
|
||||
PART_CM = Decimal(os.environ.get('PRINT_PART_CM', '1000'))
|
||||
# A cut through artwork only when no gap between pieces is this close to the limit.
|
||||
CUT_SEARCH_CM = Decimal('200')
|
||||
BAND_ROWS = 512
|
||||
# A pixel above this alpha takes ink (web/site-sheet.js ALFA_TINTA).
|
||||
INK_ALPHA = 10
|
||||
# Above this a source is read band by band instead of decoded whole.
|
||||
STREAM_ABOVE_PIXELS = 40_000_000
|
||||
FOOTER_TEXT_CM = 1.1
|
||||
@@ -266,9 +270,44 @@ class Source:
|
||||
top, bottom = round(height * top_cm / full_cm), round(height * bottom_cm / full_cm)
|
||||
if top + bottom >= height:
|
||||
raise Unsupported(f'"{self.name}": o corte das faixas vazias tiraria o arquivo inteiro')
|
||||
self._require_clear(top, bottom)
|
||||
self.cut = (top, bottom)
|
||||
self.size = (width, height - top - bottom)
|
||||
|
||||
def _require_clear(self, top, bottom):
|
||||
"""The strips the Site measured as empty must be: cut on a measure the
|
||||
file does not bear out, artwork would leave the print unseen. A pixel
|
||||
takes ink above INK_ALPHA, as the Site counts it. Not clear, or too
|
||||
big to read here: the item goes to hand preparation, with the reason."""
|
||||
width, height = self.size
|
||||
where = lambda first: 'do começo' if first else 'do fim'
|
||||
|
||||
def check(band, offset):
|
||||
for start, stop, first in ((0, top, True), (height - bottom, height, False)):
|
||||
a, b = max(start, offset), min(stop, offset + band.height)
|
||||
if a < b and rgba(band.crop((0, a - offset, band.width, b - offset))).getchannel('A').getextrema()[1] > INK_ALPHA:
|
||||
raise Unsupported(f'"{self.name}": a faixa que o site cortou {where(first)} do arquivo tem arte. '
|
||||
'Confira o arquivo e prepare a folha à mão')
|
||||
|
||||
if self.streamable:
|
||||
reader = PngRows(self.path)
|
||||
try:
|
||||
done = 0
|
||||
# Read in order to the end of the bottom strip (or of the top one).
|
||||
while done < (height if bottom else top):
|
||||
band = reader.band(BAND_ROWS)
|
||||
if done < top or done + band.height > height - bottom:
|
||||
check(band, done)
|
||||
done += band.height
|
||||
finally:
|
||||
reader.close()
|
||||
return
|
||||
if width * height > MAX_DECODED_PIXELS:
|
||||
raise Unsupported(f'"{self.name}" é grande demais para conferir as faixas cortadas; prepare a folha à mão')
|
||||
with Image.open(self.path) as image:
|
||||
image = ImageOps.exif_transpose(image) if self.orientation != 1 else image
|
||||
check(image, 0)
|
||||
|
||||
def decoded(self, width, height):
|
||||
"""The whole file at (width, height) px, upright, RGBA."""
|
||||
if self.pdf:
|
||||
|
||||
17
app/proof.py
17
app/proof.py
@@ -1,8 +1,9 @@
|
||||
"""The print proof (Dropstar, 2026-10-21).
|
||||
|
||||
An order above 10 m prints a proof before the rest, checked by the print room
|
||||
without stopping the order. Dropstar's current rule: up to 15 cm, from
|
||||
the part with the thinnest lines, a piece of each different artwork, at most
|
||||
without stopping the order. Dropstar's current rule: 15 cm from the part
|
||||
with the thinnest lines plus samples of the file's main colours, up to 30 cm
|
||||
in all (Marcus, 2026-11-26), a piece of each different artwork, at most
|
||||
three proofs per order, never billed. On an order above 10 m the customer
|
||||
may also ask for a proof at checkout (below 10 m there is none, Dropstar
|
||||
2026-10-28): that order waits for them, marked "Aguardando contato", until
|
||||
@@ -37,12 +38,14 @@ def needs_proof(snapshot):
|
||||
#
|
||||
# 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 15 cm per contraction class, and follows the normal flow up
|
||||
# sheet of up to 30 cm per contraction class, 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.
|
||||
# The finest stroke's window; with the colour samples the sheet reaches
|
||||
# app/printpng.py PROOF_MAX_CM.
|
||||
PROOF_SHEET_CM = Decimal('15')
|
||||
# Three proofs at most per order, one per item (Dropstar, 2026-10-23).
|
||||
MAX_PROOFS = 3
|
||||
@@ -149,8 +152,12 @@ def approve_parent(c, parent, operator):
|
||||
WHERE f.order_id=%s AND f.item_index=%s AND {FINAL_OK} {treatment_clause} LIMIT 1''',
|
||||
(parent['id'], i)).fetchone() for i in range(len(parent['snapshot']['items'])))
|
||||
if ready:
|
||||
c.execute('''UPDATE dtf_local.orders SET state='tra', version=version+1, updated_at=now()
|
||||
WHERE id=%s''', (parent['id'],))
|
||||
version = c.execute('''UPDATE dtf_local.orders SET state='tra', version=version+1, updated_at=now()
|
||||
WHERE id=%s RETURNING version''', (parent['id'],)).fetchone()['version']
|
||||
c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason)
|
||||
VALUES(%s,'rec','tra',%s,'Prova OK')''', (parent['id'], operator))
|
||||
# Entering the queue this way is Tiny's "Preparando envio" too, as a
|
||||
# card moved by hand: orders with a proof skipped it.
|
||||
from .payments import stage_event
|
||||
stage_event(c, parent, 'tra', 'Prova OK', version)
|
||||
return ready
|
||||
|
||||
@@ -114,9 +114,9 @@ def report(order, uploads):
|
||||
if item.get('stroke_px') and item.get('stroke_class'):
|
||||
lines.append(f'{lead}Menor traço {item["stroke_px"]} px → {item["stroke_class"]}')
|
||||
if item.get('stroke_choice') == 'client_c3':
|
||||
lines.append(f'{lead}Aviso de traço fino disparou — cliente escolheu proteger as áreas chapadas (C3)')
|
||||
lines.append(f'{lead}Aviso de traço fino: cliente escolheu proteger as áreas chapadas (C3)')
|
||||
elif item.get('stroke_choice') == 'measured':
|
||||
lines.append(f'{lead}Aviso de traço fino disparou — cliente escolheu imprimir em C1')
|
||||
lines.append(f'{lead}Aviso de traço fino: cliente escolheu imprimir em C1')
|
||||
else:
|
||||
lines.append(f'{lead}Aviso de traço fino não disparou')
|
||||
if row:
|
||||
|
||||
@@ -124,13 +124,32 @@ def check_large(head, row):
|
||||
return 'rejected', 'O conteúdo do arquivo não corresponde ao formato do nome'
|
||||
|
||||
|
||||
# When the scan of the file now in hand began (None between files): the
|
||||
# worker's health reports a scan held on one file for longer than
|
||||
# SCAN_STUCK_SECONDS, since every upload waits behind it.
|
||||
busy_since=None
|
||||
SCAN_STUCK_SECONDS=900
|
||||
|
||||
def stuck():
|
||||
"""Whether the scan has been on the same file for SCAN_STUCK_SECONDS."""
|
||||
return busy_since is not None and time.monotonic()-busy_since>SCAN_STUCK_SECONDS
|
||||
|
||||
def scan_one(storage, scanner=None):
|
||||
global busy_since
|
||||
scanner=scanner or ClamAV()
|
||||
with connect() as c:
|
||||
row=c.execute('''SELECT * FROM dtf_local.uploads WHERE complete AND purged_at IS NULL
|
||||
AND expires_at>now() AND scan_state IN ('pending','error') AND scan_after<=now()
|
||||
ORDER BY created_at FOR UPDATE SKIP LOCKED LIMIT 1''').fetchone()
|
||||
if not row:return False
|
||||
busy_since=time.monotonic()
|
||||
try:
|
||||
_scan_row(c, storage, scanner, row)
|
||||
finally:
|
||||
busy_since=None
|
||||
return True
|
||||
|
||||
def _scan_row(c, storage, scanner, row):
|
||||
name=row['name']
|
||||
try:
|
||||
# Every later decision reads the stored name (the manual charge,
|
||||
@@ -162,7 +181,6 @@ def scan_one(storage, scanner=None):
|
||||
expires_at=CASE WHEN %s IN ('rejected','error') THEN LEAST(expires_at,now()+interval '3 days') ELSE expires_at END
|
||||
WHERE id=%s""",(name,state,reason,checked,checked,pdf_dpi_value,state,row['id']))
|
||||
audit('artwork_scan', upload=str(row['id']), result=state, c=c)
|
||||
return True
|
||||
|
||||
def scan_loop(storage):
|
||||
while True:
|
||||
|
||||
18
app/tiny.py
18
app/tiny.py
@@ -195,6 +195,11 @@ class TinyRateLimit(TinyError):
|
||||
transient = True
|
||||
|
||||
|
||||
class TinyUnavailable(TinyError):
|
||||
"""Tiny answered with a server error (5xx): down for a moment, so what
|
||||
depends on the answer waits for the outbox's next try."""
|
||||
|
||||
|
||||
class TinyNotConnected(TinyError):
|
||||
"""No authorised connection yet: an operator must click "Conectar Tiny"."""
|
||||
|
||||
@@ -822,6 +827,8 @@ class TinyOrders:
|
||||
response = self.http.request(method, path, headers=headers, **kwargs)
|
||||
if response.status_code == 429:
|
||||
raise TinyRateLimit('Tiny rate limit reached; the outbox will retry')
|
||||
if response.status_code >= 500:
|
||||
raise TinyUnavailable(f'{method} {path}: {response.status_code} {response.text[:300]}')
|
||||
if response.status_code >= 400:
|
||||
raise TinyError(f'{method} {path}: {response.status_code} {response.text[:300]}')
|
||||
return response.json() if response.content else {}
|
||||
@@ -870,14 +877,17 @@ class TinyOrders:
|
||||
|
||||
def contact_seller(self, contact_id):
|
||||
"""The seller (vendedor) in a contact's registration, or None. A
|
||||
failed reading leaves the order without one: it must still go."""
|
||||
reading Tiny refuses leaves the order without one: it must still go.
|
||||
The seller cannot be set after the order is made, so a busy or
|
||||
unavailable Tiny (429, 5xx, no answer) tries the whole delivery again."""
|
||||
try:
|
||||
seller = (self.request('GET', f'/contatos/{contact_id}').get('vendedor') or {}).get('id')
|
||||
except TinyRateLimit:
|
||||
# Busy for a moment: the whole delivery is tried again, the seller with it.
|
||||
except (TinyRateLimit, TinyUnavailable):
|
||||
raise
|
||||
except TinyError as exc:
|
||||
logging.warning('Tiny: could not read the seller of contact %s: %s', contact_id, exc)
|
||||
# The order goes without its seller, for good: Sentry hears of it.
|
||||
logging.error('Tiny: could not read the seller of contact %s; the order goes without one: %s',
|
||||
contact_id, exc)
|
||||
return None
|
||||
return int(seller) if str(seller or '').isdigit() and int(seller) > 0 else None
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ abandonment rate.
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from . import mail, payments
|
||||
from .payments import QUOTE_VALID_HOURS
|
||||
from .payments import CARD_REVIEW_HOURS, QUOTE_VALID_HOURS
|
||||
|
||||
# An intent in one of these no longer waits for money: approved (it became an
|
||||
# order), rejected, cancelled, expired or refunded (app/payments.py).
|
||||
@@ -34,11 +34,12 @@ def expire(c, origin):
|
||||
AND i.id = (SELECT i2.id FROM dtf_local.payment_intents i2
|
||||
WHERE i2.quote_id=q.id ORDER BY i2.created_at DESC LIMIT 1)
|
||||
AND i.status <> ALL(%s)
|
||||
AND i.created_at > now() - make_interval(hours => %s)
|
||||
-- a card in review may be approved days later (payments.CARD_REVIEW_HOURS)
|
||||
AND i.created_at > now() - make_interval(hours => CASE WHEN i.method='card' THEN %s ELSE %s END)
|
||||
AND (i.response->>'expires_at' IS NULL
|
||||
OR (i.response->>'expires_at')::timestamptz > now()))
|
||||
ORDER BY q.approved_at LIMIT 50 FOR UPDATE OF q SKIP LOCKED''',
|
||||
(QUOTE_VALID_HOURS, list(FINAL_INTENT), QUOTE_VALID_HOURS + 1)).fetchall()
|
||||
(QUOTE_VALID_HOURS, list(FINAL_INTENT), CARD_REVIEW_HOURS, QUOTE_VALID_HOURS + 1)).fetchall()
|
||||
for row in rows:
|
||||
c.execute('UPDATE dtf_local.quotes SET expired_at=now() WHERE id=%s', (row['id'],))
|
||||
# expired_at is set first: release_files must no longer see this quote
|
||||
|
||||
@@ -8,7 +8,7 @@ from http.server import BaseHTTPRequestHandler, HTTPServer
|
||||
import psycopg
|
||||
from botocore.exceptions import ClientError
|
||||
from psycopg.types.json import Jsonb
|
||||
from . import mail, observability, unpaid
|
||||
from . import mail, observability, scanning, unpaid
|
||||
from .adapters import FakeTiny, LocalS3Storage, require_runtime
|
||||
from .core.secrets import load as load_secret_files
|
||||
from .core.db import connect
|
||||
@@ -17,12 +17,37 @@ from .scanning import ClamAV, scan_loop
|
||||
|
||||
load_secret_files()
|
||||
require_runtime()
|
||||
adapters = {'tiny': FakeTiny()}
|
||||
# Not yet confirmed against the client's account; see app/tiny.py.
|
||||
if os.environ.get('TINY_ADAPTER') == 'tiny':
|
||||
# Production without the real Tiny (TINY_ADAPTER missing from the stack):
|
||||
# the sends wait and Sentry is told, instead of the simulator marking real
|
||||
# orders delivered with made-up receipts that had to be queued again by hand.
|
||||
HELD = 'Tiny desligado em produção (TINY_ADAPTER não é tiny): o envio espera'
|
||||
|
||||
|
||||
class HeldTiny:
|
||||
def deliver(self, event_key, payload):
|
||||
raise RuntimeError(HELD)
|
||||
|
||||
|
||||
def tiny_adapter(adapter=None, environment=None):
|
||||
"""The Tiny the outbox delivers to: the real one when configured; in
|
||||
production otherwise none (HeldTiny); elsewhere the simulator."""
|
||||
adapter = os.environ.get('TINY_ADAPTER') if adapter is None else adapter
|
||||
environment = os.environ.get('APP_ENV', 'local') if environment is None else environment
|
||||
if adapter == 'tiny':
|
||||
from .tiny import TinyOrders
|
||||
from .cnpj import company
|
||||
adapters['tiny'] = TinyOrders(names=company)
|
||||
return TinyOrders(names=company)
|
||||
return HeldTiny() if environment == 'production' else FakeTiny()
|
||||
|
||||
|
||||
adapters = {'tiny': tiny_adapter()}
|
||||
|
||||
|
||||
def release_held(c):
|
||||
"""With the real Tiny back, the sends held meanwhile go at once instead
|
||||
of after their back-off."""
|
||||
return c.execute('''UPDATE dtf_local.outbox SET available_at=now() WHERE provider='tiny'
|
||||
AND delivered_at IS NULL AND last_error=%s''', (HELD,)).rowcount
|
||||
last_tick = 0.0
|
||||
last_cleanup = 0.0
|
||||
last_reconcile = 0.0
|
||||
@@ -180,13 +205,25 @@ def loop():
|
||||
delay = 1
|
||||
time.sleep(1)
|
||||
|
||||
scan_stuck_reported = False
|
||||
|
||||
class Health(BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
global scan_stuck_reported
|
||||
scanner = False
|
||||
try:
|
||||
scanner = bool(scan_thread and scan_thread.is_alive() and ClamAV().ping())
|
||||
except Exception:
|
||||
pass
|
||||
# Alive but held on one file: every upload waits behind it.
|
||||
if scanning.stuck():
|
||||
scanner = False
|
||||
if not scan_stuck_reported:
|
||||
scan_stuck_reported = True
|
||||
logging.error('The upload scan has been on one file for over %s min: every upload waits',
|
||||
scanning.SCAN_STUCK_SECONDS // 60)
|
||||
else:
|
||||
scan_stuck_reported = False
|
||||
renderer = bool(render_thread and render_thread.is_alive())
|
||||
healthy = time.monotonic()-last_tick < 15 and scanner and renderer
|
||||
self.send_response(200 if self.path == '/health' and healthy else 503)
|
||||
@@ -199,6 +236,14 @@ class Health(BaseHTTPRequestHandler):
|
||||
|
||||
if __name__ == '__main__':
|
||||
observability.init('worker')
|
||||
if isinstance(adapters['tiny'], HeldTiny):
|
||||
logging.error('Worker started in production without the real Tiny: Tiny sends are held')
|
||||
elif not isinstance(adapters['tiny'], FakeTiny):
|
||||
try:
|
||||
with connect() as c:
|
||||
release_held(c)
|
||||
except Exception:
|
||||
logging.exception('Could not release the Tiny sends held while Tiny was off')
|
||||
scan_thread = threading.Thread(target=scan_loop,args=(storage,),daemon=True)
|
||||
scan_thread.start()
|
||||
render_thread = threading.Thread(target=render_loop,args=(storage,),daemon=True)
|
||||
|
||||
@@ -41,9 +41,9 @@ SOURCE_BLOCKERS = {
|
||||
'app/runtime.py': (
|
||||
'payment = FakePayment()',
|
||||
),
|
||||
'app/worker.py': (
|
||||
"adapters = {'tiny': FakeTiny()}",
|
||||
),
|
||||
# app/worker.py's "adapters = {'tiny': FakeTiny()}" left on 2026-11-27: in
|
||||
# production the worker uses the real Tiny or holds the sends (HeldTiny),
|
||||
# never the simulator.
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -122,7 +122,6 @@ class ProductionPreflightTests(unittest.TestCase):
|
||||
def test_fake_checkout_is_explicitly_blocked(self):
|
||||
errors = source_errors()
|
||||
self.assertTrue(any('app/runtime.py remains local-only' in error for error in errors))
|
||||
self.assertTrue(any('app/worker.py remains local-only' in error for error in errors))
|
||||
|
||||
def test_secret_reuse_and_incoherent_limits_are_rejected(self):
|
||||
values = valid_config()
|
||||
|
||||
@@ -219,7 +219,7 @@ try{
|
||||
// JPG has no transparency: refused in loose artwork as in a sheet (Dropstar,
|
||||
// 2026-10-23), with the reason, before anything is read.
|
||||
await evaluate(`sel([new File(['x'],'arte.jpg',{type:'image/jpeg'})])`);
|
||||
assert.equal(await evaluate(`artes.length===0 && $('recusa').textContent.includes('JPG não dá para enviar')`),true);
|
||||
assert.equal(await evaluate(`artes.length===0 && $('recusa').textContent.includes('JPG não entra')`),true);
|
||||
// The content decides, not the name (D-13): a JPG called ".png" is refused as a JPG.
|
||||
await evaluate(`sel([new File([new Uint8Array([0xFF,0xD8,0xFF,0xE0])],'disfarce.png',{type:'image/png'})])`);
|
||||
assert.equal(await evaluate(`artes.length===0 && $('recusa').textContent.includes('disfarce.png é JPG')`),true);
|
||||
@@ -383,7 +383,7 @@ try{
|
||||
// A ready sheet now offers the same acceptance as loose art (Dropstar,
|
||||
// 2026-11-05): the dots may be part of the art; the customer can take them.
|
||||
assert.deepEqual(await evaluate(`({box:!!document.querySelector('[data-residuo]'),
|
||||
text:$('lista').textContent.includes('Li e concordo'),stopped:itemAtual===null})`),{box:true,text:true,stopped:true});
|
||||
text:$('lista').textContent.includes('Quero imprimir assim'),stopped:itemAtual===null})`),{box:true,text:true,stopped:true});
|
||||
await evaluate(`(()=>{const el=document.querySelector('[data-residuo]');el.checked=true;
|
||||
el.dispatchEvent(new Event('change',{bubbles:true}));})()`);
|
||||
await waitFor(()=>evaluate('itemAtual!==null'),'accepted residue lets the sheet through');
|
||||
|
||||
@@ -91,7 +91,7 @@ try{
|
||||
const itemCents=Math.round(1.1*(1990+extraCents));
|
||||
const total=Math.round(itemCents)/100;
|
||||
await waitFor(()=>site.eval(`Math.abs(itemAtual.total-${total})<0.005`),'manual-file price');
|
||||
assert.equal(await site.eval(`$('carrLin').textContent.includes('Arquivo aberto na mão')`),extraCents>0);
|
||||
assert.equal(await site.eval(`$('carrLin').textContent.includes('Abertura manual do arquivo')`),extraCents>0);
|
||||
await site.fill('#fNome','Cliente Teste');
|
||||
await site.fill('#fCnpj','11222333000181');
|
||||
await site.fill('#fZap','11999999999');
|
||||
|
||||
@@ -33,15 +33,16 @@ def run():
|
||||
manager = manager.operator_client
|
||||
coupon_id = None
|
||||
quote_id = None
|
||||
early_id = None
|
||||
order_id = None
|
||||
upload_id = None
|
||||
try:
|
||||
upload_id = upload_bytes(client, artwork(), name=f'LOCAL-COUPON-{tag}.png')
|
||||
sheet = {**item_spec('uvfile', '1', 0, upload_id),
|
||||
sheet = {**item_spec('uvfile', '1', 0, upload_id, aspect=2),
|
||||
'quality_status': 'warning', 'quality_acknowledged': True}
|
||||
# The sheet is the customer's own file, not one someone opens by hand.
|
||||
sheet['production']['sources'][0]['measurement'] = 'file'
|
||||
art = {**item_spec('uv', '1', 0, upload_id),
|
||||
art = {**item_spec('uv', '1', 0, upload_id, aspect=2),
|
||||
'quality_status': 'warning', 'quality_acknowledged': True}
|
||||
items = [sheet, art]
|
||||
|
||||
@@ -61,6 +62,9 @@ def run():
|
||||
assert [line['total_cents'] for line in approved['items']] == [7990, 8990], approved
|
||||
assert approved['total_cents'] == 16081, approved
|
||||
|
||||
# A second cart with the coupon, made while it still had uses.
|
||||
early_id = quote(client, items, code, mail)['id']
|
||||
|
||||
# One paid order spends a use (a fake payment, no print job).
|
||||
order_id = uuid4()
|
||||
with db.connect() as c:
|
||||
@@ -110,6 +114,10 @@ def run():
|
||||
manager.call('/operator/site/coupons/' + coupon_id, {'max_uses': 1})
|
||||
refused = quote(client, items, code, mail, expected=422)
|
||||
assert refused['detail'] == 'Este cupom já foi usado o máximo de vezes.', refused
|
||||
# The limit is spent at payment: the cart made before it ran out no
|
||||
# longer pays with its discount.
|
||||
refused = client.call('/payments/intent', {'quote_id': early_id, 'method': {'type': 'pix'}}, expected=409)
|
||||
assert 'máximo de vezes' in refused['detail'] and 'sem o cupom' in refused['detail'], refused
|
||||
manager.call('/operator/site/coupons/' + coupon_id,
|
||||
{'max_uses': None, 'max_uses_per_customer': 1})
|
||||
refused = quote(client, items, code, mail, expected=422)
|
||||
@@ -135,13 +143,16 @@ def run():
|
||||
stats = manager.call('/operator/stats?days=30')
|
||||
assert any(entry['id'] == coupon_id for entry in stats['coupons']), stats['coupons']
|
||||
print('PASS: a coupon discounts one product, refuses paused/expired/not-started/'
|
||||
'minimum/product/use states, reaches Tiny data and Números, and soft delete keeps history')
|
||||
'minimum/product/use states, also at payment, reaches Tiny data and Números, and soft delete keeps history')
|
||||
finally:
|
||||
with db.connect() as c:
|
||||
if order_id:
|
||||
c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (order_id,))
|
||||
if quote_id:
|
||||
c.execute('DELETE FROM dtf_local.quotes WHERE id=%s', (quote_id,))
|
||||
if early_id:
|
||||
c.execute('DELETE FROM dtf_local.payment_intents WHERE quote_id=%s', (early_id,))
|
||||
c.execute('DELETE FROM dtf_local.quotes WHERE id=%s', (early_id,))
|
||||
if coupon_id:
|
||||
c.execute('DELETE FROM dtf_local.coupons WHERE id=%s', (coupon_id,))
|
||||
if upload_id:
|
||||
|
||||
@@ -44,7 +44,7 @@ def run():
|
||||
assert rules['treatment_offered'] is True, rules
|
||||
|
||||
upload_id = upload_bytes(client, artwork(), name=f'LOCAL-GRADE-{tag}.png')
|
||||
item = {**item_spec('uv', '1', 50, upload_id),
|
||||
item = {**item_spec('uv', '1', 50, upload_id, aspect=2),
|
||||
'quality_status': 'warning', 'quality_acknowledged': True}
|
||||
|
||||
refused = client.call('/quotes', quote_body(item, False, mail), expected=422)
|
||||
|
||||
@@ -62,4 +62,27 @@ window.dtfObservability.apiError('/board', 503, 'O sistema está reiniciando.');
|
||||
window.dtfObservability.uiError('O sistema está reiniciando.', 'kanban');
|
||||
assert.equal(captured, null, 'a skipped restart 503 stays skipped');
|
||||
|
||||
// A refusal the server explains (a 4xx with a sentence) is no bug: on the
|
||||
// Kanban a warning, on the Site nothing; a field list or a 5xx is an error
|
||||
// (2026-11-30).
|
||||
const refused = (app, status, detail) => {
|
||||
// A fresh copy per app: a page starts Sentry once, for its own app.
|
||||
vm.runInThisContext(readFileSync('web/observability.js', 'utf8'));
|
||||
window.dtfObservability.start('https://key@o1.ingest.sentry.io/1', app);
|
||||
captured = null;
|
||||
window.dtfObservability.apiError('/orders/1/move', status, 'Puxe o pedido na mesma máquina.', detail);
|
||||
return captured;
|
||||
};
|
||||
assert.equal(refused('kanban', 409, 'Puxe o pedido na mesma máquina.').options.level, 'warning');
|
||||
assert.equal(refused('kanban', 409, 'Puxe o pedido na mesma máquina.').options.tags.recusa, 'sim');
|
||||
assert.equal(refused('site', 409, 'Cupom não encontrado.'), null, 'a refusal on the Site is not sent');
|
||||
assert.equal(refused('site', 422, [{loc: ['body', 'items'], msg: 'bad'}]).options.level, 'error');
|
||||
assert.equal(refused('site', 500, 'Internal Server Error').options.level, 'error');
|
||||
assert.equal(refused('kanban', 422, [{loc: ['body'], msg: 'bad'}]).options.level, 'error');
|
||||
// Shown in red after it, the refusal is not sent again as a page error.
|
||||
refused('site', 409, 'Cupom não encontrado.');
|
||||
captured = null;
|
||||
window.dtfObservability.uiError('Puxe o pedido na mesma máquina.', 'site');
|
||||
assert.equal(captured, null, 'a refusal shown in red is not sent as an error');
|
||||
|
||||
console.log('observability web checks passed');
|
||||
|
||||
@@ -109,6 +109,10 @@ def run():
|
||||
client.call(f'/operator/orders/{paid_order}/delete', {}, operator=True)
|
||||
with db.connect() as c:
|
||||
assert not c.execute('SELECT 1 FROM dtf_local.orders WHERE id=%s', (paid_order,)).fetchone()
|
||||
# Its cancellation still goes to Tiny: deleted at once, or with Tiny
|
||||
# down, it must not be lost with the order.
|
||||
assert c.execute('SELECT 1 FROM dtf_local.outbox WHERE event_key=%s',
|
||||
(f'{paid_order}:cancelled:tiny',)).fetchone(), 'the Tiny cancellation was lost'
|
||||
# Deleted: no state at all, so the folder removes its files too.
|
||||
assert client.call('/operator/queue/folder', {'held': [str(paid_order)]}, operator=True)['states'] == {}
|
||||
with db.connect() as c:
|
||||
@@ -156,7 +160,7 @@ def run():
|
||||
c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (order,))
|
||||
c.execute('DELETE FROM dtf_local.quotes WHERE id=ANY(%s)', ([gone_quote, other_quote, test2_quote],))
|
||||
c.execute('DELETE FROM dtf_local.uploads WHERE id=ANY(%s)', (list(files.values()),))
|
||||
print('PASS: discard hides and blocks a quote; test orders delete; paid orders cancel, then delete '
|
||||
print('PASS: discard hides and blocks a quote; test orders delete; paid orders cancel, then delete, keeping the Tiny cancellation, '
|
||||
'and free their files')
|
||||
finally:
|
||||
with db.connect() as c:
|
||||
|
||||
@@ -121,7 +121,12 @@ def run():
|
||||
later = deliver({**payload, 'event_id': 'retry-' + uuid4().hex})
|
||||
assert 'already existed' in later.get('outcome', ''), later
|
||||
assert customer.call('/quotes/' + quote_id)['order']['id'] == order['id'], 'a second order appeared'
|
||||
print('PASS: one order from a repeated and re-sent approval')
|
||||
# Another payment of the same cart (a PIX and a card): the customer paid
|
||||
# twice, and it is listed for a refund, not taken for a re-sent approval.
|
||||
second = deliver({**payload, 'event_id': 'second-' + uuid4().hex, 'payment_id': 'second-' + uuid4().hex[:8]})
|
||||
assert second.get('outcome', '').startswith('attention: second payment'), second
|
||||
assert customer.call('/quotes/' + quote_id)['order']['id'] == order['id'], 'a second order appeared'
|
||||
print('PASS: one order from a repeated and re-sent approval; a second payment is listed for a refund')
|
||||
|
||||
assert customer.call('/orders/dev-paid', {'quote_id': quote_id})['id'] == order['id']
|
||||
other = Client()
|
||||
|
||||
@@ -155,6 +155,9 @@ def run():
|
||||
mine = [f for f in early['files'] if f['order'] == oid]
|
||||
assert [(f['upload_id'], f['state']) for f in mine] == [(str(row['upload_id']), 'rec')], early['files']
|
||||
assert mine[0]['name'].startswith('DTF-%d-item-1' % order['number']) and early['states'] == {oid: 'rec'}
|
||||
# The folders download a whole list one file after another: an hour's link,
|
||||
# not the 5 minutes that ran out before the last ones began.
|
||||
assert 'X-Amz-Expires=3600' in mine[0]['url'], mine[0]['url']
|
||||
late = client.call('/operator/queue/folder', {'early': False, 'held': []}, operator=True)
|
||||
assert not [f for f in late['files'] if f['order'] == oid] and late['states'] == {}
|
||||
client.call('/operator/queue/folder', {'early': True, 'held': []}, expected=401)
|
||||
@@ -251,6 +254,13 @@ def run():
|
||||
# No class measured or chosen: the part waits for one.
|
||||
assert not [p for p in client.call('/operator/queue/hot', {}, operator=True)['write'] if p['order'] == oid]
|
||||
client.call('/operator/orders/' + oid + '/contraction', {'item_index': 0, 'value': 'C2'}, operator=True)
|
||||
# Renamed, the machine keeps its folder, the path FlexiPRINT watches;
|
||||
# no other machine may then take that folder's name.
|
||||
client.call('/operator/machines/' + machine, {'name': f'Hot {tag} renomeada', 'products': ['textil']},
|
||||
operator=True)
|
||||
listed = next(m for m in client.call('/operator/machines', operator=True)['machines'] if m['id'] == machine)
|
||||
assert listed['name'] == f'Hot {tag} renomeada' and listed['folder'] == f'Hot {tag}', listed
|
||||
client.call('/operator/machines', {'name': f'Hot {tag}', 'products': ['textil']}, operator=True, expected=409)
|
||||
hot = client.call('/operator/queue/hot', {}, operator=True)
|
||||
due = [p for p in hot['write'] if p['order'] == oid]
|
||||
assert hot['folder'] == '3. Imprimindo' and [(p['folder'], p['name']) for p in due] == \
|
||||
@@ -269,7 +279,8 @@ def run():
|
||||
assert board['hot'] == {'parts': 1, 'taken': 1, 'waiting': 0}, board['hot']
|
||||
# Which items go again is chosen before Imprimindo, not while printing (#105).
|
||||
client.call('/operator/orders/' + oid + '/print-items', {'items': [0]}, operator=True, expected=409)
|
||||
print('PASS: the printing file goes once into its machine\'s hot folder for its class')
|
||||
print('PASS: the printing file goes once into its machine\'s hot folder for its class, '
|
||||
'and a renamed machine keeps its folder')
|
||||
finally:
|
||||
client.call('/operator/machines/' + machine, {'name': f'Hot {tag}', 'products': ['textil'], 'active': False},
|
||||
operator=True)
|
||||
@@ -398,7 +409,13 @@ def run():
|
||||
final = c.execute('''SELECT note,created_by FROM dtf_local.order_files
|
||||
WHERE order_id=%s AND kind='final' AND active''', (parent['id'],)).fetchone()
|
||||
assert final['created_by'] == 'Prumo' and 'prova' in final['note'].lower(), final
|
||||
print('PASS: Prova OK turns Prumo\'s full file into the parent final and queues it')
|
||||
# Entering the queue by Prova OK is Tiny's "Preparando envio", as a card
|
||||
# moved by hand (orders with a proof skipped it).
|
||||
with db.connect() as c:
|
||||
started = c.execute("SELECT payload FROM dtf_local.outbox WHERE event_key=%s",
|
||||
(f"{parent['id']}:production_started:tiny",)).fetchone()
|
||||
assert started and started['payload']['event'] == 'production_started', started
|
||||
print('PASS: Prova OK turns Prumo\'s full file into the parent final, queues it and tells Tiny')
|
||||
|
||||
# Prova OK while the parent's file is still being generated (#81, 91,5 m,
|
||||
# 2026-11-24): the parent waits in Arte recebida and enters the queue on
|
||||
@@ -433,7 +450,40 @@ def run():
|
||||
moved = c.execute('''SELECT operator,reason FROM dtf_local.movements
|
||||
WHERE order_id=%s AND to_state='tra' ORDER BY id DESC LIMIT 1''', (parent['id'],)).fetchone()
|
||||
assert (moved['operator'], moved['reason']) == ('Prumo', 'Prova OK'), moved
|
||||
print('PASS: a file finished after Prova OK becomes the final and queues the order')
|
||||
with db.connect() as c:
|
||||
assert c.execute("SELECT 1 FROM dtf_local.outbox WHERE event_key=%s",
|
||||
(f"{parent['id']}:production_started:tiny",)).fetchone()
|
||||
print('PASS: a file finished after Prova OK becomes the final, queues the order and tells Tiny')
|
||||
|
||||
# Cancelled, an order takes its proof card not yet answered with it: left
|
||||
# on the board, the card could still be pulled and printed.
|
||||
readable = upload_bytes(client, artwork(), name='LOCAL-PROOF-CANCEL.png')
|
||||
parent = paid_order(client, loose_item(readable, copies=1))
|
||||
with db.connect() as c:
|
||||
c.execute("UPDATE dtf_local.orders SET snapshot=jsonb_set(snapshot,'{proof}','true') WHERE id=%s",
|
||||
(parent['id'],))
|
||||
card = client.call('/operator/orders/' + parent['id'] + '/proof-card', {}, operator=True)
|
||||
client.call('/operator/orders/' + parent['id'] + '/cancel', {'note': 'cliente desistiu'}, operator=True)
|
||||
with db.connect() as c:
|
||||
gone = c.execute('SELECT cancelled_at, cancel_reason FROM dtf_local.orders WHERE id=%s', (card['id'],)).fetchone()
|
||||
assert gone['cancelled_at'] and 'cliente desistiu' in gone['cancel_reason'], gone
|
||||
print('PASS: cancelling an order cancels its open proof card')
|
||||
|
||||
# A film in parts is approved whole: only some of its parts are refused,
|
||||
# or the others never reach the machine (#114, #128, #130).
|
||||
whole = upload_bytes(client, artwork(), name='LOCAL-PARTS.png')
|
||||
film = paid_order(client, loose_item(whole, copies=1))
|
||||
_, film_row = wait_print(client, film['id'], 'ready')
|
||||
second = upload_bytes(client, artwork(), name='LOCAL-PARTS-P2.png')
|
||||
with db.connect() as c:
|
||||
c.execute('INSERT INTO dtf_local.print_parts(order_id,item_index,part,upload_id) VALUES(%s,0,2,%s)',
|
||||
(film['id'], second))
|
||||
refused = client.call('/operator/orders/' + film['id'] + '/final-files',
|
||||
{'version': version_of(film['id']), 'note': 'só a primeira',
|
||||
'files': [{'item_index': 0, 'upload_id': str(film_row['upload_id'])}]},
|
||||
operator=True, expected=422)
|
||||
assert 'faltam p2' in refused['detail'], refused
|
||||
print('PASS: a film in parts is approved with all its parts or not at all')
|
||||
|
||||
# Reprinting some items (Marcus, 2026-11-26, #105): an order the machine
|
||||
# already printed, back in the queue after one item's final changed, sends
|
||||
@@ -472,30 +522,69 @@ def run():
|
||||
{'item_index': 1, 'upload_id': corrected}]}, operator=True)['version']
|
||||
board_order = next(o for o in client.call('/operator/board', operator=True)['orders'] if o['id'] == rid)
|
||||
assert board_order['printed_before'] and board_order['print_suggested'] == [1], board_order.get('print_suggested')
|
||||
client.call('/operator/orders/' + rid + '/move', {'state': 'tra', 'version': v}, operator=True)
|
||||
from app import hotfolder
|
||||
v = client.call('/operator/orders/' + rid + '/move', {'state': 'tra', 'version': v}, operator=True)['version']
|
||||
|
||||
def print_items():
|
||||
with db.connect() as c:
|
||||
return c.execute('SELECT print_items FROM dtf_local.orders WHERE id=%s', (rid,)).fetchone()['print_items']
|
||||
|
||||
def version():
|
||||
return next(o for o in client.call('/operator/board', operator=True)['orders'] if o['id'] == rid)['version']
|
||||
|
||||
assert print_items() == [1], print_items()
|
||||
# Every item ticked by hand in Arte recebida is a choice too: entering the
|
||||
# queue keeps it, the suggestion does not take its place.
|
||||
client.call('/operator/orders/' + rid + '/move', {'state': 'rec', 'version': v, 'reason': 'teste'}, operator=True)
|
||||
assert client.call('/operator/orders/' + rid + '/print-items', {'items': [0, 1]}, operator=True)['print_items'] == [0, 1]
|
||||
client.call('/operator/orders/' + rid + '/move', {'state': 'tra', 'version': version()}, operator=True)
|
||||
assert print_items() == [0, 1], print_items()
|
||||
# Back to only the corrected item, then pulled onto a machine for real.
|
||||
assert client.call('/operator/orders/' + rid + '/print-items', {'items': [1]}, operator=True)['print_items'] == [1]
|
||||
machine = client.call('/operator/machines', {'name': f'Reprint {uuid4().hex[:6]}', 'products': ['textil']},
|
||||
operator=True)['id']
|
||||
v = client.call('/operator/orders/' + rid + '/move', {'state': 'imp', 'version': version(), 'machine_id': machine},
|
||||
operator=True)['version']
|
||||
with db.connect() as c:
|
||||
assert c.execute('SELECT print_items FROM dtf_local.orders WHERE id=%s', (rid,)).fetchone()['print_items'] == [1]
|
||||
hotfolder.start(c, rid)
|
||||
queued = c.execute('SELECT item_index,upload_id FROM dtf_local.hot_parts WHERE order_id=%s AND round=2',
|
||||
(rid,)).fetchall()
|
||||
assert [(q['item_index'], str(q['upload_id'])) for q in queued] == [(1, corrected)], queued
|
||||
c.execute("UPDATE dtf_local.hot_parts SET state='consumed' WHERE order_id=%s AND round=2", (rid,))
|
||||
c.execute("UPDATE dtf_local.orders SET state='imp' WHERE id=%s", (rid,))
|
||||
v = c.execute('SELECT version FROM dtf_local.orders WHERE id=%s', (rid,)).fetchone()['version']
|
||||
client.call('/operator/orders/' + rid + '/move', {'state': 'rev', 'version': v}, operator=True)
|
||||
# Sent to Revisão by mistake before Flexi took the file, and undone: the
|
||||
# file goes back to the folder, alone, and the choice is the same.
|
||||
v = client.call('/operator/orders/' + rid + '/move', {'state': 'rev', 'version': v}, operator=True)['version']
|
||||
assert print_items() is None
|
||||
v = client.call('/operator/orders/' + rid + '/move', {'state': 'imp', 'version': v, 'reason': 'engano'},
|
||||
operator=True)['version']
|
||||
assert print_items() == [1], print_items()
|
||||
with db.connect() as c:
|
||||
moved = c.execute('''SELECT items FROM dtf_local.movements WHERE order_id=%s AND to_state='rev'
|
||||
ORDER BY id DESC LIMIT 1''', (rid,)).fetchone()
|
||||
left = c.execute('SELECT print_items FROM dtf_local.orders WHERE id=%s', (rid,)).fetchone()['print_items']
|
||||
assert moved['items'] == [1] and left is None, (moved, left)
|
||||
# Chosen by hand: every item means all, as on a first print.
|
||||
again = c.execute('SELECT item_index,upload_id,state FROM dtf_local.hot_parts WHERE order_id=%s AND round=3',
|
||||
(rid,)).fetchall()
|
||||
assert [(r['item_index'], str(r['upload_id']), r['state']) for r in again] == [(1, corrected, 'queued')], again
|
||||
c.execute("UPDATE dtf_local.hot_parts SET state='consumed' WHERE order_id=%s AND round=3", (rid,))
|
||||
# Flexi took it: undoing a later pass to Revisão writes nothing again.
|
||||
v = client.call('/operator/orders/' + rid + '/move', {'state': 'rev', 'version': v}, operator=True)['version']
|
||||
v = client.call('/operator/orders/' + rid + '/move', {'state': 'imp', 'version': v, 'reason': 'engano'},
|
||||
operator=True)['version']
|
||||
with db.connect() as c:
|
||||
assert not c.execute('SELECT 1 FROM dtf_local.hot_parts WHERE order_id=%s AND round>3', (rid,)).fetchone()
|
||||
client.call('/operator/orders/' + rid + '/move', {'state': 'rev', 'version': v}, operator=True)
|
||||
from app import machine_log
|
||||
with db.connect() as c:
|
||||
moved = c.execute("SELECT items FROM dtf_local.movements WHERE order_id=%s AND to_state='rev' "
|
||||
"ORDER BY id DESC LIMIT 1", (rid,)).fetchone()
|
||||
item = c.execute('SELECT snapshot FROM dtf_local.orders WHERE id=%s', (rid,)).fetchone()['snapshot']['items'][1]
|
||||
metres = machine_log.printed_since(c, machine, None)
|
||||
assert moved['items'] == [1] and print_items() is None, moved
|
||||
# Three passes to Revisão, two of them undone: item 2's film, once.
|
||||
expected = Decimal(str(item['metres'] if item.get('metres') is not None else item.get('billed_metres') or 0))
|
||||
assert metres == expected, (metres, expected)
|
||||
# Chosen by hand: every item, or some; never an item the order lacks.
|
||||
with db.connect() as c:
|
||||
c.execute("UPDATE dtf_local.orders SET state='rec' WHERE id=%s", (rid,))
|
||||
assert client.call('/operator/orders/' + rid + '/print-items', {'items': [0, 1]}, operator=True)['print_items'] is None
|
||||
assert client.call('/operator/orders/' + rid + '/print-items', {'items': [1, 0, 1]}, operator=True)['print_items'] == [0, 1]
|
||||
assert client.call('/operator/orders/' + rid + '/print-items', {'items': [0]}, operator=True)['print_items'] == [0]
|
||||
client.call('/operator/orders/' + rid + '/print-items', {'items': [5]}, operator=True, expected=422)
|
||||
print('PASS: a reprint sends only the item whose final changed, and the choice ends with the print')
|
||||
print('PASS: a reprint sends only the items chosen, keeps an all-items choice, and an undone pass to Revisão '
|
||||
'neither writes again what Flexi took nor counts the film twice')
|
||||
|
||||
# A CDR cannot be decoded by the worker. The designer prepares the full
|
||||
# parent PNG, then the worker automatically cuts the child's proof from it.
|
||||
|
||||
@@ -27,6 +27,7 @@ def run():
|
||||
quote, payment_id = uuid4(), str(900_000_000 + uuid4().int % 99_999_999)
|
||||
approved = {'customer': {'mail': 'reconcile@example.test'}, 'items': [], 'total_cents': 1490}
|
||||
order_id = None
|
||||
extra = []
|
||||
try:
|
||||
with db.connect() as c:
|
||||
c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved,approved_at)
|
||||
@@ -55,7 +56,36 @@ def run():
|
||||
asked = paid.asked
|
||||
assert payments.reconcile(db.connect, paid, quote_id=quote) == [] and paid.asked == asked
|
||||
print('PASS: an approved payment is found by asking the provider; a short one is refused; each applies once')
|
||||
|
||||
# Approved after the quote's 24 h: a payment started in time (a PIX paid
|
||||
# in its last minutes, a card approved after review) is the order; one
|
||||
# started after the deadline is refused.
|
||||
for started, expected in (("now()-interval '3 hours'", 'order '), ("now()-interval '1 hour'", 'refused: quote expired')):
|
||||
late, late_payment = uuid4(), str(800_000_000 + uuid4().int % 99_999_999)
|
||||
extra.append((late, late_payment))
|
||||
with db.connect() as c:
|
||||
c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved,approved_at)
|
||||
VALUES(%s,%s,%s,'reconcile-fixture',%s,%s,now()-interval '26 hours')''',
|
||||
(late, uuid4(), uuid4(), Jsonb({'customer': approved['customer'], 'items': []}), Jsonb(approved)))
|
||||
c.execute(f'''INSERT INTO dtf_local.payment_intents(id,quote_id,provider,provider_payment_id,method,status,
|
||||
amount_cents,response,created_at) VALUES(%s,%s,'mercadopago',%s,'card','pending',1490,'{{}}',{started})''',
|
||||
(uuid4(), late, late_payment))
|
||||
provider = Provider({'id': late_payment, 'status': 'approved', 'currency_id': 'BRL',
|
||||
'transaction_amount': 14.9, 'external_reference': str(late)})
|
||||
outcomes = payments.reconcile(db.connect, provider, quote_id=late)
|
||||
assert len(outcomes) == 1 and outcomes[0].startswith(expected), (started, outcomes)
|
||||
print('PASS: a payment started within the 24 h is the order whenever approved; one started later is refused')
|
||||
finally:
|
||||
for late, late_payment in extra:
|
||||
with db.connect() as c:
|
||||
for row in c.execute('SELECT id FROM dtf_local.orders WHERE quote_id=%s', (late,)).fetchall():
|
||||
c.execute("DELETE FROM dtf_local.outbox WHERE event_key LIKE %s", (f"{row['id']}:%",))
|
||||
c.execute('DELETE FROM dtf_local.print_files WHERE order_id=%s', (row['id'],))
|
||||
c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (row['id'],))
|
||||
c.execute("DELETE FROM dtf_local.payment_events WHERE provider='mercadopago' AND event_id LIKE %s",
|
||||
(f'{late_payment}:%',))
|
||||
c.execute('DELETE FROM dtf_local.payment_intents WHERE quote_id=%s', (late,))
|
||||
c.execute('DELETE FROM dtf_local.quotes WHERE id=%s', (late,))
|
||||
with db.connect() as c:
|
||||
if order_id:
|
||||
c.execute("DELETE FROM dtf_local.outbox WHERE event_key LIKE %s", (f'{order_id}:%',))
|
||||
|
||||
@@ -40,12 +40,13 @@ def quote(client, item, mail, expected=200):
|
||||
|
||||
|
||||
def arts_item(upload_id, arts):
|
||||
"""One loose-art item with `arts` sources of 10 x 10 cm, one metre long."""
|
||||
sources = [{'upload_id': upload_id, 'kind': 'artwork', 'width_cm': 10, 'length_cm': 10,
|
||||
"""One loose-art item with `arts` sources of 10 x 5 cm (artwork() is 2:1),
|
||||
one every 10 cm."""
|
||||
sources = [{'upload_id': upload_id, 'kind': 'artwork', 'width_cm': 10, 'length_cm': 5,
|
||||
'copies': 1, 'rotation_degrees': 0, 'mirrored': False,
|
||||
'measurement': 'customer'} for _ in range(arts)]
|
||||
placements = [{'source_index': index, 'copy_index': 0, 'x_cm': 0, 'y_cm': index * 10,
|
||||
'width_cm': 10, 'length_cm': 10, 'rotation_degrees': 0, 'mirrored': False}
|
||||
'width_cm': 10, 'length_cm': 5, 'rotation_degrees': 0, 'mirrored': False}
|
||||
for index in range(arts)]
|
||||
return {'mode': 'avulsa', 'metres': '1', 'grade': 90, 'uploads': [upload_id] * arts,
|
||||
'production': {'version': 3, 'film_width_cm': 57, 'height_cm': arts * 10,
|
||||
@@ -76,7 +77,7 @@ def run():
|
||||
assert premium_entry['title'] == 'Têxtil Premium · 8 passadas', premium_entry
|
||||
assert client.call('/session')['products'][PREMIUM]['enabled'] is False
|
||||
premium_item = {**item_spec(PREMIUM, '1', 0, upload_bytes(
|
||||
client, premium_sheet(), name='LOCAL-SITE-PREMIUM.png')),
|
||||
client, premium_sheet(), name='LOCAL-SITE-PREMIUM.png'), aspect=3),
|
||||
'quality_status': 'warning', 'quality_acknowledged': True}
|
||||
refused = quote(client, premium_item, mail, expected=422)
|
||||
assert refused['detail'] == 'Este produto não está à venda agora.', refused
|
||||
@@ -188,7 +189,7 @@ def run():
|
||||
|
||||
manager.call(f'/operator/site/products/{UV}', {'enabled': True})
|
||||
uid = upload_bytes(client, artwork(), name='LOCAL-SITE-ADMIN.png')
|
||||
item = {**item_spec('uv', '1', 0, uid), 'quality_status': 'warning', 'quality_acknowledged': True}
|
||||
item = {**item_spec('uv', '1', 0, uid, aspect=2), 'quality_status': 'warning', 'quality_acknowledged': True}
|
||||
before = client.call('/session')['products'][UV]['unit_cents']
|
||||
|
||||
# Switched off: the Site sees it off and the server refuses a new quote.
|
||||
|
||||
@@ -140,11 +140,15 @@ def review_photo(client, order_id):
|
||||
wait_scan(client,uid,operator=True)
|
||||
return client.call('/operator/orders/'+order_id+'/reviews',{'upload_id':uid},operator=True)
|
||||
|
||||
def item_spec(mode, metres, grade, uid):
|
||||
def item_spec(mode, metres, grade, uid, aspect=None):
|
||||
"""One file across the film, `metres` long. `aspect` (width / length) for
|
||||
a real image: the piece then keeps the file's proportions, as the server
|
||||
checks, inside the same billed length."""
|
||||
film_width=27 if mode in ('uvfile','uv') else 57
|
||||
length_cm=float(metres)*100
|
||||
height_cm=float(metres)*100
|
||||
length_cm=round(film_width/aspect,4) if aspect else height_cm
|
||||
return {'mode':mode,'metres':str(metres),'grade':grade,'uploads':[uid],
|
||||
'production':{'version':2,'film_width_cm':film_width,'height_cm':length_cm,
|
||||
'production':{'version':2,'film_width_cm':film_width,'height_cm':height_cm,
|
||||
'sources':[{'upload_id':uid,
|
||||
'kind':'sheet' if mode in ('file','uvfile','premium') else 'artwork',
|
||||
'width_cm':film_width,'length_cm':length_cm,'copies':1,
|
||||
@@ -249,10 +253,11 @@ def run():
|
||||
# A cart the Site priced is approved at once and can be paid straight away,
|
||||
# at the server's own prices; no operator can then change it.
|
||||
# The server works the grade out from the file: this PNG is 6059 px across
|
||||
# 57 cm, 270 DPI, which is grade 100 under the 200 DPI clean threshold.
|
||||
png=b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR'+(6059).to_bytes(4,'big')+(2000).to_bytes(4,'big')+b'\x08\x06\x00\x00\x00'+b'\x00'*4
|
||||
# 57 cm, 270 DPI, which is grade 100 under the 200 DPI clean threshold;
|
||||
# 29232 px long, the 275 cm it is laid out at (the server checks it).
|
||||
png=b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR'+(6059).to_bytes(4,'big')+(29232).to_bytes(4,'big')+b'\x08\x06\x00\x00\x00'+b'\x00'*4
|
||||
graded=upload_bytes(client,png,name='arte-270dpi.png')
|
||||
low_png=b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR'+(3366).to_bytes(4,'big')+(2000).to_bytes(4,'big')+b'\x08\x06\x00\x00\x00'+b'\x00'*4
|
||||
low_png=b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR'+(3366).to_bytes(4,'big')+(16240).to_bytes(4,'big')+b'\x08\x06\x00\x00\x00'+b'\x00'*4
|
||||
low=upload_bytes(client,low_png,name='arte-150dpi.png')
|
||||
small={**draft,'request_key':str(uuid4()),'items':[item_spec('avulsa','2.75',90,graded)]}
|
||||
auto=client.call('/quotes',small)
|
||||
@@ -283,7 +288,11 @@ def run():
|
||||
assert mixed_item['stroke_choice']=='client_c3', mixed_item
|
||||
# Loose art split by stroke (item 17): each sheet is an item, and the pair
|
||||
# has one 1 m minimum, on its first sheet.
|
||||
part=lambda metres,n,mode='avulsa':{**item_spec(mode,metres,90,graded),'split':{'group':'f0','part':n,'of':2}}
|
||||
# Each sheet's own file, 6059 px across 57 cm, as long as the sheet.
|
||||
header=lambda rows:b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR'+(6059).to_bytes(4,'big')+rows.to_bytes(4,'big')+b'\x08\x06\x00\x00\x00'+b'\x00'*4
|
||||
sheet_files={'0.3':upload_bytes(client,header(3189),name='folha-30.png'),
|
||||
'0.15':upload_bytes(client,header(1594),name='folha-15.png')}
|
||||
part=lambda metres,n,mode='avulsa':{**item_spec(mode,metres,90,sheet_files[metres]),'split':{'group':'f0','part':n,'of':2}}
|
||||
split={**small,'request_key':str(uuid4()),'items':[part('0.3',1),part('0.15',2)]}
|
||||
client.call('/quotes',{**split,'items':split['items'][:1]},expected=422)
|
||||
client.call('/quotes',{**split,'items':[part('0.3',1),part('0.15',1)]},expected=422)
|
||||
|
||||
@@ -165,8 +165,10 @@ class CartPricingCharacterizationTest(unittest.TestCase):
|
||||
split = priced('split-under-one-metre')
|
||||
self.assertEqual([(p['billed_metres'], p['total_cents']) for p in split],
|
||||
[('0.8', 1752), ('0.2', 438)])
|
||||
# A float's noise past 2,80 m is inside the 8 mm grace (Marcus,
|
||||
# 2026-11-27): billed 2,80 m at the band from 2,8 m, no longer 2,90 m.
|
||||
floating = priced('band-floating-metres')[0]
|
||||
self.assertEqual((floating['billed_metres'], floating['total_cents']), ('2.9', 24650))
|
||||
self.assertEqual((floating['billed_metres'], floating['total_cents']), ('2.8', 23800))
|
||||
|
||||
def test_ajuste_fino_is_per_art_with_the_band(self):
|
||||
# Front 1a: 1 to 9 arts at R$ 9,90, from 10 at R$ 6,90, all arts charged
|
||||
|
||||
@@ -105,7 +105,7 @@ class GradeCheckTests(unittest.TestCase):
|
||||
storage = CountingStorage({'k.pdf': b'%PDF-1.4 test', 'k.png': encoded('PNG', (100, 50))})
|
||||
files = grade_check.Files(storage)
|
||||
pdf_row = {'object_key': 'k.pdf', 'size': 15, 'name': 'a.pdf'}
|
||||
with mock.patch.object(grade_check, 'pdf_dpi', return_value=300):
|
||||
with mock.patch.object(grade_check, 'bounded_pdf_dpi', return_value=300):
|
||||
self.assertEqual(files.pdf_dpi(pdf_row), 300)
|
||||
self.assertEqual(files.pdf_dpi(pdf_row), 300)
|
||||
self.assertEqual(storage.downloads, 1)
|
||||
@@ -158,5 +158,89 @@ class GradeCheckTests(unittest.TestCase):
|
||||
self.assertIn('confirme a ressalva', issue(199.4))
|
||||
|
||||
|
||||
def nested_forms_pdf(path, fanout=10, levels=8):
|
||||
"""A 2 KB PDF whose page draws form F0 ten times, F0 draws F1 ten times,
|
||||
eight deep: 10^8 draws for a reader that walks them."""
|
||||
pdf = pikepdf.new()
|
||||
pdf.add_blank_page(page_size=(200, 200))
|
||||
forms = []
|
||||
for level in reversed(range(levels)):
|
||||
if forms:
|
||||
content = b''.join(b'q /F%d Do Q\n' % (level + 1) for _ in range(fanout))
|
||||
resources = pikepdf.Dictionary(XObject=pikepdf.Dictionary({'/F%d' % (level + 1): forms[0]}))
|
||||
else:
|
||||
content, resources = b'0 0 1 1 re f\n', pikepdf.Dictionary()
|
||||
form = pikepdf.Stream(pdf, content)
|
||||
form.Type, form.Subtype, form.BBox, form.Resources = (pikepdf.Name.XObject, pikepdf.Name.Form,
|
||||
[0, 0, 1, 1], resources)
|
||||
forms.insert(0, pdf.make_indirect(form))
|
||||
page = pdf.pages[0]
|
||||
page.obj.Resources = pikepdf.Dictionary(XObject=pikepdf.Dictionary({'/F0': forms[0]}))
|
||||
page.obj.Contents = pdf.make_indirect(pikepdf.Stream(pdf, b''.join(b'q /F0 Do Q\n' for _ in range(fanout))))
|
||||
pdf.save(path)
|
||||
|
||||
|
||||
class HostilePdfTests(unittest.TestCase):
|
||||
"""A tiny PDF must not hold the scanner's one thread (security review,
|
||||
2026-11-27): it held it for hours, and every upload behind it."""
|
||||
|
||||
def test_nested_forms_end_unknown_in_seconds(self):
|
||||
import time
|
||||
with tempfile.NamedTemporaryFile(suffix='.pdf') as handle:
|
||||
nested_forms_pdf(handle.name)
|
||||
start = time.monotonic()
|
||||
self.assertIsNone(grade_check.pdf_dpi(handle.name))
|
||||
self.assertLess(time.monotonic() - start, grade_check.PDF_MAX_SECONDS + 2)
|
||||
start = time.monotonic()
|
||||
self.assertIsNone(grade_check.bounded_pdf_dpi(handle.name))
|
||||
self.assertLess(time.monotonic() - start, grade_check.PDF_MAX_SECONDS + 10)
|
||||
|
||||
def test_a_heavy_vector_page_is_still_read(self):
|
||||
# Vector art has many paths and few draws: only draws are counted.
|
||||
pdf = pikepdf.new()
|
||||
pdf.add_blank_page(page_size=(200, 200))
|
||||
pdf.pages[0].obj.Contents = pdf.make_indirect(pikepdf.Stream(pdf, b'0 0 1 1 re f\n' * 200000))
|
||||
with tempfile.NamedTemporaryFile(suffix='.pdf') as handle:
|
||||
pdf.save(handle.name)
|
||||
self.assertEqual(grade_check.pdf_dpi(handle.name), grade_check.PDF_VECTOR_DPI)
|
||||
|
||||
def test_a_scan_held_on_one_file_is_reported(self):
|
||||
from app import scanning
|
||||
import time
|
||||
self.assertFalse(scanning.stuck())
|
||||
with mock.patch.object(scanning, 'busy_since', time.monotonic() - scanning.SCAN_STUCK_SECONDS - 1):
|
||||
self.assertTrue(scanning.stuck())
|
||||
with mock.patch.object(scanning, 'busy_since', time.monotonic()):
|
||||
self.assertFalse(scanning.stuck())
|
||||
|
||||
|
||||
class ProportionTests(unittest.TestCase):
|
||||
"""A file laid out at proportions it does not have is refused before
|
||||
payment, not found at print time (a 5 m sheet sent as 10 cm)."""
|
||||
|
||||
def cart(self, length, rotation=0, top=0, bottom=0, name='sheet.png'):
|
||||
source = {'upload_id': name, 'kind': 'sheet', 'width_cm': 57, 'length_cm': length,
|
||||
'rotation_degrees': rotation, 'trim_top_cm': top, 'trim_bottom_cm': bottom}
|
||||
return [{'production': {'sources': [source]}}], {name: {'name': name}}
|
||||
|
||||
def test_the_files_own_proportions_pass(self):
|
||||
files = FakeFiles({'sheet.png': encoded('PNG', (570, 1000)), 'turned.png': encoded('PNG', (1000, 570))})
|
||||
for args in ((100,), (90, 0, 4, 6)):
|
||||
items, rows = self.cart(*args)
|
||||
self.assertIsNone(grade_check.proportion_issue(files, items, rows), args)
|
||||
items, rows = self.cart(100, 90, name='turned.png')
|
||||
self.assertIsNone(grade_check.proportion_issue(files, items, rows))
|
||||
|
||||
def test_other_proportions_are_refused(self):
|
||||
files = FakeFiles({'sheet.png': encoded('PNG', (570, 50000))})
|
||||
items, rows = self.cart(10)
|
||||
self.assertIn('não são as proporções', grade_check.proportion_issue(files, items, rows))
|
||||
|
||||
def test_a_pdf_is_left_to_the_print_file(self):
|
||||
files = FakeFiles({})
|
||||
items, rows = self.cart(10, name='sheet.pdf')
|
||||
self.assertIsNone(grade_check.proportion_issue(files, items, rows))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
|
||||
@@ -16,9 +16,14 @@ class PricingTests(unittest.TestCase):
|
||||
source = Path('web/site-config.js').read_text()
|
||||
prices = source.split('const PRECO=')[1].split(';',1)[0]
|
||||
calculator = source.split('const cobrar=')[1].split(';',1)[0]
|
||||
js = f'const PRECO={prices};const MINIMO_M=1;const cobrar={calculator};'
|
||||
# Every 10 cm with 8 mm of grace (Marcus, 2026-11-27): the Site's own rounding.
|
||||
grace = source.split('const TOLERANCIA_M=')[1].split(';',1)[0]
|
||||
rounding = source.split('const arredonda10=')[1].split(';',1)[0]
|
||||
js = (f'const PRECO={prices};const MINIMO_M=1;const TOLERANCIA_M={grace};'
|
||||
f'const arredonda10={rounding};const cobrar={calculator};')
|
||||
js += '''const results=[];for(const mode of Object.keys(PRECO))
|
||||
for(const metres of [0.01,0.99,1,1.01,1.1,2.75,2.8,2.8000000000000003,19.99,60,12000]){
|
||||
for(const metres of [0.01,0.99,1,1.01,1.1,2.75,2.8,2.8000000000000003,19.99,60,12000,
|
||||
1.008,1.0081,4.452,6.001,6.008,6.0081,6.009,5.992]){
|
||||
const unit=PRECO[mode];
|
||||
results.push([mode,String(metres),cobrar(metres),Math.round(unit*100),Math.round(cobrar(metres)*unit*100)]);
|
||||
}process.stdout.write(JSON.stringify(results));'''
|
||||
@@ -32,6 +37,18 @@ class PricingTests(unittest.TestCase):
|
||||
self.assertEqual(result['unit_cents'],unit)
|
||||
self.assertEqual(result['total_cents'],total)
|
||||
|
||||
def test_every_10_cm_with_8_mm_in_the_customers_favour(self):
|
||||
# Marcus, 2026-11-27: up to 8 mm past a step stays in it, more goes on.
|
||||
from app.core.pricing import billed_length
|
||||
for metres, billed in (('6.001', '6'), ('6.008', '6'), ('6.0081', '6.1'), ('6.009', '6.1'),
|
||||
('4.452', '4.5'), ('4.42', '4.5'), ('2.75', '2.8'), ('0.005', '0.1')):
|
||||
with self.subTest(metres=metres):
|
||||
self.assertEqual(billed_length(metres), Decimal(billed))
|
||||
# Marcus's two examples: 3 copies of ~199,5 cm with 8 mm between them,
|
||||
# and 5 copies of 88,4 cm.
|
||||
self.assertEqual(price('file', '6.001', 100)['billed_metres'], '6')
|
||||
self.assertEqual(price('file', '4.452', 100)['billed_metres'], '4.5')
|
||||
|
||||
def test_one_price_per_product(self):
|
||||
# Dropstar, 2026-10-23: textile R$ 19,90 ready sheet and R$ 21,90 loose
|
||||
# art; UV R$ 79,90 and R$ 89,90. Premium R$ 39,90 (2026-11-10).
|
||||
|
||||
@@ -48,9 +48,10 @@ class RenderLimitTests(unittest.TestCase):
|
||||
return {'production': {'height_cm': height, 'placements': [
|
||||
{'y_cm': 0, 'length_cm': height, 'source_index': 0}]}}
|
||||
self.assertEqual(render_seconds(film(800)), RENDER_SECONDS)
|
||||
# A film in parts gets one part more: a cut moved to a clear band (#136).
|
||||
self.assertEqual(render_seconds(film(2359.2)), 3 * RENDER_SECONDS)
|
||||
self.assertEqual(render_seconds(film(4600)), 5 * RENDER_SECONDS)
|
||||
# Parts of 10 m (Marcus, 2026-11-18), and a film in parts gets one
|
||||
# part more: a cut moved to a clear band (#136).
|
||||
self.assertEqual(render_seconds(film(2359.2)), 4 * RENDER_SECONDS)
|
||||
self.assertEqual(render_seconds(film(4600)), 6 * RENDER_SECONDS)
|
||||
self.assertEqual(render_seconds({'mode': 'file'}), RENDER_SECONDS)
|
||||
|
||||
|
||||
|
||||
@@ -23,7 +23,7 @@ class Database:
|
||||
"""Just the reads and writes approve_parent makes."""
|
||||
|
||||
def __init__(self, parts, active):
|
||||
self.parts, self.active, self.inserted = parts, active, []
|
||||
self.parts, self.active, self.inserted, self.outbox = parts, active, [], []
|
||||
|
||||
def execute(self, sql, params=()):
|
||||
text = ' '.join(sql.split())
|
||||
@@ -37,10 +37,17 @@ class Database:
|
||||
return Rows([{'upload_id': u} for u in self.active])
|
||||
if text.startswith('INSERT INTO dtf_local.order_files'):
|
||||
self.inserted.append(params[2])
|
||||
if text.startswith('UPDATE dtf_local.orders SET state'):
|
||||
return Rows([{'version': 2}])
|
||||
if 'FROM dtf_local.outbox' in text:
|
||||
return Rows([])
|
||||
if text.startswith('INSERT INTO dtf_local.outbox'):
|
||||
self.outbox.append((params[0], params[2].obj['event']))
|
||||
return Rows([{'ok': 1}])
|
||||
|
||||
|
||||
ORDER = {'id': 'o', 'state': 'rec', 'cancelled_at': None, 'snapshot': {'items': [{'mode': 'file'}]}}
|
||||
ORDER = {'id': 'o', 'number': 131, 'state': 'rec', 'cancelled_at': None, 'payment': {'provider': 'mercadopago'},
|
||||
'snapshot': {'items': [{'mode': 'file'}]}}
|
||||
|
||||
|
||||
class ProofPartsTests(unittest.TestCase):
|
||||
@@ -54,6 +61,13 @@ class ProofPartsTests(unittest.TestCase):
|
||||
approve_parent(db, ORDER, 'Prumo')
|
||||
self.assertEqual(db.inserted, ['p2'])
|
||||
|
||||
def test_entering_the_queue_by_prova_ok_tells_tiny(self):
|
||||
# Tiny's "Preparando envio", as for a card moved by hand: orders with
|
||||
# a proof skipped it.
|
||||
db = Database(['p1'], set())
|
||||
self.assertTrue(approve_parent(db, ORDER, 'Prumo'))
|
||||
self.assertEqual(db.outbox, [('o:production_started:tiny', 'production_started')])
|
||||
|
||||
def test_a_final_someone_prepared_stays(self):
|
||||
db = Database(['p1', 'p2'], {'treated'})
|
||||
approve_parent(db, ORDER, 'Prumo')
|
||||
|
||||
@@ -7,7 +7,7 @@ import unittest
|
||||
from decimal import Decimal
|
||||
|
||||
from app.hotfolder import reprint_default
|
||||
from app.machine_stats import _film
|
||||
from app.machine_log import film_metres
|
||||
|
||||
|
||||
class ReprintTests(unittest.TestCase):
|
||||
@@ -27,8 +27,24 @@ class ReprintTests(unittest.TestCase):
|
||||
|
||||
def test_the_machine_counts_only_the_items_printed_again(self):
|
||||
snapshot = {'items': [{'billed_metres': '2.0'}, {'billed_metres': '3.5'}]}
|
||||
self.assertEqual(_film(snapshot), Decimal('5.5'))
|
||||
self.assertEqual(_film(snapshot, [1]), Decimal('3.5'))
|
||||
self.assertEqual(film_metres(snapshot), Decimal('5.5'))
|
||||
self.assertEqual(film_metres(snapshot, [1]), Decimal('3.5'))
|
||||
|
||||
|
||||
class ProofFilmTests(unittest.TestCase):
|
||||
# A proof sheet is centimetres of film, counted in metres: it once counted
|
||||
# 15 m per proof, enough for the machine's 10 m cleaning alert.
|
||||
proof = {'proof_of': 81, 'items': [{'billed_metres': '0'}, {'billed_metres': '0'}]}
|
||||
|
||||
def test_a_proof_with_colour_samples_counts_its_real_length(self):
|
||||
# Marcus, 2026-11-26: the finest stroke's 15 cm and two 5 cm samples,
|
||||
# 1 cm of clear film between them: 27 cm.
|
||||
windows = {'0': [['10', '25'], ['40', '45'], ['80', '85']]}
|
||||
self.assertEqual(film_metres(self.proof, [0], windows), Decimal('0.27'))
|
||||
|
||||
def test_a_proof_made_before_the_samples_counts_15_cm(self):
|
||||
self.assertEqual(film_metres(self.proof), Decimal('0.30'))
|
||||
self.assertEqual(film_metres(self.proof, None, {'1': [['0', '15']]}), Decimal('0.30'))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@@ -39,6 +39,36 @@ class SheetGapTests(unittest.TestCase):
|
||||
self.assertEqual(str(caught.exception), SHEET_GAP_CHANGED)
|
||||
|
||||
|
||||
def loose(xs_ys):
|
||||
upload = str(uuid4())
|
||||
placements = [{'source_index': 0, 'copy_index': i, 'x_cm': x, 'y_cm': y, 'width_cm': 20, 'length_cm': 10,
|
||||
'rotation_degrees': 0, 'mirrored': False} for i, (x, y) in enumerate(xs_ys)]
|
||||
height = max(y for _, y in xs_ys) + 10
|
||||
return {'mode': 'avulsa', 'metres': str(height / 100), 'grade': 100, 'uploads': [upload],
|
||||
'quality_status': 'ok', 'quality_acknowledged': False,
|
||||
'production': {'version': 3, 'film_width_cm': 57, 'height_cm': height,
|
||||
'sources': [{'upload_id': upload, 'kind': 'artwork', 'width_cm': 20, 'length_cm': 10,
|
||||
'copies': len(xs_ys), 'measurement': 'file'}],
|
||||
'placements': placements}}
|
||||
|
||||
|
||||
class OverlapTests(unittest.TestCase):
|
||||
"""Pieces stacked on each other bill less film than they print on: the
|
||||
server refuses them, whatever the browser sent."""
|
||||
def test_pieces_apart_or_touching_pass(self):
|
||||
Item.model_validate(loose([(0, 0), (20.5, 0), (0, 10.5), (20.5, 10.5)]))
|
||||
Item.model_validate(loose([(0, 0), (20, 0), (0, 10)]))
|
||||
|
||||
def test_pieces_on_each_other_are_refused(self):
|
||||
for layout in ([(0, 0), (0, 0)], [(0, 0), (10, 5)], [(0, 0), (19.9, 9.9)],
|
||||
[(0, 0)] * 100):
|
||||
with self.assertRaises(ValueError) as caught:
|
||||
Item.model_validate(loose(layout))
|
||||
self.assertIn('uma sobre a outra', str(caught.exception))
|
||||
with self.assertRaises(ValueError):
|
||||
sheet(gap=-5)
|
||||
|
||||
|
||||
class ClosePiecesTests(unittest.TestCase):
|
||||
"""The Site's count of pieces under 5 mm travels with the item to the
|
||||
Kanban card (Marcus, 2026-11-26, #81)."""
|
||||
|
||||
@@ -46,5 +46,44 @@ class SheetTrimTests(unittest.TestCase):
|
||||
Item.model_validate(sheet_item(top=-1))
|
||||
|
||||
|
||||
|
||||
class CutStripsAreEmptyTests(unittest.TestCase):
|
||||
"""The print file cuts the strips only when they hold no ink: on a measure
|
||||
the file does not bear out, artwork would leave the print unseen."""
|
||||
|
||||
def source(self, ink_row=None, alpha=255, fmt='PNG'):
|
||||
import os
|
||||
import tempfile
|
||||
from PIL import Image
|
||||
from app.printpng import Source
|
||||
folder = tempfile.mkdtemp()
|
||||
image = Image.new('RGBA', (60, 1200), (0, 0, 0, 0))
|
||||
image.paste((200, 30, 30, 255), (0, 300, 60, 900)) # the art, rows 300-899
|
||||
if ink_row is not None:
|
||||
image.putpixel((30, ink_row), (0, 0, 0, alpha))
|
||||
path = os.path.join(folder, 'folha.' + fmt.lower())
|
||||
image.save(path, fmt)
|
||||
return Source(path, 'folha.' + fmt.lower())
|
||||
|
||||
# 1200 rows for 120 cm: 20 cm (200 rows) cut at each end.
|
||||
spec = {'length_cm': 80, 'trim_top_cm': 20, 'trim_bottom_cm': 20}
|
||||
|
||||
def test_clear_strips_are_cut(self):
|
||||
for fmt in ('PNG', 'TIFF'):
|
||||
source = self.source(fmt=fmt)
|
||||
source.trim(self.spec)
|
||||
self.assertEqual(source.cut, (200, 200), fmt)
|
||||
# A residue the Site does not count as ink does not hold the cut either.
|
||||
self.source(ink_row=50, alpha=10, fmt=fmt).trim(self.spec)
|
||||
|
||||
def test_ink_in_a_cut_strip_goes_to_hand_preparation(self):
|
||||
from app.printfile import Unsupported
|
||||
for fmt in ('PNG', 'TIFF'):
|
||||
for row, where in ((150, 'do começo'), (1100, 'do fim')):
|
||||
with self.assertRaises(Unsupported) as caught:
|
||||
self.source(ink_row=row, fmt=fmt).trim(self.spec)
|
||||
self.assertIn(where, str(caught.exception), (fmt, row))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
|
||||
@@ -77,7 +77,7 @@ class FakeTinyCase(unittest.TestCase):
|
||||
if request.method == 'GET' and path.startswith('/contatos/'):
|
||||
wanted = int(path.rsplit('/', 1)[-1])
|
||||
if self.refuse_contact:
|
||||
return httpx.Response(429 if self.refuse_contact == 429 else 503, text='indisponível')
|
||||
return httpx.Response(self.refuse_contact, text='indisponível')
|
||||
return httpx.Response(200, json=next(c for c in self.contacts if c['id'] == wanted))
|
||||
if request.method == 'POST' and path == '/contatos':
|
||||
contact = {**json.loads(request.content), 'id': 500 + len(self.contacts)}
|
||||
@@ -267,11 +267,26 @@ class TinyTests(FakeTinyCase):
|
||||
self.tiny.deliver('k2', {**PAID, 'number': 43})
|
||||
self.assertNotIn('vendedor', self.orders[1])
|
||||
|
||||
def test_a_failed_seller_reading_does_not_hold_the_order(self):
|
||||
def test_a_refused_seller_reading_does_not_hold_the_order_and_reaches_sentry(self):
|
||||
self.contacts.append({'id': 321, 'cpfCnpj': '11.222.333/0001-81', 'vendedor': {'id': 977231477}})
|
||||
self.refuse_contact = True
|
||||
self.refuse_contact = 400
|
||||
with self.assertLogs(level='ERROR') as logged:
|
||||
self.assertEqual(self.tiny.deliver('k1', PAID)['status'], 'created')
|
||||
self.assertNotIn('vendedor', self.orders[0])
|
||||
self.assertIn('without one', logged.output[0])
|
||||
|
||||
def test_an_unavailable_tiny_retries_the_delivery_instead_of_dropping_the_seller(self):
|
||||
# The seller cannot be set after the order is made (order 151250): a
|
||||
# 5xx while reading it tries the whole delivery again.
|
||||
from app.tiny import TinyUnavailable
|
||||
self.contacts.append({'id': 321, 'cpfCnpj': '11.222.333/0001-81', 'vendedor': {'id': 977231477}})
|
||||
self.refuse_contact = 503
|
||||
with self.assertRaises(TinyUnavailable):
|
||||
self.tiny.deliver('k1', PAID)
|
||||
self.assertEqual(self.orders, [])
|
||||
self.refuse_contact = None
|
||||
self.tiny.deliver('k1', PAID)
|
||||
self.assertEqual(self.orders[0]['vendedor'], {'id': 977231477})
|
||||
|
||||
def test_a_busy_tiny_retries_the_delivery_instead_of_dropping_the_seller(self):
|
||||
from app.tiny import TinyRateLimit
|
||||
|
||||
@@ -53,5 +53,29 @@ class RefusedDeliveryTest(unittest.TestCase):
|
||||
self.assertEqual(self.tick_with(9, limit).call_count, 1)
|
||||
|
||||
|
||||
class HeldTinyTest(unittest.TestCase):
|
||||
"""Production without the real Tiny holds the sends and tells Sentry; the
|
||||
simulator marked real orders delivered with made-up receipts."""
|
||||
def test_production_without_the_real_tiny_holds(self):
|
||||
self.assertIsInstance(worker.tiny_adapter('fake', 'production'), worker.HeldTiny)
|
||||
self.assertIsInstance(worker.tiny_adapter(None, 'production'), worker.HeldTiny)
|
||||
self.assertIsInstance(worker.tiny_adapter('fake', 'local'), worker.FakeTiny)
|
||||
|
||||
def test_a_held_send_stays_undelivered_and_is_reported(self):
|
||||
job = {'id': 1, 'provider': 'tiny', 'event_key': 'o:paid:tiny', 'payload': {}, 'attempts': 0}
|
||||
conn = mock.MagicMock()
|
||||
conn.execute.return_value.fetchone.return_value = job
|
||||
connect = mock.MagicMock()
|
||||
connect.return_value.__enter__.return_value = conn
|
||||
with mock.patch.object(worker, 'connect', connect), \
|
||||
mock.patch.dict(worker.adapters, {'tiny': worker.HeldTiny()}), \
|
||||
mock.patch.object(worker.logging, 'error') as error:
|
||||
worker.tick()
|
||||
updates = [call.args[0] for call in conn.execute.call_args_list[1:]]
|
||||
self.assertTrue(updates and 'delivered_at=now()' not in updates[0] and 'last_error' in updates[0], updates)
|
||||
self.assertEqual(conn.execute.call_args_list[1].args[1][0], worker.HELD)
|
||||
self.assertEqual(error.call_count, 1)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
|
||||
@@ -58,6 +58,21 @@ def run():
|
||||
assert quote_id in {q['id'] for q in page['quotes']}
|
||||
print('PASS: a live payment attempt keeps an approved quote and its files')
|
||||
|
||||
# A card in review (Mercado Pago "em análise") tried 30 h ago is still
|
||||
# live: it may be approved days later (payments.CARD_REVIEW_HOURS).
|
||||
with db.connect() as c:
|
||||
c.execute('''UPDATE dtf_local.payment_intents SET status='expired', created_at=now()-interval '31 hours'
|
||||
WHERE quote_id=%s''', (quote_id,))
|
||||
c.execute('''INSERT INTO dtf_local.payment_intents(id,quote_id,provider,provider_payment_id,method,status,
|
||||
amount_cents,response,created_at) VALUES(%s,%s,'fake',%s,'card','pending',%s,'{}',now()-interval '30 hours')''',
|
||||
(uuid4(), quote_id, 'unpaid-card-' + uuid4().hex, approved['total_cents']))
|
||||
c.execute("UPDATE dtf_local.quotes SET approved_at=now()-interval '31 hours' WHERE id=%s", (quote_id,))
|
||||
with db.connect() as c:
|
||||
unpaid.expire(c, ORIGIN)
|
||||
assert c.execute('SELECT expired_at FROM dtf_local.quotes WHERE id=%s',
|
||||
(quote_id,)).fetchone()['expired_at'] is None
|
||||
print('PASS: a card in review keeps its quote and files past the 24 h')
|
||||
|
||||
# The attempt is final now: the quote expires, its files are freed and the
|
||||
# customer is told once.
|
||||
with db.connect() as c:
|
||||
|
||||
@@ -84,12 +84,12 @@
|
||||
// What the server charges for a file opened by hand, never the page's own text.
|
||||
const zona=document.getElementById('zManual');
|
||||
const extra=session.manual_extra_cents>0?rs(session.manual_extra_cents/100):'';
|
||||
if(zona)zona.innerHTML='Tem <b>CDR, AI, PSD ou TIFF</b>? Pode mandar também. Alguém abre na mão'+
|
||||
(extra?', e o metro custa '+extra+' a mais':'')+'.';
|
||||
if(zona)zona.innerHTML='<b>CDR, AI, PSD e TIFF</b> também entram. Abrimos o arquivo manualmente'+
|
||||
(extra?' e o metro custa '+extra+' a mais':'')+'.';
|
||||
const duvida=document.getElementById('duvidaManual');
|
||||
if(duvida)duvida.textContent='alguém abre na mão'+(extra?', sai mais devagar e o metro custa '+extra+' a mais':' e sai mais devagar');
|
||||
if(duvida)duvida.textContent='abrimos o arquivo manualmente'+(extra?', leva mais tempo e o metro custa '+extra+' a mais':' e leva mais tempo');
|
||||
const tabela=document.getElementById('tabelaManual');
|
||||
if(tabela){tabela.hidden=!extra;tabela.textContent='Arquivo em CDR, AI, PSD ou TIFF, que alguém abre na mão: + '+extra+' por metro.';}
|
||||
if(tabela){tabela.hidden=!extra;tabela.textContent='Arquivo em CDR, AI, PSD ou TIFF, aberto manualmente: + '+extra+' por metro.';}
|
||||
if(session.manual_extra_cents>0){
|
||||
TAXA_MANUAL=session.manual_extra_cents/100;
|
||||
if(typeof folhas!=='undefined'&&folhas.length&&typeof pintaFolha==='function')pintaFolha();
|
||||
@@ -406,7 +406,7 @@
|
||||
if (texto) el.append(document.createTextNode(texto));
|
||||
if (e?.fase==='enviando') {
|
||||
const nota=document.createElement('small'); nota.className='envioNota';
|
||||
nota.textContent='O tempo depende da velocidade da sua internet. Mantenha a página aberta.';
|
||||
nota.textContent='Mantenha a página aberta até o envio terminar.';
|
||||
el.append(nota);
|
||||
}
|
||||
el.classList.toggle('ok', e?.fase==='pronto');
|
||||
@@ -475,12 +475,17 @@
|
||||
if (draftId && quotedCart === cartSnapshot()) { await refresh(true); return; }
|
||||
if (draftId) clearDraft();
|
||||
if (!clienteOk() || !entrega.cotado) return;
|
||||
if (!enderecoOk()) return message('Preencha o endereço de entrega.','error');
|
||||
// Guidance: the customer fills it in (Sentry DTF-WEB-24).
|
||||
if (!enderecoOk()) return message('Preencha o endereço de entrega.','warn');
|
||||
// Guidance, not a failure: the customer still has a quality note to
|
||||
// confirm, and the page takes them to it (Sentry DTF-WEB-Y).
|
||||
if (!cartPodeEnviar()) {
|
||||
if (itensAPagar().some(semMargem)) {
|
||||
document.querySelector('.item .avisoF')?.scrollIntoView({behavior:'smooth',block:'center'});
|
||||
return message('Uma folha do carrinho foi montada antes dos 8 mm entre as cópias: remova e adicione de novo.','warn');
|
||||
}
|
||||
document.querySelector('.aceiteRes input:not(:checked)')?.closest('label')?.scrollIntoView({behavior:'smooth',block:'center'});
|
||||
return message('Revise a qualidade e confirme a ressalva de cada item antes de enviar o pedido.','warn');
|
||||
return message('Confirme a ressalva de cada item antes de seguir.','warn');
|
||||
}
|
||||
const semArquivo=faltaEnvioMensagem();
|
||||
if (semArquivo) return message(semArquivo+'.','error');
|
||||
@@ -513,7 +518,7 @@
|
||||
}
|
||||
// Layout versions the server takes: 3 since 2026-10-21, 2 for a cart saved before.
|
||||
if (![2,3].includes(item.production?.version) || item.production.sources?.length!==uploads.length)
|
||||
throw new Error('A montagem deste item precisa ser refeita antes da cotação.');
|
||||
throw new Error('Monte este item de novo antes de seguir.');
|
||||
items.push({mode:item.modo, metres:String(item.metros), grade:item.nota, uploads,
|
||||
production:{...item.production,sources:item.production.sources.map((source,index)=>({
|
||||
upload_id:uploads[index],...source}))},
|
||||
@@ -597,7 +602,7 @@
|
||||
if (quote.status==='pending_review') {
|
||||
message((await ready).environment==='local'
|
||||
? 'Arquivos enviados. No Kanban, confira a metragem e os arquivos e aprove a cotação '+draftId.slice(0,8)+'.'
|
||||
: 'Arquivos enviados. Nossa equipe está conferindo a cotação '+draftId.slice(0,8)+'; o valor final aparece aqui em seguida.');
|
||||
: 'Arquivos enviados. Nossa equipe confere a cotação '+draftId.slice(0,8)+' e o valor final aparece aqui.');
|
||||
} else if (quote.status==='approved') {
|
||||
if ((await ready).payment_provider === 'mercadopago') {
|
||||
if (naPix()) await paginaPix(quote, version);
|
||||
@@ -622,7 +627,7 @@
|
||||
});
|
||||
} else {
|
||||
message(quote.status==='discarded'
|
||||
? 'Esta cotação foi cancelada pela nossa equipe. Envie o carrinho de novo ou fale com a gente.'
|
||||
? 'Nossa equipe cancelou esta cotação. Envie o carrinho de novo ou fale conosco.'
|
||||
: 'Cotação expirada. Envie o carrinho de novo para pagar.','warn');
|
||||
button('Voltar ao carrinho',()=>{clearDraft();vaiPara(CARRINHO);});
|
||||
}
|
||||
@@ -874,10 +879,10 @@
|
||||
unmountCard();
|
||||
into.replaceChildren(node('p',result.status==='approved'
|
||||
? 'Pagamento aprovado. Confirmando seu pedido…'
|
||||
: 'Pagamento em análise pelo Mercado Pago. Esta página atualiza assim que ele for confirmado.','pagNota'));
|
||||
: 'Pagamento em análise pelo Mercado Pago. Esta página atualiza quando ele for confirmado.','pagNota'));
|
||||
waitForOrder();
|
||||
} else {
|
||||
message(result.message||'O pagamento foi recusado. Confira os dados ou use outro cartão ou pague com PIX.','error');
|
||||
message(result.message||'O pagamento foi recusado. Confira os dados, use outro cartão ou pague com PIX.','error');
|
||||
throw new Error('rejected');
|
||||
}
|
||||
}
|
||||
|
||||
104
web/index.html
104
web/index.html
@@ -3,7 +3,7 @@
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>DTF Dropstar · mande sua arte e veja a qualidade</title>
|
||||
<title>DTF Dropstar · envie sua arte e veja o preço</title>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&family=Roboto:wght@300;400;500;700&display=swap" rel="stylesheet">
|
||||
@@ -719,8 +719,8 @@ h2 em{font-style:normal;color:var(--laranja)}
|
||||
<span class="chip2 destaque">Metro a partir de <span data-preco="file">R$ 19,90</span></span>
|
||||
<span class="chip2">Franca · SP · envio em até 24 h</span>
|
||||
</div>
|
||||
<h1>A gente encaixa sua folha e você paga <em>menos metro</em></h1>
|
||||
<p>Mande a arte, confira a folha montada e veja o preço antes de pagar. Revisão de 5 pontos e reencaixe por nossa conta.</p>
|
||||
<h1>Encaixamos sua folha e você paga <em>menos metro</em></h1>
|
||||
<p>Envie a arte e confira a folha montada e o preço antes de pagar. Revisamos 5 pontos e reencaixamos sem custo.</p>
|
||||
<div class="hero2-cta">
|
||||
<a href="/#envio" class="btn-laranja">Enviar minha arte <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" aria-hidden="true"><path d="M5 12h14M13 6l6 6-6 6"/></svg></a>
|
||||
<span>Sem cadastro · preço em segundos</span>
|
||||
@@ -757,7 +757,7 @@ h2 em{font-style:normal;color:var(--laranja)}
|
||||
<section id="videos" class="videos2"><div class="w">
|
||||
<div class="videosCab">
|
||||
<div><div class="et">Vídeos</div><h2>A DTF por dentro</h2></div>
|
||||
<p>Do upload à retirada: o que acontece com a sua arte, sem letra miúda.</p>
|
||||
<p>O que acontece com a sua arte, do envio à retirada.</p>
|
||||
</div>
|
||||
<div class="videosGrid" id="videosGrid"></div>
|
||||
</div></section>
|
||||
@@ -794,7 +794,7 @@ h2 em{font-style:normal;color:var(--laranja)}
|
||||
<button class="ec a" data-modo="avulsa">
|
||||
<div class="ec-top"><span class="ec-kind">DTF TÊXTIL · 57 CM</span></div>
|
||||
<h3>Artes avulsas</h3>
|
||||
<p>Cada arte num arquivo. A gente monta a folha com o melhor encaixe. Montagem inclusa no preço.</p>
|
||||
<p>Cada arte num arquivo. Montamos a folha com o melhor encaixe. Montagem inclusa no preço.</p>
|
||||
<div class="ec-pe">
|
||||
<div class="ec-preco"><b data-preco="avulsa">R$ 21,90</b><span>por metro</span></div>
|
||||
<span class="ec-go">Enviar minhas artes</span>
|
||||
@@ -862,8 +862,8 @@ h2 em{font-style:normal;color:var(--laranja)}
|
||||
<span id="zLimite">Até 4 GB por arquivo.</span>
|
||||
<span class="bt">ou escolher no computador</span>
|
||||
<span class="zOutra"><b id="zOutra">Adicionar outra folha</b> ou arraste aqui</span>
|
||||
<span class="zManual" id="zManual">Tem <b>CDR, AI, PSD ou TIFF</b>? Pode mandar também.
|
||||
Alguém abre na mão, e o metro custa R$ 2,00 a mais.</span>
|
||||
<span class="zManual" id="zManual"><b>CDR, AI, PSD e TIFF</b> também entram. Abrimos o arquivo
|
||||
manualmente e o metro custa R$ 2,00 a mais.</span>
|
||||
</div>
|
||||
<div class="envios" id="envios" aria-live="polite"></div>
|
||||
<div class="recusa" id="recusa" style="display:none"></div>
|
||||
@@ -876,63 +876,60 @@ h2 em{font-style:normal;color:var(--laranja)}
|
||||
<details>
|
||||
<summary>Dicas para o seu arquivo</summary>
|
||||
<ul>
|
||||
<li class="s"><b>300 DPI no tamanho que vai imprimir.</b> É a resolução ideal</li>
|
||||
<li class="s"><b>O tamanho manda mais que o arquivo.</b> A mesma arte passa
|
||||
em 20 cm e não passa em 40. Reduzir um pouco costuma melhorar a resolução</li>
|
||||
<li class="s"><b>Larguras parecidas rendem mais.</b> Se as suas artes têm
|
||||
medidas próximas, cabem mais por fileira e a folha encolhe</li>
|
||||
<li class="s"><b>300 DPI no tamanho de impressão.</b> É a resolução ideal</li>
|
||||
<li class="s"><b>A resolução depende do tamanho.</b> A mesma arte passa
|
||||
em 20 cm e não passa em 40. Reduzir um pouco melhora a resolução</li>
|
||||
<li class="s"><b>Larguras parecidas rendem mais.</b> Cabem mais artes por
|
||||
fileira e a folha fica menor</li>
|
||||
</ul>
|
||||
<p class="obs2">A resolução não muda o preço do metro; ela mostra se o arquivo pode sair nítido.</p>
|
||||
<p class="obs2">A resolução não muda o preço. Ela mostra se a arte sai nítida.</p>
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>O que arrumamos sem cobrar</summary>
|
||||
<ul>
|
||||
<li class="s"><b>Artes coladas.</b> Separamos com 5 mm, sem você refazer nada</li>
|
||||
<li class="s"><b>Encaixe mal aproveitado.</b> Remanejamos e a sua folha
|
||||
encolhe — você paga menos metro do que enviou</li>
|
||||
<li class="s"><b>Peça passando da largura.</b> Remanejamos em vez de cortar</li>
|
||||
<li class="s"><b>Margem.</b> Não precisa deixar. Só respeitar a largura do filme</li>
|
||||
<li class="s"><b>Artes coladas.</b> Separamos com 5 mm</li>
|
||||
<li class="s"><b>Encaixe com sobra.</b> Reencaixamos, e você paga pela
|
||||
folha menor</li>
|
||||
<li class="s"><b>Arte passando da largura.</b> Reencaixamos em vez de cortar</li>
|
||||
<li class="s"><b>Margem.</b> Não precisa deixar, basta respeitar a largura do filme</li>
|
||||
</ul>
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Manda em PNG e sai na hora</summary>
|
||||
<summary>Formatos de arquivo</summary>
|
||||
<ul>
|
||||
<li class="s"><b>PNG</b> com fundo transparente entra direto, sem passar
|
||||
por ninguém, e não tem limite de comprimento. Só que a gente lê a resolução
|
||||
<b>do arquivo</b>: se a arte foi ampliada antes de exportar, isso não aparece
|
||||
para nós — e sai serrilhado no filme do mesmo jeito</li>
|
||||
<li class="s"><b>PDF é o que conferimos melhor.</b> Nele medimos a resolução de
|
||||
cada imagem dentro da folha, uma por uma. É onde a conferência
|
||||
de resolução fica mais precisa</li>
|
||||
<li class="a"><b>PDF grande.</b> Sem UserUnit, a página passa do limite de 508 cm
|
||||
do formato; divida a folha ou mande PNG. Envie um PDF de uma página por folha.</li>
|
||||
<li class="a"><b>TIFF, PSD, AI e CDR</b> a gente aceita, mas ninguém consegue
|
||||
conferir sozinho: <span id="duvidaManual">alguém abre na mão, sai mais devagar
|
||||
<li class="s"><b>PNG</b> com fundo transparente entra direto e não tem
|
||||
limite de comprimento. Lemos a resolução <b>do arquivo</b>: uma arte ampliada
|
||||
antes de exportar passa na conferência e sai serrilhada no filme</li>
|
||||
<li class="s"><b>PDF tem a conferência mais precisa.</b> Medimos a resolução
|
||||
de cada imagem dentro da folha</li>
|
||||
<li class="a"><b>PDF acima de 508 cm.</b> Só entra com UserUnit. Sem ele,
|
||||
divida a folha ou envie em PNG. Um PDF de uma página por folha</li>
|
||||
<li class="a"><b>TIFF, PSD, AI e CDR</b> também entram, mas o site não confere:
|
||||
<span id="duvidaManual">abrimos o arquivo manualmente, leva mais tempo
|
||||
e o metro custa R$ 2,00 a mais</span></li>
|
||||
<li class="a"><b>JPG não passa:</b> não tem fundo transparente, e o branco do
|
||||
fundo sai no filme. Exporte a folha em PNG ou PDF</li>
|
||||
<li class="a">Em <b>artes avulsas</b> só PNG com fundo transparente: a montagem
|
||||
precisa enxergar a sua arte para encaixar pela forma</li>
|
||||
<li class="a"><b>JPG não entra:</b> não tem fundo transparente, e o fundo
|
||||
sai branco no filme. Exporte em PNG ou PDF</li>
|
||||
<li class="a">Em <b>artes avulsas</b>, só PNG com fundo transparente: a montagem
|
||||
encaixa pela forma da arte</li>
|
||||
</ul>
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>O que só você resolve</summary>
|
||||
<ul>
|
||||
<li class="n"><b>Fundo branco ou colorido.</b> Precisa ser transparente de
|
||||
verdade — branco parecendo transparente sai branco no filme. Sem isso, o site
|
||||
não deixa pagar</li>
|
||||
<li class="n"><b>Pontinho de recorte.</b> A impressora enxerga qualquer
|
||||
resíduo e imprime. Não existe pequeno demais: o site mostra onde cada um está
|
||||
e pede que você apague ou aceite imprimir assim</li>
|
||||
<li class="n"><b>Fundo branco ou colorido.</b> O fundo precisa ser transparente:
|
||||
branco sai branco no filme, e o site não deixa pagar</li>
|
||||
<li class="n"><b>Pontinho de recorte.</b> Todo ponto de tinta sai impresso,
|
||||
por menor que seja. Mostramos onde estão: apague no arquivo ou aceite
|
||||
imprimir assim</li>
|
||||
<li class="n"><b>Cópias sobrepostas.</b> Duas iguais com 1 mm de diferença
|
||||
saem duplicadas</li>
|
||||
<li class="n"><b>Menos de 96 DPI.</b> Abaixo disso não imprimimos: sai
|
||||
serrilhado a ponto de não valer o filme</li>
|
||||
<li class="n"><b>Degradê de transparência</b>, comum em arte de IA. O branco
|
||||
por baixo sai irregular e sai assim mesmo</li>
|
||||
<li class="n"><b>Menos de 96 DPI.</b> Não imprimimos: sai serrilhado
|
||||
demais</li>
|
||||
<li class="n"><b>Degradê de transparência</b>, comum em arte feita por IA.
|
||||
O branco por baixo sai irregular, e imprimimos assim mesmo</li>
|
||||
</ul>
|
||||
</details>
|
||||
</aside>
|
||||
@@ -971,7 +968,7 @@ h2 em{font-style:normal;color:var(--laranja)}
|
||||
<div class="ampliaCab"><b id="mistaTit">Traços finos e áreas chapadas</b></div>
|
||||
<div class="mistaCorpo">
|
||||
<p id="mistaTxt"></p>
|
||||
<div class="mistaBot"><button type="button" class="ec-go" id="mistaSegue">Imprimir assim mesmo (C1)</button><button type="button" id="mistaSep">Quero subir em dois arquivos</button></div>
|
||||
<div class="mistaBot"><button type="button" class="ec-go" id="mistaSegue">Imprimir assim mesmo</button><button type="button" id="mistaSep">Subir em dois arquivos</button></div>
|
||||
</div>
|
||||
</dialog>
|
||||
<dialog class="ampliaDlg mistaDlg" id="linhaDlg" aria-labelledby="linhaTit">
|
||||
@@ -1125,16 +1122,15 @@ h2 em{font-style:normal;color:var(--laranja)}
|
||||
<h4>Prova antes de imprimir</h4>
|
||||
<label class="provaOp"><input type="checkbox" id="fProva">
|
||||
<span><b>Quero aprovar uma prova antes de imprimir</b>
|
||||
Imprimimos até 15 cm por classe de contração e mandamos a foto pelo WhatsApp. O resto só é impresso
|
||||
depois do seu ok, então o pedido espera a sua resposta. Até 3 provas por pedido, sem custo.</span></label>
|
||||
Imprimimos uma prova de até 30 cm e mandamos a foto pelo WhatsApp. O resto sai depois
|
||||
que você aprovar. Até 3 provas por pedido, sem custo.</span></label>
|
||||
</div>
|
||||
|
||||
<div class="cxE" id="tratamentoBox" hidden>
|
||||
<h4>Ajuste Fino</h4>
|
||||
<label class="provaOp"><input type="checkbox" id="fTratamento">
|
||||
<span><b>Ajuste Fino em todas as artes — <span id="tratamentoPreco"></span> por arte</b>
|
||||
O designer ajusta a arte para DTF, com fundo transparente e 300 DPI, e sobe o arquivo
|
||||
pelo card. O prazo do pedido aumenta em 24 h.</span></label>
|
||||
<span><b>Ajuste Fino em todas as artes, <span id="tratamentoPreco"></span> por arte</b>
|
||||
Nosso designer deixa cada arte com fundo transparente e 300 DPI. O pedido leva 24 h a mais.</span></label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1189,13 +1185,13 @@ h2 em{font-style:normal;color:var(--laranja)}
|
||||
</tbody>
|
||||
</table>
|
||||
<div class="nota2" id="tabelaFaixas" hidden></div>
|
||||
<p class="nota2" id="tabelaManual">Arquivo em CDR, AI, PSD ou TIFF, que alguém abre na mão: + R$ 2,00 por metro.</p>
|
||||
<p class="nota2" id="tabelaManual">Arquivo em CDR, AI, PSD ou TIFF, aberto manualmente: + R$ 2,00 por metro.</p>
|
||||
</div>
|
||||
<div class="info2-vant">
|
||||
<div><b class="n">57 cm</b><b>O dobro do filme padrão</b><span>Cabe o dobro de arte por metro corrido.</span></div>
|
||||
<div><b class="n">10 cm</b><b>Você paga o que usa</b><span>Folha de 2,75 m custa 2,80 m, não 3. Pedido mínimo de 1 metro.</span></div>
|
||||
<div><b class="n">Grátis</b><b>Reencaixe da folha</b><span>Sobrou espaço? Refazemos o encaixe e a conta diminui.</span></div>
|
||||
<div><b class="n">5 pontos</b><b>Revisão sem custo</b><span>Erro pego antes de imprimir. Arquivo guardado por 30 dias.</span></div>
|
||||
<div><b class="n">Grátis</b><b>Reencaixe da folha</b><span>Se sobrar espaço, reencaixamos e a folha fica menor.</span></div>
|
||||
<div><b class="n">5 pontos</b><b>Revisão sem custo</b><span>Conferimos antes de imprimir e guardamos o arquivo por 30 dias.</span></div>
|
||||
</div>
|
||||
</div></section>
|
||||
|
||||
@@ -1217,7 +1213,7 @@ h2 em{font-style:normal;color:var(--laranja)}
|
||||
<a href="https://wa.me/message/NJ76CLIOUGXLB1" target="_blank" rel="noopener">16 99428-0056</a>
|
||||
· arquivos 16 99230-2546<br>
|
||||
<a href="mailto:atendimentodropstar@gmail.com">atendimentodropstar@gmail.com</a><br>
|
||||
Mande sua arte em qualquer horário.<br>
|
||||
Envie sua arte a qualquer hora.<br>
|
||||
Retirada em Franca, de segunda a sexta, das 7h às 18h
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -30,7 +30,7 @@ const contactWho=order=>(order.contact_by||'')+' em '+when(order.contact_since);
|
||||
// The print proof (app/proof.py): asked for at checkout, or an order above 10 m.
|
||||
// The room marks "Prova OK" once it is checked; without it, no Finalizado.
|
||||
const PROOF_ABOVE_METRES=10;
|
||||
const PROOF_RULE='Até 15 cm por classe, do trecho de traço mais fino; no máximo 3 provas por pedido, sem cobrança.';
|
||||
const PROOF_RULE='Até 30 cm por classe: o trecho de traço mais fino e amostras das cores principais; no máximo 3 provas por pedido, sem cobrança.';
|
||||
const needsProof=order=>!!order.snapshot.proof||order.snapshot.items.reduce((t,i)=>t+Number(i.billed_metres),0)>PROOF_ABOVE_METRES;
|
||||
const proofPending=order=>needsProof(order)&&!order.proof_ok_at&&order.state!=='fin'&&!order.cancelled_at&&!order.proof_parent;
|
||||
// The proof card (app/proof.py): the order's own card waits outside the queue
|
||||
@@ -427,7 +427,8 @@ function cardFlags(order){
|
||||
const dots=s.items.reduce((t,i)=>t+(i.residue_accepted||0),0);
|
||||
if(live&&dots)out.push(['warn','Resíduo','O cliente aceitou imprimir com '+residueNote({residue_accepted:dots})]);
|
||||
// A reprint: only some items go to the machine again (#105).
|
||||
if(live&&order.print_items?.length)out.push(['warn','Reimpressão','Vão para a máquina só: '+order.print_items.map(i=>'item '+(i+1)).join(', ')]);
|
||||
// Every item ticked is a choice too, but no reprint of some: no flag.
|
||||
if(live&&order.print_items?.length&&order.print_items.length<s.items.length)out.push(['warn','Reimpressão','Vão para a máquina só: '+order.print_items.map(i=>'item '+(i+1)).join(', ')]);
|
||||
// A ready sheet with pieces closer than 5 mm (Marcus, 2026-11-26, #81).
|
||||
const close=s.items.reduce((t,i)=>t+(i.close_pieces||0),0);
|
||||
if(live&&close)out.push(['warn','Peças coladas',closeNote(close)]);
|
||||
|
||||
@@ -103,7 +103,7 @@ function renderIssues(){
|
||||
if(key==='open')b.append(node('span',String(board.payment_issues_total||0),'n'));
|
||||
b.onclick=()=>{issueState=key;issuePage=1;loadIssues().catch(e=>say(e.message,true));};seg.append(b);
|
||||
}
|
||||
const tools=node('div',undefined,'pagetools');tools.append(seg,node('span','Pagamentos que o sistema não conseguiu ligar a um pedido sozinho.','lbl'));
|
||||
const tools=node('div',undefined,'pagetools');tools.append(seg,node('span','Pagamentos que não se ligaram a um pedido.','lbl'));
|
||||
if(!issueRows.length){
|
||||
$('payments').replaceChildren(tools,emptyState(IC.check,issueState==='resolved'?'Nenhum pagamento resolvido':'Nenhum pagamento pendente',
|
||||
issueState==='open'?'Quando um pagamento precisar de alguém, ele aparece aqui.':''));
|
||||
@@ -343,7 +343,7 @@ function renderIntegrations(){
|
||||
function mailRow(m){
|
||||
const name='E-mail';
|
||||
if(m.adapter!=='smtp'&&m.adapter!=='log')return integRow({name,state:'Não configurado',tone:'off',
|
||||
summary:'Sem recuperação de senha por e-mail: o cliente é orientado a chamar no WhatsApp.'});
|
||||
summary:'Sem recuperação de senha por e-mail: o cliente chama no WhatsApp.'});
|
||||
const local=m.adapter==='log';
|
||||
return integRow({name,state:m.error?'Verificar':local?'Só registro':'Ativo',tone:m.error?'warn':local?'off':'ok',
|
||||
summary:m.error?'Falhou o envio para '+m.error.to+': '+m.error.error:'E-mails dos clientes: confirmação de pedido, recuperação de senha e códigos de confirmação.',
|
||||
|
||||
@@ -154,7 +154,8 @@ function montarQuoteFigures(lines){
|
||||
});
|
||||
const catalog=MONTAR.catalog?.avulsa;
|
||||
if(!catalog)throw new Error('Preço de tabela indisponível agora.');
|
||||
const billed=heights.map(metres=>Math.max(1,Math.ceil(metres*10)/10));
|
||||
// Every 10 cm, 8 mm in the customer's favour (app/core/pricing.py billed_length).
|
||||
const billed=heights.map(metres=>Math.max(1,Math.ceil(+((metres-0.008)*10).toFixed(6))/10));
|
||||
const total=+billed.reduce((sum,metres)=>sum+metres,0).toFixed(2);
|
||||
let unit=catalog.unit_cents,best=null;
|
||||
for(const band of catalog.bands||[]){
|
||||
@@ -395,7 +396,7 @@ function montarPaintTotals(){
|
||||
$('montar-sum-pieces').textContent=String(pieces);
|
||||
$('montar-sum-film').textContent=count?(done?metres(film):metres(film)+' …'):'—';
|
||||
$('montar-film-length').textContent=count?metres(film):'—';
|
||||
$('montar-film-hint').textContent='em filme de 57 cm, já encaixada. Atualiza a cada mudança na lista.'+
|
||||
$('montar-film-hint').textContent='em filme de 57 cm, já encaixada.'+
|
||||
(count&&!done?' Calculando a montagem…':'');
|
||||
$('montar-clear').disabled=!count;
|
||||
$('montar-warning').hidden=!(count>20||MONTAR.lines.some(line=>line.qty>200));
|
||||
@@ -948,7 +949,7 @@ function montarOpenAdjustments(){
|
||||
if(!may('manage')||$('montar-sizes'))return;
|
||||
MONTAR.dirty=false;MONTAR.internalDirty=false;
|
||||
formDialog('Ajustes do Montar',{
|
||||
text:'Valem para todas as folhas. Mudam pouco, por isso ficam aqui e não na tela.',
|
||||
text:'Valem para todas as folhas.',
|
||||
fields:montarAdjustmentFields(),label:'Salvar ajustes',width:720,className:'montar-ajustes-dlg',
|
||||
onsave:async()=>montarSaveAdjustments()
|
||||
});
|
||||
|
||||
@@ -266,7 +266,7 @@ function nextBox(order){
|
||||
title='Aguardando prova do #'+order.proof_card.number;
|
||||
const manual=(board.orders.find(o=>o.id===order.proof_card.id)?.print_files||[]).some(r=>r.status==='manual');
|
||||
note(manual?'O Prumo não abriu o original. Prepare o PNG completo deste pedido; a prova será gerada automaticamente a partir dele.'
|
||||
:'O pedido segue para Arte conferida após Prova OK no card da prova. Você pode abrir o arquivo para consultar.');
|
||||
:'O pedido segue para Arte conferida com Prova OK no card da prova.');
|
||||
if(manual&&may('produce'))main.push(button('Preparar arquivo para a prova',()=>finalDialog(order,readyFinals(order)),'btn pri lg'));
|
||||
if(order.proof_card.reviews?.length)more.push(...reviewButtons(order.proof_card.id,order.proof_card.reviews,order.proof_card.number));
|
||||
return composeNext(title,body,main,more);
|
||||
@@ -304,9 +304,8 @@ function nextBox(order){
|
||||
if((st==='rec'||st==='tra'||st==='imp')&&!order.proof_parent&&!fixed&&may('produce')&&
|
||||
(order.print_files||[]).some(r=>r.status==='ready'))
|
||||
more.push(button('Gerar de novo',async()=>{
|
||||
if(!await ask('Gerar o arquivo de novo?','O sistema gera o arquivo do pedido de novo, com o tamanho de parte de agora. '+
|
||||
'O arquivo final aprovado sai: o pedido volta para Arte recebida'+(st==='imp'?', sai da hot folder da máquina,':'')+
|
||||
' e o arquivo novo precisa ser aprovado.',
|
||||
if(!await ask('Gerar o arquivo de novo?','O arquivo sai com o tamanho de parte atual. O pedido volta para Arte recebida'+
|
||||
(st==='imp'?' e sai da hot folder':'')+', e o arquivo novo precisa ser aprovado.',
|
||||
'Gerar de novo',{host:$('drawer')}))return;
|
||||
await api('/orders/'+order.id+'/print-files/again',{});await load();
|
||||
say('Gerando o arquivo do #'+order.number+' de novo. Aprove quando ficar pronto.');
|
||||
@@ -330,7 +329,7 @@ function nextBox(order){
|
||||
const manual=(order.print_files||[]).some(r=>r.status==='manual');
|
||||
note(finalDone(order)?'Abra o PNG gerado pelo Prumo e confirme a contração.':manual
|
||||
?'O original exige preparo manual. Abra o pedido pai, envie o PNG completo e depois gere a prova de novo.'
|
||||
:'O Prumo prepara até 15 cm por classe e aprova o PNG final automaticamente.');
|
||||
:'O Prumo prepara até 30 cm por classe e aprova o PNG final automaticamente.');
|
||||
if(manual&&may('produce'))more.push(button('Abrir pedido pai',()=>openPanel(order.proof_parent.id),'btn lg'));
|
||||
if(finalDone(order)&&may('produce'))main.push(checkButton(order,'btn pri lg'));
|
||||
if((order.print_files||[]).some(r=>r.status==='failed'||r.status==='manual'||r.timed_out)&&may('produce'))
|
||||
@@ -440,7 +439,7 @@ function correctionDialog(order){
|
||||
const text=node('textarea');text.placeholder='Ex.: o logo da manga veio em 72 DPI';text.maxLength=1000;text.required=true;
|
||||
text.setAttribute('aria-label','Motivo da correção');
|
||||
formDialog('Pedir correção do pedido #'+order.number,{host:$('drawer'),className:'reason',width:540,
|
||||
text:'O pedido vai para Correção. Depois, a mensagem para o cliente fica pronta para mandar no WhatsApp.',
|
||||
text:'O pedido vai para Correção e a mensagem para o cliente fica pronta para o WhatsApp.',
|
||||
fields:[field('Motivo',text,'O cliente vê este motivo na mensagem.')],label:'Enviar para correção',tone:'red',
|
||||
onsave:async()=>{await move(order,'cor',text.value.trim());}});
|
||||
}
|
||||
@@ -463,7 +462,7 @@ function cancelDialog(order){
|
||||
const why=node('textarea');why.placeholder='Ex.: cliente desistiu, vai refazer a arte';why.setAttribute('aria-label','Motivo do cancelamento');
|
||||
why.required=true;why.minLength=3;why.maxLength=1000;
|
||||
formDialog('Cancelar o pedido #'+order.number+'?',{host:$('drawer'),className:'reason',width:520,
|
||||
text:'O pedido sai do quadro e fica em Cancelados, com o pagamento e o histórico. O valor fica como crédito do cliente, no controle financeiro, e o pedido no Tiny se cancela lá.',
|
||||
text:'O pedido vai para Cancelados com o pagamento e o histórico. O valor vira crédito do cliente e o pedido é cancelado no Tiny.',
|
||||
fields:[field('Motivo',why,'Fica no histórico do pedido.')],label:'Cancelar pedido',tone:'red',
|
||||
onsave:async()=>{await api('/orders/'+order.id+'/cancel',{note:why.value.trim()});say('Pedido #'+order.number+' cancelado.');await load();}});
|
||||
}
|
||||
@@ -553,12 +552,12 @@ async function finalsOk(order,uploads){
|
||||
async function approveReady(order,ready){
|
||||
if(!await finalsOk(order,ready.flatMap(r=>r.files.map(f=>f.upload_id))))return;
|
||||
const many=ready.length>1;
|
||||
if(!await ask('Aprovar o arquivo final?','Conferiu? É este arquivo que vai para a impressão: '+
|
||||
if(!await ask('Aprovar o arquivo final?','Este é o arquivo que vai para a impressão: '+
|
||||
ready.map((r,i)=>(many?'item '+(i+1)+', ':'')+r.label).join('; ')+'.','Aprovar arquivo final',{host:$('drawer')}))return;
|
||||
const note='Aprovado como está: '+[...new Set(ready.map(r=>FINAL_SOURCE[r.source]))].join(', ');
|
||||
if(await saveFinalFiles(order,
|
||||
ready.flatMap((r,i)=>r.files.map(f=>({item_index:i,upload_id:f.upload_id}))),note))return;
|
||||
await load();say(mayMove(order.state,'tra')?'Arquivo final aprovado. Agora é só mover para Arte conferida.':'Arquivo final aprovado. Falta mover para Arte conferida.');
|
||||
await load();say(mayMove(order.state,'tra')?'Arquivo final aprovado. Mova para Arte conferida.':'Arquivo final aprovado. Falta mover para Arte conferida.');
|
||||
}
|
||||
// The file the operator prepared, per item; a ready file comes ticked.
|
||||
function finalDialog(order,ready,{replace=false}={}){
|
||||
@@ -857,7 +856,7 @@ function isOk(order){
|
||||
const treat=button('Tratar a arte',()=>{m.close();treatDialog(order);},'btn');
|
||||
const m=formDialog('Está OK?',{host:$('drawer'),fields,left:[treat],label:'Mover para Arte conferida',
|
||||
text:missing?'Falta o arquivo final de um item: trate a arte e envie o arquivo preparado.'
|
||||
:'A arte chegou boa? Confira a contração e mova para Arte conferida.',
|
||||
:'Confira a arte e a contração e mova para Arte conferida.',
|
||||
onsave:async()=>{
|
||||
if(missing)throw new Error('Falta o arquivo final de um item.');
|
||||
for(const [index,select] of selects.entries())
|
||||
@@ -894,12 +893,12 @@ function treatDialog(order){
|
||||
row.path.textContent=name?(base.value.trim()?'':'…\\')+where(name):'Este item ainda não tem arquivo na pasta.';
|
||||
row.copy.disabled=!name;
|
||||
row.copy.onclick=async()=>{try{await navigator.clipboard.writeText(where(name));
|
||||
say(base.value.trim()?'Caminho copiado.':'Caminho copiado a partir da pasta dos pedidos: informe onde ela fica neste computador para copiar o caminho inteiro.');}
|
||||
say(base.value.trim()?'Caminho copiado.':'Caminho copiado sem o começo. Informe onde fica a pasta dos pedidos neste computador para copiar o caminho completo.');}
|
||||
catch(_){say('Não foi possível copiar.',true);}};
|
||||
});
|
||||
base.onchange=()=>{kv.set(FOLDER_PATH_KEY,base.value.trim()).catch(()=>{});paint();};
|
||||
formDialog('Tratar a arte',{host:$('drawer'),width:620,className:'finalform',
|
||||
text:'Copie o caminho e abra o arquivo. Trate e salve por cima, com o mesmo nome. Depois suba aqui o arquivo tratado.',
|
||||
text:'Copie o caminho e abra o arquivo. Trate, salve por cima com o mesmo nome e envie aqui o arquivo tratado.',
|
||||
fields:[...rows.map(r=>r.input.closest('.fslot')),field('Pasta dos pedidos neste computador',base)],label:'Subir arte tratada',
|
||||
onsave:async()=>{
|
||||
// Each item keeps its approved final, or else the file ready to approve,
|
||||
@@ -924,7 +923,7 @@ function treatDialog(order){
|
||||
}
|
||||
if(await saveFinalFiles(order,refs,TREAT_NOTE))return;
|
||||
await load();
|
||||
say(mayMove(order.state,'tra')?'Arte tratada aprovada como arquivo final. Agora é só mover para Arte conferida.':'Arte tratada aprovada como arquivo final.');
|
||||
say(mayMove(order.state,'tra')?'Arte tratada aprovada como arquivo final. Mova para Arte conferida.':'Arte tratada aprovada como arquivo final.');
|
||||
}});
|
||||
// Filled once open: the names the automatic folders give the files.
|
||||
(async()=>{
|
||||
@@ -1074,7 +1073,7 @@ function itemCard(order,item,index){
|
||||
(item.residue_accepted_at?' às '+when(item.residue_accepted_at):'')+'.','warn'));
|
||||
if(item.stroke_choice)notes.append(itemNote('Traços finos e áreas chapadas no mesmo arquivo: '+
|
||||
(item.stroke_choice==='client_c3'?'o cliente escolheu proteger as áreas chapadas (C3); o traço fino pode sumir em tecido escuro.'
|
||||
:'o cliente foi avisado e quis imprimir assim mesmo (C1).')+
|
||||
:'o cliente escolheu imprimir assim mesmo (C1).')+
|
||||
(item.stroke_choice_at?' Aceito às '+when(item.stroke_choice_at)+'.':''),'warn'));
|
||||
if(mirroredItem(item))notes.append(itemNote(MIRROR_NOTE+'.','bad'));
|
||||
// After a customer correction, that file is the artwork: the generated
|
||||
@@ -1144,7 +1143,10 @@ function reprintChoice(order){
|
||||
const input=node('input');input.checked=chosen.has(index);input.disabled=!may('produce');
|
||||
box.append(checkbox('Item '+(index+1)+', '+productName(item),input));return input;
|
||||
});
|
||||
box.append(node('small',order.print_items?'Só os itens marcados vão para a máquina.'
|
||||
// A saved choice is the whole list when every item goes (never NULL, which
|
||||
// is "not chosen yet" and would show the suggestion again).
|
||||
const all=order.print_items?.length===order.snapshot.items.length;
|
||||
box.append(node('small',order.print_items?(all?'Todos os itens vão para a máquina.':'Só os itens marcados vão para a máquina.')
|
||||
:order.print_suggested?'Marcados os itens cujo arquivo mudou desde a última impressão.'
|
||||
:'O pedido já foi impresso: marque só os itens que precisam sair de novo.'));
|
||||
if(may('produce')){
|
||||
|
||||
@@ -323,7 +323,10 @@ function machineForm(m){
|
||||
left.push(remove);
|
||||
}
|
||||
const d=formDialog(m?'Editar máquina':'Nova máquina',{width:520,left,
|
||||
fields:[field('Nome',name),group('Imprime',products),
|
||||
// The hot folder is the machine's first name, for good (FlexiPRINT watches
|
||||
// that path): renaming the machine does not move it.
|
||||
fields:[field('Nome',name,m?'Pasta no FlexiPRINT: 3. Imprimindo/'+(m.folder||m.name)+'. Trocar o nome não muda a pasta.':undefined),
|
||||
group('Imprime',products),
|
||||
field('Limite de metros em aberto',unit(limit,'metros'),'Pedidos novos vão para a máquina do produto com menos metros em aberto, dentro do limite.'),
|
||||
field('Vagas em Imprimindo',places,PLACES_NOTE),
|
||||
checkbox('Ativa: recebe pedidos',active)],
|
||||
@@ -738,7 +741,7 @@ function accountForm(){
|
||||
sect.append(node('b','Trocar a senha'),field('Senha atual',current),row);
|
||||
formDialog(ME.name||ME.email,{width:560,lead:avatar({name:ME.name,email:ME.email,active:true,seen_at:new Date().toISOString()},'bigava'),
|
||||
text:rolesLabel(myRoles())+(myMachine()?', na '+myMachine().name:''),fields:[dl,sect],
|
||||
note:'Nome, e-mail e perfil quem muda é o administrador.',label:'Salvar senha',onsave:async()=>{
|
||||
note:'Só o administrador muda nome, e-mail e perfil.',label:'Salvar senha',onsave:async()=>{
|
||||
if(next.value!==again.value)throw new Error('A nova senha e a repetição não conferem.');
|
||||
await api('/me/password',{current:current.value,new:next.value});say('Senha trocada.');
|
||||
}});
|
||||
|
||||
@@ -122,7 +122,7 @@
|
||||
<section class="panel montar-nofolder-panel" id="montar-nofolder-panel" hidden>
|
||||
<span class="montar-nofolder-ico"><svg class="i" viewBox="0 0 256 256" aria-hidden="true"><path fill="currentColor" d="M216,72H131.31L104,44.69A15.86,15.86,0,0,0,92.69,40H40a16,16,0,0,0-16,16V200.62A15.4,15.4,0,0,0,39.38,216H216.89A15.13,15.13,0,0,0,232,200.89V88A16,16,0,0,0,216,72ZM40,56H92.69l16,16H40ZM216,200H40V88H216Z"></path></svg></span>
|
||||
<b>Escolha a pasta dos pedidos</b>
|
||||
<span>O Montar lê as estampas da pasta Estampas/, dentro da pasta dos pedidos deste computador. É a mesma pasta de Integrações; basta escolher uma vez.</span>
|
||||
<span>As estampas vêm da pasta Estampas/, dentro da pasta dos pedidos (a mesma de Integrações).</span>
|
||||
<button class="btn pri" id="montar-nofolder-choose" type="button">Escolher pasta</button>
|
||||
</section>
|
||||
<section class="panel clip" id="montar-setup" hidden>
|
||||
@@ -146,7 +146,7 @@
|
||||
<div class="montar-sheetinfo">
|
||||
<span>Prévia da folha</span>
|
||||
<b id="montar-film-length">—</b>
|
||||
<span id="montar-film-hint">em filme de 57 cm, já encaixada. Atualiza a cada mudança na lista.</span>
|
||||
<span id="montar-film-hint">em filme de 57 cm, já encaixada.</span>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -27,6 +27,8 @@ function outcomeText(outcome){
|
||||
[/^refused: quote was never reviewed/,()=>'a cotação ainda não tinha sido revisada'],
|
||||
[/^refused: quote uses an obsolete/,()=>'a cotação usa uma montagem antiga'],
|
||||
[/^attention: payment (\w+) for order (\d+)/,m=>'pagamento '+(m[1]==='refunded'?'estornado':'cancelado')+' depois do pedido #'+m[2]],
|
||||
// The customer paid the same cart twice (a PIX and a card): one is refunded.
|
||||
[/^attention: second payment (\S+) for order (\d+)/,m=>'segundo pagamento ('+m[1]+') do pedido #'+m[2]+': o cliente pagou duas vezes, estorne um no Mercado Pago'],
|
||||
];
|
||||
for(const [pattern,text] of rules){const m=outcome.match(pattern);if(m)return text(m);}
|
||||
return outcome;
|
||||
@@ -368,10 +370,10 @@ function folderCard(){
|
||||
if(FOLDER.mode==='none'){
|
||||
if(FOLDER.brave){
|
||||
const first=node('li','Copie este endereço: ');first.append(node('code',BRAVE_FLAG,'flag'));
|
||||
row=integration({name,state:'Desligada no Brave',tone:'warn',summary:'O Brave bloqueia o acesso a pastas. Dá para liberar em 1 minuto.',
|
||||
row=integration({name,state:'Desligada no Brave',tone:'warn',summary:'O Brave bloqueia o acesso a pastas. Libere com os passos abaixo.',
|
||||
actions:[act('Copiar endereço',async()=>{await navigator.clipboard.writeText(BRAVE_FLAG);say('Endereço copiado: cole na barra do Brave.');})],
|
||||
details:[steps(first,'Cole na barra do Brave e mude “File System Access API” para “Enabled”.','Reinicie o Brave e volte aqui.'),
|
||||
node('p','Ou abra o Kanban no Chrome ou no Edge, que já vêm com isso ligado.')]});
|
||||
node('p','Ou abra o Kanban no Chrome ou no Edge.')]});
|
||||
}else row=integration({name,state:'Não funciona aqui',tone:'off',summary:'Abra o Kanban no Chrome ou no Edge para salvar numa pasta.'});
|
||||
}else if(FOLDER.mode==='downloads'){
|
||||
const how=[steps('No Firefox, abra Configurações → Geral → Arquivos e aplicativos.',
|
||||
@@ -381,13 +383,12 @@ function folderCard(){
|
||||
? integration({name,state:FOLDER.error?'Verificar':'Ligada',tone:FOLDER.error?'warn':'ok',
|
||||
summary:FOLDER.error||FOLDER.status||'Baixando na pasta de downloads do Firefox · '+folderCount(),
|
||||
details:how,extra:[ghost('Desligar',()=>setDownloads(false))]})
|
||||
: integration({name,state:'Desligada',tone:'off',summary:'No Firefox, baixa sozinho os arquivos que entram em Arte conferida; as pastas do fluxo pedem o Chrome ou o Edge.',
|
||||
: integration({name,state:'Desligada',tone:'off',summary:'No Firefox, baixa os arquivos que entram em Arte conferida. As pastas do fluxo precisam do Chrome ou do Edge.',
|
||||
actions:[act('Ligar',()=>setDownloads(true))],details:how});
|
||||
}else if(!h){
|
||||
row=integration({name,state:'Desligada',tone:'off',summary:'Salva sozinho os arquivos dos pedidos nas pastas do fluxo, de 1. Arte recebida a 5. Finalizado, o recibo de cada retirada em Recibos e as fotos da revisão em Revisões.',
|
||||
row=integration({name,state:'Desligada',tone:'off',summary:'Salva o arquivo de cada pedido na pasta da etapa em que ele está, os recibos em Recibos e as fotos da revisão em Revisões.',
|
||||
actions:[act('Escolher pasta',chooseFolder)],
|
||||
details:[node('p','Escolha uma vez a pasta principal, na rede do servidor: o Kanban cria dentro dela as pastas do fluxo e move o arquivo conforme o card anda. '+
|
||||
'Os arquivos levam o número do pedido no nome. Funciona neste computador, com o Kanban aberto e um usuário que vê todos os pedidos, como o de Gestão.')]});
|
||||
details:[node('p','Escolha a pasta principal, na rede do servidor. Funciona com o Kanban aberto neste computador, num usuário que vê todos os pedidos, como o de Gestão.')]});
|
||||
}else if(!FOLDER.granted){
|
||||
row=integration({name,state:'Liberar',tone:'warn',summary:'O navegador pede um clique para voltar a salvar em “'+h.name+'”.',
|
||||
actions:[act('Liberar pasta',releaseFolder)],extra:[ghost('Trocar pasta',chooseFolder),ghost('Desligar',forgetFolder)]});
|
||||
@@ -396,13 +397,11 @@ function folderCard(){
|
||||
summary:FOLDER.error||FOLDER.status||'Salvando em “'+h.name+'” · '+folderCount(),
|
||||
details:[['Pasta','“'+h.name+'”'],['Arquivos salvos',String(FOLDER.saved.size)],
|
||||
['Último',FOLDER.last?FOLDER.last.toLocaleTimeString('pt-BR',{hour:'2-digit',minute:'2-digit'}):'—'],
|
||||
node('p','Dentro de “'+h.name+'”: o arquivo do pedido chega em '+STAGE_FOLDERS.rec+', passa para '+STAGE_FOLDERS.tra+' quando o card vai para lá '+
|
||||
'e fica lá enquanto imprime, vai para '+STAGE_FOLDERS.rev+' com o card e para '+STAGE_FOLDERS.fin+' quando o pedido é finalizado, onde fica '+KEEP_FINISHED_DAYS+' dias.'),
|
||||
node('p','A pasta '+WORK_FOLDER+' é a de trabalho do Kanban: cada arquivo é gravado nela e só entra na pasta da etapa ou na hot folder completo, com o nome final. Não coloque nada nela.'),
|
||||
node('p','Pedido de retirada que chega em Finalizado: o recibo para a bobina de 80 mm vai para '+RECEIPTS_FOLDER+', uma vez só, por um dos computadores com a pasta ligada. As fotos da revisão vão para '+REVIEWS_FOLDER+' e não saem de lá.'),
|
||||
node('p','Pedido cancelado, excluído ou devolvido para correção: o arquivo sai das pastas. Arquivo trocado: a versão antiga sai. '+
|
||||
'Pedidos que já estavam imprimindo quando a pasta foi escolhida não são baixados. Se este computador ficar desligado, '+
|
||||
'ao voltar ele busca também o que passou nesse tempo, cada arquivo na pasta da etapa em que o pedido está. Deixe o Kanban aberto neste computador.')],
|
||||
node('p','Cada arquivo fica na pasta da etapa do pedido, de '+STAGE_FOLDERS.rec+' a '+STAGE_FOLDERS.fin+'. Em '+STAGE_FOLDERS.fin+' fica '+KEEP_FINISHED_DAYS+' dias.'),
|
||||
node('p','Não coloque nada na pasta '+WORK_FOLDER+': é a de trabalho do Kanban.'),
|
||||
node('p','O recibo de cada retirada vai para '+RECEIPTS_FOLDER+' quando o pedido é finalizado. As fotos da revisão ficam em '+REVIEWS_FOLDER+'.'),
|
||||
node('p','Pedido cancelado, excluído ou em correção sai das pastas. Pedidos que já imprimiam quando a pasta foi escolhida não são baixados.'),
|
||||
node('p','Deixe o Kanban aberto neste computador. Se ele ficar desligado, ao voltar busca o que faltou.')],
|
||||
extra:[ghost('Trocar pasta',chooseFolder),ghost('Desligar',forgetFolder)]});
|
||||
}
|
||||
row.id='folder-card';return row;
|
||||
@@ -566,6 +565,9 @@ async function fetchFile(url,options){
|
||||
}
|
||||
async function fetchInto(dir,file,watched=false){
|
||||
const r=await fetchFile(file.url,{referrerPolicy:'no-referrer'});
|
||||
// A link that ran out while the files before it were downloading: the next
|
||||
// pass asks for a new one, as for a network that dropped.
|
||||
if(r.status===403){const e=new Error('o link de '+file.name+' venceu antes do download.');e.unreachable=true;throw e;}
|
||||
if(!r.ok||!r.body)throw new Error('não foi possível baixar '+file.name+' (erro '+r.status+').');
|
||||
await writeWhole(dir,file.name,r,watched);
|
||||
}
|
||||
@@ -624,9 +626,16 @@ async function syncFolder(force=false){
|
||||
FOLDER.busy=true;
|
||||
try{
|
||||
if(stages)await makeStageFolders();
|
||||
const held=stages?[...new Set([...FOLDER.saved.values()].filter(r=>!r.review).map(r=>r.order).filter(Boolean))].slice(-1000):[];
|
||||
// The server answers for up to 1000 orders a pass: the ones still in the
|
||||
// flow first, then those in Finalizado. A file whose order was not asked
|
||||
// this time stays as it is; only an order the server says is gone,
|
||||
// cancelled or moved changes its files.
|
||||
const records=[...FOLDER.saved.values()].filter(r=>!r.review&&r.order);
|
||||
const held=stages?[...new Set([...records.filter(r=>r.folder!==STAGE_FOLDERS.fin),...records.filter(r=>r.folder===STAGE_FOLDERS.fin)]
|
||||
.map(r=>r.order))].slice(0,1000):[];
|
||||
const asked=new Set(held);
|
||||
const {files,states,receipts=[],reviews=[]}=await api('/queue/folder',{early:stages,held,since:stages?FOLDER.since||await folderSince():null});
|
||||
// By file: an item over 15 m is several parts (item 13), each its own file.
|
||||
// By file: an item longer than a part (10 m) is several parts (item 13), each its own file.
|
||||
const wanted=new Map(files.map(f=>[f.upload_id,f]));
|
||||
const where=stages?'“'+FOLDER.handle.name+'”':'a pasta de downloads';
|
||||
let removed=0, moved=0, saved=0;
|
||||
@@ -640,7 +649,7 @@ async function syncFolder(force=false){
|
||||
...(folder===STAGE_FOLDERS.fin?{at:file.at||Date.now()}:{})});
|
||||
FOLDER.last=new Date();await keepSaved();};
|
||||
if(stages)for(const [uid,rec] of [...FOLDER.saved])await step(rec.name,async()=>{
|
||||
if(!rec.order||!rec.folder)return;
|
||||
if(!rec.order||!rec.folder||!asked.has(rec.order))return;
|
||||
const state=states[rec.order], target=STAGE_FOLDERS[state];
|
||||
const now=wanted.get(uid);
|
||||
const replaced=(state==='rec'||state==='tra')&&(!now||now.order!==rec.order);
|
||||
@@ -769,7 +778,7 @@ async function syncFolder(force=false){
|
||||
}
|
||||
FOLDER.awaySince=0;FOLDER.awayReported=false;
|
||||
if(e.name==='NotAllowedError')FOLDER.granted=false;
|
||||
else if(e.name==='NotFoundError')FOLDER.error='Um arquivo ou pasta dentro de “'+name+'” sumiu durante a passagem (alguém tirou ou renomeou?). O Kanban tenta de novo sozinho.';
|
||||
else if(e.name==='NotFoundError')FOLDER.error='Um arquivo ou pasta dentro de “'+name+'” foi movido ou renomeado. O Kanban tenta de novo sozinho.';
|
||||
else FOLDER.error='A última tentativa falhou: '+e.message+' O Kanban tenta de novo sozinho.';
|
||||
FOLDER.status='';say('Pastas automáticas: '+(FOLDER.error||'o navegador pediu para liberar a pasta de novo, em Integrações.'),true);
|
||||
}finally{FOLDER.busy=false;paintFolder();}
|
||||
|
||||
@@ -122,6 +122,14 @@
|
||||
if (!started || status === 401 || typeof Sentry === 'undefined') return;
|
||||
// A restart's few seconds without the database (app/app.py): not a bug.
|
||||
if (status === 503 && /reiniciando/.test(String(message))) return;
|
||||
// A refusal the server explains to the person (a rule, a check, a limit:
|
||||
// a 4xx with a sentence for them) is the system working, not a bug: on
|
||||
// the Kanban it stays, as a warning, since a refusal the team keeps
|
||||
// meeting says a screen confuses; on the Site the customer reads it and
|
||||
// nothing is sent (2026-11-30). A 4xx without a sentence (a list of
|
||||
// fields: what the page sent was wrong) and a 5xx stay errors.
|
||||
const refusal = status >= 400 && status < 500 && typeof detail === 'string';
|
||||
if (refusal && app !== 'kanban') return;
|
||||
try {
|
||||
// One issue per kind of API error: without this Sentry groups them all
|
||||
// by apiError and DTF-WEB-1 mixes a 422 for 66 files with a 422 for
|
||||
@@ -131,7 +139,7 @@
|
||||
const extra = {path, status, page: location.pathname};
|
||||
if (status === 422 && detail) extra.detail = detail;
|
||||
Sentry.captureMessage('API ' + status + ' ' + kindPath + ': ' + kindMessage,
|
||||
{level: 'error', tags: {app}, extra,
|
||||
{level: refusal ? 'warning' : 'error', tags: {app, ...(refusal ? {recusa: 'sim'} : {})}, extra,
|
||||
fingerprint: ['api-error', String(status), kindPath, kindMessage]});
|
||||
} catch (error) {
|
||||
// Reporting an error must never break the page.
|
||||
|
||||
@@ -208,7 +208,7 @@
|
||||
<a href="https://wa.me/message/NJ76CLIOUGXLB1" target="_blank" rel="noopener">16 99428-0056</a>
|
||||
· arquivos 16 99230-2546<br>
|
||||
<a href="mailto:atendimentodropstar@gmail.com">atendimentodropstar@gmail.com</a><br>
|
||||
Mande sua arte em qualquer horário.<br>
|
||||
Envie sua arte a qualquer hora.<br>
|
||||
Retirada em Franca, de segunda a sexta, das 7h às 18h
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -326,7 +326,7 @@ $('fPerfil').onsubmit=async event=>{
|
||||
try{
|
||||
const r=await api('/account/profile',{name:$('dNomeCli').value,zap:$('dZap').value,address});
|
||||
conta=r.customer;aviso('Dados salvos.');
|
||||
}catch(e){aviso(e.status===422?(algum?'Confira o nome, o WhatsApp e o endereço: todos os campos, menos o complemento, são necessários.':'Confira o nome e o WhatsApp.'):e.message,true);}
|
||||
}catch(e){aviso(e.status===422?(algum?'Preencha nome, WhatsApp e endereço. Só o complemento é opcional.':'Confira o nome e o WhatsApp.'):e.message,true);}
|
||||
};
|
||||
// A new e-mail is confirmed with the code sent to it before the account changes.
|
||||
let troca=null, trocaTimer=null;
|
||||
|
||||
@@ -118,9 +118,18 @@ function invalidaItemAtual(){
|
||||
pintaPedido();
|
||||
}
|
||||
function itemPodeEnviar(item){
|
||||
if(semMargem(item)) return false;
|
||||
return item.qualityStatus==='ok' || item.qualityStatus==='unverified' ||
|
||||
(item.qualityStatus==='warning' && item.qualityAcknowledged===true);
|
||||
}
|
||||
// Uma folha pronta guardada no carrinho antes dos 8 mm entre as cópias
|
||||
// (27/11/2026): o servidor a recusa no pagamento, então o carrinho diz já,
|
||||
// no próprio item, para refazê-lo (Sentry DTF-WEB-22).
|
||||
function semMargem(item){
|
||||
if(!['file','uvfile','premium'].includes(item.modo) || !item.production?.placements) return false;
|
||||
const ps=[...item.production.placements].sort((a,b)=>a.y_cm-b.y_cm);
|
||||
return ps.some((p,i)=>i>0 && p.y_cm < ps[i-1].y_cm+ps[i-1].length_cm+MARGEM_FOLHA_CM-0.02);
|
||||
}
|
||||
// Os itens marcados no carrinho são os que vão para o pagamento; um item
|
||||
// desmarcado fica guardado para depois. O item aberto no produto sempre vai.
|
||||
function itensAPagar(){
|
||||
@@ -176,7 +185,7 @@ function aplicaTratamento(aPagar){
|
||||
document.querySelectorAll('[data-ajuste],[data-ajustea]').forEach(el=>{el.checked=true;});
|
||||
}
|
||||
check.checked=ajusteTudo;check.disabled=true;
|
||||
mostraAvisoTratamento('Sua arte tem nota '+worst+': para imprimir com qualidade, o Ajuste Fino é obrigatório neste pedido.');
|
||||
mostraAvisoTratamento('Sua arte tem nota '+worst+', então o Ajuste Fino é obrigatório neste pedido.');
|
||||
}else{
|
||||
check.checked=ajusteTudo;check.disabled=false;mostraAvisoTratamento('');
|
||||
}
|
||||
@@ -209,7 +218,8 @@ function pintaPedido(){
|
||||
' aria-label="Incluir '+escapeHTML(it.tit)+' no pagamento"></label>'+
|
||||
'<span class="miniItem">'+(it.mini ? '<img src="'+escapeHTML(it.mini)+'" alt="">' : '<i>'+escapeHTML(it.ext||'')+'</i>')+
|
||||
(it.arquivos>1 ? '<em>+'+(it.arquivos-1)+'</em>' : '')+'</span>'+
|
||||
'<div class="nm2"><b>'+escapeHTML(it.tit)+'</b><span>'+escapeHTML(it.desc)+'</span></div>'+
|
||||
'<div class="nm2"><b>'+escapeHTML(it.tit)+'</b><span>'+escapeHTML(it.desc)+'</span>'+
|
||||
(semMargem(it)?'<span class="avisoF">O espaço entre as cópias passou a ser de 8 mm. Remova este item e adicione a folha de novo.</span>':'')+'</div>'+
|
||||
'<div class="vl2">'+rs(it.total)+'</div>'+
|
||||
'<button type="button" class="x" data-rmi="'+i+'" aria-label="Remover '+escapeHTML(it.tit)+'">'+icone('lixeira')+'<span>Remover</span></button></div>').join('');
|
||||
$('itens').querySelectorAll('[data-sel]').forEach(c=>c.addEventListener('change',()=>{
|
||||
@@ -232,8 +242,8 @@ function pintaPedido(){
|
||||
// The whole order waits 48 h when any art was sent to Redesenho, else 24 h.
|
||||
const prazoTratamento=document.querySelector('#tratamentoBox .provaOp span');
|
||||
if(prazoTratamento) for(const no of prazoTratamento.childNodes)
|
||||
if(no.nodeType===3) no.textContent=no.textContent.replace(/aumenta em \d+ h/,
|
||||
'aumenta em '+(artesRedesenho>0?48:24)+' h');
|
||||
if(no.nodeType===3) no.textContent=no.textContent.replace(/leva \d+ h a mais/,
|
||||
'leva '+(artesRedesenho>0?48:24)+' h a mais');
|
||||
const soma = itens + frete + tratamento + redesenho;
|
||||
const n = aPagar.length, noCarrinho = pedido.length + (itemAtual?1:0);
|
||||
$('resLin').innerHTML =
|
||||
@@ -285,8 +295,8 @@ function carrinho(){
|
||||
$('carr').classList.add('on');
|
||||
let l='<div class="l"><span>'+MODOS[modo].tit+'</span><b>'+rs(base)+'/m</b></div>';
|
||||
if(!ehFolha()) l += '<div class="l" style="color:#8D9AB0"><span>'+(montagemFolhas?'Montagem em '+montagemFolhas.length+' folhas, pela espessura do traço':'Montagem da folha')+'</span><b>inclusa</b></div>';
|
||||
if(extra) l += '<div class="l"><span>Arquivo aberto na mão</span><b>+'+rs(extra)+'/m</b></div>';
|
||||
l += '<div class="l"><span>Metragem'+(sobra>0.001?' · arredondada para 10 cm':'')+
|
||||
if(extra) l += '<div class="l"><span>Abertura manual do arquivo</span><b>+'+rs(extra)+'/m</b></div>';
|
||||
l += '<div class="l"><span>Metragem'+(sobra>0.001?' · a cada 10 cm':'')+
|
||||
'</span><b>'+fmtM(cob)+' m</b></div>';
|
||||
l += '<div class="l"><span>Preço final do metro</span><b>'+rs(unit)+'</b></div>'+
|
||||
'<div class="l" style="color:var(--laranja2)"><span>Revisão e reencaixe</span><b>grátis</b></div>';
|
||||
|
||||
@@ -12,13 +12,24 @@
|
||||
$('cMetroLbl').textContent = it.extra ? 'Metro · com '+rs(it.extra)+' de arquivo manual' : 'Metro';
|
||||
$('cMetro').textContent=rs(it.unit);
|
||||
$('cMetragem').textContent=fmtM(it.cob)+' m';
|
||||
const partes=ehFolha(it.modo) ? Math.ceil(it.metros/20) : 1;
|
||||
$('cPartes').textContent = partes>1 ? ' Sai em '+partes+' partes de até 20 m.' : '';
|
||||
// Partes de até 10 m (Marcus, 18/11/2026): o FlexiPRINT não abre mais que isso.
|
||||
const partes=ehFolha(it.modo) ? Math.ceil(it.metros/10) : 1;
|
||||
$('cPartes').textContent = partes>1 ? ' Sai em '+partes+' partes de até 10 m.' : '';
|
||||
const sobraCm=Math.round((it.cob-it.metros)*100);
|
||||
// A metragem cobrada explicada como vantagem (Marcus, 27/11/2026): a cada
|
||||
// 10 cm, e até 8 mm a mais ficam por nossa conta.
|
||||
const exata=n1(it.metros*100)+' cm';
|
||||
const aMais=Math.round((it.metros-it.cob)*1000);
|
||||
$('cObs').textContent =
|
||||
it.cob===MINIMO_M && it.metros<MINIMO_M
|
||||
? (ehFolha(it.modo) ? 'Pedido mínimo de 1 m.'
|
||||
: 'Pedido mínimo de 1 m: ainda cabem '+sobraCm+' cm de artes sem custo.')
|
||||
: it.cob<it.metros-1e-6
|
||||
? 'A folha tem '+exata+': cobramos a cada 10 cm e '+
|
||||
(aMais>1?'os '+aMais+' mm a mais ficam':aMais===1?'o 1 mm a mais fica':'o que passou fica')+' por nossa conta.'
|
||||
: it.cob>it.metros+1e-6
|
||||
? 'A folha tem '+exata+'. Cobramos a cada 10 cm, então fica '+fmtM(it.cob)+' m. '+
|
||||
'Se passar até 8 mm de uma faixa, esse pedaço fica por nossa conta.'
|
||||
: '';
|
||||
$('cTotal').textContent=rs(it.total);
|
||||
}
|
||||
|
||||
@@ -206,11 +206,16 @@ function faltaLeitura(l){
|
||||
return s<10 ? 'faltam '+Math.max(1,Math.ceil(s))+' s' : s<60 ? 'faltam cerca de '+Math.ceil(s/5)*5+' s' : 'faltam cerca de '+duracao(s);
|
||||
}
|
||||
const larguraFilme=()=>MODOS[modo].larg;
|
||||
// cobrança proporcional: arredonda para cima em 10 cm · 2,75 m vira 2,80 m
|
||||
const cobrar=m=>Math.max(MINIMO_M, Math.ceil(m*10)/10);
|
||||
// Cobrança a cada 10 cm, com 8 mm a favor do cliente (Marcus, 27/11/2026):
|
||||
// passou até 8 mm de um múltiplo de 10 cm, fica nele; passou mais, vai para o
|
||||
// próximo. 2,75 m vira 2,80 m; 6,005 m fica 6,00 m. A mesma regra do servidor
|
||||
// (app/core/pricing.py billed_length).
|
||||
const TOLERANCIA_M=0.008;
|
||||
const arredonda10=m=>Math.max(0.1, Math.ceil(+((m-TOLERANCIA_M)*10).toFixed(6))/10);
|
||||
const cobrar=m=>Math.max(MINIMO_M, arredonda10(m));
|
||||
// Com as artes em folhas separadas por traço (item 17), cada folha arredonda
|
||||
// a 10 cm e o mínimo de 1 m vale para a soma: o cliente não escolheu separar.
|
||||
const cobrarFolhas=fs=>Math.max(MINIMO_M, +fs.reduce((t,f)=>t+Math.ceil(+(f.alturaCm/100).toFixed(4)*10)/10,0).toFixed(1));
|
||||
const cobrarFolhas=fs=>Math.max(MINIMO_M, +fs.reduce((t,f)=>t+arredonda10(+(f.alturaCm/100).toFixed(4)),0).toFixed(1));
|
||||
const cobrarMontagem=()=>!ehFolha() && montagemFolhas ? cobrarFolhas(montagemFolhas) : cobrar(metros);
|
||||
const fmtM=m=>m.toFixed(2).replace('.',',');
|
||||
const cls=n=>n>=85?'ok':n>=50?'av':'er';
|
||||
|
||||
@@ -13,8 +13,8 @@ $('qOk').addEventListener('click',()=>{
|
||||
if($('qOk').disabled) return;
|
||||
if(!$('prev').classList.contains('on')){ adicionaAoCarrinho(); return; }
|
||||
const ok=$('ciente').classList.contains('on');
|
||||
qm(ok? '<b>Registrado.</b> Você confirmou que viu a ressalva de resolução.'
|
||||
: '<b>Certo.</b> Confira a folha montada abaixo.','var(--tx)');
|
||||
qm(ok? '<b>Ressalva aceita.</b> Confira a folha montada abaixo.'
|
||||
: 'Confira a folha montada abaixo.','var(--tx)');
|
||||
$('prev').scrollIntoView({behavior:'smooth',block:'start'});
|
||||
});
|
||||
|
||||
|
||||
@@ -95,8 +95,8 @@ function recusaFolha(x, md){
|
||||
folhas=folhas.filter(y=>y!==x);
|
||||
pintaFolha();
|
||||
avisoTipo('<b>'+escapeHTML(arquivo.name)+' não é uma folha montada.</b> '+
|
||||
'Para ocupar os '+n1(larguraFilme())+' cm do filme ela teria só '+md.dpiFolha+
|
||||
' DPI, e o mínimo para imprimir é '+DPI_RECUSA+'. '+
|
||||
'Nos '+n1(larguraFilme())+' cm do filme ela teria só '+md.dpiFolha+
|
||||
' DPI, abaixo do mínimo de '+DPI_RECUSA+'. '+
|
||||
'Se for uma arte para montarmos, use <b>'+MODOS[destino].tit+'</b>, '+
|
||||
'a '+rs(PRECO[destino])+' o metro. '+
|
||||
'<button type="button" id="usarAvulsa">Enviar como '+MODOS[destino].tit.toLowerCase()+'</button>');
|
||||
|
||||
@@ -90,7 +90,7 @@ function desenhaMontagem(area,lista,mts,W,fora,aoTerminar){
|
||||
if(fora) fora.innerHTML='';
|
||||
if(!itens.length){
|
||||
area.innerHTML='<div class="semmont"><b>A montagem aparece aqui</b>'+
|
||||
'<span>informe a largura de cada arte e a folha se desenha sozinha</span></div>';
|
||||
'<span>informe a largura de cada arte para montar a folha</span></div>';
|
||||
if(aoTerminar) aoTerminar({alturaCm:0, uso:0, girou:0});
|
||||
return;
|
||||
}
|
||||
@@ -148,8 +148,8 @@ function desenhaMontagem(area,lista,mts,W,fora,aoTerminar){
|
||||
el.className = uso>=70? 'usoBom' : 'usoRuim';
|
||||
el.innerHTML = (uso>=70
|
||||
? '<b>'+uso+'% da folha virou arte</b> bom aproveitamento'
|
||||
: '<b>'+uso+'% da folha virou arte</b> dá para melhorar: artes de larguras parecidas '+
|
||||
'se encaixam melhor lado a lado')
|
||||
: '<b>'+uso+'% da folha virou arte</b> artes de larguras parecidas '+
|
||||
'encaixam melhor lado a lado')
|
||||
+ (girou? ' · <b style="display:inline">'+girou+
|
||||
(girou>1?' artes giradas':' arte girada')+' 90°</b> para caber melhor':'');
|
||||
(fora||area).appendChild(el);
|
||||
@@ -208,9 +208,9 @@ function previaAoVivo(){
|
||||
? medidas.length+' folhas · '+fmtM(tot)+' m'
|
||||
: n1(medidas[0].med.larg)+' × '+n1(medidas[0].med.alt)+' cm')+'</b>'+
|
||||
'<span>'+(medidas.length>1? 'medidas lidas de cada arquivo' : medidas[0].med.fonte)+
|
||||
' · vão para a máquina do jeito que você montou</span></div>'
|
||||
' · imprimimos como você montou</span></div>'
|
||||
: '<div class="semmont"><b>Sua folha aparece aqui</b>'+
|
||||
'<span>a medida é lida do próprio arquivo, não do peso dele</span></div>';
|
||||
'<span>lemos a medida do próprio arquivo</span></div>';
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -257,7 +257,7 @@ function montaFolhasDeTraco(grupos,W){
|
||||
figura.append(legenda,desenho); painel.append(figura);
|
||||
desenhaMontagem(desenho, lista, 0, W, uso, r=>{
|
||||
if(area.montagemVersao!==versao) return; // a montagem mudou nesse meio-tempo
|
||||
legenda.textContent='Folha '+(i+1)+' · '+NOMES_TRACO[i]+' · '+fmtM(Math.ceil(+(r.alturaCm/100).toFixed(4)*10)/10)+' m';
|
||||
legenda.textContent='Folha '+(i+1)+' · '+NOMES_TRACO[i]+' · '+fmtM(arredonda10(+(r.alturaCm/100).toFixed(4)))+' m';
|
||||
feitas[i]={nome:NOMES_TRACO[i], artes:lista, alturaCm:r.alturaCm, folgaCm:r.folgaCm ?? MARGEM_CM,
|
||||
layout:r.placements ? {height_cm:+r.alturaCm.toFixed(4), placements:r.placements} : null};
|
||||
if(feitas.filter(Boolean).length<grupos.length) return;
|
||||
@@ -274,7 +274,7 @@ function montaFolhasDeTraco(grupos,W){
|
||||
}
|
||||
|
||||
function motivoNota(){
|
||||
if(!nota) return 'sem nota ainda · a conferência roda na sala antes de imprimir';
|
||||
if(!nota) return 'sem nota ainda · conferimos antes de imprimir';
|
||||
if(!ehFolha()){
|
||||
const ruins=artes.filter(a=>a.cm>0 && dpiDe(a)<300);
|
||||
if(!ruins.length) return 'nota '+nota+' · todas as artes em 300 DPI ou mais';
|
||||
@@ -284,7 +284,7 @@ function motivoNota(){
|
||||
Math.round(dpiDe(pior))+' DPI em '+pior.cm.toFixed(1).replace('.',',')+' cm';
|
||||
}
|
||||
return nota>=90 ? 'nota '+nota+' · resolução ótima em toda a folha'
|
||||
: 'nota '+nota+' · a resolução é o único ponto — o resto corrigimos por você';
|
||||
: 'nota '+nota+' · só a resolução pede atenção, o resto corrigimos';
|
||||
}
|
||||
function previa(){
|
||||
const T=window.dtfTimings;
|
||||
@@ -301,12 +301,11 @@ function previa(){
|
||||
['var(--verde)','✓','Espaço entre artes', montagemFolgaCm>=MARGEM_CM-1e-9
|
||||
? '5 mm entre as artes e nas bordas'
|
||||
: n1(montagemFolgaCm*10)+' mm · 5 mm não cabem na largura, a sobra fica dividida por igual'],
|
||||
['var(--verde)','✓','Metragem proporcional',
|
||||
'sua folha tem '+fmtM(metros)+' m e você paga '+fmtM(cob)+
|
||||
' m · arredondamos só até os 10 cm mais próximos'],
|
||||
['var(--verde)','✓','Metragem',
|
||||
'sua folha tem '+fmtM(metros)+' m e você paga '+fmtM(cob)+' m · cobramos a cada 10 cm'],
|
||||
];
|
||||
linhas.push(['var(--verde)','+','Identificação do pedido',
|
||||
'aplicamos seu nome e o número do pedido no fim da folha · por nossa conta']);
|
||||
'seu nome e o número do pedido no fim da folha, sem custo']);
|
||||
$('pInfo').innerHTML=linhas.map(l=>
|
||||
'<div class="li"><span class="c" style="background:'+l[0]+
|
||||
(l[0]==='var(--laranja)'?';color:#241703':'')+'">'+l[1]+'</span>'+
|
||||
@@ -315,5 +314,5 @@ function previa(){
|
||||
$('pArea').innerHTML='<div class="carregando">montando a prévia…</div>';
|
||||
try{ previaArtes(); }
|
||||
catch(e){ $('pArea').innerHTML='<div class="semprev"><b>Prévia indisponível</b>'+
|
||||
'O arquivo será processado normalmente.</div>'; }
|
||||
'O pedido segue normalmente.</div>'; }
|
||||
}
|
||||
|
||||
@@ -378,29 +378,29 @@ function medirFolha(file){
|
||||
verbosity:0}).promise;
|
||||
if(doc.numPages!==1)
|
||||
return {rejected:true, reason:'O PDF tem '+doc.numPages+
|
||||
' páginas. Envie cada folha como um PDF de uma página para calcular o preço correto.'};
|
||||
' páginas. Envie cada folha como um PDF de uma página.'};
|
||||
const page=await doc.getPage(1);
|
||||
const view=page.view, unit=page.userUnit, vp=page.getViewport({scale:1});
|
||||
if(!Array.isArray(view) || view.length!==4 ||
|
||||
!Number.isFinite(unit) || unit<=0 ||
|
||||
!Number.isFinite(vp.width) || !Number.isFinite(vp.height) ||
|
||||
vp.width<=0 || vp.height<=0)
|
||||
return {rejected:true, reason:'Não conseguimos determinar o tamanho desta página PDF. Exporte-a novamente.'};
|
||||
return {rejected:true, reason:'Não conseguimos ler o tamanho desta página. Exporte o PDF de novo.'};
|
||||
const ptW=Math.abs(view[2]-view[0]), ptH=Math.abs(view[3]-view[1]);
|
||||
if(!(ptW>0 && ptH>0) ||
|
||||
(unit===1 && (ptW>PDF_MAX_PT || ptH>PDF_MAX_PT)))
|
||||
return {rejected:true, reason:'A página passa do limite de 508 cm sem UserUnit. Divida a folha ou exporte em PNG.'};
|
||||
return {rejected:true, reason:'A página passa de 508 cm e não tem UserUnit. Divida a folha ou exporte em PNG.'};
|
||||
// This pinned PDF.js build exposes the page's rotated view in points;
|
||||
// userUnit is separate and must scale both physical dimensions.
|
||||
const w=vp.width*unit*PT_CM, h=vp.height*unit*PT_CM;
|
||||
if(!Number.isFinite(w) || !Number.isFinite(h) || w<=0 || h<=0 || h>6000)
|
||||
return {rejected:true, reason:'O tamanho desta página PDF não é suportado. Divida a folha em partes menores.'};
|
||||
return {rejected:true, reason:'Esta página é grande demais. Divida a folha em partes menores.'};
|
||||
// Keep precise geometry for the fit and quote; the UI rounds only
|
||||
// when displaying dimensions.
|
||||
return {larg:+w.toFixed(3), alt:+h.toFixed(3),
|
||||
fonte:'página do PDF'+(unit!==1 ? ' · UserUnit '+unit : '')};
|
||||
}).then(res).catch(()=>res({rejected:true,
|
||||
reason:'Não conseguimos ler este PDF. Exporte-o novamente como PDF de uma página ou PNG.'}))
|
||||
reason:'Não conseguimos ler este PDF. Exporte de novo como PDF de uma página ou PNG.'}))
|
||||
.finally(()=>{ if(doc) doc.destroy().catch(()=>{}); });
|
||||
return;
|
||||
}
|
||||
@@ -463,7 +463,7 @@ function chipsDaFolha(a,aceito){
|
||||
return dpi+chip('ok','Fundo transparente')+
|
||||
(a.residuos? chip(aceito?'av':'er',a.residuos+' resíduo'+(a.residuos>1?'s':'')+(aceito?' aceito'+(a.residuos>1?'s':''):''))
|
||||
: chip('ok','Sem resíduos'))+
|
||||
(a.encostadas? chip('fix',a.encostadas+' peças coladas · separamos grátis') : chip('ok','Peças separadas'));
|
||||
(a.encostadas? chip('fix',a.encostadas+' peças coladas · separamos sem custo') : chip('ok','Peças separadas'));
|
||||
}
|
||||
// Resíduo e fundo chapado barram o pedido (Dropstar, 21/10/2026): o texto diz
|
||||
// quantos pontos, onde estão e o que fazer, sem "arquivo com problema". O
|
||||
@@ -471,20 +471,20 @@ function chipsDaFolha(a,aceito){
|
||||
function avisosDaFolha(a,nome,i,aceito,aceitavel=false){
|
||||
if(a.grande) return '';
|
||||
if(a.fundoChapado) return /\.jpe?g$/i.test(nome||'')
|
||||
? '<p class="avisoF"><b>JPG não tem fundo transparente.</b> O que parece branco na tela sai branco '+
|
||||
'no filme. Exporte a folha em PNG ou PDF, com fundo transparente, e envie de novo.</p>'
|
||||
: '<p class="avisoF"><b>O fundo da sua folha não é transparente.</b> O que parece branco na tela sai '+
|
||||
'branco no filme. Exporte a folha com fundo transparente, em PNG ou PDF, e envie de novo.</p>';
|
||||
? '<p class="avisoF"><b>JPG não tem fundo transparente.</b> O fundo sai branco no filme. '+
|
||||
'Exporte em PNG ou PDF com fundo transparente e envie de novo.</p>'
|
||||
: '<p class="avisoF"><b>O fundo da sua folha não é transparente.</b> Ele sai impresso no filme. '+
|
||||
'Exporte com fundo transparente, em PNG ou PDF, e envie de novo.</p>';
|
||||
if(!a.residuos) return '';
|
||||
const n=a.residuos, varios=n>1;
|
||||
const aceite='<label class="aceiteRes"><input type="checkbox" data-residuo="'+i+'"'+(aceito?' checked':'')+'>'+
|
||||
'<span>Esses pontos fazem parte da arte. Li e concordo em imprimir assim — eles podem sair no recorte.</span></label>';
|
||||
'<span>Esses pontos fazem parte da arte e podem sair impressos. Quero imprimir assim.</span></label>';
|
||||
if(aceitavel && aceito) return aceite;
|
||||
return '<p class="avisoF"><b>'+(varios?'Sobraram ':'Sobrou ')+n+(varios?' pontos':' ponto')+
|
||||
' de recorte na sua folha.</b> São restos da remoção de fundo: não aparecem na sua tela, mas a '+
|
||||
'impressora enxerga e imprime. Apague '+(varios?'os pontos':'o ponto')+' na ferramenta que você '+
|
||||
'usou e envie de novo. '+(varios?'Os círculos vermelhos na prévia mostram onde estão.':'O círculo vermelho na prévia mostra onde está.')+
|
||||
(aceitavel?' Se '+(varios?'os pontos são':'o ponto é')+' da própria arte, marque abaixo.</p>'+aceite:'</p>');
|
||||
' de recorte na sua folha.</b> Não aparece'+(varios?'m':'')+' na tela, mas sai'+(varios?'em':'')+' impresso'+(varios?'s':'')+'. '+
|
||||
(varios?'Os círculos vermelhos na prévia mostram onde estão':'O círculo vermelho na prévia mostra onde está')+
|
||||
': apague e envie de novo.'+
|
||||
(aceitavel?' Se '+(varios?'fazem':'faz')+' parte da arte, marque abaixo.</p>'+aceite:'</p>');
|
||||
}
|
||||
// Ajuste Fino (front 1a) and Ajuste Fino Redesenho (front 1b): under a Prumo
|
||||
// warning, the customer may hand this art to the designer. One service per
|
||||
@@ -511,21 +511,21 @@ function ajusteLinha(i,attr){
|
||||
const marcado=ajusteTudo || !!x.ajuste;
|
||||
linha+='<label class="aceiteRes ajusteArte"><input type="checkbox" '+attr+'="'+i+'"'+
|
||||
(marcado?' checked':'')+'>'+
|
||||
'<span>Quer que um designer resolva? <b>Ajuste Fino</b> — '+rs(TAXA_TRATAMENTO)+'</span></label>';
|
||||
'<span><b>Ajuste Fino</b>: nosso designer ajusta esta arte por '+rs(TAXA_TRATAMENTO)+'</span></label>';
|
||||
}
|
||||
if(redesenhado){
|
||||
const attrRedesenhado=folha?'data-redesenho':'data-redesenhoa';
|
||||
linha+='<label class="aceiteRes ajusteArte"><input type="checkbox" '+attrRedesenhado+'="'+i+'"'+
|
||||
(x.redesenho?' checked':'')+'>'+
|
||||
'<span>Precisa redesenhar ou vetorizar? <b>Ajuste Fino Redesenho</b> — '+rs(TAXA_REDESENHO)+
|
||||
' (com prévia, +48 h)</span></label>';
|
||||
'<span><b>Ajuste Fino Redesenho</b>: redesenhamos ou vetorizamos esta arte por '+rs(TAXA_REDESENHO)+
|
||||
', com prévia e 48 h a mais</span></label>';
|
||||
}
|
||||
return linha;
|
||||
}
|
||||
function detalhesDaFolha(a,i,aberto){
|
||||
const linhas = a.grande
|
||||
? ['Resolução '+a.dpi+' DPI, lida do arquivo',
|
||||
'Arquivo grande: peças, resíduos e fundo são conferidos pela equipe']
|
||||
'Arquivo grande: a equipe confere peças, resíduos e fundo']
|
||||
: [a.artes+' peça'+(a.artes===1?'':'s')+' · '+a.aproveitamento+'% da folha com arte',
|
||||
'Resolução '+a.dpi+' DPI · '+(a.fonteDpi==='imagens'? 'medida imagem por imagem dentro do PDF'
|
||||
: a.fonteDpi==='vetor'? 'arte vetorial, sem imagem embutida' : 'lida do arquivo'),
|
||||
@@ -568,20 +568,17 @@ function pintaFolha(){
|
||||
// Over 150 MB the browser cannot check a PDF: said before payment, as
|
||||
// for a file opened by hand (Dropstar, 2026-10-23).
|
||||
(x.pdfGrande? '<span class="chipSo">Conferência manual · sem conferência no site</span>'+
|
||||
'<p class="repTxt">Este PDF tem mais de 150 MB, e o site não confere arquivo desse tamanho: '+
|
||||
'resíduo de recorte, fundo e resolução ficam para a equipe, que abre antes de imprimir, e o '+
|
||||
'pedido pode voltar depois de pago. '+
|
||||
'Exportando em <b>PNG</b>, ou num PDF menor, a conferência sai aqui, antes de pagar.</p>' : '')+
|
||||
(suspeito? '<p class="avisoF"><b>Este PDF passa do tamanho que o formato comporta.</b> '+
|
||||
'A especificação para em 508 cm e o seu tem '+n1(x.med.alt)+' cm. '+
|
||||
'Ele abre certo só em quem o gerou — aqui vai precisar do Ajuste Fino. '+
|
||||
'Manda em <b>PNG ou TIFF</b>, ou divide em partes de até 5 m, que sai na hora.</p>':'')+
|
||||
(larga? '<p class="avisoF"><b>Esta folha não roda neste filme.</b> Ela tem '+n1(x.med.larg)+
|
||||
' cm de largura e o filme aqui tem '+n1(L)+' cm. Não dá para reduzir: '+
|
||||
'encolher a folha encolheria cada arte junto.'+
|
||||
'<p class="repTxt">O site não confere PDF acima de 150 MB: a equipe confere antes de imprimir, '+
|
||||
'e o pedido pode voltar depois de pago. '+
|
||||
'Em <b>PNG</b> ou num PDF menor, a conferência sai aqui, antes de pagar.</p>' : '')+
|
||||
(suspeito? '<p class="avisoF"><b>Este PDF passa de 508 cm, o limite do formato.</b> '+
|
||||
'O seu tem '+n1(x.med.alt)+' cm e só abre certo no programa que o gerou, então precisaria do Ajuste Fino. '+
|
||||
'Envie em <b>PNG ou TIFF</b>, ou divida em partes de até 5 m.</p>':'')+
|
||||
(larga? '<p class="avisoF"><b>Esta folha não cabe neste filme.</b> Ela tem '+n1(x.med.larg)+
|
||||
' cm de largura e o filme tem '+n1(L)+' cm. Reduzir a folha reduziria cada arte.'+
|
||||
(x.med.larg<=57.5
|
||||
? ' Ela cabe no <b>DTF têxtil de 57 cm</b> — troque de produto ali em cima.'
|
||||
: ' Remonte a folha em '+n1(L)+' cm e suba de novo.')+'</p>':'');
|
||||
? ' Ela cabe no <b>DTF têxtil de 57 cm</b>: troque de produto acima.'
|
||||
: ' Remonte a folha em '+n1(L)+' cm e envie de novo.')+'</p>':'');
|
||||
}else if(x.measurementError){
|
||||
medida='<span class="repPeso">'+escapeHTML(extDe(x.f.name))+' · '+fmt(x.f.size)+'</span>'+
|
||||
'<p class="avisoF"><b>Este arquivo não pode ser orçado.</b> '+escapeHTML(x.measurementError)+'</p>';
|
||||
@@ -589,13 +586,13 @@ function pintaFolha(){
|
||||
// Só a abertura manual muda o metro (TAXA_MANUAL); a nota não mexe no preço.
|
||||
const dif=(x.m>0)? TAXA_MANUAL*cobrar(x.m*(x.rep||1)) : 0;
|
||||
medida='<span class="chipSo">Conferência manual</span>'+
|
||||
'<p class="repTxt">O navegador não abre '+escapeHTML(extDe(x.f.name))+', então alguém da equipe '+
|
||||
'<p class="repTxt">O site não abre '+escapeHTML(extDe(x.f.name))+': a equipe '+
|
||||
'confere antes de imprimir'+
|
||||
(TAXA_MANUAL? ' e o metro sai a <b>'+rs(precoMetro()+TAXA_MANUAL)+'</b>, com <b>'+rs(TAXA_MANUAL)+
|
||||
'</b> pela abertura manual' : '')+'. '+
|
||||
'Exportando em <b>PNG ou PDF</b>, a conferência sai aqui, antes de pagar'+
|
||||
'Em <b>PNG ou PDF</b>, a conferência sai aqui, antes de pagar'+
|
||||
(TAXA_MANUAL? ', e o metro fica em <b>'+rs(precoMetro())+'</b>'+
|
||||
(dif>0.5? ' — <b>'+rs(dif)+' a menos</b> só nesta folha' : '') : '')+'.</p>';
|
||||
(dif>0.5? ' (<b>'+rs(dif)+' a menos</b> nesta folha)' : '') : '')+'.</p>';
|
||||
manual='<div class="campo"><label for="comp'+i+'">Comprimento</label>'+
|
||||
'<span class="un"><input type="number" id="comp'+i+'" min="0.5" max="60" step="0.01" data-comp="'+i+'" '+
|
||||
'placeholder="0,00" value="'+(x.m? x.m.toFixed(2):'')+'"><i>m</i></span></div>';
|
||||
@@ -605,8 +602,8 @@ function pintaFolha(){
|
||||
'<span class="progT">'+textoProgresso(x)+'</span>'
|
||||
: x.semAnalise
|
||||
? '<div class="progF"><b>Não conseguimos conferir esta folha.</b> '+escapeHTML(x.semAnalise)+
|
||||
'. A conferência será feita na sala. Para conferir a resolução aqui, exporte a mesma '+
|
||||
'folha em <b>PNG</b>.</div>'
|
||||
'. A equipe confere antes de imprimir. Para ver a resolução aqui, exporte '+
|
||||
'em <b>PNG</b>.</div>'
|
||||
: '';
|
||||
// A small thumbnail made once: the list is rebuilt on every change, and the
|
||||
// full preview of a file up to 150 MB would be re-parsed each time.
|
||||
@@ -620,7 +617,12 @@ function pintaFolha(){
|
||||
'<span class="passo"><button type="button" data-passo="-1" data-i="'+i+'" aria-label="Menos uma cópia">−</button>'+
|
||||
'<input type="number" id="repf'+i+'" min="1" max="200" data-repf="'+i+'" value="'+x.rep+'">'+
|
||||
'<button type="button" data-passo="1" data-i="'+i+'" aria-label="Mais uma cópia">+</button></span></div>'+
|
||||
'<div class="conta">'+(x.rep>1? x.rep+' × '+fmtM(x.m)+' m = ' : '')+'<b>'+fmtM(sub)+' m</b></div>' : '')+
|
||||
// A conta inteira, como é cobrada: o comprimento exato do arquivo e os
|
||||
// 8 mm entre as cópias (Marcus, 27/11/2026: "falta explicar melhor").
|
||||
'<div class="conta">'+(x.rep>1
|
||||
? x.rep+' × '+n1(x.m*100)+' cm + '+(x.rep-1)+(x.rep>2?' espaços':' espaço')+' de 8 mm = <b>'+
|
||||
n1(sub*100+(x.rep-1)*MARGEM_FOLHA_CM)+' cm</b>'
|
||||
: '<b>'+n1(x.m*100)+' cm</b>')+'</div>' : '')+
|
||||
'</div>' : '';
|
||||
return '<div class="rep" data-folha="'+i+'">'+
|
||||
'<div class="repTopo"><div class="miniF">'+mini+'</div><div class="repInfo">'+
|
||||
@@ -719,7 +721,7 @@ function pintaArtes(){
|
||||
}else if(a.decodeError){
|
||||
aviso='<p class="avisoF"><b>Não conseguimos ler esta imagem.</b> Exporte novamente em PNG.</p>';
|
||||
}else if(a.cm>larguraFilme()){
|
||||
aviso='<p class="avisoF"><b>Largura maior que o filme.</b> O filme aqui tem '+n1(larguraFilme())+' cm.</p>';
|
||||
aviso='<p class="avisoF"><b>Largura maior que o filme.</b> O filme tem '+n1(larguraFilme())+' cm.</p>';
|
||||
}else if(a.cm>0 && (a.src||a.semPrevia)){
|
||||
const dpi=Math.round(dpiDe(a));
|
||||
medida='<b>'+n1(a.cm)+' × '+n1(a.cm*propDe(a))+' cm</b>';
|
||||
@@ -733,8 +735,8 @@ function pintaArtes(){
|
||||
? '<div class="dica av">Pequena para '+n1(a.cm)+' cm. Em '+DPI_AVISA+' DPI ela sai com até '+
|
||||
n1(maxCm)+' cm, ou envie um arquivo maior.</div>'
|
||||
: sug
|
||||
? '<div class="dica">Com '+n1(sug.alvo)+' cm cabem '+sug.para+' por fileira e a folha encolhe '+
|
||||
n1(sug.cm)+' cm.<button data-usar="'+i+'" data-cm="'+sug.alvo+'">Usar '+n1(sug.alvo)+' cm</button></div>'
|
||||
? '<div class="dica">Com '+n1(sug.alvo)+' cm cabem '+sug.para+' por fileira e a folha fica '+
|
||||
n1(sug.cm)+' cm menor.<button data-usar="'+i+'" data-cm="'+sug.alvo+'">Usar '+n1(sug.alvo)+' cm</button></div>'
|
||||
: '';
|
||||
}
|
||||
// Item 4: the art's dots under 2 mm, with the same warning and acceptance as a sheet.
|
||||
|
||||
@@ -21,13 +21,13 @@ const residuosAceitos=()=>ehFolha()
|
||||
// no máximo 10% da tinta em traços de até 4 px.
|
||||
const mista=t=>!!(t && t.px<=4 && t.largos>=0.6 && t.finos<=0.10);
|
||||
const tracoDoArquivo=x=>ehFolha()?x.an&&x.an.traco:tracoDaArte(x);
|
||||
const MISTA_BRANCO='O branco por baixo precisa de um ajuste para traço fino e outro para área chapada. '+
|
||||
'Imprimindo assim, protegemos os traços e as áreas chapadas podem ganhar uma borda branca muito fina. ';
|
||||
const TEXTO_MISTA={
|
||||
arte:'Esta arte tem traços finos e áreas chapadas no mesmo arquivo. O branco por baixo precisa de ajuste diferente pra cada um. '+
|
||||
'Vamos proteger os traços finos; as áreas chapadas podem mostrar uma borda branca muito fina. Quer evitar? Suba esta arte em dois '+
|
||||
'arquivos, um com os traços finos e outro com as áreas chapadas; a gente monta cada um na folha certa. Pode dar alguns centímetros a mais de filme.',
|
||||
folha:'Esta folha tem traços finos e áreas chapadas no mesmo arquivo. O branco por baixo precisa de ajuste diferente pra cada um. '+
|
||||
'Vamos proteger os traços finos; as áreas chapadas podem mostrar uma borda branca muito fina. Quer evitar? Mande em duas folhas, '+
|
||||
'uma com os traços finos e outra com as áreas chapadas. Pode dar alguns centímetros a mais de filme.'};
|
||||
arte:MISTA_BRANCO+'Para evitar, suba em dois arquivos: um com os traços finos, outro com as áreas chapadas. '+
|
||||
'Montamos cada um na folha certa, com alguns centímetros a mais de filme.',
|
||||
folha:MISTA_BRANCO+'Para evitar, envie em duas folhas: uma com os traços finos, outra com as áreas chapadas. '+
|
||||
'Pode usar alguns centímetros a mais de filme.'};
|
||||
// O aviso não barra e aparece uma vez por arquivo, na folha pronta e na arte
|
||||
// avulsa: imprimir assim mesmo (C1), ou trocar o arquivo por dois.
|
||||
function perguntaMista(){
|
||||
@@ -117,9 +117,9 @@ function avaliar(){
|
||||
const ausentes=folhas.filter(f=>!f.an);
|
||||
const exts=[...new Set(ausentes.map(f=>extDe(f.f.name)))].join(', ');
|
||||
mostraNota([
|
||||
['av','Conferência manual · '+exts+' sem análise completa',
|
||||
ausentes.length+' de '+folhas.length+' folha(s) precisam de conferência manual'],
|
||||
['fix','Alguém abre seu arquivo','a conferência é feita na mão, na sala']
|
||||
['av','Conferência manual · '+exts,
|
||||
ausentes.length+' de '+folhas.length+' folha(s) sem conferência automática'],
|
||||
['fix','Conferimos manualmente','antes de imprimir']
|
||||
], 0, folhas.length>1? folhas.length+' folhas' : folhas[0].f.name,
|
||||
larguraFilme()+' cm · '+fmtM(metros)+' m');
|
||||
return {pronto:true};
|
||||
@@ -134,7 +134,7 @@ function avaliar(){
|
||||
ans.some(a=>a.fonteDpi==='imagens')
|
||||
? 'média por área das imagens dentro do PDF · pior em '+
|
||||
Math.min(...ans.map(a=>a.res? a.res.pior : a.dpi))+' DPI'
|
||||
: 'resolução do arquivo · arte ampliada antes de exportar não aparece aqui'],
|
||||
: 'resolução do arquivo · não mostra arte ampliada antes de exportar'],
|
||||
ans.some(a=>a.grande) ? ['ok','Arquivo grande','peças, resíduos e fundo conferidos pela equipe'] : null,
|
||||
ans.some(a=>a.grande) ? null : ['ok', soma('artes')+' peças na folha',
|
||||
Math.round(soma('aproveitamento')/ans.length)+'% da folha virou arte'],
|
||||
@@ -156,7 +156,7 @@ function avaliar(){
|
||||
const grande=artes.find(a=>a.lendo!=null);
|
||||
if(grande) return {pronto:false, falta:'Gerando a prévia das artes grandes… · '+segundosDesde(grande.analiseInicio)+' s'};
|
||||
if(artes.some(a=>a.decodeError || !(a.src||a.semPrevia) || !(a.px>0) || !(a.py>0)))
|
||||
return {pronto:false, falta:'Não conseguimos ler uma das imagens. Exporte-a novamente em PNG antes de continuar.'};
|
||||
return {pronto:false, falta:'Não conseguimos ler uma das imagens. Exporte de novo em PNG.'};
|
||||
if(artes.some(a=>!Number.isFinite(a.cm) || a.cm>larguraFilme()))
|
||||
return {pronto:false, falta:'A largura da arte precisa caber no filme de '+
|
||||
n1(larguraFilme())+' cm. Reduza a medida solicitada antes de continuar.'};
|
||||
@@ -178,7 +178,7 @@ function avaliar(){
|
||||
const notas=artes.map(a=>Math.max(6,Math.min(100,Math.round(dpiDe(a)/DPI_AVISA*100))));
|
||||
const media=Math.round(notas.reduce((s,n)=>s+n,0)/notas.length), pior=Math.min(...notas);
|
||||
mostraNota([
|
||||
['ok','Montagem por nossa conta','5 mm garantidos'],
|
||||
['ok','Montagem inclusa','5 mm entre as artes'],
|
||||
[cls(pior),'Resolução das artes',pior>=85?'todas em boa resolução':'há arte abaixo da resolução ideal']
|
||||
],media,artes.length+' arte'+(artes.length>1?'s':''),
|
||||
'folha montada por nós · '+fmtM(metros)+' m');
|
||||
@@ -197,8 +197,8 @@ function agendaAvaliacao(){
|
||||
if(!el) return;
|
||||
if(r.pronto){
|
||||
el.className='aoVivo pronto';
|
||||
el.innerHTML='<span class="pt2"></span><span><b>Conferência e preço calculados.</b> '+
|
||||
'Confira abaixo e feche o pedido.</span>';
|
||||
el.innerHTML='<span class="pt2"></span><span><b>Conferência e preço prontos.</b> '+
|
||||
'Confira abaixo e adicione ao carrinho.</span>';
|
||||
}else{
|
||||
el.className='aoVivo';
|
||||
el.innerHTML='<span class="pt2"></span><span>'+escapeHTML(r.falta)+'</span>';
|
||||
@@ -258,16 +258,16 @@ function ressalvaResolucao(){
|
||||
// e não existe aceite que destrave.
|
||||
if(recusadas.length){
|
||||
$('cienteTxt').innerHTML=
|
||||
'<p><b>A média da folha ficou abaixo de '+DPI_RECUSA+' DPI.</b> Nesse ponto a peça '+
|
||||
'sai serrilhada a ponto de não valer o filme. Reenvie maior ou reduza a largura.</p>'+
|
||||
'<div class="lista">'+recusadas.map(b=>'<div><b>'+escapeHTML(b.nome)+'</b> — '+
|
||||
'<p><b>A média da folha ficou abaixo de '+DPI_RECUSA+' DPI.</b> Não imprimimos assim: '+
|
||||
'sai serrilhado demais. Envie em resolução maior ou reduza a largura.</p>'+
|
||||
'<div class="lista">'+recusadas.map(b=>'<div><b>'+escapeHTML(b.nome)+'</b>: '+
|
||||
(b.quantas
|
||||
? 'média de '+b.dpi+' DPI · pior imagem em '+b.pior+' DPI · '+b.quantas+
|
||||
' de '+b.de+' imagens abaixo de '+DPI_RECUSA+' DPI, cobrindo '+b.parte+'% da arte'
|
||||
: b.dpi+' DPI em '+n1(b.cm)+' cm · precisa de '+
|
||||
Math.ceil(DPI_AVISA*b.cm/2.54)+' px de largura')+'</div>')
|
||||
.join('')+'</div>';
|
||||
$('cienteTit').textContent='Resolução abaixo do que imprimimos';
|
||||
$('cienteTit').textContent='Resolução baixa demais para imprimir';
|
||||
box.className='ciente on recusa'; chk.checked=false; $('qOk').disabled=true;
|
||||
return;
|
||||
}
|
||||
@@ -280,9 +280,9 @@ function ressalvaResolucao(){
|
||||
const media=Math.round(baixas.reduce((s,b)=>s+b.dpi,0)/baixas.length);
|
||||
$('cienteTxt').innerHTML=
|
||||
'<p><b>Parte da arte está abaixo de '+DPI_AVISA+' DPI.</b> Essas peças podem sair '+
|
||||
'com traço serrilhado, e isso não tem conserto depois de impresso. '+
|
||||
'serrilhadas, sem conserto depois de impressas. '+
|
||||
'O resto da folha sai normal.</p>'+
|
||||
'<div class="lista">'+baixas.map(b=>'<div><b>'+escapeHTML(b.nome)+'</b> — '+
|
||||
'<div class="lista">'+baixas.map(b=>'<div><b>'+escapeHTML(b.nome)+'</b>: '+
|
||||
(b.quantasAviso
|
||||
? 'média de '+b.dpi+' DPI · '+b.quantasAviso+' de '+b.de+' imagens abaixo de '+
|
||||
DPI_AVISA+' DPI, cobrindo '+b.parteAviso+'% da arte'+
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
aviso.style.cssText='position:fixed;left:12px;right:12px;bottom:12px;z-index:9999;padding:14px 16px;border-radius:10px;'+
|
||||
'background:#1f1f1f;color:#fff;font:15px/1.4 system-ui,sans-serif;display:flex;gap:12px;align-items:center;justify-content:space-between';
|
||||
const texto=document.createElement('span');
|
||||
texto.textContent='Uma parte do site não carregou, provavelmente a conexão oscilou. Atualize a página para continuar.';
|
||||
texto.textContent='Uma parte do site não carregou. Atualize a página para continuar.';
|
||||
const botao=document.createElement('button');
|
||||
botao.type='button'; botao.textContent='Atualizar';
|
||||
botao.style.cssText='flex:none;padding:8px 14px;border:0;border-radius:8px;background:#F28C1E;color:#111;font-weight:700';
|
||||
|
||||
@@ -36,18 +36,17 @@ function recusa(lista){
|
||||
el.style.display='block';
|
||||
if(lista.every(f=>/\.jpe?g$/i.test(f.name))){
|
||||
const disfarcados=lista.filter(f=>f.nomeEnviado).map(f=>f.nomeEnviado);
|
||||
el.innerHTML='<b>JPG não dá para enviar.</b> '+
|
||||
el.innerHTML='<b>JPG não entra.</b> '+
|
||||
(disfarcados.length ? escapeHTML(disfarcados.join(', '))+' é JPG, mesmo com outro nome. ' : '')+
|
||||
'JPG não tem fundo transparente, e o branco do fundo '+
|
||||
'sai no filme. Exporte em '+(ehFolha()?'PNG ou PDF':'PNG')+' com fundo transparente e envie de novo.';
|
||||
'JPG não tem fundo transparente, e o fundo '+
|
||||
'sai branco no filme. Exporte em '+(ehFolha()?'PNG ou PDF':'PNG')+' com fundo transparente e envie de novo.';
|
||||
return;
|
||||
}
|
||||
el.innerHTML = ehFolha()
|
||||
? '<b>'+exts+' não dá para enviar aqui.</b> A folha pronta aceita PNG, PDF, TIFF, '+
|
||||
? '<b>'+exts+' não entra aqui.</b> A folha pronta aceita PNG, PDF, TIFF, '+
|
||||
'PSD, AI e CDR, com fundo transparente.'
|
||||
: '<b>'+exts+' não dá para enviar aqui.</b> Artes avulsas precisam de PNG com '+
|
||||
'fundo transparente — é o que a montagem enxerga para encaixar. '+
|
||||
'Se o seu arquivo é CDR, AI ou PSD, exporte em PNG ou use <b>Arquivo por metro</b>.';
|
||||
: '<b>'+exts+' não entra aqui.</b> Artes avulsas só aceitam PNG com '+
|
||||
'fundo transparente. Para CDR, AI ou PSD, exporte em PNG ou use <b>Arquivo por metro</b>.';
|
||||
}
|
||||
const Z=$('zona'), I=$('inp');
|
||||
Z.addEventListener('click',()=>I.click());
|
||||
@@ -261,7 +260,7 @@ async function sel(fs){
|
||||
rasterizarPdf(x.f, md.larg, md.alt, true).then(r=>{
|
||||
if(r && r.erro){
|
||||
x.semAnalise = r.erro + (r.semWorker
|
||||
? ' · este navegador não deixa o leitor rodar em segundo plano'
|
||||
? ' · o navegador bloqueou a leitura em segundo plano'
|
||||
: '');
|
||||
}
|
||||
if(r && r.tela && r.mapa){
|
||||
|
||||
@@ -3,7 +3,7 @@ const VIDEOS = [
|
||||
{id: 'subindo', title: 'Subindo a arte pelo celular',
|
||||
desc: 'Do primeiro toque ao preço, sem instalar nada.', product: null,
|
||||
src: null, captions: null},
|
||||
{id: 'nota', title: 'O que é a nota da arte — e o que ela não é',
|
||||
{id: 'nota', title: 'O que a nota da arte mostra',
|
||||
desc: 'A nota explica o arquivo; ela não muda o preço.', product: 'file',
|
||||
src: null, captions: null},
|
||||
{id: 'png', title: 'Por que PNG com fundo transparente',
|
||||
|
||||
@@ -81,9 +81,17 @@ async function sendUpload(file, {api, prefix='/uploads', startPath=prefix, progr
|
||||
signal?.addEventListener('abort',()=>xhr.abort(),{once:true});
|
||||
xhr.send(body);
|
||||
});
|
||||
// A file taken off the page while it went gives its place back at once: a
|
||||
// reservation it left would hold the pending cap for 20 minutes, and a
|
||||
// customer switching products filled it (Sentry DTF-WEB-14, 29/11).
|
||||
const giveBack=()=>{
|
||||
fetch('/api'+prefix+'/'+id,{method:'DELETE',credentials:'same-origin'}).catch(()=>{});
|
||||
if(resume)localStorage.removeItem(key);
|
||||
};
|
||||
if(signal?.aborted){giveBack();throw cancelled();}
|
||||
for(let offset=0,part=1;offset<file.size;offset+=size,part++){
|
||||
if(done.has(part))continue;
|
||||
if(signal?.aborted)throw cancelled();
|
||||
if(signal?.aborted){giveBack();throw cancelled();}
|
||||
progress('Enviando '+file.name+' · parte '+part+'/'+Math.ceil(file.size/size));
|
||||
// A part the network dropped goes again twice, on a fresh link, before
|
||||
// the customer is asked to resume (DTF-WEB-13).
|
||||
@@ -91,7 +99,8 @@ async function sendUpload(file, {api, prefix='/uploads', startPath=prefix, progr
|
||||
const signed=await withRetry(options=>api(prefix+'/'+id+'/parts/'+part,{},options));
|
||||
try{await put(signed.url,file.slice(offset,offset+size));break;}
|
||||
catch(error){
|
||||
if(error?.name==='AbortError'||attempt>=2)throw error;
|
||||
if(error?.name==='AbortError'){giveBack();throw error;}
|
||||
if(attempt>=2)throw error;
|
||||
await new Promise(resolve=>setTimeout(resolve,(attempt+1)*3000));
|
||||
}
|
||||
}
|
||||
@@ -104,6 +113,10 @@ async function sendUpload(file, {api, prefix='/uploads', startPath=prefix, progr
|
||||
window.dtfUpload = async (file, options) => {
|
||||
if(options?.signal?.aborted)throw new DOMException('Envio cancelado.','AbortError');
|
||||
await uploadSlot();
|
||||
try{return await sendUpload(file, options);}
|
||||
try{
|
||||
// Taken off the page while it waited for a place: no reservation at all.
|
||||
if(options?.signal?.aborted)throw new DOMException('Envio cancelado.','AbortError');
|
||||
return await sendUpload(file, options);
|
||||
}
|
||||
finally{releaseUploadSlot();}
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user