feat: password recovery by e-mail, team alerts, and a price for files opened by hand

Pilot customers had no way to reset a forgotten password, and the 7 October
meeting asked for two things that only needed the client's inputs to go live.

Password recovery: "Esqueci minha senha" in Minha conta sends a link that
works once, for an hour (/conta/redefinir#token, in the fragment so it never
reaches a server or a Referer). Only the token's hash is stored, the e-mail's
text is erased once sent, the answer never says whether an account exists,
and a reset signs out every other session. Limited per address and source.

Team alerts: Kanban users who tick "Receber alertas por e-mail" in Usuários
get one when an order is paid, a cart waits for review, or a payment needs
attention. Messages are queued in the transaction that caused them and sent
by the worker with retries (app/mail.py). Integrações shows an E-mail row
with "Enviar teste".

E-mail is off in production (MAIL_ADAPTER=off; recovery keeps offering
WhatsApp) until the client's SMTP account exists; then it is only settings
(docs/PORTAINER.md). The local stack keeps messages in the database and log.

Files opened by hand: a finished sheet in CDR, AI, PSD or TIFF (or with a
length the customer typed) pays the full price plus MANUAL_FILE_EXTRA_CENTS
per metre, to steer customers to PNG as the meeting asked. It is 0 until
Marcus gives the amount. The Site shows it before checkout, the server
charges it, Tiny gets it in the unit price, and the Kanban says it.

Tested: new tests/mail_test (reset flow, SMTP delivery against a local SMTP
server, retry, who gets alerts), pricing unit tests, and the browser test now
checks the Site total equals the server's, run with the charge at 0 and at
R$ 5,00. The full CI suite passes in a CI-style stack.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-10-13 11:48:24 -03:00
parent 86507ed7b5
commit 3664fe827e
35 changed files with 834 additions and 52 deletions

View File

@@ -43,6 +43,14 @@ TINY_ADAPTER=fake
# JADLOG_CONTA=... # conta corrente
# JADLOG_CONTRATO= # only if Jadlog issued a contract number
WHATSAPP_ADAPTER=fake
# E-mail stays in the database and the worker log (MAIL_ADAPTER=log). To send
# through a real server: MAIL_ADAPTER=smtp with the settings below.
# MAIL_FROM=DTF Dropstar <nao-responda@exemplo.com.br>
# SMTP_HOST=smtp.exemplo.com.br
# SMTP_PORT=587
# SMTP_SECURITY=starttls
# SMTP_USER=...
# SMTP_PASSWORD=...
STORAGE_ADAPTER=s3-local
MOCK_FREIGHT_CENTS=1500
MAX_UPLOAD_BYTES=5368709120

View File

@@ -73,7 +73,7 @@ jobs:
# one a developer exercises on localhost.
- name: API and workflow regressions
run: |
for suite in smoke_test workflow_test security_test scanning_test payment_test quote_pagination_test kanban_test reconcile_test order_actions_test print_file_test users_test thumbnail_backfill_test launch_reset_test; do
for suite in smoke_test workflow_test security_test scanning_test payment_test quote_pagination_test kanban_test reconcile_test order_actions_test print_file_test users_test mail_test thumbnail_backfill_test launch_reset_test; do
echo "--- $suite"
$COMPOSE exec -T \
-e SITE_BASE_URL=http://site \

View File

@@ -44,6 +44,16 @@ def require_runtime():
raise RuntimeError(f'{name} is required for the Mercado Pago adapter')
elif payment != 'fake':
raise RuntimeError('PAYMENT must use the fake or mercadopago adapter')
mail = os.environ.get('MAIL_ADAPTER', 'off')
if mail == 'smtp':
from .mail import required_settings as mail_settings
for name in mail_settings():
if not os.environ.get(name):
raise RuntimeError(f'{name} is required for e-mail by SMTP')
if os.environ.get('SMTP_SECURITY', 'starttls') not in ('starttls', 'ssl', 'none'):
raise RuntimeError('SMTP_SECURITY must be starttls, ssl or none')
elif mail not in ('off', 'log'):
raise RuntimeError('MAIL_ADAPTER must be off, log or smtp')
if environment == 'local':
if os.environ.get('STORAGE_ADAPTER') != 's3-local':
raise RuntimeError('Local runtime requires local S3 storage')

View File

