glacier-web 0.4.1

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
//! Taking payments with Stripe: customers, Checkout for one-off payments
//! and subscriptions, and keeping the app's copy of charges and
//! subscriptions in step with Stripe, from the return URL and from
//! webhooks alike ("sync from the source": both fetch the object from
//! Stripe and upsert it, so repeats and reordering do no harm).
//!
//! Records live in Glacier's tables, `billing_customers`,
//! `billing_subscriptions` and `billing_charges`, from a migration that
//! calls `glacier::billing::create_tables(s)`. An app coming from the pay
//! gem can copy pay's rows across once (`copy_from_pay`), or keep using
//! pay's tables in place (`Billing::pay_tables`), as when it shares its
//! database with the Rails app.
//!
//! ```ignore
//! App::new().billing(
//!     Billing::stripe(&secret_key)
//!         .on_charge(|synced: Synced<Charge>| async move { /* grant access */ Ok(()) }),
//! )
//!
//! // In an action: send the buyer to Stripe Checkout…
//! let customer = billing::customer("User", user.id, &user.email).await?;
//! let session = billing::checkout(&customer, Checkout::payment("price_123", &success, &cancel)).await?;
//! redirect(session.url)
//! // …and on the success URL (`?session_id={CHECKOUT_SESSION_ID}`):
//! billing::sync_checkout(&session_id).await?;
//! ```
//!
//! In development and tests, `Billing::fake()` stands in for Stripe:
//! checkout goes straight to the success URL, as though paid.

mod fake;
mod stripe;

use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, RwLock};

use serde_json::{Value as Json, json};

pub use self::fake::Fake;
pub use self::stripe::Stripe;
use crate::db::migration::Schema;
use crate::db::{self, Sql, Timestamp, Value};
use crate::error::{Error, Result};

/// Glacier's billing tables, for a migration's `up`.
pub fn create_tables(s: &mut Schema) {
    s.create_table("billing_customers", |t| {
        t.string("owner_type");
        t.bigint("owner_id");
        t.string("processor").not_null();
        t.string("processor_id");
        t.timestamp("deleted_at");
        t.timestamps();
    });
    s.add_unique_index("billing_customers", &["processor", "processor_id"]);
    s.add_index("billing_customers", &["owner_type", "owner_id"]);
    s.create_table("billing_subscriptions", |t| {
        t.bigint("customer_id").not_null();
        t.string("name").not_null();
        t.string("processor_id").not_null();
        t.string("price").not_null();
        t.integer("quantity").not_null().default(1);
        t.string("status").not_null();
        t.timestamp("current_period_start");
        t.timestamp("current_period_end");
        t.timestamp("trial_ends_at");
        t.timestamp("ends_at");
        t.json("metadata");
        t.json("data");
        t.timestamps();
    });
    s.add_unique_index("billing_subscriptions", &["customer_id", "processor_id"]);
    s.create_table("billing_charges", |t| {
        t.bigint("customer_id").not_null();
        t.bigint("subscription_id");
        t.string("processor_id").not_null();
        t.bigint("amount").not_null();
        t.string("currency");
        t.bigint("amount_refunded");
        t.json("metadata");
        t.json("data");
        t.timestamps();
    });
    s.add_unique_index("billing_charges", &["customer_id", "processor_id"]);
    s.add_index("billing_charges", &["subscription_id"]);
}

/// The pay gem's tables, as its migrations make them: for tests of an app
/// that uses them in place ([`Billing::pay_tables`]). In a Rails app's
/// database, its own migrations made them already.
pub fn create_pay_tables(s: &mut Schema) {
    s.create_table("pay_customers", |t| {
        t.string("owner_type");
        t.bigint("owner_id");
        t.string("processor").not_null();
        t.string("processor_id");
        t.boolean("default");
        t.json("data");
        t.string("stripe_account");
        t.timestamp("deleted_at");
        t.timestamp("created_at").not_null();
        t.timestamp("updated_at").not_null();
        t.string("type");
        t.json("object");
    });
    s.add_unique_index("pay_customers", &["processor", "processor_id"]);
    s.add_unique_index("pay_customers", &["owner_type", "owner_id", "deleted_at"]);
    s.create_table("pay_subscriptions", |t| {
        t.bigint("customer_id").not_null();
        t.string("name").not_null();
        t.string("processor_id").not_null();
        t.string("processor_plan").not_null();
        t.integer("quantity").not_null().default(1);
        t.string("status").not_null();
        t.timestamp("current_period_start");
        t.timestamp("current_period_end");
        t.timestamp("trial_ends_at");
        t.timestamp("ends_at");
        t.boolean("metered");
        t.string("pause_behavior");
        t.timestamp("pause_starts_at");
        t.timestamp("pause_resumes_at");
        t.json("metadata");
        t.json("data");
        t.string("stripe_account");
        t.string("payment_method_id");
        t.timestamp("created_at").not_null();
        t.timestamp("updated_at").not_null();
        t.string("type");
        t.json("object");
    });
    s.add_unique_index("pay_subscriptions", &["customer_id", "processor_id"]);
    s.create_table("pay_charges", |t| {
        t.bigint("customer_id").not_null();
        t.bigint("subscription_id");
        t.string("processor_id").not_null();
        t.integer("amount").not_null();
        t.string("currency");
        t.integer("application_fee_amount");
        t.integer("amount_refunded");
        t.json("metadata");
        t.json("data");
        t.string("stripe_account");
        t.timestamp("created_at").not_null();
        t.timestamp("updated_at").not_null();
        t.string("type");
        t.json("object");
    });
    s.add_unique_index("pay_charges", &["customer_id", "processor_id"]);
}

