Files
dtf-system/app/core/models.py
Cauê Faleiros c88d81588e feat: products and prices from the database, edited in the Kanban's Site tab (front 8.1)
Gestão and the administrators switch each product on and off and set its
price from a start date; a price that has started is history and cannot
change, a scheduled one can be cancelled. The Site and the server read
the current price; with no row the code's prices and TREATMENT_CENTS
still apply, so nothing changes until someone sets one. A switched-off
product disappears from the Site and new quotes with it are refused.
Approved quotes and paid orders keep their price.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-09 13:50:45 -03:00

458 lines
19 KiB
Python

import re
from datetime import date, datetime
from decimal import Decimal
from typing import Literal
from uuid import UUID
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
class StrictModel(BaseModel):
model_config = ConfigDict(extra='forbid', allow_inf_nan=False)
def check_digit(base, weights):
rem = sum(int(n) * w for n, w in zip(base, weights)) % 11
return 0 if rem < 2 else 11 - rem
def cpf_ok(digits):
return (len(digits) == 11 and len(set(digits)) > 1
and check_digit(digits[:9], range(10, 1, -1)) == int(digits[9])
and check_digit(digits[:10], range(11, 1, -1)) == int(digits[10]))
def cnpj_ok(digits):
return (len(digits) == 14 and len(set(digits)) > 1
and check_digit(digits[:12], [5,4,3,2,9,8,7,6,5,4,3,2]) == int(digits[12])
and check_digit(digits[:13], [6,5,4,3,2,9,8,7,6,5,4,3,2]) == int(digits[13]))
def person_name(value):
"""A name as typed, with its spaces tidied; at least two letters when given."""
name = ' '.join(str(value or '').split())
if name and sum(ch.isalpha() for ch in name) < 2:
raise ValueError('Invalid name')
return name
class Customer(StrictModel):
# The customer's CPF or CNPJ, digits only. The key keeps the name it had
# when only companies bought, as stored orders, quotes and accounts use it.
cnpj: str
zap: str
mail: str = Field(max_length=254)
# Who to greet: the Tiny contact and the WhatsApp notices use it. Empty in
# orders placed before the Site asked for it.
name: str = Field(default='', max_length=80)
@field_validator('name')
@classmethod
def name_valid(cls, value):
return person_name(value)
@field_validator('cnpj')
@classmethod
def document_valid(cls, value):
digits = re.sub(r'\D', '', value)
if not digits.isascii() or not (cpf_ok(digits) or cnpj_ok(digits)):
raise ValueError('Invalid CPF or CNPJ')
return digits
@field_validator('zap')
@classmethod
def phone_valid(cls, value):
digits = re.sub(r'\D', '', value)
if len(digits) not in (10,11) or not digits.isascii():
raise ValueError('Invalid phone')
return digits
@field_validator('mail')
@classmethod
def email_valid(cls, value):
if not re.fullmatch(r'[^\s@]+@[^\s@]+\.[a-zA-Z]{2,}', value.strip()):
raise ValueError('Invalid email')
return value.strip()
class Freight(StrictModel):
service: Literal['pickup','mock-standard','jadlog','pac','sedex'] = 'pickup'
postal_code: str = Field(default='', max_length=8)
class FreightEstimate(Freight):
"""The cart's estimate. The charged freight is quoted again by the server
from the approved items, never from these numbers."""
metres: Decimal | None = Field(default=None, gt=0, le=12000)
declared_cents: int = Field(default=0, ge=0, le=100_000_000, strict=True)
class FreightAsk(StrictModel):
"""Every delivery option for the cart's package to a CEP."""
postal_code: str = Field(pattern=r'^[0-9]{8}$')
metres: Decimal = Field(gt=0, le=12000)
declared_cents: int = Field(default=0, ge=0, le=100_000_000, strict=True)
UF = Literal['AC','AL','AP','AM','BA','CE','DF','ES','GO','MA','MT','MS','MG','PA','PB',
'PR','PE','PI','RJ','RN','RS','RO','RR','SC','SP','SE','TO']
class Destination(StrictModel):
"""Where a shipped order goes. A CEP alone quotes freight; it does not deliver."""
recipient: str = Field(min_length=2, max_length=120)
street: str = Field(min_length=2, max_length=160)
number: str = Field(min_length=1, max_length=20)
complement: str = Field(default='', max_length=80)
district: str = Field(min_length=2, max_length=80)
city: str = Field(min_length=2, max_length=80)
state: UF
postal_code: str = Field(pattern=r'^[0-9]{8}$')
@field_validator('recipient', 'street', 'number', 'complement', 'district', 'city', mode='before')
@classmethod
def trimmed(cls, value):
if isinstance(value, str):
value = ' '.join(value.split())
if any(ord(ch) < 32 for ch in value):
raise ValueError('Invalid characters')
return value
class UploadStart(StrictModel):
name: str = Field(min_length=1, max_length=200, pattern=r'^[^/\\\x00-\x1f]+$')
size: int = Field(gt=0, strict=True)
@field_validator('name')
@classmethod
def artwork_extension(cls, value):
# Union of existing Site product formats; this is NOT malware/pre-flight validation.
if not re.search(r'\.(png|jpe?g|webp|tiff?|pdf|psd|psb|ai|cdr)$', value, re.I):
raise ValueError('Unsupported artwork file extension')
return value
class ProductionSource(StrictModel):
upload_id: UUID
kind: Literal['sheet', 'artwork']
width_cm: Decimal = Field(gt=0, le=57)
length_cm: Decimal = Field(gt=0, le=6000)
copies: int = Field(ge=1, le=200, strict=True)
rotation_degrees: Literal[0, 90] = 0
mirrored: bool = False
measurement: Literal['file', 'customer']
class ProductionPlacement(StrictModel):
source_index: int = Field(ge=0, le=19, strict=True)
copy_index: int = Field(ge=0, le=199, strict=True)
x_cm: Decimal = Field(ge=0, le=57)
y_cm: Decimal = Field(ge=0, le=1200000)
width_cm: Decimal = Field(gt=0, le=57)
length_cm: Decimal = Field(gt=0, le=6000)
rotation_degrees: Literal[0, 90, 180, 270]
mirrored: bool
# The layout rule an order was packed with. 2: pieces 5 mm apart on a 5 mm grid,
# no margins. 3 (Dropstar, 2026-10-21): 5 mm margins top and bottom and between
# rows, and across the width 5 mm or the space left shared out equally.
PRODUCTION_VERSIONS = (2, 3)
class ProductionSpec(StrictModel):
version: Literal[2, 3]
film_width_cm: Decimal
height_cm: Decimal = Field(gt=0, le=1200000)
sources: list[ProductionSource] = Field(min_length=1, max_length=20)
placements: list[ProductionPlacement] = Field(min_length=1, max_length=4000)
class Split(StrictModel):
"""One sheet of loose art the Site split by contraction class (item 17,
Dropstar 2026-10-30): fine lines (C1, C2) on one sheet, thick (C3) on
another, each its own item and print file, billed together."""
group: str = Field(pattern=r'^[a-z0-9]{1,16}$')
part: int = Field(ge=1, le=10, strict=True)
of: int = Field(ge=2, le=10, strict=True)
def check_splits(items):
"""Every split group has each of its parts once, of one product."""
groups = {}
for item in items:
if item.split:
groups.setdefault(item.split.group, []).append(item)
for parts in groups.values():
of = parts[0].split.of
if sorted(item.split.part for item in parts) != list(range(1, of + 1)) or \
any(item.split.of != of or item.mode != parts[0].mode for item in parts):
raise ValueError('Split sheets must list each part once, of one product')
class Item(StrictModel):
mode: Literal['file','avulsa','uvfile','uv']
metres: Decimal = Field(gt=0, le=12000)
grade: int = Field(ge=0, le=100, strict=True)
uploads: list[UUID] = Field(min_length=1, max_length=20)
production: ProductionSpec
quality_status: Literal['ok', 'warning', 'unverified']
quality_acknowledged: bool
# Residue dots under 2 mm the customer accepted printing on a ready sheet,
# rather than erasing them (Dropstar, 2026-10-29): 0 when none.
residue_accepted: int = Field(default=0, ge=0, le=1000000, strict=True)
# The thinnest stroke the browser measured, in pixels at 300 DPI, and its
# contraction class (Dropstar, 2026-10-30): up to 4 C1, 5 to 19 C2, 20+ C3.
stroke_px: int | None = Field(default=None, ge=1, le=10000, strict=True)
stroke_class: Literal['C1', 'C2', 'C3'] | None = None
# A sheet with fine lines and solid areas (item 16): the customer kept the
# measure (protect the fine lines) or chose to protect the solid areas (C3).
stroke_choice: Literal['measured', 'client_c3'] | None = None
# Where the thinnest stroke sits in the assembled film, from 0 (top) to 1
# (bottom): the proof card crops a 15 cm window around it (Dropstar, 05/11).
proof_y_fraction: Decimal | None = Field(default=None, ge=0, le=1)
# The lowest source resolution the server measured, for the Prumo report
# (Dropstar, 05/11). None when the format cannot be measured.
source_dpi: int | None = Field(default=None, ge=0, le=1000000)
split: Split | None = None
@model_validator(mode='after')
def production_matches_uploads(self):
if self.split and (self.mode not in ('avulsa', 'uv') or self.split.part > self.split.of):
raise ValueError('Only loose artwork is split into sheets')
if [source.upload_id for source in self.production.sources] != self.uploads:
raise ValueError('Production sources must match uploaded files in order')
is_sheet = self.mode in ('file', 'uvfile')
# UV is 27 cm wide (Dropstar, 2026-10-28; it was 28,5).
film_width = Decimal('27') if self.mode in ('uvfile', 'uv') else Decimal('57')
if self.production.film_width_cm != film_width:
raise ValueError('Production film width does not match the product')
for source in self.production.sources:
if (source.kind == 'sheet') != is_sheet or source.width_cm > film_width:
raise ValueError('Production source does not fit the selected product')
if is_sheet and (source.rotation_degrees or source.mirrored):
raise ValueError('Finished sheets cannot be rotated or mirrored by the layout')
# A textile transfer is pressed face down: mirrored, it prints backwards.
if self.mode == 'avulsa' and source.mirrored:
raise ValueError('Textile artwork cannot be mirrored')
expected={(index,copy) for index,source in enumerate(self.production.sources)
for copy in range(source.copies)}
placed=set()
tolerance=Decimal('0.02')
for placement in self.production.placements:
key=(placement.source_index,placement.copy_index)
if key not in expected or key in placed:
raise ValueError('Production placement has a missing or duplicate source copy')
placed.add(key)
source=self.production.sources[placement.source_index]
auto_rotation=(placement.rotation_degrees-source.rotation_degrees)%360
if auto_rotation not in (0,90) or placement.mirrored != source.mirrored:
raise ValueError('Production placement changes the source transform')
width,length=(source.width_cm,source.length_cm) if auto_rotation==0 else (source.length_cm,source.width_cm)
if abs(placement.width_cm-width)>tolerance or abs(placement.length_cm-length)>tolerance:
raise ValueError('Production placement changes the source size')
if placement.x_cm+placement.width_cm>film_width+tolerance or placement.y_cm+placement.length_cm>self.production.height_cm+tolerance:
raise ValueError('Production placement is outside the film')
if is_sheet and (placement.x_cm or auto_rotation):
raise ValueError('Finished sheets must retain their original orientation')
if placed != expected:
raise ValueError('Production layout does not cover every source copy')
if self.quality_status == 'warning' and not self.quality_acknowledged:
raise ValueError('Resolution warning must be acknowledged')
return self
class ClientTimings(StrictModel):
"""What the browser measured on the way to a quote (item 0.12).
They are only numbers for Números; a cart may send none of them, and the
server never uses them to price or accept an order.
"""
page_ms: int | None = Field(default=None, ge=0, le=600000)
upload_ms: int | None = Field(default=None, ge=0, le=3600000)
upload_bytes: int | None = Field(default=None, ge=0, le=10**12)
analysis_ms: int | None = Field(default=None, ge=0, le=3600000)
montage_ms: int | None = Field(default=None, ge=0, le=3600000)
class QuoteRequest(StrictModel):
request_key: UUID
customer: Customer
items: list[Item] = Field(min_length=1, max_length=30)
freight: Freight
destination: Destination | None = None
# "Quero aprovar uma prova antes de imprimir": the order waits for the customer.
proof: bool = False
# "Quero o tratamento pelo designer": a fixed service line, when priced (front 5).
treatment: bool = False
# What the browser measured while the customer built the cart (item 0.12).
timings: ClientTimings | None = None
@model_validator(mode='after')
def splits_complete(self):
check_splits(self.items)
return self
@model_validator(mode='after')
def destination_matches_freight(self):
if self.freight.service == 'pickup':
if self.destination is not None:
raise ValueError('Pickup orders do not take a delivery address')
elif self.destination is None:
raise ValueError('Delivery requires the full address')
elif self.destination.postal_code != self.freight.postal_code:
raise ValueError('The delivery address CEP must be the CEP freight was quoted for')
return self
class Review(StrictModel):
items: list[Item] = Field(min_length=1, max_length=30)
@model_validator(mode='after')
def splits_complete(self):
check_splits(self.items)
return self
class Pay(StrictModel):
quote_id: UUID
class PaymentMethod(StrictModel):
type: Literal['pix', 'card']
# Card fields come from the provider's own form, which tokenises the card
# in the browser; the number never reaches this server.
token: str | None = Field(default=None, max_length=200)
payment_method_id: str | None = Field(default=None, max_length=40, pattern=r'^[a-z_]+$')
# Up to 3, as Dropstar sells; the card form offers no more.
installments: int = Field(default=1, ge=1, le=3, strict=True)
issuer_id: str | None = Field(default=None, max_length=40)
# The cardholder's document from the card form: for a card, the payer is
# the cardholder, not necessarily the company on the invoice.
payer_document_type: Literal['CPF', 'CNPJ'] | None = None
payer_document: str | None = Field(default=None, pattern=r'^[0-9]{11,14}$')
@model_validator(mode='after')
def card_needs_token(self):
if self.type == 'card' and not (self.token and self.payment_method_id):
raise ValueError('Card payment requires the provider token and method')
# The store takes credit cards and PIX only. Mercado Pago's debit
# methods are debvisa, debmaster, debelo...; the adapter still knows
# how to pay one, should debit be offered again.
if self.type == 'card' and self.payment_method_id.startswith('deb'):
raise ValueError('Só aceitamos cartão de crédito ou PIX.')
return self
class PaymentIntent(StrictModel):
quote_id: UUID
method: PaymentMethod
class Move(StrictModel):
state: Literal['rec','tra','imp','cor','rev','fin']
version: int = Field(ge=0)
reason: str = Field(default='', max_length=1000)
# Pulled into Imprimindo onto a machine's lane: the machine it prints on.
machine_id: UUID | None = None
class MachineEntry(StrictModel):
"""One thing entered into a machine (Fase 2, front 1a, app/machine_log.py)."""
kind: Literal['supply', 'part', 'event']
item: str = Field(min_length=1, max_length=40)
quantity: Decimal | None = Field(default=None, gt=0, le=999999, decimal_places=3)
cost_cents: int | None = Field(default=None, ge=0, le=10**12, strict=True)
serial: str | None = Field(default=None, max_length=200)
note: str | None = Field(default=None, max_length=1000)
stop_minutes: int | None = Field(default=None, gt=0, le=100000, strict=True)
from_alert: bool = False
class MachineSheet(StrictModel):
"""The machine's own data, typed by Gestão: cost, start and supply minimums."""
price_cents: int | None = Field(default=None, ge=0, le=10**12, strict=True)
installed_on: date | None = None
minimums: dict[str, Decimal | None] = Field(default_factory=dict)
class SiteProductToggle(StrictModel):
"""Ligar ou desligar um produto na aba Site (Fase 2, front 8)."""
enabled: bool
class SitePriceNew(StrictModel):
"""Um novo preço e a data em que começa; sem data, começa agora."""
unit_cents: int = Field(ge=0, le=10000000, strict=True)
starts_at: datetime | None = None
class Contraction(StrictModel):
item_index: int = Field(ge=0, le=100)
# None returns the item to the class the browser measured.
value: Literal['C1', 'C2', 'C3'] | None = None
class Resolution(StrictModel):
note: str = Field(min_length=3, max_length=1000)
class Register(StrictModel):
customer: Customer
password: str = Field(min_length=8, max_length=128)
class ProfileUpdate(StrictModel):
"""What a customer may change about their account; the CPF/CNPJ is not among it."""
zap: str
address: Destination | None = None
name: str | None = Field(default=None, max_length=80)
@field_validator('name')
@classmethod
def name_valid(cls, value):
return None if value is None else person_name(value)
@field_validator('zap')
@classmethod
def phone_valid(cls, value):
digits = re.sub(r'\D', '', value)
if len(digits) not in (10,11) or not digits.isascii():
raise ValueError('Invalid phone')
return digits
class EmailChange(StrictModel):
email: str = Field(max_length=254)
password: str = Field(min_length=1, max_length=128)
@field_validator('email')
@classmethod
def email_valid(cls, value):
value = value.strip().lower()
if not re.fullmatch(r'[^\s@]+@[^\s@]+\.[a-zA-Z]{2,}', value):
raise ValueError('Invalid email')
return value
class PasswordChange(StrictModel):
current: str = Field(min_length=1, max_length=128)
new: str = Field(min_length=8, max_length=128)
class SignupCode(StrictModel):
signup: UUID
code: str = Field(pattern=r'^[0-9]{6}$')
class SignupResend(StrictModel):
signup: UUID
class EmailCode(StrictModel):
change: UUID
code: str = Field(pattern=r'^[0-9]{6}$')
class EmailResend(StrictModel):
change: UUID
class ForgotPassword(StrictModel):
email: str = Field(min_length=3, max_length=254)
class PasswordReset(StrictModel):
token: str = Field(min_length=20, max_length=100, pattern=r'^[A-Za-z0-9_-]+$')
password: str = Field(min_length=8, max_length=128)
class Login(StrictModel):
email: str = Field(min_length=3, max_length=254)
password: str = Field(min_length=1, max_length=128)
class OperatorLogin(StrictModel):
email: str = Field(min_length=3, max_length=254)
password: str = Field(min_length=1, max_length=128)
@field_validator('email')
@classmethod
def operator_email_valid(cls, value):
value = value.strip().lower()
if not re.fullmatch(r'[^\s@]+@[^\s@]+\.[a-zA-Z]{2,}', value):
raise ValueError('Invalid email')
return value
class FileReference(StrictModel):
upload_id: UUID
item_index: int = Field(ge=0, strict=True)
class ArtworkSubmission(StrictModel):
version: int = Field(ge=0, strict=True)
files: list[FileReference] = Field(min_length=1, max_length=60)
note: str = Field(min_length=1, max_length=1000)