From d4494a0654d37ae8f35727132937e0da11af5ad7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cau=C3=AA=20Faleiros?= Date: Thu, 22 Oct 2026 10:09:15 -0300 Subject: [PATCH] feat: Dropstar's corrections of 21/10 that need no answer from them MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - the home example priced as the ready sheet it shows (nota 92, R$ 14,90) - opening hours 7h to 18h, and art sent at any time - uploads up to 1 GB, every file scanned - a Designer profile: artwork and corrections on every order, moving only among Arte recebida, Arte conferida and Correção - Números by date range, per machine, and orders apart from passages Co-Authored-By: Claude Opus 5.5 --- .env.example | 2 +- app/api/operator.py | 126 ++++++++++++++++++++++++++------- app/api/users.py | 2 +- app/core/auth.py | 17 +++-- app/core/limits.py | 2 +- app/scanning.py | 5 +- app/schema.sql | 9 ++- compose.local.yaml | 4 +- deploy/portainer.env.example | 2 +- docker-compose.yml | 10 +-- docs/CONTEXT.md | 11 +++ tests/artwork_browser_test.mjs | 10 +-- tests/kanban_test.py | 19 +++++ tests/smoke_test.py | 4 +- tests/users_test.py | 35 ++++++++- web/index.html | 11 +-- web/kanban.css | 6 +- web/kanban.html | 9 ++- web/kanban.js | 79 +++++++++++++++------ web/portal.html | 3 +- web/site-upload.js | 2 +- 21 files changed, 279 insertions(+), 89 deletions(-) diff --git a/.env.example b/.env.example index 3d9bb84..3c916c2 100644 --- a/.env.example +++ b/.env.example @@ -52,7 +52,7 @@ TINY_ADAPTER=fake # SMTP_PASSWORD=... STORAGE_ADAPTER=s3-local MOCK_FREIGHT_CENTS=1500 -MAX_UPLOAD_BYTES=5368709120 +MAX_UPLOAD_BYTES=1073741824 UPLOAD_PART_BYTES=8388608 STORAGE_QUOTA_BYTES=53687091200 OWNER_UPLOAD_QUOTA_BYTES=10737418240 diff --git a/app/api/operator.py b/app/api/operator.py index 8cb49d8..9cabd53 100644 --- a/app/api/operator.py +++ b/app/api/operator.py @@ -3,7 +3,7 @@ import hashlib import os import re import secrets -from datetime import datetime, timedelta, timezone +from datetime import date, datetime, timedelta, timezone from typing import Literal from uuid import UUID @@ -12,7 +12,7 @@ from fastapi.responses import RedirectResponse from pydantic import Field from ..core import db -from ..core.auth import (COOKIE_SECURE, DUMMY_PASSWORD_HASH, audit, can, client_ip, operator, +from ..core.auth import (COOKIE_SECURE, DESIGNER_STATES, DUMMY_PASSWORD_HASH, audit, can, client_ip, operator, login_failed, password_matches, throttle) from ..core.models import Move, OperatorLogin, Resolution, Review, StrictModel from ..printjobs import queue as queue_print_files @@ -508,12 +508,19 @@ def cancel_order(uid: UUID, body: Resolution, user=Depends(can('manage'))): return {'ok': True} +def designer_only(request, *states): + """A designer works on the artwork stages only: Arte recebida, Arte + conferida and Correção. The queue onwards is the print room's.""" + if request.state.operator['role'] == 'designer' and not set(states) <= set(DESIGNER_STATES): + raise HTTPException(403, 'O perfil Designer move pedidos só entre Arte recebida, Arte conferida e Correção.') + + class MachineChoice(StrictModel): machine_id: UUID | None = None @router.post('/api/operator/orders/{uid}/machine') -def choose_machine(uid: UUID, body: MachineChoice, user=Depends(can('produce'))): +def choose_machine(uid: UUID, body: MachineChoice, user=Depends(can('print'))): """Send an order to a machine, or back to the automatic choice (None).""" with db.connect() as c: if body.machine_id and not c.execute('SELECT 1 FROM dtf_local.machines WHERE id=%s', (body.machine_id,)).fetchone(): @@ -562,7 +569,7 @@ QUEUE_KEY = 'COALESCE(queue_key, extract(epoch FROM created_at))' @router.post('/api/operator/orders/{uid}/queue') -def queue_place(uid: UUID, body: QueuePlace, user=Depends(can('produce'))): +def queue_place(uid: UUID, body: QueuePlace, request: Request, user=Depends(can('produce'))): """An order's place in its column: by default its payment time; dragged, halfway between the orders it was dropped between. It neither changes the order's stage nor counts as activity (the stalled clock keeps running).""" @@ -572,6 +579,7 @@ def queue_place(uid: UUID, body: QueuePlace, user=Depends(can('produce'))): row = c.execute('SELECT state FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone() if not row: raise HTTPException(404, 'Order not found') + designer_only(request, row['state']) keys = {} for side in ('after', 'before'): other = getattr(body, side) @@ -592,7 +600,7 @@ def queue_place(uid: UUID, body: QueuePlace, user=Depends(can('produce'))): @router.post('/api/operator/orders/{uid}/move') -def move(uid: UUID, body: Move, user=Depends(can('produce'))): +def move(uid: UUID, body: Move, request: Request, user=Depends(can('produce'))): with db.connect() as c: row = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone() if not row: @@ -603,6 +611,7 @@ def move(uid: UUID, body: Move, user=Depends(can('produce'))): raise HTTPException(409, 'Pedido cancelado.') if body.state == row['state']: return row + designer_only(request, row['state'], body.state) back = BACK.get(row['state']) == body.state if body.state not in TRANSITIONS[row['state']] and not back: raise HTTPException(409, f"Não dá para ir de {STATES[row['state']]} para {STATES[body.state]}.") @@ -755,56 +764,121 @@ REAL_ORDER = "o.cancelled_at IS NULL AND COALESCE(o.payment->>'provider','') <> LOCAL_DAY = "(o.created_at AT TIME ZONE 'America/Sao_Paulo')::date" +# Longest period one request may cover: a year and a day, for a year against the last. +STATS_MAX_DAYS = 366 + + +def stats_period(days, start, end): + """The local days a request covers: the last `days`, or start to end.""" + today = datetime.now(timezone(timedelta(hours=-3))).date() + if start is None and end is None: + days = days or 30 + return today - timedelta(days=days - 1), today + if start is None or end is None: + raise HTTPException(422, 'Informe a data inicial e a final.') + if start > end: + raise HTTPException(422, 'A data inicial é depois da final.') + if (end - start).days + 1 > STATS_MAX_DAYS: + raise HTTPException(422, f'O período vai até {STATS_MAX_DAYS} dias.') + return start, end + + @router.get('/api/operator/stats') -def production_stats(days: int = Query(default=30, ge=7, le=365), user=Depends(operator)): +def production_stats(days: int | None = Query(default=None, ge=7, le=365), start: date | None = None, + end: date | None = None, user=Depends(operator)): """Production numbers from what the board already records: orders paid in - the period, how long each stage holds an order, and what is waiting now.""" - # From the start of the first local day of the period. - since = ("o.created_at >= (((now() AT TIME ZONE 'America/Sao_Paulo')::date - make_interval(days => %s - 1))" - " AT TIME ZONE 'America/Sao_Paulo')") + the period, how long each stage holds an order, what each machine printed, + and what is waiting now. The period is the last `days`, or start to end.""" + start, end = stats_period(days, start, end) + period = (start, end) + within = f"{LOCAL_DAY} BETWEEN %s AND %s" metres = "(SELECT COALESCE(sum((i->>'billed_metres')::numeric),0) FROM jsonb_array_elements(o.snapshot->'items') i)" with db.connect() as c: total = c.execute(f'''SELECT count(*) AS orders, COALESCE(sum((o.snapshot->>'total_cents')::bigint),0) AS cents, COALESCE(sum({metres}),0) AS metres, count(*) FILTER (WHERE EXISTS (SELECT 1 FROM dtf_local.movements m WHERE m.order_id=o.id AND m.to_state='cor' AND NOT m.back)) AS corrected - FROM dtf_local.orders o WHERE {REAL_ORDER} AND {since}''', (days,)).fetchone() + FROM dtf_local.orders o WHERE {REAL_ORDER} AND {within}''', period).fetchone() daily = {row['day']: row for row in c.execute(f'''SELECT {LOCAL_DAY} AS day, count(*) AS orders, - COALESCE(sum({metres}),0) AS metres FROM dtf_local.orders o WHERE {REAL_ORDER} AND {since} - GROUP BY 1''', (days,)).fetchall()} + COALESCE(sum({metres}),0) AS metres FROM dtf_local.orders o WHERE {REAL_ORDER} AND {within} + GROUP BY 1''', period).fetchall()} # Each order's stages as spans: from entering a stage to the next move. spans = f'''WITH events AS ( - SELECT o.id, 'rec' AS state, o.created_at AS at FROM dtf_local.orders o WHERE {REAL_ORDER} AND {since} + SELECT o.id, 'rec' AS state, o.created_at AS at FROM dtf_local.orders o WHERE {REAL_ORDER} AND {within} UNION ALL SELECT m.order_id, m.to_state, m.created_at FROM dtf_local.movements m - JOIN dtf_local.orders o ON o.id=m.order_id WHERE {REAL_ORDER} AND {since}) + JOIN dtf_local.orders o ON o.id=m.order_id WHERE {REAL_ORDER} AND {within}) SELECT id, state, at, LEAD(at) OVER (PARTITION BY id ORDER BY at) AS until FROM events''' - stages = c.execute(f'''SELECT state, count(*) AS orders, + # Orders, not passages: an order sent back counts once, its passages apart. + stages = c.execute(f'''SELECT state, count(DISTINCT id) AS orders, count(*) AS passages, percentile_cont(0.5) WITHIN GROUP (ORDER BY extract(epoch FROM until-at)) / 3600 AS median_hours - FROM ({spans}) s WHERE until IS NOT NULL GROUP BY state''', (days, days)).fetchall() + FROM ({spans}) s WHERE until IS NOT NULL GROUP BY state''', period + period).fetchall() lead = c.execute(f'''SELECT count(*) AS orders, percentile_cont(0.5) WITHIN GROUP (ORDER BY extract(epoch FROM f.at - o.created_at)) / 3600 AS median_hours FROM dtf_local.orders o JOIN LATERAL (SELECT min(created_at) AS at FROM dtf_local.movements m WHERE m.order_id=o.id AND m.to_state='fin') f ON f.at IS NOT NULL - WHERE {REAL_ORDER} AND {since}''', (days,)).fetchone() + WHERE {REAL_ORDER} AND {within}''', period).fetchone() # What waits now, however old, and since when in its stage. waiting = c.execute(f'''SELECT o.state, count(*) AS orders, max(extract(epoch FROM now() - COALESCE( (SELECT max(m.created_at) FROM dtf_local.movements m WHERE m.order_id=o.id AND m.to_state=o.state), o.created_at))) / 3600 AS oldest_hours FROM dtf_local.orders o WHERE {REAL_ORDER} AND o.state<>'fin' GROUP BY o.state''').fetchall() - today = datetime.now(timezone(timedelta(hours=-3))).date() + printed = machine_output(c, start, end) series = [] - for offset in range(days - 1, -1, -1): - day = today - timedelta(days=offset) + for offset in range((end - start).days + 1): + day = start + timedelta(days=offset) row = daily.get(day) series.append({'day': day.isoformat(), 'orders': row['orders'] if row else 0, 'metres': float(row['metres']) if row else 0.0}) hours = lambda value: round(float(value), 1) if value is not None else None - return {'days': days, 'orders': total['orders'], 'cents': int(total['cents']), 'metres': float(total['metres']), + return {'days': len(series), 'start': start.isoformat(), 'end': end.isoformat(), + 'orders': total['orders'], 'cents': int(total['cents']), 'metres': float(total['metres']), 'corrected': total['corrected'], 'daily': series, 'lead': {'orders': lead['orders'], 'median_hours': hours(lead['median_hours'])}, - 'stages': {row['state']: {'orders': row['orders'], 'median_hours': hours(row['median_hours'])} for row in stages}, - 'waiting': {row['state']: {'orders': row['orders'], 'oldest_hours': hours(row['oldest_hours'])} for row in waiting}} + 'stages': {row['state']: {'orders': row['orders'], 'passages': row['passages'], + 'median_hours': hours(row['median_hours'])} for row in stages}, + 'waiting': {row['state']: {'orders': row['orders'], 'oldest_hours': hours(row['oldest_hours'])} for row in waiting}, + 'machines': printed} + + +def machine_output(c, start, end): + """What each machine printed in the period: the orders that reached + Finalizado then, on the machine they were on, their metres, the hours they + spent in Imprimindo (so metres per hour is the machine's real pace, as the + room moves the cards), when it last finished one, and what it has now.""" + metres = "(SELECT COALESCE(sum((i->>'billed_metres')::numeric),0) FROM jsonb_array_elements(o.snapshot->'items') i)" + done = c.execute(f'''SELECT o.id, o.machine_id, {metres} AS metres, f.at + FROM dtf_local.orders o + JOIN LATERAL (SELECT min(created_at) AS at FROM dtf_local.movements m + WHERE m.order_id=o.id AND m.to_state='fin') f ON f.at IS NOT NULL + WHERE {REAL_ORDER} AND (f.at AT TIME ZONE 'America/Sao_Paulo')::date BETWEEN %s AND %s''', + (start, end)).fetchall() + ids = [row['id'] for row in done] + printing = {row['id']: float(row['hours']) for row in c.execute('''WITH events AS ( + SELECT m.order_id AS id, m.to_state AS state, m.created_at AS at FROM dtf_local.movements m + WHERE m.order_id=ANY(%s)), + spans AS (SELECT id, state, at, LEAD(at) OVER (PARTITION BY id ORDER BY at) AS until FROM events) + SELECT id, sum(extract(epoch FROM until-at)) / 3600 AS hours FROM spans + WHERE state='imp' AND until IS NOT NULL GROUP BY id''', (ids,)).fetchall()} if ids else {} + last = {str(row['machine_id']): row['at'] for row in c.execute(f'''SELECT o.machine_id, max(m.created_at) AS at + FROM dtf_local.orders o JOIN dtf_local.movements m ON m.order_id=o.id AND m.to_state='fin' + WHERE {REAL_ORDER} AND o.machine_id IS NOT NULL GROUP BY o.machine_id''').fetchall()} + result = [] + for m in machines.rows(c): + mine = [row for row in done if str(row['machine_id'] or '') == m['id']] + hours_in = sum(printing.get(row['id'], 0.0) for row in mine) + made = float(sum(row['metres'] for row in mine)) + result.append({'id': m['id'], 'name': m['name'], 'active': m['active'], 'orders': len(mine), + 'metres': made, 'printing_hours': round(hours_in, 2), + 'metres_per_hour': round(made / hours_in, 1) if hours_in > 0 else None, + 'last_finished': last[m['id']].isoformat() if m['id'] in last else None, + 'now': {state: m['states'].get(state, 0) for state in ('fil', 'imp')}}) + loose = [row for row in done if row['machine_id'] is None] + if loose: + result.append({'id': None, 'name': 'Sem máquina', 'active': True, 'orders': len(loose), + 'metres': float(sum(row['metres'] for row in loose)), 'printing_hours': None, + 'metres_per_hour': None, 'last_finished': None, 'now': {}}) + return result def named_files(rows): @@ -854,7 +928,7 @@ def print_ready(c, request, states): @router.get('/api/operator/queue/finals') -def queue_finals(request: Request, auto: bool = False, user=Depends(can('produce'))): +def queue_finals(request: Request, auto: bool = False, user=Depends(can('print'))): """The approved final files of every order in the print queue. The browser downloads them straight from storage: a zip of multi-GB sheets would go through the server.""" @@ -872,7 +946,7 @@ class FolderSync(StrictModel): @router.post('/api/operator/queue/folder') -def queue_folder(body: FolderSync, request: Request, user=Depends(can('produce'))): +def queue_folder(body: FolderSync, request: Request, user=Depends(can('print'))): """What the Kanban's automatic folder should hold. Early, it also gets the files of orders just received (to a "Recebidos" folder), so a large sheet is already on the computer when the order reaches the queue. `states` answers diff --git a/app/api/users.py b/app/api/users.py index 5ea9c8c..697957a 100644 --- a/app/api/users.py +++ b/app/api/users.py @@ -24,7 +24,7 @@ class UserIn(StrictModel): # The profiles an administrator may give; superadmin only comes from the console. name: str = Field(min_length=1, max_length=80) email: str = Field(min_length=3, max_length=254) - role: Literal['admin', 'gestao', 'operador', 'vendedor'] + role: Literal['admin', 'gestao', 'designer', 'operador', 'vendedor'] password: str | None = Field(default=None, min_length=8, max_length=128) active: bool = True machines: list[UUID] = Field(default_factory=list, max_length=50) diff --git a/app/core/auth.py b/app/core/auth.py index e532fa0..a98d7a2 100644 --- a/app/core/auth.py +++ b/app/core/auth.py @@ -115,14 +115,19 @@ def login_failed(email): rate_limit('auth-account', email, 1_000_000) # What each Kanban profile may do. "view" is reading; "produce" moves cards and -# handles artwork; "manage" covers quotes, cancellations and payments; "users" -# is the Usuários page; "integrations" is everything in Integrações but the -# print room's folder (connecting Tiny, the checks, the backup, the Tiny log): -# the others see there only what is on and off. -ROLES = ('superadmin', 'admin', 'gestao', 'operador', 'vendedor') +# handles artwork; "print" is the print room's side of it (the machine, the +# queue's order, its files and folder); "manage" covers quotes, cancellations +# and payments; "users" is the Usuários page; "integrations" is everything in +# Integrações but the print room's folder (connecting Tiny, the checks, the +# backup, the Tiny log): the others see there only what is on and off. +# The designer approves and refuses artwork and asks for corrections, on every +# order whatever its machine, and moves cards only among DESIGNER_STATES. +ROLES = ('superadmin', 'admin', 'gestao', 'designer', 'operador', 'vendedor') +DESIGNER_STATES = ('rec', 'tra', 'cor') CAPABILITIES = { 'view': set(ROLES), - 'produce': {'superadmin', 'admin', 'gestao', 'operador'}, + 'produce': {'superadmin', 'admin', 'gestao', 'designer', 'operador'}, + 'print': {'superadmin', 'admin', 'gestao', 'operador'}, 'manage': {'superadmin', 'admin', 'gestao'}, 'users': {'superadmin', 'admin'}, 'integrations': {'superadmin'}, diff --git a/app/core/limits.py b/app/core/limits.py index e154c86..544da46 100644 --- a/app/core/limits.py +++ b/app/core/limits.py @@ -10,4 +10,4 @@ def scan_limit_bytes(): def upload_limit_bytes(): - return int(os.environ.get('MAX_UPLOAD_BYTES', '5368709120')) + return int(os.environ.get('MAX_UPLOAD_BYTES', '1073741824')) diff --git a/app/scanning.py b/app/scanning.py index 207c21d..708b70a 100644 --- a/app/scanning.py +++ b/app/scanning.py @@ -1,8 +1,9 @@ """Releasing artwork: ClamAV up to its size limit, a format check above it. Unknown or error results NEVER release artwork. ClamAV scans files up to -scan_limit_bytes() (2 GB). Sheets of several GB are the normal order and -ClamAV cannot take them, so a larger file is released only if its first bytes +scan_limit_bytes() (at most 2 GB). Since 2026-10-21 a file is at most 1 GB and +the scan limit is the same, so every file is scanned. Were the upload limit +raised above it again, a larger file would be released only if its first bytes are those of the format its name claims (a PNG that really is a PNG, not a program renamed .png). That is the check the client chose for large files; it does not look for malware inside a valid file. diff --git a/app/schema.sql b/app/schema.sql index e892bcd..a5a3e8c 100644 --- a/app/schema.sql +++ b/app/schema.sql @@ -247,12 +247,11 @@ CREATE TABLE IF NOT EXISTS dtf_local.cnpj_names ( -- Who may do what on the Kanban. superadmin is the system's own account (set -- from the console); administrators manage users and machines; gestão runs --- the business; operadores produce; vendedores only read. +-- the business; designers approve artwork; operadores produce; vendedores only read. ALTER TABLE dtf_local.operators ADD COLUMN IF NOT EXISTS role text NOT NULL DEFAULT 'admin'; -DO $$ BEGIN - ALTER TABLE dtf_local.operators ADD CONSTRAINT operators_role - CHECK (role IN ('superadmin','admin','gestao','operador','vendedor')); -EXCEPTION WHEN duplicate_object THEN NULL; END $$; +ALTER TABLE dtf_local.operators DROP CONSTRAINT IF EXISTS operators_role; +ALTER TABLE dtf_local.operators ADD CONSTRAINT operators_role + CHECK (role IN ('superadmin','admin','gestao','designer','operador','vendedor')); -- The print machines, and which products each prints. An order keeps the -- machine someone chose (machine_chosen) or the one given automatically: the -- active machine of its product with the fewest metres open (app/machines.py). diff --git a/compose.local.yaml b/compose.local.yaml index 56584ab..73ecfc3 100644 --- a/compose.local.yaml +++ b/compose.local.yaml @@ -91,12 +91,12 @@ x-app: &app SMTP_PASSWORD: ${SMTP_PASSWORD:-} STORAGE_ADAPTER: s3-local MOCK_FREIGHT_CENTS: ${MOCK_FREIGHT_CENTS:-1500} - MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-5368709120} + MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-1073741824} UPLOAD_PART_BYTES: ${UPLOAD_PART_BYTES:-8388608} STORAGE_QUOTA_BYTES: ${STORAGE_QUOTA_BYTES:-53687091200} OWNER_UPLOAD_QUOTA_BYTES: ${OWNER_UPLOAD_QUOTA_BYTES:-10737418240} MAX_PENDING_UPLOADS: ${MAX_PENDING_UPLOADS:-10} - SCAN_MAX_BYTES: ${SCAN_MAX_BYTES:-2097152000} + SCAN_MAX_BYTES: ${SCAN_MAX_BYTES:-1073741824} networks: [local] init: true security_opt: [no-new-privileges:true] diff --git a/deploy/portainer.env.example b/deploy/portainer.env.example index 1457715..58c2dec 100644 --- a/deploy/portainer.env.example +++ b/deploy/portainer.env.example @@ -56,7 +56,7 @@ SMTP_PASSWORD=TBD STORAGE_QUOTA_BYTES=TBD OWNER_UPLOAD_QUOTA_BYTES=TBD MAX_PENDING_UPLOADS=10 -MAX_UPLOAD_BYTES=5368709120 +MAX_UPLOAD_BYTES=1073741824 UPLOAD_PART_BYTES=8388608 SCAN_MAX_BYTES=134217728 # Daily encrypted database backup to its own bucket (docs/BACKUP.md). diff --git a/docker-compose.yml b/docker-compose.yml index 7d20820..ba8e09a 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -129,15 +129,17 @@ x-app-environment: &app-environment ALLOWED_HOSTS: ${SITE_DOMAIN:?set SITE_DOMAIN},${KANBAN_DOMAIN:?set KANBAN_DOMAIN} ALLOWED_ORIGINS: https://${SITE_DOMAIN:?set SITE_DOMAIN},https://${KANBAN_DOMAIN:?set KANBAN_DOMAIN} COOKIE_SECURE: "true" - MAX_UPLOAD_BYTES: "5368709120" + # 1 GB per file (Dropstar, 2026-10-21): a 57 cm x 5 m sheet at 300 DPI is + # 200 to 300 MB, and much more takes an hour to send on a common connection. + MAX_UPLOAD_BYTES: "1073741824" UPLOAD_PART_BYTES: "8388608" # Sheets of several GB are the normal order, so room for many of them. STORAGE_QUOTA_BYTES: "${STORAGE_QUOTA_BYTES:-536870912000}" OWNER_UPLOAD_QUOTA_BYTES: "${OWNER_UPLOAD_QUOTA_BYTES:-53687091200}" MAX_PENDING_UPLOADS: "10" - # ClamAV scans up to this; larger files (up to MAX_UPLOAD_BYTES) are released - # after a file-format check instead (app/scanning.py). - SCAN_MAX_BYTES: "2097152000" + # ClamAV scans up to this, so every file up to MAX_UPLOAD_BYTES is scanned; + # a larger one would be released after a file-format check (app/scanning.py). + SCAN_MAX_BYTES: "1073741824" services: db: diff --git a/docs/CONTEXT.md b/docs/CONTEXT.md index d6d283e..fbdfd7b 100644 --- a/docs/CONTEXT.md +++ b/docs/CONTEXT.md @@ -337,6 +337,17 @@ longer printing the product hands its automatic orders, not yet printing, to that choice again. Only operators are linked to machines (from the user or the machine form); a linked operator sees only those machines' orders. +Dropstar's corrections of 2026-10-21 already done: the home example priced as +a ready sheet; opening hours 7h to 18h with "send your art any time"; uploads +up to 1 GB (MAX_UPLOAD_BYTES, scanned whole by ClamAV); a Designer profile +(artwork stages only, every order, no machine, queue or cancelling; +DESIGNER_STATES in app/core/auth.py, the "print" capability for the room's +side); Números by date range, per machine (metres finished, metres per hour +in Imprimindo, last finished, now) and orders apart from passages. Waiting on +Dropstar: the Tiny category/seller/tag conflict, residue and opaque background +blocking, the print-file footer, the packing margins, the DTF terms, the +manual-file value, the proof print, and mirroring. + ### Active localhost milestone (2026-09-15) The current implementation target is localhost before any production connection. diff --git a/tests/artwork_browser_test.mjs b/tests/artwork_browser_test.mjs index d7e946f..074f236 100644 --- a/tests/artwork_browser_test.mjs +++ b/tests/artwork_browser_test.mjs @@ -156,14 +156,14 @@ try{ assert.deepEqual(await evaluate(`({shown:!$('tipoEnvio').hidden, on:[...document.querySelectorAll('#tipoEnvio .cam.on')].map(b=>b.dataset.tipo)})`), {shown:true,on:['folha']}); - await evaluate(`(()=>{const f=new File(['x'],'oversize.cdr');Object.defineProperty(f,'size',{value:5*1073741824+1});sel([f]);})()`); - assert.equal(await evaluate(`folhas.length===0 && $('recusa').textContent.includes('5 GB')`),true, - 'files beyond the 5 GB upload limit are rejected before browser analysis'); - // A multi-GB sheet is the normal order: graded from the pixel size in its + await evaluate(`(()=>{const f=new File(['x'],'oversize.cdr');Object.defineProperty(f,'size',{value:1073741824+1});sel([f]);})()`); + assert.equal(await evaluate(`folhas.length===0 && $('recusa').textContent.includes('1 GB')`),true, + 'files beyond the 1 GB upload limit are rejected before browser analysis'); + // A large sheet (here 900 MB) is the normal order: graded from the pixel size in its // header, never decoded. 6732 x 35433 px across 57 cm is 3 m at 300 DPI. await evaluate(`(()=>{const h=new Uint8Array(33);h.set([0x89,0x50,0x4E,0x47,0x0D,0x0A,0x1A,0x0A,0,0,0,13,0x49,0x48,0x44,0x52]); const v=new DataView(h.buffer);v.setUint32(16,6732);v.setUint32(20,35433);h.set([8,6,0,0,0],24); - const f=new File([h],'folha-grande.png');Object.defineProperty(f,'size',{value:3*1073741824});sel([f]);})()`); + const f=new File([h],'folha-grande.png');Object.defineProperty(f,'size',{value:900*1048576});sel([f]);})()`); await waitFor(()=>evaluate(`folhas.length===1 && !!folhas[0].an`),'large sheet graded from its header'); assert.deepEqual(await evaluate(`({grande:folhas[0].an.grande,dpi:folhas[0].an.dpi,alt:folhas[0].med.alt,preview:!!folhas[0].previewSrc})`), {grande:true,dpi:300,alt:300,preview:false}); diff --git a/tests/kanban_test.py b/tests/kanban_test.py index b3d9068..632c520 100644 --- a/tests/kanban_test.py +++ b/tests/kanban_test.py @@ -126,6 +126,24 @@ def run(): assert after['daily'][-1]['orders'] == before['daily'][-1]['orders'] + 1 assert after['waiting']['rec']['orders'] == before.get('waiting', {}).get('rec', {}).get('orders', 0) + 1 client.call('/operator/stats?days=3', operator=True, expected=422) + # Or two dates: the same week asked as a range gives the same numbers. + week = client.call(f"/operator/stats?start={after['start']}&end={after['end']}", operator=True) + assert (week['orders'], week['cents'], len(week['daily'])) == (after['orders'], after['cents'], 7), week + one = client.call(f"/operator/stats?start={after['end']}&end={after['end']}", operator=True) + assert len(one['daily']) == 1 and one['daily'][0] == after['daily'][-1] + client.call(f"/operator/stats?start={after['end']}&end={after['start']}", operator=True, expected=422) + client.call(f"/operator/stats?start={after['start']}", operator=True, expected=422) + client.call('/operator/stats?start=2025-01-01&end=2026-12-31', operator=True, expected=422) + assert isinstance(after['machines'], list) + # An order sent back counts once per stage; its passages are counted apart. + with db.connect() as c: + for step, (frm, to) in enumerate((('rec', 'tra'), ('tra', 'cor'), ('cor', 'tra'), ('tra', 'fil'))): + c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason,back,created_at) + VALUES(%s,%s,%s,'kanban-test','',false,now()+%s*interval '1 second')''', (order_id, frm, to, step + 1)) + moved = client.call('/operator/stats?days=7', operator=True) + tra_before = after['stages'].get('tra', {'orders': 0, 'passages': 0}) + assert moved['stages']['tra']['orders'] == tra_before['orders'] + 1, moved['stages'] + assert moved['stages']['tra']['passages'] == tra_before['passages'] + 2, moved['stages'] # The company's name from the registry: on the board, and found by the search. from app import cnpj as registry @@ -158,6 +176,7 @@ def run(): 'and a backup asked for now') finally: with db.connect() as c: + c.execute('DELETE FROM dtf_local.movements WHERE order_id=%s', (order_id,)) c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (order_id,)) c.execute('DELETE FROM dtf_local.quotes WHERE id=ANY(%s)', ([pending, approved, paid],)) c.execute('DELETE FROM dtf_local.upload_thumbnails WHERE upload_id=%s', (uid,)) diff --git a/tests/smoke_test.py b/tests/smoke_test.py index 36d4a74..0b18d05 100644 --- a/tests/smoke_test.py +++ b/tests/smoke_test.py @@ -117,8 +117,8 @@ def run(): client=Client();other=Client() config=client.call('/session');other.call('/session') assert client.call('/health')['integrations']=='fake' - # Sheets of several GB are the normal order: 5 GB per file. - assert config['max_upload_bytes'] == 5 * 1024 ** 3 + # 1 GB per file: a 57 cm x 5 m sheet at 300 DPI is 200 to 300 MB. + assert config['max_upload_bytes'] == 1024 ** 3 client.call('/uploads',{'name':'too-large.cdr', 'size':config['max_upload_bytes']+1},expected=413) cancelled=client.call('/uploads',{'name':'CANCELLED-PART.cdr','size':3})['id'] diff --git a/tests/users_test.py b/tests/users_test.py index 2a42ce9..6d01b67 100644 --- a/tests/users_test.py +++ b/tests/users_test.py @@ -67,7 +67,7 @@ def run(): su = Client() su.call('/session') assert su.call('/operator/me', operator=True)['role'] == 'superadmin' - emails = {r: f'{r}-{tag}@example.test' for r in ('admin', 'operador', 'vendedor')} + emails = {r: f'{r}-{tag}@example.test' for r in ('admin', 'operador', 'vendedor', 'designer')} owner = uuid4() machines, made = [], [] try: @@ -140,6 +140,24 @@ def run(): seller.call(f'/operator/orders/{textil_o}/machine', {'machine_id': None}, expected=403) seller.call(f'/operator/orders/{textil_o}/contact', {'waiting': True, 'note': 'Ligar'}, expected=403) assert seller.call('/operator/me')['can'] == ['view'] + # The designer: every order, whatever its machine; the artwork stages only. + admin.call('/operator/users', {'name': 'Arte', 'email': emails['designer'], 'role': 'designer', + 'password': PASSWORD, 'machines': [uv]}) + assert next(u for u in admin.call('/operator/users')['users'] if u['email'] == emails['designer'])['machines'] == [] + designer = signed_in(emails['designer']) + assert set(designer.call('/operator/me')['can']) == {'view', 'produce'} + assert {str(uv_o), str(textil_o)} <= {o['id'] for o in designer.call('/operator/board')['orders']} + version = next(o for o in designer.call('/operator/board')['orders'] if o['id'] == str(textil_o))['version'] + moved = designer.call(f'/operator/orders/{textil_o}/move', {'state': 'tra', 'version': version, 'reason': ''}) + designer.call(f'/operator/orders/{textil_o}/move', {'state': 'fil', 'version': moved['version'], 'reason': ''}, + expected=403) + designer.call(f'/operator/orders/{textil_o}/move', {'state': 'rec', 'version': moved['version'], + 'reason': 'arte trocada'}) + designer.call(f'/operator/orders/{textil_o}/machine', {'machine_id': None}, expected=403) + designer.call(f'/operator/orders/{textil_o}/cancel', {'note': 'não pode'}, expected=403) + designer.call('/operator/queue/finals', expected=403) + designer.call('/operator/users', expected=403) + # Their own password: the current one is asked for. seller.call('/operator/me/password', {'current': 'errada', 'new': 'outra-senha-de-teste'}, expected=403) # Eight characters or more. @@ -191,6 +209,21 @@ def run(): board = {o['id']: o for o in su.call('/operator/board', operator=True)['orders']} assert not board[second]['machine']['chosen'] + # Números per machine: an order printed for half an hour on its machine, then finished. + before = {m['id']: m for m in su.call('/operator/stats?days=7', operator=True)['machines']} + with db.connect() as c: + # A real payment: Números leaves test orders out. + c.execute('UPDATE dtf_local.orders SET payment=%s WHERE id=%s', + (Jsonb({'provider': 'mercadopago', 'id': f'users-{tag}'}), third)) + for frm, to, at in (('rec', 'imp', "now()-interval '30 minutes'"), ('imp', 'fin', 'now()')): + c.execute(f'''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason,back,created_at) + VALUES(%s,%s,%s,'users-test','',false,{at})''', (third, frm, to)) + after = {m['id']: m for m in su.call('/operator/stats?days=7', operator=True)['machines']} + assert after[target]['orders'] == before[target]['orders'] + 1 + assert after[target]['metres'] == before[target]['metres'] + 1.0 + assert after[target]['last_finished'] and after[target]['metres_per_hour'] is not None + assert after[target]['printing_hours'] >= before[target]['printing_hours'] + 0.49 + # Switched off, a machine gives its automatic orders to another one. with db.connect() as c: c.execute('UPDATE dtf_local.orders SET machine_id=%s, machine_chosen=false WHERE id=%s', (textil2, second)) diff --git a/web/index.html b/web/index.html index 3fdb3a7..c3c7abf 100644 --- a/web/index.html +++ b/web/index.html @@ -735,9 +735,9 @@ h2 em{font-style:normal;color:var(--laranja)}
-
Metragem0,60 m
+
Metragem1,20 m
Nota da arte92
-
Preço do metroR$ 24,90
+
Preço do metroR$ 14,90
@@ -839,7 +839,7 @@ h2 em{font-style:normal;color:var(--laranja)}
Arraste aqui - Até 5 GB por arquivo. + Até 1 GB por arquivo. ou escolher no computador Adicionar outra folha ou arraste aqui Tem CDR, AI, PSD ou TIFF? Pode mandar também. @@ -1036,7 +1036,7 @@ h2 em{font-style:normal;color:var(--laranja)}
Retirar em Franca Av. Major Elias Motta, 1281 · Jardim São Luís
- Segunda a sexta, das 7h às 17h
+ Segunda a sexta, das 7h às 18h
Grátis @@ -1157,7 +1157,8 @@ h2 em{font-style:normal;color:var(--laranja)} 16 99428-0056 · arquivos 16 99230-2546
atendimentodropstar@gmail.com
- Segunda a sexta, 07h às 17h + Mande sua arte em qualquer horário.
+ Retirada em Franca, de segunda a sexta, das 7h às 18h
diff --git a/web/kanban.css b/web/kanban.css index cd5d121..5fc17c1 100644 --- a/web/kanban.css +++ b/web/kanban.css @@ -230,6 +230,10 @@ main{padding:0 24px 24px} .pagehead{display:flex;align-items:center;gap:16px;flex-wrap:wrap} .statchips{display:flex;gap:8px;margin-left:auto} .stats-note{margin:-12px 0 0;font-size:13.5px} +.stats-hint{margin:-4px 0 10px;font-size:13px} +.daterange{display:flex;align-items:center;gap:6px} +.daterange input[type=date]{height:34px;padding:0 8px;border-radius:8px;border:1px solid var(--line2);background:var(--bg);color:var(--tx);font:inherit;font-size:13.5px;color-scheme:dark} +.statchips{flex-wrap:wrap} .kpis{display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:12px} .kpi{display:flex;flex-direction:column;gap:4px;padding:14px 16px;border:1px solid var(--line2);border-radius:12px;background:var(--card)} .kpi span{font-size:13.5px;color:var(--muted)} @@ -461,7 +465,7 @@ a.zap{display:inline-flex;align-items:center;gap:4px;vertical-align:bottom} #tab-users .pagehead .btn{margin-left:auto} #tab-users td.actions{text-align:right;white-space:nowrap} #tab-users td.actions .btn+.btn{margin-left:6px} -#tab-users tr.off td{opacity:.55} +#tab-users tr.off td,#tab-stats tr.off td{opacity:.55} .faint.block{display:block;font-size:13px} .danger-text{color:var(--bad)} .machine-select{height:36px;padding:0 10px;border-radius:8px;border:1px solid var(--line3);background:var(--bg);color:var(--tx);font:inherit;font-size:14px} diff --git a/web/kanban.html b/web/kanban.html index e9f2779..ced3eae 100644 --- a/web/kanban.html +++ b/web/kanban.html @@ -78,9 +78,13 @@
diff --git a/web/site-upload.js b/web/site-upload.js index a7e9603..fd34818 100644 --- a/web/site-upload.js +++ b/web/site-upload.js @@ -37,7 +37,7 @@ function sel(fs){ const fora = fs.filter(f=>!regra.test(f.name)); fs = fs.filter(f=>regra.test(f.name)); recusa(fora); - const max=window.dtfUploadMaxBytes||5*1073741824; + const max=window.dtfUploadMaxBytes||1073741824; const grandes=fs.filter(f=>f.size>max); if(grandes.length){ const el=$('recusa');