/// Copies the pay gem's rows into Glacier's tables, for a migration's `up`
/// after `create_tables`, when moving off pay. Ids are kept, so the app's
/// own references (`licenses.pay_charge_id`) stay right, and on Postgres
/// the id sequences move past them. pay's tables are left as they are, to
/// drop once nothing reads them.
pub fn copy_from_pay(s: &mut Schema) {
    s.execute(
        "INSERT INTO billing_customers (id, owner_type, owner_id, processor, processor_id, deleted_at, \
         inserted_at, updated_at) \
         SELECT id, owner_type, owner_id, processor, processor_id, deleted_at, created_at, updated_at \
         FROM pay_customers",
    );
    s.execute(
        "INSERT INTO billing_subscriptions (id, customer_id, name, processor_id, price, quantity, status, \
         current_period_start, current_period_end, trial_ends_at, ends_at, metadata, data, inserted_at, updated_at) \
         SELECT id, customer_id, name, processor_id, processor_plan, quantity, status, current_period_start, \
         current_period_end, trial_ends_at, ends_at, metadata, COALESCE(object, data), created_at, updated_at \
         FROM pay_subscriptions",
    );
    s.execute(
        "INSERT INTO billing_charges (id, customer_id, subscription_id, processor_id, amount, currency, \
         amount_refunded, metadata, data, inserted_at, updated_at) \
         SELECT id, customer_id, subscription_id, processor_id, amount, currency, amount_refunded, metadata, \
         COALESCE(object, data), created_at, updated_at FROM pay_charges",
    );
    if s.dialect() == crate::db::Dialect::Postgres {
        for table in [
            "billing_customers",
            "billing_subscriptions",
            "billing_charges",
        ] {
            s.execute(&format!(
                "SELECT setval(pg_get_serial_sequence('{table}', 'id'), \
                 COALESCE((SELECT MAX(id) FROM {table}), 0) + 1, false)"
            ));
        }
    }
}

/// Which tables records live in, and the columns whose names differ.
#[derive(Clone, Copy, Debug)]
struct Tables {
    customers: &'static str,
    subscriptions: &'static str,
    charges: &'static str,
    /// When a row was made.
    inserted_at: &'static str,
    /// A subscription's price.
    price: &'static str,
    /// The processor's object, as JSON.
    data: &'static str,
}

const GLACIER_TABLES: Tables = Tables {
    customers: "billing_customers",
    subscriptions: "billing_subscriptions",
    charges: "billing_charges",
    inserted_at: "inserted_at",
    price: "price",
    data: "data",
};

const PAY_TABLES: Tables = Tables {
    customers: "pay_customers",
    subscriptions: "pay_subscriptions",
    charges: "pay_charges",
    inserted_at: "created_at",
    price: "processor_plan",
    data: "object",
};

/// A customer: an app record (`owner_type`, `owner_id`) and its id at the
/// processor.
#[derive(Debug, Clone, PartialEq)]
pub struct Customer {
    pub id: i64,
    pub owner_type: String,
    pub owner_id: i64,
    pub processor_id: String,
}

/// A one-off payment.
#[derive(Debug, Clone, PartialEq)]
pub struct Charge {
    pub id: i64,
    pub customer_id: i64,
    pub subscription_id: Option<i64>,
    pub processor_id: String,
    /// In the currency's smallest unit (pence, cents).
    pub amount: i64,
    pub currency: String,
    pub amount_refunded: i64,
    /// What the checkout was given: `{"user_id": "1", "product_id": "2"}`.
    pub metadata: Json,
}

