@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 369 lines 12.4 KB
Raw
1 import * as androidpublisher from "@distilled.cloud/gcp/androidpublisher_v3";
2 import { unownedUnlessPrevious } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import { GcpEnvironment } from "../Environment.ts";
9 import type { Providers } from "../Providers.ts";
10 import {
11 DEFAULT_REGIONS_VERSION,
12 defaultOfferPhases,
13 defaultOfferRegionalConfigs,
14 defaultOfferTargeting,
15 getOffer,
16 jsonEqual,
17 toOfferId,
18 updateMaskOf,
19 } from "./internal.ts";
20
21 export type MonetizationSubscriptionsBasePlansOfferProps = {
22 /**
23 * Play package name of the parent app. Immutable — changing it
24 * replaces the offer.
25 */
26 packageName: string;
27 /**
28 * Parent subscription product id. Immutable — changing it replaces
29 * the offer.
30 */
31 productId: string;
32 /**
33 * Parent auto-renewing base plan id. Immutable — changing it
34 * replaces the offer.
35 */
36 basePlanId: string;
37 /**
38 * Unique offer id within the base plan. If omitted, a unique id is
39 * generated. Immutable — changing it replaces the offer.
40 */
41 offerId?: string;
42 /**
43 * Offer phases (1-2). Defaults to a one-week free phase in the US.
44 */
45 phases?: androidpublisher.SubscriptionOfferPhase[];
46 /**
47 * Region-specific availability. Defaults to the US.
48 */
49 regionalConfigs?: androidpublisher.RegionalSubscriptionOfferConfig[];
50 /**
51 * Configuration for locations Play may launch in later.
52 */
53 otherRegionsConfig?: androidpublisher.OtherRegionsSubscriptionOfferConfig;
54 /**
55 * Custom billing-library tags (RFC-1034, max 20 characters each).
56 */
57 offerTags?: androidpublisher.OfferTag[];
58 /**
59 * Eligibility targeting. Defaults to new subscribers of this
60 * subscription.
61 */
62 targeting?: androidpublisher.SubscriptionOfferTargeting;
63 /**
64 * Regions-version string used when creating or updating regional
65 * prices (for example `2025/01`).
66 * @default "2025/01"
67 */
68 regionsVersion?: string;
69 /**
70 * Propagation latency tolerance for product updates.
71 */
72 latencyTolerance?:
73 | androidpublisher.PatchMonetizationSubscriptionsBasePlansOffersLatencyToleranceEnum
74 | (string & {});
75 };
76
77 export type MonetizationSubscriptionsBasePlansOffer = Resource<
78 "GCP.AndroidPublisher.MonetizationSubscriptionsBasePlansOffer",
79 MonetizationSubscriptionsBasePlansOfferProps,
80 {
81 /** Play package name. */
82 packageName: string;
83 /** Parent subscription product id. */
84 productId: string;
85 /** Parent base plan id. */
86 basePlanId: string;
87 /** Offer id. */
88 offerId: string;
89 /** Project id used when the offer was reconciled. */
90 project: string;
91 /** Offer state (`DRAFT`, `ACTIVE`, `INACTIVE`). */
92 state: string | undefined;
93 /** Offer phases. */
94 phases: androidpublisher.SubscriptionOfferPhase[] | undefined;
95 /** Regional availability. */
96 regionalConfigs: androidpublisher.RegionalSubscriptionOfferConfig[] | undefined;
97 /** Configuration for future Play locations. */
98 otherRegionsConfig: androidpublisher.OtherRegionsSubscriptionOfferConfig | undefined;
99 /** Custom billing-library tags. */
100 offerTags: androidpublisher.OfferTag[] | undefined;
101 /** Eligibility targeting. */
102 targeting: androidpublisher.SubscriptionOfferTargeting | undefined;
103 },
104 never,
105 Providers
106 >;
107
108 /**
109 * A Google Play subscription offer
110 * (`monetization.subscriptions.basePlans.offers`).
111 *
112 * Offers have no labels field, so ownership rests on the deterministic
113 * offer id: `read` reports an offer it finds without prior state as
114 * unowned (adopt it with `--adopt`). `packageName`, `productId`,
115 * `basePlanId`, and `offerId` are identity — changing any of them
116 * replaces the offer. Phases, regional configs, tags, and targeting
117 * update in place. Only draft offers can be deleted. The parent base
118 * plan must be auto-renewing.
119 *
120 * ### Creating an Offer
121 * **Example:** Generated offer id (one-week free trial)
122 * ```typescript
123 * const offer = yield* GCP.AndroidPublisher.MonetizationSubscriptionsBasePlansOffer(
124 * "Intro",
125 * {
126 * packageName: "com.example.app",
127 * productId: subscription.productId,
128 * basePlanId: "monthly",
129 * },
130 * );
131 * ```
132 *
133 * **Example:** Explicit id and discounted first month
134 * ```typescript
135 * const offer = yield* GCP.AndroidPublisher.MonetizationSubscriptionsBasePlansOffer(
136 * "Intro",
137 * {
138 * packageName: "com.example.app",
139 * productId: "premium",
140 * basePlanId: "monthly",
141 * offerId: "intro",
142 * phases: [
143 * {
144 * duration: "P1M",
145 * recurrenceCount: 1,
146 * regionalConfigs: [
147 * { regionCode: "US", relativeDiscount: 0.5 },
148 * ],
149 * },
150 * ],
151 * },
152 * );
153 * ```
154 *
155 * ### Updating an Offer
156 * **Example:** Close the offer to new subscribers
157 * ```typescript
158 * // Same logical id as before; only the regional config changes.
159 * const offer = yield* GCP.AndroidPublisher.MonetizationSubscriptionsBasePlansOffer(
160 * "Intro",
161 * {
162 * packageName: "com.example.app",
163 * productId: subscription.productId,
164 * basePlanId: "monthly",
165 * regionalConfigs: [
166 * { regionCode: "US", newSubscriberAvailability: false },
167 * ],
168 * },
169 * );
170 * ```
171 *
172 * @resource
173 * @category AndroidPublisher
174 */
175 export const MonetizationSubscriptionsBasePlansOffer =
176 Resource<MonetizationSubscriptionsBasePlansOffer>(
177 "GCP.AndroidPublisher.MonetizationSubscriptionsBasePlansOffer",
178 );
179
180 export class MonetizationSubscriptionsBasePlansOfferNotResolved extends Data.TaggedError(
181 "GCP.AndroidPublisher.MonetizationSubscriptionsBasePlansOfferNotResolved",
182 )<{
183 packageName: string;
184 productId: string;
185 basePlanId: string;
186 offerId: string;
187 }> {}
188
189 const toAttrs = (offer: androidpublisher.SubscriptionOffer, project: string) => ({
190 packageName: offer.packageName ?? "",
191 productId: offer.productId ?? "",
192 basePlanId: offer.basePlanId ?? "",
193 offerId: offer.offerId ?? "",
194 project,
195 state: offer.state,
196 phases: offer.phases,
197 regionalConfigs: offer.regionalConfigs,
198 otherRegionsConfig: offer.otherRegionsConfig,
199 offerTags: offer.offerTags,
200 targeting: offer.targeting,
201 });
202
203 const desiredBody = (input: {
204 packageName: string;
205 productId: string;
206 basePlanId: string;
207 offerId: string;
208 news: MonetizationSubscriptionsBasePlansOfferProps;
209 }): androidpublisher.SubscriptionOffer => ({
210 packageName: input.packageName,
211 productId: input.productId,
212 basePlanId: input.basePlanId,
213 offerId: input.offerId,
214 phases: input.news.phases ?? defaultOfferPhases(),
215 regionalConfigs: input.news.regionalConfigs ?? defaultOfferRegionalConfigs(),
216 otherRegionsConfig: input.news.otherRegionsConfig,
217 offerTags: input.news.offerTags,
218 targeting: input.news.targeting ?? defaultOfferTargeting(),
219 });
220
221 const needsSync = (
222 current: androidpublisher.SubscriptionOffer,
223 desired: androidpublisher.SubscriptionOffer,
224 ) =>
225 !jsonEqual(current.phases, desired.phases) ||
226 !jsonEqual(current.regionalConfigs, desired.regionalConfigs) ||
227 (desired.otherRegionsConfig !== undefined &&
228 !jsonEqual(current.otherRegionsConfig, desired.otherRegionsConfig)) ||
229 (desired.offerTags !== undefined && !jsonEqual(current.offerTags, desired.offerTags)) ||
230 (desired.targeting !== undefined && !jsonEqual(current.targeting, desired.targeting));
231
232 const syncMask = (
233 current: androidpublisher.SubscriptionOffer,
234 desired: androidpublisher.SubscriptionOffer,
235 ) =>
236 updateMaskOf(
237 !jsonEqual(current.phases, desired.phases) ? "phases" : undefined,
238 !jsonEqual(current.regionalConfigs, desired.regionalConfigs) ? "regionalConfigs" : undefined,
239 desired.otherRegionsConfig !== undefined &&
240 !jsonEqual(current.otherRegionsConfig, desired.otherRegionsConfig)
241 ? "otherRegionsConfig"
242 : undefined,
243 desired.offerTags !== undefined && !jsonEqual(current.offerTags, desired.offerTags)
244 ? "offerTags"
245 : undefined,
246 desired.targeting !== undefined && !jsonEqual(current.targeting, desired.targeting)
247 ? "targeting"
248 : undefined,
249 );
250
251 export const MonetizationSubscriptionsBasePlansOfferProvider = () =>
252 Provider.succeed(MonetizationSubscriptionsBasePlansOffer, {
253 stables: ["packageName", "productId", "basePlanId", "offerId", "project"],
254
255 diff: Effect.fn(function* ({ news, olds, output }) {
256 if (!isResolved(news)) return undefined;
257 const previousPackage = olds?.packageName ?? output?.packageName;
258 if (previousPackage !== undefined && news.packageName !== previousPackage) {
259 return { action: "replace" as const, deleteFirst: false };
260 }
261 const previousProduct = olds?.productId ?? output?.productId;
262 if (previousProduct !== undefined && news.productId !== previousProduct) {
263 return { action: "replace" as const, deleteFirst: true };
264 }
265 const previousPlan = olds?.basePlanId ?? output?.basePlanId;
266 if (previousPlan !== undefined && news.basePlanId !== previousPlan) {
267 return { action: "replace" as const, deleteFirst: true };
268 }
269 const previousOffer = olds?.offerId ?? output?.offerId;
270 if (
271 previousOffer !== undefined &&
272 news.offerId !== undefined &&
273 news.offerId !== previousOffer
274 ) {
275 return { action: "replace" as const, deleteFirst: true };
276 }
277 return undefined;
278 }),
279
280 read: Effect.fn(function* ({ id, olds, output, previous }) {
281 const env = yield* GcpEnvironment.current;
282 const packageName = olds?.packageName ?? output?.packageName ?? "";
283 const productId = olds?.productId ?? output?.productId ?? "";
284 const basePlanId = olds?.basePlanId ?? output?.basePlanId ?? "";
285 const offerId = yield* toOfferId(id, olds?.offerId, output?.offerId);
286 const existing = yield* getOffer(packageName, productId, basePlanId, offerId);
287 if (existing === undefined) return undefined;
288 const attrs = toAttrs(existing, env.project);
289 // No labels field: without prior state the offer may not be ours.
290 return output !== undefined ? attrs : unownedUnlessPrevious(attrs, previous, "offerId");
291 }),
292
293 reconcile: Effect.fn(function* ({ id, news, output }) {
294 const env = yield* GcpEnvironment.current;
295 const packageName = news.packageName;
296 const productId = news.productId;
297 const basePlanId = news.basePlanId;
298 const offerId = yield* toOfferId(id, news.offerId, output?.offerId);
299 const regionsVersion = news.regionsVersion ?? DEFAULT_REGIONS_VERSION;
300 const desired = desiredBody({
301 packageName,
302 productId,
303 basePlanId,
304 offerId,
305 news,
306 });
307
308 let current = yield* getOffer(packageName, productId, basePlanId, offerId);
309
310 if (current === undefined) {
311 const created = yield* androidpublisher
312 .createMonetizationSubscriptionsBasePlansOffers({
313 packageName,
314 productId,
315 basePlanId,
316 offerId,
317 "regionsVersion.version": regionsVersion,
318 body: desired,
319 })
320 .pipe(
321 Effect.catchTag("Conflict", () =>
322 getOffer(packageName, productId, basePlanId, offerId),
323 ),
324 );
325 current = created ?? undefined;
326 }
327
328 if (current === undefined) {
329 return yield* new MonetizationSubscriptionsBasePlansOfferNotResolved({
330 packageName,
331 productId,
332 basePlanId,
333 offerId,
334 });
335 }
336
337 if (needsSync(current, desired)) {
338 const updateMask = syncMask(current, desired);
339 if (updateMask.length > 0) {
340 current = yield* androidpublisher.patchMonetizationSubscriptionsBasePlansOffers({
341 packageName,
342 productId,
343 basePlanId,
344 offerId: current.offerId ?? offerId,
345 updateMask,
346 "regionsVersion.version": regionsVersion,
347 latencyTolerance: news.latencyTolerance,
348 body: desired,
349 });
350 }
351 }
352
353 return toAttrs(current, env.project);
354 }),
355
356 delete: Effect.fn(function* ({ output }) {
357 if (!output.packageName || !output.productId || !output.basePlanId || !output.offerId) {
358 return;
359 }
360 yield* androidpublisher
361 .deleteMonetizationSubscriptionsBasePlansOffers({
362 packageName: output.packageName,
363 productId: output.productId,
364 basePlanId: output.basePlanId,
365 offerId: output.offerId,
366 })
367 .pipe(Effect.catchTag("NotFound", () => Effect.void));
368 }),
369 });