@vocdoni/skills 0.5.2 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/.claude-plugin/marketplace.json +5 -15
  2. package/CHANGELOG.md +26 -0
  3. package/README.md +32 -21
  4. package/bin/install.js +22 -5
  5. package/package.json +2 -1
  6. package/plugins/agentic-dev/.claude-plugin/plugin.json +2 -2
  7. package/plugins/agentic-dev/agents/model-router.md +105 -0
  8. package/plugins/agentic-dev/skills/subagent-driven-development/SKILL.md +22 -12
  9. package/plugins/agentic-dev/skills/subagent-driven-development/references/audits.md +20 -13
  10. package/plugins/agentic-dev/skills/subagent-driven-development/references/dispatch.md +37 -1
  11. package/plugins/agentic-dev/skills/subagent-driven-development/references/ledger.md +5 -3
  12. package/plugins/agentic-dev/skills/subagent-driven-development/references/model-catalog.md +118 -0
  13. package/plugins/agentic-dev/skills/subagent-driven-development/references/models.md +93 -70
  14. package/plugins/agentic-dev/skills/subagent-driven-development/scripts/init-workspace.sh +1 -1
  15. package/plugins/agentic-dev/skills/subagent-driven-development/scripts/model-inventory.sh +140 -0
  16. package/plugins/claude-pi-subagent/plugins/pi-subagent/package-lock.json +6 -6
  17. package/plugins/vocdoni-comments/.claude-plugin/plugin.json +2 -2
  18. package/plugins/vocdoni-comments/hooks/hooks.json +28 -0
  19. package/plugins/vocdoni-comments/hooks/session-start.sh +45 -0
  20. package/plugins/vocdoni-contributing/.claude-plugin/plugin.json +3 -2
  21. package/plugins/vocdoni-contributing/hooks/hooks.json +14 -2
  22. package/plugins/vocdoni-contributing/hooks/session-start.sh +18 -6
  23. package/plugins/vocdoni-contributing/skills/contributing/SKILL.md +26 -2
  24. package/plugins/vocdoni-stripe/.claude-plugin/plugin.json +0 -22
  25. package/plugins/vocdoni-stripe/skills/stripe-subscription/SKILL.md +0 -276
  26. package/plugins/vocdoni-stripe/skills/stripe-subscription/references/backend-contract.md +0 -142
  27. package/plugins/vocdoni-stripe/skills/stripe-subscription/references/product-templates.md +0 -132
  28. package/plugins/vocdoni-stripe/skills/stripe-subscription/references/stripe-cli.md +0 -212
  29. package/plugins/vocdoni-stripe/skills/stripe-subscription/scripts/clone-product.sh +0 -247
  30. package/plugins/vocdoni-stripe/skills/stripe-subscription/scripts/stripe-json.sh +0 -223