/// A subscription and its state at the processor.
#[derive(Debug, Clone, PartialEq)]
pub struct Subscription {
    pub id: i64,
    pub customer_id: i64,
    pub processor_id: String,
    /// The price it's for (`price_…`).
    pub price: String,
    pub quantity: i64,
    /// Stripe's: `active`, `trialing`, `past_due`, `canceled`, …
    pub status: String,
    pub current_period_end: Option<Timestamp>,
    pub ends_at: Option<Timestamp>,
    pub metadata: Json,
}

impl Subscription {
    /// Whether it gives access now: active, trialing, or cancelled but
    /// paid up to `ends_at`.
    pub fn is_active(&self) -> bool {
        matches!(self.status.as_str(), "active" | "trialing")
            || self.ends_at.is_some_and(|at| at > crate::time::now())
    }
}

/// A record just synced, with whether it's new and what it was before.
#[derive(Debug, Clone)]
pub struct Synced<T> {
    pub record: T,
    /// First seen now (its row was just inserted).
    pub created: bool,
    /// The status before this sync (subscriptions), if it existed.
    pub previous_status: Option<String>,
}

/// What a checkout sells.
#[derive(Debug, Clone)]
pub struct Checkout {
    /// `payment` (one-off) or `subscription`.
    pub mode: &'static str,
    pub price: String,
    pub quantity: u32,
    /// Where Stripe sends the buyer after paying; `{CHECKOUT_SESSION_ID}`
    /// in it is replaced with the session's id (added as `?session_id=`
    /// when it's missing).
    pub success_url: String,
    pub cancel_url: String,
    /// Kept on the charge or subscription it makes, for the app's hooks.
    pub metadata: Vec<(String, String)>,
    pub allow_promotion_codes: bool,
}

impl Checkout {
    /// A one-off payment for `price`.
    pub fn payment(price: &str, success_url: &str, cancel_url: &str) -> Self {
        Self {
            mode: "payment",
            price: price.to_owned(),
            quantity: 1,
            success_url: success_url.to_owned(),
            cancel_url: cancel_url.to_owned(),
            metadata: Vec::new(),
            allow_promotion_codes: false,
        }
    }

    /// A subscription to `price`.
    pub fn subscription(price: &str, success_url: &str, cancel_url: &str) -> Self {
        Self {
            mode: "subscription",
            ..Self::payment(price, success_url, cancel_url)
        }
    }

    #[must_use]
    pub fn metadata(mut self, key: &str, value: impl ToString) -> Self {
        self.metadata.push((key.to_owned(), value.to_string()));
        self
    }

    #[must_use]
    pub fn allow_promotion_codes(mut self) -> Self {
        self.allow_promotion_codes = true;
        self
    }

    fn success_url_with_id(&self) -> String {
        if self.success_url.contains("{CHECKOUT_SESSION_ID}") {
            self.success_url.clone()
        } else {
            let joiner = if self.success_url.contains('?') {
                '&'
            } else {
                '?'
            };
            format!(
                "{}{joiner}session_id={{CHECKOUT_SESSION_ID}}",
                self.success_url
            )
        }
    }
}

/// A checkout session: where to send the buyer.
#[derive(Debug, Clone)]
pub struct CheckoutSession {
    pub id: String,
    pub url: String,
}

type Pending<'a, T> = Pin<Box<dyn Future<Output = Result<T>> + Send + 'a>>;

/// Where payments happen: Stripe, or a fake for development and tests.
/// Objects come back in Stripe's JSON shapes.
pub trait Processor: Send + Sync + 'static {
    /// `stripe` (also the fake's, so its rows look like Stripe's).
    fn name(&self) -> &'static str {
        "stripe"
    }
    fn create_customer<'a>(&'a self, email: &'a str) -> Pending<'a, String>;
    fn create_checkout<'a>(
        &'a self,
        customer: &'a str,
        checkout: &'a Checkout,
    ) -> Pending<'a, CheckoutSession>;
    /// The checkout session, with its `subscription` and its payment
    /// intent's `latest_charge` expanded.
    fn checkout_session<'a>(&'a self, id: &'a str) -> Pending<'a, Json>;
    fn subscription<'a>(&'a self, id: &'a str) -> Pending<'a, Json>;
    fn charge<'a>(&'a self, id: &'a str) -> Pending<'a, Json>;
}

type Hook<T> =
    Arc<dyn Fn(Synced<T>) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> + Send + Sync>;

/// The app's billing: a processor and what to do as records sync.
#[derive(Clone)]
pub struct Billing {
    processor: Arc<dyn Processor>,
    tables: Tables,
    on_charge: Option<Hook<Charge>>,
    on_subscription: Option<Hook<Subscription>>,
}

