diff --git a/app/api/operator.py b/app/api/operator.py index aa34e5d..0ead2f2 100644 --- a/app/api/operator.py +++ b/app/api/operator.py @@ -422,12 +422,40 @@ def test_order(uid: UUID, user=Depends(can('manage'))): 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) + 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 @@ -513,7 +541,7 @@ def cancel_order(uid: UUID, body: Resolution, user=Depends(can('manage'))): (user, body.note, uid)).fetchone() if not row: raise HTTPException(404, 'Pedido não encontrado ou já cancelado.') - if not payments.is_test(row): + if payments.in_tiny(row): sale = c.execute("SELECT receipt FROM dtf_local.outbox WHERE event_key=%s AND delivered_at IS NOT NULL", (f'{uid}:paid:tiny',)).fetchone() enqueue(c, f'{uid}:cancelled:tiny', 'tiny', @@ -664,7 +692,7 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)): # Entering the queue (Arte conferida) is Tiny's "Preparando envio"; # Finalizado its "Pronto para envio" (Dropstar's flow, 2026-10-23). events = {'tra':'production_started','cor':'correction_needed','fin':'ready'} - if body.state in events and not back and not payments.is_test(row): + if body.state in events and not back and payments.in_tiny(row): # "Production started" and "ready" reach the customer once per order, # even if a mistaken move is undone and made again. Each correction # is a new request, so it keeps one message per movement. diff --git a/app/api/orders.py b/app/api/orders.py index 6b5e0e1..aa9f219 100644 --- a/app/api/orders.py +++ b/app/api/orders.py @@ -34,5 +34,5 @@ def dev_paid(body: Pay, session_id=Depends(owner)): # The charge happens inside the transaction that persists the order, so a # failure to record it cannot leave a customer charged without an order. receipt = payment.pay(str(body.quote_id), quote['approved']['total_cents']) - order, _ = payments.create_order(c, quote, receipt) + order, _ = payments.create_order(c, quote, receipt, 'site') return order diff --git a/app/core/auth.py b/app/core/auth.py index 7697e72..75fe677 100644 --- a/app/core/auth.py +++ b/app/core/auth.py @@ -128,6 +128,8 @@ CAPABILITIES = { 'produce': {'superadmin', 'admin', 'gestao', 'designer', 'operador'}, 'print': {'superadmin', 'admin', 'gestao', 'operador'}, 'manage': {'superadmin', 'admin', 'gestao'}, + # Registering an order paid outside the system, from its Site quote (D-35). + 'enter': {'superadmin', 'admin', 'gestao', 'vendedor'}, 'users': {'superadmin', 'admin'}, 'integrations': {'superadmin'}, } diff --git a/app/payments.py b/app/payments.py index f6ec54d..d6156ee 100644 --- a/app/payments.py +++ b/app/payments.py @@ -55,6 +55,20 @@ def is_test(order): return (order.get('payment') or {}).get('provider') == TEST_PROVIDER +# An order paid outside the system (Pix or cash at the counter, a card machine, +# the customer's credit) and registered by the team from its Site quote +# (Dropstar's rule D-35, 2026-10-26; the user's answers of 2026-10-27). +MANUAL_PROVIDER = 'manual' +OUTSIDE_METHODS = ('pix', 'card', 'cash', 'credit') + + +def in_tiny(order): + """Whether the order goes to Tiny: not a test, and not a Dropflow order, + held until Dropstar names that channel's revenue category (it must not be + DTF SITE, their rules document says).""" + return not is_test(order) and order['origin'] != 'dropflow' + + # How long a file is kept while nothing has been paid for it. A cart's files # are uploaded before payment, so the price and the security check are done on # the file itself; a cart that is never paid must not keep them for 30 days. @@ -75,8 +89,9 @@ def hold_uploads(c, upload_ids, interval): WHERE id=ANY(%s) AND purged_at IS NULL''', (interval, [str(u) for u in upload_ids])) -def create_order(c, quote, payment): +def create_order(c, quote, payment, origin): """Create the order for a reviewed quote, or return the one already there. + `origin` is where it came from (D-21): each way in names its own. Returns (order, created). The caller decides what to do about a duplicate; the important part is that asking twice cannot produce two orders, because @@ -93,8 +108,8 @@ def create_order(c, quote, payment): order = c.execute( '''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,origin) - VALUES(%s,%s,%s,%s,%s,'site') RETURNING *''', - (uuid4(), quote['id'], quote['owner'], Jsonb(approved), Jsonb(payment))).fetchone() + VALUES(%s,%s,%s,%s,%s,%s) RETURNING *''', + (uuid4(), quote['id'], quote['owner'], Jsonb(approved), Jsonb(payment), origin)).fetchone() # Paid: the files are kept for the order's retention, counted from upload. c.execute('''UPDATE dtf_local.uploads SET expires_at=GREATEST(expires_at, created_at+%s::interval) WHERE id=ANY(%s) AND purged_at IS NULL''', (ORDER_RETENTION, quote_uploads(approved))) @@ -108,13 +123,18 @@ def create_order(c, quote, payment): if is_test(order): return order, True mail.order_paid(c, order, PUBLIC_ORIGIN) + if not in_tiny(order): + return order, True # How it was paid, for the order's payment in Tiny. - paid = c.execute('''SELECT method FROM dtf_local.payment_intents WHERE quote_id=%s AND status='approved' - ORDER BY created_at DESC LIMIT 1''', (quote['id'],)).fetchone() + if payment.get('provider') == MANUAL_PROVIDER: + paid = {'method': payment['method'], 'outside': True} + else: + paid = c.execute('''SELECT method FROM dtf_local.payment_intents WHERE quote_id=%s AND status='approved' + ORDER BY created_at DESC LIMIT 1''', (quote['id'],)).fetchone() enqueue(c, f"{order['id']}:paid:tiny", 'tiny', {'order_id': str(order['id']), 'number': order['number'], - 'event': 'payment_approved', 'order': approved, - 'payment': {'method': paid['method']} if paid else {}}) + 'event': 'payment_approved', 'order': approved, 'origin': origin, + 'payment': dict(paid) if paid else {}}) return order, True @@ -171,7 +191,7 @@ def apply(c, event): expected_cents=expected, paid_cents=event.amount_cents) return f'refused: paid {event.amount_cents} but quote total is {expected}' - order, created = create_order(c, quote, {'provider': event.raw.get('provider', 'webhook'), **event.raw}) + order, created = create_order(c, quote, {'provider': event.raw.get('provider', 'webhook'), **event.raw}, 'site') return f"order {order['number']}" + ('' if created else ' (already existed)') diff --git a/app/tiny.py b/app/tiny.py index d85ed83..1ed315c 100644 --- a/app/tiny.py +++ b/app/tiny.py @@ -92,6 +92,18 @@ SITUACOES = {0: 'Aberta', 3: 'Aprovada', 4: 'Preparando envio', 1: 'Faturada', 7 # react to these situações. Off until go-live: while n8n still sends the # designer message for DTFIMP products on "Aprovado", setting it would reach # Site customers. +# Where the order came from (D-21) and, when the team registered it, how it was +# paid outside the system (D-35), for whoever reads the order in Tiny. +ORIGIN_NOTES = {'site': 'Site DTF', 'atendimento': 'Atendimento DTF', 'dropflow': 'Dropflow DTF'} +OUTSIDE_NOTES = {'pix': 'Pix', 'card': 'cartão', 'cash': 'dinheiro', 'credit': 'crédito do cliente'} + + +def internal_note(payload): + paid = payload.get('payment') or {} + how = f"pago fora do site ({OUTSIDE_NOTES.get(paid.get('method'), paid.get('method'))})" if paid.get('outside') else 'pago' + return f"{ORIGIN_NOTES.get(payload.get('origin') or 'site')} · {how} · {payload['order_id']}" + + STATUS_UPDATES_SETTING = 'TINY_STATUS_UPDATES' # The client's custom "retirar pessoalmente" forma de envio (v2 code X), which # the pickup notice is keyed on. Found in Tiny by name; this setting, an id, @@ -482,7 +494,7 @@ def order_payload(payload, contact_id, today=None, product_id=None, shipping=Non 'itens': items, 'valorFrete': money(freight['total_cents']), 'observacoes': f"Pedido DTF #{payload['number']}" + (' · retirada em Franca' if pickup else ''), - 'observacoesInternas': f"Site DTF · pago · {payload['order_id']}"} + 'observacoesInternas': internal_note(payload)} carrier = shipping(service) if shipping else None if carrier: pedido['transportador'] = {'fretePorConta': FREIGHT_PAID_BY, **carrier} diff --git a/docs/CONTEXT.md b/docs/CONTEXT.md index 147d400..7d9f568 100644 --- a/docs/CONTEXT.md +++ b/docs/CONTEXT.md @@ -471,10 +471,23 @@ Still to do (2026-10-26): card and in the order panel, filters by it (Origem), and Números has a "Por origem" table: orders, metres, money received and the median time from payment to Finalizado for each way in, Aguardando contato left out. -- Still open from the internal rules (docs received 2026-10-26): the manual - order entry in the Kanban, where the origin must be chosen (D-35; also how - orders paid with credit come in, and the Dropflow batches until their API), - the Tiny revenue category for Dropflow orders (not DTF SITE; its name and +- An order paid outside the system is registered from its Site quote (D-35; + the user's answers of 2026-10-27): the team builds the cart on the Site as + a customer would (the art comes in through the Site, D-08), stops at the + payment step, and in the Kanban's Cotações, on the approved quote, picks the + origin and how it was paid (Pix, cartão, dinheiro, crédito do cliente), + neither preselected, with an optional note. The price is the quote's, the + Site's table price. Allowed to Administrador, Gestão and Vendedor (the + "enter" capability). The order's payment is `{'provider': 'manual', + 'method', 'note', 'operator'}`; it counts in Números like any paid order and + the customer gets the usual paid e-mail. An Atendimento (or Site) order + goes to Tiny like a Site one, its internal note saying "pago fora do site" + and how, Pix and card naming Tiny's forma de recebimento. A Dropflow order + stays out of Tiny, its status updates and cancelling included + (payments.in_tiny), until Dropstar names that channel's revenue category. +- Still open from the internal rules (docs received 2026-10-26): customer + credit as a payment the system keeps track of (today "crédito do cliente" + is only how a registered order was paid), the Tiny revenue category for Dropflow orders (not DTF SITE; its name and the origin value must be the same word, the document says), and the rework register (D-02 to D-04: four causes, falha de impressão, perfil de cor, erro de tratamento and erro de pedido; opened and classified by Mayana, diff --git a/tests/payment_test.py b/tests/payment_test.py index 9b1500d..24d2ead 100644 --- a/tests/payment_test.py +++ b/tests/payment_test.py @@ -166,6 +166,30 @@ def run(): assert queued == 0 and jobs == 1, (queued, jobs) print('PASS: an operator test order reaches the board and the print queue, never Tiny') + # An order paid outside the system, registered by the team from its Site + # quote (D-35): origin and payment are chosen, never assumed. + _, counter_quote, counter_total = reviewed_quote() + register = lambda qid, body, expected=200: board.call('/operator/quotes/' + qid + '/register', body, + operator=True, expected=expected) + for body in ({'method': 'pix'}, {'origin': 'atendimento'}, {'origin': 'whatsapp', 'method': 'pix'}, + {'origin': 'atendimento', 'method': 'boleto'}): + register(counter_quote, body, expected=422) + order = register(counter_quote, {'origin': 'atendimento', 'method': 'cash', 'note': 'Balcão'}) + assert (order['origin'], order['state'], order['payment']['provider'], order['payment']['method'], + order['payment']['total_cents']) == ('atendimento', 'rec', 'manual', 'cash', counter_total), order + register(counter_quote, {'origin': 'atendimento', 'method': 'cash'}, expected=409) + with db.connect() as c: + sent = c.execute("SELECT payload FROM dtf_local.outbox WHERE event_key=%s", (order['id'] + ':paid:tiny',)).fetchone() + assert sent and sent['payload']['origin'] == 'atendimento' and sent['payload']['payment'] == {'method': 'cash', 'outside': True}, sent + # A Dropflow batch stays out of Tiny until its revenue category exists, cancelled or not. + _, batch_quote, _ = reviewed_quote() + batch = register(batch_quote, {'origin': 'dropflow', 'method': 'credit'}) + board.call('/operator/orders/' + batch['id'] + '/cancel', {'note': 'Lote refeito'}, operator=True) + with db.connect() as c: + held = c.execute("SELECT count(*) AS n FROM dtf_local.outbox WHERE event_key LIKE %s", (batch['id'] + ':%',)).fetchone()['n'] + assert batch['origin'] == 'dropflow' and held == 0, (batch, held) + print('PASS: an order paid outside is registered with its origin and payment; Dropflow stays out of Tiny') + # Files are uploaded before payment. An unpaid cart keeps them briefly; a # paid order keeps them for its 30 days; a payment never starts for files # that are gone. diff --git a/tests/test_tiny.py b/tests/test_tiny.py index 397f892..5e26398 100644 --- a/tests/test_tiny.py +++ b/tests/test_tiny.py @@ -370,6 +370,16 @@ class TinyStatusTests(FakeTinyCase): self.assertNotIn('transportador', plain) self.assertEqual(plain['pagamento'], {'categoria': {'id': CATEGORY}}) self.assertNotIn('vendedor', plain) + self.assertTrue(plain['observacoesInternas'].startswith('Site DTF · pago · ')) + # An order the team registered (D-35): its origin, and how it was paid + # outside the site; Pix and card still name Tiny's forma de recebimento. + counter = order_payload({**PAID, 'origin': 'atendimento', 'payment': {'method': 'cash', 'outside': True}}, + 1, thursday, shipping=self.tiny.shipping) + self.assertTrue(counter['observacoesInternas'].startswith('Atendimento DTF · pago fora do site (dinheiro) · ')) + self.assertEqual(counter['pagamento'], {'categoria': {'id': CATEGORY}}) + pix = order_payload({**PAID, 'origin': 'atendimento', 'payment': {'method': 'pix', 'outside': True}}, + 1, thursday, shipping=self.tiny.shipping) + self.assertEqual(pix['pagamento']['formaRecebimento'], {'id': RECEIPT_METHODS['pix']}) def test_the_order_is_tagged_kanbandtf_once(self): first = self.tiny.deliver('k1', PAID) diff --git a/tests/users_test.py b/tests/users_test.py index 788d785..72db0a1 100644 --- a/tests/users_test.py +++ b/tests/users_test.py @@ -152,7 +152,10 @@ def run(): seller.call(f'/operator/quotes/{uv_q}/discard', {}, expected=403) seller.call(f'/operator/orders/{textil_o}/machine', {'machine_id': None}, expected=403) seller.call(f'/operator/orders/{textil_o}/contact', {'waiting': True, 'note': 'Ligar'}, expected=403) - assert seller.call('/operator/me')['can'] == ['view'] + # The seller registers orders paid outside (D-35); this quote already has + # its order, so the answer is 409, past the permission. + assert seller.call('/operator/me')['can'] == ['enter', 'view'] + seller.call(f'/operator/quotes/{uv_q}/register', {'origin': 'atendimento', 'method': 'pix'}, expected=409) # Only the Revisor releases to Finalizado: not even the administrator. admin.call(f'/operator/orders/{uv_o}/move', {'state': 'fin', 'version': printed['version'], 'reason': ''}, expected=403) @@ -171,6 +174,7 @@ def run(): assert next(u for u in admin.call('/operator/users')['users'] if u['email'] == emails['designer'])['machines'] == [] designer = signed_in(emails['designer']) assert set(designer.call('/operator/me')['can']) == {'view', 'produce'} + designer.call(f'/operator/quotes/{uv_q}/register', {'origin': 'atendimento', 'method': 'pix'}, expected=403) assert {str(uv_o), str(textil_o)} <= {o['id'] for o in designer.call('/operator/board')['orders']} version = next(o for o in designer.call('/operator/board')['orders'] if o['id'] == str(textil_o))['version'] # A correction and back; Arte conferida only with the final approved. @@ -223,7 +227,7 @@ def run(): c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved,approved_at) VALUES(%s,%s,%s,'users-fixture',%s,%s,now())''', (asked, owner, uuid4(), Jsonb(content), Jsonb(content))) quote = c.execute('SELECT * FROM dtf_local.quotes WHERE id=%s', (asked,)).fetchone() - order, created = payments.create_order(c, quote, {'provider': 'teste', 'id': f'proof-{tag}'}) + order, created = payments.create_order(c, quote, {'provider': 'teste', 'id': f'proof-{tag}'}, 'site') made.append((asked, order['id'])) assert created and order['contact_since'] and order['contact_note'] == proof.CUSTOMER_NOTE, order diff --git a/web/kanban.css b/web/kanban.css index ccc98ff..9fde6f9 100644 --- a/web/kanban.css +++ b/web/kanban.css @@ -221,6 +221,13 @@ main{padding:0 24px 24px} .pane .foot .total{margin-left:auto;font-family:var(--mono);color:var(--muted)} .pane .foot .total b{color:var(--tx)} .pane .note{padding:24px;color:var(--muted)} +.pane .register{flex-direction:column;align-items:stretch;gap:10px;border-top:1px solid var(--line)} +.register .opts{display:grid;grid-template-columns:110px 1fr;align-items:center;gap:8px} +.register .optset{display:flex;flex-wrap:wrap;gap:8px 16px} +.register .optlabel{font-size:13.5px;font-weight:600;color:var(--muted)} +.register .opt{display:inline-flex;align-items:center;gap:6px;font-size:14px;color:var(--tx2);cursor:pointer} +.register .optrow{display:flex;gap:12px;align-items:center;flex-wrap:wrap} +.register .optrow input{flex:1;min-width:200px;height:38px;padding:0 10px;border-radius:8px;border:1px solid var(--line3);background:var(--bg);color:var(--tx)} /* Payments and integrations */ .page{display:flex;flex-direction:column;gap:22px;padding-top:18px} diff --git a/web/kanban.html b/web/kanban.html index 297dc03..6f7043d 100644 --- a/web/kanban.html +++ b/web/kanban.html @@ -110,7 +110,7 @@

