Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
ad92744a94 |
|||
|
2dcbcd35b3 |
|||
|
5d03b2e477 |
|||
|
ed51e62b29 |
69 changed files with 13667 additions and 88 deletions
38
CHANGELOG.md
38
CHANGELOG.md
|
|
@ -1,10 +1,41 @@
|
|||
# Changelog
|
||||
|
||||
## [1.0.8-rc29] - unstable
|
||||
|
||||
### Added
|
||||
|
||||
* [PostIt.Android] Lecture des podcasts directs et replays dans la page
|
||||
video partagee avec le desktop : surface LibVLC native Android et moteur
|
||||
embarque, transport authentifie commun et controles uniques. Liberation
|
||||
du lecteur en arriere-plan ; reouverture du flux au retour dans l'application.
|
||||
|
||||
* [PostIt.Android] Emission depuis la camera et le microphone Android
|
||||
(Android 8 minimum), encodage H.264/AAC natif et segmentation MPEG-TS
|
||||
sur images cles. Interface, envoi authentifie, retries et finalisation
|
||||
du replay partages avec le desktop. Service de premier plan avec
|
||||
notification d'arret et maintien de la capture en arriere-plan.
|
||||
|
||||
### Changed
|
||||
|
||||
* [PostIt] Mise a jour d'Avalonia vers 12.1.4.
|
||||
|
||||
|
||||
## [1.0.8-rc28] - unstable
|
||||
|
||||
|
||||
### Added
|
||||
|
||||
* [Yavsc.Api, Yavsc.Server, Yavsc.Api.Client] Creation explicite et
|
||||
idempotente d'une facture depuis un devis doublement signe, avec lignes,
|
||||
total et parties figes. Historique des encaissements hors ligne attestes
|
||||
par le prestataire et des transactions PayPal verifiees cote serveur ;
|
||||
references uniques, cumul atomique et protection contre les ecritures
|
||||
concurrentes. Routes documentees, client HTTP et migration associes.
|
||||
|
||||
* [Yavsc.Abstract, Yavsc.Server] Modele de solde des commandes facturables :
|
||||
montants dus et payes persistants, reste a payer et etats non paye,
|
||||
partiellement paye ou acquitte. L'acquittement depend des montants,
|
||||
et non du seul statut PayPal ; migration sans montant historique invente.
|
||||
|
||||
* [PostIt.Desktop, Yavsc.Api] Podcasts en direct avec replay HLS conserve :
|
||||
capture camera et microphone par LibVLC (H.264/AAC, segments MPEG-TS),
|
||||
envoi ordonne et idempotent, catalogue et lecture authentifiee dans PostIt.
|
||||
|
|
@ -15,6 +46,11 @@
|
|||
|
||||
### Fixed
|
||||
|
||||
* [Facturation] Les commandes facturees et leur devis ne peuvent plus etre
|
||||
supprimes via les routes de commande usuelles. Les additions distinguent
|
||||
montant verse, solde restant et acquittement ; les anciennes routes de
|
||||
generation exigent une facture etablie depuis un devis signe.
|
||||
|
||||
## [1.0.8-rc27] - unstable
|
||||
|
||||
### Added
|
||||
|
|
|
|||
81
INSTALL.md
81
INSTALL.md
|
|
@ -140,6 +140,87 @@ reads a replay from its beginning; seeking is not implemented. Native
|
|||
camera/microphone permissions, drivers and codecs must still be verified
|
||||
on each target Windows/Linux machine.
|
||||
|
||||
### Android podcasts
|
||||
|
||||
The Android APK bundles LibVLC and uses a native Android video surface inside
|
||||
the same Avalonia video page as desktop. Catalogue, playback controls and
|
||||
authenticated segment downloads are shared; no external browser, public media
|
||||
URL or camera/microphone permissions are needed to watch a podcast.
|
||||
|
||||
Leaving the app stops playback and cancels downloads. Returning recreates the
|
||||
player: a replay starts from the beginning, and a live stream rejoins near the
|
||||
live edge. Seeking and background audio are not supported.
|
||||
|
||||
Broadcasting requires **Android 8 (API 26) or newer**. In the shared podcast
|
||||
page, detect devices, select front/rear camera and optionally the microphone,
|
||||
then start the live broadcast while PostIt is visible. Camera permission,
|
||||
microphone permission when selected, and notification permission on Android 13+
|
||||
must be granted. A permission denial is reported in the page without starting
|
||||
capture or creating a server broadcast. Permissions are requested before the
|
||||
server session is created so a long permission dialog cannot expire it.
|
||||
Watching does not request these permissions.
|
||||
|
||||
Android uses Camera2 and its native MediaRecorder H.264/AAC encoder, up to 480p at 30 fps,
|
||||
not the desktop LibVLC camera inputs or software encoders. MPEG-TS is segmented
|
||||
at IDR frames, with timestamps used for segment durations. Closed segments
|
||||
enter the same ordered upload/retry/quota/replay pipeline as desktop.
|
||||
Devices without a supported camera/encoder report a startup error.
|
||||
|
||||
A camera/microphone foreground service and a partial wake lock maintain the
|
||||
broadcast when PostIt is backgrounded or the screen locks. Its ongoing
|
||||
notification returns to the app and offers **Arreter et publier**. Stopping
|
||||
flushes the final segment before completing the replay. Leaving the podcast
|
||||
page or logging out still stops capture. Android's explicit service stop,
|
||||
process termination or application restart does not automatically restart a
|
||||
camera; segments already received by the server remain available under the
|
||||
interrupted-replay rules above. Device power policies can impose additional
|
||||
restrictions and must be tested on the intended physical devices.
|
||||
|
||||
**Native library limitation:** bundled `VideoLAN.LibVLC.Android` 3.6.5 emits
|
||||
`XA0141`: its native libraries are not aligned for 16 KiB memory pages.
|
||||
Playback on 16 KiB-page devices and store distribution requiring this alignment
|
||||
are not validated/supported by this package choice. A compatible native LibVLC
|
||||
release is required before claiming that support; a successful APK build or
|
||||
a test on a 4 KiB-page emulator does not establish it.
|
||||
|
||||
Build with the Android workload and SDK configured:
|
||||
|
||||
```bash
|
||||
dotnet build src/PostIt/PostIt.Android/PostIt.Android.csproj
|
||||
```
|
||||
|
||||
On an Android device, verify replay video/audio, live playback, pause/resume,
|
||||
rotation, Back navigation and returning after backgrounding the app. Also
|
||||
verify an expired session or interrupted network reports a playback error.
|
||||
For broadcasting, test front/rear cameras, microphone enabled/disabled,
|
||||
permission denial, screen lock, background capture, notification stop and the
|
||||
final replay. No automatic retry of a denied permission or a killed camera
|
||||
service is performed.
|
||||
|
||||
The Debug APK includes a local native-capture test activity (excluded from
|
||||
Release); it does not create a server podcast. On a dedicated emulator, grant
|
||||
camera, audio and notification permissions, then run:
|
||||
|
||||
```bash
|
||||
adb shell am start -W -f 0x18000000 -n fr.pschneider.postit/fr.pschneider.postit.PodcastCaptureTestActivity
|
||||
# Wait about 20 seconds for foreground/background recording and final flush.
|
||||
adb shell run-as fr.pschneider.postit cat files/podcast-capture-test-result.txt
|
||||
# Repeat with the second camera, no audio, and the notification stop action:
|
||||
adb shell am start -W -f 0x18000000 -n fr.pschneider.postit/fr.pschneider.postit.PodcastCaptureTestActivity --es microphone false --es camera front --es notificationStop true
|
||||
```
|
||||
|
||||
The result reports the segment count, the background progress and the private
|
||||
recording directory under `files/podcast-capture-tests`. Recordings remain
|
||||
there for local decoder inspection and can be removed after the test.
|
||||
|
||||
The implementation was checked on an Android 16 x64 emulator with 4 KiB
|
||||
pages: camera/microphone capture produced five independently decodable
|
||||
H.264/AAC segments across foreground/background operation; the second camera
|
||||
without audio produced six decodable H.264 segments, including screen-off
|
||||
operation and stop through the notification action. The foreground service
|
||||
was gone after both tests. These local tests do not replace an authenticated
|
||||
Android-to-server broadcast/replay test or validation on physical devices.
|
||||
|
||||
## Resources
|
||||
|
||||
System resources needed to install.
|
||||
|
|
|
|||
299
doc/invoicing.md
Normal file
299
doc/invoicing.md
Normal file
|
|
@ -0,0 +1,299 @@
|
|||
# Facturation et paiement après devis signé
|
||||
|
||||
## Objectif
|
||||
|
||||
Ce document fixe le plan métier et technique pour le flux qui suit la validation du devis :
|
||||
|
||||
- le devis est signé par les deux parties,
|
||||
- le prestataire déclenche la création d'une facture non acquittée,
|
||||
- la facture contient la ligne associée au mode de paiement choisi par le prestataire,
|
||||
- le client règle le montant partiel ou total,
|
||||
- la facture reste non acquittée tant que le total n'est pas intégralement payé.
|
||||
|
||||
## Règle métier de base
|
||||
|
||||
1. Le devis n'est considéré comme valide que lorsqu'il est signé par le fournisseur et par le client.
|
||||
2. Une facture ne peut être générée qu'après cette double validation.
|
||||
3. Le type de contrat choisi dans les settings du prestataire détermine le mode de règlement :
|
||||
- arrhes,
|
||||
- avance,
|
||||
- ou autre mode de facturation supporté par le système.
|
||||
4. Le montant payé partiellement est enregistré comme paiement partiel, sans transformer la facture en facture entièrement payée.
|
||||
5. La facture est marquée comme acquittée uniquement lorsque le montant total est effectivement réglé.
|
||||
6. L'addition / le relevé de paiement doit mentionner le paiement effectué, sans prétendre que la facture est déjà entièrement acquittée.
|
||||
|
||||
## Flux attendu
|
||||
|
||||
### 1. Devis signé par les deux parties
|
||||
|
||||
Le flux contractuel suit la séquence :
|
||||
|
||||
- commande / demande,
|
||||
- devis préparé,
|
||||
- validation prestataire,
|
||||
- validation client,
|
||||
- double signature persistée.
|
||||
|
||||
Une fois cette étape passée, le devis est un contrat exploitable pour la facture.
|
||||
|
||||
### 2. Génération de la facture non acquittée
|
||||
|
||||
Le prestataire déclenche la création de la facture depuis le contexte du devis validé.
|
||||
|
||||
Le système doit alors :
|
||||
|
||||
- identifier le devis validé,
|
||||
- récupérer le client et le prestataire,
|
||||
- sélectionner le mode de contrat défini dans les settings du prestataire,
|
||||
- ajouter la ligne de frais correspondante à la facture,
|
||||
- créer la facture dans un état "non acquittée".
|
||||
|
||||
### 3. Paiement partiel
|
||||
|
||||
Le client peut payer en premier :
|
||||
|
||||
- l'avance,
|
||||
- les arrhes,
|
||||
- ou une tranche partielle.
|
||||
|
||||
Dans ce cas :
|
||||
|
||||
- le paiement est enregistré,
|
||||
- le montant payé est ajouté au total enregistré,
|
||||
- la facture reste "non acquittée" tant qu'elle n'a pas été réglée intégralement,
|
||||
- l'addition doit refléter la transaction effectuée sans annoncer un paiement total abusif.
|
||||
|
||||
### 4. Acquittement total
|
||||
|
||||
Lorsque le client a payé la somme totale due :
|
||||
|
||||
- le statut de la facture passe à "payée" / "acquittée",
|
||||
- la facture peut être considérée comme totalement soldée,
|
||||
- la génération de documents ou notifications finales peut s'appuyer sur cet état.
|
||||
|
||||
## Règles de codage à respecter
|
||||
|
||||
### Règle 1 — ne pas confondre paiement partiel et paiement total
|
||||
|
||||
Le modèle de paiement ne doit pas se limiter à un booléen "payé / non payé".
|
||||
|
||||
Le bon niveau de modélisation est :
|
||||
|
||||
- montant dû,
|
||||
- montant payé,
|
||||
- montant restant,
|
||||
- statut de paiement partiel / total,
|
||||
- état d'acquittement final.
|
||||
|
||||
### Règle 2 — la facture ne doit pas être "payée" trop tôt
|
||||
|
||||
Le système ne doit pas marquer la facture comme entièrement payée à la première transaction.
|
||||
|
||||
L'état métier doit être calculé de manière explicite :
|
||||
|
||||
- `montantPaye < montantTotal` => facture non acquittée,
|
||||
- `montantPaye >= montantTotal` => facture acquittée (reste à payer borné à zéro).
|
||||
|
||||
### Règle 3 — les arrhes / avances doivent rester cohérents avec le contexte contractuel
|
||||
|
||||
Le mode choisi par le prestataire (arrhes ou avance) doit être représenté de façon explicite dans le flux de génération de facture et dans l'addition.
|
||||
|
||||
Le comportement attendu est :
|
||||
|
||||
- la ligne de frais correspondante est ajoutée à la facture,
|
||||
- le paiement initial est comptabilisé correctement,
|
||||
- le solde restant reste visible et exploitable.
|
||||
|
||||
## Plan d'implémentation proposé
|
||||
|
||||
### Étape 1 — modéliser les règles de paiement
|
||||
|
||||
Implémentée sur le point d'entrée existant `IBillable` /
|
||||
`NominativeServiceCommand`, sans créer encore d'entité Facture distincte :
|
||||
|
||||
- `AmountDue` et `AmountPaid` sont persistés sur la commande ; le montant dû
|
||||
reste `null` tant que le total de facture n'a pas été établi.
|
||||
- `SetPaymentAmounts(amountDue, amountPaid)` définit un instantané validé
|
||||
des montants (décimaux non négatifs), côté métier uniquement. Les setters
|
||||
privés empêchent leur alimentation par les requêtes de modification de commande.
|
||||
- `PaymentSummary` expose les montants dû, payé et restant, ainsi que
|
||||
`Unpaid`, `PartiallyPaid` ou `Paid` ; il est absent si le montant dû est inconnu.
|
||||
- Le restant est borné à zéro en cas de trop-perçu, sans perdre le montant payé.
|
||||
L'acquittement est atteint si `AmountPaid >= AmountDue`. Une facture
|
||||
explicitement établie à zéro est soldée ; un montant inconnu ne l'est pas.
|
||||
- `GetIsAcquitted()` et le suffixe documentaire `-ack` utilisent ce calcul,
|
||||
jamais le seul statut PayPal `SUCCESS`.
|
||||
|
||||
La migration ajoute les montants sans reconstituer de paiements historiques :
|
||||
les anciennes commandes ont un dû inconnu et un payé nul. Un rapprochement
|
||||
explicite est nécessaire avant de les considérer comme acquittées.
|
||||
La génération depuis le devis et l'alimentation du payé sont désormais
|
||||
branchées par le service `InvoicingService` (étapes 2 et 4 ci-dessous).
|
||||
L'appel `SetPaymentAmounts` remplace un total cumulé ; il n'enregistre pas
|
||||
une transaction et ne doit pas être utilisé pour additionner un retour PayPal
|
||||
sans contrôle d'idempotence.
|
||||
|
||||
Objectifs couverts :
|
||||
|
||||
- identifier le point d'entrée métier de la facture,
|
||||
- ajouter un modèle de montant dû / montant payé / montant restant,
|
||||
- distinguer clairement l'état partiel du statut de paiement total,
|
||||
- éviter toute logique qui force un booléen `IsPaid = true` dès le premier paiement.
|
||||
|
||||
### Étape 2 — brancher la génération de facture sur le devis signé
|
||||
|
||||
Implémentée par `POST /api/v1/invoices/from-estimate/{estimateId}` :
|
||||
|
||||
- réservée au prestataire du devis (ou à un administrateur) ;
|
||||
- exige les deux dates de validation **et** les deux signatures persistées,
|
||||
non vides, associées aux bons signataires ; une date seule ne suffit pas ;
|
||||
- exige une commande existante, dont le client et le prestataire correspondent
|
||||
au devis ; les devis sans commande restent des devis, non des factures ;
|
||||
- copie les lignes du devis, sa devise EUR, son total et ses parties dans
|
||||
un instantané de facture sur la commande, daté côté serveur ;
|
||||
- accepte les remises mais refuse un total négatif, les quantités non positives,
|
||||
les prix infra-centime et les devis multidevises ;
|
||||
- initialise le payé à zéro, sans assimiler un ancien checkout à un encaissement ;
|
||||
- renvoie la même facture lors d'un nouvel appel pour le même devis, sans
|
||||
changer le total ou effacer les paiements ; une autre facture ou un solde
|
||||
historique préexistant sur la commande provoque un conflit de rapprochement.
|
||||
|
||||
`GET /api/v1/invoices/{commandId}` expose l'instantané et l'historique aux
|
||||
parties de la facture et aux administrateurs. Les statuts sont des chaînes
|
||||
`Unpaid`, `PartiallyPaid` et `Paid`. Les lignes utilisées par `GetBillItems()`
|
||||
sont celles de la facture figée, même si le devis est modifié ensuite.
|
||||
Les commandes facturées et leurs devis ne sont plus supprimables par les
|
||||
routes de commande concernées. Le changement de prestataire est bloqué sur
|
||||
les routes usuelles de modification ; l'instantané reste la référence des parties.
|
||||
|
||||
Cette création établit la facture métier et ses montants, **pas un PDF** :
|
||||
le moteur historique de rendu documentaire reste distinct. Ses routes de
|
||||
génération exigent désormais une facture établie.
|
||||
|
||||
### Étape 3 — intégrer le mode de contrat du prestataire
|
||||
|
||||
- lire le setting du prestataire qui indique le type de contrat,
|
||||
- associer ce mode à la ligne de frais ajoutée sur la facture,
|
||||
- garantir que la ligne peut être différenciée selon arrhes ou avance.
|
||||
|
||||
### Étape 4 — enregistrer les paiements sans surinterpréter le statut
|
||||
|
||||
Implémentée par deux sources d'encaissement, sans débit déclenché par ces routes :
|
||||
|
||||
| Route POST sous `/api/v1/invoices/{commandId}` | Source de vérité | Accès |
|
||||
| --- | --- | --- |
|
||||
| `/payments/offline` | Attestation du prestataire : référence, montant, devise, date de réception | Prestataire ou administrateur |
|
||||
| `/payments/paypal` | Réponse serveur PayPal `GetTransactionDetails` pour un identifiant de transaction | Parties ou administrateur |
|
||||
|
||||
Le reçu hors ligne doit être strictement positif, en centimes EUR, avec une
|
||||
référence non vide et une date non future. Il est attesté, pas vérifié auprès
|
||||
de la banque. La référence est unique par prestataire ; le client ne peut
|
||||
pas s'auto-déclarer acquitté.
|
||||
|
||||
Pour PayPal, seul l'identifiant est accepté du client. Le serveur vérifie :
|
||||
|
||||
- statut `Completed`, et non un simple `ACK=Success` ou un statut `Pending` ;
|
||||
- identifiant exact, référence de facture `TypeCommande/Id` (`INVNUM`),
|
||||
devise de la facture et compte marchand destinataire (`RECEIVERID`) ;
|
||||
- montant brut reçu strictement positif et date retournés par PayPal.
|
||||
|
||||
Le token de checkout historique n'est **pas** un identifiant de transaction.
|
||||
Le retour historique `ConfirmPayment` ne constitue toujours pas une preuve
|
||||
d'encaissement et n'alimente pas le solde. Cette intégration vérifie des
|
||||
transactions déjà encaissées ; elle n'ajoute ni capture, ni webhook, ni
|
||||
automatisation du retour navigateur. Le protocole NVP reprend le système
|
||||
Classic déjà utilisé par le dépôt ; il est déprécié par PayPal et réservé
|
||||
aux marchands existants compatibles.
|
||||
|
||||
Chaque encaissement conserve sa référence, son origine, son montant, sa
|
||||
devise, ses dates de réception/enregistrement et l'identifiant de l'acteur.
|
||||
La référence PayPal est unique globalement : une même transaction ne peut
|
||||
pas solder deux factures. Rejouer un reçu identique ne l'ajoute pas deux fois ;
|
||||
réutiliser sa référence avec d'autres détails renvoie `409`.
|
||||
|
||||
L'ajout au journal et la mise à jour du total payé sont sauvegardés dans la
|
||||
même transaction EF relationnelle. Un jeton de concurrence sur la commande
|
||||
empêche les pertes de mise à jour. En cas de conflit concurrent, la route
|
||||
renvoie `409` : rejouer **la même référence et le même corps** permet de
|
||||
réessayer sans double comptage. Un solde ne correspondant pas au journal
|
||||
requiert un rapprochement, sans réinitialisation silencieuse.
|
||||
|
||||
Le solde est calculé à partir des reçus cumulés. Un paiement partiel garde
|
||||
la facture non acquittée ; un trop-perçu est conservé avec un restant nul.
|
||||
Le texte de l'addition affiche payé, restant et statut.
|
||||
|
||||
#### Configuration et utilisation
|
||||
|
||||
Appliquer la migration `SignedEstimateInvoicing` avant déploiement.
|
||||
Elle ajoute l'instantané, le jeton de concurrence et le journal `InvoicePayments`,
|
||||
sans créer de facture ni de reçu pour les données historiques.
|
||||
|
||||
La vérification PayPal utilise la section `Authentication:PayPal` :
|
||||
`Mode` (`sandbox` ou `production`), `MerchantAccountId` et
|
||||
`MerchantAccountUserName`. Une entrée de `Accounts` doit correspondre à ce
|
||||
dernier via `ApiUsername`, avec `ApiPassword` et `Signature`.
|
||||
Conserver les identifiants dans les secrets ou l'environnement, jamais dans
|
||||
un fichier versionné. Sans configuration exploitable, la route renvoie `503`
|
||||
sans enregistrer de paiement ; une panne ou une réponse invalide PayPal
|
||||
renvoie `502`/`504`, sans modifier le solde.
|
||||
|
||||
Le client partagé `InvoicesApiClient` expose les quatre opérations.
|
||||
Le document `/openapi/invoicing.json` est réservé aux administrateurs en
|
||||
développement, comme les autres documents OpenAPI du serveur.
|
||||
Des exemples de requêtes sont fournis dans `src/Yavsc.Api/Invoicing.http` ;
|
||||
adapter l'adresse du serveur et les jetons. Aucun écran PostIt n'est ajouté
|
||||
dans ce lot.
|
||||
|
||||
### Étape 5 — finaliser l'état acquitté
|
||||
|
||||
- calculer le total payé,
|
||||
- si `totalPaye >= totalDu`, alors passer la facture en état acquittée,
|
||||
- envoyer les notifications / documents associés au cas échéant.
|
||||
|
||||
Le calcul du statut est branché aux encaissements. Les notifications finales,
|
||||
le rendu documentaire, les remboursements/annulations de reçus et les
|
||||
rapprochements historiques restent hors de ce lot, tout comme l'étape 3.
|
||||
Un remboursement ou litige ultérieur n'est pas synchronisé automatiquement :
|
||||
ne pas utiliser ce journal d'encaissements comme gestion complète des
|
||||
remboursements PayPal.
|
||||
|
||||
## Tests à couvrir
|
||||
|
||||
Les tests implémentés du backend s'exécutent avec le runner MTP du dépôt :
|
||||
|
||||
```bash
|
||||
dotnet test --project src/test/Yavsc.Api.Tests/Yavsc.Api.Tests.csproj \
|
||||
--filter-class '*InvoiceApiTests' --filter-class '*HairCutQueryApiControllerTests'
|
||||
dotnet test --project src/test/Yavsc.Server.Tests/Yavsc.Server.Tests.csproj \
|
||||
--filter-class '*PaymentSummaryTests' --filter-class '*PayPalTransactionVerifierTests'
|
||||
dotnet test --project src/PostIt/PostIt.Tests/PostIt.Tests.csproj \
|
||||
--filter-class '*InvoicesApiClientTests'
|
||||
```
|
||||
|
||||
Les tests HTTP utilisent la base relationnelle isolée de la fixture.
|
||||
Ils vérifient notamment qu'un ajout concurrent perdant est entièrement
|
||||
annulé (journal et total), puis rejouable. Les tests PayPal utilisent des
|
||||
réponses HTTP simulées, sans identifiants réels ni appel au prestataire.
|
||||
Ils ne remplacent pas une recette sandbox sur un compte Classic compatible.
|
||||
|
||||
Le flux doit être validé par des tests ciblés sur :
|
||||
|
||||
- devis signé par les deux parties → génération d'une facture non acquittée,
|
||||
- mode arrhes / avance → ligne de frais correctement ajoutée,
|
||||
- paiement partiel → montant enregistré sans statut payé complet,
|
||||
- paiement total → facture marquée acquittée,
|
||||
- addition / message de paiement → mention du montant réellement versé sans faux état d'acquittement complet.
|
||||
|
||||
## Critère de sortie fonctionnel
|
||||
|
||||
Le comportement attendu est considéré comme atteint si le scénario suivant est vérifié :
|
||||
|
||||
1. le devis est doublé signé,
|
||||
2. le prestataire génère une facture non acquittée,
|
||||
3. le client paye une avance ou des arrhes,
|
||||
4. la facture reste non acquittée tant qu'elle n'est pas totalement soldée,
|
||||
5. la facture devient acquittée uniquement lorsque le total est réglé.
|
||||
|
||||
## Note de contexte
|
||||
|
||||
Ce document consolide la décision métier issue du workflow “Prestation / devis” et est volontairement limité au périmètre de la facturation et du paiement après signature du devis. Il ne remplace pas les règles plus larges de gestion des litiges, workflows d'annulation ou paiements transverses déjà documentés ailleurs.
|
||||
|
|
@ -4,7 +4,7 @@
|
|||
<!-- https://learn.microsoft.com/en-us/nuget/consume-packages/central-package-management -->
|
||||
<PropertyGroup>
|
||||
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
|
||||
<AvaloniaVersionBase>12.1.3</AvaloniaVersionBase>
|
||||
<AvaloniaVersionBase>12.1.4</AvaloniaVersionBase>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageVersion Include="Avalonia" Version="$(AvaloniaVersionBase)" />
|
||||
|
|
@ -13,11 +13,13 @@
|
|||
<PackageVersion Include="Avalonia.Desktop" Version="$(AvaloniaVersionBase)" />
|
||||
<PackageVersion Include="Avalonia.Browser" Version="$(AvaloniaVersionBase)" />
|
||||
<PackageVersion Include="Avalonia.Android" Version="$(AvaloniaVersionBase)" />
|
||||
<PackageVersion Include="Avalonia.Headless" Version="12.1.3" />
|
||||
<PackageVersion Include="Avalonia.Headless" Version="12.1.4" />
|
||||
<PackageVersion Include="Avalonia.Headless.Xunit" Version="$(AvaloniaVersionBase)" />
|
||||
<PackageVersion Include="Avalonia.Fonts.Inter" Version="$(AvaloniaVersionBase)" />
|
||||
<PackageVersion Include="DirectShowLib" Version="1.0.0" />
|
||||
<PackageVersion Include="LibVLCSharp.Avalonia" Version="3.10.2" />
|
||||
<PackageVersion Include="LibVLCSharp" Version="3.10.2" />
|
||||
<PackageVersion Include="VideoLAN.LibVLC.Android" Version="3.6.5" />
|
||||
<PackageVersion Include="Live.Avalonia" Version="1.4.2" />
|
||||
<PackageVersion Include="Mapsui" Version="5.1.0" />
|
||||
<PackageVersion Include="Mapsui.Avalonia12" Version="5.1.0" />
|
||||
|
|
|
|||
|
|
@ -25,6 +25,7 @@ public class MainActivity : AvaloniaMainActivity
|
|||
/// The current MainActivity instance.
|
||||
/// </summary>
|
||||
public static MainActivity? Current { get; private set; }
|
||||
internal static bool IsForeground { get; private set; }
|
||||
|
||||
protected override void OnCreate(global::Android.OS.Bundle? savedInstanceState)
|
||||
{
|
||||
|
|
@ -36,8 +37,8 @@ public class MainActivity : AvaloniaMainActivity
|
|||
EmojiCompat.Config config = new FontRequestEmojiCompatConfig(this, fontRequest);
|
||||
EmojiCompat.Init(config);
|
||||
PlatformBootstrap.InitPlatform();
|
||||
base.OnCreate(savedInstanceState);
|
||||
Current = this;
|
||||
base.OnCreate(savedInstanceState);
|
||||
}
|
||||
/// <summary>
|
||||
/// Receives the deep-link Intent fired by the system browser after the
|
||||
|
|
@ -60,9 +61,34 @@ public class MainActivity : AvaloniaMainActivity
|
|||
|
||||
}
|
||||
|
||||
public override void OnRequestPermissionsResult(int requestCode, string[]? permissions, Permission[]? grantResults)
|
||||
protected override void OnStop()
|
||||
{
|
||||
if (PostIt.Android.Services.AndroidCurrentLocationProvider
|
||||
PostIt.Services.Platform.SuspendPlayback();
|
||||
base.OnStop();
|
||||
}
|
||||
|
||||
protected override void OnResume()
|
||||
{
|
||||
base.OnResume();
|
||||
IsForeground = true;
|
||||
}
|
||||
|
||||
protected override void OnPause()
|
||||
{
|
||||
IsForeground = false;
|
||||
base.OnPause();
|
||||
}
|
||||
|
||||
protected override void OnRestart()
|
||||
{
|
||||
base.OnRestart();
|
||||
PostIt.Services.Platform.ResumePlayback();
|
||||
}
|
||||
|
||||
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults)
|
||||
{
|
||||
if (PostIt.Android.Services.PodcastPermissions.HandleResult(requestCode, permissions, grantResults)
|
||||
|| PostIt.Android.Services.AndroidCurrentLocationProvider
|
||||
.HandlePermissionResult(requestCode, grantResults))
|
||||
{
|
||||
return;
|
||||
|
|
|
|||
|
|
@ -21,5 +21,12 @@ internal static class PlatformBootstrap
|
|||
};
|
||||
|
||||
Platform.TryGetCurrentLocationAsync = AndroidCurrentLocationProvider.TryGetCurrentLocationAsync;
|
||||
Platform.CreateVideoSurface = player => new AndroidVideoSurface(player);
|
||||
if (System.OperatingSystem.IsAndroidVersionAtLeast(26))
|
||||
{
|
||||
Platform.GetPodcastCaptureDevices = AndroidPodcastCapture.GetDevices;
|
||||
Platform.RequestPodcastPermissionsAsync = AndroidPodcastCapture.RequestPermissionsAsync;
|
||||
Platform.CreatePodcastCaptureAsync = AndroidPodcastCapture.StartAsync;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -21,12 +21,17 @@
|
|||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Avalonia.Android" />
|
||||
<PackageReference Include="LibVLCSharp" />
|
||||
<PackageReference Include="VideoLAN.LibVLC.Android" />
|
||||
<PackageReference Include="Xamarin.AndroidX.Core.SplashScreen" />
|
||||
<PackageReference Include="Xamarin.AndroidX.Browser" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\PostIt\PostIt.csproj" />
|
||||
</ItemGroup>
|
||||
<ItemGroup Condition="'$(Configuration)' == 'Debug'">
|
||||
<Compile Include="..\PostIt.Tests\AndroidPodcastCaptureTestActivity.cs" Link="Tests\AndroidPodcastCaptureTestActivity.cs" />
|
||||
</ItemGroup>
|
||||
<!-- This is an Avalonia app, not a MAUI app: exclude the .NET MAUI VS Code
|
||||
extension's injected HotReload agent (references Microsoft.Maui.*).
|
||||
The agent file is added via CustomAfterMicrosoftCommonTargets, i.e. after
|
||||
|
|
|
|||
|
|
@ -1,6 +1,15 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:installLocation="auto">
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.CAMERA" />
|
||||
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_CAMERA" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" />
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<uses-feature android:name="android.hardware.camera" android:required="false" />
|
||||
<uses-feature android:name="android.hardware.microphone" android:required="false" />
|
||||
<application
|
||||
android:label="PostIt"
|
||||
android:icon="@drawable/Icon"
|
||||
|
|
|
|||
309
src/PostIt/PostIt.Android/Services/AndroidPodcastCapture.cs
Normal file
309
src/PostIt/PostIt.Android/Services/AndroidPodcastCapture.cs
Normal file
|
|
@ -0,0 +1,309 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Runtime.Versioning;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Android.Content;
|
||||
using Android.Hardware.Camera2;
|
||||
using Android.Hardware.Camera2.Params;
|
||||
using Android.Media;
|
||||
using Android.OS;
|
||||
using Android.Views;
|
||||
using Microsoft.Win32.SafeHandles;
|
||||
using PostIt.Services;
|
||||
|
||||
namespace PostIt.Android.Services;
|
||||
|
||||
[SupportedOSPlatform("android26.0")]
|
||||
internal sealed class AndroidPodcastCapture : IPodcastCapture
|
||||
{
|
||||
private readonly PodcastCaptureService _service;
|
||||
private readonly SemaphoreSlim _stopGate = new(1);
|
||||
private readonly TaskCompletionSource _completion = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
private readonly Handler _handler = new(Looper.MainLooper!);
|
||||
private CameraDevice? _camera;
|
||||
private CameraCaptureSession? _session;
|
||||
private MediaRecorder? _recorder;
|
||||
private Surface? _surface;
|
||||
private ParcelFileDescriptor? _readPipe;
|
||||
private ParcelFileDescriptor? _writePipe;
|
||||
private Task _pump = Task.CompletedTask;
|
||||
private Exception? _failure;
|
||||
private bool _stopped;
|
||||
private bool _stopRequested;
|
||||
private bool _started;
|
||||
private bool _disposed;
|
||||
public Task Completion => _completion.Task;
|
||||
|
||||
private AndroidPodcastCapture(PodcastCaptureService service) => _service = service;
|
||||
|
||||
private static CameraManager GetManager(Context context)
|
||||
=> context.GetSystemService(Context.CameraService) as CameraManager
|
||||
?? throw new InvalidOperationException("Service camera Android indisponible.");
|
||||
|
||||
public static PodcastCaptureDevices GetDevices()
|
||||
{
|
||||
var activity = MainActivity.Current ?? throw new InvalidOperationException("Activite Android indisponible.");
|
||||
var manager = GetManager(activity);
|
||||
var cameras = new List<CaptureDevice>();
|
||||
foreach (var id in manager.GetCameraIdList())
|
||||
{
|
||||
using var characteristics = manager.GetCameraCharacteristics(id);
|
||||
using var facing = characteristics.Get(CameraCharacteristics.LensFacing) as Java.Lang.Integer;
|
||||
cameras.Add(new(facing?.IntValue() == (int)LensFacing.Front ? "Camera avant" : "Camera arriere", id));
|
||||
}
|
||||
return new(cameras, [new("Sans microphone", ""), new("Microphone Android", "microphone")]);
|
||||
}
|
||||
|
||||
public static async Task RequestPermissionsAsync(string? microphone, CancellationToken ct)
|
||||
{
|
||||
var activity = MainActivity.Current ?? throw new InvalidOperationException("Activite Android indisponible.");
|
||||
await PodcastPermissions.EnsureAsync(activity, microphone is not null, ct);
|
||||
if (!MainActivity.IsForeground)
|
||||
throw new InvalidOperationException("Revenez dans PostIt pour demarrer la camera.");
|
||||
}
|
||||
|
||||
public static async Task<IPodcastCapture> StartAsync(string camera, string? microphone, string directory, CancellationToken ct)
|
||||
{
|
||||
await RequestPermissionsAsync(microphone, ct);
|
||||
var activity = MainActivity.Current ?? throw new InvalidOperationException("Activite Android indisponible.");
|
||||
var service = await PodcastCaptureService.StartAsync(activity, microphone is not null, ct);
|
||||
var capture = new AndroidPodcastCapture(service);
|
||||
service.Capture = capture;
|
||||
try
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
await capture.StartNativeAsync(camera, microphone is not null, directory, ct);
|
||||
return capture;
|
||||
}
|
||||
catch
|
||||
{
|
||||
await capture.DisposeAsync();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task StartNativeAsync(string cameraId, bool microphone, string directory, CancellationToken ct)
|
||||
{
|
||||
await _stopGate.WaitAsync(ct);
|
||||
try { await ConfigureNativeAsync(cameraId, microphone, directory, ct); }
|
||||
finally { _stopGate.Release(); }
|
||||
}
|
||||
|
||||
private async Task ConfigureNativeAsync(string cameraId, bool microphone, string directory, CancellationToken ct)
|
||||
{
|
||||
var manager = GetManager(_service);
|
||||
using var characteristics = manager.GetCameraCharacteristics(cameraId);
|
||||
using var formats = characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap) as StreamConfigurationMap
|
||||
?? throw new InvalidOperationException("Formats camera indisponibles.");
|
||||
var sizes = formats.GetOutputSizes(Java.Lang.Class.FromType(typeof(MediaRecorder)))
|
||||
?? throw new InvalidOperationException("Aucun format video disponible.");
|
||||
var size = sizes.Where(s => s.Width <= 640 && s.Height <= 480)
|
||||
.OrderByDescending(s => s.Width * s.Height).FirstOrDefault()
|
||||
?? throw new InvalidOperationException("La camera ne propose aucun format jusqu'a 480p.");
|
||||
#pragma warning disable CS0618
|
||||
_recorder = OperatingSystem.IsAndroidVersionAtLeast(31)
|
||||
? new MediaRecorder(_service) : new MediaRecorder();
|
||||
#pragma warning restore CS0618
|
||||
_recorder.Error += OnRecorderError;
|
||||
if (microphone) _recorder.SetAudioSource(AudioSource.Mic);
|
||||
_recorder.SetVideoSource(VideoSource.Surface);
|
||||
_recorder.SetOutputFormat(OutputFormat.Mpeg2Ts);
|
||||
_recorder.SetVideoSize(size.Width, size.Height);
|
||||
_recorder.SetVideoFrameRate(30);
|
||||
_recorder.SetVideoEncodingBitRate(1200000);
|
||||
_recorder.SetVideoEncoder(VideoEncoder.H264);
|
||||
if (microphone)
|
||||
{
|
||||
_recorder.SetAudioSamplingRate(48000);
|
||||
_recorder.SetAudioChannels(1);
|
||||
_recorder.SetAudioEncodingBitRate(96000);
|
||||
_recorder.SetAudioEncoder(AudioEncoder.Aac);
|
||||
}
|
||||
var pipe = ParcelFileDescriptor.CreatePipe()
|
||||
?? throw new IOException("Creation du canal MPEG-TS impossible.");
|
||||
_readPipe = pipe[0];
|
||||
_writePipe = pipe[1];
|
||||
_recorder.SetOutputFile(_writePipe.FileDescriptor);
|
||||
await Task.Run(_recorder.Prepare, ct);
|
||||
ct.ThrowIfCancellationRequested();
|
||||
if (_stopRequested) throw new System.OperationCanceledException("Demarrage de la capture annule.");
|
||||
_surface = _recorder.Surface ?? throw new InvalidOperationException("Surface encodeur indisponible.");
|
||||
var opened = new TaskCompletionSource<CameraDevice>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
manager.OpenCamera(cameraId, new DeviceCallback(this, opened), _handler);
|
||||
_camera = await opened.Task.WaitAsync(TimeSpan.FromSeconds(10), ct);
|
||||
var configured = new TaskCompletionSource<CameraCaptureSession>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
#pragma warning disable CS0618, CA1422
|
||||
_camera.CreateCaptureSession(new List<Surface> { _surface }, new SessionCallback(this, configured), _handler);
|
||||
#pragma warning restore CS0618, CA1422
|
||||
_session = await configured.Task.WaitAsync(TimeSpan.FromSeconds(10), ct);
|
||||
ct.ThrowIfCancellationRequested();
|
||||
if (_stopRequested) throw new System.OperationCanceledException("Demarrage de la capture annule.");
|
||||
using var request = _camera.CreateCaptureRequest(CameraTemplate.Record);
|
||||
request.AddTarget(_surface);
|
||||
using var built = request.Build();
|
||||
_session.SetRepeatingRequest(built, null, _handler);
|
||||
var handle = new SafeFileHandle((IntPtr)_readPipe.Fd, ownsHandle: false);
|
||||
var stream = new FileStream(handle, FileAccess.Read);
|
||||
_pump = Task.Run(async () =>
|
||||
{
|
||||
using (handle)
|
||||
using (stream)
|
||||
{
|
||||
try
|
||||
{
|
||||
await new TransportStreamCapture(directory).RunAsync(stream, CancellationToken.None);
|
||||
if (_failure is not null) throw new IOException("Capture Android interrompue.", _failure);
|
||||
if (!_stopped) throw new IOException("Le flux de capture Android s'est ferme prematurement.");
|
||||
_completion.TrySetResult();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_completion.TrySetException(ex);
|
||||
// Drain until MediaRecorder stops, so its writer cannot block Stop().
|
||||
await stream.CopyToAsync(System.IO.Stream.Null);
|
||||
}
|
||||
}
|
||||
});
|
||||
await Task.Run(_recorder.Start, ct);
|
||||
_started = true;
|
||||
_writePipe.Close();
|
||||
_writePipe.Dispose();
|
||||
_writePipe = null;
|
||||
}
|
||||
|
||||
private sealed class DeviceCallback(AndroidPodcastCapture capture, TaskCompletionSource<CameraDevice> opened)
|
||||
: CameraDevice.StateCallback
|
||||
{
|
||||
public override void OnOpened(CameraDevice camera)
|
||||
{
|
||||
if (capture._stopRequested || opened.Task.IsCompleted)
|
||||
{
|
||||
camera.Close();
|
||||
opened.TrySetException(new IOException("Ouverture camera annulee."));
|
||||
}
|
||||
else
|
||||
{
|
||||
capture._camera = camera;
|
||||
opened.TrySetResult(camera);
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnDisconnected(CameraDevice camera) => Fail(camera, "Camera Android deconnectee.");
|
||||
public override void OnError(CameraDevice camera, CameraError error) => Fail(camera, $"Erreur camera Android : {error}.");
|
||||
private void Fail(CameraDevice camera, string message)
|
||||
{
|
||||
camera.Close();
|
||||
var error = new IOException(message);
|
||||
opened.TrySetException(error);
|
||||
capture.Fail(error);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class SessionCallback(AndroidPodcastCapture capture, TaskCompletionSource<CameraCaptureSession> configured)
|
||||
: CameraCaptureSession.StateCallback
|
||||
{
|
||||
public override void OnConfigured(CameraCaptureSession session)
|
||||
{
|
||||
if (capture._stopRequested || configured.Task.IsCompleted)
|
||||
{
|
||||
session.Close();
|
||||
configured.TrySetException(new IOException("Configuration camera annulee."));
|
||||
}
|
||||
else
|
||||
{
|
||||
capture._session = session;
|
||||
configured.TrySetResult(session);
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnConfigureFailed(CameraCaptureSession session)
|
||||
{
|
||||
session.Close();
|
||||
var error = new IOException("Configuration de la capture Android impossible.");
|
||||
configured.TrySetException(error);
|
||||
capture.Fail(error);
|
||||
}
|
||||
}
|
||||
|
||||
private void OnRecorderError(object? sender, MediaRecorder.ErrorEventArgs e)
|
||||
=> Fail(new IOException($"Erreur encodeur Android : {e.What}/{e.Extra}."));
|
||||
|
||||
private void Fail(Exception error)
|
||||
{
|
||||
if (_stopped) return;
|
||||
_failure = error;
|
||||
_completion.TrySetException(error);
|
||||
RequestStop();
|
||||
}
|
||||
|
||||
internal async void RequestStop()
|
||||
{
|
||||
try { await StopAsync(); }
|
||||
catch (Exception ex) { global::Android.Util.Log.Error("PostIt.Podcast", ex.ToString()); }
|
||||
}
|
||||
|
||||
public async Task StopAsync()
|
||||
{
|
||||
_stopRequested = true;
|
||||
await _stopGate.WaitAsync();
|
||||
try
|
||||
{
|
||||
if (_stopped) return;
|
||||
_stopped = true;
|
||||
await Task.Run(StopNative);
|
||||
await _pump;
|
||||
}
|
||||
finally { _stopGate.Release(); }
|
||||
}
|
||||
|
||||
private void StopNative()
|
||||
{
|
||||
try { if (_started) _recorder?.Stop(); }
|
||||
catch (Java.Lang.RuntimeException ex)
|
||||
{
|
||||
_failure = ex;
|
||||
_completion.TrySetException(new IOException("L'encodeur Android n'a pas pu finaliser la capture.", ex));
|
||||
}
|
||||
finally
|
||||
{
|
||||
_started = false;
|
||||
_session?.Close();
|
||||
_session?.Dispose();
|
||||
_session = null;
|
||||
_camera?.Close();
|
||||
_camera?.Dispose();
|
||||
_camera = null;
|
||||
if (_recorder is not null)
|
||||
{
|
||||
_recorder.Error -= OnRecorderError;
|
||||
_recorder.Release();
|
||||
_recorder.Dispose();
|
||||
_recorder = null;
|
||||
}
|
||||
_surface?.Dispose();
|
||||
_surface = null;
|
||||
_writePipe?.Close();
|
||||
_writePipe?.Dispose();
|
||||
_writePipe = null;
|
||||
}
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
try { await StopAsync(); }
|
||||
finally
|
||||
{
|
||||
_readPipe?.Dispose();
|
||||
_readPipe = null;
|
||||
_service.Capture = null;
|
||||
_service.StopSelf();
|
||||
_handler.Dispose();
|
||||
_stopGate.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
37
src/PostIt/PostIt.Android/Services/AndroidVideoSurface.cs
Normal file
37
src/PostIt/PostIt.Android/Services/AndroidVideoSurface.cs
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
using System;
|
||||
using Avalonia.Android;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Platform;
|
||||
using LibVLCSharp.Shared;
|
||||
using VideoView = LibVLCSharp.Platforms.Android.VideoView;
|
||||
|
||||
namespace PostIt.Android.Services;
|
||||
|
||||
internal sealed class AndroidVideoSurface(MediaPlayer player) : NativeControlHost, IDisposable
|
||||
{
|
||||
private VideoView? _video;
|
||||
private bool _disposed;
|
||||
|
||||
protected override IPlatformHandle CreateNativeControlCore(IPlatformHandle parent)
|
||||
{
|
||||
var activity = MainActivity.Current
|
||||
?? throw new InvalidOperationException("L'activite Android est indisponible.");
|
||||
var video = new VideoView(activity) { MediaPlayer = _disposed ? null : player };
|
||||
_video = video;
|
||||
return new AndroidViewControlHandle(video);
|
||||
}
|
||||
|
||||
protected override void DestroyNativeControlCore(IPlatformHandle control)
|
||||
{
|
||||
if (control is AndroidViewControlHandle { View: VideoView video })
|
||||
video.MediaPlayer = null;
|
||||
_video = null;
|
||||
base.DestroyNativeControlCore(control);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_disposed = true;
|
||||
if (_video is not null) _video.MediaPlayer = null;
|
||||
}
|
||||
}
|
||||
109
src/PostIt/PostIt.Android/Services/PodcastCaptureService.cs
Normal file
109
src/PostIt/PostIt.Android/Services/PodcastCaptureService.cs
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
using System;
|
||||
using System.Runtime.Versioning;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Android.App;
|
||||
using Android.Content;
|
||||
using Android.Content.PM;
|
||||
using Android.OS;
|
||||
using AndroidX.Core.App;
|
||||
|
||||
namespace PostIt.Android.Services;
|
||||
|
||||
[Service(Exported = false, ForegroundServiceType = ForegroundService.TypeCamera | ForegroundService.TypeMicrophone)]
|
||||
[SupportedOSPlatform("android26.0")]
|
||||
public sealed class PodcastCaptureService : Service
|
||||
{
|
||||
private const string Channel = "podcast-broadcast";
|
||||
internal const string StopAction = "fr.pschneider.postit.STOP_PODCAST";
|
||||
private const int NotificationId = 4044;
|
||||
private static TaskCompletionSource<PodcastCaptureService>? _pending;
|
||||
private PowerManager.WakeLock? _wakeLock;
|
||||
internal AndroidPodcastCapture? Capture { get; set; }
|
||||
|
||||
public static async Task<PodcastCaptureService> StartAsync(Activity activity, bool microphone, CancellationToken ct)
|
||||
{
|
||||
if (_pending is not null) throw new InvalidOperationException("Un direct Android est deja en cours.");
|
||||
var pending = new TaskCompletionSource<PodcastCaptureService>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
_pending = pending;
|
||||
try
|
||||
{
|
||||
var intent = new Intent(activity, typeof(PodcastCaptureService)).PutExtra("microphone", microphone);
|
||||
activity.StartForegroundService(intent);
|
||||
return await pending.Task.WaitAsync(TimeSpan.FromSeconds(10), ct);
|
||||
}
|
||||
catch
|
||||
{
|
||||
activity.StopService(new Intent(activity, typeof(PodcastCaptureService)));
|
||||
_pending = null;
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public override StartCommandResult OnStartCommand(Intent? intent, StartCommandFlags flags, int startId)
|
||||
{
|
||||
if (intent?.Action == StopAction)
|
||||
{
|
||||
if (Capture is { } capture) capture.RequestStop();
|
||||
else
|
||||
{
|
||||
_pending?.TrySetException(new System.OperationCanceledException("Demarrage du direct annule depuis la notification."));
|
||||
StopSelf();
|
||||
}
|
||||
return StartCommandResult.NotSticky;
|
||||
}
|
||||
try
|
||||
{
|
||||
var manager = GetSystemService(NotificationService) as NotificationManager
|
||||
?? throw new InvalidOperationException("Notifications Android indisponibles.");
|
||||
manager.CreateNotificationChannel(new NotificationChannel(Channel, "Diffusion podcast", NotificationImportance.Low));
|
||||
var launch = PackageManager?.GetLaunchIntentForPackage(PackageName!)
|
||||
?? throw new InvalidOperationException("Application Android indisponible.");
|
||||
var open = PendingIntent.GetActivity(this, 0, launch, PendingIntentFlags.UpdateCurrent | PendingIntentFlags.Immutable);
|
||||
var stop = PendingIntent.GetService(this, 1,
|
||||
new Intent(this, typeof(PodcastCaptureService)).SetAction(StopAction),
|
||||
PendingIntentFlags.UpdateCurrent | PendingIntentFlags.Immutable);
|
||||
var builder = new NotificationCompat.Builder(this, Channel);
|
||||
builder.SetSmallIcon(global::Android.Resource.Drawable.IcMenuCamera);
|
||||
builder.SetContentTitle("Podcast en direct");
|
||||
builder.SetContentText("Camera active. Toucher pour revenir au direct.");
|
||||
builder.SetContentIntent(open);
|
||||
builder.SetOngoing(true);
|
||||
builder.AddAction(global::Android.Resource.Drawable.IcMediaPause, "Arreter et publier", stop);
|
||||
var notification = builder.Build();
|
||||
var type = (ForegroundService)0;
|
||||
if (OperatingSystem.IsAndroidVersionAtLeast(30))
|
||||
{
|
||||
type = ForegroundService.TypeCamera;
|
||||
if (intent?.GetBooleanExtra("microphone", false) == true) type |= ForegroundService.TypeMicrophone;
|
||||
}
|
||||
ServiceCompat.StartForeground(this, NotificationId, notification, (int)type);
|
||||
var power = GetSystemService(PowerService) as PowerManager
|
||||
?? throw new InvalidOperationException("Gestion d'alimentation Android indisponible.");
|
||||
_wakeLock = power.NewWakeLock(WakeLockFlags.Partial, "PostIt:Podcast")
|
||||
?? throw new InvalidOperationException("Le verrou d'alimentation Android est indisponible.");
|
||||
_wakeLock.Acquire();
|
||||
_pending?.TrySetResult(this);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_pending?.TrySetException(ex);
|
||||
StopSelf();
|
||||
}
|
||||
return StartCommandResult.NotSticky;
|
||||
}
|
||||
|
||||
public override IBinder? OnBind(Intent? intent) => null;
|
||||
|
||||
public override void OnDestroy()
|
||||
{
|
||||
_pending?.TrySetException(new InvalidOperationException("Le service de diffusion Android a ete arrete."));
|
||||
Capture?.RequestStop();
|
||||
Capture = null;
|
||||
if (_wakeLock?.IsHeld == true) _wakeLock.Release();
|
||||
_wakeLock?.Dispose();
|
||||
_wakeLock = null;
|
||||
_pending = null;
|
||||
base.OnDestroy();
|
||||
}
|
||||
}
|
||||
47
src/PostIt/PostIt.Android/Services/PodcastPermissions.cs
Normal file
47
src/PostIt/PostIt.Android/Services/PodcastPermissions.cs
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
using System;
|
||||
using System.Linq;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Android;
|
||||
using Android.App;
|
||||
using Android.Content.PM;
|
||||
using AndroidX.Core.App;
|
||||
using AndroidX.Core.Content;
|
||||
|
||||
namespace PostIt.Android.Services;
|
||||
|
||||
internal static class PodcastPermissions
|
||||
{
|
||||
private const int RequestCode = 4043;
|
||||
private static TaskCompletionSource<bool>? _pending;
|
||||
private static string[] _requested = [];
|
||||
|
||||
public static async Task EnsureAsync(Activity activity, bool microphone, CancellationToken ct)
|
||||
{
|
||||
var requested = new List<string> { Manifest.Permission.Camera };
|
||||
if (microphone) requested.Add(Manifest.Permission.RecordAudio);
|
||||
if (OperatingSystem.IsAndroidVersionAtLeast(33)) requested.Add(Manifest.Permission.PostNotifications);
|
||||
var permissions = requested.ToArray();
|
||||
if (permissions.All(p => ContextCompat.CheckSelfPermission(activity, p) == Permission.Granted)) return;
|
||||
if (_pending is not null) throw new InvalidOperationException("Une demande de permissions est deja en cours.");
|
||||
_requested = permissions;
|
||||
var pending = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
_pending = pending;
|
||||
ActivityCompat.RequestPermissions(activity, permissions, RequestCode);
|
||||
if (!await pending.Task.WaitAsync(ct))
|
||||
throw new UnauthorizedAccessException("Autorisez la camera, les notifications et, si selectionne, le microphone pour diffuser.");
|
||||
}
|
||||
|
||||
public static bool HandleResult(int requestCode, string[]? permissions, Permission[]? results)
|
||||
{
|
||||
if (requestCode != RequestCode) return false;
|
||||
var granted = permissions is not null && results is not null && permissions.Length == results.Length
|
||||
&& _requested.All(p => Array.IndexOf(permissions, p) is var index && index >= 0
|
||||
&& results[index] == Permission.Granted);
|
||||
var pending = _pending;
|
||||
_pending = null;
|
||||
pending?.TrySetResult(granted);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
100
src/PostIt/PostIt.Tests/AndroidPodcastCaptureTestActivity.cs
Normal file
100
src/PostIt/PostIt.Tests/AndroidPodcastCaptureTestActivity.cs
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
#if ANDROID
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Runtime.Versioning;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Android.App;
|
||||
using Android.Content;
|
||||
using Android.OS;
|
||||
using Avalonia.Threading;
|
||||
using PostIt.Android;
|
||||
using PostIt.Android.Services;
|
||||
using PostIt.Services;
|
||||
|
||||
namespace PostIt.Tests;
|
||||
|
||||
/// <summary>Debug-only local encoder test; never connects to the podcast API.</summary>
|
||||
[Activity(Name = "fr.pschneider.postit.PodcastCaptureTestActivity", Exported = true)]
|
||||
[SupportedOSPlatform("android26.0")]
|
||||
public sealed class AndroidPodcastCaptureTestActivity : Activity
|
||||
{
|
||||
private bool _microphone = true;
|
||||
private bool _notificationStop;
|
||||
private int _cameraIndex;
|
||||
protected override async void OnCreate(Bundle? state)
|
||||
{
|
||||
base.OnCreate(state);
|
||||
_microphone = Intent?.GetStringExtra("microphone") != "false";
|
||||
_notificationStop = Intent?.GetStringExtra("notificationStop") == "true";
|
||||
_cameraIndex = Intent?.GetStringExtra("camera") == "front" ? 1 : 0;
|
||||
var resultPath = Path.Combine(FilesDir!.AbsolutePath, "podcast-capture-test-result.txt");
|
||||
File.WriteAllText(resultPath, "RUNNING");
|
||||
var result = new Bundle();
|
||||
try
|
||||
{
|
||||
await RunAsync(result);
|
||||
File.WriteAllText(resultPath, $"PASS\nsegments={result.GetInt("segments")}\ndirectory={result.GetString("directory")}\nbackground={result.GetString("background")}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
File.WriteAllText(resultPath, $"FAIL\n{ex}");
|
||||
}
|
||||
finally { Finish(); }
|
||||
}
|
||||
|
||||
private async Task RunAsync(Bundle result)
|
||||
{
|
||||
if (!OperatingSystem.IsAndroidVersionAtLeast(26))
|
||||
throw new PlatformNotSupportedException("Android 8 required.");
|
||||
var context = this;
|
||||
var intent = new Intent(context, typeof(MainActivity)).AddFlags(ActivityFlags.NewTask);
|
||||
StartActivity(intent);
|
||||
for (var i = 0; i < 100 && !MainActivity.IsForeground; i++) await Task.Delay(100);
|
||||
await Task.Delay(1000);
|
||||
var directory = Path.Combine(context.FilesDir!.AbsolutePath, "podcast-capture-tests", Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(directory);
|
||||
var devices = AndroidPodcastCapture.GetDevices();
|
||||
if (devices.Cameras.Count == 0) throw new InvalidOperationException("No emulator camera.");
|
||||
IPodcastCapture? capture = null;
|
||||
try
|
||||
{
|
||||
capture = await Dispatcher.UIThread.InvokeAsync(() => AndroidPodcastCapture.StartAsync(
|
||||
devices.Cameras[Math.Min(_cameraIndex, devices.Cameras.Count - 1)].Value,
|
||||
_microphone ? "microphone" : null, directory, CancellationToken.None));
|
||||
await Task.Delay(3000);
|
||||
var before = SegmentCount(directory);
|
||||
context.StartActivity(new Intent(Intent.ActionMain).AddCategory(Intent.CategoryHome).AddFlags(ActivityFlags.NewTask));
|
||||
await Task.Delay(9000);
|
||||
var after = SegmentCount(directory);
|
||||
if (capture.Completion.IsFaulted) await capture.Completion;
|
||||
if (after <= before) throw new InvalidOperationException($"Capture did not continue in background: {before} -> {after} segments.");
|
||||
if (_notificationStop)
|
||||
{
|
||||
using var stop = PendingIntent.GetService(context, 1,
|
||||
new Intent(context, typeof(PodcastCaptureService)).SetAction(PodcastCaptureService.StopAction),
|
||||
PendingIntentFlags.NoCreate | PendingIntentFlags.Immutable)
|
||||
?? throw new InvalidOperationException("Notification stop action missing.");
|
||||
stop.Send();
|
||||
}
|
||||
else await capture.StopAsync().WaitAsync(TimeSpan.FromSeconds(15));
|
||||
await capture.Completion.WaitAsync(TimeSpan.FromSeconds(15));
|
||||
var segments = HlsCapturePlaylist.Parse(await File.ReadAllTextAsync(Path.Combine(directory, "index.m3u8")));
|
||||
if (segments.Count < 3) throw new InvalidOperationException("Insufficient capture segments.");
|
||||
result.PutInt("segments", segments.Count);
|
||||
result.PutString("directory", directory);
|
||||
result.PutString("background", $"segments {before} -> {after}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (capture is not null) await capture.DisposeAsync();
|
||||
}
|
||||
}
|
||||
|
||||
private static int SegmentCount(string directory)
|
||||
{
|
||||
var path = Path.Combine(directory, "index.m3u8");
|
||||
return File.Exists(path) ? HlsCapturePlaylist.Parse(File.ReadAllText(path)).Count : 0;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
|
@ -464,11 +464,31 @@ public class BlogReaderTests
|
|||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public void Video_viewmodel_resolves_to_a_page_with_a_vlc_control()
|
||||
public void Video_viewmodel_resolves_to_the_shared_page_with_a_platform_video_surface_slot()
|
||||
{
|
||||
var vm = new VideoPageViewModel(new Uri("https://org.example.test/files/paul/clip.mp4"), "video/mp4");
|
||||
var page = Assert.IsType<VideoPage>(new ViewLocator().Build(vm));
|
||||
Assert.NotNull(page.FindControl<LibVLCSharp.Avalonia.VideoView>("Video"));
|
||||
Assert.NotNull(page.FindControl<ContentControl>("VideoSurface"));
|
||||
Assert.NotNull(page.FindControl<Button>("PlayButton"));
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task Video_page_observes_platform_lifecycle_only_while_navigated()
|
||||
{
|
||||
var nav = new NavigationPage();
|
||||
await nav.PushAsync(new ContentPage());
|
||||
var page = new VideoPage();
|
||||
await nav.PushAsync(page);
|
||||
var status = page.FindControl<TextBlock>("PlaybackStatus")!;
|
||||
Platform.SuspendPlayback();
|
||||
Assert.Equal("Lecture suspendue.", status.Text);
|
||||
Assert.False(page.FindControl<Button>("PlayButton")!.IsEnabled);
|
||||
Platform.ResumePlayback();
|
||||
Assert.Null(page.FindControl<ContentControl>("VideoSurface")!.Content);
|
||||
await nav.PopAsync();
|
||||
status.Text = "No longer active";
|
||||
Platform.SuspendPlayback();
|
||||
Assert.Equal("No longer active", status.Text);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
|
|
|||
84
src/PostIt/PostIt.Tests/InvoicesApiClientTests.cs
Normal file
84
src/PostIt/PostIt.Tests/InvoicesApiClientTests.cs
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
using System.Net.Http;
|
||||
using Yavsc.Api.Client;
|
||||
using Yavsc.Billing;
|
||||
|
||||
namespace PostIt.Tests;
|
||||
|
||||
public sealed class InvoicesApiClientTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Client_maps_invoice_operations_and_forwards_cancellation()
|
||||
{
|
||||
var api = new RecordingApi();
|
||||
var client = new InvoicesApiClient(api, () => "https://business.example/api/v1/");
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
|
||||
await client.GenerateAsync(7, ct);
|
||||
Assert.Equal(HttpMethod.Post, api.Method);
|
||||
Assert.Equal("https://business.example/api/v1/invoices/from-estimate/7", api.Path);
|
||||
Assert.Null(api.Body);
|
||||
Assert.Equal(ct, api.Cancellation);
|
||||
|
||||
await client.GetAsync(42, ct);
|
||||
Assert.Equal(HttpMethod.Get, api.Method);
|
||||
Assert.Equal("https://business.example/api/v1/invoices/42", api.Path);
|
||||
|
||||
var receipt = new RecordInvoicePaymentRequest
|
||||
{
|
||||
Reference = "bank-1", Amount = 30m, Currency = "EUR",
|
||||
ReceivedAtUtc = DateTimeOffset.UtcNow.AddDays(-1)
|
||||
};
|
||||
await client.RecordOfflineAsync(42, receipt, ct);
|
||||
Assert.Equal(HttpMethod.Post, api.Method);
|
||||
Assert.Equal("https://business.example/api/v1/invoices/42/payments/offline", api.Path);
|
||||
Assert.Same(receipt, api.Body);
|
||||
|
||||
await client.VerifyPayPalAsync(42, "TX-1", ct);
|
||||
Assert.Equal(HttpMethod.Post, api.Method);
|
||||
Assert.Equal("https://business.example/api/v1/invoices/42/payments/paypal", api.Path);
|
||||
Assert.Equal("TX-1", Assert.IsType<VerifyInvoicePayPalRequest>(api.Body).TransactionId);
|
||||
Assert.Equal(ct, api.Cancellation);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Invalid_arguments_fail_before_transport()
|
||||
{
|
||||
var api = new RecordingApi();
|
||||
var client = new InvoicesApiClient(api, () => "https://business.example/api/v1/");
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
await Assert.ThrowsAsync<ArgumentOutOfRangeException>(() => client.GenerateAsync(0, ct));
|
||||
await Assert.ThrowsAsync<ArgumentOutOfRangeException>(() => client.GetAsync(-1, ct));
|
||||
await Assert.ThrowsAsync<ArgumentNullException>(() => client.RecordOfflineAsync(42, null!, ct));
|
||||
await Assert.ThrowsAsync<ArgumentException>(() => client.VerifyPayPalAsync(42, "", ct));
|
||||
Assert.Null(api.Path);
|
||||
}
|
||||
|
||||
private sealed class RecordingApi : IYavscApiClient
|
||||
{
|
||||
public HttpClient Http { get; } = new();
|
||||
public HttpMethod? Method { get; private set; }
|
||||
public string? Path { get; private set; }
|
||||
public object? Body { get; private set; }
|
||||
public CancellationToken Cancellation { get; private set; }
|
||||
|
||||
public Task<T> CallAsync<T>(HttpMethod method, string path, object? body = null, CancellationToken ct = default)
|
||||
{
|
||||
Method = method;
|
||||
Path = path;
|
||||
Body = body;
|
||||
Cancellation = ct;
|
||||
return Task.FromResult(default(T)!);
|
||||
}
|
||||
|
||||
public Task CallAsync(HttpMethod method, string path, object? body = null, CancellationToken ct = default)
|
||||
=> throw new NotSupportedException();
|
||||
|
||||
public Task<T> CallAsync<T>(HttpMethod method, string path, Func<HttpContent> contentFactory, CancellationToken ct = default)
|
||||
=> throw new NotSupportedException();
|
||||
|
||||
public Task CallAsync(HttpMethod method, string path, Func<HttpContent> contentFactory, CancellationToken ct = default)
|
||||
=> throw new NotSupportedException();
|
||||
|
||||
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
|
||||
}
|
||||
}
|
||||
175
src/PostIt/PostIt.Tests/PodcastBroadcasterTests.cs
Normal file
175
src/PostIt/PostIt.Tests/PodcastBroadcasterTests.cs
Normal file
|
|
@ -0,0 +1,175 @@
|
|||
using System.Net;
|
||||
using Avalonia.Headless.XUnit;
|
||||
using PostIt.Services;
|
||||
using PostIt.ViewModels;
|
||||
using Yavsc.Abstract.Streaming;
|
||||
using Yavsc.Api.Client;
|
||||
|
||||
namespace PostIt.Tests;
|
||||
|
||||
public sealed class PodcastBroadcasterTests
|
||||
{
|
||||
[AvaloniaFact]
|
||||
public async Task Shared_page_uses_platform_devices_and_requests_permissions_before_creating_server_broadcast()
|
||||
{
|
||||
var tokenPath = Path.Combine(Path.GetTempPath(), $"postit-podcast-{Guid.NewGuid():N}.json");
|
||||
var devices = Platform.GetPodcastCaptureDevices;
|
||||
var permissions = Platform.RequestPodcastPermissionsAsync;
|
||||
var factory = Platform.CreatePodcastCaptureAsync;
|
||||
var store = new TokenStore(tokenPath);
|
||||
store.Save(new RefreshTokenRecord("test-access-token", "test-refresh-token", DateTimeOffset.UtcNow.AddHours(1), null));
|
||||
await using var api = new YavscApiClient(new Settings(), store);
|
||||
await using var transport = new Transport();
|
||||
try
|
||||
{
|
||||
Platform.GetPodcastCaptureDevices = () => new(
|
||||
[new("Front", "front"), new("Rear", "rear")],
|
||||
[new("None", ""), new("Android microphone", "microphone")]);
|
||||
Platform.RequestPodcastPermissionsAsync = (_, _) =>
|
||||
Task.FromException(new UnauthorizedAccessException("Camera denied"));
|
||||
Platform.CreatePodcastCaptureAsync = (_, _, _, _) =>
|
||||
throw new InvalidOperationException("Capture must not start after permission denial.");
|
||||
var session = new SessionStatusViewModel { Api = api };
|
||||
session.Refresh();
|
||||
var vm = new PodcastsPageViewModel(new PodcastApiClient(transport, () => "https://api.example/"), api, session)
|
||||
{
|
||||
Title = "Android live"
|
||||
};
|
||||
Assert.True(vm.CanBroadcast);
|
||||
vm.DetectDevicesCommand.Execute(null);
|
||||
Assert.Equal(2, vm.Cameras.Count);
|
||||
Assert.Equal("front", vm.SelectedCamera?.Value);
|
||||
Assert.Equal("microphone", vm.SelectedMicrophone?.Value);
|
||||
Assert.True(vm.StartCommand.CanExecute(null));
|
||||
await vm.StartCommand.ExecuteAsync(null);
|
||||
Assert.Contains("Camera denied", vm.Status);
|
||||
Assert.Equal(0, transport.CreateCount);
|
||||
Assert.False(vm.IsBusy);
|
||||
Assert.False(vm.IsBroadcasting);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Platform.GetPodcastCaptureDevices = devices;
|
||||
Platform.RequestPodcastPermissionsAsync = permissions;
|
||||
Platform.CreatePodcastCaptureAsync = factory;
|
||||
File.Delete(tokenPath);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Native_stop_flushes_final_segment_before_completing_server_replay()
|
||||
{
|
||||
await using var transport = new Transport();
|
||||
var client = new PodcastApiClient(transport, () => "https://api.example/");
|
||||
FakeCapture? capture = null;
|
||||
await using var broadcaster = await PodcastBroadcaster.StartAsync(client, "Android",
|
||||
(directory, _) =>
|
||||
{
|
||||
capture = new FakeCapture(directory);
|
||||
return Task.FromResult<IPodcastCapture>(capture);
|
||||
}, TestContext.Current.CancellationToken);
|
||||
await transport.FirstUpload.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||||
await capture!.StopAsync();
|
||||
await broadcaster.Completion.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||||
Assert.Equal(new[] { 0, 1 }, transport.Uploads);
|
||||
Assert.Equal(new[] { "upload:0", "upload:1", "complete" }, transport.Events);
|
||||
Assert.True(capture.Stopped);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Native_failure_stops_capture_and_preserves_unacknowledged_segments()
|
||||
{
|
||||
await using var transport = new Transport { FailUpload = true };
|
||||
var client = new PodcastApiClient(transport, () => "https://api.example/");
|
||||
FakeCapture? capture = null;
|
||||
var broadcaster = await PodcastBroadcaster.StartAsync(client, "Android",
|
||||
(directory, _) =>
|
||||
{
|
||||
capture = new FakeCapture(directory);
|
||||
return Task.FromResult<IPodcastCapture>(capture);
|
||||
}, TestContext.Current.CancellationToken);
|
||||
try
|
||||
{
|
||||
await Assert.ThrowsAsync<HttpRequestException>(() => broadcaster.Completion);
|
||||
Assert.True(capture!.Stopped);
|
||||
Assert.True(File.Exists(Path.Combine(capture.Directory, "segment-00000000.ts")));
|
||||
Assert.DoesNotContain("complete", transport.Events);
|
||||
await Assert.ThrowsAsync<HttpRequestException>(() => broadcaster.DisposeAsync().AsTask());
|
||||
Assert.True(capture.Disposed);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (capture is not null) Directory.Delete(capture.Directory, recursive: true);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Startup_failure_finalizes_empty_server_broadcast()
|
||||
{
|
||||
await using var transport = new Transport();
|
||||
var client = new PodcastApiClient(transport, () => "https://api.example/");
|
||||
await Assert.ThrowsAsync<UnauthorizedAccessException>(() => PodcastBroadcaster.StartAsync(client, "Denied",
|
||||
(_, _) => Task.FromException<IPodcastCapture>(new UnauthorizedAccessException("Camera denied")),
|
||||
TestContext.Current.CancellationToken));
|
||||
Assert.Equal(new[] { "complete" }, transport.Events);
|
||||
}
|
||||
|
||||
private sealed class FakeCapture : IPodcastCapture
|
||||
{
|
||||
private readonly TaskCompletionSource _completion = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
public string Directory { get; }
|
||||
public bool Stopped { get; private set; }
|
||||
public bool Disposed { get; private set; }
|
||||
public Task Completion => _completion.Task;
|
||||
public FakeCapture(string directory)
|
||||
{
|
||||
Directory = directory;
|
||||
File.WriteAllBytes(Path.Combine(directory, "segment-00000000.ts"), [0x47, 1]);
|
||||
File.WriteAllText(Path.Combine(directory, "index.m3u8"), "#EXTM3U\n#EXTINF:2,\nsegment-00000000.ts\n");
|
||||
}
|
||||
public Task StopAsync()
|
||||
{
|
||||
if (Stopped) return Task.CompletedTask;
|
||||
File.WriteAllBytes(Path.Combine(Directory, "segment-00000001.ts"), [0x47, 2]);
|
||||
File.AppendAllText(Path.Combine(Directory, "index.m3u8"), "#EXTINF:0.5,\nsegment-00000001.ts\n");
|
||||
Stopped = true;
|
||||
_completion.TrySetResult();
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
public ValueTask DisposeAsync() { Disposed = true; return ValueTask.CompletedTask; }
|
||||
}
|
||||
|
||||
private sealed class Transport : IYavscApiClient
|
||||
{
|
||||
private readonly PodcastResponse _podcast = new(Guid.NewGuid(), "Test", "alice", "Alice",
|
||||
DateTimeOffset.UtcNow, DateTimeOffset.UtcNow, PodcastState.Live, 0, 0, 0);
|
||||
public HttpClient Http { get; } = new();
|
||||
public List<int> Uploads { get; } = [];
|
||||
public List<string> Events { get; } = [];
|
||||
public bool FailUpload { get; init; }
|
||||
public int CreateCount { get; private set; }
|
||||
public TaskCompletionSource FirstUpload { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
public Task<T> CallAsync<T>(HttpMethod method, string path, object? body = null, CancellationToken ct = default)
|
||||
{
|
||||
if (path.EndsWith("/complete", StringComparison.Ordinal)) Events.Add("complete");
|
||||
else CreateCount++;
|
||||
return Task.FromResult((T)(object)_podcast);
|
||||
}
|
||||
public Task<T> CallAsync<T>(HttpMethod method, string path, Func<HttpContent> contentFactory, CancellationToken ct = default)
|
||||
{
|
||||
if (FailUpload) throw new HttpRequestException("Denied", null, HttpStatusCode.Forbidden);
|
||||
var sequence = int.Parse(new Uri(path).Segments[^1], System.Globalization.CultureInfo.InvariantCulture);
|
||||
Uploads.Add(sequence);
|
||||
Events.Add($"upload:{sequence}");
|
||||
FirstUpload.TrySetResult();
|
||||
return Task.FromResult((T)(object)_podcast);
|
||||
}
|
||||
public Task CallAsync(HttpMethod method, string path, object? body = null, CancellationToken ct = default)
|
||||
=> CallAsync<PodcastResponse>(method, path, body, ct);
|
||||
public Task CallAsync(HttpMethod method, string path, Func<HttpContent> contentFactory, CancellationToken ct = default)
|
||||
=> CallAsync<PodcastResponse>(method, path, contentFactory, ct);
|
||||
public Task<byte[]> DownloadAsync(HttpMethod method, string path, CancellationToken ct = default)
|
||||
=> throw new NotSupportedException();
|
||||
public ValueTask DisposeAsync() { Http.Dispose(); return ValueTask.CompletedTask; }
|
||||
}
|
||||
}
|
||||
146
src/PostIt/PostIt.Tests/TransportStreamCaptureTests.cs
Normal file
146
src/PostIt/PostIt.Tests/TransportStreamCaptureTests.cs
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
using PostIt.Services;
|
||||
|
||||
namespace PostIt.Tests;
|
||||
|
||||
public sealed class TransportStreamCaptureTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Segments_on_IDR_and_flushes_final_segment_with_real_PTS_durations()
|
||||
{
|
||||
var directory = Path.Combine(Path.GetTempPath(), $"postit-ts-{Guid.NewGuid():N}");
|
||||
Directory.CreateDirectory(directory);
|
||||
try
|
||||
{
|
||||
using var input = new MemoryStream();
|
||||
input.Write(Pat());
|
||||
input.Write(Pmt());
|
||||
for (var i = 0; i <= 120; i++) input.Write(Video(i * 3000L, i % 60 == 0));
|
||||
input.Position = 0;
|
||||
await new TransportStreamCapture(directory).RunAsync(input, TestContext.Current.CancellationToken);
|
||||
var segments = HlsCapturePlaylist.Parse(await File.ReadAllTextAsync(Path.Combine(directory, "index.m3u8"), TestContext.Current.CancellationToken));
|
||||
Assert.Equal(3, segments.Count);
|
||||
Assert.Equal(2, segments[0].DurationSeconds);
|
||||
Assert.Equal(2, segments[1].DurationSeconds);
|
||||
Assert.InRange(segments[2].DurationSeconds, 0.033, 0.034);
|
||||
foreach (var segment in segments)
|
||||
{
|
||||
var bytes = await File.ReadAllBytesAsync(Path.Combine(directory, segment.FileName), TestContext.Current.CancellationToken);
|
||||
Assert.Equal(0, bytes.Length % 188);
|
||||
Assert.Equal(Pat(), bytes[..188]);
|
||||
Assert.Equal(Pmt(), bytes[188..376]);
|
||||
Assert.Contains((byte)0x65, bytes[376..]);
|
||||
}
|
||||
}
|
||||
finally { Directory.Delete(directory, recursive: true); }
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(true)]
|
||||
[InlineData(false)]
|
||||
public async Task Rejects_corrupt_or_truncated_transport_without_publishing_a_segment(bool truncated)
|
||||
{
|
||||
var directory = Path.Combine(Path.GetTempPath(), $"postit-ts-{Guid.NewGuid():N}");
|
||||
Directory.CreateDirectory(directory);
|
||||
try
|
||||
{
|
||||
using var input = new MemoryStream(new byte[truncated ? 187 : 188]);
|
||||
await Assert.ThrowsAsync<InvalidDataException>(() =>
|
||||
new TransportStreamCapture(directory).RunAsync(input, TestContext.Current.CancellationToken));
|
||||
Assert.False(File.Exists(Path.Combine(directory, "index.m3u8")));
|
||||
}
|
||||
finally { Directory.Delete(directory, recursive: true); }
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Preserves_out_of_band_H264_configuration_at_every_segment_start()
|
||||
{
|
||||
var directory = Path.Combine(Path.GetTempPath(), $"postit-ts-{Guid.NewGuid():N}");
|
||||
Directory.CreateDirectory(directory);
|
||||
try
|
||||
{
|
||||
using var input = new MemoryStream();
|
||||
input.Write(Pat());
|
||||
input.Write(Pmt());
|
||||
var configuration = Video(0, false);
|
||||
configuration[22] = 0x67;
|
||||
new byte[] { 0, 0, 0, 1, 0x68, 0x80 }.CopyTo(configuration, 25);
|
||||
input.Write(configuration);
|
||||
for (var i = 0; i <= 120; i++) input.Write(Video(90000 + i * 3000L, i % 60 == 0));
|
||||
input.Position = 0;
|
||||
await new TransportStreamCapture(directory).RunAsync(input, TestContext.Current.CancellationToken);
|
||||
var segments = HlsCapturePlaylist.Parse(await File.ReadAllTextAsync(Path.Combine(directory, "index.m3u8"), TestContext.Current.CancellationToken));
|
||||
Assert.Equal(3, segments.Count);
|
||||
foreach (var segment in segments)
|
||||
{
|
||||
var bytes = await File.ReadAllBytesAsync(Path.Combine(directory, segment.FileName), TestContext.Current.CancellationToken);
|
||||
Assert.Equal(0x67, bytes[376 + 22]);
|
||||
Assert.Equal(0x68, bytes[376 + 29]);
|
||||
Assert.Equal(0x65, bytes[564 + 22]);
|
||||
Assert.Equal((bytes[564 + 3] - 1) & 0x0f, bytes[376 + 3] & 0x0f);
|
||||
Assert.Equal(bytes[(564 + 13)..(564 + 18)], bytes[(376 + 13)..(376 + 18)]);
|
||||
}
|
||||
}
|
||||
finally { Directory.Delete(directory, recursive: true); }
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handles_33_bit_PTS_wrap_without_negative_duration()
|
||||
{
|
||||
var directory = Path.Combine(Path.GetTempPath(), $"postit-ts-{Guid.NewGuid():N}");
|
||||
Directory.CreateDirectory(directory);
|
||||
try
|
||||
{
|
||||
using var input = new MemoryStream();
|
||||
input.Write(Pat());
|
||||
input.Write(Pmt());
|
||||
for (var i = 0; i <= 120; i++)
|
||||
input.Write(Video(((1L << 33) - 90000 + i * 3000L) & ((1L << 33) - 1), i % 60 == 0));
|
||||
input.Position = 0;
|
||||
await new TransportStreamCapture(directory).RunAsync(input, TestContext.Current.CancellationToken);
|
||||
var segments = HlsCapturePlaylist.Parse(await File.ReadAllTextAsync(Path.Combine(directory, "index.m3u8"), TestContext.Current.CancellationToken));
|
||||
Assert.Equal(3, segments.Count);
|
||||
Assert.Equal(2, segments[0].DurationSeconds);
|
||||
}
|
||||
finally { Directory.Delete(directory, recursive: true); }
|
||||
}
|
||||
|
||||
private static byte[] Packet(int pid)
|
||||
{
|
||||
var packet = Enumerable.Repeat((byte)0xff, 188).ToArray();
|
||||
packet[0] = 0x47;
|
||||
packet[1] = (byte)(0x40 | (pid >> 8));
|
||||
packet[2] = (byte)pid;
|
||||
packet[3] = 0x10;
|
||||
return packet;
|
||||
}
|
||||
|
||||
private static byte[] Pat()
|
||||
{
|
||||
var packet = Packet(0);
|
||||
packet[4] = 0;
|
||||
new byte[] { 0, 0xb0, 13, 0, 1, 0xc1, 0, 0, 0, 1, 0xe1, 0 }.CopyTo(packet, 5);
|
||||
return packet;
|
||||
}
|
||||
|
||||
private static byte[] Pmt()
|
||||
{
|
||||
var packet = Packet(256);
|
||||
packet[4] = 0;
|
||||
new byte[] { 2, 0xb0, 18, 0, 1, 0xc1, 0, 0, 0xe1, 1, 0xf0, 0,
|
||||
0x1b, 0xe1, 1, 0xf0, 0 }.CopyTo(packet, 5);
|
||||
return packet;
|
||||
}
|
||||
|
||||
private static byte[] Video(long pts, bool idr)
|
||||
{
|
||||
var packet = Packet(257);
|
||||
new byte[] { 0, 0, 1, 0xe0, 0, 0, 0x84, 0x80, 5 }.CopyTo(packet, 4);
|
||||
packet[13] = (byte)(0x21 | ((pts >> 29) & 0xe));
|
||||
packet[14] = (byte)(pts >> 22);
|
||||
packet[15] = (byte)(1 | ((pts >> 14) & 0xfe));
|
||||
packet[16] = (byte)(pts >> 7);
|
||||
packet[17] = (byte)(1 | ((pts << 1) & 0xfe));
|
||||
new byte[] { 0, 0, 0, 1, idr ? (byte)0x65 : (byte)0x41, 0x88 }.CopyTo(packet, 18);
|
||||
return packet;
|
||||
}
|
||||
}
|
||||
|
|
@ -34,6 +34,7 @@ public static class ServiceCollectionHelpers
|
|||
() => settings.Authentication?.Authority);
|
||||
var billingClient = new BillingApiClient(api, () => settings.ApiUrl);
|
||||
var estimateClient = new EstimateApiClient(api, () => settings.ApiUrl);
|
||||
var invoicesClient = new InvoicesApiClient(api, () => settings.ApiUrl);
|
||||
var frontClient = new FrontOfficeApiClient(api, () => settings.ApiUrl);
|
||||
var resourceUsageClient = new ResourceUsageApiClient(api, () => settings.ApiUrl);
|
||||
var administrationClient = new AdministrationApiClient(api, () => settings.ApiUrl);
|
||||
|
|
@ -104,6 +105,7 @@ public static class ServiceCollectionHelpers
|
|||
services.AddSingleton(activityClient);
|
||||
services.AddSingleton(billingClient);
|
||||
services.AddSingleton(estimateClient);
|
||||
services.AddSingleton(invoicesClient);
|
||||
services.AddSingleton(frontClient);
|
||||
services.AddSingleton(resourceUsageClient);
|
||||
services.AddSingleton(administrationClient);
|
||||
|
|
|
|||
16
src/PostIt/PostIt/Services/IPodcastCapture.cs
Normal file
16
src/PostIt/PostIt/Services/IPodcastCapture.cs
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace PostIt.Services;
|
||||
|
||||
public sealed record CaptureDevice(string Name, string Value);
|
||||
public sealed record PodcastCaptureDevices(
|
||||
IReadOnlyList<CaptureDevice> Cameras, IReadOnlyList<CaptureDevice> Microphones);
|
||||
|
||||
/// <summary>A running encoder publishing closed segments and an atomic index.m3u8.</summary>
|
||||
public interface IPodcastCapture : IAsyncDisposable
|
||||
{
|
||||
Task Completion { get; }
|
||||
Task StopAsync();
|
||||
}
|
||||
62
src/PostIt/PostIt/Services/LibVlcPodcastCapture.cs
Normal file
62
src/PostIt/PostIt/Services/LibVlcPodcastCapture.cs
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using LibVLCSharp.Shared;
|
||||
|
||||
namespace PostIt.Services;
|
||||
|
||||
internal sealed class LibVlcPodcastCapture : IPodcastCapture
|
||||
{
|
||||
private readonly LibVLC _vlc;
|
||||
private readonly Media _media;
|
||||
private readonly MediaPlayer _player;
|
||||
private readonly TaskCompletionSource _completion = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
private bool _stopped;
|
||||
|
||||
public Task Completion => _completion.Task;
|
||||
|
||||
public LibVlcPodcastCapture(Func<LibVLC, Media> createMedia, string directory)
|
||||
{
|
||||
Core.Initialize();
|
||||
_vlc = CameraStreamer.CreatePreferredLibVlc();
|
||||
try
|
||||
{
|
||||
_media = createMedia(_vlc);
|
||||
PodcastBroadcaster.ConfigureOutput(_media, directory);
|
||||
_player = new MediaPlayer(_vlc);
|
||||
_player.EncounteredError += OnError;
|
||||
if (!_player.Play(_media))
|
||||
throw new InvalidOperationException("LibVLC ne peut pas demarrer la capture. Verifiez la camera et les encodeurs H.264/AAC.");
|
||||
}
|
||||
catch
|
||||
{
|
||||
_player?.Dispose();
|
||||
_media?.Dispose();
|
||||
_vlc.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnError(object? sender, EventArgs e)
|
||||
=> _completion.TrySetException(new InvalidOperationException(
|
||||
"La capture LibVLC a echoue. Verifiez camera, microphone et encodeurs H.264/AAC."));
|
||||
|
||||
public async Task StopAsync()
|
||||
{
|
||||
if (_stopped) return;
|
||||
_stopped = true;
|
||||
await Task.Run(_player.Stop);
|
||||
_completion.TrySetResult();
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
try { await StopAsync(); }
|
||||
finally
|
||||
{
|
||||
_player.EncounteredError -= OnError;
|
||||
_player.Dispose();
|
||||
_media.Dispose();
|
||||
_vlc.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -2,19 +2,28 @@ using System;
|
|||
using IdentityModel.OidcClient.Browser;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia.Controls;
|
||||
using LibVLCSharp.Shared;
|
||||
|
||||
namespace PostIt.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Per-platform access to native integration points used by the OIDC
|
||||
/// Authorization Code + PKCE flow. The shared <c>PostIt</c> library does
|
||||
/// not reference any UI framework; platform projects (PostIt.Android,
|
||||
/// PostIt.Desktop, PostIt.Browser) populate this class once at startup so
|
||||
/// the shared OIDC login path can drive a native browser without taking
|
||||
/// a hard dependency on any specific UI toolkit.
|
||||
/// Native integration points populated by platform projects at startup.
|
||||
/// </summary>
|
||||
public static class Platform
|
||||
{
|
||||
public static Func<PodcastCaptureDevices>? GetPodcastCaptureDevices { get; set; }
|
||||
public static Func<string?, CancellationToken, Task>? RequestPodcastPermissionsAsync { get; set; }
|
||||
public static Func<string, string?, string, CancellationToken, Task<IPodcastCapture>>? CreatePodcastCaptureAsync { get; set; }
|
||||
|
||||
/// <summary>Platform-specific video surface inside the shared video page.</summary>
|
||||
public static Func<MediaPlayer, Control>? CreateVideoSurface { get; set; }
|
||||
|
||||
public static event Action? PlaybackSuspending;
|
||||
public static event Action? PlaybackResuming;
|
||||
public static void SuspendPlayback() => PlaybackSuspending?.Invoke();
|
||||
public static void ResumePlayback() => PlaybackResuming?.Invoke();
|
||||
|
||||
/// <summary>
|
||||
/// Default redirect URI for the running platform. The shared
|
||||
/// default uses a custom URI scheme (<c>postit://callback</c>)
|
||||
|
|
|
|||
|
|
@ -16,14 +16,11 @@ namespace PostIt.Services;
|
|||
public sealed class PodcastBroadcaster : IAsyncDisposable
|
||||
{
|
||||
private readonly PodcastApiClient _api;
|
||||
private readonly LibVLC _vlc;
|
||||
private readonly MediaPlayer _player;
|
||||
private readonly Media _media;
|
||||
private readonly IPodcastCapture _capture;
|
||||
private readonly string _directory;
|
||||
private readonly CancellationTokenSource _cancellation = new();
|
||||
private readonly SemaphoreSlim _stopGate = new(1);
|
||||
private volatile bool _stopped;
|
||||
private volatile bool _encoderFailed;
|
||||
private bool _disposed;
|
||||
|
||||
public PodcastResponse Podcast { get; private set; }
|
||||
|
|
@ -31,15 +28,12 @@ public sealed class PodcastBroadcaster : IAsyncDisposable
|
|||
public event Action<PodcastResponse>? Progress;
|
||||
|
||||
private PodcastBroadcaster(PodcastApiClient api, PodcastResponse podcast,
|
||||
LibVLC vlc, MediaPlayer player, Media media, string directory)
|
||||
IPodcastCapture capture, string directory)
|
||||
{
|
||||
_api = api;
|
||||
Podcast = podcast;
|
||||
_vlc = vlc;
|
||||
_player = player;
|
||||
_media = media;
|
||||
_capture = capture;
|
||||
_directory = directory;
|
||||
_player.EncounteredError += OnEncoderError;
|
||||
}
|
||||
|
||||
public static void ConfigureOutput(Media media, string directory)
|
||||
|
|
@ -57,11 +51,13 @@ public sealed class PodcastBroadcaster : IAsyncDisposable
|
|||
|
||||
internal static async Task<PodcastBroadcaster> StartAsync(PodcastApiClient api, string title,
|
||||
Func<LibVLC, Media> createMedia, CancellationToken ct)
|
||||
=> await StartAsync(api, title,
|
||||
(directory, _) => Task.FromResult<IPodcastCapture>(new LibVlcPodcastCapture(createMedia, directory)), ct);
|
||||
|
||||
public static async Task<PodcastBroadcaster> StartAsync(PodcastApiClient api, string title,
|
||||
Func<string, CancellationToken, Task<IPodcastCapture>> createCapture, CancellationToken ct)
|
||||
{
|
||||
Core.Initialize();
|
||||
var vlc = CameraStreamer.CreatePreferredLibVlc();
|
||||
Media? media = null;
|
||||
MediaPlayer? player = null;
|
||||
IPodcastCapture? capture = null;
|
||||
PodcastBroadcaster? broadcaster = null;
|
||||
var directory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
|
||||
"PostIt", "podcast-capture", Guid.NewGuid().ToString("N"));
|
||||
|
|
@ -69,15 +65,12 @@ public sealed class PodcastBroadcaster : IAsyncDisposable
|
|||
try
|
||||
{
|
||||
Directory.CreateDirectory(directory);
|
||||
media = createMedia(vlc);
|
||||
ConfigureOutput(media, directory);
|
||||
player = new MediaPlayer(vlc);
|
||||
podcast = await api.CreateAsync(title, ct);
|
||||
await File.WriteAllTextAsync(Path.Combine(directory, "podcast.json"), JsonSerializer.Serialize(podcast), ct);
|
||||
ct.ThrowIfCancellationRequested();
|
||||
broadcaster = new PodcastBroadcaster(api, podcast, vlc, player, media, directory);
|
||||
if (!player.Play(media))
|
||||
throw new InvalidOperationException("LibVLC ne peut pas demarrer la capture. Verifiez la camera et les encodeurs H.264/AAC.");
|
||||
capture = await createCapture(directory, ct);
|
||||
ct.ThrowIfCancellationRequested();
|
||||
broadcaster = new PodcastBroadcaster(api, podcast, capture, directory);
|
||||
broadcaster.Completion = broadcaster.UploadAsync(broadcaster._cancellation.Token);
|
||||
return broadcaster;
|
||||
}
|
||||
|
|
@ -85,13 +78,10 @@ public sealed class PodcastBroadcaster : IAsyncDisposable
|
|||
{
|
||||
if (broadcaster is not null)
|
||||
{
|
||||
broadcaster._player.EncounteredError -= broadcaster.OnEncoderError;
|
||||
broadcaster._cancellation.Dispose();
|
||||
broadcaster._stopGate.Dispose();
|
||||
}
|
||||
player?.Dispose();
|
||||
media?.Dispose();
|
||||
vlc.Dispose();
|
||||
if (capture is not null) await capture.DisposeAsync();
|
||||
if (Directory.Exists(directory)) Directory.Delete(directory, recursive: true);
|
||||
if (podcast is not null)
|
||||
{
|
||||
|
|
@ -122,7 +112,7 @@ public sealed class PodcastBroadcaster : IAsyncDisposable
|
|||
{
|
||||
if (!_stopped)
|
||||
{
|
||||
await Task.Run(_player.Stop);
|
||||
await _capture.StopAsync();
|
||||
_stopped = true;
|
||||
}
|
||||
}
|
||||
|
|
@ -138,9 +128,9 @@ public sealed class PodcastBroadcaster : IAsyncDisposable
|
|||
while (true)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
var finalPass = _stopped;
|
||||
if (_encoderFailed)
|
||||
throw new InvalidOperationException("La capture LibVLC a echoue. Verifiez camera, microphone et encodeurs H.264/AAC.");
|
||||
var finalPass = _stopped || _capture.Completion.IsCompleted;
|
||||
if (_capture.Completion.IsCompleted)
|
||||
await _capture.Completion;
|
||||
var pendingBytes = Directory.EnumerateFiles(_directory, "*.ts").Sum(path => new FileInfo(path).Length);
|
||||
if (pendingBytes > 64L * 1024 * 1024)
|
||||
throw new IOException("Le reseau est trop lent : la capture depasse 64 Mio de segments en attente.");
|
||||
|
|
@ -174,7 +164,7 @@ public sealed class PodcastBroadcaster : IAsyncDisposable
|
|||
return;
|
||||
}
|
||||
if (lastSegment.Elapsed > TimeSpan.FromSeconds(25))
|
||||
throw new IOException("Aucun segment produit depuis 25 secondes. Verifiez la capture et les encodeurs LibVLC.");
|
||||
throw new IOException("Aucun segment produit depuis 25 secondes. Verifiez la camera et les encodeurs H.264/AAC.");
|
||||
await Task.Delay(400, ct);
|
||||
}
|
||||
}
|
||||
|
|
@ -207,8 +197,6 @@ public sealed class PodcastBroadcaster : IAsyncDisposable
|
|||
}
|
||||
}
|
||||
|
||||
private void OnEncoderError(object? sender, EventArgs e) => _encoderFailed = true;
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if (_disposed) return;
|
||||
|
|
@ -217,10 +205,7 @@ public sealed class PodcastBroadcaster : IAsyncDisposable
|
|||
try { await Completion; }
|
||||
finally
|
||||
{
|
||||
_player.EncounteredError -= OnEncoderError;
|
||||
_player.Dispose();
|
||||
_media.Dispose();
|
||||
_vlc.Dispose();
|
||||
await _capture.DisposeAsync();
|
||||
_cancellation.Dispose();
|
||||
_stopGate.Dispose();
|
||||
// Keep failed, unacknowledged segments for manual recovery.
|
||||
|
|
|
|||
222
src/PostIt/PostIt/Services/TransportStreamCapture.cs
Normal file
222
src/PostIt/PostIt/Services/TransportStreamCapture.cs
Normal file
|
|
@ -0,0 +1,222 @@
|
|||
using System;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace PostIt.Services;
|
||||
|
||||
/// <summary>Segments a single-program H.264 MPEG-TS encoder output at IDR frames.</summary>
|
||||
public sealed class TransportStreamCapture(string directory)
|
||||
{
|
||||
private const int PacketSize = 188;
|
||||
private const int MaxSegmentBytes = 8 * 1024 * 1024;
|
||||
private readonly MemoryStream _frame = new();
|
||||
private readonly MemoryStream _video = new();
|
||||
private readonly StringBuilder _playlist = new("#EXTM3U\n");
|
||||
private byte[]? _pat;
|
||||
private byte[]? _pmt;
|
||||
private byte[]? _configuration;
|
||||
private int _pmtPid = -1;
|
||||
private int _videoPid = -1;
|
||||
private FileStream? _segment;
|
||||
private int _sequence;
|
||||
private long? _framePts;
|
||||
private long _startPts;
|
||||
private long _lastPts;
|
||||
private long _frameDuration = 3000;
|
||||
private long? _previousPts;
|
||||
private long _ptsEpoch;
|
||||
|
||||
public async Task RunAsync(Stream input, CancellationToken ct)
|
||||
{
|
||||
var packet = new byte[PacketSize];
|
||||
try
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
var read = 0;
|
||||
while (read < PacketSize)
|
||||
{
|
||||
var count = await input.ReadAsync(packet.AsMemory(read), ct);
|
||||
if (count == 0)
|
||||
{
|
||||
if (read != 0) throw new InvalidDataException("Paquet MPEG-TS tronque.");
|
||||
FlushFrame();
|
||||
CloseSegment(_lastPts + _frameDuration);
|
||||
return;
|
||||
}
|
||||
read += count;
|
||||
}
|
||||
Consume(packet);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_segment?.Dispose();
|
||||
_frame.Dispose();
|
||||
_video.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
private void Consume(byte[] packet)
|
||||
{
|
||||
if (packet[0] != 0x47 || (packet[1] & 0x80) != 0 || (packet[3] & 0xc0) != 0)
|
||||
throw new InvalidDataException("Flux MPEG-TS invalide.");
|
||||
var pid = ((packet[1] & 0x1f) << 8) | packet[2];
|
||||
var hasPayload = (packet[3] & 0x10) != 0;
|
||||
if (!hasPayload) return;
|
||||
var offset = 4;
|
||||
if ((packet[3] & 0x20) != 0) offset += 1 + packet[4];
|
||||
if (offset >= PacketSize) throw new InvalidDataException("Adaptation MPEG-TS invalide.");
|
||||
var start = (packet[1] & 0x40) != 0;
|
||||
if (pid == 0 || pid == _pmtPid)
|
||||
{
|
||||
if (!start) throw new InvalidDataException("Table MPEG-TS multi-paquets non prise en charge.");
|
||||
var section = offset + 1 + packet[offset];
|
||||
if (section + 3 > PacketSize) throw new InvalidDataException("Table MPEG-TS tronquee.");
|
||||
var end = section + 3 + (((packet[section + 1] & 0x0f) << 8) | packet[section + 2]);
|
||||
if (end > PacketSize) throw new InvalidDataException("Table MPEG-TS trop grande.");
|
||||
if (pid == 0)
|
||||
{
|
||||
if (packet[section] != 0 || end - section < 16)
|
||||
throw new InvalidDataException("PAT MPEG-TS invalide.");
|
||||
_pmtPid = ((packet[section + 10] & 0x1f) << 8) | packet[section + 11];
|
||||
_pat = (byte[])packet.Clone();
|
||||
}
|
||||
else
|
||||
{
|
||||
if (packet[section] != 2 || end - section < 16)
|
||||
throw new InvalidDataException("PMT MPEG-TS invalide.");
|
||||
var entry = section + 12 + (((packet[section + 10] & 0x0f) << 8) | packet[section + 11]);
|
||||
while (entry + 5 <= end - 4)
|
||||
{
|
||||
if (packet[entry] == 0x1b)
|
||||
_videoPid = ((packet[entry + 1] & 0x1f) << 8) | packet[entry + 2];
|
||||
entry += 5 + (((packet[entry + 3] & 0x0f) << 8) | packet[entry + 4]);
|
||||
}
|
||||
_pmt = (byte[])packet.Clone();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (pid == _videoPid && start)
|
||||
{
|
||||
FlushFrame();
|
||||
if (offset + 14 > PacketSize || packet[offset] != 0 || packet[offset + 1] != 0
|
||||
|| packet[offset + 2] != 1 || (packet[offset + 7] & 0x80) == 0)
|
||||
throw new InvalidDataException("Horodatage video MPEG-TS absent.");
|
||||
var ptsOffset = offset + 9;
|
||||
var pts = ((long)(packet[ptsOffset] & 0x0e) << 29)
|
||||
| ((long)packet[ptsOffset + 1] << 22) | ((long)(packet[ptsOffset + 2] & 0xfe) << 14)
|
||||
| ((long)packet[ptsOffset + 3] << 7) | (uint)(packet[ptsOffset + 4] >> 1);
|
||||
if (_previousPts is { } previous && pts < previous)
|
||||
{
|
||||
if (previous - pts < (1L << 32))
|
||||
throw new InvalidDataException("Horodatages video non croissants.");
|
||||
_ptsEpoch += 1L << 33;
|
||||
}
|
||||
_previousPts = pts;
|
||||
_framePts = pts + _ptsEpoch;
|
||||
offset += 9 + packet[offset + 8];
|
||||
if (offset > PacketSize) throw new InvalidDataException("En-tete PES invalide.");
|
||||
}
|
||||
if (_framePts is null) return;
|
||||
_frame.Write(packet);
|
||||
if (pid == _videoPid) _video.Write(packet, offset, PacketSize - offset);
|
||||
if (_frame.Length > MaxSegmentBytes)
|
||||
throw new IOException("Une image de capture depasse 8 Mio.");
|
||||
}
|
||||
|
||||
private void FlushFrame()
|
||||
{
|
||||
if (_framePts is not { } pts) return;
|
||||
var video = _video.GetBuffer().AsSpan(0, (int)_video.Length);
|
||||
var idr = false;
|
||||
var hasConfiguration = false;
|
||||
var hasSlice = false;
|
||||
for (var i = 0; i + 3 < video.Length; i++)
|
||||
if (video[i] == 0 && video[i + 1] == 0 && video[i + 2] == 1)
|
||||
{
|
||||
var type = video[i + 3] & 0x1f;
|
||||
if (type == 5) idr = true;
|
||||
if (type is 7 or 8) hasConfiguration = true;
|
||||
if (type is 1 or 5) hasSlice = true;
|
||||
}
|
||||
if (hasConfiguration && !hasSlice)
|
||||
{
|
||||
using var packets = new MemoryStream();
|
||||
for (var i = 0; i < _frame.Length; i += PacketSize)
|
||||
{
|
||||
var packet = _frame.GetBuffer().AsSpan(i, PacketSize);
|
||||
if ((((packet[1] & 0x1f) << 8) | packet[2]) == _videoPid)
|
||||
packets.Write(packet);
|
||||
}
|
||||
_configuration = packets.ToArray();
|
||||
}
|
||||
if (_segment is not null && idr && pts - _startPts >= 180000)
|
||||
CloseSegment(pts);
|
||||
if (_segment is null && idr)
|
||||
{
|
||||
if (_pat is null || _pmt is null)
|
||||
throw new InvalidDataException("Tables MPEG-TS manquantes.");
|
||||
_startPts = pts;
|
||||
_segment = File.Create(Path.Combine(directory, SegmentName()));
|
||||
_segment.Write(_pat);
|
||||
_segment.Write(_pmt);
|
||||
if (!hasConfiguration && _configuration is not null) WriteConfiguration(pts);
|
||||
}
|
||||
if (_segment is not null)
|
||||
{
|
||||
if (_segment.Length + _frame.Length > MaxSegmentBytes || pts - _startPts > 14 * 90000)
|
||||
throw new IOException("Segment trop grand ou absence d'image cle depuis 14 secondes.");
|
||||
_segment.Write(_frame.GetBuffer(), 0, (int)_frame.Length);
|
||||
if (pts > _lastPts && _lastPts >= _startPts)
|
||||
_frameDuration = Math.Min(pts - _lastPts, 9000);
|
||||
_lastPts = pts;
|
||||
}
|
||||
_frame.SetLength(0);
|
||||
_video.SetLength(0);
|
||||
_framePts = null;
|
||||
}
|
||||
|
||||
private string SegmentName() => $"segment-{_sequence:D8}.ts";
|
||||
|
||||
private void WriteConfiguration(long pts)
|
||||
{
|
||||
var packets = (byte[])_configuration!.Clone();
|
||||
var first = _frame.GetBuffer()[3] & 0x0f;
|
||||
var counter = (first - packets.Length / PacketSize) & 0x0f;
|
||||
for (var i = 0; i < packets.Length; i += PacketSize)
|
||||
{
|
||||
packets[i + 3] = (byte)((packets[i + 3] & 0xf0) | counter);
|
||||
counter = (counter + 1) & 0x0f;
|
||||
if ((packets[i + 1] & 0x40) == 0) continue;
|
||||
var offset = i + 4;
|
||||
if ((packets[i + 3] & 0x20) != 0) offset += packets[offset] + 1;
|
||||
offset += 9;
|
||||
if (offset + 5 > i + PacketSize) throw new InvalidDataException("Configuration H.264 invalide.");
|
||||
packets[offset] = (byte)(0x21 | ((pts >> 29) & 0x0e));
|
||||
packets[offset + 1] = (byte)(pts >> 22);
|
||||
packets[offset + 2] = (byte)(1 | ((pts >> 14) & 0xfe));
|
||||
packets[offset + 3] = (byte)(pts >> 7);
|
||||
packets[offset + 4] = (byte)(1 | ((pts << 1) & 0xfe));
|
||||
}
|
||||
_segment!.Write(packets);
|
||||
}
|
||||
|
||||
private void CloseSegment(long endPts)
|
||||
{
|
||||
if (_segment is null) return;
|
||||
_segment.Dispose();
|
||||
_segment = null;
|
||||
var duration = (endPts - _startPts) / 90000d;
|
||||
if (duration <= 0 || duration > 15) throw new InvalidDataException("Duree MPEG-TS invalide.");
|
||||
_playlist.Append("#EXTINF:").Append(duration.ToString("0.######", CultureInfo.InvariantCulture))
|
||||
.Append(",\n").Append(SegmentName()).Append('\n');
|
||||
var index = Path.Combine(directory, "index.m3u8");
|
||||
File.WriteAllText(index + ".tmp", _playlist.ToString());
|
||||
File.Move(index + ".tmp", index, overwrite: true);
|
||||
_sequence++;
|
||||
}
|
||||
}
|
||||
|
|
@ -15,8 +15,6 @@ using Yavsc.Api.Client;
|
|||
|
||||
namespace PostIt.ViewModels;
|
||||
|
||||
public sealed record CaptureDevice(string Name, string Value);
|
||||
|
||||
public partial class PodcastsPageViewModel : ViewModelBase
|
||||
{
|
||||
private readonly PodcastApiClient _client;
|
||||
|
|
@ -36,7 +34,8 @@ public partial class PodcastsPageViewModel : ViewModelBase
|
|||
public ObservableCollection<PodcastResponse> Podcasts { get; } = new();
|
||||
public ObservableCollection<CaptureDevice> Cameras { get; } = new();
|
||||
public ObservableCollection<CaptureDevice> Microphones { get; } = new();
|
||||
public bool IsDesktop => OperatingSystem.IsWindows() || OperatingSystem.IsLinux();
|
||||
public bool CanBroadcast => Platform.CreatePodcastCaptureAsync is not null
|
||||
|| (!OperatingSystem.IsAndroid() && (OperatingSystem.IsWindows() || OperatingSystem.IsLinux()));
|
||||
|
||||
|
||||
public string Title { get => _title; set { if (SetProperty(ref _title, value)) UpdateCommands(); } }
|
||||
|
|
@ -89,9 +88,9 @@ public partial class PodcastsPageViewModel : ViewModelBase
|
|||
_api = api;
|
||||
_session = session;
|
||||
RefreshCommand = new AsyncRelayCommand(RefreshAsync, () => !IsBusy);
|
||||
DetectDevicesCommand = new RelayCommand(DetectDevices, () => IsDesktop && !IsBroadcasting && !IsBusy);
|
||||
DetectDevicesCommand = new RelayCommand(DetectDevices, () => CanBroadcast && !IsBroadcasting && !IsBusy);
|
||||
StartCommand = new AsyncRelayCommand(StartAsync,
|
||||
() => IsDesktop && !IsBroadcasting && !IsBusy && _session.IsLoggedIn
|
||||
() => CanBroadcast && !IsBroadcasting && !IsBusy && _session.IsLoggedIn
|
||||
&& SelectedCamera is not null && !string.IsNullOrWhiteSpace(Title));
|
||||
StopCommand = new AsyncRelayCommand(StopAsync, () => IsBroadcasting && !IsBusy);
|
||||
PlayCommand = new AsyncRelayCommand(PlayAsync, () => SelectedPodcast is { SegmentCount: > 0 } && !IsBroadcasting && !IsBusy);
|
||||
|
|
@ -151,14 +150,23 @@ public partial class PodcastsPageViewModel : ViewModelBase
|
|||
{
|
||||
try
|
||||
{
|
||||
Core.Initialize();
|
||||
using var vlc = CameraStreamer.CreatePreferredLibVlc();
|
||||
var capture = new CameraStreamer(vlc);
|
||||
Cameras.Clear();
|
||||
foreach (var item in capture.GetCaptureDevices()) Cameras.Add(new(item.Key, item.Value));
|
||||
Microphones.Clear();
|
||||
Microphones.Add(new("Sans microphone", ""));
|
||||
foreach (var item in capture.GetAudioCaptureDevices()) Microphones.Add(new(item.Key, item.Value));
|
||||
if (Platform.GetPodcastCaptureDevices is { } getDevices)
|
||||
{
|
||||
var devices = getDevices();
|
||||
foreach (var item in devices.Cameras) Cameras.Add(item);
|
||||
foreach (var item in devices.Microphones) Microphones.Add(item);
|
||||
}
|
||||
else
|
||||
{
|
||||
Core.Initialize();
|
||||
using var vlc = CameraStreamer.CreatePreferredLibVlc();
|
||||
var capture = new CameraStreamer(vlc);
|
||||
foreach (var item in capture.GetCaptureDevices()) Cameras.Add(new(item.Key, item.Value));
|
||||
Microphones.Add(new("Sans microphone", ""));
|
||||
foreach (var item in capture.GetAudioCaptureDevices()) Microphones.Add(new(item.Key, item.Value));
|
||||
}
|
||||
SelectedCamera = Cameras.Count == 0 ? null : Cameras[0];
|
||||
SelectedMicrophone = Microphones.Count > 1 ? Microphones[1] : Microphones[0];
|
||||
Status = Cameras.Count == 0 ? "Aucune camera detectee." : "Choisissez camera et microphone avant de demarrer.";
|
||||
|
|
@ -172,8 +180,14 @@ public partial class PodcastsPageViewModel : ViewModelBase
|
|||
try
|
||||
{
|
||||
if (SelectedCamera is null) throw new InvalidOperationException("Choisissez une camera.");
|
||||
_broadcaster = await PodcastBroadcaster.StartAsync(_client, Title, SelectedCamera.Value,
|
||||
string.IsNullOrWhiteSpace(SelectedMicrophone?.Value) ? null : SelectedMicrophone.Value, _pageCancellation.Token);
|
||||
var camera = SelectedCamera.Value;
|
||||
var microphone = string.IsNullOrWhiteSpace(SelectedMicrophone?.Value) ? null : SelectedMicrophone.Value;
|
||||
if (Platform.RequestPodcastPermissionsAsync is { } requestPermissions)
|
||||
await requestPermissions(microphone, _pageCancellation.Token);
|
||||
_broadcaster = Platform.CreatePodcastCaptureAsync is { } createCapture
|
||||
? await PodcastBroadcaster.StartAsync(_client, Title,
|
||||
(directory, ct) => createCapture(camera, microphone, directory, ct), _pageCancellation.Token)
|
||||
: await PodcastBroadcaster.StartAsync(_client, Title, camera, microphone, _pageCancellation.Token);
|
||||
_broadcaster.Progress += OnProgress;
|
||||
_session.LogoutCompleted += OnLogout;
|
||||
IsBroadcasting = true;
|
||||
|
|
|
|||
|
|
@ -2,13 +2,12 @@
|
|||
x:Class="PostIt.Views.Blogs.VideoPage"
|
||||
xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:vlc="clr-namespace:LibVLCSharp.Avalonia;assembly=LibVLCSharp.Avalonia"
|
||||
xmlns:vm="using:PostIt.ViewModels"
|
||||
x:DataType="vm:VideoPageViewModel">
|
||||
<Grid RowDefinitions="Auto,*,Auto,Auto" Margin="16" RowSpacing="12">
|
||||
<TextBlock Text="{Binding Title}" FontSize="22" TextWrapping="Wrap" />
|
||||
<Border Grid.Row="1" Background="Black" BorderThickness="1" BorderBrush="Green">
|
||||
<vlc:VideoView x:Name="Video" />
|
||||
<ContentControl x:Name="VideoSurface" />
|
||||
</Border>
|
||||
<StackPanel Grid.Row="2" Orientation="Horizontal" Spacing="12">
|
||||
<Button x:Name="PlayButton" Content="Lire / Pause" Click="PlayPause_Click" />
|
||||
|
|
|
|||
|
|
@ -21,6 +21,13 @@ public partial class VideoPage : ContentPage
|
|||
protected override void OnNavigatedTo(NavigatedToEventArgs e)
|
||||
{
|
||||
base.OnNavigatedTo(e);
|
||||
Platform.PlaybackSuspending += SuspendPlayback;
|
||||
Platform.PlaybackResuming += ResumePlayback;
|
||||
InitializePlayer();
|
||||
}
|
||||
|
||||
private void InitializePlayer()
|
||||
{
|
||||
ReleasePlayer();
|
||||
if (Design.IsDesignMode || DataContext is not VideoPageViewModel vm)
|
||||
return;
|
||||
|
|
@ -39,13 +46,15 @@ public partial class VideoPage : ContentPage
|
|||
: new Media(_libVlc, _podcastInput);
|
||||
if (_podcastInput is not null)
|
||||
media.AddOption(":demux=ts");
|
||||
Video.MediaPlayer = _player;
|
||||
var surface = Platform.CreateVideoSurface?.Invoke(_player)
|
||||
?? new LibVLCSharp.Avalonia.VideoView { MediaPlayer = _player };
|
||||
VideoSurface.Content = surface;
|
||||
var player = _player;
|
||||
// Navigation transforms do not change Bounds, so refresh the native surface after layout.
|
||||
Dispatcher.UIThread.Post(() =>
|
||||
{
|
||||
if (ReferenceEquals(_player, player))
|
||||
Video.TryUpdateNativeControlPosition();
|
||||
if (ReferenceEquals(_player, player) && surface is LibVLCSharp.Avalonia.VideoView desktopVideo)
|
||||
desktopVideo.TryUpdateNativeControlPosition();
|
||||
}, DispatcherPriority.Loaded);
|
||||
PlayButton.IsEnabled = true;
|
||||
PlaybackStatus.Text = vm.MimeType;
|
||||
|
|
@ -63,12 +72,16 @@ public partial class VideoPage : ContentPage
|
|||
|
||||
protected override void OnNavigatedFrom(NavigatedFromEventArgs e)
|
||||
{
|
||||
Platform.PlaybackSuspending -= SuspendPlayback;
|
||||
Platform.PlaybackResuming -= ResumePlayback;
|
||||
ReleasePlayer();
|
||||
base.OnNavigatedFrom(e);
|
||||
}
|
||||
|
||||
protected override void OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs e)
|
||||
{
|
||||
Platform.PlaybackSuspending -= SuspendPlayback;
|
||||
Platform.PlaybackResuming -= ResumePlayback;
|
||||
ReleasePlayer();
|
||||
base.OnDetachedFromVisualTree(e);
|
||||
}
|
||||
|
|
@ -76,8 +89,12 @@ public partial class VideoPage : ContentPage
|
|||
private void ReleasePlayer()
|
||||
{
|
||||
PlayButton.IsEnabled = false;
|
||||
Video.MediaPlayer = null;
|
||||
_podcastInput?.Cancel();
|
||||
if (VideoSurface.Content is LibVLCSharp.Avalonia.VideoView desktopVideo)
|
||||
desktopVideo.MediaPlayer = null;
|
||||
if (VideoSurface.Content is IDisposable nativeSurface)
|
||||
nativeSurface.Dispose();
|
||||
VideoSurface.Content = null;
|
||||
if (_player is not null)
|
||||
{
|
||||
_player.EncounteredError -= Player_EncounteredError;
|
||||
|
|
@ -95,6 +112,14 @@ public partial class VideoPage : ContentPage
|
|||
_libVlc = null;
|
||||
}
|
||||
|
||||
private void SuspendPlayback()
|
||||
{
|
||||
ReleasePlayer();
|
||||
PlaybackStatus.Text = "Lecture suspendue.";
|
||||
}
|
||||
|
||||
private void ResumePlayback() => InitializePlayer();
|
||||
|
||||
private void PodcastFailed(string message) => Dispatcher.UIThread.Post(() => PlaybackStatus.Text = message);
|
||||
|
||||
private static bool CanLaunchExternally(Uri source)
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
<ContentPage xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:vm="using:PostIt.ViewModels"
|
||||
xmlns:services="using:PostIt.Services"
|
||||
xmlns:streaming="clr-namespace:Yavsc.Abstract.Streaming;assembly=Yavsc.Abstract"
|
||||
x:Class="PostIt.Views.PodcastsPage"
|
||||
x:DataType="vm:PodcastsPageViewModel"
|
||||
|
|
@ -9,17 +10,17 @@
|
|||
<StackPanel Margin="16" Spacing="12" MaxWidth="900">
|
||||
<TextBlock Text="Podcasts : directs et replays" FontSize="22" />
|
||||
<TextBlock Text="Lecture et emission reservees aux utilisateurs connectes. Quitter cette page arrete la capture." TextWrapping="Wrap" />
|
||||
<StackPanel Spacing="8" IsVisible="{Binding IsDesktop}" IsEnabled="{Binding !IsBroadcasting}">
|
||||
<StackPanel Spacing="8" IsVisible="{Binding CanBroadcast}" IsEnabled="{Binding !IsBroadcasting}">
|
||||
<TextBox Text="{Binding Title}" PlaceholderText="Titre du direct" MaxLength="160" />
|
||||
<Button Content="Detecter cameras et microphones" Command="{Binding DetectDevicesCommand}" />
|
||||
<ComboBox ItemsSource="{Binding Cameras}" SelectedItem="{Binding SelectedCamera}" PlaceholderText="Camera">
|
||||
<ComboBox.ItemTemplate>
|
||||
<DataTemplate x:DataType="vm:CaptureDevice"><TextBlock Text="{Binding Name}" /></DataTemplate>
|
||||
<DataTemplate x:DataType="services:CaptureDevice"><TextBlock Text="{Binding Name}" /></DataTemplate>
|
||||
</ComboBox.ItemTemplate>
|
||||
</ComboBox>
|
||||
<ComboBox ItemsSource="{Binding Microphones}" SelectedItem="{Binding SelectedMicrophone}" PlaceholderText="Microphone">
|
||||
<ComboBox.ItemTemplate>
|
||||
<DataTemplate x:DataType="vm:CaptureDevice"><TextBlock Text="{Binding Name}" /></DataTemplate>
|
||||
<DataTemplate x:DataType="services:CaptureDevice"><TextBlock Text="{Binding Name}" /></DataTemplate>
|
||||
</ComboBox.ItemTemplate>
|
||||
</ComboBox>
|
||||
<Button Content="Demarrer le direct" Command="{Binding StartCommand}" />
|
||||
|
|
|
|||
|
|
@ -20,6 +20,8 @@ namespace Yavsc.Billing
|
|||
|
||||
DateTime? ValidationDate { get; }
|
||||
|
||||
PaymentSummary? PaymentSummary { get; }
|
||||
|
||||
bool GetIsAcquitted ();
|
||||
|
||||
string GetFileBaseName (IBillingService service);
|
||||
|
|
|
|||
38
src/Yavsc.Abstract/Billing/InvoiceDtos.cs
Normal file
38
src/Yavsc.Abstract/Billing/InvoiceDtos.cs
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
#nullable enable
|
||||
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace Yavsc.Billing;
|
||||
|
||||
/// <summary>A frozen invoice line copied from the signed estimate.</summary>
|
||||
public sealed record InvoiceLineResponse(string Name, string Description, int Count, decimal UnitaryCost);
|
||||
|
||||
/// <summary>An invoice and its cumulative settlement balance.</summary>
|
||||
public sealed record InvoiceResponse(
|
||||
long CommandId, long EstimateId, string Reference, string ClientId, string PerformerId,
|
||||
DateTimeOffset CreatedAtUtc, string Currency, decimal AmountDue, decimal AmountPaid,
|
||||
decimal AmountRemaining, string PaymentStatus, bool IsAcquitted,
|
||||
IReadOnlyList<InvoiceLineResponse> Lines, IReadOnlyList<InvoicePaymentResponse> Payments);
|
||||
|
||||
/// <summary>An immutable recorded receipt, not an instruction to debit the client.</summary>
|
||||
public sealed record InvoicePaymentResponse(
|
||||
long Id, string Source, string Reference, decimal Amount, string Currency,
|
||||
DateTimeOffset ReceivedAtUtc, DateTimeOffset RecordedAtUtc, string RecordedBy);
|
||||
|
||||
/// <summary>A receipt attested by the invoice's performer.</summary>
|
||||
public sealed record RecordInvoicePaymentRequest
|
||||
{
|
||||
[Required, MaxLength(128)]
|
||||
public required string Reference { get; init; }
|
||||
public required decimal Amount { get; init; }
|
||||
[Required, StringLength(3, MinimumLength = 3)]
|
||||
public required string Currency { get; init; }
|
||||
public required DateTimeOffset ReceivedAtUtc { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>A PayPal transaction identifier to verify on the server; no client amount is trusted.</summary>
|
||||
public sealed record VerifyInvoicePayPalRequest
|
||||
{
|
||||
[Required, MaxLength(128)]
|
||||
public required string TransactionId { get; init; }
|
||||
}
|
||||
8
src/Yavsc.Abstract/Billing/PaymentStatus.cs
Normal file
8
src/Yavsc.Abstract/Billing/PaymentStatus.cs
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
namespace Yavsc.Billing;
|
||||
|
||||
public enum PaymentStatus
|
||||
{
|
||||
Unpaid,
|
||||
PartiallyPaid,
|
||||
Paid
|
||||
}
|
||||
21
src/Yavsc.Abstract/Billing/PaymentSummary.cs
Normal file
21
src/Yavsc.Abstract/Billing/PaymentSummary.cs
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
namespace Yavsc.Billing;
|
||||
|
||||
public sealed class PaymentSummary
|
||||
{
|
||||
public PaymentSummary(decimal amountDue, decimal amountPaid)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(amountDue);
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(amountPaid);
|
||||
|
||||
AmountDue = amountDue;
|
||||
AmountPaid = amountPaid;
|
||||
}
|
||||
|
||||
public decimal AmountDue { get; }
|
||||
public decimal AmountPaid { get; }
|
||||
public decimal AmountRemaining => Math.Max(0m, AmountDue - AmountPaid);
|
||||
public bool IsAcquitted => AmountPaid >= AmountDue;
|
||||
public PaymentStatus Status => IsAcquitted
|
||||
? PaymentStatus.Paid
|
||||
: AmountPaid > 0m ? PaymentStatus.PartiallyPaid : PaymentStatus.Unpaid;
|
||||
}
|
||||
50
src/Yavsc.Api.Client/InvoicesApiClient.cs
Normal file
50
src/Yavsc.Api.Client/InvoicesApiClient.cs
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
using System;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Yavsc.Billing;
|
||||
|
||||
namespace Yavsc.Api.Client;
|
||||
|
||||
public sealed class InvoicesApiClient
|
||||
{
|
||||
private readonly IYavscApiClient _api;
|
||||
private readonly Func<string> _businessBaseAddress;
|
||||
|
||||
public InvoicesApiClient(IYavscApiClient api, Func<string> businessBaseAddress)
|
||||
{
|
||||
_api = api ?? throw new ArgumentNullException(nameof(api));
|
||||
_businessBaseAddress = businessBaseAddress ?? throw new ArgumentNullException(nameof(businessBaseAddress));
|
||||
}
|
||||
|
||||
public Task<InvoiceResponse> GenerateAsync(long estimateId, CancellationToken ct = default)
|
||||
=> CallAsync(HttpMethod.Post, $"from-estimate/{PositiveId(estimateId)}", null, ct);
|
||||
|
||||
public Task<InvoiceResponse> GetAsync(long commandId, CancellationToken ct = default)
|
||||
=> CallAsync(HttpMethod.Get, $"{PositiveId(commandId)}", null, ct);
|
||||
|
||||
public Task<InvoiceResponse> RecordOfflineAsync(long commandId, RecordInvoicePaymentRequest request, CancellationToken ct = default)
|
||||
=> CallAsync(HttpMethod.Post, $"{PositiveId(commandId)}/payments/offline",
|
||||
request ?? throw new ArgumentNullException(nameof(request)), ct);
|
||||
|
||||
public Task<InvoiceResponse> VerifyPayPalAsync(long commandId, string transactionId, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(transactionId);
|
||||
return CallAsync(HttpMethod.Post, $"{PositiveId(commandId)}/payments/paypal",
|
||||
new VerifyInvoicePayPalRequest { TransactionId = transactionId }, ct);
|
||||
}
|
||||
|
||||
private Task<InvoiceResponse> CallAsync(HttpMethod method, string path, object? body, CancellationToken ct)
|
||||
{
|
||||
var baseAddress = _businessBaseAddress();
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(baseAddress);
|
||||
return _api.CallAsync<InvoiceResponse>(method, new Uri(new Uri(baseAddress, UriKind.Absolute), $"invoices/{path}").ToString(),
|
||||
body: body, ct: ct);
|
||||
}
|
||||
|
||||
private static long PositiveId(long id)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(id);
|
||||
return id;
|
||||
}
|
||||
}
|
||||
|
|
@ -89,6 +89,8 @@ namespace Yavsc.ApiControllers
|
|||
{
|
||||
return new ChallengeResult();
|
||||
}
|
||||
if (bill is not NominativeServiceCommand { InvoiceEstimateId: not null })
|
||||
return Conflict(new { Error = "Create the invoice from a signed estimate first." });
|
||||
Response.ContentType = "text/x-tex";
|
||||
return ViewComponent("Bill",new object[] { billingCode, bill , OutputFormat.LaTeX, true });
|
||||
}
|
||||
|
|
@ -103,6 +105,10 @@ namespace Yavsc.ApiControllers
|
|||
return this.NotFound();
|
||||
}
|
||||
logger.LogWarning("Got bill ack:"+bill.GetIsAcquitted().ToString());
|
||||
if (bill is not NominativeServiceCommand { InvoiceEstimateId: not null } invoice)
|
||||
return Conflict(new { Error = "Create the invoice from a signed estimate first." });
|
||||
if (User.GetUserId() != invoice.InvoicePerformerId && !User.IsInRole(Constants.AdminGroupName))
|
||||
return Forbid();
|
||||
return ViewComponent("Bill",new object[] { billingCode, bill, OutputFormat.Pdf, true } );
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -193,6 +193,8 @@ namespace Yavsc.Controllers
|
|||
return BadRequest(ModelState);
|
||||
}
|
||||
}
|
||||
if (_context.NominativeServiceCommands.Any(command => command.InvoiceEstimateId == id))
|
||||
return Conflict(new { Error = "An invoiced estimate cannot be deleted." });
|
||||
_context.Estimates.Remove(estimate);
|
||||
_context.SaveChanges(User.GetUserId());
|
||||
|
||||
|
|
|
|||
|
|
@ -154,6 +154,9 @@ public class HairCutQueryApiController : Controller
|
|||
return BadRequest(ModelState);
|
||||
}
|
||||
|
||||
if (existing.InvoiceEstimateId.HasValue && existing.PerformerId != query.PerformerId)
|
||||
return Conflict(new { Error = "An invoiced command cannot change performer." });
|
||||
|
||||
existing.ActivityCode = query.ActivityCode;
|
||||
existing.PerformerId = query.PerformerId;
|
||||
existing.Consent = query.Consent;
|
||||
|
|
@ -187,6 +190,8 @@ public class HairCutQueryApiController : Controller
|
|||
return Forbid();
|
||||
}
|
||||
|
||||
if (query.InvoiceEstimateId.HasValue)
|
||||
return Conflict(new { Error = "An invoiced command cannot be deleted." });
|
||||
_context.HairCutQueries.Remove(query);
|
||||
await _context.SaveChangesAsync(User.GetUserId(), cancellationToken);
|
||||
|
||||
|
|
|
|||
|
|
@ -170,6 +170,8 @@ public class HairMultiCutQueryApiController : Controller
|
|||
return BadRequest(ModelState);
|
||||
}
|
||||
|
||||
if (existing.InvoiceEstimateId.HasValue && existing.PerformerId != query.PerformerId)
|
||||
return Conflict(new { Error = "An invoiced command cannot change performer." });
|
||||
_context.RemoveRange(existing.Prestations);
|
||||
existing.ActivityCode = query.ActivityCode;
|
||||
existing.PerformerId = query.PerformerId;
|
||||
|
|
@ -203,6 +205,8 @@ public class HairMultiCutQueryApiController : Controller
|
|||
return Forbid();
|
||||
}
|
||||
|
||||
if (query.InvoiceEstimateId.HasValue)
|
||||
return Conflict(new { Error = "An invoiced command cannot be deleted." });
|
||||
_context.RemoveRange(query.Prestations);
|
||||
_context.HairMultiCutQueries.Remove(query);
|
||||
await _context.SaveChangesAsync(User.GetUserId(), cancellationToken);
|
||||
|
|
|
|||
59
src/Yavsc.Api/Controllers/Business/InvoicesController.cs
Normal file
59
src/Yavsc.Api/Controllers/Business/InvoicesController.cs
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Yavsc.Billing;
|
||||
using Yavsc.Server.Helpers;
|
||||
using Yavsc.Services;
|
||||
|
||||
namespace Yavsc.ApiControllers;
|
||||
|
||||
[Authorize, ApiController, Route(Constants.APIPrefix + "/invoices")]
|
||||
[Produces("application/json")]
|
||||
[ApiExplorerSettings(GroupName = "invoicing")]
|
||||
public sealed class InvoicesController(IInvoicingService invoices, ILogger<InvoicesController> logger) : ControllerBase
|
||||
{
|
||||
/// <summary>Creates a frozen invoice from an estimate signed by both parties, or returns its existing invoice.</summary>
|
||||
[HttpPost("from-estimate/{estimateId:long}")]
|
||||
[ProducesResponseType<InvoiceResponse>(StatusCodes.Status201Created)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
|
||||
public Task<ActionResult<InvoiceResponse>> Generate(long estimateId, CancellationToken ct)
|
||||
=> ExecuteAsync(() => invoices.GenerateAsync(estimateId, User.GetUserId(), IsAdmin, ct), created: true);
|
||||
|
||||
/// <summary>Returns the invoice, balance and receipt history to its parties.</summary>
|
||||
[HttpGet("{commandId:long}")]
|
||||
[ProducesResponseType<InvoiceResponse>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status404NotFound)]
|
||||
public Task<ActionResult<InvoiceResponse>> Get(long commandId, CancellationToken ct)
|
||||
=> ExecuteAsync(() => invoices.GetAsync(commandId, User.GetUserId(), IsAdmin, ct));
|
||||
|
||||
/// <summary>Records an offline receipt attested by the performer, idempotently by reference.</summary>
|
||||
[HttpPost("{commandId:long}/payments/offline")]
|
||||
[ProducesResponseType<InvoiceResponse>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
|
||||
public Task<ActionResult<InvoiceResponse>> RecordOffline(long commandId, RecordInvoicePaymentRequest request, CancellationToken ct)
|
||||
=> ExecuteAsync(() => invoices.RecordOfflineAsync(commandId, request, User.GetUserId(), IsAdmin, ct));
|
||||
|
||||
/// <summary>Verifies a completed PayPal transaction server-side before recording its receipt.</summary>
|
||||
[HttpPost("{commandId:long}/payments/paypal")]
|
||||
[ProducesResponseType<InvoiceResponse>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status502BadGateway)]
|
||||
public Task<ActionResult<InvoiceResponse>> VerifyPayPal(long commandId, VerifyInvoicePayPalRequest request, CancellationToken ct)
|
||||
=> ExecuteAsync(() => invoices.VerifyPayPalAsync(commandId, request.TransactionId, User.GetUserId(), IsAdmin, ct));
|
||||
|
||||
private bool IsAdmin => User.IsInRole(Constants.AdminGroupName);
|
||||
|
||||
private async Task<ActionResult<InvoiceResponse>> ExecuteAsync(Func<Task<InvoiceResponse>> action, bool created = false)
|
||||
{
|
||||
try
|
||||
{
|
||||
var invoice = await action();
|
||||
return created
|
||||
? CreatedAtAction(nameof(Get), new { commandId = invoice.CommandId }, invoice)
|
||||
: Ok(invoice);
|
||||
}
|
||||
catch (InvoiceOperationException exception)
|
||||
{
|
||||
logger.LogWarning("Invoice operation rejected ({StatusCode}): {Reason}", exception.StatusCode, exception.Message);
|
||||
return Problem(statusCode: exception.StatusCode, title: exception.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -162,6 +162,9 @@ public class RdvQueryApiController : Controller
|
|||
return Forbid();
|
||||
}
|
||||
|
||||
if (existing.InvoiceEstimateId.HasValue && existing.PerformerId != query.PerformerId)
|
||||
return Conflict(new { Error = "An invoiced command cannot change performer." });
|
||||
|
||||
existing.ActivityCode = query.ActivityCode;
|
||||
existing.PerformerId = query.PerformerId;
|
||||
existing.Consent = query.Consent;
|
||||
|
|
@ -224,6 +227,8 @@ public class RdvQueryApiController : Controller
|
|||
return Forbid();
|
||||
}
|
||||
|
||||
if (query.InvoiceEstimateId.HasValue)
|
||||
return Conflict(new { Error = "An invoiced command cannot be deleted." });
|
||||
_context.RdvQueries.Remove(query);
|
||||
await _context.SaveChangesAsync(User.GetUserId(), cancellationToken);
|
||||
|
||||
|
|
|
|||
|
|
@ -88,7 +88,22 @@ namespace Yavsc.ApiControllers
|
|||
return BadRequest();
|
||||
}
|
||||
|
||||
var persisted = await _context.HairCutQueries.AsNoTracking().SingleOrDefaultAsync(q => q.Id == id);
|
||||
if (persisted is null) return NotFound();
|
||||
if (persisted.InvoiceEstimateId.HasValue
|
||||
&& (persisted.ClientId != hairCutQuery.ClientId || persisted.PerformerId != hairCutQuery.PerformerId))
|
||||
return Conflict(new { Error = "An invoiced command cannot change parties." });
|
||||
_context.Entry(hairCutQuery).State = EntityState.Modified;
|
||||
_context.Entry(hairCutQuery).Property(q => q.PaymentRevision).OriginalValue = persisted.PaymentRevision;
|
||||
_context.Entry(hairCutQuery).Property(q => q.AmountDue).IsModified = false;
|
||||
_context.Entry(hairCutQuery).Property(q => q.AmountPaid).IsModified = false;
|
||||
_context.Entry(hairCutQuery).Property(q => q.InvoiceEstimateId).IsModified = false;
|
||||
_context.Entry(hairCutQuery).Property(q => q.InvoicedAtUtc).IsModified = false;
|
||||
_context.Entry(hairCutQuery).Property(q => q.InvoiceCurrency).IsModified = false;
|
||||
_context.Entry(hairCutQuery).Property(q => q.InvoiceClientId).IsModified = false;
|
||||
_context.Entry(hairCutQuery).Property(q => q.InvoicePerformerId).IsModified = false;
|
||||
_context.Entry(hairCutQuery).Property(q => q.InvoiceLinesJson).IsModified = false;
|
||||
_context.Entry(hairCutQuery).Property(q => q.PaymentRevision).IsModified = false;
|
||||
|
||||
try
|
||||
{
|
||||
|
|
@ -204,6 +219,8 @@ namespace Yavsc.ApiControllers
|
|||
return NotFound();
|
||||
}
|
||||
|
||||
if (hairCutQuery.InvoiceEstimateId.HasValue)
|
||||
return Conflict(new { Error = "An invoiced command cannot be deleted." });
|
||||
_context.HairCutQueries.Remove(hairCutQuery);
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
|
|
|
|||
51
src/Yavsc.Api/Invoicing.http
Normal file
51
src/Yavsc.Api/Invoicing.http
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
@baseUrl = https://localhost:5001/api/v1
|
||||
@providerToken = replace-with-provider-access-token
|
||||
@clientToken = replace-with-client-access-token
|
||||
@estimateId = 1
|
||||
@commandId = 1
|
||||
@paypalTransactionId = replace-with-completed-paypal-transaction-id
|
||||
|
||||
### Create an invoice from an estimate with both persisted signatures (performer)
|
||||
POST {{baseUrl}}/invoices/from-estimate/{{estimateId}}
|
||||
Authorization: Bearer {{providerToken}}
|
||||
|
||||
### Read its frozen lines, balance and receipt history (either party)
|
||||
GET {{baseUrl}}/invoices/{{commandId}}
|
||||
Authorization: Bearer {{clientToken}}
|
||||
|
||||
### Record an offline receipt (performer); replay the exact body to test idempotence
|
||||
POST {{baseUrl}}/invoices/{{commandId}}/payments/offline
|
||||
Authorization: Bearer {{providerToken}}
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"reference": "bank-transfer-2026-001",
|
||||
"amount": 30.00,
|
||||
"currency": "EUR",
|
||||
"receivedAtUtc": "2026-10-19T12:00:00Z"
|
||||
}
|
||||
|
||||
### Verify an already captured PayPal transaction (either party); not a checkout token
|
||||
POST {{baseUrl}}/invoices/{{commandId}}/payments/paypal
|
||||
Authorization: Bearer {{clientToken}}
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"transactionId": "{{paypalTransactionId}}"
|
||||
}
|
||||
|
||||
### Missing invoice -> 404
|
||||
GET {{baseUrl}}/invoices/999999999
|
||||
Authorization: Bearer {{providerToken}}
|
||||
|
||||
### A client cannot attest an offline receipt -> 403
|
||||
POST {{baseUrl}}/invoices/{{commandId}}/payments/offline
|
||||
Authorization: Bearer {{clientToken}}
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"reference": "not-authorized",
|
||||
"amount": 30.00,
|
||||
"currency": "EUR",
|
||||
"receivedAtUtc": "2026-10-19T12:00:00Z"
|
||||
}
|
||||
|
|
@ -72,6 +72,7 @@ internal class Program
|
|||
// the document-generation flow and BillingController.
|
||||
services.Configure<SiteSettings>(builder.Configuration.GetSection("Site"));
|
||||
services.AddPodcasts(builder.Configuration);
|
||||
services.AddInvoicing(builder.Configuration);
|
||||
|
||||
// accepts any access token issued by identity server
|
||||
services.AddAuthentication("Bearer")
|
||||
|
|
|
|||
|
|
@ -0,0 +1,17 @@
|
|||
using Yavsc.Services;
|
||||
|
||||
namespace Yavsc.Api.Services;
|
||||
|
||||
public static class InvoicingServiceCollectionExtensions
|
||||
{
|
||||
public static IServiceCollection AddInvoicing(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
services.AddScoped<IInvoicingService, InvoicingService>();
|
||||
services.Configure<PayPalSettings>(configuration.GetSection("Authentication:PayPal"));
|
||||
services.AddHttpClient<IPayPalTransactionVerifier, PayPalTransactionVerifier>(client =>
|
||||
client.Timeout = TimeSpan.FromSeconds(30));
|
||||
services.AddOpenApi("invoicing", options =>
|
||||
options.ShouldInclude = description => description.GroupName == "invoicing");
|
||||
return services;
|
||||
}
|
||||
}
|
||||
|
|
@ -147,6 +147,8 @@ namespace Yavsc.Controllers
|
|||
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
if (query.ClientId != uid)
|
||||
return new ChallengeResult();
|
||||
if (query.InvoiceEstimateId.HasValue)
|
||||
return Conflict(new { Error = "An invoiced command cannot be deleted." });
|
||||
_context.HairCutQueries.Remove(query);
|
||||
await _context.SaveChangesAsync();
|
||||
return await Index();
|
||||
|
|
|
|||
|
|
@ -158,6 +158,8 @@ namespace Yavsc.Controllers
|
|||
public async Task<IActionResult> DeleteConfirmed(long id)
|
||||
{
|
||||
Project project = await _context.Project.SingleAsync(m => m.Id == id);
|
||||
if (project.InvoiceEstimateId.HasValue)
|
||||
return Conflict(new { Error = "An invoiced command cannot be deleted." });
|
||||
_context.Project.Remove(project);
|
||||
await _context.SaveChangesAsync();
|
||||
return RedirectToAction("Index");
|
||||
|
|
|
|||
4867
src/Yavsc.Org/Migrations/20261019182518_InvoicePaymentAmounts.Designer.cs
generated
Normal file
4867
src/Yavsc.Org/Migrations/20261019182518_InvoicePaymentAmounts.Designer.cs
generated
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -0,0 +1,39 @@
|
|||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Yavsc.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class InvoicePaymentAmounts : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<decimal>(
|
||||
name: "AmountDue",
|
||||
table: "NominativeServiceCommands",
|
||||
type: "numeric",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<decimal>(
|
||||
name: "AmountPaid",
|
||||
table: "NominativeServiceCommands",
|
||||
type: "numeric",
|
||||
nullable: false,
|
||||
defaultValue: 0m);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropColumn(
|
||||
name: "AmountDue",
|
||||
table: "NominativeServiceCommands");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "AmountPaid",
|
||||
table: "NominativeServiceCommands");
|
||||
}
|
||||
}
|
||||
}
|
||||
4966
src/Yavsc.Org/Migrations/20261019184909_SignedEstimateInvoicing.Designer.cs
generated
Normal file
4966
src/Yavsc.Org/Migrations/20261019184909_SignedEstimateInvoicing.Designer.cs
generated
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -0,0 +1,155 @@
|
|||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Yavsc.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class SignedEstimateInvoicing : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "InvoiceClientId",
|
||||
table: "NominativeServiceCommands",
|
||||
type: "text",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "InvoiceCurrency",
|
||||
table: "NominativeServiceCommands",
|
||||
type: "character varying(3)",
|
||||
maxLength: 3,
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<long>(
|
||||
name: "InvoiceEstimateId",
|
||||
table: "NominativeServiceCommands",
|
||||
type: "bigint",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "InvoiceLinesJson",
|
||||
table: "NominativeServiceCommands",
|
||||
type: "text",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "InvoicePerformerId",
|
||||
table: "NominativeServiceCommands",
|
||||
type: "text",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<DateTimeOffset>(
|
||||
name: "InvoicedAtUtc",
|
||||
table: "NominativeServiceCommands",
|
||||
type: "timestamp with time zone",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<Guid>(
|
||||
name: "PaymentRevision",
|
||||
table: "NominativeServiceCommands",
|
||||
type: "uuid",
|
||||
nullable: false,
|
||||
defaultValue: new Guid("00000000-0000-0000-0000-000000000000"));
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "InvoicePayments",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<long>(type: "bigint", nullable: false)
|
||||
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
|
||||
CommandId = table.Column<long>(type: "bigint", nullable: false),
|
||||
Source = table.Column<string>(type: "character varying(16)", maxLength: 16, nullable: false),
|
||||
ReferenceScope = table.Column<string>(type: "character varying(450)", maxLength: 450, nullable: false),
|
||||
Reference = table.Column<string>(type: "character varying(128)", maxLength: 128, nullable: false),
|
||||
Amount = table.Column<decimal>(type: "numeric", nullable: false),
|
||||
Currency = table.Column<string>(type: "character varying(3)", maxLength: 3, nullable: false),
|
||||
ReceivedAtUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
|
||||
RecordedAtUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
|
||||
RecordedBy = table.Column<string>(type: "character varying(450)", maxLength: 450, nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_InvoicePayments", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_InvoicePayments_NominativeServiceCommands_CommandId",
|
||||
column: x => x.CommandId,
|
||||
principalTable: "NominativeServiceCommands",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Restrict);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_NominativeServiceCommands_InvoiceEstimateId",
|
||||
table: "NominativeServiceCommands",
|
||||
column: "InvoiceEstimateId",
|
||||
unique: true);
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_InvoicePayments_CommandId",
|
||||
table: "InvoicePayments",
|
||||
column: "CommandId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_InvoicePayments_Source_ReferenceScope_Reference",
|
||||
table: "InvoicePayments",
|
||||
columns: new[] { "Source", "ReferenceScope", "Reference" },
|
||||
unique: true);
|
||||
|
||||
migrationBuilder.AddForeignKey(
|
||||
name: "FK_NominativeServiceCommands_Estimates_InvoiceEstimateId",
|
||||
table: "NominativeServiceCommands",
|
||||
column: "InvoiceEstimateId",
|
||||
principalTable: "Estimates",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Restrict);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropForeignKey(
|
||||
name: "FK_NominativeServiceCommands_Estimates_InvoiceEstimateId",
|
||||
table: "NominativeServiceCommands");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "InvoicePayments");
|
||||
|
||||
migrationBuilder.DropIndex(
|
||||
name: "IX_NominativeServiceCommands_InvoiceEstimateId",
|
||||
table: "NominativeServiceCommands");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "InvoiceClientId",
|
||||
table: "NominativeServiceCommands");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "InvoiceCurrency",
|
||||
table: "NominativeServiceCommands");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "InvoiceEstimateId",
|
||||
table: "NominativeServiceCommands");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "InvoiceLinesJson",
|
||||
table: "NominativeServiceCommands");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "InvoicePerformerId",
|
||||
table: "NominativeServiceCommands");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "InvoicedAtUtc",
|
||||
table: "NominativeServiceCommands");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "PaymentRevision",
|
||||
table: "NominativeServiceCommands");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -17,7 +17,7 @@ namespace Yavsc.Migrations
|
|||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "10.0.12")
|
||||
.HasAnnotation("ProductVersion", "10.0.13")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
|
@ -1442,6 +1442,61 @@ namespace Yavsc.Migrations
|
|||
b.ToTable("ExceptionsSIREN");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Yavsc.Models.Billing.InvoicePayment", b =>
|
||||
{
|
||||
b.Property<long>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("bigint");
|
||||
|
||||
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
|
||||
|
||||
b.Property<decimal>("Amount")
|
||||
.HasColumnType("numeric");
|
||||
|
||||
b.Property<long>("CommandId")
|
||||
.HasColumnType("bigint");
|
||||
|
||||
b.Property<string>("Currency")
|
||||
.IsRequired()
|
||||
.HasMaxLength(3)
|
||||
.HasColumnType("character varying(3)");
|
||||
|
||||
b.Property<DateTimeOffset>("ReceivedAtUtc")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<DateTimeOffset>("RecordedAtUtc")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("RecordedBy")
|
||||
.IsRequired()
|
||||
.HasMaxLength(450)
|
||||
.HasColumnType("character varying(450)");
|
||||
|
||||
b.Property<string>("Reference")
|
||||
.IsRequired()
|
||||
.HasMaxLength(128)
|
||||
.HasColumnType("character varying(128)");
|
||||
|
||||
b.Property<string>("ReferenceScope")
|
||||
.IsRequired()
|
||||
.HasMaxLength(450)
|
||||
.HasColumnType("character varying(450)");
|
||||
|
||||
b.Property<string>("Source")
|
||||
.IsRequired()
|
||||
.HasMaxLength(16)
|
||||
.HasColumnType("character varying(16)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("CommandId");
|
||||
|
||||
b.HasIndex("Source", "ReferenceScope", "Reference")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("InvoicePayments");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Yavsc.Models.Billing.NominativeServiceCommand", b =>
|
||||
{
|
||||
b.Property<long>("Id")
|
||||
|
|
@ -1454,6 +1509,14 @@ namespace Yavsc.Migrations
|
|||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<decimal?>("AmountDue")
|
||||
.HasColumnType("numeric");
|
||||
|
||||
b.Property<decimal>("AmountPaid")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("numeric")
|
||||
.HasDefaultValue(0m);
|
||||
|
||||
b.Property<string>("ClientId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
|
@ -1476,9 +1539,34 @@ namespace Yavsc.Migrations
|
|||
.HasMaxLength(34)
|
||||
.HasColumnType("character varying(34)");
|
||||
|
||||
b.Property<string>("InvoiceClientId")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("InvoiceCurrency")
|
||||
.HasMaxLength(3)
|
||||
.HasColumnType("character varying(3)");
|
||||
|
||||
b.Property<long?>("InvoiceEstimateId")
|
||||
.HasColumnType("bigint");
|
||||
|
||||
b.Property<string>("InvoiceLinesJson")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("InvoicePerformerId")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTimeOffset?>("InvoicedAtUtc")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("PaymentId")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<Guid>("PaymentRevision")
|
||||
.IsConcurrencyToken()
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasDefaultValue(new Guid("00000000-0000-0000-0000-000000000000"));
|
||||
|
||||
b.Property<string>("PerformerId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
|
@ -1506,6 +1594,9 @@ namespace Yavsc.Migrations
|
|||
|
||||
b.HasIndex("ClientId");
|
||||
|
||||
b.HasIndex("InvoiceEstimateId")
|
||||
.IsUnique();
|
||||
|
||||
b.HasIndex("PaymentId");
|
||||
|
||||
b.HasIndex("PerformerId");
|
||||
|
|
@ -3945,6 +4036,17 @@ namespace Yavsc.Migrations
|
|||
b.Navigation("File");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Yavsc.Models.Billing.InvoicePayment", b =>
|
||||
{
|
||||
b.HasOne("Yavsc.Models.Billing.NominativeServiceCommand", "Command")
|
||||
.WithMany()
|
||||
.HasForeignKey("CommandId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Command");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Yavsc.Models.Billing.NominativeServiceCommand", b =>
|
||||
{
|
||||
b.HasOne("Yavsc.Models.Workflow.Activity", "Context")
|
||||
|
|
@ -3959,6 +4061,11 @@ namespace Yavsc.Migrations
|
|||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("Yavsc.Models.Billing.Estimate", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("InvoiceEstimateId")
|
||||
.OnDelete(DeleteBehavior.Restrict);
|
||||
|
||||
b.HasOne("Yavsc.Models.Payment.PayPalPayment", "Regularization")
|
||||
.WithMany()
|
||||
.HasForeignKey("PaymentId");
|
||||
|
|
|
|||
|
|
@ -18,6 +18,12 @@ namespace Yavsc.Helpers
|
|||
string total = query.GetBillItems().Addition().ToString("C", CultureInfo.CurrentUICulture);
|
||||
string bill = string.Join("\n", query.GetBillItems().Select(l=> $"{l.Name} {l.Description} : {l.UnitaryCost} € " + ((l.Count != 1) ? "*"+l.Count.ToString() : ""))) +
|
||||
$"\n\nTotal: {total}";
|
||||
if (query.PaymentSummary is { } payment)
|
||||
{
|
||||
bill += $"\nPaid: {payment.AmountPaid.ToString("C", CultureInfo.CurrentUICulture)}"
|
||||
+ $"\nRemaining: {payment.AmountRemaining.ToString("C", CultureInfo.CurrentUICulture)}"
|
||||
+ $"\nStatus: {payment.Status}";
|
||||
}
|
||||
return bill;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ using Yavsc.ViewModels.PayPal;
|
|||
using Yavsc.Models;
|
||||
using Yavsc.Models.Payment;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System.Globalization;
|
||||
|
||||
namespace Yavsc.Helpers
|
||||
{
|
||||
|
|
@ -72,7 +73,7 @@ namespace Yavsc.Helpers
|
|||
public static SetExpressCheckoutResponseType CreatePayment(this HttpRequest request, string controllerName, NominativeServiceCommand query, string intent = "sale", ILogger logger = null)
|
||||
{
|
||||
var items = query.GetBillItems();
|
||||
var total = items.Addition().ToString("F2");
|
||||
var total = items.Addition().ToString("F2", CultureInfo.InvariantCulture);
|
||||
var coreq = new SetExpressCheckoutReq {};
|
||||
var urls = request.GetPaymentUrls(controllerName, query.Id.ToString());
|
||||
|
||||
|
|
@ -89,7 +90,7 @@ namespace Yavsc.Helpers
|
|||
},
|
||||
PaymentDetailsItem = new List <PaymentDetailsItemType> (
|
||||
items.Select(i => new PaymentDetailsItemType {
|
||||
Amount = new BasicAmountType { currencyID = CurrencyCodeType.EUR, value = i.UnitaryCost.ToString("F2") },
|
||||
Amount = new BasicAmountType { currencyID = CurrencyCodeType.EUR, value = i.UnitaryCost.ToString("F2", CultureInfo.InvariantCulture) },
|
||||
Name = i.Name,
|
||||
Quantity = i.Count,
|
||||
Description = i.Description
|
||||
|
|
|
|||
|
|
@ -117,7 +117,8 @@ namespace Yavsc.Helpers
|
|||
((db, id) =>
|
||||
{
|
||||
var query = db.HairCutQueries.Include(q => q.Prestation).Include(q => q.Regularization).Single(q => q.Id == id);
|
||||
query.SelectedProfile = db.BrusherProfile.Single(b => b.UserId == query.PerformerId);
|
||||
if (!query.InvoiceEstimateId.HasValue)
|
||||
query.SelectedProfile = db.BrusherProfile.Single(b => b.UserId == query.PerformerId);
|
||||
return query;
|
||||
}));
|
||||
|
||||
|
|
|
|||
|
|
@ -58,6 +58,26 @@ namespace Yavsc.Models
|
|||
}
|
||||
builder.UseIdentityByDefaultColumns();
|
||||
|
||||
builder.Entity<NominativeServiceCommand>()
|
||||
.Property(command => command.AmountPaid)
|
||||
.HasDefaultValue(0m);
|
||||
builder.Entity<NominativeServiceCommand>()
|
||||
.Property(command => command.PaymentRevision)
|
||||
.HasDefaultValue(Guid.Empty);
|
||||
builder.Entity<NominativeServiceCommand>()
|
||||
.HasOne<Estimate>().WithMany()
|
||||
.HasForeignKey(command => command.InvoiceEstimateId)
|
||||
.OnDelete(DeleteBehavior.Restrict);
|
||||
builder.Entity<NominativeServiceCommand>()
|
||||
.HasIndex(command => command.InvoiceEstimateId).IsUnique();
|
||||
builder.Entity<InvoicePayment>()
|
||||
.HasIndex(payment => new { payment.Source, payment.ReferenceScope, payment.Reference })
|
||||
.IsUnique();
|
||||
builder.Entity<InvoicePayment>()
|
||||
.HasOne(payment => payment.Command).WithMany()
|
||||
.HasForeignKey(payment => payment.CommandId)
|
||||
.OnDelete(DeleteBehavior.Restrict);
|
||||
|
||||
builder.Entity<ResourceUsageRecord>(entity =>
|
||||
{
|
||||
entity.HasKey(r => r.Id);
|
||||
|
|
@ -354,6 +374,7 @@ namespace Yavsc.Models
|
|||
public DbSet<BlogTag> TagsDomain { get; set; }
|
||||
|
||||
public DbSet<EstimateTemplate> EstimateTemplates { get; set; }
|
||||
public DbSet<InvoicePayment> InvoicePayments { get; set; }
|
||||
|
||||
public DbSet<Contact> Contact { get; set; }
|
||||
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ namespace Yavsc.Server.Models.Billing;
|
|||
|
||||
public class FrontmatterOffreResult
|
||||
{
|
||||
public string Formulaire { get; set; }
|
||||
public string Devis { get; set; }
|
||||
public string Corps { get; set; } // le Markdown sans l'en-tête
|
||||
public string Formulaire { get; set; } = string.Empty;
|
||||
public string Devis { get; set; } = string.Empty;
|
||||
public string Corps { get; set; } = string.Empty; // le Markdown sans l'en-tête
|
||||
}
|
||||
|
|
|
|||
28
src/Yavsc.Server/Models/Billing/InvoicePayment.cs
Normal file
28
src/Yavsc.Server/Models/Billing/InvoicePayment.cs
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
#nullable enable
|
||||
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Yavsc.Models.Billing;
|
||||
|
||||
public sealed class InvoicePayment
|
||||
{
|
||||
public long Id { get; set; }
|
||||
public long CommandId { get; set; }
|
||||
[ForeignKey(nameof(CommandId)), JsonIgnore, Newtonsoft.Json.JsonIgnore]
|
||||
public NominativeServiceCommand Command { get; set; } = null!;
|
||||
[MaxLength(16)]
|
||||
public string Source { get; set; } = "";
|
||||
[MaxLength(450)]
|
||||
public string ReferenceScope { get; set; } = "";
|
||||
[MaxLength(128)]
|
||||
public string Reference { get; set; } = "";
|
||||
public decimal Amount { get; set; }
|
||||
[MaxLength(3)]
|
||||
public string Currency { get; set; } = "";
|
||||
public DateTimeOffset ReceivedAtUtc { get; set; }
|
||||
public DateTimeOffset RecordedAtUtc { get; set; }
|
||||
[MaxLength(450)]
|
||||
public string RecordedBy { get; set; } = "";
|
||||
}
|
||||
|
|
@ -80,9 +80,76 @@ namespace Yavsc.Models.Billing
|
|||
|
||||
public abstract System.Collections.Generic.List<IBillItem> GetBillItems();
|
||||
|
||||
/// <summary>
|
||||
/// Null until an invoice total has been established; never inferred
|
||||
/// from a provisional price or a payment gateway acknowledgement.
|
||||
/// </summary>
|
||||
public decimal? AmountDue { get; private set; }
|
||||
|
||||
public decimal AmountPaid { get; private set; }
|
||||
|
||||
public long? InvoiceEstimateId { get; private set; }
|
||||
public DateTimeOffset? InvoicedAtUtc { get; private set; }
|
||||
[MaxLength(3)]
|
||||
public string? InvoiceCurrency { get; private set; }
|
||||
public string? InvoiceClientId { get; private set; }
|
||||
public string? InvoicePerformerId { get; private set; }
|
||||
[JsonIgnore, System.Text.Json.Serialization.JsonIgnore]
|
||||
public string? InvoiceLinesJson { get; private set; }
|
||||
[ConcurrencyCheck]
|
||||
public Guid PaymentRevision { get; private set; }
|
||||
|
||||
public void EstablishInvoice(long estimateId, string currency, IReadOnlyList<InvoiceLineResponse> lines)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(lines);
|
||||
if (InvoiceEstimateId.HasValue || AmountDue.HasValue || AmountPaid != 0m)
|
||||
throw new InvalidOperationException("A balance or invoice already exists for this command.");
|
||||
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(estimateId);
|
||||
if (currency != "EUR" || lines.Count == 0
|
||||
|| lines.Any(line => line.Count <= 0 || decimal.Round(line.UnitaryCost, 2) != line.UnitaryCost))
|
||||
throw new ArgumentException("An invoice requires EUR lines with positive quantities.");
|
||||
var due = lines.Sum(line => checked(line.Count * line.UnitaryCost));
|
||||
SetPaymentAmounts(due, 0m);
|
||||
InvoiceEstimateId = estimateId;
|
||||
InvoiceCurrency = currency;
|
||||
InvoiceClientId = ClientId;
|
||||
InvoicePerformerId = PerformerId;
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
InvoicedAtUtc = new DateTimeOffset(now.UtcTicks - now.UtcTicks % 10, TimeSpan.Zero);
|
||||
InvoiceLinesJson = System.Text.Json.JsonSerializer.Serialize(lines);
|
||||
}
|
||||
|
||||
public List<IBillItem> GetInvoiceBillItems()
|
||||
{
|
||||
if (InvoiceLinesJson is null || InvoiceCurrency is null)
|
||||
throw new InvalidOperationException("The invoice has no frozen lines.");
|
||||
var lines = System.Text.Json.JsonSerializer.Deserialize<List<InvoiceLineResponse>>(InvoiceLinesJson)
|
||||
?? throw new InvalidOperationException("The invoice lines are invalid.");
|
||||
return lines.Select(line => (IBillItem)new CommandLine
|
||||
{
|
||||
Name = line.Name, Description = line.Description,
|
||||
Count = line.Count, UnitaryCost = line.UnitaryCost, Currency = InvoiceCurrency
|
||||
}).ToList();
|
||||
}
|
||||
|
||||
[NotMapped]
|
||||
public PaymentSummary? PaymentSummary => AmountDue.HasValue
|
||||
? new PaymentSummary(AmountDue.Value, AmountPaid)
|
||||
: null;
|
||||
|
||||
public void SetPaymentAmounts(decimal amountDue, decimal amountPaid)
|
||||
{
|
||||
if (InvoiceEstimateId.HasValue && AmountDue != amountDue)
|
||||
throw new InvalidOperationException("An established invoice total cannot be changed.");
|
||||
var summary = new PaymentSummary(amountDue, amountPaid);
|
||||
AmountDue = summary.AmountDue;
|
||||
AmountPaid = summary.AmountPaid;
|
||||
PaymentRevision = Guid.NewGuid();
|
||||
}
|
||||
|
||||
public bool GetIsAcquitted()
|
||||
{
|
||||
return Regularization?.IsOk() ?? false;
|
||||
return PaymentSummary?.IsAcquitted ?? false;
|
||||
}
|
||||
|
||||
public string GetFileBaseName(IBillingService billingService)
|
||||
|
|
|
|||
|
|
@ -60,6 +60,7 @@ namespace Yavsc.Models.Haircut
|
|||
|
||||
public override List<IBillItem> GetBillItems()
|
||||
{
|
||||
if (InvoiceEstimateId.HasValue) return GetInvoiceBillItems();
|
||||
string longhairsuffix = " (cheveux longs)";
|
||||
string halflonghairsuffix = " (cheveux mi-longs)";
|
||||
string shorthairsuffix = " (cheveux courts)";
|
||||
|
|
|
|||
|
|
@ -39,6 +39,7 @@ namespace Yavsc.Models.Haircut
|
|||
|
||||
public override List<IBillItem> GetBillItems()
|
||||
{
|
||||
if (InvoiceEstimateId.HasValue) return GetInvoiceBillItems();
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -44,6 +44,7 @@ namespace Yavsc.Server.Models.IT
|
|||
}
|
||||
public override List<IBillItem> GetBillItems()
|
||||
{
|
||||
if (InvoiceEstimateId.HasValue) return GetInvoiceBillItems();
|
||||
return bill;
|
||||
}
|
||||
|
||||
|
|
@ -62,4 +63,3 @@ namespace Yavsc.Server.Models.IT
|
|||
}
|
||||
}
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -71,6 +71,7 @@ namespace Yavsc.Models.Workflow
|
|||
|
||||
public override List<IBillItem> GetBillItems()
|
||||
{
|
||||
if (InvoiceEstimateId.HasValue) return GetInvoiceBillItems();
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,8 +6,8 @@ namespace Yavsc.Server.Services;
|
|||
|
||||
public static class FrontmatterParser
|
||||
{
|
||||
public const string YamlHeader = "---\n";
|
||||
public const string YamlSeparator = "\n---";
|
||||
public const string YamlHeader = "---";
|
||||
public const string YamlSeparator = "---";
|
||||
|
||||
private static readonly IDeserializer _deserializer =
|
||||
new DeserializerBuilder()
|
||||
|
|
@ -17,17 +17,23 @@ public static class FrontmatterParser
|
|||
|
||||
public static FrontmatterOffreResult Parse(string markdown)
|
||||
{
|
||||
// Le contenu doit commencer par ----
|
||||
if (!markdown.TrimStart().StartsWith(YamlHeader, StringComparison.Ordinal))
|
||||
ArgumentNullException.ThrowIfNull(markdown);
|
||||
|
||||
var trimmed = markdown.TrimStart();
|
||||
|
||||
if (!trimmed.StartsWith(YamlHeader, StringComparison.Ordinal))
|
||||
return new FrontmatterOffreResult { Corps = markdown };
|
||||
|
||||
var parts = markdown.Substring(YamlHeader.Length).Trim().Split(new[] { YamlSeparator }, 2,
|
||||
StringSplitOptions.None);
|
||||
var afterOpeningMarker = trimmed[YamlHeader.Length..];
|
||||
var parts = afterOpeningMarker
|
||||
.Split(new[] { "\r\n---", "\n---" }, 2, StringSplitOptions.None);
|
||||
|
||||
if (parts.Length < 2)
|
||||
return new FrontmatterOffreResult { Corps = markdown };
|
||||
var yamlBlock = parts[0];
|
||||
var corps = parts[1];
|
||||
var meta = _deserializer.Deserialize<FrontmatterOffreResult>(yamlBlock);
|
||||
|
||||
var yamlBlock = parts[0].Trim();
|
||||
var corps = parts[1].TrimStart();
|
||||
var meta = _deserializer.Deserialize<FrontmatterOffreResult>(yamlBlock) ?? new FrontmatterOffreResult();
|
||||
meta.Corps = corps;
|
||||
return meta;
|
||||
}
|
||||
|
|
|
|||
191
src/Yavsc.Server/Services/InvoicingService.cs
Normal file
191
src/Yavsc.Server/Services/InvoicingService.cs
Normal file
|
|
@ -0,0 +1,191 @@
|
|||
#nullable enable
|
||||
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Yavsc.Billing;
|
||||
using Yavsc.Models;
|
||||
using Yavsc.Models.Billing;
|
||||
|
||||
namespace Yavsc.Services;
|
||||
|
||||
public interface IInvoicingService
|
||||
{
|
||||
Task<InvoiceResponse> GenerateAsync(long estimateId, string actorId, bool administrator, CancellationToken ct);
|
||||
Task<InvoiceResponse> GetAsync(long commandId, string actorId, bool administrator, CancellationToken ct);
|
||||
Task<InvoiceResponse> RecordOfflineAsync(long commandId, RecordInvoicePaymentRequest request, string actorId, bool administrator, CancellationToken ct);
|
||||
Task<InvoiceResponse> VerifyPayPalAsync(long commandId, string transactionId, string actorId, bool administrator, CancellationToken ct);
|
||||
}
|
||||
|
||||
public sealed class InvoiceOperationException(int statusCode, string message) : Exception(message)
|
||||
{
|
||||
public int StatusCode { get; } = statusCode;
|
||||
}
|
||||
|
||||
public sealed class InvoicingService(ApplicationDbContext db, IPayPalTransactionVerifier payPal) : IInvoicingService
|
||||
{
|
||||
public async Task<InvoiceResponse> GenerateAsync(long estimateId, string actorId, bool administrator, CancellationToken ct)
|
||||
{
|
||||
var estimate = await db.Estimates.Include(e => e.Bill).Include(e => e.Signatures)
|
||||
.SingleOrDefaultAsync(e => e.Id == estimateId, ct)
|
||||
?? throw new InvoiceOperationException(404, "Estimate not found.");
|
||||
RequirePerformer(actorId, estimate.OwnerId, administrator);
|
||||
if (!estimate.CommandId.HasValue)
|
||||
throw new InvoiceOperationException(409, "The estimate must be attached to a command.");
|
||||
|
||||
var command = await db.NominativeServiceCommands.SingleOrDefaultAsync(q => q.Id == estimate.CommandId, ct)
|
||||
?? throw new InvoiceOperationException(409, "The estimate's command no longer exists.");
|
||||
if (command.InvoiceEstimateId == estimateId)
|
||||
{
|
||||
RequirePerformer(actorId, command.InvoicePerformerId!, administrator);
|
||||
return await ResponseAsync(command, ct);
|
||||
}
|
||||
if (command.InvoiceEstimateId.HasValue || command.AmountDue.HasValue || command.AmountPaid != 0m)
|
||||
throw new InvoiceOperationException(409, "This command already has an invoice or a balance requiring reconciliation.");
|
||||
if (command.ClientId != estimate.ClientId || command.PerformerId != estimate.OwnerId)
|
||||
throw new InvoiceOperationException(409, "The estimate and command must have the same client and performer.");
|
||||
if (estimate.ProviderValidationDate == default || estimate.ClientValidationDate == default
|
||||
|| estimate.SignaturePro?.SignerId != estimate.OwnerId || estimate.SignatureClient?.SignerId != estimate.ClientId
|
||||
|| estimate.SignaturePro.Strokes.Length == 0 || estimate.SignatureClient.Strokes.Length == 0)
|
||||
throw new InvoiceOperationException(409, "Both parties must have signed and validated the estimate.");
|
||||
if (estimate.Bill.Count == 0 || estimate.Bill.Any(line => line.Currency != "EUR" || line.Count <= 0
|
||||
|| decimal.Round(line.UnitaryCost, 2) != line.UnitaryCost))
|
||||
throw new InvoiceOperationException(409, "The estimate requires EUR lines with positive quantities and prices in whole cents.");
|
||||
|
||||
var lines = estimate.Bill.Select(line => new InvoiceLineResponse(
|
||||
line.Name, line.Description, line.Count, line.UnitaryCost)).ToList();
|
||||
decimal due;
|
||||
try
|
||||
{
|
||||
due = lines.Sum(line => checked(line.Count * line.UnitaryCost));
|
||||
}
|
||||
catch (OverflowException)
|
||||
{
|
||||
throw new InvoiceOperationException(409, "The estimate total is too large.");
|
||||
}
|
||||
if (due < 0m)
|
||||
throw new InvoiceOperationException(409, "The invoice total cannot be negative.");
|
||||
|
||||
command.EstablishInvoice(estimateId, "EUR", lines);
|
||||
await SaveAsync(actorId, ct);
|
||||
return await ResponseAsync(command, ct);
|
||||
}
|
||||
|
||||
public async Task<InvoiceResponse> GetAsync(long commandId, string actorId, bool administrator, CancellationToken ct)
|
||||
{
|
||||
var command = await LoadAsync(commandId, actorId, administrator, ct);
|
||||
return await ResponseAsync(command, ct);
|
||||
}
|
||||
|
||||
public async Task<InvoiceResponse> RecordOfflineAsync(long commandId, RecordInvoicePaymentRequest request,
|
||||
string actorId, bool administrator, CancellationToken ct)
|
||||
{
|
||||
var command = await LoadAsync(commandId, actorId, administrator, ct);
|
||||
RequirePerformer(actorId, command.InvoicePerformerId!, administrator);
|
||||
if (string.IsNullOrWhiteSpace(request.Reference) || request.Reference.Length > 128
|
||||
|| request.Reference != request.Reference.Trim() || request.Amount <= 0m
|
||||
|| decimal.Round(request.Amount, 2) != request.Amount
|
||||
|| request.Currency != command.InvoiceCurrency || request.ReceivedAtUtc == default
|
||||
|| request.ReceivedAtUtc > DateTimeOffset.UtcNow)
|
||||
throw new InvoiceOperationException(400, "A positive receipt, invoice currency, reference and non-future receipt date are required.");
|
||||
return await RecordAsync(command, "Offline", command.InvoicePerformerId!, request.Reference, request.Amount,
|
||||
request.Currency, request.ReceivedAtUtc.ToUniversalTime(), actorId, ct);
|
||||
}
|
||||
|
||||
public async Task<InvoiceResponse> VerifyPayPalAsync(long commandId, string transactionId,
|
||||
string actorId, bool administrator, CancellationToken ct)
|
||||
{
|
||||
var command = await LoadAsync(commandId, actorId, administrator, ct);
|
||||
if (string.IsNullOrWhiteSpace(transactionId) || transactionId.Length > 128 || transactionId != transactionId.Trim())
|
||||
throw new InvoiceOperationException(400, "A PayPal transaction identifier is required.");
|
||||
var receipt = await payPal.VerifyAsync(transactionId, command.GetInvoiceId(), command.InvoiceCurrency!, ct);
|
||||
return await RecordAsync(command, "PayPal", "", receipt.TransactionId, receipt.Amount,
|
||||
receipt.Currency, receipt.ReceivedAtUtc, actorId, ct);
|
||||
}
|
||||
|
||||
private async Task<InvoiceResponse> RecordAsync(NominativeServiceCommand command, string source, string scope,
|
||||
string reference, decimal amount, string currency, DateTimeOffset receivedAtUtc, string actorId, CancellationToken ct)
|
||||
{
|
||||
// PostgreSQL persists microseconds; normalize before comparing a replay.
|
||||
receivedAtUtc = new DateTimeOffset(receivedAtUtc.UtcTicks - receivedAtUtc.UtcTicks % 10, TimeSpan.Zero);
|
||||
var existing = await db.InvoicePayments.SingleOrDefaultAsync(
|
||||
payment => payment.Source == source && payment.ReferenceScope == scope && payment.Reference == reference, ct);
|
||||
if (existing is not null)
|
||||
{
|
||||
if (existing.CommandId != command.Id || existing.Amount != amount || existing.Currency != currency
|
||||
|| existing.ReceivedAtUtc != receivedAtUtc)
|
||||
throw new InvoiceOperationException(409, "The receipt reference is already used with different details.");
|
||||
return await ResponseAsync(command, ct);
|
||||
}
|
||||
|
||||
var payments = await db.InvoicePayments.Where(payment => payment.CommandId == command.Id).ToListAsync(ct);
|
||||
var total = payments.Sum(payment => payment.Amount);
|
||||
if (command.AmountPaid != total)
|
||||
throw new InvoiceOperationException(409, "The recorded balance requires reconciliation with the receipt history.");
|
||||
try
|
||||
{
|
||||
command.SetPaymentAmounts(command.AmountDue!.Value, checked(total + amount));
|
||||
}
|
||||
catch (OverflowException)
|
||||
{
|
||||
throw new InvoiceOperationException(400, "The cumulative payment amount is too large.");
|
||||
}
|
||||
db.InvoicePayments.Add(new InvoicePayment
|
||||
{
|
||||
CommandId = command.Id, Source = source, ReferenceScope = scope, Reference = reference,
|
||||
Amount = amount, Currency = currency, ReceivedAtUtc = receivedAtUtc,
|
||||
RecordedAtUtc = DateTimeOffset.UtcNow, RecordedBy = actorId
|
||||
});
|
||||
await SaveAsync(actorId, ct);
|
||||
return await ResponseAsync(command, ct);
|
||||
}
|
||||
|
||||
private async Task<NominativeServiceCommand> LoadAsync(long commandId, string actorId, bool administrator, CancellationToken ct)
|
||||
{
|
||||
var command = await db.NominativeServiceCommands.SingleOrDefaultAsync(q => q.Id == commandId, ct)
|
||||
?? throw new InvoiceOperationException(404, "Invoice not found.");
|
||||
if (!command.InvoiceEstimateId.HasValue)
|
||||
throw new InvoiceOperationException(404, "Invoice not found.");
|
||||
if (!administrator && actorId != command.InvoiceClientId && actorId != command.InvoicePerformerId)
|
||||
throw new InvoiceOperationException(403, "Only the invoice parties may access it.");
|
||||
return command;
|
||||
}
|
||||
|
||||
private async Task<InvoiceResponse> ResponseAsync(NominativeServiceCommand command, CancellationToken ct)
|
||||
{
|
||||
var payments = await db.InvoicePayments.AsNoTracking().Where(payment => payment.CommandId == command.Id)
|
||||
.OrderBy(payment => payment.Id).ToListAsync(ct);
|
||||
var summary = new PaymentSummary(command.AmountDue
|
||||
?? throw new InvalidOperationException("An established invoice must have a balance."),
|
||||
payments.Sum(payment => payment.Amount));
|
||||
var lines = command.GetInvoiceBillItems().Select(line =>
|
||||
new InvoiceLineResponse(line.Name, line.Description, line.Count, line.UnitaryCost)).ToList();
|
||||
return new InvoiceResponse(command.Id, command.InvoiceEstimateId!.Value, command.GetInvoiceId(),
|
||||
command.InvoiceClientId!, command.InvoicePerformerId!, command.InvoicedAtUtc!.Value, command.InvoiceCurrency!,
|
||||
summary.AmountDue, summary.AmountPaid, summary.AmountRemaining, summary.Status.ToString(), summary.IsAcquitted,
|
||||
lines, payments.Select(payment => new InvoicePaymentResponse(
|
||||
payment.Id, payment.Source, payment.Reference, payment.Amount, payment.Currency,
|
||||
payment.ReceivedAtUtc, payment.RecordedAtUtc, payment.RecordedBy)).ToList());
|
||||
}
|
||||
|
||||
private async Task SaveAsync(string actorId, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
await db.SaveChangesAsync(actorId, ct);
|
||||
}
|
||||
catch (DbUpdateConcurrencyException)
|
||||
{
|
||||
throw new InvoiceOperationException(409, "The invoice changed concurrently. Retry the same request.");
|
||||
}
|
||||
catch (DbUpdateException exception) when (exception.InnerException is
|
||||
System.Data.Common.DbException { SqlState: Npgsql.PostgresErrorCodes.UniqueViolation })
|
||||
{
|
||||
throw new InvoiceOperationException(409, "The invoice or receipt reference already exists. Retry the same request.");
|
||||
}
|
||||
}
|
||||
|
||||
private static void RequirePerformer(string actorId, string performerId, bool administrator)
|
||||
{
|
||||
if (!administrator && actorId != performerId)
|
||||
throw new InvoiceOperationException(403, "Only the performer may perform this operation.");
|
||||
}
|
||||
}
|
||||
77
src/Yavsc.Server/Services/PayPalTransactionVerifier.cs
Normal file
77
src/Yavsc.Server/Services/PayPalTransactionVerifier.cs
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
#nullable enable
|
||||
|
||||
using System.Globalization;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Yavsc.Services;
|
||||
|
||||
public sealed record VerifiedPayPalReceipt(string TransactionId, decimal Amount, string Currency, DateTimeOffset ReceivedAtUtc);
|
||||
|
||||
public interface IPayPalTransactionVerifier
|
||||
{
|
||||
Task<VerifiedPayPalReceipt> VerifyAsync(string transactionId, string invoiceReference, string currency, CancellationToken ct);
|
||||
}
|
||||
|
||||
public sealed class PayPalTransactionVerifier(HttpClient http, IOptions<PayPalSettings> options) : IPayPalTransactionVerifier
|
||||
{
|
||||
public async Task<VerifiedPayPalReceipt> VerifyAsync(string transactionId, string invoiceReference, string currency, CancellationToken ct)
|
||||
{
|
||||
var settings = options.Value;
|
||||
var accounts = settings.Accounts?.Where(account => account.ApiUsername == settings.MerchantAccountUserName).ToArray();
|
||||
if (accounts is not { Length: 1 })
|
||||
throw new InvoiceOperationException(503, "PayPal transaction verification requires one matching merchant account.");
|
||||
var credentials = accounts[0];
|
||||
if (string.IsNullOrWhiteSpace(credentials.ApiUsername)
|
||||
|| string.IsNullOrWhiteSpace(credentials.ApiPassword) || string.IsNullOrWhiteSpace(credentials.Signature)
|
||||
|| string.IsNullOrWhiteSpace(settings.MerchantAccountId) || settings.Mode is not ("production" or "sandbox"))
|
||||
throw new InvoiceOperationException(503, "PayPal transaction verification is not configured.");
|
||||
var endpoint = settings.Mode == "production"
|
||||
? "https://api-3t.paypal.com/nvp" : "https://api-3t.sandbox.paypal.com/nvp";
|
||||
using var content = new FormUrlEncodedContent(new Dictionary<string, string>
|
||||
{
|
||||
["METHOD"] = "GetTransactionDetails", ["VERSION"] = "124.0",
|
||||
["USER"] = credentials.ApiUsername, ["PWD"] = credentials.ApiPassword,
|
||||
["SIGNATURE"] = credentials.Signature, ["TRANSACTIONID"] = transactionId
|
||||
});
|
||||
|
||||
string body;
|
||||
try
|
||||
{
|
||||
using var response = await http.PostAsync(endpoint, content, ct);
|
||||
if (!response.IsSuccessStatusCode)
|
||||
throw new InvoiceOperationException(502, "PayPal transaction verification failed.");
|
||||
body = await response.Content.ReadAsStringAsync(ct);
|
||||
}
|
||||
catch (HttpRequestException)
|
||||
{
|
||||
throw new InvoiceOperationException(502, "PayPal is unavailable. No receipt was recorded.");
|
||||
}
|
||||
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
|
||||
{
|
||||
throw new InvoiceOperationException(504, "PayPal verification timed out. No receipt was recorded.");
|
||||
}
|
||||
|
||||
var fields = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
foreach (var pair in body.Split('&'))
|
||||
{
|
||||
var parts = pair.Split('=', 2);
|
||||
if (parts.Length != 2 || !fields.TryAdd(Decode(parts[0]), Decode(parts[1])))
|
||||
throw new InvoiceOperationException(502, "PayPal returned an invalid verification response.");
|
||||
}
|
||||
string? Field(string name) => fields.GetValueOrDefault(name);
|
||||
if (Field("ACK") is not ("Success" or "SuccessWithWarning"))
|
||||
throw new InvoiceOperationException(502, "PayPal did not verify the transaction.");
|
||||
if (Field("TRANSACTIONID") != transactionId || Field("INVNUM") != invoiceReference
|
||||
|| Field("RECEIVERID") != settings.MerchantAccountId || Field("CURRENCYCODE") != currency
|
||||
|| Field("PAYMENTSTATUS") != "Completed")
|
||||
throw new InvoiceOperationException(409, "The PayPal receipt is not a completed payment for this invoice, currency and merchant.");
|
||||
if (!decimal.TryParse(Field("AMT"), NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var amount)
|
||||
|| amount <= 0m || decimal.Round(amount, 2) != amount
|
||||
|| !DateTimeOffset.TryParse(Field("ORDERTIME"), CultureInfo.InvariantCulture,
|
||||
DateTimeStyles.AssumeUniversal, out var receivedAt) || receivedAt == default || receivedAt > DateTimeOffset.UtcNow)
|
||||
throw new InvoiceOperationException(502, "PayPal returned an invalid receipt amount or date.");
|
||||
return new VerifiedPayPalReceipt(transactionId, amount, currency, receivedAt.ToUniversalTime());
|
||||
}
|
||||
|
||||
private static string Decode(string value) => Uri.UnescapeDataString(value.Replace("+", " "));
|
||||
}
|
||||
|
|
@ -78,6 +78,7 @@ public sealed class ApiWebServerFixture : WebHostFixture
|
|||
builder.Services.Configure<GoogleAuthSettings>(_ => { });
|
||||
builder.Services.Configure<SiteSettings>(settings => settings.Authority = "example.test");
|
||||
builder.Services.AddTransient<IBillingService, BillingService>();
|
||||
builder.Services.AddInvoicing(builder.Configuration);
|
||||
builder.Services.AddSingleton<RecordingMessageDelivery>();
|
||||
builder.Services.AddSingleton<ITrueEmailSender>(sp => sp.GetRequiredService<RecordingMessageDelivery>());
|
||||
builder.Services.AddSingleton<IHubContext<ChatHub>>(sp => sp.GetRequiredService<RecordingMessageDelivery>());
|
||||
|
|
|
|||
|
|
@ -1,8 +1,12 @@
|
|||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Yavsc.ApiControllers;
|
||||
using Yavsc.Billing;
|
||||
using Yavsc.Api.Test.Fixtures;
|
||||
using Yavsc.Models;
|
||||
using Yavsc.Models.Haircut;
|
||||
|
|
@ -75,6 +79,14 @@ public sealed class HairCutQueryApiControllerTests : IClassFixture<ApiWebServerF
|
|||
Assert.NotEqual(0, created!.Id);
|
||||
Assert.Equal("alice", created.ClientId);
|
||||
|
||||
using (var scope = _fixture.Services.CreateScope())
|
||||
{
|
||||
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
var command = await db.HairCutQueries.SingleAsync(q => q.Id == created.Id, TestContext.Current.CancellationToken);
|
||||
command.SetPaymentAmounts(100m, 30m);
|
||||
await db.SaveChangesAsync("alice", TestContext.Current.CancellationToken);
|
||||
}
|
||||
|
||||
var getResponse = await http.GetAsync($"/api/v1/billing/Brush/{created.Id}", TestContext.Current.CancellationToken);
|
||||
Assert.Equal(HttpStatusCode.OK, getResponse.StatusCode);
|
||||
|
||||
|
|
@ -87,6 +99,15 @@ public sealed class HairCutQueryApiControllerTests : IClassFixture<ApiWebServerF
|
|||
var putResponse = await http.PutAsJsonAsync($"/api/v1/billing/Brush/{fetched.Id}", fetched, TestContext.Current.CancellationToken);
|
||||
Assert.Equal(HttpStatusCode.NoContent, putResponse.StatusCode);
|
||||
|
||||
using (var scope = _fixture.Services.CreateScope())
|
||||
{
|
||||
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
var command = await db.HairCutQueries.SingleAsync(q => q.Id == created.Id, TestContext.Current.CancellationToken);
|
||||
Assert.Equal(100m, command.AmountDue);
|
||||
Assert.Equal(30m, command.AmountPaid);
|
||||
Assert.False(command.GetIsAcquitted());
|
||||
}
|
||||
|
||||
var deleteResponse = await http.DeleteAsync($"/api/v1/billing/Brush/{fetched.Id}", TestContext.Current.CancellationToken);
|
||||
Assert.Equal(HttpStatusCode.OK, deleteResponse.StatusCode);
|
||||
|
||||
|
|
@ -111,6 +132,58 @@ public sealed class HairCutQueryApiControllerTests : IClassFixture<ApiWebServerF
|
|||
&& item.Details == "Coupe · Brushing · Aucune technique spécifique · Shampoing · Sans soins");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Legacy_haircut_update_preserves_persisted_payment_amounts()
|
||||
{
|
||||
_fixture.ResetAndSeedHaircutGraph();
|
||||
HairCutQuery payload;
|
||||
using (var scope = _fixture.Services.CreateScope())
|
||||
{
|
||||
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
var command = await db.HairCutQueries.SingleAsync(TestContext.Current.CancellationToken);
|
||||
var estimate = new Yavsc.Models.Billing.Estimate
|
||||
{
|
||||
CommandId = command.Id, ClientId = command.ClientId, OwnerId = command.PerformerId,
|
||||
CommandType = "Brush", Title = "Invoice test", Description = "Invoice test",
|
||||
Bill = [], AttachedFiles = [], AttachedGraphics = []
|
||||
};
|
||||
db.Estimates.Add(estimate);
|
||||
await db.SaveChangesAsync("alice", TestContext.Current.CancellationToken);
|
||||
command.EstablishInvoice(estimate.Id, "EUR", [new InvoiceLineResponse("Service", "Service", 1, 100m)]);
|
||||
command.SetPaymentAmounts(100m, 30m);
|
||||
await db.SaveChangesAsync("alice", TestContext.Current.CancellationToken);
|
||||
payload = Newtonsoft.Json.JsonConvert.DeserializeObject<HairCutQuery>(
|
||||
Newtonsoft.Json.JsonConvert.SerializeObject(command))!;
|
||||
}
|
||||
|
||||
Assert.Null(payload.AmountDue);
|
||||
Assert.Equal(0m, payload.AmountPaid);
|
||||
payload.AdditionalInfo = "Updated without payment amounts";
|
||||
|
||||
using (var scope = _fixture.Services.CreateScope())
|
||||
{
|
||||
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
var controller = new HairCutController(db, NullLoggerFactory.Instance);
|
||||
var response = await controller.PutHairCutQuery(payload.Id, payload);
|
||||
Assert.Equal(204, Assert.IsType<StatusCodeResult>(response).StatusCode);
|
||||
}
|
||||
|
||||
using (var scope = _fixture.Services.CreateScope())
|
||||
{
|
||||
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
var command = await db.HairCutQueries.SingleAsync(q => q.Id == payload.Id, TestContext.Current.CancellationToken);
|
||||
Assert.Equal(payload.AdditionalInfo, command.AdditionalInfo);
|
||||
Assert.Equal(100m, command.AmountDue);
|
||||
Assert.Equal(30m, command.AmountPaid);
|
||||
Assert.False(command.GetIsAcquitted());
|
||||
Assert.NotNull(command.InvoiceEstimateId);
|
||||
Assert.Equal("EUR", command.InvoiceCurrency);
|
||||
Assert.Equal("alice", command.InvoiceClientId);
|
||||
Assert.Equal("alice", command.InvoicePerformerId);
|
||||
Assert.Equal(100m, command.GetBillItems().Sum(item => item.Count * item.UnitaryCost));
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<long> GetPrestationIdAsync()
|
||||
{
|
||||
using var scope = _fixture.Services.CreateScope();
|
||||
|
|
|
|||
449
src/test/Yavsc.Api.Tests/InvoiceApiTests.cs
Normal file
449
src/test/Yavsc.Api.Tests/InvoiceApiTests.cs
Normal file
|
|
@ -0,0 +1,449 @@
|
|||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Diagnostics;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Yavsc.Api.Test.Fixtures;
|
||||
using Yavsc.Billing;
|
||||
using Yavsc.Helpers;
|
||||
using Yavsc.Models;
|
||||
using Yavsc.Models.Billing;
|
||||
using Yavsc.Models.Workflow;
|
||||
using Yavsc.Services;
|
||||
using Yavsc.Tests.Shared;
|
||||
|
||||
namespace Yavsc.Api.Test;
|
||||
|
||||
[Collection("Yavsc Api")]
|
||||
public sealed class InvoiceApiTests(ApiWebServerFixture fixture) : IClassFixture<ApiWebServerFixture>
|
||||
{
|
||||
private static CancellationToken Ct => TestContext.Current.CancellationToken;
|
||||
private static readonly DateTimeOffset Received = new(2026, 1, 2, 12, 0, 0, TimeSpan.Zero);
|
||||
|
||||
private HttpClient Client(string? subject = "alice")
|
||||
{
|
||||
var http = new HttpClient(new HttpClientHandler
|
||||
{
|
||||
ServerCertificateCustomValidationCallback = (_, _, _, _) => true
|
||||
}) { BaseAddress = new Uri(fixture.BaseAddress) };
|
||||
if (subject is not null)
|
||||
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", TestTokenIssuer.Issue(subject, "api"));
|
||||
return http;
|
||||
}
|
||||
|
||||
private (long Estimate, long Command) Seed(bool providerSignature = true, bool clientSignature = true, bool reset = true)
|
||||
{
|
||||
if (reset) fixture.ResetAndSeedActivityGraph();
|
||||
using var scope = fixture.Services.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
var command = new RdvQuery
|
||||
{
|
||||
ClientId = "bob", PerformerId = "alice", ActivityCode = "dev",
|
||||
Consent = true, Reason = "Invoice test", Location = db.Locations.Single(),
|
||||
EventDate = DateTime.UtcNow.AddDays(1), UserCreated = "alice", UserModified = "alice"
|
||||
};
|
||||
db.Add(command);
|
||||
db.SaveChanges();
|
||||
var estimate = new Estimate
|
||||
{
|
||||
CommandId = command.Id, ClientId = "bob", OwnerId = "alice", CommandType = BillingCodes.Rdv,
|
||||
Title = "Signed estimate", Description = "Invoice test",
|
||||
AttachedFiles = [], AttachedGraphics = [],
|
||||
ProviderValidationDate = DateTime.UtcNow, ClientValidationDate = DateTime.UtcNow,
|
||||
Bill =
|
||||
[
|
||||
new CommandLine { Name = "Service", Description = "Service", Count = 2, UnitaryCost = 60m },
|
||||
new CommandLine { Name = "Discount", Description = "Discount", Count = 1, UnitaryCost = -20m }
|
||||
]
|
||||
};
|
||||
db.Add(estimate);
|
||||
db.SaveChanges();
|
||||
if (providerSignature) db.Signatures.Add(Signature(estimate.Id, SignatureType.Pro, "alice"));
|
||||
if (clientSignature) db.Signatures.Add(Signature(estimate.Id, SignatureType.Client, "bob"));
|
||||
db.SaveChanges();
|
||||
return (estimate.Id, command.Id);
|
||||
}
|
||||
|
||||
private static Signature Signature(long estimateId, SignatureType type, string signer)
|
||||
=> new()
|
||||
{
|
||||
EstimateId = estimateId, Type = type, SignerId = signer, CoordinateMax = 10_000,
|
||||
CapturedAtUtc = DateTime.UtcNow, Strokes = [2, 0, 0, 100, 100]
|
||||
};
|
||||
|
||||
private static RecordInvoicePaymentRequest Receipt(string reference, decimal amount = 30m)
|
||||
=> new() { Reference = reference, Amount = amount, Currency = "EUR", ReceivedAtUtc = Received };
|
||||
|
||||
private static async Task<InvoiceResponse> InvoiceAsync(HttpResponseMessage response, HttpStatusCode expected)
|
||||
{
|
||||
var body = await response.Content.ReadAsStringAsync(Ct);
|
||||
Assert.True(response.StatusCode == expected, $"{response.StatusCode}: {body}");
|
||||
return (await response.Content.ReadFromJsonAsync<InvoiceResponse>(Ct))!;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Signed_estimate_creates_a_frozen_unpaid_invoice_and_generation_is_idempotent()
|
||||
{
|
||||
var (estimateId, commandId) = Seed();
|
||||
using var http = Client();
|
||||
using var created = await http.PostAsync($"/api/v1/invoices/from-estimate/{estimateId}", null, Ct);
|
||||
var invoice = await InvoiceAsync(created, HttpStatusCode.Created);
|
||||
Assert.EndsWith($"/api/v1/invoices/{commandId}", created.Headers.Location!.ToString());
|
||||
Assert.Equal(commandId, invoice.CommandId);
|
||||
Assert.Equal(estimateId, invoice.EstimateId);
|
||||
Assert.Equal("bob", invoice.ClientId);
|
||||
Assert.Equal("alice", invoice.PerformerId);
|
||||
Assert.Equal(100m, invoice.AmountDue);
|
||||
Assert.Equal(0m, invoice.AmountPaid);
|
||||
Assert.Equal(100m, invoice.AmountRemaining);
|
||||
Assert.Equal("Unpaid", invoice.PaymentStatus);
|
||||
Assert.False(invoice.IsAcquitted);
|
||||
Assert.Empty(invoice.Payments);
|
||||
using (var scope = fixture.Services.CreateScope())
|
||||
{
|
||||
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
var line = db.Estimates.Include(e => e.Bill).Single(e => e.Id == estimateId).Bill.First();
|
||||
line.UnitaryCost = 999m;
|
||||
db.SaveChanges();
|
||||
var command = db.RdvQueries.Single(q => q.Id == commandId);
|
||||
Assert.Equal(100m, command.GetBillItems().Sum(item => item.Count * item.UnitaryCost));
|
||||
}
|
||||
var repeated = await InvoiceAsync(
|
||||
await http.PostAsync($"/api/v1/invoices/from-estimate/{estimateId}", null, Ct), HttpStatusCode.Created);
|
||||
Assert.Equal(invoice.CreatedAtUtc, repeated.CreatedAtUtc);
|
||||
Assert.Equal(100m, repeated.AmountDue);
|
||||
Assert.Equal(invoice.Lines.ToArray(), repeated.Lines.ToArray());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false, false)]
|
||||
[InlineData(true, false)]
|
||||
[InlineData(false, true)]
|
||||
public async Task Dates_without_both_persisted_signatures_cannot_generate_an_invoice(bool provider, bool client)
|
||||
{
|
||||
var (estimateId, commandId) = Seed(provider, client);
|
||||
using var http = Client();
|
||||
var response = await http.PostAsync($"/api/v1/invoices/from-estimate/{estimateId}", null, Ct);
|
||||
Assert.Equal(HttpStatusCode.Conflict, response.StatusCode);
|
||||
using var scope = fixture.Services.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
Assert.Null(db.RdvQueries.Single(q => q.Id == commandId).AmountDue);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("wrong-signer")]
|
||||
[InlineData("missing-date")]
|
||||
[InlineData("wrong-client")]
|
||||
[InlineData("wrong-performer")]
|
||||
[InlineData("standalone")]
|
||||
[InlineData("negative-total")]
|
||||
[InlineData("wrong-currency")]
|
||||
[InlineData("invalid-quantity")]
|
||||
[InlineData("fractional-cent")]
|
||||
[InlineData("empty-signature")]
|
||||
public async Task Inconsistent_estimates_are_rejected(string fault)
|
||||
{
|
||||
var (estimateId, _) = Seed();
|
||||
using (var scope = fixture.Services.CreateScope())
|
||||
{
|
||||
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
var estimate = db.Estimates.Include(e => e.Bill).Include(e => e.Signatures).Single(e => e.Id == estimateId);
|
||||
switch (fault)
|
||||
{
|
||||
case "wrong-signer": estimate.SignatureClient!.SignerId = "alice"; break;
|
||||
case "missing-date": estimate.ClientValidationDate = default; break;
|
||||
case "wrong-client": estimate.ClientId = "alice"; break;
|
||||
case "wrong-performer": db.RdvQueries.Single().PerformerId = "bob"; break;
|
||||
case "standalone": estimate.CommandId = null; break;
|
||||
case "negative-total": estimate.Bill.ForEach(line => line.UnitaryCost = -1m); break;
|
||||
case "wrong-currency": estimate.Bill[0].Currency = "USD"; break;
|
||||
case "invalid-quantity": estimate.Bill[0].Count = 0; break;
|
||||
case "fractional-cent": estimate.Bill[0].UnitaryCost = 0.001m; break;
|
||||
case "empty-signature": estimate.SignatureClient!.Strokes = []; break;
|
||||
}
|
||||
db.SaveChanges();
|
||||
}
|
||||
using var http = Client();
|
||||
Assert.Equal(HttpStatusCode.Conflict,
|
||||
(await http.PostAsync($"/api/v1/invoices/from-estimate/{estimateId}", null, Ct)).StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Receipts_accumulate_idempotently_until_the_invoice_is_fully_paid()
|
||||
{
|
||||
var (estimateId, commandId) = Seed();
|
||||
using var http = Client();
|
||||
await InvoiceAsync(await http.PostAsync($"/api/v1/invoices/from-estimate/{estimateId}", null, Ct), HttpStatusCode.Created);
|
||||
var path = $"/api/v1/invoices/{commandId}/payments/offline";
|
||||
var partial = await InvoiceAsync(await http.PostAsJsonAsync(path, Receipt("bank-1"), Ct), HttpStatusCode.OK);
|
||||
Assert.Equal(30m, partial.AmountPaid);
|
||||
Assert.Equal(70m, partial.AmountRemaining);
|
||||
Assert.Equal("PartiallyPaid", partial.PaymentStatus);
|
||||
Assert.False(partial.IsAcquitted);
|
||||
Assert.Single(partial.Payments);
|
||||
using (var partialScope = fixture.Services.CreateScope())
|
||||
{
|
||||
var partialDb = partialScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
var partialCommand = partialDb.RdvQueries.Single(q => q.Id == commandId);
|
||||
Assert.Contains("Status: PartiallyPaid", partialCommand.GetBillText());
|
||||
Assert.DoesNotContain("Status: Paid", partialCommand.GetBillText());
|
||||
}
|
||||
var replay = await InvoiceAsync(await http.PostAsJsonAsync(path, Receipt("bank-1"), Ct), HttpStatusCode.OK);
|
||||
Assert.Equal(30m, replay.AmountPaid);
|
||||
Assert.Single(replay.Payments);
|
||||
Assert.Equal(HttpStatusCode.Conflict, (await http.PostAsJsonAsync(path, Receipt("bank-1", 31m), Ct)).StatusCode);
|
||||
var total = await InvoiceAsync(await http.PostAsJsonAsync(path, Receipt("cash-2", 70m), Ct), HttpStatusCode.OK);
|
||||
Assert.Equal(100m, total.AmountPaid);
|
||||
Assert.Equal(0m, total.AmountRemaining);
|
||||
Assert.True(total.IsAcquitted);
|
||||
Assert.Equal("Paid", total.PaymentStatus);
|
||||
Assert.Equal(2, total.Payments.Count);
|
||||
using var client = Client("bob");
|
||||
var read = await InvoiceAsync(await client.GetAsync($"/api/v1/invoices/{commandId}", Ct), HttpStatusCode.OK);
|
||||
Assert.Equal(100m, read.AmountPaid);
|
||||
using var scope = fixture.Services.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
var command = db.RdvQueries.Single(q => q.Id == commandId);
|
||||
Assert.Equal(100m, command.AmountPaid);
|
||||
Assert.True(command.GetIsAcquitted());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("negative")]
|
||||
[InlineData("zero")]
|
||||
[InlineData("currency")]
|
||||
[InlineData("date")]
|
||||
[InlineData("future")]
|
||||
[InlineData("fractional-cent")]
|
||||
public async Task Invalid_receipts_do_not_change_the_invoice(string fault)
|
||||
{
|
||||
var (estimateId, commandId) = Seed();
|
||||
using var http = Client();
|
||||
await InvoiceAsync(await http.PostAsync($"/api/v1/invoices/from-estimate/{estimateId}", null, Ct), HttpStatusCode.Created);
|
||||
var request = fault switch
|
||||
{
|
||||
"negative" => Receipt("bad") with { Amount = -1m },
|
||||
"zero" => Receipt("bad") with { Amount = 0m },
|
||||
"currency" => Receipt("bad") with { Currency = "USD" },
|
||||
"date" => Receipt("bad") with { ReceivedAtUtc = default },
|
||||
"future" => Receipt("bad") with { ReceivedAtUtc = DateTimeOffset.UtcNow.AddDays(1) },
|
||||
_ => Receipt("bad") with { Amount = 0.001m }
|
||||
};
|
||||
Assert.Equal(HttpStatusCode.BadRequest,
|
||||
(await http.PostAsJsonAsync($"/api/v1/invoices/{commandId}/payments/offline", request, Ct)).StatusCode);
|
||||
var invoice = await InvoiceAsync(await http.GetAsync($"/api/v1/invoices/{commandId}", Ct), HttpStatusCode.OK);
|
||||
Assert.Equal(0m, invoice.AmountPaid);
|
||||
Assert.Empty(invoice.Payments);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Only_performer_can_generate_or_attest_and_only_parties_can_read_or_verify()
|
||||
{
|
||||
var (estimateId, commandId) = Seed();
|
||||
using var provider = Client();
|
||||
using var client = Client("bob");
|
||||
using var outsider = Client("mallory");
|
||||
using var anonymous = Client(null);
|
||||
var generate = $"/api/v1/invoices/from-estimate/{estimateId}";
|
||||
Assert.Equal(HttpStatusCode.Forbidden, (await client.PostAsync(generate, null, Ct)).StatusCode);
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, (await anonymous.PostAsync(generate, null, Ct)).StatusCode);
|
||||
await InvoiceAsync(await provider.PostAsync(generate, null, Ct), HttpStatusCode.Created);
|
||||
Assert.Equal(HttpStatusCode.Forbidden,
|
||||
(await client.PostAsJsonAsync($"/api/v1/invoices/{commandId}/payments/offline", Receipt("bank-1"), Ct)).StatusCode);
|
||||
Assert.Equal(HttpStatusCode.Forbidden, (await outsider.GetAsync($"/api/v1/invoices/{commandId}", Ct)).StatusCode);
|
||||
Assert.Equal(HttpStatusCode.Forbidden, (await outsider.PostAsJsonAsync(
|
||||
$"/api/v1/invoices/{commandId}/payments/paypal", new { transactionId = "TX-1" }, Ct)).StatusCode);
|
||||
Assert.Equal(HttpStatusCode.NotFound, (await provider.GetAsync("/api/v1/invoices/999999999", Ct)).StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Unconfigured_paypal_never_creates_a_receipt()
|
||||
{
|
||||
var (estimateId, commandId) = Seed();
|
||||
using var http = Client();
|
||||
await InvoiceAsync(await http.PostAsync($"/api/v1/invoices/from-estimate/{estimateId}", null, Ct), HttpStatusCode.Created);
|
||||
var response = await http.PostAsJsonAsync($"/api/v1/invoices/{commandId}/payments/paypal", new { transactionId = "TX-1" }, Ct);
|
||||
Assert.Equal(HttpStatusCode.ServiceUnavailable, response.StatusCode);
|
||||
var invoice = await InvoiceAsync(await http.GetAsync($"/api/v1/invoices/{commandId}", Ct), HttpStatusCode.OK);
|
||||
Assert.Empty(invoice.Payments);
|
||||
Assert.Equal(0m, invoice.AmountPaid);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Verified_paypal_receipts_combine_with_offline_payments_without_double_counting()
|
||||
{
|
||||
var (estimateId, commandId) = Seed();
|
||||
using var http = Client();
|
||||
await InvoiceAsync(await http.PostAsync($"/api/v1/invoices/from-estimate/{estimateId}", null, Ct), HttpStatusCode.Created);
|
||||
await InvoiceAsync(await http.PostAsJsonAsync(
|
||||
$"/api/v1/invoices/{commandId}/payments/offline", Receipt("bank-1"), Ct), HttpStatusCode.OK);
|
||||
using (var scope = fixture.Services.CreateScope())
|
||||
{
|
||||
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
var service = new InvoicingService(db, new VerifiedPayPalStub());
|
||||
var invoice = await service.VerifyPayPalAsync(commandId, "TX-1", "bob", false, Ct);
|
||||
Assert.True(invoice.IsAcquitted);
|
||||
Assert.Equal(100m, invoice.AmountPaid);
|
||||
Assert.Equal(2, invoice.Payments.Count);
|
||||
}
|
||||
using (var scope = fixture.Services.CreateScope())
|
||||
{
|
||||
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
var service = new InvoicingService(db, new VerifiedPayPalStub());
|
||||
var invoice = await service.VerifyPayPalAsync(commandId, "TX-1", "bob", false, Ct);
|
||||
Assert.Equal(100m, invoice.AmountPaid);
|
||||
Assert.Equal(2, invoice.Payments.Count);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_receipt_reference_cannot_be_reused_for_another_invoice()
|
||||
{
|
||||
var first = Seed();
|
||||
var second = Seed(reset: false);
|
||||
using var http = Client();
|
||||
await InvoiceAsync(await http.PostAsync($"/api/v1/invoices/from-estimate/{first.Estimate}", null, Ct), HttpStatusCode.Created);
|
||||
await InvoiceAsync(await http.PostAsync($"/api/v1/invoices/from-estimate/{second.Estimate}", null, Ct), HttpStatusCode.Created);
|
||||
await InvoiceAsync(await http.PostAsJsonAsync(
|
||||
$"/api/v1/invoices/{first.Command}/payments/offline", Receipt("bank-1"), Ct), HttpStatusCode.OK);
|
||||
Assert.Equal(HttpStatusCode.Conflict, (await http.PostAsJsonAsync(
|
||||
$"/api/v1/invoices/{second.Command}/payments/offline", Receipt("bank-1"), Ct)).StatusCode);
|
||||
using (var scope = fixture.Services.CreateScope())
|
||||
{
|
||||
var service = new InvoicingService(scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(), new VerifiedPayPalStub());
|
||||
await service.VerifyPayPalAsync(first.Command, "TX-1", "bob", false, Ct);
|
||||
}
|
||||
using (var scope = fixture.Services.CreateScope())
|
||||
{
|
||||
var service = new InvoicingService(scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(), new VerifiedPayPalStub());
|
||||
var error = await Assert.ThrowsAsync<InvoiceOperationException>(
|
||||
() => service.VerifyPayPalAsync(second.Command, "TX-1", "bob", false, Ct));
|
||||
Assert.Equal(409, error.StatusCode);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Concurrent_receipts_are_atomic_and_the_losing_request_can_be_retried()
|
||||
{
|
||||
var (estimateId, commandId) = Seed();
|
||||
using var http = Client();
|
||||
await InvoiceAsync(await http.PostAsync($"/api/v1/invoices/from-estimate/{estimateId}", null, Ct), HttpStatusCode.Created);
|
||||
using var scope = fixture.Services.CreateScope();
|
||||
var pause = new SavePause();
|
||||
var options = new DbContextOptionsBuilder<ApplicationDbContext>(
|
||||
scope.ServiceProvider.GetRequiredService<DbContextOptions<ApplicationDbContext>>())
|
||||
.AddInterceptors(pause).Options;
|
||||
await using var stale = new ApplicationDbContext(options);
|
||||
var staleService = new InvoicingService(stale, new VerifiedPayPalStub());
|
||||
var first = staleService.RecordOfflineAsync(commandId, Receipt("bank-1"), "alice", false, Ct);
|
||||
try
|
||||
{
|
||||
await pause.Started.Task.WaitAsync(TimeSpan.FromSeconds(10), Ct);
|
||||
using var otherScope = fixture.Services.CreateScope();
|
||||
var otherService = new InvoicingService(otherScope.ServiceProvider.GetRequiredService<ApplicationDbContext>(), new VerifiedPayPalStub());
|
||||
var other = await otherService.RecordOfflineAsync(commandId, Receipt("bank-2", 40m), "alice", false, Ct);
|
||||
Assert.Equal(40m, other.AmountPaid);
|
||||
}
|
||||
finally
|
||||
{
|
||||
pause.Resume.TrySetResult();
|
||||
}
|
||||
var conflict = await Assert.ThrowsAsync<InvoiceOperationException>(() => first);
|
||||
Assert.Equal(409, conflict.StatusCode);
|
||||
using (var checkScope = fixture.Services.CreateScope())
|
||||
{
|
||||
var db = checkScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
Assert.Single(db.InvoicePayments);
|
||||
Assert.Equal(40m, db.RdvQueries.Single(q => q.Id == commandId).AmountPaid);
|
||||
}
|
||||
var retry = await InvoiceAsync(await http.PostAsJsonAsync(
|
||||
$"/api/v1/invoices/{commandId}/payments/offline", Receipt("bank-1"), Ct), HttpStatusCode.OK);
|
||||
Assert.Equal(70m, retry.AmountPaid);
|
||||
Assert.Equal(2, retry.Payments.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Invoiced_commands_and_estimates_cannot_be_deleted()
|
||||
{
|
||||
var (estimateId, commandId) = Seed();
|
||||
using var provider = Client();
|
||||
using var client = Client("bob");
|
||||
await InvoiceAsync(await provider.PostAsync($"/api/v1/invoices/from-estimate/{estimateId}", null, Ct), HttpStatusCode.Created);
|
||||
Assert.Equal(HttpStatusCode.Conflict, (await client.DeleteAsync($"/api/v1/billing/Rdv/{commandId}", Ct)).StatusCode);
|
||||
Assert.Equal(HttpStatusCode.Conflict, (await provider.DeleteAsync($"/api/v1/estimate/{estimateId}", Ct)).StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Legacy_document_generation_cannot_bypass_invoice_establishment()
|
||||
{
|
||||
var (_, commandId) = Seed();
|
||||
using var provider = Client();
|
||||
Assert.Equal(HttpStatusCode.Conflict,
|
||||
(await provider.PostAsync($"/api/v1/bill/genpdf/Rdv/{commandId}", null, Ct)).StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Invoice_total_cannot_be_overwritten_and_overpayments_keep_the_actual_amount()
|
||||
{
|
||||
var (estimateId, commandId) = Seed();
|
||||
using var http = Client();
|
||||
await InvoiceAsync(await http.PostAsync($"/api/v1/invoices/from-estimate/{estimateId}", null, Ct), HttpStatusCode.Created);
|
||||
using (var scope = fixture.Services.CreateScope())
|
||||
{
|
||||
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
var command = db.RdvQueries.Single(q => q.Id == commandId);
|
||||
Assert.Throws<InvalidOperationException>(() => command.SetPaymentAmounts(10m, 0m));
|
||||
Assert.Equal(100m, command.AmountDue);
|
||||
}
|
||||
var request = Receipt("bank-overpaid", 120m) with { ReceivedAtUtc = Received.AddTicks(1234567) };
|
||||
var invoice = await InvoiceAsync(await http.PostAsJsonAsync(
|
||||
$"/api/v1/invoices/{commandId}/payments/offline", request, Ct), HttpStatusCode.OK);
|
||||
Assert.Equal(120m, invoice.AmountPaid);
|
||||
Assert.Equal(0m, invoice.AmountRemaining);
|
||||
Assert.True(invoice.IsAcquitted);
|
||||
var replay = await InvoiceAsync(await http.PostAsJsonAsync(
|
||||
$"/api/v1/invoices/{commandId}/payments/offline", request, Ct), HttpStatusCode.OK);
|
||||
Assert.Equal(120m, replay.AmountPaid);
|
||||
Assert.Single(replay.Payments);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Openapi_documents_the_invoice_routes()
|
||||
{
|
||||
using var admin = Client();
|
||||
admin.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",
|
||||
TestTokenIssuer.Issue("alice", "api", extraClaims:
|
||||
[new System.Security.Claims.Claim(Constants.RoleClaimType, Constants.AdminGroupName)]));
|
||||
var response = await admin.GetAsync("/openapi/invoicing.json", Ct);
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
var json = await response.Content.ReadAsStringAsync(Ct);
|
||||
Assert.Contains("/api/v1/invoices/from-estimate/{estimateId}", json);
|
||||
Assert.Contains("/api/v1/invoices/{commandId}/payments/paypal", json);
|
||||
Assert.Contains("/api/v1/invoices/{commandId}/payments/offline", json);
|
||||
}
|
||||
|
||||
private sealed class SavePause : SaveChangesInterceptor
|
||||
{
|
||||
public TaskCompletionSource Started { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
public TaskCompletionSource Resume { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
public override async ValueTask<InterceptionResult<int>> SavingChangesAsync(
|
||||
DbContextEventData eventData, InterceptionResult<int> result, CancellationToken cancellationToken = default)
|
||||
{
|
||||
Started.TrySetResult();
|
||||
await Resume.Task.WaitAsync(cancellationToken);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class VerifiedPayPalStub : IPayPalTransactionVerifier
|
||||
{
|
||||
public Task<VerifiedPayPalReceipt> VerifyAsync(string transactionId, string invoiceReference, string currency, CancellationToken ct)
|
||||
{
|
||||
Assert.StartsWith("RdvQuery/", invoiceReference);
|
||||
Assert.Equal("EUR", currency);
|
||||
return Task.FromResult(new VerifiedPayPalReceipt(transactionId, 70m, currency, Received));
|
||||
}
|
||||
}
|
||||
}
|
||||
42
src/test/Yavsc.Server.Tests/FrontmatterParserTests.cs
Normal file
42
src/test/Yavsc.Server.Tests/FrontmatterParserTests.cs
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
using Yavsc.Server.Services;
|
||||
|
||||
namespace Yavsc.Server.Tests;
|
||||
|
||||
public class FrontmatterParserTests
|
||||
{
|
||||
[Fact]
|
||||
public void Parse_extracts_formulaire_devis_and_body_for_unix_line_endings()
|
||||
{
|
||||
const string markdown = "---\nformulaire: Prestation Musicale\ndevis: Arrangement Orchestral\n---\n\nContenu du devis\n";
|
||||
|
||||
var result = FrontmatterParser.Parse(markdown);
|
||||
|
||||
Assert.Equal("Prestation Musicale", result.Formulaire);
|
||||
Assert.Equal("Arrangement Orchestral", result.Devis);
|
||||
Assert.Equal("Contenu du devis", result.Corps.Trim());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_accepts_windows_line_endings()
|
||||
{
|
||||
const string markdown = "---\r\nformulaire: Prestation Musicale\r\ndevis: Arrangement Orchestral\r\n---\r\n\r\nContenu du devis\r\n";
|
||||
|
||||
var result = FrontmatterParser.Parse(markdown);
|
||||
|
||||
Assert.Equal("Prestation Musicale", result.Formulaire);
|
||||
Assert.Equal("Arrangement Orchestral", result.Devis);
|
||||
Assert.Equal("Contenu du devis", result.Corps.Trim());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_returns_original_markdown_when_no_frontmatter_is_present()
|
||||
{
|
||||
const string markdown = "# Hello\n\nThis is plain markdown.";
|
||||
|
||||
var result = FrontmatterParser.Parse(markdown);
|
||||
|
||||
Assert.Equal(string.Empty, result.Formulaire);
|
||||
Assert.Equal(string.Empty, result.Devis);
|
||||
Assert.Equal(markdown, result.Corps);
|
||||
}
|
||||
}
|
||||
153
src/test/Yavsc.Server.Tests/PayPalTransactionVerifierTests.cs
Normal file
153
src/test/Yavsc.Server.Tests/PayPalTransactionVerifierTests.cs
Normal file
|
|
@ -0,0 +1,153 @@
|
|||
using System.Globalization;
|
||||
using System.Net;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Yavsc.Services;
|
||||
|
||||
namespace Yavsc.Server.Tests;
|
||||
|
||||
public sealed class PayPalTransactionVerifierTests
|
||||
{
|
||||
private static CancellationToken Ct => TestContext.Current.CancellationToken;
|
||||
private static Dictionary<string, string> Completed() => new()
|
||||
{
|
||||
["ACK"] = "Success", ["TRANSACTIONID"] = "TX-1", ["INVNUM"] = "RdvQuery/42",
|
||||
["RECEIVERID"] = "merchant-id", ["CURRENCYCODE"] = "EUR", ["PAYMENTSTATUS"] = "Completed",
|
||||
["AMT"] = "30.25", ["ORDERTIME"] = "2026-01-02T12:00:00Z"
|
||||
};
|
||||
|
||||
private static PayPalSettings Settings(string mode = "sandbox") => new()
|
||||
{
|
||||
Mode = mode, MerchantAccountUserName = "test-api-user", MerchantAccountId = "merchant-id",
|
||||
Accounts =
|
||||
[
|
||||
new PayPalSettings.ClassicPayPalAccountApiCredential
|
||||
{
|
||||
ApiUsername = "test-api-user", ApiPassword = "test-password", Signature = "test-signature"
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
private static string Encode(Dictionary<string, string> fields)
|
||||
=> string.Join("&", fields.Select(field => $"{Uri.EscapeDataString(field.Key)}={Uri.EscapeDataString(field.Value)}"));
|
||||
|
||||
[Theory]
|
||||
[InlineData("sandbox", "api-3t.sandbox.paypal.com")]
|
||||
[InlineData("production", "api-3t.paypal.com")]
|
||||
public async Task Completed_receipt_is_verified_with_server_credentials_and_invariant_amount(string mode, string host)
|
||||
{
|
||||
using var handler = new Handler(Encode(Completed()));
|
||||
using var http = new HttpClient(handler);
|
||||
var verifier = new PayPalTransactionVerifier(http, Options.Create(Settings(mode)));
|
||||
var previousCulture = CultureInfo.CurrentCulture;
|
||||
try
|
||||
{
|
||||
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("fr-FR");
|
||||
var receipt = await verifier.VerifyAsync("TX-1", "RdvQuery/42", "EUR", Ct);
|
||||
Assert.Equal(30.25m, receipt.Amount);
|
||||
Assert.Equal("EUR", receipt.Currency);
|
||||
Assert.Equal("TX-1", receipt.TransactionId);
|
||||
Assert.Equal(TimeSpan.Zero, receipt.ReceivedAtUtc.Offset);
|
||||
Assert.Equal(host, handler.Uri!.Host);
|
||||
Assert.Equal("https", handler.Uri.Scheme);
|
||||
Assert.Contains("METHOD=GetTransactionDetails", handler.Body);
|
||||
Assert.Contains("TRANSACTIONID=TX-1", handler.Body);
|
||||
Assert.Contains("USER=test-api-user", handler.Body);
|
||||
Assert.Contains("PWD=test-password", handler.Body);
|
||||
}
|
||||
finally
|
||||
{
|
||||
CultureInfo.CurrentCulture = previousCulture;
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("PAYMENTSTATUS", "Pending", 409)]
|
||||
[InlineData("PAYMENTSTATUS", "Refunded", 409)]
|
||||
[InlineData("PAYMENTSTATUS", "Reversed", 409)]
|
||||
[InlineData("TRANSACTIONID", "TX-2", 409)]
|
||||
[InlineData("INVNUM", "RdvQuery/43", 409)]
|
||||
[InlineData("RECEIVERID", "another-merchant", 409)]
|
||||
[InlineData("CURRENCYCODE", "USD", 409)]
|
||||
[InlineData("ACK", "Failure", 502)]
|
||||
[InlineData("AMT", "-1", 502)]
|
||||
[InlineData("AMT", "0", 502)]
|
||||
[InlineData("AMT", "30,25", 502)]
|
||||
[InlineData("AMT", "0.001", 502)]
|
||||
[InlineData("ORDERTIME", "not-a-date", 502)]
|
||||
[InlineData("ORDERTIME", "2999-01-01T12:00:00Z", 502)]
|
||||
public async Task Unverified_or_mismatched_transactions_are_rejected(string field, string value, int status)
|
||||
{
|
||||
var fields = Completed();
|
||||
fields[field] = value;
|
||||
using var handler = new Handler(Encode(fields));
|
||||
using var http = new HttpClient(handler);
|
||||
var verifier = new PayPalTransactionVerifier(http, Options.Create(Settings()));
|
||||
|
||||
var exception = await Assert.ThrowsAsync<InvoiceOperationException>(
|
||||
() => verifier.VerifyAsync("TX-1", "RdvQuery/42", "EUR", Ct));
|
||||
Assert.Equal(status, exception.StatusCode);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")]
|
||||
[InlineData("ACK=Success&ACK=Success")]
|
||||
[InlineData("ACK=Success&malformed")]
|
||||
public async Task Malformed_responses_do_not_confirm_receipts(string body)
|
||||
{
|
||||
using var handler = new Handler(body);
|
||||
using var http = new HttpClient(handler);
|
||||
var verifier = new PayPalTransactionVerifier(http, Options.Create(Settings()));
|
||||
var exception = await Assert.ThrowsAsync<InvoiceOperationException>(
|
||||
() => verifier.VerifyAsync("TX-1", "RdvQuery/42", "EUR", Ct));
|
||||
Assert.Equal(502, exception.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Missing_configuration_fails_before_any_network_call()
|
||||
{
|
||||
using var handler = new Handler(Encode(Completed()));
|
||||
using var http = new HttpClient(handler);
|
||||
var verifier = new PayPalTransactionVerifier(http, Options.Create(new PayPalSettings()));
|
||||
var exception = await Assert.ThrowsAsync<InvoiceOperationException>(
|
||||
() => verifier.VerifyAsync("TX-1", "RdvQuery/42", "EUR", Ct));
|
||||
Assert.Equal(503, exception.StatusCode);
|
||||
Assert.Null(handler.Uri);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Http_failure_does_not_confirm_a_receipt()
|
||||
{
|
||||
using var handler = new Handler("unavailable", HttpStatusCode.ServiceUnavailable);
|
||||
using var http = new HttpClient(handler);
|
||||
var verifier = new PayPalTransactionVerifier(http, Options.Create(Settings()));
|
||||
var exception = await Assert.ThrowsAsync<InvoiceOperationException>(
|
||||
() => verifier.VerifyAsync("TX-1", "RdvQuery/42", "EUR", Ct));
|
||||
Assert.Equal(502, exception.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Caller_cancellation_is_not_converted_into_a_payment_failure()
|
||||
{
|
||||
using var handler = new Handler(Encode(Completed()));
|
||||
using var http = new HttpClient(handler);
|
||||
var verifier = new PayPalTransactionVerifier(http, Options.Create(Settings()));
|
||||
using var cancellation = CancellationTokenSource.CreateLinkedTokenSource(Ct);
|
||||
cancellation.Cancel();
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(
|
||||
() => verifier.VerifyAsync("TX-1", "RdvQuery/42", "EUR", cancellation.Token));
|
||||
}
|
||||
|
||||
private sealed class Handler(string body, HttpStatusCode status = HttpStatusCode.OK) : HttpMessageHandler
|
||||
{
|
||||
public Uri? Uri { get; private set; }
|
||||
public string? Body { get; private set; }
|
||||
|
||||
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
Uri = request.RequestUri;
|
||||
Body = await request.Content!.ReadAsStringAsync(ct);
|
||||
return new HttpResponseMessage(status) { Content = new StringContent(body) };
|
||||
}
|
||||
}
|
||||
}
|
||||
209
src/test/Yavsc.Server.Tests/PaymentSummaryTests.cs
Normal file
209
src/test/Yavsc.Server.Tests/PaymentSummaryTests.cs
Normal file
|
|
@ -0,0 +1,209 @@
|
|||
using Microsoft.EntityFrameworkCore;
|
||||
using Yavsc.Abstract.Workflow;
|
||||
using Yavsc.Billing;
|
||||
using Yavsc.Models;
|
||||
using Yavsc.Models.Billing;
|
||||
using Yavsc.Models.Payment;
|
||||
using Yavsc.Models.Workflow;
|
||||
using Yavsc.Services;
|
||||
|
||||
namespace Yavsc.Server.Tests;
|
||||
|
||||
public class PaymentSummaryTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData(100, 0, 100, PaymentStatus.Unpaid, false)]
|
||||
[InlineData(100, 30, 70, PaymentStatus.PartiallyPaid, false)]
|
||||
[InlineData(100, 100, 0, PaymentStatus.Paid, true)]
|
||||
[InlineData(100, 120, 0, PaymentStatus.Paid, true)]
|
||||
[InlineData(0, 0, 0, PaymentStatus.Paid, true)]
|
||||
public void Summary_distinguishes_partial_and_total_payment(
|
||||
decimal due, decimal paid, decimal remaining, PaymentStatus status, bool acquitted)
|
||||
{
|
||||
var summary = new PaymentSummary(due, paid);
|
||||
|
||||
Assert.Equal(due, summary.AmountDue);
|
||||
Assert.Equal(paid, summary.AmountPaid);
|
||||
Assert.Equal(remaining, summary.AmountRemaining);
|
||||
Assert.Equal(status, summary.Status);
|
||||
Assert.Equal(acquitted, summary.IsAcquitted);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Summary_uses_exact_decimal_amounts()
|
||||
{
|
||||
var summary = new PaymentSummary(0.3m, 0.1m + 0.2m);
|
||||
|
||||
Assert.Equal(0m, summary.AmountRemaining);
|
||||
Assert.True(summary.IsAcquitted);
|
||||
Assert.False(new PaymentSummary(100m, 99.99m).IsAcquitted);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(-1, 0, "amountDue")]
|
||||
[InlineData(100, -1, "amountPaid")]
|
||||
public void Negative_amounts_are_rejected(decimal due, decimal paid, string parameter)
|
||||
{
|
||||
var exception = Assert.Throws<ArgumentOutOfRangeException>(() => new PaymentSummary(due, paid));
|
||||
|
||||
Assert.Equal(parameter, exception.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Gateway_success_without_known_amounts_does_not_acquit_the_bill()
|
||||
{
|
||||
IBillable command = new TestCommand
|
||||
{
|
||||
Regularization = new PayPalPayment { State = "SUCCESS" }
|
||||
};
|
||||
|
||||
Assert.Null(command.PaymentSummary);
|
||||
Assert.False(command.GetIsAcquitted());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Acquittal_and_document_name_follow_the_balance_not_gateway_success()
|
||||
{
|
||||
var command = new TestCommand
|
||||
{
|
||||
Id = 42,
|
||||
Regularization = new PayPalPayment { State = "SUCCESS" }
|
||||
};
|
||||
var service = new TestBillingService();
|
||||
command.SetPaymentAmounts(100m, 30m);
|
||||
Assert.False(command.GetIsAcquitted());
|
||||
Assert.Equal(PaymentStatus.PartiallyPaid, command.PaymentSummary!.Status);
|
||||
Assert.Equal("facture-payment-summary-test-42", command.GetFileBaseName(service));
|
||||
|
||||
command.Regularization = null!;
|
||||
command.SetPaymentAmounts(100m, 100m);
|
||||
Assert.True(command.GetIsAcquitted());
|
||||
Assert.Equal("facture-payment-summary-test-42-ack", command.GetFileBaseName(service));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Invalid_amount_update_leaves_previous_balance_unchanged()
|
||||
{
|
||||
var command = new TestCommand();
|
||||
command.SetPaymentAmounts(100m, 30m);
|
||||
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => command.SetPaymentAmounts(50m, -1m));
|
||||
|
||||
Assert.Equal(100m, command.AmountDue);
|
||||
Assert.Equal(30m, command.AmountPaid);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Amounts_and_derived_status_survive_reloading_the_command()
|
||||
{
|
||||
var options = new DbContextOptionsBuilder<ApplicationDbContext>()
|
||||
.UseInMemoryDatabase(Guid.NewGuid().ToString())
|
||||
.Options;
|
||||
long id;
|
||||
using (var context = new ApplicationDbContext(options))
|
||||
{
|
||||
var command = new RdvQuery
|
||||
{
|
||||
ClientId = "client",
|
||||
PerformerId = "provider",
|
||||
ActivityCode = "test",
|
||||
Reason = "Payment test",
|
||||
UserCreated = "client",
|
||||
UserModified = "client"
|
||||
};
|
||||
context.Add(command);
|
||||
await context.SaveChangesAsync();
|
||||
id = command.Id;
|
||||
}
|
||||
|
||||
using (var context = new ApplicationDbContext(options))
|
||||
{
|
||||
var command = await context.RdvQueries.SingleAsync(q => q.Id == id, TestContext.Current.CancellationToken);
|
||||
Assert.Null(command.AmountDue);
|
||||
Assert.Equal(0m, command.AmountPaid);
|
||||
Assert.False(command.GetIsAcquitted());
|
||||
command.SetPaymentAmounts(100.50m, 30.25m);
|
||||
await context.SaveChangesAsync();
|
||||
}
|
||||
|
||||
using (var context = new ApplicationDbContext(options))
|
||||
{
|
||||
var command = await context.RdvQueries.SingleAsync(q => q.Id == id, TestContext.Current.CancellationToken);
|
||||
Assert.Equal(100.50m, command.AmountDue);
|
||||
Assert.Equal(30.25m, command.AmountPaid);
|
||||
Assert.Equal(70.25m, command.PaymentSummary!.AmountRemaining);
|
||||
Assert.Equal(PaymentStatus.PartiallyPaid, command.PaymentSummary.Status);
|
||||
Assert.False(command.GetIsAcquitted());
|
||||
command.SetPaymentAmounts(100.50m, 100.50m);
|
||||
await context.SaveChangesAsync();
|
||||
}
|
||||
|
||||
using (var context = new ApplicationDbContext(options))
|
||||
{
|
||||
var command = await context.RdvQueries.SingleAsync(q => q.Id == id, TestContext.Current.CancellationToken);
|
||||
Assert.True(command.GetIsAcquitted());
|
||||
Assert.Equal(0m, command.PaymentSummary!.AmountRemaining);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Command_amounts_cannot_be_set_by_request_json()
|
||||
{
|
||||
const string json = """{"AmountDue":100,"AmountPaid":100}""";
|
||||
var newtonsoftCommand = Newtonsoft.Json.JsonConvert.DeserializeObject<RdvQuery>(json)!;
|
||||
var systemTextCommand = System.Text.Json.JsonSerializer.Deserialize<RdvQuery>(json)!;
|
||||
|
||||
Assert.Null(newtonsoftCommand.AmountDue);
|
||||
Assert.Equal(0m, newtonsoftCommand.AmountPaid);
|
||||
Assert.Null(systemTextCommand.AmountDue);
|
||||
Assert.Equal(0m, systemTextCommand.AmountPaid);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Payment_migration_adds_only_amounts_without_inventing_historical_payments()
|
||||
{
|
||||
var migration = new Yavsc.Migrations.InvoicePaymentAmounts();
|
||||
Assert.Equal(2, migration.UpOperations.Count);
|
||||
var columns = migration.UpOperations
|
||||
.Cast<Microsoft.EntityFrameworkCore.Migrations.Operations.AddColumnOperation>()
|
||||
.ToList();
|
||||
Assert.All(columns, column => Assert.Equal("NominativeServiceCommands", column.Table));
|
||||
var due = Assert.Single(columns, column => column.Name == "AmountDue");
|
||||
Assert.True(due.IsNullable);
|
||||
Assert.Null(due.DefaultValue);
|
||||
var paid = Assert.Single(columns, column => column.Name == "AmountPaid");
|
||||
Assert.False(paid.IsNullable);
|
||||
Assert.Equal(0m, paid.DefaultValue);
|
||||
Assert.Equal(2, migration.DownOperations.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Payment_model_matches_the_postgresql_migration_snapshot()
|
||||
{
|
||||
var options = new DbContextOptionsBuilder<ApplicationDbContext>()
|
||||
.UseNpgsql("Host=localhost;Database=model_comparison_only",
|
||||
provider => provider.MigrationsAssembly("Yavsc.Org"))
|
||||
.Options;
|
||||
using var context = new ApplicationDbContext(options);
|
||||
|
||||
Assert.False(context.Database.HasPendingModelChanges());
|
||||
}
|
||||
|
||||
private sealed class TestCommand : NominativeServiceCommand
|
||||
{
|
||||
public override long Id { get; set; }
|
||||
public override string Description { get; set; } = "Test";
|
||||
public override List<IBillItem> GetBillItems() => throw new NotSupportedException();
|
||||
}
|
||||
|
||||
private sealed class TestBillingService : IBillingService
|
||||
{
|
||||
public Dictionary<string, string> BillingMap { get; } = new()
|
||||
{
|
||||
[nameof(TestCommand)] = "payment-summary-test"
|
||||
};
|
||||
|
||||
public Task<IQuery> GetBillAsync(string billingCode, long queryId) => throw new NotSupportedException();
|
||||
public Task<IUserSettings> GetPerformersSettingsAsync(string activityCode, string userId) => throw new NotSupportedException();
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue