feat: Dropstar's corrections of 21/10 that need no answer from them
All checks were successful
Build and deploy / Validate source (push) Successful in 1m30s
Build and deploy / Integration suite on a real stack (push) Successful in 4m2s
Build and deploy / Secret scan and release gate (push) Successful in 14s
Build and deploy / Publish images (push) Successful in 1m48s
All checks were successful
Build and deploy / Validate source (push) Successful in 1m30s
Build and deploy / Integration suite on a real stack (push) Successful in 4m2s
Build and deploy / Secret scan and release gate (push) Successful in 14s
Build and deploy / Publish images (push) Successful in 1m48s
- 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 <noreply@anthropic.com>
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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'},
|
||||
|
||||
@@ -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'))
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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).
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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).
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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});
|
||||
|
||||
@@ -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,))
|
||||
|
||||
@@ -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']
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -735,9 +735,9 @@ h2 em{font-style:normal;color:var(--laranja)}
|
||||
<i style="left:75%;top:63%;width:22%;height:26%;background:#E9C23A"></i>
|
||||
</div>
|
||||
<div class="hf-num">
|
||||
<div><span>Metragem</span><b>0,60 m</b></div>
|
||||
<div><span>Metragem</span><b>1,20 m</b></div>
|
||||
<div><span>Nota da arte</span><b class="verde">92</b></div>
|
||||
<div><span>Preço do metro</span><b class="laranja">R$ 24,90</b></div>
|
||||
<div><span>Preço do metro</span><b class="laranja">R$ 14,90</b></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -839,7 +839,7 @@ h2 em{font-style:normal;color:var(--laranja)}
|
||||
<div class="zona" id="zona" tabindex="0" role="button">
|
||||
<div class="ico"><svg class="ic" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="m17 8-5-5-5 5"/><path d="M12 3v12"/></svg></div>
|
||||
<b id="zTit">Arraste aqui</b><span id="zSub"></span>
|
||||
<span id="zLimite">Até 5 GB por arquivo.</span>
|
||||
<span id="zLimite">Até 1 GB por arquivo.</span>
|
||||
<span class="bt">ou escolher no computador</span>
|
||||
<span class="zOutra"><b id="zOutra">Adicionar outra folha</b> ou arraste aqui</span>
|
||||
<span class="zManual" id="zManual">Tem <b>CDR, AI, PSD ou TIFF</b>? Pode mandar também.
|
||||
@@ -1036,7 +1036,7 @@ h2 em{font-style:normal;color:var(--laranja)}
|
||||
<div>
|
||||
<b><svg class="ic" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M20 10c0 4.99-5.54 10.19-7.4 11.8a1 1 0 0 1-1.2 0C9.54 20.19 4 14.99 4 10a8 8 0 0 1 16 0"/><circle cx="12" cy="10" r="3"/></svg>Retirar em Franca</b>
|
||||
<span>Av. Major Elias Motta, 1281 · Jardim São Luís<br>
|
||||
Segunda a sexta, das 7h às 17h</span>
|
||||
Segunda a sexta, das 7h às 18h</span>
|
||||
</div>
|
||||
<em>Grátis</em>
|
||||
</button>
|
||||
@@ -1157,7 +1157,8 @@ h2 em{font-style:normal;color:var(--laranja)}
|
||||
<a href="https://wa.me/message/NJ76CLIOUGXLB1" target="_blank" rel="noopener">16 99428-0056</a>
|
||||
· arquivos 16 99230-2546<br>
|
||||
<a href="mailto:atendimentodropstar@gmail.com">atendimentodropstar@gmail.com</a><br>
|
||||
Segunda a sexta, 07h às 17h
|
||||
Mande sua arte em qualquer horário.<br>
|
||||
Retirada em Franca, de segunda a sexta, das 7h às 18h
|
||||
</div>
|
||||
</div>
|
||||
<div class="fbase">
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -78,9 +78,13 @@
|
||||
</section>
|
||||
<section id="tab-stats" class="page" hidden>
|
||||
<div class="pagehead"><h1>Números</h1><div class="statchips" id="stats-period"></div></div>
|
||||
<p class="faint stats-note">Pedidos pagos no período. Pedidos de teste e cancelados ficam de fora.</p>
|
||||
<p class="faint stats-note" id="stats-note">Pedidos pagos no período. Pedidos de teste e cancelados ficam de fora.</p>
|
||||
<div class="kpis" id="stats-kpis"></div>
|
||||
<section class="statbox"><h2>Metros por dia</h2><div class="chart" id="stats-chart"></div></section>
|
||||
<section class="statbox"><h2>Por máquina</h2>
|
||||
<p class="faint stats-hint">Pedidos que chegaram a Finalizado no período, na máquina em que estavam. Metros por hora: o tempo que ficaram em Imprimindo.</p>
|
||||
<table class="log"><thead><tr><th scope="col">Máquina</th><th scope="col">Impresso</th><th scope="col">Metros por hora</th><th scope="col">Último finalizado</th><th scope="col">Agora</th></tr></thead><tbody id="stats-machines"></tbody></table>
|
||||
</section>
|
||||
<section class="statbox"><h2>Tempo em cada etapa</h2>
|
||||
<table class="log"><thead><tr><th scope="col">Etapa</th><th scope="col">Tempo mediano</th><th scope="col">Pedidos que passaram</th><th scope="col">Agora</th></tr></thead><tbody id="stats-stages"></tbody></table>
|
||||
</section>
|
||||
@@ -88,7 +92,8 @@
|
||||
<section id="tab-users" class="page" hidden>
|
||||
<div class="pagehead"><h1>Usuários</h1><button class="btn primary" id="new-user" type="button">Novo usuário</button></div>
|
||||
<p class="faint stats-note">Quem entra no Kanban e o que cada perfil pode fazer. Administrador: tudo, inclusive esta página.
|
||||
Gestão: tudo, menos usuários. Operador: move pedidos e aprova arquivos. Vendedor: só consulta.</p>
|
||||
Gestão: tudo, menos usuários. Designer: aprova arquivos e pede correção, em Arte recebida, Arte conferida e Correção.
|
||||
Operador: move pedidos e aprova arquivos. Vendedor: só consulta.</p>
|
||||
<section class="statbox"><table class="log"><thead><tr><th scope="col">Nome</th><th scope="col">Perfil</th><th scope="col">Máquinas</th><th scope="col">Último acesso</th><th scope="col"></th></tr></thead><tbody id="users-list"></tbody></table></section>
|
||||
<div class="pagehead"><h2>Máquinas</h2><button class="btn" id="new-machine" type="button">Nova máquina</button></div>
|
||||
<p class="faint stats-note">Cada pedido vai para a máquina do produto com menos metros em aberto, dentro do limite. No pedido dá para trocar.</p>
|
||||
|
||||
@@ -36,10 +36,13 @@ let quoteQuery='', quoteProduct='', quoteLayout='', quoteFlag='', quoteTimer=nul
|
||||
// The signed-in operator and what their profile allows (app/core/auth.py).
|
||||
let ME=null;
|
||||
const may=cap=>!!ME?.can?.includes(cap);
|
||||
const ROLE_NAMES={superadmin:'Superadmin',admin:'Administrador',gestao:'Gestão',operador:'Operador',vendedor:'Vendedor'};
|
||||
const ROLE_NAMES={superadmin:'Superadmin',admin:'Administrador',gestao:'Gestão',designer:'Designer',operador:'Operador',vendedor:'Vendedor'};
|
||||
// The designer moves cards only among the artwork stages; the queue onwards is the print room's (app/core/auth.py).
|
||||
const DESIGNER_STATES=['rec','tra','cor'];
|
||||
const mayMove=(from,to)=>may('produce')&&(ME?.role!=='designer'||DESIGNER_STATES.includes(from)&&DESIGNER_STATES.includes(to));
|
||||
// Which tabs each capability opens.
|
||||
const TAB_NEEDS={quotes:o=>may('manage')||ME?.role==='vendedor',payments:()=>may('manage'),
|
||||
stats:()=>may('manage')||ME?.role==='vendedor',integrations:()=>may('manage')||may('produce'),users:()=>may('users')};
|
||||
stats:()=>may('manage')||ME?.role==='vendedor',integrations:()=>may('manage')||may('print'),users:()=>may('users')};
|
||||
function applyRole(){
|
||||
for(const b of document.querySelectorAll('[data-tab]')){const need=TAB_NEEDS[b.dataset.tab];b.hidden=!!need&&!need();}
|
||||
if(TAB_NEEDS[tab]&&!TAB_NEEDS[tab]())showTab('board');
|
||||
@@ -300,7 +303,7 @@ function folderCount(){
|
||||
// The folder's row and the tab's warning sign, which shows the folder needs a click.
|
||||
function paintFolder(){
|
||||
$('folder-card')?.replaceWith(folderCard());
|
||||
const attention=may('produce')&&(FOLDER.mode==='folder'&&!!FOLDER.handle&&!FOLDER.granted||folderActive()&&!!FOLDER.error);
|
||||
const attention=may('print')&&(FOLDER.mode==='folder'&&!!FOLDER.handle&&!FOLDER.granted||folderActive()&&!!FOLDER.error);
|
||||
$('badge-integrations').textContent=attention?'!':'';
|
||||
}
|
||||
async function chooseFolder(){
|
||||
@@ -373,7 +376,7 @@ async function moveToQueue(rec){
|
||||
// board load it asks only when something it follows changed; the folder's
|
||||
// own timer always asks, since another computer may have moved the order.
|
||||
async function syncFolder(force=false){
|
||||
if(!folderActive()||FOLDER.busy||!board||!may('produce'))return;
|
||||
if(!folderActive()||FOLDER.busy||!board||!may('print'))return;
|
||||
const follows=early()?['rec','tra','cor','fil']:['fil'];
|
||||
const sig=FOLDER.when+'|'+board.orders.filter(o=>follows.includes(o.state)||o.cancelled_at)
|
||||
.map(o=>o.id+':'+o.version+':'+o.state+(o.cancelled_at?':x':'')).join(',');
|
||||
@@ -600,7 +603,7 @@ function renderBoard(){
|
||||
const count=state==='fin'&&board.finished_total>orders.length?orders.length+' de '+board.finished_total:String(orders.length);
|
||||
line.append(swatch,node('h2',title),node('span',count,'n'));
|
||||
// The print queue's tools need the room: there it says only the metres.
|
||||
const tools=state==='fil'&&may('produce');
|
||||
const tools=state==='fil'&&may('print');
|
||||
const sub=node('div',undefined,'col-sub');sub.append(node('small',orders.length?metres(total)+(tools?'':' no total'):'vazio'));
|
||||
// The print queue's files, all at once, to import into FlexiPRINT.
|
||||
if(tools){
|
||||
@@ -615,7 +618,7 @@ function renderBoard(){
|
||||
// Dragging only goes forward to the next stage. Going back or asking for a
|
||||
// correction needs a reason, so those happen in the order panel.
|
||||
column.ondragover=e=>{
|
||||
if(dragging?.state===state&&state!=='fin'){e.preventDefault();markDrop(column,e.clientY);return;}
|
||||
if(dragging?.state===state&&state!=='fin'&&mayMove(state,state)){e.preventDefault();markDrop(column,e.clientY);return;}
|
||||
if(!column.classList.contains('allowed'))return;e.preventDefault();column.classList.add('target');};
|
||||
column.ondragleave=e=>{if(!column.contains(e.relatedTarget)){column.classList.remove('target');clearDrop();}};
|
||||
column.ondrop=async e=>{e.preventDefault();column.classList.remove('target');
|
||||
@@ -632,7 +635,7 @@ function renderBoard(){
|
||||
// An operator's test order: no payment, no Tiny.
|
||||
const isTest=order=>order.payment?.provider==='teste';
|
||||
function card(order){
|
||||
const c=node('button',undefined,'card');c.type='button';c.dataset.card=order.id;c.draggable=!order.cancelled_at&&may('produce');
|
||||
const c=node('button',undefined,'card');c.type='button';c.dataset.card=order.id;c.draggable=!order.cancelled_at&&mayMove(order.state,order.state);
|
||||
if(order.id===openOrder)c.classList.add('open');
|
||||
const s=order.snapshot;
|
||||
const top=node('div',undefined,'row');
|
||||
@@ -657,7 +660,7 @@ function card(order){
|
||||
c.ondragstart=e=>{
|
||||
dragging=order;
|
||||
e.dataTransfer.setData('text/plain',order.id);
|
||||
const forward=board.transitions[order.state].filter(s=>s!=='cor');
|
||||
const forward=board.transitions[order.state].filter(s=>s!=='cor'&&mayMove(order.state,s));
|
||||
for(const col of document.querySelectorAll('.col[data-state]'))col.classList.toggle('allowed',forward.includes(col.dataset.state));
|
||||
say((forward.length?'Mover para '+forward.map(s=>board.states[s]).join(' ou ')+', ou ':'')+'arraste para cima ou para baixo para mudar a prioridade',false,60000);
|
||||
};
|
||||
@@ -806,6 +809,7 @@ function moves(order){
|
||||
let step=null;
|
||||
for(const next of board.transitions[order.state]){
|
||||
if(next==='cor'){
|
||||
if(!mayMove(order.state,next))continue;
|
||||
const b=node('button','Pedir correção','btn danger');b.type='button';b.dataset.move='cor';
|
||||
b.onclick=()=>toggle(reason);row.append(b);
|
||||
}else if(next==='fil'&&!finalDone(order)){
|
||||
@@ -832,13 +836,13 @@ function moves(order){
|
||||
upload.append(cancel);sync=()=>{actions.hidden=!upload.hidden;};
|
||||
text.append(actions,upload);
|
||||
step=node('div',undefined,'nextstep lead');step.append(node('span','!','nextmark'),text);
|
||||
}else{
|
||||
}else if(mayMove(order.state,next)){
|
||||
const b=button('Mover para '+board.states[next],()=>move(order,next),'btn primary');b.dataset.move=next;row.append(b);
|
||||
}
|
||||
}
|
||||
if(!row.children.length)row.append(node('span','Pedido concluído.','muted'));
|
||||
if(!row.children.length)row.append(node('span',order.state==='fin'?'Pedido concluído.':'Daqui em diante, com a produção.','muted'));
|
||||
// Undo a mistaken move: one stage back, internal reason, no customer message.
|
||||
const previous=board.back?.[order.state];
|
||||
const previous=mayMove(order.state,board.back?.[order.state])?board.back?.[order.state]:null;
|
||||
const sub=node('div',undefined,'subactions');
|
||||
const backForm=node('form',undefined,'reason');backForm.hidden=true;forms.push(backForm);
|
||||
if(previous){
|
||||
@@ -949,7 +953,7 @@ async function approveReady(order,ready){
|
||||
ready.map((r,i)=>(many?'Item '+(i+1)+': ':'')+r.label).join('\n')))return;
|
||||
const note='Aprovado como está: '+[...new Set(ready.map(r=>FINAL_SOURCE[r.source]))].join(', ');
|
||||
await api('/orders/'+order.id+'/final-files',{version:order.version,files:ready.map((r,i)=>({item_index:i,upload_id:r.upload_id})),note});
|
||||
await load();say('Arquivo final aprovado. Agora é só mover para a fila.');
|
||||
await load();say(mayMove(order.state,'fil')?'Arquivo final aprovado. Agora é só mover para a fila.':'Arquivo final aprovado. A produção coloca na fila.');
|
||||
}
|
||||
// The form for a file the operator prepared, or to pick per item; ready
|
||||
// files come ticked.
|
||||
@@ -1078,7 +1082,7 @@ function historySection(order,rows,section){
|
||||
function machineCard(order){
|
||||
const box=node('div',undefined,'fcard');box.append(node('p','Máquina','eyebrow'));
|
||||
const current=order.machine;
|
||||
if(!may('produce')||!board.machines?.length){
|
||||
if(!may('print')||!board.machines?.length){
|
||||
box.append(node('b',current?current.name:'Nenhuma máquina cadastrada'));return box;
|
||||
}
|
||||
const select=node('select',undefined,'machine-select');select.setAttribute('aria-label','Máquina do pedido');
|
||||
@@ -1174,7 +1178,7 @@ function userForm(u){
|
||||
const name=node('input');name.required=true;name.maxLength=80;name.value=u?.name||'';
|
||||
const email=node('input');email.type='email';email.required=true;email.value=u?.email||'';
|
||||
const role=node('select');
|
||||
const roles=u?.role==='superadmin'?['superadmin']:['admin','gestao','operador','vendedor'];
|
||||
const roles=u?.role==='superadmin'?['superadmin']:['admin','gestao','designer','operador','vendedor'];
|
||||
for(const r of roles){const o=node('option',ROLE_NAMES[r]);o.value=r;role.append(o);}
|
||||
role.value=u?.role||'operador';role.disabled=u?.role==='superadmin'||u?.email===ME.email;
|
||||
const pass=node('input');pass.type='password';pass.minLength=8;pass.maxLength=128;pass.autocomplete='new-password';
|
||||
@@ -1228,18 +1232,36 @@ $('new-machine').onclick=()=>machineForm(null);
|
||||
|
||||
// ---- Numbers -------------------------------------------------------------
|
||||
|
||||
let statsDays=30;
|
||||
// The period: the last 7, 30 or 90 days, or two dates the person picks.
|
||||
let statsDays=30, statsRange=null;
|
||||
function duration(hours){
|
||||
if(hours===null||hours===undefined)return '—';
|
||||
if(hours<1)return Math.max(1,Math.round(hours*60))+' min';
|
||||
if(hours<48)return (hours<10?hours.toFixed(1):Math.round(hours).toString()).replace('.',',')+' h';
|
||||
return Math.round(hours/24)+' dias';
|
||||
}
|
||||
const dayLabel=iso=>new Date(iso+'T12:00:00').toLocaleDateString('pt-BR',{day:'2-digit',month:'2-digit',year:'numeric'});
|
||||
function statsPeriod(){
|
||||
const box=$('stats-period');
|
||||
const chips=[[7,'7 dias'],[30,'30 dias'],[90,'90 dias']].map(([days,label])=>{
|
||||
const b=node('button',label,'chip');b.type='button';b.setAttribute('aria-pressed',String(!statsRange&&days===statsDays));
|
||||
b.onclick=()=>{statsDays=days;statsRange=null;loadStats().catch(e=>say(e.message,true));};return b;});
|
||||
const from=node('input');from.type='date';from.setAttribute('aria-label','De');
|
||||
const to=node('input');to.type='date';to.setAttribute('aria-label','Até');
|
||||
const today=new Date(Date.now()-3*3600e3).toISOString().slice(0,10);
|
||||
from.max=to.max=today;
|
||||
if(statsRange){from.value=statsRange.start;to.value=statsRange.end;}
|
||||
const apply=button('Ver',()=>{
|
||||
if(!from.value||!to.value)return say('Escolha a data inicial e a final.',true);
|
||||
if(from.value>to.value)return say('A data inicial é depois da final.',true);
|
||||
statsRange={start:from.value,end:to.value};loadStats().catch(e=>say(e.message,true));},'btn small');
|
||||
const range=node('div',undefined,'daterange');range.append(from,node('span','até','faint'),to,apply);
|
||||
box.replaceChildren(...chips,range);
|
||||
}
|
||||
async function loadStats(){
|
||||
const data=await api('/stats?days='+statsDays);
|
||||
$('stats-period').replaceChildren(...[[7,'7 dias'],[30,'30 dias'],[90,'90 dias']].map(([days,label])=>{
|
||||
const b=node('button',label,'chip');b.type='button';b.setAttribute('aria-pressed',String(days===statsDays));
|
||||
b.onclick=()=>{statsDays=days;loadStats().catch(e=>say(e.message,true));};return b;}));
|
||||
const data=await api('/stats?'+(statsRange?'start='+statsRange.start+'&end='+statsRange.end:'days='+statsDays));
|
||||
statsPeriod();
|
||||
$('stats-note').textContent='Pedidos pagos de '+dayLabel(data.start)+' a '+dayLabel(data.end)+'. Pedidos de teste e cancelados ficam de fora.';
|
||||
const kpi=(label,value,note)=>{const k=node('div',undefined,'kpi');k.append(node('span',label),node('b',value));if(note)k.append(node('small',note));return k;};
|
||||
const pct=data.orders?Math.round(100*data.corrected/data.orders):0;
|
||||
$('stats-kpis').replaceChildren(
|
||||
@@ -1250,11 +1272,24 @@ async function loadStats(){
|
||||
kpi('Pedidos com correção',String(data.corrected),data.orders?pct+'% dos pedidos':null),
|
||||
kpi('Do pagamento ao Finalizado',duration(data.lead.median_hours),data.lead.orders?'mediana de '+data.lead.orders+' pedidos':'nenhum finalizado'));
|
||||
statsChart($('stats-chart'),data.daily);
|
||||
const machineRows=data.machines.map(m=>{
|
||||
const tr=node('tr');if(!m.active)tr.classList.add('off');
|
||||
const now=[m.now.imp?m.now.imp+' imprimindo':'',m.now.fil?m.now.fil+' na fila':''].filter(Boolean).join(' · ');
|
||||
tr.append(node('td',m.name+(m.active?'':' · desativada')),
|
||||
node('td',m.orders?metres(m.metres)+' · '+m.orders+(m.orders>1?' pedidos':' pedido'):'nada'),
|
||||
node('td',m.metres_per_hour!=null?String(m.metres_per_hour).replace('.',',')+' m/h':'—'),
|
||||
node('td',m.last_finished?when(m.last_finished):'nunca','faint'),
|
||||
node('td',m.id?now||'nada na fila':'—'));
|
||||
return tr;});
|
||||
if(!machineRows.length){const tr=node('tr');const td=node('td','Nenhuma máquina cadastrada.','faint');td.colSpan=5;tr.append(td);machineRows.push(tr);}
|
||||
$('stats-machines').replaceChildren(...machineRows);
|
||||
const rows=['rec','tra','fil','imp','cor'].map(state=>{
|
||||
const tr=node('tr'),name=node('td'),sw=node('span',undefined,'swatch');sw.style.setProperty('--c',STAGE_COLORS[state]);
|
||||
name.append(sw,board.states[state]);
|
||||
const st=data.stages[state], now=data.waiting[state];
|
||||
tr.append(name,node('td',st?duration(st.median_hours):'—'),node('td',st?String(st.orders):'0'),
|
||||
// Orders; when some came back to the stage, how many times it was entered.
|
||||
const passed=st?String(st.orders)+(st.passages>st.orders?' · '+st.passages+' passagens':''):'0';
|
||||
tr.append(name,node('td',st?duration(st.median_hours):'—'),node('td',passed),
|
||||
node('td',now?now.orders+(now.orders>1?' pedidos':' pedido')+' · o mais antigo há '+duration(now.oldest_hours):'nenhum'));
|
||||
return tr;});
|
||||
$('stats-stages').replaceChildren(...rows);
|
||||
@@ -1267,7 +1302,7 @@ function statsChart(box,daily){
|
||||
const step=max<=0?1:(()=>{const raw=max/4, p=10**Math.floor(Math.log10(raw)), f=raw/p;return (f<=1?1:f<=2?2:f<=5?5:10)*p;})();
|
||||
const ceiling=step*Math.max(1,Math.ceil(max/step));
|
||||
const svg=document.createElementNS(ns,'svg');svg.setAttribute('viewBox','0 0 '+w+' '+h);svg.setAttribute('role','img');
|
||||
svg.setAttribute('aria-label','Metros vendidos por dia nos últimos '+daily.length+' dias');
|
||||
svg.setAttribute('aria-label','Metros vendidos por dia, '+daily.length+' dias');
|
||||
const el=(tag,attrs)=>{const e=document.createElementNS(ns,tag);for(const [k,v] of Object.entries(attrs))e.setAttribute(k,v);return e;};
|
||||
const y=v=>top+(h-top-bottom)*(1-v/ceiling);
|
||||
for(let v=0;v<=ceiling+1e-9;v+=step){
|
||||
@@ -1673,7 +1708,7 @@ const eventsIfAllowed=async()=>{if(may('integrations'))await loadEvents();};
|
||||
const integRow=o=>may('integrations')?integration(o):integration({name:o.name,state:o.state,tone:o.tone,summary:o.summary});
|
||||
let mpCheck=null;
|
||||
function renderIntegrations(){
|
||||
const t=board.tiny||{};const rows=may('produce')?[folderCard()]:[];
|
||||
const t=board.tiny||{};const rows=may('print')?[folderCard()]:[];
|
||||
$('event-log').hidden=!may('integrations');
|
||||
if(!may('manage')){$('integrations').replaceChildren(...rows);return;}
|
||||
const act=(text,fn)=>button(text,fn,'btn small');
|
||||
|
||||
@@ -208,7 +208,8 @@
|
||||
<a href="https://wa.me/message/NJ76CLIOUGXLB1" target="_blank" rel="noopener">16 99428-0056</a>
|
||||
· arquivos 16 99230-2546<br>
|
||||
<a href="mailto:atendimentodropstar@gmail.com">atendimentodropstar@gmail.com</a><br>
|
||||
Segunda a sexta, 07h às 17h
|
||||
Mande sua arte em qualquer horário.<br>
|
||||
Retirada em Franca, de segunda a sexta, das 7h às 18h
|
||||
</div>
|
||||
</div>
|
||||
<div class="fbase">
|
||||
|
||||
@@ -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');
|
||||
|
||||
Reference in New Issue
Block a user