From 3664fe827e811b5496a03231660fb6f535bf91f1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cau=C3=AA=20Faleiros?= Date: Tue, 13 Oct 2026 11:48:24 -0300 Subject: [PATCH] feat: password recovery by e-mail, team alerts, and a price for files opened by hand MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- .env.example | 8 ++ .gitea/workflows/deploy.yml | 2 +- app/adapters.py | 10 ++ app/api/customer.py | 68 +++++++++- app/api/health.py | 5 + app/api/operator.py | 5 +- app/api/quotes.py | 5 +- app/api/users.py | 32 +++-- app/core/models.py | 7 ++ app/core/pricing.py | 42 ++++++- app/core/secrets.py | 1 + app/mail.py | 169 +++++++++++++++++++++++++ app/payments.py | 16 ++- app/quote_review.py | 10 +- app/schema.sql | 20 +++ app/worker.py | 2 + compose.local.yaml | 12 ++ deploy/nginx.conf.template | 2 +- deploy/portainer.env.example | 9 ++ docker-compose.yml | 17 +++ docs/CONTEXT.md | 22 +++- docs/PORTAINER.md | 15 +++ infra/nginx.conf.template | 2 +- tests/browser_test.mjs | 14 ++- tests/mail_test.py | 234 +++++++++++++++++++++++++++++++++++ tests/test_pricing.py | 22 +++- web/checkout.js | 8 ++ web/kanban.js | 33 ++++- web/portal.html | 29 ++++- web/portal.js | 39 +++++- web/site-cart.js | 10 +- web/site-compra.js | 5 +- web/site-config.js | 4 + web/site-pdf.js | 5 +- web/site-v2.css | 2 + 35 files changed, 834 insertions(+), 52 deletions(-) create mode 100644 app/mail.py create mode 100644 tests/mail_test.py diff --git a/.env.example b/.env.example index f7aa48e..b366e49 100644 --- a/.env.example +++ b/.env.example @@ -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 +# 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 diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml index e4d0426..a9221dc 100644 --- a/.gitea/workflows/deploy.yml +++ b/.gitea/workflows/deploy.yml @@ -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 \ diff --git a/app/adapters.py b/app/adapters.py index 95c03d7..6128bf2 100644 --- a/app/adapters.py +++ b/app/adapters.py @@ -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') diff --git a/app/api/customer.py b/app/api/customer.py index 91a1e03..bd8b21e 100644 --- a/app/api/customer.py +++ b/app/api/customer.py @@ -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 ( diff --git a/app/api/health.py b/app/api/health.py index ca0527b..7269462 100644 --- a/app/api/health.py +++ b/app/api/health.py @@ -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. diff --git a/app/api/operator.py b/app/api/operator.py index 98efdc2..7a75db7 100644 --- a/app/api/operator.py +++ b/app/api/operator.py @@ -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( diff --git a/app/api/quotes.py b/app/api/quotes.py index 6f92731..a2fe846 100644 --- a/app/api/quotes.py +++ b/app/api/quotes.py @@ -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}') diff --git a/app/api/users.py b/app/api/users.py index 036b717..67da42d 100644 --- a/app/api/users.py +++ b/app/api/users.py @@ -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} diff --git a/app/core/models.py b/app/core/models.py index b50f43b..cf8029b 100644 --- a/app/core/models.py +++ b/app/core/models.py @@ -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) diff --git a/app/core/pricing.py b/app/core/pricing.py index e9e1d05..21444e7 100644 --- a/app/core/pricing.py +++ b/app/core/pricing.py @@ -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 diff --git a/app/core/secrets.py b/app/core/secrets.py index 55b6c21..e410d7b 100644 --- a/app/core/secrets.py +++ b/app/core/secrets.py @@ -28,6 +28,7 @@ SECRET_FILE_SETTINGS = ( 'PAYMENT_WEBHOOK_SECRET', 'TINY_TOKEN', 'WHATSAPP_TOKEN', + 'SMTP_PASSWORD', ) SUFFIX = '_FILE' diff --git a/app/mail.py b/app/mail.py new file mode 100644 index 0000000..db38d9b --- /dev/null +++ b/app/mail.py @@ -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 ') + 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} diff --git a/app/payments.py b/app/payments.py index 7aa9c95..986eb09 100644 --- a/app/payments.py +++ b/app/payments.py @@ -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() diff --git a/app/quote_review.py b/app/quote_review.py index fffaab9..c4781f3 100644 --- a/app/quote_review.py +++ b/app/quote_review.py @@ -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']}) diff --git a/app/schema.sql b/app/schema.sql index 2ef6fbf..634e862 100644 --- a/app/schema.sql +++ b/app/schema.sql @@ -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; diff --git a/app/worker.py b/app/worker.py index 28d8192..458cf6d 100644 --- a/app/worker.py +++ b/app/worker.py @@ -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() diff --git a/compose.local.yaml b/compose.local.yaml index 6486140..decf240 100644 --- a/compose.local.yaml +++ b/compose.local.yaml @@ -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 } + 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} diff --git a/deploy/nginx.conf.template b/deploy/nginx.conf.template index f80b4b8..ce3f2d1 100644 --- a/deploy/nginx.conf.template +++ b/deploy/nginx.conf.template @@ -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; } diff --git a/deploy/portainer.env.example b/deploy/portainer.env.example index bcb2dde..f5e3bcd 100644 --- a/deploy/portainer.env.example +++ b/deploy/portainer.env.example @@ -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 +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 diff --git a/docker-compose.yml b/docker-compose.yml index d9d7d0b..139fb72 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -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} diff --git a/docs/CONTEXT.md b/docs/CONTEXT.md index 6000e01..0c97887 100644 --- a/docs/CONTEXT.md +++ b/docs/CONTEXT.md @@ -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 diff --git a/docs/PORTAINER.md b/docs/PORTAINER.md index f3dd866..d8fb19f 100644 --- a/docs/PORTAINER.md +++ b/docs/PORTAINER.md @@ -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 `), `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 diff --git a/infra/nginx.conf.template b/infra/nginx.conf.template index 787cff4..7f12f78 100644 --- a/infra/nginx.conf.template +++ b/infra/nginx.conf.template @@ -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; } diff --git a/tests/browser_test.mjs b/tests/browser_test.mjs index 11fd122..732b738 100644 --- a/tests/browser_test.mjs +++ b/tests/browser_test.mjs @@ -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'); diff --git a/tests/mail_test.py b/tests/mail_test.py new file mode 100644 index 0000000..8573e08 --- /dev/null +++ b/tests/mail_test.py @@ -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 ') + 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 ' + 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() diff --git a/tests/test_pricing.py b/tests/test_pricing.py index b833071..7ba7d3e 100644 --- a/tests/test_pricing.py +++ b/tests/test_pricing.py @@ -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) diff --git a/web/checkout.js b/web/checkout.js index 3ff4cff..057ab36 100644 --- a/web/checkout.js +++ b/web/checkout.js @@ -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 CDR, AI, PSD ou TIFF? 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; diff --git a/web/kanban.js b/web/kanban.js index 09db408..3a684d0 100644 --- a/web/kanban.js +++ b/web/kanban.js @@ -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'], diff --git a/web/portal.html b/web/portal.html index 42f978d..a9298ce 100644 --- a/web/portal.html +++ b/web/portal.html @@ -42,7 +42,18 @@ - + + +

Criar conta

@@ -60,6 +71,22 @@ + +
+