7. Agreements, E-Signing, Resolutions & Offers
Repository:
Backend (planovi-backend)• Rule Prefix:BR-SIGN• Documented Rules: 7 • Open[TEAM_WHY_NEEDED]Questions: 3
1. Business Purpose & Actors
Covers three document & signature subdomains: (1) CRM commercial offers (generate-offer) and multi-signatory eIDAS Simple Electronic Signature (SES) agreements (generate-agreement, send-signature-request, signing-api, finalize-agreement), (2) Energy cooperative Tauron building agreements (Załącznik 1 / 1a, send-agreement-email), and (3) Cooperative governance voting protocols (Protokół Głosowania, generate-resolution-document).
- Actors: Active company members (CRM offers/agreements), unauthenticated external signatories (via HMAC link on
agreements/sign.php), cooperativeadmin/owner(Tauron building agreement emails), internalsigning-apiservice-role finalizer, and CRM webhook consumers (webhook_deliveries).
2. All Features & End-to-End Flows
- CRM Offer PDF (
generate-offer/index.ts):requireUser+ activecompany_members-> loadsoffers+offer_items-> renders A4 PDF (pdf-lib@1.17.1+@pdf-lib/fontkit@1.1.1,documents/fonts/Roboto-{Regular,Bold}.ttffallback Helvetica, Planovi#09090B/#32CA42, hardcoded"Planovi sp. z o.o.", VAT default23%preserving0%, validity+14d) -> merges plain-pathattached_pdfsfromdocumentsbucket (SSRF-guarded: rejects://and leading/) -> uploadsdocuments/offers/{offerId}.pdf-> 7-day (604800s) public signed URL -> updatesoffers.pdf_url(anddraft -> pending+sent_at) -> if owneddealIdindealflow_entries, links/createsdraftagreementsrow & setscurrent_stage = "bid_sent"-> logsactivity_log+ optionalwebhook_deliveries(offer.generated) -> emails client via Resend (non-fatal). - CRM Agreement PDF (
generate-agreement/index.ts):requireUser+ active member -> renders single-page A4 PDF (legacy#0F172A/#2DD4BF, hardcoded"Planowi sp. z o.o.", 5 static clauses truncated at 100 chars, deliberately omits any personal signing link) -> uploadsdocuments/agreements/{id}.pdf(7-day signed URL) -> updatesagreements-> emailsclient_email-> logsactivity_log+webhook_deliveries(agreement.generated). - Signature Request Dispatch (
send-signature-request/index.ts):requireUser+ active member -> persistsagreements.signing_mode("parallel"or default"serial") -> selects pendingagreement_signatories(lowestsigning_ordertier forserial, all pending forparallel) -> computesHMAC-SHA256(SIGNING_SECRET, "${agreementId}:${sigId}")-> emails{SIGNING_PAGE_URL}?signatoryId=...&token=...via Resend -> logsactivity_log(no token) +webhook_deliveries(agreement.signature_requested). - Public E-Signing API (
signing-api/index.ts):POSTonly (405) -> validatessafeEqual(token, HMAC(agreementId:signatoryId))(403,404if signatory missing):action: "load": returnslocked_layout.html_code, fresh 24h (86400s) public signed URL for base PDF,company_settingsbranding, andalreadySigned.action: "sign": rejects already-signed (409 "already_signed") -> captures client IP + ISO timestamp +nameUsed(<= 200chars) -> computes audit hashHMAC-SHA256(SIGNING_SECRET, "${sigId}:${agreementId}:${nameUsed}:${ip}:${signedAt}")-> atomic conditional updateWHERE id = ? AND status != 'signed'-> logsactivity_log(hash_prefix12 chars) +webhook_deliveries(agreement.signature_received) -> inserialmode notifies nextsigning_ordertier whennextOrder > signedOrder-> ifnobodyPending, invokesfinalize-agreementinternally viaSUPABASE_SERVICE_ROLE_KEY(non-fatal).
- Agreement Finalization (
finalize-agreement/index.ts):service_rolekey OR user JWT + active member -> requires >= 1 signatory and ALLstatus === "signed"(400) -> fast-path returns stored URL ifstatus === "accepted" && signed_pdf_url-> merges base agreement PDF + generated eIDAS(UE) 910/2014Audit Trail page (legacy#0F172A/#2DD4BF, 16-char hash prefix) + optionaldocuments/offers/{offer_id}.pdf-> uploadsdocuments/agreements/{id}_final.pdf(72h259200ssigned URL) -> conditional update (.neq("status","accepted")or.is("signed_pdf_url", null)) so only winning writer triggers fulfillment-order DB trigger, emails deduplicated signatories +sender_email+client_email(using tenantemail_templatestrigger="agreement_signed"or built-in fallback), and logsactivity_log+webhook_deliveries(agreement.finalized). - Tauron Building Agreement Email (
send-agreement-email/index.ts):requireUser+activeRole ∈ {'admin','owner'}-> loadsbuilding_agreementsscoped to(id, company_id)-> resolves member email fromuser_profiles(rejects invalid or@deleted.local):mode: "sign_request": requiresstatus ∈ {'draft','sent'}(409) -> emails panel link (Origin allowlisted*.planovi.app/localhost) -> transitions to'sent'.mode: "signed_copy": requiresstatus === 'completed'(409), validatespdf_base64(<= 5 MB413,%PDF400) -> emailsZalacznik_1[a]_Wniosek_*.pdf.
- Governance Resolution Protocol (
generate-resolution-document/index.ts):validateAuth(req)(any user JWT, NO tenant check!) -> computespassed = quorumReached && approvalPercentage >= passingThreshold-> renders standalone HTML -> uploadsgovernance_documents/{coopId}/resolutions/{resolutionId}/protokol_glosowania.html-> insertscoop_documents(category: 'resolution',status: 'approved',visibility_level: 'all') -> returns 1h (3600s) signed URL.
3. Hard Business Rules, Validations, Calculations & Edge Cases (BR-SIGN)
BR-SIGN-01(Stateless HMAC Signing Token & Audit Hash): Signing token =HMAC-SHA256(SIGNING_SECRET, "${agreementId}:${signatoryId}")(never persisted or logged). Audit hash =HMAC-SHA256(SIGNING_SECRET, "${signatoryId}:${agreementId}:${nameUsed}:${ip}:${signedAt}")(12-char prefix in logs, 16-char prefix on Audit Trail PDF).BR-SIGN-02(No Personal Link in Shared Agreement PDF):generate-agreementstrictly excludes signing URLs/tokens fromdocuments/agreements/{id}.pdf.BR-SIGN-03(Atomic Single-Sign & Exactly-Once Finalization):signing-apienforces.neq("status", "signed")(409 "already_signed");finalize-agreementenforces all signatories'signed'(400) and conditional.neq("status", "accepted")so emails, webhooks, and the downstream fulfillment-order DB trigger fire at most once.BR-SIGN-04(Signed URL TTLs): Offers & base agreements:7d(604800s); signing load view:24h(86400s); finalized PDF:72h(259200s); resolution HTML:1h(3600s).BR-SIGN-05(Offer Immutability, VAT & SSRF Guard):generate-offerpreservesvat_rate = 0(default23%only when null/non-finite), rejects://or leading/inattached_pdfs, verifiesdealflow_entries.company_id, never overwritestracking_token/locked_data/locked_layout, and only advancesoffers.statusfrom null/draft->pending.BR-SIGN-06(Building Agreement State & Email Guards):send-agreement-emailrequiresadmin/owner, DB-only non-@deleted.localemail,draft|sentforsign_request,completed+<= 5 MB%PDFforsigned_copy.BR-SIGN-07(Resolution Pass Formula):passed = quorumReached && approvalPercentage >= passingThreshold.
4. State Machines & Data Lifecycle
agreements.status:'draft'->'accepted'(finalize-agreement, setsaccepted_at; downstream DB trigger creates fulfillment order).signing_mode:'serial'|'parallel'.signature_level:'SES'.agreement_signatories.status:'pending'->'signed'(atomic viasigning-api).building_agreements.status:'draft'->'sent'(send-agreement-emailsign_request) ->'completed'(external signing -> enablessigned_copy).doc_type:'odbiorca'(Załącznik 1) |'wytworca'(Załącznik 1a).offers.status:null/'draft'->'pending'(generate-offer).
5. Technical Contract
- Endpoints:
generate-offer,generate-agreement,send-signature-request,signing-api,finalize-agreement,send-agreement-email,generate-resolution-document. - Tables:
agreements,agreement_signatories,building_agreements,offers,offer_items,dealflow_entries,company_members,company_settings,companies,buildings,user_profiles,email_templates,coop_documents,activity_log,webhook_deliveries. - Storage Buckets:
documents(fonts/Roboto-*.ttf,offers/{id}.pdf,agreements/{id}.pdf,agreements/{id}_final.pdf),governance_documents({coopId}/resolutions/{id}/protokol_glosowania.html). - Outbound Webhooks (
webhook_deliveries,consumer_type: "crm"):offer.generated,agreement.generated,agreement.signature_requested,agreement.signature_received,agreement.finalized.
6. Cross-Repository Dependencies
| Caller -> Callee | Protocol & Auth | Exact Endpoint / Contract |
|---|---|---|
planovi-microservices (agreements/sign.php) -> signing-api | HTTPS POST / HMAC token | `{ signatoryId, token, action: “load” |
planovi-flutter-app -> Module 7 Functions | HTTPS POST / User JWT | generate-offer, generate-agreement, send-signature-request, finalize-agreement, send-agreement-email (client PDF), generate-resolution-document |
External Webhook Worker -> webhook_deliveries | Out-of-repo consumer | Polls status = 'pending', consumer_type = 'crm' |
7. Why It Works This Way
toPublicUrlorigin rewrite: Self-hosted Edge Runtime uses internal DockerSUPABASE_URL; rewriting toPUBLIC_SUPABASE_URLmakes signed Storage links reachable by external browsers and email clients.- Hidden DB triggers relied on by code: Comments document that
agreements.status = 'accepted'fires an external DB trigger to create a fulfillment order (finalize-agreement:8), and DB triggers ownoffers.tracking_token/locked_data/locked_layout(generate-offer:11-12). [TEAM_WHY_NEEDED: What worker consumes pending rows from webhook_deliveries (consumer_type = "crm")? None exists in planovi-backend.][TEAM_WHY_NEEDED: Why do generate-agreement, generate-offer, and finalize-agreement hardcode "Planowi sp. z o.o. / ul. Przykladowa 1 / NIP: 000-000-00-00" instead of tenant company data?][TEAM_WHY_NEEDED: Should signing tokens include a cryptographic TTL or enforce agreements.locked_layout.signing_deadline in signing-api? Currently tokens never expire.]
8. Debugging, Logs & Common Failure Modes
| Symptom / Error Message | Root Cause in Code | How to Verify / Exact Query or Log | Fix |
|---|---|---|---|
| Any user can overwrite another cooperative’s resolution protocol or forge vote tallies + Stored XSS | generate-resolution-document/index.ts: uses validateAuth (no coopId membership check!), trusts client vote counts verbatim, interpolates raw HTML, has mojibake (PRZYJĘTA), omits toPublicUrl, and inserts duplicate coop_documents rows | Inspect generate-resolution-document/index.ts:19-49,84,216-359 | Enforce requireStaff, load votes from DB, escape HTML, fix UTF-8, apply toPublicUrl, upsert coop_documents |
| Signatories sign out of order, past deadline, or on cancelled agreements | signing-api:308-328 ignores signing_order, signing_deadline, agreements.status, and non-signed statuses (declined) | Test action: "sign" with order-2 signatory before order-1 | Validate agreements.status, sig.status === 'pending', signing_order tier, and signing_deadline |
finalize-agreement called prematurely when a signatory declined | signing-api:387,396 triggers callFinalize on nobodyPending instead of allSigned | Inspect signing-api/index.ts:387,396-398 | Gate callFinalize on allSigned |
| Offer & agreement PDFs excluded from company storage quota | Paths offers/{id}.pdf and agreements/{id}.pdf lack leading {companyId}/ required by fn_storage_company_of (20261102120000:126-147) | Compare storage.objects.name vs company_storage_quotas | Prefix paths with ${companyId}/ or update fn_storage_company_of |
PDF table overflow or WinAnsi crash on Polish names in finalize-agreement/generate-offer | No multi-page pagination (>13 signatories or many offer items overflow page); fallback to Helvetica crashes on Polish diacritics if Roboto-*.ttf fails to load | Check Storage bucket documents/fonts/Roboto-{Regular,Bold}.ttf | Add page-break pagination and fail loudly or bundle fonts |
Legacy "Planowi" typo & #0F172A/#2DD4BF colors in PDFs | generate-agreement:82-88,140-230 and finalize-agreement:83-89 still use old brand palette & misspelling | Inspect rendered PDFs | Migrate to BRANDING_GUIDE.md §5.4 |