BlueGit

ict rusty-teams

Merged

feat(kvt): Business Central-kaarten en koppelen met sleutels.kvt.nl

!7 · merged 3 days ago

hephaestus bot wants to merge 1 commit from feat/kvt-bc-kaarten into master

Pipeline

#497 Passed

Reviews

  • No reviews yet.

Merged by hephaestus on 28 November 2026 f9632b38

Overview Commits 1 Pipelines 1 Changes 37

Changes

37 files changed +3883 −1
Cargo.lock +17 −0
@@ -291,6 +291,7 @@ dependencies = [
291 291 "gpui-pre-reqwest-client",
292 292 "graph",
293 293 "image",
294 "kvt-sleutels",
294 295 "log",
295 296 "mcp",
296 297 "regex",
@@ -5144,6 +5145,22 @@ dependencies = [
5144 5145 "smallvec",
5145 5146 ]
5146 5147
5148 [[package]]
5149 name = "kvt-sleutels"
5150 version = "0.6.1"
5151 dependencies = [
5152 "base64 0.22.1",
5153 "keyring",
5154 "percent-encoding",
5155 "rand 0.9.5",
5156 "reqwest 0.13.5",
5157 "serde",
5158 "serde_json",
5159 "sha2 0.10.9",
5160 "tokio",
5161 "url",
5162 ]
5163
5147 5164 [[package]]
5148 5165 name = "kvt-update"
5149 5166 version = "0.6.1"
@@ -291,6 +291,7 @@ dependencies = [
291 "gpui-pre-reqwest-client",
291 "gpui-pre-reqwest-client",
292 "graph",
292 "graph",
293 "image",
293 "image",
294 "kvt-sleutels",
294 "log",
295 "log",
295 "mcp",
296 "mcp",
296 "regex",
297 "regex",
@@ -5144,6 +5145,22 @@ dependencies = [
5144 "smallvec",
5145 "smallvec",
5145]
5146]
5146
5147
5148[[package]]
5149name = "kvt-sleutels"
5150version = "0.6.1"
5151dependencies = [
5152 "base64 0.22.1",
5153 "keyring",
5154 "percent-encoding",
5155 "rand 0.9.5",
5156 "reqwest 0.13.5",
5157 "serde",
5158 "serde_json",
5159 "sha2 0.10.9",
5160 "tokio",
5161 "url",
5162]
5163
5147[[package]]
5164[[package]]
5148name = "kvt-update"
5165name = "kvt-update"
5149version = "0.6.1"
5166version = "0.6.1"
KVT-FORK.md +46 −0
@@ -138,6 +138,49 @@ Laat die staan. `hicolor` is gegenereerd; bij een conflict opnieuw
138 138 `packaging/linux/icons.sh` draaien. Titelbalk: als upstream de leading mark herschrijft,
139 139 behoud `title_leading_mark` of de aanroep naar `kvt_brand::title_logo_png`.
140 140
141 ### Business Central-kaarten via sleutels.kvt.nl
142
143 Een BC-link in een bericht (project, werkorder of contract, ook `sleutels.kvt.nl/daedalus?workorder=` en
144 `/ponos?project=`) krijgt onder de tekst een kaartje, hooguit drie per bericht, niet uit een geciteerd
145 bericht. Een klik opent een venster met vaste velden uit Mímir en de knoppen «Open in BC», «Open in
146 Daedalus» (werkorders) en «Copy number». Een verwijzing naar project of contract opent die kaart.
147 Details komen pas bij het openen, met de token van wie kijkt.
148
149 Verzenden blijft een gewone link met leesbare tekst (`Werkorder WO… - omschrijving`): de officiële
150 Teams ziet een normale link. Invoegen gaat via het plusmenu van het opstelvak, «Business Central
151 link»: soort, bedrijf, zoeken (vanaf 2 tekens), Enter of klik voegt de link in.
152
153 Koppelen (Instellingen > Algemeen > KVT, «Connect to sleutels.kvt.nl»): één klik. De app opent de
154 koppelpagina van de Login (`/login/app_connect.php`, PKCE S256, redirect naar `127.0.0.1`) in een
155 tabblad op de achtergrond van de eigen sessiebrowser, die al met Microsoft is ingelogd (ADR 0003).
156 De Entra-SSO van de Login loopt dan stil door en de app klikt zelf «Koppelen» op de toestemmingspagina.
157 Vraagt Microsoft om invoer (accountkeuze, MFA) of loopt het vast, dan sluit de app het tabblad en
158 opent dezelfde link in de systeembrowser. Windows gebruikt voorlopig altijd de systeembrowser: de
159 WebView2-host kan nog geen los tabblad openen. Er gaat geen Teams- of Graph-token naar de Login.
160 De app-token (`sat_…`, 90 dagen) staat in de keyring (`rusty-teams.kvt-sleutels`). «Disconnect»
161 trekt hem in bij de Login en wist hem. `KVT_SLEUTELS_URL` (alleen `https://`) wijst een andere
162 Login/Mímir aan, bijvoorbeeld .test.
163
164 Taal: knoppen in het Engels en Duits (ADR 0008, `crates/app-base/locales/kvt.yml`, Nederlands staat
165 klaar), veldnamen en waarden in het Nederlands uit Mímir. `--demo` toont een verzonnen bericht in de
166 chat met Jonas Ortega en verzonnen kaarten. Besluit: ADR 0024.
167
168 | | |
169 |---|---|
170 | Wat | BC-kaarten in berichten, detailvenster, picker, koppelen met de Login |
171 | Eigen bestanden | `crates/kvt-sleutels/` (links, client, koppelen, sessietabblad-logica, keyring; zonder GPUI).<br>`crates/app/src/kvt/` (state, kaartje, venster, picker, demo, sessiebrowser).<br>`crates/app/src/settings/kvt.rs`, `crates/app/src/views/composer/kvt.rs`.<br>`crates/browser/src/browser/kvt.rs` (los tabblad: openen, script, sluiten), `crates/browser/tests/kvt_live_chrome.rs`.<br>`crates/app-state/src/kvt_demo.rs`, `crates/app-base/locales/kvt.yml`.<br>`docs/decisions/0024-kvt-cards-and-sleutels-link.md` |
172 | Upstream aangeraakt | `crates/app/src/main.rs` (`mod kvt`).<br>`crates/app/Cargo.toml` (crate `kvt-sleutels`).<br>`crates/app/src/views/shell.rs` (`kvt::install` in `install_globals`, `kvt::overlay`, `kvt::dialog_open` in de telling van modale lagen).<br>`crates/app/src/views/message_row.rs` (kaartjes onder de tekst, telt mee als `trailing_content`).<br>`crates/app/src/views/post_card.rs` (kaartjes in kanaalberichten).<br>`crates/app/src/views/composer.rs` (`mod kvt`), `composer/plus_menu.rs` (regel «Business Central link»).<br>`crates/app/src/settings/mod.rs` (`mod kvt`), `settings/general.rs` (rijen na de updates).<br>`crates/app/src/linux_browser.rs` (`managed()`).<br>`crates/browser/src/browser.rs` (`mod kvt`).<br>`crates/app-state/src/lib.rs` (`mod kvt_demo`), `demo.rs` (één `upsert_messages`).<br>`docs/decisions/README.md` (regel 0024).<br>`Cargo.lock` |
173 | Commits / MR's | zie hieronder |
174
175 Serverkant (geen deel van deze repo): `ict/login` (app-tokens, `app_connect.php`, README «App-tokens
176 voor native apps») en `ict/mimir` (`/mimir/api/cards.php`, README «Kaarten voor apps»).
177
178 Merge-tip: alle haken zijn één regel of één `.children(...)`. Als upstream `bubble()` in
179 `message_row.rs` of `install_globals` in `shell.rs` herschrijft, zet de aanroep naar `crate::kvt`
180 terug. `browser/kvt.rs` gebruikt `cdp_call`, `CDP_TIMEOUT` en `OPEN_TAB_TIMEOUT` uit `browser.rs`;
181 hernoemt upstream die, pas dan alleen `kvt.rs` aan. De loopback-pagina en de PROBE-selector in
182 `kvt-sleutels/src/session.rs` volgen de markup van `app_connect.php` in `ict/login`.
183
141 184 ## Eigen modules in het kort
142 185
143 186 | Pad | Rol |
@@ -149,4 +192,7 @@ behoud `title_leading_mark` of de aanroep naar `kvt_brand::title_logo_png`.
149 192 | `packaging/kvt/` | CI-setup, Windows-cross-build, AUR, release-assets |
150 193 | `crates/app/assets/icon/kvt-teams.*`, `kvt-app.rc` | App-icoon in KVT-kleuren |
151 194 | `crates/app/assets/brand/` | Officieel woordmerk |
195 | `crates/kvt-sleutels/` | sleutels.kvt.nl: BC-links, Mímir-kaarten, koppelen (PKCE, loopback, sessietabblad), keyring |
196 | `crates/app/src/kvt/`, `settings/kvt.rs`, `composer/kvt.rs` | BC-kaarten, detailvenster, picker, instellingen |
197 | `crates/browser/src/browser/kvt.rs` | Los tabblad in de sessiebrowser voor het koppelen |
152 198 | `blue-ci-cd.yml` | Sync, test, release, AUR (KVT-gedeelte) |
@@ -138,6 +138,49 @@ Laat die staan. `hicolor` is gegenereerd; bij een conflict opnieuw
138`packaging/linux/icons.sh` draaien. Titelbalk: als upstream de leading mark herschrijft,
138`packaging/linux/icons.sh` draaien. Titelbalk: als upstream de leading mark herschrijft,
139behoud `title_leading_mark` of de aanroep naar `kvt_brand::title_logo_png`.
139behoud `title_leading_mark` of de aanroep naar `kvt_brand::title_logo_png`.
140
140
141### Business Central-kaarten via sleutels.kvt.nl
142
143Een BC-link in een bericht (project, werkorder of contract, ook `sleutels.kvt.nl/daedalus?workorder=` en
144`/ponos?project=`) krijgt onder de tekst een kaartje, hooguit drie per bericht, niet uit een geciteerd
145bericht. Een klik opent een venster met vaste velden uit Mímir en de knoppen «Open in BC», «Open in
146Daedalus» (werkorders) en «Copy number». Een verwijzing naar project of contract opent die kaart.
147Details komen pas bij het openen, met de token van wie kijkt.
148
149Verzenden blijft een gewone link met leesbare tekst (`Werkorder WO… - omschrijving`): de officiële
150Teams ziet een normale link. Invoegen gaat via het plusmenu van het opstelvak, «Business Central
151link»: soort, bedrijf, zoeken (vanaf 2 tekens), Enter of klik voegt de link in.
152
153Koppelen (Instellingen > Algemeen > KVT, «Connect to sleutels.kvt.nl»): één klik. De app opent de
154koppelpagina van de Login (`/login/app_connect.php`, PKCE S256, redirect naar `127.0.0.1`) in een
155tabblad op de achtergrond van de eigen sessiebrowser, die al met Microsoft is ingelogd (ADR 0003).
156De Entra-SSO van de Login loopt dan stil door en de app klikt zelf «Koppelen» op de toestemmingspagina.
157Vraagt Microsoft om invoer (accountkeuze, MFA) of loopt het vast, dan sluit de app het tabblad en
158opent dezelfde link in de systeembrowser. Windows gebruikt voorlopig altijd de systeembrowser: de
159WebView2-host kan nog geen los tabblad openen. Er gaat geen Teams- of Graph-token naar de Login.
160De app-token (`sat_…`, 90 dagen) staat in de keyring (`rusty-teams.kvt-sleutels`). «Disconnect»
161trekt hem in bij de Login en wist hem. `KVT_SLEUTELS_URL` (alleen `https://`) wijst een andere
162Login/Mímir aan, bijvoorbeeld .test.
163
164Taal: knoppen in het Engels en Duits (ADR 0008, `crates/app-base/locales/kvt.yml`, Nederlands staat
165klaar), veldnamen en waarden in het Nederlands uit Mímir. `--demo` toont een verzonnen bericht in de
166chat met Jonas Ortega en verzonnen kaarten. Besluit: ADR 0024.
167
168| | |
169|---|---|
170| Wat | BC-kaarten in berichten, detailvenster, picker, koppelen met de Login |
171| Eigen bestanden | `crates/kvt-sleutels/` (links, client, koppelen, sessietabblad-logica, keyring; zonder GPUI).<br>`crates/app/src/kvt/` (state, kaartje, venster, picker, demo, sessiebrowser).<br>`crates/app/src/settings/kvt.rs`, `crates/app/src/views/composer/kvt.rs`.<br>`crates/browser/src/browser/kvt.rs` (los tabblad: openen, script, sluiten), `crates/browser/tests/kvt_live_chrome.rs`.<br>`crates/app-state/src/kvt_demo.rs`, `crates/app-base/locales/kvt.yml`.<br>`docs/decisions/0024-kvt-cards-and-sleutels-link.md` |
172| Upstream aangeraakt | `crates/app/src/main.rs` (`mod kvt`).<br>`crates/app/Cargo.toml` (crate `kvt-sleutels`).<br>`crates/app/src/views/shell.rs` (`kvt::install` in `install_globals`, `kvt::overlay`, `kvt::dialog_open` in de telling van modale lagen).<br>`crates/app/src/views/message_row.rs` (kaartjes onder de tekst, telt mee als `trailing_content`).<br>`crates/app/src/views/post_card.rs` (kaartjes in kanaalberichten).<br>`crates/app/src/views/composer.rs` (`mod kvt`), `composer/plus_menu.rs` (regel «Business Central link»).<br>`crates/app/src/settings/mod.rs` (`mod kvt`), `settings/general.rs` (rijen na de updates).<br>`crates/app/src/linux_browser.rs` (`managed()`).<br>`crates/browser/src/browser.rs` (`mod kvt`).<br>`crates/app-state/src/lib.rs` (`mod kvt_demo`), `demo.rs` (één `upsert_messages`).<br>`docs/decisions/README.md` (regel 0024).<br>`Cargo.lock` |
173| Commits / MR's | zie hieronder |
174
175Serverkant (geen deel van deze repo): `ict/login` (app-tokens, `app_connect.php`, README «App-tokens
176voor native apps») en `ict/mimir` (`/mimir/api/cards.php`, README «Kaarten voor apps»).
177
178Merge-tip: alle haken zijn één regel of één `.children(...)`. Als upstream `bubble()` in
179`message_row.rs` of `install_globals` in `shell.rs` herschrijft, zet de aanroep naar `crate::kvt`
180terug. `browser/kvt.rs` gebruikt `cdp_call`, `CDP_TIMEOUT` en `OPEN_TAB_TIMEOUT` uit `browser.rs`;
181hernoemt upstream die, pas dan alleen `kvt.rs` aan. De loopback-pagina en de PROBE-selector in
182`kvt-sleutels/src/session.rs` volgen de markup van `app_connect.php` in `ict/login`.
183
141## Eigen modules in het kort
184## Eigen modules in het kort
142
185
143| Pad | Rol |
186| Pad | Rol |
@@ -149,4 +192,7 @@ behoud `title_leading_mark` of de aanroep naar `kvt_brand::title_logo_png`.
149| `packaging/kvt/` | CI-setup, Windows-cross-build, AUR, release-assets |
192| `packaging/kvt/` | CI-setup, Windows-cross-build, AUR, release-assets |
150| `crates/app/assets/icon/kvt-teams.*`, `kvt-app.rc` | App-icoon in KVT-kleuren |
193| `crates/app/assets/icon/kvt-teams.*`, `kvt-app.rc` | App-icoon in KVT-kleuren |
151| `crates/app/assets/brand/` | Officieel woordmerk |
194| `crates/app/assets/brand/` | Officieel woordmerk |
195| `crates/kvt-sleutels/` | sleutels.kvt.nl: BC-links, Mímir-kaarten, koppelen (PKCE, loopback, sessietabblad), keyring |
196| `crates/app/src/kvt/`, `settings/kvt.rs`, `composer/kvt.rs` | BC-kaarten, detailvenster, picker, instellingen |
197| `crates/browser/src/browser/kvt.rs` | Los tabblad in de sessiebrowser voor het koppelen |
152| `blue-ci-cd.yml` | Sync, test, release, AUR (KVT-gedeelte) |
198| `blue-ci-cd.yml` | Sync, test, release, AUR (KVT-gedeelte) |
crates/app-base/locales/kvt.yml added +133 −0
@@ -0,0 +1,133 @@
1 _version: 2
2 # KVT-fork: koppeling met sleutels.kvt.nl (BC-kaarten). Zie KVT-FORK.md.
3 # Alleen en/de worden getoond (ADR 0008); nl staat klaar voor als dat verandert.
4 kvt:
5 settings:
6 caption:
7 en: KVT
8 de: KVT
9 nl: KVT
10 title:
11 en: Business Central cards
12 de: Business-Central-Karten
13 nl: Business Central-kaarten
14 detail:
15 en: Show projects, work orders and contracts from links in messages.
16 de: Projekte, Arbeitsaufträge und Verträge aus Links in Nachrichten anzeigen.
17 nl: Toon projecten, werkorders en contracten uit links in berichten.
18 linked:
19 en: "Connected as %{email}"
20 de: "Verbunden als %{email}"
21 nl: "Gekoppeld als %{email}"
22 connect:
23 en: Connect to sleutels.kvt.nl
24 de: Mit sleutels.kvt.nl verbinden
25 nl: Koppelen met sleutels.kvt.nl
26 connecting:
27 en: Finish in your browser…
28 de: Im Browser abschliessen…
29 nl: Rond af in je browser…
30 disconnect:
31 en: Disconnect
32 de: Trennen
33 nl: Ontkoppelen
34 notice:
35 connected:
36 en: Connected to sleutels.kvt.nl
37 de: Mit sleutels.kvt.nl verbunden
38 nl: Gekoppeld met sleutels.kvt.nl
39 disconnected:
40 en: Disconnected from sleutels.kvt.nl
41 de: Von sleutels.kvt.nl getrennt
42 nl: Ontkoppeld van sleutels.kvt.nl
43 denied:
44 en: Connecting was cancelled
45 de: Verbinden wurde abgebrochen
46 nl: Koppelen is geannuleerd
47 timed_out:
48 en: No answer from the browser, try again
49 de: Keine Antwort vom Browser, bitte erneut versuchen
50 nl: Geen antwoord van de browser, probeer het opnieuw
51 failed:
52 en: Connecting failed
53 de: Verbinden fehlgeschlagen
54 nl: Koppelen mislukt
55 copied:
56 en: Number copied
57 de: Nummer kopiert
58 nl: Nummer gekopieerd
59 kind:
60 project:
61 en: Project
62 de: Projekt
63 nl: Project
64 werkorder:
65 en: Work order
66 de: Arbeitsauftrag
67 nl: Werkorder
68 contract:
69 en: Contract
70 de: Vertrag
71 nl: Contract
72 card:
73 open_in_bc:
74 en: Open in BC
75 de: In BC öffnen
76 nl: Openen in BC
77 open_daedalus:
78 en: Open in Daedalus
79 de: In Daedalus öffnen
80 nl: Openen in Daedalus
81 copy_no:
82 en: Copy number
83 de: Nummer kopieren
84 nl: Nummer kopiëren
85 refresh:
86 en: Refresh
87 de: Aktualisieren
88 nl: Vernieuwen
89 loading:
90 en: Loading…
91 de: Wird geladen…
92 nl: Laden…
93 sign_in:
94 en: Sign in to see details
95 de: Anmelden, um Details zu sehen
96 nl: Inloggen om details te zien
97 not_found:
98 en: Not found in Business Central
99 de: In Business Central nicht gefunden
100 nl: Niet gevonden in Business Central
101 forbidden:
102 en: This connection may not read cards
103 de: Diese Verbindung darf keine Karten lesen
104 nl: Deze koppeling mag geen kaarten lezen
105 rate_limited:
106 en: Too many requests, try again in a minute
107 de: Zu viele Anfragen, in einer Minute erneut versuchen
108 nl: Te veel verzoeken, probeer het over een minuut opnieuw
109 unavailable:
110 en: Business Central cannot be reached right now
111 de: Business Central ist gerade nicht erreichbar
112 nl: Business Central is nu niet bereikbaar
113 picker:
114 menu:
115 en: Business Central link
116 de: Business-Central-Link
117 nl: Business Central-link
118 title:
119 en: Insert a Business Central link
120 de: Business-Central-Link einfügen
121 nl: Business Central-link invoegen
122 search:
123 en: Search by number or description
124 de: Nach Nummer oder Beschreibung suchen
125 nl: Zoek op nummer of omschrijving
126 type_more:
127 en: Type at least 2 characters
128 de: Mindestens 2 Zeichen eingeben
129 nl: Typ minstens 2 tekens
130 empty:
131 en: No results
132 de: Keine Treffer
133 nl: Geen resultaten
@@ -0,0 +1,133 @@
1_version: 2
2# KVT-fork: koppeling met sleutels.kvt.nl (BC-kaarten). Zie KVT-FORK.md.
3# Alleen en/de worden getoond (ADR 0008); nl staat klaar voor als dat verandert.
4kvt:
5 settings:
6 caption:
7 en: KVT
8 de: KVT
9 nl: KVT
10 title:
11 en: Business Central cards
12 de: Business-Central-Karten
13 nl: Business Central-kaarten
14 detail:
15 en: Show projects, work orders and contracts from links in messages.
16 de: Projekte, Arbeitsaufträge und Verträge aus Links in Nachrichten anzeigen.
17 nl: Toon projecten, werkorders en contracten uit links in berichten.
18 linked:
19 en: "Connected as %{email}"
20 de: "Verbunden als %{email}"
21 nl: "Gekoppeld als %{email}"
22 connect:
23 en: Connect to sleutels.kvt.nl
24 de: Mit sleutels.kvt.nl verbinden
25 nl: Koppelen met sleutels.kvt.nl
26 connecting:
27 en: Finish in your browser…
28 de: Im Browser abschliessen…
29 nl: Rond af in je browser…
30 disconnect:
31 en: Disconnect
32 de: Trennen
33 nl: Ontkoppelen
34 notice:
35 connected:
36 en: Connected to sleutels.kvt.nl
37 de: Mit sleutels.kvt.nl verbunden
38 nl: Gekoppeld met sleutels.kvt.nl
39 disconnected:
40 en: Disconnected from sleutels.kvt.nl
41 de: Von sleutels.kvt.nl getrennt
42 nl: Ontkoppeld van sleutels.kvt.nl
43 denied:
44 en: Connecting was cancelled
45 de: Verbinden wurde abgebrochen
46 nl: Koppelen is geannuleerd
47 timed_out:
48 en: No answer from the browser, try again
49 de: Keine Antwort vom Browser, bitte erneut versuchen
50 nl: Geen antwoord van de browser, probeer het opnieuw
51 failed:
52 en: Connecting failed
53 de: Verbinden fehlgeschlagen
54 nl: Koppelen mislukt
55 copied:
56 en: Number copied
57 de: Nummer kopiert
58 nl: Nummer gekopieerd
59 kind:
60 project:
61 en: Project
62 de: Projekt
63 nl: Project
64 werkorder:
65 en: Work order
66 de: Arbeitsauftrag
67 nl: Werkorder
68 contract:
69 en: Contract
70 de: Vertrag
71 nl: Contract
72 card:
73 open_in_bc:
74 en: Open in BC
75 de: In BC öffnen
76 nl: Openen in BC
77 open_daedalus:
78 en: Open in Daedalus
79 de: In Daedalus öffnen
80 nl: Openen in Daedalus
81 copy_no:
82 en: Copy number
83 de: Nummer kopieren
84 nl: Nummer kopiëren
85 refresh:
86 en: Refresh
87 de: Aktualisieren
88 nl: Vernieuwen
89 loading:
90 en: Loading…
91 de: Wird geladen…
92 nl: Laden…
93 sign_in:
94 en: Sign in to see details
95 de: Anmelden, um Details zu sehen
96 nl: Inloggen om details te zien
97 not_found:
98 en: Not found in Business Central
99 de: In Business Central nicht gefunden
100 nl: Niet gevonden in Business Central
101 forbidden:
102 en: This connection may not read cards
103 de: Diese Verbindung darf keine Karten lesen
104 nl: Deze koppeling mag geen kaarten lezen
105 rate_limited:
106 en: Too many requests, try again in a minute
107 de: Zu viele Anfragen, in einer Minute erneut versuchen
108 nl: Te veel verzoeken, probeer het over een minuut opnieuw
109 unavailable:
110 en: Business Central cannot be reached right now
111 de: Business Central ist gerade nicht erreichbar
112 nl: Business Central is nu niet bereikbaar
113 picker:
114 menu:
115 en: Business Central link
116 de: Business-Central-Link
117 nl: Business Central-link
118 title:
119 en: Insert a Business Central link
120 de: Business-Central-Link einfügen
121 nl: Business Central-link invoegen
122 search:
123 en: Search by number or description
124 de: Nach Nummer oder Beschreibung suchen
125 nl: Zoek op nummer of omschrijving
126 type_more:
127 en: Type at least 2 characters
128 de: Mindestens 2 Zeichen eingeben
129 nl: Typ minstens 2 tekens
130 empty:
131 en: No results
132 de: Keine Treffer
133 nl: Geen resultaten
crates/app-state/src/demo.rs +1 −0
@@ -921,6 +921,7 @@ pub fn seed(store: &Store) {
921 921 let _ = store.upsert_messages(&call_messages());
922 922 let _ = store.upsert_messages(&crate::demo_meetings::meeting_messages());
923 923 let _ = store.upsert_messages(&bot_messages());
924 let _ = store.upsert_messages(&crate::kvt_demo::messages());
924 925 seed_agent_access(store);
925 926 }
926 927
@@ -921,6 +921,7 @@ pub fn seed(store: &Store) {
921 let _ = store.upsert_messages(&call_messages());
921 let _ = store.upsert_messages(&call_messages());
922 let _ = store.upsert_messages(&crate::demo_meetings::meeting_messages());
922 let _ = store.upsert_messages(&crate::demo_meetings::meeting_messages());
923 let _ = store.upsert_messages(&bot_messages());
923 let _ = store.upsert_messages(&bot_messages());
924 let _ = store.upsert_messages(&crate::kvt_demo::messages());
924 seed_agent_access(store);
925 seed_agent_access(store);
925}
926}
926
927
crates/app-state/src/kvt_demo.rs added +34 −0
@@ -0,0 +1,34 @@
1 //! KVT-fork: een demobericht met Business Central-links, zodat `--demo` de
2 //! kaartjes van `crate::kvt` (app) laat zien. Verzonnen nummers, geen echte data.
3
4 use store::MessageRecord;
5
6 use crate::demo::{JONAS_ID, at};
7
8 const WORK_ORDER: &str = "https://kvtmd365.kvt.nl/KVTMDLive_AAD/?company=Koninklijke%20van%20Twist&amp;page=11333028&amp;filter=%27No.%27%20IS%20%27WO2699001%27";
9 const CONTRACT: &str = "https://kvtmd365.kvt.nl/KVTMDLive_AAD/?company=Koninklijke%20van%20Twist&amp;page=11333015&amp;filter=%27Contract%20No.%27%20IS%20%27CT2699001%27";
10
11 pub fn messages() -> Vec<MessageRecord> {
12 let time = at(0, 11, 0);
13 vec![MessageRecord {
14 conversation_id: "demo-chat-jonas".to_owned(),
15 message_id: "kvt1".to_owned(),
16 reply_to_id: None,
17 sender_id: Some(JONAS_ID.to_owned()),
18 sender_name: Some("Jonas Ortega".to_owned()),
19 sender_application_id: None,
20 links_json: "[]".to_owned(),
21 created_at: time,
22 edited_at: None,
23 deleted: false,
24 body_html: format!(
25 "<p>Could you check <a href=\"{WORK_ORDER}\">Werkorder WO2699001 - Onderhoud 500 uur</a> before Friday? It falls under <a href=\"{CONTRACT}\">Contract CT2699001 - Onderhoudscontract vloot</a>.</p>"
26 ),
27 attachments_json: "[]".to_owned(),
28 reactions_json: "[]".to_owned(),
29 mentions_json: "[]".to_owned(),
30 subject: None,
31 call_event_json: None,
32 importance: Default::default(),
33 }]
34 }
@@ -0,0 +1,34 @@
1//! KVT-fork: een demobericht met Business Central-links, zodat `--demo` de
2//! kaartjes van `crate::kvt` (app) laat zien. Verzonnen nummers, geen echte data.
3
4use store::MessageRecord;
5
6use crate::demo::{JONAS_ID, at};
7
8const WORK_ORDER: &str = "https://kvtmd365.kvt.nl/KVTMDLive_AAD/?company=Koninklijke%20van%20Twist&amp;page=11333028&amp;filter=%27No.%27%20IS%20%27WO2699001%27";
9const CONTRACT: &str = "https://kvtmd365.kvt.nl/KVTMDLive_AAD/?company=Koninklijke%20van%20Twist&amp;page=11333015&amp;filter=%27Contract%20No.%27%20IS%20%27CT2699001%27";
10
11pub fn messages() -> Vec<MessageRecord> {
12 let time = at(0, 11, 0);
13 vec![MessageRecord {
14 conversation_id: "demo-chat-jonas".to_owned(),
15 message_id: "kvt1".to_owned(),
16 reply_to_id: None,
17 sender_id: Some(JONAS_ID.to_owned()),
18 sender_name: Some("Jonas Ortega".to_owned()),
19 sender_application_id: None,
20 links_json: "[]".to_owned(),
21 created_at: time,
22 edited_at: None,
23 deleted: false,
24 body_html: format!(
25 "<p>Could you check <a href=\"{WORK_ORDER}\">Werkorder WO2699001 - Onderhoud 500 uur</a> before Friday? It falls under <a href=\"{CONTRACT}\">Contract CT2699001 - Onderhoudscontract vloot</a>.</p>"
26 ),
27 attachments_json: "[]".to_owned(),
28 reactions_json: "[]".to_owned(),
29 mentions_json: "[]".to_owned(),
30 subject: None,
31 call_event_json: None,
32 importance: Default::default(),
33 }]
34}
crates/app-state/src/lib.rs +1 −0
@@ -37,6 +37,7 @@ pub mod google_calendar_sync;
37 37 pub mod ics_sync;
38 38 pub mod image_view_gallery;
39 39 pub mod importance;
40 pub mod kvt_demo;
40 41 pub mod local_previews;
41 42 pub mod manage_team;
42 43 pub mod message_actions;
@@ -37,6 +37,7 @@ pub mod google_calendar_sync;
37pub mod ics_sync;
37pub mod ics_sync;
38pub mod image_view_gallery;
38pub mod image_view_gallery;
39pub mod importance;
39pub mod importance;
40pub mod kvt_demo;
40pub mod local_previews;
41pub mod local_previews;
41pub mod manage_team;
42pub mod manage_team;
42pub mod message_actions;
43pub mod message_actions;
crates/app/Cargo.toml +2 −0
@@ -32,6 +32,8 @@ gpui-kit.workspace = true
32 32 regex.workspace = true
33 33 reqwest_client.workspace = true
34 34 graph.workspace = true
35 # KVT-fork: koppeling met sleutels.kvt.nl (zie KVT-FORK.md)
36 kvt-sleutels = { path = "../kvt-sleutels" }
35 37 log = "0.4"
36 38 mcp.workspace = true
37 39 serde.workspace = true
@@ -32,6 +32,8 @@ gpui-kit.workspace = true
32regex.workspace = true
32regex.workspace = true
33reqwest_client.workspace = true
33reqwest_client.workspace = true
34graph.workspace = true
34graph.workspace = true
35# KVT-fork: koppeling met sleutels.kvt.nl (zie KVT-FORK.md)
36kvt-sleutels = { path = "../kvt-sleutels" }
35log = "0.4"
37log = "0.4"
36mcp.workspace = true
38mcp.workspace = true
37serde.workspace = true
39serde.workspace = true
crates/app/src/kvt/card.rs added +246 −0
@@ -0,0 +1,246 @@
1 //! Het kaartje onder een bericht met een BC- of sleutels-link.
2
3 use gpui_kit::component::{h_flex, v_flex};
4 use gpui_kit::prelude::FluentBuilder as _;
5 use gpui_kit::*;
6 use kvt_sleutels::{CardRef, MAX_CARDS_PER_MESSAGE, parse_card_link};
7
8 use super::{Load, cached_card, kind_label, kind_symbol, open_card};
9 use crate::render::Block;
10 use crate::theme;
11 use crate::views::widgets::symbol;
12
13 const CARD_WIDTH: f32 = 360.;
14 const BADGE_SIZE: f32 = 32.;
15 const BADGE_ICON_SIZE: f32 = 18.;
16
17 /// Kaart-verwijzingen met hun linktekst, in volgorde, zonder dubbele en zonder
18 /// links in een geciteerd bericht. Hooguit [`MAX_CARDS_PER_MESSAGE`].
19 pub(crate) fn card_links(blocks: &[Block]) -> Vec<(CardRef, String)> {
20 let mut found: Vec<(CardRef, String)> = Vec::new();
21 collect(blocks, &mut found);
22 found
23 }
24
25 fn collect(blocks: &[Block], found: &mut Vec<(CardRef, String)>) {
26 for block in blocks {
27 if found.len() >= MAX_CARDS_PER_MESSAGE {
28 return;
29 }
30 match block {
31 Block::Paragraph(inline) | Block::Heading { inline, .. } => {
32 collect_inline(inline, found)
33 }
34 Block::Quote(children) | Block::Indent { children, .. } => collect(children, found),
35 Block::List { items, .. } => {
36 for item in items {
37 collect(item, found);
38 }
39 }
40 Block::Table { rows, .. } => {
41 for cell in rows.iter().flatten() {
42 collect_inline(&cell.inline, found);
43 }
44 }
45 Block::Reply { .. }
46 | Block::Code { .. }
47 | Block::CodeLine { .. }
48 | Block::Rule
49 | Block::Image { .. } => {}
50 }
51 }
52 }
53
54 fn collect_inline(inline: &crate::render::blocks::Inline, found: &mut Vec<(CardRef, String)>) {
55 for segment in &inline.segments {
56 if found.len() >= MAX_CARDS_PER_MESSAGE {
57 return;
58 }
59 let Some(reference) = segment.link.as_deref().and_then(parse_card_link) else {
60 continue;
61 };
62 let text = inline
63 .text
64 .get(segment.range.clone())
65 .unwrap_or_default()
66 .trim();
67 match found.iter_mut().find(|(known, _)| {
68 known.kind == reference.kind
69 && known.company == reference.company
70 && known.no == reference.no
71 }) {
72 // Eén link kan in meerdere opgemaakte stukken staan: tekst aanvullen.
73 Some((_, known_text)) if !text.is_empty() && !known_text.contains(text) => {
74 known_text.push(' ');
75 known_text.push_str(text);
76 }
77 Some(_) => {}
78 None => found.push((reference, text.to_owned())),
79 }
80 }
81 }
82
83 /// Omschrijving uit de linktekst: «Werkorder WO2699001 - Onderhoud» → «Onderhoud».
84 /// Een kale URL als tekst geeft niets.
85 pub(crate) fn title_from_anchor(reference: &CardRef, text: &str) -> String {
86 let text = text.trim();
87 if text.contains("://") {
88 return String::new();
89 }
90 let prefix = format!("{} {}", reference.kind.label_nl(), reference.no);
91 match text.strip_prefix(&prefix) {
92 Some(rest) => rest.trim_start_matches([' ', '-', '–']).trim().to_owned(),
93 None if text == reference.no => String::new(),
94 None => text.to_owned(),
95 }
96 }
97
98 pub fn message_cards(blocks: &[Block], id: &str, cx: &App) -> Vec<AnyElement> {
99 if !cx.has_global::<super::Kvt>() {
100 return Vec::new();
101 }
102 card_links(blocks)
103 .into_iter()
104 .enumerate()
105 .map(|(index, (reference, text))| {
106 card_chip(reference, text, format!("{id}-kvt-{index}"), cx)
107 })
108 .collect()
109 }
110
111 fn card_chip(reference: CardRef, text: String, id: String, cx: &App) -> AnyElement {
112 let (title, subtitle) = match cached_card(&reference, cx) {
113 Some(Load::Loaded(card)) => (card.title.clone(), card.subtitle.clone()),
114 _ => (title_from_anchor(&reference, &text), String::new()),
115 };
116 let heading = format!("{} {}", kind_label(reference.kind), reference.no);
117 let detail = if subtitle.is_empty() {
118 reference.company.clone()
119 } else {
120 format!("{subtitle} · {}", reference.company)
121 };
122 let kind = reference.kind;
123 h_flex()
124 .id(ElementId::Name(id.into()))
125 .w_full()
126 .max_w(px(CARD_WIDTH))
127 .gap(px(10.))
128 .p(px(8.))
129 .items_center()
130 .rounded(px(10.))
131 .bg(theme::surface())
132 .cursor_pointer()
133 .hover(|card| card.bg(theme::row_hover()))
134 .child(
135 div()
136 .size(px(BADGE_SIZE))
137 .flex_none()
138 .flex()
139 .items_center()
140 .justify_center()
141 .rounded(px(8.))
142 .bg(theme::accent())
143 .child(symbol(
144 kind_symbol(kind),
145 BADGE_ICON_SIZE,
146 theme::on_accent(),
147 )),
148 )
149 .child(
150 v_flex()
151 .flex_1()
152 .min_w_0()
153 .gap(px(1.))
154 .child(
155 div()
156 .truncate()
157 .text_size(px(11.))
158 .font_weight(FontWeight::SEMIBOLD)
159 .text_color(theme::text_muted())
160 .child(heading),
161 )
162 .when(!title.is_empty(), |column| {
163 column.child(
164 div()
165 .truncate()
166 .text_size(px(13.))
167 .font_weight(FontWeight::SEMIBOLD)
168 .text_color(theme::text_strong())
169 .child(title),
170 )
171 })
172 .child(
173 div()
174 .truncate()
175 .text_size(px(11.))
176 .text_color(theme::text_muted())
177 .child(detail),
178 ),
179 )
180 .child(symbol("open_in_new", 14., theme::text_muted()))
181 .on_click(move |_, _, cx| {
182 cx.stop_propagation();
183 open_card(reference.clone(), text.clone(), cx);
184 })
185 .into_any_element()
186 }
187
188 #[cfg(test)]
189 mod tests {
190 use super::{card_links, title_from_anchor};
191 use crate::render::Block;
192 use crate::render::blocks::Inline;
193 use kvt_sleutels::CardKind;
194 use kvt_sleutels::links::bc_url;
195
196 fn linked(text: &str, url: &str) -> Inline {
197 let mut inline = Inline::plain(text);
198 inline.segments[0].link = Some(url.to_owned());
199 inline
200 }
201
202 #[test]
203 fn finds_card_links_but_not_in_quotes_of_replies() {
204 let wo = bc_url(CardKind::Werkorder, "Testbedrijf", "WO2699001", None);
205 let ct = bc_url(CardKind::Contract, "Testbedrijf", "CT2699001", None);
206 let blocks = vec![
207 Block::Reply {
208 message_id: None,
209 children: vec![Block::Paragraph(linked("oud", &ct))],
210 },
211 Block::Paragraph(linked("Werkorder WO2699001 - Onderhoud", &wo)),
212 Block::List {
213 ordered: false,
214 start: 1,
215 items: vec![vec![Block::Paragraph(linked("nog eens", &wo))]],
216 },
217 Block::Paragraph(linked("site", "https://example.com/")),
218 ];
219 let found = card_links(&blocks);
220 assert_eq!(found.len(), 1);
221 assert_eq!(found[0].0.no, "WO2699001");
222 assert_eq!(found[0].1, "Werkorder WO2699001 - Onderhoud nog eens");
223 }
224
225 #[test]
226 fn title_comes_from_readable_anchor_text() {
227 let reference = kvt_sleutels::parse_card_link(&bc_url(
228 CardKind::Project,
229 "Testbedrijf",
230 "PRJ2699001",
231 None,
232 ))
233 .unwrap();
234 assert_eq!(
235 title_from_anchor(&reference, "Project PRJ2699001 - Nieuwbouw"),
236 "Nieuwbouw"
237 );
238 assert_eq!(title_from_anchor(&reference, "Project PRJ2699001"), "");
239 assert_eq!(title_from_anchor(&reference, "PRJ2699001"), "");
240 assert_eq!(
241 title_from_anchor(&reference, "https://kvtmd365.kvt.nl/x"),
242 ""
243 );
244 assert_eq!(title_from_anchor(&reference, "dit project"), "dit project");
245 }
246 }
@@ -0,0 +1,246 @@
1//! Het kaartje onder een bericht met een BC- of sleutels-link.
2
3use gpui_kit::component::{h_flex, v_flex};
4use gpui_kit::prelude::FluentBuilder as _;
5use gpui_kit::*;
6use kvt_sleutels::{CardRef, MAX_CARDS_PER_MESSAGE, parse_card_link};
7
8use super::{Load, cached_card, kind_label, kind_symbol, open_card};
9use crate::render::Block;
10use crate::theme;
11use crate::views::widgets::symbol;
12
13const CARD_WIDTH: f32 = 360.;
14const BADGE_SIZE: f32 = 32.;
15const BADGE_ICON_SIZE: f32 = 18.;
16
17/// Kaart-verwijzingen met hun linktekst, in volgorde, zonder dubbele en zonder
18/// links in een geciteerd bericht. Hooguit [`MAX_CARDS_PER_MESSAGE`].
19pub(crate) fn card_links(blocks: &[Block]) -> Vec<(CardRef, String)> {
20 let mut found: Vec<(CardRef, String)> = Vec::new();
21 collect(blocks, &mut found);
22 found
23}
24
25fn collect(blocks: &[Block], found: &mut Vec<(CardRef, String)>) {
26 for block in blocks {
27 if found.len() >= MAX_CARDS_PER_MESSAGE {
28 return;
29 }
30 match block {
31 Block::Paragraph(inline) | Block::Heading { inline, .. } => {
32 collect_inline(inline, found)
33 }
34 Block::Quote(children) | Block::Indent { children, .. } => collect(children, found),
35 Block::List { items, .. } => {
36 for item in items {
37 collect(item, found);
38 }
39 }
40 Block::Table { rows, .. } => {
41 for cell in rows.iter().flatten() {
42 collect_inline(&cell.inline, found);
43 }
44 }
45 Block::Reply { .. }
46 | Block::Code { .. }
47 | Block::CodeLine { .. }
48 | Block::Rule
49 | Block::Image { .. } => {}
50 }
51 }
52}
53
54fn collect_inline(inline: &crate::render::blocks::Inline, found: &mut Vec<(CardRef, String)>) {
55 for segment in &inline.segments {
56 if found.len() >= MAX_CARDS_PER_MESSAGE {
57 return;
58 }
59 let Some(reference) = segment.link.as_deref().and_then(parse_card_link) else {
60 continue;
61 };
62 let text = inline
63 .text
64 .get(segment.range.clone())
65 .unwrap_or_default()
66 .trim();
67 match found.iter_mut().find(|(known, _)| {
68 known.kind == reference.kind
69 && known.company == reference.company
70 && known.no == reference.no
71 }) {
72 // Eén link kan in meerdere opgemaakte stukken staan: tekst aanvullen.
73 Some((_, known_text)) if !text.is_empty() && !known_text.contains(text) => {
74 known_text.push(' ');
75 known_text.push_str(text);
76 }
77 Some(_) => {}
78 None => found.push((reference, text.to_owned())),
79 }
80 }
81}
82
83/// Omschrijving uit de linktekst: «Werkorder WO2699001 - Onderhoud» → «Onderhoud».
84/// Een kale URL als tekst geeft niets.
85pub(crate) fn title_from_anchor(reference: &CardRef, text: &str) -> String {
86 let text = text.trim();
87 if text.contains("://") {
88 return String::new();
89 }
90 let prefix = format!("{} {}", reference.kind.label_nl(), reference.no);
91 match text.strip_prefix(&prefix) {
92 Some(rest) => rest.trim_start_matches([' ', '-', '–']).trim().to_owned(),
93 None if text == reference.no => String::new(),
94 None => text.to_owned(),
95 }
96}
97
98pub fn message_cards(blocks: &[Block], id: &str, cx: &App) -> Vec<AnyElement> {
99 if !cx.has_global::<super::Kvt>() {
100 return Vec::new();
101 }
102 card_links(blocks)
103 .into_iter()
104 .enumerate()
105 .map(|(index, (reference, text))| {
106 card_chip(reference, text, format!("{id}-kvt-{index}"), cx)
107 })
108 .collect()
109}
110
111fn card_chip(reference: CardRef, text: String, id: String, cx: &App) -> AnyElement {
112 let (title, subtitle) = match cached_card(&reference, cx) {
113 Some(Load::Loaded(card)) => (card.title.clone(), card.subtitle.clone()),
114 _ => (title_from_anchor(&reference, &text), String::new()),
115 };
116 let heading = format!("{} {}", kind_label(reference.kind), reference.no);
117 let detail = if subtitle.is_empty() {
118 reference.company.clone()
119 } else {
120 format!("{subtitle} · {}", reference.company)
121 };
122 let kind = reference.kind;
123 h_flex()
124 .id(ElementId::Name(id.into()))
125 .w_full()
126 .max_w(px(CARD_WIDTH))
127 .gap(px(10.))
128 .p(px(8.))
129 .items_center()
130 .rounded(px(10.))
131 .bg(theme::surface())
132 .cursor_pointer()
133 .hover(|card| card.bg(theme::row_hover()))
134 .child(
135 div()
136 .size(px(BADGE_SIZE))
137 .flex_none()
138 .flex()
139 .items_center()
140 .justify_center()
141 .rounded(px(8.))
142 .bg(theme::accent())
143 .child(symbol(
144 kind_symbol(kind),
145 BADGE_ICON_SIZE,
146 theme::on_accent(),
147 )),
148 )
149 .child(
150 v_flex()
151 .flex_1()
152 .min_w_0()
153 .gap(px(1.))
154 .child(
155 div()
156 .truncate()
157 .text_size(px(11.))
158 .font_weight(FontWeight::SEMIBOLD)
159 .text_color(theme::text_muted())
160 .child(heading),
161 )
162 .when(!title.is_empty(), |column| {
163 column.child(
164 div()
165 .truncate()
166 .text_size(px(13.))
167 .font_weight(FontWeight::SEMIBOLD)
168 .text_color(theme::text_strong())
169 .child(title),
170 )
171 })
172 .child(
173 div()
174 .truncate()
175 .text_size(px(11.))
176 .text_color(theme::text_muted())
177 .child(detail),
178 ),
179 )
180 .child(symbol("open_in_new", 14., theme::text_muted()))
181 .on_click(move |_, _, cx| {
182 cx.stop_propagation();
183 open_card(reference.clone(), text.clone(), cx);
184 })
185 .into_any_element()
186}
187
188#[cfg(test)]
189mod tests {
190 use super::{card_links, title_from_anchor};
191 use crate::render::Block;
192 use crate::render::blocks::Inline;
193 use kvt_sleutels::CardKind;
194 use kvt_sleutels::links::bc_url;
195
196 fn linked(text: &str, url: &str) -> Inline {
197 let mut inline = Inline::plain(text);
198 inline.segments[0].link = Some(url.to_owned());
199 inline
200 }
201
202 #[test]
203 fn finds_card_links_but_not_in_quotes_of_replies() {
204 let wo = bc_url(CardKind::Werkorder, "Testbedrijf", "WO2699001", None);
205 let ct = bc_url(CardKind::Contract, "Testbedrijf", "CT2699001", None);
206 let blocks = vec![
207 Block::Reply {
208 message_id: None,
209 children: vec![Block::Paragraph(linked("oud", &ct))],
210 },
211 Block::Paragraph(linked("Werkorder WO2699001 - Onderhoud", &wo)),
212 Block::List {
213 ordered: false,
214 start: 1,
215 items: vec![vec![Block::Paragraph(linked("nog eens", &wo))]],
216 },
217 Block::Paragraph(linked("site", "https://example.com/")),
218 ];
219 let found = card_links(&blocks);
220 assert_eq!(found.len(), 1);
221 assert_eq!(found[0].0.no, "WO2699001");
222 assert_eq!(found[0].1, "Werkorder WO2699001 - Onderhoud nog eens");
223 }
224
225 #[test]
226 fn title_comes_from_readable_anchor_text() {
227 let reference = kvt_sleutels::parse_card_link(&bc_url(
228 CardKind::Project,
229 "Testbedrijf",
230 "PRJ2699001",
231 None,
232 ))
233 .unwrap();
234 assert_eq!(
235 title_from_anchor(&reference, "Project PRJ2699001 - Nieuwbouw"),
236 "Nieuwbouw"
237 );
238 assert_eq!(title_from_anchor(&reference, "Project PRJ2699001"), "");
239 assert_eq!(title_from_anchor(&reference, "PRJ2699001"), "");
240 assert_eq!(
241 title_from_anchor(&reference, "https://kvtmd365.kvt.nl/x"),
242 ""
243 );
244 assert_eq!(title_from_anchor(&reference, "dit project"), "dit project");
245 }
246}
crates/app/src/kvt/demo.rs added +183 −0
@@ -0,0 +1,183 @@
1 //! Verzonnen kaarten voor `--demo` (geen echte BC-gegevens, geen echte personen).
2
3 use kvt_sleutels::links::bc_url;
4 use kvt_sleutels::{
5 Card, CardField, CardKind, CardLinks, CardRef, FieldRef, SearchResult, StoredToken,
6 };
7
8 use super::DEFAULT_COMPANY as COMPANY;
9
10 pub(super) fn token() -> StoredToken {
11 StoredToken {
12 token: String::new(),
13 expires_at: i64::MAX,
14 email: "dana.demo@example.com".to_owned(),
15 name: "Dana Demo".to_owned(),
16 }
17 }
18
19 pub(super) fn companies() -> Vec<String> {
20 vec![COMPANY.to_owned(), "KVT Germany".to_owned()]
21 }
22
23 fn field(key: &str, label: &str, value: &str) -> CardField {
24 CardField {
25 key: key.to_owned(),
26 label: label.to_owned(),
27 value: value.to_owned(),
28 date: None,
29 reference: None,
30 }
31 }
32
33 fn reference(key: &str, label: &str, kind: CardKind, company: &str, no: &str) -> CardField {
34 CardField {
35 reference: Some(FieldRef {
36 kind: kind.api_name().to_owned(),
37 no: no.to_owned(),
38 bc_url: bc_url(kind, company, no, None),
39 }),
40 ..field(key, label, no)
41 }
42 }
43
44 struct Entry {
45 kind: CardKind,
46 no: &'static str,
47 title: &'static str,
48 subtitle: &'static str,
49 }
50
51 const ENTRIES: [Entry; 5] = [
52 Entry {
53 kind: CardKind::Werkorder,
54 no: "WO2699001",
55 title: "Onderhoud 500 uur",
56 subtitle: "MS Voorbeeld",
57 },
58 Entry {
59 kind: CardKind::Werkorder,
60 no: "WO2699002",
61 title: "Inspectie generator",
62 subtitle: "Pontveer Demo",
63 },
64 Entry {
65 kind: CardKind::Project,
66 no: "PRJ2699001",
67 title: "Nieuwbouw aandrijving",
68 subtitle: "Rederij Voorbeeld",
69 },
70 Entry {
71 kind: CardKind::Project,
72 no: "PRJ2699002",
73 title: "Retrofit noodstroom",
74 subtitle: "Haven Demo",
75 },
76 Entry {
77 kind: CardKind::Contract,
78 no: "CT2699001",
79 title: "Onderhoudscontract vloot",
80 subtitle: "Rederij Voorbeeld",
81 },
82 ];
83
84 pub(super) fn card(reference_to: &CardRef) -> Option<Card> {
85 let entry = ENTRIES
86 .iter()
87 .find(|entry| entry.kind == reference_to.kind && entry.no == reference_to.no)?;
88 let company = reference_to.company.as_str();
89 let fields = match entry.kind {
90 CardKind::Werkorder => vec![
91 field("Main_Entity_Description", "Object", entry.subtitle),
92 field("Sell_to_Name", "Klant", "Rederij Voorbeeld"),
93 field("Component_Description", "Component", "Hoofdmotor"),
94 field("Task_Code", "Taakcode", "OH-500"),
95 field("Status", "Status", "Gepland"),
96 field("Start_Date", "Begindatum", "15 jan 2026"),
97 field("End_Date", "Einddatum", "16 jan 2026"),
98 field("Resource_Name", "Monteur", "Mara Lindqvist"),
99 field(
100 "KVT_Service_Coordinator",
101 "Servicecoördinator",
102 "Jonas Ortega",
103 ),
104 reference(
105 "Job_No",
106 "Project",
107 CardKind::Project,
108 company,
109 "PRJ2699001",
110 ),
111 reference(
112 "Contract_No",
113 "Contract",
114 CardKind::Contract,
115 company,
116 "CT2699001",
117 ),
118 ],
119 CardKind::Project => vec![
120 field("Sell_to_Customer_Name", "Klant", entry.subtitle),
121 field("Status", "Status", "Open"),
122 field("Starting_Date", "Begindatum", "2 feb 2026"),
123 field("Ending_Date", "Einddatum", "30 jun 2026"),
124 field("Project_Manager", "Projectleider", "Priya Nair"),
125 reference(
126 "KVT_Contract_No",
127 "Contract",
128 CardKind::Contract,
129 company,
130 "CT2699001",
131 ),
132 ],
133 CardKind::Contract => vec![
134 field("Name", "Klant", entry.subtitle),
135 field("Contract_Type", "Soort", "Onderhoud"),
136 field("Document_Status", "Status", "Getekend"),
137 field("Starting_Date", "Begindatum", "1 jan 2026"),
138 field("End_Date", "Einddatum", "31 dec 2028"),
139 field(
140 "KVT_Service_Coordinator",
141 "Servicecoördinator",
142 "Jonas Ortega",
143 ),
144 ],
145 };
146 Some(Card {
147 kind: entry.kind.api_name().to_owned(),
148 type_label: entry.kind.label_nl().to_owned(),
149 company: company.to_owned(),
150 no: entry.no.to_owned(),
151 title: entry.title.to_owned(),
152 subtitle: entry.subtitle.to_owned(),
153 fields,
154 links: CardLinks {
155 bc: bc_url(entry.kind, company, entry.no, None),
156 daedalus: (entry.kind == CardKind::Werkorder).then(|| {
157 format!(
158 "https://sleutels.kvt.nl/daedalus/index.php?workorder={}",
159 entry.no
160 )
161 }),
162 },
163 })
164 }
165
166 pub(super) fn search(kind: CardKind, company: &str, query: &str) -> Vec<SearchResult> {
167 let query = query.trim().to_lowercase();
168 ENTRIES
169 .iter()
170 .filter(|entry| entry.kind == kind)
171 .filter(|entry| {
172 entry.no.to_lowercase().contains(&query) || entry.title.to_lowercase().contains(&query)
173 })
174 .map(|entry| SearchResult {
175 kind: kind.api_name().to_owned(),
176 company: company.to_owned(),
177 no: entry.no.to_owned(),
178 title: entry.title.to_owned(),
179 subtitle: entry.subtitle.to_owned(),
180 bc_url: bc_url(kind, company, entry.no, None),
181 })
182 .collect()
183 }
@@ -0,0 +1,183 @@
1//! Verzonnen kaarten voor `--demo` (geen echte BC-gegevens, geen echte personen).
2
3use kvt_sleutels::links::bc_url;
4use kvt_sleutels::{
5 Card, CardField, CardKind, CardLinks, CardRef, FieldRef, SearchResult, StoredToken,
6};
7
8use super::DEFAULT_COMPANY as COMPANY;
9
10pub(super) fn token() -> StoredToken {
11 StoredToken {
12 token: String::new(),
13 expires_at: i64::MAX,
14 email: "dana.demo@example.com".to_owned(),
15 name: "Dana Demo".to_owned(),
16 }
17}
18
19pub(super) fn companies() -> Vec<String> {
20 vec![COMPANY.to_owned(), "KVT Germany".to_owned()]
21}
22
23fn field(key: &str, label: &str, value: &str) -> CardField {
24 CardField {
25 key: key.to_owned(),
26 label: label.to_owned(),
27 value: value.to_owned(),
28 date: None,
29 reference: None,
30 }
31}
32
33fn reference(key: &str, label: &str, kind: CardKind, company: &str, no: &str) -> CardField {
34 CardField {
35 reference: Some(FieldRef {
36 kind: kind.api_name().to_owned(),
37 no: no.to_owned(),
38 bc_url: bc_url(kind, company, no, None),
39 }),
40 ..field(key, label, no)
41 }
42}
43
44struct Entry {
45 kind: CardKind,
46 no: &'static str,
47 title: &'static str,
48 subtitle: &'static str,
49}
50
51const ENTRIES: [Entry; 5] = [
52 Entry {
53 kind: CardKind::Werkorder,
54 no: "WO2699001",
55 title: "Onderhoud 500 uur",
56 subtitle: "MS Voorbeeld",
57 },
58 Entry {
59 kind: CardKind::Werkorder,
60 no: "WO2699002",
61 title: "Inspectie generator",
62 subtitle: "Pontveer Demo",
63 },
64 Entry {
65 kind: CardKind::Project,
66 no: "PRJ2699001",
67 title: "Nieuwbouw aandrijving",
68 subtitle: "Rederij Voorbeeld",
69 },
70 Entry {
71 kind: CardKind::Project,
72 no: "PRJ2699002",
73 title: "Retrofit noodstroom",
74 subtitle: "Haven Demo",
75 },
76 Entry {
77 kind: CardKind::Contract,
78 no: "CT2699001",
79 title: "Onderhoudscontract vloot",
80 subtitle: "Rederij Voorbeeld",
81 },
82];
83
84pub(super) fn card(reference_to: &CardRef) -> Option<Card> {
85 let entry = ENTRIES
86 .iter()
87 .find(|entry| entry.kind == reference_to.kind && entry.no == reference_to.no)?;
88 let company = reference_to.company.as_str();
89 let fields = match entry.kind {
90 CardKind::Werkorder => vec![
91 field("Main_Entity_Description", "Object", entry.subtitle),
92 field("Sell_to_Name", "Klant", "Rederij Voorbeeld"),
93 field("Component_Description", "Component", "Hoofdmotor"),
94 field("Task_Code", "Taakcode", "OH-500"),
95 field("Status", "Status", "Gepland"),
96 field("Start_Date", "Begindatum", "15 jan 2026"),
97 field("End_Date", "Einddatum", "16 jan 2026"),
98 field("Resource_Name", "Monteur", "Mara Lindqvist"),
99 field(
100 "KVT_Service_Coordinator",
101 "Servicecoördinator",
102 "Jonas Ortega",
103 ),
104 reference(
105 "Job_No",
106 "Project",
107 CardKind::Project,
108 company,
109 "PRJ2699001",
110 ),
111 reference(
112 "Contract_No",
113 "Contract",
114 CardKind::Contract,
115 company,
116 "CT2699001",
117 ),
118 ],
119 CardKind::Project => vec![
120 field("Sell_to_Customer_Name", "Klant", entry.subtitle),
121 field("Status", "Status", "Open"),
122 field("Starting_Date", "Begindatum", "2 feb 2026"),
123 field("Ending_Date", "Einddatum", "30 jun 2026"),
124 field("Project_Manager", "Projectleider", "Priya Nair"),
125 reference(
126 "KVT_Contract_No",
127 "Contract",
128 CardKind::Contract,
129 company,
130 "CT2699001",
131 ),
132 ],
133 CardKind::Contract => vec![
134 field("Name", "Klant", entry.subtitle),
135 field("Contract_Type", "Soort", "Onderhoud"),
136 field("Document_Status", "Status", "Getekend"),
137 field("Starting_Date", "Begindatum", "1 jan 2026"),
138 field("End_Date", "Einddatum", "31 dec 2028"),
139 field(
140 "KVT_Service_Coordinator",
141 "Servicecoördinator",
142 "Jonas Ortega",
143 ),
144 ],
145 };
146 Some(Card {
147 kind: entry.kind.api_name().to_owned(),
148 type_label: entry.kind.label_nl().to_owned(),
149 company: company.to_owned(),
150 no: entry.no.to_owned(),
151 title: entry.title.to_owned(),
152 subtitle: entry.subtitle.to_owned(),
153 fields,
154 links: CardLinks {
155 bc: bc_url(entry.kind, company, entry.no, None),
156 daedalus: (entry.kind == CardKind::Werkorder).then(|| {
157 format!(
158 "https://sleutels.kvt.nl/daedalus/index.php?workorder={}",
159 entry.no
160 )
161 }),
162 },
163 })
164}
165
166pub(super) fn search(kind: CardKind, company: &str, query: &str) -> Vec<SearchResult> {
167 let query = query.trim().to_lowercase();
168 ENTRIES
169 .iter()
170 .filter(|entry| entry.kind == kind)
171 .filter(|entry| {
172 entry.no.to_lowercase().contains(&query) || entry.title.to_lowercase().contains(&query)
173 })
174 .map(|entry| SearchResult {
175 kind: kind.api_name().to_owned(),
176 company: company.to_owned(),
177 no: entry.no.to_owned(),
178 title: entry.title.to_owned(),
179 subtitle: entry.subtitle.to_owned(),
180 bc_url: bc_url(kind, company, entry.no, None),
181 })
182 .collect()
183}
crates/app/src/kvt/mod.rs added +489 −0
@@ -0,0 +1,489 @@
1 //! KVT-fork: kaarten voor Business Central-links via sleutels.kvt.nl.
2 //!
3 //! Een bericht met een BC-link (project, werkorder, contract) krijgt onder de tekst
4 //! een kaartje; een klik opent details uit Mímir. Verzenden blijft een gewone link
5 //! met leesbare tekst, dus de officiële Teams ziet niets bijzonders (GUARDRAILS:
6 //! geen eigen berichtformaten). Zie KVT-FORK.md en ADR 0024.
7 //!
8 //! Upstream-haken: `views/shell.rs` (install, overlay, dialog-telling),
9 //! `views/message_row.rs` en `views/post_card.rs` (kaartjes), `settings/general.rs`
10 //! (instellingen, via `settings/kvt.rs`), `views/composer/plus_menu.rs` (picker), `views/composer.rs`
11 //! (`mod kvt`).
12
13 mod card;
14 mod demo;
15 mod modal;
16 mod picker;
17 mod session;
18
19 use std::collections::HashMap;
20
21 use gpui_kit::*;
22 use kvt_sleutels::connect::{self, ConnectError};
23 use kvt_sleutels::{Card, CardKind, CardRef, CardsClient, ClientError, StoredToken, token};
24
25 use crate::app_state::AppHandle;
26 use crate::i18n::tr;
27 use crate::runtime;
28
29 pub use card::message_cards;
30 pub use modal::render_modal;
31 pub use picker::{open_picker, plus_item};
32
33 /// Alleen voor testen tegen een andere Login/Mímir (bijv. .test); altijd https.
34 const BASE_URL_ENV: &str = "KVT_SLEUTELS_URL";
35 /// Standaardbedrijf in BC (picker, demo).
36 pub(crate) const DEFAULT_COMPANY: &str = "Koninklijke van Twist";
37
38 #[derive(Clone)]
39 pub enum Link {
40 /// Keyring nog niet gelezen.
41 Unknown,
42 NotLinked,
43 Connecting,
44 Linked(StoredToken),
45 }
46
47 #[derive(Clone)]
48 pub(crate) enum Load {
49 Loading,
50 Loaded(Card),
51 Failed(ClientError),
52 }
53
54 type CardKey = (CardKind, String, String);
55
56 fn card_key(reference: &CardRef) -> CardKey {
57 (
58 reference.kind,
59 reference.company.clone(),
60 reference.no.clone(),
61 )
62 }
63
64 pub(crate) struct Kvt {
65 demo: bool,
66 client: CardsClient,
67 link: Link,
68 cards: HashMap<CardKey, Load>,
69 /// Open kaart en de linktekst uit het bericht (titel tot Mímir antwoordt).
70 modal: Option<(CardRef, String)>,
71 picker: Option<Entity<picker::Picker>>,
72 companies: Vec<String>,
73 connecting: Option<tokio::task::AbortHandle>,
74 connect_generation: u64,
75 }
76
77 impl Global for Kvt {}
78
79 fn base_url() -> String {
80 std::env::var(BASE_URL_ENV)
81 .ok()
82 .filter(|url| url.starts_with("https://"))
83 .unwrap_or_else(|| kvt_sleutels::DEFAULT_BASE_URL.to_owned())
84 }
85
86 /// Eenmalig bij het opstarten (vanuit `install_globals`).
87 pub fn install(demo: bool, cx: &mut App) {
88 cx.set_global(Kvt {
89 demo,
90 client: CardsClient::new(&base_url()),
91 link: if demo {
92 Link::Linked(demo::token())
93 } else {
94 Link::Unknown
95 },
96 cards: HashMap::new(),
97 modal: None,
98 picker: None,
99 companies: if demo { demo::companies() } else { Vec::new() },
100 connecting: None,
101 connect_generation: 0,
102 });
103 if demo {
104 return;
105 }
106 let loading = runtime::spawn(token::load_async());
107 cx.spawn(async move |cx| {
108 let stored = loading.await.ok().and_then(Result::ok).flatten();
109 cx.update(|cx| {
110 let now = now();
111 update(cx, |kvt| {
112 if matches!(kvt.link, Link::Unknown) {
113 kvt.link = match stored {
114 Some(stored) if !stored.is_expired(now) => Link::Linked(stored),
115 _ => Link::NotLinked,
116 };
117 }
118 });
119 });
120 })
121 .detach();
122 }
123
124 fn now() -> i64 {
125 std::time::SystemTime::now()
126 .duration_since(std::time::UNIX_EPOCH)
127 .map_or(0, |elapsed| elapsed.as_secs() as i64)
128 }
129
130 pub(crate) fn installed(cx: &App) -> bool {
131 cx.has_global::<Kvt>()
132 }
133
134 pub(crate) fn read<R>(cx: &App, read: impl FnOnce(&Kvt) -> R) -> Option<R> {
135 cx.try_global::<Kvt>().map(read)
136 }
137
138 pub(crate) fn update(cx: &mut App, change: impl FnOnce(&mut Kvt)) {
139 if cx.has_global::<Kvt>() {
140 change(cx.global_mut::<Kvt>());
141 cx.refresh_windows();
142 }
143 }
144
145 pub fn link(cx: &App) -> Link {
146 read(cx, |kvt| kvt.link.clone()).unwrap_or(Link::NotLinked)
147 }
148
149 pub(crate) fn is_demo(cx: &App) -> bool {
150 read(cx, |kvt| kvt.demo).unwrap_or(false)
151 }
152
153 pub(crate) fn token_and_client(cx: &App) -> Option<(String, CardsClient)> {
154 read(cx, |kvt| match &kvt.link {
155 Link::Linked(stored) => Some((stored.token.clone(), kvt.client.clone())),
156 _ => None,
157 })
158 .flatten()
159 }
160
161 /// Een 401: de token is verlopen of ingetrokken. Uit de keyring, opnieuw koppelen.
162 pub(crate) fn forget_token(cx: &mut App) {
163 update(cx, |kvt| {
164 kvt.link = Link::NotLinked;
165 kvt.cards.clear();
166 });
167 let _ = runtime::spawn(token::delete_async());
168 }
169
170 pub(crate) fn notice(text: String, cx: &mut App) {
171 if let Some(handle) = cx.try_global::<AppHandle>() {
172 handle
173 .0
174 .clone()
175 .update(cx, |state, cx| state.raise_notice(text, None, cx));
176 }
177 }
178
179 fn open_external(url: &str, cx: &mut App) {
180 let Some(handle) = cx.try_global::<AppHandle>() else {
181 cx.open_url(url);
182 return;
183 };
184 let store = handle.0.read(cx).store.clone();
185 crate::external_browser::open_url(cx, &store, url);
186 }
187
188 pub(crate) fn trusted_link(url: &str) -> bool {
189 kvt_sleutels::links::is_trusted_link(url)
190 }
191
192 pub(crate) fn kind_label(kind: CardKind) -> String {
193 tr(match kind {
194 CardKind::Project => "kvt.kind.project",
195 CardKind::Werkorder => "kvt.kind.werkorder",
196 CardKind::Contract => "kvt.kind.contract",
197 })
198 }
199
200 pub(crate) fn kind_symbol(kind: CardKind) -> &'static str {
201 match kind {
202 CardKind::Project => "folder",
203 CardKind::Werkorder => "build",
204 CardKind::Contract => "description",
205 }
206 }
207
208 pub(crate) fn error_text(error: &ClientError) -> String {
209 tr(match error {
210 ClientError::Unauthorized => "kvt.card.sign_in",
211 ClientError::Forbidden => "kvt.card.forbidden",
212 ClientError::NotFound | ClientError::BadRequest => "kvt.card.not_found",
213 ClientError::RateLimited => "kvt.card.rate_limited",
214 ClientError::Unavailable => "kvt.card.unavailable",
215 })
216 }
217
218 pub(crate) fn cached_card(reference: &CardRef, cx: &App) -> Option<Load> {
219 read(cx, |kvt| kvt.cards.get(&card_key(reference)).cloned()).flatten()
220 }
221
222 /// Open de kaart in de modal en haal hem op als hij er nog niet is.
223 pub(crate) fn open_card(reference: CardRef, anchor: String, cx: &mut App) {
224 let cached = matches!(
225 cached_card(&reference, cx),
226 Some(Load::Loaded(_) | Load::Loading)
227 );
228 update(cx, |kvt| kvt.modal = Some((reference.clone(), anchor)));
229 if !cached {
230 fetch(reference, cx);
231 }
232 }
233
234 pub(crate) fn close_card(cx: &mut App) {
235 update(cx, |kvt| kvt.modal = None);
236 }
237
238 pub(crate) fn fetch(reference: CardRef, cx: &mut App) {
239 let key = card_key(&reference);
240 if is_demo(cx) {
241 let load = match demo::card(&reference) {
242 Some(card) => Load::Loaded(card),
243 None => Load::Failed(ClientError::NotFound),
244 };
245 update(cx, |kvt| {
246 kvt.cards.insert(key, load);
247 });
248 return;
249 }
250 let Some((token, client)) = token_and_client(cx) else {
251 return;
252 };
253 update(cx, |kvt| {
254 kvt.cards.insert(key.clone(), Load::Loading);
255 });
256 let loading = runtime::spawn(async move {
257 client
258 .card(&token, reference.kind, &reference.company, &reference.no)
259 .await
260 });
261 cx.spawn(async move |cx| {
262 let result = loading.await.unwrap_or(Err(ClientError::Unavailable));
263 cx.update(|cx| {
264 if result == Err(ClientError::Unauthorized) {
265 forget_token(cx);
266 }
267 update(cx, |kvt| {
268 kvt.cards.insert(
269 key,
270 match result {
271 Ok(card) => Load::Loaded(card),
272 Err(error) => Load::Failed(error),
273 },
274 );
275 });
276 });
277 })
278 .detach();
279 }
280
281 fn device_name() -> String {
282 let host = std::env::var("COMPUTERNAME")
283 .ok()
284 .or_else(|| std::fs::read_to_string("/etc/hostname").ok())
285 .or_else(|| std::env::var("HOSTNAME").ok())
286 .unwrap_or_default();
287 let host: String = host
288 .trim()
289 .chars()
290 .filter(|c| c.is_alphanumeric() || "-_. ".contains(*c))
291 .take(40)
292 .collect();
293 if host.is_empty() {
294 "rusty-teams".to_owned()
295 } else {
296 host
297 }
298 }
299
300 fn host_of(base_url: &str) -> String {
301 base_url
302 .split_once("://")
303 .map_or(base_url, |(_, rest)| rest)
304 .split(['/', ':', '?', '#'])
305 .next()
306 .unwrap_or_default()
307 .to_ascii_lowercase()
308 }
309
310 /// Koppelen. Eerst stil in de sessiebrowser van de app (die al met Microsoft is
311 /// ingelogd); vraagt de Login daar om invoer, dan dezelfde koppeling in de
312 /// systeembrowser. In beide gevallen wacht de app op 127.0.0.1 op de code.
313 pub fn connect(cx: &mut App) {
314 if is_demo(cx) {
315 update(cx, |kvt| {
316 kvt.link = Link::Linked(demo::token());
317 kvt.companies = demo::companies();
318 });
319 notice(tr("kvt.notice.connected"), cx);
320 return;
321 }
322 if matches!(link(cx), Link::Connecting) {
323 return;
324 }
325 let Some(client) = read(cx, |kvt| kvt.client.clone()) else {
326 return;
327 };
328 let base = client.base_url().to_owned();
329 let sleutels_host = host_of(&base);
330 let http = client.http().clone();
331 let device = device_name();
332 let tabs = session::session_tabs();
333 // Alleen gevuld als de systeembrowser nodig is.
334 let (fallback_sender, fallback_receiver) = tokio::sync::oneshot::channel::<String>();
335 let (connecting, abort) = runtime::spawn_abortable(async move {
336 let pending = connect::begin(&base, &device).await?;
337 let url = pending.url.clone();
338 let waiting = connect::finish(pending, &http);
339 tokio::pin!(waiting);
340 let mut finished = None;
341 match &tabs {
342 Some(tabs) => {
343 let driving = kvt_sleutels::session::drive(
344 tabs.as_ref(),
345 &url,
346 &sleutels_host,
347 kvt_sleutels::session::Timing::default(),
348 );
349 tokio::pin!(driving);
350 let (outcome, tab) = loop {
351 tokio::select! {
352 result = &mut waiting, if finished.is_none() => finished = Some(result),
353 driven = &mut driving => break driven,
354 }
355 };
356 if outcome == kvt_sleutels::session::Outcome::NeedsUser && finished.is_none() {
357 log::info!(
358 "kvt-sleutels: session browser needs the user, using the system browser"
359 );
360 let _ = fallback_sender.send(url.clone());
361 }
362 if finished.is_some() || tab.is_some() {
363 if finished.is_none() {
364 finished = Some((&mut waiting).await);
365 }
366 kvt_sleutels::session::close_after(tabs.as_ref(), tab).await;
367 }
368 }
369 None => {
370 let _ = fallback_sender.send(url);
371 }
372 }
373 let stored = match finished {
374 Some(result) => result?,
375 None => (&mut waiting).await?,
376 };
377 if let Err(error) = token::store_async(stored.clone()).await {
378 // Zonder keyring blijft de koppeling alleen deze sessie bestaan.
379 log::warn!("kvt-sleutels: keyring unavailable: {error}");
380 }
381 Ok::<StoredToken, ConnectError>(stored)
382 });
383 let mut generation = 0;
384 update(cx, |kvt| {
385 kvt.connect_generation += 1;
386 generation = kvt.connect_generation;
387 kvt.link = Link::Connecting;
388 kvt.connecting = Some(abort);
389 });
390 cx.spawn(async move |cx| {
391 if let Ok(url) = fallback_receiver.await {
392 cx.update(|cx| open_external(&url, cx));
393 }
394 let result = connecting
395 .await
396 .unwrap_or(Err(ConnectError::Failed("cancelled".into())));
397 cx.update(|cx| {
398 let current = read(cx, |kvt| kvt.connect_generation == generation).unwrap_or(false);
399 if !current {
400 return;
401 }
402 let (link, text) = match result {
403 Ok(stored) => (Link::Linked(stored), tr("kvt.notice.connected")),
404 Err(ConnectError::Denied) => (Link::NotLinked, tr("kvt.notice.denied")),
405 Err(ConnectError::TimedOut) => (Link::NotLinked, tr("kvt.notice.timed_out")),
406 Err(ConnectError::Failed(reason)) => {
407 log::warn!("kvt-sleutels: connect failed: {reason}");
408 (Link::NotLinked, tr("kvt.notice.failed"))
409 }
410 };
411 update(cx, |kvt| {
412 kvt.link = link;
413 kvt.connecting = None;
414 kvt.cards.retain(|_, load| matches!(load, Load::Loaded(_)));
415 });
416 notice(text, cx);
417 });
418 })
419 .detach();
420 }
421
422 pub fn cancel_connect(cx: &mut App) {
423 update(cx, |kvt| {
424 kvt.connect_generation += 1;
425 if let Some(abort) = kvt.connecting.take() {
426 abort.abort();
427 }
428 if matches!(kvt.link, Link::Connecting) {
429 kvt.link = Link::NotLinked;
430 }
431 });
432 }
433
434 /// Ontkoppelen: token bij de Login intrekken en uit de keyring halen.
435 pub fn disconnect(cx: &mut App) {
436 let previous = if is_demo(cx) {
437 None
438 } else {
439 token_and_client(cx)
440 };
441 update(cx, |kvt| {
442 kvt.link = Link::NotLinked;
443 kvt.cards.clear();
444 kvt.companies.clear();
445 });
446 if let Some((token, client)) = previous {
447 let _ = runtime::spawn(async move {
448 client.revoke(&token).await;
449 let _ = token::delete_async().await;
450 });
451 }
452 notice(tr("kvt.notice.disconnected"), cx);
453 }
454
455 /// Telt mee voor de modale lagen van de shell.
456 pub fn dialog_open(cx: &App) -> bool {
457 read(cx, |kvt| kvt.modal.is_some() || kvt.picker.is_some()).unwrap_or(false)
458 }
459
460 /// Modal en picker boven de shell.
461 pub fn overlay(cx: &App) -> Vec<AnyElement> {
462 let mut layers = Vec::new();
463 if let Some(modal) = render_modal(cx) {
464 layers.push(modal);
465 }
466 if let Some(picker) = read(cx, |kvt| kvt.picker.clone()).flatten() {
467 layers.push(picker.into_any_element());
468 }
469 layers
470 }
471
472 #[cfg(test)]
473 mod tests {
474 use super::{device_name, host_of};
475
476 #[test]
477 fn host_of_base_url() {
478 assert_eq!(host_of("https://sleutels.kvt.nl"), "sleutels.kvt.nl");
479 assert_eq!(
480 host_of("https://Sleutels.test.kvt.nl:443/x"),
481 "sleutels.test.kvt.nl"
482 );
483 }
484
485 #[test]
486 fn device_name_is_never_empty() {
487 assert!(!device_name().is_empty());
488 }
489 }
@@ -0,0 +1,489 @@
1//! KVT-fork: kaarten voor Business Central-links via sleutels.kvt.nl.
2//!
3//! Een bericht met een BC-link (project, werkorder, contract) krijgt onder de tekst
4//! een kaartje; een klik opent details uit Mímir. Verzenden blijft een gewone link
5//! met leesbare tekst, dus de officiële Teams ziet niets bijzonders (GUARDRAILS:
6//! geen eigen berichtformaten). Zie KVT-FORK.md en ADR 0024.
7//!
8//! Upstream-haken: `views/shell.rs` (install, overlay, dialog-telling),
9//! `views/message_row.rs` en `views/post_card.rs` (kaartjes), `settings/general.rs`
10//! (instellingen, via `settings/kvt.rs`), `views/composer/plus_menu.rs` (picker), `views/composer.rs`
11//! (`mod kvt`).
12
13mod card;
14mod demo;
15mod modal;
16mod picker;
17mod session;
18
19use std::collections::HashMap;
20
21use gpui_kit::*;
22use kvt_sleutels::connect::{self, ConnectError};
23use kvt_sleutels::{Card, CardKind, CardRef, CardsClient, ClientError, StoredToken, token};
24
25use crate::app_state::AppHandle;
26use crate::i18n::tr;
27use crate::runtime;
28
29pub use card::message_cards;
30pub use modal::render_modal;
31pub use picker::{open_picker, plus_item};
32
33/// Alleen voor testen tegen een andere Login/Mímir (bijv. .test); altijd https.
34const BASE_URL_ENV: &str = "KVT_SLEUTELS_URL";
35/// Standaardbedrijf in BC (picker, demo).
36pub(crate) const DEFAULT_COMPANY: &str = "Koninklijke van Twist";
37
38#[derive(Clone)]
39pub enum Link {
40 /// Keyring nog niet gelezen.
41 Unknown,
42 NotLinked,
43 Connecting,
44 Linked(StoredToken),
45}
46
47#[derive(Clone)]
48pub(crate) enum Load {
49 Loading,
50 Loaded(Card),
51 Failed(ClientError),
52}
53
54type CardKey = (CardKind, String, String);
55
56fn card_key(reference: &CardRef) -> CardKey {
57 (
58 reference.kind,
59 reference.company.clone(),
60 reference.no.clone(),
61 )
62}
63
64pub(crate) struct Kvt {
65 demo: bool,
66 client: CardsClient,
67 link: Link,
68 cards: HashMap<CardKey, Load>,
69 /// Open kaart en de linktekst uit het bericht (titel tot Mímir antwoordt).
70 modal: Option<(CardRef, String)>,
71 picker: Option<Entity<picker::Picker>>,
72 companies: Vec<String>,
73 connecting: Option<tokio::task::AbortHandle>,
74 connect_generation: u64,
75}
76
77impl Global for Kvt {}
78
79fn base_url() -> String {
80 std::env::var(BASE_URL_ENV)
81 .ok()
82 .filter(|url| url.starts_with("https://"))
83 .unwrap_or_else(|| kvt_sleutels::DEFAULT_BASE_URL.to_owned())
84}
85
86/// Eenmalig bij het opstarten (vanuit `install_globals`).
87pub fn install(demo: bool, cx: &mut App) {
88 cx.set_global(Kvt {
89 demo,
90 client: CardsClient::new(&base_url()),
91 link: if demo {
92 Link::Linked(demo::token())
93 } else {
94 Link::Unknown
95 },
96 cards: HashMap::new(),
97 modal: None,
98 picker: None,
99 companies: if demo { demo::companies() } else { Vec::new() },
100 connecting: None,
101 connect_generation: 0,
102 });
103 if demo {
104 return;
105 }
106 let loading = runtime::spawn(token::load_async());
107 cx.spawn(async move |cx| {
108 let stored = loading.await.ok().and_then(Result::ok).flatten();
109 cx.update(|cx| {
110 let now = now();
111 update(cx, |kvt| {
112 if matches!(kvt.link, Link::Unknown) {
113 kvt.link = match stored {
114 Some(stored) if !stored.is_expired(now) => Link::Linked(stored),
115 _ => Link::NotLinked,
116 };
117 }
118 });
119 });
120 })
121 .detach();
122}
123
124fn now() -> i64 {
125 std::time::SystemTime::now()
126 .duration_since(std::time::UNIX_EPOCH)
127 .map_or(0, |elapsed| elapsed.as_secs() as i64)
128}
129
130pub(crate) fn installed(cx: &App) -> bool {
131 cx.has_global::<Kvt>()
132}
133
134pub(crate) fn read<R>(cx: &App, read: impl FnOnce(&Kvt) -> R) -> Option<R> {
135 cx.try_global::<Kvt>().map(read)
136}
137
138pub(crate) fn update(cx: &mut App, change: impl FnOnce(&mut Kvt)) {
139 if cx.has_global::<Kvt>() {
140 change(cx.global_mut::<Kvt>());
141 cx.refresh_windows();
142 }
143}
144
145pub fn link(cx: &App) -> Link {
146 read(cx, |kvt| kvt.link.clone()).unwrap_or(Link::NotLinked)
147}
148
149pub(crate) fn is_demo(cx: &App) -> bool {
150 read(cx, |kvt| kvt.demo).unwrap_or(false)
151}
152
153pub(crate) fn token_and_client(cx: &App) -> Option<(String, CardsClient)> {
154 read(cx, |kvt| match &kvt.link {
155 Link::Linked(stored) => Some((stored.token.clone(), kvt.client.clone())),
156 _ => None,
157 })
158 .flatten()
159}
160
161/// Een 401: de token is verlopen of ingetrokken. Uit de keyring, opnieuw koppelen.
162pub(crate) fn forget_token(cx: &mut App) {
163 update(cx, |kvt| {
164 kvt.link = Link::NotLinked;
165 kvt.cards.clear();
166 });
167 let _ = runtime::spawn(token::delete_async());
168}
169
170pub(crate) fn notice(text: String, cx: &mut App) {
171 if let Some(handle) = cx.try_global::<AppHandle>() {
172 handle
173 .0
174 .clone()
175 .update(cx, |state, cx| state.raise_notice(text, None, cx));
176 }
177}
178
179fn open_external(url: &str, cx: &mut App) {
180 let Some(handle) = cx.try_global::<AppHandle>() else {
181 cx.open_url(url);
182 return;
183 };
184 let store = handle.0.read(cx).store.clone();
185 crate::external_browser::open_url(cx, &store, url);
186}
187
188pub(crate) fn trusted_link(url: &str) -> bool {
189 kvt_sleutels::links::is_trusted_link(url)
190}
191
192pub(crate) fn kind_label(kind: CardKind) -> String {
193 tr(match kind {
194 CardKind::Project => "kvt.kind.project",
195 CardKind::Werkorder => "kvt.kind.werkorder",
196 CardKind::Contract => "kvt.kind.contract",
197 })
198}
199
200pub(crate) fn kind_symbol(kind: CardKind) -> &'static str {
201 match kind {
202 CardKind::Project => "folder",
203 CardKind::Werkorder => "build",
204 CardKind::Contract => "description",
205 }
206}
207
208pub(crate) fn error_text(error: &ClientError) -> String {
209 tr(match error {
210 ClientError::Unauthorized => "kvt.card.sign_in",
211 ClientError::Forbidden => "kvt.card.forbidden",
212 ClientError::NotFound | ClientError::BadRequest => "kvt.card.not_found",
213 ClientError::RateLimited => "kvt.card.rate_limited",
214 ClientError::Unavailable => "kvt.card.unavailable",
215 })
216}
217
218pub(crate) fn cached_card(reference: &CardRef, cx: &App) -> Option<Load> {
219 read(cx, |kvt| kvt.cards.get(&card_key(reference)).cloned()).flatten()
220}
221
222/// Open de kaart in de modal en haal hem op als hij er nog niet is.
223pub(crate) fn open_card(reference: CardRef, anchor: String, cx: &mut App) {
224 let cached = matches!(
225 cached_card(&reference, cx),
226 Some(Load::Loaded(_) | Load::Loading)
227 );
228 update(cx, |kvt| kvt.modal = Some((reference.clone(), anchor)));
229 if !cached {
230 fetch(reference, cx);
231 }
232}
233
234pub(crate) fn close_card(cx: &mut App) {
235 update(cx, |kvt| kvt.modal = None);
236}
237
238pub(crate) fn fetch(reference: CardRef, cx: &mut App) {
239 let key = card_key(&reference);
240 if is_demo(cx) {
241 let load = match demo::card(&reference) {
242 Some(card) => Load::Loaded(card),
243 None => Load::Failed(ClientError::NotFound),
244 };
245 update(cx, |kvt| {
246 kvt.cards.insert(key, load);
247 });
248 return;
249 }
250 let Some((token, client)) = token_and_client(cx) else {
251 return;
252 };
253 update(cx, |kvt| {
254 kvt.cards.insert(key.clone(), Load::Loading);
255 });
256 let loading = runtime::spawn(async move {
257 client
258 .card(&token, reference.kind, &reference.company, &reference.no)
259 .await
260 });
261 cx.spawn(async move |cx| {
262 let result = loading.await.unwrap_or(Err(ClientError::Unavailable));
263 cx.update(|cx| {
264 if result == Err(ClientError::Unauthorized) {
265 forget_token(cx);
266 }
267 update(cx, |kvt| {
268 kvt.cards.insert(
269 key,
270 match result {
271 Ok(card) => Load::Loaded(card),
272 Err(error) => Load::Failed(error),
273 },
274 );
275 });
276 });
277 })
278 .detach();
279}
280
281fn device_name() -> String {
282 let host = std::env::var("COMPUTERNAME")
283 .ok()
284 .or_else(|| std::fs::read_to_string("/etc/hostname").ok())
285 .or_else(|| std::env::var("HOSTNAME").ok())
286 .unwrap_or_default();
287 let host: String = host
288 .trim()
289 .chars()
290 .filter(|c| c.is_alphanumeric() || "-_. ".contains(*c))
291 .take(40)
292 .collect();
293 if host.is_empty() {
294 "rusty-teams".to_owned()
295 } else {
296 host
297 }
298}
299
300fn host_of(base_url: &str) -> String {
301 base_url
302 .split_once("://")
303 .map_or(base_url, |(_, rest)| rest)
304 .split(['/', ':', '?', '#'])
305 .next()
306 .unwrap_or_default()
307 .to_ascii_lowercase()
308}
309
310/// Koppelen. Eerst stil in de sessiebrowser van de app (die al met Microsoft is
311/// ingelogd); vraagt de Login daar om invoer, dan dezelfde koppeling in de
312/// systeembrowser. In beide gevallen wacht de app op 127.0.0.1 op de code.
313pub fn connect(cx: &mut App) {
314 if is_demo(cx) {
315 update(cx, |kvt| {
316 kvt.link = Link::Linked(demo::token());
317 kvt.companies = demo::companies();
318 });
319 notice(tr("kvt.notice.connected"), cx);
320 return;
321 }
322 if matches!(link(cx), Link::Connecting) {
323 return;
324 }
325 let Some(client) = read(cx, |kvt| kvt.client.clone()) else {
326 return;
327 };
328 let base = client.base_url().to_owned();
329 let sleutels_host = host_of(&base);
330 let http = client.http().clone();
331 let device = device_name();
332 let tabs = session::session_tabs();
333 // Alleen gevuld als de systeembrowser nodig is.
334 let (fallback_sender, fallback_receiver) = tokio::sync::oneshot::channel::<String>();
335 let (connecting, abort) = runtime::spawn_abortable(async move {
336 let pending = connect::begin(&base, &device).await?;
337 let url = pending.url.clone();
338 let waiting = connect::finish(pending, &http);
339 tokio::pin!(waiting);
340 let mut finished = None;
341 match &tabs {
342 Some(tabs) => {
343 let driving = kvt_sleutels::session::drive(
344 tabs.as_ref(),
345 &url,
346 &sleutels_host,
347 kvt_sleutels::session::Timing::default(),
348 );
349 tokio::pin!(driving);
350 let (outcome, tab) = loop {
351 tokio::select! {
352 result = &mut waiting, if finished.is_none() => finished = Some(result),
353 driven = &mut driving => break driven,
354 }
355 };
356 if outcome == kvt_sleutels::session::Outcome::NeedsUser && finished.is_none() {
357 log::info!(
358 "kvt-sleutels: session browser needs the user, using the system browser"
359 );
360 let _ = fallback_sender.send(url.clone());
361 }
362 if finished.is_some() || tab.is_some() {
363 if finished.is_none() {
364 finished = Some((&mut waiting).await);
365 }
366 kvt_sleutels::session::close_after(tabs.as_ref(), tab).await;
367 }
368 }
369 None => {
370 let _ = fallback_sender.send(url);
371 }
372 }
373 let stored = match finished {
374 Some(result) => result?,
375 None => (&mut waiting).await?,
376 };
377 if let Err(error) = token::store_async(stored.clone()).await {
378 // Zonder keyring blijft de koppeling alleen deze sessie bestaan.
379 log::warn!("kvt-sleutels: keyring unavailable: {error}");
380 }
381 Ok::<StoredToken, ConnectError>(stored)
382 });
383 let mut generation = 0;
384 update(cx, |kvt| {
385 kvt.connect_generation += 1;
386 generation = kvt.connect_generation;
387 kvt.link = Link::Connecting;
388 kvt.connecting = Some(abort);
389 });
390 cx.spawn(async move |cx| {
391 if let Ok(url) = fallback_receiver.await {
392 cx.update(|cx| open_external(&url, cx));
393 }
394 let result = connecting
395 .await
396 .unwrap_or(Err(ConnectError::Failed("cancelled".into())));
397 cx.update(|cx| {
398 let current = read(cx, |kvt| kvt.connect_generation == generation).unwrap_or(false);
399 if !current {
400 return;
401 }
402 let (link, text) = match result {
403 Ok(stored) => (Link::Linked(stored), tr("kvt.notice.connected")),
404 Err(ConnectError::Denied) => (Link::NotLinked, tr("kvt.notice.denied")),
405 Err(ConnectError::TimedOut) => (Link::NotLinked, tr("kvt.notice.timed_out")),
406 Err(ConnectError::Failed(reason)) => {
407 log::warn!("kvt-sleutels: connect failed: {reason}");
408 (Link::NotLinked, tr("kvt.notice.failed"))
409 }
410 };
411 update(cx, |kvt| {
412 kvt.link = link;
413 kvt.connecting = None;
414 kvt.cards.retain(|_, load| matches!(load, Load::Loaded(_)));
415 });
416 notice(text, cx);
417 });
418 })
419 .detach();
420}
421
422pub fn cancel_connect(cx: &mut App) {
423 update(cx, |kvt| {
424 kvt.connect_generation += 1;
425 if let Some(abort) = kvt.connecting.take() {
426 abort.abort();
427 }
428 if matches!(kvt.link, Link::Connecting) {
429 kvt.link = Link::NotLinked;
430 }
431 });
432}
433
434/// Ontkoppelen: token bij de Login intrekken en uit de keyring halen.
435pub fn disconnect(cx: &mut App) {
436 let previous = if is_demo(cx) {
437 None
438 } else {
439 token_and_client(cx)
440 };
441 update(cx, |kvt| {
442 kvt.link = Link::NotLinked;
443 kvt.cards.clear();
444 kvt.companies.clear();
445 });
446 if let Some((token, client)) = previous {
447 let _ = runtime::spawn(async move {
448 client.revoke(&token).await;
449 let _ = token::delete_async().await;
450 });
451 }
452 notice(tr("kvt.notice.disconnected"), cx);
453}
454
455/// Telt mee voor de modale lagen van de shell.
456pub fn dialog_open(cx: &App) -> bool {
457 read(cx, |kvt| kvt.modal.is_some() || kvt.picker.is_some()).unwrap_or(false)
458}
459
460/// Modal en picker boven de shell.
461pub fn overlay(cx: &App) -> Vec<AnyElement> {
462 let mut layers = Vec::new();
463 if let Some(modal) = render_modal(cx) {
464 layers.push(modal);
465 }
466 if let Some(picker) = read(cx, |kvt| kvt.picker.clone()).flatten() {
467 layers.push(picker.into_any_element());
468 }
469 layers
470}
471
472#[cfg(test)]
473mod tests {
474 use super::{device_name, host_of};
475
476 #[test]
477 fn host_of_base_url() {
478 assert_eq!(host_of("https://sleutels.kvt.nl"), "sleutels.kvt.nl");
479 assert_eq!(
480 host_of("https://Sleutels.test.kvt.nl:443/x"),
481 "sleutels.test.kvt.nl"
482 );
483 }
484
485 #[test]
486 fn device_name_is_never_empty() {
487 assert!(!device_name().is_empty());
488 }
489}
crates/app/src/kvt/modal.rs added +345 −0
@@ -0,0 +1,345 @@
1 //! Modal met de details van één kaart en de knop «Openen in BC».
2
3 use gpui_kit::component::scroll::ScrollableElement as _;
4 use gpui_kit::component::tooltip::Tooltip;
5 use gpui_kit::component::{h_flex, v_flex};
6 use gpui_kit::prelude::FluentBuilder as _;
7 use gpui_kit::*;
8 use kvt_sleutels::links::bc_url;
9 use kvt_sleutels::{Card, CardKind, CardRef, parse_card_link};
10
11 use super::card::title_from_anchor;
12 use super::{
13 Link, Load, cached_card, close_card, connect, error_text, fetch, kind_label, kind_symbol, link,
14 notice, open_card, read, trusted_link,
15 };
16 use crate::i18n::tr;
17 use crate::theme::{self, ElevatedSurface as _};
18 use crate::views::widgets::symbol;
19
20 pub const KVT_CARD_DIALOG_TAG: &str = "kvt-card-dialog";
21 const BACKDROP_OPACITY: f32 = 0.55;
22 const PANEL_WIDTH: f32 = 500.;
23 const PANEL_MARGIN: f32 = 32.;
24 const PANEL_RADIUS: f32 = 10.;
25 const PANEL_PADDING: f32 = 16.;
26 const SECTION_GAP: f32 = 12.;
27 const CLOSE_SIZE: f32 = 28.;
28 const BADGE_SIZE: f32 = 36.;
29 const LABEL_WIDTH: f32 = 150.;
30 const BUTTON_HEIGHT: f32 = 32.;
31 const FIELDS_MAX_HEIGHT: f32 = 360.;
32
33 pub fn render_modal(cx: &App) -> Option<AnyElement> {
34 let (reference, anchor) = read(cx, |kvt| kvt.modal.clone()).flatten()?;
35 Some(
36 div()
37 .id("kvt-card-layer")
38 .absolute()
39 .top_0()
40 .left_0()
41 .size_full()
42 .flex()
43 .items_center()
44 .justify_center()
45 .child(
46 div()
47 .id("kvt-card-backdrop")
48 .absolute()
49 .top_0()
50 .left_0()
51 .size_full()
52 .bg(black().opacity(BACKDROP_OPACITY))
53 .occlude()
54 .on_click(|_, _, cx| close_card(cx)),
55 )
56 .child(panel(reference, anchor, cx))
57 .into_any_element(),
58 )
59 }
60
61 fn panel(reference: CardRef, anchor: String, cx: &App) -> Div {
62 let load = cached_card(&reference, cx);
63 let loaded = match &load {
64 Some(Load::Loaded(card)) => Some(card.clone()),
65 _ => None,
66 };
67 v_flex()
68 .debug_selector(|| KVT_CARD_DIALOG_TAG.into())
69 .w(px(PANEL_WIDTH))
70 .max_w(relative(1.))
71 .max_h(relative(1.))
72 .m(px(PANEL_MARGIN))
73 .p(px(PANEL_PADDING))
74 .gap(px(SECTION_GAP))
75 .rounded(px(PANEL_RADIUS))
76 .dialog_surface()
77 .text_color(theme::text())
78 .occlude()
79 .child(header(&reference, &anchor, loaded.as_ref()))
80 .child(body(&reference, load, cx))
81 .child(actions(&reference, loaded.as_ref()))
82 }
83
84 fn header(reference: &CardRef, anchor: &str, card: Option<&Card>) -> Div {
85 let (title, subtitle) = match card {
86 Some(card) => (card.title.clone(), card.subtitle.clone()),
87 None => (title_from_anchor(reference, anchor), String::new()),
88 };
89 let detail = if subtitle.is_empty() {
90 reference.company.clone()
91 } else {
92 format!("{subtitle} · {}", reference.company)
93 };
94 h_flex()
95 .w_full()
96 .gap(px(SECTION_GAP))
97 .items_start()
98 .child(
99 div()
100 .size(px(BADGE_SIZE))
101 .flex_none()
102 .flex()
103 .items_center()
104 .justify_center()
105 .rounded(px(8.))
106 .bg(theme::accent())
107 .child(symbol(kind_symbol(reference.kind), 20., theme::on_accent())),
108 )
109 .child(
110 v_flex()
111 .flex_1()
112 .min_w_0()
113 .gap(px(2.))
114 .child(
115 div()
116 .text_size(px(12.))
117 .font_weight(FontWeight::SEMIBOLD)
118 .text_color(theme::text_muted())
119 .child(format!("{} {}", kind_label(reference.kind), reference.no)),
120 )
121 .when(!title.is_empty(), |column| {
122 column.child(
123 div()
124 .text_size(px(15.))
125 .font_weight(FontWeight::SEMIBOLD)
126 .text_color(theme::text_strong())
127 .child(title),
128 )
129 })
130 .child(
131 div()
132 .truncate()
133 .text_size(px(12.))
134 .text_color(theme::text_muted())
135 .child(detail),
136 ),
137 )
138 .child(
139 icon_button("kvt-card-refresh", "refresh", tr("kvt.card.refresh")).on_click({
140 let reference = reference.clone();
141 move |_, _, cx| fetch(reference.clone(), cx)
142 }),
143 )
144 .child(
145 div()
146 .id("kvt-card-close")
147 .size(px(CLOSE_SIZE))
148 .flex_none()
149 .flex()
150 .items_center()
151 .justify_center()
152 .rounded_full()
153 .cursor_pointer()
154 .hover(|button| button.bg(theme::popup_hover()))
155 .on_click(|_, _, cx| close_card(cx))
156 .child(symbol("close", 16., theme::text_muted())),
157 )
158 }
159
160 fn icon_button(id: &'static str, symbol_name: &'static str, label: String) -> Stateful<Div> {
161 div()
162 .id(id)
163 .size(px(CLOSE_SIZE))
164 .flex_none()
165 .flex()
166 .items_center()
167 .justify_center()
168 .rounded_full()
169 .cursor_pointer()
170 .hover(|button| button.bg(theme::popup_hover()))
171 .tooltip(move |window, cx| Tooltip::new(label.clone()).build(window, cx))
172 .child(symbol(symbol_name, 16., theme::text_muted()))
173 }
174
175 fn message(text: String) -> Div {
176 div()
177 .w_full()
178 .py(px(8.))
179 .text_size(px(13.))
180 .text_color(theme::text_muted())
181 .child(text)
182 }
183
184 fn body(reference: &CardRef, load: Option<Load>, cx: &App) -> AnyElement {
185 match (link(cx), load) {
186 (_, Some(Load::Loaded(card))) => fields(reference, &card).into_any_element(),
187 (Link::Connecting, _) => message(tr("kvt.settings.connecting")).into_any_element(),
188 (Link::NotLinked | Link::Unknown, _) => v_flex()
189 .w_full()
190 .gap(px(8.))
191 .child(message(tr("kvt.card.sign_in")))
192 .child(
193 primary_button("kvt-card-connect", tr("kvt.settings.connect"))
194 .self_start()
195 .on_click(|_, _, cx| connect(cx)),
196 )
197 .into_any_element(),
198 (_, Some(Load::Failed(error))) => message(error_text(&error)).into_any_element(),
199 (_, Some(Load::Loading) | None) => message(tr("kvt.card.loading")).into_any_element(),
200 }
201 }
202
203 fn fields(reference: &CardRef, card: &Card) -> impl IntoElement + use<> {
204 let rows: Vec<AnyElement> = card
205 .fields
206 .iter()
207 .filter(|field| !field.value.trim().is_empty())
208 .enumerate()
209 .map(|(index, field)| {
210 let value = div().flex_1().min_w_0().text_size(px(13.));
211 let value = match field.reference.as_ref().and_then(|target| {
212 let kind = CardKind::from_api_name(&target.kind)?;
213 let url = if trusted_link(&target.bc_url) {
214 target.bc_url.clone()
215 } else {
216 bc_url(
217 kind,
218 &reference.company,
219 &target.no,
220 reference.environment.as_deref(),
221 )
222 };
223 parse_card_link(&url)
224 }) {
225 Some(target) => {
226 let anchor = field.value.clone();
227 value
228 .id(ElementId::Name(format!("kvt-card-ref-{index}").into()))
229 .text_color(theme::accent_text())
230 .cursor_pointer()
231 .hover(|value| value.underline())
232 .on_click(move |_, _, cx| open_card(target.clone(), anchor.clone(), cx))
233 .child(field.value.clone())
234 .into_any_element()
235 }
236 None => value
237 .text_color(theme::text())
238 .child(field.value.clone())
239 .into_any_element(),
240 };
241 h_flex()
242 .w_full()
243 .gap(px(SECTION_GAP))
244 .items_start()
245 .child(
246 div()
247 .w(px(LABEL_WIDTH))
248 .flex_none()
249 .text_size(px(12.))
250 .line_height(px(19.))
251 .text_color(theme::text_muted())
252 .child(field.label.clone()),
253 )
254 .child(value)
255 .into_any_element()
256 })
257 .collect();
258 v_flex()
259 .id("kvt-card-fields")
260 .w_full()
261 .max_h(px(FIELDS_MAX_HEIGHT))
262 .overflow_y_scrollbar()
263 .gap(px(6.))
264 .children(rows)
265 }
266
267 fn primary_button(id: &'static str, label: String) -> Stateful<Div> {
268 h_flex()
269 .id(id)
270 .h(px(BUTTON_HEIGHT))
271 .flex_none()
272 .px(px(16.))
273 .gap(px(6.))
274 .items_center()
275 .rounded(px(6.))
276 .bg(theme::accent())
277 .text_color(theme::on_accent())
278 .text_size(px(13.))
279 .font_weight(FontWeight::SEMIBOLD)
280 .cursor_pointer()
281 .hover(|button| button.bg(theme::accent_text()))
282 .child(label)
283 }
284
285 fn secondary_button(id: &'static str, symbol_name: &'static str, label: String) -> Stateful<Div> {
286 h_flex()
287 .id(id)
288 .h(px(BUTTON_HEIGHT))
289 .flex_none()
290 .px(px(12.))
291 .gap(px(6.))
292 .items_center()
293 .rounded(px(6.))
294 .bg(theme::popup_hover())
295 .text_color(theme::text())
296 .text_size(px(13.))
297 .cursor_pointer()
298 .hover(|button| button.bg(theme::row_hover()))
299 .child(symbol(symbol_name, 14., theme::text_soft()))
300 .child(label)
301 }
302
303 fn actions(reference: &CardRef, card: Option<&Card>) -> Div {
304 let bc = card
305 .map(|card| card.links.bc.clone())
306 .filter(|url| trusted_link(url))
307 .unwrap_or_else(|| {
308 bc_url(
309 reference.kind,
310 &reference.company,
311 &reference.no,
312 reference.environment.as_deref(),
313 )
314 });
315 let daedalus = card
316 .and_then(|card| card.links.daedalus.clone())
317 .filter(|url| trusted_link(url));
318 let no = reference.no.clone();
319 h_flex()
320 .w_full()
321 .flex_wrap()
322 .gap(px(8.))
323 .items_center()
324 .child(
325 primary_button("kvt-card-open-bc", tr("kvt.card.open_in_bc"))
326 .child(symbol("open_in_new", 14., theme::on_accent()))
327 .on_click(move |_, _, cx| app_ui_kit::render::hooks::open_link(&bc, cx)),
328 )
329 .children(daedalus.map(|url| {
330 secondary_button(
331 "kvt-card-open-daedalus",
332 "open_in_new",
333 tr("kvt.card.open_daedalus"),
334 )
335 .on_click(move |_, _, cx| app_ui_kit::render::hooks::open_link(&url, cx))
336 }))
337 .child(
338 secondary_button("kvt-card-copy", "content_copy", tr("kvt.card.copy_no")).on_click(
339 move |_, _, cx| {
340 cx.write_to_clipboard(ClipboardItem::new_string(no.clone()));
341 notice(tr("kvt.notice.copied"), cx);
342 },
343 ),
344 )
345 }
@@ -0,0 +1,345 @@
1//! Modal met de details van één kaart en de knop «Openen in BC».
2
3use gpui_kit::component::scroll::ScrollableElement as _;
4use gpui_kit::component::tooltip::Tooltip;
5use gpui_kit::component::{h_flex, v_flex};
6use gpui_kit::prelude::FluentBuilder as _;
7use gpui_kit::*;
8use kvt_sleutels::links::bc_url;
9use kvt_sleutels::{Card, CardKind, CardRef, parse_card_link};
10
11use super::card::title_from_anchor;
12use super::{
13 Link, Load, cached_card, close_card, connect, error_text, fetch, kind_label, kind_symbol, link,
14 notice, open_card, read, trusted_link,
15};
16use crate::i18n::tr;
17use crate::theme::{self, ElevatedSurface as _};
18use crate::views::widgets::symbol;
19
20pub const KVT_CARD_DIALOG_TAG: &str = "kvt-card-dialog";
21const BACKDROP_OPACITY: f32 = 0.55;
22const PANEL_WIDTH: f32 = 500.;
23const PANEL_MARGIN: f32 = 32.;
24const PANEL_RADIUS: f32 = 10.;
25const PANEL_PADDING: f32 = 16.;
26const SECTION_GAP: f32 = 12.;
27const CLOSE_SIZE: f32 = 28.;
28const BADGE_SIZE: f32 = 36.;
29const LABEL_WIDTH: f32 = 150.;
30const BUTTON_HEIGHT: f32 = 32.;
31const FIELDS_MAX_HEIGHT: f32 = 360.;
32
33pub fn render_modal(cx: &App) -> Option<AnyElement> {
34 let (reference, anchor) = read(cx, |kvt| kvt.modal.clone()).flatten()?;
35 Some(
36 div()
37 .id("kvt-card-layer")
38 .absolute()
39 .top_0()
40 .left_0()
41 .size_full()
42 .flex()
43 .items_center()
44 .justify_center()
45 .child(
46 div()
47 .id("kvt-card-backdrop")
48 .absolute()
49 .top_0()
50 .left_0()
51 .size_full()
52 .bg(black().opacity(BACKDROP_OPACITY))
53 .occlude()
54 .on_click(|_, _, cx| close_card(cx)),
55 )
56 .child(panel(reference, anchor, cx))
57 .into_any_element(),
58 )
59}
60
61fn panel(reference: CardRef, anchor: String, cx: &App) -> Div {
62 let load = cached_card(&reference, cx);
63 let loaded = match &load {
64 Some(Load::Loaded(card)) => Some(card.clone()),
65 _ => None,
66 };
67 v_flex()
68 .debug_selector(|| KVT_CARD_DIALOG_TAG.into())
69 .w(px(PANEL_WIDTH))
70 .max_w(relative(1.))
71 .max_h(relative(1.))
72 .m(px(PANEL_MARGIN))
73 .p(px(PANEL_PADDING))
74 .gap(px(SECTION_GAP))
75 .rounded(px(PANEL_RADIUS))
76 .dialog_surface()
77 .text_color(theme::text())
78 .occlude()
79 .child(header(&reference, &anchor, loaded.as_ref()))
80 .child(body(&reference, load, cx))
81 .child(actions(&reference, loaded.as_ref()))
82}
83
84fn header(reference: &CardRef, anchor: &str, card: Option<&Card>) -> Div {
85 let (title, subtitle) = match card {
86 Some(card) => (card.title.clone(), card.subtitle.clone()),
87 None => (title_from_anchor(reference, anchor), String::new()),
88 };
89 let detail = if subtitle.is_empty() {
90 reference.company.clone()
91 } else {
92 format!("{subtitle} · {}", reference.company)
93 };
94 h_flex()
95 .w_full()
96 .gap(px(SECTION_GAP))
97 .items_start()
98 .child(
99 div()
100 .size(px(BADGE_SIZE))
101 .flex_none()
102 .flex()
103 .items_center()
104 .justify_center()
105 .rounded(px(8.))
106 .bg(theme::accent())
107 .child(symbol(kind_symbol(reference.kind), 20., theme::on_accent())),
108 )
109 .child(
110 v_flex()
111 .flex_1()
112 .min_w_0()
113 .gap(px(2.))
114 .child(
115 div()
116 .text_size(px(12.))
117 .font_weight(FontWeight::SEMIBOLD)
118 .text_color(theme::text_muted())
119 .child(format!("{} {}", kind_label(reference.kind), reference.no)),
120 )
121 .when(!title.is_empty(), |column| {
122 column.child(
123 div()
124 .text_size(px(15.))
125 .font_weight(FontWeight::SEMIBOLD)
126 .text_color(theme::text_strong())
127 .child(title),
128 )
129 })
130 .child(
131 div()
132 .truncate()
133 .text_size(px(12.))
134 .text_color(theme::text_muted())
135 .child(detail),
136 ),
137 )
138 .child(
139 icon_button("kvt-card-refresh", "refresh", tr("kvt.card.refresh")).on_click({
140 let reference = reference.clone();
141 move |_, _, cx| fetch(reference.clone(), cx)
142 }),
143 )
144 .child(
145 div()
146 .id("kvt-card-close")
147 .size(px(CLOSE_SIZE))
148 .flex_none()
149 .flex()
150 .items_center()
151 .justify_center()
152 .rounded_full()
153 .cursor_pointer()
154 .hover(|button| button.bg(theme::popup_hover()))
155 .on_click(|_, _, cx| close_card(cx))
156 .child(symbol("close", 16., theme::text_muted())),
157 )
158}
159
160fn icon_button(id: &'static str, symbol_name: &'static str, label: String) -> Stateful<Div> {
161 div()
162 .id(id)
163 .size(px(CLOSE_SIZE))
164 .flex_none()
165 .flex()
166 .items_center()
167 .justify_center()
168 .rounded_full()
169 .cursor_pointer()
170 .hover(|button| button.bg(theme::popup_hover()))
171 .tooltip(move |window, cx| Tooltip::new(label.clone()).build(window, cx))
172 .child(symbol(symbol_name, 16., theme::text_muted()))
173}
174
175fn message(text: String) -> Div {
176 div()
177 .w_full()
178 .py(px(8.))
179 .text_size(px(13.))
180 .text_color(theme::text_muted())
181 .child(text)
182}
183
184fn body(reference: &CardRef, load: Option<Load>, cx: &App) -> AnyElement {
185 match (link(cx), load) {
186 (_, Some(Load::Loaded(card))) => fields(reference, &card).into_any_element(),
187 (Link::Connecting, _) => message(tr("kvt.settings.connecting")).into_any_element(),
188 (Link::NotLinked | Link::Unknown, _) => v_flex()
189 .w_full()
190 .gap(px(8.))
191 .child(message(tr("kvt.card.sign_in")))
192 .child(
193 primary_button("kvt-card-connect", tr("kvt.settings.connect"))
194 .self_start()
195 .on_click(|_, _, cx| connect(cx)),
196 )
197 .into_any_element(),
198 (_, Some(Load::Failed(error))) => message(error_text(&error)).into_any_element(),
199 (_, Some(Load::Loading) | None) => message(tr("kvt.card.loading")).into_any_element(),
200 }
201}
202
203fn fields(reference: &CardRef, card: &Card) -> impl IntoElement + use<> {
204 let rows: Vec<AnyElement> = card
205 .fields
206 .iter()
207 .filter(|field| !field.value.trim().is_empty())
208 .enumerate()
209 .map(|(index, field)| {
210 let value = div().flex_1().min_w_0().text_size(px(13.));
211 let value = match field.reference.as_ref().and_then(|target| {
212 let kind = CardKind::from_api_name(&target.kind)?;
213 let url = if trusted_link(&target.bc_url) {
214 target.bc_url.clone()
215 } else {
216 bc_url(
217 kind,
218 &reference.company,
219 &target.no,
220 reference.environment.as_deref(),
221 )
222 };
223 parse_card_link(&url)
224 }) {
225 Some(target) => {
226 let anchor = field.value.clone();
227 value
228 .id(ElementId::Name(format!("kvt-card-ref-{index}").into()))
229 .text_color(theme::accent_text())
230 .cursor_pointer()
231 .hover(|value| value.underline())
232 .on_click(move |_, _, cx| open_card(target.clone(), anchor.clone(), cx))
233 .child(field.value.clone())
234 .into_any_element()
235 }
236 None => value
237 .text_color(theme::text())
238 .child(field.value.clone())
239 .into_any_element(),
240 };
241 h_flex()
242 .w_full()
243 .gap(px(SECTION_GAP))
244 .items_start()
245 .child(
246 div()
247 .w(px(LABEL_WIDTH))
248 .flex_none()
249 .text_size(px(12.))
250 .line_height(px(19.))
251 .text_color(theme::text_muted())
252 .child(field.label.clone()),
253 )
254 .child(value)
255 .into_any_element()
256 })
257 .collect();
258 v_flex()
259 .id("kvt-card-fields")
260 .w_full()
261 .max_h(px(FIELDS_MAX_HEIGHT))
262 .overflow_y_scrollbar()
263 .gap(px(6.))
264 .children(rows)
265}
266
267fn primary_button(id: &'static str, label: String) -> Stateful<Div> {
268 h_flex()
269 .id(id)
270 .h(px(BUTTON_HEIGHT))
271 .flex_none()
272 .px(px(16.))
273 .gap(px(6.))
274 .items_center()
275 .rounded(px(6.))
276 .bg(theme::accent())
277 .text_color(theme::on_accent())
278 .text_size(px(13.))
279 .font_weight(FontWeight::SEMIBOLD)
280 .cursor_pointer()
281 .hover(|button| button.bg(theme::accent_text()))
282 .child(label)
283}
284
285fn secondary_button(id: &'static str, symbol_name: &'static str, label: String) -> Stateful<Div> {
286 h_flex()
287 .id(id)
288 .h(px(BUTTON_HEIGHT))
289 .flex_none()
290 .px(px(12.))
291 .gap(px(6.))
292 .items_center()
293 .rounded(px(6.))
294 .bg(theme::popup_hover())
295 .text_color(theme::text())
296 .text_size(px(13.))
297 .cursor_pointer()
298 .hover(|button| button.bg(theme::row_hover()))
299 .child(symbol(symbol_name, 14., theme::text_soft()))
300 .child(label)
301}
302
303fn actions(reference: &CardRef, card: Option<&Card>) -> Div {
304 let bc = card
305 .map(|card| card.links.bc.clone())
306 .filter(|url| trusted_link(url))
307 .unwrap_or_else(|| {
308 bc_url(
309 reference.kind,
310 &reference.company,
311 &reference.no,
312 reference.environment.as_deref(),
313 )
314 });
315 let daedalus = card
316 .and_then(|card| card.links.daedalus.clone())
317 .filter(|url| trusted_link(url));
318 let no = reference.no.clone();
319 h_flex()
320 .w_full()
321 .flex_wrap()
322 .gap(px(8.))
323 .items_center()
324 .child(
325 primary_button("kvt-card-open-bc", tr("kvt.card.open_in_bc"))
326 .child(symbol("open_in_new", 14., theme::on_accent()))
327 .on_click(move |_, _, cx| app_ui_kit::render::hooks::open_link(&bc, cx)),
328 )
329 .children(daedalus.map(|url| {
330 secondary_button(
331 "kvt-card-open-daedalus",
332 "open_in_new",
333 tr("kvt.card.open_daedalus"),
334 )
335 .on_click(move |_, _, cx| app_ui_kit::render::hooks::open_link(&url, cx))
336 }))
337 .child(
338 secondary_button("kvt-card-copy", "content_copy", tr("kvt.card.copy_no")).on_click(
339 move |_, _, cx| {
340 cx.write_to_clipboard(ClipboardItem::new_string(no.clone()));
341 notice(tr("kvt.notice.copied"), cx);
342 },
343 ),
344 )
345}
crates/app/src/kvt/picker.rs added +603 −0
@@ -0,0 +1,603 @@
1 //! Picker in het plusmenu van het opstelvak: project, werkorder of contract zoeken
2 //! en als gewone link met leesbare tekst invoegen.
3
4 use std::time::Duration;
5
6 use gpui_kit::component::fluent::{
7 MENU_ICON_LABEL_GAP, MENU_ICON_SLOT, MENU_ITEM_HEIGHT, MENU_ITEM_PADDING_X,
8 };
9 use gpui_kit::component::input::{Input, InputEvent, InputState};
10 use gpui_kit::component::scroll::ScrollableElement as _;
11 use gpui_kit::component::{h_flex, v_flex};
12 use gpui_kit::prelude::FluentBuilder as _;
13 use gpui_kit::*;
14 use kvt_sleutels::links::{anchor_text, bc_url};
15 use kvt_sleutels::{CardKind, ClientError, SearchResult, parse_card_link};
16
17 use super::{
18 DEFAULT_COMPANY, Link, connect, error_text, forget_token, is_demo, kind_label, kind_symbol,
19 link, read, token_and_client, trusted_link, update,
20 };
21 use crate::i18n::tr;
22 use crate::runtime;
23 use crate::theme::{self, ElevatedSurface as _};
24 use crate::views::composer::Composer;
25 use crate::views::widgets::symbol;
26
27 pub const KVT_PICKER_TAG: &str = "kvt-picker";
28 pub const KVT_PLUS_ITEM_TAG: &str = "composer-plus/kvt-link";
29 const SEARCH_DEBOUNCE: Duration = Duration::from_millis(300);
30 const MIN_QUERY: usize = 2;
31 const BACKDROP_OPACITY: f32 = 0.55;
32 const PANEL_WIDTH: f32 = 480.;
33 const PANEL_MARGIN: f32 = 32.;
34 const PANEL_RADIUS: f32 = 10.;
35 const PANEL_PADDING: f32 = 16.;
36 const SECTION_GAP: f32 = 12.;
37 const CLOSE_SIZE: f32 = 28.;
38 const FIELD_HEIGHT: f32 = 36.;
39 const CHIP_HEIGHT: f32 = 28.;
40 const ROW_HEIGHT: f32 = 44.;
41 const MAX_ROWS: usize = 10;
42 const ITEM_ICON_SIZE: f32 = 20.;
43
44 #[derive(Clone, PartialEq, Eq)]
45 enum Status {
46 TypeMore,
47 Searching,
48 Done,
49 Failed(ClientError),
50 }
51
52 pub struct Picker {
53 composer: WeakEntity<Composer>,
54 kind: CardKind,
55 company: Option<String>,
56 search: Entity<InputState>,
57 results: Vec<SearchResult>,
58 status: Status,
59 highlighted: usize,
60 generation: u64,
61 task: Option<Task<()>>,
62 _subscription: Subscription,
63 }
64
65 /// Regel in het plusmenu; `None` als de KVT-koppeling niet geladen is.
66 pub fn plus_item(
67 on_click: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
68 cx: &App,
69 ) -> Option<Stateful<Div>> {
70 if !super::installed(cx) {
71 return None;
72 }
73 Some(
74 h_flex()
75 .id(KVT_PLUS_ITEM_TAG)
76 .debug_selector(|| KVT_PLUS_ITEM_TAG.into())
77 .w_full()
78 .h(MENU_ITEM_HEIGHT)
79 .flex_none()
80 .px(MENU_ITEM_PADDING_X)
81 .gap(MENU_ICON_LABEL_GAP)
82 .items_center()
83 .rounded(px(6.))
84 .cursor_pointer()
85 .hover(|row| row.bg(theme::popup_hover()))
86 .child(
87 div()
88 .size(MENU_ICON_SLOT)
89 .flex_none()
90 .flex()
91 .items_center()
92 .justify_center()
93 .child(symbol("link", ITEM_ICON_SIZE, theme::text_soft())),
94 )
95 .child(
96 div()
97 .text_size(px(13.))
98 .text_color(theme::text())
99 .child(tr("kvt.picker.menu")),
100 )
101 .on_click(on_click),
102 )
103 }
104
105 pub fn open_picker(composer: WeakEntity<Composer>, window: &mut Window, cx: &mut App) {
106 if !super::installed(cx) {
107 return;
108 }
109 let picker = cx.new(|cx| Picker::new(composer, window, cx));
110 update(cx, |kvt| kvt.picker = Some(picker));
111 ensure_companies(cx);
112 }
113
114 fn close_picker(cx: &mut App) {
115 update(cx, |kvt| kvt.picker = None);
116 }
117
118 /// Bedrijvenlijst eenmalig ophalen (alleen nodig voor de keuze in de picker).
119 fn ensure_companies(cx: &mut App) {
120 let known = read(cx, |kvt| !kvt.companies.is_empty()).unwrap_or(true);
121 if known || is_demo(cx) {
122 return;
123 }
124 let Some((token, client)) = token_and_client(cx) else {
125 return;
126 };
127 let loading = runtime::spawn(async move { client.companies(&token).await });
128 cx.spawn(async move |cx| {
129 if let Ok(Ok(companies)) = loading.await {
130 cx.update(|cx| update(cx, |kvt| kvt.companies = companies));
131 }
132 })
133 .detach();
134 }
135
136 fn companies(cx: &App) -> Vec<String> {
137 read(cx, |kvt| kvt.companies.clone()).unwrap_or_default()
138 }
139
140 /// Het gekozen bedrijf, anders het eerste uit Mímir, anders KVT.
141 fn effective_company(chosen: Option<&str>, known: &[String]) -> String {
142 chosen
143 .map(str::to_owned)
144 .or_else(|| {
145 known
146 .iter()
147 .find(|name| name.as_str() == DEFAULT_COMPANY)
148 .cloned()
149 })
150 .or_else(|| known.first().cloned())
151 .unwrap_or_else(|| DEFAULT_COMPANY.to_owned())
152 }
153
154 /// Link en tekst voor een zoekresultaat. Alleen een BC-link uit Mímir als die
155 /// echt naar de webclient wijst; anders zelf opbouwen.
156 fn link_for(result: &SearchResult, fallback: CardKind) -> (String, String) {
157 let kind = CardKind::from_api_name(&result.kind).unwrap_or(fallback);
158 let url = if trusted_link(&result.bc_url) && parse_card_link(&result.bc_url).is_some() {
159 result.bc_url.clone()
160 } else {
161 bc_url(kind, &result.company, &result.no, None)
162 };
163 (url, anchor_text(kind, &result.no, Some(&result.title)))
164 }
165
166 impl Picker {
167 fn new(composer: WeakEntity<Composer>, window: &mut Window, cx: &mut Context<Self>) -> Self {
168 let search = cx.new(|cx| InputState::new(window, cx).placeholder(tr("kvt.picker.search")));
169 let subscription = cx.subscribe_in(&search, window, Self::on_search_event);
170 search.update(cx, |input, cx| input.focus(window, cx));
171 Picker {
172 composer,
173 kind: CardKind::Werkorder,
174 company: None,
175 search,
176 results: Vec::new(),
177 status: Status::TypeMore,
178 highlighted: 0,
179 generation: 0,
180 task: None,
181 _subscription: subscription,
182 }
183 }
184
185 fn on_search_event(
186 &mut self,
187 _: &Entity<InputState>,
188 event: &InputEvent,
189 window: &mut Window,
190 cx: &mut Context<Self>,
191 ) {
192 match event {
193 InputEvent::Change => self.run_search(cx),
194 InputEvent::PressEnter { .. } => self.choose(self.highlighted, window, cx),
195 _ => {}
196 }
197 }
198
199 fn run_search(&mut self, cx: &mut Context<Self>) {
200 self.generation += 1;
201 self.task = None;
202 self.highlighted = 0;
203 let query = self.search.read(cx).value().trim().to_owned();
204 if query.chars().count() < MIN_QUERY {
205 self.results.clear();
206 self.status = Status::TypeMore;
207 cx.notify();
208 return;
209 }
210 let kind = self.kind;
211 let company = effective_company(self.company.as_deref(), &companies(cx));
212 if is_demo(cx) {
213 self.results = super::demo::search(kind, &company, &query);
214 self.status = Status::Done;
215 cx.notify();
216 return;
217 }
218 let Some((token, client)) = token_and_client(cx) else {
219 cx.notify();
220 return;
221 };
222 self.status = Status::Searching;
223 let generation = self.generation;
224 self.task = Some(cx.spawn(async move |this, cx| {
225 cx.background_executor().timer(SEARCH_DEBOUNCE).await;
226 let searching =
227 runtime::spawn(async move { client.search(&token, kind, &company, &query).await });
228 let result = searching.await.unwrap_or(Err(ClientError::Unavailable));
229 this.update(cx, |this, cx| {
230 if this.generation != generation {
231 return;
232 }
233 match result {
234 Ok(results) => {
235 this.results = results.into_iter().take(MAX_ROWS).collect();
236 this.status = Status::Done;
237 }
238 Err(error) => {
239 if error == ClientError::Unauthorized {
240 forget_token(cx);
241 }
242 this.results.clear();
243 this.status = Status::Failed(error);
244 }
245 }
246 cx.notify();
247 })
248 .ok();
249 }));
250 cx.notify();
251 }
252
253 fn set_kind(&mut self, kind: CardKind, cx: &mut Context<Self>) {
254 if self.kind != kind {
255 self.kind = kind;
256 self.run_search(cx);
257 }
258 }
259
260 fn set_company(&mut self, company: String, cx: &mut Context<Self>) {
261 self.company = Some(company);
262 self.run_search(cx);
263 }
264
265 fn choose(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
266 let Some(result) = self.results.get(index) else {
267 return;
268 };
269 let (url, text) = link_for(result, self.kind);
270 let composer = self.composer.clone();
271 close_picker(cx);
272 composer
273 .update(cx, |composer, cx| {
274 composer.insert_kvt_link(&text, &url, window, cx)
275 })
276 .ok();
277 }
278
279 fn on_key_down(&mut self, event: &KeyDownEvent, _: &mut Window, cx: &mut Context<Self>) {
280 let count = self.results.len();
281 match event.keystroke.key.as_str() {
282 "escape" => close_picker(cx),
283 "down" if count > 0 => {
284 self.highlighted = (self.highlighted + 1).min(count - 1);
285 cx.notify();
286 }
287 "up" if count > 0 => {
288 self.highlighted = self.highlighted.saturating_sub(1);
289 cx.notify();
290 }
291 _ => {}
292 }
293 }
294
295 fn header(&self) -> Div {
296 h_flex()
297 .w_full()
298 .items_center()
299 .gap(px(SECTION_GAP))
300 .child(
301 div()
302 .flex_1()
303 .min_w_0()
304 .text_size(px(15.))
305 .font_weight(FontWeight::SEMIBOLD)
306 .child(tr("kvt.picker.title")),
307 )
308 .child(
309 div()
310 .id("kvt-picker-close")
311 .size(px(CLOSE_SIZE))
312 .flex_none()
313 .flex()
314 .items_center()
315 .justify_center()
316 .rounded_full()
317 .cursor_pointer()
318 .hover(|button| button.bg(theme::popup_hover()))
319 .on_click(|_, _, cx| close_picker(cx))
320 .child(symbol("close", 16., theme::text_muted())),
321 )
322 }
323
324 fn chip(id: SharedString, label: String, selected: bool) -> Stateful<Div> {
325 h_flex()
326 .id(id)
327 .h(px(CHIP_HEIGHT))
328 .flex_none()
329 .px(px(12.))
330 .gap(px(6.))
331 .items_center()
332 .rounded_full()
333 .text_size(px(13.))
334 .cursor_pointer()
335 .map(|chip| {
336 if selected {
337 chip.bg(theme::accent())
338 .text_color(theme::on_accent())
339 .font_weight(FontWeight::SEMIBOLD)
340 } else {
341 chip.bg(theme::popup_hover())
342 .text_color(theme::text())
343 .hover(|chip| chip.bg(theme::row_hover()))
344 }
345 })
346 .child(label)
347 }
348
349 fn kind_chips(&self, cx: &mut Context<Self>) -> Div {
350 h_flex()
351 .w_full()
352 .flex_wrap()
353 .gap(px(6.))
354 .children(CardKind::ALL.into_iter().map(|kind| {
355 Self::chip(
356 format!("kvt-picker-kind-{}", kind.api_name()).into(),
357 kind_label(kind),
358 kind == self.kind,
359 )
360 .on_click(cx.listener(move |this, _, _, cx| this.set_kind(kind, cx)))
361 }))
362 }
363
364 fn company_chips(&self, cx: &mut Context<Self>) -> Option<Div> {
365 let known = companies(cx);
366 if known.len() < 2 {
367 return None;
368 }
369 let selected = effective_company(self.company.as_deref(), &known);
370 Some(
371 h_flex()
372 .w_full()
373 .flex_wrap()
374 .gap(px(6.))
375 .children(known.into_iter().enumerate().map(|(index, company)| {
376 let chosen = company == selected;
377 let label = company.clone();
378 Self::chip(format!("kvt-picker-company-{index}").into(), label, chosen)
379 .on_click(
380 cx.listener(move |this, _, _, cx| {
381 this.set_company(company.clone(), cx)
382 }),
383 )
384 })),
385 )
386 }
387
388 fn field(&self) -> Div {
389 h_flex()
390 .w_full()
391 .h(px(FIELD_HEIGHT))
392 .flex_none()
393 .px(px(10.))
394 .gap(px(8.))
395 .items_center()
396 .rounded(px(6.))
397 .bg(theme::popup_hover())
398 .child(symbol("search", 14., theme::text_muted()))
399 .child(
400 div()
401 .flex_1()
402 .child(Input::new(&self.search).appearance(false).bordered(false)),
403 )
404 }
405
406 fn status_line(text: String) -> Div {
407 div()
408 .w_full()
409 .py(px(8.))
410 .text_size(px(13.))
411 .text_color(theme::text_muted())
412 .child(text)
413 }
414
415 fn list(&self, cx: &mut Context<Self>) -> AnyElement {
416 if !matches!(link(cx), Link::Linked(_)) {
417 return v_flex()
418 .w_full()
419 .gap(px(8.))
420 .child(Self::status_line(tr(
421 if matches!(link(cx), Link::Connecting) {
422 "kvt.settings.connecting"
423 } else {
424 "kvt.card.sign_in"
425 },
426 )))
427 .child(
428 Self::chip(
429 "kvt-picker-connect".into(),
430 tr("kvt.settings.connect"),
431 true,
432 )
433 .on_click(|_, _, cx| connect(cx)),
434 )
435 .into_any_element();
436 }
437 match &self.status {
438 Status::TypeMore => Self::status_line(tr("kvt.picker.type_more")).into_any_element(),
439 Status::Searching => Self::status_line(tr("kvt.card.loading")).into_any_element(),
440 Status::Failed(error) => Self::status_line(error_text(error)).into_any_element(),
441 Status::Done if self.results.is_empty() => {
442 Self::status_line(tr("kvt.picker.empty")).into_any_element()
443 }
444 Status::Done => {
445 let rows: Vec<AnyElement> = self
446 .results
447 .iter()
448 .enumerate()
449 .map(|(index, result)| self.row(index, result, cx))
450 .collect();
451 v_flex()
452 .id("kvt-picker-results")
453 .w_full()
454 .max_h(px(ROW_HEIGHT * 6.))
455 .overflow_y_scrollbar()
456 .children(rows)
457 .into_any_element()
458 }
459 }
460 }
461
462 fn row(&self, index: usize, result: &SearchResult, cx: &mut Context<Self>) -> AnyElement {
463 let kind = CardKind::from_api_name(&result.kind).unwrap_or(self.kind);
464 let subtitle = if result.subtitle.is_empty() {
465 result.no.clone()
466 } else {
467 format!("{} · {}", result.no, result.subtitle)
468 };
469 h_flex()
470 .id(ElementId::Name(format!("kvt-picker-result-{index}").into()))
471 .w_full()
472 .h(px(ROW_HEIGHT))
473 .flex_none()
474 .px(px(8.))
475 .gap(px(10.))
476 .items_center()
477 .rounded(px(6.))
478 .cursor_pointer()
479 .when(index == self.highlighted, |row| {
480 row.bg(theme::popup_hover())
481 })
482 .hover(|row| row.bg(theme::popup_hover()))
483 .child(symbol(kind_symbol(kind), 18., theme::accent_text()))
484 .child(
485 v_flex()
486 .flex_1()
487 .min_w_0()
488 .child(
489 div()
490 .truncate()
491 .text_size(px(13.))
492 .text_color(theme::text())
493 .child(if result.title.is_empty() {
494 result.no.clone()
495 } else {
496 result.title.clone()
497 }),
498 )
499 .child(
500 div()
501 .truncate()
502 .text_size(px(12.))
503 .text_color(theme::text_muted())
504 .child(subtitle),
505 ),
506 )
507 .on_click(cx.listener(move |this, _, window, cx| this.choose(index, window, cx)))
508 .into_any_element()
509 }
510 }
511
512 impl Render for Picker {
513 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
514 div()
515 .id("kvt-picker-layer")
516 .absolute()
517 .top_0()
518 .left_0()
519 .size_full()
520 .flex()
521 .items_center()
522 .justify_center()
523 .child(
524 div()
525 .id("kvt-picker-backdrop")
526 .absolute()
527 .top_0()
528 .left_0()
529 .size_full()
530 .bg(black().opacity(BACKDROP_OPACITY))
531 .occlude()
532 .on_click(|_, _, cx| close_picker(cx)),
533 )
534 .child(
535 v_flex()
536 .debug_selector(|| KVT_PICKER_TAG.into())
537 .w(px(PANEL_WIDTH))
538 .max_w(relative(1.))
539 .max_h(relative(1.))
540 .m(px(PANEL_MARGIN))
541 .p(px(PANEL_PADDING))
542 .gap(px(SECTION_GAP))
543 .rounded(px(PANEL_RADIUS))
544 .dialog_surface()
545 .text_color(theme::text())
546 .occlude()
547 .on_key_down(cx.listener(Self::on_key_down))
548 .child(self.header())
549 .child(self.kind_chips(cx))
550 .children(self.company_chips(cx))
551 .child(self.field())
552 .child(self.list(cx)),
553 )
554 }
555 }
556
557 #[cfg(test)]
558 mod tests {
559 use kvt_sleutels::links::bc_url;
560 use kvt_sleutels::{CardKind, SearchResult};
561
562 use super::{DEFAULT_COMPANY, effective_company, link_for};
563
564 #[test]
565 fn company_defaults_to_kvt_then_first_known() {
566 let known = vec!["KVT Germany".to_owned(), DEFAULT_COMPANY.to_owned()];
567 assert_eq!(effective_company(None, &known), DEFAULT_COMPANY);
568 assert_eq!(
569 effective_company(Some("KVT Germany"), &known),
570 "KVT Germany"
571 );
572 assert_eq!(
573 effective_company(None, &["Ander bedrijf".to_owned()]),
574 "Ander bedrijf"
575 );
576 assert_eq!(effective_company(None, &[]), DEFAULT_COMPANY);
577 }
578
579 #[test]
580 fn inserted_link_is_readable_and_never_points_elsewhere() {
581 let mut result = SearchResult {
582 kind: "werkorder".to_owned(),
583 company: "Testbedrijf".to_owned(),
584 no: "WO2699001".to_owned(),
585 title: "Onderhoud 500 uur".to_owned(),
586 subtitle: String::new(),
587 bc_url: "https://example.com/phish".to_owned(),
588 };
589 let (url, text) = link_for(&result, CardKind::Project);
590 assert_eq!(text, "Werkorder WO2699001 - Onderhoud 500 uur");
591 assert_eq!(
592 url,
593 bc_url(CardKind::Werkorder, "Testbedrijf", "WO2699001", None)
594 );
595 result.bc_url = bc_url(
596 CardKind::Werkorder,
597 "Testbedrijf",
598 "WO2699001",
599 Some("KVTGermanyLive_AAD"),
600 );
601 assert_eq!(link_for(&result, CardKind::Project).0, result.bc_url);
602 }
603 }
@@ -0,0 +1,603 @@
1//! Picker in het plusmenu van het opstelvak: project, werkorder of contract zoeken
2//! en als gewone link met leesbare tekst invoegen.
3
4use std::time::Duration;
5
6use gpui_kit::component::fluent::{
7 MENU_ICON_LABEL_GAP, MENU_ICON_SLOT, MENU_ITEM_HEIGHT, MENU_ITEM_PADDING_X,
8};
9use gpui_kit::component::input::{Input, InputEvent, InputState};
10use gpui_kit::component::scroll::ScrollableElement as _;
11use gpui_kit::component::{h_flex, v_flex};
12use gpui_kit::prelude::FluentBuilder as _;
13use gpui_kit::*;
14use kvt_sleutels::links::{anchor_text, bc_url};
15use kvt_sleutels::{CardKind, ClientError, SearchResult, parse_card_link};
16
17use super::{
18 DEFAULT_COMPANY, Link, connect, error_text, forget_token, is_demo, kind_label, kind_symbol,
19 link, read, token_and_client, trusted_link, update,
20};
21use crate::i18n::tr;
22use crate::runtime;
23use crate::theme::{self, ElevatedSurface as _};
24use crate::views::composer::Composer;
25use crate::views::widgets::symbol;
26
27pub const KVT_PICKER_TAG: &str = "kvt-picker";
28pub const KVT_PLUS_ITEM_TAG: &str = "composer-plus/kvt-link";
29const SEARCH_DEBOUNCE: Duration = Duration::from_millis(300);
30const MIN_QUERY: usize = 2;
31const BACKDROP_OPACITY: f32 = 0.55;
32const PANEL_WIDTH: f32 = 480.;
33const PANEL_MARGIN: f32 = 32.;
34const PANEL_RADIUS: f32 = 10.;
35const PANEL_PADDING: f32 = 16.;
36const SECTION_GAP: f32 = 12.;
37const CLOSE_SIZE: f32 = 28.;
38const FIELD_HEIGHT: f32 = 36.;
39const CHIP_HEIGHT: f32 = 28.;
40const ROW_HEIGHT: f32 = 44.;
41const MAX_ROWS: usize = 10;
42const ITEM_ICON_SIZE: f32 = 20.;
43
44#[derive(Clone, PartialEq, Eq)]
45enum Status {
46 TypeMore,
47 Searching,
48 Done,
49 Failed(ClientError),
50}
51
52pub struct Picker {
53 composer: WeakEntity<Composer>,
54 kind: CardKind,
55 company: Option<String>,
56 search: Entity<InputState>,
57 results: Vec<SearchResult>,
58 status: Status,
59 highlighted: usize,
60 generation: u64,
61 task: Option<Task<()>>,
62 _subscription: Subscription,
63}
64
65/// Regel in het plusmenu; `None` als de KVT-koppeling niet geladen is.
66pub fn plus_item(
67 on_click: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
68 cx: &App,
69) -> Option<Stateful<Div>> {
70 if !super::installed(cx) {
71 return None;
72 }
73 Some(
74 h_flex()
75 .id(KVT_PLUS_ITEM_TAG)
76 .debug_selector(|| KVT_PLUS_ITEM_TAG.into())
77 .w_full()
78 .h(MENU_ITEM_HEIGHT)
79 .flex_none()
80 .px(MENU_ITEM_PADDING_X)
81 .gap(MENU_ICON_LABEL_GAP)
82 .items_center()
83 .rounded(px(6.))
84 .cursor_pointer()
85 .hover(|row| row.bg(theme::popup_hover()))
86 .child(
87 div()
88 .size(MENU_ICON_SLOT)
89 .flex_none()
90 .flex()
91 .items_center()
92 .justify_center()
93 .child(symbol("link", ITEM_ICON_SIZE, theme::text_soft())),
94 )
95 .child(
96 div()
97 .text_size(px(13.))
98 .text_color(theme::text())
99 .child(tr("kvt.picker.menu")),
100 )
101 .on_click(on_click),
102 )
103}
104
105pub fn open_picker(composer: WeakEntity<Composer>, window: &mut Window, cx: &mut App) {
106 if !super::installed(cx) {
107 return;
108 }
109 let picker = cx.new(|cx| Picker::new(composer, window, cx));
110 update(cx, |kvt| kvt.picker = Some(picker));
111 ensure_companies(cx);
112}
113
114fn close_picker(cx: &mut App) {
115 update(cx, |kvt| kvt.picker = None);
116}
117
118/// Bedrijvenlijst eenmalig ophalen (alleen nodig voor de keuze in de picker).
119fn ensure_companies(cx: &mut App) {
120 let known = read(cx, |kvt| !kvt.companies.is_empty()).unwrap_or(true);
121 if known || is_demo(cx) {
122 return;
123 }
124 let Some((token, client)) = token_and_client(cx) else {
125 return;
126 };
127 let loading = runtime::spawn(async move { client.companies(&token).await });
128 cx.spawn(async move |cx| {
129 if let Ok(Ok(companies)) = loading.await {
130 cx.update(|cx| update(cx, |kvt| kvt.companies = companies));
131 }
132 })
133 .detach();
134}
135
136fn companies(cx: &App) -> Vec<String> {
137 read(cx, |kvt| kvt.companies.clone()).unwrap_or_default()
138}
139
140/// Het gekozen bedrijf, anders het eerste uit Mímir, anders KVT.
141fn effective_company(chosen: Option<&str>, known: &[String]) -> String {
142 chosen
143 .map(str::to_owned)
144 .or_else(|| {
145 known
146 .iter()
147 .find(|name| name.as_str() == DEFAULT_COMPANY)
148 .cloned()
149 })
150 .or_else(|| known.first().cloned())
151 .unwrap_or_else(|| DEFAULT_COMPANY.to_owned())
152}
153
154/// Link en tekst voor een zoekresultaat. Alleen een BC-link uit Mímir als die
155/// echt naar de webclient wijst; anders zelf opbouwen.
156fn link_for(result: &SearchResult, fallback: CardKind) -> (String, String) {
157 let kind = CardKind::from_api_name(&result.kind).unwrap_or(fallback);
158 let url = if trusted_link(&result.bc_url) && parse_card_link(&result.bc_url).is_some() {
159 result.bc_url.clone()
160 } else {
161 bc_url(kind, &result.company, &result.no, None)
162 };
163 (url, anchor_text(kind, &result.no, Some(&result.title)))
164}
165
166impl Picker {
167 fn new(composer: WeakEntity<Composer>, window: &mut Window, cx: &mut Context<Self>) -> Self {
168 let search = cx.new(|cx| InputState::new(window, cx).placeholder(tr("kvt.picker.search")));
169 let subscription = cx.subscribe_in(&search, window, Self::on_search_event);
170 search.update(cx, |input, cx| input.focus(window, cx));
171 Picker {
172 composer,
173 kind: CardKind::Werkorder,
174 company: None,
175 search,
176 results: Vec::new(),
177 status: Status::TypeMore,
178 highlighted: 0,
179 generation: 0,
180 task: None,
181 _subscription: subscription,
182 }
183 }
184
185 fn on_search_event(
186 &mut self,
187 _: &Entity<InputState>,
188 event: &InputEvent,
189 window: &mut Window,
190 cx: &mut Context<Self>,
191 ) {
192 match event {
193 InputEvent::Change => self.run_search(cx),
194 InputEvent::PressEnter { .. } => self.choose(self.highlighted, window, cx),
195 _ => {}
196 }
197 }
198
199 fn run_search(&mut self, cx: &mut Context<Self>) {
200 self.generation += 1;
201 self.task = None;
202 self.highlighted = 0;
203 let query = self.search.read(cx).value().trim().to_owned();
204 if query.chars().count() < MIN_QUERY {
205 self.results.clear();
206 self.status = Status::TypeMore;
207 cx.notify();
208 return;
209 }
210 let kind = self.kind;
211 let company = effective_company(self.company.as_deref(), &companies(cx));
212 if is_demo(cx) {
213 self.results = super::demo::search(kind, &company, &query);
214 self.status = Status::Done;
215 cx.notify();
216 return;
217 }
218 let Some((token, client)) = token_and_client(cx) else {
219 cx.notify();
220 return;
221 };
222 self.status = Status::Searching;
223 let generation = self.generation;
224 self.task = Some(cx.spawn(async move |this, cx| {
225 cx.background_executor().timer(SEARCH_DEBOUNCE).await;
226 let searching =
227 runtime::spawn(async move { client.search(&token, kind, &company, &query).await });
228 let result = searching.await.unwrap_or(Err(ClientError::Unavailable));
229 this.update(cx, |this, cx| {
230 if this.generation != generation {
231 return;
232 }
233 match result {
234 Ok(results) => {
235 this.results = results.into_iter().take(MAX_ROWS).collect();
236 this.status = Status::Done;
237 }
238 Err(error) => {
239 if error == ClientError::Unauthorized {
240 forget_token(cx);
241 }
242 this.results.clear();
243 this.status = Status::Failed(error);
244 }
245 }
246 cx.notify();
247 })
248 .ok();
249 }));
250 cx.notify();
251 }
252
253 fn set_kind(&mut self, kind: CardKind, cx: &mut Context<Self>) {
254 if self.kind != kind {
255 self.kind = kind;
256 self.run_search(cx);
257 }
258 }
259
260 fn set_company(&mut self, company: String, cx: &mut Context<Self>) {
261 self.company = Some(company);
262 self.run_search(cx);
263 }
264
265 fn choose(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
266 let Some(result) = self.results.get(index) else {
267 return;
268 };
269 let (url, text) = link_for(result, self.kind);
270 let composer = self.composer.clone();
271 close_picker(cx);
272 composer
273 .update(cx, |composer, cx| {
274 composer.insert_kvt_link(&text, &url, window, cx)
275 })
276 .ok();
277 }
278
279 fn on_key_down(&mut self, event: &KeyDownEvent, _: &mut Window, cx: &mut Context<Self>) {
280 let count = self.results.len();
281 match event.keystroke.key.as_str() {
282 "escape" => close_picker(cx),
283 "down" if count > 0 => {
284 self.highlighted = (self.highlighted + 1).min(count - 1);
285 cx.notify();
286 }
287 "up" if count > 0 => {
288 self.highlighted = self.highlighted.saturating_sub(1);
289 cx.notify();
290 }
291 _ => {}
292 }
293 }
294
295 fn header(&self) -> Div {
296 h_flex()
297 .w_full()
298 .items_center()
299 .gap(px(SECTION_GAP))
300 .child(
301 div()
302 .flex_1()
303 .min_w_0()
304 .text_size(px(15.))
305 .font_weight(FontWeight::SEMIBOLD)
306 .child(tr("kvt.picker.title")),
307 )
308 .child(
309 div()
310 .id("kvt-picker-close")
311 .size(px(CLOSE_SIZE))
312 .flex_none()
313 .flex()
314 .items_center()
315 .justify_center()
316 .rounded_full()
317 .cursor_pointer()
318 .hover(|button| button.bg(theme::popup_hover()))
319 .on_click(|_, _, cx| close_picker(cx))
320 .child(symbol("close", 16., theme::text_muted())),
321 )
322 }
323
324 fn chip(id: SharedString, label: String, selected: bool) -> Stateful<Div> {
325 h_flex()
326 .id(id)
327 .h(px(CHIP_HEIGHT))
328 .flex_none()
329 .px(px(12.))
330 .gap(px(6.))
331 .items_center()
332 .rounded_full()
333 .text_size(px(13.))
334 .cursor_pointer()
335 .map(|chip| {
336 if selected {
337 chip.bg(theme::accent())
338 .text_color(theme::on_accent())
339 .font_weight(FontWeight::SEMIBOLD)
340 } else {
341 chip.bg(theme::popup_hover())
342 .text_color(theme::text())
343 .hover(|chip| chip.bg(theme::row_hover()))
344 }
345 })
346 .child(label)
347 }
348
349 fn kind_chips(&self, cx: &mut Context<Self>) -> Div {
350 h_flex()
351 .w_full()
352 .flex_wrap()
353 .gap(px(6.))
354 .children(CardKind::ALL.into_iter().map(|kind| {
355 Self::chip(
356 format!("kvt-picker-kind-{}", kind.api_name()).into(),
357 kind_label(kind),
358 kind == self.kind,
359 )
360 .on_click(cx.listener(move |this, _, _, cx| this.set_kind(kind, cx)))
361 }))
362 }
363
364 fn company_chips(&self, cx: &mut Context<Self>) -> Option<Div> {
365 let known = companies(cx);
366 if known.len() < 2 {
367 return None;
368 }
369 let selected = effective_company(self.company.as_deref(), &known);
370 Some(
371 h_flex()
372 .w_full()
373 .flex_wrap()
374 .gap(px(6.))
375 .children(known.into_iter().enumerate().map(|(index, company)| {
376 let chosen = company == selected;
377 let label = company.clone();
378 Self::chip(format!("kvt-picker-company-{index}").into(), label, chosen)
379 .on_click(
380 cx.listener(move |this, _, _, cx| {
381 this.set_company(company.clone(), cx)
382 }),
383 )
384 })),
385 )
386 }
387
388 fn field(&self) -> Div {
389 h_flex()
390 .w_full()
391 .h(px(FIELD_HEIGHT))
392 .flex_none()
393 .px(px(10.))
394 .gap(px(8.))
395 .items_center()
396 .rounded(px(6.))
397 .bg(theme::popup_hover())
398 .child(symbol("search", 14., theme::text_muted()))
399 .child(
400 div()
401 .flex_1()
402 .child(Input::new(&self.search).appearance(false).bordered(false)),
403 )
404 }
405
406 fn status_line(text: String) -> Div {
407 div()
408 .w_full()
409 .py(px(8.))
410 .text_size(px(13.))
411 .text_color(theme::text_muted())
412 .child(text)
413 }
414
415 fn list(&self, cx: &mut Context<Self>) -> AnyElement {
416 if !matches!(link(cx), Link::Linked(_)) {
417 return v_flex()
418 .w_full()
419 .gap(px(8.))
420 .child(Self::status_line(tr(
421 if matches!(link(cx), Link::Connecting) {
422 "kvt.settings.connecting"
423 } else {
424 "kvt.card.sign_in"
425 },
426 )))
427 .child(
428 Self::chip(
429 "kvt-picker-connect".into(),
430 tr("kvt.settings.connect"),
431 true,
432 )
433 .on_click(|_, _, cx| connect(cx)),
434 )
435 .into_any_element();
436 }
437 match &self.status {
438 Status::TypeMore => Self::status_line(tr("kvt.picker.type_more")).into_any_element(),
439 Status::Searching => Self::status_line(tr("kvt.card.loading")).into_any_element(),
440 Status::Failed(error) => Self::status_line(error_text(error)).into_any_element(),
441 Status::Done if self.results.is_empty() => {
442 Self::status_line(tr("kvt.picker.empty")).into_any_element()
443 }
444 Status::Done => {
445 let rows: Vec<AnyElement> = self
446 .results
447 .iter()
448 .enumerate()
449 .map(|(index, result)| self.row(index, result, cx))
450 .collect();
451 v_flex()
452 .id("kvt-picker-results")
453 .w_full()
454 .max_h(px(ROW_HEIGHT * 6.))
455 .overflow_y_scrollbar()
456 .children(rows)
457 .into_any_element()
458 }
459 }
460 }
461
462 fn row(&self, index: usize, result: &SearchResult, cx: &mut Context<Self>) -> AnyElement {
463 let kind = CardKind::from_api_name(&result.kind).unwrap_or(self.kind);
464 let subtitle = if result.subtitle.is_empty() {
465 result.no.clone()
466 } else {
467 format!("{} · {}", result.no, result.subtitle)
468 };
469 h_flex()
470 .id(ElementId::Name(format!("kvt-picker-result-{index}").into()))
471 .w_full()
472 .h(px(ROW_HEIGHT))
473 .flex_none()
474 .px(px(8.))
475 .gap(px(10.))
476 .items_center()
477 .rounded(px(6.))
478 .cursor_pointer()
479 .when(index == self.highlighted, |row| {
480 row.bg(theme::popup_hover())
481 })
482 .hover(|row| row.bg(theme::popup_hover()))
483 .child(symbol(kind_symbol(kind), 18., theme::accent_text()))
484 .child(
485 v_flex()
486 .flex_1()
487 .min_w_0()
488 .child(
489 div()
490 .truncate()
491 .text_size(px(13.))
492 .text_color(theme::text())
493 .child(if result.title.is_empty() {
494 result.no.clone()
495 } else {
496 result.title.clone()
497 }),
498 )
499 .child(
500 div()
501 .truncate()
502 .text_size(px(12.))
503 .text_color(theme::text_muted())
504 .child(subtitle),
505 ),
506 )
507 .on_click(cx.listener(move |this, _, window, cx| this.choose(index, window, cx)))
508 .into_any_element()
509 }
510}
511
512impl Render for Picker {
513 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
514 div()
515 .id("kvt-picker-layer")
516 .absolute()
517 .top_0()
518 .left_0()
519 .size_full()
520 .flex()
521 .items_center()
522 .justify_center()
523 .child(
524 div()
525 .id("kvt-picker-backdrop")
526 .absolute()
527 .top_0()
528 .left_0()
529 .size_full()
530 .bg(black().opacity(BACKDROP_OPACITY))
531 .occlude()
532 .on_click(|_, _, cx| close_picker(cx)),
533 )
534 .child(
535 v_flex()
536 .debug_selector(|| KVT_PICKER_TAG.into())
537 .w(px(PANEL_WIDTH))
538 .max_w(relative(1.))
539 .max_h(relative(1.))
540 .m(px(PANEL_MARGIN))
541 .p(px(PANEL_PADDING))
542 .gap(px(SECTION_GAP))
543 .rounded(px(PANEL_RADIUS))
544 .dialog_surface()
545 .text_color(theme::text())
546 .occlude()
547 .on_key_down(cx.listener(Self::on_key_down))
548 .child(self.header())
549 .child(self.kind_chips(cx))
550 .children(self.company_chips(cx))
551 .child(self.field())
552 .child(self.list(cx)),
553 )
554 }
555}
556
557#[cfg(test)]
558mod tests {
559 use kvt_sleutels::links::bc_url;
560 use kvt_sleutels::{CardKind, SearchResult};
561
562 use super::{DEFAULT_COMPANY, effective_company, link_for};
563
564 #[test]
565 fn company_defaults_to_kvt_then_first_known() {
566 let known = vec!["KVT Germany".to_owned(), DEFAULT_COMPANY.to_owned()];
567 assert_eq!(effective_company(None, &known), DEFAULT_COMPANY);
568 assert_eq!(
569 effective_company(Some("KVT Germany"), &known),
570 "KVT Germany"
571 );
572 assert_eq!(
573 effective_company(None, &["Ander bedrijf".to_owned()]),
574 "Ander bedrijf"
575 );
576 assert_eq!(effective_company(None, &[]), DEFAULT_COMPANY);
577 }
578
579 #[test]
580 fn inserted_link_is_readable_and_never_points_elsewhere() {
581 let mut result = SearchResult {
582 kind: "werkorder".to_owned(),
583 company: "Testbedrijf".to_owned(),
584 no: "WO2699001".to_owned(),
585 title: "Onderhoud 500 uur".to_owned(),
586 subtitle: String::new(),
587 bc_url: "https://example.com/phish".to_owned(),
588 };
589 let (url, text) = link_for(&result, CardKind::Project);
590 assert_eq!(text, "Werkorder WO2699001 - Onderhoud 500 uur");
591 assert_eq!(
592 url,
593 bc_url(CardKind::Werkorder, "Testbedrijf", "WO2699001", None)
594 );
595 result.bc_url = bc_url(
596 CardKind::Werkorder,
597 "Testbedrijf",
598 "WO2699001",
599 Some("KVTGermanyLive_AAD"),
600 );
601 assert_eq!(link_for(&result, CardKind::Project).0, result.bc_url);
602 }
603}
crates/app/src/kvt/session.rs added +57 −0
@@ -0,0 +1,57 @@
1 //! De sessiebrowser van rusty-teams als [`SessionTabs`] voor het koppelen
2 //! (Linux/macOS: de beheerde Chrome/Firefox uit ADR 0003). Op Windows kan de
3 //! WebView2-host nog geen los tabblad openen; daar blijft de systeembrowser.
4
5 use std::sync::Arc;
6
7 use kvt_sleutels::session::SessionTabs;
8
9 #[cfg(any(target_os = "linux", target_os = "macos"))]
10 mod managed {
11 use kvt_sleutels::session::{BoxFuture, SessionTabs};
12 use serde_json::Value;
13
14 pub(super) struct ManagedTabs(pub(super) browser::Browser);
15
16 impl SessionTabs for ManagedTabs {
17 fn open<'a>(&'a self, url: &'a str) -> BoxFuture<'a, Result<String, String>> {
18 Box::pin(async move {
19 self.0
20 .kvt_open_tab(url)
21 .await
22 .map_err(|error| error.to_string())
23 })
24 }
25
26 fn evaluate<'a>(
27 &'a self,
28 tab: &'a str,
29 expression: &'a str,
30 ) -> BoxFuture<'a, Result<Value, String>> {
31 Box::pin(async move {
32 self.0
33 .kvt_evaluate(tab, expression)
34 .await
35 .map_err(|error| error.to_string())
36 })
37 }
38
39 fn close<'a>(&'a self, tab: &'a str) -> BoxFuture<'a, ()> {
40 Box::pin(async move {
41 let _ = self.0.kvt_close_tab(tab).await;
42 })
43 }
44 }
45 }
46
47 pub(super) fn session_tabs() -> Option<Arc<dyn SessionTabs>> {
48 #[cfg(any(target_os = "linux", target_os = "macos"))]
49 {
50 crate::linux_browser::managed()
51 .map(|browser| Arc::new(managed::ManagedTabs(browser)) as Arc<dyn SessionTabs>)
52 }
53 #[cfg(not(any(target_os = "linux", target_os = "macos")))]
54 {
55 None
56 }
57 }
@@ -0,0 +1,57 @@
1//! De sessiebrowser van rusty-teams als [`SessionTabs`] voor het koppelen
2//! (Linux/macOS: de beheerde Chrome/Firefox uit ADR 0003). Op Windows kan de
3//! WebView2-host nog geen los tabblad openen; daar blijft de systeembrowser.
4
5use std::sync::Arc;
6
7use kvt_sleutels::session::SessionTabs;
8
9#[cfg(any(target_os = "linux", target_os = "macos"))]
10mod managed {
11 use kvt_sleutels::session::{BoxFuture, SessionTabs};
12 use serde_json::Value;
13
14 pub(super) struct ManagedTabs(pub(super) browser::Browser);
15
16 impl SessionTabs for ManagedTabs {
17 fn open<'a>(&'a self, url: &'a str) -> BoxFuture<'a, Result<String, String>> {
18 Box::pin(async move {
19 self.0
20 .kvt_open_tab(url)
21 .await
22 .map_err(|error| error.to_string())
23 })
24 }
25
26 fn evaluate<'a>(
27 &'a self,
28 tab: &'a str,
29 expression: &'a str,
30 ) -> BoxFuture<'a, Result<Value, String>> {
31 Box::pin(async move {
32 self.0
33 .kvt_evaluate(tab, expression)
34 .await
35 .map_err(|error| error.to_string())
36 })
37 }
38
39 fn close<'a>(&'a self, tab: &'a str) -> BoxFuture<'a, ()> {
40 Box::pin(async move {
41 let _ = self.0.kvt_close_tab(tab).await;
42 })
43 }
44 }
45}
46
47pub(super) fn session_tabs() -> Option<Arc<dyn SessionTabs>> {
48 #[cfg(any(target_os = "linux", target_os = "macos"))]
49 {
50 crate::linux_browser::managed()
51 .map(|browser| Arc::new(managed::ManagedTabs(browser)) as Arc<dyn SessionTabs>)
52 }
53 #[cfg(not(any(target_os = "linux", target_os = "macos")))]
54 {
55 None
56 }
57}
crates/app/src/linux_browser.rs +5 −0
@@ -227,6 +227,11 @@ async fn hide_after_login(browser: browser::Browser, headless_notify: Arc<Notify
227 227 }
228 228 }
229 229
230 /// KVT-fork: the managed session browser, for the sleutels.kvt.nl sign-in (`crate::kvt`).
231 pub(crate) fn managed() -> Option<browser::Browser> {
232 LINUX_BROWSER.get().cloned()
233 }
234
230 235 pub fn start(endpoint: &str) -> Arc<dyn session::Transport> {
231 236 let browser = match browser::Browser::detect() {
232 237 Ok(browser) => browser,
@@ -227,6 +227,11 @@ async fn hide_after_login(browser: browser::Browser, headless_notify: Arc<Notify
227 }
227 }
228}
228}
229
229
230/// KVT-fork: the managed session browser, for the sleutels.kvt.nl sign-in (`crate::kvt`).
231pub(crate) fn managed() -> Option<browser::Browser> {
232 LINUX_BROWSER.get().cloned()
233}
234
230pub fn start(endpoint: &str) -> Arc<dyn session::Transport> {
235pub fn start(endpoint: &str) -> Arc<dyn session::Transport> {
231 let browser = match browser::Browser::detect() {
236 let browser = match browser::Browser::detect() {
232 Ok(browser) => browser,
237 Ok(browser) => browser,
crates/app/src/main.rs +1 −0
@@ -10,6 +10,7 @@ pub mod agents;
10 10 pub mod call;
11 11 mod i18n;
12 12 mod inline_video;
13 mod kvt;
13 14 #[cfg(test)]
14 15 mod layout_guard;
15 16 #[cfg(any(target_os = "linux", target_os = "macos"))]
@@ -10,6 +10,7 @@ pub mod agents;
10pub mod call;
10pub mod call;
11mod i18n;
11mod i18n;
12mod inline_video;
12mod inline_video;
13mod kvt;
13#[cfg(test)]
14#[cfg(test)]
14mod layout_guard;
15mod layout_guard;
15#[cfg(any(target_os = "linux", target_os = "macos"))]
16#[cfg(any(target_os = "linux", target_os = "macos"))]
crates/app/src/settings/general.rs +1 −0
@@ -87,6 +87,7 @@ pub fn render(center: &Entity<NotificationCenter>, app: &Entity<AppState>, cx: &
87 87 .children(external_browser_rows(app, cx))
88 88 .children(install_rows(cx))
89 89 .children(update_rows(cx))
90 .children(super::kvt::settings_rows(cx))
90 91 .child(caption(tr("settings.caption.compose_box")))
91 92 .child(account_select(
92 93 app,
@@ -87,6 +87,7 @@ pub fn render(center: &Entity<NotificationCenter>, app: &Entity<AppState>, cx: &
87 .children(external_browser_rows(app, cx))
87 .children(external_browser_rows(app, cx))
88 .children(install_rows(cx))
88 .children(install_rows(cx))
89 .children(update_rows(cx))
89 .children(update_rows(cx))
90 .children(super::kvt::settings_rows(cx))
90 .child(caption(tr("settings.caption.compose_box")))
91 .child(caption(tr("settings.caption.compose_box")))
91 .child(account_select(
92 .child(account_select(
92 app,
93 app,
crates/app/src/settings/kvt.rs added +38 −0
@@ -0,0 +1,38 @@
1 //! KVT-fork. Instellingen > Algemeen: koppelen met sleutels.kvt.nl (zie `crate::kvt`).
2
3 use gpui_kit::*;
4
5 use super::rows::{caption, control_row, text_button};
6 use crate::i18n::{tr, tr_args};
7 use crate::kvt::{Link, cancel_connect, connect, disconnect, link};
8
9 pub fn settings_rows(cx: &App) -> Vec<AnyElement> {
10 if !crate::kvt::installed(cx) {
11 return Vec::new();
12 }
13 let (detail, button) = match link(cx) {
14 Link::Linked(stored) => {
15 let mut args = std::collections::HashMap::new();
16 args.insert("email".to_owned(), stored.email.clone());
17 (
18 tr_args("kvt.settings.linked", &args),
19 text_button("settings-kvt-disconnect", tr("kvt.settings.disconnect"))
20 .on_click(|_, _, cx| disconnect(cx)),
21 )
22 }
23 Link::Connecting => (
24 tr("kvt.settings.connecting"),
25 text_button("settings-kvt-cancel", tr("common.cancel"))
26 .on_click(|_, _, cx| cancel_connect(cx)),
27 ),
28 Link::NotLinked | Link::Unknown => (
29 tr("kvt.settings.detail"),
30 text_button("settings-kvt-connect", tr("kvt.settings.connect"))
31 .on_click(|_, _, cx| connect(cx)),
32 ),
33 };
34 vec![
35 caption(tr("kvt.settings.caption")).into_any_element(),
36 control_row(tr("kvt.settings.title"), detail, button).into_any_element(),
37 ]
38 }
@@ -0,0 +1,38 @@
1//! KVT-fork. Instellingen > Algemeen: koppelen met sleutels.kvt.nl (zie `crate::kvt`).
2
3use gpui_kit::*;
4
5use super::rows::{caption, control_row, text_button};
6use crate::i18n::{tr, tr_args};
7use crate::kvt::{Link, cancel_connect, connect, disconnect, link};
8
9pub fn settings_rows(cx: &App) -> Vec<AnyElement> {
10 if !crate::kvt::installed(cx) {
11 return Vec::new();
12 }
13 let (detail, button) = match link(cx) {
14 Link::Linked(stored) => {
15 let mut args = std::collections::HashMap::new();
16 args.insert("email".to_owned(), stored.email.clone());
17 (
18 tr_args("kvt.settings.linked", &args),
19 text_button("settings-kvt-disconnect", tr("kvt.settings.disconnect"))
20 .on_click(|_, _, cx| disconnect(cx)),
21 )
22 }
23 Link::Connecting => (
24 tr("kvt.settings.connecting"),
25 text_button("settings-kvt-cancel", tr("common.cancel"))
26 .on_click(|_, _, cx| cancel_connect(cx)),
27 ),
28 Link::NotLinked | Link::Unknown => (
29 tr("kvt.settings.detail"),
30 text_button("settings-kvt-connect", tr("kvt.settings.connect"))
31 .on_click(|_, _, cx| connect(cx)),
32 ),
33 };
34 vec![
35 caption(tr("kvt.settings.caption")).into_any_element(),
36 control_row(tr("kvt.settings.title"), detail, button).into_any_element(),
37 ]
38}
crates/app/src/settings/mod.rs +1 −0
@@ -9,6 +9,7 @@ mod devices;
9 9 mod dialog;
10 10 mod general;
11 11 mod help;
12 mod kvt;
12 13 mod mcp;
13 14 mod nav;
14 15 mod notifications;
@@ -9,6 +9,7 @@ mod devices;
9mod dialog;
9mod dialog;
10mod general;
10mod general;
11mod help;
11mod help;
12mod kvt;
12mod mcp;
13mod mcp;
13mod nav;
14mod nav;
14mod notifications;
15mod notifications;
crates/app/src/views/composer.rs +1 −0
@@ -36,6 +36,7 @@ mod cloud_picker;
36 36 pub(crate) mod delivery;
37 37 mod drafts;
38 38 mod format_menus;
39 mod kvt;
39 40 pub(crate) mod plus_menu;
40 41 mod post;
41 42 mod rewrite;
@@ -36,6 +36,7 @@ mod cloud_picker;
36pub(crate) mod delivery;
36pub(crate) mod delivery;
37mod drafts;
37mod drafts;
38mod format_menus;
38mod format_menus;
39mod kvt;
39pub(crate) mod plus_menu;
40pub(crate) mod plus_menu;
40mod post;
41mod post;
41mod rewrite;
42mod rewrite;
crates/app/src/views/composer/kvt.rs added +22 −0
@@ -0,0 +1,22 @@
1 //! KVT-fork: een BC-link uit de picker invoegen (zie `crate::kvt`).
2
3 use gpui_kit::*;
4
5 use super::Composer;
6
7 impl Composer {
8 /// Voegt `text` als link naar `url` in op de cursor (vervangt een selectie niet).
9 pub(crate) fn insert_kvt_link(
10 &mut self,
11 text: &str,
12 url: &str,
13 window: &mut Window,
14 cx: &mut Context<Self>,
15 ) {
16 let cursor = self.selection(cx).end;
17 let end = self.draft.insert_link(cursor, text, url);
18 self.commit(Some(end), window, cx);
19 self.focus(window, cx);
20 cx.notify();
21 }
22 }
@@ -0,0 +1,22 @@
1//! KVT-fork: een BC-link uit de picker invoegen (zie `crate::kvt`).
2
3use gpui_kit::*;
4
5use super::Composer;
6
7impl Composer {
8 /// Voegt `text` als link naar `url` in op de cursor (vervangt een selectie niet).
9 pub(crate) fn insert_kvt_link(
10 &mut self,
11 text: &str,
12 url: &str,
13 window: &mut Window,
14 cx: &mut Context<Self>,
15 ) {
16 let cursor = self.selection(cx).end;
17 let end = self.draft.insert_link(cursor, text, url);
18 self.commit(Some(end), window, cx);
19 self.focus(window, cx);
20 cx.notify();
21 }
22}
crates/app/src/views/composer/plus_menu.rs +8 −0
@@ -130,6 +130,14 @@ impl Composer {
130 130 cx.notify();
131 131 }))
132 132 .children(rows)
133 .children(crate::kvt::plus_item(
134 cx.listener(|this, _, window, cx| {
135 this.plus_menu = false;
136 crate::kvt::open_picker(cx.entity().downgrade(), window, cx);
137 cx.notify();
138 }),
139 cx,
140 ))
133 141 .into_any_element(),
134 142 )
135 143 }
@@ -130,6 +130,14 @@ impl Composer {
130 cx.notify();
130 cx.notify();
131 }))
131 }))
132 .children(rows)
132 .children(rows)
133 .children(crate::kvt::plus_item(
134 cx.listener(|this, _, window, cx| {
135 this.plus_menu = false;
136 crate::kvt::open_picker(cx.entity().downgrade(), window, cx);
137 cx.notify();
138 }),
139 cx,
140 ))
133 .into_any_element(),
141 .into_any_element(),
134 )
142 )
135 }
143 }
crates/app/src/views/message_row.rs +4 −1
@@ -325,10 +325,12 @@ fn bubble(
325 325 extras.open_image.as_ref(),
326 326 );
327 327 let cards = cards_view(&row.adaptive_cards, &row.conversation_id, &row.key, cx);
328 let kvt_cards = crate::kvt::message_cards(&row.blocks, &format!("message-{index}"), cx);
328 329 let trailing_content = attachments.is_some()
329 330 || row.meeting_link.is_some()
330 331 || row.link_preview.is_some()
331 || !cards.is_empty();
332 || !cards.is_empty()
333 || !kvt_cards.is_empty();
332 334 let padded_blocks = if has_reactions || trailing_content || jumbo.is_some() {
333 335 None
334 336 } else {
@@ -365,6 +367,7 @@ fn bubble(
365 367 None,
366 368 )
367 369 }));
370 content = content.children(kvt_cards);
368 371 content = content.children(cards);
369 372 if has_reactions {
370 373 let pills = reaction_pills(
@@ -325,10 +325,12 @@ fn bubble(
325 extras.open_image.as_ref(),
325 extras.open_image.as_ref(),
326 );
326 );
327 let cards = cards_view(&row.adaptive_cards, &row.conversation_id, &row.key, cx);
327 let cards = cards_view(&row.adaptive_cards, &row.conversation_id, &row.key, cx);
328 let kvt_cards = crate::kvt::message_cards(&row.blocks, &format!("message-{index}"), cx);
328 let trailing_content = attachments.is_some()
329 let trailing_content = attachments.is_some()
329 || row.meeting_link.is_some()
330 || row.meeting_link.is_some()
330 || row.link_preview.is_some()
331 || row.link_preview.is_some()
331 || !cards.is_empty();
332 || !cards.is_empty()
333 || !kvt_cards.is_empty();
332 let padded_blocks = if has_reactions || trailing_content || jumbo.is_some() {
334 let padded_blocks = if has_reactions || trailing_content || jumbo.is_some() {
333 None
335 None
334 } else {
336 } else {
@@ -365,6 +367,7 @@ fn bubble(
365 None,
367 None,
366 )
368 )
367 }));
369 }));
370 content = content.children(kvt_cards);
368 content = content.children(cards);
371 content = content.children(cards);
369 if has_reactions {
372 if has_reactions {
370 let pills = reaction_pills(
373 let pills = reaction_pills(
crates/app/src/views/post_card.rs +5 −0
@@ -151,6 +151,11 @@ fn message_content(
151 151 None,
152 152 )
153 153 }));
154 content = content.children(crate::kvt::message_cards(
155 &row.blocks,
156 &format!("message-{index}"),
157 cx,
158 ));
154 159 content = content.children(cards_view(
155 160 &row.adaptive_cards,
156 161 &row.conversation_id,
@@ -151,6 +151,11 @@ fn message_content(
151 None,
151 None,
152 )
152 )
153 }));
153 }));
154 content = content.children(crate::kvt::message_cards(
155 &row.blocks,
156 &format!("message-{index}"),
157 cx,
158 ));
154 content = content.children(cards_view(
159 content = content.children(cards_view(
155 &row.adaptive_cards,
160 &row.adaptive_cards,
156 &row.conversation_id,
161 &row.conversation_id,
crates/app/src/views/shell.rs +3 −0
@@ -98,6 +98,7 @@ pub fn install_globals(state: &Entity<AppState>, user_input: Arc<UserInput>, cx:
98 98 inline_image,
99 99 open_link,
100 100 });
101 crate::kvt::install(state.read(cx).mode.demo, cx);
101 102 }
102 103
103 104 fn open_link(url: &str, cx: &mut App) {
@@ -1067,6 +1068,7 @@ impl Render for AppShell {
1067 1068 self.shortcuts_dialog.is_some(),
1068 1069 self.agent_dialog.is_some(),
1069 1070 self.settings_dialog.is_some(),
1071 crate::kvt::dialog_open(cx),
1070 1072 ]
1071 1073 .into_iter()
1072 1074 .filter(|open| *open)
@@ -1384,6 +1386,7 @@ impl Render for AppShell {
1384 1386 .children(self.agent_dialog.clone())
1385 1387 .children(self.settings_dialog.clone())
1386 1388 .children(self.profile_card.clone())
1389 .children(crate::kvt::overlay(cx))
1387 1390 .child(crate::frame_log::probe("last"))
1388 1391 }
1389 1392 }
@@ -98,6 +98,7 @@ pub fn install_globals(state: &Entity<AppState>, user_input: Arc<UserInput>, cx:
98 inline_image,
98 inline_image,
99 open_link,
99 open_link,
100 });
100 });
101 crate::kvt::install(state.read(cx).mode.demo, cx);
101}
102}
102
103
103fn open_link(url: &str, cx: &mut App) {
104fn open_link(url: &str, cx: &mut App) {
@@ -1067,6 +1068,7 @@ impl Render for AppShell {
1067 self.shortcuts_dialog.is_some(),
1068 self.shortcuts_dialog.is_some(),
1068 self.agent_dialog.is_some(),
1069 self.agent_dialog.is_some(),
1069 self.settings_dialog.is_some(),
1070 self.settings_dialog.is_some(),
1071 crate::kvt::dialog_open(cx),
1070 ]
1072 ]
1071 .into_iter()
1073 .into_iter()
1072 .filter(|open| *open)
1074 .filter(|open| *open)
@@ -1384,6 +1386,7 @@ impl Render for AppShell {
1384 .children(self.agent_dialog.clone())
1386 .children(self.agent_dialog.clone())
1385 .children(self.settings_dialog.clone())
1387 .children(self.settings_dialog.clone())
1386 .children(self.profile_card.clone())
1388 .children(self.profile_card.clone())
1389 .children(crate::kvt::overlay(cx))
1387 .child(crate::frame_log::probe("last"))
1390 .child(crate::frame_log::probe("last"))
1388 }
1391 }
1389}
1392}
crates/browser/src/browser.rs +3 −0
@@ -19,6 +19,9 @@ const HTTP_TIMEOUT: Duration = Duration::from_secs(5);
19 19 const OPEN_TAB_TIMEOUT: Duration = Duration::from_secs(10);
20 20 const CDP_TIMEOUT: Duration = Duration::from_secs(5);
21 21
22 // KVT-fork: extra tab for a KVT web sign-in (see browser/kvt.rs).
23 mod kvt;
24
22 25 #[derive(Debug, Clone, Serialize)]
23 26 pub struct Status {
24 27 pub running: bool,
@@ -19,6 +19,9 @@ const HTTP_TIMEOUT: Duration = Duration::from_secs(5);
19const OPEN_TAB_TIMEOUT: Duration = Duration::from_secs(10);
19const OPEN_TAB_TIMEOUT: Duration = Duration::from_secs(10);
20const CDP_TIMEOUT: Duration = Duration::from_secs(5);
20const CDP_TIMEOUT: Duration = Duration::from_secs(5);
21
21
22// KVT-fork: extra tab for a KVT web sign-in (see browser/kvt.rs).
23mod kvt;
24
22#[derive(Debug, Clone, Serialize)]
25#[derive(Debug, Clone, Serialize)]
23pub struct Status {
26pub struct Status {
24 pub running: bool,
27 pub running: bool,
crates/browser/src/browser/kvt.rs added +112 −0
@@ -0,0 +1,112 @@
1 //! KVT-fork: a short-lived extra tab in the managed session browser, so a KVT
2 //! web sign-in (sleutels.kvt.nl) can reuse the Microsoft session of the profile
3 //! instead of asking again in the system browser. The tab is not an app tab:
4 //! `ensure_tabs`, parking and duplicate cleanup leave it alone, and the caller
5 //! closes it. See `KVT-FORK.md`.
6
7 use serde_json::{Value, json};
8
9 use super::{Browser, CDP_TIMEOUT, OPEN_TAB_TIMEOUT, cdp_call};
10 use crate::error::BrowserError;
11 use crate::http;
12
13 /// Chrome unescapes the query of `/json/new?<url>` once, so the whole URL is escaped.
14 fn escape_all(url: &str) -> String {
15 let mut out = String::with_capacity(url.len() * 3);
16 for byte in url.bytes() {
17 if byte.is_ascii_alphanumeric() {
18 out.push(byte as char);
19 } else {
20 out.push_str(&format!("%{byte:02X}"));
21 }
22 }
23 out
24 }
25
26 impl Browser {
27 /// Opens `url` in a new tab of the running managed browser; returns the tab id.
28 pub async fn kvt_open_tab(&self, url: &str) -> Result<String, BrowserError> {
29 if !self.is_running().await {
30 return Err(BrowserError::NoBrowser(self.inner.config.port.to_string()));
31 }
32 if let Some(bidi) = &self.inner.bidi {
33 let open = async {
34 let created = bidi
35 .call(
36 "browsingContext.create",
37 json!({"type": "tab", "background": true}),
38 )
39 .await?;
40 let context = created["context"].as_str().unwrap_or_default().to_owned();
41 if context.is_empty() {
42 return Err(BrowserError::Cdp(
43 "browsingContext.create: no context".into(),
44 ));
45 }
46 bidi.navigate(&context, url).await?;
47 Ok(context)
48 };
49 return tokio::time::timeout(OPEN_TAB_TIMEOUT, open)
50 .await
51 .map_err(|_| BrowserError::Cdp("opening the KVT tab timed out".into()))?;
52 }
53 let path = format!("/json/new?{}", escape_all(url));
54 let response =
55 http::request(self.inner.config.port, "PUT", &path, OPEN_TAB_TIMEOUT).await?;
56 if response.status != 200 {
57 return Err(BrowserError::Http(format!(
58 "PUT /json/new returned {}",
59 response.status
60 )));
61 }
62 let created: Value = serde_json::from_slice(&response.body)
63 .map_err(|error| BrowserError::Parse(format!("/json/new: {error}")))?;
64 created["id"]
65 .as_str()
66 .filter(|id| !id.is_empty())
67 .map(str::to_owned)
68 .ok_or_else(|| BrowserError::Parse("/json/new: no id".into()))
69 }
70
71 /// Evaluates `expression` in the tab and returns its JSON value.
72 pub async fn kvt_evaluate(&self, tab: &str, expression: &str) -> Result<Value, BrowserError> {
73 if let Some(bidi) = &self.inner.bidi {
74 return tokio::time::timeout(CDP_TIMEOUT, bidi.evaluate(tab, expression))
75 .await
76 .map_err(|_| BrowserError::Cdp("script.evaluate timed out".into()))?;
77 }
78 let url = format!(
79 "ws://127.0.0.1:{}/devtools/page/{tab}",
80 self.inner.config.port
81 );
82 let params = json!({ "expression": expression, "returnByValue": true });
83 let result = cdp_call(&url, "Runtime.evaluate", params, CDP_TIMEOUT).await?;
84 Ok(result["result"]["value"].clone())
85 }
86
87 /// Closes a tab opened with [`Browser::kvt_open_tab`]. Errors are ignored by callers.
88 pub async fn kvt_close_tab(&self, tab: &str) -> Result<(), BrowserError> {
89 if let Some(bidi) = &self.inner.bidi {
90 return tokio::time::timeout(CDP_TIMEOUT, bidi.close_tab(tab))
91 .await
92 .map_err(|_| BrowserError::Cdp("browsingContext.close timed out".into()))?;
93 }
94 let path = format!("/json/close/{tab}");
95 http::request(self.inner.config.port, "GET", &path, CDP_TIMEOUT)
96 .await
97 .map(drop)
98 }
99 }
100
101 #[cfg(test)]
102 mod tests {
103 use super::escape_all;
104
105 #[test]
106 fn escapes_the_whole_url_once() {
107 assert_eq!(
108 escape_all("https://a.b/c?x=1&y=%20"),
109 "https%3A%2F%2Fa%2Eb%2Fc%3Fx%3D1%26y%3D%2520"
110 );
111 }
112 }
@@ -0,0 +1,112 @@
1//! KVT-fork: a short-lived extra tab in the managed session browser, so a KVT
2//! web sign-in (sleutels.kvt.nl) can reuse the Microsoft session of the profile
3//! instead of asking again in the system browser. The tab is not an app tab:
4//! `ensure_tabs`, parking and duplicate cleanup leave it alone, and the caller
5//! closes it. See `KVT-FORK.md`.
6
7use serde_json::{Value, json};
8
9use super::{Browser, CDP_TIMEOUT, OPEN_TAB_TIMEOUT, cdp_call};
10use crate::error::BrowserError;
11use crate::http;
12
13/// Chrome unescapes the query of `/json/new?<url>` once, so the whole URL is escaped.
14fn escape_all(url: &str) -> String {
15 let mut out = String::with_capacity(url.len() * 3);
16 for byte in url.bytes() {
17 if byte.is_ascii_alphanumeric() {
18 out.push(byte as char);
19 } else {
20 out.push_str(&format!("%{byte:02X}"));
21 }
22 }
23 out
24}
25
26impl Browser {
27 /// Opens `url` in a new tab of the running managed browser; returns the tab id.
28 pub async fn kvt_open_tab(&self, url: &str) -> Result<String, BrowserError> {
29 if !self.is_running().await {
30 return Err(BrowserError::NoBrowser(self.inner.config.port.to_string()));
31 }
32 if let Some(bidi) = &self.inner.bidi {
33 let open = async {
34 let created = bidi
35 .call(
36 "browsingContext.create",
37 json!({"type": "tab", "background": true}),
38 )
39 .await?;
40 let context = created["context"].as_str().unwrap_or_default().to_owned();
41 if context.is_empty() {
42 return Err(BrowserError::Cdp(
43 "browsingContext.create: no context".into(),
44 ));
45 }
46 bidi.navigate(&context, url).await?;
47 Ok(context)
48 };
49 return tokio::time::timeout(OPEN_TAB_TIMEOUT, open)
50 .await
51 .map_err(|_| BrowserError::Cdp("opening the KVT tab timed out".into()))?;
52 }
53 let path = format!("/json/new?{}", escape_all(url));
54 let response =
55 http::request(self.inner.config.port, "PUT", &path, OPEN_TAB_TIMEOUT).await?;
56 if response.status != 200 {
57 return Err(BrowserError::Http(format!(
58 "PUT /json/new returned {}",
59 response.status
60 )));
61 }
62 let created: Value = serde_json::from_slice(&response.body)
63 .map_err(|error| BrowserError::Parse(format!("/json/new: {error}")))?;
64 created["id"]
65 .as_str()
66 .filter(|id| !id.is_empty())
67 .map(str::to_owned)
68 .ok_or_else(|| BrowserError::Parse("/json/new: no id".into()))
69 }
70
71 /// Evaluates `expression` in the tab and returns its JSON value.
72 pub async fn kvt_evaluate(&self, tab: &str, expression: &str) -> Result<Value, BrowserError> {
73 if let Some(bidi) = &self.inner.bidi {
74 return tokio::time::timeout(CDP_TIMEOUT, bidi.evaluate(tab, expression))
75 .await
76 .map_err(|_| BrowserError::Cdp("script.evaluate timed out".into()))?;
77 }
78 let url = format!(
79 "ws://127.0.0.1:{}/devtools/page/{tab}",
80 self.inner.config.port
81 );
82 let params = json!({ "expression": expression, "returnByValue": true });
83 let result = cdp_call(&url, "Runtime.evaluate", params, CDP_TIMEOUT).await?;
84 Ok(result["result"]["value"].clone())
85 }
86
87 /// Closes a tab opened with [`Browser::kvt_open_tab`]. Errors are ignored by callers.
88 pub async fn kvt_close_tab(&self, tab: &str) -> Result<(), BrowserError> {
89 if let Some(bidi) = &self.inner.bidi {
90 return tokio::time::timeout(CDP_TIMEOUT, bidi.close_tab(tab))
91 .await
92 .map_err(|_| BrowserError::Cdp("browsingContext.close timed out".into()))?;
93 }
94 let path = format!("/json/close/{tab}");
95 http::request(self.inner.config.port, "GET", &path, CDP_TIMEOUT)
96 .await
97 .map(drop)
98 }
99}
100
101#[cfg(test)]
102mod tests {
103 use super::escape_all;
104
105 #[test]
106 fn escapes_the_whole_url_once() {
107 assert_eq!(
108 escape_all("https://a.b/c?x=1&y=%20"),
109 "https%3A%2F%2Fa%2Eb%2Fc%3Fx%3D1%26y%3D%2520"
110 );
111 }
112}
crates/browser/tests/kvt_live_chrome.rs added +42 −0
@@ -0,0 +1,42 @@
1 //! KVT-fork: the extra sign-in tab (`kvt_open_tab`) on a real Chrome.
2
3 use std::time::Duration;
4
5 use browser::{Browser, Config};
6
7 const TEST_PORT: u16 = 9445;
8
9 #[tokio::test]
10 #[ignore = "starts a real Chrome on port 9445 with a throwaway profile"]
11 async fn kvt_tab_opens_the_exact_url_evaluates_and_closes() {
12 let profile_name = format!("rusty-teams-kvt-test-{}", std::process::id());
13 let config = Config::detect()
14 .unwrap()
15 .with_port(TEST_PORT)
16 .with_profile_name(&profile_name);
17 let mode_file = config.mode_file.clone();
18 let profile_directory = mode_file.with_extension("");
19 let browser = Browser::new(config);
20 assert!(!browser.is_running().await, "port {TEST_PORT} is in use");
21
22 let outcome = async {
23 browser.ensure_running().await.unwrap();
24 let url = "data:text/html,<p>ok</p><script>window.kvt=location.href</script>#a=1&b=%20c";
25 let tab = browser.kvt_open_tab(url).await.unwrap();
26 tokio::time::sleep(Duration::from_secs(1)).await;
27 let href = browser.kvt_evaluate(&tab, "window.kvt").await.unwrap();
28 assert_eq!(href.as_str(), Some(url));
29 let tabs_before = browser.tabs().await.unwrap().len();
30 browser.kvt_close_tab(&tab).await.unwrap();
31 tokio::time::sleep(Duration::from_millis(500)).await;
32 assert_eq!(browser.tabs().await.unwrap().len(), tabs_before - 1);
33 browser.stop().await.unwrap();
34 }
35 .await;
36
37 let _ = browser.stop().await;
38 tokio::time::sleep(Duration::from_secs(2)).await;
39 let _ = std::fs::remove_dir_all(&profile_directory);
40 let _ = std::fs::remove_file(&mode_file);
41 outcome
42 }
@@ -0,0 +1,42 @@
1//! KVT-fork: the extra sign-in tab (`kvt_open_tab`) on a real Chrome.
2
3use std::time::Duration;
4
5use browser::{Browser, Config};
6
7const TEST_PORT: u16 = 9445;
8
9#[tokio::test]
10#[ignore = "starts a real Chrome on port 9445 with a throwaway profile"]
11async fn kvt_tab_opens_the_exact_url_evaluates_and_closes() {
12 let profile_name = format!("rusty-teams-kvt-test-{}", std::process::id());
13 let config = Config::detect()
14 .unwrap()
15 .with_port(TEST_PORT)
16 .with_profile_name(&profile_name);
17 let mode_file = config.mode_file.clone();
18 let profile_directory = mode_file.with_extension("");
19 let browser = Browser::new(config);
20 assert!(!browser.is_running().await, "port {TEST_PORT} is in use");
21
22 let outcome = async {
23 browser.ensure_running().await.unwrap();
24 let url = "data:text/html,<p>ok</p><script>window.kvt=location.href</script>#a=1&b=%20c";
25 let tab = browser.kvt_open_tab(url).await.unwrap();
26 tokio::time::sleep(Duration::from_secs(1)).await;
27 let href = browser.kvt_evaluate(&tab, "window.kvt").await.unwrap();
28 assert_eq!(href.as_str(), Some(url));
29 let tabs_before = browser.tabs().await.unwrap().len();
30 browser.kvt_close_tab(&tab).await.unwrap();
31 tokio::time::sleep(Duration::from_millis(500)).await;
32 assert_eq!(browser.tabs().await.unwrap().len(), tabs_before - 1);
33 browser.stop().await.unwrap();
34 }
35 .await;
36
37 let _ = browser.stop().await;
38 tokio::time::sleep(Duration::from_secs(2)).await;
39 let _ = std::fs::remove_dir_all(&profile_directory);
40 let _ = std::fs::remove_file(&mode_file);
41 outcome
42}
crates/kvt-sleutels/Cargo.toml added +28 −0
@@ -0,0 +1,28 @@
1 [package]
2 name = "kvt-sleutels"
3 description = "KVT fork: koppeling met sleutels.kvt.nl (app-token, BC-kaarten), zonder GPUI."
4 edition.workspace = true
5 version.workspace = true
6 license.workspace = true
7 publish.workspace = true
8
9 [dependencies]
10 base64.workspace = true
11 keyring = { version = "3", features = [
12 "apple-native",
13 "windows-native",
14 "async-secret-service",
15 "tokio",
16 "crypto-rust",
17 ] }
18 percent-encoding.workspace = true
19 rand = "0.9"
20 reqwest = { version = "0.13", default-features = false, features = ["rustls", "json", "query", "form"] }
21 serde.workspace = true
22 serde_json.workspace = true
23 sha2 = "0.10"
24 tokio.workspace = true
25 url.workspace = true
26
27 [dev-dependencies]
28 tokio = { workspace = true }
@@ -0,0 +1,28 @@
1[package]
2name = "kvt-sleutels"
3description = "KVT fork: koppeling met sleutels.kvt.nl (app-token, BC-kaarten), zonder GPUI."
4edition.workspace = true
5version.workspace = true
6license.workspace = true
7publish.workspace = true
8
9[dependencies]
10base64.workspace = true
11keyring = { version = "3", features = [
12 "apple-native",
13 "windows-native",
14 "async-secret-service",
15 "tokio",
16 "crypto-rust",
17] }
18percent-encoding.workspace = true
19rand = "0.9"
20reqwest = { version = "0.13", default-features = false, features = ["rustls", "json", "query", "form"] }
21serde.workspace = true
22serde_json.workspace = true
23sha2 = "0.10"
24tokio.workspace = true
25url.workspace = true
26
27[dev-dependencies]
28tokio = { workspace = true }
crates/kvt-sleutels/src/client.rs added +126 −0
@@ -0,0 +1,126 @@
1 //! Client voor het kaart-endpoint van Mímir (`/mimir/api/cards.php`).
2
3 use std::time::Duration;
4
5 use crate::links::CardKind;
6 use crate::model::{Card, CardEnvelope, CompaniesEnvelope, SearchEnvelope, SearchResult};
7
8 #[derive(Debug, Clone, PartialEq, Eq)]
9 pub enum ClientError {
10 /// Token ongeldig, verlopen of ingetrokken: opnieuw koppelen.
11 Unauthorized,
12 /// De koppeling heeft geen scope `mimir.cards`.
13 Forbidden,
14 NotFound,
15 RateLimited,
16 /// Netwerk of Business Central niet bereikbaar (zonder details of geheimen).
17 Unavailable,
18 /// Ongeldige invoer (zou de client niet moeten sturen).
19 BadRequest,
20 }
21
22 #[derive(Clone)]
23 pub struct CardsClient {
24 base_url: String,
25 http: reqwest::Client,
26 }
27
28 impl CardsClient {
29 pub fn new(base_url: &str) -> Self {
30 let http = reqwest::Client::builder()
31 .timeout(Duration::from_secs(20))
32 .redirect(reqwest::redirect::Policy::none())
33 .build()
34 .unwrap_or_default();
35 Self {
36 base_url: base_url.trim_end_matches('/').to_owned(),
37 http,
38 }
39 }
40
41 pub fn http(&self) -> &reqwest::Client {
42 &self.http
43 }
44
45 pub fn base_url(&self) -> &str {
46 &self.base_url
47 }
48
49 async fn get<T: serde::de::DeserializeOwned>(
50 &self,
51 token: &str,
52 query: &[(&str, &str)],
53 ) -> Result<T, ClientError> {
54 let response = self
55 .http
56 .get(format!("{}/mimir/api/cards.php", self.base_url))
57 .query(query)
58 .bearer_auth(token)
59 .send()
60 .await
61 .map_err(|_| ClientError::Unavailable)?;
62 match response.status().as_u16() {
63 200 => response
64 .json::<T>()
65 .await
66 .map_err(|_| ClientError::Unavailable),
67 401 => Err(ClientError::Unauthorized),
68 403 => Err(ClientError::Forbidden),
69 404 => Err(ClientError::NotFound),
70 429 => Err(ClientError::RateLimited),
71 400 => Err(ClientError::BadRequest),
72 _ => Err(ClientError::Unavailable),
73 }
74 }
75
76 pub async fn card(
77 &self,
78 token: &str,
79 kind: CardKind,
80 company: &str,
81 no: &str,
82 ) -> Result<Card, ClientError> {
83 self.get::<CardEnvelope>(
84 token,
85 &[("type", kind.api_name()), ("company", company), ("no", no)],
86 )
87 .await
88 .map(|envelope| envelope.card)
89 }
90
91 pub async fn search(
92 &self,
93 token: &str,
94 kind: CardKind,
95 company: &str,
96 query: &str,
97 ) -> Result<Vec<SearchResult>, ClientError> {
98 self.get::<SearchEnvelope>(
99 token,
100 &[
101 ("type", kind.api_name()),
102 ("company", company),
103 ("q", query),
104 ],
105 )
106 .await
107 .map(|envelope| envelope.results)
108 }
109
110 pub async fn companies(&self, token: &str) -> Result<Vec<String>, ClientError> {
111 self.get::<CompaniesEnvelope>(token, &[("companies", "1")])
112 .await
113 .map(|envelope| envelope.companies)
114 }
115
116 /// Token bij de Login intrekken (ontkoppelen). Fouten zijn niet erg: de
117 /// token verloopt anders vanzelf en staat niet meer in de keyring.
118 pub async fn revoke(&self, token: &str) {
119 let _ = self
120 .http
121 .post(format!("{}/login/app_token_revoke.php", self.base_url))
122 .bearer_auth(token)
123 .send()
124 .await;
125 }
126 }
@@ -0,0 +1,126 @@
1//! Client voor het kaart-endpoint van Mímir (`/mimir/api/cards.php`).
2
3use std::time::Duration;
4
5use crate::links::CardKind;
6use crate::model::{Card, CardEnvelope, CompaniesEnvelope, SearchEnvelope, SearchResult};
7
8#[derive(Debug, Clone, PartialEq, Eq)]
9pub enum ClientError {
10 /// Token ongeldig, verlopen of ingetrokken: opnieuw koppelen.
11 Unauthorized,
12 /// De koppeling heeft geen scope `mimir.cards`.
13 Forbidden,
14 NotFound,
15 RateLimited,
16 /// Netwerk of Business Central niet bereikbaar (zonder details of geheimen).
17 Unavailable,
18 /// Ongeldige invoer (zou de client niet moeten sturen).
19 BadRequest,
20}
21
22#[derive(Clone)]
23pub struct CardsClient {
24 base_url: String,
25 http: reqwest::Client,
26}
27
28impl CardsClient {
29 pub fn new(base_url: &str) -> Self {
30 let http = reqwest::Client::builder()
31 .timeout(Duration::from_secs(20))
32 .redirect(reqwest::redirect::Policy::none())
33 .build()
34 .unwrap_or_default();
35 Self {
36 base_url: base_url.trim_end_matches('/').to_owned(),
37 http,
38 }
39 }
40
41 pub fn http(&self) -> &reqwest::Client {
42 &self.http
43 }
44
45 pub fn base_url(&self) -> &str {
46 &self.base_url
47 }
48
49 async fn get<T: serde::de::DeserializeOwned>(
50 &self,
51 token: &str,
52 query: &[(&str, &str)],
53 ) -> Result<T, ClientError> {
54 let response = self
55 .http
56 .get(format!("{}/mimir/api/cards.php", self.base_url))
57 .query(query)
58 .bearer_auth(token)
59 .send()
60 .await
61 .map_err(|_| ClientError::Unavailable)?;
62 match response.status().as_u16() {
63 200 => response
64 .json::<T>()
65 .await
66 .map_err(|_| ClientError::Unavailable),
67 401 => Err(ClientError::Unauthorized),
68 403 => Err(ClientError::Forbidden),
69 404 => Err(ClientError::NotFound),
70 429 => Err(ClientError::RateLimited),
71 400 => Err(ClientError::BadRequest),
72 _ => Err(ClientError::Unavailable),
73 }
74 }
75
76 pub async fn card(
77 &self,
78 token: &str,
79 kind: CardKind,
80 company: &str,
81 no: &str,
82 ) -> Result<Card, ClientError> {
83 self.get::<CardEnvelope>(
84 token,
85 &[("type", kind.api_name()), ("company", company), ("no", no)],
86 )
87 .await
88 .map(|envelope| envelope.card)
89 }
90
91 pub async fn search(
92 &self,
93 token: &str,
94 kind: CardKind,
95 company: &str,
96 query: &str,
97 ) -> Result<Vec<SearchResult>, ClientError> {
98 self.get::<SearchEnvelope>(
99 token,
100 &[
101 ("type", kind.api_name()),
102 ("company", company),
103 ("q", query),
104 ],
105 )
106 .await
107 .map(|envelope| envelope.results)
108 }
109
110 pub async fn companies(&self, token: &str) -> Result<Vec<String>, ClientError> {
111 self.get::<CompaniesEnvelope>(token, &[("companies", "1")])
112 .await
113 .map(|envelope| envelope.companies)
114 }
115
116 /// Token bij de Login intrekken (ontkoppelen). Fouten zijn niet erg: de
117 /// token verloopt anders vanzelf en staat niet meer in de keyring.
118 pub async fn revoke(&self, token: &str) {
119 let _ = self
120 .http
121 .post(format!("{}/login/app_token_revoke.php", self.base_url))
122 .bearer_auth(token)
123 .send()
124 .await;
125 }
126}
crates/kvt-sleutels/src/connect.rs added +335 −0
@@ -0,0 +1,335 @@
1 //! Koppelen met de Login van sleutels.kvt.nl, zoals OAuth voor native apps
2 //! (RFC 8252): PKCE S256, een tijdelijke luisteraar op 127.0.0.1 en de
3 //! systeembrowser. Zie `ict/login` README, «App-tokens voor native apps».
4
5 use std::net::SocketAddr;
6 use std::time::Duration;
7
8 use base64::Engine as _;
9 use base64::engine::general_purpose::URL_SAFE_NO_PAD;
10 use rand::RngCore as _;
11 use serde::Deserialize;
12 use sha2::{Digest, Sha256};
13 use tokio::io::{AsyncReadExt, AsyncWriteExt};
14 use tokio::net::TcpListener;
15
16 use crate::token::StoredToken;
17 use crate::{CLIENT_ID, SCOPES};
18
19 const CALLBACK_PATH: &str = "/kvt-callback";
20 const WAIT: Duration = Duration::from_secs(300);
21
22 /// Een lopende koppeling: open `url` in de browser en wacht met [`finish`].
23 pub struct PendingConnect {
24 pub url: String,
25 redirect_uri: String,
26 state: String,
27 verifier: String,
28 listener: TcpListener,
29 base_url: String,
30 }
31
32 impl std::fmt::Debug for PendingConnect {
33 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
34 f.debug_struct("PendingConnect")
35 .field("redirect_uri", &self.redirect_uri)
36 .finish_non_exhaustive()
37 }
38 }
39
40 #[derive(Debug, Clone, PartialEq, Eq)]
41 pub enum ConnectError {
42 /// De gebruiker klikte Annuleren.
43 Denied,
44 /// Geen antwoord binnen 5 minuten.
45 TimedOut,
46 /// Iets anders (netwerk, ongeldig antwoord). Zonder geheimen.
47 Failed(String),
48 }
49
50 fn random_url_safe(bytes: usize) -> String {
51 let mut buffer = vec![0_u8; bytes];
52 rand::rng().fill_bytes(&mut buffer);
53 URL_SAFE_NO_PAD.encode(buffer)
54 }
55
56 pub fn pkce_challenge(verifier: &str) -> String {
57 URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes()))
58 }
59
60 fn encode(value: &str) -> String {
61 percent_encoding::utf8_percent_encode(value, percent_encoding::NON_ALPHANUMERIC).to_string()
62 }
63
64 /// Start een koppeling: kiest een vrije poort en bouwt de koppel-URL.
65 pub async fn begin(base_url: &str, device_name: &str) -> Result<PendingConnect, ConnectError> {
66 let listener = TcpListener::bind(SocketAddr::from(([127, 0, 0, 1], 0)))
67 .await
68 .map_err(|error| ConnectError::Failed(error.to_string()))?;
69 let port = listener
70 .local_addr()
71 .map_err(|error| ConnectError::Failed(error.to_string()))?
72 .port();
73 let redirect_uri = format!("http://127.0.0.1:{port}{CALLBACK_PATH}");
74 let verifier = random_url_safe(48);
75 let state = random_url_safe(24);
76 let base = base_url.trim_end_matches('/').to_owned();
77 let url = format!(
78 "{base}/login/app_connect.php?client_id={}&redirect_uri={}&state={}&code_challenge={}&code_challenge_method=S256&scope={}&device_name={}",
79 encode(CLIENT_ID),
80 encode(&redirect_uri),
81 encode(&state),
82 encode(&pkce_challenge(&verifier)),
83 encode(SCOPES),
84 encode(device_name),
85 );
86 Ok(PendingConnect {
87 url,
88 redirect_uri,
89 state,
90 verifier,
91 listener,
92 base_url: base,
93 })
94 }
95
96 #[derive(Debug, PartialEq, Eq)]
97 enum Callback {
98 Code(String),
99 Denied,
100 Other,
101 }
102
103 fn parse_callback(request_line: &str, expected_state: &str) -> Callback {
104 let Some(target) = request_line
105 .strip_prefix("GET ")
106 .and_then(|rest| rest.split_whitespace().next())
107 else {
108 return Callback::Other;
109 };
110 let (path, query) = target.split_once('?').unwrap_or((target, ""));
111 if path != CALLBACK_PATH {
112 return Callback::Other;
113 }
114 let mut code = None;
115 let mut state = None;
116 let mut error = None;
117 for (key, value) in url::form_urlencoded::parse(query.as_bytes()) {
118 match key.as_ref() {
119 "code" => code = Some(value.into_owned()),
120 "state" => state = Some(value.into_owned()),
121 "error" => error = Some(value.into_owned()),
122 _ => {}
123 }
124 }
125 if state.as_deref() != Some(expected_state) {
126 return Callback::Other;
127 }
128 match (code, error) {
129 (Some(code), None) if code.len() == 64 && code.bytes().all(|b| b.is_ascii_hexdigit()) => {
130 Callback::Code(code)
131 }
132 (_, Some(_)) => Callback::Denied,
133 _ => Callback::Other,
134 }
135 }
136
137 async fn respond(stream: &mut tokio::net::TcpStream, status: &str, body: &str) {
138 let response = format!(
139 "HTTP/1.1 {status}\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: {}\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n{body}",
140 body.len()
141 );
142 let _ = stream.write_all(response.as_bytes()).await;
143 let _ = stream.shutdown().await;
144 }
145
146 async fn wait_for_callback(pending: &PendingConnect) -> Result<String, ConnectError> {
147 let deadline = tokio::time::Instant::now() + WAIT;
148 loop {
149 let accepted = tokio::time::timeout_at(deadline, pending.listener.accept())
150 .await
151 .map_err(|_| ConnectError::TimedOut)?;
152 let Ok((mut stream, _)) = accepted else {
153 continue;
154 };
155 let mut buffer = vec![0_u8; 4096];
156 let read =
157 match tokio::time::timeout(Duration::from_secs(5), stream.read(&mut buffer)).await {
158 Ok(Ok(read)) => read,
159 _ => continue,
160 };
161 let request = String::from_utf8_lossy(&buffer[..read]);
162 match parse_callback(request.lines().next().unwrap_or_default(), &pending.state) {
163 Callback::Code(code) => {
164 respond(&mut stream, "200 OK", PAGE_OK).await;
165 return Ok(code);
166 }
167 Callback::Denied => {
168 respond(&mut stream, "200 OK", PAGE_DENIED).await;
169 return Err(ConnectError::Denied);
170 }
171 Callback::Other => respond(&mut stream, "404 Not Found", PAGE_UNKNOWN).await,
172 }
173 }
174 }
175
176 #[derive(Deserialize)]
177 struct TokenResponse {
178 access_token: String,
179 expires_at: i64,
180 #[serde(default)]
181 user: TokenUser,
182 }
183
184 #[derive(Default, Deserialize)]
185 struct TokenUser {
186 #[serde(default)]
187 email: String,
188 #[serde(default)]
189 name: String,
190 }
191
192 /// Wacht op de browser en wissel de code in voor een app-token.
193 pub async fn finish(
194 pending: PendingConnect,
195 http: &reqwest::Client,
196 ) -> Result<StoredToken, ConnectError> {
197 let code = wait_for_callback(&pending).await?;
198 let response = http
199 .post(format!("{}/login/app_token_exchange.php", pending.base_url))
200 .form(&[
201 ("grant_type", "authorization_code"),
202 ("code", code.as_str()),
203 ("code_verifier", pending.verifier.as_str()),
204 ("client_id", CLIENT_ID),
205 ("redirect_uri", pending.redirect_uri.as_str()),
206 ])
207 .timeout(Duration::from_secs(30))
208 .send()
209 .await
210 .map_err(|error| ConnectError::Failed(error.without_url().to_string()))?;
211 if !response.status().is_success() {
212 return Err(ConnectError::Failed(format!(
213 "HTTP {}",
214 response.status().as_u16()
215 )));
216 }
217 let token: TokenResponse = response
218 .json()
219 .await
220 .map_err(|_| ConnectError::Failed("unexpected answer".into()))?;
221 if !token.access_token.starts_with("sat_") || token.access_token.len() != 68 {
222 return Err(ConnectError::Failed("unexpected answer".into()));
223 }
224 Ok(StoredToken {
225 token: token.access_token,
226 expires_at: token.expires_at,
227 email: token.user.email,
228 name: token.user.name,
229 })
230 }
231
232 const PAGE_OK: &str = concat!(
233 "<!DOCTYPE html><html lang=\"nl\"><head><meta charset=\"utf-8\"><title>rusty-teams</title><style>",
234 "body{font-family:system-ui,sans-serif;max-width:32rem;margin:3rem auto;padding:0 1rem;line-height:1.5;color:#00101F}h1{font-size:1.25rem;margin:0 0 .75rem;color:#00529B}",
235 "</style></head><body><h1>Gekoppeld</h1><p>Je kunt dit venster sluiten en teruggaan naar rusty-teams.</p>",
236 "<p lang=\"en\">Connected. You can close this window and return to rusty-teams.</p></body></html>"
237 );
238 const PAGE_DENIED: &str = concat!(
239 "<!DOCTYPE html><html lang=\"nl\"><head><meta charset=\"utf-8\"><title>rusty-teams</title><style>",
240 "body{font-family:system-ui,sans-serif;max-width:32rem;margin:3rem auto;padding:0 1rem;line-height:1.5;color:#00101F}h1{font-size:1.25rem;margin:0 0 .75rem;color:#00529B}",
241 "</style></head><body><h1>Niet gekoppeld</h1><p>Je kunt dit venster sluiten.</p>",
242 "<p lang=\"en\">Not connected. You can close this window.</p></body></html>"
243 );
244 const PAGE_UNKNOWN: &str = "<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>rusty-teams</title></head><body></body></html>";
245
246 #[cfg(test)]
247 mod tests {
248 use super::*;
249
250 #[test]
251 fn pkce_matches_rfc7636_example() {
252 assert_eq!(
253 pkce_challenge("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"),
254 "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"
255 );
256 }
257
258 #[test]
259 fn callback_needs_path_state_and_hex_code() {
260 let code = "a".repeat(64);
261 assert_eq!(
262 parse_callback(
263 &format!("GET /kvt-callback?code={code}&state=s1 HTTP/1.1"),
264 "s1"
265 ),
266 Callback::Code(code.clone())
267 );
268 assert_eq!(
269 parse_callback(
270 &format!("GET /kvt-callback?code={code}&state=other HTTP/1.1"),
271 "s1"
272 ),
273 Callback::Other
274 );
275 assert_eq!(
276 parse_callback(
277 &format!("GET /favicon.ico?code={code}&state=s1 HTTP/1.1"),
278 "s1"
279 ),
280 Callback::Other
281 );
282 assert_eq!(
283 parse_callback("GET /kvt-callback?code=xyz&state=s1 HTTP/1.1", "s1"),
284 Callback::Other
285 );
286 assert_eq!(
287 parse_callback(
288 "GET /kvt-callback?error=access_denied&state=s1 HTTP/1.1",
289 "s1"
290 ),
291 Callback::Denied
292 );
293 assert_eq!(
294 parse_callback("POST /kvt-callback?error=x&state=s1 HTTP/1.1", "s1"),
295 Callback::Other
296 );
297 }
298
299 #[tokio::test]
300 async fn begin_builds_a_loopback_connect_url() {
301 let pending = begin("https://sleutels.kvt.nl/", "Laptop").await.unwrap();
302 assert!(pending.url.starts_with("https://sleutels.kvt.nl/login/app_connect.php?client_id=rusty%2Dteams&redirect_uri=http%3A%2F%2F127%2E0%2E0%2E1%3A"));
303 assert!(pending.url.contains("code_challenge_method=S256"));
304 assert!(
305 pending
306 .url
307 .contains("scope=mimir%2Ecards%20asclepius%20ponos%20daedalus")
308 );
309 assert!(pending.redirect_uri.ends_with("/kvt-callback"));
310 assert!(!pending.url.contains(&pending.verifier));
311 }
312
313 #[tokio::test]
314 async fn waits_past_unrelated_requests_until_the_callback() {
315 let pending = begin("https://sleutels.kvt.nl", "x").await.unwrap();
316 let addr = pending.listener.local_addr().unwrap();
317 let state = pending.state.clone();
318 let client = tokio::spawn(async move {
319 for target in [
320 "/favicon.ico".to_owned(),
321 format!("/kvt-callback?code={}&state={state}", "b".repeat(64)),
322 ] {
323 let mut stream = tokio::net::TcpStream::connect(addr).await.unwrap();
324 stream
325 .write_all(format!("GET {target} HTTP/1.1\r\nHost: x\r\n\r\n").as_bytes())
326 .await
327 .unwrap();
328 let mut out = String::new();
329 stream.read_to_string(&mut out).await.unwrap();
330 }
331 });
332 assert_eq!(wait_for_callback(&pending).await.unwrap(), "b".repeat(64));
333 client.await.unwrap();
334 }
335 }
@@ -0,0 +1,335 @@
1//! Koppelen met de Login van sleutels.kvt.nl, zoals OAuth voor native apps
2//! (RFC 8252): PKCE S256, een tijdelijke luisteraar op 127.0.0.1 en de
3//! systeembrowser. Zie `ict/login` README, «App-tokens voor native apps».
4
5use std::net::SocketAddr;
6use std::time::Duration;
7
8use base64::Engine as _;
9use base64::engine::general_purpose::URL_SAFE_NO_PAD;
10use rand::RngCore as _;
11use serde::Deserialize;
12use sha2::{Digest, Sha256};
13use tokio::io::{AsyncReadExt, AsyncWriteExt};
14use tokio::net::TcpListener;
15
16use crate::token::StoredToken;
17use crate::{CLIENT_ID, SCOPES};
18
19const CALLBACK_PATH: &str = "/kvt-callback";
20const WAIT: Duration = Duration::from_secs(300);
21
22/// Een lopende koppeling: open `url` in de browser en wacht met [`finish`].
23pub struct PendingConnect {
24 pub url: String,
25 redirect_uri: String,
26 state: String,
27 verifier: String,
28 listener: TcpListener,
29 base_url: String,
30}
31
32impl std::fmt::Debug for PendingConnect {
33 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
34 f.debug_struct("PendingConnect")
35 .field("redirect_uri", &self.redirect_uri)
36 .finish_non_exhaustive()
37 }
38}
39
40#[derive(Debug, Clone, PartialEq, Eq)]
41pub enum ConnectError {
42 /// De gebruiker klikte Annuleren.
43 Denied,
44 /// Geen antwoord binnen 5 minuten.
45 TimedOut,
46 /// Iets anders (netwerk, ongeldig antwoord). Zonder geheimen.
47 Failed(String),
48}
49
50fn random_url_safe(bytes: usize) -> String {
51 let mut buffer = vec![0_u8; bytes];
52 rand::rng().fill_bytes(&mut buffer);
53 URL_SAFE_NO_PAD.encode(buffer)
54}
55
56pub fn pkce_challenge(verifier: &str) -> String {
57 URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes()))
58}
59
60fn encode(value: &str) -> String {
61 percent_encoding::utf8_percent_encode(value, percent_encoding::NON_ALPHANUMERIC).to_string()
62}
63
64/// Start een koppeling: kiest een vrije poort en bouwt de koppel-URL.
65pub async fn begin(base_url: &str, device_name: &str) -> Result<PendingConnect, ConnectError> {
66 let listener = TcpListener::bind(SocketAddr::from(([127, 0, 0, 1], 0)))
67 .await
68 .map_err(|error| ConnectError::Failed(error.to_string()))?;
69 let port = listener
70 .local_addr()
71 .map_err(|error| ConnectError::Failed(error.to_string()))?
72 .port();
73 let redirect_uri = format!("http://127.0.0.1:{port}{CALLBACK_PATH}");
74 let verifier = random_url_safe(48);
75 let state = random_url_safe(24);
76 let base = base_url.trim_end_matches('/').to_owned();
77 let url = format!(
78 "{base}/login/app_connect.php?client_id={}&redirect_uri={}&state={}&code_challenge={}&code_challenge_method=S256&scope={}&device_name={}",
79 encode(CLIENT_ID),
80 encode(&redirect_uri),
81 encode(&state),
82 encode(&pkce_challenge(&verifier)),
83 encode(SCOPES),
84 encode(device_name),
85 );
86 Ok(PendingConnect {
87 url,
88 redirect_uri,
89 state,
90 verifier,
91 listener,
92 base_url: base,
93 })
94}
95
96#[derive(Debug, PartialEq, Eq)]
97enum Callback {
98 Code(String),
99 Denied,
100 Other,
101}
102
103fn parse_callback(request_line: &str, expected_state: &str) -> Callback {
104 let Some(target) = request_line
105 .strip_prefix("GET ")
106 .and_then(|rest| rest.split_whitespace().next())
107 else {
108 return Callback::Other;
109 };
110 let (path, query) = target.split_once('?').unwrap_or((target, ""));
111 if path != CALLBACK_PATH {
112 return Callback::Other;
113 }
114 let mut code = None;
115 let mut state = None;
116 let mut error = None;
117 for (key, value) in url::form_urlencoded::parse(query.as_bytes()) {
118 match key.as_ref() {
119 "code" => code = Some(value.into_owned()),
120 "state" => state = Some(value.into_owned()),
121 "error" => error = Some(value.into_owned()),
122 _ => {}
123 }
124 }
125 if state.as_deref() != Some(expected_state) {
126 return Callback::Other;
127 }
128 match (code, error) {
129 (Some(code), None) if code.len() == 64 && code.bytes().all(|b| b.is_ascii_hexdigit()) => {
130 Callback::Code(code)
131 }
132 (_, Some(_)) => Callback::Denied,
133 _ => Callback::Other,
134 }
135}
136
137async fn respond(stream: &mut tokio::net::TcpStream, status: &str, body: &str) {
138 let response = format!(
139 "HTTP/1.1 {status}\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: {}\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n{body}",
140 body.len()
141 );
142 let _ = stream.write_all(response.as_bytes()).await;
143 let _ = stream.shutdown().await;
144}
145
146async fn wait_for_callback(pending: &PendingConnect) -> Result<String, ConnectError> {
147 let deadline = tokio::time::Instant::now() + WAIT;
148 loop {
149 let accepted = tokio::time::timeout_at(deadline, pending.listener.accept())
150 .await
151 .map_err(|_| ConnectError::TimedOut)?;
152 let Ok((mut stream, _)) = accepted else {
153 continue;
154 };
155 let mut buffer = vec![0_u8; 4096];
156 let read =
157 match tokio::time::timeout(Duration::from_secs(5), stream.read(&mut buffer)).await {
158 Ok(Ok(read)) => read,
159 _ => continue,
160 };
161 let request = String::from_utf8_lossy(&buffer[..read]);
162 match parse_callback(request.lines().next().unwrap_or_default(), &pending.state) {
163 Callback::Code(code) => {
164 respond(&mut stream, "200 OK", PAGE_OK).await;
165 return Ok(code);
166 }
167 Callback::Denied => {
168 respond(&mut stream, "200 OK", PAGE_DENIED).await;
169 return Err(ConnectError::Denied);
170 }
171 Callback::Other => respond(&mut stream, "404 Not Found", PAGE_UNKNOWN).await,
172 }
173 }
174}
175
176#[derive(Deserialize)]
177struct TokenResponse {
178 access_token: String,
179 expires_at: i64,
180 #[serde(default)]
181 user: TokenUser,
182}
183
184#[derive(Default, Deserialize)]
185struct TokenUser {
186 #[serde(default)]
187 email: String,
188 #[serde(default)]
189 name: String,
190}
191
192/// Wacht op de browser en wissel de code in voor een app-token.
193pub async fn finish(
194 pending: PendingConnect,
195 http: &reqwest::Client,
196) -> Result<StoredToken, ConnectError> {
197 let code = wait_for_callback(&pending).await?;
198 let response = http
199 .post(format!("{}/login/app_token_exchange.php", pending.base_url))
200 .form(&[
201 ("grant_type", "authorization_code"),
202 ("code", code.as_str()),
203 ("code_verifier", pending.verifier.as_str()),
204 ("client_id", CLIENT_ID),
205 ("redirect_uri", pending.redirect_uri.as_str()),
206 ])
207 .timeout(Duration::from_secs(30))
208 .send()
209 .await
210 .map_err(|error| ConnectError::Failed(error.without_url().to_string()))?;
211 if !response.status().is_success() {
212 return Err(ConnectError::Failed(format!(
213 "HTTP {}",
214 response.status().as_u16()
215 )));
216 }
217 let token: TokenResponse = response
218 .json()
219 .await
220 .map_err(|_| ConnectError::Failed("unexpected answer".into()))?;
221 if !token.access_token.starts_with("sat_") || token.access_token.len() != 68 {
222 return Err(ConnectError::Failed("unexpected answer".into()));
223 }
224 Ok(StoredToken {
225 token: token.access_token,
226 expires_at: token.expires_at,
227 email: token.user.email,
228 name: token.user.name,
229 })
230}
231
232const PAGE_OK: &str = concat!(
233 "<!DOCTYPE html><html lang=\"nl\"><head><meta charset=\"utf-8\"><title>rusty-teams</title><style>",
234 "body{font-family:system-ui,sans-serif;max-width:32rem;margin:3rem auto;padding:0 1rem;line-height:1.5;color:#00101F}h1{font-size:1.25rem;margin:0 0 .75rem;color:#00529B}",
235 "</style></head><body><h1>Gekoppeld</h1><p>Je kunt dit venster sluiten en teruggaan naar rusty-teams.</p>",
236 "<p lang=\"en\">Connected. You can close this window and return to rusty-teams.</p></body></html>"
237);
238const PAGE_DENIED: &str = concat!(
239 "<!DOCTYPE html><html lang=\"nl\"><head><meta charset=\"utf-8\"><title>rusty-teams</title><style>",
240 "body{font-family:system-ui,sans-serif;max-width:32rem;margin:3rem auto;padding:0 1rem;line-height:1.5;color:#00101F}h1{font-size:1.25rem;margin:0 0 .75rem;color:#00529B}",
241 "</style></head><body><h1>Niet gekoppeld</h1><p>Je kunt dit venster sluiten.</p>",
242 "<p lang=\"en\">Not connected. You can close this window.</p></body></html>"
243);
244const PAGE_UNKNOWN: &str = "<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>rusty-teams</title></head><body></body></html>";
245
246#[cfg(test)]
247mod tests {
248 use super::*;
249
250 #[test]
251 fn pkce_matches_rfc7636_example() {
252 assert_eq!(
253 pkce_challenge("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"),
254 "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"
255 );
256 }
257
258 #[test]
259 fn callback_needs_path_state_and_hex_code() {
260 let code = "a".repeat(64);
261 assert_eq!(
262 parse_callback(
263 &format!("GET /kvt-callback?code={code}&state=s1 HTTP/1.1"),
264 "s1"
265 ),
266 Callback::Code(code.clone())
267 );
268 assert_eq!(
269 parse_callback(
270 &format!("GET /kvt-callback?code={code}&state=other HTTP/1.1"),
271 "s1"
272 ),
273 Callback::Other
274 );
275 assert_eq!(
276 parse_callback(
277 &format!("GET /favicon.ico?code={code}&state=s1 HTTP/1.1"),
278 "s1"
279 ),
280 Callback::Other
281 );
282 assert_eq!(
283 parse_callback("GET /kvt-callback?code=xyz&state=s1 HTTP/1.1", "s1"),
284 Callback::Other
285 );
286 assert_eq!(
287 parse_callback(
288 "GET /kvt-callback?error=access_denied&state=s1 HTTP/1.1",
289 "s1"
290 ),
291 Callback::Denied
292 );
293 assert_eq!(
294 parse_callback("POST /kvt-callback?error=x&state=s1 HTTP/1.1", "s1"),
295 Callback::Other
296 );
297 }
298
299 #[tokio::test]
300 async fn begin_builds_a_loopback_connect_url() {
301 let pending = begin("https://sleutels.kvt.nl/", "Laptop").await.unwrap();
302 assert!(pending.url.starts_with("https://sleutels.kvt.nl/login/app_connect.php?client_id=rusty%2Dteams&redirect_uri=http%3A%2F%2F127%2E0%2E0%2E1%3A"));
303 assert!(pending.url.contains("code_challenge_method=S256"));
304 assert!(
305 pending
306 .url
307 .contains("scope=mimir%2Ecards%20asclepius%20ponos%20daedalus")
308 );
309 assert!(pending.redirect_uri.ends_with("/kvt-callback"));
310 assert!(!pending.url.contains(&pending.verifier));
311 }
312
313 #[tokio::test]
314 async fn waits_past_unrelated_requests_until_the_callback() {
315 let pending = begin("https://sleutels.kvt.nl", "x").await.unwrap();
316 let addr = pending.listener.local_addr().unwrap();
317 let state = pending.state.clone();
318 let client = tokio::spawn(async move {
319 for target in [
320 "/favicon.ico".to_owned(),
321 format!("/kvt-callback?code={}&state={state}", "b".repeat(64)),
322 ] {
323 let mut stream = tokio::net::TcpStream::connect(addr).await.unwrap();
324 stream
325 .write_all(format!("GET {target} HTTP/1.1\r\nHost: x\r\n\r\n").as_bytes())
326 .await
327 .unwrap();
328 let mut out = String::new();
329 stream.read_to_string(&mut out).await.unwrap();
330 }
331 });
332 assert_eq!(wait_for_callback(&pending).await.unwrap(), "b".repeat(64));
333 client.await.unwrap();
334 }
335}
crates/kvt-sleutels/src/lib.rs added +30 −0
@@ -0,0 +1,30 @@
1 //! KVT fork: koppeling met sleutels.kvt.nl.
2 //!
3 //! - [`links`]: BC-webclient- en sleutels-links herkennen en maken (kaart-verwijzingen).
4 //! - [`connect`]: koppelen via de systeembrowser (PKCE, loopback) met de Login.
5 //! - [`session`]: dat koppelen in de sessiebrowser van de app (Microsoft-sessie hergebruiken).
6 //! - [`token`]: het app-token in de keyring van het OS.
7 //! - [`client`]: het kaart-endpoint van Mímir (`/mimir/api/cards.php`).
8 //!
9 //! Geen GPUI: ook bruikbaar voor een latere Android-client.
10
11 pub mod client;
12 pub mod connect;
13 pub mod links;
14 pub mod model;
15 pub mod session;
16 pub mod token;
17
18 pub use client::{CardsClient, ClientError};
19 pub use links::{CardKind, CardRef, MAX_CARDS_PER_MESSAGE, card_refs_in_urls, parse_card_link};
20 pub use model::{Card, CardField, CardLinks, FieldRef, SearchResult};
21 pub use token::StoredToken;
22
23 /// Basisadres van de sleutels-apps.
24 pub const DEFAULT_BASE_URL: &str = "https://sleutels.kvt.nl";
25 /// Host van de BC-webclient.
26 pub const BC_WEB_HOST: &str = "kvtmd365.kvt.nl";
27 /// Client-id bij de Login (`login_app_clients()`).
28 pub const CLIENT_ID: &str = "rusty-teams";
29 /// Scopes die rusty-teams vraagt.
30 pub const SCOPES: &str = "mimir.cards asclepius ponos daedalus";
@@ -0,0 +1,30 @@
1//! KVT fork: koppeling met sleutels.kvt.nl.
2//!
3//! - [`links`]: BC-webclient- en sleutels-links herkennen en maken (kaart-verwijzingen).
4//! - [`connect`]: koppelen via de systeembrowser (PKCE, loopback) met de Login.
5//! - [`session`]: dat koppelen in de sessiebrowser van de app (Microsoft-sessie hergebruiken).
6//! - [`token`]: het app-token in de keyring van het OS.
7//! - [`client`]: het kaart-endpoint van Mímir (`/mimir/api/cards.php`).
8//!
9//! Geen GPUI: ook bruikbaar voor een latere Android-client.
10
11pub mod client;
12pub mod connect;
13pub mod links;
14pub mod model;
15pub mod session;
16pub mod token;
17
18pub use client::{CardsClient, ClientError};
19pub use links::{CardKind, CardRef, MAX_CARDS_PER_MESSAGE, card_refs_in_urls, parse_card_link};
20pub use model::{Card, CardField, CardLinks, FieldRef, SearchResult};
21pub use token::StoredToken;
22
23/// Basisadres van de sleutels-apps.
24pub const DEFAULT_BASE_URL: &str = "https://sleutels.kvt.nl";
25/// Host van de BC-webclient.
26pub const BC_WEB_HOST: &str = "kvtmd365.kvt.nl";
27/// Client-id bij de Login (`login_app_clients()`).
28pub const CLIENT_ID: &str = "rusty-teams";
29/// Scopes die rusty-teams vraagt.
30pub const SCOPES: &str = "mimir.cards asclepius ponos daedalus";
crates/kvt-sleutels/src/model.rs added +117 −0
@@ -0,0 +1,117 @@
1 //! Antwoorden van `/mimir/api/cards.php`.
2
3 use serde::Deserialize;
4
5 use crate::links::CardKind;
6
7 #[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
8 pub struct Card {
9 #[serde(rename = "type")]
10 pub kind: String,
11 pub type_label: String,
12 pub company: String,
13 pub no: String,
14 #[serde(default)]
15 pub title: String,
16 #[serde(default)]
17 pub subtitle: String,
18 #[serde(default)]
19 pub fields: Vec<CardField>,
20 #[serde(default)]
21 pub links: CardLinks,
22 }
23
24 impl Card {
25 pub fn card_kind(&self) -> Option<CardKind> {
26 CardKind::from_api_name(&self.kind)
27 }
28
29 pub fn field(&self, key: &str) -> Option<&CardField> {
30 self.fields.iter().find(|field| field.key == key)
31 }
32 }
33
34 #[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
35 pub struct CardField {
36 pub key: String,
37 pub label: String,
38 pub value: String,
39 /// ISO-datum (`2026-01-15`) bij datumvelden; `value` is al `15 jan 2026`.
40 #[serde(default)]
41 pub date: Option<String>,
42 #[serde(default, rename = "ref")]
43 pub reference: Option<FieldRef>,
44 }
45
46 #[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
47 pub struct FieldRef {
48 #[serde(rename = "type")]
49 pub kind: String,
50 pub no: String,
51 #[serde(default)]
52 pub bc_url: String,
53 }
54
55 #[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
56 pub struct CardLinks {
57 #[serde(default)]
58 pub bc: String,
59 #[serde(default)]
60 pub daedalus: Option<String>,
61 }
62
63 #[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
64 pub struct SearchResult {
65 #[serde(rename = "type")]
66 pub kind: String,
67 pub company: String,
68 pub no: String,
69 #[serde(default)]
70 pub title: String,
71 #[serde(default)]
72 pub subtitle: String,
73 #[serde(default)]
74 pub bc_url: String,
75 }
76
77 #[derive(Debug, Deserialize)]
78 pub(crate) struct CardEnvelope {
79 pub card: Card,
80 }
81
82 #[derive(Debug, Deserialize)]
83 pub(crate) struct SearchEnvelope {
84 pub results: Vec<SearchResult>,
85 }
86
87 #[derive(Debug, Deserialize)]
88 pub(crate) struct CompaniesEnvelope {
89 pub companies: Vec<String>,
90 }
91
92 #[cfg(test)]
93 mod tests {
94 use super::*;
95
96 #[test]
97 fn parses_the_mimir_card_shape() {
98 let json = r#"{"card":{"type":"werkorder","type_label":"Werkorder","company":"Koninklijke van Twist","no":"WO2699001",
99 "title":"Onderhoud 500 uur","subtitle":"Testschip",
100 "fields":[{"key":"Start_Date","label":"Begindatum","value":"15 jan 2026","date":"2026-01-15"},
101 {"key":"Job_No","label":"Project","value":"PRJ2699001","ref":{"type":"project","no":"PRJ2699001","bc_url":"https://x"}}],
102 "links":{"bc":"https://bc","daedalus":"https://d"}},"fetched_at":1}"#;
103 let card = serde_json::from_str::<CardEnvelope>(json).unwrap().card;
104 assert_eq!(card.card_kind(), Some(CardKind::Werkorder));
105 assert_eq!(card.field("Start_Date").unwrap().value, "15 jan 2026");
106 assert_eq!(
107 card.field("Job_No")
108 .unwrap()
109 .reference
110 .as_ref()
111 .unwrap()
112 .kind,
113 "project"
114 );
115 assert_eq!(card.links.daedalus.as_deref(), Some("https://d"));
116 }
117 }
@@ -0,0 +1,117 @@
1//! Antwoorden van `/mimir/api/cards.php`.
2
3use serde::Deserialize;
4
5use crate::links::CardKind;
6
7#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
8pub struct Card {
9 #[serde(rename = "type")]
10 pub kind: String,
11 pub type_label: String,
12 pub company: String,
13 pub no: String,
14 #[serde(default)]
15 pub title: String,
16 #[serde(default)]
17 pub subtitle: String,
18 #[serde(default)]
19 pub fields: Vec<CardField>,
20 #[serde(default)]
21 pub links: CardLinks,
22}
23
24impl Card {
25 pub fn card_kind(&self) -> Option<CardKind> {
26 CardKind::from_api_name(&self.kind)
27 }
28
29 pub fn field(&self, key: &str) -> Option<&CardField> {
30 self.fields.iter().find(|field| field.key == key)
31 }
32}
33
34#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
35pub struct CardField {
36 pub key: String,
37 pub label: String,
38 pub value: String,
39 /// ISO-datum (`2026-01-15`) bij datumvelden; `value` is al `15 jan 2026`.
40 #[serde(default)]
41 pub date: Option<String>,
42 #[serde(default, rename = "ref")]
43 pub reference: Option<FieldRef>,
44}
45
46#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
47pub struct FieldRef {
48 #[serde(rename = "type")]
49 pub kind: String,
50 pub no: String,
51 #[serde(default)]
52 pub bc_url: String,
53}
54
55#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
56pub struct CardLinks {
57 #[serde(default)]
58 pub bc: String,
59 #[serde(default)]
60 pub daedalus: Option<String>,
61}
62
63#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
64pub struct SearchResult {
65 #[serde(rename = "type")]
66 pub kind: String,
67 pub company: String,
68 pub no: String,
69 #[serde(default)]
70 pub title: String,
71 #[serde(default)]
72 pub subtitle: String,
73 #[serde(default)]
74 pub bc_url: String,
75}
76
77#[derive(Debug, Deserialize)]
78pub(crate) struct CardEnvelope {
79 pub card: Card,
80}
81
82#[derive(Debug, Deserialize)]
83pub(crate) struct SearchEnvelope {
84 pub results: Vec<SearchResult>,
85}
86
87#[derive(Debug, Deserialize)]
88pub(crate) struct CompaniesEnvelope {
89 pub companies: Vec<String>,
90}
91
92#[cfg(test)]
93mod tests {
94 use super::*;
95
96 #[test]
97 fn parses_the_mimir_card_shape() {
98 let json = r#"{"card":{"type":"werkorder","type_label":"Werkorder","company":"Koninklijke van Twist","no":"WO2699001",
99 "title":"Onderhoud 500 uur","subtitle":"Testschip",
100 "fields":[{"key":"Start_Date","label":"Begindatum","value":"15 jan 2026","date":"2026-01-15"},
101 {"key":"Job_No","label":"Project","value":"PRJ2699001","ref":{"type":"project","no":"PRJ2699001","bc_url":"https://x"}}],
102 "links":{"bc":"https://bc","daedalus":"https://d"}},"fetched_at":1}"#;
103 let card = serde_json::from_str::<CardEnvelope>(json).unwrap().card;
104 assert_eq!(card.card_kind(), Some(CardKind::Werkorder));
105 assert_eq!(card.field("Start_Date").unwrap().value, "15 jan 2026");
106 assert_eq!(
107 card.field("Job_No")
108 .unwrap()
109 .reference
110 .as_ref()
111 .unwrap()
112 .kind,
113 "project"
114 );
115 assert_eq!(card.links.daedalus.as_deref(), Some("https://d"));
116 }
117}
crates/kvt-sleutels/src/session.rs added +302 −0
@@ -0,0 +1,302 @@
1 //! Koppelen in de sessiebrowser van rusty-teams in plaats van de systeembrowser.
2 //!
3 //! rusty-teams heeft al een browserprofiel met de Microsoft-sessie (ADR 0003). Als de
4 //! koppelpagina daar in een los tabblad opent, loopt de Entra-SSO van de Login stil
5 //! door. De app klikt dan zelf op «Koppelen» op de toestemmingspagina: de gebruiker
6 //! heeft dat al gedaan met de knop in Instellingen. De Login-pagina, de CSRF-check en
7 //! de loopback-redirect blijven precies zoals bij de systeembrowser; er gaat geen
8 //! Teams- of Graph-token naar de Login.
9 //!
10 //! Vraagt de pagina iets wat alleen de gebruiker kan (accountkeuze, MFA, wachtwoord)
11 //! of loopt het vast, dan geeft [`drive`] [`Outcome::NeedsUser`] en opent de app
12 //! dezelfde koppeling in de systeembrowser.
13
14 use std::future::Future;
15 use std::pin::Pin;
16 use std::time::Duration;
17
18 use serde_json::Value;
19
20 pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
21
22 /// Tabbladen in de sessiebrowser (Linux/macOS: de beheerde Chrome/Firefox).
23 pub trait SessionTabs: Send + Sync {
24 fn open<'a>(&'a self, url: &'a str) -> BoxFuture<'a, Result<String, String>>;
25 fn evaluate<'a>(
26 &'a self,
27 tab: &'a str,
28 expression: &'a str,
29 ) -> BoxFuture<'a, Result<Value, String>>;
30 fn close<'a>(&'a self, tab: &'a str) -> BoxFuture<'a, ()>;
31 }
32
33 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
34 pub enum Outcome {
35 /// De browser is naar de loopback doorgestuurd; [`crate::connect::finish`] krijgt de code.
36 Redirected,
37 /// Hier lukt het niet stil: open de koppeling in de systeembrowser.
38 NeedsUser,
39 }
40
41 #[derive(Debug, Clone, Copy)]
42 pub struct Timing {
43 pub poll: Duration,
44 /// Zo lang mag een Microsoft-loginpagina openstaan voordat we aannemen dat hij
45 /// om invoer vraagt.
46 pub microsoft_grace: Duration,
47 pub total: Duration,
48 }
49
50 impl Default for Timing {
51 fn default() -> Self {
52 Timing {
53 poll: Duration::from_millis(400),
54 microsoft_grace: Duration::from_secs(8),
55 total: Duration::from_secs(45),
56 }
57 }
58 }
59
60 const MICROSOFT_LOGIN_HOSTS: [&str; 3] = [
61 "login.microsoftonline.com",
62 "login.live.com",
63 "login.microsoft.com",
64 ];
65
66 /// Waar staat het tabblad, en staat de knop «Koppelen» van `app_connect.php` er?
67 const PROBE: &str = r#"(() => { const allow = document.querySelector('form[action="app_connect.php"] button[name="decision"][value="allow"]'); return { host: location.hostname, path: location.pathname, allow: !!allow, ready: document.readyState === 'complete' }; })()"#;
68 const APPROVE: &str = r#"(() => { const allow = document.querySelector('form[action="app_connect.php"] button[name="decision"][value="allow"]'); if (!allow) return false; allow.click(); return true; })()"#;
69
70 #[derive(Debug, PartialEq, Eq)]
71 enum Page {
72 Loopback,
73 Consent,
74 Microsoft,
75 Other,
76 }
77
78 fn classify(probe: &Value, sleutels_host: &str) -> Page {
79 let host = probe["host"].as_str().unwrap_or_default();
80 if host == "127.0.0.1" || host == "localhost" {
81 return Page::Loopback;
82 }
83 if host == sleutels_host
84 && probe["path"]
85 .as_str()
86 .unwrap_or_default()
87 .ends_with("/app_connect.php")
88 && probe["allow"] == true
89 {
90 return Page::Consent;
91 }
92 if MICROSOFT_LOGIN_HOSTS.contains(&host) {
93 return Page::Microsoft;
94 }
95 Page::Other
96 }
97
98 /// Open `url` in een tabblad van de sessiebrowser en help de koppeling stil door.
99 /// Sluit het tabblad weer, behalve als het naar de loopback ging (dan sluit de
100 /// aanroeper het zodra de code binnen is, zie [`close_after`]).
101 pub async fn drive(
102 tabs: &dyn SessionTabs,
103 url: &str,
104 sleutels_host: &str,
105 timing: Timing,
106 ) -> (Outcome, Option<String>) {
107 let Ok(tab) = tabs.open(url).await else {
108 return (Outcome::NeedsUser, None);
109 };
110 let started = tokio::time::Instant::now();
111 let mut microsoft_since: Option<tokio::time::Instant> = None;
112 let mut clicked = false;
113 loop {
114 tokio::time::sleep(timing.poll).await;
115 let now = tokio::time::Instant::now();
116 if now - started > timing.total {
117 break;
118 }
119 let Ok(probe) = tabs.evaluate(&tab, PROBE).await else {
120 // Tijdens een navigatie kan evaluate falen; gewoon opnieuw.
121 continue;
122 };
123 match classify(&probe, sleutels_host) {
124 Page::Loopback => return (Outcome::Redirected, Some(tab)),
125 Page::Consent if !clicked && probe["ready"] == true => {
126 clicked = matches!(tabs.evaluate(&tab, APPROVE).await, Ok(Value::Bool(true)));
127 microsoft_since = None;
128 }
129 Page::Consent => microsoft_since = None,
130 Page::Microsoft => {
131 let since = *microsoft_since.get_or_insert(now);
132 if now - since > timing.microsoft_grace {
133 break;
134 }
135 }
136 Page::Other => microsoft_since = None,
137 }
138 }
139 tabs.close(&tab).await;
140 (Outcome::NeedsUser, None)
141 }
142
143 /// Het tabblad sluiten nadat de loopback de code heeft.
144 pub async fn close_after(tabs: &dyn SessionTabs, tab: Option<String>) {
145 if let Some(tab) = tab {
146 tabs.close(&tab).await;
147 }
148 }
149
150 #[cfg(test)]
151 mod tests {
152 use std::sync::Mutex;
153
154 use serde_json::json;
155
156 use super::*;
157
158 /// Speelt een reeks pagina's af; elke evaluate van PROBE schuift één stap op.
159 struct Script {
160 pages: Mutex<Vec<Value>>,
161 log: Mutex<Vec<String>>,
162 open_fails: bool,
163 }
164
165 impl Script {
166 fn new(pages: Vec<Value>) -> Self {
167 Script {
168 pages: Mutex::new(pages),
169 log: Mutex::new(Vec::new()),
170 open_fails: false,
171 }
172 }
173 fn log(&self) -> Vec<String> {
174 self.log.lock().unwrap().clone()
175 }
176 }
177
178 impl SessionTabs for Script {
179 fn open<'a>(&'a self, url: &'a str) -> BoxFuture<'a, Result<String, String>> {
180 self.log.lock().unwrap().push(format!("open {url}"));
181 let fails = self.open_fails;
182 Box::pin(async move {
183 if fails {
184 Err("no browser".into())
185 } else {
186 Ok("tab1".into())
187 }
188 })
189 }
190 fn evaluate<'a>(
191 &'a self,
192 _: &'a str,
193 expression: &'a str,
194 ) -> BoxFuture<'a, Result<Value, String>> {
195 let result = if expression == APPROVE {
196 self.log.lock().unwrap().push("click".into());
197 Ok(Value::Bool(true))
198 } else {
199 let mut pages = self.pages.lock().unwrap();
200 if pages.len() > 1 {
201 Ok(pages.remove(0))
202 } else {
203 pages.first().cloned().ok_or_else(|| "gone".to_owned())
204 }
205 };
206 Box::pin(async move { result })
207 }
208 fn close<'a>(&'a self, tab: &'a str) -> BoxFuture<'a, ()> {
209 self.log.lock().unwrap().push(format!("close {tab}"));
210 Box::pin(async {})
211 }
212 }
213
214 fn page(host: &str, path: &str, allow: bool) -> Value {
215 json!({"host": host, "path": path, "allow": allow, "ready": true})
216 }
217
218 fn fast() -> Timing {
219 Timing {
220 poll: Duration::from_millis(1),
221 microsoft_grace: Duration::from_millis(30),
222 total: Duration::from_millis(500),
223 }
224 }
225
226 #[tokio::test]
227 async fn silent_sso_clicks_connect_once_and_reaches_the_loopback() {
228 let script = Script::new(vec![
229 page("login.microsoftonline.com", "/x/oauth2/authorize", false),
230 page("sleutels.kvt.nl", "/login/app_connect.php", true),
231 page("sleutels.kvt.nl", "/login/app_connect.php", true),
232 page("127.0.0.1", "/kvt-callback", false),
233 ]);
234 let (outcome, tab) = drive(
235 &script,
236 "https://sleutels.kvt.nl/login/app_connect.php?x",
237 "sleutels.kvt.nl",
238 fast(),
239 )
240 .await;
241 assert_eq!(outcome, Outcome::Redirected);
242 assert_eq!(tab.as_deref(), Some("tab1"));
243 assert_eq!(
244 script.log().iter().filter(|line| *line == "click").count(),
245 1
246 );
247 close_after(&script, tab).await;
248 assert_eq!(script.log().last().map(String::as_str), Some("close tab1"));
249 }
250
251 #[tokio::test]
252 async fn a_microsoft_page_that_waits_for_input_falls_back() {
253 let script = Script::new(vec![page(
254 "login.microsoftonline.com",
255 "/common/oauth2/authorize",
256 false,
257 )]);
258 let (outcome, tab) = drive(
259 &script,
260 "https://sleutels.kvt.nl/login/app_connect.php",
261 "sleutels.kvt.nl",
262 fast(),
263 )
264 .await;
265 assert_eq!(outcome, Outcome::NeedsUser);
266 assert!(tab.is_none());
267 assert!(!script.log().contains(&"click".to_owned()));
268 assert_eq!(script.log().last().map(String::as_str), Some("close tab1"));
269 }
270
271 #[tokio::test]
272 async fn never_clicks_on_a_look_alike_host() {
273 let script = Script::new(vec![page(
274 "sleutels.kvt.nl.example.com",
275 "/login/app_connect.php",
276 true,
277 )]);
278 let (outcome, _) = drive(
279 &script,
280 "https://sleutels.kvt.nl/",
281 "sleutels.kvt.nl",
282 fast(),
283 )
284 .await;
285 assert_eq!(outcome, Outcome::NeedsUser);
286 assert!(!script.log().contains(&"click".to_owned()));
287 }
288
289 #[tokio::test]
290 async fn no_session_browser_means_system_browser() {
291 let mut script = Script::new(vec![]);
292 script.open_fails = true;
293 let (outcome, _) = drive(
294 &script,
295 "https://sleutels.kvt.nl/",
296 "sleutels.kvt.nl",
297 fast(),
298 )
299 .await;
300 assert_eq!(outcome, Outcome::NeedsUser);
301 }
302 }
@@ -0,0 +1,302 @@
1//! Koppelen in de sessiebrowser van rusty-teams in plaats van de systeembrowser.
2//!
3//! rusty-teams heeft al een browserprofiel met de Microsoft-sessie (ADR 0003). Als de
4//! koppelpagina daar in een los tabblad opent, loopt de Entra-SSO van de Login stil
5//! door. De app klikt dan zelf op «Koppelen» op de toestemmingspagina: de gebruiker
6//! heeft dat al gedaan met de knop in Instellingen. De Login-pagina, de CSRF-check en
7//! de loopback-redirect blijven precies zoals bij de systeembrowser; er gaat geen
8//! Teams- of Graph-token naar de Login.
9//!
10//! Vraagt de pagina iets wat alleen de gebruiker kan (accountkeuze, MFA, wachtwoord)
11//! of loopt het vast, dan geeft [`drive`] [`Outcome::NeedsUser`] en opent de app
12//! dezelfde koppeling in de systeembrowser.
13
14use std::future::Future;
15use std::pin::Pin;
16use std::time::Duration;
17
18use serde_json::Value;
19
20pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
21
22/// Tabbladen in de sessiebrowser (Linux/macOS: de beheerde Chrome/Firefox).
23pub trait SessionTabs: Send + Sync {
24 fn open<'a>(&'a self, url: &'a str) -> BoxFuture<'a, Result<String, String>>;
25 fn evaluate<'a>(
26 &'a self,
27 tab: &'a str,
28 expression: &'a str,
29 ) -> BoxFuture<'a, Result<Value, String>>;
30 fn close<'a>(&'a self, tab: &'a str) -> BoxFuture<'a, ()>;
31}
32
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub enum Outcome {
35 /// De browser is naar de loopback doorgestuurd; [`crate::connect::finish`] krijgt de code.
36 Redirected,
37 /// Hier lukt het niet stil: open de koppeling in de systeembrowser.
38 NeedsUser,
39}
40
41#[derive(Debug, Clone, Copy)]
42pub struct Timing {
43 pub poll: Duration,
44 /// Zo lang mag een Microsoft-loginpagina openstaan voordat we aannemen dat hij
45 /// om invoer vraagt.
46 pub microsoft_grace: Duration,
47 pub total: Duration,
48}
49
50impl Default for Timing {
51 fn default() -> Self {
52 Timing {
53 poll: Duration::from_millis(400),
54 microsoft_grace: Duration::from_secs(8),
55 total: Duration::from_secs(45),
56 }
57 }
58}
59
60const MICROSOFT_LOGIN_HOSTS: [&str; 3] = [
61 "login.microsoftonline.com",
62 "login.live.com",
63 "login.microsoft.com",
64];
65
66/// Waar staat het tabblad, en staat de knop «Koppelen» van `app_connect.php` er?
67const PROBE: &str = r#"(() => { const allow = document.querySelector('form[action="app_connect.php"] button[name="decision"][value="allow"]'); return { host: location.hostname, path: location.pathname, allow: !!allow, ready: document.readyState === 'complete' }; })()"#;
68const APPROVE: &str = r#"(() => { const allow = document.querySelector('form[action="app_connect.php"] button[name="decision"][value="allow"]'); if (!allow) return false; allow.click(); return true; })()"#;
69
70#[derive(Debug, PartialEq, Eq)]
71enum Page {
72 Loopback,
73 Consent,
74 Microsoft,
75 Other,
76}
77
78fn classify(probe: &Value, sleutels_host: &str) -> Page {
79 let host = probe["host"].as_str().unwrap_or_default();
80 if host == "127.0.0.1" || host == "localhost" {
81 return Page::Loopback;
82 }
83 if host == sleutels_host
84 && probe["path"]
85 .as_str()
86 .unwrap_or_default()
87 .ends_with("/app_connect.php")
88 && probe["allow"] == true
89 {
90 return Page::Consent;
91 }
92 if MICROSOFT_LOGIN_HOSTS.contains(&host) {
93 return Page::Microsoft;
94 }
95 Page::Other
96}
97
98/// Open `url` in een tabblad van de sessiebrowser en help de koppeling stil door.
99/// Sluit het tabblad weer, behalve als het naar de loopback ging (dan sluit de
100/// aanroeper het zodra de code binnen is, zie [`close_after`]).
101pub async fn drive(
102 tabs: &dyn SessionTabs,
103 url: &str,
104 sleutels_host: &str,
105 timing: Timing,
106) -> (Outcome, Option<String>) {
107 let Ok(tab) = tabs.open(url).await else {
108 return (Outcome::NeedsUser, None);
109 };
110 let started = tokio::time::Instant::now();
111 let mut microsoft_since: Option<tokio::time::Instant> = None;
112 let mut clicked = false;
113 loop {
114 tokio::time::sleep(timing.poll).await;
115 let now = tokio::time::Instant::now();
116 if now - started > timing.total {
117 break;
118 }
119 let Ok(probe) = tabs.evaluate(&tab, PROBE).await else {
120 // Tijdens een navigatie kan evaluate falen; gewoon opnieuw.
121 continue;
122 };
123 match classify(&probe, sleutels_host) {
124 Page::Loopback => return (Outcome::Redirected, Some(tab)),
125 Page::Consent if !clicked && probe["ready"] == true => {
126 clicked = matches!(tabs.evaluate(&tab, APPROVE).await, Ok(Value::Bool(true)));
127 microsoft_since = None;
128 }
129 Page::Consent => microsoft_since = None,
130 Page::Microsoft => {
131 let since = *microsoft_since.get_or_insert(now);
132 if now - since > timing.microsoft_grace {
133 break;
134 }
135 }
136 Page::Other => microsoft_since = None,
137 }
138 }
139 tabs.close(&tab).await;
140 (Outcome::NeedsUser, None)
141}
142
143/// Het tabblad sluiten nadat de loopback de code heeft.
144pub async fn close_after(tabs: &dyn SessionTabs, tab: Option<String>) {
145 if let Some(tab) = tab {
146 tabs.close(&tab).await;
147 }
148}
149
150#[cfg(test)]
151mod tests {
152 use std::sync::Mutex;
153
154 use serde_json::json;
155
156 use super::*;
157
158 /// Speelt een reeks pagina's af; elke evaluate van PROBE schuift één stap op.
159 struct Script {
160 pages: Mutex<Vec<Value>>,
161 log: Mutex<Vec<String>>,
162 open_fails: bool,
163 }
164
165 impl Script {
166 fn new(pages: Vec<Value>) -> Self {
167 Script {
168 pages: Mutex::new(pages),
169 log: Mutex::new(Vec::new()),
170 open_fails: false,
171 }
172 }
173 fn log(&self) -> Vec<String> {
174 self.log.lock().unwrap().clone()
175 }
176 }
177
178 impl SessionTabs for Script {
179 fn open<'a>(&'a self, url: &'a str) -> BoxFuture<'a, Result<String, String>> {
180 self.log.lock().unwrap().push(format!("open {url}"));
181 let fails = self.open_fails;
182 Box::pin(async move {
183 if fails {
184 Err("no browser".into())
185 } else {
186 Ok("tab1".into())
187 }
188 })
189 }
190 fn evaluate<'a>(
191 &'a self,
192 _: &'a str,
193 expression: &'a str,
194 ) -> BoxFuture<'a, Result<Value, String>> {
195 let result = if expression == APPROVE {
196 self.log.lock().unwrap().push("click".into());
197 Ok(Value::Bool(true))
198 } else {
199 let mut pages = self.pages.lock().unwrap();
200 if pages.len() > 1 {
201 Ok(pages.remove(0))
202 } else {
203 pages.first().cloned().ok_or_else(|| "gone".to_owned())
204 }
205 };
206 Box::pin(async move { result })
207 }
208 fn close<'a>(&'a self, tab: &'a str) -> BoxFuture<'a, ()> {
209 self.log.lock().unwrap().push(format!("close {tab}"));
210 Box::pin(async {})
211 }
212 }
213
214 fn page(host: &str, path: &str, allow: bool) -> Value {
215 json!({"host": host, "path": path, "allow": allow, "ready": true})
216 }
217
218 fn fast() -> Timing {
219 Timing {
220 poll: Duration::from_millis(1),
221 microsoft_grace: Duration::from_millis(30),
222 total: Duration::from_millis(500),
223 }
224 }
225
226 #[tokio::test]
227 async fn silent_sso_clicks_connect_once_and_reaches_the_loopback() {
228 let script = Script::new(vec![
229 page("login.microsoftonline.com", "/x/oauth2/authorize", false),
230 page("sleutels.kvt.nl", "/login/app_connect.php", true),
231 page("sleutels.kvt.nl", "/login/app_connect.php", true),
232 page("127.0.0.1", "/kvt-callback", false),
233 ]);
234 let (outcome, tab) = drive(
235 &script,
236 "https://sleutels.kvt.nl/login/app_connect.php?x",
237 "sleutels.kvt.nl",
238 fast(),
239 )
240 .await;
241 assert_eq!(outcome, Outcome::Redirected);
242 assert_eq!(tab.as_deref(), Some("tab1"));
243 assert_eq!(
244 script.log().iter().filter(|line| *line == "click").count(),
245 1
246 );
247 close_after(&script, tab).await;
248 assert_eq!(script.log().last().map(String::as_str), Some("close tab1"));
249 }
250
251 #[tokio::test]
252 async fn a_microsoft_page_that_waits_for_input_falls_back() {
253 let script = Script::new(vec![page(
254 "login.microsoftonline.com",
255 "/common/oauth2/authorize",
256 false,
257 )]);
258 let (outcome, tab) = drive(
259 &script,
260 "https://sleutels.kvt.nl/login/app_connect.php",
261 "sleutels.kvt.nl",
262 fast(),
263 )
264 .await;
265 assert_eq!(outcome, Outcome::NeedsUser);
266 assert!(tab.is_none());
267 assert!(!script.log().contains(&"click".to_owned()));
268 assert_eq!(script.log().last().map(String::as_str), Some("close tab1"));
269 }
270
271 #[tokio::test]
272 async fn never_clicks_on_a_look_alike_host() {
273 let script = Script::new(vec![page(
274 "sleutels.kvt.nl.example.com",
275 "/login/app_connect.php",
276 true,
277 )]);
278 let (outcome, _) = drive(
279 &script,
280 "https://sleutels.kvt.nl/",
281 "sleutels.kvt.nl",
282 fast(),
283 )
284 .await;
285 assert_eq!(outcome, Outcome::NeedsUser);
286 assert!(!script.log().contains(&"click".to_owned()));
287 }
288
289 #[tokio::test]
290 async fn no_session_browser_means_system_browser() {
291 let mut script = Script::new(vec![]);
292 script.open_fails = true;
293 let (outcome, _) = drive(
294 &script,
295 "https://sleutels.kvt.nl/",
296 "sleutels.kvt.nl",
297 fast(),
298 )
299 .await;
300 assert_eq!(outcome, Outcome::NeedsUser);
301 }
302}
crates/kvt-sleutels/src/token.rs added +95 −0
@@ -0,0 +1,95 @@
1 //! Het app-token in de keyring van het OS (zoals de CalDAV-wachtwoorden, ADR 0019).
2 //! Nooit in SQLite, logs of diagnostiek.
3
4 use serde::{Deserialize, Serialize};
5
6 const SERVICE: &str = "rusty-teams.kvt-sleutels";
7 const ACCOUNT: &str = "app-token";
8
9 #[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
10 pub struct StoredToken {
11 pub token: String,
12 /// Unix-tijd waarop de Login de token laat verlopen.
13 pub expires_at: i64,
14 #[serde(default)]
15 pub email: String,
16 #[serde(default)]
17 pub name: String,
18 }
19
20 impl std::fmt::Debug for StoredToken {
21 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
22 f.debug_struct("StoredToken")
23 .field("token", &"***")
24 .field("expires_at", &self.expires_at)
25 .field("email", &self.email)
26 .finish()
27 }
28 }
29
30 impl StoredToken {
31 pub fn is_expired(&self, now: i64) -> bool {
32 self.expires_at <= now
33 }
34 }
35
36 fn entry() -> Result<keyring::Entry, String> {
37 keyring::Entry::new(SERVICE, ACCOUNT).map_err(|e| e.to_string())
38 }
39
40 pub fn store(token: &StoredToken) -> Result<(), String> {
41 let json = serde_json::to_string(token).map_err(|e| e.to_string())?;
42 entry()?.set_password(&json).map_err(|e| e.to_string())
43 }
44
45 /// `Ok(None)` als er (nog) niets gekoppeld is.
46 pub fn load() -> Result<Option<StoredToken>, String> {
47 match entry()?.get_password() {
48 Ok(json) => Ok(serde_json::from_str(&json).ok()),
49 Err(keyring::Error::NoEntry) => Ok(None),
50 Err(error) => Err(error.to_string()),
51 }
52 }
53
54 pub fn delete() -> Result<(), String> {
55 match entry()?.delete_credential() {
56 Ok(()) | Err(keyring::Error::NoEntry) => Ok(()),
57 Err(error) => Err(error.to_string()),
58 }
59 }
60
61 pub async fn load_async() -> Result<Option<StoredToken>, String> {
62 tokio::task::spawn_blocking(load)
63 .await
64 .map_err(|e| e.to_string())?
65 }
66
67 pub async fn store_async(token: StoredToken) -> Result<(), String> {
68 tokio::task::spawn_blocking(move || store(&token))
69 .await
70 .map_err(|e| e.to_string())?
71 }
72
73 pub async fn delete_async() -> Result<(), String> {
74 tokio::task::spawn_blocking(delete)
75 .await
76 .map_err(|e| e.to_string())?
77 }
78
79 #[cfg(test)]
80 mod tests {
81 use super::*;
82
83 #[test]
84 fn debug_never_shows_the_token() {
85 let token = StoredToken {
86 token: "sat_geheim".into(),
87 expires_at: 10,
88 email: "a@b".into(),
89 name: String::new(),
90 };
91 assert!(!format!("{token:?}").contains("geheim"));
92 assert!(token.is_expired(10));
93 assert!(!token.is_expired(9));
94 }
95 }
@@ -0,0 +1,95 @@
1//! Het app-token in de keyring van het OS (zoals de CalDAV-wachtwoorden, ADR 0019).
2//! Nooit in SQLite, logs of diagnostiek.
3
4use serde::{Deserialize, Serialize};
5
6const SERVICE: &str = "rusty-teams.kvt-sleutels";
7const ACCOUNT: &str = "app-token";
8
9#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
10pub struct StoredToken {
11 pub token: String,
12 /// Unix-tijd waarop de Login de token laat verlopen.
13 pub expires_at: i64,
14 #[serde(default)]
15 pub email: String,
16 #[serde(default)]
17 pub name: String,
18}
19
20impl std::fmt::Debug for StoredToken {
21 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
22 f.debug_struct("StoredToken")
23 .field("token", &"***")
24 .field("expires_at", &self.expires_at)
25 .field("email", &self.email)
26 .finish()
27 }
28}
29
30impl StoredToken {
31 pub fn is_expired(&self, now: i64) -> bool {
32 self.expires_at <= now
33 }
34}
35
36fn entry() -> Result<keyring::Entry, String> {
37 keyring::Entry::new(SERVICE, ACCOUNT).map_err(|e| e.to_string())
38}
39
40pub fn store(token: &StoredToken) -> Result<(), String> {
41 let json = serde_json::to_string(token).map_err(|e| e.to_string())?;
42 entry()?.set_password(&json).map_err(|e| e.to_string())
43}
44
45/// `Ok(None)` als er (nog) niets gekoppeld is.
46pub fn load() -> Result<Option<StoredToken>, String> {
47 match entry()?.get_password() {
48 Ok(json) => Ok(serde_json::from_str(&json).ok()),
49 Err(keyring::Error::NoEntry) => Ok(None),
50 Err(error) => Err(error.to_string()),
51 }
52}
53
54pub fn delete() -> Result<(), String> {
55 match entry()?.delete_credential() {
56 Ok(()) | Err(keyring::Error::NoEntry) => Ok(()),
57 Err(error) => Err(error.to_string()),
58 }
59}
60
61pub async fn load_async() -> Result<Option<StoredToken>, String> {
62 tokio::task::spawn_blocking(load)
63 .await
64 .map_err(|e| e.to_string())?
65}
66
67pub async fn store_async(token: StoredToken) -> Result<(), String> {
68 tokio::task::spawn_blocking(move || store(&token))
69 .await
70 .map_err(|e| e.to_string())?
71}
72
73pub async fn delete_async() -> Result<(), String> {
74 tokio::task::spawn_blocking(delete)
75 .await
76 .map_err(|e| e.to_string())?
77}
78
79#[cfg(test)]
80mod tests {
81 use super::*;
82
83 #[test]
84 fn debug_never_shows_the_token() {
85 let token = StoredToken {
86 token: "sat_geheim".into(),
87 expires_at: 10,
88 email: "a@b".into(),
89 name: String::new(),
90 };
91 assert!(!format!("{token:?}").contains("geheim"));
92 assert!(token.is_expired(10));
93 assert!(!token.is_expired(9));
94 }
95}
docs/decisions/README.md +1 −0
@@ -39,5 +39,6 @@ Statuses: `proposed`, `accepted`, `superseded`.
39 39 | [0021](0021-linux-packages.md) | Linux releases also ship an AppImage, a deb and an rpm |
40 40 | [0022](0022-linux-parks-the-idle-teams-tab.md) | Linux parks the idle Teams tab in a Chromium browser |
41 41 | [0023](0023-calendar-slot-selection-for-new-meetings.md) | Picking empty calendar slots for a new meeting |
42 | [0024](0024-kvt-cards-and-sleutels-link.md) | KVT fork: Business Central cards through sleutels.kvt.nl |
42 43
43 44 Records `0001` to `0021` are the decisions already shipped. `0001` follows Daniel's call-window note in `GUARDRAILS.md`.
@@ -39,5 +39,6 @@ Statuses: `proposed`, `accepted`, `superseded`.
39| [0021](0021-linux-packages.md) | Linux releases also ship an AppImage, a deb and an rpm |
39| [0021](0021-linux-packages.md) | Linux releases also ship an AppImage, a deb and an rpm |
40| [0022](0022-linux-parks-the-idle-teams-tab.md) | Linux parks the idle Teams tab in a Chromium browser |
40| [0022](0022-linux-parks-the-idle-teams-tab.md) | Linux parks the idle Teams tab in a Chromium browser |
41| [0023](0023-calendar-slot-selection-for-new-meetings.md) | Picking empty calendar slots for a new meeting |
41| [0023](0023-calendar-slot-selection-for-new-meetings.md) | Picking empty calendar slots for a new meeting |
42| [0024](0024-kvt-cards-and-sleutels-link.md) | KVT fork: Business Central cards through sleutels.kvt.nl |
42
43
43Records `0001` to `0021` are the decisions already shipped. `0001` follows Daniel's call-window note in `GUARDRAILS.md`.
44Records `0001` to `0021` are the decisions already shipped. `0001` follows Daniel's call-window note in `GUARDRAILS.md`.