diff --git a/README.md b/README.md index 5df9545..0ad3024 100644 --- a/README.md +++ b/README.md @@ -1,26 +1,26 @@ # HPH -**Il lavoro, in armonia.** Una base riutilizzabile per un gestionale aziendale modulare, con frontend e backend scritti in Rust. +**Work, in harmony.** A reusable foundation for modular business management software, with a Rust frontend and backend. -HPH è attualmente una **demo locale eseguibile**, non un gestionale pronto per dati reali. Il primo incremento dimostra il design, la composizione dei moduli e un flusso di timbratura controllato dal server. +HPH is currently a **runnable local demo**, not a system ready for real company data. The first working slice demonstrates the design, module composition and a server-validated time-tracking workflow. ## Stack -| Parte | Scelta | +| Area | Choice | | --- | --- | -| Interfaccia | Leptos 0.8, rendering server e hydration WebAssembly | +| Interface | Leptos 0.8, server-side rendering and WebAssembly hydration | | Server | Axum 0.8 + Tokio | -| Regole condivise | Crate indipendente `hph-core` | -| Design | CSS responsive con token; temi sage e indigo, nessun font remoto | -| Build | cargo-leptos 0.3.11, Cargo.lock versionato | -| Persistenza attuale | PostgreSQL/SQLx per infrastruttura e repository; l'interfaccia usa ancora memoria demo | -| Persistenza prevista | Completare autenticazione e integrare i repository SQLx nelle schermate operative | +| Shared rules | Independent `hph-core` crate | +| Design | Responsive CSS with design tokens; sage and indigo themes, no remote fonts | +| Build | cargo-leptos 0.3.11, versioned Cargo.lock | +| Current persistence | PostgreSQL/SQLx infrastructure and repositories; the interface still uses demo memory | +| Next persistence step | Complete authentication and connect SQLx repositories to operational screens | -Il codice applicativo è Rust. Il browser usa anche CSS e il piccolo loader JavaScript generato da wasm-bindgen/Leptos: non serve mantenere una seconda applicazione React o TypeScript. Non sono richiesti Node o npm. +Application code is written in Rust. The browser also uses CSS and the small JavaScript loader generated by wasm-bindgen/Leptos: there is no separate React or TypeScript application to maintain. Node and npm are not required. English is the default language for the interface and repository documentation. -## Avvio locale +## Run locally -Prerequisiti: Git e Rust tramite [rustup](https://rustup.rs). Il file `rust-toolchain.toml` installa target WebAssembly e componenti richiesti. +Prerequisites: Git and Rust installed through [rustup](https://rustup.rs). The `rust-toolchain.toml` file installs the required WebAssembly target and components. ```bash git clone https://github.com/Stcant/HPH.git @@ -29,62 +29,63 @@ cargo install cargo-leptos --version 0.3.11 --locked HPH_DEMO=true cargo leptos watch ``` -In PowerShell, impostare prima `$env:HPH_DEMO = "true"`, poi eseguire `cargo leptos watch`. +In PowerShell, first set `$env:HPH_DEMO = "true"`, then run `cargo leptos watch`. -Aprire **http://127.0.0.1:3000**. La demo rifiuta l'avvio senza consenso esplicito `HPH_DEMO=true` o con un indirizzo di ascolto diverso da loopback. Non esporla tramite proxy, tunnel o rete pubblica: non è presente un sistema di autenticazione. L'integrazione PostgreSQL è facoltativa e limitata alla connessione, alle migrazioni e al health check; le schermate usano ancora dati in memoria. Vedi [docs/DATABASE.md](docs/DATABASE.md). +Open **http://127.0.0.1:3000**. The demo refuses to start without the explicit `HPH_DEMO=true` setting or on a non-loopback address. Do not expose it through a proxy, tunnel or public network: authentication is not available yet. PostgreSQL integration is optional and currently limited to connections, migrations and the health check; screens still use in-memory data. See [docs/DATABASE.md](docs/DATABASE.md). -## Provare il flusso +## Try the workflow -1. Dalla dashboard, registrare **Entrata** per il profilo demo Elena Conti. -2. Aprire **Presenze**: registrare **Inizio pausa**, **Fine pausa**, **Uscita**. Gli eventi arrivano al server e sono visibili dopo un aggiornamento pagina. -3. Aprire **Il tuo workspace**, attivare **Report** e consultare il tempo degli intervalli chiusi. Gli intervalli ancora aperti non sono inclusi. -4. Provare a disattivare **Presenze** mentre Report è attivo: il server rifiuta la modifica perché Reports dipende da Attendance. Con una sessione aperta, le presenze non possono essere disattivate. -5. Disattivare Report, chiudere eventuali sessioni e disattivare Presenze. Il menu si aggiorna; riattivandolo, gli eventi della sessione rimangono. +1. From the dashboard, select **Clock in** for the demo profile, Elena Conti. +2. Open **Attendance** and select **Start break**, **End break**, then **Clock out**. Events reach the server and remain visible after refreshing the page. +3. Open **Your workspace**, enable **Reports** and inspect the recorded time for closed work intervals. Open intervals are excluded. +4. Try disabling **Time and attendance** while Reports is enabled: the server rejects the change because Reports depends on Attendance. Open work sessions also prevent Attendance from being disabled. +5. Disable Reports, close any open work sessions, then disable Attendance. The menu updates; enabling Attendance again restores access to the session's existing events. -Tutti i profili sono inventati. L'unico attore della demo è un'amministratrice fissa scelta dal server, non dal browser. Le modifiche ai moduli e gli eventi sono condivisi tra le schede della stessa istanza e **si perdono al riavvio del processo**. L'interfaccia non aggiorna in tempo reale altre schede: usare il pulsante di aggiornamento. +All profiles are fictional. The demo's only actor is a fixed administrator selected by the server, not the browser. Module changes and events are shared between tabs using the same server instance and **are lost when the process restarts**. Other tabs do not update in real time: use the refresh button. -## Personalizzare il template +## Customize the template -Modificare `hph.toml` e riavviare il server: +Edit `hph.toml` and restart the server: ```toml -organization = "La tua azienda" +organization = "Your company" theme = "sage" # sage | indigo preset = "team" # essential | team | complete -# modules = ["people", "attendance"] # opzionale: sovrascrive preset +# modules = ["people", "attendance"] # optional: overrides preset ``` -`modules` è facoltativo e accetta gli ID `people`, `attendance` e `reports`. I moduli devono includere le proprie dipendenze; HPH rifiuta una configurazione non valida all'avvio. Se `modules` è omesso, usa il preset. Le scelte iniziali in `hph.toml` restano salvate; le attivazioni fatte dall'interfaccia demo valgono solo fino al riavvio. +The optional `modules` setting accepts the IDs `people`, `attendance` and `reports`. Modules must include their dependencies; HPH rejects invalid configurations at startup. When `modules` is omitted, the preset applies. Initial choices in `hph.toml` persist across restarts; changes made in the demo interface last only until the server restarts. -| Preset | Moduli | +| Preset | Modules | | --- | --- | -| essential | Persone | -| team | Persone + Timbrature e presenze | -| complete | Persone + Timbrature e presenze + Report | +| essential | People | +| team | People + Time and attendance | +| complete | People + Time and attendance + Reports | -I moduli sono composizioni del codice Rust compilato. L'amministratore può abilitarli o disabilitarli nell'interfaccia; aggiungere una nuova funzione richiede codice e una nuova build. Non è un marketplace di plugin caricati da terze parti. +Modules are compiled Rust components. Company administrators can enable or disable them in the interface; adding a new feature requires code and a new build. This is not a marketplace of third-party plugins loaded at runtime. -La configurazione dei moduli appartiene all'azienda: ogni workspace compone HPH scegliendo ciò che serve ai propri processi. Nella demo le attivazioni restano in memoria e si azzerano al riavvio; la configurazione persistente per azienda è parte del prossimo incremento PostgreSQL. +Module configuration belongs to the company: each workspace is composed around its own processes. The demo keeps changes in memory; a PostgreSQL repository for company configuration exists, but it still needs to be connected to authenticated requests. -La base può essere clonata/forkata e personalizzata. La creazione del codice riutilizzabile non imposta automaticamente il flag **Template repository** nelle impostazioni GitHub. +The foundation can be cloned or forked and customized. Reusable code does not automatically enable GitHub's **Template repository** setting. -## Cosa funziona oggi +## What works today -| Funzione | Stato | +| Feature | Status | | --- | --- | -| Dashboard responsive, schermate e temi | Implementati; QA browser ancora da eseguire | -| Elenco persone | Profili demo in sola lettura | -| Moduli e dipendenze | Configurazione eseguita e verificata sul server | -| Entrata / pausa / rientro / uscita | Controllo sequenza e orario sul server | -| Riepilogo del tempo | Intervalli chiusi, pause escluse, precisione al secondo | -| Ruoli e confine aziendale | Regole di dominio testate; nessuna autenticazione reale | -| Aziende multiple, database, utenti reali | Non implementati | -| Ferie, turni, rettifiche, audit, esportazioni | Non implementati | -| Paghe, contabilità, magazzino | Fuori dalla prima versione | +| Responsive dashboard, screens and themes | Implemented; browser QA still pending | +| People directory | Read-only demo profiles | +| Modules and dependencies | Configuration enforced and verified on the server | +| Clock in / start break / end break / clock out | Sequence and timestamp validation on the server | +| Recorded-time summary | Closed intervals, excluding breaks, with second-level precision | +| Roles and company boundaries | Tested domain rules; no real authentication yet | +| PostgreSQL schema, module and membership repositories | Tested under RLS in CI; not connected to the screens | +| Multiple companies and real accounts in the application | Not implemented | +| Leave, shifts, corrections, audit and exports | Not implemented | +| Payroll, accounting and inventory | Outside the first version | -Gli eventi usano timestamp UTC; i riepiloghi coprono la sessione della demo, non una giornata contrattuale. Nessun calcolo automatico di straordinari, ferie maturate o busta paga. +Events use UTC timestamps displayed as `YYYY-MM-DD`. Summaries cover the demo session, not a contractual working day. There is no automatic calculation of overtime, accrued leave or payroll. -## Verifiche +## Verification ```bash cargo fmt --all --check @@ -93,17 +94,33 @@ cargo check --target wasm32-unknown-unknown --features hydrate --lib --locked cargo leptos build ``` -I test del dominio coprono dipendenze, permessi, azienda errata, doppia entrata, orario retrogrado, pause, disattivazione e conservazione degli eventi. I test HTTP esercitano le vere server function attraverso il router Axum e controllano il rendering SSR. Il job PostgreSQL della CI applica le policy RLS e prova pool SQLx, migrazioni e contesto tenant contro PostgreSQL reale. Non sono test browser né provano operazioni aziendali persistite. +Domain tests cover dependencies, permissions, foreign companies, duplicate clock-ins, reversed timestamps, breaks, disabling modules and data retention. HTTP tests exercise the real server functions through the Axum router and check SSR output. The PostgreSQL CI job applies RLS policies and tests SQLx pools, migrations, tenant context, module configuration and active membership lookup against a real PostgreSQL instance using a restricted runtime role. These are not browser tests and do not establish persistent business operations through the interface. -## Struttura +## Structure -- `crates/hph-core/`: moduli, ruoli, regole di timbratura, contratti serializzati e test. -- `src/app.rs`: componenti e schermate Leptos. -- `src/api.rs`: server function, senza accettare l'identità aziendale dal client. -- `src/server.rs`: configurazione e stato della demo, router e test HTTP. -- `src/database.rs`: pool PostgreSQL SQLx, migrazioni, ping e transazioni scoped per tenant. -- `style/main.css`: layout, token, temi e adattamento mobile. -- `docs/MODULES.md`: contratto per estendere il template. -- `harness/PROJECT_MAP.md` e `harness/PROJECT_STATE.md`: architettura e checkpoint. +- `crates/hph-core/`: modules, roles, time-tracking rules, serialized contracts and tests. +- `src/app.rs`: Leptos components and screens. +- `src/api.rs`: server functions; the client does not supply the acting identity. +- `src/server.rs`: demo configuration and state, router and HTTP tests. +- `src/database.rs`: SQLx PostgreSQL pool, migrations, health check and tenant-scoped transactions. +- `src/module_repository.rs` and `src/membership_repository.rs`: company module configuration and active membership lookup. +- `style/main.css`: layout, tokens, themes and mobile styles. +- `docs/MODULES.md`: the module extension contract. +- `harness/PROJECT_MAP.md` and `harness/PROJECT_STATE.md`: architecture and project checkpoint. -Il prossimo incremento è **autenticazione e sessioni**: il repository SQLx risolve già la membership attiva dell'utente nell'azienda selezionata, ma le schermate non lo usano ancora. Fino all'integrazione di autenticazione, autorizzazione e persistenza applicativa, HPH resta una demo locale e non deve ospitare dati aziendali reali. +The next functional increment is **authentication and sessions**. The SQLx repository can already resolve an active membership for a selected company, but the screens do not use it yet. Until authentication, authorization and application persistence are integrated, HPH remains a local demo and must not host real company data. + +--- + +
+🦀 Recruiter side quest: you found the Easter egg + +If you made it this far, you probably followed the link on my CV—or took a very productive wrong turn on GitHub. Either way, thanks for looking beyond the bullet points. + +I'm Stefano. HPH is where I turn architecture decisions into working code, tests and the occasional conversation with the Rust compiler. + +Curious about the choices behind the project? [Let's talk](https://www.linkedin.com/in/stefano-contini-464933127/). Bonus points if you mention this Easter egg. + +*Achievement unlocked: actually read the README.* + +
diff --git a/crates/hph-core/src/lib.rs b/crates/hph-core/src/lib.rs index 2601c65..9eba3f3 100644 --- a/crates/hph-core/src/lib.rs +++ b/crates/hph-core/src/lib.rs @@ -21,21 +21,21 @@ pub fn catalog() -> Vec { vec![ ModuleDefinition { id: ModuleId::People, - name: "Persone".into(), - description: "Il tuo team, i reparti e i contatti. Un punto di partenza condiviso." - .into(), + name: "People".into(), + description: "Your team, departments and contacts. A shared starting point.".into(), dependencies: vec![], }, ModuleDefinition { id: ModuleId::Attendance, - name: "Timbrature e presenze".into(), - description: "Entrate, pause e uscite. Una giornata di lavoro sempre leggibile.".into(), + name: "Time and attendance".into(), + description: "Clock-ins, breaks and clock-outs. A clear view of the working day." + .into(), dependencies: vec![ModuleId::People], }, ModuleDefinition { id: ModuleId::Reports, - name: "Report".into(), - description: "Riepiloghi delle ore registrate e delle sessioni concluse.".into(), + name: "Reports".into(), + description: "Summaries of recorded hours and completed work sessions.".into(), dependencies: vec![ModuleId::Attendance], }, ] @@ -78,7 +78,7 @@ impl UserIdentity { person_id: membership.person_id.clone(), role: membership.role, }) - .ok_or_else(|| "Nessuna appartenenza attiva per l'azienda selezionata.".into()) + .ok_or_else(|| "No active membership for the selected company.".into()) } } @@ -100,7 +100,7 @@ impl ModuleSet { "essential" => vec![ModuleId::People], "team" => vec![ModuleId::People, ModuleId::Attendance], "complete" => vec![ModuleId::People, ModuleId::Attendance, ModuleId::Reports], - _ => return Err("Configurazione moduli non riconosciuta.".into()), + _ => return Err("Unrecognized module configuration.".into()), }; Self::from_enabled(enabled) } @@ -109,7 +109,7 @@ impl ModuleSet { let mut unique = Vec::with_capacity(enabled.len()); for id in &enabled { if unique.contains(id) { - return Err("La configurazione contiene un modulo duplicato.".into()); + return Err("The configuration contains a duplicate module.".into()); } unique.push(*id); } @@ -125,7 +125,7 @@ impl ModuleSet { .any(|dependency| !modules.contains(*dependency)) { return Err(format!( - "{} richiede le sue dipendenze attive. Attiva prima le dipendenze oppure disattiva prima questo modulo.", + "{} requires its dependencies to be enabled. Enable the dependencies first or disable this module first.", definition.name )); } @@ -157,10 +157,10 @@ pub enum PunchKind { impl PunchKind { pub fn label(self) -> &'static str { match self { - Self::In => "Entrata", - Self::BreakStart => "Inizio pausa", - Self::BreakEnd => "Fine pausa", - Self::Out => "Uscita", + Self::In => "Clock in", + Self::BreakStart => "Start break", + Self::BreakEnd => "End break", + Self::Out => "Clock out", } } } @@ -174,9 +174,9 @@ pub enum WorkState { impl WorkState { pub fn label(self) -> &'static str { match self { - Self::Off => "Fuori servizio", - Self::Working => "Al lavoro", - Self::Paused => "In pausa", + Self::Off => "Off duty", + Self::Working => "Working", + Self::Paused => "On break", } } pub fn next(self, kind: PunchKind) -> Result { @@ -186,7 +186,7 @@ impl WorkState { (Self::Paused, PunchKind::BreakEnd) => Ok(Self::Working), (Self::Working | Self::Paused, PunchKind::Out) => Ok(Self::Off), _ => Err( - "Timbratura non valida per lo stato attuale. Aggiorna la pagina e riprova.".into(), + "Invalid time entry for the current status. Refresh the page and try again.".into(), ), } } @@ -220,7 +220,7 @@ impl Workspace { pub fn authorize(&self, actor: &Actor) -> Result<(), String> { if actor.tenant_id != self.tenant_id || !self.people.iter().any(|p| p.id == actor.person_id) { - return Err("Accesso non autorizzato a questa azienda.".into()); + return Err("Access to this company is not authorized.".into()); } Ok(()) } @@ -240,7 +240,7 @@ impl Workspace { pub fn set_module(&mut self, actor: &Actor, id: ModuleId, enabled: bool) -> Result<(), String> { self.authorize(actor)?; if actor.role != Role::Admin { - return Err("Solo un amministratore può configurare i moduli.".into()); + return Err("Only an administrator can configure modules.".into()); } if !enabled && id == ModuleId::Attendance @@ -249,7 +249,7 @@ impl Workspace { .iter() .any(|p| self.state(&p.id) != WorkState::Off) { - return Err("Chiudi tutte le sessioni aperte prima di disattivare le presenze.".into()); + return Err("Close all open work sessions before disabling attendance.".into()); } self.modules.set(id, enabled) } @@ -262,7 +262,7 @@ impl Workspace { ) -> Result<(), String> { self.authorize(actor)?; if !self.modules.contains(ModuleId::Attendance) { - return Err("Il modulo presenze non è attivo.".into()); + return Err("The attendance module is disabled.".into()); } self.state(&actor.person_id).next(kind)?; if self @@ -272,7 +272,7 @@ impl Workspace { .find(|p| p.person_id == actor.person_id) .is_some_and(|p| p.timestamp > timestamp) { - return Err("Orario precedente all'ultima timbratura.".into()); + return Err("The timestamp is earlier than the last time entry.".into()); } self.punches.push(Punch { person_id: actor.person_id.clone(), diff --git a/docs/MODULES.md b/docs/MODULES.md index 00595ed..d073048 100644 --- a/docs/MODULES.md +++ b/docs/MODULES.md @@ -1,39 +1,39 @@ -# Estendere HPH +# Extending HPH -## Contratto attuale +## Current contract -La composizione dei moduli è dichiarata in `crates/hph-core/src/lib.rs`: `ModuleId`, `catalog()` e `ModuleSet`. È una fonte condivisa compilata sia per il server sia per il browser. Non mantenere un secondo elenco JavaScript o un secondo motore di dipendenze nella UI. +Module composition is declared in `crates/hph-core/src/lib.rs`: `ModuleId`, `catalog()` and `ModuleSet`. This shared source is compiled for both the server and the browser. Do not maintain a second JavaScript catalog or a separate dependency engine in the UI. -La scelta dei moduli è una configurazione dell'azienda: HPH Core è sempre presente e ogni azienda abilita le funzioni adatte ai propri processi. I moduli restano codice Rust del template, compilato e versionato; non sono plugin di terze parti caricati a runtime. La demo mantiene la scelta solo in memoria; il prossimo livello persistente deve associarla all'organizzazione autenticata. +Module selection is a company setting: HPH Core is always included, and each company enables the features that fit its processes. Modules remain compiled, versioned Rust code within the template; they are not third-party plugins loaded at runtime. The demo keeps the selection in memory; persistent application configuration must be associated with the authenticated organization. -Il core è sempre presente. I moduli attuali formano una catena: Persone → Presenze → Report. Per attivare un modulo, le sue dipendenze devono essere attive; per disattivarne una, occorre disattivare prima i moduli che la usano. Una modifica non valida non altera lo stato precedente. +Core is always present. The current modules form a dependency chain: People → Attendance → Reports. A module's dependencies must be enabled before enabling it. Before disabling a dependency, disable the modules that use it. An invalid change must leave the previous state intact. -Disabilitare un modulo deve interromperne le operazioni protette e nascondere le schermate applicabili, **senza eliminare i dati**. Le sessioni di timbratura aperte impediscono di disattivare Presenze. +Disabling a module must stop its protected operations and hide the relevant screens **without deleting its data**. Open work sessions prevent Attendance from being disabled. -## Personalizzare una singola installazione aziendale +## Customize a single company installation -In `hph.toml` si può impostare `modules` come lista esplicita di ID (`people`, `attendance`, `reports`). La lista opzionale sostituisce `preset` e viene validata all'avvio: dipendenze mancanti o ID duplicati fanno rifiutare la configurazione. L'esempio commentato è in `hph.toml`. +In `hph.toml`, set `modules` to an explicit list of IDs (`people`, `attendance`, `reports`). This optional list overrides `preset` and is validated at startup: missing dependencies or duplicate IDs cause the configuration to be rejected. A commented example is included in `hph.toml`. -Questa è una configurazione iniziale persistente per l'installazione dell'azienda. Le modifiche dalla schermata demo sono ancora temporanee e si azzerano al riavvio; la persistenza delle impostazioni runtime per organizzazione arriverà con il database. +This is persistent initial configuration for the company installation. Changes made from the demo screen remain temporary and reset on restart. Persisting runtime settings per organization requires connecting the PostgreSQL repository to authenticated requests. -## Aggiungere un modulo +## Add a module -1. Aggiungere un identificatore tipizzato a `ModuleId` e una definizione in `catalog()` con dipendenze esplicite. Non creare cicli. -2. Definire le regole del dominio e i tipi serializzati nel core o, quando cresce, in un crate dedicato. Tenere Leptos, HTTP e database fuori dalle regole pure. -3. Implementare l'operazione server in `src/api.rs`. Ottenere l'attore dal contesto server, verificare appartenenza, permesso e attivazione prima della mutazione. Un pulsante nascosto non è un controllo di accesso. -4. Aggiungere la schermata e la navigazione in `src/app.rs`. Riutilizzare colori, componenti, stati vuoti ed errori esistenti. -5. Definire cosa succede alle operazioni aperte quando si disattiva il modulo. Non cancellare implicitamente documenti o eventi. -6. Scrivere test delle regole e del confine HTTP: operazione valida, permesso negato, azienda estranea, modulo spento, input errato e conservazione dei dati. -7. Aggiornare preset e documentazione solo se il nuovo modulo fa realmente parte di quel preset. Non mostrare come disponibile un modulo non implementato. +1. Add a typed identifier to `ModuleId` and a definition to `catalog()` with explicit dependencies. Do not introduce cycles. +2. Define domain rules and serialized types in the core or, as it grows, a dedicated crate. Keep Leptos, HTTP and database concerns out of pure domain rules. +3. Implement the server operation in `src/api.rs`. Obtain the actor from server context and verify membership, permissions and module activation before mutating state. A hidden button is not an access control. +4. Add the screen and navigation in `src/app.rs`. Reuse existing colors, components, empty states and errors. Keep interface text, accessibility labels, comments and documentation in English. +5. Define what happens to open operations when the module is disabled. Do not implicitly delete documents or events. +6. Test domain rules and the HTTP boundary: valid operations, denied permissions, foreign companies, disabled modules, invalid input and data retention. +7. Update presets and documentation only if the new module actually belongs to that preset. Do not present an unimplemented module as available. -## Esempio futuro: ferie +## Future example: leave -Dipendenza: Persone. Requisiti da chiarire prima del codice: intervalli di date, fuso aziendale, calendario lavorativo, approvatore, sovrapposizioni e rettifiche. Una richiesta è associata all'azienda e al dipendente; l'approvazione richiede un permesso distinto dall'invio. Il saldo ferie richiede regole esplicite e non va ricavato da ipotesi sui contratti. +Dependency: People. Clarify these requirements before implementation: date ranges, company time zone, working calendar, approver, overlaps and corrections. A request belongs to a company and employee; approval requires a permission distinct from submission. Leave balances require explicit rules and must not be inferred from assumptions about employment contracts. -## Confine della demo +## Demo boundary -`DemoState` usa memoria condivisa protetta da mutex e un attore fisso. Il controllo del tenant nel dominio non equivale a un sistema multi-azienda sicuro: mancano autenticazione, verifica della membership a ogni richiesta e isolamento nel database. +`DemoState` uses mutex-protected shared memory and a fixed actor. Domain-level tenant checks do not establish a secure multi-company service. Authentication, per-request membership verification and database isolation at the HTTP boundary still need to be integrated. -La futura implementazione PostgreSQL deve usare transazioni per modifiche correlate, vincoli per impedire sessioni incompatibili, chiavi collegate al tenant e test di isolamento con almeno due aziende. L'abilitazione del modulo è una scelta aziendale, mentre il permesso è una proprietà dell'utente: entrambe vanno verificate. +PostgreSQL operations must use transactions for related changes, constraints to prevent incompatible work sessions, tenant-linked keys and isolation tests with at least two companies. Module activation is a company setting, while permissions belong to the user: both must be checked. -Per preservare configurazioni e dati durante l'evoluzione del template, usare migrazioni versionate. Non ricopiare i dati di esempio sopra quelli di un'installazione esistente. +Use versioned migrations to preserve configuration and data as the template evolves. Do not overwrite an existing installation with demo data. diff --git a/harness/PROJECT_MAP.md b/harness/PROJECT_MAP.md index 55f4d3b..d26e1d9 100644 --- a/harness/PROJECT_MAP.md +++ b/harness/PROJECT_MAP.md @@ -1,62 +1,72 @@ -# HPH — Mappa del progetto - -## Requisiti confermati -- Progetto personale dell'utente: gestionale aziendale con timbrature e presenze, estendibile a ulteriori funzioni. -- Template riutilizzabile: ciascuna installazione/azienda deve poter scegliere i moduli. -- Ogni azienda deve poter comporre il proprio gestionale attivando i moduli adatti ai suoi processi; la selezione appartiene all'azienda e deve diventare persistente. -- Dopo iniziale libertà tecnologica, l'utente ha espresso preferenza per tutta l'applicazione in Rust. Scelta adottata: Rust frontend e backend. -- Qualità estetica e cura dell'esperienza utente sono requisiti centrali. -- Repository pubblica di portfolio: https://github.com/Stcant/HPH, branch main. Nessuna distribuzione dell'app richiesta. - -## Decisioni architetturali -| Area | Scelta e motivo | +# HPH — Project map + +## Confirmed requirements + +- A personal business management project with time tracking and attendance, extensible to additional functions. +- A reusable template: each installation/company can select its own modules. +- Each company composes HPH around its processes; module selection belongs to the company and must become persistent in the application. +- After initially leaving technology choices open, the owner expressed a preference for Rust throughout. Adopted choice: a Rust frontend and backend. +- Visual quality and a carefully designed user experience are central requirements. +- English is the default language for the interface, accessibility labels, errors, comments and documentation (requested on 2026-10-13). Preserve proper names and stable identifiers. +- Public portfolio repository: https://github.com/Stcant/HPH, branch `main`. No application deployment requested. + +## Architectural decisions + +| Area | Choice and rationale | | --- | --- | -| Frontend | Leptos 0.8, SSR + hydration WASM: componenti e contratti in Rust, una sola applicazione | -| HTTP | Axum 0.8 + Tokio, integrazione ufficiale Leptos | -| Organizzazione | Monolite modulare: un deploy, regole indipendenti in hph-core, niente microservizi iniziali | -| Moduli | Catalogo tipizzato, dipendenze dichiarate e abilitazione controllata sul server; configurazione persistente per azienda nel prossimo incremento | -| Configurazione | hph.toml per azienda, tema, preset o lista esplicita di moduli; le modifiche runtime demo sono temporanee | -| Design | CSS con token, verde salvia e alternativa indigo; sidebar, card, tabelle e layout responsive | -| Persistenza | Schema PostgreSQL e policy RLS testate in CI; pool SQLx, migrazioni e repository per moduli e membership. Le schermate usano ancora stato in memoria; l'API attende un'identità autenticata | -| Identità | Contratti Rust e repository SQLx per membership attiva/ruolo/persona per tenant. Login, sessioni e collegamento del resolver alle server function restano da implementare | - -Compromesso: Rust end-to-end condivide tipi e competenze, ma comporta build WASM e un ecosistema UI meno ampio rispetto a React. Leptos genera un loader JavaScript; il codice applicativo resta Rust. Non promettere assenza assoluta di JavaScript nel browser. - -## Implementazione iniziale -- `crates/hph-core/src/lib.rs`: catalogo e dipendenze, identità e membership aziendali, macchina a stati delle timbrature, calcolo di intervalli chiusi e test. -- `migrations/0001_company_data.sql`: schema PostgreSQL multi-azienda e policy RLS; `migrations/tests/tenant_isolation.sql` verifica visibilità e scritture cross-company. -- `src/database.rs`: pool SQLx, migrator runtime, ping e transazioni con contesto RLS transaction-local. -- `src/module_repository.rs`: lettura/scrittura atomica di moduli aziendali sotto RLS, membership attiva e ruolo admin. Non è ancora collegato alle server function finché manca una sessione autenticata con UUID verificati. -- `src/membership_repository.rs`: risolve l'attore da una membership persistita, attiva e tenant-scoped, a partire da un'identità e da un tenant già verificati dal livello di autenticazione. - -- `src/app.rs`: dashboard, anagrafica dimostrativa, timbrature, report, configurazione moduli e componenti condivisi. -- `src/api.rs`: server function snapshot, configurazione e timbratura. L'identità dell'attore viene dal contesto server. -- `src/server.rs`: configurazione, stato demo in memoria, router Axum e test HTTP/SSR; health check PostgreSQL opzionale. -- `src/main.rs`: avvio esclusivamente con HPH_DEMO=true e ascolto loopback; pool runtime e migrator separato sono opzionali via environment. -- `style/main.css`: estetica, token e adattamento mobile; nessun font o asset remoto richiesto. -- `Cargo.lock`: versioni risolte; `rust-toolchain.toml`: toolchain e target. -- `.github/workflows/ci.yml`: formattazione, test SSR, controllo WASM e integrazione PostgreSQL. - -## Moduli -La configurazione iniziale dell'azienda può usare un preset o una lista esplicita validata in hph.toml; la UI può cambiare la selezione durante la demo. In produzione la configurazione runtime deve essere persistita e autorizzata per organizzazione. -Core sempre attivo. Persone contiene profili sintetici in sola lettura. Presenze dipende da Persone; Report dipende da Presenze. I moduli si disattivano senza cancellare eventi; sessioni aperte impediscono la disattivazione di Presenze. Report mostra il tempo degli intervalli chiusi della sessione, pause escluse. - -## Confini attuali -Questa è una demo locale con una membership amministrativa sintetica. I contratti identità/membership, lo schema RLS, il repository moduli e il repository SQLx per membership persistite sono coperti dalla CI. Login, sessioni e collegamento dei repository alle server function non sono ancora integrati. Il tenant è modellato e testato nel dominio, ma questo non prova un servizio multi-azienda sicuro. Dati e modifiche ai moduli si azzerano al riavvio. Aggiornamento tra schede manuale. - -Il percorso verso più aziende richiede membership verificata, scope tenant obbligatorio su query/mutazioni, migrazioni, vincoli e test di isolamento nel database. Nessun dato reale prima di questa fase. - -Timestamp UTC, orologio del server e sequenze validate. Calendario aziendale, fuso di visualizzazione, regole contrattuali, arrotondamenti, rettifiche/audit e idempotenza di richieste ritentate richiedono implementazione dedicata. - -## Modello di personalizzazione -HPH Core resta condiviso; i moduli sono funzionalità Rust versionate nel template, selezionabili dall'amministratore dell'azienda e protette sul server. Disattivarli nasconde e blocca le operazioni senza cancellare i dati. La demo applica la scelta a un solo workspace in memoria. La configurazione persistente deve essere associata all'organizzazione; il modello di distribuzione (istanza dedicata o servizio multi-azienda) resta una scelta futura, quindi il confine tenant va mantenuto esplicito fin da subito. - -## Evoluzione del prodotto -Primo flusso operativo target: autenticazione, anagrafica reale, timbrature persistenti e controllo del responsabile. Poi ferie/permessi e calendario presenze. Turni, documenti, note spese, commesse, clienti, fatturazione, magazzino e integrazioni rimangono moduli candidati. Paghe e contabilità richiedono specifiche autonome. - -## Lettura -- [Stato operativo](PROJECT_STATE.md): evidenza e prossimo passo. -- [Avvio e limiti](../README.md). -- [Contratto dei moduli](../docs/MODULES.md). - -Riferimenti primari consultati: https://book.leptos.dev/getting_started/index.html ; https://book.leptos.dev/ssr/21_cargo_leptos.html ; https://github.com/leptos-rs/start-axum ; https://docs.rs/axum/latest/axum/ ; https://www.postgresql.org/docs/current/ddl-rowsecurity.html . +| Frontend | Leptos 0.8, SSR + WASM hydration: Rust components and contracts in one application | +| HTTP | Axum 0.8 + Tokio, using the official Leptos integration | +| Organization | Modular monolith: one deployment, independent rules in hph-core, no initial microservices | +| Modules | Typed catalog, declared dependencies and server-enforced activation; persistent per-company configuration still needs application integration | +| Configuration | hph.toml for company, theme, preset or explicit module list; demo runtime changes are temporary | +| Design | CSS tokens, sage and indigo themes, sidebar, cards, tables and responsive layout | +| Persistence | PostgreSQL schema and RLS policies tested in CI; SQLx pool, migrations, module and membership repositories. Screens still use in-memory state; the API awaits an authenticated identity | +| Identity | Rust contracts and a SQLx repository for active membership, role and person per tenant. Login, sessions and connecting the resolver to server functions remain to be implemented | +| Language | English interface and repository content; HTML language is en. UTC timestamps use an unambiguous YYYY-MM-DD display format | + +Tradeoff: Rust end to end shares types and expertise, but requires WASM builds and offers a smaller UI ecosystem than React. Leptos generates a JavaScript loader; application code remains Rust. Do not claim that the browser runs no JavaScript at all. + +## Implementation + +- `crates/hph-core/src/lib.rs`: catalog and dependencies, user identity and company membership, attendance state machine, closed-interval calculations and tests. +- `migrations/0001_company_data.sql`: multi-company PostgreSQL schema and RLS policies; `migrations/tests/tenant_isolation.sql` verifies visibility and cross-company writes. +- `src/database.rs`: SQLx pool, runtime migrator, health check and transactions with transaction-local RLS context. +- `src/module_repository.rs`: atomic company module reads/writes under RLS, active membership and admin role checks. Not connected to server functions until an authenticated session provides verified UUIDs. +- `src/membership_repository.rs`: resolves an actor from a persisted active membership in the selected tenant, given an identity and tenant selection validated by the authentication layer. +- `src/app.rs`: dashboard, demo directory, time tracking, reports, module configuration and shared components. +- `src/api.rs`: snapshot, configuration and time-entry server functions. The acting identity comes from server context. +- `src/server.rs`: configuration, in-memory demo state, Axum router and HTTP/SSR tests; optional PostgreSQL health check. +- `src/main.rs`: startup requires HPH_DEMO=true and a loopback address; runtime pool and separate migrator are optional environment settings. +- `style/main.css`: visual design, tokens and mobile styles; no remote fonts or assets required. +- `Cargo.lock`: resolved versions; `rust-toolchain.toml`: toolchain and target. +- `.github/workflows/ci.yml`: formatting, SSR tests, WASM check and PostgreSQL integration. + +## Modules + +Initial company configuration can use a preset or an explicit validated list in hph.toml; the UI can change the selection during the demo. Production runtime configuration must be persisted and authorized per organization. + +Core is always active. People contains read-only synthetic profiles. Attendance depends on People; Reports depends on Attendance. Disabling modules preserves events; open work sessions prevent Attendance from being disabled. Reports show closed work intervals in the session, excluding breaks. + +## Current boundaries + +This is a local demo with a synthetic administrator membership. Identity/membership contracts, RLS schema, module repository and persisted membership repository are covered by CI. Login, sessions and connecting repositories to server functions are not integrated. The tenant is modeled and tested in the domain, but this does not prove a secure multi-company service. Data and module changes reset on restart. Refreshing other tabs is manual. + +Supporting multiple companies requires verified membership, mandatory tenant scope on queries/mutations, migrations, constraints and database isolation tests. No real data before this phase is complete. + +Timestamps are UTC and server-generated; sequences are validated. Company calendars, display time zones, contract rules, rounding, corrections/audit and retry idempotency require dedicated application implementation. + +## Customization model + +HPH Core remains shared. Modules are versioned Rust features in the template, selectable by company administrators and enforced on the server. Disabling them hides and blocks their operations without deleting data. The demo applies the selection to one in-memory workspace. Persistent configuration must be associated with the organization. The deployment model—dedicated instance or multi-company service—remains open, so the tenant boundary must stay explicit from the start. + +## Product evolution + +First target operational workflow: authentication, a real employee directory, persistent time entries and manager oversight. Then leave requests and an attendance calendar. Shifts, documents, expenses, projects, customers, invoicing, inventory and integrations remain candidate modules. Payroll and accounting require separate specifications. + +## Reading order + +- [Project state](PROJECT_STATE.md): evidence and next action. +- [Startup and limitations](../README.md). +- [Module contract](../docs/MODULES.md). + +Primary references consulted: https://book.leptos.dev/getting_started/index.html ; https://book.leptos.dev/ssr/21_cargo_leptos.html ; https://github.com/leptos-rs/start-axum ; https://docs.rs/axum/latest/axum/ ; https://www.postgresql.org/docs/current/ddl-rowsecurity.html . diff --git a/harness/PROJECT_STATE.md b/harness/PROJECT_STATE.md index 3b80608..2d06823 100644 --- a/harness/PROJECT_STATE.md +++ b/harness/PROJECT_STATE.md @@ -1,133 +1,156 @@ -# HPH — Stato operativo +# HPH — Project state -## Obiettivo e fase -Costruire un gestionale aziendale modulare e riutilizzabile, con frontend/backend Rust e un'interfaccia curata. La preferenza Rust anche per il frontend sostituisce la scelta frontend aperta nel kickoff. +## Goal and phase -Ultimo incremento completato: repository SQLx per la membership persistita, **verified** e integrato in `main` con PR #7, merge `812a5bb21b232039151dd375b4671d019588e284`. Run CI [38466818515](https://github.com/Stcant/HPH/actions/runs/38466818515) verde: job `checks` e `database`; lookup tenant-scoped e rifiuto delle membership assenti o revocate sotto RLS. PR #6 è integrata in `main` con merge `231762216f4582e5e7ffe0550497d975f7f153c6`; Actions run [38465298093](https://github.com/Stcant/HPH/actions/runs/38465298093) verde sul commit `85573ff444bebe43d7a09da848bd08a80608b601`. Il progetto complessivo resta in progress; autenticazione e QA browser mancano. -Checkpoint originario: 2026-10-12. Repository pubblica `Stcant/HPH` (portfolio). Lavoro e verifiche eseguiti tramite GitHub; clone locale e test locali non disponibili in questo ambiente. CI GitHub è il gate eseguibile. +Build a reusable modular business management application with a Rust frontend/backend and a carefully designed interface. The preference for Rust on the frontend supersedes the open frontend choice from the kickoff. -## Decisioni -Leptos + Axum; core di dominio indipendente; catalogo e dipendenze dei moduli; CSS responsive e temi; PostgreSQL con SQLx per pool, migrazioni e contesto tenant transazionale; repository applicativi restano da integrare. La lista iniziale dei moduli è configurazione persistente per installazione, validata all'avvio. Le modifiche runtime demo restano temporanee; PostgreSQL dovrà persistere la configurazione per organizzazione. Il modello di deploy (istanza dedicata o multi-azienda) resta aperto. Dettagli e confini in [PROJECT_MAP.md](PROJECT_MAP.md). +Current increment: English throughout the repository and interface, plus a recruiter Easter egg in the README. Status: **verified** in PR #8 on `chore/english-language`; merge follows the final checkpoint checks. Scope: interface and accessibility text, domain/server errors, English HTML language, unambiguous UTC date display, documentation and existing SSR assertions. Acceptance: English content across maintained files, a readable expandable README note, and passing formatting/SSR/WASM/PostgreSQL checks. No authentication or persistence behavior changes are included. -## Risultato implementato -- Dashboard, persone demo in sola lettura, timbrature, riepiloghi e configurazione moduli. -- Preset essential/team/complete e temi sage/indigo in hph.toml; lista esplicita di moduli aziendali supportata come override persistente del preset, con dipendenze e duplicati validati all'avvio. -- Server function reali e stato in memoria: entrata, pausa, rientro, uscita; sequenze e orario verificati dal server. -- Attivazione con dipendenze e permesso amministratore nel dominio; disattivazione senza cancellazione degli eventi e senza interrompere sessioni aperte. -- Avvio solo con HPH_DEMO=true e binding loopback. Un attore e un'azienda sintetici: nessuna autenticazione o persistenza reale. -- README di avvio, contratto di estensione moduli e workflow CI. +Previous completed increment: persisted membership SQLx repository, **verified** and integrated into `main` by PR #7, merge `812a5bb21b232039151dd375b4671d019588e284`. CI run [38466818515](https://github.com/Stcant/HPH/actions/runs/38466818515) passed both `checks` and `database`, including tenant-scoped lookup and rejection of missing or revoked memberships under RLS. PR #6 was integrated with merge `231762216f4582e5e7ffe0550497d975f7f153c6`; run [38465298093](https://github.com/Stcant/HPH/actions/runs/38465298093) passed on commit `85573ff444bebe43d7a09da848bd08a80608b601`. Post-merge CI [38467158574](https://github.com/Stcant/HPH/actions/runs/38467158574) passed on `1d58132cba643ba740804275056b6c22fca15050`, the base of this language change. The overall project remains in progress; authentication and browser QA are still missing. -## Evidenza del 2026-10-12 -Scope: sorgenti del primo template salvati insieme a questo checkpoint; test applicati prima del commit remoto. La cronologia del commit identifica i file. Nessun test browser o database è implicato. +Original checkpoint: 2026-10-12. Current update: 2026-10-13. Public portfolio repository: `Stcant/HPH`. Source files are available as a local snapshot fetched through GitHub; there is no local Git checkout or Rust toolchain. Rust and PostgreSQL verification runs through GitHub Actions. -| Criterio | Risultato | Azione ed evidenza | +## Decisions + +Leptos + Axum; independent domain core; module catalog and dependencies; responsive CSS and themes; PostgreSQL/SQLx for pooling, migrations and transaction-local tenant context. Application repositories still need to be integrated into the screens. The initial module list is persistent installation configuration validated at startup; interactive demo changes remain temporary. PostgreSQL will persist runtime configuration per organization. The deployment model (dedicated instance or multi-company service) remains open. English is the default language for maintained repository content and the UI. Details and boundaries are in [PROJECT_MAP.md](PROJECT_MAP.md). + +## Implemented result + +- Dashboard, read-only demo people directory, time tracking, summaries and module configuration. +- essential/team/complete presets and sage/indigo themes in hph.toml; an explicit company module list can persistently override the preset, with dependency and duplicate validation at startup. +- Real server functions with in-memory state: clock in, start break, end break and clock out; sequence and timestamp validation on the server. +- Dependency and administrator checks for activation in the domain; disabling modules preserves events and does not interrupt open work sessions. +- Startup only with HPH_DEMO=true and loopback binding. One synthetic actor and company: no authenticated or persistent operational application yet. +- Startup README, module extension contract and CI workflow. + +## Evidence from 2026-10-12 + +Scope: initial template sources saved with this checkpoint; tests ran before the remote commit. Commit history identifies the files. No browser or database verification is implied by this historical evidence. + +| Criterion | Result | Action and evidence | | --- | --- | --- | -| Regole moduli, tenant e timbrature | PASS | cargo test --workspace --features ssr --locked: 6 test hph-core superati | -| RPC reali e applicazione regole lato HTTP | PASS | Stesso comando: 2 test del router Axum superati; doppia entrata, modulo spento e dipendenze respinti | -| Rendering server della pagina completa | PASS | Stesso comando: 1 test SSR superato; nome azienda, avviso demo, contenuto e CSS presenti | -| Build frontend e backend | PASS | cargo-leptos 0.3.11 build: binario SSR, libreria WASM, CSS e loader generati; exit 0 | -| Formattazione | PASS | cargo fmt --all --check: exit 0 | -| Avvio demo esplicito e binding locale | PASS | Esecuzione del binario senza HPH_DEMO=true e con 0.0.0.0: rifiuto verificato in entrambi i casi | -| Aspetto, mobile, navigazione e hydration nel browser | NOT RUN | Browser QA non disponibile nell'ambiente; build e SSR non provano interazione o resa visiva | -| Autenticazione, PostgreSQL e isolamento multi-azienda | NOT RUN | Non implementati; appartengono al prossimo incremento | +| Module, tenant and time-tracking rules | PASS | cargo test --workspace --features ssr --locked: 6 hph-core tests passed | +| Real RPCs and HTTP rule enforcement | PASS | Same command: 2 Axum router tests passed; duplicate clock-in, disabled module and invalid dependencies rejected | +| Full-page server rendering | PASS | Same command: 1 SSR test passed; company name, demo notice, content and CSS present | +| Frontend and backend build | PASS | cargo-leptos 0.3.11 build: SSR binary, WASM library, CSS and loader generated; exit 0 | +| Formatting | PASS | cargo fmt --all --check: exit 0 | +| Explicit demo startup and local binding | PASS | Running without HPH_DEMO=true and with 0.0.0.0 was rejected in both cases | +| Visual appearance, mobile, navigation and browser hydration | NOT RUN | Browser QA unavailable; build and SSR do not prove interaction or visual quality | +| Authentication, PostgreSQL and multi-company isolation | NOT RUN | Not implemented at that checkpoint; subsequent increments are recorded below | -## Incremento: selezione personalizzata dei moduli — 2026-10-13 +## Increment: custom module selection — 2026-10-13 -Scope: override `modules` di `hph.toml`, mantenimento dei preset, validazione delle dipendenze e dei duplicati. Commit sorgenti: `8f350db4aec6c1dc3974c6d67086dd9079ace1da`. +Scope: hph.toml `modules` override, preserving presets and validating dependencies/duplicates. Source commit: `8f350db4aec6c1dc3974c6d67086dd9079ace1da`. -| Criterio | Risultato | Evidenza | +| Criterion | Result | Evidence | | --- | --- | --- | -| TOML consente una lista aziendale valida che sostituisce il preset | PASS | Test `explicit_company_modules_override_preset_and_invalid_lists_fail`; TOML deserializzato, preset essential sovrascritto da people/attendance/reports | -| Dipendenze mancanti e ID duplicati sono rifiutati senza mutare la selezione | PASS | Test `custom_module_lists_validate_dependencies_and_duplicates` e test config invalida | -| Formattazione, test SSR e check WASM | PASS | [GitHub Actions run 38320041661](https://github.com/Stcant/HPH/actions/runs/38320041661), concluso success. Commit `8f350db4aec6c1dc3974c6d67086dd9079ace1da`; 2026-10-12T23:02:44Z–23:03:55Z. | +| TOML accepts a valid company list that overrides the preset | PASS | `explicit_company_modules_override_preset_and_invalid_lists_fail`: TOML deserialized, essential overridden by people/attendance/reports | +| Missing dependencies and duplicate IDs are rejected without changing the selection | PASS | `custom_module_lists_validate_dependencies_and_duplicates` and invalid configuration test | +| Formatting, SSR tests and WASM check | PASS | [Run 38320041661](https://github.com/Stcant/HPH/actions/runs/38320041661), success on `8f350db4aec6c1dc3974c6d67086dd9079ace1da`; 2026-10-12T23:02:44Z–23:03:55Z | -La selezione statica in `hph.toml` persiste tra riavvii; le modifiche dalla schermata demo restano in memoria. +Static selection in hph.toml persists across restarts; changes made in the demo screen remain in memory. -## Incremento: identità e membership — 2026-10-13 +## Increment: identity and membership — 2026-10-13 -Scope: contratti di dominio per identità utente e membership attiva per azienda; il server demo crea l'attore selezionando una membership esplicita. Non introduce login, sessioni o persistenza. +Scope: domain contracts for user identity and active company membership; the demo server creates the actor from an explicit membership. This increment did not introduce login, sessions or persistence. -| Criterio | Risultato | Evidenza | +| Criterion | Result | Evidence | | --- | --- | --- | -| Un utente può avere ruoli differenti in più aziende | PASS | Test `identity_resolves_only_an_active_membership_in_the_selected_company`: seleziona la membership Employee corretta, rifiuta la membership inattiva e un utente senza membership | -| L'attore demo è derivato da una membership esplicita | PASS | `DemoState::new` chiama `UserIdentity::actor_for` | -| Formattazione, test SSR e check WASM | PASS | [GitHub Actions run 38454681554](https://github.com/Stcant/HPH/actions/runs/38454681554), tutti gli step conclusi success; commit testato `8097d605f6ed95547dec2688cd03ce61c09ee6e3` | +| One user can have different roles in different companies | PASS | `identity_resolves_only_an_active_membership_in_the_selected_company`: selects the correct Employee membership; rejects inactive membership and a user without membership | +| Demo actor is derived from an explicit membership | PASS | DemoState::new calls UserIdentity::actor_for | +| Formatting, SSR tests and WASM check | PASS | [Run 38454681554](https://github.com/Stcant/HPH/actions/runs/38454681554), all steps successful on `8097d605f6ed95547dec2688cd03ce61c09ee6e3` | -Le membership restano in memoria nella demo. L'identità verificata deve arrivare da un middleware di autenticazione e la membership dovrà essere letta dal database prima delle operazioni aziendali. +Demo memberships remain in memory. A verified identity must come from authentication middleware, and membership must be read from the database before company operations. -## Incremento: schema PostgreSQL multi-azienda — 2026-10-13 +## Increment: multi-company PostgreSQL schema — 2026-10-13 -Scope: organizzazioni, identità esterne, persone, membership, moduli configurati e timbrature idempotenti; Row-Level Security scoped per azienda. Il repository SQL non è ancora integrato nell'app Rust. +Scope: organizations, external identities, people, memberships, configured modules and idempotent attendance events; company-scoped Row-Level Security. The SQL repository was not yet integrated into the Rust app. -| Criterio | Risultato | Evidenza | +| Criterion | Result | Evidence | | --- | --- | --- | -| Dati aziendali e coerenza tra organizzazioni | PASS | FK composte legano membership/persona e timbrature/persona alla stessa organizzazione; vincoli univoci e chiave idempotente per timbratura | -| Letture scoped, membership proprie e blocco insert/update/delete cross-company | PASS | Script `migrations/tests/tenant_isolation.sql` eseguito contro PostgreSQL 18 in CI, run 38456551456 | -| Test Rust, formattazione e check WASM | PASS | Job `checks` del run CI 38456551456 | +| Company data and cross-organization consistency | PASS | Composite foreign keys bind membership/person and attendance/person to the same organization; uniqueness constraints and attendance idempotency key | +| Scoped reads, own memberships and blocked cross-company insert/update/delete | PASS | migrations/tests/tenant_isolation.sql executed against PostgreSQL 18 in CI, run 38456551456 | +| Rust tests, formatting and WASM check | PASS | checks job in run 38456551456 | + +The runtime app must set hph.tenant_id and hph.user_id transaction-locally, verify membership and roles in the service, and use a non-owner role without BYPASSRLS. This schema alone does not prove HTTP operation security. -La runtime app dovrà impostare `hph.tenant_id` e `hph.user_id` transazionalmente, verificare membership e ruoli nel servizio e usare un ruolo non proprietario senza `BYPASSRLS`; questo schema da solo non prova la sicurezza delle operazioni HTTP. +## Increment: PostgreSQL schema and tenant isolation — 2026-10-13 -## Incremento: schema PostgreSQL e isolamento tenant — 2026-10-13 +Scope: initial schema for organizations, external identities, people, memberships, company modules and attendance events; forced RLS on company tables; SQL tests with a runtime role without bypass privileges. This increment did not add SQLx repositories to the app. -Scope: schema iniziale per organizzazioni, identità esterne, persone, membership, moduli aziendali e timbrature; RLS forzata sulle tabelle aziendali; test SQL con ruolo runtime senza privilegi di bypass. Non introduce repository SQLx nell'app. +| Criterion | Result | Evidence | +| --- | --- | --- | +| PostgreSQL migration applies | PASS | database job in CI run 38456551456 | +| Tenant-scoped queries do not expose another company's rows | PASS | Automated tests for visibility, cross-company update/delete and insert, and missing tenant context | +| Rust and WASM checks stay green | PASS | checks job in the same CI run | + +## Increment: SQLx application foundation — 2026-10-13 -| Criterio | Risultato | Evidenza | +Verified scope: SQLx PostgreSQL pool for the SSR server; separable migrator using a dedicated role; helper that sets user and tenant only for the transaction's lifetime; optional health check. Server functions still use in-memory demo state. + +| Criterion | Result | Evidence | | --- | --- | --- | -| La migrazione PostgreSQL si applica | PASS | Job `database` del run CI 38456551456 | -| Le query tenant-scoped non espongono righe di un'altra azienda | PASS | Test automatici di visibilità, update/delete cross-company, insert cross-company e assenza del contesto tenant | -| Verifiche Rust e WASM restano verdi | PASS | Job `checks` dello stesso run CI | +| SQLx pool, migration and tenant context compile | PASS | Run 38460315357: cargo fmt, workspace tests and WASM check passed | +| Migration applies twice and PostgreSQL pool is reachable | PASS | database job in run 38460315357; sqlx_pool_migrates_and_scopes_tenant_context | +| Tenant and user context are transaction-local | PASS | Test reads both values inside the transaction and verifies a null tenant after commit | +| Rust, SSR, WASM and existing RLS checks | PASS | checks and database jobs in [run 38460315357](https://github.com/Stcant/HPH/actions/runs/38460315357), commit `6b3964a4acef3b1241ead813f2980c9b9a140cba` | -## Incremento: fondazione SQLx applicativa — 2026-10-13 +## Increment: SQLx company module repository — 2026-10-13 -Scope verificato: pool PostgreSQL SQLx per il server SSR; migrator separabile con ruolo dedicato; helper che assegna user e tenant solo per la durata di una transazione; health check opzionale. Le server function continuano a usare lo stato demo in memoria. +Added src/module_repository.rs: tenant-scoped reads requiring active membership; atomic writes of every flag with dependency validation and an admin check in the same transaction. An unsaved selection returns None. UI integration is deferred until the synthetic demo identity is replaced by verified UUIDs from an authenticated session. -| Criterio | Risultato | Evidenza | +| Criterion | Result | Evidence | | --- | --- | --- | -| Pool SQLx, migrazione e tenant context compilano | PASS | Run CI 38460315357: cargo fmt, test workspace e check WASM superati | -| Migrazione applicata due volte e pool raggiungibile su PostgreSQL | PASS | Job `database` del run 38460315357; `sqlx_pool_migrates_and_scopes_tenant_context` | -| Tenant e user context sono transaction-local | PASS | Il test legge entrambi i valori nella transazione e verifica il tenant nullo dopo il commit | -| CI Rust, SSR, WASM e RLS preesistente | PASS | Job `checks` e `database` del run [38460315357](https://github.com/Stcant/HPH/actions/runs/38460315357) sul commit `6b3964a4acef3b1241ead813f2980c9b9a140cba` | +| Repository scopes queries and writes to the tenant through RLS context | PASS | PostgreSQL test company_module_selection_is_tenant_scoped_and_admin_only passed in the database job of run 38461693770 | +| Only active admin membership can save configuration | PASS | PostgreSQL test verifies admin round-trip and rejection of the employee role | +| Formatting, SSR tests and WASM check | PASS | checks job in run 38461693770 passed | -## Incremento: repository SQLx per moduli aziendali — 2026-10-13 +## Additional verification: non-owner PostgreSQL runtime role — 2026-10-13 -Aggiunto `src/module_repository.rs`: lettura tenant-scoped per membership attiva; scrittura atomica di tutti i flag, validazione dipendenze e controllo admin nella stessa transazione. Una selezione non ancora salvata è restituita come `None`; l'integrazione UI è rinviata finché l'identità demo sintetica non viene sostituita da UUID verificati di una sessione autenticata. +The first repository test used a superuser connection, so it did not actually exercise RLS policies. The correction separates the fixture/migration admin pool from the hph_runtime pool, created with NOSUPERUSER NOBYPASSRLS; integration tests exercise repository operations through the runtime role. -| Criterio | Risultato | Evidenza | +| Criterion | Result | Evidence | | --- | --- | --- | -| Repository limita query e scritture al tenant tramite contesto RLS | PASS | Test PostgreSQL `company_module_selection_is_tenant_scoped_and_admin_only` superato nel job database del run 38461693770 | -| Solo membership admin attiva può salvare la configurazione | PASS | Test PostgreSQL verifica round-trip admin e rifiuto per ruolo employee | -| Formattazione, test SSR e check WASM | PASS | Job `checks` del run CI 38461693770 superato | +| Repository tested with effective RLS | PASS | company_module_selection_is_tenant_scoped_and_admin_only ran with NOSUPERUSER NOBYPASSRLS; [run 38465298093](https://github.com/Stcant/HPH/actions/runs/38465298093), tested commit `85573ff444bebe43d7a09da848bd08a80608b601` | +| Formatting, SSR tests and WASM check | PASS | checks job in [run 38465298093](https://github.com/Stcant/HPH/actions/runs/38465298093) passed | -## Verifica aggiuntiva: ruolo PostgreSQL runtime non proprietario — 2026-10-13 +## Increment: persisted membership lookup — 2026-10-13 -Il primo test del repository usava una connessione superuser e quindi non esercitava davvero le policy RLS. La correzione separa il pool admin per fixture/migrazioni dal pool runtime `hph_runtime`, creato con `NOSUPERUSER NOBYPASSRLS`; il test di integrazione prova le operazioni repository sotto il ruolo runtime. +Scope: MembershipRepository::resolve_actor(user_id, tenant_id) resolves an actor only from an active membership in the selected tenant, inside an RLS-context transaction. UUIDs must come from an authenticated session; login/session and UI integration are excluded. -| Criterio | Risultato | Evidenza | +| Criterion | Result | Evidence | | --- | --- | --- | -| Repository testato sotto RLS effettiva | PASS | Test `company_module_selection_is_tenant_scoped_and_admin_only` eseguito con ruolo runtime `NOSUPERUSER NOBYPASSRLS`; Actions run [38465298093](https://github.com/Stcant/HPH/actions/runs/38465298093), commit testato `85573ff444bebe43d7a09da848bd08a80608b601` | -| Formattazione, test SSR e check WASM | PASS | Job `checks` del run [38465298093](https://github.com/Stcant/HPH/actions/runs/38465298093) superato | +| Active membership returns the correct person, tenant and role for multi-company users | PASS | Dedicated PostgreSQL test with two tenants and a non-owner runtime role | +| Missing membership in a tenant and revoked membership are rejected | PASS | Dedicated integration test; [run 38466596064](https://github.com/Stcant/HPH/actions/runs/38466596064) | +| Formatting, SSR tests, WASM and PostgreSQL checks | PASS | checks and database jobs in [run 38466596064](https://github.com/Stcant/HPH/actions/runs/38466596064), tested commit `a5617a2e8f68f647feb8a1b07fc379d1776292c8` | -## Incremento: lookup membership persistita — 2026-10-13 +## Increment: English language and recruiter Easter egg — 2026-10-13 -Scope: `MembershipRepository::resolve_actor(user_id, tenant_id)` risolve l'attore solo da una membership attiva nella tenant selezionata, dentro transazione con contesto RLS. Gli UUID devono provenire da sessione autenticata; login/sessione e integrazione UI restano esclusi. +Source commit: `2a21a36cd0700a0c066a971228508b56758f710b`, PR #8. [CI run 38468961276](https://github.com/Stcant/HPH/actions/runs/38468961276) passed both jobs. -| Criterio | Risultato | Evidenza | +| Criterion | Result | Evidence | | --- | --- | --- | -| Membership attiva restituisce persona, tenant e ruolo corretti anche per utenti multi-azienda | PASS | Test PostgreSQL dedicato con due tenant e ruolo runtime non proprietario | -| Tenant senza membership e membership revocata vengono respinti | PASS | Test d'integrazione dedicato; run [38466596064](https://github.com/Stcant/HPH/actions/runs/38466596064) | -| Formattazione, test SSR, check WASM e verifiche PostgreSQL | PASS | Job `checks` e `database` del run [38466596064](https://github.com/Stcant/HPH/actions/runs/38466596064), commit testato `a5617a2e8f68f647feb8a1b07fc379d1776292c8` | +| English UI, errors, accessibility and maintained documentation | PASS | Source review; existing SSR page test checks English content and `lang="en"` | +| Formatting, workspace/SSR tests and WASM compilation | PASS | `checks` job in run 38468961276 | +| PostgreSQL migrations, RLS and repository integration | PASS | `database` job in the same run | +| Expandable recruiter note | PASS | README source contains the recruiter side quest and contact link | +| Visual layout and browser interaction | NOT RUN | No browser QA in this increment | + +## Relevant resolved problems + +- An executor interruption invalidated an initial test run; valid results came from subsequent executions. +- Deeply nested SSR component rendering caused a stack overflow. Component boundaries were converted to AnyView; all 9 tests then passed with the standard stack size. + +## Limitations and open work + +The demo loses data and interactive settings on restart. Profiles are synthetic and the administrator role is fixed. The domain tenant model does not establish isolation for a real service. No deployment or external exposure has been performed. +Leave, time off, shifts, employee CRUD, corrections/audit, application-level idempotency, exports and contract rules remain to be implemented. The GitHub Template repository flag has not been changed. -## Problemi rilevanti risolti -- Un'interruzione dell'esecutore ha invalidato una prima esecuzione dei test; i risultati validi provengono dalle esecuzioni successive. -- Il rendering SSR dei componenti profondamente annidati produceva uno stack overflow. Confini dei componenti resi AnyView; successivamente tutti i 9 test sono passati con la configurazione standard, senza aumentare lo stack. +## Next action -## Limiti e lavoro aperto -La demo perde dati e configurazioni interattive al riavvio. I profili sono sintetici e il ruolo amministratore è fisso. Il modello tenant del dominio non costituisce isolamento di un servizio reale. Nessuna pubblicazione o esposizione esterna. -Ferie, permessi, turni, CRUD dipendenti, rettifiche/audit, idempotenza, esportazioni e regole contrattuali rimangono da implementare. Il flag GitHub Template repository non è stato modificato. +Merge PR #8 after the final checkpoint checks. The next functional increment remains provider-neutral authentication/sessions and connecting session context to repositories; do not use the demo actor for tenant-scoped SQL. Then implement people and attendance repositories. Run desktop/mobile browser QA when an executable build and browser environment are available. A local source snapshot is available, but Rust verification still runs through GitHub CI. -## Prossima azione -Dopo aver integrato il repository membership, progettare autenticazione/sessioni provider-neutral e collegare il contesto di sessione ai repository; non usare l'attore demo per query SQL tenant-scoped. Poi proseguire con repository per persone e presenze. Eseguire QA browser desktop/mobile quando il checkout locale sarà disponibile. Il clone locale non è disponibile in questo ambiente; il controllo Rust avviene tramite CI GitHub. +## Files and reading order -## File e lettura -Codice: Cargo.toml/Cargo.lock, rust-toolchain.toml, crates/hph-core, src e style. Configurazione: hph.toml. Avvio e limiti: [README](../README.md). Estensioni: [MODULES](../docs/MODULES.md). Conservare questi due file harness come stato e mappa canonici. +Code: Cargo.toml/Cargo.lock, rust-toolchain.toml, crates/hph-core, src and style. Configuration: hph.toml. Startup and limitations: [README](../README.md). Extensions: [MODULES](../docs/MODULES.md). Keep these two harness files as the canonical state and map. diff --git a/src/api.rs b/src/api.rs index 64792ba..7ae41be 100644 --- a/src/api.rs +++ b/src/api.rs @@ -7,7 +7,7 @@ pub async fn get_snapshot() -> Result { let workspace = state .workspace .lock() - .map_err(|_| ServerFnError::new("Stato temporaneamente non disponibile."))?; + .map_err(|_| ServerFnError::new("State is temporarily unavailable."))?; workspace .authorize(&state.actor) .map_err(ServerFnError::new)?; @@ -20,7 +20,7 @@ pub async fn configure_module(id: ModuleId, enabled: bool) -> Result<(), ServerF let mut workspace = state .workspace .lock() - .map_err(|_| ServerFnError::new("Stato temporaneamente non disponibile."))?; + .map_err(|_| ServerFnError::new("State is temporarily unavailable."))?; workspace .set_module(&state.actor, id, enabled) .map_err(ServerFnError::new) @@ -33,13 +33,13 @@ pub async fn register_punch(kind: PunchKind) -> Result<(), ServerFnError> { let mut workspace = state .workspace .lock() - .map_err(|_| ServerFnError::new("Stato temporaneamente non disponibile."))?; + .map_err(|_| ServerFnError::new("State is temporarily unavailable."))?; workspace .punch( &state.actor, kind, now.timestamp(), - now.format("%d/%m %H:%M:%S UTC").to_string(), + now.format("%Y-%m-%d %H:%M:%S UTC").to_string(), ) .map_err(ServerFnError::new) } diff --git a/src/app.rs b/src/app.rs index fe8bff8..ce64010 100644 --- a/src/app.rs +++ b/src/app.rs @@ -10,7 +10,7 @@ use leptos_router::{ pub fn shell(options: LeptosOptions) -> AnyView { view! { - + @@ -30,9 +30,9 @@ pub fn App() -> AnyView { provide_meta_context(); view! { - + <Title text="HPH — Work, in harmony"/> <Router> - <Routes fallback=|| view! { <main class="empty"><h1>"Questa pagina non esiste"</h1><a href="/">"Torna a HPH"</a></main> }> + <Routes fallback=|| view! { <main class="empty"><h1>"This page does not exist"</h1><a href="/">"Back to HPH"</a></main> }> <Route path=StaticSegment("") view=WorkspacePage/> </Routes> </Router> @@ -50,11 +50,11 @@ enum Screen { impl Screen { fn title(self) -> &'static str { match self { - Self::Overview => "Panoramica", - Self::People => "Persone", - Self::Attendance => "Presenze", - Self::Reports => "Report", - Self::Modules => "Il tuo workspace", + Self::Overview => "Overview", + Self::People => "People", + Self::Attendance => "Attendance", + Self::Reports => "Reports", + Self::Modules => "Your workspace", } } } @@ -83,10 +83,7 @@ fn dispatch( }; match result { Ok(()) => { - message.set(Some(( - true, - "Modifica registrata nella sessione demo.".into(), - ))); + message.set(Some((true, "Change saved for this demo session.".into()))); refresh.run(()); } Err(error) => message.set(Some((false, error.to_string()))), @@ -103,11 +100,11 @@ fn WorkspacePage() -> AnyView { let message = RwSignal::new(None::<(bool, String)>); let refresh = Callback::new(move |()| snapshot.refetch()); view! { - <a class="skip" href="#main">"Vai al contenuto"</a> - <Suspense fallback=|| view! { <main class="empty" role="status"><div class="brand-mark">"h"</div><h1>"Prepariamo il tuo workspace…"</h1></main> }> + <a class="skip" href="#main">"Skip to content"</a> + <Suspense fallback=|| view! { <main class="empty" role="status"><div class="brand-mark">"h"</div><h1>"Getting your workspace ready…"</h1></main> }> {move || snapshot.get().map(|result| match result { Ok(data) => view! { <WorkspaceView data screen busy message refresh/> }.into_any(), - Err(error) => view! { <main class="empty"><h1>"Non riusciamo a caricare il workspace"</h1><p>{error.to_string()}</p><button class="primary" on:click=move |_| snapshot.refetch()>"Riprova"</button></main> }.into_any(), + Err(error) => view! { <main class="empty"><h1>"We could not load your workspace"</h1><p>{error.to_string()}</p><button class="primary" on:click=move |_| snapshot.refetch()>"Try again"</button></main> }.into_any(), })} </Suspense> }.into_any() @@ -156,9 +153,9 @@ fn WorkspaceView( let data = StoredValue::new(data); view! { <div class="workspace" data-theme=theme> - <aside class="sidebar" aria-label="Navigazione principale"> - <a href="/" class="brand" aria-label="HPH, pagina iniziale"><span class="brand-mark">"h"</span><span>"hph"<span class="brand-dot">"."</span></span></a> - <div class="org"><span class="org-icon">"A"</span><div><strong>{organization}</strong><small>"Workspace dimostrativo"</small></div></div> + <aside class="sidebar" aria-label="Main navigation"> + <a href="/" class="brand" aria-label="HPH home"><span class="brand-mark">"h"</span><span>"hph"<span class="brand-dot">"."</span></span></a> + <div class="org"><span class="org-icon">"A"</span><div><strong>{organization}</strong><small>"Demo workspace"</small></div></div> <div class="nav-heading">"WORKSPACE"</div> <nav> <NavItem target=Screen::Overview screen icon="grid"/> @@ -168,13 +165,13 @@ fn WorkspaceView( <div class="nav-divider"></div> <NavItem target=Screen::Modules screen icon="modules"/> </nav> - <div class="sidebar-bottom"><div class="build-note"><Icon name="spark"/><strong>"Spazio alle tue idee."</strong><p>"Componi il gestionale intorno al tuo modo di lavorare."</p><button on:click=move |_| screen.set(Screen::Modules)>"Esplora i moduli →"</button></div> - <div class="profile"><span class="avatar">"EC"</span><div><strong>"Elena Conti"</strong><small>"Amministratrice demo"</small></div><span class="online-dot"></span></div></div> + <div class="sidebar-bottom"><div class="build-note"><Icon name="spark"/><strong>"Room for your ideas."</strong><p>"Build your workspace around the way you work."</p><button on:click=move |_| screen.set(Screen::Modules)>"Explore modules →"</button></div> + <div class="profile"><span class="avatar">"EC"</span><div><strong>"Elena Conti"</strong><small>"Demo administrator"</small></div><span class="online-dot"></span></div></div> </aside> <div class="main-wrap"> - <header class="topbar"><div class="breadcrumb">"Workspace"<span>"/"</span><strong>{move || screen.get().title()}</strong></div><div class="top-actions"><span class="demo-badge">"DEMO LOCALE"</span><button class="icon-button" aria-label="Aggiorna i dati" disabled=move || busy.get() on:click=move |_| refresh.run(())>"↻"</button></div></header> + <header class="topbar"><div class="breadcrumb">"Workspace"<span>"/"</span><strong>{move || screen.get().title()}</strong></div><div class="top-actions"><span class="demo-badge">"LOCAL DEMO"</span><button class="icon-button" aria-label="Refresh data" disabled=move || busy.get() on:click=move |_| refresh.run(())>"↻"</button></div></header> <main id="main"> - <div class="demo-notice">"Dati di esempio · nessun account reale · le modifiche si azzerano al riavvio del server."</div> + <div class="demo-notice">"Sample data · no real accounts · changes reset when the server restarts."</div> <div role="status" aria-live="polite">{move || message.get().map(|(ok, text)| view! { <div class="notice" class:error=!ok>{text}</div> })}</div> {move || { let snapshot = data.get_value(); @@ -184,10 +181,10 @@ fn WorkspaceView( Screen::Attendance if attendance_enabled => view! { <Attendance data=snapshot busy message refresh/> }.into_any(), Screen::Reports if reports_enabled => view! { <Reports data=snapshot/> }.into_any(), Screen::Modules => view! { <Modules data=snapshot busy message refresh/> }.into_any(), - _ => view! { <section class="empty"><h1>"Questo modulo è disattivato"</h1><p>"Puoi riattivarlo dal tuo workspace. I dati della sessione vengono conservati."</p><button class="primary" on:click=move |_| screen.set(Screen::Modules)>"Configura i moduli"</button></section> }.into_any(), + _ => view! { <section class="empty"><h1>"This module is disabled"</h1><p>"You can enable it again in your workspace. Session data is preserved."</p><button class="primary" on:click=move |_| screen.set(Screen::Modules)>"Configure modules"</button></section> }.into_any(), } }} - <footer>"HPH · Il lavoro, in armonia."<span>"Anteprima 0.1 · Rust / Leptos"</span></footer> + <footer>"HPH · Work, in harmony."<span>"Preview 0.1 · Rust / Leptos"</span></footer> </main> </div> </div> @@ -214,20 +211,20 @@ fn Overview( let active = data.workspace.modules.enabled.len(); let events = data.workspace.punches.len(); view! { - <div class="page-heading"><div><p class="eyebrow">"IL TUO SPAZIO DI LAVORO"</p><h1>"Tutto al posto giusto."</h1><p>"Persone, tempo e strumenti. Finalmente insieme."</p></div><button class="secondary" on:click=move |_| screen.set(Screen::Modules)><Icon name="modules"/>"Personalizza workspace"</button></div> - <section class="hero"><div><div class="hero-kicker"><span class="tiny-dot"></span>"UN BUON LAVORO INIZIA QUI"</div><h2>"Meno complessità."<br/>"Più spazio alle persone."</h2><p>"Un workspace che cresce con te. Scegli ciò che serve al tuo team e costruisci il resto, un modulo alla volta."</p><button class="hero-button" on:click=move |_| screen.set(Screen::Modules)>"Crea il tuo equilibrio"<Icon name="arrow"/></button></div><div class="hero-art" aria-hidden="true"><div class="arch arch-one"></div><div class="arch arch-two"></div><div class="arch arch-three"></div><div class="floating-card"><span class="icon-tile"><Icon name="check"/></span><div><strong>"Il tuo team."</strong><span>"Il tuo modo di lavorare."</span></div></div><span class="hero-star">"✳"</span></div></section> + <div class="page-heading"><div><p class="eyebrow">"YOUR WORKSPACE"</p><h1>"Everything in its place."</h1><p>"People, time and tools. Finally together."</p></div><button class="secondary" on:click=move |_| screen.set(Screen::Modules)><Icon name="modules"/>"Customize workspace"</button></div> + <section class="hero"><div><div class="hero-kicker"><span class="tiny-dot"></span>"GOOD WORK STARTS HERE"</div><h2>"Less complexity."<br/>"More room for people."</h2><p>"A workspace that grows with you. Choose what your team needs and build the rest, one module at a time."</p><button class="hero-button" on:click=move |_| screen.set(Screen::Modules)>"Find your balance"<Icon name="arrow"/></button></div><div class="hero-art" aria-hidden="true"><div class="arch arch-one"></div><div class="arch arch-two"></div><div class="arch arch-three"></div><div class="floating-card"><span class="icon-tile"><Icon name="check"/></span><div><strong>"Your team."</strong><span>"Your way of working."</span></div></div><span class="hero-star">"✳"</span></div></section> <div class="stats-grid"> - <Stat title="Persone nel team" value=if people { total.to_string() } else { "—".into() } note=if people { "Profili dimostrativi" } else { "Modulo non attivo" } icon="people"/> - <Stat title="Al lavoro adesso" value=if attendance { working.to_string() } else { "—".into() } note="Da timbrature della sessione" icon="clock"/> - <Stat title="Eventi registrati" value=if attendance { events.to_string() } else { "—".into() } note="Entrate, pause e uscite" icon="chart"/> - <Stat title="Moduli attivi" value=format!("{active} / 3") note="Un workspace su misura" icon="modules"/> + <Stat title="People on the team" value=if people { total.to_string() } else { "—".into() } note=if people { "Demo profiles" } else { "Module disabled" } icon="people"/> + <Stat title="Working now" value=if attendance { working.to_string() } else { "—".into() } note="From this session’s time entries" icon="clock"/> + <Stat title="Recorded events" value=if attendance { events.to_string() } else { "—".into() } note="Clock-ins, breaks and clock-outs" icon="chart"/> + <Stat title="Active modules" value=format!("{active} / 3") note="A workspace that fits" icon="modules"/> </div> - <div class="content-grid"><section class="panel"><div class="panel-heading"><div><h2>"Il tuo team"</h2><p>"Le persone al centro, ogni giorno."</p></div>{people.then(|| view! { <button class="text-button" on:click=move |_| screen.set(Screen::People)>"Tutte le persone →"</button> })}</div> - {if people { view! { <PeopleTable data=data.clone()/> }.into_any() } else { view! { <div class="empty small"><Icon name="people"/><p>"Attiva il modulo Persone per iniziare."</p></div> }.into_any() }}</section> - <section class="panel time-panel"><div class="panel-heading"><div><p class="eyebrow">"IL TUO TEMPO"</p><h2>"Un gesto. Sei al lavoro."</h2></div><Icon name="clock"/></div> - {if attendance { view! { <PunchCard data=data.clone() busy message refresh/> }.into_any() } else { view! { <p>"Attiva Timbrature e presenze per registrare la tua giornata."</p> }.into_any() }} + <div class="content-grid"><section class="panel"><div class="panel-heading"><div><h2>"Your team"</h2><p>"People at the heart of every day."</p></div>{people.then(|| view! { <button class="text-button" on:click=move |_| screen.set(Screen::People)>"View everyone →"</button> })}</div> + {if people { view! { <PeopleTable data=data.clone()/> }.into_any() } else { view! { <div class="empty small"><Icon name="people"/><p>"Enable the People module to get started."</p></div> }.into_any() }}</section> + <section class="panel time-panel"><div class="panel-heading"><div><p class="eyebrow">"YOUR TIME"</p><h2>"One click. You’re clocked in."</h2></div><Icon name="clock"/></div> + {if attendance { view! { <PunchCard data=data.clone() busy message refresh/> }.into_any() } else { view! { <p>"Enable Time and attendance to record your day."</p> }.into_any() }} </section></div> - <section class="bottom-banner"><div class="icon-tile"><Icon name="modules"/></div><div><h3>"Il gestionale segue te. Non il contrario."</h3><p>"Attiva solo i moduli utili. Una base condivisa, possibilità da costruire."</p></div><button class="text-button" on:click=move |_| screen.set(Screen::Modules)>"Configura HPH →"</button></section> + <section class="bottom-banner"><div class="icon-tile"><Icon name="modules"/></div><div><h3>"Business software built around you."</h3><p>"Enable the modules you need. A shared foundation with room to grow."</p></div><button class="text-button" on:click=move |_| screen.set(Screen::Modules)>"Configure HPH →"</button></section> }.into_any() } @@ -241,14 +238,14 @@ fn PeopleTable(data: Snapshot) -> AnyView { let attendance = data.workspace.modules.contains(ModuleId::Attendance); let rows = data.workspace.people.iter().map(|person| { let state = data.workspace.state(&person.id); - view! { <tr><td><div class="person"><span class="avatar">{person.initials.clone()}</span><div><strong>{person.name.clone()}</strong><small>{person.job.clone()}</small></div></div></td><td>{person.department.clone()}</td><td><span class="status" class:working=state==WorkState::Working class:paused=state==WorkState::Paused>{if attendance { state.label() } else { "Non rilevato" }}</span></td></tr> } + view! { <tr><td><div class="person"><span class="avatar">{person.initials.clone()}</span><div><strong>{person.name.clone()}</strong><small>{person.job.clone()}</small></div></div></td><td>{person.department.clone()}</td><td><span class="status" class:working=state==WorkState::Working class:paused=state==WorkState::Paused>{if attendance { state.label() } else { "Not tracked" }}</span></td></tr> } }).collect_view(); - view! { <div class="table-scroll"><table><caption class="sr-only">"Persone e stato di presenza della sessione demo"</caption><thead><tr><th scope="col">"PERSONA"</th><th scope="col">"REPARTO"</th><th scope="col">"STATO"</th></tr></thead><tbody>{rows}</tbody></table></div> }.into_any() + view! { <div class="table-scroll"><table><caption class="sr-only">"People and attendance status in the demo session"</caption><thead><tr><th scope="col">"PERSON"</th><th scope="col">"DEPARTMENT"</th><th scope="col">"STATUS"</th></tr></thead><tbody>{rows}</tbody></table></div> }.into_any() } #[component] fn People(data: Snapshot) -> AnyView { - view! { <div class="page-heading"><div><p class="eyebrow">"PERSONE"</p><h1>"Il valore è nel team."</h1><p>"Anagrafica dimostrativa. La gestione dei profili arriverà nel prossimo incremento."</p></div><span class="pill">{format!("{} persone", data.workspace.people.len())}</span></div><section class="panel"><PeopleTable data/></section> }.into_any() + view! { <div class="page-heading"><div><p class="eyebrow">"PEOPLE"</p><h1>"Your team makes the difference."</h1><p>"Demo directory. Profile management is planned for a future update."</p></div><span class="pill">{format!("{} people", data.workspace.people.len())}</span></div><section class="panel"><PeopleTable data/></section> }.into_any() } #[component] @@ -272,9 +269,9 @@ fn PunchCard( .find(|p| p.person_id == data.actor_id) .map(|p| p.label.clone()); view! { - <div class="clock-face"><div class="clock-ring"><Icon name="clock"/></div><span class="status" class:working=state==WorkState::Working class:paused=state==WorkState::Paused>{state.label()}</span><h3>{match state { WorkState::Off => "Pronta quando vuoi.", WorkState::Working => "Buon lavoro, Elena.", WorkState::Paused => "Prenditi il tuo tempo." }}</h3><p>{last.map(|value| format!("Ultimo evento: {value}")).unwrap_or_else(|| "Nessuna timbratura nella sessione.".into())}</p></div> + <div class="clock-face"><div class="clock-ring"><Icon name="clock"/></div><span class="status" class:working=state==WorkState::Working class:paused=state==WorkState::Paused>{state.label()}</span><h3>{match state { WorkState::Off => "Ready when you are.", WorkState::Working => "Have a good day, Elena.", WorkState::Paused => "Enjoy your break." }}</h3><p>{last.map(|value| format!("Last event: {value}")).unwrap_or_else(|| "No time entries in this session.".into())}</p></div> <div class="punch-actions">{buttons.into_iter().map(|kind| view! { <button class="primary" disabled=move || busy.get() on:click=move |_| dispatch(Command::Punch(kind), busy, message, refresh)>{kind.label()}<Icon name="arrow"/></button> }).collect_view()}</div> - <p class="microcopy">"Ora registrata dal server · UTC · profilo demo Elena Conti"</p> + <p class="microcopy">"Server-recorded time · UTC · demo profile Elena Conti"</p> }.into_any() } @@ -287,7 +284,7 @@ fn Attendance( ) -> AnyView { let events = data.workspace.punches.iter().rev().map(|p| view! { <li><span class="event-dot"></span><div><strong>{p.kind.label()}</strong><small>{p.label.clone()}</small></div><span class="pill">"Elena Conti"</span></li> }).collect_view(); let empty = data.workspace.punches.is_empty(); - view! { <div class="page-heading"><div><p class="eyebrow">"PRESENZE"</p><h1>"Ogni giornata ha il suo ritmo."</h1><p>"Registra entrate, pause e uscite. Tutti gli orari sono espressi in UTC."</p></div></div><div class="attendance-grid"><section class="panel time-panel"><h2>"La tua timbratura"</h2><PunchCard data=data.clone() busy message refresh/></section><section class="panel"><div class="panel-heading"><div><h2>"Attività della sessione"</h2><p>"Gli eventi vengono controllati e registrati dal server."</p></div></div>{empty.then(|| view! { <div class="empty small"><Icon name="clock"/><h3>"Una nuova giornata ti aspetta"</h3><p>"Registra la prima entrata: comparirà qui."</p></div> })}<ol class="event-list">{events}</ol></section></div> }.into_any() + view! { <div class="page-heading"><div><p class="eyebrow">"ATTENDANCE"</p><h1>"Every day has its own rhythm."</h1><p>"Record clock-ins, breaks and clock-outs. All times are shown in UTC."</p></div></div><div class="attendance-grid"><section class="panel time-panel"><h2>"Your time entry"</h2><PunchCard data=data.clone() busy message refresh/></section><section class="panel"><div class="panel-heading"><div><h2>"Session activity"</h2><p>"Events are validated and recorded by the server."</p></div></div>{empty.then(|| view! { <div class="empty small"><Icon name="clock"/><h3>"A new day awaits"</h3><p>"Clock in for the first time and your entry will appear here."</p></div> })}<ol class="event-list">{events}</ol></section></div> }.into_any() } #[component] @@ -296,7 +293,7 @@ fn Reports(data: Snapshot) -> AnyView { let seconds = data.workspace.recorded_seconds(&p.id); view! { <tr><td>{p.name.clone()}</td><td>{format!("{}h {:02}m {:02}s", seconds / 3600, seconds % 3600 / 60, seconds % 60)}</td><td>{data.workspace.state(&p.id).label()}</td></tr> } }).collect_view(); - view! { <div class="page-heading"><div><p class="eyebrow">"REPORT"</p><h1>"Il tempo, con chiarezza."</h1><p>"Riepilogo della sessione demo, calcolato dalle timbrature."</p></div></div><section class="panel"><div class="panel-heading"><div><h2>"Tempo registrato per persona"</h2><p>"Solo intervalli chiusi da una pausa o un'uscita. Pause escluse; intervallo in corso non conteggiato."</p></div></div><div class="table-scroll"><table><thead><tr><th scope="col">"PERSONA"</th><th scope="col">"TEMPO REGISTRATO"</th><th scope="col">"STATO"</th></tr></thead><tbody>{rows}</tbody></table></div></section><p class="microcopy">"Questo riepilogo non applica regole contrattuali, arrotondamenti, straordinari o calcoli paghe."</p> }.into_any() + view! { <div class="page-heading"><div><p class="eyebrow">"REPORTS"</p><h1>"A clearer view of time."</h1><p>"A summary of the demo session, calculated from time entries."</p></div></div><section class="panel"><div class="panel-heading"><div><h2>"Recorded time per person"</h2><p>"Only intervals closed by a break or clock-out. Breaks and the current open interval are excluded."</p></div></div><div class="table-scroll"><table><thead><tr><th scope="col">"PERSON"</th><th scope="col">"RECORDED TIME"</th><th scope="col">"STATUS"</th></tr></thead><tbody>{rows}</tbody></table></div></section><p class="microcopy">"This summary does not apply contract rules, rounding, overtime or payroll calculations."</p> }.into_any() } #[component] @@ -309,10 +306,10 @@ fn Modules( let cards = data.catalog.into_iter().map(|definition| { let id = definition.id; let enabled = data.workspace.modules.contains(id); - let dependency = match id { ModuleId::People => "Nessuna dipendenza", ModuleId::Attendance => "Richiede Persone", ModuleId::Reports => "Richiede Timbrature e presenze" }; + let dependency = match id { ModuleId::People => "No dependencies", ModuleId::Attendance => "Requires People", ModuleId::Reports => "Requires Time and attendance" }; let icon = match id { ModuleId::People => "people", ModuleId::Attendance => "clock", ModuleId::Reports => "chart" }; - let label = format!("{} {}", if enabled { "Disattiva" } else { "Attiva" }, definition.name); - view! { <article class="module-card" class:enabled><div class="module-top"><span class="icon-tile"><Icon name=icon/></span><span class="pill" class:active-pill=enabled>{if enabled { "Attivo" } else { "Disponibile" }}</span></div><h2>{definition.name}</h2><p>{definition.description}</p><small>{dependency}</small><button class="module-toggle" role="switch" aria-label=label aria-checked=enabled.to_string() disabled=move || busy.get() on:click=move |_| dispatch(Command::Module(id, !enabled), busy, message, refresh)><span>{if enabled { "Modulo attivo" } else { "Attiva modulo" }}</span><span class="switch" class:on=enabled><span></span></span></button></article> } + let label = format!("{} {}", if enabled { "Disable" } else { "Enable" }, definition.name); + view! { <article class="module-card" class:enabled><div class="module-top"><span class="icon-tile"><Icon name=icon/></span><span class="pill" class:active-pill=enabled>{if enabled { "Active" } else { "Available" }}</span></div><h2>{definition.name}</h2><p>{definition.description}</p><small>{dependency}</small><button class="module-toggle" role="switch" aria-label=label aria-checked=enabled.to_string() disabled=move || busy.get() on:click=move |_| dispatch(Command::Module(id, !enabled), busy, message, refresh)><span>{if enabled { "Module enabled" } else { "Enable module" }}</span><span class="switch" class:on=enabled><span></span></span></button></article> } }).collect_view(); - view! { <div class="page-heading"><div><p class="eyebrow">"IL TUO WORKSPACE"</p><h1>"Scegli ciò che ti serve."</h1><p>"Una base solida. I moduli giusti. Un gestionale che ti somiglia."</p></div></div><section class="core-banner"><span class="icon-tile"><Icon name="check"/></span><div><h2>"HPH Core"</h2><p>"Configurazione, design condiviso e regole dei moduli. Sempre presente."</p></div><span class="pill">"Incluso"</span></section><div class="module-grid">{cards}</div><section class="panel next-modules"><p class="eyebrow">"DA COSTRUIRE INSIEME"</p><h2>"Il prossimo capitolo."</h2><p>"Ferie e permessi, turni, documenti, note spese e commesse sono possibili estensioni. Non sono ancora implementate."</p><div class="roadmap-tags"><span>"Ferie e permessi"</span><span>"Turni"</span><span>"Documenti"</span><span>"Commesse"</span></div></section><p class="microcopy">"Le dipendenze vengono verificate sul server. Disattivare un modulo non elimina i dati; le presenze richiedono la chiusura delle sessioni aperte."</p> }.into_any() + view! { <div class="page-heading"><div><p class="eyebrow">"YOUR WORKSPACE"</p><h1>"Choose what you need."</h1><p>"A solid foundation. The right modules. A workspace that feels like yours."</p></div></div><section class="core-banner"><span class="icon-tile"><Icon name="check"/></span><div><h2>"HPH Core"</h2><p>"Configuration, shared design and module rules. Always included."</p></div><span class="pill">"Included"</span></section><div class="module-grid">{cards}</div><section class="panel next-modules"><p class="eyebrow">"BUILDING WHAT COMES NEXT"</p><h2>"The next chapter."</h2><p>"Leave, shifts, documents, expenses and projects are possible extensions. They are not implemented yet."</p><div class="roadmap-tags"><span>"Leave and time off"</span><span>"Shifts"</span><span>"Documents"</span><span>"Projects"</span></div></section><p class="microcopy">"Dependencies are checked on the server. Disabling a module preserves its data; attendance requires all open sessions to be closed."</p> }.into_any() } diff --git a/src/main.rs b/src/main.rs index f329e1d..019e2e4 100644 --- a/src/main.rs +++ b/src/main.rs @@ -9,12 +9,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> { use std::sync::Arc; if std::env::var("HPH_DEMO").as_deref() != Ok("true") { - return Err("Questa versione è una demo locale. Imposta HPH_DEMO=true; autenticazione e database di produzione non sono ancora implementati.".into()); + return Err("This version is a local demo. Set HPH_DEMO=true; authentication and production database integration are not implemented yet.".into()); } let options = get_configuration(None)?.leptos_options; let address = options.site_addr; if !address.ip().is_loopback() { - return Err("La demo senza autenticazione può ascoltare solo su loopback.".into()); + return Err("The unauthenticated demo can only listen on a loopback address.".into()); } let config: Config = toml::from_str(&std::fs::read_to_string("hph.toml")?)?; let state = DemoState::new(config)?; @@ -22,7 +22,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> { let runtime_database_url = std::env::var("HPH_DATABASE_URL").ok(); let migration_database_url = std::env::var("HPH_MIGRATION_DATABASE_URL").ok(); if migration_database_url.is_some() && runtime_database_url.is_none() { - return Err("HPH_MIGRATION_DATABASE_URL richiede HPH_DATABASE_URL.".into()); + return Err("HPH_MIGRATION_DATABASE_URL requires HPH_DATABASE_URL.".into()); } if let Some(database_url) = migration_database_url { let migration_database = Database::connect(&database_url).await?; diff --git a/src/membership_repository.rs b/src/membership_repository.rs index aac4252..540213b 100644 --- a/src/membership_repository.rs +++ b/src/membership_repository.rs @@ -18,12 +18,8 @@ pub enum MembershipError { impl fmt::Display for MembershipError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Self::Database(_) => { - f.write_str("Errore durante la verifica dell'appartenenza aziendale.") - } - Self::Unauthorized => { - f.write_str("Nessuna appartenenza attiva per l'azienda selezionata.") - } + Self::Database(_) => f.write_str("Could not verify company membership."), + Self::Unauthorized => f.write_str("No active membership for the selected company."), } } } diff --git a/src/module_repository.rs b/src/module_repository.rs index 1556592..7328a36 100644 --- a/src/module_repository.rs +++ b/src/module_repository.rs @@ -23,9 +23,9 @@ pub enum CompanyModuleError { impl fmt::Display for CompanyModuleError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Self::Database(_) => f.write_str("Errore durante l'accesso ai moduli aziendali."), - Self::Unauthorized => f.write_str("Membership aziendale non autorizzata."), - Self::InvalidConfiguration(_) => f.write_str("Configurazione dei moduli non valida."), + Self::Database(_) => f.write_str("Could not access company modules."), + Self::Unauthorized => f.write_str("Company membership is not authorized."), + Self::InvalidConfiguration(_) => f.write_str("Invalid module configuration."), } } } @@ -104,7 +104,7 @@ impl<'a> CompanyModuleRepository<'a> { "attendance" => Ok(ModuleId::Attendance), "reports" => Ok(ModuleId::Reports), _ => Err(CompanyModuleError::InvalidConfiguration( - "ID modulo sconosciuto.".into(), + "Unknown module ID.".into(), )), }) .collect::<Result<Vec<_>, _>>()?; diff --git a/src/server.rs b/src/server.rs index 2379f7f..53389a0 100644 --- a/src/server.rs +++ b/src/server.rs @@ -21,10 +21,10 @@ pub struct DemoState { impl DemoState { pub fn new(config: Config) -> Result<Self, String> { if config.organization.trim().is_empty() || config.organization.len() > 100 { - return Err("Nome azienda non valido.".into()); + return Err("Invalid company name.".into()); } if !["sage", "indigo"].contains(&config.theme.as_str()) { - return Err("Tema non valido: usa sage o indigo.".into()); + return Err("Invalid theme: use sage or indigo.".into()); } let modules = match config.modules { Some(enabled) => ModuleSet::from_enabled(enabled)?, @@ -99,14 +99,14 @@ impl DemoState { actor_id: self.actor.person_id.clone(), catalog: catalog(), server_time: chrono::Utc::now() - .format("%d/%m/%Y · %H:%M UTC") + .format("%Y-%m-%d · %H:%M UTC") .to_string(), } } } pub fn state() -> Result<Arc<DemoState>, ServerFnError> { use_context::<Arc<DemoState>>() - .ok_or_else(|| ServerFnError::new("Contesto aziendale non disponibile.")) + .ok_or_else(|| ServerFnError::new("Company context is unavailable.")) } pub fn router(options: LeptosOptions, state: Arc<DemoState>) -> axum::Router { @@ -295,9 +295,10 @@ mod tests { assert_eq!(response.status(), StatusCode::OK); let bytes = response.into_body().collect().await.unwrap().to_bytes(); let html = String::from_utf8(bytes.to_vec()).unwrap(); + assert!(html.contains("lang=\"en\"")); assert!(html.contains("Test Company")); - assert!(html.contains("DEMO LOCALE")); - assert!(html.contains("Tutto al posto giusto.")); + assert!(html.contains("LOCAL DEMO")); + assert!(html.contains("Everything in its place.")); assert!(html.contains("/pkg/hph.css")); } }