# HYP, חיוב ומסמכים

> תיעוד מקור. מקור: docs/commercial-system/hyp-payments.md · 6a466bf · 2026-11-21.

Status (2026-11-21): the approved charging commission is **0.99% before VAT for all four plans**, in catalog **1.4.0**. Provider credentials and terminal verification are still required. External payments and refunds remain disabled; a catalog or database revision does not activate HYP collection.

## Goal

LinkNodes Energy owns the commercial state. HYP is the external payment and legal-document rail. Subscription billing, charging-service fees, refunds and document references have server-side implementations. Provider activation requires a verified test terminal first. Unresolved payment outcomes are held for reconciliation; they never authorize another automatic charge.

This implementation never stores a full card number or CVV. LinkNodes stores HYP's reusable token only in the private database schema plus safe display metadata (brand, last four digits and expiry).

## Provider configuration

Server-only environment variables:

- `HYP_PAYMENTS_ENABLED` — must be explicitly `true` in addition to terminal credentials before any payment-provider operation is enabled; leave `false` until provider verification is complete.
- `HYP_REFUNDS_ENABLED` — independent refund switch; requires payment activation too. Leave `false` until refund verification is complete.
- `HYP_MASOF` — terminal number.
- `HYP_API_KEY` — API signing key.
- `HYP_PASSP` — API password.
- `HYP_PAGE_LANG` — `HEB` or `ENG`, defaults to `HEB`.
- `HYP_TEMPLATE` — optional hosted-page template number.
- `CRON_SECRET` — generated operational secret for the billing worker; LinkNodes provisions this internally in Vercel and Supabase Vault. It is not a HYP credential and does not require customer input.

HYP terminal success URL:

`https://product.linknodesenergy.com/api/billing/hyp/return`

No HYP secret is exposed through a `NEXT_PUBLIC_*` variable.

## Provider flows

### Initial paid checkout

1. Customer explicitly accepts billing terms in the LinkNodes Billing screen.
2. LinkNodes creates an immutable subscription/obligation/payment-attempt snapshot in PostgreSQL.
3. Server calls HYP `APISign / SIGN`.
4. Browser is redirected to the signed HYP hosted payment page.
5. HYP redirects to the product return route.
6. LinkNodes calls HYP `APISign / VERIFY` server-to-server. Browser redirect data alone never activates service.
7. LinkNodes verifies internal attempt ID and exact amount.
8. The verified HYP transaction is persisted before token retrieval.
9. LinkNodes calls `getToken` and stores only the token in `ev1_private.payment_tokens`.
10. Paid checkout becomes `active`; HYP's document reference is stored as the legal financial-document reference.

If verification succeeds but token retrieval temporarily fails, the attempt remains `processing`. The billing worker retries tokenization; the customer is not asked to pay again.

### Personal 14-day trial

Personal uses HYP J2 card verification for the initial mandate:

- no subscription fee is captured at trial start;
- no invoice is requested for the J2 verification;
- the token is stored after server-side verification;
- the first subscription obligation becomes due at the server-defined trial end;
- the unattended worker then performs the normal token charge.

A succeeded J2 mandate is not treated as a succeeded subscription payment and therefore does not block the day-14 charge.

### Renewals and charging-service fees

Supabase Cron calls `https://product.linknodesenergy.com/api/internal/billing/renewals` every ten minutes through `pg_net`, using a bearer secret stored in Supabase Vault and the matching `CRON_SECRET` stored only in the Vercel product environment. The server first processes durable charging completions through the service-only `lne_billing_process_charging_completions` RPC. Completion processing can record obligations or waiting/no-charge outcomes while HYP dispatch remains disabled.

When provider activation is enabled, the worker:

1. expires canceled subscriptions whose paid/trial period ended;
2. reconciles verified hosted payments that still need tokenization;
3. conservatively recovers expired charging-commission claims only when they have no payment attempt, then atomically claims due obligations with a short lease;
4. creates an idempotent payment attempt and sends only if the database returns `created=true`;
5. calls HYP `soft` with the stored token;
6. on approval, marks the obligation paid, creates the next subscription obligation and records HYP's document reference;
7. on any nonzero, missing, duplicate or malformed provider decision, retains the attempt for reconciliation;
8. on transport or local-finalization ambiguity, marks the attempt `unknown` and does **not** retry the charge.

