waffo-pancake 0.3.0 → 0.5.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.
@@ -0,0 +1,293 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "time"
4
+
5
+ module Waffo
6
+ module Pancake
7
+ module API
8
+ # GraphQL reads, generated from the tables below. The tables follow the schema that
9
+ # introspection reports, not the documentation pages: those show a `version` field on
10
+ # products, `prices` as a scalar and `filter` on the version queries, and none of those exist.
11
+ # test/live/queries_test.rb runs every default selection against the real schema.
12
+ #
13
+ # Filters travel as GraphQL variables, so user data is never interpolated into a query.
14
+ # `fields:` is interpolated: it must come from your code, never from a request.
15
+ module Queries
16
+ PRICES = "prices { currency priceInfo { amount taxCategory } }"
17
+ SUBSCRIPTION_PRICES = "prices { currency priceInfo { amount taxCategory trialAmount } }"
18
+ MEDIA = "media { type url alt thumbnail }"
19
+ AGGREGATE_METRICS = "amount { sum avg min max }"
20
+
21
+ STORE_FIELDS = "id name status slug logo supportEmail website prodEnabled createdAt updatedAt"
22
+ ONETIME_PRODUCT_FIELDS = "id storeId name description #{PRICES} status #{MEDIA} successUrl metadata " \
23
+ "createdAt updatedAt"
24
+ SUBSCRIPTION_PRODUCT_FIELDS = "id storeId name description billingPeriod #{SUBSCRIPTION_PRICES} status " \
25
+ "#{MEDIA} successUrl metadata createdAt updatedAt"
26
+ GROUP_FIELDS = "id storeId name description rules { sharedTrial selfServicePlanChange } productIds " \
27
+ "environment createdAt updatedAt"
28
+ ORDER_FIELDS = "id storeId status testMode buyerEmail merchantProvidedBuyerIdentity orderMerchantExternalId " \
29
+ "currency metadata createdAt updatedAt"
30
+ SUBSCRIPTION_ORDER_FIELDS = "#{ORDER_FIELDS} billingPeriod isInTrial willRenew canReactivate " \
31
+ "currentPeriodStart currentPeriodEnd canceledAt"
32
+ PAYMENT_FIELDS = "id orderId status refundStatus orderMerchantExternalId periodNumber testMode " \
33
+ "invoiceToken snapshotAmountDetails { subtotal listTotal discountAmount taxAmount total " \
34
+ "currency } createdAt"
35
+ REFUND_FIELDS = "id paymentId ticketId status testMode orderMerchantExternalId " \
36
+ "refundTicketMerchantExternalId pspAmountDetails { amount currency } createdAt"
37
+ REFUND_TICKET_FIELDS = "id status refundTicketMerchantExternalId " \
38
+ "versionData { reason requestedAmount { amount currency } } reviewNote rejectReason " \
39
+ "executedAt createdAt updatedAt"
40
+ CHARGEBACK_FIELDS = "id paymentId orderId storeId status reason reasonCode amount { amount currency } " \
41
+ "testMode createdAt updatedAt"
42
+ CUSTOMER_FIELDS = "id email name country status testMode orderCount subscriptionCount " \
43
+ "activeSubscriptionCount createdAt updatedAt"
44
+ COUPON_FIELDS = "id storeId name code status redeemable discountType percentOff amountOff { amount currency } " \
45
+ "duration durationInPeriods productIds maxRedemptions redeemBy timesRedeemed " \
46
+ "promotionCodesCount createdAt updatedAt"
47
+ PROMOTION_CODE_FIELDS = "id couponId code status batchId timesRedeemed createdAt"
48
+ DISCOUNT_APPLICATION_FIELDS = "id orderId couponId promotionCodeId code sourceType entryChannel appliedVia " \
49
+ "status listAmount { amount currency } discountAmount { amount currency } createdAt"
50
+ EMAIL_DELIVERY_FIELDS = "id storeId eventType eventId recipientType toAddress subject testMode status " \
51
+ "sentAt deliveredAt bounceType errorMessage createdAt"
52
+ CANCEL_REASON_FIELDS = "id orderId storeId reasonCode reasonDetail createdAt"
53
+ MERCHANT_FIELDS = "id email name status createdAt updatedAt"
54
+ STORE_MERCHANT_FIELDS = "id storeId merchantId role memberEmail memberName createdAt updatedAt"
55
+ WEBHOOK_FIELDS = "id storeId channel url events testMode secret createdAt updatedAt"
56
+ RECIPIENT_FIELDS = "id storeId email isPrimary createdAt preferences { notifyNewOrders notifyNewSubscriptions " \
57
+ "notifySubscriptionCanceled notifySubscriptionRenewed notifySubscriptionEnded " \
58
+ "notifySubscriptionPastDue notifySubscriptionUncanceled notifySubscriptionPlanChanged " \
59
+ "notifyChargeback notifyRefundSucceeded }"
60
+ ONETIME_VERSION_FIELDS = "id productId versionNumber name description #{PRICES} #{MEDIA} successUrl metadata " \
61
+ "createdAt isTestVersion isProdVersion"
62
+ SUBSCRIPTION_VERSION_FIELDS = "id productId versionNumber name description billingPeriod " \
63
+ "#{SUBSCRIPTION_PRICES} #{MEDIA} successUrl metadata createdAt isTestVersion " \
64
+ "isProdVersion"
65
+
66
+ # scope: how the list is tied to its owner.
67
+ # :store storeId: String! (defaults to the configured store)
68
+ # :store_slug storeId or storeSlug, both optional
69
+ # :store_opt storeId: String, optional
70
+ # :coupon couponId: String!
71
+ # nil no owner argument
72
+ LISTS = {
73
+ stores: { field: "stores", type: "Store", order: true, fields: STORE_FIELDS },
74
+ merchants: { field: "merchants", type: "Merchant", order: true, single: :merchant, fields: MERCHANT_FIELDS },
75
+ store_merchants: { field: "storeMerchants", type: "StoreMerchant", single: :store_merchant,
76
+ fields: STORE_MERCHANT_FIELDS },
77
+ onetime_products: { field: "onetimeProducts", type: "OnetimeProduct", scope: :store_slug,
78
+ single: :onetime_product, fields: ONETIME_PRODUCT_FIELDS },
79
+ subscription_products: { field: "subscriptionProducts", type: "SubscriptionProduct", scope: :store_slug,
80
+ single: :subscription_product, fields: SUBSCRIPTION_PRODUCT_FIELDS },
81
+ subscription_product_groups: { field: "subscriptionProductGroups", type: "SubscriptionProductGroup",
82
+ scope: :store_slug, single: :subscription_product_group, fields: GROUP_FIELDS },
83
+ onetime_orders: { field: "onetimeOrders", type: "OnetimeOrder", scope: :store_slug, order: true,
84
+ single: :onetime_order, fields: ORDER_FIELDS },
85
+ subscription_orders: { field: "subscriptionOrders", type: "SubscriptionOrder", scope: :store_slug, order: true,
86
+ fields: SUBSCRIPTION_ORDER_FIELDS },
87
+ payments: { field: "payments", type: "Payment", scope: :store_opt, order: true, single: :payment,
88
+ fields: PAYMENT_FIELDS },
89
+ refunds: { field: "refunds", type: "Refund", order: true, single: :refund, fields: REFUND_FIELDS },
90
+ refund_tickets: { field: "refundTickets", type: "RefundTicket", order: true, single: :refund_ticket,
91
+ fields: REFUND_TICKET_FIELDS },
92
+ chargebacks: { field: "chargebacks", type: "Chargeback", order: true, single: :chargeback,
93
+ fields: CHARGEBACK_FIELDS },
94
+ customers: { field: "customers", type: "Customer", scope: :store, order: true, fields: CUSTOMER_FIELDS },
95
+ coupons: { field: "coupons", type: "Coupon", scope: :store, single: :coupon, fields: COUPON_FIELDS },
96
+ promotion_codes: { field: "promotionCodes", type: "PromotionCode", scope: :coupon,
97
+ fields: PROMOTION_CODE_FIELDS },
98
+ discount_applications: { field: "discountApplications", type: "DiscountApplication", scope: :store,
99
+ fields: DISCOUNT_APPLICATION_FIELDS },
100
+ email_deliveries: { field: "emailDeliveries", type: "EmailDelivery", scope: :store, order: true,
101
+ fields: EMAIL_DELIVERY_FIELDS },
102
+ subscription_cancel_reasons: { field: "subscriptionCancelReasons", type: "SubscriptionCancelReason",
103
+ scope: :store, order: true, fields: CANCEL_REASON_FIELDS },
104
+ store_webhooks: { field: "storeWebhooks", type: "StoreWebhook", scope: :store, fields: WEBHOOK_FIELDS }
105
+ }.freeze
106
+
107
+ # method => [GraphQL field, type prefix, reports an amount]. Delivery and reason aggregates only count.
108
+ AGGREGATES = {
109
+ payments_aggregate: ["paymentsAggregate", "Payment", true],
110
+ refunds_aggregate: ["refundsAggregate", "Refund", true],
111
+ onetime_orders_aggregate: ["onetimeOrdersAggregate", "OnetimeOrder", true],
112
+ subscription_orders_aggregate: ["subscriptionOrdersAggregate", "SubscriptionOrder", true],
113
+ payout_tickets_aggregate: ["payoutTicketsAggregate", "PayoutTicket", true],
114
+ settlement_batches_aggregate: ["settlementBatchesAggregate", "SettlementBatch", true],
115
+ webhook_deliveries_aggregate: ["webhookDeliveriesAggregate", "WebhookDelivery", false],
116
+ email_deliveries_aggregate: ["emailDeliveriesAggregate", "EmailDelivery", false],
117
+ subscription_cancel_reasons_aggregate: ["subscriptionCancelReasonsAggregate", "SubscriptionCancelReason", false]
118
+ }.freeze
119
+
120
+ ANALYTICS = {
121
+ order_statistics: "orderStatistics",
122
+ payment_statistics: "paymentStatistics",
123
+ product_statistics: "productStatistics",
124
+ trend_analysis: "trendAnalysis",
125
+ distribution_analysis: "distributionAnalysis",
126
+ customer_analysis: "customerAnalysis",
127
+ tax_analysis: "taxAnalysis",
128
+ subscription_analysis: "subscriptionAnalysis",
129
+ refund_ticket_analysis: "refundTicketAnalysis",
130
+ settlement_analysis: "settlementAnalysis",
131
+ delivery_analysis: "deliveryAnalysis"
132
+ }.freeze
133
+
134
+ OWNER_KEYS = { store: [:store_id], store_slug: %i[store_id store_slug], store_opt: [:store_id],
135
+ coupon: [:coupon_id], nil => [] }.freeze
136
+
137
+ # What a stand-in such as TestHelpers::FakeClient should answer, by method name.
138
+ def self.empty_answers
139
+ @empty_answers ||= begin
140
+ answers = {}
141
+ LISTS.each do |name, spec|
142
+ answers[name] = []
143
+ answers[:"#{name}_count"] = 0
144
+ answers[spec[:single]] = nil if spec[:single]
145
+ end
146
+ answers[:onetime_product_versions] = []
147
+ answers[:subscription_product_versions] = []
148
+ answers[:notification_recipients] = []
149
+ answers[:notification_recipients_count] = 0
150
+ answers[:store] = answers[:me] = answers[:payout_analysis] = nil
151
+ AGGREGATES.each_key { |name| answers[name] = nil }
152
+ ANALYTICS.each_key { |name| answers[name] = nil }
153
+ answers.freeze
154
+ end
155
+ end
156
+
157
+ LISTS.each do |name, spec|
158
+ define_method(name) do |filter: nil, order_by: nil, limit: nil, offset: nil, fields: spec[:fields], **owner|
159
+ arguments = owner_arguments(spec[:scope], owner, name)
160
+ arguments[:limit] = ["Int", limit && Integer(limit)]
161
+ arguments[:offset] = ["Int", offset && Integer(offset)]
162
+ arguments[:filter] = ["#{spec[:type]}Filter", filter]
163
+ raise ArgumentError, "#{name} takes no order_by" if order_by && !spec[:order]
164
+
165
+ arguments[:orderBy] = ["[#{spec[:type]}OrderBy!]", order_by && Array(order_by).map(&:to_s)]
166
+ run_query(spec[:field], arguments, fields) || []
167
+ end
168
+
169
+ define_method(:"#{name}_count") do |filter: nil, **owner|
170
+ arguments = owner_arguments(spec[:scope], owner, name)
171
+ arguments[:filter] = ["#{spec[:type]}Filter", filter]
172
+ run_query("#{spec[:field]}Count", arguments, nil)
173
+ end
174
+
175
+ next unless spec[:single]
176
+
177
+ field = spec[:single].to_s.gsub(/_([a-z])/) { Regexp.last_match(1).upcase }
178
+ define_method(spec[:single]) do |id, fields: spec[:fields]|
179
+ run_query(field, { id: ["String!", id] }, fields)
180
+ end
181
+ end
182
+
183
+ AGGREGATES.each do |name, (field, type, has_amount)|
184
+ default_fields = "count #{AGGREGATE_METRICS if has_amount} " \
185
+ "groups { keys { dimension value } count #{AGGREGATE_METRICS if has_amount} } isTruncated"
186
+ define_method(name) do |filter: nil, group_by: nil, granularity: nil, fields: default_fields|
187
+ run_query(field, {
188
+ filter: ["#{type}Filter", filter],
189
+ groupBy: ["[#{type}Dimension!]", group_by && Array(group_by).map(&:to_s)],
190
+ granularity: ["TimeGranularity", granularity&.to_s]
191
+ }, fields)
192
+ end
193
+ end
194
+
195
+ ANALYTICS.each do |name, field|
196
+ define_method(name) do |fields:, start_date:, end_date:, currency: nil, status: nil, **owner|
197
+ arguments = owner_arguments(:store_slug, owner, name)
198
+ if arguments.values.all? { |_, value| value.nil? }
199
+ raise ArgumentError, "#{name} needs store_id or store_slug"
200
+ end
201
+
202
+ arguments[:filter] = ["AnalyticsFilterInput!", analytics_filter(start_date, end_date, currency, status)]
203
+ run_query(field, arguments, fields)
204
+ end
205
+ end
206
+
207
+ def payout_analysis(fields:, start_date:, end_date:, merchant_id: nil, currency: nil, status: nil)
208
+ run_query("payoutAnalysis", {
209
+ merchantId: ["String", merchant_id],
210
+ filter: ["AnalyticsFilterInput!", analytics_filter(start_date, end_date, currency, status)]
211
+ }, fields)
212
+ end
213
+
214
+ # Defaults to the configured store; pass `slug:` to find a store by slug instead.
215
+ def store(id = nil, slug: nil, fields: STORE_FIELDS)
216
+ id ||= @store_id unless slug
217
+ raise ArgumentError, "id or slug is required" if blank?(id) && blank?(slug)
218
+
219
+ run_query("store", { id: ["String", id], slug: ["String", slug] }, fields)
220
+ end
221
+
222
+ # The merchant the API key belongs to.
223
+ def me(fields: MERCHANT_FIELDS)
224
+ run_query("me", {}, fields)
225
+ end
226
+
227
+ def onetime_product_versions(product_id, fields: ONETIME_VERSION_FIELDS)
228
+ run_query("onetimeProductVersions", { productId: ["String!", product_id] }, fields) || []
229
+ end
230
+
231
+ def subscription_product_versions(product_id, fields: SUBSCRIPTION_VERSION_FIELDS)
232
+ run_query("subscriptionProductVersions", { productId: ["String!", product_id] }, fields) || []
233
+ end
234
+
235
+ def notification_recipients(store_id: @store_id, limit: nil, offset: nil, fields: RECIPIENT_FIELDS)
236
+ run_query("storeNotificationRecipients", {
237
+ storeId: ["String!", require_store_id(store_id)],
238
+ limit: ["Int", limit && Integer(limit)],
239
+ offset: ["Int", offset && Integer(offset)]
240
+ }, fields) || []
241
+ end
242
+
243
+ def notification_recipients_count(store_id: @store_id)
244
+ run_query("storeNotificationRecipientsCount", { storeId: ["String!", require_store_id(store_id)] }, nil)
245
+ end
246
+
247
+ private
248
+ def owner_arguments(scope, owner, name)
249
+ unknown = owner.keys - OWNER_KEYS.fetch(scope)
250
+ # An unknown owner would be dropped, and the query would then read every store.
251
+ raise ArgumentError, "#{name} does not take #{unknown.join(", ")}" unless unknown.empty?
252
+
253
+ store_id = owner.fetch(:store_id, @store_id)
254
+ case scope
255
+ when :store then { storeId: ["String!", require_store_id(store_id)] }
256
+ when :coupon
257
+ raise ArgumentError, "#{name} needs coupon_id" if blank?(owner[:coupon_id])
258
+
259
+ { couponId: ["String!", owner[:coupon_id]] }
260
+ when :store_opt then { storeId: ["String", store_id] }
261
+ when :store_slug
262
+ # A slug names the store on its own, so the configured store must not join it.
263
+ slug = owner[:store_slug]
264
+ { storeId: ["String", slug ? nil : store_id], storeSlug: ["String", slug] }
265
+ else {}
266
+ end
267
+ end
268
+
269
+ # `arguments` is { name: [GraphQL type, value] }; a nil value leaves the argument out.
270
+ def run_query(field, arguments, fields)
271
+ given = arguments.reject { |_, (_, value)| value.nil? }
272
+ declared = given.map { |name, (type, _)| "$#{name}: #{type}" }.join(", ")
273
+ passed = given.keys.map { |name| "#{name}: $#{name}" }.join(", ")
274
+ query = "query#{" (#{declared})" unless given.empty?} { #{field}#{"(#{passed})" unless given.empty?}" \
275
+ "#{" { #{fields} }" if fields} }"
276
+ data = graphql(query, given.transform_values(&:last))
277
+ data && data[field]
278
+ end
279
+
280
+ def analytics_filter(start_date, end_date, currency, status)
281
+ filter = { timeRange: { startDate: time_string(start_date), endDate: time_string(end_date) } }
282
+ filter[:currency] = currency if currency
283
+ filter[:status] = status if status
284
+ filter
285
+ end
286
+
287
+ def time_string(value)
288
+ value.respond_to?(:utc) ? value.dup.utc.iso8601 : value.to_s
289
+ end
290
+ end
291
+ end
292
+ end
293
+ end
@@ -0,0 +1,64 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Waffo
4
+ module Pancake
5
+ module API
6
+ # Stores, their members, webhook endpoints and notification recipients. Merchant API key.
7
+ module StoreActions
8
+ def create_store(name:, **params)
9
+ action("/v1/actions/store/create-store", name: name, **params)
10
+ end
11
+
12
+ # Omitted keeps a field, Waffo::Pancake::NULL clears it, a value sets it.
13
+ def update_store(id:, **params)
14
+ action("/v1/actions/store/update-store", id: id, **params)
15
+ end
16
+
17
+ def delete_store(id:, **params)
18
+ action("/v1/actions/store/delete-store", id: id, **params)
19
+ end
20
+
21
+ def add_store_merchant(store_id:, email:, role:, **params)
22
+ action("/v1/actions/store-merchant/add-merchant", store_id: store_id, email: email, role: role, **params)
23
+ end
24
+
25
+ def remove_store_merchant(store_id:, merchant_id:, **params)
26
+ action("/v1/actions/store-merchant/remove-merchant", store_id: store_id, merchant_id: merchant_id, **params)
27
+ end
28
+
29
+ def update_store_merchant_role(store_id:, merchant_id:, role:, **params)
30
+ action("/v1/actions/store-merchant/update-role", store_id: store_id, merchant_id: merchant_id, role: role,
31
+ **params)
32
+ end
33
+
34
+ def add_webhook(store_id:, url:, events:, test_mode:, channel: "http", **params)
35
+ action("/v1/actions/store/add-webhook", store_id: store_id, channel: channel, url: url, events: events,
36
+ test_mode: test_mode, **params)
37
+ end
38
+
39
+ # `secret: Waffo::Pancake::NULL` clears the secret.
40
+ def update_webhook(id:, **params)
41
+ action("/v1/actions/store/update-webhook", id: id, **params)
42
+ end
43
+
44
+ def remove_webhook(id:, **params)
45
+ action("/v1/actions/store/remove-webhook", id: id, **params)
46
+ end
47
+
48
+ def add_notification_recipient(store_id:, email:, **params)
49
+ action("/v1/actions/store-notification-recipient/add-recipient", store_id: store_id, email: email, **params)
50
+ end
51
+
52
+ def update_notification_recipient(store_id:, recipient_id:, preferences:, **params)
53
+ action("/v1/actions/store-notification-recipient/update-recipient",
54
+ store_id: store_id, recipient_id: recipient_id, preferences: preferences, **params)
55
+ end
56
+
57
+ def remove_notification_recipient(store_id:, recipient_id:, **params)
58
+ action("/v1/actions/store-notification-recipient/remove-recipient",
59
+ store_id: store_id, recipient_id: recipient_id, **params)
60
+ end
61
+ end
62
+ end
63
+ end
64
+ end