diff --git a/CHANGELOG.md b/CHANGELOG.md index 275f7d1..85c4084 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -42,6 +42,17 @@ un'immagine `gitea.encke-hake.ts.net/balbosoft/khaemhat:X.Y.Z`. - Compilazione automatica: comune, provincia e regione dal CAP e CAP dal comune, codice fiscale, verifica VIES, ABI, CAB, banca e BIC dall'IBAN, data di consegna sul calendario lavorativo; ogni opzione si spegne nelle preferenze, e il job dei cambi BCE salta le aziende che l'hanno spento. Pagina *Preferenze azienda* (`/tabelle/preferenze`). +- Anagrafiche (ADR 0029): clienti, fornitori, prospect e lead in un solo archivio, con tre radar + (`/anagrafiche/clienti`, `/fornitori`, `/contatti`) con ricerca, filtri rapidi, disattivazione e riattivazione di + più righe, e la scheda a otto schede: dati principali, indirizzi, contatti, condizioni di vendita e di acquisto, + fiscale e SDI (fatturazione elettronica, regime IVA, ritenute e casse, dichiarazione d'intento), banche, note e + allegati, storico. Controlli del pacchetto fiscale su partita IVA, codice fiscale, codice destinatario e paese, con + avvisi che non bloccano (P.IVA doppia, privato senza codice fiscale); codice destinatario proposto per privati ed + esteri; verifica VIES al salvataggio e su richiesta; calcolo del codice fiscale; CAP e comune compilati a vicenda. + *Converti in cliente* per prospect e lead (nuovo codice, il vecchio resta come codice precedente) e per i fornitori + (diventano anche clienti con lo stesso codice). Un'anagrafica usata da altri dati si disattiva invece di cancellarsi. +- Dati di esempio delle anagrafiche con `KHAEMHAT_SEED_DEMO=true`: 3 agenti, 12 clienti di ogni tipo soggetto, + 5 fornitori, 2 prospect e 2 lead, con numeri inventati ma formalmente validi. ## [0.3.0] - 2026-11-11 diff --git a/docs/DATA-MODEL.md b/docs/DATA-MODEL.md index f0848b9..9e8550a 100644 --- a/docs/DATA-MODEL.md +++ b/docs/DATA-MODEL.md @@ -177,13 +177,13 @@ public sealed class M20261013_001_CreateParties : IMigration | Tabella | Colonne principali | Relazioni / note | |---|---|---| -| `parties` | `code` (automatico), `kind` (cliente/fornitore/prospect/lead), ragione sociale o nome/cognome, P.IVA, codice fiscale, `party_type` (*azienda/privato/PA/UE/extra-UE/forfettario*), sede, contatti, lingua, `country_id` →, `category_id` →, `salesperson_id` →, note, `disabled`, `is_demo`, conti cliente/fornitore → | disabilitazione al posto della cancellazione se esistono documenti | -| `party_addresses` | `party_id` →, tipo (destinazione), indirizzo | | -| `party_contacts` | `party_id` →, nome, ruolo, telefono, e-mail | | -| `party_bank_accounts` | `party_id` →, IBAN, BIC, banca | | -| `party_sales_terms` | `party_id` →, listino →, sconti, pagamento →, banca RiBa, agente →, vettore →, porto, deposito →, fido, blocco, raggruppa DDT, giorno fatturazione, invio documenti e-mail/PEC | | -| `party_purchase_terms` | `party_id` →, pagamento →, lead time, minimo, sconti | | -| `party_fiscal` | `party_id` →, codice destinatario, PEC, split payment, reverse charge, ritenuta e aliquota, causale, cassa previdenza, ENASARCO, EORI, GLN, forfettario, esito VIES | | +| `parties` | `code` (automatico per tipo, ADR 0027), `previous_code` (codice da lead o prospect), `kind` (cliente/fornitore/prospect/lead), `is_also_supplier`, `subject_type` (*impresa/privato/PA/UE/extra-UE/forfettario*), ragione sociale o cognome e nome, P.IVA, codice fiscale, REA, sede, `country_code`, recapiti, lingua, valuta, `category_id` →, `salesperson_id` →, consensi, note, esito e data VIES, conti cliente/fornitore, `disabled`, `is_demo` | disattivazione al posto della cancellazione se altri dati la usano (ADR 0029) | +| `party_addresses` | `party_id` → (cascata), tipo (destinazione, fatturazione, cantiere, altro), denominazione, indirizzo, predefinito | | +| `party_contacts` | `party_id` → (cascata), nome, ruolo, telefono, cellulare, e-mail, principale | | +| `party_bank_accounts` | `party_id` → (cascata), IBAN, BIC, banca, ABI, CAB, predefinito | | +| `party_sales_terms` | `party_id` → (unico), listino →, sconti, pagamento →, nostra banca →, vettore →, porto →, deposito →, fido, blocco, raggruppa DDT, giorno fatturazione, invio documenti e-mail/PEC | i dati di vendita del cliente | +| `party_purchase_terms` | `party_id` → (unico), pagamento →, lead time, minimo d'ordine, sconto, porto →, registro IVA, conto di costo, e-mail ordini | i dati di acquisto del fornitore | +| `party_fiscal` | `party_id` → (unico), codice destinatario, PEC, riferimento amministrazione, split payment, reverse charge, codice IVA →, esigibilità, bollo, ritenuta e aliquota, causale, cassa previdenza, ENASARCO, dichiarazione d'intento (numero, data, protocollo, codice IVA →, plafond, utilizzato, validità), EORI, GLN | | | `intent_declarations` † | `party_id` →, direzione (ricevuta/emessa), protocollo, anno, plafond, utilizzato, residuo, validità | mockup 061 | | `party_item_codes` | `party_id` →, `item_id` →, codice e descrizione del cliente/fornitore | | @@ -727,6 +727,7 @@ Migrazioni applicate in ordine: - `core` 20261111013 `create_logistics_tables` (M20261111_013_CreateLogisticsTables) - `core` 20261111014 `create_catalog_tables` (M20261111_014_CreateCatalogTables) - `core` 20261111015 `create_code_sequences` (M20261111_015_CreateCodeSequences) +- `core` 20261112001 `create_parties` (M20261112_001_CreateParties) #### `attachments` @@ -1229,6 +1230,103 @@ Migrazioni applicate in ordine: - indice `ix_notifications_recipient_user_id` su `recipient_user_id` +#### `parties` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `code` | String(30) | no | | | +| `previous_code` | String(30) | sì | | | +| `kind` | String(40) | no | | | +| `is_also_supplier` | Bool | no | `false` | | +| `subject_type` | String(40) | no | | | +| `name` | String(200) | no | | | +| `first_name` | String(80) | sì | | | +| `last_name` | String(80) | sì | | | +| `fiscal_name` | String(200) | sì | | | +| `vat_number` | String(30) | sì | | | +| `tax_code` | String(30) | sì | | | +| `rea` | String(20) | sì | | | +| `category_id` | Int64 | sì | | -> `party_categories` (Restrict) | +| `address` | String(200) | sì | | | +| `street_number` | String(20) | sì | | | +| `postal_code` | String(10) | sì | | | +| `city` | String(100) | sì | | | +| `province` | String(10) | sì | | | +| `country_code` | String(2) | no | | | +| `phone` | String(40) | sì | | | +| `email` | String(200) | sì | | | +| `pec` | String(200) | sì | | | +| `website` | String(200) | sì | | | +| `salesperson_id` | Int64 | sì | | -> `salespeople` (Restrict) | +| `language` | String(5) | no | | | +| `currency_code` | String(3) | no | | | +| `since` | Date | sì | | | +| `privacy_accepted` | Bool | no | `false` | | +| `marketing` | Bool | no | `false` | | +| `notes` | Text | sì | | | +| `vat_check` | String(40) | no | | | +| `vat_checked_at` | DateTimeUtc | sì | | | +| `customer_account_code` | String(20) | sì | | | +| `supplier_account_code` | String(20) | sì | | | +| `disabled` | Bool | no | `false` | | +| `is_demo` | Bool | no | `false` | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice `ix_parties_kind` su `kind` +- indice `ix_parties_name` su `name` +- indice `ix_parties_tax_code` su `tax_code` +- indice `ix_parties_vat_number` su `vat_number` +- indice unico `ux_parties_code` su `code` + +#### `party_addresses` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `party_id` | Int64 | no | | -> `parties` (Cascade) | +| `kind` | String(40) | no | | | +| `name` | String(200) | no | | | +| `address` | String(200) | sì | | | +| `street_number` | String(20) | sì | | | +| `postal_code` | String(10) | sì | | | +| `city` | String(100) | sì | | | +| `province` | String(10) | sì | | | +| `country_code` | String(2) | no | | | +| `is_default` | Bool | no | `false` | | +| `notes` | Text | sì | | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice `ix_party_addresses_party` su `party_id` + +#### `party_bank_accounts` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `party_id` | Int64 | no | | -> `parties` (Cascade) | +| `iban` | String(34) | no | | | +| `bic` | String(11) | sì | | | +| `bank_name` | String(100) | sì | | | +| `bank_code` | String(10) | sì | | | +| `branch_code` | String(10) | sì | | | +| `is_default` | Bool | no | `false` | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice `ix_party_bank_accounts_party` su `party_id` + #### `party_categories` | Colonna | Tipo | Null | Default | Note | @@ -1246,6 +1344,119 @@ Migrazioni applicate in ordine: - indice unico `ux_party_categories_code` su `code` +#### `party_contacts` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `party_id` | Int64 | no | | -> `parties` (Cascade) | +| `name` | String(120) | no | | | +| `role` | String(80) | sì | | | +| `phone` | String(40) | sì | | | +| `mobile` | String(40) | sì | | | +| `email` | String(200) | sì | | | +| `is_default` | Bool | no | `false` | | +| `notes` | Text | sì | | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice `ix_party_contacts_party` su `party_id` + +#### `party_fiscal` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `party_id` | Int64 | no | | -> `parties` (Cascade) | +| `recipient_code` | String(7) | sì | | | +| `recipient_pec` | String(200) | sì | | | +| `administration_reference` | String(20) | sì | | | +| `attach_pdf` | Bool | no | `true` | | +| `send_copy` | Bool | no | `false` | | +| `split_payment` | Bool | no | `false` | | +| `reverse_charge` | Bool | no | `false` | | +| `tax_code_id` | Int64 | sì | | -> `tax_codes` (Restrict) | +| `exigibility` | String(1) | sì | | | +| `stamp_duty_charged` | Bool | no | `true` | | +| `withholding` | Bool | no | `false` | | +| `withholding_rate` | Decimal(19,6) | sì | | | +| `withholding_reason` | String(4) | sì | | | +| `pension_fund` | String(4) | sì | | | +| `pension_fund_rate` | Decimal(19,6) | sì | | | +| `enasarco` | Bool | no | `false` | | +| `intent_active` | Bool | no | `false` | | +| `intent_number` | String(40) | sì | | | +| `intent_date` | Date | sì | | | +| `intent_protocol` | String(40) | sì | | | +| `intent_tax_code_id` | Int64 | sì | | -> `tax_codes` (Restrict) | +| `intent_ceiling` | Decimal(19,6) | sì | | | +| `intent_used` | Decimal(19,6) | no | `0` | | +| `intent_from` | Date | sì | | | +| `intent_to` | Date | sì | | | +| `gln` | String(13) | sì | | | +| `eori` | String(17) | sì | | | +| `our_code` | String(40) | sì | | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice unico `ux_party_fiscal_party` su `party_id` + +#### `party_purchase_terms` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `party_id` | Int64 | no | | -> `parties` (Cascade) | +| `payment_term_id` | Int64 | sì | | -> `payment_terms` (Restrict) | +| `lead_time_days` | Int32 | sì | | | +| `minimum_order` | Decimal(19,6) | sì | | | +| `discount` | Decimal(19,6) | sì | | | +| `shipping_term_id` | Int64 | sì | | -> `shipping_terms` (Restrict) | +| `vat_register_code` | String(10) | sì | | | +| `cost_account_code` | String(20) | sì | | | +| `orders_email` | String(200) | sì | | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice unico `ux_party_purchase_terms_party` su `party_id` + +#### `party_sales_terms` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `party_id` | Int64 | no | | -> `parties` (Cascade) | +| `price_list_id` | Int64 | sì | | -> `price_lists` (Restrict) | +| `discount1` | Decimal(19,6) | sì | | | +| `discount2` | Decimal(19,6) | sì | | | +| `payment_term_id` | Int64 | sì | | -> `payment_terms` (Restrict) | +| `company_bank_account_id` | Int64 | sì | | -> `bank_accounts` (Restrict) | +| `carrier_id` | Int64 | sì | | -> `carriers` (Restrict) | +| `shipping_term_id` | Int64 | sì | | -> `shipping_terms` (Restrict) | +| `warehouse_id` | Int64 | sì | | -> `warehouses` (Restrict) | +| `credit_limit` | Decimal(19,6) | sì | | | +| `blocked` | Bool | no | `false` | | +| `group_delivery_notes` | Bool | no | `true` | | +| `invoice_day` | Int32 | sì | | | +| `send_documents` | String(40) | no | | | +| `documents_email` | String(200) | sì | | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice unico `ux_party_sales_terms_party` su `party_id` + #### `payment_methods` | Colonna | Tipo | Null | Default | Note | diff --git a/docs/STATUS.md b/docs/STATUS.md index de90d48..ed3999c 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -6,8 +6,9 @@ **Milestone corrente:** M4 — Tabelle, anagrafiche, articoli (issue #37-#46), ramo `feat/37-tabelle-anagrafiche`. Fatti: pacchetto fiscale (#37), validatori e VIES (#40), tabelle azienda, profilo, esercizi e cambi con le maschere (#38, #39), dati di base e `scripts/seed.sh --base` (#45) con province e comuni ISTAT e CAP GeoNames (ADR 0028; -mancano le banche ABI/CAB, senza fonte con licenza compatibile), codici automatici e compilazione automatica (#43). ADR 0025-0028. -**Prossimo passo:** anagrafiche (#41) e articoli e listini (#42) con i dati di esempio, import/export guidato (#44), +mancano le banche ABI/CAB, senza fonte con licenza compatibile), codici automatici e compilazione automatica (#43), anagrafiche con radar, scheda, controlli, VIES e +21 anagrafiche di esempio (#41, ADR 0029). ADR 0025-0029. +**Prossimo passo:** articoli e listini (#42) con `party_item_codes` e `seed --demo`, import/export guidato (#44), chiusura M4 (#46). #35 (PNG ad alta risoluzione) resta aperta e non blocca. Da recuperare: misure di riferimento su PostgreSQL in `docs/DATA-MODEL.md` §6.1; indicatore di robustezza della @@ -17,7 +18,7 @@ filtro predefinito nei radar. ## Fatto - Specifica normativa in `docs/SPEC.md`; `CLAUDE.md` con emendamenti E1-E6. -- ADR 0001-0028. +- ADR 0001-0029. - Mockup in `docs/mockups/` (22 in alta risoluzione + galleria, 88 miniature, `mockup.css`, indice). - Icone in `assets/`; deploy in `deploy/` (compose Unraid, `.env.example`, template Unraid). - Documentazione tecnica: `ARCHITECTURE.md`, `DATA-MODEL.md` (provvisorio, sarà generato), `MODULES.md`, `API.md`, diff --git a/docs/adr/0029-anagrafiche.md b/docs/adr/0029-anagrafiche.md new file mode 100644 index 0000000..a0f2e07 --- /dev/null +++ b/docs/adr/0029-anagrafiche.md @@ -0,0 +1,65 @@ +# ADR 0029 - Anagrafiche: un archivio per clienti, fornitori, prospect e lead + +- **Stato:** accettata +- **Data:** 2026-11-12 +- **Modifica:** SPEC §9 (modello dati delle anagrafiche), §11.2, §11.12, §14; milestone M4, issue #41 + +## Contesto + +SPEC §11.2 descrive clienti, fornitori, prospect e lead con radar (mockup 012-013), scheda a gruppi (014-016), +condizioni commerciali, dati fiscali e SDI, banche, contatti e indirizzi. §9 elenca le tabelle `parties` e i +dettagli, ma lascia aperti alcuni punti: come si rappresenta un soggetto che è sia cliente sia fornitore, che codice +riceve un prospect, quando si verifica il VIES, come si cancella un'anagrafica usata, come sono fatti i dati di +esempio prima che esistano gli articoli e i documenti. + +## Decisione + +1. **Un archivio, quattro tipi.** `parties` ha un `kind` (*Customer*, *Supplier*, *Prospect*, *Lead*) e un + `subject_type` (*Company*, *Person*, *PublicAdministration*, *EuCompany*, *NonEuCompany*, *FlatRate*) che decide i + controlli e i valori proposti. Un soggetto che è sia cliente sia fornitore è un **cliente** con + `is_also_supplier`: compare in entrambi i radar con lo stesso codice cliente. Un fornitore che diventa cliente + (azione *Converti in cliente*) diventa quindi `Customer` con `is_also_supplier = true` e tiene il suo codice. +2. **Tre radar.** `/anagrafiche/clienti` (tipo *Customer*), `/anagrafiche/fornitori` (*Supplier* più i clienti che + sono anche fornitori), `/anagrafiche/contatti` (*Prospect* e *Lead*, con il filtro rapido del tipo). +3. **Codici.** Clienti e fornitori usano le maschere `customers` e `suppliers`; prospect e lead la maschera `leads` + (`L{anno}-{seq:0000}`, ADR 0027). Alla conversione in cliente un prospect o un lead riceve il codice cliente e il + vecchio resta in `previous_code`, così i riferimenti esterni (e-mail, appunti) si ritrovano con la ricerca. +4. **Dettagli in tabelle proprie.** Indirizzi, contatti e conti sono liste (`party_addresses`, `party_contacts`, + `party_bank_accounts`, al più un predefinito per tipo); condizioni di vendita, di acquisto e dati fiscali sono + tabelle 1:1 (`party_sales_terms`, `party_purchase_terms`, `party_fiscal`) create insieme all'anagrafica. Il + salvataggio riscrive la scheda intera in una transazione; lo storico registra testata e dettagli. La cancellazione + dei dettagli è a cascata. +5. **Controlli dal pacchetto fiscale.** Partita IVA, codice fiscale, codice destinatario e PEC passano da + `ITaxIdentifierRules` (ADR 0025). Errori bloccanti: ragione sociale, P.IVA per un'impresa, identificativo per una + PA, codice fiscale non valido, codice duplicato, paese incoerente con il tipo soggetto, dichiarazione d'intento + senza numero o plafond. **Avvisi**, che non bloccano: P.IVA già usata da un'altra anagrafica (filiali, sedi + distinte), privato senza codice fiscale. Per un cliente privato o estero, o per un'impresa con sola PEC, il codice + destinatario mancante si compila con il valore del formato (`0000000`, `XXXXXXX`). +6. **VIES al salvataggio.** Per un'impresa UE la verifica parte dopo il commit, solo se la P.IVA o il paese sono + cambiati o non è mai stata verificata, e solo se la compilazione automatica *Vies* è accesa. L'esito (*valida*, + *non valida*, *non verificata*) e la data restano sull'anagrafica; un VIES irraggiungibile non impedisce di + salvare. L'azione *Verifica VIES* della scheda ripete la verifica. Le date sono `DateTime` in UTC, come nel + resto del modello. +7. **Cancellare o disattivare.** *Elimina* prova a cancellare; se il database rifiuta per riferimenti (documenti dalle + prossime milestone), l'anagrafica viene **disattivata** e l'utente lo legge in un messaggio. Il radar disattiva e + riattiva più righe insieme; le disattivate sono escluse per filtro iniziale. +8. **Dati di esempio senza documenti.** `DemoPartiesSeeder` (seeder *Demo*, solo se le anagrafiche sono vuote) crea + 3 agenti e 21 anagrafiche con `is_demo`: 12 clienti che coprono tutti i tipi soggetto (PA con split payment, + cliente bloccato, disattivato, anche fornitore, con dichiarazione d'intento), 5 fornitori (ritenuta, ENASARCO, UE), + 2 prospect e 2 lead. Partite IVA, codici fiscali e IBAN sono **numeri inventati ma formalmente validi** (cifra di + controllo, mod 97), scritti come costanti e controllati da un test; nessuno appartiene a un soggetto reale per + scelta, ma la coincidenza non si può escludere e per questo non si verificano sul VIES. Il volume completo della + SPEC (40 clienti, 15 fornitori, documenti) arriva in M9 con `seed --demo`. +9. **Rinviati.** `party_item_codes` (codici articolo del cliente o del fornitore) arriva con gli articoli (#42); + fatturato, scaduto, fido usato e *Scheda 360°* con vendite (M5) e scadenzario (M9); il flag utente *vede solo i + propri clienti* con i filtri per riga sui permessi, non ancora previsti in una milestone. Gli agenti di esempio non hanno `is_demo` perché la tabella + degli agenti (ADR 0026) non ha la colonna: si rimuovono a mano. + +## Conseguenze + +- Una sola tabella e una sola query per i tre radar; le condizioni commerciali si leggono con un join 1:1. +- Il passaggio fornitore → cliente non cambia codice né documenti; il passaggio prospect → cliente cambia codice e + lascia traccia in `previous_code` e nello storico. +- I controlli fiscali italiani restano nel pacchetto; un altro paese porterà le sue regole senza toccare il servizio. +- I dati di esempio non hanno numeri reali e restano validi per i controlli, quindi le prove automatiche li usano come + casi realistici (ogni anagrafica di esempio supera `ValidateAsync`). diff --git a/docs/wiki/Anagrafiche.md b/docs/wiki/Anagrafiche.md index 072dd5f..1e740c2 100644 --- a/docs/wiki/Anagrafiche.md +++ b/docs/wiki/Anagrafiche.md @@ -1,7 +1,7 @@ # Anagrafiche -> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M4) -> **Modulo di licenza:** CORE · **Permessi principali:** famiglia `parties.*` (`read`, `write`, `delete`, `export`; codici esatti definiti in sviluppo) · **Specifica:** SPEC §11.2, §11.12, §22 +> **Stato:** bozza · **Ultima revisione:** 2026-11-12 · **Versione software:** non ancora rilasciata (milestone M4) +> **Modulo di licenza:** CORE · **Permessi principali:** `parties.party.read` (consultare), `parties.party.write` (inserire, modificare, disattivare, convertire), `parties.party.delete` (eliminare) · **Specifica:** SPEC §11.2, §11.12, §22 · **Decisioni:** ADR 0029 Le **anagrafiche** sono l'archivio unico delle controparti dell'azienda: **clienti**, **fornitori**, **prospect** e **lead**. Un soggetto è registrato una volta sola; il suo *tipo* (cliente, fornitore…) dice come viene usato. Dalla @@ -10,8 +10,9 @@ codici che il cliente o il fornitore usa per i tuoi articoli. ## Dove si trova -Menu **Anagrafiche** → **Clienti**, **Fornitori**, **Contatti** (prospect e lead), **Categorie**. Nello stesso menu ci -sono anche *Articoli* e *Listini* (vedi [Articoli e listini](Articoli-e-listini)). +Menu **Anagrafiche** → **Clienti** (`/anagrafiche/clienti`), **Fornitori** (`/anagrafiche/fornitori`), **Contatti** +(`/anagrafiche/contatti`, prospect e lead). Le categorie sono una tabella azienda (vedi [Tabelle azienda](Tabelle-azienda)). +Nello stesso menu arriveranno *Articoli* e *Listini* (vedi [Articoli e listini](Articoli-e-listini)). ## Tipi di anagrafica @@ -19,13 +20,15 @@ sono anche *Articoli* e *Listini* (vedi [Articoli e listini](Articoli-e-listini) |---|---|---| | **Cliente** | intestatario di preventivi, ordini, DDT e fatture di vendita | `C{seq:000000}` → `C000124` | | **Fornitore** | intestatario di ordini fornitore, DDT di carico, fatture di acquisto | `F{seq:000000}` → `F000032` | -| **Prospect** | potenziale cliente già qualificato, senza documenti fiscali | assegnato alla conversione in cliente | +| **Prospect** | potenziale cliente già qualificato, senza documenti fiscali | come i lead; alla conversione riceve il codice cliente | | **Lead** | contatto commerciale da qualificare (gestito con il CRM) | `L{anno}-{seq:0000}` → `L2026-0001` | -Lo stesso soggetto può essere sia cliente sia fornitore. +Lo stesso soggetto può essere sia cliente sia fornitore: è un **cliente** con la casella *È anche fornitore* e compare +in entrambi gli elenchi con lo stesso codice. -Il **tipo soggetto** (*azienda*, *privato*, *pubblica amministrazione*, *UE*, *extra-UE*, *forfettario*) determina -i controlli e i valori proposti: codice destinatario SDI, split payment, bollo, partita IVA estera. +Il **tipo soggetto** (*impresa italiana*, *privato*, *pubblica amministrazione*, *impresa UE*, *impresa extra-UE*, +*forfettario*) determina i controlli e i valori proposti: codice destinatario SDI, split payment, partita IVA estera, +paese della sede. ## Radar dei clienti @@ -35,15 +38,17 @@ i controlli e i valori proposti: codice destinatario SDI, split payment, bollo, ![012 · Clienti · radar](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/012-clienti-radar.png) *Mockup 012 — lo stesso radar con il menu espanso (anteprima ridotta).* -Il radar elenca le anagrafiche con le colonne **Codice**, **Ragione sociale**, **P.IVA / C.F.**, **Città**, -**Pagamento**, **Listino**, **Agente**, **Fatturato** dell'anno, **Scaduto** (in rosso se presente) e **Stato**. Lo -stato è un badge: *Attivo*, *Disabilitato*, *PA · split*, *UE*, *Extra-UE*, *Privato*, *Fido superato*. +Il radar elenca le anagrafiche con le colonne **Codice**, **Ragione sociale**, **P.IVA / C.F.**, **Città** (con la +provincia), **Pagamento**, **Listino** (solo clienti), **Agente** e **Stato**; nei *Contatti* al posto di pagamento e +listino c'è il **Tipo** (prospect o lead). Lo stato è un badge: *Attivo*, *Disattivato*, *Bloccato*, *PA · split*, +*Privato*, *Impresa UE*, *Impresa extra-UE*, *Anche fornitore* / *Anche cliente*. Le colonne **Fatturato** e +**Scaduto** del mockup arrivano con le vendite (M5) e lo scadenzario (M9). -- Filtri: ricerca libera, **Tipo**, **Agente**, **Stato**, più filtri aggiunti come chip (ad esempio *Scaduto > 0*, - *Provincia: CN, TO, AT*). -- Il piede mostra i totali della selezione (ad esempio *1.284 clienti · 12 selezionati · fatturato visibile*). -- Tasti: `F9` radar, `Invio` apri, `Spazio` seleziona. Con più righe selezionate si possono usare le azioni - multiple (stampa, e-mail, esporta, **Disabilita**). +- Ricerca libera su codice, nome, partita IVA, codice fiscale e città. +- Filtri rapidi: **Tipo** (solo contatti), **Soggetto**, **Agente**, **Stato**; all'apertura sono mostrate solo le + anagrafiche attive. +- Tasti: `F9` radar, `Invio` o doppio clic apre la scheda, `Spazio` seleziona. Con più righe selezionate si usano + **Disattiva** e **Riattiva**; l'esportazione CSV/XLSX è quella di tutti i radar. ## La scheda anagrafica @@ -51,39 +56,43 @@ stato è un badge: *Attivo*, *Disabilitato*, *PA · split*, *UE*, *Extra-UE*, *P *Mockup 014 — scheda cliente: azioni Scheda 360°, Nuovo documento, VIES, Attività CRM; intestazione con identità, condizioni e fatturato; scheda Dati principali a gruppi (anteprima ridotta).* **Toolbar**: comandi standard a icone (vedi [Interfaccia e scorciatoie](Interfaccia-e-scorciatoie)) e le azioni -contestuali **Scheda 360°** (visione completa: documenti, partite, attività CRM), **Nuovo documento**, **VIES** -(verifica della partita IVA comunitaria), **Attività CRM**. +contestuali **Verifica VIES** (partita IVA comunitaria) e, per prospect, lead e fornitori, **Converti in cliente**; +nel menu `…` **Disattiva** o **Riattiva**. *Scheda 360°*, *Nuovo documento* e *Attività CRM* arrivano con vendite e +CRM. -**Intestazione** in tre blocchi: a sinistra tipo (*Cliente*), codice e nome, stato (*Attivo*), uso del fido, data -di inizio rapporto, agente; al centro ragione sociale con P.IVA, indirizzo, contatti e i chip delle condizioni -(pagamento, listino e sconto, codice SDI, dichiarazione d'intento, scaduto); a destra il **fatturato** dell'anno con -anno precedente, aperto e fido. +**Intestazione**: tipo, codice e nome, stato, data di inizio rapporto e agente; i chip delle condizioni (pagamento, +listino, agente, esito VIES, split payment). Il blocco del **fatturato** arriva con le vendite (M5). **Schede**: | Scheda | Contenuto | |---|---| -| **Dati principali** | gruppi *Identità*, *Sede legale*, *Classificazione e note* | -| **Indirizzi** | destinazioni diverse (cantieri, sedi di consegna, indirizzo di fatturazione) | -| **Contatti** | persone di riferimento con ruolo, telefono, e-mail | -| **Condizioni commerciali** | condizioni di vendita (clienti) o di acquisto (fornitori) | -| **Fiscale e SDI** | fatturazione elettronica, regime IVA, ritenute, dichiarazione d'intento, identificativi | -| **Banche** | conti correnti della controparte (IBAN) | -| **Articoli e codici** | codici con cui la controparte identifica i tuoi articoli | +| **Dati principali** | gruppi *Identità*, *Dati di nascita* (privati), *Sede legale*, *Recapiti*, *Classificazione e consensi* | +| **Indirizzi** | destinazioni diverse (destinazione merce, fatturazione, cantiere o sede operativa), una predefinita per tipo | +| **Contatti** | persone di riferimento con ruolo, telefono, cellulare, e-mail; un contatto principale | +| **Condizioni** | condizioni di vendita (clienti), di acquisto (fornitori, e clienti che sono anche fornitori), conti contabili | +| **Fiscale e SDI** | fatturazione elettronica, regime IVA, ritenute e casse, dichiarazione d'intento, identificativi | +| **Banche** | conti correnti della controparte (IBAN), uno predefinito | | **Note e allegati** | note libere e file allegati all'anagrafica | -| **CRM** | lead, opportunità e attività collegate (con modulo CRM) | | **Storico** | modifiche registrate: chi, quando, cosa | +Una scheda con errori mostra il numero degli errori nell'etichetta; le liste mostrano quante righe contengono. La +scheda *Articoli e codici* (codici con cui la controparte identifica i tuoi articoli) arriva con gli articoli, la +scheda *CRM* con il modulo CRM. + ### Dati principali | Gruppo | Campi | |---|---| -| **Identità** | Codice (automatico), Tipo, Tipo soggetto, **Ragione sociale** *, Denominazione fiscale, **Partita IVA** *, Codice fiscale, REA, Categoria | -| **Sede legale** | Indirizzo, N., CAP, Comune, Provincia, Paese, Telefono, E-mail, PEC, Sito | -| **Classificazione e note** | Agente, Lingua, Valuta, Attivo, Privacy accettata, Marketing, Note | +| **Identità** | Codice (automatico), Codice precedente, Tipo, Tipo soggetto, **Ragione sociale** *, Denominazione per i documenti, **Partita IVA** *, Codice fiscale, REA, Categoria | +| **Dati di nascita** | Data, Sesso, Comune di nascita (codice catastale) | +| **Sede legale** | Indirizzo, Civico, CAP, Comune, Provincia, Paese | +| **Recapiti** | Telefono, Cellulare, E-mail, PEC, Sito web | +| **Classificazione e consensi** | Agente, Lingua, Valuta, In anagrafica dal, Informativa privacy accettata, Consenso al marketing | -Per i privati si inseriscono nome e cognome al posto della ragione sociale. Digitando il **CAP** Khaemhat propone -comune, provincia e regione; il **codice fiscale** di una persona fisica può essere calcolato dai dati anagrafici. +Per i privati si inseriscono cognome e nome al posto della ragione sociale. Digitando il **CAP** Khaemhat propone +comune e provincia (se il CAP è di più comuni li elenca e si sceglie); digitando il comune propone il CAP. Il +**codice fiscale** di un privato si calcola con il pulsante accanto al campo da cognome, nome e dati di nascita. ### Fiscale e SDI @@ -93,7 +102,8 @@ comune, provincia e regione; il **codice fiscale** di una persona fisica può es | Gruppo | Campi | |---|---| | **Fatturazione elettronica** | **Codice destinatario** *, PEC destinatario, tipo destinatario, formato (FPR12 privati / FPA12 PA), riferimento amministrazione, *Allega PDF di cortesia*, *Invia copia via e-mail all'emissione* | -| **Regime IVA e ritenute** | *Split payment* (art. 17-ter), *Reverse charge* predefinito, codice IVA predefinito, esigibilità, *Soggetto a ritenuta*, cassa previdenza, bollo (a carico del cliente o dell'azienda), regime | +| **Regime IVA** | *Scissione dei pagamenti* (art. 17-ter), *Inversione contabile*, codice IVA abituale, esigibilità (I, D, S), bollo a carico del cliente | +| **Ritenute e casse** | *Ritenuta d'acconto* con aliquota e causale, cassa previdenziale con aliquota, *ENASARCO* | | **Dichiarazione d'intento** (esportatore abituale) | Attiva, Numero, Data, Protocollo AdE, Codice IVA (non imponibile art. 8 c.1 lett. c, natura N3.5), **Plafond**, **Utilizzato**, **Residuo**, Validità | | **Identificativi** | GLN, EORI, nostro codice presso il cliente | @@ -101,21 +111,22 @@ comune, provincia e regione; il **codice fiscale** di una persona fisica può es | Controparte | Valore | |---|---| -| Azienda italiana (B2B) | 7 caratteri, comunicati dal cliente (in alternativa la PEC) | +| Azienda italiana (B2B) | 7 caratteri, comunicati dal cliente; con la sola PEC si usa `0000000` (proposto) | | Pubblica amministrazione | **codice IPA** dell'ufficio, 6 caratteri | -| Estero (UE ed extra-UE) | `XXXXXXX` | -| Privato | `0000000` | +| Estero (UE ed extra-UE) | `XXXXXXX` (proposto se vuoto) | +| Privato | `0000000` (proposto se vuoto) | **Dichiarazione d'intento**: quando il cliente è esportatore abituale, le fatture usano il codice IVA non imponibile collegato e riportano numero e protocollo della dichiarazione; l'utilizzato si aggiorna con le fatture e il residuo avvisa quando il plafond sta per esaurirsi (il mockup mostra un avviso all'80% e un blocco al 100%; le -soglie definitive saranno fissate in sviluppo). Il registro completo delle dichiarazioni ricevute ed emesse è nel +soglie si fissano con la fatturazione, M5). Una dichiarazione attiva richiede numero e plafond. Il registro completo delle dichiarazioni ricevute ed emesse è nel modulo Fatturazione elettronica (vedi [Fatturazione elettronica](Fatturazione-elettronica)). ### Condizioni di vendita (clienti) -Listino, sconti, pagamento, banca d'appoggio per le RiBa, agente, vettore, porto, deposito, **fido** e **blocco**, -raggruppamento dei DDT in fattura differita, giorno di fatturazione, invio dei documenti per e-mail o PEC. Queste +Listino, due sconti, pagamento, nostra banca d'appoggio per le RiBa, vettore, porto, deposito, **fido** e **ordini +bloccati**, raggruppamento dei DDT in fattura differita, giorno di fatturazione, invio dei documenti per e-mail o PEC +con l'indirizzo dedicato. Queste condizioni vengono proposte automaticamente nei documenti del cliente (vedi [Vendite](Vendite)). Il **fido** è l'esposizione massima ammessa: quando viene superato, o se il cliente ha scaduto, gli ordini @@ -128,13 +139,12 @@ segnalano il blocco, superabile solo da chi ha il permesso di forzarlo. | Gruppo | Campi | |---|---| -| **Condizioni di acquisto** | Pagamento, Valuta, **Lead time** (giorni), **Minimo d'ordine**, Sconto %, Porto, Registro IVA acquisti, Conto di costo predefinito | -| **Ritenute e contributi** | *Professionista (ritenuta d'acconto)*, aliquota ritenuta, causale, cassa previdenza, *Agente ENASARCO*, *Regime forfettario* (niente IVA, bollo), *Reverse charge* (es. subappalto edile) | -| **Banca e contatti** | IBAN, BIC, referente, e-mail per gli ordini | +| **Condizioni di acquisto** | Pagamento, **Tempo di consegna** (giorni), **Ordine minimo**, Sconto %, Porto, Registro IVA, Conto di costo, E-mail per gli ordini | +| **Ritenute e casse** (scheda *Fiscale e SDI*) | *Ritenuta d'acconto* con aliquota e causale, cassa previdenziale, *ENASARCO*; il tipo soggetto *Forfettario* per chi non applica l'IVA | +| **Banche** e **Contatti** | IBAN, BIC, banca, ABI e CAB; referenti | -L'intestazione del fornitore mostra il totale **acquisti** dell'anno, l'aperto, lo scaduto e gli ordini aperti; tra -le schede *Articoli forniti* elenca gli articoli che il fornitore ti vende. Il lead time viene usato per calcolare -le date di consegna previste negli ordini fornitore. +Il tempo di consegna servirà a calcolare le date previste negli ordini fornitore. Il totale **acquisti**, l'aperto, +lo scaduto e gli *Articoli forniti* del mockup arrivano con acquisti e articoli. ## Come si usa @@ -142,41 +152,54 @@ le date di consegna previste negli ordini fornitore. 1. **Anagrafiche → Clienti**, premi **Nuovo cliente** (o `Ctrl+N`). 2. Scegli il **tipo soggetto**. Il codice viene assegnato automaticamente al salvataggio (vedi più sotto). -3. Inserisci ragione sociale e partita IVA: al salvataggio Khaemhat controlla la partita IVA e, se è comunitaria, +3. Inserisci ragione sociale e partita IVA: al salvataggio Khaemhat controlla la partita IVA e, per un'impresa UE, la verifica sul servizio **VIES** (l'esito resta salvato con la data). 4. Compila la sede legale partendo dal CAP. 5. In **Fiscale e SDI** inserisci il codice destinatario o la PEC. -6. In **Condizioni commerciali** imposta pagamento, listino, agente e fido. -7. **Salva** (`Ctrl+S`). +6. In **Condizioni** imposta pagamento, listino e fido; l'agente è nei dati principali. +7. **Salva** (`Ctrl+S`). Gli errori portano alla scheda del primo campo da correggere; gli **avvisi** (ad esempio + una partita IVA già usata da un'altra anagrafica, che va bene per filiali e sedi distinte) non bloccano e compaiono + in un messaggio dopo il salvataggio. + +Un lead si crea da **Contatti → Nuovo lead**, un prospect da **Contatti → Nuovo prospect**. ### Convertire un lead o un prospect in cliente -Dalla scheda del lead o del prospect usa l'azione di conversione: il soggetto diventa **cliente**, riceve il codice -cliente secondo la maschera automatica e mantiene la propria storia (attività, opportunità). Con il modulo CRM la -conversione si avvia anche dalla maschera dei lead (vedi [CRM](CRM)). +Dalla scheda del lead o del prospect usa **Converti in cliente**: il soggetto diventa **cliente**, riceve il codice +cliente secondo la maschera automatica e conserva il vecchio come **codice precedente** (si trova ancora con la +ricerca), insieme a storico e allegati. Con il modulo CRM la conversione si avvierà anche dalla maschera dei lead +(vedi [CRM](CRM)). + +Su un **fornitore** la stessa azione lo rende anche cliente: il codice non cambia e l'anagrafica compare in entrambi +gli elenchi. ### Disabilitare invece di cancellare -Un'anagrafica che compare in almeno un documento **non si cancella**: si **disabilita** (azione **Disabilita** nel -radar o nella scheda). Un'anagrafica disabilitata non viene più proposta nei nuovi documenti né nelle ricerche -predefinite, ma resta consultabile con i suoi documenti. Si può cancellare solo un'anagrafica mai usata. +Un'anagrafica che compare in almeno un documento **non si cancella**: si **disattiva** (azione **Disattiva** nel +radar o nel menu della scheda). Un'anagrafica disattivata non viene più proposta nei nuovi documenti né nelle +ricerche predefinite, ma resta consultabile con i suoi documenti. Se si prova a eliminare un'anagrafica usata, +Khaemhat la disattiva e lo dice. Si cancella davvero solo un'anagrafica mai usata. ## Validazioni | Dato | Controllo | |---|---| -| **Partita IVA italiana** | 11 cifre con cifra di controllo | +| **Ragione sociale** | obbligatoria (per i privati cognome e nome) | +| **Partita IVA italiana** | 11 cifre con cifra di controllo; obbligatoria per un'impresa; un doppione è un avviso | | **Partita IVA UE** | verifica sul servizio VIES della Commissione europea; esito e data salvati | -| **Codice fiscale** | 16 caratteri con carattere di controllo (11 cifre per le società); calcolabile dai dati anagrafici | +| **Codice fiscale** | 16 caratteri con carattere di controllo (11 cifre per le società); per un privato senza codice fiscale un avviso | +| **Pubblica amministrazione** | serve il codice fiscale o la partita IVA | +| **Paese** | nella tabella dei paesi; un'impresa UE ha sede in un altro paese dell'Unione, impresa italiana, privato, PA e forfettario nel paese dell'azienda | | **IBAN** | struttura e controllo modulo 97 | | **Codice destinatario** | 7 caratteri; 6 per la PA (codice IPA); `XXXXXXX` estero; `0000000` privato | | **E-mail / PEC** | formato dell'indirizzo | +| **Codice** | unico fra tutte le anagrafiche | ## Codici automatici -Il codice di clienti, fornitori e lead è assegnato automaticamente secondo le maschere impostate in +Il codice di clienti, fornitori, prospect e lead è assegnato automaticamente secondo le maschere impostate in *Tabelle azienda → Preferenze e codici automatici* (vedi [Tabelle azienda](Tabelle-azienda)): `C{seq:000000}` per i -clienti, `F{seq:000000}` per i fornitori, `L{anno}-{seq:0000}` per i lead. La maschera mostra l'anteprima del +clienti, `F{seq:000000}` per i fornitori, `L{anno}-{seq:0000}` per prospect e lead. La maschera mostra l'anteprima del prossimo codice; un'impostazione decide se è ammesso scrivere un **codice manuale**. Il progressivo è assegnato in modo atomico: due utenti che salvano insieme non ottengono mai lo stesso codice. @@ -184,25 +207,31 @@ modo atomico: due utenti che salvano insieme non ottengono mai lo stesso codice. | Quando | Khaemhat propone | |---|---| -| inserisci il CAP | comune, provincia e regione | -| inserisci i dati anagrafici di una persona | il codice fiscale | +| inserisci il CAP | comune e provincia (scelta fra più comuni) | +| inserisci il comune | CAP e provincia | +| premi *Calcola* accanto al codice fiscale di un privato | il codice fiscale | | salvi una P.IVA UE | la verifica VIES | -| inserisci un IBAN | banca e BIC (tabella ABI) | -| crei un documento per il cliente | destinazione, listino, pagamento, agente | +| inserisci un IBAN | ABI, CAB e banca (dalla tabella delle banche, quando caricata) | +| lasci vuoto il codice destinatario di un privato o di un estero | `0000000` o `XXXXXXX` | +| crei un documento per il cliente | destinazione, listino, pagamento, agente (con le vendite, M5) | Le singole compilazioni si attivano o disattivano in *Tabelle azienda → Preferenze e codici automatici*. ## Permessi e licenza -Le anagrafiche fanno parte del modulo **CORE**. Il flag utente *vede solo i propri clienti* limita un agente ai -clienti a lui assegnati. Le schede *CRM* e *Scheda 360°* mostrano i dati CRM solo con il modulo **CRM** attivo; il +Le anagrafiche fanno parte del modulo **CORE**: `parties.party.read` per consultare, `parties.party.write` per +inserire, modificare, disattivare e convertire, `parties.party.delete` per eliminare. Il flag utente *vede solo i +propri clienti*, che limiterà un agente ai clienti assegnati, non è ancora attivo. Le schede *CRM* e *Scheda 360°* mostrano i dati CRM solo con il modulo **CRM** attivo; il registro delle dichiarazioni d'intento richiede **EINV**. Ogni modifica è registrata nello **Storico**. ## Domande frequenti - **Non riesco a cancellare un cliente.** Ha documenti collegati: disabilitalo. - **La verifica VIES non risponde.** Il servizio europeo può essere temporaneamente non disponibile: salva - comunque e ripeti la verifica con l'azione **VIES** più tardi. + comunque e ripeti la verifica con l'azione **Verifica VIES** più tardi. +- **Ho convertito un prospect e il vecchio codice è sparito.** È nel campo *Codice precedente* e la ricerca lo trova. +- **Un fornitore compare anche fra i clienti.** È un cliente con *È anche fornitore*: un solo soggetto, un solo + codice. - **Un cliente privato non ha codice destinatario.** È corretto: si usa `0000000` e la fattura resta disponibile nell'area riservata del cliente sul sito dell'Agenzia delle Entrate; consegnagli comunque una copia di cortesia. diff --git a/docs/wiki/Dati-di-base-e-esempio.md b/docs/wiki/Dati-di-base-e-esempio.md index 5c057a3..a960add 100644 --- a/docs/wiki/Dati-di-base-e-esempio.md +++ b/docs/wiki/Dati-di-base-e-esempio.md @@ -124,6 +124,13 @@ reale. Contiene: | Log | voci di log di esempio in tutte le sezioni | Tutte le righe dimostrative sono marcate come tali (`is_demo`), così si possono rimuovere senza toccare il resto. + +**Oggi (M4)** i dati di esempio contengono 3 agenti e **21 anagrafiche**: 12 clienti che coprono tutti i tipi +soggetto (fra cui un comune con split payment, un cliente bloccato, uno disattivato, uno che è anche fornitore e +uno con dichiarazione d'intento), 5 fornitori (professionista con ritenuta, agente ENASARCO, fornitore UE), +2 prospect e 2 lead. Partite IVA, codici fiscali e IBAN sono numeri inventati ma formalmente validi, perché passino +i controlli; non si verificano sul VIES (ADR 0029). Gli agenti di esempio non sono marcati e si rimuovono a mano. +Il resto della tabella arriva con le milestone dei rispettivi moduli. I dati sono costruiti con gli stessi motori del programma (documenti, contabilità): ogni quadratura torna, e lo stesso caricamento è usato come prova automatica di correttezza. @@ -169,7 +176,8 @@ docker compose run --rm --entrypoint /app/scripts/seed.sh khaemhat --base --comp In sviluppo, dalla cartella del repository: `scripts/seed.sh --base [--company CODICE]`. Le opzioni `--demo [--scale N]` per i dati di esempio (`--scale N` moltiplica i volumi, per le prove di prestazione) -arrivano con anagrafiche e articoli; oggi vengono rifiutate con un messaggio. +arrivano con gli articoli (#42); oggi vengono rifiutate con un messaggio. Le anagrafiche di esempio si caricano già +al primo avvio con `KHAEMHAT_SEED_DEMO=true`. ## Migrazioni diff --git a/src/Khaemhat.Application/Parties/PartyService.cs b/src/Khaemhat.Application/Parties/PartyService.cs new file mode 100644 index 0000000..04c85b3 --- /dev/null +++ b/src/Khaemhat.Application/Parties/PartyService.cs @@ -0,0 +1,979 @@ +using System.Data.Common; +using Khaemhat.Application.Audit; +using Khaemhat.Core.Instance; +using Khaemhat.Application.Querying; +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Parties; +using Khaemhat.Core.Tables; +using Khaemhat.Core.Validation; +using Khaemhat.Data; +using Khaemhat.Data.Querying; +using Khaemhat.Fiscal.Abstractions; +using Khaemhat.Infrastructure.Http; + +namespace Khaemhat.Application.Parties; + +/// A party with every detail: what the record page shows and saves in one go. +public sealed class PartyRecord +{ + /// The party. + public Party Party { get; set; } = new(); + + /// The sales terms (customers). + public PartySalesTerms Sales { get; set; } = new(); + + /// The purchase terms (suppliers). + public PartyPurchaseTerms Purchase { get; set; } = new(); + + /// The fiscal data. + public PartyFiscal Fiscal { get; set; } = new(); + + /// The other addresses. + public List Addresses { get; set; } = []; + + /// The contact people. + public List Contacts { get; set; } = []; + + /// The bank accounts. + public List BankAccounts { get; set; } = []; +} + +/// Which parties a radar shows (menu Anagrafiche). +public enum PartyArchive +{ + /// Customers (also those that are suppliers). + Customers = 0, + + /// Suppliers (also customers that are suppliers). + Suppliers = 1, + + /// Prospects and leads. + Contacts = 2, +} + +/// A row of the radar of the parties (mockup 012). +/// The id. +/// The code. +/// The name. +/// What the party is. +/// A customer that is also a supplier. +/// The kind of subject. +/// The VAT number. +/// The tax code. +/// The city. +/// The province. +/// The country. +/// The salesperson. +/// The category. +/// Disabled. +public sealed record PartyRow( + long Id, string Code, string Name, PartyKind Kind, bool IsAlsoSupplier, SubjectType SubjectType, string? VatNumber, string? TaxCode, string? City, + string? Province, string CountryCode, long? SalespersonId, long? CategoryId, bool Disabled) +{ + /// The terms of the row, filled for the page shown. + public PartyRowTerms? Terms { get; init; } + + /// VAT number or, without one, tax code (column P.IVA / C.F.). + public string? Identifier => VatNumber ?? TaxCode; +} + +/// The terms shown on a radar row. +/// The payment terms. +/// The price list. +/// Orders blocked. +/// Split payment. +public sealed record PartyRowTerms(long? PaymentTermId, long? PriceListId, bool Blocked, bool SplitPayment); + +/// What deleting a party did. +public enum PartyDeleteOutcome +{ + /// The party is gone. + Deleted = 0, + + /// The party is used by documents: it was disabled instead. + Disabled = 1, +} + +/// +/// The parties (SPEC §11.2, issue #41, ADR 0029): radar, read and save of a party with its details in one transaction, +/// automatic codes by kind, the checks of the fiscal pack, the VIES check of EU numbers, conversion of leads and prospects +/// into customers, delete or disable. +/// +/// Permissions parties.party.read, write, delete. +public sealed class PartyService +{ + /// Permission to see the parties. + public const string ReadPermission = "parties.party.read"; + + /// Permission to create and change the parties. + public const string WritePermission = "parties.party.write"; + + /// Permission to delete the parties. + public const string DeletePermission = "parties.party.delete"; + + /// Error: the name is missing. + public const string NameRequired = "parties.name.required"; + + /// Error: the VAT number is required for this kind of subject. + public const string VatNumberRequired = "parties.vat-number.required"; + + /// Error: a public administration needs a VAT number or a tax code. + public const string IdentifierRequired = "parties.identifier.required"; + + /// Error: the tax code is not valid. + public const string TaxCodeInvalid = "parties.tax-code.invalid"; + + /// Warning: a private customer without tax code. + public const string TaxCodeMissing = "parties.tax-code.missing"; + + /// Error: another party has the code. + public const string CodeDuplicate = "parties.code.duplicate"; + + /// Error: the country is not in the table of the countries. + public const string CountryUnknown = "parties.country.unknown"; + + /// Error: an EU subject needs a member state other than the company's. + public const string CountryNotEu = "parties.country.not-eu"; + + /// Error: a domestic subject needs the company's country. + public const string CountryNotDomestic = "parties.country.not-domestic"; + + /// Warning: another party has the same VAT number. + public const string VatNumberDuplicate = "parties.vat-number.duplicate"; + + /// Error: a declaration of intent needs number and ceiling. + public const string IntentIncomplete = "parties.intent.incomplete"; + + /// Error: the exigibility is not I, D or S. + public const string ExigibilityInvalid = "parties.exigibility.invalid"; + + /// Error: the day of the month is not 1-31. + public const string DayRange = "parties.day.range"; + + /// Error: a value cannot be negative. + public const string NotNegative = "parties.value.negative"; + + /// Error: an address or contact without name, a bank account without IBAN. + public const string DetailRequired = "parties.detail.required"; + + /// Error: the party is not a lead or prospect, nor a supplier (conversion). + public const string AlreadyCustomer = "parties.convert.already-customer"; + + /// Error: the party changed or was deleted meanwhile. + public const string NotFound = "parties.not-found"; + + /// The entity name of the attachments and the history. + public const string Entity = "parties.party"; + + private readonly IUnitOfWorkFactory _factory; + private readonly PermissionService _permissions; + private readonly AuditTrail _audit; + private readonly CompanyFiscalContext _fiscal; + private readonly CodeRuleService _codes; + private readonly AutoFillService _autoFill; + private readonly TimeProvider _clock; + + /// Creates the service. + /// Opens the company databases. + /// Checks permissions. + /// Writes the history. + /// The fiscal pack of each company. + /// The automatic codes. + /// The automatic filling options and the VIES check. + /// The clock. + public PartyService( + IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit, CompanyFiscalContext fiscal, CodeRuleService codes, AutoFillService autoFill, + TimeProvider clock) + { + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(permissions); + ArgumentNullException.ThrowIfNull(audit); + ArgumentNullException.ThrowIfNull(fiscal); + ArgumentNullException.ThrowIfNull(codes); + ArgumentNullException.ThrowIfNull(autoFill); + ArgumentNullException.ThrowIfNull(clock); + _factory = factory; + _permissions = permissions; + _audit = audit; + _fiscal = fiscal; + _codes = codes; + _autoFill = autoFill; + _clock = clock; + } + + /// The fields of the radar: search on code, name, VAT number, tax code and city. + public static ListFields Fields { get; } = new ListFields() + .Add("code", p => p.Code, searchable: true) + .Add("name", p => p.Name, searchable: true) + .Add("vatNumber", p => p.VatNumber, searchable: true) + .Add("taxCode", p => p.TaxCode, searchable: true) + .Add("city", p => p.City, searchable: true) + .Add("province", p => p.Province) + .Add("country", p => p.CountryCode) + .Add("subjectType", p => p.SubjectType) + .Add("kind", p => p.Kind) + .Add("salesperson", p => p.SalespersonId) + .Add("category", p => p.CategoryId) + .Add("disabled", p => p.Disabled) + .OrderByDefault(new ListSort("name")); + + /// The code archive of a kind of party (ADR 0027). + /// The kind. + /// The key of . + public static string CodeRuleOf(PartyKind kind) => kind switch + { + PartyKind.Customer => "customers", + PartyKind.Supplier => "suppliers", + _ => "leads", + }; + + /// The kind of e-invoice recipient of a subject. + /// The kind of subject. + /// The recipient kind. + public static RecipientKind RecipientOf(SubjectType subject) => subject switch + { + SubjectType.PublicAdministration => RecipientKind.PublicAdministration, + SubjectType.Person => RecipientKind.Consumer, + SubjectType.EuCompany or SubjectType.NonEuCompany => RecipientKind.Foreign, + _ => RecipientKind.Business, + }; + + /// A page of the radar. + /// Who reads. + /// The company. + /// Customers, suppliers or contacts. + /// Search, filters, ordering and page. + /// Cancellation. + /// The page, with the terms of its rows. + public async Task> ListAsync(Actor actor, string companyCode, PartyArchive archive, ListQuery query, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(query); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var select = archive switch + { + PartyArchive.Customers => Query.For().Where(p => p.Kind == PartyKind.Customer), + PartyArchive.Suppliers => Query.For().Where(p => p.Kind == PartyKind.Supplier || (p.Kind == PartyKind.Customer && p.IsAlsoSupplier)), + _ => Query.For().Where(p => p.Kind == PartyKind.Prospect || p.Kind == PartyKind.Lead), + }; + var page = await uow.Repository().ListAsync(Fields.Apply(select, query), cancellationToken).ConfigureAwait(false); + var ids = page.Items.Select(p => p.Id).ToList(); + var sales = ids.Count == 0 + ? [] + : (await uow.Repository().ListAsync(Query.For().Where(s => ids.Contains(s.PartyId)), cancellationToken).ConfigureAwait(false)).Items; + var purchase = ids.Count == 0 + ? [] + : (await uow.Repository().ListAsync(Query.For().Where(s => ids.Contains(s.PartyId)), cancellationToken).ConfigureAwait(false)).Items; + var fiscal = ids.Count == 0 + ? [] + : (await uow.Repository().ListAsync(Query.For().Where(s => ids.Contains(s.PartyId)), cancellationToken).ConfigureAwait(false)).Items; + var salesBy = sales.ToDictionary(s => s.PartyId); + var purchaseBy = purchase.ToDictionary(s => s.PartyId); + var fiscalBy = fiscal.ToDictionary(s => s.PartyId); + IReadOnlyList rows = + [ + .. page.Items.Select(p => RowOf(p) with + { + Terms = new PartyRowTerms( + archive == PartyArchive.Suppliers ? purchaseBy.GetValueOrDefault(p.Id)?.PaymentTermId : salesBy.GetValueOrDefault(p.Id)?.PaymentTermId, + salesBy.GetValueOrDefault(p.Id)?.PriceListId, + salesBy.GetValueOrDefault(p.Id)?.Blocked ?? false, + fiscalBy.GetValueOrDefault(p.Id)?.SplitPayment ?? false), + }), + ]; + return new ListPage(rows, page.TotalCount, new Dictionary()); + } + + /// Parties for a hotlink: active ones whose code or name starts with or contains the text. + /// Who reads. + /// The company. + /// Customers, suppliers or contacts. + /// The text typed. + /// Cancellation. + /// Up to 20 rows. + public async Task> SearchAsync(Actor actor, string companyCode, PartyArchive archive, string? text, CancellationToken cancellationToken = default) + { + var page = await ListAsync( + actor, companyCode, archive, + new ListQuery { Search = text, Filters = [ListFilter.Of("disabled", ListFilterOperator.Equals, "false")], Limit = 20 }, + cancellationToken).ConfigureAwait(false); + return page.Items; + } + + /// A party with every detail. + /// Who reads. + /// The company. + /// The party. + /// Cancellation. + /// The record, or . + public async Task GetAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + return await LoadAsync(uow, id, cancellationToken).ConfigureAwait(false); + } + + /// A new party of a kind, with the values proposed by the company (country, currency, defaults). + /// Who creates it. + /// The company. + /// The kind. + /// Cancellation. + /// The record, not saved. + public async Task NewAsync(Actor actor, string companyCode, PartyKind kind, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false); + var pack = await _fiscal.PackOfAsync(company, cancellationToken).ConfigureAwait(false); + var today = DateOnly.FromDateTime(_clock.GetLocalNow().DateTime); + return new PartyRecord + { + Party = new Party { Kind = kind, CountryCode = pack.CountryCode, Since = kind is PartyKind.Customer or PartyKind.Supplier ? today : null }, + }; + } + + /// Checks a record without saving it: normalizes it in place and returns errors and warnings. + /// Who checks. + /// The company. + /// The record. + /// Cancellation. + /// The problems, with fields such as VatNumber, Fiscal.RecipientCode or Addresses.0.Name. + public async Task> ValidateAsync(Actor actor, string companyCode, PartyRecord record, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(record); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false); + var pack = await _fiscal.PackOfAsync(company, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + return await CheckAsync(uow, pack, record, cancellationToken).ConfigureAwait(false); + } + + /// + /// Saves a party with its details: inserts it when its id is 0 (assigning the code when empty), updates it otherwise. + /// An EU VAT number that is new or changed is checked on VIES when the option is on; the outcome is saved. + /// + /// Who saves. + /// The company. + /// The record. + /// Cancellation. + /// The saved record, read back. + /// A rule failed; errors are Field:code. + /// Someone else changed the party meanwhile. + public async Task SaveAsync(Actor actor, string companyCode, PartyRecord record, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(record); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false); + var pack = await _fiscal.PackOfAsync(company, cancellationToken).ConfigureAwait(false); + var party = record.Party; + long id; + PartyRecord? before; + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + before = party.Id == 0 ? null : await LoadAsync(uow, party.Id, cancellationToken).ConfigureAwait(false) ?? throw new ValidationFailedException([":" + NotFound]); + var problems = (await CheckAsync(uow, pack, record, cancellationToken).ConfigureAwait(false)).Where(p => !p.IsWarning).Select(p => p.Field + ":" + p.Code).ToList(); + var codeChanged = before is null || !string.Equals(before.Party.Code, party.Code, StringComparison.Ordinal); + var rule = await _codes.RuleAsync(company, CodeRuleOf(party.Kind), cancellationToken).ConfigureAwait(false); + if (party.Code.Length > 0 && codeChanged && CodeRuleService.CheckManual(rule, party.Code) is { } manual) + { + problems.Add(nameof(Party.Code) + ":" + manual); + } + + if (problems.Count > 0) + { + throw new ValidationFailedException(problems); + } + + if (party.Code.Length == 0) + { + var today = DateOnly.FromDateTime(_clock.GetLocalNow().DateTime); + party.Code = await CodeRuleService.AssignAsync(uow, rule, today, null, (c, ct) => TakenAsync(uow, c, ct), cancellationToken).ConfigureAwait(false); + } + + id = await WriteAsync(uow, record, before, actor.UserName, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + if (party.SubjectType == SubjectType.EuCompany && party.VatNumber is { Length: > 0 } + && (before is null || before.Party.VatNumber != party.VatNumber || before.Party.CountryCode != party.CountryCode || before.Party.VatCheck == VatCheckStatus.None) + && await _autoFill.IsOnAsync(company, AutoFillService.Vies, cancellationToken).ConfigureAwait(false)) + { + await CheckVatCoreAsync(company, id, actor.UserName, cancellationToken).ConfigureAwait(false); + } + + await using var read = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + return await LoadAsync(read, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFound); + } + + /// Checks the VAT number of an EU party on VIES now (action VIES) and saves the outcome. + /// Who asks. + /// The company. + /// The party. + /// Cancellation. + /// The answer of VIES, or when the party has no VAT number of a member state. + public async Task CheckVatAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false); + return await CheckVatCoreAsync(company, id, actor.UserName, cancellationToken).ConfigureAwait(false); + } + + /// + /// Turns a lead or prospect into a customer with a customer code (the old code stays in + /// ), or makes a supplier also a customer (it keeps its code). + /// + /// Who converts. + /// The company. + /// The party. + /// Cancellation. + /// The party. + public async Task ConvertToCustomerAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false); + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var repository = uow.Repository(); + var party = await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFound); + var before = Clone(party); + switch (party.Kind) + { + case PartyKind.Customer: + throw new ValidationFailedException(["Kind:" + AlreadyCustomer]); + case PartyKind.Supplier: + party.Kind = PartyKind.Customer; + party.IsAlsoSupplier = true; + break; + default: + var rule = await _codes.RuleAsync(company, CodeRuleOf(PartyKind.Customer), cancellationToken).ConfigureAwait(false); + var today = DateOnly.FromDateTime(_clock.GetLocalNow().DateTime); + party.PreviousCode = party.Code; + party.Code = await CodeRuleService.AssignAsync(uow, rule, today, null, (c, ct) => TakenAsync(uow, c, ct), cancellationToken).ConfigureAwait(false); + party.Kind = PartyKind.Customer; + party.Since ??= today; + break; + } + + await repository.UpdateAsync(party, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Update, id, before, party, actor.UserName, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + return await GetAsync(actor, company, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFound); + } + + /// Disables or enables parties (radar action Disabilita). + /// Who acts. + /// The company. + /// The parties. + /// Disable or enable. + /// Cancellation. + /// The parties changed. + public async Task SetDisabledAsync(Actor actor, string companyCode, IEnumerable ids, bool disabled, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(ids); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var repository = uow.Repository(); + var changed = 0; + foreach (var id in ids.Distinct()) + { + if (await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) is { } party && party.Disabled != disabled) + { + var before = Clone(party); + party.Disabled = disabled; + await repository.UpdateAsync(party, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Update, id, before, party, actor.UserName, cancellationToken).ConfigureAwait(false); + changed++; + } + } + + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return changed; + } + + /// Deletes a party never used, or disables it when documents refer to it. + /// Who deletes. + /// The company. + /// The party. + /// Cancellation. + /// What happened. + public async Task DeleteAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, DeletePermission, cancellationToken).ConfigureAwait(false); + try + { + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var before = await LoadAsync(uow, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFound); + + // The details go with the party (cascade); the documents of later milestones refuse the delete. + await uow.Repository().DeleteAsync(id, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Delete, id, before.Party, null, actor.UserName, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return PartyDeleteOutcome.Deleted; + } + catch (DbException) + { + await SetDisabledAsync(actor, company, [id], true, cancellationToken).ConfigureAwait(false); + return PartyDeleteOutcome.Disabled; + } + } + + /// The history of a party, newest first. + /// Who reads. + /// The company. + /// The party. + /// Cancellation. + /// The changes of the party and of its details. + public async Task> HistoryAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var key = id.ToString(System.Globalization.CultureInfo.InvariantCulture); + var entries = new List(); + foreach (var entity in new[] { nameof(Party), nameof(PartySalesTerms), nameof(PartyPurchaseTerms), nameof(PartyFiscal) }) + { + entries.AddRange(await AuditTrail.HistoryAsync(uow, entity, key, cancellationToken).ConfigureAwait(false)); + } + + return [.. entries.OrderByDescending(e => e.At).ThenByDescending(e => e.Id)]; + } + + private static PartyRow RowOf(Party p) => + new(p.Id, p.Code, p.Name, p.Kind, p.IsAlsoSupplier, p.SubjectType, p.VatNumber, p.TaxCode, p.City, p.Province, p.CountryCode, p.SalespersonId, p.CategoryId, p.Disabled); + + private static async Task TakenAsync(IUnitOfWork uow, string code, CancellationToken cancellationToken) => + await uow.Repository().CountAsync(Query.For().Where(p => p.Code == code), cancellationToken).ConfigureAwait(false) > 0; + + private static async Task LoadAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken) + { + if (await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } party) + { + return null; + } + + return new PartyRecord + { + Party = party, + Sales = await uow.Repository().FindAsync(Query.For().Where(s => s.PartyId == id), cancellationToken).ConfigureAwait(false) + ?? new PartySalesTerms { PartyId = id }, + Purchase = await uow.Repository().FindAsync(Query.For().Where(s => s.PartyId == id), cancellationToken).ConfigureAwait(false) + ?? new PartyPurchaseTerms { PartyId = id }, + Fiscal = await uow.Repository().FindAsync(Query.For().Where(s => s.PartyId == id), cancellationToken).ConfigureAwait(false) + ?? new PartyFiscal { PartyId = id }, + Addresses = [.. (await uow.Repository().ListAsync(Query.For().Where(a => a.PartyId == id).OrderBy(a => a.Id), cancellationToken).ConfigureAwait(false)).Items], + Contacts = [.. (await uow.Repository().ListAsync(Query.For().Where(a => a.PartyId == id).OrderBy(a => a.Id), cancellationToken).ConfigureAwait(false)).Items], + BankAccounts = [.. (await uow.Repository().ListAsync(Query.For().Where(a => a.PartyId == id).OrderBy(a => a.Id), cancellationToken).ConfigureAwait(false)).Items], + }; + } + + private async Task WriteAsync(IUnitOfWork uow, PartyRecord record, PartyRecord? before, string userName, CancellationToken cancellationToken) + { + var party = record.Party; + var parties = uow.Repository(); + if (before is null) + { + party.Id = await parties.InsertAsync(party, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Insert, party.Id, null, party, userName, cancellationToken).ConfigureAwait(false); + } + else + { + await parties.UpdateAsync(party, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Update, party.Id, before.Party, party, userName, cancellationToken).ConfigureAwait(false); + } + + var id = party.Id; + await UpsertAsync(uow, record.Sales, before?.Sales, id, userName, s => s.PartyId = id, cancellationToken).ConfigureAwait(false); + await UpsertAsync(uow, record.Purchase, before?.Purchase, id, userName, s => s.PartyId = id, cancellationToken).ConfigureAwait(false); + await UpsertAsync(uow, record.Fiscal, before?.Fiscal, id, userName, s => s.PartyId = id, cancellationToken).ConfigureAwait(false); + await ReplaceAsync(uow, record.Addresses, before?.Addresses ?? [], a => a.PartyId = id, cancellationToken).ConfigureAwait(false); + await ReplaceAsync(uow, record.Contacts, before?.Contacts ?? [], a => a.PartyId = id, cancellationToken).ConfigureAwait(false); + await ReplaceAsync(uow, record.BankAccounts, before?.BankAccounts ?? [], a => a.PartyId = id, cancellationToken).ConfigureAwait(false); + return id; + } + + // The one-to-one details: inserted the first time, then updated; the history is kept under the id of the party. + private async Task UpsertAsync(IUnitOfWork uow, T row, T? before, long partyId, string userName, Action link, CancellationToken cancellationToken) + where T : Core.Entities.Entity, new() + { + link(row); + var repository = uow.Repository(); + if (before is null || before.Id == 0) + { + row.Id = await repository.InsertAsync(row, cancellationToken).ConfigureAwait(false); + return; + } + + row.Id = before.Id; + row.RowVersion = before.RowVersion; + await repository.UpdateAsync(row, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Update, partyId, before, row, userName, cancellationToken).ConfigureAwait(false); + } + + // The lists: rows removed are deleted, rows kept are updated, new rows inserted. + private static async Task ReplaceAsync(IUnitOfWork uow, List rows, List before, Action link, CancellationToken cancellationToken) + where T : Core.Entities.Entity, new() + { + var repository = uow.Repository(); + var kept = rows.Where(r => r.Id != 0).Select(r => r.Id).ToHashSet(); + foreach (var old in before.Where(b => !kept.Contains(b.Id))) + { + await repository.DeleteAsync(old.Id, cancellationToken).ConfigureAwait(false); + } + + var versions = before.ToDictionary(b => b.Id, b => b.RowVersion); + foreach (var row in rows) + { + link(row); + if (row.Id != 0 && versions.TryGetValue(row.Id, out var version)) + { + row.RowVersion = version; + await repository.UpdateAsync(row, cancellationToken).ConfigureAwait(false); + } + else + { + row.Id = await repository.InsertAsync(row, cancellationToken).ConfigureAwait(false); + } + } + } + + private async Task CheckVatCoreAsync(string company, long id, string userName, CancellationToken cancellationToken) + { + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var repository = uow.Repository(); + var party = await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFound); + if (party.VatNumber is not { Length: > 0 } number || ViesClient.MemberStateCode(party.CountryCode) is not { } state) + { + return null; + } + + var result = await _autoFill.CheckVatAsync(state, number, cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + party = await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFound); + var before = Clone(party); + party.VatCheck = result.Status switch + { + ViesStatus.Valid => VatCheckStatus.Valid, + ViesStatus.Invalid or ViesStatus.InvalidInput => VatCheckStatus.Invalid, + _ => VatCheckStatus.Unavailable, + }; + party.VatCheckedAt = result.CheckedAt.UtcDateTime; + await repository.UpdateAsync(party, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Update, id, before, party, userName, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return result; + } + + private static async Task> CheckAsync(IUnitOfWork uow, IFiscalPack pack, PartyRecord record, CancellationToken cancellationToken) + { + var problems = new List(); + var party = record.Party; + var trading = party.Kind is PartyKind.Customer or PartyKind.Supplier; + Normalize(party); + + if (party.SubjectType == SubjectType.Person && party.Name.Length == 0 && (party.LastName is not null || party.FirstName is not null)) + { + party.Name = string.Join(' ', new[] { party.LastName, party.FirstName }.Where(n => n is not null)); + } + + if (party.Name.Length == 0) + { + problems.Add(new(nameof(Party.Name), NameRequired)); + } + + if (party.Code.Length > 0) + { + var code = party.Code; + var id = party.Id; + if (await uow.Repository().CountAsync(Query.For().Where(p => p.Code == code && p.Id != id), cancellationToken).ConfigureAwait(false) > 0) + { + problems.Add(new(nameof(Party.Code), CodeDuplicate)); + } + } + + // Country: the domestic subjects live in the company's country, the EU ones in another member state. + var countryCode = party.CountryCode; + var country = await uow.Repository().FindAsync(Query.For().Where(c => c.Code == countryCode), cancellationToken).ConfigureAwait(false); + var domestic = party.CountryCode == pack.CountryCode; + if (country is null) + { + problems.Add(new(nameof(Party.CountryCode), CountryUnknown)); + } + else if (party.SubjectType == SubjectType.EuCompany && (!country.EuMember || domestic)) + { + problems.Add(new(nameof(Party.CountryCode), CountryNotEu)); + } + else if (party.SubjectType is SubjectType.Company or SubjectType.PublicAdministration or SubjectType.FlatRate && !domestic) + { + problems.Add(new(nameof(Party.CountryCode), CountryNotDomestic)); + } + + var rules = pack.GetFeature(); + if (party.VatNumber is not null) + { + if (domestic && rules is not null) + { + party.VatNumber = rules.NormalizeVatNumber(party.VatNumber); + if (!rules.IsValidVatNumber(party.VatNumber)) + { + problems.Add(new(nameof(Party.VatNumber), TableCatalog.VatNumberInvalid)); + } + } + else if ((country?.VatPrefix ?? country?.Code) is { } prefix && party.VatNumber.StartsWith(prefix, StringComparison.Ordinal)) + { + party.VatNumber = party.VatNumber[prefix.Length..]; + } + + var vat = party.VatNumber; + var self = party.Id; + if (await uow.Repository().CountAsync(Query.For().Where(p => p.VatNumber == vat && p.CountryCode == countryCode && p.Id != self), cancellationToken).ConfigureAwait(false) > 0) + { + problems.Add(new(nameof(Party.VatNumber), VatNumberDuplicate, IsWarning: true)); + } + } + else if (trading && party.SubjectType is SubjectType.Company or SubjectType.FlatRate or SubjectType.EuCompany) + { + problems.Add(new(nameof(Party.VatNumber), VatNumberRequired)); + } + + if (party.TaxCode is not null && domestic && rules is not null && !rules.IsValidTaxCode(party.TaxCode)) + { + problems.Add(new(nameof(Party.TaxCode), TaxCodeInvalid)); + } + + if (trading && party.SubjectType == SubjectType.PublicAdministration && party.VatNumber is null && party.TaxCode is null) + { + problems.Add(new(nameof(Party.TaxCode), IdentifierRequired)); + } + + if (party.Kind == PartyKind.Customer && party.SubjectType == SubjectType.Person && party.TaxCode is null) + { + problems.Add(new(nameof(Party.TaxCode), TaxCodeMissing, IsWarning: true)); + } + + Email(party.Email, nameof(Party.Email), problems); + Email(party.Pec, nameof(Party.Pec), problems); + CheckFiscal(record.Fiscal, party, rules, problems); + CheckTerms(record, problems); + CheckDetails(record, pack, problems); + return problems; + } + + private static void Normalize(Party party) + { + party.Code = party.Code.Trim().ToUpperInvariant(); + party.Name = party.Name.Trim(); + party.FirstName = Clean(party.FirstName); + party.LastName = Clean(party.LastName); + party.FiscalName = Clean(party.FiscalName); + party.VatNumber = Clean(party.VatNumber)?.Replace(" ", string.Empty, StringComparison.Ordinal).ToUpperInvariant(); + party.TaxCode = Clean(party.TaxCode)?.Replace(" ", string.Empty, StringComparison.Ordinal).ToUpperInvariant(); + party.Province = Clean(party.Province)?.ToUpperInvariant(); + party.CountryCode = (Clean(party.CountryCode) ?? string.Empty).ToUpperInvariant(); + party.CurrencyCode = (Clean(party.CurrencyCode) ?? "EUR").ToUpperInvariant(); + party.Language = (Clean(party.Language) ?? "it").ToLowerInvariant(); + party.Email = Clean(party.Email); + party.Pec = Clean(party.Pec); + party.PostalCode = Clean(party.PostalCode); + party.City = Clean(party.City); + party.Address = Clean(party.Address); + } + + private static void CheckFiscal(PartyFiscal fiscal, Party party, ITaxIdentifierRules? rules, List problems) + { + fiscal.RecipientCode = Clean(fiscal.RecipientCode)?.ToUpperInvariant(); + fiscal.RecipientPec = Clean(fiscal.RecipientPec); + fiscal.Exigibility = Clean(fiscal.Exigibility)?.ToUpperInvariant(); + var recipient = RecipientOf(party.SubjectType); + if (party.Kind is PartyKind.Customer && rules is not null) + { + // Consumers and foreign customers get the code of the e-invoice format; a business with only a PEC gets 0000000. + if (fiscal.RecipientCode is null && (recipient is RecipientKind.Consumer or RecipientKind.Foreign || fiscal.RecipientPec is not null)) + { + fiscal.RecipientCode = rules.DefaultRecipientCode(recipient); + } + + problems.AddRange(rules.CheckRecipientCode(fiscal.RecipientCode, recipient) + .Select(p => new TableProblem("Fiscal." + p.Field, p.Code, p.Severity == FiscalProblemSeverity.Warning))); + } + + Email(fiscal.RecipientPec, "Fiscal." + nameof(PartyFiscal.RecipientPec), problems); + if (fiscal.SplitPayment) + { + fiscal.Exigibility = "S"; + } + + if (fiscal.Exigibility is not (null or "I" or "D" or "S")) + { + problems.Add(new("Fiscal." + nameof(PartyFiscal.Exigibility), ExigibilityInvalid)); + } + + Percent(fiscal.WithholdingRate, "Fiscal." + nameof(PartyFiscal.WithholdingRate), problems); + Percent(fiscal.PensionFundRate, "Fiscal." + nameof(PartyFiscal.PensionFundRate), problems); + if (fiscal.IntentActive) + { + fiscal.IntentNumber = Clean(fiscal.IntentNumber); + if (fiscal.IntentNumber is null) + { + problems.Add(new("Fiscal." + nameof(PartyFiscal.IntentNumber), IntentIncomplete)); + } + + if (fiscal.IntentCeiling is null) + { + problems.Add(new("Fiscal." + nameof(PartyFiscal.IntentCeiling), IntentIncomplete)); + } + } + + if (fiscal.IntentCeiling < 0) + { + problems.Add(new("Fiscal." + nameof(PartyFiscal.IntentCeiling), NotNegative)); + } + + if (fiscal.IntentFrom is { } from && fiscal.IntentTo is { } to && to < from) + { + problems.Add(new("Fiscal." + nameof(PartyFiscal.IntentTo), TableCatalog.ValidityOrder)); + } + } + + private static void CheckTerms(PartyRecord record, List problems) + { + var sales = record.Sales; + Percent(sales.Discount1, "Sales." + nameof(PartySalesTerms.Discount1), problems); + Percent(sales.Discount2, "Sales." + nameof(PartySalesTerms.Discount2), problems); + if (sales.CreditLimit < 0) + { + problems.Add(new("Sales." + nameof(PartySalesTerms.CreditLimit), NotNegative)); + } + + if (sales.InvoiceDay is < 1 or > 31) + { + problems.Add(new("Sales." + nameof(PartySalesTerms.InvoiceDay), DayRange)); + } + + sales.DocumentsEmail = Clean(sales.DocumentsEmail); + Email(sales.DocumentsEmail, "Sales." + nameof(PartySalesTerms.DocumentsEmail), problems); + + var purchase = record.Purchase; + Percent(purchase.Discount, "Purchase." + nameof(PartyPurchaseTerms.Discount), problems); + if (purchase.LeadTimeDays < 0) + { + problems.Add(new("Purchase." + nameof(PartyPurchaseTerms.LeadTimeDays), NotNegative)); + } + + if (purchase.MinimumOrder < 0) + { + problems.Add(new("Purchase." + nameof(PartyPurchaseTerms.MinimumOrder), NotNegative)); + } + + purchase.OrdersEmail = Clean(purchase.OrdersEmail); + Email(purchase.OrdersEmail, "Purchase." + nameof(PartyPurchaseTerms.OrdersEmail), problems); + } + + private static void CheckDetails(PartyRecord record, IFiscalPack pack, List problems) + { + for (var i = 0; i < record.Addresses.Count; i++) + { + var address = record.Addresses[i]; + address.Name = address.Name.Trim(); + address.CountryCode = (Clean(address.CountryCode) ?? pack.CountryCode).ToUpperInvariant(); + address.Province = Clean(address.Province)?.ToUpperInvariant(); + if (address.Name.Length == 0) + { + problems.Add(new($"Addresses.{i}.{nameof(PartyAddress.Name)}", DetailRequired)); + } + } + + for (var i = 0; i < record.Contacts.Count; i++) + { + var contact = record.Contacts[i]; + contact.Name = contact.Name.Trim(); + contact.Email = Clean(contact.Email); + if (contact.Name.Length == 0) + { + problems.Add(new($"Contacts.{i}.{nameof(PartyContact.Name)}", DetailRequired)); + } + + Email(contact.Email, $"Contacts.{i}.{nameof(PartyContact.Email)}", problems); + } + + var directory = pack.GetFeature(); + for (var i = 0; i < record.BankAccounts.Count; i++) + { + var account = record.BankAccounts[i]; + account.Iban = IbanValidator.Normalize(account.Iban); + account.Bic = Clean(account.Bic)?.ToUpperInvariant(); + if (account.Iban.Length == 0) + { + problems.Add(new($"BankAccounts.{i}.{nameof(PartyBankAccount.Iban)}", DetailRequired)); + continue; + } + + if (!IbanValidator.IsValid(account.Iban)) + { + problems.Add(new($"BankAccounts.{i}.{nameof(PartyBankAccount.Iban)}", TableCatalog.IbanInvalid)); + continue; + } + + if (directory?.ReadIban(account.Iban) is { } bank) + { + account.BankCode = bank.BankCode; + account.BranchCode = bank.BranchCode; + account.BankName ??= bank.Name; + account.Bic ??= bank.Bic; + } + } + + // One default per list: the first one marked wins. + OneDefault(record.Contacts, c => c.IsDefault, (c, v) => c.IsDefault = v); + OneDefault(record.BankAccounts, c => c.IsDefault, (c, v) => c.IsDefault = v); + foreach (var kind in record.Addresses.Select(a => a.Kind).Distinct().ToList()) + { + OneDefault([.. record.Addresses.Where(a => a.Kind == kind)], a => a.IsDefault, (a, v) => a.IsDefault = v); + } + } + + private static void OneDefault(List rows, Func get, Action set) + { + var found = false; + foreach (var row in rows) + { + if (get(row)) + { + if (found) + { + set(row, false); + } + + found = true; + } + } + } + + private static void Email(string? value, string field, List problems) + { + if (value is not null && !EmailValidator.IsValid(value)) + { + problems.Add(new(field, TableCatalog.EmailInvalid)); + } + } + + private static void Percent(decimal? value, string field, List problems) + { + if (value is < 0 or > 100) + { + problems.Add(new(field, TableCatalog.PercentRange)); + } + } + + private static string? Clean(string? value) => string.IsNullOrWhiteSpace(value) ? null : value.Trim(); + + private static Party Clone(Party party) + { + var copy = new Party(); + foreach (var property in typeof(Party).GetProperties().Where(p => p.CanRead && p.CanWrite)) + { + property.SetValue(copy, property.GetValue(party)); + } + + return copy; + } +} diff --git a/src/Khaemhat.Application/Seeding/DemoPartiesSeeder.cs b/src/Khaemhat.Application/Seeding/DemoPartiesSeeder.cs new file mode 100644 index 0000000..1407be1 --- /dev/null +++ b/src/Khaemhat.Application/Seeding/DemoPartiesSeeder.cs @@ -0,0 +1,293 @@ +using Khaemhat.Application.Modules; +using Khaemhat.Application.Parties; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Parties; +using Khaemhat.Core.Tables; +using Khaemhat.Data; +using Khaemhat.Data.Querying; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Application.Seeding; + +/// +/// The parties of the demo company (SPEC §14, issue #41): customers of every kind of subject (companies, public +/// administration with split payment, private persons, EU and non-EU companies, flat rate, a declaration of intent, a +/// customer blocked over its credit, one that is also a supplier, one disabled), suppliers (a professional with +/// withholding, an ENASARCO agent, an EU supplier), prospects and leads, and three salespeople. Every name, number and +/// bank account is fictitious: the VAT numbers have a valid check digit, the IBANs a valid check, the ABI codes belong +/// to no bank. Runs only on a company without parties; the rows are marked as demo. +/// +/// The automatic code rules. +public sealed class DemoPartiesSeeder(CodeRuleService codes) : ISeeder +{ + /// The fictitious VAT numbers, valid for the Italian check digit (tests check them with the pack). + public static readonly IReadOnlyList VatNumbers = + [ + "04123456784", "05234567898", "06345678905", "07456789010", "08567890127", "09678901233", "10789012340", "11890123455", + "12901234562", "13012345677", "14123456700", "15234567814", "16345678920", "17456789035", + ]; + + /// The fictitious tax code of the public administration (numeric, valid check digit). + public const string AdministrationTaxCode = "80012345676"; + + /// The fictitious IBANs, with a valid check and ABI codes of no bank. + public static readonly IReadOnlyList Ibans = ["IT53X0123410100000012345678", "IT21X0567822000000000987654", "IT11X0987645600000101234567"]; + + /// + public string ModuleCode => ModuleCodes.Core; + + /// + public SeedKind Kind => SeedKind.Demo; + + /// + public int Order => 10; + + /// + public async Task RunAsync(SeedContext context, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(context); + var uow = context.UnitOfWork; + if (await uow.Repository().CountAsync(Query.For(), cancellationToken).ConfigureAwait(false) > 0) + { + return; + } + + var rules = new Dictionary(); + foreach (var kind in Enum.GetValues()) + { + rules[kind] = await codes.RuleAsync(context.CompanyCode, PartyService.CodeRuleOf(kind), cancellationToken).ConfigureAwait(false); + } + + var salespeople = await context.EnsureAsync( + "salespeople", + [ + new Salesperson { Code = "VERDI", Description = "Marco Verdi", Email = "m.verdi@demo.example", CommissionPercent = 5m, Enasarco = true }, + new Salesperson { Code = "NERI", Description = "Laura Neri", Email = "l.neri@demo.example", CommissionPercent = 4m, Enasarco = true }, + new Salesperson { Code = "BIANCO", Description = "Paolo Bianco", Email = "p.bianco@demo.example", CommissionPercent = 3m }, + ], + cancellationToken).ConfigureAwait(false); + var terms = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items + .ToDictionary(t => t.Code, t => t.Id, StringComparer.OrdinalIgnoreCase); + var priceList = (await uow.Repository().FindAsync(Query.For().Where(p => p.Code == "BASE"), cancellationToken).ConfigureAwait(false))?.Id; + long? Term(string code) => terms.TryGetValue(code, out var id) ? id : null; + long? Agent(string code) => salespeople.TryGetValue(code, out var s) ? s.Id : null; + var identifiers = context.Pack.GetFeature(); + var year = context.Today.Year; + + var seeds = new List + { + Customer("Rossi Impianti S.r.l.", SubjectType.Company, VatNumbers[0], "Via Nizza", "120", "10126", "Torino", "TO", Term("RB60FM"), Agent("VERDI"), r => + { + r.Fiscal.RecipientCode = "M5UXCR1"; + r.Party.Phone = "011 5550101"; + r.Party.Email = "amministrazione@rossi-impianti.example"; + r.Contacts.Add(new PartyContact { Name = "Mario Rossi", Role = "Titolare", Mobile = "333 5550101", Email = "mario@rossi-impianti.example", IsDefault = true }); + r.Contacts.Add(new PartyContact { Name = "Anna Ferri", Role = "Amministrazione", Phone = "011 5550102", Email = "amministrazione@rossi-impianti.example" }); + r.Addresses.Add(new PartyAddress { Kind = PartyAddressKind.Site, Name = "Cantiere Lingotto", Address = "Via Ventimiglia", StreetNumber = "88", PostalCode = "10126", City = "Torino", Province = "TO", IsDefault = true }); + r.BankAccounts.Add(new PartyBankAccount { Iban = Ibans[0], BankCode = "01234", BranchCode = "10100", IsDefault = true }); + r.Sales.Discount1 = 5m; + r.Sales.CreditLimit = 30000m; + r.Sales.SendDocuments = DocumentDelivery.Email; + r.Sales.DocumentsEmail = "amministrazione@rossi-impianti.example"; + }), + Customer("Bianchi & Figli S.n.c.", SubjectType.Company, VatNumbers[1], "Corso Langhe", "5", "12051", "Alba", "CN", Term("RB3060FM"), Agent("VERDI"), r => + { + r.Fiscal.RecipientCode = "0000000"; + r.Fiscal.RecipientPec = "bianchiefigli@pec.demo.example"; + r.Party.Pec = "bianchiefigli@pec.demo.example"; + }), + Customer("Comune di Valdora", SubjectType.PublicAdministration, null, "Piazza del Municipio", "1", "12060", "Valdora", "CN", Term("BB30"), null, r => + { + r.Party.TaxCode = AdministrationTaxCode; + r.Fiscal.RecipientCode = "UFX9K2"; + r.Fiscal.SplitPayment = true; + r.Fiscal.Exigibility = "S"; + r.Fiscal.AdministrationReference = "SETT-TECNICO"; + }), + Customer("Ferramenta Gallo", SubjectType.Company, VatNumbers[2], "Corso Alfieri", "210", "14100", "Asti", "AT", Term("RD"), Agent("NERI"), r => + { + r.Fiscal.RecipientCode = "KRRH6B9"; + r.Sales.CreditLimit = 5000m; + r.Sales.Blocked = true; + r.Party.Notes = "Ordini bloccati: fido superato, rientro concordato entro fine mese."; + }), + Customer("Bergwerk Bau GmbH", SubjectType.EuCompany, "U12345678", "Museumstrasse", "12", "6020", "Innsbruck", null, Term("BB30"), Agent("NERI"), r => + { + r.Party.CountryCode = "AT"; + r.Party.Language = "de"; + r.Fiscal.RecipientCode = "XXXXXXX"; + }), + Customer("Esposito Mario", SubjectType.Person, null, "Via Po", "18", "10124", "Torino", "TO", Term("RD"), null, r => + { + r.Party.LastName = "Esposito"; + r.Party.FirstName = "Mario"; + r.Party.TaxCode = Personal(identifiers, "Esposito", "Mario", new DateOnly(1980, 1, 1), PersonSex.Male, "L219"); + r.Party.Email = "mario.esposito@posta.example"; + r.Fiscal.RecipientCode = "0000000"; + r.Party.PrivacyAccepted = true; + }), + Customer("Idrotermica Piemonte S.r.l.", SubjectType.Company, VatNumbers[3], "Via Roma", "44", "12100", "Cuneo", "CN", Term("RB3060FM"), Agent("VERDI"), r => + { + r.Fiscal.RecipientCode = "T04ZHR3"; + r.Fiscal.IntentActive = true; + r.Fiscal.IntentNumber = "14/" + year; + r.Fiscal.IntentDate = new DateOnly(year, 1, 15); + r.Fiscal.IntentProtocol = "26011512345678901-000001"; + r.Fiscal.IntentCeiling = 150000m; + r.Fiscal.IntentFrom = new DateOnly(year, 1, 1); + r.Fiscal.IntentTo = new DateOnly(year, 12, 31); + }), + Customer("Nordic Pipes AS", SubjectType.NonEuCompany, "987654321", "Storgata", "7", "0155", "Oslo", null, Term("RD"), Agent("NERI"), r => + { + r.Party.CountryCode = "NO"; + r.Party.Language = "en"; + r.Fiscal.RecipientCode = "XXXXXXX"; + }), + Customer("Studio Tecnico Ing. Ferrero", SubjectType.FlatRate, VatNumbers[4], "Via Vittorio Emanuele", "3", "12051", "Alba", "CN", Term("BB30"), null, r => + { + r.Fiscal.RecipientCode = "USAL8PV"; + r.Fiscal.StampDutyCharged = true; + }), + Customer("Edilizia Moderna S.p.A.", SubjectType.Company, VatNumbers[5], "Viale Monza", "250", "20126", "Milano", "MI", Term("RB3060FM"), Agent("BIANCO"), r => + { + r.Party.IsAlsoSupplier = true; + r.Fiscal.RecipientCode = "W7YVJK9"; + r.Purchase.PaymentTermId = Term("BB30FM"); + r.Sales.Discount1 = 10m; + r.Sales.Discount2 = 3m; + }), + Customer("Termoidraulica Sacco", SubjectType.Company, VatNumbers[6], "Via Cavour", "9", "12042", "Bra", "CN", Term("RD"), Agent("NERI"), r => + { + r.Fiscal.RecipientCode = "SUBM70N"; + r.Party.Disabled = true; + r.Party.Notes = "Attività cessata."; + }), + Customer("Hotel Belvedere S.r.l.", SubjectType.Company, VatNumbers[7], "Passeggiata Cadorna", "15", "17021", "Alassio", "SV", Term("BB30FM"), Agent("BIANCO"), r => + { + r.Fiscal.RecipientCode = "5RUO82D"; + r.Contacts.Add(new PartyContact { Name = "Giulia Marino", Role = "Direzione", Phone = "0182 555010", IsDefault = true }); + }), + Supplier("Metalli Nord S.p.A.", VatNumbers[8], "Via Industriale", "40", "25125", "Brescia", "BS", Term("RB60FM"), r => + { + r.Purchase.LeadTimeDays = 10; + r.Purchase.MinimumOrder = 500m; + r.Purchase.OrdersEmail = "ordini@metalli-nord.example"; + r.BankAccounts.Add(new PartyBankAccount { Iban = Ibans[1], BankCode = "05678", BranchCode = "22000", IsDefault = true }); + }), + Supplier("Plastica Sud S.r.l.", VatNumbers[9], "Via Appia", "301", "81100", "Caserta", "CE", Term("BB30FM"), r => r.Purchase.LeadTimeDays = 15), + Supplier("Studio Rag. Neri Paola", VatNumbers[10], "Via Vittorio Veneto", "21", "12100", "Cuneo", "CN", Term("RD"), r => + { + r.Fiscal.Withholding = true; + r.Fiscal.WithholdingRate = 20m; + r.Fiscal.WithholdingReason = "A"; + r.Fiscal.PensionFund = "TC04"; + r.Fiscal.PensionFundRate = 4m; + r.BankAccounts.Add(new PartyBankAccount { Iban = Ibans[2], BankCode = "09876", BranchCode = "45600", IsDefault = true }); + }), + Supplier("Agenzia Commerciale Bruno", VatNumbers[11], "Corso Francia", "77", "10138", "Torino", "TO", Term("BB30FM"), r => + { + r.Fiscal.Withholding = true; + r.Fiscal.WithholdingRate = 23m; + r.Fiscal.WithholdingReason = "R"; + r.Fiscal.Enasarco = true; + }), + Supplier("Elektro Werke Süd GmbH", "123456789", "Industriestrasse", "5", "80331", "München", null, Term("BB30"), r => + { + r.Party.SubjectType = SubjectType.EuCompany; + r.Party.CountryCode = "DE"; + r.Party.Language = "de"; + }), + Contact(PartyKind.Prospect, "Caseificio Valle Stura S.r.l.", VatNumbers[12], "12014", "Demonte", "CN", Agent("VERDI")), + Contact(PartyKind.Prospect, "Agriturismo Le Vigne", VatNumbers[13], "12060", "Barolo", "CN", Agent("BIANCO")), + Contact(PartyKind.Lead, "Fontana Marco (fiera di Bologna)", null, null, null, null, Agent("NERI")), + Contact(PartyKind.Lead, "Cantina Sociale del Roero", null, "12043", "Canale", "CN", null), + }; + + foreach (var record in seeds) + { + record.Sales.PriceListId ??= record.Party.IsCustomer ? priceList : null; + await InsertAsync(uow, record, rules[record.Party.Kind], context.Today, cancellationToken).ConfigureAwait(false); + context.Count("parties"); + } + } + + private static PartyRecord Customer(string name, SubjectType subject, string? vat, string address, string number, string postalCode, string city, string? province, + long? paymentTermId, long? salespersonId, Action more) + { + var record = New(PartyKind.Customer, name, subject, vat, postalCode, city, province, salespersonId); + record.Party.Address = address; + record.Party.StreetNumber = number; + record.Sales.PaymentTermId = paymentTermId; + more(record); + return record; + } + + private static PartyRecord Supplier(string name, string vat, string address, string number, string postalCode, string city, string? province, long? paymentTermId, + Action more) + { + var record = New(PartyKind.Supplier, name, SubjectType.Company, vat, postalCode, city, province, null); + record.Party.Address = address; + record.Party.StreetNumber = number; + record.Purchase.PaymentTermId = paymentTermId; + more(record); + return record; + } + + private static PartyRecord Contact(PartyKind kind, string name, string? vat, string? postalCode, string? city, string? province, long? salespersonId) => + New(kind, name, SubjectType.Company, vat, postalCode, city, province, salespersonId); + + private static PartyRecord New(PartyKind kind, string name, SubjectType subject, string? vat, string? postalCode, string? city, string? province, long? salespersonId) => new() + { + Party = new Party + { + Kind = kind, Name = name, SubjectType = subject, VatNumber = vat, PostalCode = postalCode, City = city, Province = province, SalespersonId = salespersonId, + CategoryId = null, PrivacyAccepted = kind is PartyKind.Customer or PartyKind.Supplier, IsDemo = true, + }, + }; + + private static string? Personal(ITaxIdentifierRules? rules, string surname, string name, DateOnly birth, PersonSex sex, string place) => + rules?.ComputePersonalTaxCode(new PersonalTaxCodeData(surname, name, birth, sex, place)); + + private static async Task InsertAsync(IUnitOfWork uow, PartyRecord record, CodeRule rule, DateOnly today, CancellationToken cancellationToken) + { + var parties = uow.Repository(); + var party = record.Party; + party.Code = await CodeRuleService.AssignAsync( + uow, rule, today, null, + async (code, ct) => await parties.CountAsync(Query.For().Where(p => p.Code == code), ct).ConfigureAwait(false) > 0, + cancellationToken).ConfigureAwait(false); + party.Id = await parties.InsertAsync(party, cancellationToken).ConfigureAwait(false); + if (party.IsCustomer) + { + record.Sales.PartyId = party.Id; + await uow.Repository().InsertAsync(record.Sales, cancellationToken).ConfigureAwait(false); + } + + if (party.IsSupplier) + { + record.Purchase.PartyId = party.Id; + await uow.Repository().InsertAsync(record.Purchase, cancellationToken).ConfigureAwait(false); + } + + record.Fiscal.PartyId = party.Id; + await uow.Repository().InsertAsync(record.Fiscal, cancellationToken).ConfigureAwait(false); + foreach (var address in record.Addresses) + { + address.PartyId = party.Id; + address.CountryCode = address.CountryCode.Length == 0 ? party.CountryCode : address.CountryCode; + await uow.Repository().InsertAsync(address, cancellationToken).ConfigureAwait(false); + } + + foreach (var contact in record.Contacts) + { + contact.PartyId = party.Id; + await uow.Repository().InsertAsync(contact, cancellationToken).ConfigureAwait(false); + } + + foreach (var account in record.BankAccounts) + { + account.PartyId = party.Id; + await uow.Repository().InsertAsync(account, cancellationToken).ConfigureAwait(false); + } + } +} diff --git a/src/Khaemhat.Application/Seeding/Seeding.cs b/src/Khaemhat.Application/Seeding/Seeding.cs index 661a8bb..7550e37 100644 --- a/src/Khaemhat.Application/Seeding/Seeding.cs +++ b/src/Khaemhat.Application/Seeding/Seeding.cs @@ -207,6 +207,12 @@ public sealed partial class SeedRunner : ICompanySeeder { await RunAsync(companyCode, SeedKind.Base, cancellationToken).ConfigureAwait(false); } + + // The demo seeders fill only a company without data of their own (each checks its tables). + if (context.Demo) + { + await RunAsync(companyCode, SeedKind.Demo, cancellationToken).ConfigureAwait(false); + } } /// The button Aggiorna tabelle di base: runs the base seeders for a company. diff --git a/src/Khaemhat.Core/Parties/Parties.cs b/src/Khaemhat.Core/Parties/Parties.cs new file mode 100644 index 0000000..63a7e82 --- /dev/null +++ b/src/Khaemhat.Core/Parties/Parties.cs @@ -0,0 +1,475 @@ +using Khaemhat.Core.Entities; + +namespace Khaemhat.Core.Parties; + +/// What a party is to the company (SPEC §11.2): the archive and the code mask follow from it. +public enum PartyKind +{ + /// A customer (it may also be a supplier). + Customer = 0, + + /// A supplier that is not a customer. + Supplier = 1, + + /// A qualified potential customer, without fiscal documents. + Prospect = 2, + + /// A commercial contact still to qualify (CRM). + Lead = 3, +} + +/// The kind of subject: it decides the checks and the values proposed (SDI code, split payment, VAT number). +public enum SubjectType +{ + /// A domestic business. + Company = 0, + + /// A private person (consumer). + Person = 1, + + /// A public administration (split payment, office code of 6 characters). + PublicAdministration = 2, + + /// A business in another EU member state (VIES). + EuCompany = 3, + + /// A business outside the EU. + NonEuCompany = 4, + + /// A domestic business under the flat-rate scheme (no VAT charged, stamp duty). + FlatRate = 5, +} + +/// The outcome of the last check of the VAT number on VIES, saved on the party. +public enum VatCheckStatus +{ + /// Not checked. + None = 0, + + /// Registered for intra-EU operations. + Valid = 1, + + /// Not registered. + Invalid = 2, + + /// The service could not answer; to repeat. + Unavailable = 3, +} + +/// How the documents are sent to a customer. +public enum DocumentDelivery +{ + /// Not sent: printed or downloaded. + None = 0, + + /// By e-mail. + Email = 1, + + /// By certified e-mail (PEC). + Pec = 2, +} + +/// What an address of a party is used for. +public enum PartyAddressKind +{ + /// Delivery address (destination of delivery notes). + Delivery = 0, + + /// Address for invoices, when different from the registered office. + Billing = 1, + + /// A building site or a branch. + Site = 2, + + /// Another address. + Other = 3, +} + +/// +/// A party (SPEC §11.2, wiki Anagrafiche): customer, supplier, prospect or lead, registered once. The code follows +/// the mask of its kind (ADR 0027); converting a lead or prospect into a customer gives it a customer code and keeps the +/// old one in . +/// +public sealed class Party : Entity, IDemoMarkable +{ + /// The code, unique among the parties. + public string Code { get; set; } = string.Empty; + + /// The code it had before a conversion. + public string? PreviousCode { get; set; } + + /// What the party is. + public PartyKind Kind { get; set; } + + /// A customer that also sells to the company. + public bool IsAlsoSupplier { get; set; } + + /// The kind of subject. + public SubjectType SubjectType { get; set; } + + /// The business name, or "last name first name" for a person. + public string Name { get; set; } = string.Empty; + + /// The first name of a person. + public string? FirstName { get; set; } + + /// The last name of a person. + public string? LastName { get; set; } + + /// The name on fiscal documents, when different. + public string? FiscalName { get; set; } + + /// The VAT number, compact, without the country prefix. + public string? VatNumber { get; set; } + + /// The tax code. + public string? TaxCode { get; set; } + + /// The registration in the companies register (REA). + public string? Rea { get; set; } + + /// The category (party_categories). + public long? CategoryId { get; set; } + + /// Street of the registered office. + public string? Address { get; set; } + + /// Street number. + public string? StreetNumber { get; set; } + + /// Postal code. + public string? PostalCode { get; set; } + + /// Municipality or city. + public string? City { get; set; } + + /// Province abbreviation (or region abroad). + public string? Province { get; set; } + + /// Country (ISO 3166-1 alpha-2). + public string CountryCode { get; set; } = "IT"; + + /// Phone. + public string? Phone { get; set; } + + /// E-mail. + public string? Email { get; set; } + + /// Certified e-mail (PEC). + public string? Pec { get; set; } + + /// Web site. + public string? Website { get; set; } + + /// The salesperson (salespeople). + public long? SalespersonId { get; set; } + + /// Language of the documents (ISO 639-1). + public string Language { get; set; } = "it"; + + /// Currency of the documents (ISO 4217). + public string CurrencyCode { get; set; } = "EUR"; + + /// Start of the relationship. + public DateOnly? Since { get; set; } + + /// Privacy notice accepted. + public bool PrivacyAccepted { get; set; } + + /// Consent to marketing. + public bool Marketing { get; set; } + + /// Notes. + public string? Notes { get; set; } + + /// Last VIES outcome. + public VatCheckStatus VatCheck { get; set; } + + /// When VIES answered (or failed), UTC. + public DateTime? VatCheckedAt { get; set; } + + /// The customer sub-account of the ledger, created at the first posting (M7). + public string? CustomerAccountCode { get; set; } + + /// The supplier sub-account of the ledger, created at the first posting (M7). + public string? SupplierAccountCode { get; set; } + + /// Hidden from new documents and default searches; kept with its documents. + public bool Disabled { get; set; } + + /// + public bool IsDemo { get; set; } + + /// Whether the party is a customer (also a supplier that is a customer). + public bool IsCustomer => Kind == PartyKind.Customer; + + /// Whether the party is a supplier, alone or also a customer. + public bool IsSupplier => Kind == PartyKind.Supplier || (Kind == PartyKind.Customer && IsAlsoSupplier); +} + +/// An address of a party besides the registered office. +public sealed class PartyAddress : Entity +{ + /// The party. + public long PartyId { get; set; } + + /// What it is used for. + public PartyAddressKind Kind { get; set; } + + /// The name shown on documents (site, branch). + public string Name { get; set; } = string.Empty; + + /// Street. + public string? Address { get; set; } + + /// Street number. + public string? StreetNumber { get; set; } + + /// Postal code. + public string? PostalCode { get; set; } + + /// City. + public string? City { get; set; } + + /// Province. + public string? Province { get; set; } + + /// Country (ISO 3166-1 alpha-2). + public string CountryCode { get; set; } = "IT"; + + /// The address proposed first for its kind. + public bool IsDefault { get; set; } + + /// Notes (opening hours, how to reach it). + public string? Notes { get; set; } +} + +/// A contact person of a party. +public sealed class PartyContact : Entity +{ + /// The party. + public long PartyId { get; set; } + + /// Name and surname. + public string Name { get; set; } = string.Empty; + + /// Role (purchasing, administration...). + public string? Role { get; set; } + + /// Phone. + public string? Phone { get; set; } + + /// Mobile phone. + public string? Mobile { get; set; } + + /// E-mail. + public string? Email { get; set; } + + /// The main contact. + public bool IsDefault { get; set; } + + /// Notes. + public string? Notes { get; set; } +} + +/// A bank account of a party: the bank of its RiBa, or where the company pays it. +public sealed class PartyBankAccount : Entity +{ + /// The party. + public long PartyId { get; set; } + + /// The IBAN, compact. + public string Iban { get; set; } = string.Empty; + + /// The BIC. + public string? Bic { get; set; } + + /// The bank. + public string? BankName { get; set; } + + /// The national bank code (ABI), read from the IBAN. + public string? BankCode { get; set; } + + /// The branch code (CAB), read from the IBAN. + public string? BranchCode { get; set; } + + /// The account proposed on documents. + public bool IsDefault { get; set; } +} + +/// The sales terms of a customer, proposed on its documents (M5). +public sealed class PartySalesTerms : Entity +{ + /// The party (one row per party). + public long PartyId { get; set; } + + /// The price list (price_lists). + public long? PriceListId { get; set; } + + /// First discount, percent. + public decimal? Discount1 { get; set; } + + /// Second discount, percent. + public decimal? Discount2 { get; set; } + + /// The payment terms (payment_terms). + public long? PaymentTermId { get; set; } + + /// The account of the company where the customer pays (bank_accounts). + public long? CompanyBankAccountId { get; set; } + + /// The carrier (carriers). + public long? CarrierId { get; set; } + + /// The shipping terms (shipping_terms). + public long? ShippingTermId { get; set; } + + /// The warehouse goods leave from (warehouses). + public long? WarehouseId { get; set; } + + /// The credit limit: the most the customer may owe. + public decimal? CreditLimit { get; set; } + + /// Orders and deliveries are blocked. + public bool Blocked { get; set; } + + /// Delivery notes are grouped into one deferred invoice. + public bool GroupDeliveryNotes { get; set; } = true; + + /// The day of the month the deferred invoices are issued, if fixed. + public int? InvoiceDay { get; set; } + + /// How the documents are sent. + public DocumentDelivery SendDocuments { get; set; } + + /// Where the documents are sent, when not the main e-mail or PEC. + public string? DocumentsEmail { get; set; } +} + +/// The purchase terms of a supplier, proposed on its orders (M6). +public sealed class PartyPurchaseTerms : Entity +{ + /// The party (one row per party). + public long PartyId { get; set; } + + /// The payment terms (payment_terms). + public long? PaymentTermId { get; set; } + + /// Days between order and delivery. + public int? LeadTimeDays { get; set; } + + /// The smallest order accepted. + public decimal? MinimumOrder { get; set; } + + /// Discount, percent. + public decimal? Discount { get; set; } + + /// The shipping terms (shipping_terms). + public long? ShippingTermId { get; set; } + + /// The VAT register of the purchases (M7). + public string? VatRegisterCode { get; set; } + + /// The cost account proposed (M7). + public string? CostAccountCode { get; set; } + + /// The e-mail for the orders. + public string? OrdersEmail { get; set; } +} + +/// +/// The fiscal data of a party (mockup 015, 016): e-invoicing, VAT regime, withholding and contributions, the declaration +/// of intent of a habitual exporter and the identifiers. +/// +public sealed class PartyFiscal : Entity +{ + /// The party (one row per party). + public long PartyId { get; set; } + + /// The SDI recipient code (7 characters, 6 for a public administration). + public string? RecipientCode { get; set; } + + /// The PEC the e-invoices go to, without a recipient code. + public string? RecipientPec { get; set; } + + /// The reference of the administration (public administrations). + public string? AdministrationReference { get; set; } + + /// A courtesy PDF goes with the e-invoice. + public bool AttachPdf { get; set; } = true; + + /// A copy is sent by e-mail when the invoice is issued. + public bool SendCopy { get; set; } + + /// Split payment (art. 17-ter DPR 633/72). + public bool SplitPayment { get; set; } + + /// Reverse charge by default. + public bool ReverseCharge { get; set; } + + /// The VAT code proposed (tax_codes). + public long? TaxCodeId { get; set; } + + /// VAT exigibility: I immediate, D deferred, S split payment. + public string? Exigibility { get; set; } + + /// The stamp duty is charged to the customer. + public bool StampDutyCharged { get; set; } = true; + + /// Subject to withholding tax (professionals). + public bool Withholding { get; set; } + + /// Withholding rate, percent. + public decimal? WithholdingRate { get; set; } + + /// Withholding reason of the e-invoice (A, M, Q...). + public string? WithholdingReason { get; set; } + + /// Pension fund of the e-invoice (TC01-TC22). + public string? PensionFund { get; set; } + + /// Pension fund rate, percent. + public decimal? PensionFundRate { get; set; } + + /// Agent subject to ENASARCO. + public bool Enasarco { get; set; } + + /// Declaration of intent active. + public bool IntentActive { get; set; } + + /// Number of the declaration. + public string? IntentNumber { get; set; } + + /// Date of the declaration. + public DateOnly? IntentDate { get; set; } + + /// Protocol of the revenue agency. + public string? IntentProtocol { get; set; } + + /// The non-taxable VAT code used under the declaration (tax_codes, nature N3.5). + public long? IntentTaxCodeId { get; set; } + + /// The ceiling of the declaration. + public decimal? IntentCeiling { get; set; } + + /// The amount already invoiced under the declaration (updated by the invoices, M5). + public decimal IntentUsed { get; set; } + + /// The declaration is valid from. + public DateOnly? IntentFrom { get; set; } + + /// The declaration is valid until. + public DateOnly? IntentTo { get; set; } + + /// Global location number. + public string? Gln { get; set; } + + /// Economic operators registration and identification number (customs). + public string? Eori { get; set; } + + /// The code of the company at the party. + public string? OurCode { get; set; } + + /// What remains of the ceiling of the declaration. + public decimal? IntentRemaining => IntentCeiling is { } ceiling ? ceiling - IntentUsed : null; +} diff --git a/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261112_001_CreateParties.cs b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261112_001_CreateParties.cs new file mode 100644 index 0000000..3c2181b --- /dev/null +++ b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261112_001_CreateParties.cs @@ -0,0 +1,203 @@ +using Khaemhat.Data.Migrations; +using Khaemhat.Data.Schema; + +namespace Khaemhat.Data.CompanyDatabase.Migrations; + +/// +/// Parties and their details (SPEC §11.2, issue #41): addresses, contacts, bank accounts, sales and purchase terms and +/// fiscal data. The details go with the party; the company tables they point to cannot be deleted while used. +/// +[Migration(20261112_001, "create_parties")] +public sealed class M20261112_001_CreateParties : IMigration +{ + /// + public void Up(ISchemaBuilder schema) + { + ArgumentNullException.ThrowIfNull(schema); + schema.CreateTable("parties", t => + { + t.Id(); + t.String("code", 30).NotNull(); + t.String("previous_code", 30); + t.String("kind", 40).NotNull(); + t.Bool("is_also_supplier").NotNull().Default(false); + t.String("subject_type", 40).NotNull(); + t.String("name", 200).NotNull(); + t.String("first_name", 80); + t.String("last_name", 80); + t.String("fiscal_name", 200); + t.String("vat_number", 30); + t.String("tax_code", 30); + t.String("rea", 20); + t.Int64("category_id"); + t.String("address", 200); + t.String("street_number", 20); + t.String("postal_code", 10); + t.String("city", 100); + t.String("province", 10); + t.String("country_code", 2).NotNull(); + t.String("phone", 40); + t.String("email", 200); + t.String("pec", 200); + t.String("website", 200); + t.Int64("salesperson_id"); + t.String("language", 5).NotNull(); + t.String("currency_code", 3).NotNull(); + t.Date("since"); + t.Bool("privacy_accepted").NotNull().Default(false); + t.Bool("marketing").NotNull().Default(false); + t.Text("notes"); + t.String("vat_check", 40).NotNull(); + t.DateTimeUtc("vat_checked_at"); + t.String("customer_account_code", 20); + t.String("supplier_account_code", 20); + t.Bool("disabled").NotNull().Default(false); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_parties_code", "code"); + t.Index("ix_parties_name", "name"); + t.Index("ix_parties_vat_number", "vat_number"); + t.Index("ix_parties_tax_code", "tax_code"); + t.Index("ix_parties_kind", "kind"); + t.ForeignKey("fk_parties_category", "category_id", "party_categories", ReferentialAction.Restrict); + t.ForeignKey("fk_parties_salesperson", "salesperson_id", "salespeople", ReferentialAction.Restrict); + }); + + schema.CreateTable("party_addresses", t => + { + t.Id(); + t.Int64("party_id").NotNull(); + t.String("kind", 40).NotNull(); + t.String("name", 200).NotNull(); + t.String("address", 200); + t.String("street_number", 20); + t.String("postal_code", 10); + t.String("city", 100); + t.String("province", 10); + t.String("country_code", 2).NotNull(); + t.Bool("is_default").NotNull().Default(false); + t.Text("notes"); + t.AuditColumns(); + t.Index("ix_party_addresses_party", "party_id"); + t.ForeignKey("fk_party_addresses_party", "party_id", "parties", ReferentialAction.Cascade); + }); + + schema.CreateTable("party_contacts", t => + { + t.Id(); + t.Int64("party_id").NotNull(); + t.String("name", 120).NotNull(); + t.String("role", 80); + t.String("phone", 40); + t.String("mobile", 40); + t.String("email", 200); + t.Bool("is_default").NotNull().Default(false); + t.Text("notes"); + t.AuditColumns(); + t.Index("ix_party_contacts_party", "party_id"); + t.ForeignKey("fk_party_contacts_party", "party_id", "parties", ReferentialAction.Cascade); + }); + + schema.CreateTable("party_bank_accounts", t => + { + t.Id(); + t.Int64("party_id").NotNull(); + t.String("iban", 34).NotNull(); + t.String("bic", 11); + t.String("bank_name", 100); + t.String("bank_code", 10); + t.String("branch_code", 10); + t.Bool("is_default").NotNull().Default(false); + t.AuditColumns(); + t.Index("ix_party_bank_accounts_party", "party_id"); + t.ForeignKey("fk_party_bank_accounts_party", "party_id", "parties", ReferentialAction.Cascade); + }); + + schema.CreateTable("party_sales_terms", t => + { + t.Id(); + t.Int64("party_id").NotNull(); + t.Int64("price_list_id"); + t.Decimal("discount1"); + t.Decimal("discount2"); + t.Int64("payment_term_id"); + t.Int64("company_bank_account_id"); + t.Int64("carrier_id"); + t.Int64("shipping_term_id"); + t.Int64("warehouse_id"); + t.Decimal("credit_limit"); + t.Bool("blocked").NotNull().Default(false); + t.Bool("group_delivery_notes").NotNull().Default(true); + t.Int32("invoice_day"); + t.String("send_documents", 40).NotNull(); + t.String("documents_email", 200); + t.AuditColumns(); + t.Unique("ux_party_sales_terms_party", "party_id"); + t.ForeignKey("fk_party_sales_terms_party", "party_id", "parties", ReferentialAction.Cascade); + t.ForeignKey("fk_party_sales_terms_price_list", "price_list_id", "price_lists", ReferentialAction.Restrict); + t.ForeignKey("fk_party_sales_terms_payment_term", "payment_term_id", "payment_terms", ReferentialAction.Restrict); + t.ForeignKey("fk_party_sales_terms_bank_account", "company_bank_account_id", "bank_accounts", ReferentialAction.Restrict); + t.ForeignKey("fk_party_sales_terms_carrier", "carrier_id", "carriers", ReferentialAction.Restrict); + t.ForeignKey("fk_party_sales_terms_shipping_term", "shipping_term_id", "shipping_terms", ReferentialAction.Restrict); + t.ForeignKey("fk_party_sales_terms_warehouse", "warehouse_id", "warehouses", ReferentialAction.Restrict); + }); + + schema.CreateTable("party_purchase_terms", t => + { + t.Id(); + t.Int64("party_id").NotNull(); + t.Int64("payment_term_id"); + t.Int32("lead_time_days"); + t.Decimal("minimum_order"); + t.Decimal("discount"); + t.Int64("shipping_term_id"); + t.String("vat_register_code", 10); + t.String("cost_account_code", 20); + t.String("orders_email", 200); + t.AuditColumns(); + t.Unique("ux_party_purchase_terms_party", "party_id"); + t.ForeignKey("fk_party_purchase_terms_party", "party_id", "parties", ReferentialAction.Cascade); + t.ForeignKey("fk_party_purchase_terms_payment_term", "payment_term_id", "payment_terms", ReferentialAction.Restrict); + t.ForeignKey("fk_party_purchase_terms_shipping_term", "shipping_term_id", "shipping_terms", ReferentialAction.Restrict); + }); + + schema.CreateTable("party_fiscal", t => + { + t.Id(); + t.Int64("party_id").NotNull(); + t.String("recipient_code", 7); + t.String("recipient_pec", 200); + t.String("administration_reference", 20); + t.Bool("attach_pdf").NotNull().Default(true); + t.Bool("send_copy").NotNull().Default(false); + t.Bool("split_payment").NotNull().Default(false); + t.Bool("reverse_charge").NotNull().Default(false); + t.Int64("tax_code_id"); + t.String("exigibility", 1); + t.Bool("stamp_duty_charged").NotNull().Default(true); + t.Bool("withholding").NotNull().Default(false); + t.Decimal("withholding_rate"); + t.String("withholding_reason", 4); + t.String("pension_fund", 4); + t.Decimal("pension_fund_rate"); + t.Bool("enasarco").NotNull().Default(false); + t.Bool("intent_active").NotNull().Default(false); + t.String("intent_number", 40); + t.Date("intent_date"); + t.String("intent_protocol", 40); + t.Int64("intent_tax_code_id"); + t.Decimal("intent_ceiling"); + t.Decimal("intent_used").NotNull().Default(0m); + t.Date("intent_from"); + t.Date("intent_to"); + t.String("gln", 13); + t.String("eori", 17); + t.String("our_code", 40); + t.AuditColumns(); + t.Unique("ux_party_fiscal_party", "party_id"); + t.ForeignKey("fk_party_fiscal_party", "party_id", "parties", ReferentialAction.Cascade); + t.ForeignKey("fk_party_fiscal_tax_code", "tax_code_id", "tax_codes", ReferentialAction.Restrict); + t.ForeignKey("fk_party_fiscal_intent_tax_code", "intent_tax_code_id", "tax_codes", ReferentialAction.Restrict); + }); + } +} diff --git a/src/Khaemhat.Data/CompanyDatabase/PartyMaps.cs b/src/Khaemhat.Data/CompanyDatabase/PartyMaps.cs new file mode 100644 index 0000000..a3808d5 --- /dev/null +++ b/src/Khaemhat.Data/CompanyDatabase/PartyMaps.cs @@ -0,0 +1,129 @@ +using Khaemhat.Core.Parties; +using Khaemhat.Data.Mapping; + +namespace Khaemhat.Data.CompanyDatabase; + +/// Map of to parties. +public sealed class PartyMap : EntityMap +{ + /// Creates the map. + public PartyMap() + { + ToTable("parties"); + Map(x => x.Code).MaxLength(30); + Map(x => x.PreviousCode).MaxLength(30); + Map(x => x.Name).MaxLength(200); + Map(x => x.FirstName).MaxLength(80); + Map(x => x.LastName).MaxLength(80); + Map(x => x.FiscalName).MaxLength(200); + Map(x => x.VatNumber).MaxLength(30); + Map(x => x.TaxCode).MaxLength(30); + Map(x => x.Rea).MaxLength(20); + Map(x => x.Address).MaxLength(200); + Map(x => x.StreetNumber).MaxLength(20); + Map(x => x.PostalCode).MaxLength(10); + Map(x => x.City).MaxLength(100); + Map(x => x.Province).MaxLength(10); + Map(x => x.CountryCode).MaxLength(2); + Map(x => x.Phone).MaxLength(40); + Map(x => x.Email).MaxLength(200); + Map(x => x.Pec).MaxLength(200); + Map(x => x.Website).MaxLength(200); + Map(x => x.Language).MaxLength(5); + Map(x => x.CurrencyCode).MaxLength(3); + Map(x => x.CustomerAccountCode).MaxLength(20); + Map(x => x.SupplierAccountCode).MaxLength(20); + } +} + +/// Map of to party_addresses. +public sealed class PartyAddressMap : EntityMap +{ + /// Creates the map. + public PartyAddressMap() + { + ToTable("party_addresses"); + Map(x => x.Name).MaxLength(200); + Map(x => x.Address).MaxLength(200); + Map(x => x.StreetNumber).MaxLength(20); + Map(x => x.PostalCode).MaxLength(10); + Map(x => x.City).MaxLength(100); + Map(x => x.Province).MaxLength(10); + Map(x => x.CountryCode).MaxLength(2); + } +} + +/// Map of to party_contacts. +public sealed class PartyContactMap : EntityMap +{ + /// Creates the map. + public PartyContactMap() + { + ToTable("party_contacts"); + Map(x => x.Name).MaxLength(120); + Map(x => x.Role).MaxLength(80); + Map(x => x.Phone).MaxLength(40); + Map(x => x.Mobile).MaxLength(40); + Map(x => x.Email).MaxLength(200); + } +} + +/// Map of to party_bank_accounts. +public sealed class PartyBankAccountMap : EntityMap +{ + /// Creates the map. + public PartyBankAccountMap() + { + ToTable("party_bank_accounts"); + Map(x => x.Iban).MaxLength(34); + Map(x => x.Bic).MaxLength(11); + Map(x => x.BankName).MaxLength(100); + Map(x => x.BankCode).MaxLength(10); + Map(x => x.BranchCode).MaxLength(10); + } +} + +/// Map of to party_sales_terms. +public sealed class PartySalesTermsMap : EntityMap +{ + /// Creates the map. + public PartySalesTermsMap() + { + ToTable("party_sales_terms"); + Map(x => x.DocumentsEmail).MaxLength(200); + } +} + +/// Map of to party_purchase_terms. +public sealed class PartyPurchaseTermsMap : EntityMap +{ + /// Creates the map. + public PartyPurchaseTermsMap() + { + ToTable("party_purchase_terms"); + Map(x => x.VatRegisterCode).MaxLength(10); + Map(x => x.CostAccountCode).MaxLength(20); + Map(x => x.OrdersEmail).MaxLength(200); + } +} + +/// Map of to party_fiscal. +public sealed class PartyFiscalMap : EntityMap +{ + /// Creates the map. + public PartyFiscalMap() + { + ToTable("party_fiscal"); + Map(x => x.RecipientCode).MaxLength(7); + Map(x => x.RecipientPec).MaxLength(200); + Map(x => x.AdministrationReference).MaxLength(20); + Map(x => x.Exigibility).MaxLength(1); + Map(x => x.WithholdingReason).MaxLength(4); + Map(x => x.PensionFund).MaxLength(4); + Map(x => x.IntentNumber).MaxLength(40); + Map(x => x.IntentProtocol).MaxLength(40); + Map(x => x.Gln).MaxLength(13); + Map(x => x.Eori).MaxLength(17); + Map(x => x.OurCode).MaxLength(40); + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Parties/DetailFooter.razor b/src/Khaemhat.Web/Components/Pages/Parties/DetailFooter.razor new file mode 100644 index 0000000..7cc62a0 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Parties/DetailFooter.razor @@ -0,0 +1,30 @@ +@* The foot of a list of details of a party (addresses, contacts, bank accounts): what to say when it is empty and the + button that adds one. *@ +
+ @if (Empty is not null) + { + @Empty + } + @if (CanAdd) + { + + } +
+ +@code { + /// The text of an empty list, or . + [Parameter] + public string? Empty { get; set; } + + /// Whether a detail can be added. + [Parameter] + public bool CanAdd { get; set; } + + /// The text of the button. + [Parameter] + public string AddText { get; set; } = string.Empty; + + /// Adds a detail. + [Parameter] + public EventCallback OnAdd { get; set; } +} diff --git a/src/Khaemhat.Web/Components/Pages/Parties/PartiesPage.razor b/src/Khaemhat.Web/Components/Pages/Parties/PartiesPage.razor new file mode 100644 index 0000000..c17ae83 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Parties/PartiesPage.razor @@ -0,0 +1,165 @@ +@page "/anagrafiche/clienti" +@page "/anagrafiche/fornitori" +@page "/anagrafiche/contatti" +@attribute [Authorize] +@using Khaemhat.Application.Parties +@using Khaemhat.Application.Tables +@using Khaemhat.Core.Parties +@using Khaemhat.Web.Parties +@inject ShellSession Session +@inject PartyService Parties +@inject TableService Tables +@inject ToastService Toasts +@inject NavigationManager Navigation + +@* The radar of the parties (SPEC §11.2, mockups 012 and 013): customers, suppliers, or prospects and leads. Search on + code, name, VAT number, tax code and city; filters for kind, subject and state; selection to disable or enable; Enter + or double click opens the record. Turnover and overdue arrive with sales (M5) and the schedule (M9). *@ + + +@if (!_loaded) +{ +

@T["Common.Loading"]

+} +else if (Session.Company is null) +{ +

@T["Parties.NoCompany"]

+} +else if (!Session.Permissions.Allows(PartyService.ReadPermission)) +{ +
+ +

@T["Pages.AccessDenied.Title"]

+

@T["Pages.AccessDenied.Lead"]

+
+} +else +{ + + + @if (CanWrite) + { + + @if (_archive == PartyArchive.Contacts) + { + + } + + + } + + +} + +@code { + private PartyArchive _archive; + private PartyLookups _lookups = PartyLookups.Empty; + private KhRadar? _radar; + private List _selected = []; + private bool _loaded; + private bool _busy; + + private string Title => T["Parties.Archives." + _archive]; + + private bool CanWrite => Session.Permissions.Allows(PartyService.WritePermission); + + private static IReadOnlyList InitialFilters => [ListFilter.Of("disabled", ListFilterOperator.Equals, "false")]; + + private IReadOnlyList> Columns => + [ + new("code", T["Parties.Fields.Code"], r => r.Code) { Kind = KhColumnKind.Code, Width = "110px" }, + new("name", T["Parties.Fields.Name"], r => r.Name), + new("vatNumber", T["Parties.Radar.Identifier"], r => r.Identifier) { Width = "170px" }, + new("city", T["Parties.Radar.City"], r => r.Province is { } p ? r.City + " (" + p + ")" : r.City) { Width = "170px" }, + new("payment", T["Parties.Radar.Payment"], r => PartyScreens.Describe(_lookups.PaymentTerms, r.Terms?.PaymentTermId, full: true)) { Sortable = false, Visible = _archive != PartyArchive.Contacts }, + new("priceList", T["Parties.Radar.PriceList"], r => PartyScreens.Describe(_lookups.PriceLists, r.Terms?.PriceListId)) { Sortable = false, Width = "90px", Visible = _archive == PartyArchive.Customers }, + new("salesperson", T["Parties.Radar.Salesperson"], r => PartyScreens.Describe(_lookups.Salespeople, r.SalespersonId, full: true)) { Width = "120px" }, + new("kind", T["Parties.Radar.Kind"], r => T["Parties.Kinds." + r.Kind]) { Width = "100px", Visible = _archive == PartyArchive.Contacts }, + new("state", T["Parties.Radar.State"], r => StateOf(r).Text) + { + Sortable = false, Width = "130px", + Template = r => @@StateOf(r).Text, + }, + ]; + + private IReadOnlyList QuickFilters => + [ + .. _archive == PartyArchive.Contacts + ? [new KhQuickFilter("kind", T["Parties.Radar.Kind"], + [new(string.Empty, T["Parties.Radar.All"]), new(nameof(PartyKind.Prospect), T["Parties.Kinds.Prospect"]), new(nameof(PartyKind.Lead), T["Parties.Kinds.Lead"])])] + : Array.Empty(), + new("subjectType", T["Parties.Radar.Subject"], + [new(string.Empty, T["Parties.Radar.All"]), .. PartyScreens.Choices(T, "SubjectTypes")]), + new("salesperson", T["Parties.Radar.Salesperson"], [new(string.Empty, T["Parties.Radar.All"]), .. _lookups.Salespeople]), + new("disabled", T["Parties.Radar.State"], + [new(string.Empty, T["Parties.Radar.All"]), new("false", T["Parties.Radar.Active"]), new("true", T["Parties.Radar.Disabled"])]), + ]; + + /// + protected override async Task OnParametersSetAsync() + { + _archive = PartyScreens.ArchiveOf(Navigation.ToBaseRelativePath(Navigation.Uri)); + _selected = []; + await Session.EnsureLoadedAsync(); + if (!_loaded && Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(PartyService.ReadPermission)) + { + _lookups = await PartyLookups.ForRadarAsync(Tables, actor, company); + } + + _loaded = true; + } + + private (string Text, KhTone Tone) StateOf(PartyRow row) => row switch + { + { Disabled: true } => (T["Parties.States.Disabled"], KhTone.Neutral), + { Terms.Blocked: true } => (T["Parties.States.Blocked"], KhTone.Error), + { Terms.SplitPayment: true } => (T["Parties.States.Split"], KhTone.Info), + { SubjectType: SubjectType.EuCompany or SubjectType.NonEuCompany or SubjectType.Person } => (T["Parties.SubjectTypes." + row.SubjectType], KhTone.Info), + { Kind: PartyKind.Customer, IsAlsoSupplier: true } when _archive == PartyArchive.Suppliers => (T["Parties.States.AlsoCustomer"], KhTone.Accent), + { IsAlsoSupplier: true } => (T["Parties.States.AlsoSupplier"], KhTone.Accent), + _ => (T["Parties.States.Active"], KhTone.Ok), + }; + + private Task> ListAsync(ListQuery query, CancellationToken cancellationToken) => + Session.Actor is { } actor && Session.Company?.Code is { } company + ? Parties.ListAsync(actor, company, _archive, query, cancellationToken) + : Task.FromResult(new ListPage([], 0, new Dictionary())); + + private void SetSelection(IReadOnlyCollection keys) => _selected = [.. keys.OfType()]; + + private static string? RowClassOf(PartyRow row) => row.Disabled ? "muted" : null; + + private void Open(PartyRow row) => Navigation.NavigateTo(PartyScreens.RecordUrl(_archive, row.Id)); + + private void New(PartyKind? kind) => Navigation.NavigateTo(PartyScreens.NewUrl(_archive, kind)); + + private async Task SetDisabledAsync(bool disabled) + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _selected.Count == 0) + { + return; + } + + _busy = true; + try + { + var count = await Parties.SetDisabledAsync(actor, company, _selected, disabled); + Toasts.Show(ToastKind.Success, T.Format(disabled ? "Parties.Actions.Disabled" : "Parties.Actions.Enabled", count)); + if (_radar is not null) + { + await _radar.ReloadAsync(); + } + } + finally + { + _busy = false; + } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Parties/PartyPage.razor b/src/Khaemhat.Web/Components/Pages/Parties/PartyPage.razor new file mode 100644 index 0000000..2794be2 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Parties/PartyPage.razor @@ -0,0 +1,939 @@ +@page "/anagrafiche/clienti/nuovo" +@page "/anagrafiche/clienti/{Id:long}" +@page "/anagrafiche/fornitori/nuovo" +@page "/anagrafiche/fornitori/{Id:long}" +@page "/anagrafiche/contatti/nuovo" +@page "/anagrafiche/contatti/{Id:long}" +@attribute [Authorize] +@inherits MasterDataPage +@using Khaemhat.Application.Audit +@using Khaemhat.Application.Parties +@using Khaemhat.Application.Security +@using Khaemhat.Application.Tables +@using Khaemhat.Core.Common +@using Khaemhat.Core.Parties +@using Khaemhat.Fiscal.Abstractions +@using Khaemhat.Infrastructure.Http +@using Khaemhat.Web.Parties +@using Khaemhat.Web.Tables +@inject ShellSession Session +@inject PartyService Parties +@inject TableService Tables +@inject AutoFillService AutoFill +@inject AttachmentService Attachments + +@* The record of a party (SPEC §11.2, mockups 014-016): header with identity and conditions, tabs for main data, + addresses, contacts, terms, fiscal data and e-invoice, banks, notes with attachments, history. The checks are those + of PartyService: errors stop the save and open the tab of the first one, warnings are shown after saving. *@ + + +@if (!_loaded) +{ +

@T["Common.Loading"]

+} +else if (Session.Company is null) +{ +

@T["Parties.NoCompany"]

+} +else if (!Session.Permissions.Allows(PartyService.ReadPermission)) +{ +
+ +

@T["Pages.AccessDenied.Title"]

+

@T["Pages.AccessDenied.Lead"]

+
+} +else if (Record is null) +{ +
+ +

@T["Parties.NotFound"]

+ @T["Parties.Archives." + _archive] +
+} +else +{ + + + + + @T["Parties.SubjectTypes." + P.SubjectType] + @if (P.PreviousCode is { } previous) + { + · @T["Parties.Fields.PreviousCode"] @previous + } + + + @if (P.Disabled) + { + @T["Parties.States.Disabled"] + } + else if (Record.Sales.Blocked) + { + @T["Parties.States.Blocked"] + } + else if (!IsNew) + { + @T["Parties.States.Active"] + } + @if (P.Kind == PartyKind.Customer && P.IsAlsoSupplier) + { + @T["Parties.States.AlsoSupplier"] + } + @if (P.IsDemo) + { + @T["Parties.States.Demo"] + } + @if (IsModified) + { + @T["CompanyTables.Modified"] + } + + + @if (PartyScreens.Describe(_lookups.PaymentTerms, PaymentTermId, full: true) is { } payment) + { + + } + @if (P.IsCustomer && PartyScreens.Describe(_lookups.PriceLists, Record.Sales.PriceListId) is { } list) + { + + } + @if (PartyScreens.Describe(_lookups.Salespeople, P.SalespersonId, full: true) is { } salesperson) + { + + } + @if (P.VatCheck != VatCheckStatus.None) + { + + } + @if (Record.Fiscal.SplitPayment) + { + + } + + + + + + @switch (ActiveTab) + { + case PartyScreens.Tabs.Main: + + + + + @if (P.SubjectType == SubjectType.Person) + { + + + } + + + + + + + @if (P.SubjectType == SubjectType.Person && !IsReadOnly) + { + + + + +
+ +
+
+ } + + + + + + + @if (_places.Count > 1) + { +
+ @T.Format("Parties.Actions.Places", _places.Count) + @foreach (var place in _places) + { + + } +
+ } + +
+ + + + + + + + + + + + + + + @if (P.Kind == PartyKind.Customer) + { + + } + + + break; + + case PartyScreens.Tabs.Addresses: + @for (var i = 0; i < Record.Addresses.Count; i++) + { + var index = i; + var a = Record.Addresses[i]; + + + + + + + + + + + + @if (!IsReadOnly) + { +
+ +
+ } +
+ } + + break; + + case PartyScreens.Tabs.Contacts: + @for (var i = 0; i < Record.Contacts.Count; i++) + { + var index = i; + var c = Record.Contacts[i]; + + + + + + + + + @if (!IsReadOnly) + { +
+ +
+ } +
+ } + + break; + + case PartyScreens.Tabs.Terms: + @if (!P.IsCustomer && !P.IsSupplier) + { +

@T["Parties.NoTerms"]

+ } + @if (P.IsCustomer) + { + var s = Record.Sales; + + + + + + + + + + + + + + + + + + + } + @if (P.IsSupplier) + { + var u = Record.Purchase; + + + + + + + + + + + } + @if (P.IsCustomer || P.IsSupplier) + { + + @if (P.IsCustomer) + { + + } + @if (P.IsSupplier) + { + + } +

@T["Parties.AccountsHint"]

+
+

@T["Parties.TermsHint"]

+ } + break; + + case PartyScreens.Tabs.Fiscal: + var f = Record.Fiscal; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

@T["Parties.IntentHint"]

+
+ break; + + case PartyScreens.Tabs.Banks: + @for (var i = 0; i < Record.BankAccounts.Count; i++) + { + var index = i; + var b = Record.BankAccounts[i]; + + + + + + + + @if (!IsReadOnly) + { +
+ +
+ } +
+ } + + break; + + case PartyScreens.Tabs.Notes: + + + + break; + } +
+ @if (ActiveTab == PartyScreens.Tabs.Notes && !IsNew && Session.Permissions.Allows(AttachmentService.ReadPermission)) + { +
+ } + @if (ActiveTab == PartyScreens.Tabs.History) + { +
+ } +
+
+} + +@code { + private PartyArchive _archive; + private PartyLookups _lookups = PartyLookups.Empty; + private IReadOnlyList _history = []; + private IReadOnlyList _places = []; + private int _attachments; + private bool _loaded; + private bool _busy; + private DateOnly? _birthDate; + private string? _sex; + private string? _birthPlace; + + /// The party, absent for a new one. + [Parameter] + public long? Id { get; set; } + + /// The kind of a new party among the contacts (?tipo=lead). + [SupplyParameterFromQuery(Name = "tipo")] + public string? Kind { get; set; } + + private Party P => Record!.Party; + + private bool CanWrite => Session.Permissions.Allows(PartyService.WritePermission); + + private string KindIcon => Record?.Party.Kind switch + { + PartyKind.Supplier => "truck", + PartyKind.Prospect or PartyKind.Lead => "target", + _ => "users", + }; + + private string PageTitle => Record is null ? T["Parties.Archives." + _archive] + : IsNew ? T["Parties.New." + Record.Party.Kind] + : (Record.Party.Code + " · " + Record.Party.Name); + + private long? PaymentTermId => P.IsCustomer ? Record!.Sales.PaymentTermId : Record!.Purchase.PaymentTermId; + + private IReadOnlyList HeadLines + { + get + { + var lines = new List(); + var street = string.Join(' ', new[] { P.Address, P.StreetNumber }.Where(s => !string.IsNullOrWhiteSpace(s))); + var place = string.Join(' ', new[] { P.PostalCode, P.City, P.Province is { } p ? "(" + p + ")" : null }.Where(s => !string.IsNullOrWhiteSpace(s))); + if (string.Join(" · ", new[] { street, place }.Where(s => s.Length > 0)) is { Length: > 0 } address) + { + lines.Add(address); + } + + var ids = new List(); + if (P.VatNumber is { } vat) + { + ids.Add(T["Parties.Fields.VatNumber"] + " " + (P.CountryCode == "IT" ? vat : P.CountryCode + vat)); + } + + if (P.TaxCode is { } tax && tax != P.VatNumber) + { + ids.Add(T["Parties.Fields.TaxCode"] + " " + tax); + } + + if (ids.Count > 0) + { + lines.Add(string.Join(" · ", ids)); + } + + if (string.Join(" · ", new[] { P.Phone, P.Email ?? P.Pec }.Where(s => !string.IsNullOrWhiteSpace(s))) is { Length: > 0 } reach) + { + lines.Add(reach); + } + + return lines; + } + } + + private IReadOnlyList> KindChoices => PartyScreens.Choices(T, "Kinds"); + + private IReadOnlyList> SubjectChoices => PartyScreens.Choices(T, "SubjectTypes"); + + private IReadOnlyList> AddressKindChoices => PartyScreens.Choices(T, "AddressKinds"); + + private IReadOnlyList> DeliveryChoices => PartyScreens.Choices(T, "Delivery"); + + private IReadOnlyList> SexChoices => PartyScreens.Choices(T, "Sexes"); + + private IReadOnlyList> ExigibilityChoices => [.. new[] { "I", "D", "S" }.Select(v => new KhOption(v, T["Parties.Exigibilities." + v]))]; + + /// + public override bool IsReadOnly => !CanWrite; + + /// + protected override bool IsNew => Record is { Party.Id: 0 }; + + /// + protected override bool CanDelete => base.CanDelete && Session.Permissions.Allows(PartyService.DeletePermission); + + /// + protected override string? NewUrl => CanWrite ? PartyScreens.NewUrl(_archive) : null; + + /// + protected override int? AttachmentCount => IsNew || Record is null ? null : _attachments; + + /// + public override IReadOnlyList Tabs => Record is null ? [] : + [ + TabOf(PartyScreens.Tabs.Main, "user", "Main"), + TabOf(PartyScreens.Tabs.Addresses, "pin", "Addresses", Record.Addresses.Count), + TabOf(PartyScreens.Tabs.Contacts, "phone", "Contacts", Record.Contacts.Count), + TabOf(PartyScreens.Tabs.Terms, "coins", "Terms"), + TabOf(PartyScreens.Tabs.Fiscal, "file-check", "Fiscal"), + TabOf(PartyScreens.Tabs.Banks, "euro", "Banks", Record.BankAccounts.Count), + TabOf(PartyScreens.Tabs.Notes, "paperclip", "Notes", IsNew ? null : _attachments), + TabOf(PartyScreens.Tabs.History, "history", "History"), + ]; + + private KhTabItem TabOf(string id, string icon, string text, int? count = null) + { + // A tab with errors shows how many; otherwise how many details it holds. + var errors = Validation.Messages.Count(m => PartyScreens.TabOf(m.Field) == id); + return new(id, icon, T["Parties.Tabs." + text], errors > 0 ? errors : count is > 0 ? count : null); + } + + /// + protected override async Task OnParametersSetAsync() + { + _archive = PartyScreens.ArchiveOf(Navigation.ToBaseRelativePath(Navigation.Uri)); + await Session.EnsureLoadedAsync(); + if (Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(PartyService.ReadPermission)) + { + if (!_loaded) + { + _lookups = await PartyLookups.ForRecordAsync(Tables, actor, company); + } + + if (Record is null || Record.Party.Id != (Id ?? 0)) + { + await ReloadAsync(); + MarkSaved(); + } + } + + _loaded = true; + } + + /// + protected override async Task ReloadAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + Validation.Clear(); + _places = []; + if (Id is { } id) + { + Record = await Parties.GetAsync(actor, company, id); + await LoadSideAsync(actor, company); + } + else + { + Record = await Parties.NewAsync(actor, company, PartyScreens.KindOf(_archive, Kind)); + _history = []; + _attachments = 0; + } + } + + private async Task LoadSideAsync(Actor actor, string company) + { + if (Record is not { Party.Id: > 0 } record) + { + return; + } + + _history = [.. (await Parties.HistoryAsync(actor, company, record.Party.Id)).Select(AuditTrailService.Item)]; + _attachments = Session.Permissions.Allows(AttachmentService.ReadPermission) + ? await Attachments.CountAsync(actor, company, PartyService.Entity, record.Party.Id) + : 0; + } + + /// + protected override async Task SaveCoreAsync() + { + if (Record is null || Session.Actor is not { } actor || Session.Company?.Code is not { } company || _busy) + { + return false; + } + + _busy = true; + Validation.Clear(); + try + { + var wasNew = IsNew; + var problems = await Parties.ValidateAsync(actor, company, Record); + if (problems.Any(p => !p.IsWarning)) + { + Refuse(problems.Where(p => !p.IsWarning).Select(p => ((string?)p.Field, p.Code))); + return false; + } + + Record = await Parties.SaveAsync(actor, company, Record); + await LoadSideAsync(actor, company); + if (problems.Count > 0) + { + Toasts.Show(ToastKind.Warning, T.Format("Parties.Actions.Warnings", string.Join(" ", problems.Select(p => Message(p.Code))))); + } + + if (wasNew) + { + MarkSaved(); + Navigation.NavigateTo(PartyScreens.RecordUrl(_archive, Record.Party.Id), new NavigationOptions { ReplaceHistoryEntry = true }); + } + + return true; + } + catch (ValidationFailedException ex) + { + Refuse(ex.Errors.Select(TableValues.SplitError)); + return false; + } + catch (ConcurrencyException) + { + Toasts.Show(ToastKind.Error, T["CompanyTables.NotSaved"], T["CompanyTables.Concurrency"]); + return false; + } + finally + { + _busy = false; + } + } + + private void Refuse(IEnumerable<(string? Field, string Code)> errors) + { + foreach (var (field, code) in errors) + { + Validation.Add(field, Message(code)); + } + + // Show the tab of the first error when the open one has none. + if (!Validation.Messages.Any(m => PartyScreens.TabOf(m.Field) == ActiveTab) && Validation.Messages.FirstOrDefault() is { } first) + { + _ = ShowTabAsync(PartyScreens.TabOf(first.Field)); + } + } + + private string Message(string code) => T.Contains(code) ? T[code] : T["CompanyTables.UnknownError"]; + + /// + protected override async Task DeleteCoreAsync() + { + if (Record is not { Party.Id: > 0 } record || Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + if (await Parties.DeleteAsync(actor, company, record.Party.Id) == PartyDeleteOutcome.Disabled) + { + Toasts.Show(ToastKind.Info, T["Parties.Actions.DeletedInstead"]); + } + + Navigation.NavigateTo(PartyScreens.RadarUrl(_archive)); + } + + /// + protected override Task RadarAsync() + { + Navigation.NavigateTo(PartyScreens.RadarUrl(_archive)); + return Task.CompletedTask; + } + + /// + protected override Task AttachmentsAsync() => ShowTabAsync(PartyScreens.Tabs.Notes); + + /// + protected override IEnumerable ContextActions() + { + if (Record is null || IsNew || !CanWrite) + { + yield break; + } + + if (P.VatNumber is not null && P.SubjectType is SubjectType.EuCompany or SubjectType.Company) + { + yield return new ToolbarItem("vies", "shield-check", T["Parties.Actions.Vies"]) + { + Kind = ToolbarKind.Action, Disabled = IsModified || _busy, OnClick = CheckVatAsync, + }; + } + + if (P.Kind != PartyKind.Customer) + { + yield return new ToolbarItem("convert", "users", T["Parties.Actions.Convert"]) + { + Kind = ToolbarKind.Action, Primary = P.Kind is PartyKind.Prospect or PartyKind.Lead, Disabled = IsModified || _busy, OnClick = ConvertAsync, + }; + } + } + + /// + protected override IEnumerable MenuCommands() + { + if (Record is null || IsNew || !CanWrite) + { + yield break; + } + + yield return new ToolbarItem("disable", P.Disabled ? "check-circle" : "x-circle", T[P.Disabled ? "Parties.Actions.Enable" : "Parties.Actions.Disable"]) + { + Kind = ToolbarKind.Menu, Disabled = IsModified || _busy, OnClick = ToggleDisabledAsync, + }; + } + + private async Task CheckVatAsync() + { + if (Record is null || Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _busy = true; + try + { + var result = await Parties.CheckVatAsync(actor, company, P.Id); + if (result is null) + { + Toasts.Show(ToastKind.Warning, T["Parties.Vies.NeedsVat"]); + return; + } + + Record = await Parties.GetAsync(actor, company, P.Id) ?? Record; + var tone = result.Status == ViesStatus.Valid ? ToastKind.Success : result.Status == ViesStatus.Invalid ? ToastKind.Error : ToastKind.Warning; + Toasts.Show(tone, T["Parties.Vies." + result.Status], result.Name); + await LoadSideAsync(actor, company); + } + finally + { + _busy = false; + StateHasChanged(); + } + } + + private async Task ConvertAsync() + { + if (Record is null || Session.Actor is not { } actor || Session.Company?.Code is not { } company + || !await Dialogs.ConfirmAsync(new(T["Parties.Actions.ConvertTitle"], T["Parties.Actions.ConvertText"], T["Parties.Actions.Convert"], T["Common.Cancel"]))) + { + return; + } + + try + { + var converted = await Parties.ConvertToCustomerAsync(actor, company, P.Id); + Toasts.Show(ToastKind.Success, T.Format("Parties.Actions.Converted", converted.Party.Code)); + Record = converted; + Navigation.NavigateTo(PartyScreens.RecordUrl(PartyArchive.Customers, converted.Party.Id)); + } + catch (ValidationFailedException ex) + { + Toasts.Show(ToastKind.Error, T["CompanyTables.NotSaved"], string.Join(" ", ex.Errors.Select(TableValues.SplitError).Select(e => Message(e.Code)))); + } + } + + private async Task ToggleDisabledAsync() + { + if (Record is null || Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + var disabled = !P.Disabled; + await Parties.SetDisabledAsync(actor, company, [P.Id], disabled); + Toasts.Show(ToastKind.Success, T.Format(disabled ? "Parties.Actions.Disabled" : "Parties.Actions.Enabled", 1)); + Record = await Parties.GetAsync(actor, company, P.Id) ?? Record; + await LoadSideAsync(actor, company); + StateHasChanged(); + } + + private void Change(Action change) + { + change(); + MarkModified(); + } + + private static string Key(string list, int index, string field) => list + "." + index.ToString(System.Globalization.CultureInfo.InvariantCulture) + "." + field; + + private void Add(List list, TDetail detail) + { + list.Add(detail); + MarkModified(); + } + + private void Remove(List list, int index) + { + if (index < list.Count) + { + list.RemoveAt(index); + Validation.Clear(); + MarkModified(); + } + } + + private void SetKind(string? value) => Change(() => P.Kind = Enum.Parse(value!)); + + private void SetAddressKind(PartyAddress address, string? value) => Change(() => address.Kind = Enum.Parse(value!)); + + private void SetDelivery(PartySalesTerms terms, string? value) => Change(() => terms.SendDocuments = Enum.Parse(value!)); + + private Task SetSubjectAsync(string? value) + { + Change(() => + { + P.SubjectType = Enum.Parse(value!); + // A foreign subject lives abroad: the country is chosen again. + if (P.SubjectType is SubjectType.EuCompany or SubjectType.NonEuCompany && P.CountryCode == "IT") + { + P.CountryCode = string.Empty; + } + else if (P.SubjectType is SubjectType.Company or SubjectType.PublicAdministration or SubjectType.FlatRate or SubjectType.Person && P.CountryCode.Length == 0) + { + P.CountryCode = "IT"; + } + }); + return Task.CompletedTask; + } + + private async Task SetPostalCodeAsync(string? value) + { + Change(() => P.PostalCode = value); + _places = []; + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || P.CountryCode != "IT" + || !await AutoFill.IsOnAsync(company, AutoFillService.PostalCode)) + { + return; + } + + var places = await AutoFill.PlacesByPostalCodeAsync(actor, company, value); + if (places.Count == 1) + { + PickPlace(places[0]); + } + else if (!places.Any(p => string.Equals(p.Name, P.City, StringComparison.CurrentCultureIgnoreCase))) + { + _places = places; + } + } + + private async Task SetCityAsync(string? value) + { + Change(() => P.City = value); + _places = []; + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || P.CountryCode != "IT" + || !await AutoFill.IsOnAsync(company, AutoFillService.PostalCode)) + { + return; + } + + var exact = (await AutoFill.PlacesByNameAsync(actor, company, value)) + .Where(p => string.Equals(p.Name, value?.Trim(), StringComparison.CurrentCultureIgnoreCase)).ToList(); + if (exact.Count == 1) + { + P.Province = exact[0].ProvinceCode; + // A single postal code is filled; a city with many keeps what was typed. + if (string.IsNullOrWhiteSpace(P.PostalCode) && exact[0].PostalCode is { } code && code.All(char.IsAsciiDigit)) + { + P.PostalCode = code; + } + } + } + + private void PickPlace(PlaceSuggestion place) + { + P.City = place.Name; + P.Province = place.ProvinceCode; + _places = []; + MarkModified(); + } + + private async Task SetIbanAsync(PartyBankAccount account, string? value) + { + Change(() => account.Iban = value ?? string.Empty); + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || !await AutoFill.IsOnAsync(company, AutoFillService.BankFromIban)) + { + return; + } + + if (await AutoFill.BankFromIbanAsync(actor, company, value) is { } bank) + { + account.BankCode = bank.BankCode; + account.BranchCode = bank.BranchCode; + account.BankName ??= bank.Name; + account.Bic ??= bank.Bic; + } + } + + private async Task ComputeTaxCodeAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || Record is null) + { + return; + } + + var place = _birthPlace?.Trim().ToUpperInvariant(); + if (place is { Length: > 0 } && !(place.Length == 4 && char.IsAsciiLetter(place[0]) && place[1..].All(char.IsAsciiDigit))) + { + // A name: the municipality with exactly that name. + place = (await AutoFill.PlacesByNameAsync(actor, company, _birthPlace)) + .FirstOrDefault(p => string.Equals(p.Name, _birthPlace?.Trim(), StringComparison.CurrentCultureIgnoreCase))?.MunicipalityCode; + } + + string? code = null; + if (_birthDate is { } date && Enum.TryParse(_sex, out var sex) && place is { Length: > 0 }) + { + code = await AutoFill.PersonalTaxCodeAsync(company, new PersonalTaxCodeData(P.LastName ?? string.Empty, P.FirstName ?? string.Empty, date, sex, place)); + } + + if (code is null) + { + Toasts.Show(ToastKind.Warning, T["Parties.Actions.TaxCodeMissing"]); + return; + } + + Change(() => P.TaxCode = code); + Toasts.Show(ToastKind.Success, T["Parties.Actions.TaxCodeDone"], code); + } + + private string? FieldLabel(string field) + { + var key = "Parties.Fields." + field.Split('.')[^1]; + return T.Contains(key) ? T[key] : null; + } +} diff --git a/src/Khaemhat.Web/Hosting/KhaemhatApp.cs b/src/Khaemhat.Web/Hosting/KhaemhatApp.cs index 2fb6022..80068a6 100644 --- a/src/Khaemhat.Web/Hosting/KhaemhatApp.cs +++ b/src/Khaemhat.Web/Hosting/KhaemhatApp.cs @@ -27,7 +27,14 @@ public static class KhaemhatApp /// Command-line arguments (ASP.NET Core host conventions, e.g. --urls; also --KHAEMHAT_*=value). /// The application. /// The KHAEMHAT_* variables are missing or not valid. - public static WebApplication Build(string[] args) + public static WebApplication Build(string[] args) => Build(args, null); + + /// Creates the configured application with last changes to its services (tests: fake external services). + /// Command-line arguments. + /// Runs after every registration, before the application is built. + /// The application. + /// The KHAEMHAT_* variables are missing or not valid. + public static WebApplication Build(string[] args, Action? configureServices) { // ApplicationName pins the static web assets manifest to this assembly, also when tests host the app. var builder = WebApplication.CreateBuilder(new WebApplicationOptions @@ -81,6 +88,7 @@ public static class KhaemhatApp builder.Services.AddSingleton(ProductVersion.FromAssembly(typeof(KhaemhatApp).Assembly)); builder.Services.AddRazorComponents() .AddInteractiveServerComponents(); + configureServices?.Invoke(builder.Services); var app = builder.Build(); diff --git a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs index f730bea..5f1a9b0 100644 --- a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs +++ b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs @@ -144,11 +144,13 @@ internal static class KhaemhatServices services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddHttpClient(c => c.Timeout = TimeSpan.FromSeconds(30)); services.AddHttpClient(c => c.Timeout = TimeSpan.FromSeconds(20)); services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); // Companies and start. diff --git a/src/Khaemhat.Web/Parties/PartyLookups.cs b/src/Khaemhat.Web/Parties/PartyLookups.cs new file mode 100644 index 0000000..9ab4461 --- /dev/null +++ b/src/Khaemhat.Web/Parties/PartyLookups.cs @@ -0,0 +1,89 @@ +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Tables; +using Khaemhat.Web.Tables; +using Khaemhat.Web.Ui; + +namespace Khaemhat.Web.Parties; + +/// The company tables a party points to, read once per page as choices (code · description). +public sealed class PartyLookups +{ + /// Nothing loaded. + public static PartyLookups Empty { get; } = new(); + + /// Payment terms, by id. + public IReadOnlyList> PaymentTerms { get; private init; } = []; + + /// Price lists, by id. + public IReadOnlyList> PriceLists { get; private init; } = []; + + /// Salespeople, by id. + public IReadOnlyList> Salespeople { get; private init; } = []; + + /// Party categories, by id. + public IReadOnlyList> Categories { get; private init; } = []; + + /// Carriers, by id. + public IReadOnlyList> Carriers { get; private init; } = []; + + /// Shipping terms, by id. + public IReadOnlyList> ShippingTerms { get; private init; } = []; + + /// Warehouses, by id. + public IReadOnlyList> Warehouses { get; private init; } = []; + + /// Company bank accounts, by id. + public IReadOnlyList> BankAccounts { get; private init; } = []; + + /// VAT codes, by id. + public IReadOnlyList> TaxCodes { get; private init; } = []; + + /// Countries, by code. + public IReadOnlyList> Countries { get; private init; } = []; + + /// Currencies, by code. + public IReadOnlyList> Currencies { get; private init; } = []; + + /// Reads the choices the radar needs. + /// The tables. + /// Who reads. + /// The company. + /// Cancellation. + /// The choices. + public static async Task ForRadarAsync(TableService tables, Actor actor, string company, CancellationToken cancellationToken = default) => new() + { + PaymentTerms = await ReadAsync(tables, actor, company, false, cancellationToken).ConfigureAwait(false), + PriceLists = await ReadAsync(tables, actor, company, false, cancellationToken).ConfigureAwait(false), + Salespeople = await ReadAsync(tables, actor, company, false, cancellationToken).ConfigureAwait(false), + Categories = await ReadAsync(tables, actor, company, false, cancellationToken).ConfigureAwait(false), + }; + + /// Reads every choice of the record page. + /// The tables. + /// Who reads. + /// The company. + /// Cancellation. + /// The choices. + public static async Task ForRecordAsync(TableService tables, Actor actor, string company, CancellationToken cancellationToken = default) => new() + { + PaymentTerms = await ReadAsync(tables, actor, company, false, cancellationToken).ConfigureAwait(false), + PriceLists = await ReadAsync(tables, actor, company, false, cancellationToken).ConfigureAwait(false), + Salespeople = await ReadAsync(tables, actor, company, false, cancellationToken).ConfigureAwait(false), + Categories = await ReadAsync(tables, actor, company, false, cancellationToken).ConfigureAwait(false), + Carriers = await ReadAsync(tables, actor, company, false, cancellationToken).ConfigureAwait(false), + ShippingTerms = await ReadAsync(tables, actor, company, false, cancellationToken).ConfigureAwait(false), + Warehouses = await ReadAsync(tables, actor, company, false, cancellationToken).ConfigureAwait(false), + BankAccounts = await ReadAsync(tables, actor, company, false, cancellationToken).ConfigureAwait(false), + TaxCodes = await ReadAsync(tables, actor, company, false, cancellationToken).ConfigureAwait(false), + Countries = await ReadAsync(tables, actor, company, true, cancellationToken).ConfigureAwait(false), + Currencies = await ReadAsync(tables, actor, company, true, cancellationToken).ConfigureAwait(false), + }; + + private static async Task>> ReadAsync(TableService tables, Actor actor, string company, bool byCode, + CancellationToken cancellationToken) + { + var choices = await TableValues.LookupAsync(tables, typeof(T), byCode, actor, company, cancellationToken).ConfigureAwait(false); + return [.. choices.Select(c => new KhOption(c.Value, c.Text))]; + } +} diff --git a/src/Khaemhat.Web/Parties/PartyScreens.cs b/src/Khaemhat.Web/Parties/PartyScreens.cs new file mode 100644 index 0000000..d168256 --- /dev/null +++ b/src/Khaemhat.Web/Parties/PartyScreens.cs @@ -0,0 +1,172 @@ +using System.Globalization; +using Khaemhat.Application.Localization; +using Khaemhat.Application.Parties; +using Khaemhat.Core.Parties; +using Khaemhat.Web.Ui; + +namespace Khaemhat.Web.Parties; + +/// +/// Addresses, tabs and choices of the party screens (SPEC §11.2, mockups 012-016): the radars +/// /anagrafiche/clienti, /fornitori, /contatti and the record of a party under each of them. +/// +public static class PartyScreens +{ + /// The menu area. + public const string BasePath = "/anagrafiche"; + + /// The tab ids of the record page, in order. + public static class Tabs + { + /// Main data. + public const string Main = "dati"; + + /// Other addresses. + public const string Addresses = "indirizzi"; + + /// Contact people. + public const string Contacts = "contatti"; + + /// Sales and purchase terms. + public const string Terms = "condizioni"; + + /// Fiscal data and e-invoice. + public const string Fiscal = "fiscale"; + + /// Bank accounts. + public const string Banks = "banche"; + + /// Notes and attachments. + public const string Notes = "note"; + + /// History. + public const string History = "storico"; + } + + /// The path segment of an archive. + /// The archive. + /// clienti, fornitori or contatti. + public static string SegmentOf(PartyArchive archive) => archive switch + { + PartyArchive.Suppliers => "fornitori", + PartyArchive.Contacts => "contatti", + _ => "clienti", + }; + + /// The archive of an address such as /anagrafiche/fornitori/12. + /// The path, absolute or relative, with or without query. + /// The archive; customers when the segment is not recognised. + public static PartyArchive ArchiveOf(string? path) + { + var segments = (path ?? string.Empty).Split('?', '#')[0].Split('/', StringSplitOptions.RemoveEmptyEntries); + var index = Array.IndexOf(segments, BasePath.TrimStart('/')); + return (index >= 0 && index + 1 < segments.Length ? segments[index + 1] : null) switch + { + "fornitori" => PartyArchive.Suppliers, + "contatti" => PartyArchive.Contacts, + _ => PartyArchive.Customers, + }; + } + + /// The archive a party belongs to first. + /// The kind. + /// The archive. + public static PartyArchive ArchiveOf(PartyKind kind) => kind switch + { + PartyKind.Supplier => PartyArchive.Suppliers, + PartyKind.Prospect or PartyKind.Lead => PartyArchive.Contacts, + _ => PartyArchive.Customers, + }; + + /// The kind of a new party of an archive. + /// The archive. + /// The kind. + public static PartyKind NewKindOf(PartyArchive archive) => archive switch + { + PartyArchive.Suppliers => PartyKind.Supplier, + PartyArchive.Contacts => PartyKind.Prospect, + _ => PartyKind.Customer, + }; + + /// The radar of an archive. + /// The archive. + /// The address, relative to the base. + public static string RadarUrl(PartyArchive archive) => "anagrafiche/" + SegmentOf(archive); + + /// The record of a party. + /// The archive it is opened from. + /// The party. + /// The address, relative to the base. + public static string RecordUrl(PartyArchive archive, long id) => RadarUrl(archive) + "/" + id.ToString(CultureInfo.InvariantCulture); + + /// A new party of an archive. + /// The archive. + /// The kind, when not the default of the archive (a lead among the contacts). + /// The address, relative to the base. + public static string NewUrl(PartyArchive archive, PartyKind? kind = null) => + RadarUrl(archive) + "/nuovo" + (kind is { } k && k != NewKindOf(archive) ? "?tipo=" + k.ToString().ToLowerInvariant() : string.Empty); + + /// The kind asked by ?tipo=, when it fits the archive. + /// The archive. + /// The value of the query. + /// The kind. + public static PartyKind KindOf(PartyArchive archive, string? value) => + Enum.TryParse(value, ignoreCase: true, out var kind) && ArchiveOf(kind) == archive ? kind : NewKindOf(archive); + + /// The tab that holds a field of the service (Fiscal.RecipientCode, Contacts.0.Email). + /// The field. + /// The tab id. + public static string TabOf(string? field) + { + var head = (field ?? string.Empty).Split('.')[0]; + return head switch + { + "Addresses" => Tabs.Addresses, + "Contacts" => Tabs.Contacts, + "BankAccounts" => Tabs.Banks, + "Sales" or "Purchase" => Tabs.Terms, + "Fiscal" => Tabs.Fiscal, + nameof(Party.Notes) => Tabs.Notes, + _ => Tabs.Main, + }; + } + + /// The choices of an enum, with the texts Parties.<group>.<value>. + /// The enum. + /// The texts. + /// The group of texts. + /// The choices. + public static IReadOnlyList> Choices(ITexts texts, string group) + where TEnum : struct, Enum + { + ArgumentNullException.ThrowIfNull(texts); + return [.. Enum.GetValues().Select(v => new KhOption(v.ToString(), texts["Parties." + group + "." + v]))]; + } + + /// An id as the value of a select. + /// The id. + /// The text. + public static string? Text(long? id) => id?.ToString(CultureInfo.InvariantCulture); + + /// The value of a select as an id. + /// The text. + /// The id. + public static long? Id(string? value) => long.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out var id) ? id : null; + + /// The code part of a lookup text (RB60 · Ricevuta bancaria 60 gg). + /// The choices. + /// The id. + /// Whether to keep the description. + /// The text, or . + public static string? Describe(IReadOnlyList> options, long? id, bool full = false) + { + ArgumentNullException.ThrowIfNull(options); + if (Text(id) is not { } value || options.FirstOrDefault(o => o.Value == value) is not { } option) + { + return null; + } + + var parts = option.Text.Split(" · ", 2); + return full && parts.Length > 1 ? parts[1] : parts[0]; + } +} diff --git a/src/Khaemhat.Web/Resources/it-IT/Parties.json b/src/Khaemhat.Web/Resources/it-IT/Parties.json new file mode 100644 index 0000000..8af385a --- /dev/null +++ b/src/Khaemhat.Web/Resources/it-IT/Parties.json @@ -0,0 +1,290 @@ +{ + "Parties": { + "Archives": { + "Customers": "Clienti", + "Suppliers": "Fornitori", + "Contacts": "Contatti" + }, + "New": { + "Customer": "Nuovo cliente", + "Supplier": "Nuovo fornitore", + "Prospect": "Nuovo prospect", + "Lead": "Nuovo lead" + }, + "NewTitle": "Nuova anagrafica", + "NotFound": "Anagrafica non trovata: forse è stata eliminata.", + "NoCompany": "Apri un'azienda per vedere le anagrafiche.", + "CodeAuto": "automatico", + "Since": "dal {0}", + "Radar": { + "Identifier": "P.IVA / C.F.", + "City": "Città", + "Payment": "Pagamento", + "PriceList": "Listino", + "Salesperson": "Agente", + "Kind": "Tipo", + "Subject": "Soggetto", + "State": "Stato", + "Search": "Cerca per codice, nome, P.IVA, codice fiscale o città", + "Summary": "{0} anagrafiche", + "Selected": "{0} selezionate", + "All": "Tutti", + "Active": "Attivi", + "Disabled": "Disattivati" + }, + "States": { + "Active": "Attivo", + "Disabled": "Disattivato", + "Blocked": "Bloccato", + "Split": "PA · split", + "Demo": "Demo", + "AlsoSupplier": "Anche fornitore", + "AlsoCustomer": "Anche cliente" + }, + "Actions": { + "Disable": "Disattiva", + "Enable": "Riattiva", + "Disabled": "{0} anagrafiche disattivate", + "Enabled": "{0} anagrafiche riattivate", + "Vies": "Verifica VIES", + "Convert": "Converti in cliente", + "ConvertTitle": "Convertire in cliente?", + "ConvertText": "L'anagrafica diventa un cliente: un prospect o un lead riceve il codice cliente e conserva il vecchio come codice precedente; un fornitore resta anche fornitore con lo stesso codice.", + "Converted": "Ora è un cliente: {0}", + "DeletedInstead": "Anagrafica usata da altri dati: è stata disattivata invece che eliminata.", + "AddAddress": "Aggiungi indirizzo", + "AddContact": "Aggiungi contatto", + "AddBank": "Aggiungi conto", + "Remove": "Rimuovi", + "TaxCode": "Calcola dal nome e dai dati di nascita", + "TaxCodeTitle": "Calcolo del codice fiscale", + "TaxCodeDone": "Codice fiscale calcolato", + "TaxCodeMissing": "Servono cognome, nome, data, sesso e comune di nascita.", + "Places": "{0} comuni con questo CAP: scegli quello giusto.", + "Warnings": "Salvato con avvisi: {0}" + }, + "Vies": { + "Valid": "Partita IVA valida nel VIES", + "Invalid": "Partita IVA non valida nel VIES", + "Unavailable": "VIES non raggiungibile: riprova più tardi", + "InvalidInput": "Numero non accettato dal VIES", + "Checked": "Verificata il {0}", + "NeedsVat": "Serve una partita IVA di un paese dell'Unione europea." + }, + "Tabs": { + "Main": "Dati principali", + "Addresses": "Indirizzi", + "Contacts": "Contatti", + "Terms": "Condizioni", + "Fiscal": "Fiscale e SDI", + "Banks": "Banche", + "Notes": "Note e allegati", + "History": "Storico" + }, + "Groups": { + "Identity": "Identità", + "Office": "Sede legale", + "Reach": "Recapiti", + "Classification": "Classificazione e consensi", + "Sales": "Condizioni di vendita", + "Delivery": "Consegna e documenti", + "Purchase": "Condizioni di acquisto", + "EInvoice": "Fatturazione elettronica", + "Vat": "Regime IVA", + "Withholding": "Ritenute e casse", + "Intent": "Dichiarazione d'intento", + "Codes": "Identificativi", + "Accounts": "Conti contabili", + "Notes": "Note", + "Attachments": "Allegati", + "Birth": "Dati di nascita" + }, + "Fields": { + "Code": "Codice", + "PreviousCode": "Codice precedente", + "Kind": "Tipo", + "SubjectType": "Tipo soggetto", + "Name": "Ragione sociale", + "FirstName": "Nome", + "LastName": "Cognome", + "FiscalName": "Denominazione per i documenti", + "VatNumber": "Partita IVA", + "TaxCode": "Codice fiscale", + "Rea": "REA", + "CategoryId": "Categoria", + "Address": "Indirizzo", + "StreetNumber": "Civico", + "PostalCode": "CAP", + "City": "Comune", + "Province": "Provincia", + "CountryCode": "Paese", + "Phone": "Telefono", + "Mobile": "Cellulare", + "Email": "E-mail", + "Pec": "PEC", + "Website": "Sito web", + "SalespersonId": "Agente", + "Language": "Lingua", + "CurrencyCode": "Valuta", + "Since": "In anagrafica dal", + "PrivacyAccepted": "Informativa privacy accettata", + "Marketing": "Consenso al marketing", + "Notes": "Note", + "VatCheck": "Verifica VIES", + "VatCheckedAt": "Data della verifica VIES", + "CustomerAccountCode": "Conto cliente", + "SupplierAccountCode": "Conto fornitore", + "Disabled": "Disattivato", + "IsAlsoSupplier": "È anche fornitore", + "PriceListId": "Listino", + "Discount1": "Sconto 1 %", + "Discount2": "Sconto 2 %", + "PaymentTermId": "Pagamento", + "CompanyBankAccountId": "Nostra banca d'appoggio", + "CarrierId": "Vettore", + "ShippingTermId": "Porto", + "WarehouseId": "Deposito", + "CreditLimit": "Fido", + "Blocked": "Ordini bloccati", + "GroupDeliveryNotes": "Raggruppa i DDT in fattura", + "InvoiceDay": "Giorno di fatturazione", + "SendDocuments": "Invio dei documenti", + "DocumentsEmail": "E-mail per i documenti", + "LeadTimeDays": "Tempo di consegna (giorni)", + "MinimumOrder": "Ordine minimo", + "Discount": "Sconto %", + "VatRegisterCode": "Registro IVA", + "CostAccountCode": "Conto di costo", + "OrdersEmail": "E-mail per gli ordini", + "RecipientCode": "Codice destinatario", + "RecipientPec": "PEC per la fattura elettronica", + "AdministrationReference": "Riferimento amministrazione", + "AttachPdf": "Allega il PDF all'XML", + "SendCopy": "Invia una copia di cortesia", + "SplitPayment": "Scissione dei pagamenti", + "ReverseCharge": "Inversione contabile", + "TaxCodeId": "Codice IVA abituale", + "Exigibility": "Esigibilità IVA", + "StampDutyCharged": "Bollo a carico del cliente", + "Withholding": "Ritenuta d'acconto", + "WithholdingRate": "Aliquota ritenuta %", + "WithholdingReason": "Causale del pagamento", + "PensionFund": "Cassa previdenziale", + "PensionFundRate": "Aliquota cassa %", + "Enasarco": "ENASARCO", + "IntentActive": "Dichiarazione attiva", + "IntentNumber": "Numero", + "IntentDate": "Data", + "IntentProtocol": "Protocollo telematico", + "IntentTaxCodeId": "Codice IVA", + "IntentCeiling": "Plafond", + "IntentUsed": "Utilizzato", + "IntentRemaining": "Residuo", + "IntentFrom": "Valida dal", + "IntentTo": "Valida al", + "Gln": "GLN", + "Eori": "EORI", + "OurCode": "Nostro codice presso di lui", + "AddressKind": "Tipo indirizzo", + "AddressName": "Denominazione", + "IsDefault": "Predefinito", + "ContactName": "Nome e cognome", + "Role": "Ruolo", + "MainContact": "Contatto principale", + "Iban": "IBAN", + "Bic": "BIC", + "BankName": "Banca", + "BankCode": "ABI", + "BranchCode": "CAB", + "BirthDate": "Data di nascita", + "Sex": "Sesso", + "BirthPlace": "Comune di nascita (codice catastale)" + }, + "Kinds": { + "Customer": "Cliente", + "Supplier": "Fornitore", + "Prospect": "Prospect", + "Lead": "Lead" + }, + "SubjectTypes": { + "Company": "Impresa italiana", + "Person": "Privato", + "PublicAdministration": "Pubblica amministrazione", + "EuCompany": "Impresa UE", + "NonEuCompany": "Impresa extra-UE", + "FlatRate": "Forfettario" + }, + "Delivery": { + "None": "Non inviare", + "Email": "E-mail", + "Pec": "PEC" + }, + "AddressKinds": { + "Delivery": "Destinazione merce", + "Billing": "Fatturazione", + "Site": "Cantiere / sede operativa", + "Other": "Altro" + }, + "Exigibilities": { + "I": "I · immediata", + "D": "D · differita", + "S": "S · scissione dei pagamenti" + }, + "Sexes": { + "Male": "M", + "Female": "F" + }, + "Empty": { + "Addresses": "Nessun altro indirizzo: la sede legale è nei dati principali.", + "Contacts": "Nessun contatto.", + "Banks": "Nessun conto corrente." + }, + "TermsHint": "Le condizioni si propongono nei documenti; nel documento si possono cambiare.", + "NoTerms": "Un prospect o un lead non ha condizioni: si impostano quando diventa cliente.", + "IntentHint": "Il residuo scende con le fatture emesse in esenzione (arriva con la fatturazione, M5).", + "AccountsHint": "I sottoconti del partitario si creano alla prima registrazione (M7)." + }, + "parties": { + "name": { + "required": "Indica la ragione sociale, oppure cognome e nome." + }, + "vat-number": { + "required": "Per un'impresa la partita IVA è obbligatoria.", + "duplicate": "Un'altra anagrafica ha la stessa partita IVA (va bene per filiali e sedi distinte)." + }, + "identifier": { + "required": "Per una pubblica amministrazione serve il codice fiscale o la partita IVA." + }, + "tax-code": { + "invalid": "Codice fiscale non valido.", + "missing": "Manca il codice fiscale: serve per fatturare a un privato." + }, + "code": { + "duplicate": "Codice già usato da un'altra anagrafica." + }, + "country": { + "unknown": "Paese non presente nella tabella dei paesi.", + "not-eu": "Un'impresa UE ha sede in un altro paese dell'Unione europea.", + "not-domestic": "Per questo tipo di soggetto il paese è quello dell'azienda." + }, + "intent": { + "incomplete": "Per una dichiarazione attiva servono numero e plafond." + }, + "exigibility": { + "invalid": "Esigibilità non valida: I, D oppure S." + }, + "day": { + "range": "Il giorno va da 1 a 31." + }, + "value": { + "negative": "Il valore non può essere negativo." + }, + "detail": { + "required": "Campo obbligatorio." + }, + "convert": { + "already-customer": "L'anagrafica è già un cliente." + }, + "not-found": "Anagrafica non trovata." + } +} diff --git a/src/Khaemhat.Web/wwwroot/app.css b/src/Khaemhat.Web/wwwroot/app.css index b9e6b7a..b29e74f 100644 --- a/src/Khaemhat.Web/wwwroot/app.css +++ b/src/Khaemhat.Web/wwwroot/app.css @@ -244,6 +244,11 @@ h1[tabindex="-1"]:focus { outline: none; box-shadow: none; } /* Attachments and generated files (SPEC §9.4, mockup 024). */ .kh-tab-body { padding: 14px 16px; } + +/* Parties (issue #41): the lists of details of a record and the choice of a municipality from its postal code. */ +.kh-detailfoot { display: flex; align-items: center; gap: 12px; padding: 12px 16px; } +.kh-endrow { display: flex; align-items: flex-end; justify-content: flex-end; } +.kh-places { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; } .kh-att { display: flex; flex-direction: column; gap: 10px; } .kh-att-head { display: flex; align-items: center; gap: 8px; } .kh-att-title, .kh-att-section { font-size: 10.5px; text-transform: uppercase; letter-spacing: .5px; color: var(--kh-text-3); font-weight: 600; } diff --git a/tests/Khaemhat.Data.Tests/MappingTests.cs b/tests/Khaemhat.Data.Tests/MappingTests.cs index 9ccf070..b0b7f89 100644 --- a/tests/Khaemhat.Data.Tests/MappingTests.cs +++ b/tests/Khaemhat.Data.Tests/MappingTests.cs @@ -76,6 +76,7 @@ public sealed class MappingTests "tax_codes", "payment_methods", "payment_terms", "payment_term_lines", "bank_accounts", "salespeople", "carriers", "shipping_terms", "transport_means", "goods_appearances", "delivery_terms", "transport_reasons", "inventory_reasons", "warehouses", "item_categories", "party_categories", "price_lists", "discount_policies", "document_numerators", "document_types", "cost_centers", "jobs", "code_sequences", + "parties", "party_addresses", "party_contacts", "party_bank_accounts", "party_sales_terms", "party_purchase_terms", "party_fiscal", ]; CollectionAssert.AreEquivalent(expected, registry.Maps.Select(m => m.Table).ToArray()); } diff --git a/tests/Khaemhat.Web.Tests/Hosting/TestInstance.cs b/tests/Khaemhat.Web.Tests/Hosting/TestInstance.cs index 6b82a06..4ec9def 100644 --- a/tests/Khaemhat.Web.Tests/Hosting/TestInstance.cs +++ b/tests/Khaemhat.Web.Tests/Hosting/TestInstance.cs @@ -44,9 +44,17 @@ internal static partial class TestInstance /// Builds and starts an instance and waits until the start sequence is over. /// Cancellation. /// The running instance, its address and the company code. - public static async Task<(WebApplication App, Uri Address, string Company)> StartAsync(CancellationToken cancellationToken) + public static Task<(WebApplication App, Uri Address, string Company)> StartAsync(CancellationToken cancellationToken) => + StartAsync(null, cancellationToken); + + /// Builds and starts an instance with changes to its services (fake external services). + /// The changes. + /// Cancellation. + /// The running instance, its address and the company code. + public static async Task<(WebApplication App, Uri Address, string Company)> StartAsync( + Action? configureServices, CancellationToken cancellationToken) { - var app = KhaemhatApp.Build(Arguments(out var company)); + var app = KhaemhatApp.Build(Arguments(out var company), configureServices); await app.StartAsync(cancellationToken); var address = new Uri(app.Urls.First()); using var client = new HttpClient { BaseAddress = address }; diff --git a/tests/Khaemhat.Web.Tests/Parties/DemoPartiesTests.cs b/tests/Khaemhat.Web.Tests/Parties/DemoPartiesTests.cs new file mode 100644 index 0000000..5d15391 --- /dev/null +++ b/tests/Khaemhat.Web.Tests/Parties/DemoPartiesTests.cs @@ -0,0 +1,68 @@ +using Khaemhat.Application.Parties; +using Khaemhat.Application.Querying; +using Khaemhat.Application.Security; +using Khaemhat.Application.Seeding; +using Khaemhat.Core.Parties; +using Khaemhat.Core.Security; +using Khaemhat.Fiscal.Italy; +using Khaemhat.Web.Tests.Hosting; +using Microsoft.Extensions.DependencyInjection; + +namespace Khaemhat.Web.Tests.Parties; + +/// The demo parties (SPEC §14, issue #41): loaded once, every kind of subject, and each one passes the checks of a save. +[TestClass] +public sealed class DemoPartiesTests +{ + private static readonly Actor Root = new(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null); + + [TestMethod] + public void FictitiousNumbers_AreValid() + { + var rules = new ItalianTaxIdentifierRules(); + foreach (var vat in DemoPartiesSeeder.VatNumbers) + { + Assert.IsTrue(rules.IsValidVatNumber(vat), vat); + } + + Assert.IsTrue(rules.IsValidTaxCode(DemoPartiesSeeder.AdministrationTaxCode)); + foreach (var iban in DemoPartiesSeeder.Ibans) + { + Assert.IsTrue(Khaemhat.Core.Validation.IbanValidator.IsValid(iban), iban); + } + } + + [TestMethod] + public async Task DemoSeed_FillsAnEmptyCompanyOnce_WithPartiesThatPassTheChecks() + { + var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None); + await using (app) + { + var runner = app.Services.GetRequiredService(); + var parties = app.Services.GetRequiredService(); + var first = await runner.RunAsync(company, SeedKind.Demo); + Assert.AreEqual(21, first.Added["parties"]); + Assert.IsEmpty((await runner.RunAsync(company, SeedKind.Demo)).Added, "Only an empty company gets the demo data."); + + var customers = (await parties.ListAsync(Root, company, PartyArchive.Customers, new ListQuery { Limit = 100 })).Items; + var suppliers = (await parties.ListAsync(Root, company, PartyArchive.Suppliers, new ListQuery { Limit = 100 })).Items; + var contacts = (await parties.ListAsync(Root, company, PartyArchive.Contacts, new ListQuery { Limit = 100 })).Items; + Assert.HasCount(12, customers); + Assert.HasCount(6, suppliers, "Five suppliers and a customer that is also a supplier."); + Assert.HasCount(4, contacts); + CollectionAssert.IsSubsetOf(Enum.GetValues(), customers.Select(c => c.SubjectType).Distinct().ToList()); + Assert.AreEqual("C000001", customers.Single(c => c.Name == "Rossi Impianti S.r.l.").Code); + Assert.IsTrue(customers.Any(c => c.Terms is { Blocked: true }) && customers.Any(c => c.Terms is { SplitPayment: true }) && customers.Any(c => c.Disabled)); + + foreach (var row in customers.Concat(suppliers).Concat(contacts).DistinctBy(r => r.Id)) + { + var record = (await parties.GetAsync(Root, company, row.Id))!; + Assert.IsTrue(record.Party.IsDemo); + var errors = (await parties.ValidateAsync(Root, company, record)).Where(p => !p.IsWarning).Select(p => p.Field + ":" + p.Code).ToList(); + Assert.IsEmpty(errors, row.Name + ": " + string.Join(", ", errors)); + } + + await app.StopAsync(); + } + } +} diff --git a/tests/Khaemhat.Web.Tests/Parties/PartyScreensTests.cs b/tests/Khaemhat.Web.Tests/Parties/PartyScreensTests.cs new file mode 100644 index 0000000..7728a43 --- /dev/null +++ b/tests/Khaemhat.Web.Tests/Parties/PartyScreensTests.cs @@ -0,0 +1,77 @@ +using Khaemhat.Application.Parties; +using Khaemhat.Core.Parties; +using Khaemhat.Web.Parties; +using Khaemhat.Web.Shell; +using Khaemhat.Web.Tests.Shell; +using Khaemhat.Web.Ui; + +namespace Khaemhat.Web.Tests.Parties; + +/// Addresses, tabs and texts of the party screens (issue #41). +[TestClass] +public sealed class PartyScreensTests +{ + [TestMethod] + public void Addresses_GoBackAndForthBetweenArchivesAndRecords() + { + Assert.AreEqual(PartyArchive.Suppliers, PartyScreens.ArchiveOf("anagrafiche/fornitori/12?x=1")); + Assert.AreEqual(PartyArchive.Contacts, PartyScreens.ArchiveOf("/anagrafiche/contatti/nuovo")); + Assert.AreEqual(PartyArchive.Customers, PartyScreens.ArchiveOf("anagrafiche/clienti")); + Assert.AreEqual("anagrafiche/fornitori/42", PartyScreens.RecordUrl(PartyArchive.Suppliers, 42)); + Assert.AreEqual("anagrafiche/contatti/nuovo?tipo=lead", PartyScreens.NewUrl(PartyArchive.Contacts, PartyKind.Lead)); + Assert.AreEqual("anagrafiche/contatti/nuovo", PartyScreens.NewUrl(PartyArchive.Contacts, PartyKind.Prospect)); + Assert.AreEqual(PartyKind.Lead, PartyScreens.KindOf(PartyArchive.Contacts, "lead")); + Assert.AreEqual(PartyKind.Customer, PartyScreens.KindOf(PartyArchive.Customers, "lead"), "A kind of another archive is ignored."); + Assert.AreEqual(PartyArchive.Contacts, PartyScreens.ArchiveOf(PartyKind.Lead)); + + // Every radar is a page of the menu. + var menu = MenuCatalog.All.Single(i => i.Key == "Shell.Menu.Parties").Children.Select(c => c.Href).ToList(); + foreach (var archive in Enum.GetValues()) + { + CollectionAssert.Contains(menu, "/" + PartyScreens.RadarUrl(archive)); + } + } + + [TestMethod] + public void Errors_OpenTheTabOfTheirField() + { + Assert.AreEqual(PartyScreens.Tabs.Main, PartyScreens.TabOf("VatNumber")); + Assert.AreEqual(PartyScreens.Tabs.Fiscal, PartyScreens.TabOf("Fiscal.RecipientCode")); + Assert.AreEqual(PartyScreens.Tabs.Terms, PartyScreens.TabOf("Purchase.OrdersEmail")); + Assert.AreEqual(PartyScreens.Tabs.Contacts, PartyScreens.TabOf("Contacts.2.Email")); + Assert.AreEqual(PartyScreens.Tabs.Banks, PartyScreens.TabOf("BankAccounts.0.Iban")); + Assert.AreEqual(PartyScreens.Tabs.Addresses, PartyScreens.TabOf("Addresses.1.Name")); + Assert.AreEqual(PartyScreens.Tabs.Notes, PartyScreens.TabOf("Notes")); + } + + [TestMethod] + public void Choices_HaveTexts_AndLookupsShowTheirCode() + { + var texts = ShellTests.Texts; + foreach (var (group, values) in new (string, IEnumerable)[] + { + ("Kinds", Enum.GetNames()), ("SubjectTypes", Enum.GetNames()), ("Delivery", Enum.GetNames()), + ("AddressKinds", Enum.GetNames()), ("Archives", Enum.GetNames()), + ("Vies", Enum.GetNames().Where(v => v != nameof(VatCheckStatus.None))), ("New", Enum.GetNames()), + }) + { + foreach (var value in values) + { + Assert.IsTrue(texts.Contains("Parties." + group + "." + value), "Parties." + group + "." + value); + } + } + + // The fields of the service errors have a label for the history. + foreach (var field in typeof(Party).GetProperties().Where(p => p.CanWrite && p.Name is not ("Id" or "IsDemo" or "RowVersion" or "CreatedAt" or "CreatedBy" or "UpdatedAt" or "UpdatedBy"))) + { + Assert.IsTrue(texts.Contains("Parties.Fields." + field.Name), field.Name); + } + + IReadOnlyList> terms = [new("7", "RB60 · Ricevuta bancaria 60 gg")]; + Assert.AreEqual("RB60", PartyScreens.Describe(terms, 7)); + Assert.AreEqual("Ricevuta bancaria 60 gg", PartyScreens.Describe(terms, 7, full: true)); + Assert.IsNull(PartyScreens.Describe(terms, 8)); + Assert.AreEqual(12L, PartyScreens.Id(PartyScreens.Text(12))); + Assert.IsNull(PartyScreens.Id(string.Empty)); + } +} diff --git a/tests/Khaemhat.Web.Tests/Parties/PartyServiceTests.cs b/tests/Khaemhat.Web.Tests/Parties/PartyServiceTests.cs new file mode 100644 index 0000000..218fcc0 --- /dev/null +++ b/tests/Khaemhat.Web.Tests/Parties/PartyServiceTests.cs @@ -0,0 +1,251 @@ +using System.Globalization; +using System.Net; +using System.Text; +using Khaemhat.Application.Parties; +using Khaemhat.Application.Querying; +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Parties; +using Khaemhat.Core.Security; +using Khaemhat.Infrastructure.Http; +using Khaemhat.Web.Tests.Hosting; +using Microsoft.Extensions.DependencyInjection; + +namespace Khaemhat.Web.Tests.Parties; + +/// The parties on a real instance (issue #41): codes, details, rules, conversion, delete, VIES. +[TestClass] +public sealed class PartyServiceTests +{ + private const string ValidVat = "01234567897"; + private const string OtherVat = "02345678904"; + private static readonly Actor Root = new(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null); + private static readonly int Year = DateTime.Now.Year; + + [TestMethod] + public async Task Customer_GetsTheCustomerCode_AndItsDetailsAreSavedWithIt() + { + var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None); + await using (app) + { + var parties = app.Services.GetRequiredService(); + var record = await parties.NewAsync(Root, company, PartyKind.Customer); + Assert.AreEqual("IT", record.Party.CountryCode); + record.Party.Name = " Rossi Impianti S.r.l. "; + record.Party.VatNumber = "IT " + ValidVat; + record.Party.City = "Torino"; + record.Fiscal.RecipientCode = "abc1234"; + record.Sales.Discount1 = 5; + record.Addresses.Add(new PartyAddress { Name = "Cantiere Lingotto", Kind = PartyAddressKind.Site, City = "Torino", Province = "to" }); + record.Contacts.Add(new PartyContact { Name = "Mario Rossi", Role = "Acquisti", Email = "acquisti@rossi.example", IsDefault = true }); + record.Contacts.Add(new PartyContact { Name = "Anna Bianchi", IsDefault = true }); + record.BankAccounts.Add(new PartyBankAccount { Iban = "it60 x054 2811 1010 0000 0123 456" }); + + var saved = await parties.SaveAsync(Root, company, record); + + Assert.AreEqual("C000001", saved.Party.Code); + Assert.AreEqual("Rossi Impianti S.r.l.", saved.Party.Name); + Assert.AreEqual(ValidVat, saved.Party.VatNumber); + Assert.AreEqual("ABC1234", saved.Fiscal.RecipientCode); + Assert.AreEqual(5m, saved.Sales.Discount1); + Assert.AreEqual("TO", saved.Addresses.Single().Province); + Assert.AreEqual(1, saved.Contacts.Count(c => c.IsDefault), "One main contact."); + Assert.AreEqual(("05428", "11101"), (saved.BankAccounts[0].BankCode, saved.BankAccounts[0].BranchCode)); + + // Changing the lists: a contact removed, one added; the party keeps its code. + saved.Contacts.RemoveAt(1); + saved.Contacts.Add(new PartyContact { Name = "Luca Verdi", Role = "Amministrazione" }); + saved.Party.Phone = "011 123456"; + var again = await parties.SaveAsync(Root, company, saved); + CollectionAssert.AreEqual(new[] { "Mario Rossi", "Luca Verdi" }, again.Contacts.Select(c => c.Name).ToArray()); + Assert.AreEqual("C000001", again.Party.Code); + Assert.IsNotEmpty(await parties.HistoryAsync(Root, company, again.Party.Id)); + + var list = await parties.ListAsync(Root, company, PartyArchive.Customers, new ListQuery { Search = "rossi" }); + Assert.AreEqual("C000001", list.Items.Single().Code); + Assert.AreEqual(ValidVat, list.Items[0].Identifier); + Assert.IsEmpty((await parties.ListAsync(Root, company, PartyArchive.Suppliers, new ListQuery())).Items); + await app.StopAsync(); + } + } + + [TestMethod] + public async Task Save_RefusesWhatTheRulesDoNotAllow() + { + var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None); + await using (app) + { + var parties = app.Services.GetRequiredService(); + + async Task ErrorsAsync(Action fill, PartyKind kind = PartyKind.Customer) + { + var record = await parties.NewAsync(Root, company, kind); + record.Party.Name = "Prova"; + fill(record); + var ex = await Assert.ThrowsExactlyAsync(() => parties.SaveAsync(Root, company, record)); + return [.. ex.Errors]; + } + + CollectionAssert.AreEquivalent(new[] { "Name:" + PartyService.NameRequired, "VatNumber:" + PartyService.VatNumberRequired }, await ErrorsAsync(r => r.Party.Name = " ")); + CollectionAssert.Contains(await ErrorsAsync(r => r.Party.VatNumber = "01234567890"), "VatNumber:" + TableCatalog.VatNumberInvalid); + CollectionAssert.Contains(await ErrorsAsync(r => { r.Party.VatNumber = ValidVat; r.Fiscal.RecipientCode = "AB12"; }), "Fiscal.RecipientCode:fiscal.recipient.business-length"); + CollectionAssert.Contains( + await ErrorsAsync(r => { r.Party.SubjectType = SubjectType.PublicAdministration; r.Party.TaxCode = "80012345678"; }), + "Fiscal.RecipientCode:fiscal.recipient.required"); + CollectionAssert.Contains(await ErrorsAsync(r => { r.Party.SubjectType = SubjectType.Person; r.Party.TaxCode = "RSSMRA80A01L219X"; }), "TaxCode:" + PartyService.TaxCodeInvalid); + CollectionAssert.Contains(await ErrorsAsync(r => { r.Party.SubjectType = SubjectType.EuCompany; r.Party.VatNumber = "123456789"; }), "CountryCode:" + PartyService.CountryNotEu); + CollectionAssert.Contains(await ErrorsAsync(r => { r.Party.VatNumber = ValidVat; r.Party.Email = "non-una-mail"; }), "Email:" + TableCatalog.EmailInvalid); + CollectionAssert.Contains(await ErrorsAsync(r => { r.Party.VatNumber = ValidVat; r.Sales.Discount1 = 120; }), "Sales.Discount1:" + TableCatalog.PercentRange); + CollectionAssert.Contains( + await ErrorsAsync(r => { r.Party.VatNumber = ValidVat; r.BankAccounts.Add(new PartyBankAccount { Iban = "IT00X0542811101000000123456" }); }), + "BankAccounts.0.Iban:" + TableCatalog.IbanInvalid); + CollectionAssert.Contains( + await ErrorsAsync(r => { r.Party.VatNumber = ValidVat; r.Fiscal.IntentActive = true; }), + "Fiscal.IntentNumber:" + PartyService.IntentIncomplete); + CollectionAssert.Contains(await ErrorsAsync(r => { r.Party.VatNumber = ValidVat; r.Contacts.Add(new PartyContact()); }), "Contacts.0.Name:" + PartyService.DetailRequired); + + // A private customer: recipient code proposed, the missing tax code is only a warning. + var person = await parties.NewAsync(Root, company, PartyKind.Customer); + person.Party.SubjectType = SubjectType.Person; + person.Party.LastName = "Esposito"; + person.Party.FirstName = "Mario"; + var warnings = await parties.ValidateAsync(Root, company, person); + Assert.AreEqual(PartyService.TaxCodeMissing, warnings.Single().Code); + Assert.IsTrue(warnings[0].IsWarning); + var saved = await parties.SaveAsync(Root, company, person); + Assert.AreEqual("Esposito Mario", saved.Party.Name); + Assert.AreEqual("0000000", saved.Fiscal.RecipientCode); + + // A lead needs nothing but a name; a manual code is refused when the mask does not allow it. + var lead = await parties.NewAsync(Root, company, PartyKind.Lead); + lead.Party.Name = "Contatto fiera"; + Assert.AreEqual($"L{Year}-0001", (await parties.SaveAsync(Root, company, lead)).Party.Code); + await app.Services.GetRequiredService().SaveAsync(Root, company, [new CodeRule("customers", "C{seq:000000}", AllowManual: false)]); + CollectionAssert.Contains(await ErrorsAsync(r => { r.Party.VatNumber = OtherVat; r.Party.Code = "MIO"; }), "Code:" + CodeRuleService.ManualNotAllowed); + await app.StopAsync(); + } + } + + [TestMethod] + public async Task Kinds_HaveTheirCodesAndArchives_AndLeadsBecomeCustomers() + { + var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None); + await using (app) + { + var parties = app.Services.GetRequiredService(); + var supplier = await NewAsync(parties, company, PartyKind.Supplier, "Metalli Nord S.p.A.", ValidVat); + Assert.AreEqual("F000001", supplier.Party.Code); + Assert.AreEqual(supplier.Party.Code, (await parties.SearchAsync(Root, company, PartyArchive.Suppliers, "metalli")).Single().Code); + + var prospect = await NewAsync(parties, company, PartyKind.Prospect, "Hotel Belvedere", null); + Assert.AreEqual($"L{Year}-0001", prospect.Party.Code); + Assert.HasCount(1, (await parties.ListAsync(Root, company, PartyArchive.Contacts, new ListQuery())).Items); + + var customer = await parties.ConvertToCustomerAsync(Root, company, prospect.Party.Id); + Assert.AreEqual(PartyKind.Customer, customer.Party.Kind); + Assert.AreEqual("C000001", customer.Party.Code); + Assert.AreEqual($"L{Year}-0001", customer.Party.PreviousCode); + Assert.IsEmpty((await parties.ListAsync(Root, company, PartyArchive.Contacts, new ListQuery())).Items); + var again = await Assert.ThrowsExactlyAsync(() => parties.ConvertToCustomerAsync(Root, company, customer.Party.Id)); + Assert.AreEqual("Kind:" + PartyService.AlreadyCustomer, again.Errors.Single()); + + // A supplier that starts buying keeps its code and shows in both archives. + var both = await parties.ConvertToCustomerAsync(Root, company, supplier.Party.Id); + Assert.AreEqual("F000001", both.Party.Code); + Assert.IsTrue(both.Party.IsCustomer && both.Party.IsSupplier); + Assert.HasCount(2, (await parties.ListAsync(Root, company, PartyArchive.Customers, new ListQuery())).Items); + Assert.HasCount(1, (await parties.ListAsync(Root, company, PartyArchive.Suppliers, new ListQuery())).Items); + + // The same VAT number twice is allowed (branches), with a warning. + var twin = await parties.NewAsync(Root, company, PartyKind.Customer); + twin.Party.Name = "Metalli Nord - filiale"; + twin.Party.VatNumber = ValidVat; + Assert.AreEqual(PartyService.VatNumberDuplicate, (await parties.ValidateAsync(Root, company, twin)).Single().Code); + await app.StopAsync(); + } + } + + [TestMethod] + public async Task Delete_RemovesAPartyNeverUsed_AndDisablingHidesIt() + { + var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None); + await using (app) + { + var parties = app.Services.GetRequiredService(); + var first = await NewAsync(parties, company, PartyKind.Customer, "Bianchi & Figli S.n.c.", ValidVat); + var second = await NewAsync(parties, company, PartyKind.Customer, "Gallo Ferramenta", OtherVat); + + Assert.AreEqual(1, await parties.SetDisabledAsync(Root, company, [second.Party.Id, second.Party.Id], true)); + Assert.IsEmpty(await parties.SearchAsync(Root, company, PartyArchive.Customers, "gallo"), "Disabled parties are not proposed."); + var active = await parties.ListAsync(Root, company, PartyArchive.Customers, new ListQuery { Filters = [ListFilter.Of("disabled", ListFilterOperator.Equals, "false")] }); + Assert.AreEqual(first.Party.Code, active.Items.Single().Code); + + Assert.AreEqual(PartyDeleteOutcome.Deleted, await parties.DeleteAsync(Root, company, first.Party.Id)); + Assert.IsNull(await parties.GetAsync(Root, company, first.Party.Id)); + Assert.AreEqual("C000003", (await NewAsync(parties, company, PartyKind.Customer, "Nuovo", ValidVat)).Party.Code, "Codes are not reused."); + await app.StopAsync(); + } + } + + [TestMethod] + public async Task EuParty_IsCheckedOnVies_WhenSaved_AndTheOutcomeIsKept() + { + var handler = new ViesStub(); + var (app, _, company) = await TestInstance.StartAsync( + services => services.AddHttpClient().ConfigurePrimaryHttpMessageHandler(() => handler), CancellationToken.None); + await using (app) + { + var parties = app.Services.GetRequiredService(); + var record = await parties.NewAsync(Root, company, PartyKind.Customer); + record.Party.Name = "Alpenbau GmbH"; + record.Party.SubjectType = SubjectType.EuCompany; + record.Party.CountryCode = "DE"; + record.Party.VatNumber = "DE 123456789"; + + var saved = await parties.SaveAsync(Root, company, record); + + Assert.AreEqual("123456789", saved.Party.VatNumber); + Assert.AreEqual("XXXXXXX", saved.Fiscal.RecipientCode); + Assert.AreEqual(VatCheckStatus.Valid, saved.Party.VatCheck); + Assert.IsNotNull(saved.Party.VatCheckedAt); + Assert.AreEqual("/taxation_customs/vies/rest-api/ms/DE/vat/123456789", handler.Paths.Single()); + + // Saved again without changes: no new call. With the option off nothing is asked. + await parties.SaveAsync(Root, company, saved); + Assert.HasCount(1, handler.Paths); + await app.Services.GetRequiredService().SaveOptionsAsync(Root, company, new Dictionary { [AutoFillService.Vies] = false }); + var other = await parties.NewAsync(Root, company, PartyKind.Customer); + other.Party.Name = "Nordic Pipes"; + other.Party.SubjectType = SubjectType.EuCompany; + other.Party.CountryCode = "FR"; + other.Party.VatNumber = "12345678901"; + Assert.AreEqual(VatCheckStatus.None, (await parties.SaveAsync(Root, company, other)).Party.VatCheck); + Assert.HasCount(1, handler.Paths); + + // The action VIES asks anyway. + Assert.AreEqual(ViesStatus.Valid, (await parties.CheckVatAsync(Root, company, other.Party.Id))!.Status); + Assert.HasCount(2, handler.Paths); + await app.StopAsync(); + } + } + + private static async Task NewAsync(PartyService parties, string company, PartyKind kind, string name, string? vat) + { + var record = await parties.NewAsync(Root, company, kind); + record.Party.Name = name; + record.Party.VatNumber = vat; + return await parties.SaveAsync(Root, company, record); + } + + private sealed class ViesStub : HttpMessageHandler + { + public List Paths { get; } = []; + + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + Paths.Add(request.RequestUri!.AbsolutePath); + var body = string.Create(CultureInfo.InvariantCulture, $$"""{"isValid":true,"requestDate":"2026-11-12T10:00:00.000Z","userError":"VALID","name":"---"}"""); + return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(body, Encoding.UTF8, "application/json") }); + } + } +} diff --git a/tests/Khaemhat.Web.Tests/Shell/LocalizationRulesTests.cs b/tests/Khaemhat.Web.Tests/Shell/LocalizationRulesTests.cs index e78c232..627b70f 100644 --- a/tests/Khaemhat.Web.Tests/Shell/LocalizationRulesTests.cs +++ b/tests/Khaemhat.Web.Tests/Shell/LocalizationRulesTests.cs @@ -271,6 +271,6 @@ public sealed partial class LocalizationRulesTests [GeneratedRegex(@"&[a-zA-Z]+;|&#\d+;")] private static partial Regex EntityPattern(); - [GeneratedRegex("\"((?:Shell|Pages|Auth|Common|Ui|Dashboard)\\.[A-Za-z0-9_.]+)\"")] + [GeneratedRegex("\"((?:Shell|Pages|Auth|Common|Ui|Dashboard|Parties)\\.[A-Za-z0-9_.]+)\"")] private static partial Regex KeyPattern(); } diff --git a/tests/Khaemhat.Web.Tests/Tables/TableScreensTests.cs b/tests/Khaemhat.Web.Tests/Tables/TableScreensTests.cs index aac1a04..3db49ea 100644 --- a/tests/Khaemhat.Web.Tests/Tables/TableScreensTests.cs +++ b/tests/Khaemhat.Web.Tests/Tables/TableScreensTests.cs @@ -108,11 +108,11 @@ public sealed partial class TableScreensTests [TestMethod] public void EveryErrorCode_HasAText() { - var codes = new[] { typeof(TableService), typeof(TableCatalog), typeof(CompanyProfileService), typeof(FiscalYearService), typeof(PaymentTermService), typeof(ExchangeRateService), typeof(CodeRuleService), typeof(CodeMask) } + var codes = new[] { typeof(TableService), typeof(TableCatalog), typeof(CompanyProfileService), typeof(FiscalYearService), typeof(PaymentTermService), typeof(ExchangeRateService), typeof(CodeRuleService), typeof(CodeMask), typeof(Khaemhat.Application.Parties.PartyService) } .SelectMany(t => t.GetFields(BindingFlags.Public | BindingFlags.Static).Where(f => f.IsLiteral && f.FieldType == typeof(string))) .Select(f => (string)f.GetRawConstantValue()!) .Where(c => c.StartsWith("tables.", StringComparison.Ordinal) || c.StartsWith("profile.", StringComparison.Ordinal) || c.StartsWith("fiscal.", StringComparison.Ordinal) - || c.StartsWith("codes.", StringComparison.Ordinal)) + || c.StartsWith("codes.", StringComparison.Ordinal) || (c.StartsWith("parties.", StringComparison.Ordinal) && !c.StartsWith("parties.party", StringComparison.Ordinal))) .Where(c => !c.EndsWith('.')) .Concat(Enum.GetValues().Select(FiscalYearService.ErrorOf)) .ToList();