No decline code is currently certified for automatic retry. The legacy failure RPC also holds the obligation. Recovery leaves subscription claims, missing leases and any existing attempt for review. Only an exact single `CCode=0` with a valid provider transaction reference can advance a provider result.

The service-role-only `lne_billing_reconciliation_page` RPC and `listBillingReconciliation` helper provide a complete count for the current database snapshot and keyset pagination over unresolved obligations, payment attempts and refunds. The bounded recovery batch count is separate from the inventory total. The inventory exposes identifiers and status, without tokens or customer contact details.

### LinkNodes charging commission

A charging commission is created only from an eligible completed LinkNodes charging session. The additive `20261121230000_uniform_charging_commission.sql` migration adds `ev1_private.charging_fee_queue` and the `lne_observe_charging_fee_session` trigger. Enrollment is restricted to newly inserted sessions created at or after the catalog 1.4.0 revision cutoff; any supplied start/end timestamps must also meet the cutoff. The row initially waits for completion. A completed session must have both `provider` and `provider_session_id`, start/end timestamps at or after the cutoff, and an explicit `provider_amount_finalized_at` before it becomes pending for fee processing. That marker must be at or after `ended_at`; only the trusted service writer can record it after receiving the supplier's final amount. Updating an older session never enrolls it. Importing a supplier CSV or viewing historical energy data does not create a fee.

The queue freezes the canonical `ev1_fleet_sessions.amount_minor`, final-amount marker and provider identity when a completed session has a confirmed final price. Completion with an omitted price or a default zero stays in `waiting_completion` until that explicit confirmation arrives; it is not treated as free charging. `lne_billing_process_charging_completions` and the guarded `lne_billing_create_charging_fee` RPC use the persisted amount, rather than a browser-supplied amount or a later edit. A missing chargeable subscription or payment method leaves the completion in `waiting_payment` for a later worker pass. The live supplier completion adapter and HYP credentials are still required before real provider dispatch.

The fee snapshots:

- provider charging gross amount;
- catalog/terms revision and the uniform commission rate;
- VAT rate;
- net LinkNodes fee;
- tax;
- total amount.

There can be only one charging-fee obligation per charging session. Replaying the same session returns the same obligation. A conflicting source amount fails closed instead of creating a second fee. A genuine zero charging amount or a calculated fee that rounds to zero is recorded as `no_charge`; it creates neither a payment obligation nor a minimum charge. Incomplete or invalid provider amounts remain pending/reviewable rather than being treated as zero.

Current charging rates are frozen from commercial catalog v1.4.0:

- Personal: 0.99% before VAT
- Family: 0.99% before VAT
- Business: 0.99% before VAT
- Enterprise: 0.99% before VAT; subscription pricing and enrollment remain agreement-specific

VAT is applied to the LinkNodes service fee separately. The fee is calculated from the canonical provider gross amount, rounded half-up to whole agorot; VAT is then rounded on that fee. HYP collects **only the LinkNodes fee plus its VAT**. The provider's energy charge remains a separate settlement fact, and this implementation does not collect or transfer the whole charging gross amount.

The accepted terms revision is `billing-uniform-099-1`. Existing payment attempts, historical fees and refunds retain their original amounts and references. Legacy unattempted charging obligations without the new policy are held from automatic dispatch; the migration does not reprice or automatically charge history.

### Refunds

Refunds are tied to an original succeeded payment attempt.

- A database lock on the original payment serializes refund reservations. Pending, unknown, succeeded and historical failed reservations count against the remaining refundable balance.
- A repeated request ID returns the persisted reservation and never calls HYP again; changed payment or amount fails closed. Card-verification mandates are not refundable payments.
- HYP `zikoyAPI` performs the provider refund.
- HYP credit-document reference is stored without editing the original document.
- transport ambiguity is stored as `unknown`; it is not silently retried as a second refund.
- Lost finalization responses preserve already persisted success. Unknown outcomes retain the reservation. The unsafe legacy reservation RPC is disabled.

### Cancellation

Cancel stops future renewal. It does not delete the subscription, vehicles, history, documents or completed charging obligations.

For a paid/trial period, access remains represented by `current_period_end`. The worker changes the canceled subscription to `expired` when that time passes. Before expiry, direct account-plan changes are blocked so a plan change cannot bypass billing periods, refunds or documents.

## Financial data model

Private:

