"""Quotes: review, search, test and outside-paid orders, discard.""" import re from datetime import datetime from typing import Literal from uuid import UUID from fastapi import APIRouter, Depends, HTTPException, Query from pydantic import Field from ... import payments, quote_review from ...core import db from ...core.auth import audit, can, operator from ...core.models import Review, StrictModel from ...runtime import quote_views from .board import with_print_files from .common import (LIVE_QUOTE, MODES, company_names, customer_match, like, numeric, thumbnails) router = APIRouter() @router.get('/api/operator/quotes') def quote_page(kind: Literal['pending','approved'], before_created_at: datetime | None = None, before_id: UUID | None = None, offset: int = Query(default=0, ge=0), limit: int = Query(default=50, ge=1, le=100), q: str | None = Query(default=None, max_length=100), product: Literal['textil','uv'] | None = None, layout: Literal['folha','avulsa'] | None = None, flag: Literal['ressalva'] | None = None, user=Depends(operator)): """Unpaid quotes, newest first: by cursor, or by page (offset) with a total; filtered by customer, product, layout and an accepted resolution warning.""" if (before_created_at is None) != (before_id is None): raise HTTPException(422, 'Both quote cursor fields are required') clauses = ['o.id IS NULL', LIVE_QUOTE, 'q.approved IS NULL' if kind == 'pending' else 'q.approved IS NOT NULL'] params = [] if q and q.strip(): sql, values = customer_match('q.draft', q) clauses.append(sql); params += values if product or layout: modes = set.intersection(*(MODES[k] for k in (product, layout) if k)) clauses.append("EXISTS (SELECT 1 FROM jsonb_array_elements(q.draft->'items') i WHERE i->>'mode'=ANY(%s))") params.append(sorted(modes)) if flag: clauses.append("EXISTS (SELECT 1 FROM jsonb_array_elements(q.draft->'items') i WHERE i->>'quality_status'='warning')") where = ' AND '.join(clauses) cursor = 'AND (q.created_at,q.id)<(%s,%s)' if before_created_at else '' skip = 0 if before_created_at else offset page = params + ([before_created_at, before_id] if before_created_at else []) + [limit+1, skip] with db.connect() as c: rows = c.execute(f'''SELECT q.* FROM dtf_local.quotes q LEFT JOIN dtf_local.orders o ON o.quote_id=q.id WHERE {where} {cursor} ORDER BY q.created_at DESC,q.id DESC LIMIT %s OFFSET %s''', page).fetchall() total = c.execute(f'''SELECT count(*) AS n FROM dtf_local.quotes q LEFT JOIN dtf_local.orders o ON o.quote_id=q.id WHERE {where}''', params).fetchone()['n'] quotes = quote_views(c, rows[:limit]) return {'quotes': quotes, 'has_more': len(rows)>limit, 'total': total, 'thumbnails': thumbnails(c, quotes), 'names': company_names(c, quotes)} @router.get('/api/operator/search') def search(q: str = Query(min_length=2, max_length=100), user=Depends(operator)): """One search over orders (any stage) and unpaid quotes: customer e-mail, CNPJ or WhatsApp, the delivery recipient, or the order number.""" match, params = customer_match('snapshot', q) digits = numeric(q) sql = match + " OR lower(coalesce(snapshot->'destination'->>'recipient','')) LIKE %s" params.append(like(q.strip().lower())) if digits and len(digits) <= 9: sql += ' OR number=%s' params.append(int(digits)) # The code a customer reads out (the id's first characters, see order_code). code = q.strip().lstrip('#').lower() if 6 <= len(code) <= 12 and re.fullmatch(r'[0-9a-f]+', code): sql += " OR replace(id::text,'-','') LIKE %s" params.append(code + '%') quote_match, quote_params = customer_match('q.draft', q) with db.connect() as c: # Real orders: a proof card is found through its order (app/proof.py). orders = c.execute(f'''SELECT * FROM dtf_local.orders WHERE ({sql}) AND parent_id IS NULL ORDER BY created_at DESC LIMIT 8''', params).fetchall() rows = c.execute(f'''SELECT q.* FROM dtf_local.quotes q LEFT JOIN dtf_local.orders o ON o.quote_id=q.id WHERE o.id IS NULL AND {LIVE_QUOTE} AND {quote_match} ORDER BY q.created_at DESC LIMIT 8''', quote_params).fetchall() orders = with_print_files(c, orders) quotes = quote_views(c, rows) return {'orders': orders, 'quotes': quotes, 'thumbnails': thumbnails(c, orders, quotes), 'names': company_names(c, orders, quotes)} @router.post('/api/operator/quotes/{uid}/approve') def approve(uid: UUID, body: Review, user=Depends(can('manage'))): with db.connect() as c: row = c.execute('SELECT * FROM dtf_local.quotes WHERE id=%s FOR UPDATE', (uid,)).fetchone() if not row: raise HTTPException(404, 'Quote not found') return quote_review.approve(c, row, body.items, user) @router.post('/api/operator/quotes/{uid}/test-order') def test_order(uid: UUID, user=Depends(can('manage'))): """An order for an approved quote without payment, to try the Kanban, files and print flow in production. Marked TEST on the board, never sent to Tiny or WhatsApp, and audited.""" with db.connect() as c: try: quote = payments.approved_quote(c, uid) except payments.PaymentRefused as refusal: raise HTTPException(404 if 'not found' in str(refusal) else 409, str(refusal)) receipt = {'provider': payments.TEST_PROVIDER, 'id': f'teste-{uid}', 'status': 'paid', 'total_cents': quote['approved']['total_cents'], 'operator': user} order, created = payments.create_order(c, quote, receipt, 'site') if created: audit('test_order_created', order=str(order['id']), operator=user) return order class PaidOutside(StrictModel): # No defaults (D-35): whoever registers the order says where it came from # and how it was paid. origin: Literal['site', 'dropflow', 'atendimento'] method: Literal[payments.OUTSIDE_METHODS] note: str = Field(default='', max_length=300) @router.post('/api/operator/quotes/{uid}/register') def register_order(uid: UUID, body: PaidOutside, user=Depends(can('enter'))): """The order for an approved quote paid outside the system (Dropstar's rule D-35): the team builds the cart on the Site, as a customer would, and registers it here with its origin and how it was paid. The price is the quote's, the Site's table price.""" with db.connect() as c: try: quote = payments.approved_quote(c, uid) except payments.PaymentRefused as refusal: raise HTTPException(404 if 'not found' in str(refusal) else 409, str(refusal)) receipt = {'provider': payments.MANUAL_PROVIDER, 'method': body.method, 'note': body.note.strip(), 'status': 'paid', 'total_cents': quote['approved']['total_cents'], 'operator': user} order, created = payments.create_order(c, quote, receipt, body.origin) if not created: raise HTTPException(409, f"Esta cotação já virou o pedido #{order['number']}.") audit('manual_order_registered', order=str(order['id']), origin=body.origin, operator=user) return order @router.post('/api/operator/quotes/{uid}/discard') def discard_quote(uid: UUID, user=Depends(can('manage'))): """An unpaid quote leaves the Kanban and can no longer be paid. Its files keep their normal expiry; a payment that still arrives for it is refused and listed under Pagamentos.""" with db.connect() as c: # Locked like a payment locks it, so a discard and a payment never cross. row = c.execute('SELECT id FROM dtf_local.quotes WHERE id=%s FOR UPDATE', (uid,)).fetchone() if not row: raise HTTPException(404, 'Quote not found') if c.execute('SELECT 1 FROM dtf_local.orders WHERE quote_id=%s', (uid,)).fetchone(): raise HTTPException(409, 'Esta cotação já virou pedido.') c.execute('UPDATE dtf_local.quotes SET discarded_at=now(), discarded_by=%s WHERE id=%s AND discarded_at IS NULL', (user, uid)) audit('quote_discarded', quote=str(uid), operator=user) return {'ok': True}