Compare commits
42 Commits
ba85168c09
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c2ffe08db5 | ||
|
|
2c0dd72098 | ||
|
|
fc9e6d2681 | ||
|
|
b18f6e1312 | ||
|
|
16cc01eef5 | ||
|
|
ca1ba677ce | ||
|
|
41e905555b | ||
|
|
ea05ba6a31 | ||
|
|
885d211ae2 | ||
|
|
1a35dea7a5 | ||
|
|
07e56eaa7c | ||
|
|
3428ff68be | ||
|
|
5671235681 | ||
|
|
21858b5764 | ||
|
|
22239f21d8 | ||
|
|
35d508e561 | ||
|
|
c2aa1d4937 | ||
|
|
030b66c697 | ||
|
|
28c10aabf6 | ||
|
|
9e0d33ef47 | ||
|
|
19eb37bdd9 | ||
|
|
a275a77896 | ||
|
|
45c5493a4c | ||
|
|
aeb43500a7 | ||
|
|
857eea3379 | ||
|
|
f739c9d4e4 | ||
|
|
7fc091a1bd | ||
|
|
7e33e6fb1d | ||
|
|
37d747697a | ||
|
|
c4f8ba1b70 | ||
|
|
4283c93526 | ||
|
|
eb7a92bb89 | ||
|
|
9fc4d4e906 | ||
|
|
6ec0ea31a6 | ||
|
|
5f84db708c | ||
|
|
2ff11688bc | ||
|
|
a652d734ea | ||
|
|
48d8b2f434 | ||
|
|
4a1994bd06 | ||
|
|
bb6fb14b1a | ||
|
|
6970434e5d | ||
|
|
7454f6b840 |
@@ -88,7 +88,7 @@ jobs:
|
|||||||
# one a developer exercises on localhost.
|
# one a developer exercises on localhost.
|
||||||
- name: API and workflow regressions
|
- name: API and workflow regressions
|
||||||
run: |
|
run: |
|
||||||
for suite in smoke_test workflow_test security_test upload_limits_test scanning_test payment_test unpaid_test quote_pagination_test kanban_test label_test reconcile_test order_actions_test print_file_test users_test stage_limits_test mail_test thumbnail_backfill_test launch_reset_test finished_order_test machine_pull_test site_video_test treatment_gate_test review_media_test machine_log_test machine_stats_test site_admin_test coupons_test stamps_test grade_rules_test; do
|
for suite in smoke_test workflow_test security_test upload_limits_test scanning_test payment_test unpaid_test quote_pagination_test kanban_test label_test reconcile_test order_actions_test print_file_test users_test stage_limits_test mail_test thumbnail_backfill_test launch_reset_test finished_order_test machine_pull_test machine_transfer_test site_video_test treatment_gate_test review_media_test redesign_preview_test machine_log_test machine_stats_test site_admin_test coupons_test stamps_test grade_rules_test saved_sheets_test; do
|
||||||
echo "--- $suite"
|
echo "--- $suite"
|
||||||
$COMPOSE exec -T \
|
$COMPOSE exec -T \
|
||||||
-e SITE_BASE_URL=http://site \
|
-e SITE_BASE_URL=http://site \
|
||||||
@@ -101,7 +101,7 @@ jobs:
|
|||||||
# the generator's geometry. The provider suites use a fake transport: they
|
# the generator's geometry. The provider suites use a fake transport: they
|
||||||
# prove the documented contract, not the integration.
|
# prove the documented contract, not the integration.
|
||||||
- name: Print-file geometry and provider adapters
|
- name: Print-file geometry and provider adapters
|
||||||
run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_printpng tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_payment_messages tests.test_jadlog tests.test_correios tests.test_quote_review tests.test_moves tests.test_large_files tests.test_grade_check tests.test_schema tests.test_customer_document tests.test_mail_html tests.test_layout_rules tests.test_proof_cut tests.test_proof_render tests.test_sheet_trim tests.test_one_machine tests.test_profiles tests.test_sheet_gap tests.test_reprint tests.test_proof_parts tests.test_prumo tests.test_speed tests.test_printpng_validate tests.test_machine_log tests.test_machine_stats tests.test_label tests.test_observability tests.test_worker_drain tests.test_db_outage tests.test_health -v
|
run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_printpng tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_payment_messages tests.test_jadlog tests.test_correios tests.test_quote_review tests.test_moves tests.test_large_files tests.test_grade_check tests.test_schema tests.test_customer_document tests.test_mail_html tests.test_layout_rules tests.test_proof_cut tests.test_proof_render tests.test_sheet_trim tests.test_one_machine tests.test_profiles tests.test_sheet_gap tests.test_reprint tests.test_proof_parts tests.test_prumo tests.test_speed tests.test_printpng_validate tests.test_machine_log tests.test_machine_stats tests.test_label tests.test_observability tests.test_worker_drain tests.test_db_outage tests.test_health tests.test_saved_size -v
|
||||||
|
|
||||||
- name: Runtime and retention regressions
|
- name: Runtime and retention regressions
|
||||||
run: |
|
run: |
|
||||||
|
|||||||
@@ -232,7 +232,7 @@ class ObjectStorage(Protocol):
|
|||||||
def part_url(self, key: str, upload_id: str, part: int, size: int) -> str: ...
|
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 complete(self, key: str, upload_id: str, parts: list): ...
|
||||||
def size(self, key: str) -> int: ...
|
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 fetch(self, key: str, path: str): ...
|
||||||
def store(self, key: str, path: str, content_type: str): ...
|
def store(self, key: str, path: str, content_type: str): ...
|
||||||
def health(self): ...
|
def health(self): ...
|
||||||
@@ -299,12 +299,12 @@ class LocalS3Storage:
|
|||||||
"""Upload a file the service generated itself, such as a print file."""
|
"""Upload a file the service generated itself, such as a print file."""
|
||||||
self.patient.upload_file(path, self.bucket, key, ExtraArgs={'ContentType': content_type})
|
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
|
from urllib.parse import quote
|
||||||
return self.public.generate_presigned_url('get_object', Params={
|
return self.public.generate_presigned_url('get_object', Params={
|
||||||
'Bucket': self.bucket, 'Key': key,
|
'Bucket': self.bucket, 'Key': key,
|
||||||
'ResponseContentDisposition': "attachment; filename*=UTF-8''" + quote(name, safe=''),
|
'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):
|
def view(self, key, content_type, expires=3600):
|
||||||
"""A link to show an object in the page, not download it: the Kanban's
|
"""A link to show an object in the page, not download it: the Kanban's
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ from uuid import UUID
|
|||||||
from fastapi import APIRouter, Depends, HTTPException, Query, Response
|
from fastapi import APIRouter, Depends, HTTPException, Query, Response
|
||||||
from pydantic import Field
|
from pydantic import Field
|
||||||
|
|
||||||
from ... import hotfolder, machines, mail, payments, prumo, receipt, reviews
|
from ... import hotfolder, machine_log, machines, mail, payments, prumo, receipt, reviews
|
||||||
from ...cart_pricing import designer_hours
|
from ...cart_pricing import designer_hours
|
||||||
from ...core import db
|
from ...core import db
|
||||||
from ...core.auth import audit, can, operator
|
from ...core.auth import audit, can, operator
|
||||||
@@ -137,7 +137,15 @@ def assign_late(c, orders, limits):
|
|||||||
if not since and order['state'] == 'fin':
|
if not since and order['state'] == 'fin':
|
||||||
since = order.get('finished_at')
|
since = order.get('finished_at')
|
||||||
since = since or order['created_at']
|
since = since or order['created_at']
|
||||||
hours = max(0.0, (now - since).total_seconds() / 3600)
|
hours = (now - since).total_seconds() / 3600
|
||||||
|
# A preview waiting for the customer stops the stage clock: the time
|
||||||
|
# between sending it and its answer is left out (D2).
|
||||||
|
for preview in order.get('previews') or []:
|
||||||
|
if preview['sent_at'] < since:
|
||||||
|
continue
|
||||||
|
ended = preview['decided_at'] or now
|
||||||
|
hours -= max(0.0, (ended - preview['sent_at']).total_seconds() / 3600)
|
||||||
|
hours = max(0.0, hours)
|
||||||
limit_hours = float(limit['hours'])
|
limit_hours = float(limit['hours'])
|
||||||
# Paid designer work gives Art received its extra hours to prepare the
|
# Paid designer work gives Art received its extra hours to prepare the
|
||||||
# art: 48 h for a Redesenho, 24 h for the basic Ajuste Fino.
|
# art: 48 h for a Redesenho, 24 h for the basic Ajuste Fino.
|
||||||
@@ -207,8 +215,17 @@ def with_print_files(c, orders):
|
|||||||
# Why each order was last sent to correction, for the notice to the customer.
|
# Why each order was last sent to correction, for the notice to the customer.
|
||||||
reasons = {row['order_id']: row['reason'] for row in c.execute('''SELECT DISTINCT ON (order_id) order_id,reason
|
reasons = {row['order_id']: row['reason'] for row in c.execute('''SELECT DISTINCT ON (order_id) order_id,reason
|
||||||
FROM dtf_local.movements WHERE order_id=ANY(%s) AND to_state='cor' ORDER BY order_id,id DESC''', (ids,)).fetchall()}
|
FROM dtf_local.movements WHERE order_id=ANY(%s) AND to_state='cor' ORDER BY order_id,id DESC''', (ids,)).fetchall()}
|
||||||
|
# A redesign's previews, oldest first: the card shows them and the stage
|
||||||
|
# clock leaves out the time a preview waited for the customer (D2).
|
||||||
|
previews = c.execute('''SELECT order_id,number,sent_at,sent_by,decided_at,result,reason,decided_by
|
||||||
|
FROM dtf_local.redesign_previews WHERE order_id=ANY(%s) ORDER BY order_id,number''', (ids,)).fetchall()
|
||||||
|
# Each order's machine transfers, oldest first (Rodada 5, D4).
|
||||||
|
transfers = c.execute('''SELECT order_id,from_name,to_name,reason,resumed_from,delete_prt,created_by,created_at
|
||||||
|
FROM dtf_local.machine_transfers WHERE order_id=ANY(%s) ORDER BY id''', (ids,)).fetchall()
|
||||||
# Where a printing order's files are in its machine's hot folder (item 10).
|
# Where a printing order's files are in its machine's hot folder (item 10).
|
||||||
hot = hotfolder.progress(c, [o['id'] for o in orders if o['state'] == 'imp'])
|
hot = hotfolder.progress(c, [o['id'] for o in orders if o['state'] == 'imp'])
|
||||||
|
# Each printing order's parts, for the transfer dialog's "Recomeçar da parte" (D4).
|
||||||
|
hot_parts = hotfolder.last_round(c, [o['id'] for o in orders if o['state'] == 'imp'])
|
||||||
# Orders the machine already printed: a reprint chooses which items go
|
# Orders the machine already printed: a reprint chooses which items go
|
||||||
# again (#105), the ones whose final changed suggested.
|
# again (#105), the ones whose final changed suggested.
|
||||||
taken = hotfolder.printed(c, [o['id'] for o in orders if o['state'] in ('rec', 'tra', 'cor')])
|
taken = hotfolder.printed(c, [o['id'] for o in orders if o['state'] in ('rec', 'tra', 'cor')])
|
||||||
@@ -218,6 +235,11 @@ def with_print_files(c, orders):
|
|||||||
WHERE parent_id=ANY(%s) AND cancelled_at IS NULL ORDER BY parent_id, created_at DESC''', (ids,)).fetchall()}
|
WHERE parent_id=ANY(%s) AND cancelled_at IS NULL ORDER BY parent_id, created_at DESC''', (ids,)).fetchall()}
|
||||||
parents = {r['id']: r for r in c.execute('SELECT id,number,state FROM dtf_local.orders WHERE id=ANY(%s)',
|
parents = {r['id']: r for r in c.execute('SELECT id,number,state FROM dtf_local.orders WHERE id=ANY(%s)',
|
||||||
([o['parent_id'] for o in orders if o.get('parent_id')],)).fetchall()}
|
([o['parent_id'] for o in orders if o.get('parent_id')],)).fetchall()}
|
||||||
|
# How each Site order was paid, Pix or card: its quote's approved attempt,
|
||||||
|
# the one Tiny is told about too (app/payments.py).
|
||||||
|
paid_with = {r['quote_id']: r['method'] for r in c.execute('''SELECT DISTINCT ON (quote_id) quote_id,method
|
||||||
|
FROM dtf_local.payment_intents WHERE quote_id=ANY(%s) AND status='approved' ORDER BY quote_id,created_at DESC''',
|
||||||
|
([o['quote_id'] for o in orders if o.get('quote_id')],)).fetchall()}
|
||||||
# Every order's review photos and videos, in one query like the print files.
|
# Every order's review photos and videos, in one query like the print files.
|
||||||
review_rows = reviews.by_order(c, ids)
|
review_rows = reviews.by_order(c, ids)
|
||||||
# The proof card's go on its order too: an answered card leaves the board,
|
# The proof card's go on its order too: an answered card leaves the board,
|
||||||
@@ -226,6 +248,8 @@ def with_print_files(c, orders):
|
|||||||
proof_reviews = reviews.by_order(c, [r['id'] for r in children.values()])
|
proof_reviews = reviews.by_order(c, [r['id'] for r in children.values()])
|
||||||
for order in orders:
|
for order in orders:
|
||||||
order['hot'] = hot.get(order['id'])
|
order['hot'] = hot.get(order['id'])
|
||||||
|
order['hot_parts'] = hot_parts.get(order['id'], [])
|
||||||
|
order['paid_with'] = paid_with.get(order.get('quote_id'))
|
||||||
order['reviews'] = review_rows.get(str(order['id']), [])
|
order['reviews'] = review_rows.get(str(order['id']), [])
|
||||||
child = children.get(order['id'])
|
child = children.get(order['id'])
|
||||||
# Its machine: an order prints where its approved proof did (Dropstar, 2026-11-05).
|
# Its machine: an order prints where its approved proof did (Dropstar, 2026-11-05).
|
||||||
@@ -237,6 +261,13 @@ def with_print_files(c, orders):
|
|||||||
order['proof_parent'] = parent and {'id': parent['id'], 'number': parent['number'], 'state': parent['state']}
|
order['proof_parent'] = parent and {'id': parent['id'], 'number': parent['number'], 'state': parent['state']}
|
||||||
order['correction_reason'] = reasons.get(order['id']) if order['state'] == 'cor' else None
|
order['correction_reason'] = reasons.get(order['id']) if order['state'] == 'cor' else None
|
||||||
order['print_files'] = [row for row in generated if row['order_id'] == order['id']]
|
order['print_files'] = [row for row in generated if row['order_id'] == order['id']]
|
||||||
|
# A proof card bills nothing (0 m) but prints film: the board shows the
|
||||||
|
# film of each sheet, the same measure as Números (machine_log).
|
||||||
|
if (order.get('snapshot') or {}).get('proof_of'):
|
||||||
|
windows = {str(row['item_index']): row['detail']['proof_windows'] for row in order['print_files']
|
||||||
|
if isinstance(row.get('detail'), dict) and row['detail'].get('proof_windows')}
|
||||||
|
order['proof_film_cm'] = {str(index): float(machine_log.film_metres(order['snapshot'], {index}, windows) * 100)
|
||||||
|
for index in range(len(order['snapshot'].get('items') or []))}
|
||||||
order['prumo'] = prumo.report(order, uploads)
|
order['prumo'] = prumo.report(order, uploads)
|
||||||
approved = [row for row in finals if row['order_id'] == order['id']]
|
approved = [row for row in finals if row['order_id'] == order['id']]
|
||||||
order['final_items'] = sorted({row['item_index'] for row in approved})
|
order['final_items'] = sorted({row['item_index'] for row in approved})
|
||||||
@@ -252,6 +283,12 @@ def with_print_files(c, orders):
|
|||||||
order['corrections'] = [{k: row[k] for k in ('item_index', 'upload_id', 'name', 'expired')}
|
order['corrections'] = [{k: row[k] for k in ('item_index', 'upload_id', 'name', 'expired')}
|
||||||
for row in fixes if row['order_id'] == order['id']]
|
for row in fixes if row['order_id'] == order['id']]
|
||||||
order['reworks'] = [row for row in reworks if row['order_id'] == order['id']]
|
order['reworks'] = [row for row in reworks if row['order_id'] == order['id']]
|
||||||
|
order['previews'] = [{k: row[k] for k in ('number', 'sent_at', 'sent_by', 'decided_at', 'result',
|
||||||
|
'reason', 'decided_by')}
|
||||||
|
for row in previews if row['order_id'] == order['id']]
|
||||||
|
order['transfers'] = [{k: row[k] for k in ('from_name', 'to_name', 'reason', 'resumed_from',
|
||||||
|
'delete_prt', 'created_by', 'created_at')}
|
||||||
|
for row in transfers if row['order_id'] == order['id']]
|
||||||
return assign_machines(c, orders)
|
return assign_machines(c, orders)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -16,6 +16,10 @@ from ...scanning import require_clean
|
|||||||
from .common import FINAL_OK
|
from .common import FINAL_OK
|
||||||
|
|
||||||
router = APIRouter()
|
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):
|
def named_files(rows):
|
||||||
"""Each file named after its order and item, so a folder of them stays
|
"""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)
|
names.add(name)
|
||||||
files.append({'order': str(row['order_id']), 'state': row['state'], 'number': row['number'],
|
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']),
|
'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
|
return files
|
||||||
|
|
||||||
|
|
||||||
@@ -163,7 +167,7 @@ def queue_hot(user=Depends(can('print'))):
|
|||||||
watched = hotfolder.watched(c)
|
watched = hotfolder.watched(c)
|
||||||
return {'folder': hotfolder.PRINTING_FOLDER,
|
return {'folder': hotfolder.PRINTING_FOLDER,
|
||||||
'write': [{'id': r['id'], 'order': str(r['order_id']), 'folder': r['folder'], 'name': r['name'],
|
'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']}
|
'watch': [{'id': r['id'], 'order': str(r['order_id']), 'folder': r['folder'], 'name': r['name']}
|
||||||
for r in watched if r['state'] == 'written'],
|
for r in watched if r['state'] == 'written'],
|
||||||
'withdraw': [{'id': r['id'], 'order': str(r['order_id']), 'folder': r['folder'], 'name': r['name']}
|
'withdraw': [{'id': r['id'], 'order': str(r['order_id']), 'folder': r['folder'], 'name': r['name']}
|
||||||
|
|||||||
@@ -50,7 +50,11 @@ 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()]
|
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'):
|
for table in ('movements', 'order_files', 'print_files'):
|
||||||
c.execute(f'DELETE FROM dtf_local.{table} WHERE order_id=ANY(%s)', ([uid] + cards,))
|
c.execute(f'DELETE FROM dtf_local.{table} WHERE order_id=ANY(%s)', ([uid] + cards,))
|
||||||
c.execute('DELETE FROM dtf_local.outbox WHERE event_key LIKE %s', (f'{uid}:%',))
|
# 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,))
|
c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (uid,))
|
||||||
if not test:
|
if not test:
|
||||||
c.execute('UPDATE dtf_local.quotes SET discarded_at=COALESCE(discarded_at,now()), discarded_by=COALESCE(discarded_by,%s) WHERE id=%s',
|
c.execute('UPDATE dtf_local.quotes SET discarded_at=COALESCE(discarded_at,now()), discarded_by=COALESCE(discarded_by,%s) WHERE id=%s',
|
||||||
@@ -73,6 +77,14 @@ def cancel_order(uid: UUID, body: Resolution, user=Depends(can('cancel'))):
|
|||||||
if not row:
|
if not row:
|
||||||
raise HTTPException(404, 'Pedido não encontrado ou já cancelado.')
|
raise HTTPException(404, 'Pedido não encontrado ou já cancelado.')
|
||||||
hotfolder.stop(c, uid)
|
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):
|
if payments.in_tiny(row):
|
||||||
sale = c.execute("SELECT receipt FROM dtf_local.outbox WHERE event_key=%s AND delivered_at IS NOT NULL",
|
sale = c.execute("SELECT receipt FROM dtf_local.outbox WHERE event_key=%s AND delivered_at IS NOT NULL",
|
||||||
(f'{uid}:paid:tiny',)).fetchone()
|
(f'{uid}:paid:tiny',)).fetchone()
|
||||||
@@ -121,6 +133,56 @@ def choose_machine(uid: UUID, body: MachineChoice, request: Request, user=Depend
|
|||||||
return {'ok': True}
|
return {'ok': True}
|
||||||
|
|
||||||
|
|
||||||
|
class MachineTransfer(StrictModel):
|
||||||
|
machine_id: UUID
|
||||||
|
reason: str = Field(max_length=500)
|
||||||
|
# The part of the last round the new machine resumes from (Marcus,
|
||||||
|
# 2026-12-01): required once the old machine has taken any part.
|
||||||
|
resume_from: int | None = Field(default=None, ge=1, le=10000, strict=True)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/orders/{uid}/transfer')
|
||||||
|
def transfer_machine(uid: UUID, body: MachineTransfer, user=Depends(can('manage'))):
|
||||||
|
"""A card already in Imprimindo changes machine (Rodada 5, D4), by Gestão
|
||||||
|
or an administrator and with its reason: the old machine keeps what Flexi
|
||||||
|
already took, and the new one starts from the part it was ripping."""
|
||||||
|
reason = ' '.join(body.reason.split())
|
||||||
|
with db.connect() as c:
|
||||||
|
current = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
|
||||||
|
if not current:
|
||||||
|
raise HTTPException(404, 'Pedido não encontrado.')
|
||||||
|
if current['cancelled_at'] or current['state'] != 'imp':
|
||||||
|
raise HTTPException(409, 'Só um pedido em Imprimindo muda de máquina por aqui.')
|
||||||
|
if len(reason) < 3:
|
||||||
|
raise HTTPException(422, 'Escreva o motivo da transferência.')
|
||||||
|
target = c.execute('SELECT name,products,active FROM dtf_local.machines WHERE id=%s',
|
||||||
|
(body.machine_id,)).fetchone()
|
||||||
|
if not target or not target['active']:
|
||||||
|
raise HTTPException(404, 'Máquina não encontrada ou desativada.')
|
||||||
|
if body.machine_id == current['machine_id']:
|
||||||
|
raise HTTPException(409, 'O pedido já está nessa máquina.')
|
||||||
|
if machines.product_family(current) not in target['products']:
|
||||||
|
raise HTTPException(409, f"A {target['name']} não imprime este produto.")
|
||||||
|
from_name = (c.execute('SELECT name FROM dtf_local.machines WHERE id=%s',
|
||||||
|
(current['machine_id'],)).fetchone() if current['machine_id'] else None)
|
||||||
|
from_name = from_name and from_name['name']
|
||||||
|
parts = hotfolder.last_round(c, [uid]).get(uid, [])
|
||||||
|
if any(part['state'] == 'consumed' for part in parts) and not body.resume_from:
|
||||||
|
raise HTTPException(422, 'Escolha de qual parte a nova máquina recomeça.')
|
||||||
|
if body.resume_from and body.resume_from not in {part['seq'] for part in parts}:
|
||||||
|
raise HTTPException(422, 'Essa parte não existe neste pedido.')
|
||||||
|
resumed, delete_prt = hotfolder.transfer(c, uid, body.resume_from)
|
||||||
|
c.execute('UPDATE dtf_local.orders SET machine_id=%s, machine_chosen=true WHERE id=%s',
|
||||||
|
(body.machine_id, uid))
|
||||||
|
c.execute('''INSERT INTO dtf_local.machine_transfers(order_id,from_machine,to_machine,from_name,to_name,
|
||||||
|
reason,resumed_from,delete_prt,created_by) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s)''',
|
||||||
|
(uid, current['machine_id'], body.machine_id, from_name, target['name'], reason, resumed,
|
||||||
|
delete_prt, user))
|
||||||
|
audit('order_machine_transferred', order=current['number'], from_machine=str(current['machine_id'] or ''),
|
||||||
|
to_machine=str(body.machine_id), operator=user)
|
||||||
|
return {'ok': True, 'delete_prt': delete_prt}
|
||||||
|
|
||||||
|
|
||||||
@router.post('/api/operator/orders/{uid}/contraction')
|
@router.post('/api/operator/orders/{uid}/contraction')
|
||||||
def choose_contraction(uid: UUID, body: Contraction, user=Depends(can('produce'))):
|
def choose_contraction(uid: UUID, body: Contraction, user=Depends(can('produce'))):
|
||||||
"""The contraction class of an item (Dropstar, 2026-10-30): the browser's
|
"""The contraction class of an item (Dropstar, 2026-10-30): the browser's
|
||||||
@@ -179,6 +241,46 @@ def contact(uid: UUID, body: ContactWait, user=Depends(can('produce'))):
|
|||||||
return {'ok': True}
|
return {'ok': True}
|
||||||
|
|
||||||
|
|
||||||
|
class RedesignPreview(StrictModel):
|
||||||
|
action: Literal['sent', 'approved', 'rejected']
|
||||||
|
reason: str = Field(default='', max_length=500)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/orders/{uid}/redesign-preview')
|
||||||
|
def redesign_preview(uid: UUID, body: RedesignPreview, user=Depends(can('produce'))):
|
||||||
|
"""A redesign's preview: sent to the customer, then approved or rejected.
|
||||||
|
One preview waits at a time; the stage clock stops while it waits."""
|
||||||
|
with db.connect() as c:
|
||||||
|
row = c.execute('SELECT id,number,snapshot,state,cancelled_at FROM dtf_local.orders WHERE id=%s FOR UPDATE',
|
||||||
|
(uid,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(404, 'Pedido não encontrado.')
|
||||||
|
if not (row['snapshot'] or {}).get('redesign'):
|
||||||
|
raise HTTPException(409, 'Este pedido não tem Ajuste Fino Redesenho.')
|
||||||
|
if row['cancelled_at'] or row['state'] != 'rec':
|
||||||
|
raise HTTPException(409, 'A prévia só vale com o pedido em Arte recebida.')
|
||||||
|
prior = c.execute('''SELECT id,number,decided_at,result FROM dtf_local.redesign_previews
|
||||||
|
WHERE order_id=%s ORDER BY number''', (uid,)).fetchall()
|
||||||
|
if body.action == 'sent':
|
||||||
|
if any(preview['decided_at'] is None for preview in prior):
|
||||||
|
raise HTTPException(409, 'Já há uma prévia com o cliente.')
|
||||||
|
if any(preview['result'] == 'approved' for preview in prior):
|
||||||
|
raise HTTPException(409, 'A prévia já foi aprovada.')
|
||||||
|
number = max((preview['number'] for preview in prior), default=0) + 1
|
||||||
|
c.execute('''INSERT INTO dtf_local.redesign_previews(order_id,number,sent_by)
|
||||||
|
VALUES(%s,%s,%s)''', (uid, number, user))
|
||||||
|
else:
|
||||||
|
opened = next((preview for preview in prior if preview['decided_at'] is None), None)
|
||||||
|
if not opened:
|
||||||
|
raise HTTPException(409, 'Nenhuma prévia com o cliente.')
|
||||||
|
reason = ' '.join(body.reason.split()) if body.action == 'rejected' else ''
|
||||||
|
c.execute('''UPDATE dtf_local.redesign_previews SET decided_at=now(),result=%s,reason=%s,decided_by=%s
|
||||||
|
WHERE id=%s''', (body.action, reason, user, opened['id']))
|
||||||
|
number = opened['number']
|
||||||
|
audit('redesign_preview_' + body.action, order=row['number'], number=number, operator=user)
|
||||||
|
return {'ok': True}
|
||||||
|
|
||||||
|
|
||||||
class ProofAnswer(StrictModel):
|
class ProofAnswer(StrictModel):
|
||||||
result: Literal['ok', 'rejected']
|
result: Literal['ok', 'rejected']
|
||||||
reason: str = Field(default='', max_length=500)
|
reason: str = Field(default='', max_length=500)
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import httpx
|
|||||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||||
from psycopg.types.json import Jsonb
|
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 import db
|
||||||
from ..core.auth import audit, client_ip, owner, rate_limit
|
from ..core.auth import audit, client_ip, owner, rate_limit
|
||||||
from ..core.models import PaymentIntent
|
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))
|
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():
|
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.')
|
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
|
# 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,
|
# removed after a while. A payment under way keeps them a day longer,
|
||||||
# time enough for the provider's notice to become the order.
|
# 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)):
|
if live != len(set(uploads)):
|
||||||
raise HTTPException(410, 'Os arquivos deste pedido expiraram porque ele não foi pago a tempo. '
|
raise HTTPException(410, 'Os arquivos deste pedido expiraram porque ele não foi pago a tempo. '
|
||||||
'Monte o pedido de novo para pagar.')
|
'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
|
# Never a second charge: an approved payment is waiting for its
|
||||||
# notification to become the order, and a card in review may still be.
|
# 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
|
# 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.auth import owner
|
||||||
from ..core.models import QuoteRequest
|
from ..core.models import QuoteRequest
|
||||||
from .. import quote_review
|
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 ..runtime import freight, payment, quote_view, require_delivery_available, storage, upload_row
|
||||||
from ..scanning import require_clean
|
from ..scanning import require_clean
|
||||||
|
|
||||||
@@ -79,7 +79,7 @@ def create_quote(body: QuoteRequest, session_id=Depends(owner)):
|
|||||||
dpis.append(dpi)
|
dpis.append(dpi)
|
||||||
if dpis:
|
if dpis:
|
||||||
draft_item['source_dpi'] = round(min(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:
|
if issue:
|
||||||
raise HTTPException(422, issue)
|
raise HTTPException(422, issue)
|
||||||
note = mismatch(files, draft['items'], rows) if reason is None else None
|
note = mismatch(files, draft['items'], rows) if reason is None else None
|
||||||
|
|||||||
213
app/api/saved_sheets.py
Normal file
213
app/api/saved_sheets.py
Normal file
@@ -0,0 +1,213 @@
|
|||||||
|
"""Minhas folhas: a customer with an account keeps a built cart item and asks
|
||||||
|
for it again, edits it or deletes it later (Rodada 5, B9).
|
||||||
|
|
||||||
|
The item is stored as the Site sent it, with the local files already replaced
|
||||||
|
by the uploads they came from. Only the uploads it names are checked: they must
|
||||||
|
belong to the account, arrived complete and still be within the 30 days an
|
||||||
|
upload is kept (app/runtime.py upload_row).
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import mimetypes
|
||||||
|
import re
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
from decimal import Decimal
|
||||||
|
from typing import Literal
|
||||||
|
from uuid import UUID, uuid4
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
|
from pydantic import Field, field_validator
|
||||||
|
from psycopg.types.json import Jsonb
|
||||||
|
|
||||||
|
from ..core import db
|
||||||
|
from ..core.auth import audit, owner
|
||||||
|
from ..core.models import StrictModel
|
||||||
|
from ..runtime import storage
|
||||||
|
from .customer import account_row
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
LIMIT = 50
|
||||||
|
ITEM_BYTES = 256 * 1024
|
||||||
|
KEEP_DAYS = 30
|
||||||
|
EXPIRED = 'Os arquivos desta folha venceram. Envie de novo para pedir.'
|
||||||
|
UNAVAILABLE = 'Algum arquivo desta folha não está mais disponível. Envie de novo antes de salvar.'
|
||||||
|
NO_FILES = 'A folha precisa ter os arquivos enviados.'
|
||||||
|
PICTURE = re.compile(r'^data:image/(?:webp|png|jpeg);base64,')
|
||||||
|
|
||||||
|
|
||||||
|
class SavedSheet(StrictModel):
|
||||||
|
name: str = Field(min_length=1, max_length=80)
|
||||||
|
mode: Literal['file', 'avulsa', 'uvfile', 'uv', 'premium']
|
||||||
|
metres: Decimal = Field(gt=0, le=1000)
|
||||||
|
item: dict
|
||||||
|
picture: str | None = Field(default=None, max_length=300000)
|
||||||
|
|
||||||
|
@field_validator('picture')
|
||||||
|
@classmethod
|
||||||
|
def picture_is_data_url(cls, value):
|
||||||
|
if value is not None and not PICTURE.match(value):
|
||||||
|
raise ValueError('Invalid picture')
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def saved_files(item):
|
||||||
|
"""The `savedFiles` lists of an item, in order: the item's and each part's."""
|
||||||
|
for group in [item.get('savedFiles')] + [part.get('savedFiles') for part in item.get('partes') or []
|
||||||
|
if isinstance(part, dict)]:
|
||||||
|
if group is not None:
|
||||||
|
yield group
|
||||||
|
|
||||||
|
|
||||||
|
def upload_ids(item):
|
||||||
|
"""The uploads an item names, in the order they appear, without duplicates."""
|
||||||
|
ids = []
|
||||||
|
for group in saved_files(item):
|
||||||
|
if not isinstance(group, list):
|
||||||
|
raise HTTPException(422, NO_FILES)
|
||||||
|
for file in group:
|
||||||
|
if not isinstance(file, dict) or not file.get('upload_id'):
|
||||||
|
raise HTTPException(422, NO_FILES)
|
||||||
|
try:
|
||||||
|
ids.append(UUID(str(file['upload_id'])))
|
||||||
|
except ValueError:
|
||||||
|
raise HTTPException(422, NO_FILES)
|
||||||
|
if not ids:
|
||||||
|
raise HTTPException(422, NO_FILES)
|
||||||
|
if len(ids) > 200:
|
||||||
|
raise HTTPException(422, 'Esta folha tem mais de 200 arquivos.')
|
||||||
|
if len(set(ids)) != len(ids):
|
||||||
|
raise HTTPException(422, 'Esta folha tem arquivos repetidos.')
|
||||||
|
return ids
|
||||||
|
|
||||||
|
|
||||||
|
def file_types(item):
|
||||||
|
"""upload_id -> the MIME type the Site recorded for it, when it did."""
|
||||||
|
types = {}
|
||||||
|
for group in saved_files(item):
|
||||||
|
for file in group or []:
|
||||||
|
if isinstance(file, dict) and file.get('upload_id') and isinstance(file.get('type'), str) and file['type']:
|
||||||
|
types[str(file['upload_id'])] = file['type']
|
||||||
|
return types
|
||||||
|
|
||||||
|
|
||||||
|
def uploads_of(c, ids):
|
||||||
|
if not ids:
|
||||||
|
return []
|
||||||
|
return c.execute('SELECT id,owner,name,size,object_key,complete,purged_at,expires_at,created_at '
|
||||||
|
'FROM dtf_local.uploads WHERE id=ANY(%s)', (ids,)).fetchall()
|
||||||
|
|
||||||
|
|
||||||
|
def sheet_view(c, row):
|
||||||
|
"""The stored sheet with what the page needs to show it: whether every file
|
||||||
|
still exists and is within its 30 days, when the first one ends, and the
|
||||||
|
total size."""
|
||||||
|
ids = list(row['uploads'])
|
||||||
|
rows = uploads_of(c, ids)
|
||||||
|
by_id = {upload['id']: upload for upload in rows}
|
||||||
|
files = [by_id[uid] for uid in ids if uid in by_id]
|
||||||
|
now = datetime.now(timezone.utc)
|
||||||
|
cutoff = now - timedelta(days=KEEP_DAYS)
|
||||||
|
available = len(files) == len(ids) and all(
|
||||||
|
upload['complete'] and not upload['purged_at'] and upload['expires_at'] > now
|
||||||
|
and upload['created_at'] >= cutoff for upload in files)
|
||||||
|
until = min((upload['created_at'] for upload in files), default=None)
|
||||||
|
return {'id': row['id'], 'name': row['name'], 'mode': row['mode'], 'metres': row['metres'],
|
||||||
|
'picture': row['picture'], 'created_at': row['created_at'], 'used_at': row['used_at'],
|
||||||
|
'files_until': until + timedelta(days=KEEP_DAYS) if until else None,
|
||||||
|
'available': available, 'total_size': sum(upload['size'] for upload in files),
|
||||||
|
'item': row['item']}
|
||||||
|
|
||||||
|
|
||||||
|
def owned_sheet(c, sid, identity, lock=False):
|
||||||
|
row = c.execute('SELECT * FROM dtf_local.saved_sheets WHERE id=%s AND account=%s' +
|
||||||
|
(' FOR UPDATE' if lock else ''), (sid, identity)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(404, 'Folha não encontrada.')
|
||||||
|
return row
|
||||||
|
|
||||||
|
|
||||||
|
def require_available(c, row):
|
||||||
|
view = sheet_view(c, row)
|
||||||
|
if not view['available']:
|
||||||
|
raise HTTPException(409, EXPIRED)
|
||||||
|
return view
|
||||||
|
|
||||||
|
|
||||||
|
def touch(c, row):
|
||||||
|
return c.execute('UPDATE dtf_local.saved_sheets SET used_at=now() WHERE id=%s RETURNING *',
|
||||||
|
(row['id'],)).fetchone()
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/account/sheets')
|
||||||
|
def save_sheet(body: SavedSheet, identity=Depends(owner)):
|
||||||
|
size = len(json.dumps(body.item, ensure_ascii=False, separators=(',', ':')).encode())
|
||||||
|
if size > ITEM_BYTES:
|
||||||
|
raise HTTPException(422, 'Esta folha é grande demais para salvar.')
|
||||||
|
ids = upload_ids(body.item)
|
||||||
|
with db.connect() as c:
|
||||||
|
account_row(c, identity, lock=True)
|
||||||
|
rows = uploads_of(c, ids)
|
||||||
|
cutoff = datetime.now(timezone.utc) - timedelta(days=KEEP_DAYS)
|
||||||
|
if len(rows) != len(ids) or any(upload['owner'] != identity or not upload['complete']
|
||||||
|
or upload['purged_at'] or upload['created_at'] < cutoff
|
||||||
|
for upload in rows):
|
||||||
|
raise HTTPException(409, UNAVAILABLE)
|
||||||
|
used = c.execute('SELECT count(*) AS n FROM dtf_local.saved_sheets WHERE account=%s',
|
||||||
|
(identity,)).fetchone()['n']
|
||||||
|
if used >= LIMIT:
|
||||||
|
raise HTTPException(409, 'Você já tem 50 folhas salvas. Exclua uma antes.')
|
||||||
|
c.execute("UPDATE dtf_local.uploads SET expires_at=GREATEST(expires_at, created_at + interval '30 days') "
|
||||||
|
'WHERE id=ANY(%s) AND purged_at IS NULL', (ids,))
|
||||||
|
sid = uuid4()
|
||||||
|
c.execute('''INSERT INTO dtf_local.saved_sheets(id,account,name,mode,metres,item,uploads,picture)
|
||||||
|
VALUES(%s,%s,%s,%s,%s,%s,%s,%s)''',
|
||||||
|
(sid, identity, body.name, body.mode, body.metres, Jsonb(body.item), ids, body.picture))
|
||||||
|
audit('saved_sheet_created', account=str(identity), sheet=str(sid), files=len(ids), c=c)
|
||||||
|
return {'id': sid}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get('/api/account/sheets')
|
||||||
|
def list_sheets(identity=Depends(owner)):
|
||||||
|
with db.connect() as c:
|
||||||
|
account_row(c, identity)
|
||||||
|
rows = c.execute('SELECT * FROM dtf_local.saved_sheets WHERE account=%s ORDER BY created_at DESC',
|
||||||
|
(identity,)).fetchall()
|
||||||
|
return {'sheets': [sheet_view(c, row) for row in rows]}
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete('/api/account/sheets/{sid}')
|
||||||
|
def delete_sheet(sid: UUID, identity=Depends(owner)):
|
||||||
|
with db.connect() as c:
|
||||||
|
account_row(c, identity)
|
||||||
|
owned_sheet(c, sid, identity, lock=True)
|
||||||
|
c.execute('DELETE FROM dtf_local.saved_sheets WHERE id=%s', (sid,))
|
||||||
|
audit('saved_sheet_deleted', account=str(identity), sheet=str(sid))
|
||||||
|
return {'ok': True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/account/sheets/{sid}/use')
|
||||||
|
def use_sheet(sid: UUID, identity=Depends(owner)):
|
||||||
|
with db.connect() as c:
|
||||||
|
account_row(c, identity)
|
||||||
|
row = owned_sheet(c, sid, identity, lock=True)
|
||||||
|
require_available(c, row)
|
||||||
|
row = touch(c, row)
|
||||||
|
return sheet_view(c, row)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/account/sheets/{sid}/files')
|
||||||
|
def sheet_files(sid: UUID, identity=Depends(owner)):
|
||||||
|
with db.connect() as c:
|
||||||
|
account_row(c, identity)
|
||||||
|
row = owned_sheet(c, sid, identity, lock=True)
|
||||||
|
require_available(c, row)
|
||||||
|
rows = {upload['id']: upload for upload in uploads_of(c, list(row['uploads']))}
|
||||||
|
types = file_types(row['item'])
|
||||||
|
files = []
|
||||||
|
for uid in row['uploads']:
|
||||||
|
upload = rows[uid]
|
||||||
|
content_type = types.get(str(uid)) or mimetypes.guess_type(upload['name'])[0] or 'application/octet-stream'
|
||||||
|
files.append({'upload_id': upload['id'], 'name': upload['name'], 'size': upload['size'],
|
||||||
|
'url': storage.view(upload['object_key'], content_type)})
|
||||||
|
touch(c, row)
|
||||||
|
return {'files': files}
|
||||||
@@ -16,7 +16,7 @@ router = APIRouter()
|
|||||||
|
|
||||||
CATALOG = {
|
CATALOG = {
|
||||||
'subindo': 'Subindo a arte pelo celular',
|
'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',
|
'png': 'Por que PNG com fundo transparente',
|
||||||
'avulsas': 'Montando artes avulsas e vendo a folha ao vivo',
|
'avulsas': 'Montando artes avulsas e vendo a folha ao vivo',
|
||||||
'retirada': 'Retirada em Franca em 24 h',
|
'retirada': 'Retirada em Franca em 24 h',
|
||||||
@@ -24,15 +24,32 @@ CATALOG = {
|
|||||||
}
|
}
|
||||||
VIDEO_MAX = 500 * 1024 * 1024
|
VIDEO_MAX = 500 * 1024 * 1024
|
||||||
CAPTIONS_MAX = 1024 * 1024
|
CAPTIONS_MAX = 1024 * 1024
|
||||||
|
PRODUCTS = ('file', 'avulsa', 'uvfile', 'uv')
|
||||||
|
PRODUCT_NAMES = {
|
||||||
|
'file': 'Arquivo por metro',
|
||||||
|
'avulsa': 'Artes avulsas',
|
||||||
|
'uvfile': 'Arquivo por metro · UV',
|
||||||
|
'uv': 'Artes avulsas · UV',
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
class VideoUpdate(StrictModel):
|
class VideoUpdate(StrictModel):
|
||||||
upload_id: UUID | None = None
|
upload_id: UUID | None = None
|
||||||
captions_id: UUID | None = None
|
captions_id: UUID | None = None
|
||||||
product: Literal['file', 'avulsa', 'uvfile', 'uv'] | None = None
|
product: Literal['file', 'avulsa', 'uvfile', 'uv'] | None = None
|
||||||
|
products: list[Literal['file', 'avulsa', 'uvfile', 'uv']] = Field(default_factory=list, max_length=4)
|
||||||
enabled: bool = False
|
enabled: bool = False
|
||||||
|
|
||||||
|
|
||||||
|
def _products(body):
|
||||||
|
"""The chosen products, unique and in catalog order; the old single
|
||||||
|
`product` still works and means one product."""
|
||||||
|
chosen = set(body.products)
|
||||||
|
if not chosen and body.product:
|
||||||
|
chosen.add(body.product)
|
||||||
|
return [product for product in PRODUCTS if product in chosen]
|
||||||
|
|
||||||
|
|
||||||
class VideoUploadStart(StrictModel):
|
class VideoUploadStart(StrictModel):
|
||||||
name: str = Field(min_length=1, max_length=200, pattern=r'^[^/\\\x00-\x1f]+$')
|
name: str = Field(min_length=1, max_length=200, pattern=r'^[^/\\\x00-\x1f]+$')
|
||||||
size: int = Field(gt=0, strict=True)
|
size: int = Field(gt=0, strict=True)
|
||||||
@@ -78,14 +95,19 @@ def manage_videos(user=Depends(operator)):
|
|||||||
FROM dtf_local.site_videos v
|
FROM dtf_local.site_videos v
|
||||||
LEFT JOIN dtf_local.uploads u ON u.id=v.upload_id
|
LEFT JOIN dtf_local.uploads u ON u.id=v.upload_id
|
||||||
LEFT JOIN dtf_local.uploads t ON t.id=v.captions_id''').fetchall()}
|
LEFT JOIN dtf_local.uploads t ON t.id=v.captions_id''').fetchall()}
|
||||||
return {'videos': [dict(id=id, title=title,
|
videos = []
|
||||||
product=rows[id]['product'] if id in rows else None,
|
for id, title in CATALOG.items():
|
||||||
upload_id=rows[id]['upload_id'] if id in rows else None,
|
row = rows.get(id)
|
||||||
captions_id=rows[id]['captions_id'] if id in rows else None,
|
products = list(row['products'] or []) if row else []
|
||||||
video_name=rows[id]['video_name'] if id in rows else None,
|
videos.append(dict(id=id, title=title,
|
||||||
captions_name=rows[id]['captions_name'] if id in rows else None,
|
product=products[0] if products else None,
|
||||||
enabled=rows[id]['enabled'] if id in rows else False)
|
products=products,
|
||||||
for id, title in CATALOG.items()]}
|
upload_id=row['upload_id'] if row else None,
|
||||||
|
captions_id=row['captions_id'] if row else None,
|
||||||
|
video_name=row['video_name'] if row else None,
|
||||||
|
captions_name=row['captions_name'] if row else None,
|
||||||
|
enabled=row['enabled'] if row else False))
|
||||||
|
return {'videos': videos}
|
||||||
|
|
||||||
|
|
||||||
@router.post('/api/operator/site-videos/{video_id}')
|
@router.post('/api/operator/site-videos/{video_id}')
|
||||||
@@ -94,17 +116,20 @@ def update_video(video_id: str, body: VideoUpdate, user=Depends(can('manage'))):
|
|||||||
raise HTTPException(404, 'Vídeo não encontrado.')
|
raise HTTPException(404, 'Vídeo não encontrado.')
|
||||||
if body.enabled and not body.upload_id:
|
if body.enabled and not body.upload_id:
|
||||||
raise HTTPException(422, 'Envie o vídeo antes de publicar.')
|
raise HTTPException(422, 'Envie o vídeo antes de publicar.')
|
||||||
|
products = _products(body)
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
previous = c.execute('SELECT upload_id,captions_id,video_key,captions_key FROM dtf_local.site_videos WHERE id=%s FOR UPDATE',
|
previous = c.execute('SELECT upload_id,captions_id,video_key,captions_key FROM dtf_local.site_videos WHERE id=%s FOR UPDATE',
|
||||||
(video_id,)).fetchone() or {}
|
(video_id,)).fetchone() or {}
|
||||||
# One floating video per product page; checked before any copy, and
|
# One floating video per product page; checked before any copy, and
|
||||||
# the refusal names the video that holds the product (DTF-WEB-G).
|
# the refusal names the video and the product it holds (DTF-WEB-G).
|
||||||
if body.enabled and body.product:
|
if body.enabled and products:
|
||||||
other = c.execute('SELECT id FROM dtf_local.site_videos WHERE id<>%s AND product=%s AND enabled',
|
other = c.execute('''SELECT id,products FROM dtf_local.site_videos
|
||||||
(video_id, body.product)).fetchone()
|
WHERE id<>%s AND enabled AND products && %s''', (video_id, products)).fetchone()
|
||||||
if other:
|
if other:
|
||||||
raise HTTPException(409, f'Este produto já tem o vídeo "{CATALOG.get(other["id"], other["id"])}" '
|
common = next(product for product in products if product in other['products'])
|
||||||
'publicado. Tire esse do Site antes, ou escolha outro lugar.')
|
raise HTTPException(409, f'O produto "{PRODUCT_NAMES[common]}" já tem o vídeo '
|
||||||
|
f'"{CATALOG.get(other["id"], other["id"])}" publicado. '
|
||||||
|
'Tire esse do Site antes, ou escolha outro lugar.')
|
||||||
identity = operator_identity(user)
|
identity = operator_identity(user)
|
||||||
keys = []
|
keys = []
|
||||||
for uid, expected, previous_id, previous_key in (
|
for uid, expected, previous_id, previous_key in (
|
||||||
@@ -121,12 +146,14 @@ def update_video(video_id: str, body: VideoUpdate, user=Depends(can('manage'))):
|
|||||||
CopySource={'Bucket': storage.bucket, 'Key': upload['object_key']},
|
CopySource={'Bucket': storage.bucket, 'Key': upload['object_key']},
|
||||||
Key=key, ContentType=mime, MetadataDirective='REPLACE')
|
Key=key, ContentType=mime, MetadataDirective='REPLACE')
|
||||||
keys.append(key)
|
keys.append(key)
|
||||||
c.execute('''INSERT INTO dtf_local.site_videos(id,upload_id,captions_id,video_key,captions_key,product,enabled,updated_by)
|
c.execute('''INSERT INTO dtf_local.site_videos(id,upload_id,captions_id,video_key,captions_key,product,products,enabled,updated_by)
|
||||||
VALUES(%s,%s,%s,%s,%s,%s,%s,%s)
|
VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s)
|
||||||
ON CONFLICT (id) DO UPDATE SET upload_id=EXCLUDED.upload_id,captions_id=EXCLUDED.captions_id,
|
ON CONFLICT (id) DO UPDATE SET upload_id=EXCLUDED.upload_id,captions_id=EXCLUDED.captions_id,
|
||||||
video_key=EXCLUDED.video_key,captions_key=EXCLUDED.captions_key,
|
video_key=EXCLUDED.video_key,captions_key=EXCLUDED.captions_key,
|
||||||
product=EXCLUDED.product,enabled=EXCLUDED.enabled,updated_by=EXCLUDED.updated_by,updated_at=now()''',
|
product=EXCLUDED.product,products=EXCLUDED.products,enabled=EXCLUDED.enabled,
|
||||||
(video_id, body.upload_id, body.captions_id, keys[0], keys[1], body.product, body.enabled, user))
|
updated_by=EXCLUDED.updated_by,updated_at=now()''',
|
||||||
|
(video_id, body.upload_id, body.captions_id, keys[0], keys[1],
|
||||||
|
products[0] if products else None, products, body.enabled, user))
|
||||||
ids = [uid for uid in (body.upload_id, body.captions_id) if uid]
|
ids = [uid for uid in (body.upload_id, body.captions_id) if uid]
|
||||||
if ids:
|
if ids:
|
||||||
c.execute("UPDATE dtf_local.uploads SET expires_at=GREATEST(expires_at,now()+interval '30 days') WHERE id=ANY(%s)", (ids,))
|
c.execute("UPDATE dtf_local.uploads SET expires_at=GREATEST(expires_at,now()+interval '30 days') WHERE id=ANY(%s)", (ids,))
|
||||||
@@ -137,14 +164,18 @@ def update_video(video_id: str, body: VideoUpdate, user=Depends(can('manage'))):
|
|||||||
@router.get('/api/site/videos')
|
@router.get('/api/site/videos')
|
||||||
def published_videos():
|
def published_videos():
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
rows = c.execute('''SELECT v.id,v.product,v.video_key,v.captions_key,u.name AS video_name
|
rows = c.execute('''SELECT v.id,v.products,v.video_key,v.captions_key,u.name AS video_name
|
||||||
FROM dtf_local.site_videos v
|
FROM dtf_local.site_videos v
|
||||||
JOIN dtf_local.uploads u ON u.id=v.upload_id
|
JOIN dtf_local.uploads u ON u.id=v.upload_id
|
||||||
WHERE v.enabled AND v.video_key IS NOT NULL''').fetchall()
|
WHERE v.enabled AND v.video_key IS NOT NULL''').fetchall()
|
||||||
return {'videos': [dict(id=row['id'], product=row['product'],
|
videos = []
|
||||||
src=storage.view(row['video_key'], _kind({'name':row['video_name'],'size':0})[0]),
|
for row in rows:
|
||||||
captions=f"/api/site/videos/{row['id']}/captions" if row['captions_key'] else None)
|
products = list(row['products'] or [])
|
||||||
for row in rows]}
|
videos.append(dict(id=row['id'], product=products[0] if products else None,
|
||||||
|
products=products,
|
||||||
|
src=storage.view(row['video_key'], _kind({'name':row['video_name'],'size':0})[0]),
|
||||||
|
captions=f"/api/site/videos/{row['id']}/captions" if row['captions_key'] else None))
|
||||||
|
return {'videos': videos}
|
||||||
|
|
||||||
|
|
||||||
@router.get('/api/site/videos/{video_id}/captions')
|
@router.get('/api/site/videos/{video_id}/captions')
|
||||||
|
|||||||
@@ -120,6 +120,8 @@ def montador_order(body: MontadorOrder, request: Request, user=Depends(can('asse
|
|||||||
kinds = set().union(*(MONTADOR_KINDS.get(r, set()) for r in roles_of(request.state.operator)))
|
kinds = set().union(*(MONTADOR_KINDS.get(r, set()) for r in roles_of(request.state.operator)))
|
||||||
if body.kind not in kinds:
|
if body.kind not in kinds:
|
||||||
raise HTTPException(403, 'Seu perfil não permite este tipo de pedido.')
|
raise HTTPException(403, 'Seu perfil não permite este tipo de pedido.')
|
||||||
|
if body.batch and body.kind != 'interno':
|
||||||
|
raise HTTPException(422, 'A lista colada vira sempre pedido Interno.')
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
if body.kind == 'interno':
|
if body.kind == 'interno':
|
||||||
customer = internal_customer(c)
|
customer = internal_customer(c)
|
||||||
@@ -148,7 +150,8 @@ def montador_order(body: MontadorOrder, request: Request, user=Depends(can('asse
|
|||||||
# The order's kind and the clothing order it travels with, on the
|
# The order's kind and the clothing order it travels with, on the
|
||||||
# card and in Tiny's internal note.
|
# card and in Tiny's internal note.
|
||||||
approved = {**approved, 'kind': body.kind,
|
approved = {**approved, 'kind': body.kind,
|
||||||
**({'with_order': body.with_order} if body.with_order else {})}
|
**({'with_order': body.with_order} if body.with_order else {}),
|
||||||
|
**({'batch': body.batch.model_dump()} if body.batch else {})}
|
||||||
# A Venda's seller in Tiny is who assembled it, when their user
|
# A Venda's seller in Tiny is who assembled it, when their user
|
||||||
# names one (Marcus, 2026-11-17, app/tiny.py order_payload).
|
# names one (Marcus, 2026-11-17, app/tiny.py order_payload).
|
||||||
if body.kind == 'venda':
|
if body.kind == 'venda':
|
||||||
|
|||||||
@@ -269,11 +269,14 @@ def list_machines(user=Depends(can('view'))):
|
|||||||
def create_machine(body: MachineIn, user=Depends(can('users'))):
|
def create_machine(body: MachineIn, user=Depends(can('users'))):
|
||||||
mid = uuid4()
|
mid = uuid4()
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
if c.execute('SELECT 1 FROM dtf_local.machines WHERE lower(name)=lower(%s)', (body.name.strip(),)).fetchone():
|
# A machine's hot folder is its first name, for good: no other machine
|
||||||
raise HTTPException(409, 'Já existe uma máquina com este nome.')
|
# may be called that, or two would share one folder.
|
||||||
c.execute('''INSERT INTO dtf_local.machines(id,name,products,active,limit_metres,places)
|
if c.execute('SELECT 1 FROM dtf_local.machines WHERE lower(name)=lower(%s) OR lower(folder)=lower(%s)',
|
||||||
VALUES(%s,%s,%s,%s,%s,%s)''', (mid, body.name.strip(), sorted(set(body.products)), body.active,
|
(body.name.strip(), body.name.strip())).fetchone():
|
||||||
body.limit_metres, body.places or machines.DEFAULT_PLACES))
|
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)
|
audit('machine_created', operator=user, machine=body.name)
|
||||||
return {'id': str(mid)}
|
return {'id': str(mid)}
|
||||||
|
|
||||||
@@ -281,9 +284,9 @@ def create_machine(body: MachineIn, user=Depends(can('users'))):
|
|||||||
@router.post('/api/operator/machines/{mid}')
|
@router.post('/api/operator/machines/{mid}')
|
||||||
def update_machine(mid: UUID, body: MachineIn, user=Depends(can('users'))):
|
def update_machine(mid: UUID, body: MachineIn, user=Depends(can('users'))):
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
if c.execute('SELECT 1 FROM dtf_local.machines WHERE lower(name)=lower(%s) AND id<>%s',
|
if c.execute('''SELECT 1 FROM dtf_local.machines WHERE (lower(name)=lower(%s) OR lower(folder)=lower(%s))
|
||||||
(body.name.strip(), mid)).fetchone():
|
AND id<>%s''', (body.name.strip(), body.name.strip(), mid)).fetchone():
|
||||||
raise HTTPException(409, 'Já existe uma máquina com este nome.')
|
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,
|
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''',
|
places=COALESCE(%s,places) WHERE id=%s RETURNING id''',
|
||||||
(body.name.strip(), sorted(set(body.products)), body.active, body.limit_metres,
|
(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."""
|
"""A message to whoever asked, to prove the mail server works."""
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
if not mail.queue(c, 'test', user, 'Teste de e-mail · Kanban DTF',
|
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: '
|
'Este é um teste do Kanban DTF. Se chegou, o envio de e-mails aos clientes '
|
||||||
'os e-mails dos clientes.'):
|
'está funcionando.'):
|
||||||
raise HTTPException(409, 'O envio de e-mails não está configurado no servidor.')
|
raise HTTPException(409, 'O envio de e-mails não está configurado no servidor.')
|
||||||
audit('mail_test_queued', operator=user)
|
audit('mail_test_queued', operator=user)
|
||||||
return {'ok': True, 'to': user}
|
return {'ok': True, 'to': user}
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ from . import observability
|
|||||||
from .core import db
|
from .core import db
|
||||||
from .core.auth import audit, client_ip
|
from .core.auth import audit, client_ip
|
||||||
from .runtime import ALLOWED_HOSTS, ALLOWED_ORIGINS, storage
|
from .runtime import ALLOWED_HOSTS, ALLOWED_ORIGINS, storage
|
||||||
from .api import artwork, customer, health, machine_log, operator, orders, payments, quotes, reviews, site_admin, site_videos, stamps, uploads, users
|
from .api import artwork, customer, health, machine_log, operator, orders, payments, quotes, reviews, saved_sheets, site_admin, site_videos, stamps, uploads, users
|
||||||
|
|
||||||
observability.init('api')
|
observability.init('api')
|
||||||
|
|
||||||
@@ -82,5 +82,5 @@ async def safe_headers(request, call_next):
|
|||||||
|
|
||||||
|
|
||||||
# Order is not significant: no two routers declare the same path.
|
# Order is not significant: no two routers declare the same path.
|
||||||
for module in (health, uploads, quotes, orders, payments, operator, customer, artwork, users, site_videos, site_admin, reviews, machine_log, stamps):
|
for module in (health, uploads, quotes, orders, payments, operator, customer, artwork, users, site_videos, site_admin, reviews, machine_log, stamps, saved_sheets):
|
||||||
app.include_router(module.router)
|
app.include_router(module.router)
|
||||||
|
|||||||
@@ -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(
|
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",
|
"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()
|
(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}
|
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):
|
if kept and len(kept) == len(body.files):
|
||||||
raise HTTPException(409, 'Estes já são os arquivos finais. Envie o arquivo novo.')
|
raise HTTPException(409, 'Estes já são os arquivos finais. Envie o arquivo novo.')
|
||||||
|
|||||||
@@ -132,6 +132,10 @@ class ProductionSource(StrictModel):
|
|||||||
# and printed; the file itself is length_cm plus both trims long.
|
# and printed; the file itself is length_cm plus both trims long.
|
||||||
trim_top_cm: Decimal = Field(default=Decimal(0), ge=0, le=6000)
|
trim_top_cm: Decimal = Field(default=Decimal(0), ge=0, le=6000)
|
||||||
trim_bottom_cm: Decimal = Field(default=Decimal(0), ge=0, le=6000)
|
trim_bottom_cm: Decimal = Field(default=Decimal(0), ge=0, le=6000)
|
||||||
|
# The size the PNG itself recorded (item A1, round 5), only for the Prumo
|
||||||
|
# report; nothing on the server prices or packs by it.
|
||||||
|
saved_width_cm: Decimal | None = Field(default=None, gt=0, le=10000)
|
||||||
|
saved_dpi: int | None = Field(default=None, ge=1, le=10000, strict=True)
|
||||||
|
|
||||||
class ProductionPlacement(StrictModel):
|
class ProductionPlacement(StrictModel):
|
||||||
source_index: int = Field(ge=0, le=199, strict=True)
|
source_index: int = Field(ge=0, le=199, strict=True)
|
||||||
@@ -291,6 +295,17 @@ class Item(StrictModel):
|
|||||||
raise ValueError('Finished sheets must retain their original orientation')
|
raise ValueError('Finished sheets must retain their original orientation')
|
||||||
if placed != expected:
|
if placed != expected:
|
||||||
raise ValueError('Production layout does not cover every source copy')
|
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:
|
if self.quality_status == 'warning' and not self.quality_acknowledged:
|
||||||
raise ValueError('Resolution warning must be acknowledged')
|
raise ValueError('Resolution warning must be acknowledged')
|
||||||
return self
|
return self
|
||||||
@@ -390,6 +405,15 @@ class QuoteRequest(StrictModel):
|
|||||||
raise ValueError('The delivery address CEP must be the CEP freight was quoted for')
|
raise ValueError('The delivery address CEP must be the CEP freight was quoted for')
|
||||||
return self
|
return self
|
||||||
|
|
||||||
|
class SkippedLine(StrictModel):
|
||||||
|
line: int = Field(ge=1, le=10000, strict=True)
|
||||||
|
text: str = Field(max_length=200)
|
||||||
|
reason: str = Field(max_length=200)
|
||||||
|
|
||||||
|
class MontadorBatch(StrictModel):
|
||||||
|
lines: int = Field(ge=0, le=1000, strict=True)
|
||||||
|
skipped: list[SkippedLine] = Field(default_factory=list, max_length=1000)
|
||||||
|
|
||||||
class MontadorOrder(StrictModel):
|
class MontadorOrder(StrictModel):
|
||||||
"""What the montador sends (fronts 7a.3 and 7a.4): Interno or Venda, loose
|
"""What the montador sends (fronts 7a.3 and 7a.4): Interno or Venda, loose
|
||||||
artwork only; the server prices and approves it as a quote. An Interno
|
artwork only; the server prices and approves it as a quote. An Interno
|
||||||
@@ -406,6 +430,8 @@ class MontadorOrder(StrictModel):
|
|||||||
# A Venda with "Envio": the chosen freight service and the full address.
|
# A Venda with "Envio": the chosen freight service and the full address.
|
||||||
freight: Freight | None = None
|
freight: Freight | None = None
|
||||||
destination: Destination | None = None
|
destination: Destination | None = None
|
||||||
|
# The pasted list this order came from: the valid lines and the skipped ones.
|
||||||
|
batch: MontadorBatch | None = None
|
||||||
|
|
||||||
@model_validator(mode='after')
|
@model_validator(mode='after')
|
||||||
def order_kind(self):
|
def order_kind(self):
|
||||||
|
|||||||
@@ -8,6 +8,19 @@ import os
|
|||||||
import re
|
import re
|
||||||
from decimal import Decimal, ROUND_CEILING
|
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}
|
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
|
# 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')
|
raise ValueError('Invalid product or length')
|
||||||
if isinstance(grade, bool) or not isinstance(grade, int) or not 0 <= grade <= 100:
|
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')
|
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:
|
if isinstance(extra_cents, bool) or not isinstance(extra_cents, int) or extra_cents < 0:
|
||||||
raise ValueError('Invalid extra charge')
|
raise ValueError('Invalid extra charge')
|
||||||
unit = (PRICES[mode] if unit_cents is None else unit_cents) + extra_cents
|
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.
|
# grade them, so neither does this.
|
||||||
PDF_MAX_BYTES = 150 * 1048576
|
PDF_MAX_BYTES = 150 * 1048576
|
||||||
HEAD_BYTES = 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.
|
# Rounding in the browser and here can differ by a point on the same file.
|
||||||
TOLERANCE = 2
|
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]]
|
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):
|
def pdf_dpi(path):
|
||||||
"""The page's area-weighted image DPI, 300 for vectors only, None if the
|
"""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
|
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:
|
try:
|
||||||
with pikepdf.open(path) as pdf:
|
with pikepdf.open(path) as pdf:
|
||||||
if len(pdf.pages) != 1:
|
if len(pdf.pages) != 1:
|
||||||
@@ -99,7 +124,9 @@ def pdf_dpi(path):
|
|||||||
def walk(resources, instructions, ctm, depth):
|
def walk(resources, instructions, ctm, depth):
|
||||||
stack = []
|
stack = []
|
||||||
xobjects = resources.get('/XObject', {}) if resources is not None else {}
|
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)
|
op = str(operator)
|
||||||
if op == 'q':
|
if op == 'q':
|
||||||
stack.append(ctm)
|
stack.append(ctm)
|
||||||
@@ -108,6 +135,9 @@ def pdf_dpi(path):
|
|||||||
elif op == 'cm':
|
elif op == 'cm':
|
||||||
ctm = _multiply(ctm, [float(v) for v in operands])
|
ctm = _multiply(ctm, [float(v) for v in operands])
|
||||||
elif op == 'Do' and 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]))
|
xobject = xobjects.get(str(operands[0]))
|
||||||
if xobject is None:
|
if xobject is None:
|
||||||
continue
|
continue
|
||||||
@@ -120,9 +150,14 @@ def pdf_dpi(path):
|
|||||||
elif subtype == '/Form' and depth < 8:
|
elif subtype == '/Form' and depth < 8:
|
||||||
matrix = [float(v) for v in xobject.get('/Matrix', [1, 0, 0, 1, 0, 0])]
|
matrix = [float(v) for v in xobject.get('/Matrix', [1, 0, 0, 1, 0, 0])]
|
||||||
walk(xobject.get('/Resources', resources),
|
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)
|
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:
|
except Exception:
|
||||||
return None
|
return None
|
||||||
found = [(dpi, area) for dpi, area in found if dpi > 0]
|
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)
|
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):
|
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:
|
if row['size'] > PDF_MAX_BYTES:
|
||||||
return None
|
return None
|
||||||
with tempfile.NamedTemporaryFile(suffix='.pdf') as handle:
|
with tempfile.NamedTemporaryFile(suffix='.pdf') as handle:
|
||||||
storage.client.download_fileobj(storage.bucket, row['object_key'], handle)
|
storage.client.download_fileobj(storage.bucket, row['object_key'], handle)
|
||||||
handle.flush()
|
handle.flush()
|
||||||
return pdf_dpi(handle.name)
|
return bounded_pdf_dpi(handle.name)
|
||||||
|
|
||||||
|
|
||||||
class Files:
|
class Files:
|
||||||
@@ -227,6 +295,35 @@ def resolution_issue(files, items, rows):
|
|||||||
return None
|
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):
|
def mismatch(files, items, rows):
|
||||||
"""Why a cart's grades cannot be approved at checkout, or None."""
|
"""Why a cart's grades cannot be approved at checkout, or None."""
|
||||||
for item in items:
|
for item in items:
|
||||||
|
|||||||
@@ -29,6 +29,7 @@ def triggered(rules: dict, items, treatment_offered: bool) -> dict:
|
|||||||
|
|
||||||
|
|
||||||
def treatment_message(grade: int) -> str:
|
def treatment_message(grade: int) -> str:
|
||||||
"""The refusal the customer sees when Ajuste Fino is required."""
|
"""The refusal the customer sees when Ajuste Fino is required. The grade
|
||||||
return (f'Sua arte tem nota {grade}: para imprimir com qualidade, o Ajuste Fino '
|
stays on the Kanban: the customer never sees the number (Rodada 5, D6)."""
|
||||||
|
return ('Sua arte está abaixo da resolução mínima, então o Ajuste Fino '
|
||||||
'é obrigatório neste pedido.')
|
'é obrigatório neste pedido.')
|
||||||
|
|||||||
@@ -113,18 +113,59 @@ def stop(c, order_id):
|
|||||||
WHERE order_id=%s AND state IN ('queued','claimed','written')''', (order_id,))
|
WHERE order_id=%s AND state IN ('queued','claimed','written')''', (order_id,))
|
||||||
|
|
||||||
|
|
||||||
|
def last_round(c, order_ids):
|
||||||
|
"""Each order's parts in its last round, in order: {order id: [{seq, name,
|
||||||
|
state}]}, for the transfer dialog to ask where the new machine resumes."""
|
||||||
|
rows = c.execute('''SELECT h.order_id, h.seq, h.name, h.state FROM dtf_local.hot_parts h
|
||||||
|
WHERE h.order_id=ANY(%s) AND h.round=(SELECT max(round) FROM dtf_local.hot_parts x
|
||||||
|
WHERE x.order_id=h.order_id) ORDER BY h.order_id, h.seq''', (list(order_ids),)).fetchall()
|
||||||
|
out = {}
|
||||||
|
for row in rows:
|
||||||
|
out.setdefault(row['order_id'], []).append({'seq': row['seq'], 'name': row['name'], 'state': row['state']})
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def prt_name(name):
|
||||||
|
"""The Hoson file the RIP makes from a part: its name with .prt."""
|
||||||
|
return name.rsplit('.', 1)[0] + '.prt'
|
||||||
|
|
||||||
|
|
||||||
|
def transfer(c, order_id, resume_from=None):
|
||||||
|
"""The order changed machine in Imprimindo (Rodada 5, D4). The hot folder
|
||||||
|
takes a PNG in about 10 s (Marcus, 2026-12-01), so a part the old machine
|
||||||
|
took may still be waiting in its Hoson queue: Gestão says which part the
|
||||||
|
new machine resumes from. The old machine's folder loses what it had not
|
||||||
|
taken; the new round holds that part onward. Returns (resume_from, the
|
||||||
|
.prt files to delete from the old machine's Hoson folder: the parts from
|
||||||
|
there on that it had already taken)."""
|
||||||
|
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 1, []
|
||||||
|
parts = c.execute('''SELECT seq, name, state FROM dtf_local.hot_parts WHERE order_id=%s AND round=%s
|
||||||
|
ORDER BY seq''', (order_id, last)).fetchall()
|
||||||
|
start = resume_from or 1
|
||||||
|
delete = [prt_name(part['name']) for part in parts if part['seq'] >= start and part['state'] == 'consumed']
|
||||||
|
stop(c, order_id)
|
||||||
|
c.execute('''INSERT INTO dtf_local.hot_parts(order_id,round,seq,item_index,upload_id,name)
|
||||||
|
SELECT order_id, %s, row_number() OVER (ORDER BY seq), item_index, upload_id, name
|
||||||
|
FROM dtf_local.hot_parts WHERE order_id=%s AND round=%s AND seq >= %s''',
|
||||||
|
(last + 1, order_id, last, start))
|
||||||
|
return start, delete
|
||||||
|
|
||||||
|
|
||||||
def claim(c, user):
|
def claim(c, user):
|
||||||
"""The parts due in the folders now, claimed for this computer to write:
|
"""The parts due in the folders now, claimed for this computer to write:
|
||||||
for each machine, the next parts of its orders in Imprimindo, in the order
|
for each machine, the next parts of its orders in Imprimindo, in the order
|
||||||
they entered it, until the machine has its places' worth in its folder."""
|
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
|
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,))
|
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
|
(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
|
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
|
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
|
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()
|
due, busy, blocked = [], {}, set()
|
||||||
for row in rows:
|
for row in rows:
|
||||||
machine = row['machine_id']
|
machine = row['machine_id']
|
||||||
@@ -139,7 +180,9 @@ def claim(c, user):
|
|||||||
if busy.get(machine, 0) >= row['places'] or not cls:
|
if busy.get(machine, 0) >= row['places'] or not cls:
|
||||||
blocked.add(order)
|
blocked.add(order)
|
||||||
continue
|
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
|
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']))
|
WHERE id=%s''', (user, folder, row['id']))
|
||||||
busy[machine] = busy.get(machine, 0) + 1
|
busy[machine] = busy.get(machine, 0) + 1
|
||||||
@@ -174,9 +217,10 @@ def report(c, part_id, what, user):
|
|||||||
|
|
||||||
|
|
||||||
def progress(c, order_ids):
|
def progress(c, order_ids):
|
||||||
"""For each order in parts, where its film is (Dropstar, 2026-10-30):
|
"""For each order in parts, how many of its parts the machine took
|
||||||
"parte 3/7 imprimindo · 4/7 ripando". Flexi rips the part it took last
|
(Dropstar, 2026-10-30). The hot folder takes a PNG in about 10 s and the
|
||||||
while the one before it prints."""
|
Hoson queues it (Marcus, 2026-12-01): a part taken may still wait to be
|
||||||
|
ripped, so nothing here says which part prints."""
|
||||||
rows = c.execute('''SELECT h.order_id, count(*) AS parts,
|
rows = c.execute('''SELECT h.order_id, count(*) AS parts,
|
||||||
max(h.seq) FILTER (WHERE h.state='consumed') AS taken,
|
max(h.seq) FILTER (WHERE h.state='consumed') AS taken,
|
||||||
count(*) FILTER (WHERE h.state IN ('claimed','written')) AS waiting
|
count(*) FILTER (WHERE h.state IN ('claimed','written')) AS waiting
|
||||||
|
|||||||
@@ -205,7 +205,7 @@ def alerts(c, machine_id):
|
|||||||
'snoozable': bool, 'blocking': bool}. blocking is False when it was
|
'snoozable': bool, 'blocking': bool}. blocking is False when it was
|
||||||
postponed this cycle and no card was pulled on the machine since.
|
postponed this cycle and no card was pulled on the machine since.
|
||||||
Texts, with metres in one decimal and a comma:
|
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"
|
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")
|
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")
|
||||||
"""
|
"""
|
||||||
@@ -236,11 +236,11 @@ def alerts(c, machine_id):
|
|||||||
|
|
||||||
if counts['clean']['metres'] >= CLEAN_EVERY_METRES:
|
if counts['clean']['metres'] >= CLEAN_EVERY_METRES:
|
||||||
due('clean', f"{name}: {one_decimal(counts['clean']['metres'])} m desde a última limpeza "
|
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']
|
if (counts['film']['since'] is not None and not counts['film']['aligned']
|
||||||
and counts['film']['metres'] >= ALIGN_AFTER_FILM_METRES):
|
and counts['film']['metres'] >= ALIGN_AFTER_FILM_METRES):
|
||||||
due('align', f"{name}: {one_decimal(counts['film']['metres'])} m desde a troca de filme "
|
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():
|
for item, value in supplies.items():
|
||||||
if not supply_low(value):
|
if not supply_low(value):
|
||||||
continue
|
continue
|
||||||
|
|||||||
@@ -39,7 +39,8 @@ def loads(c):
|
|||||||
|
|
||||||
def rows(c, with_operators=False):
|
def rows(c, with_operators=False):
|
||||||
"""Every machine with its load, for the Kanban."""
|
"""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()
|
ORDER BY created_at, name''').fetchall()
|
||||||
load = loads(c)
|
load = loads(c)
|
||||||
operators = {}
|
operators = {}
|
||||||
@@ -55,7 +56,7 @@ def rows(c, with_operators=False):
|
|||||||
for m in machines:
|
for m in machines:
|
||||||
key = str(m['id'])
|
key = str(m['id'])
|
||||||
used = load.get(key, {'metres': Decimal(0), 'orders': 0, 'states': {}})
|
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,
|
'limit_metres': float(m['limit_metres']) if m['limit_metres'] is not None else None,
|
||||||
'places': m['places'],
|
'places': m['places'],
|
||||||
'open_metres': float(used['metres']), 'open_orders': used['orders'], 'states': used['states'],
|
'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']}"
|
number, link = order['number'], f"{origin}/conta/pedidos?order={order['id']}"
|
||||||
text = '\n'.join([mail_html.greeting(customer.get('name')), '',
|
text = '\n'.join([mail_html.greeting(customer.get('name')), '',
|
||||||
f'Seu pagamento foi aprovado e o pedido #{number} já está com a nossa equipe. '
|
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'{key}: {value}' for key, value in rows), '',
|
||||||
f'Acompanhe cada etapa em Minha conta: {link}', '',
|
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,
|
return queue(c, 'order', customer['mail'], f'Recebemos seu pedido #{number} · DTF Dropstar', text,
|
||||||
mail_html.order_paid(customer.get('name'), number, rows, link))
|
mail_html.order_paid(customer.get('name'), number, rows, link))
|
||||||
|
|
||||||
@@ -108,14 +108,14 @@ def quote_expired(c, quote, origin):
|
|||||||
link = f'{origin}/'
|
link = f'{origin}/'
|
||||||
text = '\n'.join([mail_html.greeting(customer.get('name')), '',
|
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.', '',
|
'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', [
|
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.pill('Pedido expirado', 'info'),
|
||||||
mail_html.title('Seu pedido expirou'),
|
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 '
|
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.'),
|
'expirou. Os arquivos que você enviou foram apagados.'),
|
||||||
mail_html.button('Montar de novo', link),
|
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)
|
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'
|
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', [
|
return layout('Clique no botão para criar uma nova senha.', 'Sua conta', [
|
||||||
title('Crie uma nova senha'),
|
title('Crie uma nova senha'),
|
||||||
para(f'{greeting(name)} Recebemos um pedido para criar uma nova senha na sua conta. '
|
para(f'{greeting(name)} Recebemos um pedido de nova senha para a sua conta.'),
|
||||||
'É só clicar no botão abaixo.'),
|
|
||||||
button('Criar nova senha', link),
|
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: '
|
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.'),
|
'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'<br><a href="{escape(link, quote=True)}" style="color:{DARK_ORANGE};word-break:break-all">'
|
||||||
f'{escape(link)}</a>'),
|
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', [
|
return layout('Este e-mail já tem conta no DTF Dropstar.', 'Sua conta', [
|
||||||
title('Este e-mail já tem uma 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á '
|
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),
|
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 '
|
callout('Esqueceu a senha?', 'Na página de entrada, clique em “Esqueci minha senha” e enviamos um link '
|
||||||
'para criar outra.'),
|
'para criar outra.'),
|
||||||
@@ -180,7 +179,7 @@ def email_changed(name, old, new):
|
|||||||
title('O e-mail da sua conta foi trocado'),
|
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:'),
|
para(f'{greeting(name)} A partir de agora, sua conta no DTF Dropstar entra com outro e-mail:'),
|
||||||
facts([('Antes', old), ('Agora', new)]),
|
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),
|
warn=True),
|
||||||
button('Falar no WhatsApp', WHATSAPP, dark=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', [
|
return layout(f'Pagamento aprovado. O pedido #{number} já está com a nossa equipe.', 'Seu pedido', [
|
||||||
pill('Pagamento aprovado'),
|
pill('Pagamento aprovado'),
|
||||||
title(f'Recebemos seu pedido #{number}'),
|
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 '
|
para(f'{greeting(name)} Seu pagamento foi aprovado e o pedido já está com a nossa equipe. '
|
||||||
'confere a arte e coloca na fila de impressão.'),
|
'Conferimos a arte e colocamos na fila de impressão.'),
|
||||||
facts(rows),
|
facts(rows),
|
||||||
steps([('Pagamento aprovado', 'Pedido recebido pela equipe', True),
|
steps([('Pagamento aprovado', 'Pedido recebido pela equipe', True),
|
||||||
('Arte conferida', 'A equipe confere se está tudo certo para imprimir', False),
|
('Arte conferida', 'A equipe confere se está tudo certo para imprimir', False),
|
||||||
('Impressão', 'Seu filme entra na máquina', False),
|
('Impressão', 'Seu filme entra na máquina', False),
|
||||||
('Pronto', 'Você recebe o aviso pelo WhatsApp', False)]),
|
('Pronto', 'Você recebe o aviso pelo WhatsApp', False)]),
|
||||||
button('Ver meu pedido', link),
|
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 '
|
small('Acompanhe cada etapa em Minha conta. Se ainda não tem conta, crie com este e-mail e o mesmo '
|
||||||
'do pedido: ele aparece lá na hora.'),
|
'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;
|
||||||
15
app/migrations/202611301200_redesign-previews.sql
Normal file
15
app/migrations/202611301200_redesign-previews.sql
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
-- Round 5, D2 (order from 2026-11-16): a redesign's preview, sent to the
|
||||||
|
-- customer, waiting for approval or rejection. One preview is open at a time.
|
||||||
|
CREATE TABLE IF NOT EXISTS dtf_local.redesign_previews (
|
||||||
|
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||||
|
order_id uuid NOT NULL REFERENCES dtf_local.orders(id) ON DELETE CASCADE,
|
||||||
|
number int NOT NULL,
|
||||||
|
sent_at timestamptz NOT NULL DEFAULT now(),
|
||||||
|
sent_by text NOT NULL,
|
||||||
|
decided_at timestamptz,
|
||||||
|
result text CHECK (result IN ('approved','rejected')),
|
||||||
|
reason text NOT NULL DEFAULT '',
|
||||||
|
decided_by text,
|
||||||
|
UNIQUE (order_id, number)
|
||||||
|
);
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS redesign_previews_open ON dtf_local.redesign_previews(order_id) WHERE decided_at IS NULL;
|
||||||
16
app/migrations/202611301400_machine-transfers.sql
Normal file
16
app/migrations/202611301400_machine-transfers.sql
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
-- Rodada 5, D4: a card already in Imprimindo changes machine, by Gestão or an
|
||||||
|
-- administrator with a reason; the part the new machine resumed from is kept
|
||||||
|
-- for the Revisor to check the tone seam.
|
||||||
|
CREATE TABLE IF NOT EXISTS dtf_local.machine_transfers (
|
||||||
|
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||||
|
order_id uuid NOT NULL REFERENCES dtf_local.orders(id) ON DELETE CASCADE,
|
||||||
|
from_machine uuid,
|
||||||
|
to_machine uuid NOT NULL,
|
||||||
|
from_name text,
|
||||||
|
to_name text NOT NULL,
|
||||||
|
reason text NOT NULL,
|
||||||
|
resumed_from int,
|
||||||
|
created_by text NOT NULL,
|
||||||
|
created_at timestamptz NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS machine_transfers_order ON dtf_local.machine_transfers(order_id);
|
||||||
8
app/migrations/202611301600_site-video-products.sql
Normal file
8
app/migrations/202611301600_site-video-products.sql
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
-- Round 5, D7: the same video can appear on more than one product page. The
|
||||||
|
-- old single `product` column stays for compatibility; the code reads
|
||||||
|
-- `products`. One floating video per product is still enforced in the API.
|
||||||
|
ALTER TABLE dtf_local.site_videos ADD COLUMN IF NOT EXISTS products text[] NOT NULL DEFAULT '{}';
|
||||||
|
UPDATE dtf_local.site_videos SET products=ARRAY[product] WHERE product IS NOT NULL AND products='{}';
|
||||||
|
ALTER TABLE dtf_local.site_videos DROP CONSTRAINT IF EXISTS site_videos_products_check;
|
||||||
|
ALTER TABLE dtf_local.site_videos ADD CONSTRAINT site_videos_products_check
|
||||||
|
CHECK (products <@ ARRAY['file','avulsa','uvfile','uv']::text[]);
|
||||||
15
app/migrations/202611301700_saved-sheets.sql
Normal file
15
app/migrations/202611301700_saved-sheets.sql
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
-- Rodada 5, B9: a customer with an account keeps a built sheet (a cart item)
|
||||||
|
-- in Minhas folhas and asks for it again, edits it or deletes it later.
|
||||||
|
CREATE TABLE IF NOT EXISTS dtf_local.saved_sheets (
|
||||||
|
id uuid PRIMARY KEY,
|
||||||
|
account uuid NOT NULL REFERENCES dtf_local.accounts(id) ON DELETE CASCADE,
|
||||||
|
name text NOT NULL,
|
||||||
|
mode text NOT NULL CHECK (mode IN ('file','avulsa','uvfile','uv','premium')),
|
||||||
|
metres numeric NOT NULL,
|
||||||
|
item jsonb NOT NULL,
|
||||||
|
uploads uuid[] NOT NULL,
|
||||||
|
picture text,
|
||||||
|
created_at timestamptz NOT NULL DEFAULT now(),
|
||||||
|
used_at timestamptz
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS saved_sheets_account ON dtf_local.saved_sheets(account);
|
||||||
4
app/migrations/202612011000_transfer-prt.sql
Normal file
4
app/migrations/202612011000_transfer-prt.sql
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
-- Marcus, 2026-12-01 (D4): the hot folder takes a PNG in about 10 s, so a
|
||||||
|
-- transfer leaves the old machine's .prt files in the Hoson folder; the
|
||||||
|
-- transfer keeps which ones to delete, for the card and the history.
|
||||||
|
ALTER TABLE dtf_local.machine_transfers ADD COLUMN IF NOT EXISTS delete_prt text[] NOT NULL DEFAULT '{}';
|
||||||
@@ -24,14 +24,20 @@ from .runtime import PUBLIC_ORIGIN, enqueue, upload_row
|
|||||||
from .scanning import require_clean
|
from .scanning import require_clean
|
||||||
|
|
||||||
QUOTE_VALID_HOURS = 24
|
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):
|
class PaymentRefused(Exception):
|
||||||
"""The payment cannot become an order, with a reason worth recording."""
|
"""The payment cannot become an order, with a reason worth recording."""
|
||||||
|
|
||||||
|
|
||||||
def approved_quote(c, quote_id, owner=None):
|
def approved_quote(c, quote_id, owner=None, payment_id=None):
|
||||||
"""The reviewed quote behind a payment, or a refusal explaining why not."""
|
"""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 '')
|
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()
|
row = c.execute(sql + ' FOR UPDATE', (quote_id, owner) if owner else (quote_id,)).fetchone()
|
||||||
if not row:
|
if not row:
|
||||||
@@ -42,8 +48,13 @@ def approved_quote(c, quote_id, owner=None):
|
|||||||
raise PaymentRefused('quote was discarded')
|
raise PaymentRefused('quote was discarded')
|
||||||
if any(item.get('production', {}).get('version') not in PRODUCTION_VERSIONS for item in row['approved']['items']):
|
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')
|
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)
|
||||||
raise PaymentRefused('quote expired before payment')
|
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
|
return row
|
||||||
|
|
||||||
|
|
||||||
@@ -240,7 +251,7 @@ def apply(c, event):
|
|||||||
return 'refused: reference is not a quote id'
|
return 'refused: reference is not a quote id'
|
||||||
|
|
||||||
try:
|
try:
|
||||||
quote = approved_quote(c, quote_id)
|
quote = approved_quote(c, quote_id, payment_id=provider_id)
|
||||||
except PaymentRefused as refusal:
|
except PaymentRefused as refusal:
|
||||||
return f'refused: {refusal}'
|
return f'refused: {refusal}'
|
||||||
|
|
||||||
@@ -255,7 +266,16 @@ def apply(c, event):
|
|||||||
return f'refused: paid {event.amount_cents} but quote total is {expected}'
|
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')
|
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):
|
def reconcile(connect, provider, quote_id=None, limit=20):
|
||||||
@@ -273,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')
|
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.created_at > now() - make_interval(hours => %s)''' +
|
||||||
(' AND i.quote_id=%s' if quote_id else '') + ' ORDER BY i.created_at DESC LIMIT %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 = []
|
outcomes = []
|
||||||
for row in rows:
|
for row in rows:
|
||||||
# Asked outside any transaction: no lock is held while the provider answers.
|
# 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 PIL import Image, ImageOps
|
||||||
|
|
||||||
from .core.models import PRODUCTION_VERSIONS
|
from .core.models import PRODUCTION_VERSIONS
|
||||||
|
from .core.pricing import STEP_GRACE_M
|
||||||
|
|
||||||
PT_PER_CM = 72 / 2.54
|
PT_PER_CM = 72 / 2.54
|
||||||
# Acrobat's page limit, 200 inches (5,08 m). A longer sheet is written at its
|
# 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']
|
production = item['production']
|
||||||
height = Decimal(str(production['height_cm']))
|
height = Decimal(str(production['height_cm']))
|
||||||
billed = Decimal(str(item['billed_metres'])) * 100
|
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')
|
raise Unsupported(f'a montagem tem {height} cm, mas só {billed} cm foram cobrados')
|
||||||
lowest = None
|
lowest = None
|
||||||
for placement in production['placements']:
|
for placement in production['placements']:
|
||||||
|
|||||||
@@ -336,11 +336,22 @@ def file_prefix(number, item_index, generation=1):
|
|||||||
return f'DTF-{number}{version}-item-{item_index + 1}'
|
return f'DTF-{number}{version}-item-{item_index + 1}'
|
||||||
|
|
||||||
|
|
||||||
|
def _footer_name(name):
|
||||||
|
"""A customer name for the footer: tidy, printable in cp1252 and at most
|
||||||
|
24 characters, the last one an ellipsis when cut."""
|
||||||
|
cleaned = ' '.join(str(name or '').split())
|
||||||
|
cleaned = cleaned.encode('cp1252', 'ignore').decode('cp1252')
|
||||||
|
cleaned = ' '.join(cleaned.split())
|
||||||
|
if len(cleaned) > 24:
|
||||||
|
cleaned = cleaned[:23] + '…'
|
||||||
|
return cleaned
|
||||||
|
|
||||||
|
|
||||||
def footer(job, item):
|
def footer(job, item):
|
||||||
"""The print file's footer line: DROPSTAR · Pedido DTF-123 · Item 1/2 ·
|
"""The print file's footer line: DROPSTAR · Pedido DTF-123 · <customer> ·
|
||||||
21/10/2026 · 0,90 m, and · ESPELHADO when the artwork is mirrored. The
|
Item 1/2 · 21/10/2026 · 0,90 m · <pieces>, and · ESPELHADO when the
|
||||||
order is named by its Kanban number, which Tiny keeps; the length is the
|
artwork is mirrored. The order is named by its Kanban number, which Tiny
|
||||||
one billed."""
|
keeps; the length is the one billed."""
|
||||||
count = len(job['snapshot']['items'])
|
count = len(job['snapshot']['items'])
|
||||||
day = job['ordered_at'].astimezone(LOCAL).strftime('%d/%m/%Y')
|
day = job['ordered_at'].astimezone(LOCAL).strftime('%d/%m/%Y')
|
||||||
billed = f"{Decimal(str(item['billed_metres'])):.2f}".replace('.', ',')
|
billed = f"{Decimal(str(item['billed_metres'])):.2f}".replace('.', ',')
|
||||||
@@ -348,11 +359,25 @@ def footer(job, item):
|
|||||||
if proof_of:
|
if proof_of:
|
||||||
return ' · '.join(['DROPSTAR', f'PROVA do #{proof_of}',
|
return ' · '.join(['DROPSTAR', f'PROVA do #{proof_of}',
|
||||||
f'Classe {item.get("stroke_class") or "C3"}', day])
|
f'Classe {item.get("stroke_class") or "C3"}', day])
|
||||||
fields = ['DROPSTAR', f'Pedido {purchase_order(job["number"])}',
|
fields = ['DROPSTAR', f'Pedido {purchase_order(job["number"])}']
|
||||||
f'Item {job["item_index"] + 1}/{count}', day, f'{billed} m']
|
customer = _footer_name((job['snapshot'].get('customer') or {}).get('name'))
|
||||||
|
if customer:
|
||||||
|
fields.append(customer)
|
||||||
|
fields += [f'Item {job["item_index"] + 1}/{count}', day, f'{billed} m']
|
||||||
|
production = item.get('production') or {}
|
||||||
|
sources = production.get('sources') or []
|
||||||
|
placements = production.get('placements') or []
|
||||||
|
if any(source.get('kind') == 'artwork' for source in sources):
|
||||||
|
pieces = len(placements)
|
||||||
|
if pieces:
|
||||||
|
fields.append(f'{pieces} peça' if pieces == 1 else f'{pieces} peças')
|
||||||
|
elif any(source.get('kind') == 'sheet' for source in sources):
|
||||||
|
copies = sum(source.get('copies') or 0 for source in sources)
|
||||||
|
if copies > 1:
|
||||||
|
fields.append(f'{copies} cópias')
|
||||||
# A mirrored artwork (UV only) is named on the sheet, for the room to see
|
# A mirrored artwork (UV only) is named on the sheet, for the room to see
|
||||||
# before printing (Dropstar, 2026-10-23).
|
# before printing (Dropstar, 2026-10-23).
|
||||||
if any(source.get('mirrored') for source in item['production']['sources']):
|
if any(source.get('mirrored') for source in sources):
|
||||||
fields.append('ESPELHADO')
|
fields.append('ESPELHADO')
|
||||||
return ' · '.join(fields)
|
return ' · '.join(fields)
|
||||||
|
|
||||||
|
|||||||
@@ -48,6 +48,8 @@ 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.
|
# A cut through artwork only when no gap between pieces is this close to the limit.
|
||||||
CUT_SEARCH_CM = Decimal('200')
|
CUT_SEARCH_CM = Decimal('200')
|
||||||
BAND_ROWS = 512
|
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.
|
# Above this a source is read band by band instead of decoded whole.
|
||||||
STREAM_ABOVE_PIXELS = 40_000_000
|
STREAM_ABOVE_PIXELS = 40_000_000
|
||||||
FOOTER_TEXT_CM = 1.1
|
FOOTER_TEXT_CM = 1.1
|
||||||
@@ -268,9 +270,44 @@ class Source:
|
|||||||
top, bottom = round(height * top_cm / full_cm), round(height * bottom_cm / full_cm)
|
top, bottom = round(height * top_cm / full_cm), round(height * bottom_cm / full_cm)
|
||||||
if top + bottom >= height:
|
if top + bottom >= height:
|
||||||
raise Unsupported(f'"{self.name}": o corte das faixas vazias tiraria o arquivo inteiro')
|
raise Unsupported(f'"{self.name}": o corte das faixas vazias tiraria o arquivo inteiro')
|
||||||
|
self._require_clear(top, bottom)
|
||||||
self.cut = (top, bottom)
|
self.cut = (top, bottom)
|
||||||
self.size = (width, height - 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):
|
def decoded(self, width, height):
|
||||||
"""The whole file at (width, height) px, upright, RGBA."""
|
"""The whole file at (width, height) px, upright, RGBA."""
|
||||||
if self.pdf:
|
if self.pdf:
|
||||||
|
|||||||
34
app/prumo.py
34
app/prumo.py
@@ -59,6 +59,15 @@ def report(order, uploads):
|
|||||||
lines = []
|
lines = []
|
||||||
if snapshot.get('proof_of'):
|
if snapshot.get('proof_of'):
|
||||||
lines.append(f'Prova do pedido #{snapshot["proof_of"]}')
|
lines.append(f'Prova do pedido #{snapshot["proof_of"]}')
|
||||||
|
batch = snapshot.get('batch') or {}
|
||||||
|
if batch:
|
||||||
|
skipped = batch.get('skipped') or []
|
||||||
|
summary = f'Lista colada: {batch.get("lines", 0)} linhas montadas'
|
||||||
|
if skipped:
|
||||||
|
summary += f', {len(skipped)} puladas'
|
||||||
|
lines.append(summary)
|
||||||
|
for row in skipped:
|
||||||
|
lines.append(f'Linha {row.get("line")} pulada ({row.get("reason")}): {row.get("text")}')
|
||||||
multi = len(items) > 1
|
multi = len(items) > 1
|
||||||
for index, item in enumerate(items):
|
for index, item in enumerate(items):
|
||||||
lead = f'Item {index + 1}: ' if multi else ''
|
lead = f'Item {index + 1}: ' if multi else ''
|
||||||
@@ -103,6 +112,27 @@ def report(order, uploads):
|
|||||||
lines.append(f'{lead}{len(placements)} arte{"s" if len(placements) != 1 else ""}, '
|
lines.append(f'{lead}{len(placements)} arte{"s" if len(placements) != 1 else ""}, '
|
||||||
f'{rotated} girada{"s" if rotated != 1 else ""} (couberam melhor), '
|
f'{rotated} girada{"s" if rotated != 1 else ""} (couberam melhor), '
|
||||||
f'altura {_cm(production.get("height_cm"))} cm')
|
f'altura {_cm(production.get("height_cm"))} cm')
|
||||||
|
# The size the PNG said it had (item A1, round 5): whether the
|
||||||
|
# customer kept it or changed it.
|
||||||
|
for k, source in enumerate(production.get('sources') or []):
|
||||||
|
saved = source.get('saved_width_cm')
|
||||||
|
if not saved:
|
||||||
|
continue
|
||||||
|
width = Decimal(str(source.get('width_cm')))
|
||||||
|
length = Decimal(str(source.get('length_cm')))
|
||||||
|
# Turned 90°, the art's own width runs along the film.
|
||||||
|
if source.get('rotation_degrees') == 90:
|
||||||
|
width, length = length, width
|
||||||
|
saved_w = Decimal(str(saved))
|
||||||
|
altura = saved_w * length / width if width else Decimal(0)
|
||||||
|
dpi = source.get('saved_dpi')
|
||||||
|
if abs(width - saved_w) < Decimal('0.05'):
|
||||||
|
lines.append(f'{lead}Arte {k + 1}: tamanho lido do arquivo '
|
||||||
|
f'{_cm(saved_w)} × {_cm(altura)} cm ({dpi} DPI), mantido')
|
||||||
|
else:
|
||||||
|
lines.append(f'{lead}Arte {k + 1}: tamanho lido do arquivo '
|
||||||
|
f'{_cm(saved_w)} × {_cm(altura)} cm ({dpi} DPI), '
|
||||||
|
f'alterado pelo cliente para {_cm(width)} cm')
|
||||||
# The empty strips the Site cut from a ready sheet (Marcus, 2026-11-18).
|
# The empty strips the Site cut from a ready sheet (Marcus, 2026-11-18).
|
||||||
trimmed = sum(Decimal(str(s.get('trim_top_cm') or 0)) + Decimal(str(s.get('trim_bottom_cm') or 0))
|
trimmed = sum(Decimal(str(s.get('trim_top_cm') or 0)) + Decimal(str(s.get('trim_bottom_cm') or 0))
|
||||||
for s in production.get('sources') or [])
|
for s in production.get('sources') or [])
|
||||||
@@ -114,9 +144,9 @@ def report(order, uploads):
|
|||||||
if item.get('stroke_px') and item.get('stroke_class'):
|
if item.get('stroke_px') and item.get('stroke_class'):
|
||||||
lines.append(f'{lead}Menor traço {item["stroke_px"]} px → {item["stroke_class"]}')
|
lines.append(f'{lead}Menor traço {item["stroke_px"]} px → {item["stroke_class"]}')
|
||||||
if item.get('stroke_choice') == 'client_c3':
|
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':
|
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:
|
else:
|
||||||
lines.append(f'{lead}Aviso de traço fino não disparou')
|
lines.append(f'{lead}Aviso de traço fino não disparou')
|
||||||
if row:
|
if row:
|
||||||
|
|||||||
@@ -124,46 +124,64 @@ def check_large(head, row):
|
|||||||
return 'rejected', 'O conteúdo do arquivo não corresponde ao formato do nome'
|
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):
|
def scan_one(storage, scanner=None):
|
||||||
|
global busy_since
|
||||||
scanner=scanner or ClamAV()
|
scanner=scanner or ClamAV()
|
||||||
with connect() as c:
|
with connect() as c:
|
||||||
row=c.execute('''SELECT * FROM dtf_local.uploads WHERE complete AND purged_at IS NULL
|
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()
|
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()
|
ORDER BY created_at FOR UPDATE SKIP LOCKED LIMIT 1''').fetchone()
|
||||||
if not row:return False
|
if not row:return False
|
||||||
name=row['name']
|
busy_since=time.monotonic()
|
||||||
try:
|
try:
|
||||||
# Every later decision reads the stored name (the manual charge,
|
_scan_row(c, storage, scanner, row)
|
||||||
# the JPG refusal, the grade, the print file, the folders), so the
|
finally:
|
||||||
# name is made to say what the file is (D-13).
|
busy_since=None
|
||||||
head=head_of(storage,row)
|
|
||||||
name=real_name(name,head)
|
|
||||||
if row['size'] > scan_limit_bytes():
|
|
||||||
state,reason=check_large(head,row)
|
|
||||||
else:
|
|
||||||
stream=storage.client.get_object(Bucket=storage.bucket,Key=row['object_key'])['Body']
|
|
||||||
try:state,reason=scanner.scan(stream,row['size'])
|
|
||||||
finally:stream.close()
|
|
||||||
except Exception:
|
|
||||||
state,reason='error','Malware scanner unavailable; file remains blocked'
|
|
||||||
# A PDF's resolution is worked out here, once, so checkout never reads
|
|
||||||
# it (Critical Corrections 2). A failure leaves it for the fallback.
|
|
||||||
checked,pdf_dpi_value=False,None
|
|
||||||
if state=='clean' and name.lower().endswith('.pdf'):
|
|
||||||
try:
|
|
||||||
pdf_dpi_value=stored_pdf_dpi(storage,row)
|
|
||||||
checked=True
|
|
||||||
except Exception:
|
|
||||||
logging.exception('Could not work out the PDF DPI of upload %s',row['id'])
|
|
||||||
c.execute("""UPDATE dtf_local.uploads SET name=%s,scan_state=%s,scan_reason=%s,scanned_at=now(),
|
|
||||||
scan_after=now()+interval '1 minute',
|
|
||||||
pdf_checked=CASE WHEN %s THEN true ELSE pdf_checked END,
|
|
||||||
pdf_dpi=CASE WHEN %s THEN %s ELSE pdf_dpi END,
|
|
||||||
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
|
return True
|
||||||
|
|
||||||
|
def _scan_row(c, storage, scanner, row):
|
||||||
|
name=row['name']
|
||||||
|
try:
|
||||||
|
# Every later decision reads the stored name (the manual charge,
|
||||||
|
# the JPG refusal, the grade, the print file, the folders), so the
|
||||||
|
# name is made to say what the file is (D-13).
|
||||||
|
head=head_of(storage,row)
|
||||||
|
name=real_name(name,head)
|
||||||
|
if row['size'] > scan_limit_bytes():
|
||||||
|
state,reason=check_large(head,row)
|
||||||
|
else:
|
||||||
|
stream=storage.client.get_object(Bucket=storage.bucket,Key=row['object_key'])['Body']
|
||||||
|
try:state,reason=scanner.scan(stream,row['size'])
|
||||||
|
finally:stream.close()
|
||||||
|
except Exception:
|
||||||
|
state,reason='error','Malware scanner unavailable; file remains blocked'
|
||||||
|
# A PDF's resolution is worked out here, once, so checkout never reads
|
||||||
|
# it (Critical Corrections 2). A failure leaves it for the fallback.
|
||||||
|
checked,pdf_dpi_value=False,None
|
||||||
|
if state=='clean' and name.lower().endswith('.pdf'):
|
||||||
|
try:
|
||||||
|
pdf_dpi_value=stored_pdf_dpi(storage,row)
|
||||||
|
checked=True
|
||||||
|
except Exception:
|
||||||
|
logging.exception('Could not work out the PDF DPI of upload %s',row['id'])
|
||||||
|
c.execute("""UPDATE dtf_local.uploads SET name=%s,scan_state=%s,scan_reason=%s,scanned_at=now(),
|
||||||
|
scan_after=now()+interval '1 minute',
|
||||||
|
pdf_checked=CASE WHEN %s THEN true ELSE pdf_checked END,
|
||||||
|
pdf_dpi=CASE WHEN %s THEN %s ELSE pdf_dpi END,
|
||||||
|
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)
|
||||||
|
|
||||||
def scan_loop(storage):
|
def scan_loop(storage):
|
||||||
while True:
|
while True:
|
||||||
try:
|
try:
|
||||||
|
|||||||
@@ -144,9 +144,15 @@ PICKUP_EXACT = 'retirar pessoalmente'
|
|||||||
# "CORREÇÃO DTF", used for it before, is for correction orders only. "Boleto" is
|
# "CORREÇÃO DTF", used for it before, is for correction orders only. "Boleto" is
|
||||||
# for a montador Venda order (front 7a.3); no id is known yet, and while
|
# for a montador Venda order (front 7a.3); no id is known yet, and while
|
||||||
# TINY_RECEIPT_BOLETO is empty the order goes without a forma de recebimento.
|
# TINY_RECEIPT_BOLETO is empty the order goes without a forma de recebimento.
|
||||||
|
# Cartão de crédito stays 977460722, read from a store order on 2026-10-19:
|
||||||
|
# the 919478945 Marcus named on 2026-12-01 is not enabled in Tiny ("Forma de
|
||||||
|
# recebimento não está habilitada", DTF-API-C), so it waits for his answer.
|
||||||
_BOLETO = os.environ.get('TINY_RECEIPT_BOLETO', '').strip()
|
_BOLETO = os.environ.get('TINY_RECEIPT_BOLETO', '').strip()
|
||||||
RECEIPT_METHODS = {'pix': 919478952, 'card': 977460722, 'cash': 919478944, 'credit': 987762591,
|
RECEIPT_METHODS = {'pix': 919478952, 'card': 977460722, 'cash': 919478944, 'credit': 987762591,
|
||||||
**({'faturado': int(_BOLETO)} if _BOLETO.isdigit() else {})}
|
**({'faturado': int(_BOLETO)} if _BOLETO.isdigit() else {})}
|
||||||
|
# A Pix or card paid on the Site names no account ("meio de pagamento"): Tiny
|
||||||
|
# answered "Meio de pagamento não encontrado" to MERCADO PAGO, 977344550, the id
|
||||||
|
# Marcus gave on 2026-12-01 (DTF-API-C, #196 and #198), so it waits for his answer.
|
||||||
PICKUP_CARRIER = 761565838
|
PICKUP_CARRIER = 761565838
|
||||||
# Dropstar's answers: the financial category "DTF SITE" (RECEITAS, id sent on
|
# Dropstar's answers: the financial category "DTF SITE" (RECEITAS, id sent on
|
||||||
# 2026-10-26; it goes in pagamento.categoria, and replaced the store's
|
# 2026-10-26; it goes in pagamento.categoria, and replaced the store's
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ abandonment rate.
|
|||||||
from datetime import datetime, timedelta, timezone
|
from datetime import datetime, timedelta, timezone
|
||||||
|
|
||||||
from . import mail, payments
|
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
|
# An intent in one of these no longer waits for money: approved (it became an
|
||||||
# order), rejected, cancelled, expired or refunded (app/payments.py).
|
# 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
|
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)
|
WHERE i2.quote_id=q.id ORDER BY i2.created_at DESC LIMIT 1)
|
||||||
AND i.status <> ALL(%s)
|
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
|
AND (i.response->>'expires_at' IS NULL
|
||||||
OR (i.response->>'expires_at')::timestamptz > now()))
|
OR (i.response->>'expires_at')::timestamptz > now()))
|
||||||
ORDER BY q.approved_at LIMIT 50 FOR UPDATE OF q SKIP LOCKED''',
|
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:
|
for row in rows:
|
||||||
c.execute('UPDATE dtf_local.quotes SET expired_at=now() WHERE id=%s', (row['id'],))
|
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
|
# 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
|
import psycopg
|
||||||
from botocore.exceptions import ClientError
|
from botocore.exceptions import ClientError
|
||||||
from psycopg.types.json import Jsonb
|
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 .adapters import FakeTiny, LocalS3Storage, require_runtime
|
||||||
from .core.secrets import load as load_secret_files
|
from .core.secrets import load as load_secret_files
|
||||||
from .core.db import connect
|
from .core.db import connect
|
||||||
@@ -17,12 +17,37 @@ from .scanning import ClamAV, scan_loop
|
|||||||
|
|
||||||
load_secret_files()
|
load_secret_files()
|
||||||
require_runtime()
|
require_runtime()
|
||||||
adapters = {'tiny': FakeTiny()}
|
# Production without the real Tiny (TINY_ADAPTER missing from the stack):
|
||||||
# Not yet confirmed against the client's account; see app/tiny.py.
|
# the sends wait and Sentry is told, instead of the simulator marking real
|
||||||
if os.environ.get('TINY_ADAPTER') == 'tiny':
|
# orders delivered with made-up receipts that had to be queued again by hand.
|
||||||
from .tiny import TinyOrders
|
HELD = 'Tiny desligado em produção (TINY_ADAPTER não é tiny): o envio espera'
|
||||||
from .cnpj import company
|
|
||||||
adapters['tiny'] = TinyOrders(names=company)
|
|
||||||
|
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
|
||||||
|
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_tick = 0.0
|
||||||
last_cleanup = 0.0
|
last_cleanup = 0.0
|
||||||
last_reconcile = 0.0
|
last_reconcile = 0.0
|
||||||
@@ -180,13 +205,25 @@ def loop():
|
|||||||
delay = 1
|
delay = 1
|
||||||
time.sleep(1)
|
time.sleep(1)
|
||||||
|
|
||||||
|
scan_stuck_reported = False
|
||||||
|
|
||||||
class Health(BaseHTTPRequestHandler):
|
class Health(BaseHTTPRequestHandler):
|
||||||
def do_GET(self):
|
def do_GET(self):
|
||||||
|
global scan_stuck_reported
|
||||||
scanner = False
|
scanner = False
|
||||||
try:
|
try:
|
||||||
scanner = bool(scan_thread and scan_thread.is_alive() and ClamAV().ping())
|
scanner = bool(scan_thread and scan_thread.is_alive() and ClamAV().ping())
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
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())
|
renderer = bool(render_thread and render_thread.is_alive())
|
||||||
healthy = time.monotonic()-last_tick < 15 and scanner and renderer
|
healthy = time.monotonic()-last_tick < 15 and scanner and renderer
|
||||||
self.send_response(200 if self.path == '/health' and healthy else 503)
|
self.send_response(200 if self.path == '/health' and healthy else 503)
|
||||||
@@ -199,6 +236,14 @@ class Health(BaseHTTPRequestHandler):
|
|||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
observability.init('worker')
|
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 = threading.Thread(target=scan_loop,args=(storage,),daemon=True)
|
||||||
scan_thread.start()
|
scan_thread.start()
|
||||||
render_thread = threading.Thread(target=render_loop,args=(storage,),daemon=True)
|
render_thread = threading.Thread(target=render_loop,args=(storage,),daemon=True)
|
||||||
|
|||||||
@@ -54,7 +54,7 @@ server {
|
|||||||
try_files /index.html =404;
|
try_files /index.html =404;
|
||||||
}
|
}
|
||||||
# The customer's area: one page, which shows the right part for each address.
|
# The customer's area: one page, which shows the right part for each address.
|
||||||
location ~ ^/conta(/(entrar|pedidos|dados|redefinir))?/?$ {
|
location ~ ^/conta(/(entrar|pedidos|dados|redefinir|folhas))?/?$ {
|
||||||
expires -1;
|
expires -1;
|
||||||
try_files /portal.html =404;
|
try_files /portal.html =404;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -41,9 +41,9 @@ SOURCE_BLOCKERS = {
|
|||||||
'app/runtime.py': (
|
'app/runtime.py': (
|
||||||
'payment = FakePayment()',
|
'payment = FakePayment()',
|
||||||
),
|
),
|
||||||
'app/worker.py': (
|
# app/worker.py's "adapters = {'tiny': FakeTiny()}" left on 2026-11-27: in
|
||||||
"adapters = {'tiny': FakeTiny()}",
|
# 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):
|
def test_fake_checkout_is_explicitly_blocked(self):
|
||||||
errors = source_errors()
|
errors = source_errors()
|
||||||
self.assertTrue(any('app/runtime.py remains local-only' in error for error in 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):
|
def test_secret_reuse_and_incoherent_limits_are_rejected(self):
|
||||||
values = valid_config()
|
values = valid_config()
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ server {
|
|||||||
try_files /index.html =404;
|
try_files /index.html =404;
|
||||||
}
|
}
|
||||||
# The customer's area: one page, which shows the right part for each address.
|
# The customer's area: one page, which shows the right part for each address.
|
||||||
location ~ ^/conta(/(entrar|pedidos|dados|redefinir))?/?$ {
|
location ~ ^/conta(/(entrar|pedidos|dados|redefinir|folhas))?/?$ {
|
||||||
try_files /portal.html =404;
|
try_files /portal.html =404;
|
||||||
}
|
}
|
||||||
location ~ ^/termos/?$ {
|
location ~ ^/termos/?$ {
|
||||||
|
|||||||
@@ -128,11 +128,26 @@ try{
|
|||||||
await call('Input.dispatchKeyEvent',{type:'keyDown',key:'Escape',code:'Escape',windowsVirtualKeyCode:27});
|
await call('Input.dispatchKeyEvent',{type:'keyDown',key:'Escape',code:'Escape',windowsVirtualKeyCode:27});
|
||||||
assert.equal(await evaluate(`document.querySelector('.videoModal').hidden &&
|
assert.equal(await evaluate(`document.querySelector('.videoModal').hidden &&
|
||||||
document.activeElement.classList.contains('videoCard')`),true);
|
document.activeElement.classList.contains('videoCard')`),true);
|
||||||
|
// A home card plays muted and in loop only while it is on screen (Rodada 5,
|
||||||
|
// D7). Chrome here decodes no video, so the test records what the page asks
|
||||||
|
// of the card's player: play when it enters the screen, pause when it leaves.
|
||||||
|
await evaluate(`(()=>{window.cardCalls=[];const P=HTMLMediaElement.prototype;
|
||||||
|
window.realPlay=P.play;window.realPause=P.pause;
|
||||||
|
P.play=function(){if(this.closest('.videoCard'))cardCalls.push('play');return Promise.resolve();};
|
||||||
|
P.pause=function(){if(this.closest('.videoCard'))cardCalls.push('pause');};
|
||||||
|
VIDEOS[0].src='/preview.mp4';videosSection();})()`);
|
||||||
|
assert.deepEqual(await evaluate(`(()=>{const v=document.querySelector('#videosGrid .videoCard video');return {muted:v.muted,loop:v.loop,inline:v.playsInline};})()`),
|
||||||
|
{muted:true,loop:true,inline:true});
|
||||||
|
await evaluate(`window.scrollTo({top:document.querySelector('#videosGrid .videoCard').getBoundingClientRect().top+scrollY-200,behavior:'instant'})`);
|
||||||
|
await waitFor(()=>evaluate(`cardCalls.at(-1)==='play'`),'home video card plays on screen');
|
||||||
|
await evaluate(`window.scrollTo({top:0,behavior:'instant'})`);
|
||||||
|
await waitFor(()=>evaluate(`cardCalls.at(-1)==='pause'`),'home video card pauses off screen');
|
||||||
|
await evaluate(`HTMLMediaElement.prototype.play=realPlay;HTMLMediaElement.prototype.pause=realPause`);
|
||||||
await evaluate(`VIDEOS[0].src=null;videosSection()`);
|
await evaluate(`VIDEOS[0].src=null;videosSection()`);
|
||||||
// Observe the actual engine, without replacing its placement or rendering.
|
// Observe the actual engine, without replacing its placement or rendering.
|
||||||
await evaluate(`(()=>{
|
await evaluate(`(()=>{
|
||||||
const original=encaixar;
|
const original=encaixar;
|
||||||
encaixar=(pieces,width)=>{const result=original(pieces,width);
|
encaixar=(pieces,width,...rest)=>{const result=original(pieces,width,...rest);
|
||||||
if(pieces.some(p=>p.a))window.lastLayout={altura:result.altura,pos:result.pos.map(p=>({x:p.x,y:p.y,w:p.w,h:p.h,rot:p.rot}))};
|
if(pieces.some(p=>p.a))window.lastLayout={altura:result.altura,pos:result.pos.map(p=>({x:p.x,y:p.y,w:p.w,h:p.h,rot:p.rot}))};
|
||||||
return result;};
|
return result;};
|
||||||
window.sendImage=async(type='image/png',drop=false)=>{
|
window.sendImage=async(type='image/png',drop=false)=>{
|
||||||
@@ -219,7 +234,7 @@ try{
|
|||||||
// JPG has no transparency: refused in loose artwork as in a sheet (Dropstar,
|
// JPG has no transparency: refused in loose artwork as in a sheet (Dropstar,
|
||||||
// 2026-10-23), with the reason, before anything is read.
|
// 2026-10-23), with the reason, before anything is read.
|
||||||
await evaluate(`sel([new File(['x'],'arte.jpg',{type:'image/jpeg'})])`);
|
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.
|
// 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'})])`);
|
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);
|
assert.equal(await evaluate(`artes.length===0 && $('recusa').textContent.includes('disfarce.png é JPG')`),true);
|
||||||
@@ -383,7 +398,7 @@ try{
|
|||||||
// A ready sheet now offers the same acceptance as loose art (Dropstar,
|
// 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.
|
// 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]'),
|
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;
|
await evaluate(`(()=>{const el=document.querySelector('[data-residuo]');el.checked=true;
|
||||||
el.dispatchEvent(new Event('change',{bubbles:true}));})()`);
|
el.dispatchEvent(new Event('change',{bubbles:true}));})()`);
|
||||||
await waitFor(()=>evaluate('itemAtual!==null'),'accepted residue lets the sheet through');
|
await waitFor(()=>evaluate('itemAtual!==null'),'accepted residue lets the sheet through');
|
||||||
|
|||||||
@@ -25,7 +25,13 @@ const pause=ms=>new Promise(r=>setTimeout(r,ms));
|
|||||||
let stderr='';chrome.stderr.on('data',data=>stderr+=data.toString());
|
let stderr='';chrome.stderr.on('data',data=>stderr+=data.toString());
|
||||||
const clients=[];
|
const clients=[];
|
||||||
let kanban,testMachine;
|
let kanban,testMachine;
|
||||||
async function waitFor(fn,description,timeout=30000){const end=Date.now()+timeout;while(Date.now()<end){if(await fn())return;await pause(200);}throw new Error('Timeout: '+description);}
|
// A check run while the page reloads meets the old page closing ("Inspected
|
||||||
|
// target navigated or closed", CI run 397): that one tries again; any other
|
||||||
|
// error still fails the test.
|
||||||
|
const navigating=error=>/navigated or closed|context was destroyed|Cannot find (default )?(execution )?context/i
|
||||||
|
.test(String(error?.message||error));
|
||||||
|
async function waitFor(fn,description,timeout=30000){const end=Date.now()+timeout;while(Date.now()<end){
|
||||||
|
try{if(await fn())return;}catch(error){if(!navigating(error))throw error;}await pause(200);}throw new Error('Timeout: '+description);}
|
||||||
class Page {
|
class Page {
|
||||||
constructor(ws){this.ws=ws;this.next=0;this.pending=new Map();this.errors=[];
|
constructor(ws){this.ws=ws;this.next=0;this.pending=new Map();this.errors=[];
|
||||||
ws.onmessage=event=>{const d=JSON.parse(event.data);if(d.id){const p=this.pending.get(d.id);if(p){this.pending.delete(d.id);d.error?p.reject(d.error):p.resolve(d.result);}}else if(d.method==='Runtime.exceptionThrown')this.errors.push(d.params.exceptionDetails);};
|
ws.onmessage=event=>{const d=JSON.parse(event.data);if(d.id){const p=this.pending.get(d.id);if(p){this.pending.delete(d.id);d.error?p.reject(d.error):p.resolve(d.result);}}else if(d.method==='Runtime.exceptionThrown')this.errors.push(d.params.exceptionDetails);};
|
||||||
@@ -91,7 +97,7 @@ try{
|
|||||||
const itemCents=Math.round(1.1*(1990+extraCents));
|
const itemCents=Math.round(1.1*(1990+extraCents));
|
||||||
const total=Math.round(itemCents)/100;
|
const total=Math.round(itemCents)/100;
|
||||||
await waitFor(()=>site.eval(`Math.abs(itemAtual.total-${total})<0.005`),'manual-file price');
|
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('#fNome','Cliente Teste');
|
||||||
await site.fill('#fCnpj','11222333000181');
|
await site.fill('#fCnpj','11222333000181');
|
||||||
await site.fill('#fZap','11999999999');
|
await site.fill('#fZap','11999999999');
|
||||||
|
|||||||
@@ -33,15 +33,16 @@ def run():
|
|||||||
manager = manager.operator_client
|
manager = manager.operator_client
|
||||||
coupon_id = None
|
coupon_id = None
|
||||||
quote_id = None
|
quote_id = None
|
||||||
|
early_id = None
|
||||||
order_id = None
|
order_id = None
|
||||||
upload_id = None
|
upload_id = None
|
||||||
try:
|
try:
|
||||||
upload_id = upload_bytes(client, artwork(), name=f'LOCAL-COUPON-{tag}.png')
|
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}
|
'quality_status': 'warning', 'quality_acknowledged': True}
|
||||||
# The sheet is the customer's own file, not one someone opens by hand.
|
# The sheet is the customer's own file, not one someone opens by hand.
|
||||||
sheet['production']['sources'][0]['measurement'] = 'file'
|
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}
|
'quality_status': 'warning', 'quality_acknowledged': True}
|
||||||
items = [sheet, art]
|
items = [sheet, art]
|
||||||
|
|
||||||
@@ -61,6 +62,9 @@ def run():
|
|||||||
assert [line['total_cents'] for line in approved['items']] == [7990, 8990], approved
|
assert [line['total_cents'] for line in approved['items']] == [7990, 8990], approved
|
||||||
assert approved['total_cents'] == 16081, 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).
|
# One paid order spends a use (a fake payment, no print job).
|
||||||
order_id = uuid4()
|
order_id = uuid4()
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
@@ -110,6 +114,10 @@ def run():
|
|||||||
manager.call('/operator/site/coupons/' + coupon_id, {'max_uses': 1})
|
manager.call('/operator/site/coupons/' + coupon_id, {'max_uses': 1})
|
||||||
refused = quote(client, items, code, mail, expected=422)
|
refused = quote(client, items, code, mail, expected=422)
|
||||||
assert refused['detail'] == 'Este cupom já foi usado o máximo de vezes.', refused
|
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,
|
manager.call('/operator/site/coupons/' + coupon_id,
|
||||||
{'max_uses': None, 'max_uses_per_customer': 1})
|
{'max_uses': None, 'max_uses_per_customer': 1})
|
||||||
refused = quote(client, items, code, mail, expected=422)
|
refused = quote(client, items, code, mail, expected=422)
|
||||||
@@ -135,13 +143,16 @@ def run():
|
|||||||
stats = manager.call('/operator/stats?days=30')
|
stats = manager.call('/operator/stats?days=30')
|
||||||
assert any(entry['id'] == coupon_id for entry in stats['coupons']), stats['coupons']
|
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/'
|
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:
|
finally:
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
if order_id:
|
if order_id:
|
||||||
c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (order_id,))
|
c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (order_id,))
|
||||||
if quote_id:
|
if quote_id:
|
||||||
c.execute('DELETE FROM dtf_local.quotes WHERE id=%s', (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:
|
if coupon_id:
|
||||||
c.execute('DELETE FROM dtf_local.coupons WHERE id=%s', (coupon_id,))
|
c.execute('DELETE FROM dtf_local.coupons WHERE id=%s', (coupon_id,))
|
||||||
if upload_id:
|
if upload_id:
|
||||||
|
|||||||
@@ -44,11 +44,11 @@ def run():
|
|||||||
assert rules['treatment_offered'] is True, rules
|
assert rules['treatment_offered'] is True, rules
|
||||||
|
|
||||||
upload_id = upload_bytes(client, artwork(), name=f'LOCAL-GRADE-{tag}.png')
|
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}
|
'quality_status': 'warning', 'quality_acknowledged': True}
|
||||||
|
|
||||||
refused = client.call('/quotes', quote_body(item, False, mail), expected=422)
|
refused = client.call('/quotes', quote_body(item, False, mail), expected=422)
|
||||||
assert refused['detail'] == ('Sua arte tem nota 50: para imprimir com qualidade, '
|
assert refused['detail'] == ('Sua arte está abaixo da resolução mínima, então '
|
||||||
'o Ajuste Fino é obrigatório neste pedido.'), refused
|
'o Ajuste Fino é obrigatório neste pedido.'), refused
|
||||||
|
|
||||||
made = client.call('/quotes', quote_body(item, True, mail))
|
made = client.call('/quotes', quote_body(item, True, mail))
|
||||||
|
|||||||
99
tests/machine_transfer_test.py
Normal file
99
tests/machine_transfer_test.py
Normal file
@@ -0,0 +1,99 @@
|
|||||||
|
"""An order in Imprimindo changes machine: Gestão says which part the new one
|
||||||
|
resumes from, the reason stays for the Revisor, and the old machine's .prt
|
||||||
|
files from that part on are named for the operator to delete (Rodada 5, D4;
|
||||||
|
Marcus, 2026-12-01)."""
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
from app.core import db
|
||||||
|
from tests.smoke_test import Client
|
||||||
|
from tests.users_test import PASSWORD, order_fixture, signed_in
|
||||||
|
|
||||||
|
|
||||||
|
def run():
|
||||||
|
client = Client()
|
||||||
|
client.call('/session')
|
||||||
|
tag = uuid4().hex[:6]
|
||||||
|
machine = client.call('/operator/machines', {'name': f'Transfere A {tag}', 'products': ['textil']},
|
||||||
|
operator=True)['id']
|
||||||
|
other = client.call('/operator/machines', {'name': f'Transfere B {tag}', 'products': ['textil']},
|
||||||
|
operator=True)['id']
|
||||||
|
email = f'transfere-{tag}@example.test'
|
||||||
|
operator_id = client.call('/operator/users', {'name': 'Operador', 'email': email, 'role': 'operador',
|
||||||
|
'password': PASSWORD}, operator=True)['id']
|
||||||
|
owner = uuid4()
|
||||||
|
quote = order = None
|
||||||
|
try:
|
||||||
|
with db.connect() as c:
|
||||||
|
quote, order = order_fixture(c, owner, 'file')
|
||||||
|
upload = uuid4()
|
||||||
|
c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,complete,
|
||||||
|
expires_at,scan_state) VALUES(%s,%s,'transfer-test.png',1,%s,'',true,now()+interval '1 day','clean')''',
|
||||||
|
(upload, owner, f'originals/transfer-test-{upload}'))
|
||||||
|
c.execute('''UPDATE dtf_local.orders SET state='imp', machine_id=%s, machine_chosen=true
|
||||||
|
WHERE id=%s''', (machine, order))
|
||||||
|
for seq, state in enumerate(('consumed', 'consumed', 'written', 'queued'), 1):
|
||||||
|
c.execute('''INSERT INTO dtf_local.hot_parts(order_id,round,seq,item_index,upload_id,name,state)
|
||||||
|
VALUES(%s,1,%s,0,%s,%s,%s)''', (order, seq, upload, f'parte {seq}.png', state))
|
||||||
|
path = f'/operator/orders/{order}/transfer'
|
||||||
|
# The reason is required, even if only spaces.
|
||||||
|
answer = client.call(path, {'machine_id': other, 'reason': ' '}, operator=True, expected=422)
|
||||||
|
assert answer['detail'] == 'Escreva o motivo da transferência.', answer
|
||||||
|
# It only goes to another machine.
|
||||||
|
answer = client.call(path, {'machine_id': machine, 'reason': 'quebrou'}, operator=True, expected=409)
|
||||||
|
assert answer['detail'] == 'O pedido já está nessa máquina.', answer
|
||||||
|
# The old machine took parts 1 and 2: the part to resume from is asked,
|
||||||
|
# and it must be one of the order's.
|
||||||
|
answer = client.call(path, {'machine_id': other, 'reason': 'quebrou'}, operator=True, expected=422)
|
||||||
|
assert answer['detail'] == 'Escolha de qual parte a nova máquina recomeça.', answer
|
||||||
|
answer = client.call(path, {'machine_id': other, 'reason': 'quebrou', 'resume_from': 9},
|
||||||
|
operator=True, expected=422)
|
||||||
|
assert answer['detail'] == 'Essa parte não existe neste pedido.', answer
|
||||||
|
# Part 1 was printed, part 2 was waiting in the Hoson queue: the new
|
||||||
|
# round resumes from part 2, renumbered, and the old machine's part 2
|
||||||
|
# .prt is to be deleted; parts 3 and 4 leave its folder.
|
||||||
|
assert client.call(path, {'machine_id': other, 'reason': ' quebrou a cabeça ', 'resume_from': 2},
|
||||||
|
operator=True) == {'ok': True, 'delete_prt': ['parte 2.prt']}
|
||||||
|
with db.connect() as c:
|
||||||
|
parts = c.execute('''SELECT round,seq,state,name FROM dtf_local.hot_parts
|
||||||
|
WHERE order_id=%s ORDER BY round,seq''', (order,)).fetchall()
|
||||||
|
old = {row['seq']: row['state'] for row in parts if row['round'] == 1}
|
||||||
|
assert old == {1: 'consumed', 2: 'consumed', 3: 'withdraw', 4: 'gone'}, old
|
||||||
|
new = [row for row in parts if row['round'] == 2]
|
||||||
|
assert [row['seq'] for row in new] == [1, 2, 3], parts
|
||||||
|
assert [row['name'] for row in new] == ['parte 2.png', 'parte 3.png', 'parte 4.png'], new
|
||||||
|
assert all(row['state'] == 'queued' for row in new), new
|
||||||
|
moved = c.execute('SELECT machine_id,machine_chosen FROM dtf_local.orders WHERE id=%s',
|
||||||
|
(order,)).fetchone()
|
||||||
|
assert str(moved['machine_id']) == other and moved['machine_chosen'], moved
|
||||||
|
row = c.execute('SELECT * FROM dtf_local.machine_transfers WHERE order_id=%s', (order,)).fetchone()
|
||||||
|
assert row['resumed_from'] == 2 and row['reason'] == 'quebrou a cabeça', row
|
||||||
|
assert row['delete_prt'] == ['parte 2.prt'], row
|
||||||
|
assert (row['from_name'], row['to_name']) == (f'Transfere A {tag}', f'Transfere B {tag}'), row
|
||||||
|
mine = next(o for o in client.call('/operator/board', operator=True)['orders'] if o['id'] == str(order))
|
||||||
|
assert mine['transfers'][0]['resumed_from'] == 2, mine.get('transfers')
|
||||||
|
assert mine['transfers'][0]['delete_prt'] == ['parte 2.prt'], mine.get('transfers')
|
||||||
|
# The board lists the new round's parts for the next transfer's dialog.
|
||||||
|
assert [p['seq'] for p in mine['hot_parts']] == [1, 2, 3], mine.get('hot_parts')
|
||||||
|
# Only Gestão and the administrators move a card between machines.
|
||||||
|
op = signed_in(email)
|
||||||
|
op.call(path, {'machine_id': machine, 'reason': 'outra tentativa'}, expected=403)
|
||||||
|
# Outside Imprimindo there is no transfer.
|
||||||
|
with db.connect() as c:
|
||||||
|
c.execute("UPDATE dtf_local.orders SET state='tra' WHERE id=%s", (order,))
|
||||||
|
answer = client.call(path, {'machine_id': machine, 'reason': 'fora de hora'}, operator=True, expected=409)
|
||||||
|
assert answer['detail'] == 'Só um pedido em Imprimindo muda de máquina por aqui.', answer
|
||||||
|
print('PASS: an order in Imprimindo transfers machine with its reason and the part to resume from, '
|
||||||
|
'the old machine unloads what was not taken and its .prt to delete is named')
|
||||||
|
finally:
|
||||||
|
if order is not None:
|
||||||
|
with db.connect() as c:
|
||||||
|
c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (order,))
|
||||||
|
c.execute('DELETE FROM dtf_local.quotes WHERE id=%s', (quote,))
|
||||||
|
if operator_id:
|
||||||
|
client.call(f'/operator/users/{operator_id}/delete', {}, operator=True)
|
||||||
|
for machine_id in (machine, other):
|
||||||
|
client.call(f'/operator/machines/{machine_id}/delete', {}, operator=True)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
run()
|
||||||
@@ -62,4 +62,27 @@ window.dtfObservability.apiError('/board', 503, 'O sistema está reiniciando.');
|
|||||||
window.dtfObservability.uiError('O sistema está reiniciando.', 'kanban');
|
window.dtfObservability.uiError('O sistema está reiniciando.', 'kanban');
|
||||||
assert.equal(captured, null, 'a skipped restart 503 stays skipped');
|
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');
|
console.log('observability web checks passed');
|
||||||
|
|||||||
@@ -109,6 +109,10 @@ def run():
|
|||||||
client.call(f'/operator/orders/{paid_order}/delete', {}, operator=True)
|
client.call(f'/operator/orders/{paid_order}/delete', {}, operator=True)
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
assert not c.execute('SELECT 1 FROM dtf_local.orders WHERE id=%s', (paid_order,)).fetchone()
|
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.
|
# 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'] == {}
|
assert client.call('/operator/queue/folder', {'held': [str(paid_order)]}, operator=True)['states'] == {}
|
||||||
with db.connect() as c:
|
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.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.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()),))
|
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')
|
'and free their files')
|
||||||
finally:
|
finally:
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
|
|||||||
@@ -121,7 +121,12 @@ def run():
|
|||||||
later = deliver({**payload, 'event_id': 'retry-' + uuid4().hex})
|
later = deliver({**payload, 'event_id': 'retry-' + uuid4().hex})
|
||||||
assert 'already existed' in later.get('outcome', ''), later
|
assert 'already existed' in later.get('outcome', ''), later
|
||||||
assert customer.call('/quotes/' + quote_id)['order']['id'] == order['id'], 'a second order appeared'
|
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']
|
assert customer.call('/orders/dev-paid', {'quote_id': quote_id})['id'] == order['id']
|
||||||
other = Client()
|
other = Client()
|
||||||
@@ -137,6 +142,21 @@ def run():
|
|||||||
assert [e['provider'] for e in paid] == ['tiny'], paid
|
assert [e['provider'] for e in paid] == ['tiny'], paid
|
||||||
print('PASS: exactly one Tiny notification for the order')
|
print('PASS: exactly one Tiny notification for the order')
|
||||||
|
|
||||||
|
# The order's paid line says how it was paid: nothing while no attempt is
|
||||||
|
# approved, then the approved one (the card attempt above).
|
||||||
|
def paid_with():
|
||||||
|
orders = board.call('/operator/board', operator=True)['orders']
|
||||||
|
return next(o for o in orders if o['id'] == order['id'])['paid_with']
|
||||||
|
assert paid_with() is None
|
||||||
|
with db.connect() as c:
|
||||||
|
c.execute("UPDATE dtf_local.payment_intents SET status='approved' WHERE quote_id=%s AND method='card'", (quote_id,))
|
||||||
|
try:
|
||||||
|
assert paid_with() == 'card'
|
||||||
|
finally:
|
||||||
|
with db.connect() as c:
|
||||||
|
c.execute("UPDATE dtf_local.payment_intents SET status='pending' WHERE quote_id=%s AND method='card'", (quote_id,))
|
||||||
|
print('PASS: the board says the order was paid with the approved attempt, card')
|
||||||
|
|
||||||
# A payment that was never reviewed, and one for something that is not a quote.
|
# A payment that was never reviewed, and one for something that is not a quote.
|
||||||
deliver({'event_id': 'nonsense-' + uuid4().hex, 'reference': 'not-a-uuid',
|
deliver({'event_id': 'nonsense-' + uuid4().hex, 'reference': 'not-a-uuid',
|
||||||
'status': 'approved', 'amount_cents': 100})
|
'status': 'approved', 'amount_cents': 100})
|
||||||
|
|||||||
@@ -33,7 +33,8 @@ def download_png(client, upload_id):
|
|||||||
image = Image.open(io.BytesIO(response.read()))
|
image = Image.open(io.BytesIO(response.read()))
|
||||||
assert image.format == 'PNG' and image.mode == 'RGBA', (image.format, image.mode)
|
assert image.format == 'PNG' and image.mode == 'RGBA', (image.format, image.mode)
|
||||||
return image
|
return image
|
||||||
CUSTOMER = {'cnpj': '11222333000181', 'zap': '11999999999', 'mail': 'print-test@example.test'}
|
CUSTOMER = {'cnpj': '11222333000181', 'zap': '11999999999', 'mail': 'print-test@example.test',
|
||||||
|
'name': 'Cliente Print Test'}
|
||||||
|
|
||||||
|
|
||||||
def artwork(kind='PNG'):
|
def artwork(kind='PNG'):
|
||||||
@@ -104,7 +105,10 @@ def run():
|
|||||||
for copy in range(2):
|
for copy in range(2):
|
||||||
assert film.getpixel((px(20 * copy + 10), px(5))) == (220, 30, 60, 255), copy
|
assert film.getpixel((px(20 * copy + 10), px(5))) == (220, 30, 60, 255), copy
|
||||||
assert film.getpixel((px(50), px(5)))[3] == 0
|
assert film.getpixel((px(50), px(5)))[3] == 0
|
||||||
assert row['detail']['footer'].startswith('DROPSTAR · Pedido DTF-%d · Item 1/1 · ' % order['number']), row['detail']
|
footer = row['detail']['footer']
|
||||||
|
assert footer.startswith('DROPSTAR · Pedido DTF-%d · %s · Item 1/1 · '
|
||||||
|
% (order['number'], CUSTOMER['name'])), footer
|
||||||
|
assert footer.endswith(' · 2 peças'), footer
|
||||||
print('PASS: paid order generated a 57 x 10 cm PNG print file with both copies and its footer')
|
print('PASS: paid order generated a 57 x 10 cm PNG print file with both copies and its footer')
|
||||||
|
|
||||||
# A ready sheet with its empty strips cut (Marcus, 2026-11-18): the cart
|
# A ready sheet with its empty strips cut (Marcus, 2026-11-18): the cart
|
||||||
@@ -155,6 +159,9 @@ def run():
|
|||||||
mine = [f for f in early['files'] if f['order'] == oid]
|
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 [(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'}
|
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)
|
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'] == {}
|
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)
|
client.call('/operator/queue/folder', {'early': True, 'held': []}, expected=401)
|
||||||
@@ -251,6 +258,13 @@ def run():
|
|||||||
# No class measured or chosen: the part waits for one.
|
# 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]
|
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)
|
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)
|
hot = client.call('/operator/queue/hot', {}, operator=True)
|
||||||
due = [p for p in hot['write'] if p['order'] == oid]
|
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] == \
|
assert hot['folder'] == '3. Imprimindo' and [(p['folder'], p['name']) for p in due] == \
|
||||||
@@ -269,7 +283,8 @@ def run():
|
|||||||
assert board['hot'] == {'parts': 1, 'taken': 1, 'waiting': 0}, board['hot']
|
assert board['hot'] == {'parts': 1, 'taken': 1, 'waiting': 0}, board['hot']
|
||||||
# Which items go again is chosen before Imprimindo, not while printing (#105).
|
# 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)
|
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:
|
finally:
|
||||||
client.call('/operator/machines/' + machine, {'name': f'Hot {tag}', 'products': ['textil'], 'active': False},
|
client.call('/operator/machines/' + machine, {'name': f'Hot {tag}', 'products': ['textil'], 'active': False},
|
||||||
operator=True)
|
operator=True)
|
||||||
@@ -444,6 +459,36 @@ def run():
|
|||||||
(f"{parent['id']}:production_started:tiny",)).fetchone()
|
(f"{parent['id']}:production_started:tiny",)).fetchone()
|
||||||
print('PASS: a file finished after Prova OK becomes the final, queues the order and tells Tiny')
|
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
|
# 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
|
# already printed, back in the queue after one item's final changed, sends
|
||||||
# only that item; the pass to Revisão keeps it for the machine's metres and
|
# only that item; the pass to Revisão keeps it for the machine's metres and
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ def run():
|
|||||||
quote, payment_id = uuid4(), str(900_000_000 + uuid4().int % 99_999_999)
|
quote, payment_id = uuid4(), str(900_000_000 + uuid4().int % 99_999_999)
|
||||||
approved = {'customer': {'mail': 'reconcile@example.test'}, 'items': [], 'total_cents': 1490}
|
approved = {'customer': {'mail': 'reconcile@example.test'}, 'items': [], 'total_cents': 1490}
|
||||||
order_id = None
|
order_id = None
|
||||||
|
extra = []
|
||||||
try:
|
try:
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved,approved_at)
|
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
|
asked = paid.asked
|
||||||
assert payments.reconcile(db.connect, paid, quote_id=quote) == [] and paid.asked == 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')
|
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:
|
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:
|
with db.connect() as c:
|
||||||
if order_id:
|
if order_id:
|
||||||
c.execute("DELETE FROM dtf_local.outbox WHERE event_key LIKE %s", (f'{order_id}:%',))
|
c.execute("DELETE FROM dtf_local.outbox WHERE event_key LIKE %s", (f'{order_id}:%',))
|
||||||
|
|||||||
77
tests/redesign_preview_test.py
Normal file
77
tests/redesign_preview_test.py
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
"""A redesign's preview: sent, then approved or rejected, stopping the clock."""
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
from psycopg.types.json import Jsonb
|
||||||
|
|
||||||
|
from app.core import db
|
||||||
|
from tests.smoke_test import Client
|
||||||
|
from tests.users_test import order_fixture
|
||||||
|
|
||||||
|
|
||||||
|
def run():
|
||||||
|
client = Client()
|
||||||
|
client.call('/session')
|
||||||
|
owner = uuid4()
|
||||||
|
quote = order = None
|
||||||
|
try:
|
||||||
|
with db.connect() as c:
|
||||||
|
quote, order = order_fixture(c, owner, 'file')
|
||||||
|
c.execute("""UPDATE dtf_local.orders SET snapshot = snapshot || %s, state='rec', payment=%s
|
||||||
|
WHERE id=%s""",
|
||||||
|
(Jsonb({'redesign': {'arts': 1, 'cents': 1990}}),
|
||||||
|
Jsonb({'provider': 'mercadopago', 'id': str(order)}), order))
|
||||||
|
path = f'/operator/orders/{order}/redesign-preview'
|
||||||
|
# Nothing to approve before a preview was sent.
|
||||||
|
answer = client.call(path, {'action': 'approved'}, operator=True, expected=409)
|
||||||
|
assert answer['detail'] == 'Nenhuma prévia com o cliente.', answer
|
||||||
|
# The first preview opens.
|
||||||
|
client.call(path, {'action': 'sent'}, operator=True)
|
||||||
|
mine = next(o for o in client.call('/operator/board', operator=True)['orders']
|
||||||
|
if o['id'] == str(order))
|
||||||
|
assert len(mine['previews']) == 1 and mine['previews'][0]['number'] == 1, mine['previews']
|
||||||
|
assert mine['previews'][0]['decided_at'] is None, mine['previews']
|
||||||
|
# Only one preview waits at a time.
|
||||||
|
answer = client.call(path, {'action': 'sent'}, operator=True, expected=409)
|
||||||
|
assert answer['detail'] == 'Já há uma prévia com o cliente.', answer
|
||||||
|
# Rejected with its reason, spaces tidied.
|
||||||
|
client.call(path, {'action': 'rejected', 'reason': ' motivo teste '}, operator=True)
|
||||||
|
mine = next(o for o in client.call('/operator/board', operator=True)['orders']
|
||||||
|
if o['id'] == str(order))
|
||||||
|
preview = mine['previews'][0]
|
||||||
|
assert preview['result'] == 'rejected' and preview['reason'] == 'motivo teste', preview
|
||||||
|
assert preview['decided_at'] and preview['decided_by'], preview
|
||||||
|
# A second preview follows.
|
||||||
|
client.call(path, {'action': 'sent'}, operator=True)
|
||||||
|
mine = next(o for o in client.call('/operator/board', operator=True)['orders']
|
||||||
|
if o['id'] == str(order))
|
||||||
|
assert [p['number'] for p in mine['previews']] == [1, 2], mine['previews']
|
||||||
|
assert mine['previews'][1]['decided_at'] is None, mine['previews']
|
||||||
|
# Three hours in Arte recebida, two of them waiting for the customer:
|
||||||
|
# the stage clock shows about one.
|
||||||
|
with db.connect() as c:
|
||||||
|
c.execute("UPDATE dtf_local.orders SET created_at=now()-interval '3 hours' WHERE id=%s", (order,))
|
||||||
|
c.execute("""UPDATE dtf_local.redesign_previews SET sent_at=now()-interval '2 hours'
|
||||||
|
WHERE order_id=%s AND decided_at IS NULL""", (order,))
|
||||||
|
mine = next(o for o in client.call('/operator/board', operator=True)['orders']
|
||||||
|
if o['id'] == str(order))
|
||||||
|
assert abs(mine['state_hours'] - 1) < 0.2, mine['state_hours']
|
||||||
|
# Approved ends the previews; no new one is sent.
|
||||||
|
client.call(path, {'action': 'approved'}, operator=True)
|
||||||
|
answer = client.call(path, {'action': 'sent'}, operator=True, expected=409)
|
||||||
|
assert answer['detail'] == 'A prévia já foi aprovada.', answer
|
||||||
|
# An order without the redesign has no previews.
|
||||||
|
with db.connect() as c:
|
||||||
|
c.execute("UPDATE dtf_local.orders SET snapshot = snapshot - 'redesign' WHERE id=%s", (order,))
|
||||||
|
answer = client.call(path, {'action': 'sent'}, operator=True, expected=409)
|
||||||
|
assert answer['detail'] == 'Este pedido não tem Ajuste Fino Redesenho.', answer
|
||||||
|
print('PASS: a redesign preview opens, closes with a reason, reopens, '
|
||||||
|
'stops the stage clock and never reopens after approval')
|
||||||
|
finally:
|
||||||
|
if order is not None:
|
||||||
|
with db.connect() as c:
|
||||||
|
c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (order,))
|
||||||
|
c.execute('DELETE FROM dtf_local.quotes WHERE id=%s', (quote,))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
run()
|
||||||
113
tests/saved_sheets_test.py
Normal file
113
tests/saved_sheets_test.py
Normal file
@@ -0,0 +1,113 @@
|
|||||||
|
"""Minhas folhas: an account keeps a built sheet and asks for it again.
|
||||||
|
|
||||||
|
Run against the local stack: python3 -m tests.saved_sheets_test
|
||||||
|
SITE_BASE_URL=http://site SITE_HOST_HEADER=localhost python -m tests.saved_sheets_test
|
||||||
|
"""
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
import secrets
|
||||||
|
|
||||||
|
from app.core import db
|
||||||
|
from tests.smoke_test import Client, register, upload_bytes
|
||||||
|
|
||||||
|
PASSWORD = 'senha-folhas-12345'
|
||||||
|
CNPJ = '11222333000181'
|
||||||
|
CONTENT = b'LOCAL SAVED SHEET ARTWORK'
|
||||||
|
|
||||||
|
|
||||||
|
def saved_file(uid, name='LOCAL-TEST.cdr'):
|
||||||
|
return {'upload_id': uid, 'name': name, 'size': len(CONTENT), 'lastModified': 0,
|
||||||
|
'type': 'application/octet-stream'}
|
||||||
|
|
||||||
|
|
||||||
|
def body(uid, name='Minha folha', mode='file', metres='1.2', picture=None):
|
||||||
|
item = {'mode': mode, 'metres': metres, 'savedFiles': [saved_file(uid)]}
|
||||||
|
data = {'name': name, 'mode': mode, 'metres': metres, 'item': item}
|
||||||
|
if picture is not None:
|
||||||
|
data['picture'] = picture
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
def run():
|
||||||
|
tag = secrets.token_hex(3)
|
||||||
|
emails = [f'folhas-{tag}@example.test', f'outra-{tag}@example.test']
|
||||||
|
client, other = Client(), Client()
|
||||||
|
try:
|
||||||
|
# A visitor has no account to keep sheets in.
|
||||||
|
client.call('/session')
|
||||||
|
client.call('/account/sheets', expected=401)
|
||||||
|
|
||||||
|
register(client, {'cnpj': CNPJ, 'zap': '16999990000', 'mail': emails[0]}, PASSWORD)
|
||||||
|
register(other, {'cnpj': CNPJ, 'zap': '16999990000', 'mail': emails[1]}, PASSWORD)
|
||||||
|
|
||||||
|
uid = upload_bytes(client, CONTENT)
|
||||||
|
picture = 'data:image/png;base64,AAAA'
|
||||||
|
first = client.call('/account/sheets', body(uid, picture=picture))
|
||||||
|
assert first['id']
|
||||||
|
|
||||||
|
sheets = client.call('/account/sheets')['sheets']
|
||||||
|
assert [s['id'] for s in sheets] == [first['id']], sheets
|
||||||
|
saved = sheets[0]
|
||||||
|
assert saved['available'] is True and saved['picture'] == picture
|
||||||
|
assert saved['total_size'] == len(CONTENT) and saved['item']['savedFiles'][0]['upload_id'] == uid
|
||||||
|
until = datetime.fromisoformat(saved['files_until'])
|
||||||
|
assert abs((until - (datetime.now(timezone.utc) + timedelta(days=30))).total_seconds()) < 300, saved
|
||||||
|
|
||||||
|
# Another account's upload cannot be saved.
|
||||||
|
stranger_uid = upload_bytes(other, CONTENT)
|
||||||
|
refused = client.call('/account/sheets', body(stranger_uid), expected=409)
|
||||||
|
assert 'não está mais disponível' in refused['detail'], refused
|
||||||
|
|
||||||
|
# A sheet of another account is not found.
|
||||||
|
second = other.call('/account/sheets', body(stranger_uid, name='Outra folha'))
|
||||||
|
assert second['id']
|
||||||
|
client.call('/account/sheets/' + second['id'], expected=404, method='DELETE')
|
||||||
|
client.call('/account/sheets/' + second['id'] + '/use', {}, expected=404)
|
||||||
|
client.call('/account/sheets/' + second['id'] + '/files', {}, expected=404)
|
||||||
|
|
||||||
|
# An upload older than 30 days is no longer available.
|
||||||
|
old_uid = upload_bytes(client, CONTENT)
|
||||||
|
old = client.call('/account/sheets', body(old_uid, name='Vencida'))
|
||||||
|
with db.connect() as c:
|
||||||
|
c.execute("UPDATE dtf_local.uploads SET created_at=now()-interval '31 days' WHERE id=%s", (old_uid,))
|
||||||
|
expired = next(s for s in client.call('/account/sheets')['sheets'] if s['id'] == old['id'])
|
||||||
|
assert expired['available'] is False, expired
|
||||||
|
refused = client.call('/account/sheets/' + old['id'] + '/use', {}, expected=409)
|
||||||
|
assert 'venceram' in refused['detail'], refused
|
||||||
|
|
||||||
|
# At most 50 sheets per account.
|
||||||
|
created = 2
|
||||||
|
while created < 50:
|
||||||
|
client.call('/account/sheets', body(uid, name=f'Folha {created + 1}'))
|
||||||
|
created += 1
|
||||||
|
full = client.call('/account/sheets', body(uid, name='A 51a'), expected=409)
|
||||||
|
assert '50 folhas' in full['detail'], full
|
||||||
|
|
||||||
|
# Asking for it again records when and hands back the item.
|
||||||
|
used = client.call('/account/sheets/' + first['id'] + '/use', {})
|
||||||
|
assert used['id'] == first['id'] and used['used_at'] and used['item']['savedFiles'][0]['upload_id'] == uid
|
||||||
|
assert next(s for s in client.call('/account/sheets')['sheets'] if s['id'] == first['id'])['used_at']
|
||||||
|
|
||||||
|
# Editing gets a link to each file, in the item's order.
|
||||||
|
files = client.call('/account/sheets/' + first['id'] + '/files', {})['files']
|
||||||
|
assert len(files) == 1 and files[0]['upload_id'] == uid
|
||||||
|
assert files[0]['name'] == 'LOCAL-TEST.cdr' and files[0]['size'] == len(CONTENT)
|
||||||
|
assert files[0]['url'].startswith('http'), files
|
||||||
|
|
||||||
|
# Deleted, it leaves the list.
|
||||||
|
assert client.call('/account/sheets/' + first['id'], method='DELETE') == {'ok': True}
|
||||||
|
assert first['id'] not in [s['id'] for s in client.call('/account/sheets')['sheets']]
|
||||||
|
client.call('/account/sheets/' + first['id'], method='DELETE', expected=404)
|
||||||
|
|
||||||
|
print('PASS: saved sheets belong to the account, last 30 days, cap at 50, and come back for '
|
||||||
|
'Pedir de novo or Editar')
|
||||||
|
finally:
|
||||||
|
with db.connect() as c:
|
||||||
|
c.execute('DELETE FROM dtf_local.uploads WHERE owner IN '
|
||||||
|
'(SELECT id FROM dtf_local.accounts WHERE email=ANY(%s))', (emails,))
|
||||||
|
c.execute('DELETE FROM dtf_local.accounts WHERE email=ANY(%s)', (emails,))
|
||||||
|
c.execute('DELETE FROM dtf_local.account_signups WHERE email=ANY(%s)', (emails,))
|
||||||
|
c.execute('DELETE FROM dtf_local.mail_queue WHERE to_addr=ANY(%s)', (emails,))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
run()
|
||||||
@@ -40,12 +40,13 @@ def quote(client, item, mail, expected=200):
|
|||||||
|
|
||||||
|
|
||||||
def arts_item(upload_id, arts):
|
def arts_item(upload_id, arts):
|
||||||
"""One loose-art item with `arts` sources of 10 x 10 cm, one metre long."""
|
"""One loose-art item with `arts` sources of 10 x 5 cm (artwork() is 2:1),
|
||||||
sources = [{'upload_id': upload_id, 'kind': 'artwork', 'width_cm': 10, 'length_cm': 10,
|
one every 10 cm."""
|
||||||
|
sources = [{'upload_id': upload_id, 'kind': 'artwork', 'width_cm': 10, 'length_cm': 5,
|
||||||
'copies': 1, 'rotation_degrees': 0, 'mirrored': False,
|
'copies': 1, 'rotation_degrees': 0, 'mirrored': False,
|
||||||
'measurement': 'customer'} for _ in range(arts)]
|
'measurement': 'customer'} for _ in range(arts)]
|
||||||
placements = [{'source_index': index, 'copy_index': 0, 'x_cm': 0, 'y_cm': index * 10,
|
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)]
|
for index in range(arts)]
|
||||||
return {'mode': 'avulsa', 'metres': '1', 'grade': 90, 'uploads': [upload_id] * arts,
|
return {'mode': 'avulsa', 'metres': '1', 'grade': 90, 'uploads': [upload_id] * arts,
|
||||||
'production': {'version': 3, 'film_width_cm': 57, 'height_cm': arts * 10,
|
'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 premium_entry['title'] == 'Têxtil Premium · 8 passadas', premium_entry
|
||||||
assert client.call('/session')['products'][PREMIUM]['enabled'] is False
|
assert client.call('/session')['products'][PREMIUM]['enabled'] is False
|
||||||
premium_item = {**item_spec(PREMIUM, '1', 0, upload_bytes(
|
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}
|
'quality_status': 'warning', 'quality_acknowledged': True}
|
||||||
refused = quote(client, premium_item, mail, expected=422)
|
refused = quote(client, premium_item, mail, expected=422)
|
||||||
assert refused['detail'] == 'Este produto não está à venda agora.', refused
|
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})
|
manager.call(f'/operator/site/products/{UV}', {'enabled': True})
|
||||||
uid = upload_bytes(client, artwork(), name='LOCAL-SITE-ADMIN.png')
|
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']
|
before = client.call('/session')['products'][UV]['unit_cents']
|
||||||
|
|
||||||
# Switched off: the Site sees it off and the server refuses a new quote.
|
# Switched off: the Site sees it off and the server refuses a new quote.
|
||||||
|
|||||||
@@ -47,9 +47,22 @@ def run():
|
|||||||
published = client.call('/site/videos')['videos']
|
published = client.call('/site/videos')['videos']
|
||||||
entry = next(row for row in published if row['id'] == 'sala')
|
entry = next(row for row in published if row['id'] == 'sala')
|
||||||
assert entry['product'] == 'file'
|
assert entry['product'] == 'file'
|
||||||
|
assert entry['products'] == ['file'], entry
|
||||||
assert entry['captions'] == '/api/site/videos/sala/captions'
|
assert entry['captions'] == '/api/site/videos/sala/captions'
|
||||||
|
# The same video can appear on more than one product; duplicates are
|
||||||
|
# dropped and the order follows the product catalog.
|
||||||
|
operator.call('/operator/site-videos/sala', {'upload_id': video,
|
||||||
|
'captions_id': captions, 'products': ['uv', 'file', 'uv'], 'enabled': True})
|
||||||
|
entry = next(row for row in client.call('/site/videos')['videos'] if row['id'] == 'sala')
|
||||||
|
assert entry['products'] == ['file', 'uv'], entry
|
||||||
|
assert entry['product'] == 'file', entry
|
||||||
# One floating video per product: a second one is refused before any
|
# One floating video per product: a second one is refused before any
|
||||||
# copy, naming the video that holds the product (DTF-WEB-G).
|
# copy, naming the video and the product in conflict (DTF-WEB-G).
|
||||||
|
refused = operator.call('/operator/site-videos/png', {'upload_id': video,
|
||||||
|
'products': ['uv'], 'enabled': True}, expected=409)
|
||||||
|
assert 'A sala às 3 da manhã' in refused['detail'], refused
|
||||||
|
assert 'Artes avulsas · UV' in refused['detail'], refused
|
||||||
|
# The old single `product` still works and is refused the same way.
|
||||||
refused = operator.call('/operator/site-videos/png', {'upload_id': video,
|
refused = operator.call('/operator/site-videos/png', {'upload_id': video,
|
||||||
'product': 'file', 'enabled': True}, expected=409)
|
'product': 'file', 'enabled': True}, expected=409)
|
||||||
assert 'A sala às 3 da manhã' in refused['detail'], refused
|
assert 'A sala às 3 da manhã' in refused['detail'], refused
|
||||||
|
|||||||
@@ -140,11 +140,15 @@ def review_photo(client, order_id):
|
|||||||
wait_scan(client,uid,operator=True)
|
wait_scan(client,uid,operator=True)
|
||||||
return client.call('/operator/orders/'+order_id+'/reviews',{'upload_id':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
|
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],
|
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,
|
'sources':[{'upload_id':uid,
|
||||||
'kind':'sheet' if mode in ('file','uvfile','premium') else 'artwork',
|
'kind':'sheet' if mode in ('file','uvfile','premium') else 'artwork',
|
||||||
'width_cm':film_width,'length_cm':length_cm,'copies':1,
|
'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,
|
# 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.
|
# 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
|
# 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.
|
# 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
|
# 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')
|
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')
|
low=upload_bytes(client,low_png,name='arte-150dpi.png')
|
||||||
small={**draft,'request_key':str(uuid4()),'items':[item_spec('avulsa','2.75',90,graded)]}
|
small={**draft,'request_key':str(uuid4()),'items':[item_spec('avulsa','2.75',90,graded)]}
|
||||||
auto=client.call('/quotes',small)
|
auto=client.call('/quotes',small)
|
||||||
@@ -283,7 +288,11 @@ def run():
|
|||||||
assert mixed_item['stroke_choice']=='client_c3', mixed_item
|
assert mixed_item['stroke_choice']=='client_c3', mixed_item
|
||||||
# Loose art split by stroke (item 17): each sheet is an item, and the pair
|
# Loose art split by stroke (item 17): each sheet is an item, and the pair
|
||||||
# has one 1 m minimum, on its first sheet.
|
# 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)]}
|
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':split['items'][:1]},expected=422)
|
||||||
client.call('/quotes',{**split,'items':[part('0.3',1),part('0.15',1)]},expected=422)
|
client.call('/quotes',{**split,'items':[part('0.3',1),part('0.15',1)]},expected=422)
|
||||||
|
|||||||
@@ -146,7 +146,9 @@ def run():
|
|||||||
|
|
||||||
# Interno is refused while Gestão has not completed the customer.
|
# Interno is refused while Gestão has not completed the customer.
|
||||||
stamp = upload_stamp(shipping)
|
stamp = upload_stamp(shipping)
|
||||||
interno = {'kind': 'interno', 'items': [montador_item(stamp)]}
|
batch = {'lines': 2, 'skipped': [
|
||||||
|
{'line': 5, 'text': 'NX.999 Z 1 REF', 'reason': 'tamanho não existe na tabela'}]}
|
||||||
|
interno = {'kind': 'interno', 'items': [montador_item(stamp)], 'batch': batch}
|
||||||
refused = shipping.call('/operator/montador/orders', {'request_key': str(uuid4()), **interno},
|
refused = shipping.call('/operator/montador/orders', {'request_key': str(uuid4()), **interno},
|
||||||
expected=409)
|
expected=409)
|
||||||
assert refused['detail'] == INTERNAL_MISSING, refused
|
assert refused['detail'] == INTERNAL_MISSING, refused
|
||||||
@@ -164,6 +166,7 @@ def run():
|
|||||||
assert order_interno['state'] == 'rec' and order_interno['origin'] == 'dropflow', order_interno
|
assert order_interno['state'] == 'rec' and order_interno['origin'] == 'dropflow', order_interno
|
||||||
assert order_interno['snapshot']['kind'] == 'interno', order_interno['snapshot'].get('kind')
|
assert order_interno['snapshot']['kind'] == 'interno', order_interno['snapshot'].get('kind')
|
||||||
assert order_interno['snapshot']['customer']['cnpj'] == '11222333000181', order_interno['snapshot']
|
assert order_interno['snapshot']['customer']['cnpj'] == '11222333000181', order_interno['snapshot']
|
||||||
|
assert order_interno['snapshot']['batch'] == batch, order_interno['snapshot'].get('batch')
|
||||||
payment = order_interno['payment']
|
payment = order_interno['payment']
|
||||||
assert (payment['provider'], payment['method'], payment['status']) == ('manual', 'interno', 'paid'), payment
|
assert (payment['provider'], payment['method'], payment['status']) == ('manual', 'interno', 'paid'), payment
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
@@ -213,6 +216,12 @@ def run():
|
|||||||
designer.call('/operator/montador/orders', {'request_key': str(uuid4()), **venda}, expected=403)
|
designer.call('/operator/montador/orders', {'request_key': str(uuid4()), **venda}, expected=403)
|
||||||
shipping.call('/operator/montador/orders', {'request_key': str(uuid4()), 'kind': 'interno',
|
shipping.call('/operator/montador/orders', {'request_key': str(uuid4()), 'kind': 'interno',
|
||||||
'items': [montador_item(stamp, 'file')]}, expected=422)
|
'items': [montador_item(stamp, 'file')]}, expected=422)
|
||||||
|
# A pasted list only becomes an Interno order.
|
||||||
|
refused = seller.call('/operator/montador/orders', {'request_key': str(uuid4()), 'kind': 'venda',
|
||||||
|
'customer': venda_customer,
|
||||||
|
'items': [montador_item(venda_stamp)],
|
||||||
|
'batch': batch}, expected=422)
|
||||||
|
assert refused['detail'] == 'A lista colada vira sempre pedido Interno.', refused
|
||||||
|
|
||||||
# Venda with Envio: the Site's freight, re-quoted by the server.
|
# Venda with Envio: the Site's freight, re-quoted by the server.
|
||||||
destination = {'recipient': 'Maria Souza', 'street': 'Rua das Flores', 'number': '100',
|
destination = {'recipient': 'Maria Souza', 'street': 'Rua das Flores', 'number': '100',
|
||||||
|
|||||||
@@ -165,8 +165,10 @@ class CartPricingCharacterizationTest(unittest.TestCase):
|
|||||||
split = priced('split-under-one-metre')
|
split = priced('split-under-one-metre')
|
||||||
self.assertEqual([(p['billed_metres'], p['total_cents']) for p in split],
|
self.assertEqual([(p['billed_metres'], p['total_cents']) for p in split],
|
||||||
[('0.8', 1752), ('0.2', 438)])
|
[('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]
|
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):
|
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
|
# 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))})
|
storage = CountingStorage({'k.pdf': b'%PDF-1.4 test', 'k.png': encoded('PNG', (100, 50))})
|
||||||
files = grade_check.Files(storage)
|
files = grade_check.Files(storage)
|
||||||
pdf_row = {'object_key': 'k.pdf', 'size': 15, 'name': 'a.pdf'}
|
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(files.pdf_dpi(pdf_row), 300)
|
self.assertEqual(files.pdf_dpi(pdf_row), 300)
|
||||||
self.assertEqual(storage.downloads, 1)
|
self.assertEqual(storage.downloads, 1)
|
||||||
@@ -158,5 +158,89 @@ class GradeCheckTests(unittest.TestCase):
|
|||||||
self.assertIn('confirme a ressalva', issue(199.4))
|
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__':
|
if __name__ == '__main__':
|
||||||
unittest.main()
|
unittest.main()
|
||||||
|
|||||||
@@ -34,7 +34,7 @@ class GradeRulesTest(unittest.TestCase):
|
|||||||
def test_treatment_message(self):
|
def test_treatment_message(self):
|
||||||
self.assertEqual(
|
self.assertEqual(
|
||||||
treatment_message(45),
|
treatment_message(45),
|
||||||
'Sua arte tem nota 45: para imprimir com qualidade, o Ajuste Fino '
|
'Sua arte está abaixo da resolução mínima, então o Ajuste Fino '
|
||||||
'é obrigatório neste pedido.')
|
'é obrigatório neste pedido.')
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -16,9 +16,14 @@ class PricingTests(unittest.TestCase):
|
|||||||
source = Path('web/site-config.js').read_text()
|
source = Path('web/site-config.js').read_text()
|
||||||
prices = source.split('const PRECO=')[1].split(';',1)[0]
|
prices = source.split('const PRECO=')[1].split(';',1)[0]
|
||||||
calculator = source.split('const cobrar=')[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))
|
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];
|
const unit=PRECO[mode];
|
||||||
results.push([mode,String(metres),cobrar(metres),Math.round(unit*100),Math.round(cobrar(metres)*unit*100)]);
|
results.push([mode,String(metres),cobrar(metres),Math.round(unit*100),Math.round(cobrar(metres)*unit*100)]);
|
||||||
}process.stdout.write(JSON.stringify(results));'''
|
}process.stdout.write(JSON.stringify(results));'''
|
||||||
@@ -32,6 +37,18 @@ class PricingTests(unittest.TestCase):
|
|||||||
self.assertEqual(result['unit_cents'],unit)
|
self.assertEqual(result['unit_cents'],unit)
|
||||||
self.assertEqual(result['total_cents'],total)
|
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):
|
def test_one_price_per_product(self):
|
||||||
# Dropstar, 2026-10-23: textile R$ 19,90 ready sheet and R$ 21,90 loose
|
# 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).
|
# art; UV R$ 79,90 and R$ 89,90. Premium R$ 39,90 (2026-11-10).
|
||||||
|
|||||||
@@ -129,7 +129,7 @@ class PrintFileTests(unittest.TestCase):
|
|||||||
job = {'snapshot': {'items': [spec, spec]}, 'number': 7, 'item_index': 1,
|
job = {'snapshot': {'items': [spec, spec]}, 'number': 7, 'item_index': 1,
|
||||||
'ordered_at': datetime(2026, 10, 23, 15, 0, tzinfo=timezone.utc)}
|
'ordered_at': datetime(2026, 10, 23, 15, 0, tzinfo=timezone.utc)}
|
||||||
line = footer(job, spec)
|
line = footer(job, spec)
|
||||||
self.assertEqual(line, 'DROPSTAR · Pedido DTF-7 · Item 2/2 · 23/10/2026 · 1,00 m · ESPELHADO')
|
self.assertEqual(line, 'DROPSTAR · Pedido DTF-7 · Item 2/2 · 23/10/2026 · 1,00 m · 1 peça · ESPELHADO')
|
||||||
self.assertIn(b'/F1 31 Tf ( \xb7 ESPELHADO) Tj', footer_commands(line, (100, 80)))
|
self.assertIn(b'/F1 31 Tf ( \xb7 ESPELHADO) Tj', footer_commands(line, (100, 80)))
|
||||||
# About 1 cm tall on the 57 cm film (Dropstar, 2026-10-28); on the 27 cm UV
|
# About 1 cm tall on the 57 cm film (Dropstar, 2026-10-28); on the 27 cm UV
|
||||||
# the line shrinks to fit the width instead of running off the film.
|
# the line shrinks to fit the width instead of running off the film.
|
||||||
@@ -149,6 +149,35 @@ class PrintFileTests(unittest.TestCase):
|
|||||||
self.assertEqual(file_prefix(130, 0, 2), 'DTF-130-v2-item-1')
|
self.assertEqual(file_prefix(130, 0, 2), 'DTF-130-v2-item-1')
|
||||||
self.assertEqual(file_prefix(130, 0, 1), 'DTF-130-item-1')
|
self.assertEqual(file_prefix(130, 0, 1), 'DTF-130-item-1')
|
||||||
|
|
||||||
|
def test_the_footer_names_the_customer_and_the_pieces(self):
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from app.printjobs import footer
|
||||||
|
|
||||||
|
def line(name, spec, items=2):
|
||||||
|
customer = {} if name is None else {'name': name}
|
||||||
|
job = {'snapshot': {'items': [spec] * items, 'customer': customer},
|
||||||
|
'number': 7, 'item_index': 0,
|
||||||
|
'ordered_at': datetime(2026, 10, 21, 15, 0, tzinfo=timezone.utc)}
|
||||||
|
return footer(job, spec)
|
||||||
|
|
||||||
|
spec = item([placement(0, 0, 20, 10)], [source(20, 10)], 10)
|
||||||
|
start = 'DROPSTAR · Pedido DTF-7 · '
|
||||||
|
end = ' · Item 1/2 · 21/10/2026 · 1,00 m · 1 peça'
|
||||||
|
# An accent stays; an emoji does not; a long name is cut with an ellipsis.
|
||||||
|
self.assertEqual(line('Gráfica São José', spec), start + 'Gráfica São José' + end)
|
||||||
|
self.assertEqual(line('Loja 🌟 Azul', spec), start + 'Loja Azul' + end)
|
||||||
|
self.assertEqual(line('Gráfica São José do Vale do Paraíba', spec),
|
||||||
|
start + 'Gráfica São José do Val…' + end)
|
||||||
|
# Without a name the field is left out, with no stray separator.
|
||||||
|
self.assertEqual(line(None, spec), 'DROPSTAR · Pedido DTF-7' + end)
|
||||||
|
# A ready sheet counts its copies, and only says so above one.
|
||||||
|
sheet = item([placement(0, 0, 20, 10)], [{**source(20, 10), 'kind': 'sheet', 'copies': 3}], 10)
|
||||||
|
self.assertEqual(line('Cliente', sheet),
|
||||||
|
'DROPSTAR · Pedido DTF-7 · Cliente · Item 1/2 · 21/10/2026 · 1,00 m · 3 cópias')
|
||||||
|
single = item([placement(0, 0, 20, 10)], [{**source(20, 10), 'kind': 'sheet', 'copies': 1}], 10)
|
||||||
|
self.assertEqual(line('Cliente', single),
|
||||||
|
'DROPSTAR · Pedido DTF-7 · Cliente · Item 1/2 · 21/10/2026 · 1,00 m')
|
||||||
|
|
||||||
def test_jpeg_bytes_are_embedded_unchanged(self):
|
def test_jpeg_bytes_are_embedded_unchanged(self):
|
||||||
path = self.save(quadrants(), 'a.jpg', quality=90)
|
path = self.save(quadrants(), 'a.jpg', quality=90)
|
||||||
pdf, _ = self.render(item([placement(0, 0, 20, 10)], [source(20, 10)], 10), [path])
|
pdf, _ = self.render(item([placement(0, 0, 20, 10)], [source(20, 10)], 10), [path])
|
||||||
|
|||||||
@@ -37,6 +37,53 @@ class PrumoReportTests(unittest.TestCase):
|
|||||||
self.assertIn('Prumo levou 41 s', text)
|
self.assertIn('Prumo levou 41 s', text)
|
||||||
self.assertNotIn('Prumo levou 341 s', text)
|
self.assertNotIn('Prumo levou 341 s', text)
|
||||||
|
|
||||||
|
def test_pasted_list_says_how_many_lines_were_mounted(self):
|
||||||
|
order = self.order()
|
||||||
|
order['snapshot']['batch'] = {'lines': 3, 'skipped': []}
|
||||||
|
lines = report(order, {'u1': {'name': 'arte.pdf'}})
|
||||||
|
text = '\n'.join(lines)
|
||||||
|
self.assertIn('Lista colada: 3 linhas montadas', text)
|
||||||
|
self.assertNotIn('puladas', text)
|
||||||
|
# Before the item lines: the designer reads the list first.
|
||||||
|
self.assertLess(text.index('Lista colada'), text.index('Formato detectado'))
|
||||||
|
|
||||||
|
def test_pasted_list_lists_the_skipped_lines(self):
|
||||||
|
order = self.order()
|
||||||
|
order['snapshot']['batch'] = {'lines': 2, 'skipped': [
|
||||||
|
{'line': 4, 'text': 'NX.999 Z 1 REF', 'reason': 'tamanho não existe na tabela'},
|
||||||
|
{'line': 7, 'text': 'NX.226 C 0', 'reason': 'quantidade de 1 a 9999'}]}
|
||||||
|
lines = report(order, {'u1': {'name': 'arte.pdf'}})
|
||||||
|
text = '\n'.join(lines)
|
||||||
|
self.assertIn('Lista colada: 2 linhas montadas, 2 puladas', text)
|
||||||
|
self.assertIn('Linha 4 pulada (tamanho não existe na tabela): NX.999 Z 1 REF', text)
|
||||||
|
self.assertIn('Linha 7 pulada (quantidade de 1 a 9999): NX.226 C 0', text)
|
||||||
|
self.assertLess(text.index('Lista colada'), text.index('Linha 4 pulada'))
|
||||||
|
self.assertLess(text.index('Linha 7 pulada'), text.index('Formato detectado'))
|
||||||
|
|
||||||
|
def test_saved_png_size_says_whether_the_customer_kept_it(self):
|
||||||
|
order = self.order()
|
||||||
|
item = order['snapshot']['items'][0]
|
||||||
|
item['production']['sources'] = [
|
||||||
|
{'width_cm': '28.0', 'length_cm': '35.2',
|
||||||
|
'saved_width_cm': '28.0', 'saved_dpi': 300},
|
||||||
|
{'width_cm': '20', 'length_cm': '25',
|
||||||
|
'saved_width_cm': '15', 'saved_dpi': 240},
|
||||||
|
]
|
||||||
|
text = '\n'.join(report(order, {'u1': {'name': 'arte.pdf'}}))
|
||||||
|
self.assertIn('Arte 1: tamanho lido do arquivo 28,0 × 35,2 cm (300 DPI), mantido', text)
|
||||||
|
self.assertIn('Arte 2: tamanho lido do arquivo 15,0 × 18,8 cm (240 DPI), '
|
||||||
|
'alterado pelo cliente para 20,0 cm', text)
|
||||||
|
# Turned 90°: the art's own width is the length along the film.
|
||||||
|
item['production']['sources'] = [
|
||||||
|
{'width_cm': '35.2', 'length_cm': '28.0', 'rotation_degrees': 90,
|
||||||
|
'saved_width_cm': '28.0', 'saved_dpi': 300}]
|
||||||
|
text = '\n'.join(report(order, {'u1': {'name': 'arte.pdf'}}))
|
||||||
|
self.assertIn('Arte 1: tamanho lido do arquivo 28,0 × 35,2 cm (300 DPI), mantido', text)
|
||||||
|
|
||||||
|
def test_without_a_saved_png_size_no_line_is_added(self):
|
||||||
|
text = '\n'.join(report(self.order(), {'u1': {'name': 'arte.pdf'}}))
|
||||||
|
self.assertNotIn('tamanho lido do arquivo', text)
|
||||||
|
|
||||||
def test_without_a_claim_time_the_generation_line_is_hidden(self):
|
def test_without_a_claim_time_the_generation_line_is_hidden(self):
|
||||||
order = self.order()
|
order = self.order()
|
||||||
del order['print_files'][0]['claimed_at']
|
del order['print_files'][0]['claimed_at']
|
||||||
|
|||||||
26
tests/test_saved_size.py
Normal file
26
tests/test_saved_size.py
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
"""The PNG's own size on an artwork source (item A1, round 5)."""
|
||||||
|
import unittest
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
try:
|
||||||
|
from pydantic import ValidationError
|
||||||
|
from app.core.models import ProductionSource
|
||||||
|
except ImportError:
|
||||||
|
# The validate job runs this file on the host, without the runtime image's
|
||||||
|
# dependencies; the runtime suites exercise the model there.
|
||||||
|
ProductionSource = ValidationError = None
|
||||||
|
|
||||||
|
|
||||||
|
class ProductionSourceSavedSizeTests(unittest.TestCase):
|
||||||
|
@unittest.skipUnless(ProductionSource, 'pydantic is only in the runtime image')
|
||||||
|
def test_saved_size_is_optional_and_saved_dpi_must_be_positive(self):
|
||||||
|
base = {'upload_id': str(uuid4()), 'kind': 'artwork', 'width_cm': '28.0',
|
||||||
|
'length_cm': '35.2', 'copies': 1, 'measurement': 'file'}
|
||||||
|
ProductionSource.model_validate(base)
|
||||||
|
ProductionSource.model_validate({**base, 'saved_width_cm': '28.0', 'saved_dpi': 300})
|
||||||
|
with self.assertRaises(ValidationError):
|
||||||
|
ProductionSource.model_validate({**base, 'saved_width_cm': '28.0', 'saved_dpi': 0})
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
unittest.main()
|
||||||
@@ -39,6 +39,36 @@ class SheetGapTests(unittest.TestCase):
|
|||||||
self.assertEqual(str(caught.exception), SHEET_GAP_CHANGED)
|
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):
|
class ClosePiecesTests(unittest.TestCase):
|
||||||
"""The Site's count of pieces under 5 mm travels with the item to the
|
"""The Site's count of pieces under 5 mm travels with the item to the
|
||||||
Kanban card (Marcus, 2026-11-26, #81)."""
|
Kanban card (Marcus, 2026-11-26, #81)."""
|
||||||
|
|||||||
@@ -46,5 +46,44 @@ class SheetTrimTests(unittest.TestCase):
|
|||||||
Item.model_validate(sheet_item(top=-1))
|
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__':
|
if __name__ == '__main__':
|
||||||
unittest.main()
|
unittest.main()
|
||||||
|
|||||||
@@ -215,7 +215,8 @@ class TinyTests(FakeTinyCase):
|
|||||||
mock.patch.dict(tiny_module.RECEIPT_METHODS, {'faturado': 919478947}):
|
mock.patch.dict(tiny_module.RECEIPT_METHODS, {'faturado': 919478947}):
|
||||||
pedido = order_payload({**PAID, 'payment': {'method': 'faturado'}}, 777, date(2026, 9, 24))
|
pedido = order_payload({**PAID, 'payment': {'method': 'faturado'}}, 777, date(2026, 9, 24))
|
||||||
self.assertNotIn('meioPagamento', pedido['pagamento']['parcelas'][0])
|
self.assertNotIn('meioPagamento', pedido['pagamento']['parcelas'][0])
|
||||||
# A pix order never gets the boleto account.
|
# A pix order never gets the boleto account, nor any other: Tiny did
|
||||||
|
# not find MERCADO PAGO, 977344550 (DTF-API-C, 2026-12-01).
|
||||||
with mock.patch.dict(os.environ, {'TINY_BOLETO_ACCOUNT': '977344551'}):
|
with mock.patch.dict(os.environ, {'TINY_BOLETO_ACCOUNT': '977344551'}):
|
||||||
pedido = order_payload({**PAID, 'payment': {'method': 'pix'}}, 777, date(2026, 9, 24))
|
pedido = order_payload({**PAID, 'payment': {'method': 'pix'}}, 777, date(2026, 9, 24))
|
||||||
self.assertNotIn('meioPagamento', pedido['pagamento']['parcelas'][0])
|
self.assertNotIn('meioPagamento', pedido['pagamento']['parcelas'][0])
|
||||||
@@ -480,8 +481,13 @@ class TinyStatusTests(FakeTinyCase):
|
|||||||
self.assertEqual(pickup['transportador'], {'fretePorConta': 'R', 'id': PICKUP_CARRIER,
|
self.assertEqual(pickup['transportador'], {'fretePorConta': 'R', 'id': PICKUP_CARRIER,
|
||||||
'formaEnvio': {'id': 77}, 'formaFrete': {'id': 771}})
|
'formaEnvio': {'id': 77}, 'formaFrete': {'id': 771}})
|
||||||
self.assertEqual(pickup['dataPrevista'], '2026-09-25')
|
self.assertEqual(pickup['dataPrevista'], '2026-09-25')
|
||||||
|
# Paid on the Site: the parcel names no account (DTF-API-C, 2026-12-01).
|
||||||
self.assertEqual(pickup['pagamento'], {'categoria': {'id': CATEGORY}, 'formaRecebimento': {'id': RECEIPT_METHODS['pix']},
|
self.assertEqual(pickup['pagamento'], {'categoria': {'id': CATEGORY}, 'formaRecebimento': {'id': RECEIPT_METHODS['pix']},
|
||||||
'parcelas': [{'dias': 0, 'data': '2026-09-24', 'valor': 84.72, 'formaRecebimento': {'id': RECEIPT_METHODS['pix']}}]})
|
'parcelas': [{'dias': 0, 'data': '2026-09-24', 'valor': 84.72, 'formaRecebimento': {'id': RECEIPT_METHODS['pix']}}]})
|
||||||
|
# The forma de recebimento ids: card stays the one Tiny accepts, 977460722;
|
||||||
|
# 919478945, which Marcus named on 2026-12-01, is not enabled (DTF-API-C).
|
||||||
|
self.assertEqual((RECEIPT_METHODS['pix'], RECEIPT_METHODS['card'], RECEIPT_METHODS['credit']),
|
||||||
|
(919478952, 977460722, 987762591))
|
||||||
# Delivery: the Correios contract's PAC or SEDEX, or Jadlog; the date in working days.
|
# Delivery: the Correios contract's PAC or SEDEX, or Jadlog; the date in working days.
|
||||||
for service, method, frete in (('pac', 78, 781), ('sedex', 78, 782), ('jadlog', 80, 801)):
|
for service, method, frete in (('pac', 78, 781), ('sedex', 78, 782), ('jadlog', 80, 801)):
|
||||||
order = {**PAID['order'], 'freight': {'service': service, 'total_cents': 1500, 'days': 6}}
|
order = {**PAID['order'], 'freight': {'service': service, 'total_cents': 1500, 'days': 6}}
|
||||||
@@ -491,6 +497,7 @@ class TinyStatusTests(FakeTinyCase):
|
|||||||
'formaFrete': {'id': frete}}, service)
|
'formaFrete': {'id': frete}}, service)
|
||||||
self.assertEqual(sent['dataPrevista'], '2026-10-02')
|
self.assertEqual(sent['dataPrevista'], '2026-10-02')
|
||||||
self.assertEqual(sent['pagamento']['formaRecebimento'], {'id': RECEIPT_METHODS['card']})
|
self.assertEqual(sent['pagamento']['formaRecebimento'], {'id': RECEIPT_METHODS['card']})
|
||||||
|
self.assertNotIn('meioPagamento', sent['pagamento']['parcelas'][0])
|
||||||
# Looked up once per service.
|
# Looked up once per service.
|
||||||
self.assertEqual(self.calls.count(('GET', '/formas-envio/78')), 2)
|
self.assertEqual(self.calls.count(('GET', '/formas-envio/78')), 2)
|
||||||
# A test order, or a carrier Tiny does not have: the order still goes, without them,
|
# A test order, or a carrier Tiny does not have: the order still goes, without them,
|
||||||
@@ -511,6 +518,9 @@ class TinyStatusTests(FakeTinyCase):
|
|||||||
1, thursday, shipping=self.tiny.shipping)
|
1, thursday, shipping=self.tiny.shipping)
|
||||||
self.assertEqual(pix['pagamento']['formaRecebimento'], {'id': RECEIPT_METHODS['pix']})
|
self.assertEqual(pix['pagamento']['formaRecebimento'], {'id': RECEIPT_METHODS['pix']})
|
||||||
self.assertEqual(pix['pagamento']['categoria'], {'id': CATEGORY})
|
self.assertEqual(pix['pagamento']['categoria'], {'id': CATEGORY})
|
||||||
|
# Paid outside the site: no account either.
|
||||||
|
self.assertNotIn('meioPagamento', pix['pagamento']['parcelas'][0])
|
||||||
|
self.assertNotIn('meioPagamento', counter['pagamento']['parcelas'][0])
|
||||||
# Dinheiro (Marcus, 2026-10-27) and the customer's credit, CREDITO
|
# Dinheiro (Marcus, 2026-10-27) and the customer's credit, CREDITO
|
||||||
# PRE-PAGO (Marcus, 2026-11-18; no longer CORREÇÃO DTF).
|
# PRE-PAGO (Marcus, 2026-11-18; no longer CORREÇÃO DTF).
|
||||||
self.assertEqual((RECEIPT_METHODS['cash'], RECEIPT_METHODS['credit']), (919478944, 987762591))
|
self.assertEqual((RECEIPT_METHODS['cash'], RECEIPT_METHODS['credit']), (919478944, 987762591))
|
||||||
|
|||||||
@@ -53,5 +53,29 @@ class RefusedDeliveryTest(unittest.TestCase):
|
|||||||
self.assertEqual(self.tick_with(9, limit).call_count, 1)
|
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__':
|
if __name__ == '__main__':
|
||||||
unittest.main()
|
unittest.main()
|
||||||
|
|||||||
@@ -58,6 +58,21 @@ def run():
|
|||||||
assert quote_id in {q['id'] for q in page['quotes']}
|
assert quote_id in {q['id'] for q in page['quotes']}
|
||||||
print('PASS: a live payment attempt keeps an approved quote and its files')
|
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
|
# The attempt is final now: the quote expires, its files are freed and the
|
||||||
# customer is told once.
|
# customer is told once.
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ Run against the local stack: python -m tests.upload_limits_test
|
|||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
import secrets
|
import secrets
|
||||||
|
import time
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from urllib.error import HTTPError
|
from urllib.error import HTTPError
|
||||||
from urllib.request import Request
|
from urllib.request import Request
|
||||||
@@ -68,6 +69,10 @@ def run():
|
|||||||
# DTF-WEB-3: a burst above MAX_PENDING_UPLOADS (now 30). The 31st start
|
# DTF-WEB-3: a burst above MAX_PENDING_UPLOADS (now 30). The 31st start
|
||||||
# answers 429 with Retry-After 15, so the Site waits and retries alone.
|
# answers 429 with Retry-After 15, so the Site waits and retries alone.
|
||||||
assert int(os.environ.get('MAX_PENDING_UPLOADS', '30')) == 30
|
assert int(os.environ.get('MAX_PENDING_UPLOADS', '30')) == 30
|
||||||
|
# The gateway allows 20 requests a second with a burst of 100
|
||||||
|
# (infra/nginx.conf.template): after the starts above, a fast runner
|
||||||
|
# meets nginx's 429 before the API's (CI run 393). Let it refill.
|
||||||
|
time.sleep(6)
|
||||||
pending = []
|
pending = []
|
||||||
for index in range(30):
|
for index in range(30):
|
||||||
pending.append(client.call('/uploads', {'name': f'PENDING-{index}.png', 'size': 1})['id'])
|
pending.append(client.call('/uploads', {'name': f'PENDING-{index}.png', 'size': 1})['id'])
|
||||||
|
|||||||
@@ -43,6 +43,7 @@
|
|||||||
// A signed-in customer's details come from the account, with the saved
|
// A signed-in customer's details come from the account, with the saved
|
||||||
// delivery address, whether or not a cart was recovered.
|
// delivery address, whether or not a cart was recovered.
|
||||||
const account=await window.dtfApi('/account/me');
|
const account=await window.dtfApi('/account/me');
|
||||||
|
window.dtfContaAberta=!!account.customer;
|
||||||
const c=account.customer;
|
const c=account.customer;
|
||||||
if(c && !cliente.mail){
|
if(c && !cliente.mail){
|
||||||
cliente={name:c.name||'',cnpj:c.cnpj,zap:c.zap,mail:c.mail};
|
cliente={name:c.name||'',cnpj:c.cnpj,zap:c.zap,mail:c.mail};
|
||||||
@@ -57,6 +58,9 @@
|
|||||||
}
|
}
|
||||||
pintaEntrega();
|
pintaEntrega();
|
||||||
}
|
}
|
||||||
|
// The account's save button only exists after this answer.
|
||||||
|
window.dispatchEvent(new Event('dtf-cart-changed'));
|
||||||
|
if(typeof pintaPedido==='function') pintaPedido();
|
||||||
}catch(error){notice.textContent='Recuperação de carrinho indisponível; o pedido ainda pode ser feito nesta sessão.';}
|
}catch(error){notice.textContent='Recuperação de carrinho indisponível; o pedido ainda pode ser feito nesta sessão.';}
|
||||||
finally{restoring=false;}
|
finally{restoring=false;}
|
||||||
})();
|
})();
|
||||||
|
|||||||
@@ -26,7 +26,8 @@
|
|||||||
residue:item.residueAccepted||0,
|
residue:item.residueAccepted||0,
|
||||||
stroke:item.strokeClass||null,strokeChoice:item.strokeChoice||null,
|
stroke:item.strokeClass||null,strokeChoice:item.strokeChoice||null,
|
||||||
sheets:(item.partes||[]).map(part=>part.production),
|
sheets:(item.partes||[]).map(part=>part.production),
|
||||||
files:(item.localFiles||[]).map(file=>({name:file.name,size:file.size,lastModified:file.lastModified}))
|
files:[...(item.localFiles||[]),...(item.savedFiles||[])]
|
||||||
|
.map(file=>({name:file.name,size:file.size,lastModified:file.lastModified}))
|
||||||
})),treatment:ajusteSnapshot(),coupon:cupomCode()});
|
})),treatment:ajusteSnapshot(),coupon:cupomCode()});
|
||||||
}
|
}
|
||||||
// The quote this browser is paying, forgotten. clearDraft also empties the
|
// The quote this browser is paying, forgotten. clearDraft also empties the
|
||||||
@@ -84,12 +85,12 @@
|
|||||||
// What the server charges for a file opened by hand, never the page's own text.
|
// What the server charges for a file opened by hand, never the page's own text.
|
||||||
const zona=document.getElementById('zManual');
|
const zona=document.getElementById('zManual');
|
||||||
const extra=session.manual_extra_cents>0?rs(session.manual_extra_cents/100):'';
|
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'+
|
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':'')+'.';
|
(extra?' e o metro custa '+extra+' a mais':'')+'.';
|
||||||
const duvida=document.getElementById('duvidaManual');
|
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');
|
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){
|
if(session.manual_extra_cents>0){
|
||||||
TAXA_MANUAL=session.manual_extra_cents/100;
|
TAXA_MANUAL=session.manual_extra_cents/100;
|
||||||
if(typeof folhas!=='undefined'&&folhas.length&&typeof pintaFolha==='function')pintaFolha();
|
if(typeof folhas!=='undefined'&&folhas.length&&typeof pintaFolha==='function')pintaFolha();
|
||||||
@@ -149,6 +150,7 @@
|
|||||||
}).catch(()=>{});
|
}).catch(()=>{});
|
||||||
window.dtfSessionReady=ready;
|
window.dtfSessionReady=ready;
|
||||||
window.dtfApi=api;
|
window.dtfApi=api;
|
||||||
|
window.dtfMensagem=message;
|
||||||
ready.catch(error => { status.textContent = error.message; });
|
ready.catch(error => { status.textContent = error.message; });
|
||||||
// One message line under the steps. Its tone says what it is: a refusal or
|
// One message line under the steps. Its tone says what it is: a refusal or
|
||||||
// a missing field is an error (red), a cart that changed a warning, a
|
// a missing field is an error (red), a cart that changed a warning, a
|
||||||
@@ -214,6 +216,7 @@
|
|||||||
rows.push(linha('Ajuste Fino Redesenho'+(arts?' · '+arts+(arts===1?' arte':' artes'):'')+' · +48 h',
|
rows.push(linha('Ajuste Fino Redesenho'+(arts?' · '+arts+(arts===1?' arte':' artes'):'')+' · +48 h',
|
||||||
rs(quote.redesign.cents/100)));
|
rs(quote.redesign.cents/100)));
|
||||||
}
|
}
|
||||||
|
if(approved.proof) rows.push(linha('Prova antes de imprimir','Grátis'));
|
||||||
if(approved.coupon)
|
if(approved.coupon)
|
||||||
rows.push(linha('Cupom '+approved.coupon.code, '− '+rs(approved.coupon.discount_cents/100)));
|
rows.push(linha('Cupom '+approved.coupon.code, '− '+rs(approved.coupon.discount_cents/100)));
|
||||||
rows.push(linha('Total', rs(approved.total_cents/100), 'tot'));
|
rows.push(linha('Total', rs(approved.total_cents/100), 'tot'));
|
||||||
@@ -268,7 +271,9 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
e.promise.then(()=>{e.done=true;if(window.dtfTimings)T.uploadEnd=performance.now();falhas.delete(k);pintaEnvio();},
|
e.promise.then(id=>{e.id=id;e.done=true;if(window.dtfTimings)T.uploadEnd=performance.now();falhas.delete(k);pintaEnvio();
|
||||||
|
// "Salvar em Minhas folhas" waits for the item's files: the cart repaints when one lands.
|
||||||
|
if(window.dtfContaAberta&&typeof pintaPedido==='function')pintaPedido();},
|
||||||
error=>{envios.delete(k);if(error?.name!=='AbortError'){falhas.set(k,{file,error});
|
error=>{envios.delete(k);if(error?.name!=='AbortError'){falhas.set(k,{file,error});
|
||||||
// A refusal with a status already went to Sentry as an API error (DTF-WEB-15).
|
// A refusal with a status already went to Sentry as an API error (DTF-WEB-15).
|
||||||
if(!error?.status)window.dtfObservability?.uiError?.('Envio de arquivo falhou: '+(error?.message||'erro no envio'),'site');}pintaEnvio();});
|
if(!error?.status)window.dtfObservability?.uiError?.('Envio de arquivo falhou: '+(error?.message||'erro no envio'),'site');}pintaEnvio();});
|
||||||
@@ -278,11 +283,23 @@
|
|||||||
}
|
}
|
||||||
// Each file's upload as the product page shows it, under the uploader.
|
// Each file's upload as the product page shows it, under the uploader.
|
||||||
window.dtfEnvio={
|
window.dtfEnvio={
|
||||||
enviar:file=>{if(!falhas.has(chaveArquivo(file)))enviar(file).catch(()=>{});},
|
enviar:file=>{
|
||||||
|
if(falhas.has(chaveArquivo(file)))return Promise.resolve(null);
|
||||||
|
const p=enviar(file); p.catch(()=>{}); return p;
|
||||||
|
},
|
||||||
estado:file=>{const k=chaveArquivo(file),e=envios.get(k),f=falhas.get(k);
|
estado:file=>{const k=chaveArquivo(file),e=envios.get(k),f=falhas.get(k);
|
||||||
return f?{fase:'falhou',erro:f.error?.message||'erro no envio'}
|
return f?{fase:'falhou',erro:f.error?.message||'erro no envio'}
|
||||||
:!e?null:e.done?{fase:'pronto'}:e.sent>=file.size?{fase:'verificando'}:{fase:'enviando',enviado:e.sent};},
|
:!e?null:e.done?{fase:'pronto'}:e.sent>=file.size?{fase:'verificando'}:{fase:'enviando',enviado:e.sent};},
|
||||||
deNovo:file=>{falhas.delete(chaveArquivo(file));enviar(file).catch(()=>{});pintaEnvio();},
|
deNovo:file=>{falhas.delete(chaveArquivo(file));enviar(file).catch(()=>{});pintaEnvio();},
|
||||||
|
// A file already on the server (a saved sheet opened for editing): its id
|
||||||
|
// is known, so a later enviar(file) resolves at once and sends nothing.
|
||||||
|
conhecido:(file,uploadId)=>{
|
||||||
|
const k=chaveArquivo(file);
|
||||||
|
falhas.delete(k);
|
||||||
|
envios.set(k,{file,sent:file.size,done:true,id:uploadId,failed:null,
|
||||||
|
stop:new AbortController(),promise:Promise.resolve(uploadId)});
|
||||||
|
},
|
||||||
|
idDe:file=>{const e=envios.get(chaveArquivo(file));return e&&e.done?(e.id??null):null;},
|
||||||
// A file taken off the page, and in no cart item, stops going.
|
// A file taken off the page, and in no cart item, stops going.
|
||||||
manter:files=>{
|
manter:files=>{
|
||||||
const quero=new Set([...files,...pedido.flatMap(it=>it.localFiles||[]),...(itemAtual?.localFiles||[])].map(chaveArquivo));
|
const quero=new Set([...files,...pedido.flatMap(it=>it.localFiles||[]),...(itemAtual?.localFiles||[])].map(chaveArquivo));
|
||||||
@@ -406,7 +423,7 @@
|
|||||||
if (texto) el.append(document.createTextNode(texto));
|
if (texto) el.append(document.createTextNode(texto));
|
||||||
if (e?.fase==='enviando') {
|
if (e?.fase==='enviando') {
|
||||||
const nota=document.createElement('small'); nota.className='envioNota';
|
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.append(nota);
|
||||||
}
|
}
|
||||||
el.classList.toggle('ok', e?.fase==='pronto');
|
el.classList.toggle('ok', e?.fase==='pronto');
|
||||||
@@ -475,12 +492,17 @@
|
|||||||
if (draftId && quotedCart === cartSnapshot()) { await refresh(true); return; }
|
if (draftId && quotedCart === cartSnapshot()) { await refresh(true); return; }
|
||||||
if (draftId) clearDraft();
|
if (draftId) clearDraft();
|
||||||
if (!clienteOk() || !entrega.cotado) return;
|
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
|
// Guidance, not a failure: the customer still has a quality note to
|
||||||
// confirm, and the page takes them to it (Sentry DTF-WEB-Y).
|
// confirm, and the page takes them to it (Sentry DTF-WEB-Y).
|
||||||
if (!cartPodeEnviar()) {
|
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'});
|
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();
|
const semArquivo=faltaEnvioMensagem();
|
||||||
if (semArquivo) return message(semArquivo+'.','error');
|
if (semArquivo) return message(semArquivo+'.','error');
|
||||||
@@ -489,14 +511,18 @@
|
|||||||
// One item carries at most 200 files (app/core/models.py); a bigger cart
|
// One item carries at most 200 files (app/core/models.py); a bigger cart
|
||||||
// line is refused here, with the reason, never by the generic 422.
|
// line is refused here, with the reason, never by the generic 422.
|
||||||
const semCap=cart.flatMap(line=>line.partes?.length?line.partes:[line]);
|
const semCap=cart.flatMap(line=>line.partes?.length?line.partes:[line]);
|
||||||
if (semCap.some(item=>(item.localFiles||[]).length>200))
|
const totalArquivos=item=>(item.localFiles||[]).length+(item.savedFiles||[]).length;
|
||||||
|
if (semCap.some(item=>totalArquivos(item)>200))
|
||||||
return message('Este item tem mais de 200 arquivos. Divida em dois itens.','error');
|
return message('Este item tem mais de 200 arquivos. Divida em dois itens.','error');
|
||||||
const initialCart=cartSnapshot();
|
const initialCart=cartSnapshot();
|
||||||
busy = true;
|
busy = true;
|
||||||
$('bPagar').disabled = true;
|
$('bPagar').disabled = true;
|
||||||
try {
|
try {
|
||||||
await ready;
|
await ready;
|
||||||
if((await api('/session')).cart_scope !== (await ready).cart_scope) throw new Error('Sua conta ou sessão mudou. Recarregue a página antes de enviar o carrinho.');
|
// Guidance, not a fault: the customer signed in or out in another tab
|
||||||
|
// (DTF-WEB-26); a warning, so it stays out of Sentry.
|
||||||
|
if((await api('/session')).cart_scope !== (await ready).cart_scope){
|
||||||
|
const changed=new Error('Sua conta ou sessão mudou. Recarregue a página antes de enviar o carrinho.');changed.guidance=true;throw changed;}
|
||||||
const items=[];
|
const items=[];
|
||||||
pintaEnvio();
|
pintaEnvio();
|
||||||
// Loose art split by stroke (item 17) is one cart line and one order item
|
// Loose art split by stroke (item 17) is one cart line and one order item
|
||||||
@@ -505,15 +531,21 @@
|
|||||||
? line.partes.map((part,i)=>({...line,...part,split:{group:'f'+index,part:i+1,of:line.partes.length}}))
|
? line.partes.map((part,i)=>({...line,...part,split:{group:'f'+index,part:i+1,of:line.partes.length}}))
|
||||||
: [line]);
|
: [line]);
|
||||||
for (const item of sheets) {
|
for (const item of sheets) {
|
||||||
if (!item.localFiles?.length) throw new Error('Selecione novamente os arquivos deste item.');
|
const locais=item.localFiles||[], salvos=item.savedFiles||[];
|
||||||
|
if (!locais.length && !salvos.length) throw new Error('Selecione novamente os arquivos deste item.');
|
||||||
const uploads=[];
|
const uploads=[];
|
||||||
for (const [index,file] of item.localFiles.entries()) {
|
if (salvos.length) {
|
||||||
uploads.push(await upload(file));
|
// A sheet kept in Minhas folhas: the server already has the files.
|
||||||
enviaFoto(uploads[index], item.fotos?.[index]);
|
for (const saved of salvos) uploads.push(saved.upload_id);
|
||||||
|
} else {
|
||||||
|
for (const [index,file] of locais.entries()) {
|
||||||
|
uploads.push(await upload(file));
|
||||||
|
enviaFoto(uploads[index], item.fotos?.[index]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
// Layout versions the server takes: 3 since 2026-10-21, 2 for a cart saved before.
|
// 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)
|
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,
|
items.push({mode:item.modo, metres:String(item.metros), grade:item.nota, uploads,
|
||||||
production:{...item.production,sources:item.production.sources.map((source,index)=>({
|
production:{...item.production,sources:item.production.sources.map((source,index)=>({
|
||||||
upload_id:uploads[index],...source}))},
|
upload_id:uploads[index],...source}))},
|
||||||
@@ -562,7 +594,7 @@
|
|||||||
quotedCart=initialCart;localStorage.setItem('dtf-quote-cart',quotedCart);
|
quotedCart=initialCart;localStorage.setItem('dtf-quote-cart',quotedCart);
|
||||||
draftId=quote.id; localStorage.setItem('dtf-quote',draftId);
|
draftId=quote.id; localStorage.setItem('dtf-quote',draftId);
|
||||||
await refresh(true);
|
await refresh(true);
|
||||||
} catch(error) { message(error.message,couponRefusal(error.status,error.message)?'warn':'error'); }
|
} catch(error) { message(error.message,error.guidance||couponRefusal(error.status,error.message)?'warn':'error'); }
|
||||||
finally { busy=false; pintaEntrega(); }
|
finally { busy=false; pintaEntrega(); }
|
||||||
};
|
};
|
||||||
// `go`: the customer asked to pay, so the cart page moves to the payment page.
|
// `go`: the customer asked to pay, so the cart page moves to the payment page.
|
||||||
@@ -597,7 +629,7 @@
|
|||||||
if (quote.status==='pending_review') {
|
if (quote.status==='pending_review') {
|
||||||
message((await ready).environment==='local'
|
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. 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') {
|
} else if (quote.status==='approved') {
|
||||||
if ((await ready).payment_provider === 'mercadopago') {
|
if ((await ready).payment_provider === 'mercadopago') {
|
||||||
if (naPix()) await paginaPix(quote, version);
|
if (naPix()) await paginaPix(quote, version);
|
||||||
@@ -622,7 +654,7 @@
|
|||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
message(quote.status==='discarded'
|
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');
|
: 'Cotação expirada. Envie o carrinho de novo para pagar.','warn');
|
||||||
button('Voltar ao carrinho',()=>{clearDraft();vaiPara(CARRINHO);});
|
button('Voltar ao carrinho',()=>{clearDraft();vaiPara(CARRINHO);});
|
||||||
}
|
}
|
||||||
@@ -874,10 +906,10 @@
|
|||||||
unmountCard();
|
unmountCard();
|
||||||
into.replaceChildren(node('p',result.status==='approved'
|
into.replaceChildren(node('p',result.status==='approved'
|
||||||
? 'Pagamento aprovado. Confirmando seu pedido…'
|
? '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();
|
waitForOrder();
|
||||||
} else {
|
} 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');
|
throw new Error('rejected');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
123
web/index.html
123
web/index.html
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
<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.googleapis.com">
|
||||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
<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">
|
<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 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>
|
<span class="chip2">Franca · SP · envio em até 24 h</span>
|
||||||
</div>
|
</div>
|
||||||
<h1>A gente encaixa sua folha e você paga <em>menos metro</em></h1>
|
<h1>Encaixamos 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>
|
<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">
|
<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>
|
<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>
|
<span>Sem cadastro · preço em segundos</span>
|
||||||
@@ -753,15 +753,6 @@ h2 em{font-style:normal;color:var(--laranja)}
|
|||||||
<div><span>4</span><div><b>Acompanhe</b><p>Em Minha conta, com aviso no WhatsApp quando ficar pronto.</p></div></div>
|
<div><span>4</span><div><b>Acompanhe</b><p>Em Minha conta, com aviso no WhatsApp quando ficar pronto.</p></div></div>
|
||||||
</div></section>
|
</div></section>
|
||||||
|
|
||||||
<!-- VÍDEOS -->
|
|
||||||
<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>
|
|
||||||
</div>
|
|
||||||
<div class="videosGrid" id="videosGrid"></div>
|
|
||||||
</div></section>
|
|
||||||
|
|
||||||
<!-- ENVIO -->
|
<!-- ENVIO -->
|
||||||
<section id="envio">
|
<section id="envio">
|
||||||
<nav class="passos" id="passos" aria-label="Etapas do pedido" hidden>
|
<nav class="passos" id="passos" aria-label="Etapas do pedido" hidden>
|
||||||
@@ -794,7 +785,7 @@ h2 em{font-style:normal;color:var(--laranja)}
|
|||||||
<button class="ec a" data-modo="avulsa">
|
<button class="ec a" data-modo="avulsa">
|
||||||
<div class="ec-top"><span class="ec-kind">DTF TÊXTIL · 57 CM</span></div>
|
<div class="ec-top"><span class="ec-kind">DTF TÊXTIL · 57 CM</span></div>
|
||||||
<h3>Artes avulsas</h3>
|
<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-pe">
|
||||||
<div class="ec-preco"><b data-preco="avulsa">R$ 21,90</b><span>por metro</span></div>
|
<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>
|
<span class="ec-go">Enviar minhas artes</span>
|
||||||
@@ -862,8 +853,8 @@ h2 em{font-style:normal;color:var(--laranja)}
|
|||||||
<span id="zLimite">Até 4 GB por arquivo.</span>
|
<span id="zLimite">Até 4 GB por arquivo.</span>
|
||||||
<span class="bt">ou escolher no computador</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="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.
|
<span class="zManual" id="zManual"><b>CDR, AI, PSD e TIFF</b> também entram. Abrimos o arquivo
|
||||||
Alguém abre na mão, e o metro custa R$ 2,00 a mais.</span>
|
manualmente e o metro custa R$ 2,00 a mais.</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="envios" id="envios" aria-live="polite"></div>
|
<div class="envios" id="envios" aria-live="polite"></div>
|
||||||
<div class="recusa" id="recusa" style="display:none"></div>
|
<div class="recusa" id="recusa" style="display:none"></div>
|
||||||
@@ -876,63 +867,60 @@ h2 em{font-style:normal;color:var(--laranja)}
|
|||||||
<details>
|
<details>
|
||||||
<summary>Dicas para o seu arquivo</summary>
|
<summary>Dicas para o seu arquivo</summary>
|
||||||
<ul>
|
<ul>
|
||||||
<li class="s"><b>300 DPI no tamanho que vai imprimir.</b> É a resolução ideal</li>
|
<li class="s"><b>300 DPI no tamanho de impressão.</b> É a resolução ideal</li>
|
||||||
<li class="s"><b>O tamanho manda mais que o arquivo.</b> A mesma arte passa
|
<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 costuma melhorar a resolução</li>
|
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> Se as suas artes têm
|
<li class="s"><b>Larguras parecidas rendem mais.</b> Cabem mais artes por
|
||||||
medidas próximas, cabem mais por fileira e a folha encolhe</li>
|
fileira e a folha fica menor</li>
|
||||||
</ul>
|
</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>
|
||||||
|
|
||||||
<details>
|
<details>
|
||||||
<summary>O que arrumamos sem cobrar</summary>
|
<summary>O que arrumamos sem cobrar</summary>
|
||||||
<ul>
|
<ul>
|
||||||
<li class="s"><b>Artes coladas.</b> Separamos com 5 mm, sem você refazer nada</li>
|
<li class="s"><b>Artes coladas.</b> Separamos com 5 mm</li>
|
||||||
<li class="s"><b>Encaixe mal aproveitado.</b> Remanejamos e a sua folha
|
<li class="s"><b>Encaixe com sobra.</b> Reencaixamos, e você paga pela
|
||||||
encolhe — você paga menos metro do que enviou</li>
|
folha menor</li>
|
||||||
<li class="s"><b>Peça passando da largura.</b> Remanejamos em vez de cortar</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. Só respeitar a largura do filme</li>
|
<li class="s"><b>Margem.</b> Não precisa deixar, basta respeitar a largura do filme</li>
|
||||||
</ul>
|
</ul>
|
||||||
</details>
|
</details>
|
||||||
|
|
||||||
<details>
|
<details>
|
||||||
<summary>Manda em PNG e sai na hora</summary>
|
<summary>Formatos de arquivo</summary>
|
||||||
<ul>
|
<ul>
|
||||||
<li class="s"><b>PNG</b> com fundo transparente entra direto, sem passar
|
<li class="s"><b>PNG</b> com fundo transparente entra direto e não tem
|
||||||
por ninguém, e não tem limite de comprimento. Só que a gente lê a resolução
|
limite de comprimento. Lemos a resolução <b>do arquivo</b>: uma arte ampliada
|
||||||
<b>do arquivo</b>: se a arte foi ampliada antes de exportar, isso não aparece
|
antes de exportar passa na conferência e sai serrilhada no filme</li>
|
||||||
para nós — e sai serrilhado no filme do mesmo jeito</li>
|
<li class="s"><b>PDF tem a conferência mais precisa.</b> Medimos a resolução
|
||||||
<li class="s"><b>PDF é o que conferimos melhor.</b> Nele medimos a resolução de
|
de cada imagem dentro da folha</li>
|
||||||
cada imagem dentro da folha, uma por uma. É onde a conferência
|
<li class="a"><b>PDF acima de 508 cm.</b> Só entra com UserUnit. Sem ele,
|
||||||
de resolução fica mais precisa</li>
|
divida a folha ou envie em PNG. Um PDF de uma página por folha</li>
|
||||||
<li class="a"><b>PDF grande.</b> Sem UserUnit, a página passa do limite de 508 cm
|
<li class="a"><b>TIFF, PSD, AI e CDR</b> também entram, mas o site não confere:
|
||||||
do formato; divida a folha ou mande PNG. Envie um PDF de uma página por folha.</li>
|
<span id="duvidaManual">abrimos o arquivo manualmente, leva mais tempo
|
||||||
<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
|
|
||||||
e o metro custa R$ 2,00 a mais</span></li>
|
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
|
<li class="a"><b>JPG não entra:</b> não tem fundo transparente, e o fundo
|
||||||
fundo sai no filme. Exporte a folha em PNG ou PDF</li>
|
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
|
<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>
|
encaixa pela forma da arte</li>
|
||||||
</ul>
|
</ul>
|
||||||
</details>
|
</details>
|
||||||
|
|
||||||
<details>
|
<details>
|
||||||
<summary>O que só você resolve</summary>
|
<summary>O que só você resolve</summary>
|
||||||
<ul>
|
<ul>
|
||||||
<li class="n"><b>Fundo branco ou colorido.</b> Precisa ser transparente de
|
<li class="n"><b>Fundo branco ou colorido.</b> O fundo precisa ser transparente:
|
||||||
verdade — branco parecendo transparente sai branco no filme. Sem isso, o site
|
branco sai branco no filme, e o site não deixa pagar</li>
|
||||||
não deixa pagar</li>
|
<li class="n"><b>Pontinho de recorte.</b> Todo ponto de tinta sai impresso,
|
||||||
<li class="n"><b>Pontinho de recorte.</b> A impressora enxerga qualquer
|
por menor que seja. Mostramos onde estão: apague no arquivo ou aceite
|
||||||
resíduo e imprime. Não existe pequeno demais: o site mostra onde cada um está
|
imprimir assim</li>
|
||||||
e pede que você apague ou aceite imprimir assim</li>
|
|
||||||
<li class="n"><b>Cópias sobrepostas.</b> Duas iguais com 1 mm de diferença
|
<li class="n"><b>Cópias sobrepostas.</b> Duas iguais com 1 mm de diferença
|
||||||
saem duplicadas</li>
|
saem duplicadas</li>
|
||||||
<li class="n"><b>Menos de 96 DPI.</b> Abaixo disso não imprimimos: sai
|
<li class="n"><b>Menos de 96 DPI.</b> Não imprimimos: sai serrilhado
|
||||||
serrilhado a ponto de não valer o filme</li>
|
demais</li>
|
||||||
<li class="n"><b>Degradê de transparência</b>, comum em arte de IA. O branco
|
<li class="n"><b>Degradê de transparência</b>, comum em arte feita por IA.
|
||||||
por baixo sai irregular e sai assim mesmo</li>
|
O branco por baixo sai irregular, e imprimimos assim mesmo</li>
|
||||||
</ul>
|
</ul>
|
||||||
</details>
|
</details>
|
||||||
</aside>
|
</aside>
|
||||||
@@ -951,7 +939,9 @@ h2 em{font-style:normal;color:var(--laranja)}
|
|||||||
<div id="compraVals" hidden>
|
<div id="compraVals" hidden>
|
||||||
<div class="cLin"><span id="cMetroLbl">Metro</span><b id="cMetro">—</b></div>
|
<div class="cLin"><span id="cMetroLbl">Metro</span><b id="cMetro">—</b></div>
|
||||||
<div class="cLin"><span>Metragem <small>(a cada 10 cm)</small></span><b id="cMetragem">—</b></div>
|
<div class="cLin"><span>Metragem <small>(a cada 10 cm)</small></span><b id="cMetragem">—</b></div>
|
||||||
|
<div id="cEncaixe" hidden></div>
|
||||||
<p class="cObs" id="cObs"></p>
|
<p class="cObs" id="cObs"></p>
|
||||||
|
<div id="cVao" hidden></div>
|
||||||
<p class="cObs" id="cProxima"></p>
|
<p class="cObs" id="cProxima"></p>
|
||||||
<div class="cTot"><span>Total</span><b id="cTotal">—</b></div>
|
<div class="cTot"><span>Total</span><b id="cTotal">—</b></div>
|
||||||
<div id="qmsg" style="display:none"></div>
|
<div id="qmsg" style="display:none"></div>
|
||||||
@@ -971,7 +961,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="ampliaCab"><b id="mistaTit">Traços finos e áreas chapadas</b></div>
|
||||||
<div class="mistaCorpo">
|
<div class="mistaCorpo">
|
||||||
<p id="mistaTxt"></p>
|
<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>
|
</div>
|
||||||
</dialog>
|
</dialog>
|
||||||
<dialog class="ampliaDlg mistaDlg" id="linhaDlg" aria-labelledby="linhaTit">
|
<dialog class="ampliaDlg mistaDlg" id="linhaDlg" aria-labelledby="linhaTit">
|
||||||
@@ -1125,16 +1115,16 @@ h2 em{font-style:normal;color:var(--laranja)}
|
|||||||
<h4>Prova antes de imprimir</h4>
|
<h4>Prova antes de imprimir</h4>
|
||||||
<label class="provaOp"><input type="checkbox" id="fProva">
|
<label class="provaOp"><input type="checkbox" id="fProva">
|
||||||
<span><b>Quero aprovar uma prova antes de imprimir</b>
|
<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
|
Imprimimos uma prova de até 30 cm e mandamos a foto pelo WhatsApp. O resto sai depois
|
||||||
depois do seu ok, então o pedido espera a sua resposta. Até 3 provas por pedido, sem custo.</span></label>
|
que você aprovar. Até 3 provas por pedido, sem custo.</span></label>
|
||||||
|
<p class="provaMin" id="provaMin" hidden>A prova é para pedidos acima de 10 m.</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="cxE" id="tratamentoBox" hidden>
|
<div class="cxE" id="tratamentoBox" hidden>
|
||||||
<h4>Ajuste Fino</h4>
|
<h4>Ajuste Fino</h4>
|
||||||
<label class="provaOp"><input type="checkbox" id="fTratamento">
|
<label class="provaOp"><input type="checkbox" id="fTratamento">
|
||||||
<span><b>Ajuste Fino em todas as artes — <span id="tratamentoPreco"></span> por arte</b>
|
<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
|
Nosso designer deixa cada arte com fundo transparente e 300 DPI. O pedido leva 24 h a mais.</span></label>
|
||||||
pelo card. O prazo do pedido aumenta em 24 h.</span></label>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -1189,13 +1179,13 @@ h2 em{font-style:normal;color:var(--laranja)}
|
|||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
<div class="nota2" id="tabelaFaixas" hidden></div>
|
<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>
|
||||||
<div class="info2-vant">
|
<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">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">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">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>Erro pego antes de imprimir. Arquivo guardado por 30 dias.</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>
|
||||||
</div></section>
|
</div></section>
|
||||||
|
|
||||||
@@ -1204,6 +1194,15 @@ h2 em{font-style:normal;color:var(--laranja)}
|
|||||||
<a href="/carrinho" id="barraMBtn">Continuar</a>
|
<a href="/carrinho" id="barraMBtn">Continuar</a>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- VÍDEOS -->
|
||||||
|
<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>O que acontece com a sua arte, do envio à retirada.</p>
|
||||||
|
</div>
|
||||||
|
<div class="videosGrid" id="videosGrid"></div>
|
||||||
|
</div></section>
|
||||||
|
|
||||||
<footer><div class="w">
|
<footer><div class="w">
|
||||||
<div class="frow">
|
<div class="frow">
|
||||||
<span class="fmarca"><img src="https://cdn.vnda.com.br/dropstar/2025/12/17/logo-header-15125700-16129080.png?v=1766009286" alt="Dropstar">DTF</span>
|
<span class="fmarca"><img src="https://cdn.vnda.com.br/dropstar/2025/12/17/logo-header-15125700-16129080.png?v=1766009286" alt="Dropstar">DTF</span>
|
||||||
@@ -1217,7 +1216,7 @@ h2 em{font-style:normal;color:var(--laranja)}
|
|||||||
<a href="https://wa.me/message/NJ76CLIOUGXLB1" target="_blank" rel="noopener">16 99428-0056</a>
|
<a href="https://wa.me/message/NJ76CLIOUGXLB1" target="_blank" rel="noopener">16 99428-0056</a>
|
||||||
· arquivos 16 99230-2546<br>
|
· arquivos 16 99230-2546<br>
|
||||||
<a href="mailto:atendimentodropstar@gmail.com">atendimentodropstar@gmail.com</a><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
|
Retirada em Franca, de segunda a sexta, das 7h às 18h
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -27,6 +27,31 @@ const stalled=order=>!!order.late;
|
|||||||
// A mark on the card, not a stage; a finished order no longer needs it.
|
// A mark on the card, not a stage; a finished order no longer needs it.
|
||||||
const waitingContact=order=>!!order.contact_since&&!order.cancelled_at&&order.state!=='fin';
|
const waitingContact=order=>!!order.contact_since&&!order.cancelled_at&&order.state!=='fin';
|
||||||
const contactWho=order=>(order.contact_by||'')+' em '+when(order.contact_since);
|
const contactWho=order=>(order.contact_by||'')+' em '+when(order.contact_since);
|
||||||
|
// The redesign previews of an order: each one is sent to the customer and
|
||||||
|
// waits for the answer; the card counts them.
|
||||||
|
const previewsOf=order=>order.previews||[];
|
||||||
|
// Only a card still in Arte recebida waits for a preview: one left open when
|
||||||
|
// the card moved on or was cancelled neither shows nor reminds anyone.
|
||||||
|
const openPreview=order=>order.state==='rec'&&!order.cancelled_at?previewsOf(order).find(p=>!p.decided_at)||null:null;
|
||||||
|
const previewApproved=order=>previewsOf(order).some(p=>p.result==='approved');
|
||||||
|
// A preview waiting three hours or more reminds the designer, once per block.
|
||||||
|
function remindPreviews(orders){
|
||||||
|
if(!may('produce'))return;
|
||||||
|
const open=[];
|
||||||
|
for(const order of orders){const preview=openPreview(order);if(preview)open.push({order,preview});}
|
||||||
|
open.sort((a,b)=>Date.parse(a.preview.sent_at)-Date.parse(b.preview.sent_at));
|
||||||
|
for(const {order,preview} of open){
|
||||||
|
const block=Math.floor((Date.now()-Date.parse(preview.sent_at))/(3*3600e3));
|
||||||
|
if(block<1)continue;
|
||||||
|
const key='dtf-preview-reminder:'+order.id+':'+preview.number;
|
||||||
|
try{
|
||||||
|
if(Number(localStorage.getItem(key))>=block)continue;
|
||||||
|
localStorage.setItem(key,String(block));
|
||||||
|
}catch(_){return;}
|
||||||
|
say('Prévia '+preview.number+' do pedido #'+order.number+' com o cliente há '+block*3+' h. Confira a resposta.',false,15000);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
// The print proof (app/proof.py): asked for at checkout, or an order above 10 m.
|
// 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.
|
// The room marks "Prova OK" once it is checked; without it, no Finalizado.
|
||||||
const PROOF_ABOVE_METRES=10;
|
const PROOF_ABOVE_METRES=10;
|
||||||
@@ -61,15 +86,16 @@ const residueBadge=item=>badge('! Resíduo aceito','warn','O cliente aceitou imp
|
|||||||
const PRINTING={imprimindo:['Imprimindo','live','Já ripou, está rodando'],
|
const PRINTING={imprimindo:['Imprimindo','live','Já ripou, está rodando'],
|
||||||
aguardando:['Na vez','wait','Na hot folder, espera os da frente'],
|
aguardando:['Na vez','wait','Na hot folder, espera os da frente'],
|
||||||
ripando:['Ripando','rip','O Flexi está ripando enquanto o anterior roda']};
|
ripando:['Ripando','rip','O Flexi está ripando enquanto o anterior roda']};
|
||||||
// A film in parts on its machine (items 10 and 13, Dropstar 2026-10-30):
|
// A film in parts on its machine (items 10 and 13, Dropstar 2026-10-30): how
|
||||||
// "parte 3/7 imprimindo · 4/7 ripando". Flexi rips the part it took last from
|
// many parts the machine has taken. The hot folder takes a PNG in about 10 s
|
||||||
// the hot folder while the one before it prints.
|
// and the Hoson queues it (Marcus, 2026-12-01), so a part taken is not known
|
||||||
|
// to be ripping or printing: the card says only what the folder shows.
|
||||||
function partsStep(order){
|
function partsStep(order){
|
||||||
const hot=order.hot;if(!hot||hot.parts<2)return null;
|
const hot=order.hot;if(!hot||hot.parts<2)return null;
|
||||||
const n=hot.parts, t=hot.taken;
|
const n=hot.parts, t=hot.taken;
|
||||||
if(!t)return ['Parte 1/'+n+' na hot folder','wait'];
|
if(!t)return ['Parte 1/'+n+' na hot folder','wait'];
|
||||||
if(t===1)return ['Parte 1/'+n+' ripando','rip'];
|
if(t<n)return [t+'/'+n+' partes com a máquina','live'];
|
||||||
return ['Parte '+(t-1)+'/'+n+' imprimindo · '+t+'/'+n+' ripando','live'];
|
return ['As '+n+' partes com a máquina','live'];
|
||||||
}
|
}
|
||||||
async function proofOk(order){
|
async function proofOk(order){
|
||||||
await api('/orders/'+order.id+'/proof',{});say('Prova do pedido #'+order.number+' conferida.');await load();
|
await api('/orders/'+order.id+'/proof',{});say('Prova do pedido #'+order.number+' conferida.');await load();
|
||||||
@@ -187,7 +213,10 @@ const GLYPH={
|
|||||||
cor:'M232,144a64.07,64.07,0,0,1-64,64H80a8,8,0,0,1,0-16h88a48,48,0,0,0,0-96H51.31l34.35,34.34a8,8,0,0,1-11.32,11.32l-48-48a8,8,0,0,1,0-11.32l48-48A8,8,0,0,1,85.66,45.66L51.31,80H168A64.07,64.07,0,0,1,232,144Z',
|
cor:'M232,144a64.07,64.07,0,0,1-64,64H80a8,8,0,0,1,0-16h88a48,48,0,0,0,0-96H51.31l34.35,34.34a8,8,0,0,1-11.32,11.32l-48-48a8,8,0,0,1,0-11.32l48-48A8,8,0,0,1,85.66,45.66L51.31,80H168A64.07,64.07,0,0,1,232,144Z',
|
||||||
rev:'M247.31,124.76c-.35-.79-8.82-19.58-27.65-38.41C194.57,61.26,162.88,48,128,48S61.43,61.26,36.34,86.35C17.51,105.18,9,124,8.69,124.76a8,8,0,0,0,0,6.5c.35.79,8.82,19.57,27.65,38.4C61.43,194.74,93.12,208,128,208s66.57-13.26,91.66-38.34c18.83-18.83,27.3-37.61,27.65-38.4A8,8,0,0,0,247.31,124.76ZM128,192c-30.78,0-57.67-11.19-79.93-33.25A133.47,133.47,0,0,1,25,128,133.33,133.33,0,0,1,48.07,97.25C70.33,75.19,97.22,64,128,64s57.67,11.19,79.93,33.25A133.46,133.46,0,0,1,231.05,128C223.84,141.46,192.43,192,128,192Zm0-112a48,48,0,1,0,48,48A48.05,48.05,0,0,0,128,80Zm0,80a32,32,0,1,1,32-32A32,32,0,0,1,128,160Z',
|
rev:'M247.31,124.76c-.35-.79-8.82-19.58-27.65-38.41C194.57,61.26,162.88,48,128,48S61.43,61.26,36.34,86.35C17.51,105.18,9,124,8.69,124.76a8,8,0,0,0,0,6.5c.35.79,8.82,19.57,27.65,38.4C61.43,194.74,93.12,208,128,208s66.57-13.26,91.66-38.34c18.83-18.83,27.3-37.61,27.65-38.4A8,8,0,0,0,247.31,124.76ZM128,192c-30.78,0-57.67-11.19-79.93-33.25A133.47,133.47,0,0,1,25,128,133.33,133.33,0,0,1,48.07,97.25C70.33,75.19,97.22,64,128,64s57.67,11.19,79.93,33.25A133.46,133.46,0,0,1,231.05,128C223.84,141.46,192.43,192,128,192Zm0-112a48,48,0,1,0,48,48A48.05,48.05,0,0,0,128,80Zm0,80a32,32,0,1,1,32-32A32,32,0,0,1,128,160Z',
|
||||||
fin:'M173.66,98.34a8,8,0,0,1,0,11.32l-56,56a8,8,0,0,1-11.32,0l-24-24a8,8,0,0,1,11.32-11.32L112,148.69l50.34-50.35A8,8,0,0,1,173.66,98.34ZM232,128A104,104,0,1,1,128,24,104.11,104.11,0,0,1,232,128Zm-16,0a88,88,0,1,0-88,88A88.1,88.1,0,0,0,216,128Z'};
|
fin:'M173.66,98.34a8,8,0,0,1,0,11.32l-56,56a8,8,0,0,1-11.32,0l-24-24a8,8,0,0,1,11.32-11.32L112,148.69l50.34-50.35A8,8,0,0,1,173.66,98.34ZM232,128A104,104,0,1,1,128,24,104.11,104.11,0,0,1,232,128Zm-16,0a88,88,0,1,0-88,88A88.1,88.1,0,0,0,216,128Z'};
|
||||||
const orderMetres=o=>o.snapshot.items.reduce((t,i)=>t+Number(i.billed_metres),0);
|
// The film an order takes: what is billed, or, for a free proof card, the film
|
||||||
|
// its sheets print (proof_film_cm, from the server).
|
||||||
|
const proofFilmMetres=o=>Object.values(o.proof_film_cm||{}).reduce((t,cm)=>t+Number(cm),0)/100;
|
||||||
|
const orderMetres=o=>o.snapshot.proof_of?proofFilmMetres(o):o.snapshot.items.reduce((t,i)=>t+Number(i.billed_metres),0);
|
||||||
// On a phone the board shows one stage at a time, picked from the chips above it.
|
// On a phone the board shows one stage at a time, picked from the chips above it.
|
||||||
let phoneCol='rec';
|
let phoneCol='rec';
|
||||||
// Atrasados (front 11): the cards past the stage limit, with the person
|
// Atrasados (front 11): the cards past the stage limit, with the person
|
||||||
@@ -405,6 +434,11 @@ function cardFlags(order){
|
|||||||
if(redo.length)out.push(['bad','Retrabalho',redo.map(r=>'Retrabalho · '+REWORK_CAUSES[r.cause]+' · '+metres(r.metres)+(r.authorized?'':' · aguardando autorização')).join(' · ')]);
|
if(redo.length)out.push(['bad','Retrabalho',redo.map(r=>'Retrabalho · '+REWORK_CAUSES[r.cause]+' · '+metres(r.metres)+(r.authorized?'':' · aguardando autorização')).join(' · ')]);
|
||||||
if(live&&s.items.some(mirroredItem))out.push(['warn','Espelhada',MIRROR_NOTE]);
|
if(live&&s.items.some(mirroredItem))out.push(['warn','Espelhada',MIRROR_NOTE]);
|
||||||
if(waitingContact(order))out.push(['warn','Contato','Aguardando contato: '+order.contact_note+' · '+contactWho(order)]);
|
if(waitingContact(order))out.push(['warn','Contato','Aguardando contato: '+order.contact_note+' · '+contactWho(order)]);
|
||||||
|
const transfers=order.transfers||[];
|
||||||
|
if(live&&transfers.length){const t=transfers[transfers.length-1];
|
||||||
|
out.push(['warn','Transferido · '+t.from_name+' → '+t.to_name,
|
||||||
|
'Motivo: '+t.reason+' · '+t.created_by+' em '+when(t.created_at)+(t.resumed_from>1?' · recomeçou da parte '+t.resumed_from:'')+
|
||||||
|
(t.delete_prt?.length?' · apague da pasta do Hoson da '+t.from_name+': '+t.delete_prt.join(', '):'')+'. Confira a emenda de tom.']);}
|
||||||
if(order.snapshot.treatment){
|
if(order.snapshot.treatment){
|
||||||
const n=Number(order.snapshot.treatment.arts)||1;
|
const n=Number(order.snapshot.treatment.arts)||1;
|
||||||
out.push(['warn','Ajuste Fino · '+n+(n===1?' arte':' artes'),
|
out.push(['warn','Ajuste Fino · '+n+(n===1?' arte':' artes'),
|
||||||
@@ -414,6 +448,13 @@ function cardFlags(order){
|
|||||||
const n=Number(order.snapshot.redesign.arts)||1;
|
const n=Number(order.snapshot.redesign.arts)||1;
|
||||||
out.push(['warn','Redesenho · '+n+(n===1?' arte':' artes'),
|
out.push(['warn','Redesenho · '+n+(n===1?' arte':' artes'),
|
||||||
'O designer redesenha ou vetoriza a arte antes de imprimir; prazo +48 h']);
|
'O designer redesenha ou vetoriza a arte antes de imprimir; prazo +48 h']);
|
||||||
|
const previews=previewsOf(order), open=openPreview(order), many=previews.length>1?' · '+previews.length+' prévias':'';
|
||||||
|
if(open)out.push(['warn','Prévia '+open.number+' com o cliente'+many,
|
||||||
|
'Enviada por '+open.sent_by+' em '+when(open.sent_at)+'; o tempo da etapa está parado']);
|
||||||
|
else if(previewApproved(order)){
|
||||||
|
const p=previews.filter(x=>x.result==='approved').slice(-1)[0];
|
||||||
|
out.push(['','Prévia aprovada'+many,'A prévia '+p.number+' foi aprovada em '+when(p.decided_at)+'; envie a arte final']);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if(order.proof_parent)out.push(['warn','Prova do #'+order.proof_parent.number,'Card da prova do pedido #'+order.proof_parent.number]);
|
if(order.proof_parent)out.push(['warn','Prova do #'+order.proof_parent.number,'Card da prova do pedido #'+order.proof_parent.number]);
|
||||||
if(live&&waitingProof(order)&&order.state!=='tra')out.push(['warn','Aguardando prova','Entra na fila com Prova OK no card #'+order.proof_card.number]);
|
if(live&&waitingProof(order)&&order.state!=='tra')out.push(['warn','Aguardando prova','Entra na fila com Prova OK no card #'+order.proof_card.number]);
|
||||||
@@ -487,7 +528,7 @@ function card(order,place){
|
|||||||
if(special){const tag=node('span',special,'origin');tag.title=special;meta.append(tag);}
|
if(special){const tag=node('span',special,'origin');tag.title=special;meta.append(tag);}
|
||||||
if(s.items.some(i=>i.mode==='premium'))meta.append(badge('Premium','','DTF Têxtil Premium: 8 passadas, branco no máximo'));
|
if(s.items.some(i=>i.mode==='premium'))meta.append(badge('Premium','','DTF Têxtil Premium: 8 passadas, branco no máximo'));
|
||||||
if(order.machine){const m=node('span',order.machine.name,'mach'+(mine?' mine':''));m.title=mine?'Sua máquina':'Máquina';meta.append(m);}
|
if(order.machine){const m=node('span',order.machine.name,'mach'+(mine?' mine':''));m.title=mine?'Sua máquina':'Máquina';meta.append(m);}
|
||||||
meta.append(node('b',metres(orderMetres(order)),'mtr'));
|
meta.append(node('b',(order.snapshot.proof_of?'prova · ':'')+metres(orderMetres(order)),'mtr'));
|
||||||
info.append(row,name,meta);
|
info.append(row,name,meta);
|
||||||
const art=artBox(s.items,'thumb');top.append(art,info);
|
const art=artBox(s.items,'thumb');top.append(art,info);
|
||||||
c.append(top);
|
c.append(top);
|
||||||
|
|||||||
@@ -103,7 +103,7 @@ function renderIssues(){
|
|||||||
if(key==='open')b.append(node('span',String(board.payment_issues_total||0),'n'));
|
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);
|
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){
|
if(!issueRows.length){
|
||||||
$('payments').replaceChildren(tools,emptyState(IC.check,issueState==='resolved'?'Nenhum pagamento resolvido':'Nenhum pagamento pendente',
|
$('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.':''));
|
issueState==='open'?'Quando um pagamento precisar de alguém, ele aparece aqui.':''));
|
||||||
@@ -343,7 +343,7 @@ function renderIntegrations(){
|
|||||||
function mailRow(m){
|
function mailRow(m){
|
||||||
const name='E-mail';
|
const name='E-mail';
|
||||||
if(m.adapter!=='smtp'&&m.adapter!=='log')return integRow({name,state:'Não configurado',tone:'off',
|
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';
|
const local=m.adapter==='log';
|
||||||
return integRow({name,state:m.error?'Verificar':local?'Só registro':'Ativo',tone:m.error?'warn':local?'off':'ok',
|
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.',
|
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.',
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ const MONTAR_GEAR='M128 80a48 48 0 1 0 48 48a48.05 48.05 0 0 0-48-48m0 80a32 32
|
|||||||
const MONTAR={sizes:[],lines:[],seq:0,preview:null,timer:null,dirty:false,token:0,
|
const MONTAR={sizes:[],lines:[],seq:0,preview:null,timer:null,dirty:false,token:0,
|
||||||
layout:null,layoutTimer:null,layoutToken:0,layoutPending:false,creating:false,requestKey:null,
|
layout:null,layoutTimer:null,layoutToken:0,layoutPending:false,creating:false,requestKey:null,
|
||||||
kind:null,internal:null,internalDirty:false,brands:new Map(),contactToken:0,contactTimer:null,
|
kind:null,internal:null,internalDirty:false,brands:new Map(),contactToken:0,contactTimer:null,
|
||||||
freights:null,freight:null,catalog:null};
|
freights:null,freight:null,catalog:null,batch:null};
|
||||||
|
|
||||||
const montarFolderReady=()=>!!FOLDER.handle&&!!FOLDER.granted;
|
const montarFolderReady=()=>!!FOLDER.handle&&!!FOLDER.granted;
|
||||||
const montarDpi=found=>found.width/(found.widthCm/2.54);
|
const montarDpi=found=>found.width/(found.widthCm/2.54);
|
||||||
@@ -154,7 +154,8 @@ function montarQuoteFigures(lines){
|
|||||||
});
|
});
|
||||||
const catalog=MONTAR.catalog?.avulsa;
|
const catalog=MONTAR.catalog?.avulsa;
|
||||||
if(!catalog)throw new Error('Preço de tabela indisponível agora.');
|
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);
|
const total=+billed.reduce((sum,metres)=>sum+metres,0).toFixed(2);
|
||||||
let unit=catalog.unit_cents,best=null;
|
let unit=catalog.unit_cents,best=null;
|
||||||
for(const band of catalog.bands||[]){
|
for(const band of catalog.bands||[]){
|
||||||
@@ -395,7 +396,7 @@ function montarPaintTotals(){
|
|||||||
$('montar-sum-pieces').textContent=String(pieces);
|
$('montar-sum-pieces').textContent=String(pieces);
|
||||||
$('montar-sum-film').textContent=count?(done?metres(film):metres(film)+' …'):'—';
|
$('montar-sum-film').textContent=count?(done?metres(film):metres(film)+' …'):'—';
|
||||||
$('montar-film-length').textContent=count?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…':'');
|
(count&&!done?' Calculando a montagem…':'');
|
||||||
$('montar-clear').disabled=!count;
|
$('montar-clear').disabled=!count;
|
||||||
$('montar-warning').hidden=!(count>20||MONTAR.lines.some(line=>line.qty>200));
|
$('montar-warning').hidden=!(count>20||MONTAR.lines.some(line=>line.qty>200));
|
||||||
@@ -432,7 +433,7 @@ async function montarLayout(token){
|
|||||||
say('A estampa não pôde ser lida.',true);return;
|
say('A estampa não pôde ser lida.',true);return;
|
||||||
}
|
}
|
||||||
const cargas=lines.flatMap((line,sourceIndex)=>Array.from({length:line.qty},(_,copyIndex)=>({
|
const cargas=lines.flatMap((line,sourceIndex)=>Array.from({length:line.qty},(_,copyIndex)=>({
|
||||||
a:{sourceIndex,giro:0,esp:false},img:line.img,copyIndex,w:line.widthCm,h:line.heightCm,travado:false})));
|
a:{sourceIndex,giro:0,esp:false},img:line.ref?null:line.img,foto:line.img,copyIndex,w:line.widthCm,h:line.heightCm,travado:false})));
|
||||||
let enc;
|
let enc;
|
||||||
try{enc=encaixar(cargas,MONTAR_FILM_CM);}
|
try{enc=encaixar(cargas,MONTAR_FILM_CM);}
|
||||||
catch(e){
|
catch(e){
|
||||||
@@ -473,7 +474,9 @@ function montarDrawPreview(layout){
|
|||||||
ctx.rotate(giro*Math.PI/180);
|
ctx.rotate(giro*Math.PI/180);
|
||||||
if(c.a&&c.a.esp)ctx.scale(-1,1);
|
if(c.a&&c.a.esp)ctx.scale(-1,1);
|
||||||
const dw=((giro%180===90)?p.h:p.w)*px, dh=((giro%180===90)?p.w:p.h)*px;
|
const dw=((giro%180===90)?p.h:p.w)*px, dh=((giro%180===90)?p.w:p.h)*px;
|
||||||
if(c.img)ctx.drawImage(c.img,-dw/2,-dh/2,dw,dh);
|
// A stamp with a reference packs as a box (img null); it draws its picture.
|
||||||
|
const picture=c.img||c.foto;
|
||||||
|
if(picture)ctx.drawImage(picture,-dw/2,-dh/2,dw,dh);
|
||||||
else{ctx.fillStyle='#E7E7E3';ctx.fillRect(-dw/2,-dh/2,dw,dh);}
|
else{ctx.fillStyle='#E7E7E3';ctx.fillRect(-dw/2,-dh/2,dw,dh);}
|
||||||
ctx.restore();
|
ctx.restore();
|
||||||
}
|
}
|
||||||
@@ -522,7 +525,7 @@ function montarItem(sources){
|
|||||||
const cargas=[];
|
const cargas=[];
|
||||||
sources.forEach((source,sourceIndex)=>{
|
sources.forEach((source,sourceIndex)=>{
|
||||||
for(let copyIndex=0;copyIndex<source.copies;copyIndex++)
|
for(let copyIndex=0;copyIndex<source.copies;copyIndex++)
|
||||||
cargas.push({a:{sourceIndex,giro:0,esp:false},img:source.line.img,copyIndex,
|
cargas.push({a:{sourceIndex,giro:0,esp:false},img:source.line.ref?null:source.line.img,copyIndex,
|
||||||
w:source.line.widthCm,h:source.line.heightCm,travado:false});
|
w:source.line.widthCm,h:source.line.heightCm,travado:false});
|
||||||
});
|
});
|
||||||
const enc=encaixar(cargas,MONTAR_FILM_CM);
|
const enc=encaixar(cargas,MONTAR_FILM_CM);
|
||||||
@@ -562,6 +565,7 @@ function montarItems(lines,uploads){
|
|||||||
async function montarCreate(){
|
async function montarCreate(){
|
||||||
if(MONTAR.creating)return;
|
if(MONTAR.creating)return;
|
||||||
const kind=MONTAR.kind||'venda';
|
const kind=MONTAR.kind||'venda';
|
||||||
|
if(MONTAR.batch&&kind!=='interno')return say('A lista colada vira sempre pedido Interno.');
|
||||||
let customer=null,name='';
|
let customer=null,name='';
|
||||||
if(kind==='interno'){
|
if(kind==='interno'){
|
||||||
if(!montarInternalReady())return say('Peça à Gestão para completar o cliente interno.');
|
if(!montarInternalReady())return say('Peça à Gestão para completar o cliente interno.');
|
||||||
@@ -595,12 +599,13 @@ async function montarCreate(){
|
|||||||
const line=lines[index];
|
const line=lines[index];
|
||||||
say('Enviando estampas '+(index+1)+' de '+lines.length+'…');
|
say('Enviando estampas '+(index+1)+' de '+lines.length+'…');
|
||||||
const id=await dtfUpload(line.file,{api,startPath:'/montador/uploads',
|
const id=await dtfUpload(line.file,{api,startPath:'/montador/uploads',
|
||||||
scope:'montador:'+line.code+'-'+line.letter,progress:say});
|
scope:'montador:'+line.code+'-'+line.letter+(line.ref?'-'+line.ref:''),progress:say});
|
||||||
uploads.set(line.id,id);
|
uploads.set(line.id,id);
|
||||||
}
|
}
|
||||||
say('Criando o pedido…');
|
say('Criando o pedido…');
|
||||||
if(!MONTAR.requestKey)MONTAR.requestKey=crypto.randomUUID();
|
if(!MONTAR.requestKey)MONTAR.requestKey=crypto.randomUUID();
|
||||||
const body={request_key:MONTAR.requestKey,kind,items:montarItems(lines,uploads)};
|
const body={request_key:MONTAR.requestKey,kind,items:montarItems(lines,uploads)};
|
||||||
|
if(MONTAR.batch)body.batch=MONTAR.batch;
|
||||||
if(kind==='venda'){
|
if(kind==='venda'){
|
||||||
body.customer=customer;
|
body.customer=customer;
|
||||||
if(withOrder)body.with_order=withOrder;
|
if(withOrder)body.with_order=withOrder;
|
||||||
@@ -629,6 +634,7 @@ function montarLine(line){
|
|||||||
const img=node('img',undefined,'montar-thumb');img.src=line.url;img.alt='';
|
const img=node('img',undefined,'montar-thumb');img.src=line.url;img.alt='';
|
||||||
const words=node('div',undefined,'montar-linemeta');
|
const words=node('div',undefined,'montar-linemeta');
|
||||||
words.append(node('b',line.code),node('span','tamanho '+line.letter+' · '+cm(line.widthCm)+' cm','sub'));
|
words.append(node('b',line.code),node('span','tamanho '+line.letter+' · '+cm(line.widthCm)+' cm','sub'));
|
||||||
|
if(line.ref)words.append(node('span','ref '+line.ref,'sub'));
|
||||||
if(line.dpi<MONTAR_DPI_WARN)words.append(badge(Math.floor(line.dpi)+' DPI','warn','Abaixo de '+MONTAR_DPI_WARN+' DPI.'));
|
if(line.dpi<MONTAR_DPI_WARN)words.append(badge(Math.floor(line.dpi)+' DPI','warn','Abaixo de '+MONTAR_DPI_WARN+' DPI.'));
|
||||||
const step=node('div',undefined,'montar-step');
|
const step=node('div',undefined,'montar-step');
|
||||||
const minus=node('button','−','montar-stepbtn');minus.type='button';minus.setAttribute('aria-label','Menos uma');
|
const minus=node('button','−','montar-stepbtn');minus.type='button';minus.setAttribute('aria-label','Menos uma');
|
||||||
@@ -661,11 +667,13 @@ function montarPaintLines(){
|
|||||||
function montarRemoveLine(line){
|
function montarRemoveLine(line){
|
||||||
URL.revokeObjectURL(line.url);
|
URL.revokeObjectURL(line.url);
|
||||||
MONTAR.lines=MONTAR.lines.filter(other=>other!==line);
|
MONTAR.lines=MONTAR.lines.filter(other=>other!==line);
|
||||||
|
if(!MONTAR.lines.length)MONTAR.batch=null;
|
||||||
montarChanged();
|
montarChanged();
|
||||||
}
|
}
|
||||||
function montarClear(){
|
function montarClear(){
|
||||||
for(const line of MONTAR.lines)URL.revokeObjectURL(line.url);
|
for(const line of MONTAR.lines)URL.revokeObjectURL(line.url);
|
||||||
MONTAR.lines=[];
|
MONTAR.lines=[];
|
||||||
|
MONTAR.batch=null;
|
||||||
montarChanged();
|
montarChanged();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -686,7 +694,9 @@ async function montarAdd(){
|
|||||||
if(found.widthCm>56)return say('A estampa tem '+cm(found.widthCm)+' cm de largura: o máximo é 56 cm.');
|
if(found.widthCm>56)return say('A estampa tem '+cm(found.widthCm)+' cm de largura: o máximo é 56 cm.');
|
||||||
const dpi=montarDpi(found);
|
const dpi=montarDpi(found);
|
||||||
if(dpi<MONTAR_DPI_REFUSE)return say('A estampa tem só '+Math.floor(dpi)+' DPI em '+size.letter+': pequena demais.');
|
if(dpi<MONTAR_DPI_REFUSE)return say('A estampa tem só '+Math.floor(dpi)+' DPI em '+size.letter+': pequena demais.');
|
||||||
const existing=MONTAR.lines.find(line=>line.code===code&&line.letter===size.letter);
|
// A line from a pasted list carries its reference printed under the stamp:
|
||||||
|
// a stamp added by hand never joins it.
|
||||||
|
const existing=MONTAR.lines.find(line=>line.code===code&&line.letter===size.letter&&!line.ref);
|
||||||
if(existing){existing.qty=Math.min(9999,existing.qty+qty);montarChanged();return;}
|
if(existing){existing.qty=Math.min(9999,existing.qty+qty);montarChanged();return;}
|
||||||
const url=URL.createObjectURL(found.file),picture=montarStampImage(url);
|
const url=URL.createObjectURL(found.file),picture=montarStampImage(url);
|
||||||
MONTAR.lines.push({id:++MONTAR.seq,code,letter:size.letter,widthCm:found.widthCm,qty,
|
MONTAR.lines.push({id:++MONTAR.seq,code,letter:size.letter,widthCm:found.widthCm,qty,
|
||||||
@@ -694,6 +704,158 @@ async function montarAdd(){
|
|||||||
montarChanged();
|
montarChanged();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function montarListSize(letter){
|
||||||
|
const wanted=String(letter||'').toUpperCase();
|
||||||
|
return MONTAR.sizes.find(size=>size.letter===wanted)||null;
|
||||||
|
}
|
||||||
|
function montarParseList(text){
|
||||||
|
const rows=[];
|
||||||
|
const lines=String(text||'').split(/\r?\n/);
|
||||||
|
for(let index=0;index<lines.length;index++){
|
||||||
|
const line=lines[index].trim();
|
||||||
|
if(!line||line.startsWith('#'))continue;
|
||||||
|
const parts=line.split(/\s+/);
|
||||||
|
const row={line:index+1,text:line,code:'',letter:'',qty:0,ref:'',error:''};
|
||||||
|
if(parts.length>4){row.error='mais de 4 campos';rows.push(row);continue;}
|
||||||
|
if(parts.length<3){row.error='faltam campos';rows.push(row);continue;}
|
||||||
|
row.code=parts[0];row.letter=parts[1];row.ref=parts[3]||'';
|
||||||
|
if(!MONTAR_CODE.test(row.code)){row.error='código inválido';rows.push(row);continue;}
|
||||||
|
const size=montarListSize(row.letter);
|
||||||
|
if(!size){row.error='tamanho não existe na tabela';rows.push(row);continue;}
|
||||||
|
row.letter=size.letter;
|
||||||
|
const quantity=Number(parts[2]);
|
||||||
|
if(!Number.isInteger(quantity)||quantity<1||quantity>9999){
|
||||||
|
row.error='quantidade de 1 a 9999';rows.push(row);continue;
|
||||||
|
}
|
||||||
|
row.qty=quantity;
|
||||||
|
if(row.ref.length>30){row.error='referência com mais de 30 caracteres';rows.push(row);continue;}
|
||||||
|
rows.push(row);
|
||||||
|
}
|
||||||
|
return rows;
|
||||||
|
}
|
||||||
|
async function montarListCheck(rows){
|
||||||
|
const cache=new Map();
|
||||||
|
for(const row of rows){
|
||||||
|
if(row.error)continue;
|
||||||
|
const size=montarListSize(row.letter);
|
||||||
|
if(!size){row.error='tamanho não existe na tabela';continue;}
|
||||||
|
const key=row.code+'\u0000'+size.letter;
|
||||||
|
let found;
|
||||||
|
if(cache.has(key))found=cache.get(key);
|
||||||
|
else{
|
||||||
|
try{found=await montarRead(row.code,size);}
|
||||||
|
catch(e){if(!montarFolderError(e))say(e.message,true);return null;}
|
||||||
|
cache.set(key,found);
|
||||||
|
}
|
||||||
|
if(!found){row.error='código não existe em Estampas/';continue;}
|
||||||
|
if(found.widthCm>56){row.error='estampa com mais de 56 cm';continue;}
|
||||||
|
if(montarDpi(found)<MONTAR_DPI_REFUSE){row.error='estampa abaixo de '+MONTAR_DPI_REFUSE+' DPI';continue;}
|
||||||
|
row.found=found;row.size=size;
|
||||||
|
}
|
||||||
|
return rows;
|
||||||
|
}
|
||||||
|
function montarListFile(row){
|
||||||
|
return row.code+'.'+row.letter+'-'+row.ref.replace(/[^A-Za-z0-9._-]/g,'_')+'.png';
|
||||||
|
}
|
||||||
|
function montarComposeRef(found,row){
|
||||||
|
return new Promise((ok,fail)=>{
|
||||||
|
const source=montarStampImage(found.url);
|
||||||
|
source.loading.then(image=>{
|
||||||
|
if(!image)return fail(new Error('A estampa não pôde ser lida.'));
|
||||||
|
const pxCm=found.width/found.widthCm;
|
||||||
|
const gap=Math.round(0.1*pxCm),cap=Math.round(0.3*pxCm),bottom=Math.round(0.5*pxCm);
|
||||||
|
const font=0.3*pxCm/0.72;
|
||||||
|
const canvas=document.createElement('canvas'),ctx=canvas.getContext('2d');
|
||||||
|
ctx.font='bold '+font+'px Arial, sans-serif';
|
||||||
|
const textWidth=Math.ceil(ctx.measureText(row.ref).width);
|
||||||
|
canvas.width=Math.max(1,Math.max(found.width,textWidth));
|
||||||
|
canvas.height=Math.max(1,found.height+gap+cap+bottom);
|
||||||
|
ctx.font='bold '+font+'px Arial, sans-serif';
|
||||||
|
ctx.textBaseline='alphabetic';ctx.fillStyle='#000';
|
||||||
|
ctx.drawImage(image,0,0,found.width,found.height);
|
||||||
|
ctx.fillText(row.ref,0,found.height+gap+cap);
|
||||||
|
canvas.toBlob(blob=>{
|
||||||
|
if(!blob)return fail(new Error('A referência não pôde ser gerada.'));
|
||||||
|
const file=new File([blob],montarListFile(row),{type:'image/png'});
|
||||||
|
const url=URL.createObjectURL(file),picture=montarStampImage(url);
|
||||||
|
ok({file,url,img:picture.img,loading:picture.loading,
|
||||||
|
widthCm:canvas.width/pxCm,heightCm:canvas.height/pxCm});
|
||||||
|
},'image/png');
|
||||||
|
},fail);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
async function montarListBuild(valid,skipped){
|
||||||
|
montarSetKind('interno');
|
||||||
|
const used=new Set();
|
||||||
|
try{
|
||||||
|
for(const row of valid){
|
||||||
|
const found=row.found;
|
||||||
|
used.add(found);
|
||||||
|
const existing=MONTAR.lines.find(line=>line.code===row.code&&line.letter===row.letter&&
|
||||||
|
(line.ref||'')===row.ref);
|
||||||
|
if(existing){existing.qty=Math.min(9999,existing.qty+row.qty);continue;}
|
||||||
|
if(row.ref){
|
||||||
|
const composed=await montarComposeRef(found,row);
|
||||||
|
MONTAR.lines.push({id:++MONTAR.seq,code:row.code,letter:row.letter,widthCm:composed.widthCm,
|
||||||
|
qty:row.qty,heightCm:composed.heightCm,dpi:montarDpi(found),url:composed.url,
|
||||||
|
img:composed.img,loading:composed.loading,file:composed.file,ref:row.ref});
|
||||||
|
}else{
|
||||||
|
const url=URL.createObjectURL(found.file),picture=montarStampImage(url);
|
||||||
|
MONTAR.lines.push({id:++MONTAR.seq,code:row.code,letter:row.letter,widthCm:found.widthCm,
|
||||||
|
qty:row.qty,heightCm:montarHeight(found),dpi:montarDpi(found),url,
|
||||||
|
img:picture.img,loading:picture.loading,file:found.file,ref:''});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}finally{
|
||||||
|
for(const found of used)URL.revokeObjectURL(found.url);
|
||||||
|
}
|
||||||
|
MONTAR.batch={lines:valid.length,skipped};
|
||||||
|
montarChanged();
|
||||||
|
}
|
||||||
|
function montarListErrors(valid,skipped){
|
||||||
|
const box=node('div',undefined,'montar-list-errors');
|
||||||
|
box.append(...skipped.map(row=>node('p','Linha '+row.line+': '+row.text+' · '+row.reason)));
|
||||||
|
const all=!valid.length;
|
||||||
|
const label=all?'Fechar':(skipped.length===1?'Montar sem essa linha':'Montar sem essas '+skipped.length+' linhas');
|
||||||
|
const dialog=formDialog('Linhas com erro',{
|
||||||
|
text:all?'Nenhuma linha será montada.':'As linhas abaixo serão puladas.',
|
||||||
|
fields:[box],label,
|
||||||
|
onsave:async()=>{
|
||||||
|
if(all)return;
|
||||||
|
await montarListBuild(valid,skipped);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if(all){
|
||||||
|
const cancel=dialog.box.querySelector('.dfoot .btn.ghost.right');
|
||||||
|
if(cancel)cancel.remove();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function montarOpenPaste(){
|
||||||
|
if(!montarKindNames().includes('interno'))
|
||||||
|
return say('Seu perfil não monta lista colada: ela vira pedido Interno.',true);
|
||||||
|
// The list is always Interno: without the internal customer it could not be ordered.
|
||||||
|
if(!montarInternalReady())return say('Peça à Gestão para completar o cliente interno.',true);
|
||||||
|
if(!montarFolderReady())return;
|
||||||
|
const text=node('textarea',undefined,'montar-list-text');
|
||||||
|
text.id='montar-list-text';text.rows=12;text.spellcheck=false;text.placeholder='NX.226 C 2 ML-4471';
|
||||||
|
formDialog('Colar lista',{
|
||||||
|
text:'Uma linha por item: código tamanho quantidade referência. Ex.: NX.226 C 2 ML-4471',
|
||||||
|
fields:[field('Lista',text)],label:'Conferir lista',width:640,
|
||||||
|
onsave:async()=>{
|
||||||
|
const rows=montarParseList(text.value);
|
||||||
|
if(rows.length>500){say('A lista tem mais de 500 linhas.',true);return false;}
|
||||||
|
if(!rows.length){say('A lista está vazia.',true);return false;}
|
||||||
|
const checked=await montarListCheck(rows);
|
||||||
|
if(!checked)return false;
|
||||||
|
const valid=checked.filter(row=>!row.error);
|
||||||
|
const skipped=checked.filter(row=>row.error)
|
||||||
|
.map(row=>({line:row.line,text:row.text,reason:row.error}));
|
||||||
|
if(skipped.length){montarListErrors(valid,skipped);return;}
|
||||||
|
await montarListBuild(valid,skipped);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
function montarPaintSelect(){
|
function montarPaintSelect(){
|
||||||
const select=$('montar-size'),current=select.value;
|
const select=$('montar-size'),current=select.value;
|
||||||
select.replaceChildren(...MONTAR.sizes.map(size=>{
|
select.replaceChildren(...MONTAR.sizes.map(size=>{
|
||||||
@@ -854,6 +1016,7 @@ $('montar-add').onclick=async()=>{
|
|||||||
$('montar-add').disabled=true;
|
$('montar-add').disabled=true;
|
||||||
try{await montarAdd();}catch(e){say(e.message,true);}finally{$('montar-add').disabled=false;}
|
try{await montarAdd();}catch(e){say(e.message,true);}finally{$('montar-add').disabled=false;}
|
||||||
};
|
};
|
||||||
|
$('montar-paste').onclick=()=>montarOpenPaste();
|
||||||
$('montar-clear').onclick=()=>montarClear();
|
$('montar-clear').onclick=()=>montarClear();
|
||||||
$('montar-build').onclick=()=>montarCreate();
|
$('montar-build').onclick=()=>montarCreate();
|
||||||
for(const id of MONTAR_CUSTOMER)$(id).addEventListener('input',()=>{MONTAR.requestKey=null;montarPaintCustomer();montarPaintActions();});
|
for(const id of MONTAR_CUSTOMER)$(id).addEventListener('input',()=>{MONTAR.requestKey=null;montarPaintCustomer();montarPaintActions();});
|
||||||
@@ -948,7 +1111,7 @@ function montarOpenAdjustments(){
|
|||||||
if(!may('manage')||$('montar-sizes'))return;
|
if(!may('manage')||$('montar-sizes'))return;
|
||||||
MONTAR.dirty=false;MONTAR.internalDirty=false;
|
MONTAR.dirty=false;MONTAR.internalDirty=false;
|
||||||
formDialog('Ajustes do Montar',{
|
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',
|
fields:montarAdjustmentFields(),label:'Salvar ajustes',width:720,className:'montar-ajustes-dlg',
|
||||||
onsave:async()=>montarSaveAdjustments()
|
onsave:async()=>montarSaveAdjustments()
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -30,7 +30,11 @@ function statsPeriod(){
|
|||||||
const open=node('button',undefined,'btn'+(statsRange?' on':''));open.type='button';open.setAttribute('aria-haspopup','dialog');
|
const open=node('button',undefined,'btn'+(statsRange?' on':''));open.type='button';open.setAttribute('aria-haspopup','dialog');
|
||||||
open.append(svgIcon(IC.calendar,'i m'),statsRange?shortDay(statsRange.start)+' a '+shortDay(statsRange.end):'Escolher datas');
|
open.append(svgIcon(IC.calendar,'i m'),statsRange?shortDay(statsRange.start)+' a '+shortDay(statsRange.end):'Escolher datas');
|
||||||
open.onclick=e=>{e.stopPropagation();const pop=wrap.querySelector('.pop');if(pop){pop.remove();return;}wrap.append(calendar());};
|
open.onclick=e=>{e.stopPropagation();const pop=wrap.querySelector('.pop');if(pop){pop.remove();return;}wrap.append(calendar());};
|
||||||
wrap.replaceChildren(open);
|
// The numbers reload when the tab opens, on 7/30/90 and every 30 s: a
|
||||||
|
// calendar open meanwhile stays (on a phone the reply came after the tap
|
||||||
|
// and closed it, so "Escolher datas" seemed to do nothing).
|
||||||
|
const pop=wrap.querySelector('.pop');
|
||||||
|
wrap.replaceChildren(open,...(pop?[pop]:[]));
|
||||||
}
|
}
|
||||||
// The calendar: presets on the left, a month where a click starts the
|
// The calendar: presets on the left, a month where a click starts the
|
||||||
// period and the next one ends it. `single`, `future` and `time` add the
|
// period and the next one ends it. `single`, `future` and `time` add the
|
||||||
|
|||||||
@@ -53,7 +53,8 @@ function renderPanel(order){
|
|||||||
// A proof card is no sale (app/proof.py): it says whose proof it is.
|
// A proof card is no sale (app/proof.py): it says whose proof it is.
|
||||||
if(order.proof_parent)paid.append(node('b','Prova do pedido #'+order.proof_parent.number),', sem custo, criada em '+when(order.created_at));
|
if(order.proof_parent)paid.append(node('b','Prova do pedido #'+order.proof_parent.number),', sem custo, criada em '+when(order.created_at));
|
||||||
else paid.append(node('b',money(s.total_cents)),isTest(order)?' sem pagamento, '+when(order.created_at):
|
else paid.append(node('b',money(s.total_cents)),isTest(order)?' sem pagamento, '+when(order.created_at):
|
||||||
paidOutside(order)?' pago fora do site ('+(PAID_OUTSIDE[order.payment.method]||order.payment.method)+'), registrado em '+when(order.created_at):' pago em '+when(order.created_at));
|
paidOutside(order)?' pago fora do site ('+(PAID_OUTSIDE[order.payment.method]||order.payment.method)+'), registrado em '+when(order.created_at):
|
||||||
|
' pago'+(PAID_WITH[order.paid_with]?' com '+PAID_WITH[order.paid_with]:'')+' em '+when(order.created_at));
|
||||||
const code=node('span',undefined,'chip');
|
const code=node('span',undefined,'chip');
|
||||||
code.append(node('span','DTF-'+order.number,'code'),copyButton(fileCode(order),'Copiar “'+fileCode(order)+'”, o começo do nome dos arquivos deste pedido'));
|
code.append(node('span','DTF-'+order.number,'code'),copyButton(fileCode(order),'Copiar “'+fileCode(order)+'”, o começo do nome dos arquivos deste pedido'));
|
||||||
const theirs=node('span','Código do cliente ','tip-l');theirs.append(node('span',orderCode(order.id),'code strong'));theirs.dataset.tip='O código que aparece para o cliente';
|
const theirs=node('span','Código do cliente ','tip-l');theirs.append(node('span',orderCode(order.id),'code strong'));theirs.dataset.tip='O código que aparece para o cliente';
|
||||||
@@ -266,7 +267,7 @@ function nextBox(order){
|
|||||||
title='Aguardando prova do #'+order.proof_card.number;
|
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');
|
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.'
|
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(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));
|
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);
|
return composeNext(title,body,main,more);
|
||||||
@@ -304,9 +305,8 @@ function nextBox(order){
|
|||||||
if((st==='rec'||st==='tra'||st==='imp')&&!order.proof_parent&&!fixed&&may('produce')&&
|
if((st==='rec'||st==='tra'||st==='imp')&&!order.proof_parent&&!fixed&&may('produce')&&
|
||||||
(order.print_files||[]).some(r=>r.status==='ready'))
|
(order.print_files||[]).some(r=>r.status==='ready'))
|
||||||
more.push(button('Gerar de novo',async()=>{
|
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. '+
|
if(!await ask('Gerar o arquivo de novo?','O arquivo sai com o tamanho de parte atual. O pedido volta para Arte recebida'+
|
||||||
'O arquivo final aprovado sai: o pedido volta para Arte recebida'+(st==='imp'?', sai da hot folder da máquina,':'')+
|
(st==='imp'?' e sai da hot folder':'')+', e o arquivo novo precisa ser aprovado.',
|
||||||
' e o arquivo novo precisa ser aprovado.',
|
|
||||||
'Gerar de novo',{host:$('drawer')}))return;
|
'Gerar de novo',{host:$('drawer')}))return;
|
||||||
await api('/orders/'+order.id+'/print-files/again',{});await load();
|
await api('/orders/'+order.id+'/print-files/again',{});await load();
|
||||||
say('Gerando o arquivo do #'+order.number+' de novo. Aprove quando ficar pronto.');
|
say('Gerando o arquivo do #'+order.number+' de novo. Aprove quando ficar pronto.');
|
||||||
@@ -330,7 +330,7 @@ function nextBox(order){
|
|||||||
const manual=(order.print_files||[]).some(r=>r.status==='manual');
|
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
|
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 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(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(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'))
|
if((order.print_files||[]).some(r=>r.status==='failed'||r.status==='manual'||r.timed_out)&&may('produce'))
|
||||||
@@ -339,6 +339,46 @@ function nextBox(order){
|
|||||||
}
|
}
|
||||||
if(st==='rec'||st==='cor'){
|
if(st==='rec'||st==='cor'){
|
||||||
if(st==='rec'&&designerPaid(order)&&!treatmentDone(order)&&finalDone(order)){
|
if(st==='rec'&&designerPaid(order)&&!treatmentDone(order)&&finalDone(order)){
|
||||||
|
if(order.snapshot.redesign){
|
||||||
|
const previews=previewsOf(order), open=openPreview(order);
|
||||||
|
if(open){
|
||||||
|
const n=open.number;
|
||||||
|
title='Prévia '+n+' com o cliente';
|
||||||
|
note('Enviada por '+open.sent_by+' em '+when(open.sent_at)+'. O tempo da etapa está parado.');
|
||||||
|
if(may('produce')){
|
||||||
|
main.push(button('Prévia aprovada',async()=>{
|
||||||
|
if(!await ask('Prévia aprovada?','O cliente aprovou a prévia '+n+'. Em seguida, envie a arte final.','Prévia aprovada'))return;
|
||||||
|
await api('/orders/'+order.id+'/redesign-preview',{action:'approved'});
|
||||||
|
await load();
|
||||||
|
},'btn pri lg'));
|
||||||
|
more.push(button('Prévia reprovada',()=>{
|
||||||
|
const reason=node('input');reason.maxLength=500;reason.setAttribute('aria-label','Motivo da reprovação');
|
||||||
|
formDialog('Prévia '+n+' reprovada',{host:$('drawer'),className:'reason',width:540,
|
||||||
|
fields:[field('Motivo',reason,'Fica no histórico do pedido.')],label:'Prévia reprovada',tone:'red',
|
||||||
|
onsave:async()=>{await api('/orders/'+order.id+'/redesign-preview',{action:'rejected',reason:reason.value.trim()});await load();}});
|
||||||
|
},'btn lg'));
|
||||||
|
}
|
||||||
|
return composeNext(title,body,main,more);
|
||||||
|
}
|
||||||
|
if(previewApproved(order)){
|
||||||
|
const p=previews.filter(x=>x.result==='approved').slice(-1)[0];
|
||||||
|
title='Enviar a arte do Ajuste Fino Redesenho';
|
||||||
|
note('Prévia '+p.number+' aprovada. O Ajuste Fino Redesenho foi pago.'+
|
||||||
|
' Envie o PNG ajustado de cada item antes de colocar o pedido na fila.');
|
||||||
|
if(may('produce'))main.push(button('Tratar a arte',()=>treatDialog(order),'btn pri lg'));
|
||||||
|
return composeNext(title,body,main,more);
|
||||||
|
}
|
||||||
|
const last=previews[previews.length-1];
|
||||||
|
title='Enviar a prévia do Redesenho';
|
||||||
|
note((last&&last.result==='rejected'?'Prévia '+last.number+' reprovada'+(last.reason?': '+last.reason:'')+'. ':'')+
|
||||||
|
'Mande a prévia ao cliente e marque aqui. O tempo da etapa para até a resposta.');
|
||||||
|
if(may('produce'))main.push(button('Prévia enviada',async()=>{
|
||||||
|
await api('/orders/'+order.id+'/redesign-preview',{action:'sent'});
|
||||||
|
await load();
|
||||||
|
},'btn pri lg'));
|
||||||
|
if(may('produce'))more.push(button('Tratar a arte',()=>treatDialog(order),'btn lg'));
|
||||||
|
return composeNext(title,body,main,more);
|
||||||
|
}
|
||||||
title='Enviar a arte do '+(order.snapshot.redesign?'Ajuste Fino Redesenho':'Ajuste Fino');
|
title='Enviar a arte do '+(order.snapshot.redesign?'Ajuste Fino Redesenho':'Ajuste Fino');
|
||||||
note((order.snapshot.redesign?'O Ajuste Fino Redesenho foi pago.':'O Ajuste Fino foi pago.')+
|
note((order.snapshot.redesign?'O Ajuste Fino Redesenho foi pago.':'O Ajuste Fino foi pago.')+
|
||||||
' Envie o PNG ajustado de cada item antes de colocar o pedido na fila.');
|
' Envie o PNG ajustado de cada item antes de colocar o pedido na fila.');
|
||||||
@@ -384,6 +424,36 @@ function nextBox(order){
|
|||||||
if(can('rev'))main.push(moveBtn('rev'));else cannot();
|
if(can('rev'))main.push(moveBtn('rev'));else cannot();
|
||||||
const p=proofBtn();if(p)more.push(p);
|
const p=proofBtn();if(p)more.push(p);
|
||||||
fixBtn();
|
fixBtn();
|
||||||
|
if(may('manage'))more.push(button('Transferir máquina',()=>{
|
||||||
|
const family=order.snapshot.items.some(i=>i.mode==='uvfile'||i.mode==='uv')?'uv':'textil';
|
||||||
|
const choices=(board.machines||[]).filter(m=>m.active&&m.id!==order.machine?.id&&
|
||||||
|
(!m.products?.length||m.products.includes(family)));
|
||||||
|
if(!choices.length){say('Nenhuma outra máquina ativa imprime este produto.',true);return;}
|
||||||
|
const select=node('select');select.required=true;select.setAttribute('aria-label','Máquina que recebe o pedido');
|
||||||
|
for(const m of choices){const o=node('option',m.name);o.value=m.id;select.append(o);}
|
||||||
|
const reason=node('input');reason.maxLength=500;reason.required=true;reason.setAttribute('aria-label','Motivo da transferência');
|
||||||
|
// The hot folder takes a PNG in about 10 s (Marcus, 2026-12-01): a part
|
||||||
|
// the machine took may still wait in its Hoson queue, so whoever moves
|
||||||
|
// the card says where the new machine resumes, after looking at the Hoson.
|
||||||
|
const parts=order.hot_parts||[], taken=parts.some(p=>p.state==='consumed');
|
||||||
|
const resume=node('select');resume.setAttribute('aria-label','Parte de onde a nova máquina recomeça');
|
||||||
|
if(taken){const pick=node('option','Escolha a parte');pick.value='';resume.append(pick);resume.required=true;}
|
||||||
|
for(const p of parts){const o=node('option','Parte '+p.seq+' · '+(p.state==='consumed'?'já pega pela máquina':'ainda na pasta'));
|
||||||
|
o.value=String(p.seq);resume.append(o);}
|
||||||
|
const fields=[field('Máquina',select)];
|
||||||
|
if(parts.length>1||taken)fields.push(field('Recomeçar da parte',resume,'Confira no Hoson qual parte a máquina atual já imprimiu.'));
|
||||||
|
fields.push(field('Motivo',reason,'Fica no card para o Revisor conferir a emenda de tom.'));
|
||||||
|
formDialog('Transferir o pedido #'+order.number,{host:$('drawer'),className:'reason',width:540,
|
||||||
|
text:'O que a máquina atual ainda não pegou sai da pasta dela.',
|
||||||
|
fields,label:'Transferir',tone:'red',
|
||||||
|
onsave:async()=>{
|
||||||
|
const body={machine_id:select.value,reason:reason.value.trim()};
|
||||||
|
if(parts.length&&resume.value)body.resume_from=Number(resume.value);
|
||||||
|
const done=await api('/orders/'+order.id+'/transfer',body);
|
||||||
|
const prt=done.delete_prt||[];
|
||||||
|
say('Pedido #'+order.number+' transferido.'+(prt.length?' Apague da pasta do Hoson da máquina antiga: '+prt.join(', ')+'.':''),false,prt.length?20000:undefined);
|
||||||
|
await load();}});
|
||||||
|
},'btn quiet lg'));
|
||||||
}else if(st==='rev'){
|
}else if(st==='rev'){
|
||||||
if(proofPending(order)){
|
if(proofPending(order)){
|
||||||
// Finalizado waits for the proof: printing it and checking it is the next step.
|
// Finalizado waits for the proof: printing it and checking it is the next step.
|
||||||
@@ -440,7 +510,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;
|
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');
|
text.setAttribute('aria-label','Motivo da correção');
|
||||||
formDialog('Pedir correção do pedido #'+order.number,{host:$('drawer'),className:'reason',width:540,
|
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',
|
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());}});
|
onsave:async()=>{await move(order,'cor',text.value.trim());}});
|
||||||
}
|
}
|
||||||
@@ -463,7 +533,7 @@ function cancelDialog(order){
|
|||||||
const why=node('textarea');why.placeholder='Ex.: cliente desistiu, vai refazer a arte';why.setAttribute('aria-label','Motivo do cancelamento');
|
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;
|
why.required=true;why.minLength=3;why.maxLength=1000;
|
||||||
formDialog('Cancelar o pedido #'+order.number+'?',{host:$('drawer'),className:'reason',width:520,
|
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',
|
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();}});
|
onsave:async()=>{await api('/orders/'+order.id+'/cancel',{note:why.value.trim()});say('Pedido #'+order.number+' cancelado.');await load();}});
|
||||||
}
|
}
|
||||||
@@ -553,12 +623,12 @@ async function finalsOk(order,uploads){
|
|||||||
async function approveReady(order,ready){
|
async function approveReady(order,ready){
|
||||||
if(!await finalsOk(order,ready.flatMap(r=>r.files.map(f=>f.upload_id))))return;
|
if(!await finalsOk(order,ready.flatMap(r=>r.files.map(f=>f.upload_id))))return;
|
||||||
const many=ready.length>1;
|
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;
|
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(', ');
|
const note='Aprovado como está: '+[...new Set(ready.map(r=>FINAL_SOURCE[r.source]))].join(', ');
|
||||||
if(await saveFinalFiles(order,
|
if(await saveFinalFiles(order,
|
||||||
ready.flatMap((r,i)=>r.files.map(f=>({item_index:i,upload_id:f.upload_id}))),note))return;
|
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.
|
// The file the operator prepared, per item; a ready file comes ticked.
|
||||||
function finalDialog(order,ready,{replace=false}={}){
|
function finalDialog(order,ready,{replace=false}={}){
|
||||||
@@ -857,7 +927,7 @@ function isOk(order){
|
|||||||
const treat=button('Tratar a arte',()=>{m.close();treatDialog(order);},'btn');
|
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',
|
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.'
|
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()=>{
|
onsave:async()=>{
|
||||||
if(missing)throw new Error('Falta o arquivo final de um item.');
|
if(missing)throw new Error('Falta o arquivo final de um item.');
|
||||||
for(const [index,select] of selects.entries())
|
for(const [index,select] of selects.entries())
|
||||||
@@ -894,12 +964,12 @@ function treatDialog(order){
|
|||||||
row.path.textContent=name?(base.value.trim()?'':'…\\')+where(name):'Este item ainda não tem arquivo na pasta.';
|
row.path.textContent=name?(base.value.trim()?'':'…\\')+where(name):'Este item ainda não tem arquivo na pasta.';
|
||||||
row.copy.disabled=!name;
|
row.copy.disabled=!name;
|
||||||
row.copy.onclick=async()=>{try{await navigator.clipboard.writeText(where(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);}};
|
catch(_){say('Não foi possível copiar.',true);}};
|
||||||
});
|
});
|
||||||
base.onchange=()=>{kv.set(FOLDER_PATH_KEY,base.value.trim()).catch(()=>{});paint();};
|
base.onchange=()=>{kv.set(FOLDER_PATH_KEY,base.value.trim()).catch(()=>{});paint();};
|
||||||
formDialog('Tratar a arte',{host:$('drawer'),width:620,className:'finalform',
|
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',
|
fields:[...rows.map(r=>r.input.closest('.fslot')),field('Pasta dos pedidos neste computador',base)],label:'Subir arte tratada',
|
||||||
onsave:async()=>{
|
onsave:async()=>{
|
||||||
// Each item keeps its approved final, or else the file ready to approve,
|
// Each item keeps its approved final, or else the file ready to approve,
|
||||||
@@ -924,7 +994,7 @@ function treatDialog(order){
|
|||||||
}
|
}
|
||||||
if(await saveFinalFiles(order,refs,TREAT_NOTE))return;
|
if(await saveFinalFiles(order,refs,TREAT_NOTE))return;
|
||||||
await load();
|
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.
|
// Filled once open: the names the automatic folders give the files.
|
||||||
(async()=>{
|
(async()=>{
|
||||||
@@ -1058,12 +1128,15 @@ function itemCard(order,item,index){
|
|||||||
info.append(node('h3',productName(item)));
|
info.append(node('h3',productName(item)));
|
||||||
const dl=node('dl',undefined,'dl');
|
const dl=node('dl',undefined,'dl');
|
||||||
const pair=(k,v)=>{if(v===null||v===undefined||v==='')return;const d=node('div');const dd=node('dd');dd.append(v);d.append(node('dt',k),dd);dl.append(d);};
|
const pair=(k,v)=>{if(v===null||v===undefined||v==='')return;const d=node('div');const dd=node('dd');dd.append(v);d.append(node('dt',k),dd);dl.append(d);};
|
||||||
pair('Metros cobrados',metres(item.billed_metres));
|
const proof=!!order.snapshot.proof_of, proofCm=Number(order.proof_film_cm?.[String(index)]||0);
|
||||||
|
pair('Metros cobrados',metres(item.billed_metres)+(proof?' · prova sem custo':''));
|
||||||
|
// A proof prints a stretch of the order's sheet, not the whole of it.
|
||||||
|
pair('Filme da prova',proof&&proofCm?metres(proofCm/100):null);
|
||||||
pair('Valor do metro',item.unit_cents?money(item.unit_cents)+manualExtra(item):null);
|
pair('Valor do metro',item.unit_cents?money(item.unit_cents)+manualExtra(item):null);
|
||||||
const g=node('span',undefined,'gradeline');g.append(gradePill(item.grade));pair('Nota da arte',g);
|
const g=node('span',undefined,'gradeline');g.append(gradePill(item.grade));pair('Nota da arte',g);
|
||||||
pair('Contração',contractionControl(order,index));
|
pair('Contração',contractionControl(order,index));
|
||||||
pair('Folha',sheetSize(spec));
|
pair(proof?'Folha do pedido':'Folha',sheetSize(spec));
|
||||||
pair('Peças',spec?String(spec.placements.length):null);
|
pair('Peças',spec&&!proof?String(spec.placements.length):null);
|
||||||
pair('Menor resolução',row?.status==='ready'&&row.detail?.min_dpi?row.detail.min_dpi+' DPI':null);
|
pair('Menor resolução',row?.status==='ready'&&row.detail?.min_dpi?row.detail.min_dpi+' DPI':null);
|
||||||
pair('Arquivos',spec&&spec.sources.length>1?String(spec.sources.length):null);
|
pair('Arquivos',spec&&spec.sources.length>1?String(spec.sources.length):null);
|
||||||
info.append(dl);
|
info.append(dl);
|
||||||
@@ -1074,7 +1147,7 @@ function itemCard(order,item,index){
|
|||||||
(item.residue_accepted_at?' às '+when(item.residue_accepted_at):'')+'.','warn'));
|
(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: '+
|
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.'
|
(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'));
|
(item.stroke_choice_at?' Aceito às '+when(item.stroke_choice_at)+'.':''),'warn'));
|
||||||
if(mirroredItem(item))notes.append(itemNote(MIRROR_NOTE+'.','bad'));
|
if(mirroredItem(item))notes.append(itemNote(MIRROR_NOTE+'.','bad'));
|
||||||
// After a customer correction, that file is the artwork: the generated
|
// After a customer correction, that file is the artwork: the generated
|
||||||
@@ -1262,6 +1335,16 @@ function historyView(order,rows,view){
|
|||||||
};
|
};
|
||||||
for(const r of [...rows].reverse())list.append(entry(r.back?'Voltou para '+stateName(r.to_state):stateName(r.to_state),
|
for(const r of [...rows].reverse())list.append(entry(r.back?'Voltou para '+stateName(r.to_state):stateName(r.to_state),
|
||||||
r.operator+(r.machine?', na '+r.machine:''),r.created_at,r.reason));
|
r.operator+(r.machine?', na '+r.machine:''),r.created_at,r.reason));
|
||||||
|
// Machine transfers in Imprimindo (D4), newest first.
|
||||||
|
for(const t of [...(order.transfers||[])].reverse())
|
||||||
|
list.append(entry('Transferido · '+t.from_name+' → '+t.to_name,t.created_by,t.created_at,
|
||||||
|
t.reason+(t.resumed_from>1?' · recomeçou da parte '+t.resumed_from:'')+
|
||||||
|
(t.delete_prt?.length?' · apagar do Hoson da '+t.from_name+': '+t.delete_prt.join(', '):'')));
|
||||||
|
// The Redesenho previews (D2), newest first, like the moves above.
|
||||||
|
for(const p of [...previewsOf(order)].reverse()){
|
||||||
|
if(p.decided_at)list.append(entry('Prévia '+p.number+(p.result==='approved'?' aprovada':' reprovada'),p.decided_by,p.decided_at,p.reason));
|
||||||
|
list.append(entry('Prévia '+p.number+' enviada',p.sent_by,p.sent_at,''));
|
||||||
|
}
|
||||||
for(const item of order.snapshot.items){
|
for(const item of order.snapshot.items){
|
||||||
if(item.residue_accepted_at)list.append(entry('Resíduo aceito','cliente',item.residue_accepted_at,
|
if(item.residue_accepted_at)list.append(entry('Resíduo aceito','cliente',item.residue_accepted_at,
|
||||||
item.residue_accepted+' pontos'));
|
item.residue_accepted+' pontos'));
|
||||||
|
|||||||
@@ -238,6 +238,8 @@ function callout(d,title,text,tone=''){
|
|||||||
// Faturado is not one of them: an invoiced sale goes through the montador's
|
// Faturado is not one of them: an invoiced sale goes through the montador's
|
||||||
// Venda (front 7a.3), and the API refuses it here (Sentry DTF-WEB-E).
|
// Venda (front 7a.3), and the API refuses it here (Sentry DTF-WEB-E).
|
||||||
const PAID_OUTSIDE={pix:'Pix',card:'Cartão',cash:'Dinheiro',credit:'Crédito do cliente'};
|
const PAID_OUTSIDE={pix:'Pix',card:'Cartão',cash:'Dinheiro',credit:'Crédito do cliente'};
|
||||||
|
// How a Site order was paid, on the order's paid line (the board's paid_with).
|
||||||
|
const PAID_WITH={pix:'Pix',card:'cartão'};
|
||||||
function registerDialog(quote){
|
function registerDialog(quote){
|
||||||
const group=(name,label,options)=>{
|
const group=(name,label,options)=>{
|
||||||
const g=node('div',undefined,'fgroup2');g.setAttribute('role','radiogroup');g.setAttribute('aria-label',label);
|
const g=node('div',undefined,'fgroup2');g.setAttribute('role','radiogroup');g.setAttribute('aria-label',label);
|
||||||
|
|||||||
@@ -11,8 +11,8 @@ const SITE_TABS=[
|
|||||||
{id:'grade',label:'Nota da arte',note:'A regra do Ajuste Fino precisa ser menor ou igual à do aviso.'},
|
{id:'grade',label:'Nota da arte',note:'A regra do Ajuste Fino precisa ser menor ou igual à do aviso.'},
|
||||||
{id:'videos',label:'Vídeos',note:'MP4 ou WebM até 500 MB; legenda VTT opcional. Só aparece no Site depois de publicado.'},
|
{id:'videos',label:'Vídeos',note:'MP4 ou WebM até 500 MB; legenda VTT opcional. Só aparece no Site depois de publicado.'},
|
||||||
];
|
];
|
||||||
const SITE_VIDEO_PRODUCTS=[['','Só na categoria DTF'],['file','Arquivo por metro'],
|
const SITE_VIDEO_PRODUCTS=[['','Só na página inicial'],['file','Arquivo por metro'],
|
||||||
['avulsa','Artes avulsas'],['uvfile','Arquivo por metro UV'],['uv','Artes avulsas UV']];
|
['avulsa','Artes avulsas'],['uvfile','Arquivo por metro · UV'],['uv','Artes avulsas · UV']];
|
||||||
let siteTab=(()=>{
|
let siteTab=(()=>{
|
||||||
try{const saved=localStorage.getItem(SITE_TAB_KEY);return SITE_TABS.some(t=>t.id===saved)?saved:'products';}
|
try{const saved=localStorage.getItem(SITE_TAB_KEY);return SITE_TABS.some(t=>t.id===saved)?saved:'products';}
|
||||||
catch(_){return 'products';}
|
catch(_){return 'products';}
|
||||||
@@ -548,8 +548,10 @@ function renderSiteGrade(){
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ---- Vídeos (S5, S6) ------------------------------------------------------
|
// ---- Vídeos (S5, S6) ------------------------------------------------------
|
||||||
function videoProductLabel(product){
|
function videoProductLabel(video){
|
||||||
return (SITE_VIDEO_PRODUCTS.find(([value])=>value===(product||''))||SITE_VIDEO_PRODUCTS[0])[1];
|
const products=(video.products&&video.products.length?video.products:[video.product]).filter(Boolean);
|
||||||
|
if(!products.length)return 'Só na página inicial';
|
||||||
|
return products.map(product=>(SITE_VIDEO_PRODUCTS.find(([value])=>value===product)||[product])[1]).join(', ');
|
||||||
}
|
}
|
||||||
function renderSiteVideos(){
|
function renderSiteVideos(){
|
||||||
const host=$('site-videos-list');if(!host)return;
|
const host=$('site-videos-list');if(!host)return;
|
||||||
@@ -562,7 +564,7 @@ function siteVideoRow(video){
|
|||||||
file.append(video.video_name?node('span',video.video_name,'siteFileName'):node('span','sem vídeo','muted'));
|
file.append(video.video_name?node('span',video.video_name,'siteFileName'):node('span','sem vídeo','muted'));
|
||||||
const captions=node('td');captions.dataset.label='Legenda';
|
const captions=node('td');captions.dataset.label='Legenda';
|
||||||
captions.append(video.captions_name?node('span',video.captions_name,'siteFileName'):node('span','sem legenda','muted'));
|
captions.append(video.captions_name?node('span',video.captions_name,'siteFileName'):node('span','sem legenda','muted'));
|
||||||
const where=node('td',videoProductLabel(video.product));where.dataset.label='Onde aparece';
|
const where=node('td',videoProductLabel(video));where.dataset.label='Onde aparece';
|
||||||
const situation=node('td');situation.dataset.label='Situação';
|
const situation=node('td');situation.dataset.label='Situação';
|
||||||
situation.append(node('span',video.enabled?'Publicado':'Rascunho','tag'+(video.enabled?' ok':'')));
|
situation.append(node('span',video.enabled?'Publicado':'Rascunho','tag'+(video.enabled?' ok':'')));
|
||||||
const action=node('td',undefined,'r siteAction');
|
const action=node('td',undefined,'r siteAction');
|
||||||
@@ -604,29 +606,44 @@ function videoDialog(video){
|
|||||||
videoInput.addEventListener('change',checkVideo);
|
videoInput.addEventListener('change',checkVideo);
|
||||||
captionsInput.addEventListener('change',checkCaptions);
|
captionsInput.addEventListener('change',checkCaptions);
|
||||||
// A product page shows one floating video: the products another published
|
// A product page shows one floating video: the products another published
|
||||||
// video holds are marked, and closed while this one is published (DTF-WEB-G).
|
// video holds are marked, and locked while this one is published (DTF-WEB-G).
|
||||||
const taken=new Map(siteVideos.filter(other=>other.id!==video.id&&other.enabled&&other.product)
|
const taken=new Map();
|
||||||
.map(other=>[other.product,other.title]));
|
for(const other of siteVideos){
|
||||||
const product=node('select');
|
if(other.id===video.id||!other.enabled)continue;
|
||||||
for(const [value,label] of SITE_VIDEO_PRODUCTS){
|
for(const value of (other.products&&other.products.length?other.products:[other.product])){
|
||||||
const option=node('option',taken.has(value)?label+' · já tem vídeo':label);option.value=value;product.append(option);
|
if(value&&!taken.has(value))taken.set(value,other.title);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
product.value=video.product||'';
|
const where=node('div',undefined,'fld');
|
||||||
const where=field('Onde aparece',product,'Ou flutuando na página de um produto.');
|
where.append(node('span','Onde aparece'));
|
||||||
const whereHint=where.querySelector('small');
|
const productBoxes=[];
|
||||||
|
for(const [value,label] of SITE_VIDEO_PRODUCTS){
|
||||||
|
if(!value)continue;
|
||||||
|
const input=node('input');input.value=value;
|
||||||
|
input.checked=(video.products&&video.products.length?video.products:[video.product]).includes(value);
|
||||||
|
where.append(checkbox(taken.has(value)?label+' · já tem vídeo':label,input));
|
||||||
|
productBoxes.push([value,input]);
|
||||||
|
}
|
||||||
|
const whereHint=node('small');
|
||||||
|
where.append(whereHint);
|
||||||
|
const busyProduct=()=>productBoxes.find(([value,input])=>input.checked&&taken.has(value));
|
||||||
const paintWhere=()=>{
|
const paintWhere=()=>{
|
||||||
for(const option of product.options)option.disabled=published&&taken.has(option.value);
|
for(const [value,input] of productBoxes)input.disabled=published&&taken.has(value);
|
||||||
if(!taken.has(product.value))where.classList.remove('warn');
|
const busy=busyProduct();
|
||||||
whereHint.textContent=taken.has(product.value)
|
where.classList.toggle('warn',!!busy);
|
||||||
?'Este produto já tem o vídeo "'+taken.get(product.value)+'" publicado. Tire esse do Site para publicar este aqui.'
|
whereHint.textContent=busy
|
||||||
:'Ou flutuando na página de um produto.';
|
?'Este produto já tem o vídeo "'+taken.get(busy[0])+'" publicado. Tire esse do Site para publicar este aqui.'
|
||||||
|
:productBoxes.some(([,input])=>input.checked)
|
||||||
|
?'Aparece flutuando na página de cada produto marcado.'
|
||||||
|
:'Nenhum marcado: só na página inicial.';
|
||||||
};
|
};
|
||||||
product.onchange=paintWhere;
|
for(const [,input] of productBoxes)input.onchange=paintWhere;
|
||||||
const sw=node('button',undefined,'sw'+(published?' on':''));
|
const sw=node('button',undefined,'sw'+(published?' on':''));
|
||||||
sw.type='button';sw.setAttribute('role','switch');sw.setAttribute('aria-checked',String(published));
|
sw.type='button';sw.setAttribute('role','switch');sw.setAttribute('aria-checked',String(published));
|
||||||
sw.append(node('span',undefined,'t'),'Publicar no Site');
|
sw.append(node('span',undefined,'t'),'Publicar no Site');
|
||||||
sw.onclick=()=>{
|
sw.onclick=()=>{
|
||||||
if(!published&&taken.has(product.value)){where.classList.add('warn');product.focus();return;}
|
const busy=busyProduct();
|
||||||
|
if(!published&&busy){paintWhere();busy[1].focus();return;}
|
||||||
published=!published;sw.classList.toggle('on',published);sw.setAttribute('aria-checked',String(published));
|
published=!published;sw.classList.toggle('on',published);sw.setAttribute('aria-checked',String(published));
|
||||||
paintWhere();
|
paintWhere();
|
||||||
};
|
};
|
||||||
@@ -644,8 +661,9 @@ function videoDialog(video){
|
|||||||
scope:'site-video:'+video.id+':video',progress:text=>say(text)});
|
scope:'site-video:'+video.id+':video',progress:text=>say(text)});
|
||||||
if(captionsInput.files[0])captionsId=await dtfUpload(captionsInput.files[0],{api,startPath:'/site-videos/uploads',
|
if(captionsInput.files[0])captionsId=await dtfUpload(captionsInput.files[0],{api,startPath:'/site-videos/uploads',
|
||||||
scope:'site-video:'+video.id+':captions',progress:text=>say(text)});
|
scope:'site-video:'+video.id+':captions',progress:text=>say(text)});
|
||||||
|
const products=productBoxes.filter(([,input])=>input.checked).map(([value])=>value);
|
||||||
await api('/site-videos/'+video.id,{upload_id:uploadId,captions_id:captionsId,
|
await api('/site-videos/'+video.id,{upload_id:uploadId,captions_id:captionsId,
|
||||||
product:product.value||null,enabled:published});
|
products,enabled:published});
|
||||||
say('Vídeo salvo. O Site mostrará a nova versão na próxima abertura.');
|
say('Vídeo salvo. O Site mostrará a nova versão na próxima abertura.');
|
||||||
await loadSiteVideos();
|
await loadSiteVideos();
|
||||||
}});
|
}});
|
||||||
|
|||||||
@@ -323,7 +323,10 @@ function machineForm(m){
|
|||||||
left.push(remove);
|
left.push(remove);
|
||||||
}
|
}
|
||||||
const d=formDialog(m?'Editar máquina':'Nova máquina',{width:520,left,
|
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('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),
|
field('Vagas em Imprimindo',places,PLACES_NOTE),
|
||||||
checkbox('Ativa: recebe pedidos',active)],
|
checkbox('Ativa: recebe pedidos',active)],
|
||||||
@@ -738,7 +741,7 @@ function accountForm(){
|
|||||||
sect.append(node('b','Trocar a senha'),field('Senha atual',current),row);
|
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'),
|
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],
|
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.');
|
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.');
|
await api('/me/password',{current:current.value,new:next.value});say('Senha trocada.');
|
||||||
}});
|
}});
|
||||||
|
|||||||
@@ -385,14 +385,9 @@ main{padding:0}
|
|||||||
.card.drop-before{box-shadow:0 -3px 0 0 var(--acc)}
|
.card.drop-before{box-shadow:0 -3px 0 0 var(--acc)}
|
||||||
.card.drop-after{box-shadow:0 3px 0 0 var(--acc)}
|
.card.drop-after{box-shadow:0 3px 0 0 var(--acc)}
|
||||||
/* A short note on hover or focus, for what a mark means. */
|
/* A short note on hover or focus, for what a mark means. */
|
||||||
[data-tip]{position:relative}
|
/* The tooltip box (kanban.js): fixed to the window, never cut by a column. */
|
||||||
[data-tip]::after{content:attr(data-tip);position:absolute;left:50%;top:calc(100% + 8px);transform:translate(-50%,-3px);width:max-content;max-width:280px;padding:7px 10px;border-radius:7px;background:var(--ink);color:var(--onink);font:500 12px/1.4 var(--font);letter-spacing:0;text-align:left;white-space:normal;text-transform:none;opacity:0;pointer-events:none;z-index:40;transition:opacity .15s,transform .15s;box-shadow:0 8px 24px -8px rgba(0,0,0,.5)}
|
.tipbox{position:fixed;z-index:200;max-width:min(320px,calc(100vw - 16px));padding:7px 10px;border-radius:7px;background:var(--ink);color:var(--onink);font:500 12px/1.4 var(--font);text-align:left;white-space:normal;pointer-events:none;box-shadow:0 8px 24px -8px rgba(0,0,0,.5)}
|
||||||
[data-tip]:hover::after,[data-tip]:focus-visible::after{opacity:1;transform:translate(-50%,0);transition-delay:.35s}
|
.tipbox[hidden]{display:none}
|
||||||
[data-tip].tip-l::after{left:auto;right:0;transform:translate(0,-3px)}
|
|
||||||
[data-tip].tip-l:hover::after,[data-tip].tip-l:focus-visible::after{transform:translate(0,0)}
|
|
||||||
[data-tip].tip-r::after{left:0;transform:translate(0,-3px)}
|
|
||||||
[data-tip].tip-r:hover::after{transform:translate(0,0)}
|
|
||||||
[data-tip='']::after{display:none}
|
|
||||||
@keyframes drop{from{transform:translateY(-6px);opacity:0}}
|
@keyframes drop{from{transform:translateY(-6px);opacity:0}}
|
||||||
@keyframes spin{to{transform:rotate(360deg)}}
|
@keyframes spin{to{transform:rotate(360deg)}}
|
||||||
@keyframes feedline{from{transform:translateX(-100%)}to{transform:translateX(100%)}}
|
@keyframes feedline{from{transform:translateX(-100%)}to{transform:translateX(100%)}}
|
||||||
@@ -703,7 +698,7 @@ label.fopt{cursor:pointer;user-select:none}
|
|||||||
|
|
||||||
/* Pages (redesign, steps 5 to 7): Pagamentos, Números, Integrações and
|
/* Pages (redesign, steps 5 to 7): Pagamentos, Números, Integrações and
|
||||||
Usuários, made of panels with a head and a table or a list. */
|
Usuários, made of panels with a head and a table or a list. */
|
||||||
.page:not([hidden]){padding:24px 28px 40px;display:flex;flex-direction:column;gap:20px;animation:fadeUp .35s cubic-bezier(.2,.8,.2,1) both}
|
.page:not([hidden]){padding:24px 28px 40px;display:flex;flex-direction:column;gap:20px;animation:fadeUp .35s cubic-bezier(.2,.8,.2,1) backwards}
|
||||||
/* Site (Phase B): the segmented tabs, the product/coupon/video tables and the
|
/* Site (Phase B): the segmented tabs, the product/coupon/video tables and the
|
||||||
price, coupon and video dialogs. */
|
price, coupon and video dialogs. */
|
||||||
#tab-site .site-sub{font-size:13.5px;color:var(--tx2)}
|
#tab-site .site-sub{font-size:13.5px;color:var(--tx2)}
|
||||||
@@ -1666,3 +1661,12 @@ dialog.viewer::backdrop{background:var(--scrim)}
|
|||||||
.montar-size-row{height:44px}
|
.montar-size-row{height:44px}
|
||||||
.montar-ajustes-dlg{max-height:92vh}
|
.montar-ajustes-dlg{max-height:92vh}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.montar-list-actions{display:flex;align-items:center;gap:8px}
|
||||||
|
.montar-list-actions>.btn{height:42px;white-space:nowrap}
|
||||||
|
.montar-list-text{min-height:210px;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:13px;line-height:1.5}
|
||||||
|
.montar-list-errors{display:flex;flex-direction:column;gap:6px;max-height:320px;overflow:auto;padding:10px 12px;border-radius:10px;background:var(--sf2)}
|
||||||
|
.montar-list-errors p{margin:0;font-size:13px;color:var(--tx2);word-break:break-word}
|
||||||
|
@media (max-width:700px){
|
||||||
|
.montar-list-actions{grid-column:1/-1;justify-content:flex-start}
|
||||||
|
}
|
||||||
|
|||||||
@@ -122,7 +122,7 @@
|
|||||||
<section class="panel montar-nofolder-panel" id="montar-nofolder-panel" hidden>
|
<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>
|
<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>
|
<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>
|
<button class="btn pri" id="montar-nofolder-choose" type="button">Escolher pasta</button>
|
||||||
</section>
|
</section>
|
||||||
<section class="panel clip" id="montar-setup" hidden>
|
<section class="panel clip" id="montar-setup" hidden>
|
||||||
@@ -131,7 +131,10 @@
|
|||||||
<label class="fld"><span>Código</span><input id="montar-code" maxlength="40" autocomplete="off" spellcheck="false" placeholder="1001"></label>
|
<label class="fld"><span>Código</span><input id="montar-code" maxlength="40" autocomplete="off" spellcheck="false" placeholder="1001"></label>
|
||||||
<label class="fld"><span>Tamanho</span><select id="montar-size"></select></label>
|
<label class="fld"><span>Tamanho</span><select id="montar-size"></select></label>
|
||||||
<label class="fld"><span>Quantidade</span><input id="montar-qty" type="number" min="1" max="9999" step="1" value="1"></label>
|
<label class="fld"><span>Quantidade</span><input id="montar-qty" type="number" min="1" max="9999" step="1" value="1"></label>
|
||||||
<button class="btn pri" id="montar-add" type="button">Adicionar</button>
|
<div class="montar-list-actions">
|
||||||
|
<button class="btn pri" id="montar-add" type="button">Adicionar</button>
|
||||||
|
<button class="btn" id="montar-paste" type="button">Colar lista</button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="montar-preview" id="montar-preview"></div>
|
<div class="montar-preview" id="montar-preview"></div>
|
||||||
</section>
|
</section>
|
||||||
@@ -146,7 +149,7 @@
|
|||||||
<div class="montar-sheetinfo">
|
<div class="montar-sheetinfo">
|
||||||
<span>Prévia da folha</span>
|
<span>Prévia da folha</span>
|
||||||
<b id="montar-film-length">—</b>
|
<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>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|||||||
@@ -27,6 +27,8 @@ function outcomeText(outcome){
|
|||||||
[/^refused: quote was never reviewed/,()=>'a cotação ainda não tinha sido revisada'],
|
[/^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'],
|
[/^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]],
|
[/^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);}
|
for(const [pattern,text] of rules){const m=outcome.match(pattern);if(m)return text(m);}
|
||||||
return outcome;
|
return outcome;
|
||||||
@@ -368,10 +370,10 @@ function folderCard(){
|
|||||||
if(FOLDER.mode==='none'){
|
if(FOLDER.mode==='none'){
|
||||||
if(FOLDER.brave){
|
if(FOLDER.brave){
|
||||||
const first=node('li','Copie este endereço: ');first.append(node('code',BRAVE_FLAG,'flag'));
|
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.');})],
|
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.'),
|
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 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'){
|
}else if(FOLDER.mode==='downloads'){
|
||||||
const how=[steps('No Firefox, abra Configurações → Geral → Arquivos e aplicativos.',
|
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',
|
? 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(),
|
summary:FOLDER.error||FOLDER.status||'Baixando na pasta de downloads do Firefox · '+folderCount(),
|
||||||
details:how,extra:[ghost('Desligar',()=>setDownloads(false))]})
|
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});
|
actions:[act('Ligar',()=>setDownloads(true))],details:how});
|
||||||
}else if(!h){
|
}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)],
|
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. '+
|
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.')]});
|
||||||
'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.')]});
|
|
||||||
}else if(!FOLDER.granted){
|
}else if(!FOLDER.granted){
|
||||||
row=integration({name,state:'Liberar',tone:'warn',summary:'O navegador pede um clique para voltar a salvar em “'+h.name+'”.',
|
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)]});
|
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(),
|
summary:FOLDER.error||FOLDER.status||'Salvando em “'+h.name+'” · '+folderCount(),
|
||||||
details:[['Pasta','“'+h.name+'”'],['Arquivos salvos',String(FOLDER.saved.size)],
|
details:[['Pasta','“'+h.name+'”'],['Arquivos salvos',String(FOLDER.saved.size)],
|
||||||
['Último',FOLDER.last?FOLDER.last.toLocaleTimeString('pt-BR',{hour:'2-digit',minute:'2-digit'}):'—'],
|
['Ú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á '+
|
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.'),
|
||||||
'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','Não coloque nada na pasta '+WORK_FOLDER+': é a de trabalho do Kanban.'),
|
||||||
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','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 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 em correção sai das pastas. Pedidos que já imprimiam quando a pasta foi escolhida não são baixados.'),
|
||||||
node('p','Pedido cancelado, excluído ou devolvido para correção: o arquivo sai das pastas. Arquivo trocado: a versão antiga sai. '+
|
node('p','Deixe o Kanban aberto neste computador. Se ele ficar desligado, ao voltar busca o que faltou.')],
|
||||||
'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.')],
|
|
||||||
extra:[ghost('Trocar pasta',chooseFolder),ghost('Desligar',forgetFolder)]});
|
extra:[ghost('Trocar pasta',chooseFolder),ghost('Desligar',forgetFolder)]});
|
||||||
}
|
}
|
||||||
row.id='folder-card';return row;
|
row.id='folder-card';return row;
|
||||||
@@ -566,6 +565,9 @@ async function fetchFile(url,options){
|
|||||||
}
|
}
|
||||||
async function fetchInto(dir,file,watched=false){
|
async function fetchInto(dir,file,watched=false){
|
||||||
const r=await fetchFile(file.url,{referrerPolicy:'no-referrer'});
|
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+').');
|
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);
|
await writeWhole(dir,file.name,r,watched);
|
||||||
}
|
}
|
||||||
@@ -624,7 +626,14 @@ async function syncFolder(force=false){
|
|||||||
FOLDER.busy=true;
|
FOLDER.busy=true;
|
||||||
try{
|
try{
|
||||||
if(stages)await makeStageFolders();
|
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});
|
const {files,states,receipts=[],reviews=[]}=await api('/queue/folder',{early:stages,held,since:stages?FOLDER.since||await folderSince():null});
|
||||||
// By file: an item longer than a part (10 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 wanted=new Map(files.map(f=>[f.upload_id,f]));
|
||||||
@@ -640,7 +649,7 @@ async function syncFolder(force=false){
|
|||||||
...(folder===STAGE_FOLDERS.fin?{at:file.at||Date.now()}:{})});
|
...(folder===STAGE_FOLDERS.fin?{at:file.at||Date.now()}:{})});
|
||||||
FOLDER.last=new Date();await keepSaved();};
|
FOLDER.last=new Date();await keepSaved();};
|
||||||
if(stages)for(const [uid,rec] of [...FOLDER.saved])await step(rec.name,async()=>{
|
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 state=states[rec.order], target=STAGE_FOLDERS[state];
|
||||||
const now=wanted.get(uid);
|
const now=wanted.get(uid);
|
||||||
const replaced=(state==='rec'||state==='tra')&&(!now||now.order!==rec.order);
|
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;
|
FOLDER.awaySince=0;FOLDER.awayReported=false;
|
||||||
if(e.name==='NotAllowedError')FOLDER.granted=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.';
|
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);
|
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();}
|
}finally{FOLDER.busy=false;paintFolder();}
|
||||||
@@ -870,6 +879,7 @@ async function load(quiet=false){
|
|||||||
askMachine();
|
askMachine();
|
||||||
syncFolder();
|
syncFolder();
|
||||||
if(typeof labelAfterLoad==='function')labelAfterLoad();
|
if(typeof labelAfterLoad==='function')labelAfterLoad();
|
||||||
|
if(typeof remindPreviews==='function')remindPreviews(board.orders);
|
||||||
}catch(e){
|
}catch(e){
|
||||||
if(e.status===401||e.status===503){$('app').hidden=true;$('login').hidden=false;$('drawer').hidden=true;}
|
if(e.status===401||e.status===503){$('app').hidden=true;$('login').hidden=false;$('drawer').hidden=true;}
|
||||||
// Not being signed in yet is the normal start, not an error.
|
// Not being signed in yet is the normal start, not an error.
|
||||||
@@ -1197,5 +1207,30 @@ function paintSync(){
|
|||||||
$('sync').onclick=e=>{e.stopPropagation();const m=$('sync-menu');m.hidden=!m.hidden;$('sync').setAttribute('aria-expanded',String(!m.hidden));
|
$('sync').onclick=e=>{e.stopPropagation();const m=$('sync-menu');m.hidden=!m.hidden;$('sync').setAttribute('aria-expanded',String(!m.hidden));
|
||||||
if(!m.hidden)document.addEventListener('click',()=>{m.hidden=true;$('sync').setAttribute('aria-expanded','false');},{once:true});};
|
if(!m.hidden)document.addEventListener('click',()=>{m.hidden=true;$('sync').setAttribute('aria-expanded','false');},{once:true});};
|
||||||
$('refresh').addEventListener('click',()=>{$('sync-menu').hidden=true;});
|
$('refresh').addEventListener('click',()=>{$('sync-menu').hidden=true;});
|
||||||
|
// Tooltips ([data-tip]): one box on the page itself, fixed to the window, so
|
||||||
|
// a card's column never cuts it and it never covers the card below; it sits
|
||||||
|
// under the element, or over it near the bottom, always inside the screen.
|
||||||
|
(()=>{
|
||||||
|
const box=node('div',undefined,'tipbox');box.setAttribute('role','tooltip');box.hidden=true;document.body.append(box);
|
||||||
|
let target=null,timer=null;
|
||||||
|
const hide=()=>{clearTimeout(timer);timer=null;target=null;box.hidden=true;};
|
||||||
|
const place=el=>{
|
||||||
|
box.textContent=el.dataset.tip;box.hidden=false;
|
||||||
|
const r=el.getBoundingClientRect(),b=box.getBoundingClientRect(),gap=8,edge=8;
|
||||||
|
let top=r.bottom+gap;
|
||||||
|
if(top+b.height>innerHeight-edge&&r.top-gap-b.height>=edge)top=r.top-gap-b.height;
|
||||||
|
const left=Math.min(Math.max(edge,r.left+r.width/2-b.width/2),innerWidth-edge-b.width);
|
||||||
|
box.style.top=Math.round(top)+'px';box.style.left=Math.round(left)+'px';
|
||||||
|
};
|
||||||
|
const show=el=>{
|
||||||
|
if(!el||!el.dataset.tip||el===target)return;
|
||||||
|
clearTimeout(timer);target=el;timer=setTimeout(()=>{if(target===el&&el.isConnected)place(el);},350);
|
||||||
|
};
|
||||||
|
document.addEventListener('mouseover',e=>{const el=e.target.closest?.('[data-tip]');if(el)show(el);else if(target)hide();});
|
||||||
|
document.addEventListener('focusin',e=>{const el=e.target.closest?.('[data-tip]');if(el)show(el);});
|
||||||
|
document.addEventListener('focusout',hide);
|
||||||
|
addEventListener('scroll',hide,true);
|
||||||
|
addEventListener('keydown',e=>{if(e.key==='Escape')hide();});
|
||||||
|
})();
|
||||||
// The tabs live in later files: wait for all scripts before loading.
|
// The tabs live in later files: wait for all scripts before loading.
|
||||||
addEventListener('DOMContentLoaded',()=>restoreFolder().finally(()=>load()));
|
addEventListener('DOMContentLoaded',()=>restoreFolder().finally(()=>load()));
|
||||||
|
|||||||
@@ -122,6 +122,14 @@
|
|||||||
if (!started || status === 401 || typeof Sentry === 'undefined') return;
|
if (!started || status === 401 || typeof Sentry === 'undefined') return;
|
||||||
// A restart's few seconds without the database (app/app.py): not a bug.
|
// A restart's few seconds without the database (app/app.py): not a bug.
|
||||||
if (status === 503 && /reiniciando/.test(String(message))) return;
|
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 {
|
try {
|
||||||
// One issue per kind of API error: without this Sentry groups them all
|
// 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
|
// 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};
|
const extra = {path, status, page: location.pathname};
|
||||||
if (status === 422 && detail) extra.detail = detail;
|
if (status === 422 && detail) extra.detail = detail;
|
||||||
Sentry.captureMessage('API ' + status + ' ' + kindPath + ': ' + kindMessage,
|
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]});
|
fingerprint: ['api-error', String(status), kindPath, kindMessage]});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Reporting an error must never break the page.
|
// Reporting an error must never break the page.
|
||||||
|
|||||||
@@ -48,12 +48,15 @@ const GANHO_FORMA_CM=1;
|
|||||||
// pecas em centímetros: {w,h,img,a,travado}. W é a largura do filme em cm.
|
// pecas em centímetros: {w,h,img,a,travado}. W é a largura do filme em cm.
|
||||||
// Devolve {pos, altura, folga}: a altura já com as margens, a folga a menor
|
// Devolve {pos, altura, folga}: a altura já com as margens, a folga a menor
|
||||||
// usada na largura.
|
// usada na largura.
|
||||||
function encaixar(pecas,W){
|
function encaixar(pecas,W,modo){
|
||||||
if(pecas.some(p=>!Number.isFinite(p.w) || p.w<=0 || p.w>W))
|
if(pecas.some(p=>!Number.isFinite(p.w) || p.w<=0 || p.w>W))
|
||||||
throw new RangeError('A largura solicitada não cabe no filme.');
|
throw new RangeError('A largura solicitada não cabe no filme.');
|
||||||
|
if(modo==='forma') return encaixarComMargens(pecas,W);
|
||||||
const linhas=encaixarEmLinhas(pecas,W);
|
const linhas=encaixarEmLinhas(pecas,W);
|
||||||
const forma=encaixarComMargens(pecas,W);
|
if(modo!=='linhas'){
|
||||||
if(forma.altura<=linhas.altura-GANHO_FORMA_CM) return forma;
|
const forma=encaixarComMargens(pecas,W);
|
||||||
|
if(forma.altura<=linhas.altura-GANHO_FORMA_CM) return forma;
|
||||||
|
}
|
||||||
// A máscara de cada peça: a área de arte que a prévia mostra como aproveitada.
|
// A máscara de cada peça: a área de arte que a prévia mostra como aproveitada.
|
||||||
const mascaras=new Map();
|
const mascaras=new Map();
|
||||||
linhas.pos.forEach(p=>{
|
linhas.pos.forEach(p=>{
|
||||||
|
|||||||
@@ -141,6 +141,21 @@ button:disabled{opacity:.6;cursor:default}
|
|||||||
.correcaoForm textarea{height:auto;padding:10px 13px;resize:vertical}
|
.correcaoForm textarea{height:auto;padding:10px 13px;resize:vertical}
|
||||||
.correcaoForm .bPri{margin-top:14px;align-self:flex-start}
|
.correcaoForm .bPri{margin-top:14px;align-self:flex-start}
|
||||||
|
|
||||||
|
/* Saved sheets (Minhas folhas). */
|
||||||
|
.folhas{display:grid;grid-template-columns:repeat(auto-fill,minmax(250px,1fr));gap:14px;padding:14px}
|
||||||
|
.folhaCard{display:flex;flex-direction:column;border:1px solid var(--linha);border-radius:var(--raio2);background:#fff;overflow:hidden}
|
||||||
|
.folhaPic{aspect-ratio:4/3;background:var(--cinza);border-bottom:1px solid var(--linha)}
|
||||||
|
.folhaPic img{display:block;width:100%;height:100%;object-fit:contain;padding:10px;box-sizing:border-box}
|
||||||
|
.folhaPic .semFoto{width:100%;height:100%;background:repeating-linear-gradient(135deg,var(--cinza),var(--cinza) 10px,#EDEDED 10px,#EDEDED 20px)}
|
||||||
|
.folhaBody{display:flex;flex-direction:column;gap:4px;padding:14px 16px 6px}
|
||||||
|
.folhaNome{font-family:"Inter",sans-serif;font-size:16px;font-weight:800;overflow-wrap:anywhere}
|
||||||
|
.folhaProduto,.folhaMetros{margin:0;font-size:14px;color:var(--fraco)}
|
||||||
|
.folhaValidade{margin:6px 0 0;font-size:14px;color:var(--texto2)}
|
||||||
|
.folhaValidade.vencida{color:#B42318}
|
||||||
|
.folhaAcoes{display:flex;flex-wrap:wrap;gap:8px;padding:12px 16px 16px;margin-top:auto}
|
||||||
|
.folhaAcoes .bPri,.folhaAcoes .bSec{height:38px;padding:0 14px;font-size:14.5px}
|
||||||
|
.folhaAcoes .folhaGrande{max-width:100%;min-height:38px;height:auto;padding:7px 12px;text-align:center;line-height:1.25;white-space:normal}
|
||||||
|
|
||||||
@media (max-width:820px){
|
@media (max-width:820px){
|
||||||
.area{grid-template-columns:1fr;gap:16px}
|
.area{grid-template-columns:1fr;gap:16px}
|
||||||
.lateral{position:static;flex-direction:row;flex-wrap:wrap}
|
.lateral{position:static;flex-direction:row;flex-wrap:wrap}
|
||||||
|
|||||||
@@ -107,6 +107,7 @@
|
|||||||
<nav class="lateral" aria-label="Minha conta">
|
<nav class="lateral" aria-label="Minha conta">
|
||||||
<a href="/conta" data-view="geral" data-conta>Visão geral</a>
|
<a href="/conta" data-view="geral" data-conta>Visão geral</a>
|
||||||
<a href="/conta/pedidos" data-view="pedidos">Pedidos</a>
|
<a href="/conta/pedidos" data-view="pedidos">Pedidos</a>
|
||||||
|
<a href="/conta/folhas" data-view="folhas" data-conta>Minhas folhas</a>
|
||||||
<a href="/conta/dados" data-view="dados" data-conta>Dados da conta</a>
|
<a href="/conta/dados" data-view="dados" data-conta>Dados da conta</a>
|
||||||
<a href="/conta/entrar" data-view="entrar" id="navEntrar">Entrar</a>
|
<a href="/conta/entrar" data-view="entrar" id="navEntrar">Entrar</a>
|
||||||
<button type="button" id="logout" hidden>Sair</button>
|
<button type="button" id="logout" hidden>Sair</button>
|
||||||
@@ -140,6 +141,11 @@
|
|||||||
<div class="paginas" id="paginas"></div>
|
<div class="paginas" id="paginas"></div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<section class="vista" id="vFolhas" hidden aria-labelledby="tFolhas">
|
||||||
|
<h1 id="tFolhas">Minhas folhas</h1>
|
||||||
|
<div class="lista" id="sheets"></div>
|
||||||
|
</section>
|
||||||
|
|
||||||
<section class="vista" id="vDados" hidden aria-labelledby="tDados">
|
<section class="vista" id="vDados" hidden aria-labelledby="tDados">
|
||||||
<h1 id="tDados">Dados da conta</h1>
|
<h1 id="tDados">Dados da conta</h1>
|
||||||
<form class="bloco" id="fPerfil">
|
<form class="bloco" id="fPerfil">
|
||||||
@@ -208,7 +214,7 @@
|
|||||||
<a href="https://wa.me/message/NJ76CLIOUGXLB1" target="_blank" rel="noopener">16 99428-0056</a>
|
<a href="https://wa.me/message/NJ76CLIOUGXLB1" target="_blank" rel="noopener">16 99428-0056</a>
|
||||||
· arquivos 16 99230-2546<br>
|
· arquivos 16 99230-2546<br>
|
||||||
<a href="mailto:atendimentodropstar@gmail.com">atendimentodropstar@gmail.com</a><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
|
Retirada em Franca, de segunda a sexta, das 7h às 18h
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -28,7 +28,8 @@ function icone(nome){
|
|||||||
return span.firstChild;
|
return span.firstChild;
|
||||||
}
|
}
|
||||||
const PRODUTO={file:'DTF Têxtil · folha montada',avulsa:'DTF Têxtil · artes avulsas',
|
const PRODUTO={file:'DTF Têxtil · folha montada',avulsa:'DTF Têxtil · artes avulsas',
|
||||||
uvfile:'DTF UV · folha montada',uv:'DTF UV · artes avulsas'};
|
uvfile:'DTF UV · folha montada',uv:'DTF UV · artes avulsas',
|
||||||
|
premium:'DTF Têxtil Premium · folha montada'};
|
||||||
// Artes avulsas que o Site separou por traço (item 17): uma folha por item.
|
// Artes avulsas que o Site separou por traço (item 17): uma folha por item.
|
||||||
const nomeItem=item=>(PRODUTO[item.mode]||item.mode)+(item.split?' · folha '+item.split.part+' de '+item.split.of:'');
|
const nomeItem=item=>(PRODUTO[item.mode]||item.mode)+(item.split?' · folha '+item.split.part+' de '+item.split.of:'');
|
||||||
// The order's steps as the customer sees them (Dropstar's flow, 2026-10-23).
|
// The order's steps as the customer sees them (Dropstar's flow, 2026-10-23).
|
||||||
@@ -50,6 +51,7 @@ function vista(){
|
|||||||
if(p==='/conta/entrar') return 'entrar';
|
if(p==='/conta/entrar') return 'entrar';
|
||||||
if(p==='/conta/redefinir') return 'redefinir';
|
if(p==='/conta/redefinir') return 'redefinir';
|
||||||
if(p==='/conta/dados') return 'dados';
|
if(p==='/conta/dados') return 'dados';
|
||||||
|
if(p==='/conta/folhas') return 'folhas';
|
||||||
if(p==='/conta') return 'geral';
|
if(p==='/conta') return 'geral';
|
||||||
return 'pedidos'; // /conta/pedidos, and the old /portal.html
|
return 'pedidos'; // /conta/pedidos, and the old /portal.html
|
||||||
}
|
}
|
||||||
@@ -64,20 +66,22 @@ document.addEventListener('click',event=>{
|
|||||||
async function mostra(){
|
async function mostra(){
|
||||||
aviso('');
|
aviso('');
|
||||||
const v=vista(), proximo=new URLSearchParams(location.search).get('next');
|
const v=vista(), proximo=new URLSearchParams(location.search).get('next');
|
||||||
// Overview and details are the account's; orders also work for a guest.
|
// Overview, details and saved sheets are the account's; orders also work for a guest.
|
||||||
if((v==='geral'||v==='dados')&&!conta){history.replaceState({},'','/conta/entrar?next='+encodeURIComponent(location.pathname));return mostra();}
|
if((v==='geral'||v==='dados'||v==='folhas')&&!conta){history.replaceState({},'','/conta/entrar?next='+encodeURIComponent(location.pathname));return mostra();}
|
||||||
if(v==='entrar'&&conta){history.replaceState({},'',proximo&&/^\/conta(\/[a-z]+)?$/.test(proximo)?proximo:'/conta');return mostra();}
|
if(v==='entrar'&&conta){history.replaceState({},'',proximo&&/^\/conta(\/[a-z]+)?$/.test(proximo)?proximo:'/conta');return mostra();}
|
||||||
$('auth').hidden=v!=='entrar';
|
$('auth').hidden=v!=='entrar';
|
||||||
$('redefinir').hidden=v!=='redefinir';
|
$('redefinir').hidden=v!=='redefinir';
|
||||||
$('area').hidden=v==='entrar'||v==='redefinir';
|
$('area').hidden=v==='entrar'||v==='redefinir';
|
||||||
if(v==='redefinir'&&!resetToken)aviso('Este link está incompleto. Peça outro em “Esqueci minha senha”.',true);
|
if(v==='redefinir'&&!resetToken)aviso('Este link está incompleto. Peça outro em “Esqueci minha senha”.',true);
|
||||||
$('vGeral').hidden=v!=='geral';$('vPedidos').hidden=v!=='pedidos';$('vDados').hidden=v!=='dados';
|
$('vGeral').hidden=v!=='geral';$('vPedidos').hidden=v!=='pedidos';$('vDados').hidden=v!=='dados';
|
||||||
|
$('vFolhas').hidden=v!=='folhas';
|
||||||
for(const a of document.querySelectorAll('.lateral a'))a.classList.toggle('on',a.dataset.view===v);
|
for(const a of document.querySelectorAll('.lateral a'))a.classList.toggle('on',a.dataset.view===v);
|
||||||
for(const a of document.querySelectorAll('.lateral [data-conta]'))a.hidden=!conta;
|
for(const a of document.querySelectorAll('.lateral [data-conta]'))a.hidden=!conta;
|
||||||
$('navEntrar').hidden=!!conta;$('logout').hidden=!conta;
|
$('navEntrar').hidden=!!conta;$('logout').hidden=!conta;
|
||||||
document.title=({entrar:'Entrar',redefinir:'Criar nova senha',geral:'Minha conta',pedidos:'Pedidos',dados:'Dados da conta'})[v]+' · DTF Dropstar';
|
document.title=({entrar:'Entrar',redefinir:'Criar nova senha',geral:'Minha conta',pedidos:'Pedidos',folhas:'Minhas folhas',dados:'Dados da conta'})[v]+' · DTF Dropstar';
|
||||||
if(v==='geral')await geral();
|
if(v==='geral')await geral();
|
||||||
else if(v==='pedidos')await pedidos();
|
else if(v==='pedidos')await pedidos();
|
||||||
|
else if(v==='folhas')await folhas();
|
||||||
else if(v==='dados')dados();
|
else if(v==='dados')dados();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -205,6 +209,8 @@ function itensPedido(snapshot){
|
|||||||
li.append(node('span',nomeItem(item),'nome'),node('span',metros(item.billed_metres),'qt'),node('b',money(item.total_cents)));
|
li.append(node('span',nomeItem(item),'nome'),node('span',metros(item.billed_metres),'qt'),node('b',money(item.total_cents)));
|
||||||
ul.append(li);
|
ul.append(li);
|
||||||
}
|
}
|
||||||
|
// The proof the customer asked for (Rodada 5, B3).
|
||||||
|
if(snapshot.proof){const li=node('li',null,'frete');li.append(node('span','Prova antes de imprimir','nome'),node('span','','qt'),node('b','Grátis'));ul.append(li);}
|
||||||
const f=snapshot.freight;
|
const f=snapshot.freight;
|
||||||
if(f&&f.total_cents){const li=node('li',null,'frete');li.append(node('span','Frete','nome'),node('span',f.days?'até '+f.days+' dias úteis':'','qt'),node('b',money(f.total_cents)));ul.append(li);}
|
if(f&&f.total_cents){const li=node('li',null,'frete');li.append(node('span','Frete','nome'),node('span',f.days?'até '+f.days+' dias úteis':'','qt'),node('b',money(f.total_cents)));ul.append(li);}
|
||||||
return ul;
|
return ul;
|
||||||
@@ -297,6 +303,85 @@ async function geral(){
|
|||||||
else{const v=node('div',null,'vazio');v.append(node('p','Seu primeiro pedido aparece aqui.'));const a=node('a','Enviar uma arte','bPri');a.href='/#envio';v.append(a);ultimo.append(v);}
|
else{const v=node('div',null,'vazio');v.append(node('p','Seu primeiro pedido aparece aqui.'));const a=node('a','Enviar uma arte','bPri');a.href='/#envio';v.append(a);ultimo.append(v);}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---- Saved sheets (Minhas folhas) ----------------------------------------
|
||||||
|
|
||||||
|
const FOLHA_PAGINA={file:'/arquivo-por-metro',avulsa:'/artes-avulsas',uvfile:'/uv-arquivo-por-metro',
|
||||||
|
uv:'/uv-artes-avulsas',premium:'/arquivo-por-metro'};
|
||||||
|
const FOLHA_MAX=300*1024*1024;
|
||||||
|
const ddmm=d=>new Date(d).toLocaleDateString('pt-BR',{day:'2-digit',month:'2-digit'});
|
||||||
|
async function excluirFolha(id){
|
||||||
|
const r=await fetch('/api/account/sheets/'+encodeURIComponent(id),{method:'DELETE'});
|
||||||
|
const d=await r.json();
|
||||||
|
if(!r.ok){const error=new Error(typeof d.detail==='string'?d.detail:'Não foi possível excluir a folha.');error.status=r.status;throw error;}
|
||||||
|
return d;
|
||||||
|
}
|
||||||
|
async function guardarNoCarrinho(item){
|
||||||
|
const database=await new Promise((resolve,reject)=>{const req=indexedDB.open('dtf-local-cart',1);req.onupgradeneeded=()=>req.result.createObjectStore('cart');req.onsuccess=()=>resolve(req.result);req.onerror=()=>reject(req.error);});
|
||||||
|
try{
|
||||||
|
await new Promise((resolve,reject)=>{
|
||||||
|
const tx=database.transaction('cart','readwrite'),store=tx.objectStore('cart');
|
||||||
|
const req=store.get(scope);
|
||||||
|
req.onsuccess=()=>{
|
||||||
|
const saved=req.result;
|
||||||
|
const items=Array.isArray(saved?.items)?saved.items:[];
|
||||||
|
store.put({items:[...items,item],expires:Date.now()+86400000},scope);
|
||||||
|
};
|
||||||
|
tx.oncomplete=resolve;tx.onerror=()=>reject(tx.error);tx.onabort=()=>reject(tx.error);
|
||||||
|
});
|
||||||
|
}finally{database.close();}
|
||||||
|
}
|
||||||
|
function folhaCartao(f){
|
||||||
|
const card=node('article',null,'folhaCard');
|
||||||
|
const pic=node('div',null,'folhaPic');
|
||||||
|
if(f.picture){const img=node('img');img.alt='Miniatura da folha '+f.name;img.loading='lazy';img.src=f.picture;pic.append(img);}
|
||||||
|
else pic.append(node('div',null,'semFoto'));
|
||||||
|
const body=node('div',null,'folhaBody');
|
||||||
|
body.append(node('h2',f.name,'folhaNome'),node('p',PRODUTO[f.mode]||f.mode,'folhaProduto'),
|
||||||
|
node('p',metros(f.metres),'folhaMetros'));
|
||||||
|
const validade=f.available?'Arquivos até '+ddmm(f.files_until)
|
||||||
|
:(f.files_until?'Arquivos vencidos em '+ddmm(f.files_until)+'. Envie de novo para pedir.'
|
||||||
|
:'Arquivos vencidos. Envie de novo para pedir.');
|
||||||
|
body.append(node('p',validade,'folhaValidade'+(f.available?'':' vencida')));
|
||||||
|
card.append(pic,body);
|
||||||
|
const acoes=node('div',null,'folhaAcoes');
|
||||||
|
if(f.available){
|
||||||
|
acoes.append(button('Pedir de novo',async()=>{
|
||||||
|
const sheet=await api('/account/sheets/'+encodeURIComponent(f.id)+'/use',{});
|
||||||
|
await guardarNoCarrinho(sheet.item);
|
||||||
|
location.assign('/carrinho');
|
||||||
|
},'bPri bMini'));
|
||||||
|
if(Number(f.total_size)<=FOLHA_MAX){
|
||||||
|
acoes.append(button('Editar',()=>location.assign(FOLHA_PAGINA[f.mode]+'?folha='+encodeURIComponent(f.id)),'bSec'));
|
||||||
|
}else{
|
||||||
|
const grande=node('button','Grande demais para editar aqui. Use Pedir de novo.','bSec folhaGrande');
|
||||||
|
grande.type='button';grande.disabled=true;acoes.append(grande);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
acoes.append(button('Excluir',async()=>{
|
||||||
|
if(!confirm('Excluir a folha “'+f.name+'”?'))return;
|
||||||
|
await excluirFolha(f.id);
|
||||||
|
await folhas();
|
||||||
|
},'bSec'));
|
||||||
|
card.append(acoes);
|
||||||
|
return card;
|
||||||
|
}
|
||||||
|
async function folhas(){
|
||||||
|
const lista=$('sheets');lista.replaceChildren();
|
||||||
|
const carregando=node('div',null,'vazio');carregando.append(node('p','Carregando…','nota2'));lista.append(carregando);
|
||||||
|
let data;
|
||||||
|
try{data=await api('/account/sheets');}
|
||||||
|
catch(error){lista.replaceChildren();aviso(error.message,true);return;}
|
||||||
|
lista.replaceChildren();
|
||||||
|
if(!data.sheets.length){
|
||||||
|
const vazio=node('div',null,'vazio');
|
||||||
|
vazio.append(node('p','Nenhuma folha salva. No carrinho, use Salvar em Minhas folhas.'));
|
||||||
|
lista.append(vazio);return;
|
||||||
|
}
|
||||||
|
const grade=node('div',null,'folhas');
|
||||||
|
for(const f of data.sheets)grade.append(folhaCartao(f));
|
||||||
|
lista.append(grade);
|
||||||
|
}
|
||||||
|
|
||||||
// ---- Account details -----------------------------------------------------
|
// ---- Account details -----------------------------------------------------
|
||||||
|
|
||||||
const CAMPOS_END=[['dNome','recipient'],['dRua','street'],['dNum','number'],['dComp','complement'],['dBairro','district'],['dCidade','city'],['dUf','state']];
|
const CAMPOS_END=[['dNome','recipient'],['dRua','street'],['dNum','number'],['dComp','complement'],['dBairro','district'],['dCidade','city'],['dUf','state']];
|
||||||
@@ -326,7 +411,7 @@ $('fPerfil').onsubmit=async event=>{
|
|||||||
try{
|
try{
|
||||||
const r=await api('/account/profile',{name:$('dNomeCli').value,zap:$('dZap').value,address});
|
const r=await api('/account/profile',{name:$('dNomeCli').value,zap:$('dZap').value,address});
|
||||||
conta=r.customer;aviso('Dados salvos.');
|
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.
|
// A new e-mail is confirmed with the code sent to it before the account changes.
|
||||||
let troca=null, trocaTimer=null;
|
let troca=null, trocaTimer=null;
|
||||||
|
|||||||
@@ -118,9 +118,18 @@ function invalidaItemAtual(){
|
|||||||
pintaPedido();
|
pintaPedido();
|
||||||
}
|
}
|
||||||
function itemPodeEnviar(item){
|
function itemPodeEnviar(item){
|
||||||
|
if(semMargem(item)) return false;
|
||||||
return item.qualityStatus==='ok' || item.qualityStatus==='unverified' ||
|
return item.qualityStatus==='ok' || item.qualityStatus==='unverified' ||
|
||||||
(item.qualityStatus==='warning' && item.qualityAcknowledged===true);
|
(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
|
// 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.
|
// desmarcado fica guardado para depois. O item aberto no produto sempre vai.
|
||||||
function itensAPagar(){
|
function itensAPagar(){
|
||||||
@@ -176,11 +185,34 @@ function aplicaTratamento(aPagar){
|
|||||||
document.querySelectorAll('[data-ajuste],[data-ajustea]').forEach(el=>{el.checked=true;});
|
document.querySelectorAll('[data-ajuste],[data-ajustea]').forEach(el=>{el.checked=true;});
|
||||||
}
|
}
|
||||||
check.checked=ajusteTudo;check.disabled=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 está abaixo da resolução mínima, então o Ajuste Fino é obrigatório neste pedido.');
|
||||||
}else{
|
}else{
|
||||||
check.checked=ajusteTudo;check.disabled=false;mostraAvisoTratamento('');
|
check.checked=ajusteTudo;check.disabled=false;mostraAvisoTratamento('');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// Minhas folhas: the files of an item, and whether they are all already on
|
||||||
|
// the server (or the item came back from Minhas folhas with its own ids).
|
||||||
|
function arquivosDoItem(it){
|
||||||
|
return [...(it.localFiles||[]),...(it.partes||[]).flatMap(p=>p.localFiles||[])];
|
||||||
|
}
|
||||||
|
function podeSalvarFolha(it){
|
||||||
|
if((it.savedFiles||[]).length || (it.partes||[]).some(p=>(p.savedFiles||[]).length)) return true;
|
||||||
|
return arquivosDoItem(it).every(f=>!!window.dtfEnvio?.idDe(f));
|
||||||
|
}
|
||||||
|
// The cart item as Minhas folhas keeps it: files become their upload ids,
|
||||||
|
// without the pictures and without the cart's own marks.
|
||||||
|
function itemParaSalvar(it){
|
||||||
|
const copia=JSON.parse(JSON.stringify(it));
|
||||||
|
const pares=[{orig:it,dest:copia}];
|
||||||
|
(it.partes||[]).forEach((p,i)=>pares.push({orig:p,dest:copia.partes[i]}));
|
||||||
|
for(const {orig,dest} of pares){
|
||||||
|
dest.savedFiles=(orig.savedFiles||[]).length ? orig.savedFiles : (orig.localFiles||[]).map(f=>({
|
||||||
|
upload_id:window.dtfEnvio?.idDe(f),name:f.name,size:f.size,lastModified:f.lastModified,type:f.type
|
||||||
|
}));
|
||||||
|
delete dest.localFiles; delete dest.fotos; delete dest.marcado;
|
||||||
|
}
|
||||||
|
return copia;
|
||||||
|
}
|
||||||
// O carrinho junta itens de produtos diferentes e cobra uma vez só.
|
// O carrinho junta itens de produtos diferentes e cobra uma vez só.
|
||||||
function pintaPedido(){
|
function pintaPedido(){
|
||||||
const aPagar = itensAPagar();
|
const aPagar = itensAPagar();
|
||||||
@@ -209,8 +241,12 @@ function pintaPedido(){
|
|||||||
' aria-label="Incluir '+escapeHTML(it.tit)+' no pagamento"></label>'+
|
' 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>')+
|
'<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>'+
|
(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>'+
|
'<div class="vl2">'+rs(it.total)+'</div>'+
|
||||||
|
(window.dtfContaAberta?'<button type="button" class="salvaBt" data-salvai="'+i+'"'+
|
||||||
|
(podeSalvarFolha(it)?'':' disabled title="Espere os arquivos terminarem de enviar."')+
|
||||||
|
'>Salvar em Minhas folhas</button>':'')+
|
||||||
'<button type="button" class="x" data-rmi="'+i+'" aria-label="Remover '+escapeHTML(it.tit)+'">'+icone('lixeira')+'<span>Remover</span></button></div>').join('');
|
'<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',()=>{
|
$('itens').querySelectorAll('[data-sel]').forEach(c=>c.addEventListener('change',()=>{
|
||||||
pedido[+c.dataset.sel].marcado=c.checked; pintaPedido();
|
pedido[+c.dataset.sel].marcado=c.checked; pintaPedido();
|
||||||
@@ -222,6 +258,20 @@ function pintaPedido(){
|
|||||||
pedido.splice(Math.min(i,pedido.length),0,item); pintaPedido();
|
pedido.splice(Math.min(i,pedido.length),0,item); pintaPedido();
|
||||||
});
|
});
|
||||||
}));
|
}));
|
||||||
|
$('itens').querySelectorAll('[data-salvai]').forEach(b=>b.addEventListener('click',async()=>{
|
||||||
|
const it=pedido[+b.dataset.salvai]; if(!it || b.disabled) return;
|
||||||
|
const picture=typeof it.mini==='string' && /^data:/.test(it.mini) && it.mini.length<=300000 ? it.mini : null;
|
||||||
|
b.disabled=true;
|
||||||
|
try{
|
||||||
|
await window.dtfApi('/account/sheets',{name:it.tit+' · '+fmtM(it.cob)+' m',mode:it.modo,
|
||||||
|
metres:it.cob,item:itemParaSalvar(it),picture});
|
||||||
|
window.dtfMensagem?.('Folha salva em Minhas folhas.','ok');
|
||||||
|
}catch(error){
|
||||||
|
window.dtfMensagem?.(error.message,'error');
|
||||||
|
}finally{
|
||||||
|
b.disabled=!podeSalvarFolha(it);
|
||||||
|
}
|
||||||
|
}));
|
||||||
$('bEsvaziar').hidden = pedido.length+(itemAtual?1:0) < 2;
|
$('bEsvaziar').hidden = pedido.length+(itemAtual?1:0) < 2;
|
||||||
const itens = aPagar.reduce((t,it)=>t+it.total,0);
|
const itens = aPagar.reduce((t,it)=>t+it.total,0);
|
||||||
const frete = entrega.tipo==='frete' && entrega.cotado ? entrega.valor : 0;
|
const frete = entrega.tipo==='frete' && entrega.cotado ? entrega.valor : 0;
|
||||||
@@ -232,8 +282,8 @@ function pintaPedido(){
|
|||||||
// The whole order waits 48 h when any art was sent to Redesenho, else 24 h.
|
// The whole order waits 48 h when any art was sent to Redesenho, else 24 h.
|
||||||
const prazoTratamento=document.querySelector('#tratamentoBox .provaOp span');
|
const prazoTratamento=document.querySelector('#tratamentoBox .provaOp span');
|
||||||
if(prazoTratamento) for(const no of prazoTratamento.childNodes)
|
if(prazoTratamento) for(const no of prazoTratamento.childNodes)
|
||||||
if(no.nodeType===3) no.textContent=no.textContent.replace(/aumenta em \d+ h/,
|
if(no.nodeType===3) no.textContent=no.textContent.replace(/leva \d+ h a mais/,
|
||||||
'aumenta em '+(artesRedesenho>0?48:24)+' h');
|
'leva '+(artesRedesenho>0?48:24)+' h a mais');
|
||||||
const soma = itens + frete + tratamento + redesenho;
|
const soma = itens + frete + tratamento + redesenho;
|
||||||
const n = aPagar.length, noCarrinho = pedido.length + (itemAtual?1:0);
|
const n = aPagar.length, noCarrinho = pedido.length + (itemAtual?1:0);
|
||||||
$('resLin').innerHTML =
|
$('resLin').innerHTML =
|
||||||
@@ -247,6 +297,8 @@ function pintaPedido(){
|
|||||||
' · +24 h</span><b>'+rs(tratamento)+'</b></div>':'')+
|
' · +24 h</span><b>'+rs(tratamento)+'</b></div>':'')+
|
||||||
(redesenho?'<div class="l"><span>Ajuste Fino Redesenho · '+artesRedesenho+
|
(redesenho?'<div class="l"><span>Ajuste Fino Redesenho · '+artesRedesenho+
|
||||||
(artesRedesenho===1?' arte':' artes')+' · +48 h</span><b>'+rs(redesenho)+'</b></div>':'')+
|
(artesRedesenho===1?' arte':' artes')+' · +48 h</span><b>'+rs(redesenho)+'</b></div>':'')+
|
||||||
|
($('fProva')?.checked?'<div class="l"><span>Prova antes de imprimir</span>'+
|
||||||
|
'<b><span style="color:var(--verde-ml)">Grátis</span></b></div>':'')+
|
||||||
'<div class="l"><span>Revisão e reencaixe</span>'+
|
'<div class="l"><span>Revisão e reencaixe</span>'+
|
||||||
'<b><span style="color:var(--verde-ml)">Grátis</span></b></div>';
|
'<b><span style="color:var(--verde-ml)">Grátis</span></b></div>';
|
||||||
$('carrTot').textContent=rs(soma);
|
$('carrTot').textContent=rs(soma);
|
||||||
@@ -258,9 +310,12 @@ function pintaPedido(){
|
|||||||
: n>1
|
: n>1
|
||||||
? 'Pagar os '+n+' itens de uma vez'
|
? 'Pagar os '+n+' itens de uma vez'
|
||||||
: 'Ir para o pagamento';
|
: 'Ir para o pagamento';
|
||||||
// The proof is only for orders above 10 m (Dropstar, 2026-10-28): below it the box is gone.
|
// The proof is only for orders above 10 m (Dropstar, 2026-10-28; the server's
|
||||||
|
// PROOF_ABOVE_METRES). Below it the box stays, closed, and says the rule
|
||||||
|
// (Rodada 5, B3).
|
||||||
const prova=$('fProva');
|
const prova=$('fProva');
|
||||||
if(prova){ const longo=aPagar.reduce((t,it)=>t+(it.cob||0),0)>10; prova.closest('.cxE').hidden=!longo; if(!longo) prova.checked=false; }
|
if(prova){ const longo=aPagar.reduce((t,it)=>t+(it.cob||0),0)>10;
|
||||||
|
prova.disabled=!longo; if(!longo) prova.checked=false; $('provaMin').hidden=longo; }
|
||||||
$('bPagar').disabled = !cartPodeEnviar() || !entrega.cotado || !clienteOk() || !enderecoOk() || falta>0;
|
$('bPagar').disabled = !cartPodeEnviar() || !entrega.cotado || !clienteOk() || !enderecoOk() || falta>0;
|
||||||
if(pedido.length || itemAtual) $('carr').classList.add('on');
|
if(pedido.length || itemAtual) $('carr').classList.add('on');
|
||||||
if($('cartN')){ $('cartN').textContent=noCarrinho>99?'99+':noCarrinho; $('cartN').hidden=!noCarrinho;
|
if($('cartN')){ $('cartN').textContent=noCarrinho>99?'99+':noCarrinho; $('cartN').hidden=!noCarrinho;
|
||||||
@@ -272,7 +327,8 @@ function pintaPedido(){
|
|||||||
// A arte avulsa como fonte da montagem: largura, comprimento, cópias e giro.
|
// A arte avulsa como fonte da montagem: largura, comprimento, cópias e giro.
|
||||||
const fonteDaArte=x=>({kind:'artwork',width_cm:x.cm,length_cm:+(x.cm*propDe(x)).toFixed(4),
|
const fonteDaArte=x=>({kind:'artwork',width_cm:x.cm,length_cm:+(x.cm*propDe(x)).toFixed(4),
|
||||||
copies:x.q,rotation_degrees:x.giro||0,mirrored:!!x.esp,
|
copies:x.q,rotation_degrees:x.giro||0,mirrored:!!x.esp,
|
||||||
measurement:(x.src||x.semPrevia)?'file':'customer'});
|
measurement:(x.src||x.semPrevia)?'file':'customer',
|
||||||
|
...(x.cmSalvo?{saved_width_cm:x.cmSalvo,saved_dpi:x.dpiSalvo}:{})});
|
||||||
function carrinho(){
|
function carrinho(){
|
||||||
const cob=cobrarMontagem();
|
const cob=cobrarMontagem();
|
||||||
const extra=folhaManual()? TAXA_MANUAL : 0;
|
const extra=folhaManual()? TAXA_MANUAL : 0;
|
||||||
@@ -285,8 +341,8 @@ function carrinho(){
|
|||||||
$('carr').classList.add('on');
|
$('carr').classList.add('on');
|
||||||
let l='<div class="l"><span>'+MODOS[modo].tit+'</span><b>'+rs(base)+'/m</b></div>';
|
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(!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>';
|
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?' · arredondada para 10 cm':'')+
|
l += '<div class="l"><span>Metragem'+(sobra>0.001?' · a cada 10 cm':'')+
|
||||||
'</span><b>'+fmtM(cob)+' m</b></div>';
|
'</span><b>'+fmtM(cob)+' m</b></div>';
|
||||||
l += '<div class="l"><span>Preço final do metro</span><b>'+rs(unit)+'</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>';
|
'<div class="l" style="color:var(--laranja2)"><span>Revisão e reencaixe</span><b>grátis</b></div>';
|
||||||
@@ -363,6 +419,7 @@ function avisaDesfazer(texto,acao){
|
|||||||
function fechaDesfazer(){ clearTimeout(desfazerTimer); desfazerAcao=null; $('desfazer').hidden=true; }
|
function fechaDesfazer(){ clearTimeout(desfazerTimer); desfazerAcao=null; $('desfazer').hidden=true; }
|
||||||
addEventListener('dtf-page-changed',fechaDesfazer);
|
addEventListener('dtf-page-changed',fechaDesfazer);
|
||||||
$('desfazerBtn').addEventListener('click',()=>{ const acao=desfazerAcao; fechaDesfazer(); if(acao) acao(); });
|
$('desfazerBtn').addEventListener('click',()=>{ const acao=desfazerAcao; fechaDesfazer(); if(acao) acao(); });
|
||||||
|
$('fProva')?.addEventListener('change',()=>pintaPedido());
|
||||||
$('fTratamento')?.addEventListener('change',()=>{
|
$('fTratamento')?.addEventListener('change',()=>{
|
||||||
if($('fTratamento').checked){ ajusteTudo=true; limpaRedesenho(); }
|
if($('fTratamento').checked){ ajusteTudo=true; limpaRedesenho(); }
|
||||||
else limpaAjuste();
|
else limpaAjuste();
|
||||||
|
|||||||
@@ -4,25 +4,94 @@
|
|||||||
price of its own, so the box and the cart always agree. */
|
price of its own, so the box and the cart always agree. */
|
||||||
(function(){
|
(function(){
|
||||||
const vals=$('compraVals'), add=$('bAdd');
|
const vals=$('compraVals'), add=$('bAdd');
|
||||||
|
const nomeCurto=n=>{ n=n||''; return n.length>24 ? n.slice(0,23)+'…' : n; };
|
||||||
|
// C2 · o cliente escolhe entre Agrupado (linhas) e Misturado (pela forma).
|
||||||
|
function pintaEncaixe(it){
|
||||||
|
const box=$('cEncaixe'); if(!box) return;
|
||||||
|
const alt=encaixeAlt;
|
||||||
|
if(!it || !alt || ehFolha(it.modo) ||
|
||||||
|
Math.abs(alt.linhas-alt.forma)<1e-9){
|
||||||
|
box.hidden=true; box.innerHTML=''; return;
|
||||||
|
}
|
||||||
|
const efetivo = modoEncaixeEmUso();
|
||||||
|
const maior=Math.max(alt.linhas,alt.forma), menor=Math.min(alt.linhas,alt.forma);
|
||||||
|
const nCm=Math.round((maior-menor)*100);
|
||||||
|
const y=nCm/100*(it.unit||0);
|
||||||
|
const vence=alt.forma<=alt.linhas ? 'Misturado' : 'Agrupado';
|
||||||
|
const bt=(m,rot,sub)=>'<button type="button" class="cEncBt'+
|
||||||
|
(efetivo===m?' on':'')+'" data-enc="'+m+'" aria-pressed="'+(efetivo===m)+'">'+
|
||||||
|
'<b>'+rot+'</b><small>'+sub+'</small></button>';
|
||||||
|
box.hidden=false;
|
||||||
|
box.innerHTML='<div class="cEncBts" role="group" aria-label="Modo de encaixe">'+
|
||||||
|
bt('linhas','Agrupado','Mais fácil de cortar · '+fmtM(alt.linhas)+' m')+
|
||||||
|
bt('forma','Misturado','Menos filme · '+fmtM(alt.forma)+' m')+
|
||||||
|
'</div>'+
|
||||||
|
'<p class="cEncDif">'+vence+' usa '+nCm+' cm a menos ('+rs(y)+' a menos).</p>';
|
||||||
|
}
|
||||||
|
// C1 · o que ainda cabe na metragem já cobrada, sem aumentar o filme.
|
||||||
|
function pintaVao(it){
|
||||||
|
const box=$('cVao'); if(!box) return;
|
||||||
|
const lista=encaixeVao;
|
||||||
|
if(!it || ehFolha(it.modo) || !lista.length){
|
||||||
|
box.hidden=true; box.innerHTML=''; return;
|
||||||
|
}
|
||||||
|
const bts=lista.map(v=>{
|
||||||
|
const i=artes.indexOf(v.a);
|
||||||
|
return i<0?'':'<button type="button" class="cVaoBt" data-vao="'+i+'" data-k="'+v.k+'">+'+
|
||||||
|
v.k+' '+escapeHTML(nomeCurto(v.a.f.name))+'</button>';
|
||||||
|
}).join('');
|
||||||
|
if(!bts){ box.hidden=true; box.innerHTML=''; return; }
|
||||||
|
box.hidden=false;
|
||||||
|
box.innerHTML='<p class="cVaoT">Sem custo: cabem mais cópias nesta metragem.</p>'+
|
||||||
|
'<div class="cVaoBts">'+bts+'</div>';
|
||||||
|
}
|
||||||
function pintaCompra(){
|
function pintaCompra(){
|
||||||
const it=itemAtual;
|
const it=itemAtual;
|
||||||
|
if(!modo || !artes.length) modoEncaixe='auto';
|
||||||
vals.hidden=!it;
|
vals.hidden=!it;
|
||||||
add.disabled=!it || !itemPodeEnviar(it);
|
add.disabled=!it || !itemPodeEnviar(it);
|
||||||
|
pintaEncaixe(it); pintaVao(it);
|
||||||
if(!it) return;
|
if(!it) return;
|
||||||
$('cMetroLbl').textContent = it.extra ? 'Metro · com '+rs(it.extra)+' de arquivo manual' : 'Metro';
|
$('cMetroLbl').textContent = it.extra ? 'Metro · com '+rs(it.extra)+' de arquivo manual' : 'Metro';
|
||||||
$('cMetro').textContent=rs(it.unit);
|
$('cMetro').textContent=rs(it.unit);
|
||||||
$('cMetragem').textContent=fmtM(it.cob)+' m';
|
$('cMetragem').textContent=fmtM(it.cob)+' m';
|
||||||
const partes=ehFolha(it.modo) ? Math.ceil(it.metros/20) : 1;
|
// Partes de até 10 m (Marcus, 18/11/2026): o FlexiPRINT não abre mais que isso.
|
||||||
$('cPartes').textContent = partes>1 ? ' Sai em '+partes+' partes de até 20 m.' : '';
|
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);
|
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 =
|
$('cObs').textContent =
|
||||||
it.cob===MINIMO_M && it.metros<MINIMO_M
|
it.cob===MINIMO_M && it.metros<MINIMO_M
|
||||||
? (ehFolha(it.modo) ? 'Pedido mínimo de 1 m.'
|
? (ehFolha(it.modo) ? 'Pedido mínimo de 1 m.'
|
||||||
: 'Pedido mínimo de 1 m: ainda cabem '+sobraCm+' cm de artes sem custo.')
|
: '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);
|
$('cTotal').textContent=rs(it.total);
|
||||||
}
|
}
|
||||||
|
$('cEncaixe')?.addEventListener('click',e=>{
|
||||||
|
const b=e.target.closest('[data-enc]'); if(!b) return;
|
||||||
|
modoEncaixe=b.dataset.enc;
|
||||||
|
pintaCompra();
|
||||||
|
previaAoVivo();
|
||||||
|
});
|
||||||
|
$('cVao')?.addEventListener('click',e=>{
|
||||||
|
const b=e.target.closest('[data-vao]'); if(!b) return;
|
||||||
|
const a=artes[+b.dataset.vao]; if(!a) return;
|
||||||
|
a.q=Math.min(200,(a.q||1)+(+b.dataset.k||0));
|
||||||
|
encaixeVao=[];
|
||||||
|
const box=$('cVao'); box.hidden=true; box.innerHTML='';
|
||||||
|
pintaArtes();
|
||||||
|
});
|
||||||
add.addEventListener('click',()=>adicionaAoCarrinho());
|
add.addEventListener('click',()=>adicionaAoCarrinho());
|
||||||
addEventListener('dtf-cart-changed',pintaCompra);
|
addEventListener('dtf-cart-changed',pintaCompra);
|
||||||
|
window.pintaCompra=pintaCompra;
|
||||||
pintaCompra();
|
pintaCompra();
|
||||||
})();
|
})();
|
||||||
|
|||||||
@@ -136,6 +136,7 @@ const folhaTotalM=()=>{
|
|||||||
// Cada modo por metro tem o seu par de artes avulsas, e o seletor anda nos dois sentidos.
|
// Cada modo por metro tem o seu par de artes avulsas, e o seletor anda nos dois sentidos.
|
||||||
const PAR={file:'avulsa', avulsa:'file', uvfile:'uv', uv:'uvfile'};
|
const PAR={file:'avulsa', avulsa:'file', uvfile:'uv', uv:'uvfile'};
|
||||||
let montagemCm=0; // altura da folha montada pelo motor, em cm
|
let montagemCm=0; // altura da folha montada pelo motor, em cm
|
||||||
|
let modoEncaixe='auto'; // C2: 'auto', 'linhas' (Agrupado) ou 'forma' (Misturado)
|
||||||
let montagemLayout=null; // posições aprovadas de cada cópia, em cm
|
let montagemLayout=null; // posições aprovadas de cada cópia, em cm
|
||||||
let montagemFolhas=null; // artes avulsas separadas por traço (item 17)
|
let montagemFolhas=null; // artes avulsas separadas por traço (item 17)
|
||||||
let montagemFolgaCm=0.5; // a menor folga da montagem na largura
|
let montagemFolgaCm=0.5; // a menor folga da montagem na largura
|
||||||
@@ -206,11 +207,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);
|
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;
|
const larguraFilme=()=>MODOS[modo].larg;
|
||||||
// cobrança proporcional: arredonda para cima em 10 cm · 2,75 m vira 2,80 m
|
// Cobrança a cada 10 cm, com 8 mm a favor do cliente (Marcus, 27/11/2026):
|
||||||
const cobrar=m=>Math.max(MINIMO_M, Math.ceil(m*10)/10);
|
// 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
|
// 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.
|
// 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 cobrarMontagem=()=>!ehFolha() && montagemFolhas ? cobrarFolhas(montagemFolhas) : cobrar(metros);
|
||||||
const fmtM=m=>m.toFixed(2).replace('.',',');
|
const fmtM=m=>m.toFixed(2).replace('.',',');
|
||||||
const cls=n=>n>=85?'ok':n>=50?'av':'er';
|
const cls=n=>n>=85?'ok':n>=50?'av':'er';
|
||||||
@@ -218,3 +224,7 @@ const dpiDe=a=>a.cm>0? (a.giro?a.py:a.px)/(a.cm/2.54) : 0;
|
|||||||
// girar 90° inverte a proporção · espelhar não muda medida, só o desenho
|
// girar 90° inverte a proporção · espelhar não muda medida, só o desenho
|
||||||
const propDe=a=>{ const p=a.prop||1; return a.giro? 1/p : p; };
|
const propDe=a=>{ const p=a.prop||1; return a.giro? 1/p : p; };
|
||||||
const TAMANHOS={57:[10,15,20,25,28.2], 27:[5,8,10,13,26.7]};
|
const TAMANHOS={57:[10,15,20,25,28.2], 27:[5,8,10,13,26.7]};
|
||||||
|
// "12x nome.png" já entra com 12 cópias (Rodada 5, B6; a BinnFlow faz assim):
|
||||||
|
// até 3 dígitos, um x e um separador, para "1920x1080.png" não virar cópias.
|
||||||
|
const copiasDoNome=nome=>{ const m=/^(\d{1,3})\s*[xX×][\s_-]+\S/.exec(nome||'');
|
||||||
|
return m? Math.max(1,Math.min(200,+m[1]||1)) : 1; };
|
||||||
|
|||||||
@@ -13,8 +13,8 @@ $('qOk').addEventListener('click',()=>{
|
|||||||
if($('qOk').disabled) return;
|
if($('qOk').disabled) return;
|
||||||
if(!$('prev').classList.contains('on')){ adicionaAoCarrinho(); return; }
|
if(!$('prev').classList.contains('on')){ adicionaAoCarrinho(); return; }
|
||||||
const ok=$('ciente').classList.contains('on');
|
const ok=$('ciente').classList.contains('on');
|
||||||
qm(ok? '<b>Registrado.</b> Você confirmou que viu a ressalva de resolução.'
|
qm(ok? '<b>Ressalva aceita.</b> Confira a folha montada abaixo.'
|
||||||
: '<b>Certo.</b> Confira a folha montada abaixo.','var(--tx)');
|
: 'Confira a folha montada abaixo.','var(--tx)');
|
||||||
$('prev').scrollIntoView({behavior:'smooth',block:'start'});
|
$('prev').scrollIntoView({behavior:'smooth',block:'start'});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -95,8 +95,8 @@ function recusaFolha(x, md){
|
|||||||
folhas=folhas.filter(y=>y!==x);
|
folhas=folhas.filter(y=>y!==x);
|
||||||
pintaFolha();
|
pintaFolha();
|
||||||
avisoTipo('<b>'+escapeHTML(arquivo.name)+' não é uma folha montada.</b> '+
|
avisoTipo('<b>'+escapeHTML(arquivo.name)+' não é uma folha montada.</b> '+
|
||||||
'Para ocupar os '+n1(larguraFilme())+' cm do filme ela teria só '+md.dpiFolha+
|
'Nos '+n1(larguraFilme())+' cm do filme ela teria só '+md.dpiFolha+
|
||||||
' DPI, e o mínimo para imprimir é '+DPI_RECUSA+'. '+
|
' DPI, abaixo do mínimo de '+DPI_RECUSA+'. '+
|
||||||
'Se for uma arte para montarmos, use <b>'+MODOS[destino].tit+'</b>, '+
|
'Se for uma arte para montarmos, use <b>'+MODOS[destino].tit+'</b>, '+
|
||||||
'a '+rs(PRECO[destino])+' o metro. '+
|
'a '+rs(PRECO[destino])+' o metro. '+
|
||||||
'<button type="button" id="usarAvulsa">Enviar como '+MODOS[destino].tit.toLowerCase()+'</button>');
|
'<button type="button" id="usarAvulsa">Enviar como '+MODOS[destino].tit.toLowerCase()+'</button>');
|
||||||
|
|||||||
@@ -83,6 +83,20 @@ function marcaDagua(ctx,w,h){
|
|||||||
}
|
}
|
||||||
ctx.restore();
|
ctx.restore();
|
||||||
}
|
}
|
||||||
|
async function cargasDe(lista){
|
||||||
|
const itens=lista.map((a,sourceIndex)=>({...a,sourceIndex}));
|
||||||
|
const imagens=await Promise.all(itens.map(a=>imagemDaArte(a).then(img=>({a,img}))));
|
||||||
|
const cargas=imagens.flatMap(c=>Array.from({length:c.a.q||1},(_,copyIndex)=>({...c,copyIndex})));
|
||||||
|
cargas.forEach(c=>{
|
||||||
|
c.w = c.a.cm; // o motor trabalha em centímetros
|
||||||
|
// The file's own proportion: a large artwork is drawn from a smaller copy.
|
||||||
|
const prop = c.a.prop>0 ? c.a.prop : c.img ? c.img.height/c.img.width : 1;
|
||||||
|
c.h = c.w * (c.a.giro? 1/prop : prop);
|
||||||
|
c.travado = !!c.a.giro; // giro do cliente manda no encaixe
|
||||||
|
});
|
||||||
|
return cargas;
|
||||||
|
}
|
||||||
|
|
||||||
function desenhaMontagem(area,lista,mts,W,fora,aoTerminar){
|
function desenhaMontagem(area,lista,mts,W,fora,aoTerminar){
|
||||||
const versao=area.montagemVersao=(area.montagemVersao||0)+1;
|
const versao=area.montagemVersao=(area.montagemVersao||0)+1;
|
||||||
const filme=larguraFilme(), PX_CM=W/filme;
|
const filme=larguraFilme(), PX_CM=W/filme;
|
||||||
@@ -90,22 +104,14 @@ function desenhaMontagem(area,lista,mts,W,fora,aoTerminar){
|
|||||||
if(fora) fora.innerHTML='';
|
if(fora) fora.innerHTML='';
|
||||||
if(!itens.length){
|
if(!itens.length){
|
||||||
area.innerHTML='<div class="semmont"><b>A montagem aparece aqui</b>'+
|
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});
|
if(aoTerminar) aoTerminar({alturaCm:0, uso:0, girou:0});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
Promise.all(itens.map(a=>imagemDaArte(a).then(img=>({a,img})))).then(imagens=>{
|
cargasDe(lista).then(cargas=>{
|
||||||
if(area.montagemVersao!==versao) return;
|
if(area.montagemVersao!==versao) return;
|
||||||
const cargas=imagens.flatMap(c=>Array.from({length:c.a.q||1},(_,copyIndex)=>({...c,copyIndex})));
|
const enc=encaixar(cargas,filme,modoEncaixe);
|
||||||
cargas.forEach(c=>{
|
|
||||||
c.w = c.a.cm; // o motor trabalha em centímetros
|
|
||||||
// The file's own proportion: a large artwork is drawn from a smaller copy.
|
|
||||||
const prop = c.a.prop>0 ? c.a.prop : c.img ? c.img.height/c.img.width : 1;
|
|
||||||
c.h = c.w * (c.a.giro? 1/prop : prop);
|
|
||||||
c.travado = !!c.a.giro; // giro do cliente manda no encaixe
|
|
||||||
});
|
|
||||||
const enc=encaixar(cargas,filme);
|
|
||||||
const alturaCm=enc.altura;
|
const alturaCm=enc.altura;
|
||||||
const pos=enc.pos.map(p=>({...p, x:p.x*PX_CM, y:p.y*PX_CM, w:p.w*PX_CM, h:p.h*PX_CM}));
|
const pos=enc.pos.map(p=>({...p, x:p.x*PX_CM, y:p.y*PX_CM, w:p.w*PX_CM, h:p.h*PX_CM}));
|
||||||
const altura=alturaCm*PX_CM;
|
const altura=alturaCm*PX_CM;
|
||||||
@@ -148,8 +154,8 @@ function desenhaMontagem(area,lista,mts,W,fora,aoTerminar){
|
|||||||
el.className = uso>=70? 'usoBom' : 'usoRuim';
|
el.className = uso>=70? 'usoBom' : 'usoRuim';
|
||||||
el.innerHTML = (uso>=70
|
el.innerHTML = (uso>=70
|
||||||
? '<b>'+uso+'% da folha virou arte</b> bom aproveitamento'
|
? '<b>'+uso+'% da folha virou arte</b> bom aproveitamento'
|
||||||
: '<b>'+uso+'% da folha virou arte</b> dá para melhorar: artes de larguras parecidas '+
|
: '<b>'+uso+'% da folha virou arte</b> artes de larguras parecidas '+
|
||||||
'se encaixam melhor lado a lado')
|
'encaixam melhor lado a lado')
|
||||||
+ (girou? ' · <b style="display:inline">'+girou+
|
+ (girou? ' · <b style="display:inline">'+girou+
|
||||||
(girou>1?' artes giradas':' arte girada')+' 90°</b> para caber melhor':'');
|
(girou>1?' artes giradas':' arte girada')+' 90°</b> para caber melhor':'');
|
||||||
(fora||area).appendChild(el);
|
(fora||area).appendChild(el);
|
||||||
@@ -160,10 +166,111 @@ function desenhaMontagem(area,lista,mts,W,fora,aoTerminar){
|
|||||||
|
|
||||||
function previaArtes(){ desenhaMontagem($('pArea'), artes, metros, 560); }
|
function previaArtes(){ desenhaMontagem($('pArea'), artes, metros, 560); }
|
||||||
|
|
||||||
|
// C1/C2 simulam encaixes que não vão para a tela: só a altura, com a mesma
|
||||||
|
// regra de encaixar (web/packing.js) e sem as máscaras que a prévia desenha,
|
||||||
|
// que custam metade do tempo. A montagem desenhada é a única que passa por
|
||||||
|
// encaixar.
|
||||||
|
function alturaSimulada(cargas,W,modo){
|
||||||
|
if(cargas.some(p=>!Number.isFinite(p.w) || p.w<=0 || p.w>W)) throw new RangeError('largura');
|
||||||
|
if(modo==='forma') return encaixarComMargens(cargas,W).altura;
|
||||||
|
const linhas=encaixarEmLinhas(cargas,W).altura;
|
||||||
|
if(modo==='linhas') return linhas;
|
||||||
|
const forma=encaixarComMargens(cargas,W).altura;
|
||||||
|
return forma<=linhas-GANHO_FORMA_CM ? forma : linhas;
|
||||||
|
}
|
||||||
|
// Acima disso o cálculo do vão pesa no celular e a sobra é pequena.
|
||||||
|
const VAO_MAX_PECAS=300;
|
||||||
|
// C2 · as mesmas peças nas duas formas de encaixar, já na metragem cobrada.
|
||||||
|
// Com as folhas de traço, cada folha arredonda sozinha e a soma tem o mínimo de 1 m.
|
||||||
|
let encaixeAlt=null; // {linhas, forma, alturasLinhas, alturasForma}
|
||||||
|
let encaixeVao=[]; // C1: [{a,k}] cópias que cabem sem custo
|
||||||
|
let tVao=null;
|
||||||
|
function metragemDasAlturas(alturas){
|
||||||
|
return cobrarFolhas(alturas.map(alturaCm=>({alturaCm})));
|
||||||
|
}
|
||||||
|
function alternativasDasCargas(grupos){
|
||||||
|
const filme=larguraFilme();
|
||||||
|
const alturas=modo=>grupos.map(cs=>alturaSimulada(cs,filme,modo));
|
||||||
|
const li=alturas('linhas'), fo=alturas('forma');
|
||||||
|
// Em automático cada folha fica pela forma só se ela encurta GANHO_FORMA_CM
|
||||||
|
// (web/packing.js): o botão marcado é o encaixe que está na tela.
|
||||||
|
const peloMotor=li.map((h,i)=>fo[i]<=h-GANHO_FORMA_CM ? 'forma' : 'linhas');
|
||||||
|
const auto=peloMotor.every(m=>m==='forma') ? 'forma' : peloMotor.every(m=>m==='linhas') ? 'linhas' : null;
|
||||||
|
return {linhas:metragemDasAlturas(li), forma:metragemDasAlturas(fo),
|
||||||
|
alturasLinhas:li, alturasForma:fo, auto};
|
||||||
|
}
|
||||||
|
function modoEncaixeEmUso(){
|
||||||
|
if(modoEncaixe!=='auto') return modoEncaixe;
|
||||||
|
return encaixeAlt ? encaixeAlt.auto : null;
|
||||||
|
}
|
||||||
|
function podeEncaixe(){
|
||||||
|
return !!modo && !ehFolha() && artes.length>0 &&
|
||||||
|
artes.every(a=>a.cm>0 && a.cm<=larguraFilme() && a.src && !a.semPrevia);
|
||||||
|
}
|
||||||
|
function pintaEncaixeUI(){
|
||||||
|
if(typeof window.pintaCompra==='function') window.pintaCompra();
|
||||||
|
}
|
||||||
|
async function preparaEncaixe(listas,versao){
|
||||||
|
if(!podeEncaixe() || !listas.length){
|
||||||
|
encaixeAlt=null; encaixeVao=[]; pintaEncaixeUI(); return;
|
||||||
|
}
|
||||||
|
let grupos;
|
||||||
|
try{ grupos=await Promise.all(listas.map(cargasDe)); }
|
||||||
|
catch(e){ return; }
|
||||||
|
if($('vArea').montagemVersao!==versao) return;
|
||||||
|
try{ encaixeAlt=alternativasDasCargas(grupos); }
|
||||||
|
catch(e){ encaixeAlt=null; encaixeVao=[]; pintaEncaixeUI(); return; }
|
||||||
|
encaixeVao=[];
|
||||||
|
pintaEncaixeUI();
|
||||||
|
clearTimeout(tVao);
|
||||||
|
tVao=setTimeout(()=>calculaVao(listas,grupos,versao),0);
|
||||||
|
}
|
||||||
|
async function calculaVao(listas,grupos,versao){
|
||||||
|
if(!encaixeAlt || $('vArea').montagemVersao!==versao) return;
|
||||||
|
// O mesmo encaixe que montou a folha na tela, automático incluído: o que
|
||||||
|
// cabe "sem custo" é medido contra a metragem cobrada de verdade.
|
||||||
|
const modo=modoEncaixe;
|
||||||
|
let base;
|
||||||
|
if(grupos.reduce((t,cs)=>t+cs.length,0)>VAO_MAX_PECAS) return;
|
||||||
|
try{ base=grupos.map(cs=>alturaSimulada(cs,larguraFilme(),modo)); }catch(e){ return; }
|
||||||
|
const alvo=metragemDasAlturas(base);
|
||||||
|
const cands=artes.filter(a=>(a.q||1)>=1).sort((a,b)=>(b.q||1)-(a.q||1)).slice(0,5);
|
||||||
|
const achados=[];
|
||||||
|
for(const a of cands){
|
||||||
|
await new Promise(r=>setTimeout(r,0));
|
||||||
|
if($('vArea').montagemVersao!==versao) return;
|
||||||
|
const gi=listas.findIndex(l=>l.includes(a));
|
||||||
|
if(gi<0) continue;
|
||||||
|
const q=Math.max(1,a.q||1), limite=Math.min(30,200-q);
|
||||||
|
if(limite<1) continue;
|
||||||
|
const testa=async k=>{
|
||||||
|
await new Promise(r=>setTimeout(r,0)); // a página respira entre as montagens
|
||||||
|
const lista=listas[gi].map(x=>x===a?{...x,q:q+k}:x);
|
||||||
|
const cargas=await cargasDe(lista);
|
||||||
|
let altura;
|
||||||
|
try{ altura=alturaSimulada(cargas,larguraFilme(),modo); }catch(e){ return Infinity; }
|
||||||
|
const alturas=base.slice(); alturas[gi]=altura;
|
||||||
|
return metragemDasAlturas(alturas);
|
||||||
|
};
|
||||||
|
let lo=1, hi=limite, k=0;
|
||||||
|
while(lo<=hi){
|
||||||
|
const mid=(lo+hi)>>1;
|
||||||
|
const total=await testa(mid);
|
||||||
|
if($('vArea').montagemVersao!==versao) return;
|
||||||
|
if(Math.abs(total-alvo)<1e-9){ k=mid; lo=mid+1; } else hi=mid-1;
|
||||||
|
}
|
||||||
|
if(k>=1) achados.push({a,k});
|
||||||
|
}
|
||||||
|
if($('vArea').montagemVersao!==versao) return;
|
||||||
|
encaixeVao=achados.sort((x,y)=>y.k-x.k).slice(0,3);
|
||||||
|
pintaEncaixeUI();
|
||||||
|
}
|
||||||
|
|
||||||
// montagem ao vivo, ao lado da fila · redesenha 140 ms depois da ultima mexida
|
// montagem ao vivo, ao lado da fila · redesenha 140 ms depois da ultima mexida
|
||||||
let tMont=null;
|
let tMont=null;
|
||||||
function previaAoVivo(){
|
function previaAoVivo(){
|
||||||
clearTimeout(tMont);
|
clearTimeout(tMont);
|
||||||
|
if(!artes.length){ modoEncaixe='auto'; encaixeAlt=null; encaixeVao=[]; }
|
||||||
montagemLayout=null;
|
montagemLayout=null;
|
||||||
$('vArea').montagemVersao=($('vArea').montagemVersao||0)+1;
|
$('vArea').montagemVersao=($('vArea').montagemVersao||0)+1;
|
||||||
if(!ehFolha()) $('bAmpliar').hidden=true;
|
if(!ehFolha()) $('bAmpliar').hidden=true;
|
||||||
@@ -208,9 +315,9 @@ function previaAoVivo(){
|
|||||||
? medidas.length+' folhas · '+fmtM(tot)+' m'
|
? medidas.length+' folhas · '+fmtM(tot)+' m'
|
||||||
: n1(medidas[0].med.larg)+' × '+n1(medidas[0].med.alt)+' cm')+'</b>'+
|
: 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)+
|
'<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>'+
|
: '<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;
|
return;
|
||||||
}
|
}
|
||||||
@@ -231,6 +338,8 @@ function previaAoVivo(){
|
|||||||
$('vMt').textContent = r.alturaCm? fmtM(cobrar(r.alturaCm/100))+' m' : '—';
|
$('vMt').textContent = r.alturaCm? fmtM(cobrar(r.alturaCm/100))+' m' : '—';
|
||||||
resumoArtes(); // o resumo lê a mesma folha
|
resumoArtes(); // o resumo lê a mesma folha
|
||||||
agendaAvaliacao(); // a nota só sai com a metragem pronta
|
agendaAvaliacao(); // a nota só sai com a metragem pronta
|
||||||
|
// C1/C2 depois, sem segurar a conferência nem o botão de compra.
|
||||||
|
preparaEncaixe([prontas],$('vArea').montagemVersao).catch(()=>{});
|
||||||
});
|
});
|
||||||
$('vArea').scrollTop=0;
|
$('vArea').scrollTop=0;
|
||||||
},140);
|
},140);
|
||||||
@@ -257,7 +366,7 @@ function montaFolhasDeTraco(grupos,W){
|
|||||||
figura.append(legenda,desenho); painel.append(figura);
|
figura.append(legenda,desenho); painel.append(figura);
|
||||||
desenhaMontagem(desenho, lista, 0, W, uso, r=>{
|
desenhaMontagem(desenho, lista, 0, W, uso, r=>{
|
||||||
if(area.montagemVersao!==versao) return; // a montagem mudou nesse meio-tempo
|
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,
|
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};
|
layout:r.placements ? {height_cm:+r.alturaCm.toFixed(4), placements:r.placements} : null};
|
||||||
if(feitas.filter(Boolean).length<grupos.length) return;
|
if(feitas.filter(Boolean).length<grupos.length) return;
|
||||||
@@ -268,24 +377,12 @@ function montaFolhasDeTraco(grupos,W){
|
|||||||
$('vMt').textContent=montagemFolhas ? fmtM(cobrarFolhas(montagemFolhas))+' m' : '—';
|
$('vMt').textContent=montagemFolhas ? fmtM(cobrarFolhas(montagemFolhas))+' m' : '—';
|
||||||
resumoArtes();
|
resumoArtes();
|
||||||
agendaAvaliacao();
|
agendaAvaliacao();
|
||||||
|
preparaEncaixe(grupos,versao).catch(()=>{});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
area.replaceChildren(painel);
|
area.replaceChildren(painel);
|
||||||
}
|
}
|
||||||
|
|
||||||
function motivoNota(){
|
|
||||||
if(!nota) return 'sem nota ainda · a conferência roda na sala 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';
|
|
||||||
const pior=ruins.reduce((p,a)=>dpiDe(a)<dpiDe(p)?a:p);
|
|
||||||
return 'nota '+nota+' · '+ruins.length+(ruins.length>1?' artes abaixo':' arte abaixo')+
|
|
||||||
' de 300 DPI · a menor é "'+pior.f.name+'" com '+
|
|
||||||
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ê';
|
|
||||||
}
|
|
||||||
function previa(){
|
function previa(){
|
||||||
const T=window.dtfTimings;
|
const T=window.dtfTimings;
|
||||||
if(T && T.montageStart!=null && T.montageEnd==null) T.montageEnd=performance.now();
|
if(T && T.montageStart!=null && T.montageEnd==null) T.montageEnd=performance.now();
|
||||||
@@ -301,12 +398,11 @@ function previa(){
|
|||||||
['var(--verde)','✓','Espaço entre artes', montagemFolgaCm>=MARGEM_CM-1e-9
|
['var(--verde)','✓','Espaço entre artes', montagemFolgaCm>=MARGEM_CM-1e-9
|
||||||
? '5 mm entre as artes e nas bordas'
|
? '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'],
|
: n1(montagemFolgaCm*10)+' mm · 5 mm não cabem na largura, a sobra fica dividida por igual'],
|
||||||
['var(--verde)','✓','Metragem proporcional',
|
['var(--verde)','✓','Metragem',
|
||||||
'sua folha tem '+fmtM(metros)+' m e você paga '+fmtM(cob)+
|
'sua folha tem '+fmtM(metros)+' m e você paga '+fmtM(cob)+' m · cobramos a cada 10 cm'],
|
||||||
' m · arredondamos só até os 10 cm mais próximos'],
|
|
||||||
];
|
];
|
||||||
linhas.push(['var(--verde)','+','Identificação do pedido',
|
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=>
|
$('pInfo').innerHTML=linhas.map(l=>
|
||||||
'<div class="li"><span class="c" style="background:'+l[0]+
|
'<div class="li"><span class="c" style="background:'+l[0]+
|
||||||
(l[0]==='var(--laranja)'?';color:#241703':'')+'">'+l[1]+'</span>'+
|
(l[0]==='var(--laranja)'?';color:#241703':'')+'">'+l[1]+'</span>'+
|
||||||
@@ -315,5 +411,5 @@ function previa(){
|
|||||||
$('pArea').innerHTML='<div class="carregando">montando a prévia…</div>';
|
$('pArea').innerHTML='<div class="carregando">montando a prévia…</div>';
|
||||||
try{ previaArtes(); }
|
try{ previaArtes(); }
|
||||||
catch(e){ $('pArea').innerHTML='<div class="semprev"><b>Prévia indisponível</b>'+
|
catch(e){ $('pArea').innerHTML='<div class="semprev"><b>Prévia indisponível</b>'+
|
||||||
'O arquivo será processado normalmente.</div>'; }
|
'O pedido segue normalmente.</div>'; }
|
||||||
}
|
}
|
||||||
|
|||||||
117
web/site-pdf.js
117
web/site-pdf.js
@@ -192,6 +192,30 @@ async function dimensoesImagem(file){
|
|||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
// The PNG may record its own resolution in the pHYs chunk. A loose art that
|
||||||
|
// says 200 DPI or more has a real size in pixels ÷ DPI, offered as "Manter";
|
||||||
|
// below 200 DPI, or without the chunk, it says nothing. Never throws.
|
||||||
|
async function dpiSalvoPng(file){
|
||||||
|
try{
|
||||||
|
if(!file || !(file.size>0)) return null;
|
||||||
|
const b=new Uint8Array(await file.slice(0,Math.min(file.size,4*1048576)).arrayBuffer());
|
||||||
|
if(!(b.length>=8 && b[0]===0x89 && b[1]===0x50 && b[2]===0x4E && b[3]===0x47)) return null;
|
||||||
|
const u32=i=>((b[i]<<24)>>>0)+(b[i+1]<<16)+(b[i+2]<<8)+b[i+3];
|
||||||
|
let i=8;
|
||||||
|
while(i+12<=b.length){
|
||||||
|
const len=u32(i), tipo=String.fromCharCode(...b.slice(i+4,i+8));
|
||||||
|
if(tipo==='pHYs'){
|
||||||
|
if(len<9 || i+8+len>b.length) return null;
|
||||||
|
const ppmX=u32(i+8), ppmY=u32(i+12), unidade=b[i+16];
|
||||||
|
if(unidade===1 && ppmX>0 && ppmX===ppmY) return Math.round(ppmX*0.0254);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if(tipo==='IDAT' || tipo==='IEND') return null;
|
||||||
|
i+=12+len;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}catch(e){ return null; }
|
||||||
|
}
|
||||||
// A small copy of a large PNG, read as a stream: the file is inflated in
|
// A small copy of a large PNG, read as a stream: the file is inflated in
|
||||||
// pieces and only every n-th pixel of every n-th row is kept, so memory stays
|
// pieces and only every n-th pixel of every n-th row is kept, so memory stays
|
||||||
// at a few MB whatever the file's size. It is the preview. Given the sheet's
|
// at a few MB whatever the file's size. It is the preview. Given the sheet's
|
||||||
@@ -378,29 +402,29 @@ function medirFolha(file){
|
|||||||
verbosity:0}).promise;
|
verbosity:0}).promise;
|
||||||
if(doc.numPages!==1)
|
if(doc.numPages!==1)
|
||||||
return {rejected:true, reason:'O PDF tem '+doc.numPages+
|
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 page=await doc.getPage(1);
|
||||||
const view=page.view, unit=page.userUnit, vp=page.getViewport({scale:1});
|
const view=page.view, unit=page.userUnit, vp=page.getViewport({scale:1});
|
||||||
if(!Array.isArray(view) || view.length!==4 ||
|
if(!Array.isArray(view) || view.length!==4 ||
|
||||||
!Number.isFinite(unit) || unit<=0 ||
|
!Number.isFinite(unit) || unit<=0 ||
|
||||||
!Number.isFinite(vp.width) || !Number.isFinite(vp.height) ||
|
!Number.isFinite(vp.width) || !Number.isFinite(vp.height) ||
|
||||||
vp.width<=0 || vp.height<=0)
|
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]);
|
const ptW=Math.abs(view[2]-view[0]), ptH=Math.abs(view[3]-view[1]);
|
||||||
if(!(ptW>0 && ptH>0) ||
|
if(!(ptW>0 && ptH>0) ||
|
||||||
(unit===1 && (ptW>PDF_MAX_PT || ptH>PDF_MAX_PT)))
|
(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;
|
// This pinned PDF.js build exposes the page's rotated view in points;
|
||||||
// userUnit is separate and must scale both physical dimensions.
|
// userUnit is separate and must scale both physical dimensions.
|
||||||
const w=vp.width*unit*PT_CM, h=vp.height*unit*PT_CM;
|
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)
|
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
|
// Keep precise geometry for the fit and quote; the UI rounds only
|
||||||
// when displaying dimensions.
|
// when displaying dimensions.
|
||||||
return {larg:+w.toFixed(3), alt:+h.toFixed(3),
|
return {larg:+w.toFixed(3), alt:+h.toFixed(3),
|
||||||
fonte:'página do PDF'+(unit!==1 ? ' · UserUnit '+unit : '')};
|
fonte:'página do PDF'+(unit!==1 ? ' · UserUnit '+unit : '')};
|
||||||
}).then(res).catch(()=>res({rejected:true,
|
}).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(()=>{}); });
|
.finally(()=>{ if(doc) doc.destroy().catch(()=>{}); });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -463,7 +487,7 @@ function chipsDaFolha(a,aceito){
|
|||||||
return dpi+chip('ok','Fundo transparente')+
|
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':''):''))
|
(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'))+
|
: 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
|
// 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
|
// quantos pontos, onde estão e o que fazer, sem "arquivo com problema". O
|
||||||
@@ -471,20 +495,20 @@ function chipsDaFolha(a,aceito){
|
|||||||
function avisosDaFolha(a,nome,i,aceito,aceitavel=false){
|
function avisosDaFolha(a,nome,i,aceito,aceitavel=false){
|
||||||
if(a.grande) return '';
|
if(a.grande) return '';
|
||||||
if(a.fundoChapado) return /\.jpe?g$/i.test(nome||'')
|
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 '+
|
? '<p class="avisoF"><b>JPG não tem fundo transparente.</b> O fundo sai branco no filme. '+
|
||||||
'no filme. Exporte a folha em PNG ou PDF, com fundo transparente, e envie de novo.</p>'
|
'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> O que parece branco na tela sai '+
|
: '<p class="avisoF"><b>O fundo da sua folha não é transparente.</b> Ele sai impresso no filme. '+
|
||||||
'branco no filme. Exporte a folha com fundo transparente, em PNG ou PDF, e envie de novo.</p>';
|
'Exporte com fundo transparente, em PNG ou PDF, e envie de novo.</p>';
|
||||||
if(!a.residuos) return '';
|
if(!a.residuos) return '';
|
||||||
const n=a.residuos, varios=n>1;
|
const n=a.residuos, varios=n>1;
|
||||||
const aceite='<label class="aceiteRes"><input type="checkbox" data-residuo="'+i+'"'+(aceito?' checked':'')+'>'+
|
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;
|
if(aceitavel && aceito) return aceite;
|
||||||
return '<p class="avisoF"><b>'+(varios?'Sobraram ':'Sobrou ')+n+(varios?' pontos':' ponto')+
|
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 '+
|
' de recorte na sua folha.</b> Não aparece'+(varios?'m':'')+' na tela, mas sai'+(varios?'em':'')+' impresso'+(varios?'s':'')+'. '+
|
||||||
'impressora enxerga e imprime. Apague '+(varios?'os pontos':'o ponto')+' na ferramenta que você '+
|
(varios?'Os círculos vermelhos na prévia mostram onde estão':'O círculo vermelho na prévia mostra onde está')+
|
||||||
'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á.')+
|
': apague e envie de novo.'+
|
||||||
(aceitavel?' Se '+(varios?'os pontos são':'o ponto é')+' da própria arte, marque abaixo.</p>'+aceite:'</p>');
|
(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
|
// 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
|
// warning, the customer may hand this art to the designer. One service per
|
||||||
@@ -511,21 +535,21 @@ function ajusteLinha(i,attr){
|
|||||||
const marcado=ajusteTudo || !!x.ajuste;
|
const marcado=ajusteTudo || !!x.ajuste;
|
||||||
linha+='<label class="aceiteRes ajusteArte"><input type="checkbox" '+attr+'="'+i+'"'+
|
linha+='<label class="aceiteRes ajusteArte"><input type="checkbox" '+attr+'="'+i+'"'+
|
||||||
(marcado?' checked':'')+'>'+
|
(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){
|
if(redesenhado){
|
||||||
const attrRedesenhado=folha?'data-redesenho':'data-redesenhoa';
|
const attrRedesenhado=folha?'data-redesenho':'data-redesenhoa';
|
||||||
linha+='<label class="aceiteRes ajusteArte"><input type="checkbox" '+attrRedesenhado+'="'+i+'"'+
|
linha+='<label class="aceiteRes ajusteArte"><input type="checkbox" '+attrRedesenhado+'="'+i+'"'+
|
||||||
(x.redesenho?' checked':'')+'>'+
|
(x.redesenho?' checked':'')+'>'+
|
||||||
'<span>Precisa redesenhar ou vetorizar? <b>Ajuste Fino Redesenho</b> — '+rs(TAXA_REDESENHO)+
|
'<span><b>Ajuste Fino Redesenho</b>: redesenhamos ou vetorizamos esta arte por '+rs(TAXA_REDESENHO)+
|
||||||
' (com prévia, +48 h)</span></label>';
|
', com prévia e 48 h a mais</span></label>';
|
||||||
}
|
}
|
||||||
return linha;
|
return linha;
|
||||||
}
|
}
|
||||||
function detalhesDaFolha(a,i,aberto){
|
function detalhesDaFolha(a,i,aberto){
|
||||||
const linhas = a.grande
|
const linhas = a.grande
|
||||||
? ['Resolução '+a.dpi+' DPI, lida do arquivo',
|
? ['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',
|
: [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'
|
'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'),
|
: a.fonteDpi==='vetor'? 'arte vetorial, sem imagem embutida' : 'lida do arquivo'),
|
||||||
@@ -568,20 +592,17 @@ function pintaFolha(){
|
|||||||
// Over 150 MB the browser cannot check a PDF: said before payment, as
|
// Over 150 MB the browser cannot check a PDF: said before payment, as
|
||||||
// for a file opened by hand (Dropstar, 2026-10-23).
|
// for a file opened by hand (Dropstar, 2026-10-23).
|
||||||
(x.pdfGrande? '<span class="chipSo">Conferência manual · sem conferência no site</span>'+
|
(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: '+
|
'<p class="repTxt">O site não confere PDF acima de 150 MB: a equipe confere antes de imprimir, '+
|
||||||
'resíduo de recorte, fundo e resolução ficam para a equipe, que abre antes de imprimir, e o '+
|
'e o pedido pode voltar depois de pago. '+
|
||||||
'pedido pode voltar depois de pago. '+
|
'Em <b>PNG</b> ou num PDF menor, a conferência sai aqui, antes de pagar.</p>' : '')+
|
||||||
'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 de 508 cm, o limite do formato.</b> '+
|
||||||
(suspeito? '<p class="avisoF"><b>Este PDF passa do tamanho que o formato comporta.</b> '+
|
'O seu tem '+n1(x.med.alt)+' cm e só abre certo no programa que o gerou, então precisaria do Ajuste Fino. '+
|
||||||
'A especificação para em 508 cm e o seu tem '+n1(x.med.alt)+' cm. '+
|
'Envie em <b>PNG ou TIFF</b>, ou divida em partes de até 5 m.</p>':'')+
|
||||||
'Ele abre certo só em quem o gerou — aqui vai precisar do Ajuste Fino. '+
|
(larga? '<p class="avisoF"><b>Esta folha não cabe neste filme.</b> Ela tem '+n1(x.med.larg)+
|
||||||
'Manda em <b>PNG ou TIFF</b>, ou divide em partes de até 5 m, que sai na hora.</p>':'')+
|
' cm de largura e o filme tem '+n1(L)+' cm. Reduzir a folha reduziria cada arte.'+
|
||||||
(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.'+
|
|
||||||
(x.med.larg<=57.5
|
(x.med.larg<=57.5
|
||||||
? ' Ela cabe no <b>DTF têxtil de 57 cm</b> — troque de produto ali em cima.'
|
? ' Ela cabe no <b>DTF têxtil de 57 cm</b>: troque de produto acima.'
|
||||||
: ' Remonte a folha em '+n1(L)+' cm e suba de novo.')+'</p>':'');
|
: ' Remonte a folha em '+n1(L)+' cm e envie de novo.')+'</p>':'');
|
||||||
}else if(x.measurementError){
|
}else if(x.measurementError){
|
||||||
medida='<span class="repPeso">'+escapeHTML(extDe(x.f.name))+' · '+fmt(x.f.size)+'</span>'+
|
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>';
|
'<p class="avisoF"><b>Este arquivo não pode ser orçado.</b> '+escapeHTML(x.measurementError)+'</p>';
|
||||||
@@ -589,13 +610,13 @@ function pintaFolha(){
|
|||||||
// Só a abertura manual muda o metro (TAXA_MANUAL); a nota não mexe no preço.
|
// 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;
|
const dif=(x.m>0)? TAXA_MANUAL*cobrar(x.m*(x.rep||1)) : 0;
|
||||||
medida='<span class="chipSo">Conferência manual</span>'+
|
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'+
|
'confere antes de imprimir'+
|
||||||
(TAXA_MANUAL? ' e o metro sai a <b>'+rs(precoMetro()+TAXA_MANUAL)+'</b>, com <b>'+rs(TAXA_MANUAL)+
|
(TAXA_MANUAL? ' e o metro sai a <b>'+rs(precoMetro()+TAXA_MANUAL)+'</b>, com <b>'+rs(TAXA_MANUAL)+
|
||||||
'</b> pela abertura 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>'+
|
(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>'+
|
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+'" '+
|
'<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>';
|
'placeholder="0,00" value="'+(x.m? x.m.toFixed(2):'')+'"><i>m</i></span></div>';
|
||||||
@@ -605,8 +626,8 @@ function pintaFolha(){
|
|||||||
'<span class="progT">'+textoProgresso(x)+'</span>'
|
'<span class="progT">'+textoProgresso(x)+'</span>'
|
||||||
: x.semAnalise
|
: x.semAnalise
|
||||||
? '<div class="progF"><b>Não conseguimos conferir esta folha.</b> '+escapeHTML(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 '+
|
'. A equipe confere antes de imprimir. Para ver a resolução aqui, exporte '+
|
||||||
'folha em <b>PNG</b>.</div>'
|
'em <b>PNG</b>.</div>'
|
||||||
: '';
|
: '';
|
||||||
// A small thumbnail made once: the list is rebuilt on every change, and the
|
// 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.
|
// full preview of a file up to 150 MB would be re-parsed each time.
|
||||||
@@ -620,7 +641,12 @@ function pintaFolha(){
|
|||||||
'<span class="passo"><button type="button" data-passo="-1" data-i="'+i+'" aria-label="Menos uma cópia">−</button>'+
|
'<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+'">'+
|
'<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>'+
|
'<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>' : '';
|
'</div>' : '';
|
||||||
return '<div class="rep" data-folha="'+i+'">'+
|
return '<div class="rep" data-folha="'+i+'">'+
|
||||||
'<div class="repTopo"><div class="miniF">'+mini+'</div><div class="repInfo">'+
|
'<div class="repTopo"><div class="miniF">'+mini+'</div><div class="repInfo">'+
|
||||||
@@ -703,6 +729,7 @@ function pintaArtes(){
|
|||||||
// A file still being read when the customer left the product page lands
|
// A file still being read when the customer left the product page lands
|
||||||
// here with no product open: nothing to paint.
|
// here with no product open: nothing to paint.
|
||||||
if(!MODOS[modo]) return;
|
if(!MODOS[modo]) return;
|
||||||
|
if(!artes.length) modoEncaixe='auto'; // C2: lista zerada volta ao automático
|
||||||
if(!espelhavel()) artes.forEach(a=>{ a.esp=false; });
|
if(!espelhavel()) artes.forEach(a=>{ a.esp=false; });
|
||||||
invalidaItemAtual();
|
invalidaItemAtual();
|
||||||
$('zona').classList.toggle('compacta', artes.length>0);
|
$('zona').classList.toggle('compacta', artes.length>0);
|
||||||
@@ -719,7 +746,7 @@ function pintaArtes(){
|
|||||||
}else if(a.decodeError){
|
}else if(a.decodeError){
|
||||||
aviso='<p class="avisoF"><b>Não conseguimos ler esta imagem.</b> Exporte novamente em PNG.</p>';
|
aviso='<p class="avisoF"><b>Não conseguimos ler esta imagem.</b> Exporte novamente em PNG.</p>';
|
||||||
}else if(a.cm>larguraFilme()){
|
}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)){
|
}else if(a.cm>0 && (a.src||a.semPrevia)){
|
||||||
const dpi=Math.round(dpiDe(a));
|
const dpi=Math.round(dpiDe(a));
|
||||||
medida='<b>'+n1(a.cm)+' × '+n1(a.cm*propDe(a))+' cm</b>';
|
medida='<b>'+n1(a.cm)+' × '+n1(a.cm*propDe(a))+' cm</b>';
|
||||||
@@ -733,8 +760,8 @@ function pintaArtes(){
|
|||||||
? '<div class="dica av">Pequena para '+n1(a.cm)+' cm. Em '+DPI_AVISA+' DPI ela sai com até '+
|
? '<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>'
|
n1(maxCm)+' cm, ou envie um arquivo maior.</div>'
|
||||||
: sug
|
: sug
|
||||||
? '<div class="dica">Com '+n1(sug.alvo)+' cm cabem '+sug.para+' por fileira e a folha encolhe '+
|
? '<div class="dica">Com '+n1(sug.alvo)+' cm cabem '+sug.para+' por fileira e a folha fica '+
|
||||||
n1(sug.cm)+' cm.<button data-usar="'+i+'" data-cm="'+sug.alvo+'">Usar '+n1(sug.alvo)+' cm</button></div>'
|
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.
|
// Item 4: the art's dots under 2 mm, with the same warning and acceptance as a sheet.
|
||||||
@@ -746,6 +773,12 @@ function pintaArtes(){
|
|||||||
'A arte entra na folha pela medida, e a equipe confere antes de imprimir. Em PNG, a prévia aparece.</p>';
|
'A arte entra na folha pela medida, e a equipe confere antes de imprimir. Em PNG, a prévia aparece.</p>';
|
||||||
const mini = a.miniSrc ? '<img src="'+escapeHTML(a.miniSrc)+'" alt="">' : '<span>'+escapeHTML(extDe(a.f.name))+'</span>';
|
const mini = a.miniSrc ? '<img src="'+escapeHTML(a.miniSrc)+'" alt="">' : '<span>'+escapeHTML(extDe(a.f.name))+'</span>';
|
||||||
const sub = a.cm>0 && (a.src||a.semPrevia) ? (a.q>1? a.q+' × ' : '')+'<b>'+n1(a.cm)+' × '+n1(a.cm*propDe(a))+' cm</b>' : '';
|
const sub = a.cm>0 && (a.src||a.semPrevia) ? (a.q>1? a.q+' × ' : '')+'<b>'+n1(a.cm)+' × '+n1(a.cm*propDe(a))+' cm</b>' : '';
|
||||||
|
// Girada, a largura na folha é a altura salva no arquivo.
|
||||||
|
const salvo = a.cmSalvo ? Math.round((a.giro? a.cmSalvo*(a.prop||1) : a.cmSalvo)*10)/10 : 0;
|
||||||
|
const manter = salvo && salvo<=larguraFilme()
|
||||||
|
? '<button class="tm'+(Math.abs(a.cm-salvo)<0.05?' on':'')+'" data-tam="'+i+'" data-t="'+salvo+'">'+
|
||||||
|
'Manter '+n1(salvo)+' × '+n1(salvo*propDe(a))+' cm</button>'
|
||||||
|
: '';
|
||||||
return '<div class="rep art2'+(a===recemChegada?' nova':'')+'" data-arte="'+i+'">'+
|
return '<div class="rep art2'+(a===recemChegada?' nova':'')+'" data-arte="'+i+'">'+
|
||||||
'<div class="repTopo"><div class="miniF">'+mini+'</div><div class="repInfo">'+
|
'<div class="repTopo"><div class="miniF">'+mini+'</div><div class="repInfo">'+
|
||||||
'<div class="l1"><b>'+escapeHTML(a.f.name)+'</b>'+(a===recemChegada?'<em class="novaT">nova</em>':'')+
|
'<div class="l1"><b>'+escapeHTML(a.f.name)+'</b>'+(a===recemChegada?'<em class="novaT">nova</em>':'')+
|
||||||
@@ -767,7 +800,7 @@ function pintaArtes(){
|
|||||||
'<button class="gr'+(a.giro?' on':'')+'" data-giro="'+i+'" title="Girar 90°" aria-label="Girar 90°">'+icone('girar')+'</button>'+
|
'<button class="gr'+(a.giro?' on':'')+'" data-giro="'+i+'" title="Girar 90°" aria-label="Girar 90°">'+icone('girar')+'</button>'+
|
||||||
(espelhavel() ? '<button class="gr'+(a.esp?' on':'')+'" data-esp="'+i+'" title="Espelhar" aria-label="Espelhar">'+icone('espelhar')+'</button>' : '')+'</span>'+
|
(espelhavel() ? '<button class="gr'+(a.esp?' on':'')+'" data-esp="'+i+'" title="Espelhar" aria-label="Espelhar">'+icone('espelhar')+'</button>' : '')+'</span>'+
|
||||||
(sub? '<div class="conta">'+sub+'</div>' : '')+
|
(sub? '<div class="conta">'+sub+'</div>' : '')+
|
||||||
'<div class="atalhos">'+(TAMANHOS[larguraFilme()]||[]).map(t=>'<button class="tm'+
|
'<div class="atalhos">'+manter+(TAMANHOS[larguraFilme()]||[]).map(t=>'<button class="tm'+
|
||||||
(Math.abs(a.cm-t)<0.05?' on':'')+'" data-tam="'+i+'" data-t="'+t+'">'+n1(t)+' cm</button>').join('')+'</div>'+
|
(Math.abs(a.cm-t)<0.05?' on':'')+'" data-tam="'+i+'" data-t="'+t+'">'+n1(t)+' cm</button>').join('')+'</div>'+
|
||||||
'</div>'+
|
'</div>'+
|
||||||
'</div>';
|
'</div>';
|
||||||
|
|||||||
@@ -21,13 +21,13 @@ const residuosAceitos=()=>ehFolha()
|
|||||||
// no máximo 10% da tinta em traços de até 4 px.
|
// 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 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 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={
|
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. '+
|
arte:MISTA_BRANCO+'Para evitar, suba em dois arquivos: um com os traços finos, outro com as áreas chapadas. '+
|
||||||
'Vamos proteger os traços finos; as áreas chapadas podem mostrar uma borda branca muito fina. Quer evitar? Suba esta arte em dois '+
|
'Montamos cada um na folha certa, com alguns centímetros a mais de filme.',
|
||||||
'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:MISTA_BRANCO+'Para evitar, envie em duas folhas: uma com os traços finos, outra com as áreas chapadas. '+
|
||||||
folha:'Esta folha tem traços finos e áreas chapadas no mesmo arquivo. O branco por baixo precisa de ajuste diferente pra cada um. '+
|
'Pode usar alguns centímetros a mais de filme.'};
|
||||||
'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.'};
|
|
||||||
// O aviso não barra e aparece uma vez por arquivo, na folha pronta e na arte
|
// 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.
|
// avulsa: imprimir assim mesmo (C1), ou trocar o arquivo por dois.
|
||||||
function perguntaMista(){
|
function perguntaMista(){
|
||||||
@@ -117,9 +117,9 @@ function avaliar(){
|
|||||||
const ausentes=folhas.filter(f=>!f.an);
|
const ausentes=folhas.filter(f=>!f.an);
|
||||||
const exts=[...new Set(ausentes.map(f=>extDe(f.f.name)))].join(', ');
|
const exts=[...new Set(ausentes.map(f=>extDe(f.f.name)))].join(', ');
|
||||||
mostraNota([
|
mostraNota([
|
||||||
['av','Conferência manual · '+exts+' sem análise completa',
|
['av','Conferência manual · '+exts,
|
||||||
ausentes.length+' de '+folhas.length+' folha(s) precisam de conferência manual'],
|
ausentes.length+' de '+folhas.length+' folha(s) sem conferência automática'],
|
||||||
['fix','Alguém abre seu arquivo','a conferência é feita na mão, na sala']
|
['fix','Conferimos manualmente','antes de imprimir']
|
||||||
], 0, folhas.length>1? folhas.length+' folhas' : folhas[0].f.name,
|
], 0, folhas.length>1? folhas.length+' folhas' : folhas[0].f.name,
|
||||||
larguraFilme()+' cm · '+fmtM(metros)+' m');
|
larguraFilme()+' cm · '+fmtM(metros)+' m');
|
||||||
return {pronto:true};
|
return {pronto:true};
|
||||||
@@ -134,7 +134,7 @@ function avaliar(){
|
|||||||
ans.some(a=>a.fonteDpi==='imagens')
|
ans.some(a=>a.fonteDpi==='imagens')
|
||||||
? 'média por área das imagens dentro do PDF · pior em '+
|
? 'média por área das imagens dentro do PDF · pior em '+
|
||||||
Math.min(...ans.map(a=>a.res? a.res.pior : a.dpi))+' DPI'
|
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) ? ['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',
|
ans.some(a=>a.grande) ? null : ['ok', soma('artes')+' peças na folha',
|
||||||
Math.round(soma('aproveitamento')/ans.length)+'% da folha virou arte'],
|
Math.round(soma('aproveitamento')/ans.length)+'% da folha virou arte'],
|
||||||
@@ -156,7 +156,7 @@ function avaliar(){
|
|||||||
const grande=artes.find(a=>a.lendo!=null);
|
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(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)))
|
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()))
|
if(artes.some(a=>!Number.isFinite(a.cm) || a.cm>larguraFilme()))
|
||||||
return {pronto:false, falta:'A largura da arte precisa caber no filme de '+
|
return {pronto:false, falta:'A largura da arte precisa caber no filme de '+
|
||||||
n1(larguraFilme())+' cm. Reduza a medida solicitada antes de continuar.'};
|
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 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);
|
const media=Math.round(notas.reduce((s,n)=>s+n,0)/notas.length), pior=Math.min(...notas);
|
||||||
mostraNota([
|
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']
|
[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':''),
|
],media,artes.length+' arte'+(artes.length>1?'s':''),
|
||||||
'folha montada por nós · '+fmtM(metros)+' m');
|
'folha montada por nós · '+fmtM(metros)+' m');
|
||||||
@@ -197,8 +197,8 @@ function agendaAvaliacao(){
|
|||||||
if(!el) return;
|
if(!el) return;
|
||||||
if(r.pronto){
|
if(r.pronto){
|
||||||
el.className='aoVivo pronto';
|
el.className='aoVivo pronto';
|
||||||
el.innerHTML='<span class="pt2"></span><span><b>Conferência e preço calculados.</b> '+
|
el.innerHTML='<span class="pt2"></span><span><b>Conferência e preço prontos.</b> '+
|
||||||
'Confira abaixo e feche o pedido.</span>';
|
'Confira abaixo e adicione ao carrinho.</span>';
|
||||||
}else{
|
}else{
|
||||||
el.className='aoVivo';
|
el.className='aoVivo';
|
||||||
el.innerHTML='<span class="pt2"></span><span>'+escapeHTML(r.falta)+'</span>';
|
el.innerHTML='<span class="pt2"></span><span>'+escapeHTML(r.falta)+'</span>';
|
||||||
@@ -258,16 +258,16 @@ function ressalvaResolucao(){
|
|||||||
// e não existe aceite que destrave.
|
// e não existe aceite que destrave.
|
||||||
if(recusadas.length){
|
if(recusadas.length){
|
||||||
$('cienteTxt').innerHTML=
|
$('cienteTxt').innerHTML=
|
||||||
'<p><b>A média da folha ficou abaixo de '+DPI_RECUSA+' DPI.</b> Nesse ponto a peça '+
|
'<p><b>'+(recusadas.length>1?recusadas.length+' artes ficaram':'Uma arte ficou')+' abaixo de '+DPI_RECUSA+' DPI.</b> Não imprimimos assim: '+
|
||||||
'sai serrilhada a ponto de não valer o filme. Reenvie maior ou reduza a largura.</p>'+
|
'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> — '+
|
'<div class="lista">'+recusadas.map(b=>'<div><b>'+escapeHTML(b.nome)+'</b>: '+
|
||||||
(b.quantas
|
(b.quantas
|
||||||
? 'média de '+b.dpi+' DPI · pior imagem em '+b.pior+' DPI · '+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'
|
' de '+b.de+' imagens abaixo de '+DPI_RECUSA+' DPI, cobrindo '+b.parte+'% da arte'
|
||||||
: b.dpi+' DPI em '+n1(b.cm)+' cm · precisa de '+
|
: b.dpi+' DPI em '+n1(b.cm)+' cm · precisa de '+
|
||||||
Math.ceil(DPI_AVISA*b.cm/2.54)+' px de largura')+'</div>')
|
Math.ceil(DPI_AVISA*b.cm/2.54)+' px de largura')+'</div>')
|
||||||
.join('')+'</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;
|
box.className='ciente on recusa'; chk.checked=false; $('qOk').disabled=true;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -280,9 +280,9 @@ function ressalvaResolucao(){
|
|||||||
const media=Math.round(baixas.reduce((s,b)=>s+b.dpi,0)/baixas.length);
|
const media=Math.round(baixas.reduce((s,b)=>s+b.dpi,0)/baixas.length);
|
||||||
$('cienteTxt').innerHTML=
|
$('cienteTxt').innerHTML=
|
||||||
'<p><b>Parte da arte está abaixo de '+DPI_AVISA+' DPI.</b> Essas peças podem sair '+
|
'<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>'+
|
'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
|
(b.quantasAviso
|
||||||
? 'média de '+b.dpi+' DPI · '+b.quantasAviso+' de '+b.de+' imagens abaixo de '+
|
? 'média de '+b.dpi+' DPI · '+b.quantasAviso+' de '+b.de+' imagens abaixo de '+
|
||||||
DPI_AVISA+' DPI, cobrindo '+b.parteAviso+'% da arte'+
|
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;'+
|
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';
|
'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');
|
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');
|
const botao=document.createElement('button');
|
||||||
botao.type='button'; botao.textContent='Atualizar';
|
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';
|
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';
|
el.style.display='block';
|
||||||
if(lista.every(f=>/\.jpe?g$/i.test(f.name))){
|
if(lista.every(f=>/\.jpe?g$/i.test(f.name))){
|
||||||
const disfarcados=lista.filter(f=>f.nomeEnviado).map(f=>f.nomeEnviado);
|
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. ' : '')+
|
(disfarcados.length ? escapeHTML(disfarcados.join(', '))+' é JPG, mesmo com outro nome. ' : '')+
|
||||||
'JPG não tem fundo transparente, e o branco do fundo '+
|
'JPG não tem fundo transparente, e o fundo '+
|
||||||
'sai no filme. Exporte em '+(ehFolha()?'PNG ou PDF':'PNG')+' com fundo transparente e envie de novo.';
|
'sai branco no filme. Exporte em '+(ehFolha()?'PNG ou PDF':'PNG')+' com fundo transparente e envie de novo.';
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
el.innerHTML = ehFolha()
|
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.'
|
'PSD, AI e CDR, com fundo transparente.'
|
||||||
: '<b>'+exts+' não dá para enviar aqui.</b> Artes avulsas precisam de PNG com '+
|
: '<b>'+exts+' não entra aqui.</b> Artes avulsas só aceitam PNG com '+
|
||||||
'fundo transparente — é o que a montagem enxerga para encaixar. '+
|
'fundo transparente. Para CDR, AI ou PSD, exporte em PNG ou use <b>Arquivo por metro</b>.';
|
||||||
'Se o seu arquivo é CDR, AI ou PSD, exporte em PNG ou use <b>Arquivo por metro</b>.';
|
|
||||||
}
|
}
|
||||||
const Z=$('zona'), I=$('inp');
|
const Z=$('zona'), I=$('inp');
|
||||||
Z.addEventListener('click',()=>I.click());
|
Z.addEventListener('click',()=>I.click());
|
||||||
@@ -188,7 +187,7 @@ async function sel(fs){
|
|||||||
// On their way at once; a JPG is refused at the order anyway.
|
// On their way at once; a JPG is refused at the order anyway.
|
||||||
fs.filter(f=>!/\.jpe?g$/i.test(f.name)).forEach(f=>window.dtfEnvio?.enviar(f));
|
fs.filter(f=>!/\.jpe?g$/i.test(f.name)).forEach(f=>window.dtfEnvio?.enviar(f));
|
||||||
if(ehFolha()){
|
if(ehFolha()){
|
||||||
const novas=fs.map(f=>({f, med:null, rep:1, m:0, corte:null, semAnalise:null, analiseInicio:Date.now()}));
|
const novas=fs.map(f=>({f, med:null, rep:copiasDoNome(f.name), m:0, corte:null, semAnalise:null, analiseInicio:Date.now()}));
|
||||||
folhas=folhas.concat(novas); // soma, não substitui
|
folhas=folhas.concat(novas); // soma, não substitui
|
||||||
pintaFolha();
|
pintaFolha();
|
||||||
novas.forEach(x=>{
|
novas.forEach(x=>{
|
||||||
@@ -261,7 +260,7 @@ async function sel(fs){
|
|||||||
rasterizarPdf(x.f, md.larg, md.alt, true).then(r=>{
|
rasterizarPdf(x.f, md.larg, md.alt, true).then(r=>{
|
||||||
if(r && r.erro){
|
if(r && r.erro){
|
||||||
x.semAnalise = r.erro + (r.semWorker
|
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){
|
if(r && r.tela && r.mapa){
|
||||||
@@ -283,7 +282,7 @@ async function sel(fs){
|
|||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const novos=fs.map(f=>({f,px:0,py:0,cm:0,q:1,prop:1,giro:0,esp:false,analiseInicio:Date.now()}));
|
const novos=fs.map(f=>({f,px:0,py:0,cm:0,q:copiasDoNome(f.name),prop:1,giro:0,esp:false,analiseInicio:Date.now()}));
|
||||||
artes=novos.concat(artes); // a mais recente fica no topo da fila
|
artes=novos.concat(artes); // a mais recente fica no topo da fila
|
||||||
recemChegada=novos[0];
|
recemChegada=novos[0];
|
||||||
pintaArtes();
|
pintaArtes();
|
||||||
@@ -297,6 +296,11 @@ function medir(a){
|
|||||||
return dimensoesImagem(a.f).then(async d=>{
|
return dimensoesImagem(a.f).then(async d=>{
|
||||||
if(!d || !(d.w>0) || !(d.h>0)){ a.decodeError=true; return a; }
|
if(!d || !(d.w>0) || !(d.h>0)){ a.decodeError=true; return a; }
|
||||||
a.px=d.w; a.py=d.h; a.prop=d.h/d.w; a.grande=true;
|
a.px=d.w; a.py=d.h; a.prop=d.h/d.w; a.grande=true;
|
||||||
|
a.dpiSalvo=await dpiSalvoPng(a.f);
|
||||||
|
if(a.dpiSalvo>=200){
|
||||||
|
a.cmSalvo=Math.round(a.px/a.dpiSalvo*2.54*10)/10;
|
||||||
|
if(a.cmSalvo>=1 && a.cmSalvo<=larguraFilme() && !a.cm) a.cm=a.cmSalvo;
|
||||||
|
}
|
||||||
// WebP cannot be read in parts (JPG is refused): the art is placed by its
|
// WebP cannot be read in parts (JPG is refused): the art is placed by its
|
||||||
// measurements, as a full box, and the team checks it before printing.
|
// measurements, as a full box, and the team checks it before printing.
|
||||||
if(!/\.png$/i.test(a.f.name)){ a.semPrevia=true; return a; }
|
if(!/\.png$/i.test(a.f.name)){ a.semPrevia=true; return a; }
|
||||||
@@ -316,7 +320,13 @@ function medir(a){
|
|||||||
}).catch(()=>{ a.decodeError=true; return a; });
|
}).catch(()=>{ a.decodeError=true; return a; });
|
||||||
}
|
}
|
||||||
return carregarImagem(a.f).then(async img=>{
|
return carregarImagem(a.f).then(async img=>{
|
||||||
if(img){ a.prop=img.height/img.width; a.px=img.width; a.py=img.height; a.src=img.src; a.miniSrc=miniatura(img); a.fotoSrc=miniatura(img,480,720);
|
if(img){ a.prop=img.height/img.width; a.px=img.width; a.py=img.height;
|
||||||
|
a.dpiSalvo=await dpiSalvoPng(a.f);
|
||||||
|
if(a.dpiSalvo>=200){
|
||||||
|
a.cmSalvo=Math.round(a.px/a.dpiSalvo*2.54*10)/10;
|
||||||
|
if(a.cmSalvo>=1 && a.cmSalvo<=larguraFilme() && !a.cm) a.cm=a.cmSalvo;
|
||||||
|
}
|
||||||
|
a.src=img.src; a.miniSrc=miniatura(img); a.fotoSrc=miniatura(img,480,720);
|
||||||
// Read at its own pixels while the customer sets the width.
|
// Read at its own pixels while the customer sets the width.
|
||||||
a.lendoArte=true;
|
a.lendoArte=true;
|
||||||
mapaDaImagem(img, a.px/300*2.54).then(m=>guardaMapaDaArte(a,m)).catch(()=>{})
|
mapaDaImagem(img, a.px/300*2.54).then(m=>guardaMapaDaArte(a,m)).catch(()=>{})
|
||||||
@@ -354,3 +364,77 @@ function tracoDaArte(a){
|
|||||||
// imagem → proporção da imagem aplicada à largura do filme
|
// imagem → proporção da imagem aplicada à largura do filme
|
||||||
// PDF → página única lida pelo PDF.js, com boxes, rotação e UserUnit
|
// PDF → página única lida pelo PDF.js, com boxes, rotação e UserUnit
|
||||||
// TIFF, PSD, AI, CDR → o navegador não abre; o cliente informa o comprimento
|
// TIFF, PSD, AI, CDR → o navegador não abre; o cliente informa o comprimento
|
||||||
|
|
||||||
|
// Minhas folhas: "Editar" opens the product with ?folha=<id>. The files come
|
||||||
|
// from the server, so nothing is sent again, and the saved measures go back
|
||||||
|
// onto the new cards.
|
||||||
|
const folhaSalvaId=new URLSearchParams(location.search).get('folha');
|
||||||
|
let folhaSalvaAberta=false;
|
||||||
|
function mensagemFolhaSalva(texto){
|
||||||
|
const el=$('aoVivo');
|
||||||
|
if(el){el.className='aoVivo'; el.textContent=texto;}
|
||||||
|
}
|
||||||
|
function seguraMensagemFolhaSalva(){
|
||||||
|
// The live check repaints aoVivo a moment after opening; while the saved
|
||||||
|
// sheet comes, that line belongs to the loading message.
|
||||||
|
try{ if(tAval){clearTimeout(tAval);tAval=null;} }catch(_){}
|
||||||
|
mensagemFolhaSalva('Abrindo a folha salva…');
|
||||||
|
}
|
||||||
|
async function abrirFolhaSalva(id){
|
||||||
|
seguraMensagemFolhaSalva();
|
||||||
|
try{
|
||||||
|
const {sheets}=await window.dtfApi('/account/sheets');
|
||||||
|
const folha=(sheets||[]).find(s=>String(s.id)===String(id));
|
||||||
|
if(!folha){ mensagemFolhaSalva('Folha não encontrada.'); return; }
|
||||||
|
seguraMensagemFolhaSalva();
|
||||||
|
const {files}=await window.dtfApi('/account/sheets/'+encodeURIComponent(id)+'/files',{});
|
||||||
|
const item=folha.item||{};
|
||||||
|
const guardadas=item.partes?.length
|
||||||
|
? item.partes.flatMap(p=>p.savedFiles||[])
|
||||||
|
: (item.savedFiles||[]);
|
||||||
|
const fontes=item.partes?.length
|
||||||
|
? item.partes.flatMap(p=>p.production?.sources||[])
|
||||||
|
: (item.production?.sources||[]);
|
||||||
|
const porId=new Map((files||[]).map(f=>[f.upload_id,f]));
|
||||||
|
const lista=guardadas.length
|
||||||
|
? guardadas.map(meta=>({meta,arquivo:porId.get(meta.upload_id)})).filter(x=>x.arquivo)
|
||||||
|
: (files||[]).map(arquivo=>({meta:null,arquivo}));
|
||||||
|
const baixados=[];
|
||||||
|
seguraMensagemFolhaSalva();
|
||||||
|
for(const {meta,arquivo} of lista){
|
||||||
|
const resposta=await fetch(arquivo.url);
|
||||||
|
if(!resposta.ok) throw new Error('download');
|
||||||
|
const blob=await resposta.blob();
|
||||||
|
const file=new File([blob],meta?.name||arquivo.name||'arquivo',
|
||||||
|
{type:meta?.type||blob.type||'',lastModified:meta?.lastModified||Date.now()});
|
||||||
|
window.dtfEnvio?.conhecido(file,arquivo.upload_id);
|
||||||
|
baixados.push(file);
|
||||||
|
}
|
||||||
|
if(!baixados.length) throw new Error('download');
|
||||||
|
const antesArtes=artes.length, antesFolhas=folhas.length;
|
||||||
|
await sel(baixados);
|
||||||
|
if(ehFolha()){
|
||||||
|
const novas=folhas.slice(antesFolhas);
|
||||||
|
novas.forEach((x,i)=>{const fonte=fontes[i]; if(fonte) x.rep=fonte.copies||1;});
|
||||||
|
pintaFolha();
|
||||||
|
}else{
|
||||||
|
const novas=artes.slice(0,Math.max(0,artes.length-antesArtes));
|
||||||
|
novas.forEach((a,i)=>{const fonte=fontes[i]; if(fonte){
|
||||||
|
a.cm=fonte.width_cm; a.q=fonte.copies;
|
||||||
|
a.giro=fonte.rotation_degrees?90:0; a.esp=!!fonte.mirrored;
|
||||||
|
}});
|
||||||
|
pintaArtes();
|
||||||
|
}
|
||||||
|
const url=new URL(location.href); url.searchParams.delete('folha');
|
||||||
|
history.replaceState(history.state,'',url.pathname+url.search+url.hash);
|
||||||
|
}catch(error){
|
||||||
|
mensagemFolhaSalva(error?.status===409
|
||||||
|
? error.message : 'Não foi possível abrir a folha salva. Tente de novo.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
addEventListener('dtf-page-changed',()=>{
|
||||||
|
if(folhaSalvaAberta || !folhaSalvaId || !modo ||
|
||||||
|
document.documentElement.dataset.rota!=='produto') return;
|
||||||
|
folhaSalvaAberta=true;
|
||||||
|
abrirFolhaSalva(folhaSalvaId);
|
||||||
|
});
|
||||||
|
|||||||
@@ -64,17 +64,22 @@ section+section{border-top:0}
|
|||||||
.videosCab h2{margin-top:8px;font-size:clamp(28px,3vw,38px);font-weight:800;letter-spacing:-.02em}
|
.videosCab h2{margin-top:8px;font-size:clamp(28px,3vw,38px);font-weight:800;letter-spacing:-.02em}
|
||||||
.videosCab p{margin-left:auto;max-width:440px;font-size:16.5px;color:var(--fraco)}
|
.videosCab p{margin-left:auto;max-width:440px;font-size:16.5px;color:var(--fraco)}
|
||||||
.videosGrid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:16px}
|
.videosGrid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:16px}
|
||||||
.videoCard{position:relative;display:flex;flex-direction:column;align-items:flex-start;gap:8px;min-height:170px;padding:20px;border:1px solid var(--linha);border-radius:14px;background:var(--cinza);color:var(--preto);text-align:left;font:inherit;cursor:pointer}
|
.videoCard{position:relative;display:flex;flex-direction:column;align-items:flex-start;gap:8px;padding:14px;border:1px solid var(--linha);border-radius:14px;background:var(--cinza);color:var(--preto);text-align:left;font:inherit;cursor:pointer}
|
||||||
.videoCard:hover{border-color:var(--laranja)}
|
.videoCard:hover{border-color:var(--laranja)}
|
||||||
.videoCard .vcPlay{display:flex;align-items:center;justify-content:center;width:38px;height:38px;border-radius:999px;background:var(--laranja);color:var(--preto);font-size:16px;font-weight:900}
|
.videoCard video{display:block;width:100%;height:auto;aspect-ratio:16/9;object-fit:cover;border-radius:10px;background:#000}
|
||||||
.videoCard b{font-family:"Inter",sans-serif;font-size:17px;line-height:1.25}
|
.videoCard b{font-family:"Inter",sans-serif;font-size:17px;line-height:1.25}
|
||||||
.videoCard span{font-size:14.5px;line-height:1.4;color:var(--fraco)}
|
.videoCard span{font-size:14.5px;line-height:1.4;color:var(--fraco)}
|
||||||
.videoCard em{margin-top:auto;font-style:normal;font-size:12.5px;font-weight:700;letter-spacing:.04em;text-transform:uppercase;color:var(--laranja-escuro)}
|
|
||||||
.videoCard[data-soon="1"]{cursor:default;opacity:.72}
|
.videoCard[data-soon="1"]{cursor:default;opacity:.72}
|
||||||
.videoCard[data-soon="1"]:hover{border-color:var(--linha)}
|
.videoCard[data-soon="1"]:hover{border-color:var(--linha)}
|
||||||
.videoFloat{position:fixed;right:max(22px,env(safe-area-inset-right));bottom:max(22px,env(safe-area-inset-bottom));z-index:70;width:min(280px,calc(100vw - 32px));border-radius:14px;overflow:hidden;background:var(--preto);box-shadow:0 14px 40px rgba(3,6,11,.35)}
|
.videoFloat{position:fixed;right:max(22px,env(safe-area-inset-right));bottom:max(22px,env(safe-area-inset-bottom));z-index:70;width:min(280px,calc(100vw - 32px));border-radius:14px;overflow:hidden;background:var(--preto);box-shadow:0 14px 40px rgba(3,6,11,.35)}
|
||||||
.videoFloat video{display:block;width:100%;height:auto;aspect-ratio:16/9;background:#000}
|
.videoFloat video{display:block;width:100%;height:auto;aspect-ratio:16/9;background:#000}
|
||||||
.videoFloat .vfClose{position:absolute;top:8px;right:8px;width:44px;height:44px;border:0;border-radius:999px;background:rgba(0,0,0,.62);color:#fff;font-size:20px;line-height:1;cursor:pointer}
|
/* Vertical, it stays small: tall enough to read, never over the buy box's button. */
|
||||||
|
.videoFloat.vertical{width:min(150px,36vw)}
|
||||||
|
.videoFloat.vertical video{aspect-ratio:9/16;max-height:44vh;object-fit:contain}
|
||||||
|
.videoFloat .vfActions{position:absolute;top:8px;right:8px;display:flex;gap:8px}
|
||||||
|
.videoFloat .vfActions button{width:44px;height:44px;padding:0;border:0;border-radius:999px;background:rgba(0,0,0,.62);color:#fff;font-size:20px;line-height:1;cursor:pointer;display:flex;align-items:center;justify-content:center}
|
||||||
|
.videoFloat .vfActions button:focus-visible{outline:3px solid var(--laranja);outline-offset:2px}
|
||||||
|
.videoFloat .vfActions svg{width:20px;height:20px;fill:none;stroke:currentColor;stroke-width:2;stroke-linecap:round;stroke-linejoin:round}
|
||||||
.videoFloat .vfLabel{padding:8px 12px;color:#fff;font-size:13px;line-height:1.3}
|
.videoFloat .vfLabel{padding:8px 12px;color:#fff;font-size:13px;line-height:1.3}
|
||||||
.videoFloat .vfLabel b{display:block;font-family:"Inter",sans-serif;font-size:14px}
|
.videoFloat .vfLabel b{display:block;font-family:"Inter",sans-serif;font-size:14px}
|
||||||
.videoAberto{overflow:hidden}
|
.videoAberto{overflow:hidden}
|
||||||
@@ -82,6 +87,8 @@ section+section{border-top:0}
|
|||||||
.videoModal[hidden]{display:none}
|
.videoModal[hidden]{display:none}
|
||||||
.videoModal .vmBox{position:relative;width:min(920px,100%);border-radius:16px;overflow:hidden;background:#000}
|
.videoModal .vmBox{position:relative;width:min(920px,100%);border-radius:16px;overflow:hidden;background:#000}
|
||||||
.videoModal video{display:block;width:100%;height:auto;max-height:82vh;background:#000}
|
.videoModal video{display:block;width:100%;height:auto;max-height:82vh;background:#000}
|
||||||
|
.videoModal.vertical .vmBox{width:auto;max-width:100%}
|
||||||
|
.videoModal.vertical video{width:auto;max-width:100%;max-height:86vh}
|
||||||
.videoModal .vmClose{position:absolute;top:10px;right:10px;width:44px;height:44px;border:0;border-radius:999px;background:rgba(0,0,0,.65);color:#fff;font-size:22px;cursor:pointer}
|
.videoModal .vmClose{position:absolute;top:10px;right:10px;width:44px;height:44px;border:0;border-radius:999px;background:rgba(0,0,0,.65);color:#fff;font-size:22px;cursor:pointer}
|
||||||
@media(max-width:900px){.videosGrid{grid-template-columns:repeat(2,minmax(0,1fr))}}
|
@media(max-width:900px){.videosGrid{grid-template-columns:repeat(2,minmax(0,1fr))}}
|
||||||
@media(max-width:620px){.videosGrid{grid-template-columns:1fr}.videos2{padding:36px 0}}
|
@media(max-width:620px){.videosGrid{grid-template-columns:1fr}.videos2{padding:36px 0}}
|
||||||
@@ -292,6 +299,22 @@ section+section{border-top:0}
|
|||||||
.cLin s{font-size:15px;color:#707070}
|
.cLin s{font-size:15px;color:#707070}
|
||||||
.cObs{margin:-4px 0 0;font-size:15px;color:var(--verde)}
|
.cObs{margin:-4px 0 0;font-size:15px;color:var(--verde)}
|
||||||
.cObs:empty{display:none}
|
.cObs:empty{display:none}
|
||||||
|
/* C2 · modo de encaixe · C1 · o que cabe sem custo, na caixa de compra */
|
||||||
|
#cEncaixe{display:flex;flex-direction:column;gap:6px}
|
||||||
|
#cEncaixe[hidden]{display:none}
|
||||||
|
.cEncBts{display:flex;gap:8px}
|
||||||
|
.cEncBt{flex:1;display:flex;flex-direction:column;gap:2px;padding:8px 10px;border:1px solid var(--linha);border-radius:var(--raio2);background:#fff;text-align:left;font:inherit;color:var(--preto);cursor:pointer}
|
||||||
|
.cEncBt b{font-size:15.5px}
|
||||||
|
.cEncBt small{font-size:13px;color:var(--fraco)}
|
||||||
|
.cEncBt.on{border-color:var(--preto);box-shadow:inset 0 0 0 1px var(--preto);background:var(--cinza)}
|
||||||
|
.cEncDif{margin:0;font-size:14.5px;color:var(--verde)}
|
||||||
|
#cVao{display:flex;flex-direction:column;gap:6px}
|
||||||
|
#cVao[hidden]{display:none}
|
||||||
|
.cVaoT{margin:0;font-size:14.5px;color:var(--verde)}
|
||||||
|
.cVaoBts{display:flex;flex-wrap:wrap;gap:8px}
|
||||||
|
.cVaoBt{padding:7px 12px;border:1px solid var(--laranja);border-radius:999px;background:var(--aviso-fundo);color:var(--preto);font:inherit;font-size:14.5px;cursor:pointer}
|
||||||
|
.cVaoBt:hover{border-color:var(--laranja2)}
|
||||||
|
.cEncBt:focus-visible,.cVaoBt:focus-visible{outline:2px solid var(--laranja2);outline-offset:2px}
|
||||||
.cTot{display:flex;align-items:baseline;padding-top:12px;border-top:1px solid #EFEFEF}
|
.cTot{display:flex;align-items:baseline;padding-top:12px;border-top:1px solid #EFEFEF}
|
||||||
.cTot span{font-family:"Inter",sans-serif;font-weight:700}
|
.cTot span{font-family:"Inter",sans-serif;font-weight:700}
|
||||||
.cTot b{margin-left:auto;font-family:"Inter",sans-serif;font-size:30px;font-weight:900;letter-spacing:-.01em}
|
.cTot b{margin-left:auto;font-family:"Inter",sans-serif;font-size:30px;font-weight:900;letter-spacing:-.01em}
|
||||||
@@ -348,6 +371,8 @@ section+section{border-top:0}
|
|||||||
.provaOp{display:flex;gap:10px;align-items:flex-start;cursor:pointer;font-size:15px;line-height:1.5;color:var(--fraco)}
|
.provaOp{display:flex;gap:10px;align-items:flex-start;cursor:pointer;font-size:15px;line-height:1.5;color:var(--fraco)}
|
||||||
.provaOp input{margin-top:3px;width:17px;height:17px;flex:none;accent-color:var(--laranja)}
|
.provaOp input{margin-top:3px;width:17px;height:17px;flex:none;accent-color:var(--laranja)}
|
||||||
.provaOp b{display:block;color:var(--preto);font-weight:700}
|
.provaOp b{display:block;color:var(--preto);font-weight:700}
|
||||||
|
.provaOp:has(input:disabled){cursor:default;opacity:.55}
|
||||||
|
.provaMin{margin:8px 0 0 27px;font-size:14px;color:var(--fraco)}
|
||||||
.cp input,.cepL input{height:46px;border-radius:var(--raio2)}
|
.cp input,.cepL input{height:46px;border-radius:var(--raio2)}
|
||||||
.cp input:focus,.cepL input:focus{border-color:var(--laranja2);box-shadow:0 0 0 3px rgba(255,168,26,.18)}
|
.cp input:focus,.cepL input:focus{border-color:var(--laranja2);box-shadow:0 0 0 3px rgba(255,168,26,.18)}
|
||||||
.opE{border-radius:12px}
|
.opE{border-radius:12px}
|
||||||
@@ -562,3 +587,10 @@ html:is([data-rota="pagamento"],[data-rota="pix"]) .pagGrid{display:grid;grid-te
|
|||||||
#vArea .folhasTraco{display:flex;flex-direction:column;gap:14px}
|
#vArea .folhasTraco{display:flex;flex-direction:column;gap:14px}
|
||||||
#vArea .folhaTraco{margin:0;display:flex;flex-direction:column;gap:6px}
|
#vArea .folhaTraco{margin:0;display:flex;flex-direction:column;gap:6px}
|
||||||
#vArea .folhaTraco figcaption{font-size:14.5px;font-weight:700;color:var(--texto2)}
|
#vArea .folhaTraco figcaption{font-size:14.5px;font-weight:700;color:var(--texto2)}
|
||||||
|
|
||||||
|
/* Minhas folhas: saving a cart item to the account. */
|
||||||
|
.salvaBt{flex:none;height:36px;padding:0 12px;border-radius:var(--raio2);border:1px solid var(--linha);background:#fff;color:var(--texto2);font-family:inherit;font-size:14px;font-weight:600;cursor:pointer}
|
||||||
|
.salvaBt:hover:not(:disabled){border-color:var(--laranja);color:var(--preto)}
|
||||||
|
.salvaBt:disabled{opacity:.55;cursor:not-allowed}
|
||||||
|
.salvaBt:focus-visible{outline:2px solid var(--laranja2);outline-offset:2px}
|
||||||
|
@media(max-width:620px){.salvaBt{padding:0 9px;font-size:13px}}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user