impl Billing {
    /// Stripe, with a secret key (`sk_live_…` or `sk_test_…`).
    pub fn stripe(secret_key: &str) -> Self {
        Self::with(Stripe::new(secret_key))
    }

    /// A stand-in for development and tests: checkouts succeed at once.
    pub fn fake() -> Self {
        Self::with(Fake::default())
    }

    /// Payments turned off: every checkout and sync fails with "Payments
    /// are not enabled." (`422`), and [`enabled`] is `false`.
    pub fn off() -> Self {
        Self::with(Off)
    }

    /// What an app has without a Stripe key: the fake, unless its config
    /// says `[billing] fake = false`, which turns payments off.
    ///
    /// # Errors
    ///
    /// When `billing.fake` isn't a boolean.
    pub fn without_key(config: &crate::Config) -> Result<Self> {
        let fake: Option<bool> = config.get_opt("billing.fake")?;
        Ok(if fake.unwrap_or(true) {
            Self::fake()
        } else {
            Self::off()
        })
    }

    /// Whether payments can be taken: not [`Billing::off`].
    pub fn is_enabled(&self) -> bool {
        self.processor.name() != "off"
    }

    pub fn with(processor: impl Processor) -> Self {
        Self {
            processor: Arc::new(processor),
            tables: GLACIER_TABLES,
            on_charge: None,
            on_subscription: None,
        }
    }

    /// Keeps records in the pay gem's tables (`pay_customers`,
    /// `pay_subscriptions`, `pay_charges`) instead of Glacier's: for an
    /// app that shares its database with a Rails app on pay. To move off
    /// pay instead, see [`copy_from_pay`].
    #[must_use]
    pub fn pay_tables(mut self) -> Self {
        self.tables = PAY_TABLES;
        self
    }

    /// Runs after each charge is synced (new, or refunded since): where an
    /// app grants what was bought. Runs in the sync's transaction.
    #[must_use]
    pub fn on_charge<F, Fut>(mut self, hook: F) -> Self
    where
        F: Fn(Synced<Charge>) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<()>> + Send + 'static,
    {
        self.on_charge = Some(Arc::new(move |synced| Box::pin(hook(synced))));
        self
    }

    /// Runs after each subscription is synced (new, or changed status).
    #[must_use]
    pub fn on_subscription<F, Fut>(mut self, hook: F) -> Self
    where
        F: Fn(Synced<Subscription>) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<()>> + Send + 'static,
    {
        self.on_subscription = Some(Arc::new(move |synced| Box::pin(hook(synced))));
        self
    }

    /// The webhook provider for Stripe's events, verified with its signing
    /// secrets, each handled by syncing the object from Stripe.
    pub fn stripe_webhooks(&self, signing_secrets: &[&str]) -> crate::webhooks::Provider {
        let sync = |kind: &'static str| {
            move |event: crate::webhooks::Event| async move {
                let id = event.payload()["data"]["object"]["id"]
                    .as_str()
                    .unwrap_or_default()
                    .to_owned();
                match kind {
                    "checkout" => sync_checkout(&id).await.map(|_| ()),
                    "subscription" => sync_subscription(&id).await.map(|_| ()),
                    _ => sync_charge(&id).await.map(|_| ()),
                }
            }
        };
        crate::webhooks::Stripe::new(signing_secrets)
            .on("checkout.session.completed", sync("checkout"))
            .on("customer.subscription.created", sync("subscription"))
            .on("customer.subscription.updated", sync("subscription"))
            .on("customer.subscription.deleted", sync("subscription"))
            .on("charge.succeeded", sync("charge"))
            .on("charge.refunded", sync("charge"))
    }
}

static INSTALLED: RwLock<Option<Billing>> = RwLock::new(None);

tokio::task_local! {
    /// A test's own billing, from `#[glacier::test]`: parallel tests that
    /// each build an app don't swap each other's.
    static TEST_SLOT: Arc<RwLock<Option<Billing>>>;
}

/// Runs `fut` with a billing slot of its own. `#[glacier::test]` does this.
#[doc(hidden)]
pub async fn with_test_slot<F: Future>(fut: F) -> F::Output {
    TEST_SLOT.scope(Arc::default(), fut).await
}

/// Makes `billing` the app's (in a test, the test's). `App::billing`
/// calls it.
pub(crate) fn install(billing: Billing) {
    let in_test = TEST_SLOT
        .try_with(|slot| *slot.write().unwrap_or_else(|e| e.into_inner()) = Some(billing.clone()))
        .is_ok();
    if !in_test {
        *INSTALLED.write().unwrap_or_else(|e| e.into_inner()) = Some(billing);
    }
}

