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>
84 lines
4.4 KiB
Python
84 lines
4.4 KiB
Python
"""Quotes: the customer's cart, approved at once when it can be (app/quote_review.py)."""
|
|
import hashlib
|
|
import json
|
|
from decimal import Decimal
|
|
from uuid import UUID, uuid4
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException
|
|
from psycopg.types.json import Jsonb
|
|
|
|
from .. import mail, payments
|
|
from ..core import db
|
|
from ..core.auth import owner
|
|
from ..core.models import QuoteRequest
|
|
from ..core.pricing import price
|
|
from .. import quote_review
|
|
from ..grade_check import Files, mismatch
|
|
from ..runtime import freight, payment, quote_view, require_delivery_available, storage, upload_row
|
|
from ..scanning import require_clean
|
|
|
|
router = APIRouter()
|
|
|
|
@router.post('/api/quotes')
|
|
def create_quote(body: QuoteRequest, session_id=Depends(owner)):
|
|
for item in body.items:
|
|
if abs(item.metres*100-item.production.height_cm) > Decimal('0.02'):
|
|
raise HTTPException(422, 'A metragem não confere com a montagem enviada. Monte o pedido de novo.')
|
|
require_delivery_available(body.freight.service)
|
|
draft = body.model_dump(mode='json', exclude={'request_key'})
|
|
digest = hashlib.sha256(json.dumps(draft, sort_keys=True).encode()).hexdigest()
|
|
reason = quote_review.review_reason(draft)
|
|
if reason is not None:
|
|
# Waits for review: check the delivery now, priced at approval.
|
|
try:
|
|
priced = [price(item.mode, str(item.metres), item.grade) for item in body.items]
|
|
freight.quote(body.freight.service, body.freight.postal_code,
|
|
sum(Decimal(i['billed_metres']) for i in priced), sum(i['total_cents'] for i in priced))
|
|
except ValueError as exc:
|
|
raise HTTPException(422, str(exc))
|
|
with db.connect() as c:
|
|
rows = {}
|
|
for item in body.items:
|
|
for uid in item.uploads:
|
|
row = upload_row(c, uid, session_id)
|
|
if not row['complete']:
|
|
raise HTTPException(409, 'Espere o envio de todos os arquivos terminar antes de continuar.')
|
|
require_clean(row)
|
|
rows[str(uid)] = row
|
|
# The grade sets the price and came from the browser: before a cart is
|
|
# approved at checkout, the server works it out from the files.
|
|
note = mismatch(Files(storage), draft['items'], rows) if reason is None else None
|
|
reason = reason or note
|
|
uid = uuid4()
|
|
c.execute('INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,review_note) VALUES(%s,%s,%s,%s,%s,%s) ON CONFLICT(owner,request_key) DO NOTHING',
|
|
(uid, session_id, body.request_key, digest, Jsonb(draft), note))
|
|
row = c.execute('SELECT * FROM dtf_local.quotes WHERE owner=%s AND request_key=%s FOR UPDATE', (session_id, body.request_key)).fetchone()
|
|
if row['request_hash'] != digest:
|
|
raise HTTPException(409, 'O carrinho mudou durante o envio. Tente de novo.')
|
|
if row['id'] == uid and reason is None:
|
|
quote_review.approve(c, row, body.items, quote_review.AUTO)
|
|
return {'id': row['id'], 'status': 'approved'}
|
|
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}')
|
|
def get_quote(uid: UUID, session_id=Depends(owner)):
|
|
with db.connect() as c:
|
|
row = c.execute('SELECT * FROM dtf_local.quotes WHERE id=%s AND owner=%s', (uid,session_id)).fetchone()
|
|
if not row:
|
|
raise HTTPException(404, 'Pedido não encontrado.')
|
|
view = quote_view(c, row)
|
|
# The payment page asks every few seconds while it waits for the order. An
|
|
# approved card with no order yet is checked with the provider now, rather
|
|
# than waiting for its notification.
|
|
if view['status'] == 'approved' and (view['payment'] or {}).get('status') == 'approved':
|
|
if payments.reconcile(db.connect, payment, quote_id=uid, limit=3):
|
|
with db.connect() as c:
|
|
view = quote_view(c, c.execute('SELECT * FROM dtf_local.quotes WHERE id=%s', (uid,)).fetchone())
|
|
return view
|