Skip to content

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), cooperative admin/owner (Tauron building agreement emails), internal signing-api service-role finalizer, and CRM webhook consumers (webhook_deliveries).

2. All Features & End-to-End Flows

  1. CRM Offer PDF (generate-offer/index.ts): requireUser + active company_members -> loads offers + offer_items -> renders A4 PDF (pdf-lib@1.17.1 + @pdf-lib/fontkit@1.1.1, documents/fonts/Roboto-{Regular,Bold}.ttf fallback Helvetica, Planovi #09090B/#32CA42, hardcoded "Planovi sp. z o.o.", VAT default 23% preserving 0%, validity +14d) -> merges plain-path attached_pdfs from documents bucket (SSRF-guarded: rejects :// and leading /) -> uploads documents/offers/{offerId}.pdf -> 7-day (604800s) public signed URL -> updates offers.pdf_url (and draft -> pending + sent_at) -> if owned dealId in dealflow_entries, links/creates draft agreements row & sets current_stage = "bid_sent" -> logs activity_log + optional webhook_deliveries (offer.generated) -> emails client via Resend (non-fatal).
  2. 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) -> uploads documents/agreements/{id}.pdf (7-day signed URL) -> updates agreements -> emails client_email -> logs activity_log + webhook_deliveries (agreement.generated).
  3. Signature Request Dispatch (send-signature-request/index.ts): requireUser + active member -> persists agreements.signing_mode ("parallel" or default "serial") -> selects pending agreement_signatories (lowest signing_order tier for serial, all pending for parallel) -> computes HMAC-SHA256(SIGNING_SECRET, "${agreementId}:${sigId}") -> emails {SIGNING_PAGE_URL}?signatoryId=...&token=... via Resend -> logs activity_log (no token) + webhook_deliveries (agreement.signature_requested).
  4. Public E-Signing API (signing-api/index.ts): POST only (405) -> validates safeEqual(token, HMAC(agreementId:signatoryId)) (403, 404 if signatory missing):
    • action: "load": returns locked_layout.html_code, fresh 24h (86400s) public signed URL for base PDF, company_settings branding, and alreadySigned.
    • action: "sign": rejects already-signed (409 "already_signed") -> captures client IP + ISO timestamp + nameUsed (<= 200 chars) -> computes audit hash HMAC-SHA256(SIGNING_SECRET, "${sigId}:${agreementId}:${nameUsed}:${ip}:${signedAt}") -> atomic conditional update WHERE id = ? AND status != 'signed' -> logs activity_log (hash_prefix 12 chars) + webhook_deliveries (agreement.signature_received) -> in serial mode notifies next signing_order tier when nextOrder > signedOrder -> if nobodyPending, invokes finalize-agreement internally via SUPABASE_SERVICE_ROLE_KEY (non-fatal).
  5. Agreement Finalization (finalize-agreement/index.ts): service_role key OR user JWT + active member -> requires >= 1 signatory and ALL status === "signed" (400) -> fast-path returns stored URL if status === "accepted" && signed_pdf_url -> merges base agreement PDF + generated eIDAS (UE) 910/2014 Audit Trail page (legacy #0F172A/#2DD4BF, 16-char hash prefix) + optional documents/offers/{offer_id}.pdf -> uploads documents/agreements/{id}_final.pdf (72h 259200s signed 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 tenant email_templates trigger="agreement_signed" or built-in fallback), and logs activity_log + webhook_deliveries (agreement.finalized).
  6. Tauron Building Agreement Email (send-agreement-email/index.ts): requireUser + activeRole ∈ {'admin','owner'} -> loads building_agreements scoped to (id, company_id) -> resolves member email from user_profiles (rejects invalid or @deleted.local):
    • mode: "sign_request": requires status ∈ {'draft','sent'} (409) -> emails panel link (Origin allowlisted *.planovi.app / localhost) -> transitions to 'sent'.
    • mode: "signed_copy": requires status === 'completed' (409), validates pdf_base64 (<= 5 MB 413, %PDF 400) -> emails Zalacznik_1[a]_Wniosek_*.pdf.
  7. Governance Resolution Protocol (generate-resolution-document/index.ts): validateAuth(req) (any user JWT, NO tenant check!) -> computes passed = quorumReached && approvalPercentage >= passingThreshold -> renders standalone HTML -> uploads governance_documents/{coopId}/resolutions/{resolutionId}/protokol_glosowania.html -> inserts coop_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-agreement strictly excludes signing URLs/tokens from documents/agreements/{id}.pdf.
  • BR-SIGN-03 (Atomic Single-Sign & Exactly-Once Finalization): signing-api enforces .neq("status", "signed") (409 "already_signed"); finalize-agreement enforces 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-offer preserves vat_rate = 0 (default 23% only when null/non-finite), rejects :// or leading / in attached_pdfs, verifies dealflow_entries.company_id, never overwrites tracking_token/locked_data/locked_layout, and only advances offers.status from null/draft -> pending.
  • BR-SIGN-06 (Building Agreement State & Email Guards): send-agreement-email requires admin/owner, DB-only non-@deleted.local email, draft|sent for sign_request, completed + <= 5 MB %PDF for signed_copy.
  • BR-SIGN-07 (Resolution Pass Formula): passed = quorumReached && approvalPercentage >= passingThreshold.

4. State Machines & Data Lifecycle

  • agreements.status: 'draft' -> 'accepted' (finalize-agreement, sets accepted_at; downstream DB trigger creates fulfillment order). signing_mode: 'serial' | 'parallel'. signature_level: 'SES'.
  • agreement_signatories.status: 'pending' -> 'signed' (atomic via signing-api).
  • building_agreements.status: 'draft' -> 'sent' (send-agreement-email sign_request) -> 'completed' (external signing -> enables signed_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 -> CalleeProtocol & AuthExact Endpoint / Contract
planovi-microservices (agreements/sign.php) -> signing-apiHTTPS POST / HMAC token`{ signatoryId, token, action: “load”
planovi-flutter-app -> Module 7 FunctionsHTTPS POST / User JWTgenerate-offer, generate-agreement, send-signature-request, finalize-agreement, send-agreement-email (client PDF), generate-resolution-document
External Webhook Worker -> webhook_deliveriesOut-of-repo consumerPolls status = 'pending', consumer_type = 'crm'

7. Why It Works This Way

  • toPublicUrl origin rewrite: Self-hosted Edge Runtime uses internal Docker SUPABASE_URL; rewriting to PUBLIC_SUPABASE_URL makes 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 own offers.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 MessageRoot Cause in CodeHow to Verify / Exact Query or LogFix
Any user can overwrite another cooperative’s resolution protocol or forge vote tallies + Stored XSSgenerate-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 rowsInspect generate-resolution-document/index.ts:19-49,84,216-359Enforce 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 agreementssigning-api:308-328 ignores signing_order, signing_deadline, agreements.status, and non-signed statuses (declined)Test action: "sign" with order-2 signatory before order-1Validate agreements.status, sig.status === 'pending', signing_order tier, and signing_deadline
finalize-agreement called prematurely when a signatory declinedsigning-api:387,396 triggers callFinalize on nobodyPending instead of allSignedInspect signing-api/index.ts:387,396-398Gate callFinalize on allSigned
Offer & agreement PDFs excluded from company storage quotaPaths 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_quotasPrefix paths with ${companyId}/ or update fn_storage_company_of
PDF table overflow or WinAnsi crash on Polish names in finalize-agreement/generate-offerNo multi-page pagination (>13 signatories or many offer items overflow page); fallback to Helvetica crashes on Polish diacritics if Roboto-*.ttf fails to loadCheck Storage bucket documents/fonts/Roboto-{Regular,Bold}.ttfAdd page-break pagination and fail loudly or bundle fonts
Legacy "Planowi" typo & #0F172A/#2DD4BF colors in PDFsgenerate-agreement:82-88,140-230 and finalize-agreement:83-89 still use old brand palette & misspellingInspect rendered PDFsMigrate to BRANDING_GUIDE.md §5.4