/// Whether the app takes payments: it has a `Billing` that isn't
/// [`Billing::off`]. For a page that offers a checkout only when it can.
pub fn enabled() -> bool {
    installed().is_ok_and(|billing| billing.is_enabled())
}

/// See [`Billing::off`].
struct Off;

impl Off {
    fn refuse<'a, T: Send + 'a>() -> Pending<'a, T> {
        Box::pin(async {
            Err(Error::new(
                http::StatusCode::UNPROCESSABLE_ENTITY,
                "Payments are not enabled.",
            ))
        })
    }
}

impl Processor for Off {
    fn name(&self) -> &'static str {
        "off"
    }
    fn create_customer<'a>(&'a self, _: &'a str) -> Pending<'a, String> {
        Self::refuse()
    }
    fn create_checkout<'a>(&'a self, _: &'a str, _: &'a Checkout) -> Pending<'a, CheckoutSession> {
        Self::refuse()
    }
    fn checkout_session<'a>(&'a self, _: &'a str) -> Pending<'a, Json> {
        Self::refuse()
    }
    fn subscription<'a>(&'a self, _: &'a str) -> Pending<'a, Json> {
        Self::refuse()
    }
    fn charge<'a>(&'a self, _: &'a str) -> Pending<'a, Json> {
        Self::refuse()
    }
}

fn installed() -> Result<Billing> {
    TEST_SLOT
        .try_with(|slot| slot.read().unwrap_or_else(|e| e.into_inner()).clone())
        .ok()
        .flatten()
        .or_else(|| INSTALLED.read().unwrap_or_else(|e| e.into_inner()).clone())
        .ok_or_else(|| Error::internal("billing isn't set up: pass a Billing to App::billing"))
}

/// The customer for an app record, made (here and at the processor) the
/// first time.
///
/// # Errors
///
/// When the processor or the database fails.
pub async fn customer(owner_type: &str, owner_id: i64, email: &str) -> Result<Customer> {
    let billing = installed()?;
    let processor = billing.processor.name();
    let mut sql = Sql::new();
    let tables = billing.tables;
    sql.push(&format!(
        "SELECT id, processor_id FROM {} WHERE owner_type = ",
        tables.customers
    ));
    sql.push_value(Value::Text(owner_type.to_owned()));
    sql.push(" AND owner_id = ");
    sql.push_value(Value::Int(owner_id));
    sql.push(" AND processor = ");
    sql.push_value(Value::Text(processor.to_owned()));
    sql.push(" AND deleted_at IS NULL");
    let rows = db::current()?.fetch_all(&sql).await?;
    if let Some(row) = rows.first()
        && let Some(processor_id) = row.get::<Option<String>>("processor_id")?
    {
        return Ok(Customer {
            id: id_of(row, "id")?,
            owner_type: owner_type.to_owned(),
            owner_id,
            processor_id,
        });
    }
    let processor_id = billing.processor.create_customer(email).await?;
    let now = crate::time::now();
    let mut sql = Sql::new();
    sql.push(&format!(
        "INSERT INTO {} (owner_type, owner_id, processor, processor_id, {}, updated_at) VALUES (",
        tables.customers, tables.inserted_at
    ));
    push_values(
        &mut sql,
        vec![
            Value::Text(owner_type.to_owned()),
            Value::Int(owner_id),
            Value::Text(processor.to_owned()),
            Value::Text(processor_id.clone()),
            Value::Timestamp(now),
            Value::Timestamp(now),
        ],
    );
    sql.push(") RETURNING id");
    let rows = db::current()?.fetch_all(&sql).await?;
    Ok(Customer {
        id: id_of(
            rows.first()
                .ok_or_else(|| Error::internal("no customer id"))?,
            "id",
        )?,
        owner_type: owner_type.to_owned(),
        owner_id,
        processor_id,
    })
}

/// Starts a checkout for `customer`: redirect the buyer to its `url`.
///
/// # Errors
///
/// When the processor refuses it.
pub async fn checkout(customer: &Customer, checkout: Checkout) -> Result<CheckoutSession> {
    installed()?
        .processor
        .create_checkout(&customer.processor_id, &checkout)
        .await
}

/// What a completed checkout made.
#[derive(Debug, Clone)]
pub enum Purchase {
    Charge(Synced<Charge>),
    Subscription(Synced<Subscription>),
    /// Not paid (yet), or free: the session as the processor gave it, for
    /// its `status`, `amount_total` and `metadata`.
    Nothing(Json),
}