Quem entra no Kanban e o que cada perfil pode fazer. Administrador: tudo, inclusive esta página. Gestão: tudo, menos usuários; no quadro só puxa para trás, com motivo (Correção ou voltar uma etapa). Designer: vê todos os pedidos, aprova e recusa o arquivo final, pede correção. Operador: ligado a uma máquina, vê só os pedidos dela; imprime e passa para a Revisão. Revisor: confere a folha impressa e libera; é o único que manda para Finalizado. - Vendedor: só consulta.

+ Vendedor: consulta e registra pedidos pagos fora do site, em Cotações.

NomePerfilMáquinasÚltimo acesso

Máquinas

Cada pedido vai para a máquina do produto com menos metros em aberto, dentro do limite. No pedido dá para trocar.

diff --git a/web/kanban.js b/web/kanban.js index f63bbaf..69e664c 100644 --- a/web/kanban.js +++ b/web/kanban.js @@ -855,7 +855,8 @@ function renderPanel(order){ row.append(node('span','#'+order.number,'num'),stage,originTag(order),...(test?[test]:[]),code,close); // What was paid and when, and whether it is stuck: the first things asked of an order. const paid=node('div',undefined,'paidline'); - paid.append(node('b',money(order.snapshot.total_cents)),isTest(order)?' sem pagamento · '+when(order.created_at):' pago em '+when(order.created_at)); + paid.append(node('b',money(order.snapshot.total_cents)),isTest(order)?' sem pagamento · '+when(order.created_at): + paidOutside(order)?' pago fora do site ('+PAID_OUTSIDE[order.payment.method]+') · registrado em '+when(order.created_at):' pago em '+when(order.created_at)); if(order.cancelled_at)paid.append(badge('Cancelado','bad')); else if(stalled(order))paid.append(badge('⏱ Parado há '+hoursSince(order.updated_at)+' h','bad')); const steps=node('ol',undefined,'steps');steps.setAttribute('aria-label','Etapas'); @@ -1211,7 +1212,9 @@ function historySection(order,rows,section){ li.append(text,node('small',when(at)));return li; }; for(const r of [...rows].reverse())list.append(entry(STAGE_COLORS[r.to_state],r.back?'Voltou para '+stateName(r.to_state):stateName(r.to_state),r.operator,r.created_at,r.reason)); - list.append(entry('var(--rec)','Pedido recebido',board.environment==='local'&&order.payment?.provider==='fake'?'pagamento de teste':isTest(order)?'teste, sem pagamento':'Site',order.created_at,'')); + list.append(entry('var(--rec)','Pedido recebido',board.environment==='local'&&order.payment?.provider==='fake'?'pagamento de teste':isTest(order)?'teste, sem pagamento': + paidOutside(order)?ORIGINS[order.origin]+' · pago fora do site ('+PAID_OUTSIDE[order.payment.method]+') · registrado por '+order.payment.operator:ORIGINS[order.origin]||'Site', + order.created_at,paidOutside(order)?order.payment.note:'')); section.replaceChildren(node('p','Histórico','eyebrow'),list); } @@ -1597,6 +1600,7 @@ function review(quote){ content.append(sums); } card.append(head,content); + if(quote.status==='approved'&&may('enter'))card.append(registerForm(quote)); if(quote.status==='approved'&&may('manage')){ foot.append(discardButton(quote)); // Tries the whole production flow without a payment. @@ -1631,6 +1635,32 @@ function review(quote){ catch(error){say(error.message,true);submit.disabled=false;}}; card.append(head,form);return card; } +// An order paid outside the site (Dropstar's rule D-35): the team builds the +// cart on the Site, as a customer would, and registers it here. Origin and +// payment start unchosen: a default would become the answer to everything. +const PAID_OUTSIDE={pix:'Pix',card:'Cartão',cash:'Dinheiro',credit:'Crédito do cliente'}; +function registerForm(quote){ + const form=node('form',undefined,'foot register'); + const group=(name,label,options)=>{ + const g=node('div',undefined,'opts');g.setAttribute('role','radiogroup');g.setAttribute('aria-label',label); + const set=node('div',undefined,'optset'); + for(const [value,text] of Object.entries(options)){ + const l=node('label',undefined,'opt'),r=node('input'); + r.type='radio';r.name=name+'-'+quote.id;r.value=value;r.required=true;l.append(r,text);set.append(l);} + g.append(node('span',label,'optlabel'),set);return g;}; + const note=node('input');note.type='text';note.maxLength=300;note.placeholder='Observação (opcional)';note.setAttribute('aria-label','Observação'); + const submit=node('button','Registrar pedido','btn primary'); + const row=node('div',undefined,'optrow');row.append(note,submit); + form.append(node('b','Pago fora do site? Registre o pedido'),group('origin','Origem',ORIGINS),group('method','Como foi pago',PAID_OUTSIDE),row); + form.onsubmit=async e=>{e.preventDefault(); + const pick=name=>form.querySelector('input[name="'+name+'-'+quote.id+'"]:checked')?.value; + submit.disabled=true; + try{const order=await api('/quotes/'+quote.id+'/register',{origin:pick('origin'),method:pick('method'),note:note.value}); + currentQuote=null;say('Pedido #'+order.number+' registrado em Arte recebida.');await load();} + catch(error){say(error.message,true);submit.disabled=false;}}; + return form; +} +const paidOutside=order=>order.payment?.provider==='manual'; // An unpaid quote leaves the list and can no longer be paid. function discardButton(quote){ return button('Descartar cotação',async()=>{ @@ -2050,7 +2080,10 @@ let autoTimer=null, lastAuto=0; function busy(){ const a=document.activeElement; const typing=!!(a&&a.matches&&a.matches('input,textarea,select')&&a.id!=='refresh-every'); - return $('app').hidden||!!dragging||!$('drawer').hidden||typing; + // An order being registered, half filled in and on screen, keeps its choices. + const registering=!$('tab-quotes').hidden&&[...document.querySelectorAll('.register')].some(f=> + f.querySelector('input:checked')||f.querySelector('input[type=text]').value); + return $('app').hidden||!!dragging||!$('drawer').hidden||typing||registering; } function autoRefresh(){ if(busy())return;