@@ -1,132 +0,0 @@
1
- # Per-customer plan products (Custom / Integrator Starter)
2
-
3
- ## Why a product per customization
4
-
5
- The backend reads every plan limit from the product's metadata (see
6
- `backend-contract.md`). Two customers with different limits therefore need two
7
- products. The catalog keeps one **template** per family:
8
-
9
- | Template name | Family | Distinguishing metadata |
10
- | -------------------- | ------------------------------------------------- | ----------------------------------------- |
11
- | `Custom` | high-limit plan negotiated per client | `customPlan: true` inside `organization` |
12
- | `Integrator Starter` | integrators managing orgs for their own customers | `integratorLimits: {"maxManagedOrgs": N}` |
13
-
14
- A customer copy is a new product named `<Template> - <org email>`, private,
15
- carrying the template's blocks with the agreed changes, plus these human-only
16
- keys:
17
-
18
- | Key | Value | Purpose |
19
- | ------------ | ----------------------- | ---------------------------------------------------------- |
20
- | `visibility` | `private` | keep it out of the public catalog (backend reads this one) |
21
- | `orgAddress` | the org's `0x…` address | find the copy from the org |
22
- | `orgEmail` | the org/customer email | find the copy from the customer |
23
- | `copiedFrom` | template `prod_…` id | trace where the limits came from |
24
- | `copiedAt` | ISO-8601 UTC timestamp | when it was cloned |
25
-
26
- Older copies may carry `restoredFrom` / `restoredAt` instead of
27
- `copiedFrom` / `copiedAt`; those came from a one-off migration. Write the
28
- `copied*` pair for new copies and leave old ones alone.
29
-
30
- ## Resolving the template
31
-
32
- Search is a substring match, so `name:'Custom'` also returns every
33
- `Custom - client@example.org`. Always filter to the exact name and require
34
- exactly one active hit:
35
-
36
- ```bash
37
- $sj products search --limit 100 --query "active:'true' AND name:'Custom'" \
38
- | jq '[.data[] | select(.name == "Custom")] | if length == 1 then .[0] else error("expected one template, got \(length)") end'
39
- ```
40
-
41
- Show the user the template's blocks pretty-printed before asking for changes:
42
-
43
- ```bash
44
- jq '.metadata | {organization: (.organization | fromjson), features: (.features | fromjson), votingTypes: (.votingTypes | fromjson), integratorLimits: ((.integratorLimits // "null") | fromjson)}'
45
- ```
46
-
47
- ## What to ask the user
48
-
49
- - **Overrides** per block, as key/value changes (e.g. "2FAemail to 10000",
50
- "maxCensus 80000", "whiteLabel true"). Keys must exist on the template; the
51
- script refuses unknown block names and unknown top-level keys inside a
52
- block, since the backend would silently ignore them. Check the spelling
53
- with the user before the dry run rather than after it refuses.
54
- - **Prices**: yearly and monthly amounts in cents. Default is the template
55
- amount; custom plans are negotiated, so ask rather than assume.
56
- - **Label**: short client name used in price nicknames
57
- (`Custom yearly (Client)`), so the price list stays readable.
58
- - **Org email**: defaults to the customer email; it becomes part of the
59
- product name.
60
-
61
- Write the overrides to a JSON file keyed by block:
62
-
63
- ```json
64
- { "features": { "2FAemail": 10000 }, "organization": { "maxCensus": 80000 } }
65
- ```
66
-
67
- ## Clone
68
-
69
- ```bash
70
- scripts/clone-product.sh \
71
- --template "Custom" \
72
- --org-email client@example.org \
73
- --org-address 0x0000000000000000000000000000000000000000 \
74
- --label "Client" \
75
- --override-file overrides.json \
76
- --yearly 100000 --monthly 10000 \
77
- --dry-run # first: paste the output into the confirmation table
78
- ```
79
-
80
- Without `--dry-run` it prints `{"product": "prod_…", "name": "…", "prices": {"year": "price_…", "month": "price_…"}}`.
81
-
82
- What the script does, in order, and why:
83
-
84
- 1. Reads the template and checks the three marker blocks parse as JSON.
85
- 2. Deep-merges the overrides into each block and re-serialises compactly.
86
- 3. `products create`, **inactive**, with name, description
87
- (`<template description> Custom copy of <template id> for <label> (<email>).`),
88
- the merged blocks and the keys above. No `default_price`: the catalog
89
- default marker lives on a default price's metadata and a copy must never
90
- become the default plan. Inactive because the backend syncs active
91
- products on `product.created`, and an integrator product synced before
92
- its prices exist has zero prices, which is exactly what the backend's
93
- free-integrator selector matches. An integrator signing up in that window
94
- would land on the client's plan.
95
- 4. One `prices create` per template interval (year, month), interval count,
96
- currency, amount and `tax_behavior` from the template unless overridden, nickname
97
- `<Template> yearly|monthly (<label>)`, and `freeTrialDays` copied if the
98
- template's price had it. It refuses a template with more than one active
99
- price per interval (the backend keeps the last one listed, so which to copy
100
- is ambiguous), a price with no `unit_amount` unless you pass the amount,
101
- and an integrator copy whose prices are all zero (it would compete with
102
- the free integrator plan).
103
- 5. `products update … active=true`: the product becomes visible to the
104
- backend only now, with both prices, through the `product.updated` webhook
105
- it listens to (`price.*` events are ignored).
106
-
107
- ## Verify the copy before using it
108
-
109
- ```bash
110
- $sj products retrieve prod_xxx | jq '{
111
- name, active, visibility: .metadata.visibility, copiedFrom: .metadata.copiedFrom, copiedAt: .metadata.copiedAt,
112
- orgAddress: .metadata.orgAddress, default_price,
113
- blocks_ok: ([.metadata.organization, .metadata.features, .metadata.votingTypes] | map(fromjson | type == "object") | all),
114
- managedOrgs: ((.metadata.integratorLimits // "{}") | fromjson | .maxManagedOrgs)
115
- }'
116
- $sj prices list --product prod_xxx --active | jq '[.data[] | {id, nickname, unit_amount, currency, interval: .recurring.interval}]'
117
- ```
118
-
119
- Expect: `active: true`, `visibility: "private"`, `default_price: null`,
120
- `blocks_ok: true`, exactly one price per interval, and for an integrator copy
121
- `managedOrgs > 0`.
122
-
123
- ## Undo
124
-
125
- Archive rather than delete, so invoices that reference the prices stay valid:
126
-
127
- ```bash
128
- $sj products update prod_xxx -d active=false
129
- ```
130
-
131
- The backend drops an inactive product from its plan cache on the next
132
- `product.updated` webhook or restart.
@@ -1,212 +0,0 @@
1
- # Stripe CLI cookbook
2
-
3
- All commands below go through the wrapper, which refuses to run without
4
- `STRIPE_ENV`. Agent shells usually drop variables between tool calls, so set
5
- both at the start of every invocation, not once per session:
6
-
7
- ```bash
8
- export STRIPE_ENV=live STRIPE_ACCOUNT_NAME='<account name>' sj=<skill dir>/scripts/stripe-json.sh # or STRIPE_ENV=sandbox
9
- ```
10
-
11
- `STRIPE_ACCOUNT_NAME` is the name `stripe-json.sh env` printed and the user
12
- confirmed; with it set the wrapper also refuses a different account in the
13
- same mode (a second live account, another sandbox).
14
-
15
- The wrapper adds `--live` for live, checks the banner (before the command
16
- too, for anything that is not a `list` / `retrieve` / `search`), strips it,
17
- turns `{"error": …}` bodies into a non-zero exit, and refuses `delete` /
18
- `delete_*` / `cancel` / `void_invoice` / `mark_uncollectible` / `detach`
19
- without `--confirm`. Everything it prints on stdout is JSON, so
20
- pipe straight into `jq`.
21
-
22
- ## Quirks worth knowing
23
-
24
- - **One active account.** `stripe config --list` shows it. `stripe switch` and
25
- `stripe login` change it for every terminal. `--live` on a sandbox account
26
- errors out; a sandbox-style command on the live account silently hits live
27
- _test_ mode. The banner `▸ Running in <name> · live|sandbox` is the only
28
- reliable signal, which is why the wrapper reads it.
29
- - **Banner placement.** It goes to stderr for most commands and to stdout for
30
- some. Never parse raw CLI output with `jq` directly.
31
- - **API errors exit 0.** The CLI prints the error JSON and returns success.
32
- - **Search is a substring match and lags.** `products search --query "name:'Custom'"`
33
- returns every `Custom - …` copy; filter with `jq 'select(.name == "Custom")'`.
34
- Search indexes update within about a minute, so use `list` for anything
35
- that must reflect what you just created.
36
- - **Boolean flags take no value.** `prices list --active`, not `--active true`.
37
- Inside `-d` parameters they do: `-d active=false`.
38
- - **Interactive prompts.** `subscriptions cancel`, `customers delete`,
39
- `coupons delete` ask "are you sure" on a TTY and hang without one. Pass
40
- `--confirm`.
41
- - **Nested params** use bracket syntax: `-d "items[0][price]=price_xxx"`,
42
- `-d "metadata[address]=0x…"`, `-d "expand[0]=discounts"`.
43
-
44
- ## Lookups
45
-
46
- ```bash
47
- # backends that will act on every write (sandbox usually reaches dev and staging)
48
- $sj webhook_endpoints list | jq '[.data[] | select(.status == "enabled") | .url]'
49
-
50
- # customer by email (expect exactly one)
51
- $sj customers list --email client@example.org | jq '.data | length, (.[0] | {id, name, email, currency, default_pm: .invoice_settings.default_payment_method})'
52
-
53
- # saved payment methods (decides the collection default)
54
- $sj payment_methods list --customer cus_xxx | jq '[.data[] | {id, type}]'
55
-
56
- # product by exact name (active only)
57
- $sj products search --limit 100 --query "active:'true' AND name:'Professional'" \
58
- | jq '[.data[] | select(.name == "Professional")]'
59
-
60
- # recurring prices of a product
61
- $sj prices list --product prod_xxx --active --limit 100 \
62
- | jq '[.data[] | select(.recurring != null) | {id, nickname, currency, unit_amount, interval: .recurring.interval, trial: .metadata.freeTrialDays}]'
63
-
64
- # one org, one subscription: list-based, case-insensitive (search lags),
65
- # paginated (100 per page is a hard cap, and a missed page is a missed duplicate).
66
- # No --status: the default already returns every non-canceled subscription,
67
- # including unpaid and paused ones that still hold the org.
68
- # Pages are collected first and the filter runs only if every page succeeded:
69
- # a failed page must stop the check, not shrink it to an empty "no duplicate".
70
- addr=0x0000000000000000000000000000000000000000
71
- pages="$(
72
- after=()
73
- while :; do
74
- page="$($sj subscriptions list --limit 100 "${after[@]}")" || exit 1
75
- printf '%s\n' "$page"
76
- [[ "$(jq -r .has_more <<<"$page")" == true ]] || break
77
- after=(--starting-after "$(jq -r '.data[-1].id' <<<"$page")")
78
- done
79
- )" && jq -s --arg a "$addr" '[.[].data[] | select(.status != "incomplete_expired") | select((.metadata.address // "" | ascii_downcase) == ($a | ascii_downcase)) | {id, status, customer}]' <<<"$pages" \
80
- || echo "duplicate check FAILED; do not continue" >&2
81
-
82
- # customer's other subscriptions
83
- $sj subscriptions list --customer cus_xxx | jq '[.data[] | {id, status, product: .items.data[0].price.product}]'
84
- ```
85
-
86
- ## Discounts
87
-
88
- ```bash
89
- # existing coupons that could fit (valid, matching discount, redemptions left)
90
- $sj coupons list --limit 100 | jq '[.data[] | select(.valid) | {id, name, percent_off, amount_off, currency, duration, duration_in_months, redeemed: .times_redeemed, max: .max_redemptions}]'
91
-
92
- # a promotion code the user named. Since API 2025-09-30.clover the coupon sits
93
- # at .promotion.coupon as a bare id; older versions embed it at .coupon.
94
- $sj promotion_codes list --active --code SOMECODE \
95
- | jq '.data[] | {id, code, coupon: (.promotion.coupon // .coupon | if type == "object" then .id else . end)}'
96
- # then `coupons retrieve <coupon>` for its percent/amount and duration
97
-
98
- # new single-use coupon (only when nothing fits)
99
- $sj coupons create -d percent_off=100 -d duration=forever -d max_redemptions=1 \
100
- -d "name=Client Name - free exception" | jq '{id, name, percent_off, duration, max_redemptions}'
101
- # amount-based variant: -d amount_off=50000 -d currency=eur
102
- # limited variant: -d duration=repeating -d duration_in_months=6
103
- ```
104
-
105
- `max_redemptions` cannot be changed after creation. If you ever need to close
106
- a coupon that was created without it, `coupons delete <id> --confirm` blocks
107
- new redemptions and leaves existing discounts untouched.
108
-
109
- ## Create the subscription
110
-
111
- ```bash
112
- # send_invoice (customer has no card, or you want an invoice emailed)
113
- $sj subscriptions create \
114
- -d customer=cus_xxx \
115
- -d "items[0][price]=price_xxx" \
116
- -d "metadata[address]=0x0000000000000000000000000000000000000000" \
117
- -d collection_method=send_invoice -d days_until_due=30 \
118
- -d "discounts[0][coupon]=COUPONID" # only if a discount was chosen
119
- # -d "discounts[0][promotion_code]=promo_xxx" # promotion code instead
120
- # -d trial_period_days=14
121
- # -d backdate_start_date=1760000000 -d billing_cycle_anchor=1762000000
122
- # -d cancel_at=1790000000
123
- # -d "description=…"
124
-
125
- # charge_automatically with the customer's default payment method
126
- $sj subscriptions create -d customer=cus_xxx -d "items[0][price]=price_xxx" \
127
- -d "metadata[address]=0x…" -d collection_method=charge_automatically
128
- # a saved card that is NOT the customer's default is never picked up on its own:
129
- # add: -d default_payment_method=pm_xxx
130
-
131
- # charge_automatically WITHOUT a card: created incomplete, expires in 23h unless paid
132
- # add: -d payment_behavior=default_incomplete
133
- # then hand over: latest_invoice.hosted_invoice_url
134
-
135
- # finalize the first invoice of a send_invoice subscription, only while it is
136
- # still a draft (a trial invoice is already paid; a future anchor may have none)
137
- $sj invoices retrieve in_xxx | jq -r .status # expect: draft
138
- $sj invoices finalize_invoice in_xxx | jq '{id, status, total, amount_due, amount_paid, hosted_invoice_url}'
139
-
140
- # a manually finalized invoice is not emailed; send it if the customer should get the email
141
- $sj invoices send_invoice in_xxx | jq '{id, status, hosted_invoice_url}'
142
- ```
143
-
144
- ## Checkout link instead of a direct subscription
145
-
146
- Mirrors what the app's own checkout does (tax, tax id collection, promotion
147
- codes), but hosted so the link can be sent by hand. Stripe creates the
148
- subscription when the customer pays; `subscription_data[metadata][address]`
149
- is what makes the backend recognise it.
150
-
151
- ```bash
152
- $sj checkout sessions create \
153
- -d mode=subscription \
154
- -d customer=cus_xxx \
155
- -d "customer_update[name]=auto" -d "customer_update[address]=auto" \
156
- -d "line_items[0][price]=price_xxx" -d "line_items[0][quantity]=1" \
157
- -d "subscription_data[metadata][address]=0x0000000000000000000000000000000000000000" \
158
- -d "automatic_tax[enabled]=true" -d "tax_id_collection[enabled]=true" \
159
- -d allow_promotion_codes=true \
160
- -d success_url="https://app.vocdoni.io/" -d cancel_url="https://app.vocdoni.io/" \
161
- | jq '{id, url, expires_at: (.expires_at | todate)}'
162
- # discount on the session instead of promotion codes: -d "discounts[0][coupon]=…" (then drop allow_promotion_codes)
163
- # trial: -d "subscription_data[trial_period_days]=14"
164
- ```
165
-
166
- Verify later with `checkout sessions retrieve cs_xxx | jq '{status, payment_status, subscription}'`.
167
-
168
- ## Read back for the final table
169
-
170
- ```bash
171
- $sj subscriptions retrieve sub_xxx -d "expand[0]=discounts" -d "expand[1]=latest_invoice" | jq '{
172
- id, status, customer, collection_method, days_until_due, metadata,
173
- price: .items.data[0].price.id, amount: .items.data[0].price.unit_amount, currency,
174
- period_end: (.items.data[0].current_period_end | todate),
175
- discount: (.discounts[0] | if . then {id, coupon: (.source.coupon // .coupon | if type == "object" then .id else . end)} else null end),
176
- invoice: (.latest_invoice | {id, status, total, amount_paid, hosted_invoice_url})
177
- }'
178
-
179
- # the Discount row: since API 2025-09-30.clover a discount no longer embeds its
180
- # coupon (it is a bare id at .source.coupon), so read the coupon itself
181
- $sj coupons retrieve COUPONID | jq '{id, percent_off, amount_off, currency, duration, duration_in_months, redeemed: "\(.times_redeemed)/\(.max_redemptions)"}'
182
- ```
183
-
184
- ## Undo (only if the user asks)
185
-
186
- ```bash
187
- $sj subscriptions cancel sub_xxx --confirm # cancels now; invoices stay
188
- $sj invoices void_invoice in_xxx --confirm # open invoice you do not want paid
189
- $sj products update prod_xxx -d active=false # archive a cloned product (backend drops the plan)
190
- $sj coupons delete COUPONID --confirm
191
- ```
192
-
193
- ## Stripe MCP equivalents
194
-
195
- When the Stripe MCP server is connected instead of the CLI, use its tools for
196
- the same phases. Names vary by server version; the usual mapping is:
197
-
198
- | Cookbook call | MCP tool |
199
- | --------------------------------------- | -------------------------------------------------------------------------------------- |
200
- | `customers list --email` | `list_customers` (email filter) |
201
- | `products search` / `products retrieve` | `list_products` / `search_stripe_resources` |
202
- | `prices list --product` | `list_prices` (product filter) |
203
- | `subscriptions list` | `list_subscriptions` |
204
- | `coupons list` / `coupons create` | `list_coupons` / `create_coupon` |
205
- | `subscriptions create` | `create_subscription` (check it accepts `metadata`, `collection_method`, `discounts`) |
206
- | `products create` / `prices create` | `create_product` / `create_price` |
207
- | `checkout sessions create` | `create_payment_link` is the closest (no `subscription_data.metadata`); prefer the CLI |
208
- | `invoices finalize_invoice` | usually absent; use the CLI |
209
-
210
- The environment guard with MCP is the `livemode` field on any object you read
211
- back. If a call the workflow needs has no MCP tool, fall back to the CLI for
212
- that call rather than skipping it.
@@ -1,247 +0,0 @@
1
- #!/usr/bin/env bash
2
- # Clone a template plan product ("Custom", "Integrator Starter") into a
3
- # per-customer product, carrying over the plan metadata the SaaS backend reads
4
- # (organization / features / votingTypes / integratorLimits) with optional
5
- # overrides, and recreating its recurring prices.
6
- #
7
- # Usage:
8
- # clone-product.sh --template <prod_id|"Custom"|"Integrator Starter"> \
9
- # --org-email <email> --org-address <0x...> --label <text> \
10
- # [--override-file <json>] [--yearly <cents>] [--monthly <cents>] \
11
- # [--dry-run]
12
- #
13
- # --override-file JSON object keyed by metadata block, deep-merged over the
14
- # template, e.g. {"features": {"2FAemail": 10000}, "organization": {"maxCensus": 80000}}
15
- # --yearly/--monthly unit_amount in the smallest currency unit (cents) for the
16
- # cloned price; default = template amount.
17
- # --dry-run print the exact stripe invocations and the metadata that
18
- # would be written; write nothing. The template/price
19
- # validation below (ambiguous prices, missing unit_amount,
20
- # an all-zero-price integrator copy) still runs and still
21
- # refuses first: a rejected combination prints nothing to
22
- # preview even under --dry-run.
23
- #
24
- # Environment: STRIPE_ENV=live|sandbox (required) and STRIPE_ACCOUNT_NAME
25
- # (optional), passed through to stripe-json.sh.
26
- #
27
- # Output (stdout): one JSON object {product, prices: {year, month}, name}.
28
- #
29
- # What is deliberately NOT done, and why:
30
- # - default_price is not set: the backend's "default plan" marker lives on the
31
- # default price's metadata, and a per-customer copy must never become the
32
- # catalog default.
33
- # - customer metadata is not touched: the backend writes the customer's
34
- # `address` itself when it is empty.
35
- set -euo pipefail
36
-
37
- here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
38
- sj="$here/stripe-json.sh"
39
-
40
- # jq does the metadata merging below; stripe-json.sh checks for it too, but
41
- # this script uses it directly before the first Stripe call.
42
- if ! command -v jq >/dev/null 2>&1; then
43
- echo "jq not found on PATH; install it first (https://jqlang.org/download/), e.g. brew install jq / sudo apt install jq" >&2
44
- exit 2
45
- fi
46
-
47
- template="" org_email="" org_address="" label="" override_file="" yearly="" monthly="" dry_run=0
48
- while [[ $# -gt 0 ]]; do
49
- case "$1" in
50
- --template) template="$2"; shift 2 ;;
51
- --org-email) org_email="$2"; shift 2 ;;
52
- --org-address) org_address="$2"; shift 2 ;;
53
- --label) label="$2"; shift 2 ;;
54
- --override-file) override_file="$2"; shift 2 ;;
55
- --yearly) yearly="$2"; shift 2 ;;
56
- --monthly) monthly="$2"; shift 2 ;;
57
- --dry-run) dry_run=1; shift ;;
58
- -h|--help) awk 'NR == 1 { next } /^#/ { print; next } { exit }' "$0"; exit 0 ;;
59
- *) echo "unknown argument: $1" >&2; exit 2 ;;
60
- esac
61
- done
62
-
63
- for v in template org_email org_address label; do
64
- [[ -n "${!v}" ]] || { echo "--${v//_/-} is required" >&2; exit 2; }
65
- done
66
- [[ "$org_address" =~ ^0x[0-9a-fA-F]{40}$ ]] || { echo "--org-address must be 0x + 40 hex chars" >&2; exit 2; }
67
- [[ "$org_email" == *@* ]] || { echo "--org-email does not look like an email" >&2; exit 2; }
68
- if [[ -n "$override_file" ]]; then
69
- jq -e 'type == "object"' "$override_file" >/dev/null || { echo "--override-file must be a JSON object" >&2; exit 2; }
70
- fi
71
- for amt in "$yearly" "$monthly"; do
72
- [[ -z "$amt" || "$amt" =~ ^[0-9]+$ ]] || { echo "--yearly/--monthly must be integer cents" >&2; exit 2; }
73
- done
74
-
75
- # Resolve the template. Search is a substring match, so filter to the exact
76
- # name; a per-customer copy is named "<Template> - <email>" and must not win.
77
- # Every copy is active and matches too, so read every page: past 100 copies
78
- # the template itself can land on a later one.
79
- if [[ "$template" == prod_* ]]; then
80
- tpl="$("$sj" products retrieve "$template")"
81
- # The name path only ever finds active templates; hold an id to the same bar.
82
- [[ "$(jq -r '.active' <<<"$tpl")" == true ]] \
83
- || { echo "product $template is archived; not a usable template" >&2; exit 1; }
84
- if jq -e '.metadata.copiedFrom // .metadata.restoredFrom' <<<"$tpl" >/dev/null; then
85
- echo "warning: $template is itself a per-customer copy; cloning its limits, not the catalog template's" >&2
86
- fi
87
- else
88
- tpl='[]' page=()
89
- while :; do
90
- res="$("$sj" products search --limit 100 --query "active:'true' AND name:'$template'" ${page[@]+"${page[@]}"})"
91
- tpl="$(jq -c --argjson acc "$tpl" --arg n "$template" '$acc + [.data[] | select(.name == $n)]' <<<"$res")"
92
- [[ "$(jq -r '.has_more' <<<"$res")" == true ]] || break
93
- page=(-d "page=$(jq -r '.next_page' <<<"$res")")
94
- done
95
- count="$(jq 'length' <<<"$tpl")"
96
- if [[ "$count" -ne 1 ]]; then
97
- echo "expected exactly one active product named '$template', found $count" >&2
98
- exit 1
99
- fi
100
- tpl="$(jq '.[0]' <<<"$tpl")"
101
- fi
102
-
103
- tpl_id="$(jq -r '.id' <<<"$tpl")"
104
- tpl_name="$(jq -r '.name' <<<"$tpl")"
105
- tpl_desc="$(jq -r '.description // ""' <<<"$tpl")"
106
-
107
- # The three marker keys are what make a product a plan for the backend. A
108
- # template without them is not a template.
109
- for k in organization features votingTypes; do
110
- jq -e --arg k "$k" '.metadata[$k] | . != null and (fromjson | type == "object")' <<<"$tpl" >/dev/null \
111
- || { echo "template $tpl_id has no valid JSON metadata '$k'; not a plan product" >&2; exit 1; }
112
- done
113
-
114
- overrides='{}'
115
- [[ -n "$override_file" ]] && overrides="$(cat "$override_file")"
116
-
117
- # Merge each JSON block: template * overrides, then re-serialise compactly.
118
- merged="$(jq -c --argjson o "$overrides" '
119
- .metadata as $m
120
- | ["organization","features","votingTypes","integratorLimits"]
121
- | map(select($m[.] != null and $m[.] != ""))
122
- | map({key: ., value: (($m[.] | fromjson) * ($o[.] // {}) | tojson)})
123
- | from_entries' <<<"$tpl")"
124
-
125
- # Refuse override blocks, and keys inside a block, that do not exist on the
126
- # template (typo guard): the backend ignores unknown keys, so a misspelt
127
- # `2FAEmail` would be written and silently never take effect.
128
- unknown="$(jq -r --argjson m "$merged" 'keys - ($m | keys) | .[]' <<<"$overrides")"
129
- [[ -z "$unknown" ]] || { echo "override block(s) not present on template: $unknown" >&2; exit 2; }
130
- unknown="$(jq -r --argjson m "$(jq -c '.metadata' <<<"$tpl")" '
131
- to_entries[] | .key as $b | select(.value | type == "object")
132
- | (.value | keys) - ($m[$b] | fromjson | keys) | .[] | "\($b).\(.)"' <<<"$overrides")"
133
- [[ -z "$unknown" ]] || { echo "override key(s) not present on template: $(tr '\n' ' ' <<<"$unknown")" >&2; exit 2; }
134
-
135
- now="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
136
- new_name="$tpl_name - $org_email"
137
- new_desc="${tpl_desc:+$tpl_desc }Custom copy of $tpl_id for $label ($org_email)."
138
-
139
- # Created INACTIVE on purpose. The backend only syncs active products, and an
140
- # integrator product that is synced before its prices exist has zero prices,
141
- # which is exactly what the backend's "free integrator plan" selector matches.
142
- # Activating only after the prices exist closes that window.
143
- product_args=(products create
144
- -d "name=$new_name"
145
- -d "description=$new_desc"
146
- -d "active=false"
147
- -d "metadata[visibility]=private"
148
- -d "metadata[orgAddress]=$org_address"
149
- -d "metadata[orgEmail]=$org_email"
150
- -d "metadata[copiedFrom]=$tpl_id"
151
- -d "metadata[copiedAt]=$now")
152
- # NUL-delimited so the JSON values go through verbatim (@tsv would double any
153
- # backslash and corrupt an escaped quote inside a block).
154
- while IFS= read -r -d '' kv; do
155
- product_args+=(-d "$kv")
156
- done < <(jq -j 'to_entries[] | "metadata[\(.key)]=\(.value)\u0000"' <<<"$merged")
157
-
158
- # Recurring prices of the template. The backend keeps the LAST active price it
159
- # lists per interval, so a template with several is ambiguous: refuse rather
160
- # than copy a price the backend does not actually use for the template.
161
- prices="$("$sj" prices list --product "$tpl_id" --active --limit 100 \
162
- | jq -c '[.data[] | select(.recurring != null and (.recurring.interval == "year" or .recurring.interval == "month"))]')"
163
- [[ "$(jq 'length' <<<"$prices")" -gt 0 ]] || { echo "template $tpl_id has no active recurring prices" >&2; exit 1; }
164
- dup="$(jq -r 'group_by(.recurring.interval) | map(select(length > 1) | "\(.[0].recurring.interval): \(map(.id) | join(", "))") | .[]' <<<"$prices")"
165
- [[ -z "$dup" ]] || { echo "template $tpl_id has more than one active price per interval ($dup); archive the extras first" >&2; exit 1; }
166
- for pair in "year:$yearly" "month:$monthly"; do
167
- [[ -z "${pair#*:}" ]] || jq -e --arg i "${pair%%:*}" 'any(.recurring.interval == $i)' <<<"$prices" >/dev/null \
168
- || { echo "template $tpl_id has no active ${pair%%:*} price to override" >&2; exit 2; }
169
- done
170
-
171
- # One row per price, \x1f-separated: unlike tab it is not IFS whitespace, so
172
- # empty fields (no trial, no tax behavior) do not shift the ones after them.
173
- # interval_count is carried over: a quarterly price is interval=month, count=3,
174
- # and dropping the count would bill the customer every month.
175
- price_rows=() paid=0
176
- while IFS=$'\x1f' read -r interval count currency amount trial tax; do
177
- case "$interval" in
178
- year) [[ -n "$yearly" ]] && amount="$yearly" ;;
179
- month) [[ -n "$monthly" ]] && amount="$monthly" ;;
180
- esac
181
- [[ "$amount" =~ ^[0-9]+$ ]] \
182
- || { echo "template $interval price has no unit_amount (tiered or decimal pricing); pass --${interval}ly explicitly" >&2; exit 1; }
183
- (( 10#$amount > 0 )) && paid=1
184
- price_rows+=("$interval"$'\x1f'"$count"$'\x1f'"$currency"$'\x1f'"$amount"$'\x1f'"$trial"$'\x1f'"$tax")
185
- done < <(jq -r '.[] | [.recurring.interval, (.recurring.interval_count // 1), .currency, (.unit_amount // ""), (.metadata.freeTrialDays // ""), (.tax_behavior // "")]
186
- | map(tostring) | join("\u001f")' <<<"$prices")
187
-
188
- # The backend picks THE free integrator plan with an unordered FindOne on
189
- # maxManagedOrgs > 0 and zero prices; an all-zero integrator copy would make
190
- # that choice random for every integrator signup.
191
- if [[ $paid -eq 0 ]] && jq -e '(.integratorLimits // "{}" | fromjson | .maxManagedOrgs // 0) > 0' <<<"$merged" >/dev/null; then
192
- echo "refusing an integrator copy whose prices are all zero: it would compete with the free integrator plan (see references/backend-contract.md)" >&2
193
- exit 2
194
- fi
195
-
196
- # Sets `args` to the prices create invocation for one row.
197
- price_args() {
198
- local product="$1" interval count currency amount trial tax
199
- IFS=$'\x1f' read -r interval count currency amount trial tax <<<"$2"
200
- args=(prices create
201
- -d "product=$product"
202
- -d "currency=$currency"
203
- -d "unit_amount=$amount"
204
- -d "recurring[interval]=$interval"
205
- -d "recurring[interval_count]=$count"
206
- -d "nickname=$tpl_name ${interval}ly ($label)")
207
- [[ -n "$trial" ]] && args+=(-d "metadata[freeTrialDays]=$trial")
208
- [[ -n "$tax" && "$tax" != unspecified ]] && args+=(-d "tax_behavior=$tax")
209
- return 0
210
- }
211
-
212
- if [[ $dry_run -eq 1 ]]; then
213
- echo "# template: $tpl_id ($tpl_name)"
214
- echo "# metadata blocks after overrides:"
215
- jq '.' <<<"$merged" | sed 's/^/# /'
216
- echo "stripe-json.sh $(printf '%q ' "${product_args[@]}")"
217
- for row in "${price_rows[@]}"; do
218
- price_args "<new product id>" "$row"
219
- echo "stripe-json.sh $(printf '%q ' "${args[@]}")"
220
- done
221
- echo "stripe-json.sh products update <new product id> -d active=true"
222
- exit 0
223
- fi
224
-
225
- product="$("$sj" "${product_args[@]}")"
226
- product_id="$(jq -r '.id' <<<"$product")"
227
-
228
- # From here on a failure leaves an inactive product behind; name it so it can
229
- # be finished or archived by hand instead of cloned a second time.
230
- finished=0
231
- trap '[[ $finished -eq 1 ]] || echo "clone-product.sh: stopped after creating inactive product $product_id; finish or archive it by hand" >&2' EXIT
232
-
233
- result="$(jq -n --arg p "$product_id" --arg n "$new_name" '{product: $p, name: $n, prices: {}}')"
234
- for row in "${price_rows[@]}"; do
235
- price_args "$product_id" "$row"
236
- price="$("$sj" "${args[@]}")"
237
- interval="$(jq -r '.recurring.interval' <<<"$price")"
238
- result="$(jq --arg i "$interval" --arg id "$(jq -r .id <<<"$price")" '.prices[$i] = $id' <<<"$result")"
239
- done
240
-
241
- # Activate now that the prices exist. This is also the product.updated event
242
- # the backend syncs on (it ignores price.* events), so the plan it caches
243
- # already carries both prices.
244
- "$sj" products update "$product_id" -d active=true >/dev/null
245
- finished=1
246
-
247
- jq -c '.' <<<"$result"