/// Syncs what checkout session `id` made, from the processor: for the
/// success URL, and the `checkout.session.completed` webhook.
///
/// # Errors
///
/// When the processor or the database fails.
pub async fn sync_checkout(id: &str) -> Result<Purchase> {
    let billing = installed()?;
    let session = billing.processor.checkout_session(id).await?;
    if session["status"] != "complete" {
        return Ok(Purchase::Nothing(session));
    }
    if session["subscription"].is_object() {
        return Ok(Purchase::Subscription(
            sync_subscription_object(&billing, &session["subscription"]).await?,
        ));
    }
    let charge = &session["payment_intent"]["latest_charge"];
    if charge.is_object() {
        return Ok(Purchase::Charge(
            sync_charge_object(&billing, charge).await?,
        ));
    }
    Ok(Purchase::Nothing(session))
}

/// Syncs subscription `id` from the processor.
///
/// # Errors
///
/// When the processor or the database fails.
pub async fn sync_subscription(id: &str) -> Result<Synced<Subscription>> {
    let billing = installed()?;
    let object = billing.processor.subscription(id).await?;
    sync_subscription_object(&billing, &object).await
}

/// Syncs charge `id` from the processor.
///
/// # Errors
///
/// When the processor or the database fails.
pub async fn sync_charge(id: &str) -> Result<Synced<Charge>> {
    let billing = installed()?;
    let object = billing.processor.charge(id).await?;
    sync_charge_object(&billing, &object).await
}

/// The customer row for a processor's customer id, made if it's new to
/// the app (a customer created in Stripe's dashboard).
async fn customer_id_for(billing: &Billing, processor_id: &str) -> Result<i64> {
    let mut sql = Sql::new();
    let tables = billing.tables;
    sql.push(&format!(
        "SELECT id FROM {} WHERE processor = ",
        tables.customers
    ));
    sql.push_value(Value::Text(billing.processor.name().to_owned()));
    sql.push(" AND processor_id = ");
    sql.push_value(Value::Text(processor_id.to_owned()));
    let rows = db::current()?.fetch_all(&sql).await?;
    if let Some(row) = rows.first() {
        return id_of(row, "id");
    }
    let now = crate::time::now();
    let mut sql = Sql::new();
    sql.push(&format!(
        "INSERT INTO {} (processor, processor_id, {}, updated_at) VALUES (",
        tables.customers, tables.inserted_at
    ));
    push_values(
        &mut sql,
        vec![
            Value::Text(billing.processor.name().to_owned()),
            Value::Text(processor_id.to_owned()),
            Value::Timestamp(now),
            Value::Timestamp(now),
        ],
    );
    sql.push(") RETURNING id");
    let rows = db::current()?.fetch_all(&sql).await?;
    id_of(
        rows.first()
            .ok_or_else(|| Error::internal("no customer id"))?,
        "id",
    )
}

fn time(value: &Json) -> Value {
    value
        .as_i64()
        .and_then(|seconds| chrono::DateTime::from_timestamp(seconds, 0))
        .map_or(Value::Null, Value::Timestamp)
}