@@ -1,4 +1,6 @@
"""Customer accounts, their orders, and the corrections they submit."""
import hashlib
import secrets
from datetime import datetime, timedelta, timezone
from uuid import UUID, uuid4
@@ -10,10 +12,12 @@ from psycopg.types.json import Jsonb
from ..core import db
from ..artwork import submit_files
from ..core.auth import (DUMMY_PASSWORD_HASH, audit, client_ip, new_session, owner,
login_failed, password_hash, password_matches, session_row, throttle, transfer_guest)
from ..core.models import ArtworkSubmission, EmailChange, Login, PasswordChange, ProfileUpdate, Register
from ..runtime import STATES, file_rows, order_code, owned_order, storage
from ..core.auth import (DUMMY_PASSWORD_HASH, audit, client_ip, new_session, owner, login_failed, password_hash,
password_matches, rate_limit, session_row, throttle, transfer_guest)
from ..core.models import (ArtworkSubmission, EmailChange, ForgotPassword, Login, PasswordChange, PasswordReset,
ProfileUpdate, Register)
from .. import mail
from ..runtime import PUBLIC_ORIGIN, STATES, file_rows, order_code, owned_order, storage
from ..scanning import require_clean
router = APIRouter()
@@ -139,6 +143,62 @@ def change_password(body: PasswordChange, request: Request, identity=Depends(own
audit('account_password_changed', account=str(identity))
return {'ok': True}
# Password recovery: a link by e-mail that works once, for an hour. The answer
# never says whether the e-mail has an account.
RESET_SENT = 'Se houver uma conta com este e-mail, enviamos um link para criar uma nova senha. Ele vale por 1 hora.'
@router.post('/api/account/forgot')
def forgot_password(body: ForgotPassword, request: Request):
if not mail.configured():
raise HTTPException(503, 'A recuperação por e-mail ainda não está disponível. Fale com a Dropstar pelo WhatsApp.')
email = body.email.strip().lower()
rate_limit('reset-source', client_ip(request), 10)
# Per address: a few links an hour, so nobody fills someone's inbox.
rate_limit('reset-account', email, 3, 3600)
token = secrets.token_urlsafe(32)
with db.connect() as c:
account = c.execute('SELECT id FROM dtf_local.accounts WHERE email=%s', (email,)).fetchone()
if account:
c.execute('''INSERT INTO dtf_local.password_resets(token_hash,account_id,expires_at)
VALUES(%s,%s,now() + %s * interval '1 minute')''',
(hashlib.sha256(token.encode()).hexdigest(), account['id'], mail.RESET_MINUTES))
# In the fragment, not the query: it is never sent to a server,
# nor in the Referer of the fonts and the logo the page loads.
link = f'{PUBLIC_ORIGIN}/conta/redefinir#{token}'
mail.queue(c, 'reset', email, 'Crie uma nova senha · DTF Dropstar',
'Olá!\n\nAlguém pediu para criar uma nova senha na sua conta do DTF Dropstar. '
f'Para criar, abra o link abaixo. Ele vale por 1 hora e funciona uma vez só.\n\n{link}\n\n'
'Se não foi você, ignore este e-mail: a sua senha continua a mesma.')
audit('password_reset_requested', account=str(account['id']) if account else None, ip=client_ip(request))
return {'ok': True, 'message': RESET_SENT}
@router.post('/api/account/reset')
def reset_password(body: PasswordReset, request: Request, response: Response):
rate_limit('reset-source', client_ip(request), 10)
digest = hashlib.sha256(body.token.encode()).hexdigest()
previous = current(request)
with db.connect() as c:
reset = c.execute('''SELECT * FROM dtf_local.password_resets WHERE token_hash=%s
AND used_at IS NULL AND expires_at>now() FOR UPDATE''', (digest,)).fetchone()
if not reset:
audit('password_reset_refused', ip=client_ip(request))
raise HTTPException(400, 'Este link venceu ou já foi usado. Peça outro em “Esqueci minha senha”.')
identity = reset['account_id']
account = account_row(c, identity, lock=True)
c.execute('UPDATE dtf_local.accounts SET password_hash=%s WHERE id=%s', (password_hash(body.password), identity))
c.execute('UPDATE dtf_local.password_resets SET used_at=now() WHERE token_hash=%s', (digest,))
# Every other link to this account stops working, and so does every
# session signed in with the old password.
c.execute('DELETE FROM dtf_local.password_resets WHERE account_id=%s AND used_at IS NULL', (identity,))
if previous:
transfer_guest(c, previous, identity)
c.execute('DELETE FROM dtf_local.sessions WHERE owner=%s', (identity,))
if previous:
c.execute('DELETE FROM dtf_local.sessions WHERE id=%s', (previous['id'],))
new_session(c, response, identity)
audit('password_reset', account=str(identity))
return {'customer': account['profile']}
# The order list's groups, as the customer filters them.
GROUPS = {'pay': 'Aguardando pagamento', 'prod': 'Em produção', 'cor': 'Correção', 'fin': 'Finalizados'}
ENTRIES = '''WITH live_quote AS (

View File

@@ -6,8 +6,10 @@ import httpx
from fastapi import APIRouter, HTTPException, Request, Response
from ..core import db
from .. import mail
from ..core.auth import client_ip, owner, new_session, rate_limit
from ..core.limits import upload_limit_bytes
from ..core.pricing import manual_extra_cents
from ..core.models import FreightEstimate
from ..runtime import (ENVIRONMENT, GUEST_SESSION_LIMIT, PART_BYTES, freight, payment,
require_delivery_available, storage)
@@ -38,6 +40,9 @@ def session(request: Request, response: Response):
session_id = new_session(c, response)
return {'environment': ENVIRONMENT, 'cart_scope': str(session_id), 'part_bytes': PART_BYTES,
'max_upload_bytes': upload_limit_bytes(), 'payment_provider': payment.name,
'password_recovery': mail.configured(),
# Per metre on a finished sheet someone opens by hand (app/core/pricing.py).
'manual_extra_cents': manual_extra_cents(),
# Public by design: Mercado Pago's card form needs it in the browser.
'payment_public_key': os.environ.get('MP_PUBLIC_KEY', '') if payment.name == 'mercadopago' else '',
# The delivery service the cart quotes, or none: pickup only.

View File

@@ -15,7 +15,7 @@ from ..core.auth import (COOKIE_SECURE, DUMMY_PASSWORD_HASH, audit, can, client_
login_failed, password_matches, throttle)
from ..core.models import Move, OperatorLogin, Resolution, Review, StrictModel
from ..printjobs import queue as queue_print_files
from .. import cnpj, payments, quote_review
from .. import cnpj, mail, payments, quote_review
from .. import tiny
from ..runtime import (BACK, BOARD_FINISHED_LIMIT, BOARD_QUOTE_LIMIT, ENVIRONMENT, PUBLIC_ORIGIN, STATES,
TRANSITIONS, payment, enqueue, freight, quote_view, storage)
@@ -122,7 +122,8 @@ def board(request: Request, user=Depends(operator)):
quotes = [quote_view(c, q) for q in pending + approved]
return {'states': STATES, 'transitions': TRANSITIONS, 'back': BACK,
'orders': orders, 'payment_issues_total': issues_total, 'tiny': tiny_status(), 'operator': user,
'providers': {'payment': payment.name, 'freight': freight_status(), 'backup': backup},
'providers': {'payment': payment.name, 'freight': freight_status(), 'backup': backup,
'mail': mail.status(c)},
'environment': ENVIRONMENT, 'site_origin': PUBLIC_ORIGIN,
'finished_shown': len(finished), 'finished_total': finished_total,
'machines': [{**m, 'id': str(m['id'])} for m in c.execute(

View File

@@ -7,7 +7,7 @@ from uuid import UUID, uuid4
from fastapi import APIRouter, Depends, HTTPException
from psycopg.types.json import Jsonb
from .. import payments
from .. import mail, payments
from ..core import db
from ..core.auth import owner
from ..core.models import QuoteRequest
@@ -61,6 +61,9 @@ def create_quote(body: QuoteRequest, session_id=Depends(owner)):
if row['id'] == uid:
# An operator reviews it first; the files wait for that review.
payments.hold_uploads(c, payments.quote_uploads(draft), payments.REVIEW_HOLD)
mail.alert(c, 'Cotação esperando revisão',
['Um cliente montou um carrinho que precisa de revisão antes do pagamento.',
f'Motivo: {reason}', '', *mail.summary(draft)], '/')
return {'id': row['id'], 'status': 'approved' if row['approved'] else 'pending_review'}
@router.get('/api/quotes/{uid}')

View File

@@ -1,7 +1,8 @@
"""Kanban users and print machines, managed by the administrators.
There is no e-mail yet, so an administrator creates each account with a
first password and the person changes it in "Minha senha". The superadmin is
An administrator creates each account with a first password and the person
changes it in "Minha senha". Whoever wants the team's alerts by e-mail has
them switched on here. The superadmin is
the system's own account, set from the console (python -m app.operators);
administrators manage everyone else. Nobody can remove, disable or demote
themselves, so the last administrator cannot lock the team out by accident.
@@ -13,6 +14,7 @@ from uuid import UUID, uuid4
from fastapi import APIRouter, Depends, HTTPException, Request
from pydantic import Field, field_validator
from .. import mail
from ..core import db
from ..core.auth import CAPABILITIES, audit, can, password_hash, password_matches, signed_in
from ..core.models import StrictModel
@@ -27,6 +29,8 @@ class UserIn(StrictModel):
password: str | None = Field(default=None, min_length=12, max_length=128)
active: bool = True
machines: list[UUID] = Field(default_factory=list, max_length=50)
# The team's alerts by e-mail: orders paid, carts waiting for review, payments to look at.
alerts: bool = False
@field_validator('email')
@classmethod
@@ -70,7 +74,7 @@ def change_password(body: PasswordChange, request: Request):
def user_rows(c):
rows = c.execute('''SELECT o.id,o.email,o.name,o.role,o.active,o.last_login_at,o.created_at,
rows = c.execute('''SELECT o.id,o.email,o.name,o.role,o.active,o.alerts,o.last_login_at,o.created_at,
COALESCE(array_agg(m.machine_id) FILTER (WHERE m.machine_id IS NOT NULL), '{}') AS machines
FROM dtf_local.operators o LEFT JOIN dtf_local.operator_machines m ON m.operator_id=o.id
GROUP BY o.id ORDER BY o.active DESC, o.name, o.email''').fetchall()
@@ -113,9 +117,9 @@ def create_user(body: UserIn, request: Request, user=Depends(can('users'))):
with db.connect() as c:
if c.execute('SELECT 1 FROM dtf_local.operators WHERE email=%s', (body.email,)).fetchone():
raise HTTPException(409, 'Já existe um usuário com este e-mail.')
c.execute('''INSERT INTO dtf_local.operators(id,email,name,password_hash,role,active)
VALUES(%s,%s,%s,%s,%s,%s)''', (uid, body.email, body.name.strip(), password_hash(body.password),
body.role, body.active))
c.execute('''INSERT INTO dtf_local.operators(id,email,name,password_hash,role,active,alerts)
VALUES(%s,%s,%s,%s,%s,%s,%s)''', (uid, body.email, body.name.strip(), password_hash(body.password),
body.role, body.active, body.alerts))
set_machines(c, uid, body.machines)
audit('operator_created', operator=user, account=body.email, role=body.role)
return {'id': str(uid)}
@@ -133,8 +137,8 @@ def update_user(uid: UUID, body: UserIn, request: Request, user=Depends(can('use
if body.email != row['email'] and c.execute(
'SELECT 1 FROM dtf_local.operators WHERE email=%s AND id<>%s', (body.email, uid)).fetchone():
raise HTTPException(409, 'Já existe um usuário com este e-mail.')
c.execute('UPDATE dtf_local.operators SET name=%s,email=%s,role=%s,active=%s WHERE id=%s',
(body.name.strip(), body.email, role, body.active, uid))
c.execute('UPDATE dtf_local.operators SET name=%s,email=%s,role=%s,active=%s,alerts=%s WHERE id=%s',
(body.name.strip(), body.email, role, body.active, body.alerts, uid))
if body.password:
c.execute('UPDATE dtf_local.operators SET password_hash=%s WHERE id=%s', (password_hash(body.password), uid))
if body.email != row['email']:
@@ -208,3 +212,15 @@ def delete_machine(mid: UUID, user=Depends(can('users'))):
raise HTTPException(404, 'Máquina não encontrada.')
audit('machine_deleted', operator=user, machine=row['name'])
return {'ok': True}
@router.post('/api/operator/mail/test')
def test_mail(request: Request, user=Depends(can('manage'))):
"""A message to whoever asked, to prove the mail server works."""
with db.connect() as c:
if not mail.queue(c, 'test', user, 'Teste de e-mail · Kanban DTF',
'Este é um teste do Kanban DTF. Se chegou, o envio de e-mails está funcionando: '
'recuperação de senha dos clientes e alertas da equipe.'):
raise HTTPException(409, 'O envio de e-mails não está configurado no servidor.')
audit('mail_test_queued', operator=user)
return {'ok': True, 'to': user}

View File

@@ -254,6 +254,13 @@ class PasswordChange(StrictModel):
current: str = Field(min_length=1, max_length=128)
new: str = Field(min_length=12, max_length=128)
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=12, max_length=128)
class Login(StrictModel):
email: str = Field(min_length=3, max_length=254)
password: str = Field(min_length=1, max_length=128)

View File

@@ -3,6 +3,8 @@
Quantity/grade must be supplied by an authenticated commercial reviewer.
This module does not inspect artwork or perform pre-flight.
"""
import os
import re
from decimal import Decimal, ROUND_CEILING
TIERS = {
@@ -12,16 +14,44 @@ TIERS = {
'uv': [(90,8390),(75,8790),(60,9190),(40,9590),(0,9990)],
}
def price(mode: str, metres: str, grade: int) -> dict:
# A finished sheet the Site cannot open (CDR, AI, PSD, TIFF) is opened by a
# person before printing. It is priced at the top of the ladder, plus this per
# metre when the business sets it, to make the formats the robot reads the
# cheaper path. Zero (the default) adds nothing.
MANUAL_FORMATS = re.compile(r'\.(cdr|ai|psd|psb|tiff?)$', re.I)
def manual_extra_cents() -> int:
value = int(os.environ.get('MANUAL_FILE_EXTRA_CENTS', '0') or 0)
if not 0 <= value <= 100000:
raise ValueError('MANUAL_FILE_EXTRA_CENTS must be between 0 and 100000')
return value
def is_manual(item, names) -> bool:
"""Whether a finished-sheet item has a file someone must open by hand: one
the customer measured, or one in a format the Site cannot read."""
return any(source['kind'] == 'sheet' and (source['measurement'] == 'customer' or
MANUAL_FORMATS.search(names.get(str(source['upload_id']), '')))
for source in item['production']['sources'])
def price(mode: str, metres: str, grade: int, extra_cents: int = 0) -> dict:
length = Decimal(str(metres))
if mode not in TIERS or not length.is_finite() or not 0 < length <= 12000:
raise ValueError('Invalid product or length')
if isinstance(grade, bool) or not isinstance(grade, int) or not 0 <= grade <= 100:
raise ValueError('Grade must be an integer between 0 and 100')
billed = max(Decimal('1'), (length * 10).to_integral_value(rounding=ROUND_CEILING) / 10)
unit = next(cents for minimum, cents in TIERS[mode] if grade >= minimum)
return {'mode': mode, 'metres': str(length), 'grade': grade,
'billed_metres': str(billed), 'unit_cents': unit,
'total_cents': int(billed * unit),
'discount_cents': int(billed * (TIERS[mode][-1][1] - unit))}
if isinstance(extra_cents, bool) or not isinstance(extra_cents, int) or extra_cents < 0:
raise ValueError('Invalid extra charge')
tier = next(cents for minimum, cents in TIERS[mode] if grade >= minimum)
unit = tier + extra_cents
priced = {'mode': mode, 'metres': str(length), 'grade': grade,
'billed_metres': str(billed), 'unit_cents': unit,
'total_cents': int(billed * unit),
'discount_cents': int(billed * (TIERS[mode][-1][1] - tier))}
if extra_cents:
priced['manual_extra_cents'] = extra_cents
return priced

View File

@@ -28,6 +28,7 @@ SECRET_FILE_SETTINGS = (
'PAYMENT_WEBHOOK_SECRET',
'TINY_TOKEN',
'WHATSAPP_TOKEN',
'SMTP_PASSWORD',
)
SUFFIX = '_FILE'

169
app/mail.py Normal file
View File

@@ -0,0 +1,169 @@
"""E-mail: password recovery for customers and alerts for the team.
Messages are queued in the database inside the transaction that caused them
(an order paid, a quote waiting for review) and sent by the worker, so a slow
or unreachable mail server never holds up a request and a failed send is
retried. MAIL_ADAPTER chooses where they go:
off nothing is queued and recovery offers WhatsApp instead (the default,
until the client's SMTP details arrive);
log kept in the database and written to the worker's log, for the local
stack, where there is no mail server;
smtp sent through SMTP_HOST as MAIL_FROM.
A recovery message carries a link that signs in, so its text is erased once it
is sent (or once the link expired unsent); only its subject stays as a record.
"""
import logging
import os
import smtplib
import ssl
from email.message import EmailMessage
from email.utils import formataddr, make_msgid, parseaddr
ADAPTER = os.environ.get('MAIL_ADAPTER', 'off')
# Every Kanban link in an alert points here.
KANBAN_ORIGIN = os.environ.get('KANBAN_ORIGIN', '').rstrip('/')
RESET_MINUTES = 60
MAX_ATTEMPTS = 12
log = logging.getLogger('dtf.mail')
def configured():
return ADAPTER in ('log', 'smtp')
def required_settings():
return ('SMTP_HOST', 'MAIL_FROM')
def queue(c, kind, to, subject, body):
"""Queue one message in the caller's transaction. Returns False when e-mail
is off, so the caller can say so instead of promising a message."""
if not configured():
return False
c.execute('INSERT INTO dtf_local.mail_queue(kind,to_addr,subject,body) VALUES(%s,%s,%s,%s)',
(kind, to, subject, body))
return True
def alert(c, subject, lines, link=''):
"""The same message to every active Kanban user who asked for alerts."""
if not configured():
return
body = '\n'.join(lines)
if link and KANBAN_ORIGIN:
body += f'\n\nAbrir no Kanban: {KANBAN_ORIGIN}{link}'
body += '\n\nVocê recebe este e-mail porque os alertas estão ligados no seu usuário do Kanban (Usuários → Editar).'
for row in c.execute('SELECT email FROM dtf_local.operators WHERE active AND alerts').fetchall():
queue(c, 'alert', row['email'], subject, body)
PRODUCTS = {'file': 'DTF Têxtil · folha montada', 'avulsa': 'DTF Têxtil · artes avulsas',
'uvfile': 'DTF UV · folha montada', 'uv': 'DTF UV · artes avulsas'}
def money(cents):
whole, cents = divmod(int(cents), 100)
return 'R$ ' + f'{whole:,}'.replace(',', '.') + f',{cents:02d}'
def summary(order):
"""The lines an alert shows about a cart or an order: who, what, delivery."""
customer = order.get('customer') or {}
cnpj = ''.join(ch for ch in str(customer.get('cnpj', '')) if ch.isdigit())
if len(cnpj) == 14:
cnpj = f'{cnpj[:2]}.{cnpj[2:5]}.{cnpj[5:8]}/{cnpj[8:12]}-{cnpj[12:]}'
lines = [f"Cliente: {cnpj} · {customer.get('mail', '')}"]
for item in order.get('items', []):
metres = item.get('billed_metres') or item.get('metres')
lines.append(f"{PRODUCTS.get(item.get('mode'), item.get('mode'))} · {str(metres).replace('.', ',')} m")
freight = order.get('freight') or {}
lines.append('Entrega: ' + ('retirada' if freight.get('service') == 'pickup' else 'frete'))
return lines
def message(to, subject, body):
sender = os.environ.get('MAIL_FROM', 'DTF Dropstar <nao-responda@localhost>')
name, address = parseaddr(sender)
msg = EmailMessage()
msg['From'] = formataddr((name or 'DTF Dropstar', address))
msg['To'] = to
msg['Subject'] = subject
msg['Message-ID'] = make_msgid(domain=address.split('@')[-1] or None)
reply = os.environ.get('MAIL_REPLY_TO', '')
if reply:
msg['Reply-To'] = reply
msg.set_content(body)
return msg
def send_smtp(msg):
host = os.environ['SMTP_HOST']
security = os.environ.get('SMTP_SECURITY', 'starttls')
port = int(os.environ.get('SMTP_PORT') or (465 if security == 'ssl' else 587))
user, password = os.environ.get('SMTP_USER', ''), os.environ.get('SMTP_PASSWORD', '')
context = ssl.create_default_context()
if security == 'ssl':
server = smtplib.SMTP_SSL(host, port, timeout=20, context=context)
else:
server = smtplib.SMTP(host, port, timeout=20)
with server:
if security == 'starttls':
server.starttls(context=context)
if user:
server.login(user, password)
server.send_message(msg)
def deliver(row):
msg = message(row['to_addr'], row['subject'], row['body'])
if ADAPTER == 'smtp':
send_smtp(msg)
else:
log.warning('mail (%s) to %s: %s', ADAPTER, row['to_addr'], row['subject'])
def send_pending(connect, limit=5, ids=None):
"""Send what is due, a few at a time. Called by the worker every second;
`ids` sends just those messages, due or not (the tests use it)."""
if not configured():
return
with connect() as c:
# A recovery link that expired before it could be sent is useless.
c.execute(f"""UPDATE dtf_local.mail_queue SET body='', last_error='expirou sem ser enviado', failed_at=now()
WHERE kind='reset' AND sent_at IS NULL AND failed_at IS NULL
AND created_at < now() - interval '{RESET_MINUTES} minutes'""")
rows = c.execute('''SELECT * FROM dtf_local.mail_queue WHERE sent_at IS NULL AND failed_at IS NULL
AND (id = ANY(%s) OR (%s::bigint[] IS NULL AND available_at <= now()))
ORDER BY id FOR UPDATE SKIP LOCKED LIMIT %s''', (ids or [], ids, limit)).fetchall()
for row in rows:
try:
deliver(row)
except Exception as exc:
attempts = row['attempts'] + 1
gave_up = attempts >= MAX_ATTEMPTS
c.execute('''UPDATE dtf_local.mail_queue SET attempts=%s, last_error=%s,
available_at=now() + %s * interval '1 second',
failed_at=CASE WHEN %s THEN now() END WHERE id=%s''',
(attempts, str(exc)[:500], min(3600, 2 ** min(attempts + 3, 12)), gave_up, row['id']))
log.warning('mail to %s failed (attempt %s): %s', row['to_addr'], attempts, exc)
continue
# The local log keeps the text so the link can be followed by hand.
erase = row['kind'] == 'reset' and ADAPTER != 'log'
c.execute('''UPDATE dtf_local.mail_queue SET sent_at=now(), attempts=attempts+1, last_error=NULL,
body=CASE WHEN %s THEN '' ELSE body END WHERE id=%s''', (erase, row['id']))
def status(c):
"""What the Kanban's Integrações shows about e-mail."""
last = c.execute('SELECT max(sent_at) AS at FROM dtf_local.mail_queue').fetchone()['at']
failing = c.execute('''SELECT to_addr, last_error, created_at FROM dtf_local.mail_queue
WHERE sent_at IS NULL AND last_error IS NOT NULL ORDER BY id DESC LIMIT 1''').fetchone()
pending = c.execute('SELECT count(*) AS n FROM dtf_local.mail_queue WHERE sent_at IS NULL AND failed_at IS NULL').fetchone()['n']
alerts = c.execute('SELECT count(*) AS n FROM dtf_local.operators WHERE active AND alerts').fetchone()['n']
return {'adapter': ADAPTER, 'from': os.environ.get('MAIL_FROM', '') if configured() else '',
'host': os.environ.get('SMTP_HOST', '') if ADAPTER == 'smtp' else '',
'last_sent': last, 'pending': pending, 'alerts': alerts,
'error': {'to': failing['to_addr'], 'error': failing['last_error'], 'at': failing['created_at']} if failing else None}

View File

@@ -16,6 +16,7 @@ from uuid import UUID, uuid4
from psycopg.types.json import Jsonb
from . import mail
from .core.auth import audit
from .printjobs import queue as queue_print_files
from .runtime import enqueue, upload_row
@@ -102,6 +103,8 @@ def create_order(c, quote, payment):
enqueue(c, f"{order['id']}:paid:{provider}", provider,
{'order_id': str(order['id']), 'number': order['number'],
'event': 'payment_approved', 'order': approved})
mail.alert(c, f"Pedido #{order['number']} pago · {mail.money(approved['total_cents'])}",
['Um pedido novo foi pago e está em Arte recebida.', '', *mail.summary(approved)], '/')
return order, True
@@ -120,8 +123,19 @@ def apply(c, event):
Outcomes starting 'refused' (money arrived, no order) or 'attention' (an
order exists but its payment was reversed) stay on the Kanban until an
operator records a resolution.
operator records a resolution, and the team is told by e-mail.
"""
outcome = _apply(c, event)
if outcome.startswith(('refused', 'attention')):
paid = mail.money(event.amount_cents) if type(event.amount_cents) is int else 'valor não informado'
mail.alert(c, f'Pagamento precisa de atenção · {paid}',
['O Mercado Pago avisou de um pagamento que não virou pedido, ou que foi estornado depois.',
'Abra Pagamentos no Kanban para ver o que aconteceu e registrar a resolução.', '',
f'Situação: {event.status} · cotação {event.reference or "—"}', f'Registro: {outcome}'], '/')
return outcome
def _apply(c, event):
provider_id = event.raw.get('payment_id')
if provider_id:
c.execute('''UPDATE dtf_local.payment_intents SET status=%s, updated_at=now()

View File

@@ -19,7 +19,7 @@ from fastapi import HTTPException
from psycopg.types.json import Jsonb
from . import payments
from .core.pricing import price
from .core.pricing import is_manual, manual_extra_cents, price
from .runtime import freight, upload_row
from .scanning import require_clean
@@ -67,9 +67,13 @@ def approve(c, row, items, reviewer):
raise HTTPException(422, 'O produto e os arquivos não podem mudar na revisão.')
if item.production.model_dump(mode='json') != original['production'] or item.quality_status != original['quality_status'] or item.quality_acknowledged != original['quality_acknowledged']:
raise HTTPException(422, 'A montagem e a confirmação do cliente não podem mudar na revisão.')
names = {}
for upload_id in item.uploads:
require_clean(upload_row(c, upload_id, row['owner']))
priced.append({**price(item.mode, str(item.metres), item.grade),
upload = upload_row(c, upload_id, row['owner'])
require_clean(upload)
names[str(upload_id)] = upload['name']
extra = manual_extra_cents() if is_manual(original, names) else 0
priced.append({**price(item.mode, str(item.metres), item.grade, extra),
'uploads': original['uploads'], 'production': original['production'],
'quality_status': original['quality_status'],
'quality_acknowledged': original['quality_acknowledged']})

View File

@@ -256,3 +256,23 @@ CREATE TABLE IF NOT EXISTS dtf_local.operator_machines (
PRIMARY KEY (operator_id, machine_id)
);
-- E-mail (app/mail.py): queued in the transaction that caused it, sent by the
-- worker. A recovery message's text is erased once sent; the subject stays.
CREATE TABLE IF NOT EXISTS dtf_local.mail_queue (
id bigserial PRIMARY KEY, kind text NOT NULL CHECK(kind IN ('reset','alert','test')),
to_addr text NOT NULL, subject text NOT NULL, body text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(), available_at timestamptz NOT NULL DEFAULT now(),
attempts int NOT NULL DEFAULT 0, last_error text, sent_at timestamptz, failed_at timestamptz
);
CREATE INDEX IF NOT EXISTS mail_queue_pending ON dtf_local.mail_queue(available_at, id)
WHERE sent_at IS NULL AND failed_at IS NULL;
-- A customer's password recovery: only the token's hash is kept, for an hour,
-- and it works once.
CREATE TABLE IF NOT EXISTS dtf_local.password_resets (
token_hash text PRIMARY KEY, account_id uuid NOT NULL REFERENCES dtf_local.accounts(id) ON DELETE CASCADE,
created_at timestamptz NOT NULL DEFAULT now(), expires_at timestamptz NOT NULL, used_at timestamptz
);
CREATE INDEX IF NOT EXISTS password_resets_account ON dtf_local.password_resets(account_id);
-- Kanban users who get the team's alerts by e-mail.
ALTER TABLE dtf_local.operators ADD COLUMN IF NOT EXISTS alerts boolean NOT NULL DEFAULT false;

View File

@@ -6,6 +6,7 @@ import threading
import time
from http.server import BaseHTTPRequestHandler, HTTPServer
from psycopg.types.json import Jsonb
from . import mail
from .adapters import FakeTiny, FakeWhatsApp, LocalS3Storage, require_runtime
from .core.secrets import load as load_secret_files
from .core.db import connect
@@ -115,6 +116,7 @@ def loop():
if time.monotonic()-last_cleanup > 60:
cleanup()
last_cleanup = time.monotonic()
mail.send_pending(connect)
tiny_keepalive()
reconcile_payments()
resolve_names()

View File

@@ -50,6 +50,7 @@ x-app: &app
# Carts the Site priced are approved at checkout; larger ones wait for review.
QUOTE_AUTO_APPROVE: ${QUOTE_AUTO_APPROVE:-true}
QUOTE_AUTO_MAX_METRES: ${QUOTE_AUTO_MAX_METRES:-50}
MANUAL_FILE_EXTRA_CENTS: ${MANUAL_FILE_EXTRA_CENTS:-0}
TINY_ADAPTER: ${TINY_ADAPTER:-fake}
TINY_CLIENT_ID: ${TINY_CLIENT_ID:-}
TINY_CLIENT_SECRET: ${TINY_CLIENT_SECRET:-}
@@ -72,6 +73,17 @@ x-app: &app
TINY_SKU_METRO_UV_AVULSA: ${TINY_SKU_METRO_UV_AVULSA:-}
TINY_ECOMMERCE_ID: ${TINY_ECOMMERCE_ID:-}
WHATSAPP_ADAPTER: fake
# log keeps each e-mail in the database and the worker's log, with the
# recovery link readable there; smtp with the SMTP_* settings in .env.
MAIL_ADAPTER: ${MAIL_ADAPTER:-log}
MAIL_FROM: ${MAIL_FROM:-DTF Dropstar <nao-responda@localhost>}
MAIL_REPLY_TO: ${MAIL_REPLY_TO:-}
SMTP_HOST: ${SMTP_HOST:-}
SMTP_PORT: ${SMTP_PORT:-}
SMTP_SECURITY: ${SMTP_SECURITY:-starttls}
SMTP_USER: ${SMTP_USER:-}
SMTP_PASSWORD: ${SMTP_PASSWORD:-}
KANBAN_ORIGIN: ${KANBAN_ORIGIN:-http://localhost:${KANBAN_PORT:-8081}}
STORAGE_ADAPTER: s3-local
MOCK_FREIGHT_CENTS: ${MOCK_FREIGHT_CENTS:-1500}
MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-5368709120}

View File

@@ -54,7 +54,7 @@ server {
try_files /index.html =404;
}
# The customer's area: one page, which shows the right part for each address.
location ~ ^/conta(/(entrar|pedidos|dados))?/?$ {
location ~ ^/conta(/(entrar|pedidos|dados|redefinir))?/?$ {
expires -1;
try_files /portal.html =404;
}

View File

@@ -45,6 +45,15 @@ TINY_FORMA_ENVIO_RETIRADA=TBD
# true only at go-live, after the n8n DTFIMP designer branch is removed.
TINY_STATUS_UPDATES=false
WHATSAPP_ADAPTER=TBD
# E-mail (password recovery and team alerts). off until the SMTP account exists.
MAIL_ADAPTER=off
MAIL_FROM=DTF Dropstar <nao-responda@SITE_DOMAIN>
MAIL_REPLY_TO=
SMTP_HOST=TBD
SMTP_PORT=587
SMTP_SECURITY=starttls
SMTP_USER=TBD
SMTP_PASSWORD=TBD
STORAGE_QUOTA_BYTES=TBD
OWNER_UPLOAD_QUOTA_BYTES=TBD
MAX_PENDING_UPLOADS=10

View File

@@ -60,6 +60,10 @@ x-app-environment: &app-environment
# compute, wait for an operator on the Kanban (app/quote_review.py).
QUOTE_AUTO_APPROVE: ${QUOTE_AUTO_APPROVE:-true}
QUOTE_AUTO_MAX_METRES: ${QUOTE_AUTO_MAX_METRES:-50}
# Cents added to each metre of a finished sheet someone has to open by hand
# (CDR, AI, PSD, TIFF, or a length the customer typed). 0 adds nothing; 500
# is R$ 5,00 a metro. The Site shows it before the customer pays.
MANUAL_FILE_EXTRA_CENTS: ${MANUAL_FILE_EXTRA_CENTS:-0}
# Order creation in Tiny stays off until it has been tested against the
# client's account (Tiny has no sandbox). The application credentials can be
# set now: they let an operator connect Tiny from the Kanban, and the worker
@@ -92,6 +96,19 @@ x-app-environment: &app-environment
# designer message for DTFIMP products.
TINY_STATUS_UPDATES: ${TINY_STATUS_UPDATES:-false}
WHATSAPP_ADAPTER: fake
# E-mail: customers' password recovery and the team's alerts (app/mail.py).
# off until the client's SMTP account exists; then smtp with the settings
# below, or the API and worker refuse to start. SMTP_SECURITY is starttls
# (port 587), ssl (465) or none.
MAIL_ADAPTER: ${MAIL_ADAPTER:-off}
MAIL_FROM: ${MAIL_FROM:-}
MAIL_REPLY_TO: ${MAIL_REPLY_TO:-}
SMTP_HOST: ${SMTP_HOST:-}
SMTP_PORT: ${SMTP_PORT:-}
SMTP_SECURITY: ${SMTP_SECURITY:-starttls}
SMTP_USER: ${SMTP_USER:-}
SMTP_PASSWORD: ${SMTP_PASSWORD:-}
KANBAN_ORIGIN: https://${KANBAN_DOMAIN:?set KANBAN_DOMAIN}
STORAGE_ADAPTER: s3-r2
PUBLIC_ORIGIN: https://${SITE_DOMAIN:?set SITE_DOMAIN}
PUBLIC_HOST: ${SITE_DOMAIN:?set SITE_DOMAIN}

View File

@@ -161,6 +161,12 @@ the ready-sheet option before uploading. PDF and manual-format ready sheets keep
their existing workflow. These models retain their separate approved price tiers;
image dimensions alone must never classify a normal artwork as a finished sheet.
A finished sheet someone must open by hand (CDR, AI, PSD, TIFF, or a length the
customer typed) pays the top of the ladder plus `MANUAL_FILE_EXTRA_CENTS` per
metre (2026-10-13, asked at the 7 October meeting to steer customers to PNG).
It defaults to 0; the amount is the client's to set. The Site reads it from
`/api/session` and shows it before checkout; `app/core/pricing.py` charges it.
## Freight
The original visual freight flow in `web/index.html` was a stub with only pickup
@@ -202,6 +208,17 @@ Tiny/Olist is already available. The implementation must create/update orders
idempotently and use the order number for traceability. Confirm the actual API
endpoints, marker/tag behaviour, and rate limits before production use.
### E-mail
`app/mail.py` (2026-10-13): customers' password recovery (a one-time link,
valid one hour, sent to `/conta/redefinir#token`; only the token's hash is
stored and the message text is erased once sent) and alerts to the Kanban
users who switch them on (order paid, quote waiting for review, payment
needing attention). Messages are queued in the transaction that caused them and
sent by the worker with retries. `MAIL_ADAPTER` is `off` in production until
the client's SMTP account exists (recovery then offers WhatsApp), `log` on the
local stack, `smtp` with `SMTP_*` and `MAIL_FROM`.
### WhatsApp
WhatsApp is already available, but the technical provider still needs to be
@@ -370,8 +387,9 @@ referenced them; recover from Git history if ever needed.
authentication, purchase history, or real cart persistence. Local order
persistence, reviewed quotes, mock freight and fake payment now work through
`web/checkout.js`. The local customer portal now provides accounts and
order history; cart recovery is browser-local. Production account verification,
recovery, and cross-device cart editing are still absent.
order history; cart recovery is browser-local. Password recovery by e-mail
exists (see E-mail) but waits for the client's SMTP account; account e-mail
verification and cross-device cart editing are still absent.
- Without the local bridge, the original freight fallback remains a stub.
Real freight quotation remains unimplemented in all runtimes.
- The existing the removed prototypes duplicated WhatsApp senders and send

View File

@@ -190,6 +190,21 @@ It refuses if any payment was made with real money. Order numbers restart at
run in the `db` container's console. Add `--contas` to remove the test
customer accounts too.
## 7. E-mail and prices set in the stack
E-mail stays off (`MAIL_ADAPTER=off`) until the client's SMTP account exists.
Then set, in the stack's environment, `MAIL_ADAPTER=smtp`, `MAIL_FROM` (for
example `DTF Dropstar <nao-responda@SITE_DOMAIN>`), `SMTP_HOST`, `SMTP_PORT`,
`SMTP_SECURITY` (`starttls` on 587, `ssl` on 465), `SMTP_USER` and
`SMTP_PASSWORD`, and redeploy; the API and worker refuse to start if a required
one is missing. Check it with **Integrações → E-mail → Enviar teste** on the
Kanban, then switch on "Receber alertas por e-mail" for whoever wants alerts in
Usuários. Use a sending domain with SPF and DKIM, or the messages land in spam.
`MANUAL_FILE_EXTRA_CENTS` is the per-metre charge on finished sheets someone
opens by hand (CDR, AI, PSD, TIFF); 500 is R$ 5,00 a metro. Change it only on
the client's instruction; the Site shows the new price after the redeploy.
## Current blocker
This is the final deployment shape, but it is not authorized for production

View File

@@ -24,7 +24,7 @@ server {
try_files /index.html =404;
}
# The customer's area: one page, which shows the right part for each address.
location ~ ^/conta(/(entrar|pedidos|dados))?/?$ {
location ~ ^/conta(/(entrar|pedidos|dados|redefinir))?/?$ {
try_files /portal.html =404;
}
location / { try_files $uri $uri/ =404; }

View File

@@ -75,7 +75,13 @@ try{
await waitFor(()=>site.eval('!!document.querySelector("[data-comp]")'),'manual length field');
await site.fill('[data-comp]','1.01','change');
await waitFor(()=>site.eval('!!itemAtual'),'cart calculation');
assert.equal(await site.eval('itemAtual.total'),21.89);
// A CDR is opened by hand: the full price, plus the per-metre charge when
// the server sets one (MANUAL_FILE_EXTRA_CENTS), shown before checkout.
const extraCents=(await site.eval('dtfSessionReady')).manual_extra_cents;
const itemCents=Math.round(1.1*(1990+extraCents));
const total=Math.round(itemCents)/100;
await waitFor(()=>site.eval(`Math.abs(itemAtual.total-${total})<0.005`),'manual-file price');
assert.equal(await site.eval(`$('carrLin').textContent.includes('Arquivo aberto na mão')`),extraCents>0);
await site.fill('#fCnpj','11222333000181');
await site.fill('#fZap','11999999999');
await site.fill('#fMail','local-browser@example.test');
@@ -97,7 +103,7 @@ try{
await waitFor(()=>site.eval(`!$('carrVazio').hidden||document.documentElement.hasAttribute('data-sem-itens')`),'empty cart state');
assert.deepEqual(await site.eval(`({items:pedido.length,empty:!$('carrVazio').hidden||document.documentElement.hasAttribute('data-sem-itens'),undo:!$('desfazer').hidden})`),{items:0,empty:true,undo:true});
await site.click('#desfazerBtn');
assert.equal(await site.eval('pedido.length===1 && pedido[0].total===21.89 && $("desfazer").hidden'),true);
assert.equal(await site.eval(`pedido.length===1 && Math.abs(pedido[0].total-${total})<0.005 && $("desfazer").hidden`),true);
// The items come back after a reload; the customer's details do not.
assert.deepEqual(await site.eval(`['fCnpj','fZap','fMail'].map(id=>$(id).value)`),['','','']);
assert.equal(await site.eval('document.getElementById("bPagar").disabled'),true);
@@ -111,7 +117,7 @@ try{
{marcado:false,pagar:0,zero:true,row:true});
await site.click('[data-sel="0"]');
assert.equal(await site.eval('pedido[0].marcado===true && itensAPagar().length===1'),true);
assert.equal(await site.eval('pedido[0].total'),21.89);
assert.equal(await site.eval(`Math.abs(pedido[0].total-${total})<0.005`),true);
assert.equal(await site.eval('document.getElementById("bPagar").disabled'),false);
await site.click('#bPagar');
try{
@@ -126,6 +132,8 @@ try{
throw error;
}
const qid=await site.eval('localStorage.getItem("dtf-quote")');
// The server charged what the Site showed.
assert.equal(await site.eval(`dtfApi('/quotes/'+${JSON.stringify(qid)}).then(q=>q.approved.items[0].total_cents)`),itemCents);
const kanban=await page(kanbanOrigin);
await kanban.fill('#email',process.env.OPERATOR_EMAIL||'operator@example.test');
await kanban.fill('#password',process.env.OPERATOR_PASSWORD||'local-operator-only');

234
tests/mail_test.py Normal file
View File

@@ -0,0 +1,234 @@
"""E-mail: a customer's password recovery, and the team's alerts.
Run inside the API container: python -m tests.mail_test
The local stack keeps e-mail in the database (MAIL_ADAPTER=log); the SMTP
path is checked against a small SMTP server this test runs itself.
"""
import email
import hashlib
import os
import re
import secrets
import socketserver
import threading
from email import policy
from uuid import uuid4
from app import mail
from app.core import db
from tests.smoke_test import Client, approved_quote, item_spec, upload_bytes
CNPJ = '11222333000181'
PASSWORD = 'senha-antiga-12345'
NEW_PASSWORD = 'senha-nova-678901'
class Sink(socketserver.ThreadingTCPServer):
"""Just enough SMTP to receive what smtplib sends, kept in `messages`."""
allow_reuse_address = True
daemon_threads = True
def __init__(self):
self.messages = []
super().__init__(('127.0.0.1', 0), SinkHandler)
class SinkHandler(socketserver.StreamRequestHandler):
def reply(self, line):
self.wfile.write(line.encode() + b'\r\n')
def handle(self):
self.reply('220 sink')
rcpt = []
while line := self.rfile.readline():
verb = line.decode().strip().split(' ')[0].upper()
if verb == 'EHLO':
self.wfile.write(b'250-sink\r\n250 8BITMIME\r\n')
elif verb == 'RCPT':
rcpt.append(line.decode().strip())
self.reply('250 ok')
elif verb == 'DATA':
self.reply('354 go')
data = b''
while (chunk := self.rfile.readline()) != b'.\r\n':
data += chunk[1:] if chunk.startswith(b'..') else chunk
self.server.messages.append((rcpt, email.message_from_bytes(data, policy=policy.default)))
self.reply('250 queued')
elif verb == 'QUIT':
self.reply('221 bye')
return
else:
self.reply('250 ok')
def queued(c, to, kind):
return c.execute('SELECT * FROM dtf_local.mail_queue WHERE to_addr=%s AND kind=%s ORDER BY id',
(to, kind)).fetchall()
def recovery(tag):
address = f'cliente-{tag}@example.test'
customer = Client()
assert customer.call('/session')['password_recovery'] is True
customer.call('/account/register', {'customer': {'cnpj': CNPJ, 'zap': '16999990000', 'mail': address},
'password': PASSWORD})
# Signed in elsewhere with the old password: the reset signs that out.
elsewhere = Client()
elsewhere.call('/session')
elsewhere.call('/account/login', {'email': address, 'password': PASSWORD})
# The same answer whether or not the e-mail has an account.
stranger = Client()
stranger.call('/session')
unknown = stranger.call('/account/forgot', {'email': f'ninguem-{tag}@example.test'})
known = stranger.call('/account/forgot', {'email': address.upper()})
assert unknown == known and 'Se houver uma conta' in known['message']
with db.connect() as c:
assert not queued(c, f'ninguem-{tag}@example.test', 'reset')
[message] = queued(c, address, 'reset')
link = re.search(r'(\S+)/conta/redefinir#([A-Za-z0-9_-]+)', message['body'])
assert link and '1 hora' in message['body'], message['body']
token = link.group(2)
with db.connect() as c:
# Only the token's hash is kept.
assert not c.execute('SELECT 1 FROM dtf_local.password_resets WHERE token_hash=%s', (token,)).fetchone()
stranger.call('/account/reset', {'token': 'x' * 43, 'password': NEW_PASSWORD}, expected=400)
stranger.call('/account/reset', {'token': token, 'password': 'curta'}, expected=422)
assert stranger.call('/account/reset', {'token': token, 'password': NEW_PASSWORD})['customer']['mail'] == address
assert stranger.call('/account/me')['customer']['mail'] == address
# Works once; the old password and the old sessions are gone.
stranger.call('/account/reset', {'token': token, 'password': NEW_PASSWORD}, expected=400)
elsewhere.call('/account/me', expected=401)
Client().call('/account/login', {'email': address, 'password': PASSWORD}, expected=401)
Client().call('/account/login', {'email': address, 'password': NEW_PASSWORD})
# An expired link does nothing.
expired = secrets.token_urlsafe(32)
with db.connect() as c:
account = c.execute('SELECT id FROM dtf_local.accounts WHERE email=%s', (address,)).fetchone()['id']
c.execute('''INSERT INTO dtf_local.password_resets(token_hash,account_id,expires_at)
VALUES(%s,%s,now()-interval '1 minute')''', (hashlib.sha256(expired.encode()).hexdigest(), account))
stranger.call('/account/reset', {'token': expired, 'password': NEW_PASSWORD}, expected=400)
# A few links an hour per address, so nobody fills someone's inbox.
other = f'muitos-{tag}@example.test'
for _ in range(3):
stranger.call('/account/forgot', {'email': other})
stranger.call('/account/forgot', {'email': other}, expected=429)
return address
def smtp_delivery(tag):
"""The worker's SMTP path, against a server of our own."""
sink = Sink()
threading.Thread(target=sink.serve_forever, daemon=True).start()
saved = mail.ADAPTER, {k: os.environ.get(k) for k in ('SMTP_HOST', 'SMTP_PORT', 'SMTP_SECURITY', 'MAIL_FROM')}
to = f'smtp-{tag}@example.test'
try:
mail.ADAPTER = 'smtp'
os.environ.update(SMTP_HOST='127.0.0.1', SMTP_PORT=str(sink.server_address[1]), SMTP_SECURITY='none',
MAIL_FROM='DTF Dropstar <nao-responda@dropstar.test>')
with db.connect() as c:
# Not due yet, so the stack's own worker leaves them to this test.
ids = [c.execute('''INSERT INTO dtf_local.mail_queue(kind,to_addr,subject,body,available_at)
VALUES(%s,%s,%s,%s,now()+interval '1 hour') RETURNING id''',
(kind, to, subject, body)).fetchone()['id']
for kind, subject, body in (('reset', 'Crie uma nova senha · DTF Dropstar', 'link secreto ção'),
('alert', 'Pedido pago', 'olá equipe'))]
mail.send_pending(db.connect, ids=ids)
assert len(sink.messages) == 2, sink.messages
rcpt, first = sink.messages[0]
assert to in rcpt[0] and first['Subject'] == 'Crie uma nova senha · DTF Dropstar'
assert first['From'] == 'DTF Dropstar <nao-responda@dropstar.test>'
assert first.get_content().strip() == 'link secreto ção'
with db.connect() as c:
sent = {r['kind']: r for r in queued(c, to, 'reset') + queued(c, to, 'alert')}
# The recovery's text is erased once sent; an alert keeps its own.
assert sent['reset']['sent_at'] and sent['reset']['body'] == ''
assert sent['alert']['sent_at'] and sent['alert']['body'] == 'olá equipe'
# A server that does not answer: retried later, with the error kept.
os.environ['SMTP_PORT'] = '1'
with db.connect() as c:
failing = c.execute('''INSERT INTO dtf_local.mail_queue(kind,to_addr,subject,body,available_at)
VALUES('alert',%s,'x','y',now()+interval '1 hour') RETURNING id''', (to,)).fetchone()['id']
mail.send_pending(db.connect, ids=[failing])
with db.connect() as c:
row = c.execute('SELECT * FROM dtf_local.mail_queue WHERE id=%s', (failing,)).fetchone()
assert row['attempts'] == 1 and row['last_error'] and not row['sent_at'] and not row['failed_at']
assert mail.status(c)['error']['to'] == to
c.execute('DELETE FROM dtf_local.mail_queue WHERE id=%s', (failing,))
finally:
mail.ADAPTER = saved[0]
for key, value in saved[1].items():
if value is None:
os.environ.pop(key, None)
else:
os.environ[key] = value
sink.shutdown()
def alerts(tag):
"""Who gets the team's alerts, and that a paid order sends one."""
su = Client()
su.call('/session')
wants, quiet, away = (f'{n}-{tag}@example.test' for n in ('alertas', 'quieto', 'fora'))
for address, on, active in ((wants, True, True), (quiet, False, True), (away, True, False)):
su.call('/operator/users', {'name': address, 'email': address, 'role': 'gestao', 'password': PASSWORD,
'alerts': on, 'active': active}, operator=True)
users = {u['email']: u for u in su.call('/operator/users', operator=True)['users']}
assert users[wants]['alerts'] is True and users[quiet]['alerts'] is False
board = su.call('/operator/board', operator=True)
assert board['providers']['mail']['adapter'] == 'log' and board['providers']['mail']['alerts'] >= 1
customer = Client()
customer.call('/session')
uid = upload_bytes(customer, b'MAIL ALERT ARTWORK')
item = item_spec('file', '1.2', 0, uid)
quote = customer.call('/quotes', {'request_key': str(uuid4()), 'items': [item],
'customer': {'cnpj': CNPJ, 'zap': '16999990000', 'mail': f'alerta-{tag}@example.test'},
'freight': {'service': 'pickup'}})
approved_quote(customer, quote, [item])
order = customer.call('/orders/dev-paid', {'quote_id': quote['id']})
with db.connect() as c:
[alert] = [r for r in queued(c, wants, 'alert') if f"#{order['number']}" in r['subject']]
assert 'pago' in alert['subject'] and '11.222.333/0001-81' in alert['body'] and '1,2 m' in alert['body']
assert 'Abrir no Kanban: http' in alert['body']
assert not queued(c, quiet, 'alert') and not queued(c, away, 'alert')
# The test message goes to whoever asked for it.
sent = su.call('/operator/mail/test', {}, operator=True)
with db.connect() as c:
assert queued(c, sent['to'], 'test')
return order['id'], quote['id']
def run():
tag = secrets.token_hex(3)
order = quote = None
with db.connect() as c:
# The recovery's per-source limit would make a second run within 15 minutes fail.
c.execute('DELETE FROM dtf_local.login_attempts')
try:
recovery(tag)
smtp_delivery(tag)
order, quote = alerts(tag)
print('PASS: password recovery by a one-time link, SMTP delivery and retry, alerts to who asked for them')
finally:
with db.connect() as c:
if order:
for table in ('movements', 'print_files'):
c.execute(f'DELETE FROM dtf_local.{table} WHERE order_id=%s', (order,))
c.execute('DELETE FROM dtf_local.outbox WHERE event_key LIKE %s', (f'{order}:%',))
c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (order,))
if quote:
c.execute('DELETE FROM dtf_local.payment_intents WHERE quote_id=%s', (quote,))
c.execute('DELETE FROM dtf_local.quotes WHERE id=%s', (quote,))
c.execute("DELETE FROM dtf_local.mail_queue WHERE to_addr LIKE %s OR kind='test'", (f'%-{tag}@example.test',))
c.execute('DELETE FROM dtf_local.accounts WHERE email LIKE %s', (f'%-{tag}@example.test',))
c.execute('DELETE FROM dtf_local.operators WHERE email LIKE %s', (f'%-{tag}@example.test',))
c.execute('DELETE FROM dtf_local.login_attempts')
if __name__ == '__main__':
run()

View File

@@ -3,7 +3,7 @@ import json
from pathlib import Path
import subprocess
import unittest
from app.core.pricing import price, TIERS
from app.core.pricing import is_manual, price, TIERS
class PricingTests(unittest.TestCase):
def test_every_grade_against_actual_site_javascript(self):
@@ -31,6 +31,26 @@ class PricingTests(unittest.TestCase):
self.assertEqual(price('avulsa','1',grade)['total_cents']-price('file','1',grade)['total_cents'],1000)
self.assertEqual(price('uv','1',grade)['total_cents']-price('uvfile','1',grade)['total_cents'],1400)
def test_manual_file_extra_is_per_metre_and_not_a_discount(self):
plain, extra = price('file', '1.01', 0), price('file', '1.01', 0, 500)
self.assertEqual(extra['unit_cents'], plain['unit_cents'] + 500)
self.assertEqual(extra['total_cents'], plain['total_cents'] + 550)
self.assertEqual(extra['discount_cents'], 0)
self.assertEqual(extra['manual_extra_cents'], 500)
self.assertNotIn('manual_extra_cents', plain)
for bad in (-1, True, 1.5):
with self.assertRaises(ValueError):price('file', '1', 0, bad)
def test_which_items_are_opened_by_hand(self):
def item(kind, measurement, uid='u1'):
return {'production': {'sources': [{'kind': kind, 'measurement': measurement, 'upload_id': uid}]}}
self.assertTrue(is_manual(item('sheet', 'customer'), {'u1': 'folha.png'}))
self.assertTrue(is_manual(item('sheet', 'file'), {'u1': 'FOLHA.CDR'}))
self.assertTrue(is_manual(item('sheet', 'file'), {'u1': 'folha.tif'}))
self.assertFalse(is_manual(item('sheet', 'file'), {'u1': 'folha.pdf'}))
# Loose artwork is assembled by the Site; it never pays this.
self.assertFalse(is_manual(item('artwork', 'customer'), {'u1': 'arte.cdr'}))
def test_invalid_inputs(self):
for value in ('0','-1','NaN','Infinity','12001'):
with self.assertRaises(ValueError):price('file',value,90)

View File

@@ -57,6 +57,14 @@
window.dtfUploadMaxBytes=session.max_upload_bytes;
const limit=document.getElementById('zLimite');
if(limit)limit.textContent='Até '+(session.max_upload_bytes/1073741824).toFixed(0)+' GB por arquivo.';
if(session.manual_extra_cents>0){
TAXA_MANUAL=session.manual_extra_cents/100;
const zona=document.getElementById('zManual');
if(zona)zona.innerHTML='Tem <b>CDR, AI, PSD ou TIFF</b>? Pode mandar também. Alguém abre na mão: '+
'o metro sai pelo preço cheio, mais '+rs(TAXA_MANUAL)+'.';
if(typeof folhas!=='undefined'&&folhas.length&&typeof pintaFolha==='function')pintaFolha();
if(typeof itemAtual!=='undefined'&&itemAtual&&typeof carrinho==='function')carrinho();
}
}).catch(()=>{});
window.dtfSessionReady=ready;
window.dtfApi=api;

View File

@@ -884,7 +884,7 @@ function itemCard(order,item,index){
const spec=item.production;
const title=node('div',undefined,'title');title.append(node('b',PRODUCT[item.mode]),gradePill(item.grade),node('span',metres(item.billed_metres),'mono'));
body.append(title,facts([['Folha',sheetSize(spec)],['Peças',spec?String(spec.placements.length):null],
['Metro',item.unit_cents?money(item.unit_cents):null],['Arquivos',spec&&spec.sources.length>1?String(spec.sources.length):null]]));
['Metro',item.unit_cents?money(item.unit_cents)+manualExtra(item):null],['Arquivos',spec&&spec.sources.length>1?String(spec.sources.length):null]]));
if(item.quality_status==='warning')body.append(badge('! Ressalva de resolução aceita','warn'));
// After a customer correction, that file is the artwork: the generated
// print file, or the reason it could not be made, no longer applies.
@@ -991,7 +991,7 @@ function renderUsers(){
const machineName=id=>machines.find(m=>m.id===id)?.name||'—';
const rows=users.map(u=>{
const tr=node('tr');if(!u.active)tr.classList.add('off');
const who=node('td');who.append(node('b',u.name||u.email),node('span',u.email,'faint block'));
const who=node('td');who.append(node('b',u.name||u.email),node('span',u.email+(u.alerts?' · recebe alertas':''),'faint block'));
const machinesTd=node('td',u.machines.length?u.machines.map(machineName).join(', '):(u.role==='operador'?'Todas':'—'));
const seen=node('td',u.last_login_at?when(u.last_login_at):'nunca entrou','faint');
const actions=node('td',undefined,'actions');
@@ -1037,14 +1037,16 @@ function userForm(u){
pass.required=!editing;pass.placeholder=editing?'Deixe em branco para manter':'12 caracteres ou mais';
const active=node('input');active.type='checkbox';active.checked=u?u.active:true;active.disabled=u?.email===ME.email;
const activeLabel=node('label',undefined,'check');activeLabel.append(active,'Ativo (pode entrar no Kanban)');
const alerts=node('input');alerts.type='checkbox';alerts.checked=!!u?.alerts;
const alertsLabel=node('label',undefined,'check');alertsLabel.append(alerts,'Receber alertas por e-mail (pedido pago, cotação para revisar, pagamento com problema)');
const boxes=usersData.machines.map(m=>{const c=node('input');c.type='checkbox';c.value=m.id;c.checked=!!u?.machines.includes(m.id);
const l=node('label',undefined,'check');l.append(c,m.name);return l;});
const machinesField=node('div',undefined,'mfield');
machinesField.append('Máquinas (só para operadores; nenhuma = todas)',...(boxes.length?boxes:[node('span','Nenhuma máquina cadastrada.','faint')]));
const syncMachines=()=>{machinesField.hidden=role.value!=='operador';};role.onchange=syncMachines;syncMachines();
dialog(editing?'Editar usuário':'Novo usuário',[field('Nome',name),field('E-mail',email),field('Perfil',role),
field(editing?'Nova senha':'Senha inicial',pass),machinesField,activeLabel],async()=>{
const body={name:name.value,email:email.value,role:role.value==='superadmin'?'admin':role.value,active:active.checked,
field(editing?'Nova senha':'Senha inicial',pass),machinesField,activeLabel,alertsLabel],async()=>{
const body={name:name.value,email:email.value,role:role.value==='superadmin'?'admin':role.value,active:active.checked,alerts:alerts.checked,
machines:role.value==='operador'?boxes.map(l=>l.querySelector('input')).filter(c=>c.checked).map(c=>c.value):[],
password:pass.value||null};
await api(editing?'/users/'+u.id:'/users',body);
@@ -1311,7 +1313,7 @@ function quoteItem(item,fields,priced){
const title=node('div',undefined,'title');
title.append(node('b',PRODUCT[item.mode]),gradePill(item.grade),...(priced?[node('span',money(priced.total_cents),'mono')]:[]));
body.append(title,facts([['Folha',sheetSize(spec)],['Cobrado',priced?metres(priced.billed_metres):null],
['Metro',priced?money(priced.unit_cents):null],['Peças',spec?String(spec.placements.length):null],
['Metro',priced?money(priced.unit_cents)+manualExtra(priced):null],['Peças',spec?String(spec.placements.length):null],
['Arquivos',spec?String(spec.sources.length):null]]));
const chips=node('div',undefined,'flags');
chips.append(item.quality_status==='ok'?badge('✓ Qualidade conferida','ok'):item.quality_status==='warning'?
@@ -1330,6 +1332,9 @@ function quoteItem(item,fields,priced){
body.append(buttons);box.append(preview,body);return box;
}
// A finished sheet someone opens by hand pays this per metre on top (app/core/pricing.py).
const manualExtra=item=>item?.manual_extra_cents?' (com '+money(item.manual_extra_cents)+' de arquivo manual)':'';
// ---- Payments and integrations ------------------------------------------
const tinyResult=new URLSearchParams(location.search).get('tiny');
@@ -1561,6 +1566,7 @@ function renderIntegrations(){
node('p',fr.box_cm?'A Jadlog cobra o maior entre o peso real e o cubado.':'Sem a caixa, a cotação usa só o peso real.')]})
: integration({name:'Frete',state:'Não configurado',tone:'off',summary:'Somente retirada.'}));
rows.push(integration({name:'WhatsApp',state:'Não configurado',tone:'off',summary:'Mensagens registradas, sem envio.'}));
rows.push(mailRow(board.providers?.mail||{}));
const bk=board.providers?.backup||{};
const ontem=bk.last_ok&&Date.now()-new Date(bk.last_ok)<26*3600e3;
const tam=bk.bytes?(bk.bytes<1048576?Math.max(1,Math.round(bk.bytes/1024))+' KB':(bk.bytes/1048576).toFixed(1).replace('.',',')+' MB'):'';
@@ -1573,6 +1579,23 @@ function renderIntegrations(){
$('integrations').replaceChildren(...rows);
eventFilters();
}
// E-mail: customers' password recovery and the team's alerts (app/mail.py).
function mailRow(m){
const name='E-mail';
if(m.adapter!=='smtp'&&m.adapter!=='log')return integration({name,state:'Não configurado',tone:'off',
summary:'Sem recuperação de senha por e-mail: o cliente é orientado a chamar no WhatsApp.'});
const local=m.adapter==='log';
const who=m.alerts?m.alerts+(m.alerts>1?' pessoas recebem':' pessoa recebe')+' os alertas':'ninguém recebe os alertas ainda';
return integration({name,state:m.error?'Verificar':local?'Só registro':'Ativo',tone:m.error?'warn':local?'off':'ok',
summary:m.error?'Falhou o envio para '+m.error.to+': '+m.error.error:'Recuperação de senha e alertas · '+who+'.',
actions:[button('Enviar teste',async()=>{const r=await api('/mail/test',{});
say(local?'Teste registrado. Neste ambiente os e-mails ficam só no registro do servidor.':'Teste enviado para '+r.to+'. Confira a caixa de entrada (e o spam).');})],
details:[...(local?[node('p','Ambiente local: os e-mails não saem do servidor, ficam no registro do worker.')]:[]),
['Remetente',m.from||'—'],...(m.host?[['Servidor',m.host]]:[]),
['Último envio',m.last_sent?when(m.last_sent):'Nenhum ainda'],['Na fila',String(m.pending||0)],
...(m.error?[['Último erro',when(m.error.at)+' · '+m.error.error]]:[]),
node('p','Quem recebe os alertas se escolhe em Usuários → Editar → “Receber alertas por e-mail”.')]});
}
function mercadoPagoCheck(r){
const w=r.webhooks||{};
return [['Credencial',r.token==='test'?'De teste':'De produção'],

View File

@@ -42,7 +42,18 @@
<input id="password" type="password" autocomplete="current-password" required>
<button class="bPri">Entrar</button>
<button type="button" class="bLink" id="esqueci">Esqueci minha senha</button>
<p class="nota2" id="esqueciTx" hidden>A recuperação por e-mail chega em breve. Enquanto isso, fale com a Dropstar pelo WhatsApp <a href="https://wa.me/message/NJ76CLIOUGXLB1" target="_blank" rel="noopener">16 99428-0056</a>.</p>
</form>
<!-- Takes the place of "Entrar" while open. -->
<form class="bloco" id="fEsqueci" hidden>
<h2>Esqueci minha senha</h2>
<div id="esqueciMailBox">
<p class="nota2">Informe o e-mail da sua conta. Enviamos um link para você criar uma nova senha.</p>
<label for="esqueciMail">E-mail</label>
<input id="esqueciMail" type="email" autocomplete="username" required>
<button class="bPri" id="esqueciEnviar">Enviar link</button>
</div>
<p class="nota2" id="esqueciZap" hidden>Fale com a Dropstar pelo WhatsApp <a href="https://wa.me/message/NJ76CLIOUGXLB1" target="_blank" rel="noopener">16 99428-0056</a> para criar uma nova senha.</p>
<button type="button" class="bLink" id="voltarEntrar">Voltar para entrar</button>
</form>
<form class="bloco" id="register">
<h2>Criar conta</h2>
@@ -60,6 +71,22 @@
</div>
</section>
<!-- /conta/redefinir#<link do e-mail> -->
<section class="acesso" id="redefinir" hidden aria-labelledby="tRedefinir">
<h1 id="tRedefinir">Criar nova senha</h1>
<div class="acessoGrid">
<form class="bloco" id="fRedefinir">
<h2>Nova senha</h2>
<p class="nota2">Depois de salvar, você já entra na sua conta.</p>
<label for="rNova">Nova senha <span class="obs">12 caracteres ou mais</span></label>
<input id="rNova" type="password" minlength="12" maxlength="128" autocomplete="new-password" required>
<label for="rRepete">Repita a nova senha</label>
<input id="rRepete" type="password" minlength="12" maxlength="128" autocomplete="new-password" required>
<button class="bPri">Salvar e entrar</button>
</form>
</div>
</section>
<!-- /conta, /conta/pedidos, /conta/dados -->
<div class="area" id="area" hidden>
<nav class="lateral" aria-label="Minha conta">

View File

@@ -42,6 +42,7 @@ function forgetCheckout(){for(const k of ['dtf-quote','dtf-request-key','dtf-req
function vista(){
const p=location.pathname.replace(/\/+$/,'');
if(p==='/conta/entrar') return 'entrar';
if(p==='/conta/redefinir') return 'redefinir';
if(p==='/conta/dados') return 'dados';
if(p==='/conta') return 'geral';
return 'pedidos'; // /conta/pedidos, and the old /portal.html
@@ -61,12 +62,14 @@ async function mostra(){
if((v==='geral'||v==='dados')&&!conta){history.replaceState({},'','/conta/entrar?next='+encodeURIComponent(location.pathname));return mostra();}
if(v==='entrar'&&conta){history.replaceState({},'',proximo&&/^\/conta(\/[a-z]+)?$/.test(proximo)?proximo:'/conta');return mostra();}
$('auth').hidden=v!=='entrar';
$('area').hidden=v==='entrar';
$('redefinir').hidden=v!=='redefinir';
$('area').hidden=v==='entrar'||v==='redefinir';
if(v==='redefinir'&&!resetToken)aviso('Este link está incompleto. Peça outro em “Esqueci minha senha”.',true);
$('vGeral').hidden=v!=='geral';$('vPedidos').hidden=v!=='pedidos';$('vDados').hidden=v!=='dados';
for(const a of document.querySelectorAll('.lateral a'))a.classList.toggle('on',a.dataset.view===v);
for(const a of document.querySelectorAll('.lateral [data-conta]'))a.hidden=!conta;
$('navEntrar').hidden=!!conta;$('logout').hidden=!conta;
document.title=({entrar:'Entrar',geral:'Minha conta',pedidos:'Pedidos',dados:'Dados da conta'})[v]+' · DTF Dropstar';
document.title=({entrar:'Entrar',redefinir:'Criar nova senha',geral:'Minha conta',pedidos:'Pedidos',dados:'Dados da conta'})[v]+' · DTF Dropstar';
if(v==='geral')await geral();
else if(v==='pedidos')await pedidos();
else if(v==='dados')dados();
@@ -328,23 +331,51 @@ async function migrateGuestCart(previous,next){
await new Promise((resolve,reject)=>{const tx=database.transaction('cart','readwrite'),store=tx.objectStore('cart'),req=store.get(previous);req.onsuccess=()=>{if(req.result){store.put(req.result,next);store.delete(previous);}};tx.oncomplete=resolve;tx.onerror=()=>reject(tx.error);});
database.close();
}
async function authenticate(path,body){
async function authenticate(path,body,destino){
const previous=scope,guest=!conta;
const r=await api(path,body);forgetCheckout();
const next=(await api('/session')).cart_scope;scope=next;
if(guest)try{await migrateGuestCart(previous,next);}catch{aviso('Não foi possível transferir o carrinho salvo neste navegador.',true);}
conta=r.customer;$('quem').textContent=conta.mail;
$('password').value='';$('register-password').value='';
if(destino)history.replaceState({},'',destino);
await mostra();
}
$('login').onsubmit=async event=>{event.preventDefault();try{await authenticate('/account/login',{email:$('email').value,password:$('password').value});}catch(e){aviso(e.message,true);}};
$('register').onsubmit=async event=>{event.preventDefault();try{await authenticate('/account/register',{customer:{cnpj:$('cnpj').value,zap:$('phone').value,mail:$('register-email').value},password:$('register-password').value});}catch(e){aviso(e.status===422?'Confira o CNPJ, o WhatsApp e o e-mail. A senha precisa ter 12 caracteres ou mais.':e.message,true);}};
$('esqueci').onclick=()=>{$('esqueciTx').hidden=!$('esqueciTx').hidden;};
// Password recovery: a link by e-mail when the server sends e-mail,
// otherwise the WhatsApp. The link arrives in the address's fragment.
let recovery=false, resetToken='';
if(location.pathname.replace(/\/+$/,'')==='/conta/redefinir'&&location.hash.length>1){
resetToken=location.hash.slice(1);history.replaceState({},'','/conta/redefinir');
}
function esqueci(abrir){
$('login').hidden=abrir;$('fEsqueci').hidden=!abrir;
$('esqueciMailBox').hidden=!recovery;$('esqueciZap').hidden=recovery;
if(abrir){$('esqueciMail').value=$('email').value;(recovery?$('esqueciMail'):$('voltarEntrar')).focus();}
else $('email').focus();
}
$('esqueci').onclick=()=>esqueci(true);
$('voltarEntrar').onclick=()=>{aviso('');esqueci(false);};
$('fEsqueci').onsubmit=async event=>{
event.preventDefault();$('esqueciEnviar').disabled=true;
try{const r=await api('/account/forgot',{email:$('esqueciMail').value});aviso(r.message);}
catch(e){aviso(e.status===422?'Confira o e-mail.':e.message,true);}
finally{$('esqueciEnviar').disabled=false;}
};
$('fRedefinir').onsubmit=async event=>{
event.preventDefault();
if($('rNova').value!==$('rRepete').value){aviso('A nova senha e a repetição não conferem.',true);return;}
try{await authenticate('/account/reset',{token:resetToken,password:$('rNova').value},'/conta');
resetToken='';$('rNova').value='';$('rRepete').value='';aviso('Senha criada. Você já está na sua conta.');}
catch(e){aviso(e.status===422?(resetToken?'A nova senha precisa ter 12 caracteres ou mais.':'Este link está incompleto. Peça outro em “Esqueci minha senha”.'):e.message,true);}
};
$('logout').onclick=async()=>{try{await window.dtfForgetPrivateData();await api('/account/logout',{});location.assign('/conta/entrar');}catch(error){aviso('Não foi possível limpar os dados deste navegador. Feche as abas do Site e limpe os dados do site nas configurações do navegador.',true);}};
(async()=>{
try{
const session=await api('/session');scope=session.cart_scope;environment=session.environment;
recovery=!!session.password_recovery;
$('dev-notice').hidden=environment!=='local';
conta=(await api('/account/me')).customer;
if(conta)$('quem').textContent=conta.mail;

View File

@@ -58,7 +58,7 @@ function pintaPedido(){
const soma = itens + frete;
const n = aPagar.length, noCarrinho = pedido.length + (itemAtual?1:0);
const eco = aPagar
.reduce((t,it)=>t+(TABELA[it.modo]-it.unit)*it.cob, 0);
.reduce((t,it)=>t+(TABELA[it.modo]-(it.unit-(it.extra||0)))*it.cob, 0);
$('resLin').innerHTML =
'<div class="l"><span>'+n+(n===1?' item':' itens')+'</span><b>'+rs(itens+eco)+'</b></div>'+
(eco>0.01? '<div class="l" style="color:var(--verde-ml)"><span>Desconto pela nota</span>'+
@@ -82,7 +82,8 @@ function pintaPedido(){
function carrinho(){
const base=precoBase(nota), cob=cobrar(metros);
const unit=base, tot=cob*unit, sobra=+(cob-metros).toFixed(2);
const extra=folhaManual()? TAXA_MANUAL : 0;
const unit=base+extra, tot=cob*unit, sobra=+(cob-metros).toFixed(2);
$('carr').classList.add('on');
let l='<div class="l"><span>'+MODOS[modo].tit+'</span><b>'+rs(base)+'/m</b></div>';
{
@@ -94,6 +95,7 @@ function carrinho(){
}
if(!ehFolha()) l += '<div class="l" style="color:#8D9AB0"><span>Montagem da folha</span>'+
'<b>inclusa · '+rs(MONTAGEM[modo])+'/m</b></div>';
if(extra) l += '<div class="l"><span>Arquivo aberto na mão</span><b>+'+rs(extra)+'/m</b></div>';
l += '<div class="l"><span>Metragem'+(sobra>0.001?' · arredondada para 10 cm':'')+
'</span><b>'+fmtM(cob)+' m</b></div>';
l += '<div class="l"><span>Preço final do metro</span><b>'+rs(unit)+'</b></div>'+
@@ -124,7 +126,7 @@ function carrinho(){
if(!montagemLayout) return;
layout=montagemLayout;
}
itemAtual={modo, tit:MODOS[modo].tit, nota, metros, cob, unit, total:tot,
itemAtual={modo, tit:MODOS[modo].tit, nota, metros, cob, unit, extra, total:tot,
localFiles:(ehFolha()?folhas:artes).map(x=>x.f),
mini:(ehFolha()?folhas:artes).map(x=>x.miniSrc).find(Boolean)||null,
fotos:(ehFolha()?folhas:artes).map(x=>x.fotoSrc||null),
@@ -138,7 +140,7 @@ function carrinho(){
pintaPedido();
previa();
if(nota<90){
const piso=pisoEscada(), ganho=(base-piso)*cob;
const piso=pisoEscada(), ganho=(unit-piso)*cob;
if(ganho>0.5) qm('<b>Dá para pagar menos.</b> Com a arte em 300 DPI, '+
'o metro cai para '+rs(piso)+' — são '+rs(ganho)+' a menos neste pedido.','var(--verde)');
}

View File

@@ -17,13 +17,14 @@
(min? min*3+'+'+(i? '' : ' DPI') : semNota? 'cheio' : 'menos')+'</span>'+
'<b>'+rs(v).slice(3)+'</b></li>').join('');
const analisadas=ehFolha(it.modo) && folhas.length && folhas.every(x=>x.an);
$('cMetroLbl').textContent = semNota ? 'Metro · preço cheio'
$('cMetroLbl').textContent = it.extra ? 'Metro · cheio + '+rs(it.extra)+' manual'
: semNota ? 'Metro · preço cheio'
: analisadas && folhas.every(x=>x.an.vetor) ? 'Metro · arte vetorial'
: analisadas ? 'Metro · '+Math.min(...folhas.map(x=>x.an.dpi))+' DPI'
: 'Metro';
$('cMetro').textContent=rs(it.unit);
$('cMetragem').textContent=fmtM(it.cob)+' m';
const economia=(TABELA[it.modo]-it.unit)*it.cob;
const economia=(TABELA[it.modo]-(it.unit-(it.extra||0)))*it.cob;
$('cEco').textContent = economia>0.005 ? rs(economia)+' a menos pela resolução da arte' : '';
const partes=ehFolha(it.modo) ? Math.ceil(it.metros/20) : 1;
$('cPartes').textContent = partes>1 ? ' Sai em '+partes+' partes de até 20 m.' : '';

View File

@@ -55,6 +55,10 @@ const FAIXAS={
};
const TABELA={file:19.90, avulsa:29.90, uvfile:85.90, uv:99.90}; // teto de cada escada
const MONTAGEM={avulsa:10.00, uv:14.00}; // o que a montagem soma sobre a folha pronta
// Folha que alguém abre na mão (CDR, AI, PSD, TIFF): R$ a mais por metro.
// Vem do servidor (/api/session), que cobra o mesmo; zero não soma nada.
let TAXA_MANUAL=0;
const folhaManual=()=>ehFolha() && folhas.some(x=>!x.med);
const ehFolha=m=>!!MODOS[m||modo].folha;
const pisoEscada=m=>FAIXAS[m||modo][0][1];
const MINIMO_M=1, GAP_CM=0.5, RODAPE_CM=5;

View File

@@ -438,10 +438,11 @@ function pintaFolha(){
'<p class="avisoF"><b>Este PDF não pode ser orçado.</b> '+escapeHTML(x.measurementError)+'</p>';
}else{
const teto=TABELA[modo], piso=pisoEscada();
const dif=(x.m>0)? (teto-piso)*cobrar(x.m*(x.rep||1)) : 0;
const dif=(x.m>0)? (teto+TAXA_MANUAL-piso)*cobrar(x.m*(x.rep||1)) : 0;
medida='<span class="chipSo">Conferência manual · preço cheio</span>'+
'<p class="repTxt">O navegador não abre '+escapeHTML(extDe(x.f.name))+', então alguém da equipe '+
'confere antes de imprimir e o metro sai pela tabela, <b>'+rs(teto)+'</b>. '+
'confere antes de imprimir e o metro sai pela tabela, <b>'+rs(teto)+'</b>'+
(TAXA_MANUAL? ', mais <b>'+rs(TAXA_MANUAL)+'</b> pela abertura manual' : '')+'. '+
'Exportando em <b>PNG ou PDF</b>, o metro pode cair até <b>'+rs(piso)+'</b>'+
(dif>0.5? ' — <b>'+rs(dif)+' a menos</b> só nesta folha' : '')+'.</p>';
manual='<div class="campo"><label for="comp'+i+'">Comprimento</label>'+

View File

@@ -264,6 +264,8 @@ section+section{border-top:0}
#ampliaArea .folhaPilha img{display:block;width:auto;max-width:100%;height:auto;max-height:calc(100vh - 180px)!important}
#ampliaArea figcaption{padding:8px 12px;font-size:15px;color:var(--texto2);border-top:1px solid var(--linha)}
.cLin{display:flex;align-items:baseline;gap:8px}
/* A price never breaks across lines; a long label wraps instead. */
.cLin>b{white-space:nowrap}
.cLin>span:last-child,.cLin>b{margin-left:auto;display:flex;gap:8px;align-items:baseline}
.cLin s{font-size:15px;color:#707070}
.cObs{margin:-4px 0 0;font-size:15px;color:var(--verde)}