- `ev1_private.billing_catalog`
- `ev1_private.payment_tokens`
- `ev1_private.charging_fee_queue`

Customer-scoped public state:

- `ev1_subscriptions`
- `ev1_billing_obligations`
- `ev1_payment_attempts`
- `ev1_financial_documents`
- `ev1_refunds`

All customer tables carry `tenant_id`, use RLS, have service-role-only writes and owner/admin/finance reads. Private token/catalog tables have no browser grants.

## Idempotency and concurrency

- Checkout has a client request UUID.
- Charging commission is unique per completed charging session.
- Refund has a request UUID.
- Subscription period obligation has a deterministic logical key.
- Due obligations are claimed with PostgreSQL `FOR UPDATE SKIP LOCKED` plus a lease.
- A provider transaction reference is unique once known.
- Unknown provider outcomes are isolated from the retry path.

## Documents and invoices

Paid checkout, token renewals and charging-fee charges request HYP document generation using HYP invoice parameters. LinkNodes stores the provider document reference and amount; HYP remains the legal-document system.

The connected Billing screen uses `ev1_financial_documents` as the source of truth. Legacy invoice fixtures remain visible only in Demo mode.

## Security

- HYP credentials are server-only.
- Hosted payment page keeps PAN/CVV outside LinkNodes.
- Browser success is not trusted; HYP verification is server-to-server.
- Exact amount and internal Order/attempt ID are checked.
- Token vault is in the private schema.
- Payment write actions require the account billing-write role.
- Demo mode never calls the payment provider.
- Enterprise cannot enter the public shelf-price checkout.

## Test environment and release sequence

The current test environment uses synthetic provider responses and an isolated local PostgreSQL 17 database. It requires no HYP credentials and sends no requests to HYP. It is not a connected HYP sandbox, and the existing provider endpoint must not be treated as a sandbox merely because a deployment is called Preview.

Run the adapter and service fixtures with:

```bash
pnpm exec vitest run lib/billing/hyp.test.ts lib/billing/service.test.ts
```

For database validation, provision the empty local `ev1_test_final_ci` database described by `scripts/run-database-regressions.mjs`, then run that runner with `EV1_TEST_DATABASE_URL`. It applies every source migration and runs the billing foundation and safety suites, including real concurrent refund reservations and lease/preparation races. Its guard rejects hosted or nonempty databases.

Release order:

1. Keep both HYP activation flags `false` in all application environments.
2. Apply `20261120160000_billing_safety.sql`, followed by `20261121230000_uniform_charging_commission.sql`, to the intended test database before deploying the updated billing service. The service requires the safety migration's `created` result and the completion-queue RPC; a missing migration fails before a charge. Repeat only the reviewed migrations on the product's configured production database after isolated verification; changing regions is outside this pricing revision.
3. Validate the deployed schema and service together, including denied browser access to service-only RPCs and a complete reconciliation inventory.
4. Obtain HYP-issued test-terminal credentials and confirm the endpoint, callback URL and supported decline semantics with HYP. Configure secrets only in the designated test environment.
5. Verify hosted checkout, J2 mandate without capture, callback signature/order/amount checks, token retrieval, one token charge, request replay, transport ambiguity and provider-side reconciliation. Verify document references against the provider's test results.
6. Enable and verify refunds separately: one refund, replay, concurrent partial refunds, excess rejection and uncertain outcomes. Compare provider-side totals to the local reservation ledger.
7. Production activation is a separate step after the test results and the production terminal are verified. Do not enable unknown-outcome retries as part of activation.

Draft PRs 53, 55 and 56 contain earlier partial versions of these fixes and must not be merged on top of the combined safety implementation without review.

## External operational caveat

HYP's Israeli invoice-allocation integration depends on authorization to the Israel Tax Authority. HYP documents that this authorization expires periodically (approximately every three months) and requires reauthorization in the provider portal. LinkNodes can automate all normal payment/invoice processing, but it cannot legitimately bypass that external government OAuth/authorization expiry.

Operational monitoring should alert before/when allocation authorization becomes invalid; it must not fabricate allocation numbers.

## Provider references

- HYP developer documentation: <https://developers.hyp.co.il/>
- HYP Pay endpoint: <https://pay.hyp.co.il/p/>
- HYP invoice API: <https://invoice.hyp.co.il/api>
- HYP invoice API reference: <https://files.ezcount.co.il/api>