async fn sync_subscription_object(
    billing: &Billing,
    object: &Json,
) -> Result<Synced<Subscription>> {
    let customer = object["customer"]
        .as_str()
        .or_else(|| object["customer"]["id"].as_str())
        .unwrap_or_default();
    let customer_id = customer_id_for(billing, customer).await?;
    let processor_id = object["id"].as_str().unwrap_or_default().to_owned();
    let item = &object["items"]["data"][0];
    let price = item["price"]["id"]
        .as_str()
        .or_else(|| object["plan"]["id"].as_str())
        .unwrap_or_default()
        .to_owned();
    let quantity = item["quantity"]
        .as_i64()
        .or_else(|| object["quantity"].as_i64())
        .unwrap_or(1);
    let status = object["status"].as_str().unwrap_or("incomplete").to_owned();
    // Newer API versions keep the period on the item.
    let period_end = if object["current_period_end"].is_null() {
        &item["current_period_end"]
    } else {
        &object["current_period_end"]
    };
    let period_start = if object["current_period_start"].is_null() {
        &item["current_period_start"]
    } else {
        &object["current_period_start"]
    };
    let ends_at = if object["cancel_at_period_end"] == true {
        period_end.clone()
    } else {
        object["ended_at"].clone()
    };
    db::transaction(async {
        let tables = billing.tables;
        let previous = previous_status(tables, customer_id, &processor_id).await?;
        let now = crate::time::now();
        let mut sql = Sql::new();
        sql.push(&format!(
            "INSERT INTO {} (customer_id, name, processor_id, {price}, quantity, status, \
             current_period_start, current_period_end, trial_ends_at, ends_at, metadata, {data}, {}, updated_at) VALUES (",
            tables.subscriptions,
            tables.inserted_at,
            price = tables.price,
            data = tables.data,
        ));
        push_values(
            &mut sql,
            vec![
                Value::Int(customer_id),
                Value::Text("default".to_owned()),
                Value::Text(processor_id.clone()),
                Value::Text(price.clone()),
                Value::Int(quantity),
                Value::Text(status.clone()),
                time(period_start),
                time(period_end),
                time(&object["trial_end"]),
                time(&ends_at),
                Value::Json(object["metadata"].clone()),
                Value::Json(object.clone()),
                Value::Timestamp(now),
                Value::Timestamp(now),
            ],
        );
        sql.push(&format!(
            ") ON CONFLICT (customer_id, processor_id) DO UPDATE SET {price} = excluded.{price}, \
             quantity = excluded.quantity, status = excluded.status, current_period_start = excluded.current_period_start, \
             current_period_end = excluded.current_period_end, trial_ends_at = excluded.trial_ends_at, \
             ends_at = excluded.ends_at, metadata = excluded.metadata, {data} = excluded.{data}, \
             updated_at = excluded.updated_at RETURNING id",
            price = tables.price,
            data = tables.data,
        ));
        let rows = db::current()?.fetch_all(&sql).await?;
        let id = id_of(rows.first().ok_or_else(|| Error::internal("no subscription id"))?, "id")?;
        let synced = Synced {
            record: Subscription {
                id,
                customer_id,
                processor_id: processor_id.clone(),
                price: price.clone(),
                quantity,
                status: status.clone(),
                current_period_end: timestamp(period_end),
                ends_at: timestamp(&ends_at),
                metadata: object["metadata"].clone(),
            },
            created: previous.is_none(),
            previous_status: previous.clone(),
        };
        if previous.as_deref() != Some(status.as_str())
            && let Some(hook) = &billing.on_subscription
        {
            hook(synced.clone()).await?;
        }
        Ok(synced)
    })
    .await
}

fn timestamp(value: &Json) -> Option<Timestamp> {
    value
        .as_i64()
        .and_then(|seconds| chrono::DateTime::from_timestamp(seconds, 0))
}

async fn previous_status(
    tables: Tables,
    customer_id: i64,
    processor_id: &str,
) -> Result<Option<String>> {
    let mut sql = Sql::new();
    sql.push(&format!(
        "SELECT status FROM {} WHERE customer_id = ",
        tables.subscriptions
    ));
    sql.push_value(Value::Int(customer_id));
    sql.push(" AND processor_id = ");
    sql.push_value(Value::Text(processor_id.to_owned()));
    let rows = db::current()?.fetch_all(&sql).await?;
    rows.first()
        .map(|row| row.get::<String>("status"))
        .transpose()
}

async fn sync_charge_object(billing: &Billing, object: &Json) -> Result<Synced<Charge>> {
    let customer = object["customer"]
        .as_str()
        .or_else(|| object["customer"]["id"].as_str())
        .unwrap_or_default();
    let customer_id = customer_id_for(billing, customer).await?;
    let processor_id = object["id"].as_str().unwrap_or_default().to_owned();
    let amount = object["amount"].as_i64().unwrap_or_default();
    let refunded = object["amount_refunded"].as_i64().unwrap_or_default();
    let currency = object["currency"].as_str().unwrap_or("usd").to_owned();
    db::transaction(async {
        let mut sql = Sql::new();
        let tables = billing.tables;
        sql.push(&format!(
            "SELECT amount_refunded FROM {} WHERE customer_id = ",
            tables.charges
        ));
        sql.push_value(Value::Int(customer_id));
        sql.push(" AND processor_id = ");
        sql.push_value(Value::Text(processor_id.clone()));
        let existing = db::current()?.fetch_all(&sql).await?;
        let before: Option<i64> = match existing.first() {
            Some(row) => Some(row.get::<Option<i64>>("amount_refunded").or_else(|_| {
                row.get::<Option<i32>>("amount_refunded").map(|n| n.map(i64::from))
            })?.unwrap_or_default()),
            None => None,
        };
        let now = crate::time::now();
        let mut sql = Sql::new();
        sql.push(&format!(
            "INSERT INTO {} (customer_id, processor_id, amount, currency, amount_refunded, metadata, {}, \
             {}, updated_at) VALUES (",
            tables.charges, tables.data, tables.inserted_at
        ));
        push_values(
            &mut sql,
            vec![
                Value::Int(customer_id),
                Value::Text(processor_id.clone()),
                Value::Int(amount),
                Value::Text(currency.clone()),
                Value::Int(refunded),
                Value::Json(object["metadata"].clone()),
                Value::Json(object.clone()),
                Value::Timestamp(now),
                Value::Timestamp(now),
            ],
        );
        sql.push(&format!(
            ") ON CONFLICT (customer_id, processor_id) DO UPDATE SET amount_refunded = excluded.amount_refunded, \
             metadata = excluded.metadata, {data} = excluded.{data}, updated_at = excluded.updated_at RETURNING id",
            data = tables.data,
        ));
        let rows = db::current()?.fetch_all(&sql).await?;
        let id = id_of(rows.first().ok_or_else(|| Error::internal("no charge id"))?, "id")?;
        let synced = Synced {
            record: Charge {
                id,
                customer_id,
                subscription_id: None,
                processor_id: processor_id.clone(),
                amount,
                currency: currency.clone(),
                amount_refunded: refunded,
                metadata: object["metadata"].clone(),
            },
            created: before.is_none(),
            previous_status: None,
        };
        if before != Some(refunded)
            && let Some(hook) = &billing.on_charge
        {
            hook(synced.clone()).await?;
        }
        Ok(synced)
    })
    .await
}

fn push_values(sql: &mut Sql, values: Vec<Value>) {
    for (i, value) in values.into_iter().enumerate() {
        if i > 0 {
            sql.push(", ");
        }
        sql.push_value(value);
    }
}

fn id_of(row: &db::Row, column: &str) -> Result<i64> {
    row.get::<i64>(column)
        .or_else(|_| row.get::<i32>(column).map(i64::from))
}

/// Stripe's form encoding of nested parameters:
/// `line_items[0][price]=price_1&metadata[user_id]=7`.
pub(crate) fn form_pairs(value: &Json, prefix: &str, out: &mut Vec<(String, String)>) {
    match value {
        Json::Object(map) => {
            for (key, value) in map {
                let name = if prefix.is_empty() {
                    key.clone()
                } else {
                    format!("{prefix}[{key}]")
                };
                form_pairs(value, &name, out);
            }
        }
        Json::Array(items) => {
            for (i, value) in items.iter().enumerate() {
                form_pairs(value, &format!("{prefix}[{i}]"), out);
            }
        }
        Json::Null => {}
        Json::String(text) => out.push((prefix.to_owned(), text.clone())),
        other => out.push((prefix.to_owned(), other.to_string())),
    }
}

/// The checkout's parameters as Stripe takes them.
pub(crate) fn checkout_params(customer: &str, checkout: &Checkout) -> Vec<(String, String)> {
    let metadata: serde_json::Map<String, Json> = checkout
        .metadata
        .iter()
        .map(|(k, v)| (k.clone(), json!(v)))
        .collect();
    let mut body = json!({
        "customer": customer,
        "mode": checkout.mode,
        "line_items": [{"price": checkout.price, "quantity": checkout.quantity}],
        "success_url": checkout.success_url_with_id(),
        "cancel_url": checkout.cancel_url,
        "metadata": metadata,
    });
    if checkout.allow_promotion_codes {
        body["allow_promotion_codes"] = json!(true);
    }
    // So the charge or subscription it makes carries the metadata too.
    let carrier = if checkout.mode == "subscription" {
        "subscription_data"
    } else {
        "payment_intent_data"
    };
    body[carrier] = json!({ "metadata": metadata });
    let mut pairs = Vec::new();
    form_pairs(&body, "", &mut pairs);
    pairs
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn encodes_checkouts_as_stripe_does() {
        let checkout = Checkout::payment("price_1", "https://x.com/return", "https://x.com/p")
            .metadata("user_id", 7)
            .allow_promotion_codes();
        let pairs = checkout_params("cus_1", &checkout);
        let get = |k: &str| {
            pairs
                .iter()
                .find(|(name, _)| name == k)
                .map(|(_, v)| v.as_str())
        };
        assert_eq!(get("line_items[0][price]"), Some("price_1"));
        assert_eq!(get("line_items[0][quantity]"), Some("1"));
        assert_eq!(get("metadata[user_id]"), Some("7"));
        assert_eq!(get("payment_intent_data[metadata][user_id]"), Some("7"));
        assert_eq!(
            get("success_url"),
            Some("https://x.com/return?session_id={CHECKOUT_SESSION_ID}")
        );
        assert_eq!(get("allow_promotion_codes"), Some("true"));
    }
}