Compare commits

...
Author SHA1 Message Date
Brandon Thomas 0c359d55d3 prevent proration 2025-09-17 11:41:51 -04:00
Brandon Thomas 8dba5d1d46 far better management flow 2025-09-17 00:38:58 -04:00
Brandon Thomas e1d83714fc rename modules 2025-09-16 23:38:13 -04:00
Brandon Thomas d4ec659568 cleanup 2025-09-16 22:56:38 -04:00
Brandon Thomas 780ee74b95 user->customer link on checkout and portal 2025-09-16 22:30:13 -04:00
Brandon Thomas 8e7cd5573e credit pack customer reuse 2025-09-16 22:25:26 -04:00
Brandon Thomas aa0524f48c save customer <-> user 2025-09-16 22:06:11 -04:00
Brandon Thomas d6b55ae5ac new table for storing customer links 2025-09-16 20:01:42 -04:00
Brandon Thomas f9e52ecebf Customer creation on checkout 2025-09-16 13:51:53 -04:00
Brandon Thomas dd656e2b61 fix bug, comment reason 2025-09-16 13:23:52 -04:00
Brandon Thomas a7a89bbd55 on second thought, don't resurrect dead subscriptions 2025-09-16 12:45:08 -04:00
Brandon Thomas bcb74b377a pull existing inactive subscription, but no fakeyou subs 2025-09-16 12:23:00 -04:00
Brandon Thomas e0400b651e credits checkout from existing subscriber record 2025-09-16 11:53:40 -04:00
Brandon Thomas 5cb06357fa add delta to ledger entries 2025-09-16 10:19:17 -04:00
Brandon Thomas 5bdb59bcce change button labels 2025-09-16 09:30:31 -04:00
Brandon Thomas 92a0674776 end and bill dates 2025-09-16 09:11:13 -04:00
Brandon Thomas 0f5ec3c83b next payment 2025-09-16 08:46:51 -04:00
Brandon Thomas 9835a238ce fix pricing modal 2025-09-16 07:34:52 -04:00
Brandon Thomas 68e77fd7d3 update payment method 2025-09-16 07:12:27 -04:00
Brandon Thomas 01053b7ccc billing portal subscription change works now 2025-09-16 06:19:07 -04:00
Brandon Thomas dec325c190 wip 2025-09-16 06:11:16 -04:00
Brandon Thomas 6c5d956bf8 tauri handles distinct customer portal cases 2025-09-16 05:44:36 -04:00
Brandon Thomas 3eeae4651c split billing portal into three distinct endpoints 2025-09-16 05:00:29 -04:00
Brandon Thomas 191b0c1463 subscription cancel within modal 2025-09-16 04:17:12 -04:00
Brandon Thomas 0b50b2d637 wip reuse of subscription modal 2025-09-16 04:10:43 -04:00
Brandon Thomas 3a9b0c100e fix 2025-09-16 04:04:18 -04:00
Brandon Thomas b2ecd4dcd1 de-duplicate plan data 2025-09-16 04:02:07 -04:00
Brandon Thomas 62c2ab0581 refresh on subscription changed 2025-09-16 03:49:09 -04:00
Brandon Thomas f90ab5771a change plan 2025-09-16 03:10:55 -04:00
Brandon Thomas 6a0abfc177 de-dupe query 2025-09-14 22:45:30 -04:00
Brandon Thomas 681fa8e76e update event 2025-09-14 20:57:35 -04:00
Brandon Thomas 9e80e0c79d hide subscribe button in settings when paid 2025-09-14 20:50:21 -04:00
Brandon Thomas ab62bcea11 only show upgrade if there's no paid plan 2025-09-14 20:45:46 -04:00
Brandon Thomas ffad39e6b7 add subscription info 2025-09-14 20:26:22 -04:00
Brandon Thomas 9b637aa6c9 fetch current plan 2025-09-14 19:26:17 -04:00
Brandon Thomas cb41b1a0af move credits, add subscriptions 2025-09-14 18:06:49 -04:00
Brandon Thomas e680bef024 notify frontend of credits changes 2025-09-14 14:40:01 -04:00
Brandon Thomas f0f2ae00fe listen to credits change event 2025-09-13 16:27:33 -04:00
Brandon Thomas 5072e38824 test billing code in server 2025-09-12 19:22:28 -04:00
Brandon Thomas ec8623e200 remove duplicate calls 2025-09-12 18:15:26 -04:00
Brandon Thomas 15c52d4e9b fix api call 2025-09-12 18:12:32 -04:00
Brandon Thomas de58d7c033 fix api call and display credits in frontend 2025-09-12 18:09:01 -04:00
Brandon Thomas 64b91cd6bc add frontend billing package, Tauri "get credits command" 2025-09-12 17:17:43 -04:00
Brandon Thomas 5360dd0f58 get rid of login button - it gets stuck in a bad state 2025-09-12 01:09:46 -04:00
Brandon Thomas f8b53872ae clients 2025-09-12 01:00:05 -04:00
Brandon Thomas 2e024efc32 new subscriptions endpoint 2025-09-12 01:00:05 -04:00
Brandon Thomas 4bb3f6af2d wallets -> credits routes instead 2025-09-12 01:00:05 -04:00
Brandon Thomas 2de4d9d9e9 move crate, sort workspace cargo.toml 2025-09-12 01:00:05 -04:00
Brandon Thomas 80d28022c0 get wallet endpoint 2025-09-12 01:00:05 -04:00
Brandon Thomas d770d81508 wallets namespaces, shorthand for query_map 2025-09-12 01:00:05 -04:00
Brandon Thomas 1fa93b5327 more metadata 2025-09-12 01:00:05 -04:00
Brandon Thomas eebfdd3d00 subscription flow 2025-09-12 01:00:05 -04:00
Brandon Thomas 90032848ee create billing portal session 2025-09-12 01:00:05 -04:00
Brandon Thomas 07722766dd log invoice, etc. tokens 2025-09-12 01:00:04 -04:00
Brandon Thomas f272dbf401 ledger entries wip 2025-09-12 01:00:04 -04:00
Brandon Thomas 6177782946 insert entries 2025-09-12 01:00:04 -04:00
Brandon Thomas ad9bda9e22 token and entry type for ledgers 2025-09-12 01:00:04 -04:00
Brandon Thomas 41e3a384db stupid irrelevant side quest for PR - safe crockford tokens 2025-09-12 01:00:04 -04:00
Brandon Thomas 168a1ace69 change prefix for subscriptions, remove fields 2025-09-12 01:00:04 -04:00
Brandon Thomas 7e32dde5b3 update schemas 2025-09-12 01:00:04 -04:00
Brandon Thomas 9de3ccac79 fill monthly wallet 2025-09-12 01:00:04 -04:00
Brandon Thomas 3f0eccf27e subscription invoices work 2025-09-12 01:00:04 -04:00
Brandon Thomas 9bbcbca1e2 better logging 2025-09-12 01:00:04 -04:00
Brandon Thomas f5696912c2 wip 2025-09-12 01:00:04 -04:00
Brandon Thomas 68559561c1 refactor 2025-09-12 01:00:04 -04:00
Brandon Thomas 75bc2a98f8 move 2025-09-12 01:00:04 -04:00
Brandon Thomas 294ee0d006 subscription paid wip 2025-09-12 01:00:04 -04:00
Brandon Thomas b9de0bf456 billing anchor 2025-09-12 01:00:04 -04:00
Brandon Thomas 437317438e new migrations 2025-09-12 01:00:04 -04:00
Brandon Thomas 8248e53ded refactor subscriptions handlers 2025-09-12 01:00:04 -04:00
Brandon Thomas 72631c94be refactor subs creation 2025-09-12 01:00:04 -04:00
Brandon Thomas e413cc94ad fix logic bug 2025-09-12 01:00:04 -04:00
Brandon Thomas 06023ae11e refactor 2025-09-12 01:00:04 -04:00
Brandon Thomas 8712b291c2 refactor 2025-09-12 01:00:04 -04:00
Brandon Thomas 6c678ec7f3 refactor 2025-09-12 01:00:04 -04:00
Brandon Thomas cba6f25a17 refactor 2025-09-12 01:00:04 -04:00
Brandon Thomas d10cb54c62 refactor 2025-09-12 01:00:04 -04:00
Brandon Thomas b5bc532b80 refactor 2025-09-12 01:00:04 -04:00
Brandon Thomas da2e7ae4b6 big refactor of this to remove http during db transactions 2025-09-12 01:00:04 -04:00
Brandon Thomas 036dbeaeb4 wallet updates work! 2025-09-12 01:00:04 -04:00
Brandon Thomas f6ed5abdb7 wip 2025-09-12 01:00:04 -04:00
Brandon Thomas 70bed32f51 query for wallet token 2025-09-12 01:00:04 -04:00
Brandon Thomas 497dbd9b4f wip 2025-09-12 01:00:04 -04:00
Brandon Thomas 0ad8421a16 subs transactions fixed 2025-09-12 01:00:04 -04:00
Brandon Thomas aef0c2f76a compile errors 2025-09-12 01:00:03 -04:00
Brandon Thomas e5f1cd00ef transactional 2025-09-12 01:00:03 -04:00
Brandon Thomas 5f3399db62 cleanup 2025-09-12 01:00:03 -04:00
Brandon Thomas 2467d6f2c7 wip 2025-09-12 01:00:03 -04:00
Brandon Thomas e48ee589ad retry behavior 2025-09-12 01:00:03 -04:00
Brandon Thomas b3e74e25f6 close billing window when done 2025-09-12 01:00:03 -04:00
Brandon Thomas ff5ebac734 info on invoices 2025-09-12 01:00:03 -04:00
Brandon Thomas b15e50e502 lookup product info from payment intents 2025-09-12 01:00:03 -04:00
Brandon Thomas 687e33df96 database migrations 2025-09-12 01:00:03 -04:00
Brandon Thomas d08753234c notes 2025-09-12 01:00:03 -04:00
Brandon Thomas bd2e091238 note 2025-09-12 01:00:03 -04:00
Brandon Thomas 67d293804b fix credits purchase 2025-09-12 01:00:03 -04:00
Brandon Thomas 1c1a75ef6b open credits window 2025-09-12 01:00:03 -04:00
Brandon Thomas 562c9a18ef attempt to move commands into separate function failed 2025-09-12 01:00:03 -04:00
Brandon Thomas fe3388a648 rewire commands 2025-09-12 01:00:03 -04:00
Brandon Thomas c8651fa2bc rework handlers to add credits 2025-09-12 01:00:03 -04:00
Brandon Thomas 65f36704cf wip 2025-09-12 01:00:03 -04:00
Brandon Thomas 74f7422e32 notes 2025-09-12 01:00:03 -04:00
Brandon Thomas 92b3245533 fixes 2025-09-12 01:00:03 -04:00
Brandon Thomas 64fbb0b04e subscription events seem okay-ish 2025-09-12 01:00:03 -04:00
Brandon Thomas 72228345d0 wip 2025-09-12 01:00:03 -04:00
Brandon Thomas b12c81dc37 cleanup 2025-09-12 01:00:03 -04:00
Brandon Thomas 80f0235c50 wip 2025-09-12 01:00:03 -04:00
Brandon Thomas 1e4fca06ee filter existing artcraft subscriptions, allow promo codes 2025-09-12 01:00:03 -04:00
Brandon Thomas 50e228aa3f enum type 2025-09-12 01:00:03 -04:00
Brandon Thomas 8fedbfcded remove old handler 2025-09-12 01:00:03 -04:00
Brandon Thomas 6696ef3366 user lookup in component 2025-09-12 01:00:03 -04:00
Brandon Thomas 837f3ecdf3 wip 2025-09-12 01:00:03 -04:00
Brandon Thomas 2b7cc30bbe omg, this yak shave worked. 2025-09-12 01:00:02 -04:00
Brandon Thomas 35554c6dde compiles with endpoint logic 2025-09-12 01:00:02 -04:00
Brandon Thomas fe46c72d06 this builds 2025-09-12 01:00:02 -04:00
Brandon Thomas cec81bfb8e about to test new crate to isolate new version of async-stripe 2025-09-12 01:00:02 -04:00
Brandon Thomas 3c89cf595e organize products by slug + production products 2025-09-12 01:00:02 -04:00
Brandon Thomas 24b8c3e69a enums 2025-09-12 01:00:02 -04:00
Brandon Thomas 474904ddd7 open pricing window to stripe 2025-09-12 01:00:02 -04:00
Brandon Thomas 859897bedb cleanup endpoint 2025-09-12 01:00:02 -04:00
Brandon Thomas 1e65125c07 checkout session handler 2025-09-12 01:00:02 -04:00
Brandon Thomas 8ae8d77187 stripe webhook handler for artcraft 2025-09-12 01:00:02 -04:00
338 changed files with 11008 additions and 641 deletions
Generated
+258 -3
View File
@@ -926,11 +926,155 @@ dependencies = [
"serde_qs 0.10.1",
"sha2 0.10.8",
"smart-default 0.6.0",
"smol_str",
"smol_str 0.1.24",
"thiserror 1.0.63",
"tokio",
]
[[package]]
name = "async-stripe"
version = "0.41.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cecbddf002ad7a13d2041eadf1b234cb3f57653ffdd901a01bc3f1c65aa77440"
dependencies = [
"chrono",
"futures-util",
"hex",
"hmac 0.12.1",
"http-types",
"hyper 0.14.28",
"hyper-tls 0.5.0",
"serde",
"serde_json",
"serde_path_to_error",
"serde_qs 0.10.1",
"sha2 0.10.8",
"smart-default 0.6.0",
"smol_str 0.1.24",
"thiserror 1.0.63",
"tokio",
]
[[package]]
name = "async-stripe"
version = "1.0.0-alpha.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a92140fa7152f9dcde7554cb1da37c7ae93b0c724db5214c754c55a9765afbe8"
dependencies = [
"async-stripe-client-core",
"async-stripe-shared",
"bytes 1.10.1",
"http-body-util",
"hyper 1.6.0",
"hyper-tls 0.6.0",
"hyper-util",
"miniserde",
"thiserror 2.0.12",
"tokio",
]
[[package]]
name = "async-stripe-billing"
version = "1.0.0-alpha.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33c4cd0ac61e0dcb39da4f3c04b049c0d8a3a98868ca976e18ff56ecac1b6e08"
dependencies = [
"async-stripe-client-core",
"async-stripe-shared",
"async-stripe-types",
"miniserde",
"serde",
"smol_str 0.3.2",
]
[[package]]
name = "async-stripe-checkout"
version = "1.0.0-alpha.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b115740c799730d4caac099d48be4908d2d99611d56a874d2d3555b5d4306a97"
dependencies = [
"async-stripe-client-core",
"async-stripe-shared",
"async-stripe-types",
"miniserde",
"serde",
"smol_str 0.3.2",
]
[[package]]
name = "async-stripe-client-core"
version = "1.0.0-alpha.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fb1f6b6693946e650a9361feb319389a1408534ec1b618cd9239f1e2e20b8668"
dependencies = [
"async-stripe-shared",
"async-stripe-types",
"bytes 1.10.1",
"futures-util",
"miniserde",
"serde",
"serde_json",
"serde_qs 0.13.0",
"thiserror 2.0.12",
"tracing",
]
[[package]]
name = "async-stripe-core"
version = "1.0.0-alpha.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "81d0445a38170bcc3e4adf52fd80c94b70b02dc73a102afcd0bc9d6051eada18"
dependencies = [
"async-stripe-client-core",
"async-stripe-shared",
"async-stripe-types",
"miniserde",
"serde",
"smol_str 0.3.2",
]
[[package]]
name = "async-stripe-shared"
version = "1.0.0-alpha.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b4328e5c0deeacd7cd5a95286d4f5dce045791b30be87583dd706c2342236c3"
dependencies = [
"async-stripe-types",
"miniserde",
"serde",
"serde_json",
"smol_str 0.3.2",
]
[[package]]
name = "async-stripe-types"
version = "1.0.0-alpha.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985b4f00fd57ce9cbd015c6410d05dfbe5d2bf90513e20b417e70b6f022e3f88"
dependencies = [
"miniserde",
"serde",
"serde_json",
"smol_str 0.3.2",
]
[[package]]
name = "async-stripe-webhook"
version = "1.0.0-alpha.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "75f8382af92463fa8e0b86e825d7d08eecbcd8715c197f1a66173fcc18e35774"
dependencies = [
"async-stripe-shared",
"async-stripe-types",
"chrono",
"hex",
"hmac 0.12.1",
"miniserde",
"serde",
"sha2 0.10.8",
"thiserror 1.0.63",
]
[[package]]
name = "async-task"
version = "4.7.1"
@@ -1201,6 +1345,41 @@ dependencies = [
"num-traits",
]
[[package]]
name = "billing_artcraft_component"
version = "0.0.1"
dependencies = [
"actix-http",
"actix-web",
"anyhow",
"artcraft_api_defs",
"async-stripe 1.0.0-alpha.2",
"async-stripe-billing",
"async-stripe-checkout",
"async-stripe-core",
"async-stripe-shared",
"async-stripe-types",
"async-stripe-webhook",
"chrono",
"component_traits",
"enums",
"errors",
"http_server_common",
"log",
"mockall",
"mysql_queries",
"once_cell",
"reusable_types",
"serde",
"serde_derive",
"serde_json",
"sqlx",
"tokens",
"tokio",
"user_traits_component",
"workspace-build-acceleration",
]
[[package]]
name = "billing_component"
version = "0.0.1"
@@ -1208,9 +1387,11 @@ dependencies = [
"actix-http",
"actix-web",
"anyhow",
"async-stripe",
"async-stripe 0.26.0",
"async-trait",
"chrono",
"component_traits",
"enums",
"errors",
"http_server_common",
"log",
@@ -2089,6 +2270,34 @@ dependencies = [
"workspace-build-acceleration",
]
[[package]]
name = "component_traits"
version = "0.0.1"
dependencies = [
"actix-http",
"actix-web",
"anyhow",
"artcraft_api_defs",
"async-trait",
"chrono",
"enums",
"errors",
"http_server_common",
"log",
"mockall",
"mysql_queries",
"once_cell",
"reusable_types",
"serde",
"serde_derive",
"serde_json",
"sqlx",
"tokens",
"tokio",
"user_traits_component",
"workspace-build-acceleration",
]
[[package]]
name = "composite_identifiers"
version = "0.0.1"
@@ -6398,6 +6607,17 @@ dependencies = [
"workspace-build-acceleration",
]
[[package]]
name = "mini-internal"
version = "0.1.42"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6c74ab4f1a0c0ab045260ee4727b23c00cc17e5eff5095262d08eef8c3c8d49"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.87",
]
[[package]]
name = "minidom"
version = "0.16.0"
@@ -6413,6 +6633,17 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
[[package]]
name = "miniserde"
version = "0.1.42"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08ec68bf2ad170a53a6efa92c3df7187968d6e475fe7a935725868154074ca0f"
dependencies = [
"itoa 1.0.11",
"mini-internal",
"ryu",
]
[[package]]
name = "miniz_oxide"
version = "0.7.2"
@@ -9528,6 +9759,17 @@ dependencies = [
"thiserror 1.0.63",
]
[[package]]
name = "serde_qs"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cd34f36fe4c5ba9654417139a9b3a20d2e1de6012ee678ad14d240c22c78d8d6"
dependencies = [
"percent-encoding",
"serde",
"thiserror 1.0.63",
]
[[package]]
name = "serde_repr"
version = "0.1.19"
@@ -9904,6 +10146,16 @@ dependencies = [
"serde",
]
[[package]]
name = "smol_str"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9676b89cd56310a87b93dec47b11af744f34d5fc9f367b829474eec0a891350d"
dependencies = [
"borsh",
"serde",
]
[[package]]
name = "socket2"
version = "0.5.10"
@@ -10292,9 +10544,11 @@ dependencies = [
"actix_helpers",
"anyhow",
"artcraft_api_defs",
"async-stripe",
"async-stripe 0.26.0",
"async-stripe 0.41.0",
"async-trait",
"base64 0.22.1",
"billing_artcraft_component",
"billing_component",
"bootstrap",
"bucket_paths",
@@ -10302,6 +10556,7 @@ dependencies = [
"chrono",
"cloud_storage",
"collections",
"component_traits",
"composite_identifiers",
"config",
"cookies",
+37 -32
View File
@@ -6,6 +6,7 @@ resolver = "2"
members = [
# API clients for external services
# These might be custom implementations or wrappers over other client libraries.
"crates/api_clients/artcraft_api_defs", # TODO: api_clients/{artcraft}/{api_defs,client}
"crates/api_clients/cloud_storage",
"crates/api_clients/fal_client",
"crates/api_clients/google_drive_common",
@@ -97,7 +98,6 @@ members = [
#"crates/schema/database/sqlite_queries",
# Schema (public): common strongly-typed tokens, ids, payloads, etc.
"crates/schema/public/api/artcraft_api_defs",
"crates/schema/public/composite_identifiers",
"crates/schema/public/enums",
"crates/schema/public/enums_public",
@@ -119,6 +119,8 @@ members = [
# Service Plugins: complete subsystems that can be plugged into services (users, billing, etc.)
"crates/service/plugins/billing",
"crates/service/plugins/billing_artcraft",
"crates/service/plugins/component_traits",
"crates/service/plugins/inference_workloads",
"crates/service/plugins/user_traits_component",
@@ -176,6 +178,40 @@ publish = false
#
workspace-build-acceleration = { path = "crates/workspace-build-acceleration" }
# Internal libs
# Setting paths here ensures we don't need to do so in every crate's Cargo.toml
# It makes refactoring much easier.
artcraft_api_defs = { path = "crates/api_clients/artcraft_api_defs" }
build_metadata = { path = "crates/lib/build_metadata" }
cloud_storage = { path = "crates/api_clients/cloud_storage" }
cloudflare_errors = { path = "crates/lib/cloudflare_errors" }
component_traits = { path = "crates/service/plugins/component_traits" }
cookie_store = { path = "crates/lib/cookie_store" }
crockford = { path = "crates/lib/data/crockford" }
enums = { path = "crates/schema/public/enums" }
enums_public = { path = "crates/schema/public/enums_public" }
errors = { path = "crates/lib/errors" }
fal_client = { path = "crates/api_clients/fal_client" }
file_to_base64_url = { path = "crates/lib/files/file_to_base64_url" }
filesys = { path = "crates/lib/files/filesys" }
idempotency = { path = "crates/lib/idempotency" }
images = { path = "crates/lib/files/images" }
jwt_light = { path = "crates/lib/jwt_light" }
memory_caching = { path = "crates/lib/caching/memory_caching" }
memory_store = { path = "crates/lib/caching/memory_store" }
midjourney_client = { path = "crates/api_clients/midjourney_client" }
mimetypes = { path = "crates/lib/files/mimetypes" }
openai_sora_client = { path = "crates/api_clients/openai_sora_client" }
primitives = { path = "crates/lib/data/primitives" }
shared_service_components = { path = "crates/lib/shared_service_components" }
sqlite_tasks = { path = "crates/schema/database/sqlite_tasks" }
storyteller_client = { path = "crates/api_clients/storyteller_client" }
subprocess_common = { path = "crates/lib/subprocess_common" }
test_data = { path = "crates/lib/test_data" }
testing = { path = "crates/lib/testing" }
tokens = { path = "crates/schema/public/tokens" }
web_base64 = { path = "crates/lib/data/web_base64" }
# External libs
# Centrally pinned versions so that we can uniformly upgrade/downgrade versions across the workspace
# If a crate needs to use an older/newer version, the dependency should be managed in that crate's own Cargo.toml
@@ -219,34 +255,3 @@ thiserror = "2.0.12"
tokio = { version = "1.45.1", features = ["macros"] }
toml = "0.8.22"
url = { version = "2.5.4", features = ["serde"] }
# Internal libs
artcraft_api_defs = { path = "crates/schema/public/api/artcraft_api_defs" }
build_metadata = { path = "crates/lib/build_metadata" }
cloud_storage = { path = "crates/api_clients/cloud_storage" }
cloudflare_errors = { path = "crates/lib/cloudflare_errors" }
cookie_store = { path = "crates/lib/cookie_store" }
crockford = { path = "crates/lib/data/crockford" }
enums = { path = "crates/schema/public/enums" }
enums_public = { path = "crates/schema/public/enums_public" }
errors = { path = "crates/lib/errors" }
fal_client = { path = "crates/api_clients/fal_client" }
file_to_base64_url = { path = "crates/lib/files/file_to_base64_url" }
filesys = { path = "crates/lib/files/filesys" }
idempotency = { path = "crates/lib/idempotency" }
images = { path = "crates/lib/files/images" }
jwt_light = { path = "crates/lib/jwt_light" }
memory_caching = { path = "crates/lib/caching/memory_caching" }
memory_store = { path = "crates/lib/caching/memory_store" }
midjourney_client = { path = "crates/api_clients/midjourney_client" }
mimetypes = { path = "crates/lib/files/mimetypes" }
openai_sora_client = { path = "crates/api_clients/openai_sora_client" }
primitives = { path = "crates/lib/data/primitives" }
shared_service_components = { path = "crates/lib/shared_service_components" }
sqlite_tasks = { path = "crates/schema/database/sqlite_tasks" }
storyteller_client = { path = "crates/api_clients/storyteller_client" }
subprocess_common = { path = "crates/lib/subprocess_common" }
test_data = { path = "crates/lib/test_data" }
testing = { path = "crates/lib/testing" }
tokens = { path = "crates/schema/public/tokens" }
web_base64 = { path = "crates/lib/data/web_base64" }
@@ -0,0 +1,5 @@
-- noinspection SqlDialectInspectionForFile
-- noinspection SqlNoDataSourceInspectionForFile
-- noinspection SqlResolveForFile
ALTER TABLE user_subscriptions DROP COLUMN maybe_stripe_invoice_is_paid;
@@ -0,0 +1,7 @@
-- noinspection SqlDialectInspectionForFile
-- noinspection SqlNoDataSourceInspectionForFile
-- noinspection SqlResolveForFile
ALTER TABLE user_subscriptions
ADD COLUMN maybe_stripe_invoice_is_paid BOOLEAN DEFAULT NULL
AFTER maybe_stripe_subscription_status;
@@ -0,0 +1,5 @@
-- noinspection SqlDialectInspectionForFile
-- noinspection SqlNoDataSourceInspectionForFile
-- noinspection SqlResolveForFile
DROP TABLE wallets;
@@ -0,0 +1,66 @@
-- noinspection SqlDialectInspectionForFile
-- noinspection SqlNoDataSourceInspectionForFile
-- noinspection SqlResolveForFile
CREATE TABLE wallets (
-- Not used for anything except replication.
id BIGINT(20) NOT NULL AUTO_INCREMENT,
-- Effective "primary key" (PUBLIC)
token VARCHAR(32) NOT NULL,
-- If we host multiple sites with distinct categories, this will enable us to
-- segregate wallets. This is effectively a wallet namespace.
-- NB: Uses the `PaymentsNamespace` enum, which is also shared with subscriptions.
wallet_namespace VARCHAR(32) NOT NULL,
-- Who owns the wallet
-- In the future, we might allow other users to use the same wallet,
-- but the wallet would still have an owner.
-- For now, we'll keep this 1:1 with users, but we may want 1:n in the future.
owner_user_token VARCHAR(32) NOT NULL,
-- The durable credits bucket.
-- This bucket is persistent and is refilled by user credit purchases.
-- Max value unsigned: 4,294,967,295 (U32)
banked_credits INTEGER UNSIGNED NOT NULL DEFAULT 0,
-- The monthly credits bucket.
-- This bucket is ephemeral and is refilled monthly.
-- Max value unsigned: 4,294,967,295 (U32)
monthly_credits INTEGER UNSIGNED NOT NULL DEFAULT 0,
-- Whether the stripe subscription is active.
-- subscription_is_active BOOLEAN NOT NULL DEFAULT FALSE,
-- Whether the stripe subscription is paid.
-- If the subscription is not paid, we should not allow usage of monthly credits.
-- subscription_is_paid BOOLEAN NOT NULL DEFAULT FALSE,
-- ========== VECTOR CLOCK ==========
-- Incremented with every update.
version INT NOT NULL DEFAULT 0,
-- ========== RECORD TIMESTAMPS ==========
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
-- ========== PAYMENTS AND SUBSCRIPTIONS TIMESTAMPS ==========
-- When the user last purchased banked (durable) credits.
-- banked_credits_last_purchased_at TIMESTAMP DEFAULT NULL,
-- When we last refilled the monthly bucket.
-- This has to do with subscription logic.
-- monthly_wallet_refilled_at TIMESTAMP DEFAULT NULL,
-- ========== INDICES ==========
PRIMARY KEY (id),
UNIQUE KEY (token),
UNIQUE KEY (wallet_namespace, owner_user_token), -- For now
INDEX idx_wallet_namespace (wallet_namespace),
INDEX idx_owner_user_token (owner_user_token)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
@@ -0,0 +1,5 @@
-- noinspection SqlDialectInspectionForFile
-- noinspection SqlNoDataSourceInspectionForFile
-- noinspection SqlResolveForFile
DROP TABLE wallet_ledger_entries;
@@ -0,0 +1,52 @@
-- noinspection SqlDialectInspectionForFile
-- noinspection SqlNoDataSourceInspectionForFile
-- noinspection SqlResolveForFile
CREATE TABLE wallet_ledger_entries (
-- Not used for anything except replication.
id BIGINT(20) NOT NULL AUTO_INCREMENT,
-- Effective "primary key" (PUBLIC)
token VARCHAR(32) NOT NULL,
-- Which wallet this entry corresponds to.
wallet_token VARCHAR(32) NOT NULL,
-- The type of ledger entry this is.
entry_type VARCHAR(32) NOT NULL,
-- A record we can look up to attribute the credit or deduction against
-- This could be an internal entity token (prompt_token, job token) or an
-- external token (stripe event_id, stripe invoice.id, etc.)
-- Length is VARCHAR(255) to accommodate Stripe IDs.
maybe_entity_ref VARCHAR(255) DEFAULT NULL,
-- Signed integer that shows the delta of credits for this event.
-- This combines impacts to both banked_credits and monthly_credits.
-- This is less authoritative than the before/after fields, but is useful
credits_delta INTEGER NOT NULL DEFAULT 0,
-- Balance of banked credits before the event.
-- Max value unsigned: 4,294,967,295 (U32)
banked_credits_before INTEGER UNSIGNED NOT NULL DEFAULT 0,
-- Balance of banked credits after the event.
banked_credits_after INTEGER UNSIGNED NOT NULL DEFAULT 0,
-- Balance of monthly credits before the event.
-- Max value unsigned: 4,294,967,295 (U32)
monthly_credits_before INTEGER UNSIGNED NOT NULL DEFAULT 0,
-- Balance of monthly credits after the event.
monthly_credits_after INTEGER UNSIGNED NOT NULL DEFAULT 0,
-- ========== RECORD TIMESTAMPS ==========
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
-- ========== INDICES ==========
PRIMARY KEY (id),
UNIQUE KEY (token),
KEY index_wallet_token (wallet_token)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
@@ -0,0 +1,5 @@
-- noinspection SqlDialectInspectionForFile
-- noinspection SqlNoDataSourceInspectionForFile
-- noinspection SqlResolveForFile
ALTER TABLE user_subscriptions DROP COLUMN maybe_stripe_billing_cycle_anchor;
@@ -0,0 +1,7 @@
-- noinspection SqlDialectInspectionForFile
-- noinspection SqlNoDataSourceInspectionForFile
-- noinspection SqlResolveForFile
ALTER TABLE user_subscriptions
ADD COLUMN maybe_stripe_billing_cycle_anchor TIMESTAMP DEFAULT NULL
AFTER maybe_stripe_invoice_is_paid;
@@ -0,0 +1,5 @@
-- noinspection SqlDialectInspectionForFile
-- noinspection SqlNoDataSourceInspectionForFile
-- noinspection SqlResolveForFile
ALTER TABLE stripe_webhook_event_logs DROP COLUMN maybe_internal_entity_token;
@@ -0,0 +1,7 @@
-- noinspection SqlDialectInspectionForFile
-- noinspection SqlNoDataSourceInspectionForFile
-- noinspection SqlResolveForFile
ALTER TABLE stripe_webhook_event_logs
ADD COLUMN maybe_internal_entity_token VARCHAR(32) DEFAULT NULL
AFTER maybe_user_token;
@@ -0,0 +1,5 @@
-- noinspection SqlDialectInspectionForFile
-- noinspection SqlNoDataSourceInspectionForFile
-- noinspection SqlResolveForFile
DROP TABLE user_stripe_customer_links;
@@ -0,0 +1,36 @@
-- noinspection SqlDialectInspectionForFile
-- noinspection SqlNoDataSourceInspectionForFile
-- noinspection SqlResolveForFile
-- 1:1 links between a user and a stripe customer (per payments namespace)
-- We can hard delete records if we have to.
-- If users need a new stripe customer ID, we need to hard delete the existing record.
CREATE TABLE user_stripe_customer_links (
-- Not used for anything except replication.
id BIGINT(20) NOT NULL AUTO_INCREMENT,
-- Composite primary key
user_token VARCHAR(32) NOT NULL,
-- Composite primary key
-- If we host multiple sites with distinct categories, this will enable us to
-- segregate accounts.
-- NB: Uses the `PaymentsNamespace` enum, which is also shared with subscriptions.
payments_namespace VARCHAR(32) NOT NULL,
-- Unique key. (We can loosen to `stripe_customer_id, wallet_namespace` later if
-- we want to share billing.)
stripe_customer_id VARCHAR(255) NOT NULL,
-- ========== RECORD TIMESTAMPS ==========
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
-- ========== INDICES ==========
PRIMARY KEY (id),
UNIQUE KEY (user_token, payments_namespace),
-- UNIQUE KEY (stripe_customer_id, payments_namespace)
UNIQUE KEY (stripe_customer_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
@@ -0,0 +1,66 @@
-- noinspection SqlDialectInspectionForFile
-- noinspection SqlNoDataSourceInspectionForFile
-- noinspection SqlResolveForFile
CREATE TABLE stripe_webhook_event_logs (
-- Not used for anything except replication.
id BIGINT(20) NOT NULL AUTO_INCREMENT,
-- ========== STRIPE DATA ==========
-- You can safely assume object IDs we generate will never exceed 255 characters,
-- but you should be able to handle IDs of up to that length. If for example you’re using MySQL,
-- you should store IDs in a VARCHAR(255) COLLATE utf8_bin column (the COLLATE configuration ensures
-- case-sensitivity in lookups).
-- https://stackoverflow.com/a/61809494
stripe_event_id VARCHAR(255) NOT NULL,
-- The type of webhook event
stripe_event_type VARCHAR(255) NOT NULL,
-- The id of the entity that was the subject of the event.
-- We don't always extract this.
maybe_stripe_event_entity_id VARCHAR(255) DEFAULT NULL,
-- The id of the entity that was the subject of the event.
-- We don't always extract this.
maybe_stripe_customer_id VARCHAR(255) DEFAULT NULL,
-- Whether this is in production or test mode in Stripe.
-- This is controlled by which API keys are used.
-- "livemode"=true in production.
stripe_is_production BOOLEAN NOT NULL DEFAULT FALSE,
-- ========== INTERNAL SYSTEM METADATA ==========
-- Whether we handled the event with any sort of action
action_was_taken BOOLEAN NOT NULL DEFAULT FALSE,
-- Whether we should ignore any future retries by Stripe replaying the event.
-- This helps us treat events with idempotency.
should_ignore_retry BOOLEAN NOT NULL DEFAULT FALSE,
-- Some event types may attach a user token
maybe_user_token VARCHAR(32) DEFAULT NULL,
-- An internal optional entity token this resolves to.
-- eg. `wallets.token` or `user_subscriptions.token`.
maybe_internal_entity_token VARCHAR(32) DEFAULT NULL,
-- ========== TIMESTAMPS ==========
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
-- When the event was created on Stripe's end
stripe_event_created_at TIMESTAMP NOT NULL,
-- ========== INDICES ==========
PRIMARY KEY (id),
UNIQUE KEY (stripe_event_id),
KEY index_stripe_event_type (stripe_event_type),
KEY index_maybe_stripe_event_entity_id (maybe_stripe_event_entity_id),
KEY index_maybe_stripe_customer_id (maybe_stripe_customer_id),
KEY fk_maybe_user_token (maybe_user_token)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
@@ -0,0 +1,36 @@
-- noinspection SqlDialectInspectionForFile
-- noinspection SqlNoDataSourceInspectionForFile
-- noinspection SqlResolveForFile
-- 1:1 links between a user and a stripe customer (per payments namespace)
-- We can hard delete records if we have to.
-- If users need a new stripe customer ID, we need to hard delete the existing record.
CREATE TABLE user_stripe_customer_links (
-- Not used for anything except replication.
id BIGINT(20) NOT NULL AUTO_INCREMENT,
-- Composite primary key
user_token VARCHAR(32) NOT NULL,
-- Composite primary key
-- If we host multiple sites with distinct categories, this will enable us to
-- segregate accounts.
-- NB: Uses the `PaymentsNamespace` enum, which is also shared with subscriptions.
payments_namespace VARCHAR(32) NOT NULL,
-- Unique key. (We can loosen to `stripe_customer_id, wallet_namespace` later if
-- we want to share billing.)
stripe_customer_id VARCHAR(255) NOT NULL,
-- ========== RECORD TIMESTAMPS ==========
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
-- ========== INDICES ==========
PRIMARY KEY (id),
UNIQUE KEY (user_token, payments_namespace),
-- UNIQUE KEY (stripe_customer_id, payments_namespace)
UNIQUE KEY (stripe_customer_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
@@ -53,6 +53,18 @@ CREATE TABLE user_subscriptions (
-- Subscription object status enum as string
maybe_stripe_subscription_status VARCHAR(32) DEFAULT NULL,
-- Primarily managed by the `invoice.paid` and `invoice.payment_failed` webhooks.
-- NB: Not applicable to FakeYou subscriptions!
maybe_stripe_invoice_is_paid BOOLEAN DEFAULT NULL,
-- Which day of the month, or month of the year, etc. to anchor the subscription to.
-- See docs on the subscription object.
-- Stripe:
-- "The reference point that aligns future billing cycle dates. It sets the day
-- of week for week intervals, the day of month for month and year intervals, and
-- the month of year for year intervals. The timestamp is in UTC format."
maybe_stripe_billing_cycle_anchor TIMESTAMP DEFAULT NULL,
maybe_stripe_is_production BOOLEAN DEFAULT NULL,
-- ========== VECTOR CLOCK ==========
@@ -64,6 +76,8 @@ CREATE TABLE user_subscriptions (
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
-- NB(bt, 2025-09-16): I don't think we write to the soft deleted_at field for user_subscriptions.
deleted_at TIMESTAMP DEFAULT NULL,
-- ========== SUBSCRIPTION TIMESTAMPS ==========
@@ -72,7 +86,10 @@ CREATE TABLE user_subscriptions (
-- This may predate the Stripe object `created` timestamp due to backdating.
subscription_start_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
-- We'll use this to determine if the subscription is active.
-- Our synthetic "expire" date. Moved forward for active subscriptions,
-- backdated for canceled subscriptions.
--
-- TODO: We'll (maybe?) use this to determine if the subscription is active.
--
-- Always compare against MySQL's clock rather than the app's clock so that we
-- don't get weird clock skew behaviors across multiple requests.
@@ -82,8 +99,12 @@ CREATE TABLE user_subscriptions (
subscription_expires_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
-- Billing periods.
-- Maybe useful for debugging.
-- Stripe API: subscription.items[0].data.current_period_start
current_billing_period_start_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
-- Stripe API: subscription.items[0].data.current_period_end
-- current_period_end is when the subscription renews (or cancels, if the
-- subscription is set to cancel).
current_billing_period_end_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
-- Subscription cancellation (future and past)
@@ -0,0 +1,52 @@
-- noinspection SqlDialectInspectionForFile
-- noinspection SqlNoDataSourceInspectionForFile
-- noinspection SqlResolveForFile
CREATE TABLE wallet_ledger_entries (
-- Not used for anything except replication.
id BIGINT(20) NOT NULL AUTO_INCREMENT,
-- Effective "primary key" (PUBLIC)
token VARCHAR(32) NOT NULL,
-- Which wallet this entry corresponds to.
wallet_token VARCHAR(32) NOT NULL,
-- The type of ledger entry this is.
entry_type VARCHAR(16) NOT NULL,
-- A record we can look up to attribute the credit or deduction against
-- This could be an internal entity token (prompt_token, job token) or an
-- external token (stripe event_id, stripe invoice.id, etc.)
-- Length is VARCHAR(255) to accommodate Stripe IDs.
maybe_entity_ref VARCHAR(255) DEFAULT NULL,
-- Signed integer that shows the delta of credits for this event.
-- This combines impacts to both banked_credits and monthly_credits.
-- This is less authoritative than the before/after fields, but is useful
credits_delta INTEGER NOT NULL DEFAULT 0,
-- Balance of banked credits before the event.
-- Max value unsigned: 4,294,967,295 (U32)
banked_credits_before INTEGER UNSIGNED NOT NULL DEFAULT 0,
-- Balance of banked credits after the event.
banked_credits_after INTEGER UNSIGNED NOT NULL DEFAULT 0,
-- Balance of monthly credits before the event.
-- Max value unsigned: 4,294,967,295 (U32)
monthly_credits_before INTEGER UNSIGNED NOT NULL DEFAULT 0,
-- Balance of monthly credits after the event.
monthly_credits_after INTEGER UNSIGNED NOT NULL DEFAULT 0,
-- ========== RECORD TIMESTAMPS ==========
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
-- ========== INDICES ==========
PRIMARY KEY (id),
UNIQUE KEY (token),
KEY index_wallet_token (wallet_token)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
@@ -0,0 +1,66 @@
-- noinspection SqlDialectInspectionForFile
-- noinspection SqlNoDataSourceInspectionForFile
-- noinspection SqlResolveForFile
CREATE TABLE wallets (
-- Not used for anything except replication.
id BIGINT(20) NOT NULL AUTO_INCREMENT,
-- Effective "primary key" (PUBLIC)
token VARCHAR(32) NOT NULL,
-- If we host multiple sites with distinct categories, this will enable us to
-- segregate wallets. This is effectively a wallet namespace.
-- NB: Uses the `PaymentsNamespace` enum, which is also shared with subscriptions.
wallet_namespace VARCHAR(32) NOT NULL,
-- Who owns the wallet
-- In the future, we might allow other users to use the same wallet,
-- but the wallet would still have an owner.
-- For now, we'll keep this 1:1 with users, but we may want 1:n in the future.
owner_user_token VARCHAR(32) NOT NULL,
-- The durable credits bucket.
-- This bucket is persistent and is refilled by user credit purchases.
-- Max value unsigned: 4,294,967,295 (U32)
banked_credits INTEGER UNSIGNED NOT NULL DEFAULT 0,
-- The monthly credits bucket.
-- This bucket is ephemeral and is refilled monthly.
-- Max value unsigned: 4,294,967,295 (U32)
monthly_credits INTEGER UNSIGNED NOT NULL DEFAULT 0,
-- Whether the stripe subscription is active.
-- subscription_is_active BOOLEAN NOT NULL DEFAULT FALSE,
-- Whether the stripe subscription is paid.
-- If the subscription is not paid, we should not allow usage of monthly credits.
-- subscription_is_paid BOOLEAN NOT NULL DEFAULT FALSE,
-- ========== VECTOR CLOCK ==========
-- Incremented with every update.
version INT NOT NULL DEFAULT 0,
-- ========== RECORD TIMESTAMPS ==========
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
-- ========== PAYMENTS AND SUBSCRIPTIONS TIMESTAMPS ==========
-- When the user last purchased banked (durable) credits.
-- banked_credits_last_purchased_at TIMESTAMP DEFAULT NULL,
-- When we last refilled the monthly bucket.
-- This has to do with subscription logic.
-- monthly_wallet_refilled_at TIMESTAMP DEFAULT NULL,
-- ========== INDICES ==========
PRIMARY KEY (id),
UNIQUE KEY (token),
UNIQUE KEY (wallet_namespace, owner_user_token), -- For now
INDEX idx_wallet_namespace (wallet_namespace),
INDEX idx_owner_user_token (owner_user_token)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
@@ -0,0 +1,20 @@
use serde_derive::{Deserialize, Serialize};
use utoipa::ToSchema;
#[derive(Serialize, Deserialize, ToSchema)]
pub struct GetSessionCreditsResponse {
pub success: bool,
/// Any free credits the user might have
/// We might support daily free credits.
pub free_credits: u64,
/// Any monthly refilling credits the user might have
pub monthly_credits: u64,
/// Any banked credits the user might have.
pub banked_credits: u64,
/// All the credit amounts added together.
pub sum_total_credits: u64,
}
@@ -0,0 +1 @@
pub mod get_session_credits;
@@ -0,0 +1,8 @@
pub mod common;
pub mod credits;
pub mod generate;
pub mod jobs;
pub mod media_file;
pub mod prompts;
pub mod stripe_artcraft;
pub mod subscriptions;
@@ -0,0 +1,17 @@
use enums::common::artcraft_credits_pack_slug::ArtcraftCreditsPackSlug;
use serde_derive::{Deserialize, Serialize};
use utoipa::ToSchema;
pub const CREATE_CREDITS_PACK_CHECKOUT_URL_PATH: &str = "/v1/stripe_artcraft/checkout/credits_pack";
#[derive(Serialize, Deserialize, ToSchema)]
pub struct StripeArtcraftCreateCreditsPackCheckoutRequest {
pub credits_pack: Option<ArtcraftCreditsPackSlug>,
}
#[derive(Serialize, Deserialize, ToSchema)]
pub struct StripeArtcraftCreateCreditsPackCheckoutResponse {
pub success: bool,
pub stripe_checkout_redirect_url: String,
}
@@ -0,0 +1,30 @@
use enums::common::artcraft_subscription_slug::ArtcraftSubscriptionSlug;
use serde_derive::{Deserialize, Serialize};
use utoipa::ToSchema;
pub const CREATE_SUBSCRIPTION_CHECKOUT_URL_PATH: &str = "/v1/stripe_artcraft/checkout/subscription";
#[derive(Serialize, Deserialize, ToSchema)]
pub struct StripeArtcraftCreateSubscriptionCheckoutRequest {
/// The (non-Stripe) internal identifier for the product or subscription.
/// This will be translated into a Stripe identifier.
pub plan: Option<ArtcraftSubscriptionSlug>,
pub cadence: Option<PlanBillingCadence>,
}
#[derive(Serialize, Deserialize, ToSchema, Debug, Copy, Clone)]
pub enum PlanBillingCadence {
#[serde(rename = "monthly")]
Monthly,
#[serde(rename = "yearly")]
Yearly,
}
#[derive(Serialize, Deserialize, ToSchema)]
pub struct StripeArtcraftCreateSubscriptionCheckoutResponse {
pub success: bool,
pub stripe_checkout_redirect_url: String,
}
@@ -0,0 +1,17 @@
use serde_derive::{Deserialize, Serialize};
use utoipa::ToSchema;
pub const CUSTOMER_PORTAL_CANCEL_PLAN_URL_PATH: &str = "/v1/stripe_artcraft/portal/cancel_plan";
#[derive(Serialize, Deserialize, ToSchema)]
pub struct StripeArtcraftCustomerPortalCancelPlanRequest {
// TODO: Not sure if this is needed
pub portal_config_id: Option<String>,
}
#[derive(Serialize, Deserialize, ToSchema)]
pub struct StripeArtcraftCustomerPortalCancelPlanResponse {
pub success: bool,
pub stripe_portal_url: String,
}
@@ -0,0 +1,17 @@
use serde_derive::{Deserialize, Serialize};
use utoipa::ToSchema;
pub const CUSTOMER_PORTAL_MANAGE_PLAN_URL_PATH: &str = "/v1/stripe_artcraft/portal/manage_plan";
#[derive(Serialize, Deserialize, ToSchema)]
pub struct StripeArtcraftCustomerPortalManagePlanRequest {
// TODO: Not sure if this is needed
pub portal_config_id: Option<String>,
}
#[derive(Serialize, Deserialize, ToSchema)]
pub struct StripeArtcraftCustomerPortalManagePlanResponse {
pub success: bool,
pub stripe_portal_url: String,
}
@@ -0,0 +1,37 @@
use enums::common::artcraft_subscription_slug::ArtcraftSubscriptionSlug;
use serde_derive::{Deserialize, Serialize};
use utoipa::ToSchema;
pub const CUSTOMER_PORTAL_SWITCH_PLAN_URL_PATH: &str = "/v1/stripe_artcraft/portal/switch_plan";
#[derive(Serialize, Deserialize, ToSchema)]
pub struct StripeArtcraftCustomerPortalSwitchPlanRequest {
// TODO: Not sure if this is needed
pub portal_config_id: Option<String>,
/// REQUIRED
/// The plan we're switching to.
pub plan: Option<ArtcraftSubscriptionSlug>,
/// REQUIRED
/// The cadence for the plan billing.
pub cadence: Option<PlanBillingCadenceConfirmation>,
}
#[derive(Serialize, Deserialize, ToSchema, Debug, Copy, Clone)]
pub enum PlanBillingCadenceConfirmation {
#[serde(rename = "monthly")]
Monthly,
#[serde(rename = "yearly")]
Yearly,
}
#[derive(Serialize, Deserialize, ToSchema)]
pub struct StripeArtcraftCustomerPortalSwitchPlanResponse {
pub success: bool,
pub stripe_portal_url: String,
}
@@ -0,0 +1,17 @@
use serde_derive::{Deserialize, Serialize};
use utoipa::ToSchema;
pub const CUSTOMER_PORTAL_UPDATE_PAYMENT_METHOD_URL_PATH: &str = "/v1/stripe_artcraft/portal/update_payment_method";
#[derive(Serialize, Deserialize, ToSchema)]
pub struct StripeArtcraftCustomerPortalUpdatePaymentMethodRequest {
// TODO: Not sure if this is needed
pub portal_config_id: Option<String>,
}
#[derive(Serialize, Deserialize, ToSchema)]
pub struct StripeArtcraftCustomerPortalUpdatePaymentMethodResponse {
pub success: bool,
pub stripe_portal_url: String,
}
@@ -0,0 +1,6 @@
pub mod create_credits_pack_checkout;
pub mod create_subscription_checkout;
pub mod customer_portal_cancel_plan;
pub mod customer_portal_manage_plan;
pub mod customer_portal_switch_plan;
pub mod customer_portal_update_payment_method;
@@ -0,0 +1,37 @@
use chrono::{DateTime, Utc};
use enums::common::payments_namespace::PaymentsNamespace;
use serde_derive::{Deserialize, Serialize};
use tokens::tokens::user_subscriptions::UserSubscriptionToken;
use utoipa::ToSchema;
// TODO: Maybe make "artcraft_subscription" or "fakeyou_subscription" with strongly typed slugs?
#[derive(Serialize, Deserialize, ToSchema)]
pub struct GetSessionSubscriptionResponse {
pub success: bool,
/// Information about the user's subscription, if any.
pub active_subscription: Option<SubscriptionInfo>,
}
#[derive(Serialize, Deserialize, ToSchema)]
pub struct SubscriptionInfo {
/// Unique token for the subscription.
pub subscription_token: UserSubscriptionToken,
/// Namespace for the subscription.
pub namespace: PaymentsNamespace,
/// Local key for the subscription.
pub product_slug: String,
/// If the subscription is currently active, this is the next billing date.
pub next_bill_at: Option<DateTime<Utc>>,
/// If the subscription is set to cancel, this is the end date of the subscription.
pub subscription_end_at: Option<DateTime<Utc>>,
///// When the current billing period ends (either
///// auto-renew/rebill date or auto-cancel/cancellation date).
//pub current_billing_period_end_at: DateTime<Utc>,
}
@@ -0,0 +1 @@
pub mod get_session_subscription;
@@ -0,0 +1,27 @@
use crate::credentials::storyteller_credential_set::StorytellerCredentialSet;
use crate::error::storyteller_error::StorytellerError;
use crate::utils::api_host::ApiHost;
use crate::utils::basic_json_get_request::basic_json_get_request;
use artcraft_api_defs::credits::get_session_credits::GetSessionCreditsResponse;
use enums::common::payments_namespace::PaymentsNamespace;
pub async fn get_session_credits(
api_host: &ApiHost,
maybe_creds: Option<&StorytellerCredentialSet>,
payments_namespace: PaymentsNamespace
) -> Result<GetSessionCreditsResponse, StorytellerError> {
let url_path = get_url_path(payments_namespace);
Ok(basic_json_get_request(
api_host,
&url_path,
maybe_creds,
).await?)
}
fn get_url_path(payments_namespace: PaymentsNamespace) -> String {
let payments_namespace = payments_namespace.to_str();
format!("/v1/credits/namespace/{}", payments_namespace)
}
@@ -0,0 +1 @@
pub mod get_session_credits;
@@ -1,10 +1,13 @@
//! An API client for Storyteller / FakeYou
pub mod credentials;
pub mod credits;
pub mod error;
pub mod generate;
pub mod jobs;
pub mod media_files;
pub mod prompts;
pub mod recipes;
pub mod stripe_artcraft;
pub mod subscriptions;
pub mod utils;
@@ -0,0 +1,18 @@
use crate::credentials::storyteller_credential_set::StorytellerCredentialSet;
use crate::error::storyteller_error::StorytellerError;
use crate::utils::api_host::ApiHost;
use crate::utils::basic_json_post_request::basic_json_post_request;
use artcraft_api_defs::stripe_artcraft::create_credits_pack_checkout::{StripeArtcraftCreateCreditsPackCheckoutRequest, StripeArtcraftCreateCreditsPackCheckoutResponse, CREATE_CREDITS_PACK_CHECKOUT_URL_PATH};
pub async fn create_credits_pack_checkout(
api_host: &ApiHost,
maybe_creds: Option<&StorytellerCredentialSet>,
request: StripeArtcraftCreateCreditsPackCheckoutRequest,
) -> Result<StripeArtcraftCreateCreditsPackCheckoutResponse, StorytellerError> {
Ok(basic_json_post_request(
api_host,
CREATE_CREDITS_PACK_CHECKOUT_URL_PATH,
maybe_creds,
request,
).await?)
}
@@ -0,0 +1,18 @@
use crate::credentials::storyteller_credential_set::StorytellerCredentialSet;
use crate::error::storyteller_error::StorytellerError;
use crate::utils::api_host::ApiHost;
use crate::utils::basic_json_post_request::basic_json_post_request;
use artcraft_api_defs::stripe_artcraft::create_subscription_checkout::{StripeArtcraftCreateSubscriptionCheckoutRequest, StripeArtcraftCreateSubscriptionCheckoutResponse, CREATE_SUBSCRIPTION_CHECKOUT_URL_PATH};
pub async fn create_subscription_checkout(
api_host: &ApiHost,
maybe_creds: Option<&StorytellerCredentialSet>,
request: StripeArtcraftCreateSubscriptionCheckoutRequest,
) -> Result<StripeArtcraftCreateSubscriptionCheckoutResponse, StorytellerError> {
Ok(basic_json_post_request(
api_host,
CREATE_SUBSCRIPTION_CHECKOUT_URL_PATH,
maybe_creds,
request,
).await?)
}
@@ -0,0 +1,18 @@
use crate::credentials::storyteller_credential_set::StorytellerCredentialSet;
use crate::error::storyteller_error::StorytellerError;
use crate::utils::api_host::ApiHost;
use crate::utils::basic_json_post_request::basic_json_post_request;
use artcraft_api_defs::stripe_artcraft::customer_portal_cancel_plan::{StripeArtcraftCustomerPortalCancelPlanRequest, StripeArtcraftCustomerPortalCancelPlanResponse, CUSTOMER_PORTAL_CANCEL_PLAN_URL_PATH};
pub async fn customer_portal_cancel_plan(
api_host: &ApiHost,
maybe_creds: Option<&StorytellerCredentialSet>,
request: StripeArtcraftCustomerPortalCancelPlanRequest,
) -> Result<StripeArtcraftCustomerPortalCancelPlanResponse, StorytellerError> {
Ok(basic_json_post_request(
api_host,
CUSTOMER_PORTAL_CANCEL_PLAN_URL_PATH,
maybe_creds,
request,
).await?)
}
@@ -0,0 +1,18 @@
use crate::credentials::storyteller_credential_set::StorytellerCredentialSet;
use crate::error::storyteller_error::StorytellerError;
use crate::utils::api_host::ApiHost;
use crate::utils::basic_json_post_request::basic_json_post_request;
use artcraft_api_defs::stripe_artcraft::customer_portal_manage_plan::{StripeArtcraftCustomerPortalManagePlanRequest, StripeArtcraftCustomerPortalManagePlanResponse, CUSTOMER_PORTAL_MANAGE_PLAN_URL_PATH};
pub async fn customer_portal_manage_plan(
api_host: &ApiHost,
maybe_creds: Option<&StorytellerCredentialSet>,
request: StripeArtcraftCustomerPortalManagePlanRequest,
) -> Result<StripeArtcraftCustomerPortalManagePlanResponse, StorytellerError> {
Ok(basic_json_post_request(
api_host,
CUSTOMER_PORTAL_MANAGE_PLAN_URL_PATH,
maybe_creds,
request,
).await?)
}
@@ -0,0 +1,18 @@
use crate::credentials::storyteller_credential_set::StorytellerCredentialSet;
use crate::error::storyteller_error::StorytellerError;
use crate::utils::api_host::ApiHost;
use crate::utils::basic_json_post_request::basic_json_post_request;
use artcraft_api_defs::stripe_artcraft::customer_portal_switch_plan::{StripeArtcraftCustomerPortalSwitchPlanRequest, StripeArtcraftCustomerPortalSwitchPlanResponse, CUSTOMER_PORTAL_SWITCH_PLAN_URL_PATH};
pub async fn customer_portal_switch_plan(
api_host: &ApiHost,
maybe_creds: Option<&StorytellerCredentialSet>,
request: StripeArtcraftCustomerPortalSwitchPlanRequest,
) -> Result<StripeArtcraftCustomerPortalSwitchPlanResponse, StorytellerError> {
Ok(basic_json_post_request(
api_host,
CUSTOMER_PORTAL_SWITCH_PLAN_URL_PATH,
maybe_creds,
request,
).await?)
}
@@ -0,0 +1,18 @@
use crate::credentials::storyteller_credential_set::StorytellerCredentialSet;
use crate::error::storyteller_error::StorytellerError;
use crate::utils::api_host::ApiHost;
use crate::utils::basic_json_post_request::basic_json_post_request;
use artcraft_api_defs::stripe_artcraft::customer_portal_update_payment_method::{StripeArtcraftCustomerPortalUpdatePaymentMethodRequest, StripeArtcraftCustomerPortalUpdatePaymentMethodResponse, CUSTOMER_PORTAL_UPDATE_PAYMENT_METHOD_URL_PATH};
pub async fn customer_portal_update_payment_method(
api_host: &ApiHost,
maybe_creds: Option<&StorytellerCredentialSet>,
request: StripeArtcraftCustomerPortalUpdatePaymentMethodRequest,
) -> Result<StripeArtcraftCustomerPortalUpdatePaymentMethodResponse, StorytellerError> {
Ok(basic_json_post_request(
api_host,
CUSTOMER_PORTAL_UPDATE_PAYMENT_METHOD_URL_PATH,
maybe_creds,
request,
).await?)
}
@@ -0,0 +1,6 @@
pub mod create_credits_pack_checkout;
pub mod create_subscription_checkout;
pub mod customer_portal_cancel_plan;
pub mod customer_portal_manage_plan;
pub mod customer_portal_switch_plan;
pub mod customer_portal_update_payment_method;
@@ -0,0 +1,28 @@
use crate::credentials::storyteller_credential_set::StorytellerCredentialSet;
use crate::error::storyteller_error::StorytellerError;
use crate::utils::api_host::ApiHost;
use crate::utils::basic_json_get_request::basic_json_get_request;
use artcraft_api_defs::subscriptions::get_session_subscription::GetSessionSubscriptionResponse;
use enums::common::payments_namespace::PaymentsNamespace;
use log::debug;
pub async fn get_session_subscription(
api_host: &ApiHost,
maybe_creds: Option<&StorytellerCredentialSet>,
payments_namespace: PaymentsNamespace
) -> Result<GetSessionSubscriptionResponse, StorytellerError> {
let url_path = get_url_path(api_host, payments_namespace);
debug!("Requesting {:?}", &url_path);
Ok(basic_json_get_request(
api_host,
&url_path,
maybe_creds,
).await?)
}
fn get_url_path(api_host: &ApiHost, payments_namespace: PaymentsNamespace) -> String {
let payments_namespace = payments_namespace.to_str();
format!("/v1/subscriptions/namespace/{}", payments_namespace)
}
@@ -0,0 +1 @@
pub mod get_session_subscription;
@@ -41,6 +41,7 @@ use storyteller_client::media_files::get_media_file::get_media_file;
use storyteller_client::utils::api_host::ApiHost;
use tauri::{AppHandle, Manager, State};
use tokens::tokens::media_files::MediaFileToken;
use crate::core::events::functional_events::credits_balance_changed_event::CreditsBalanceChangedEvent;
#[derive(Deserialize, Debug)]
pub struct EnqueueImageBgRemovalCommand {
@@ -152,6 +153,8 @@ pub async fn enqueue_image_bg_removal_command(
error!("Failed to emit event: {:?}", err); // Fail open.
}
CreditsBalanceChangedEvent{}.send_infallible(&app);
Ok(EnqueueImageBgRemovalSuccessResponse {}.into())
}
}
@@ -8,6 +8,7 @@ use crate::core::commands::response::failure_response_wrapper::{CommandErrorResp
use crate::core::commands::response::shorthand::{Response, ResponseOrErrorType};
use crate::core::commands::response::success_response_wrapper::SerializeMarker;
use crate::core::events::basic_sendable_event_trait::BasicSendableEvent;
use crate::core::events::functional_events::credits_balance_changed_event::CreditsBalanceChangedEvent;
use crate::core::events::generation_events::common::{GenerationAction, GenerationServiceProvider};
use crate::core::events::generation_events::generation_enqueue_failure_event::GenerationEnqueueFailureEvent;
use crate::core::events::generation_events::generation_enqueue_success_event::GenerationEnqueueSuccessEvent;
@@ -222,6 +223,8 @@ pub async fn enqueue_contextual_edit_image_command(
if let Err(err) = event.send(&app) {
error!("Failed to emit event: {:?}", err); // Fail open.
}
CreditsBalanceChangedEvent{}.send_infallible(&app);
Ok(EnqueueContextualEditImageSuccessResponse {}.into())
}
@@ -10,6 +10,7 @@ use crate::core::commands::response::failure_response_wrapper::{CommandErrorResp
use crate::core::commands::response::shorthand::{Response, ResponseOrErrorType};
use crate::core::commands::response::success_response_wrapper::SerializeMarker;
use crate::core::events::basic_sendable_event_trait::BasicSendableEvent;
use crate::core::events::functional_events::credits_balance_changed_event::CreditsBalanceChangedEvent;
use crate::core::events::generation_events::common::{GenerationAction, GenerationServiceProvider};
use crate::core::events::generation_events::generation_enqueue_failure_event::GenerationEnqueueFailureEvent;
use crate::core::events::generation_events::generation_enqueue_success_event::GenerationEnqueueSuccessEvent;
@@ -212,6 +213,8 @@ pub async fn enqueue_image_inpaint_command(
error!("Failed to emit event: {:?}", err); // Fail open.
}
CreditsBalanceChangedEvent{}.send_infallible(&app);
Ok(EnqueueImageInpaintSuccessResponse {}.into())
}
}
@@ -6,6 +6,7 @@ use crate::core::commands::response::failure_response_wrapper::{CommandErrorResp
use crate::core::commands::response::shorthand::Response;
use crate::core::commands::response::success_response_wrapper::SerializeMarker;
use crate::core::events::basic_sendable_event_trait::BasicSendableEvent;
use crate::core::events::functional_events::credits_balance_changed_event::CreditsBalanceChangedEvent;
use crate::core::events::generation_events::generation_enqueue_success_event::GenerationEnqueueSuccessEvent;
use crate::core::state::app_env_configs::app_env_configs::AppEnvConfigs;
use crate::core::state::data_dir::app_data_root::AppDataRoot;
@@ -146,6 +147,8 @@ pub async fn enqueue_image_to_3d_object_command(
error!("Failed to emit event: {:?}", err); // Fail open.
}
CreditsBalanceChangedEvent{}.send_infallible(&app);
Ok(EnqueueImageTo3dObjectSuccessResponse {}.into())
}
}
@@ -6,6 +6,7 @@ use crate::core::commands::response::failure_response_wrapper::{CommandErrorResp
use crate::core::commands::response::shorthand::Response;
use crate::core::commands::response::success_response_wrapper::SerializeMarker;
use crate::core::events::basic_sendable_event_trait::BasicSendableEvent;
use crate::core::events::functional_events::credits_balance_changed_event::CreditsBalanceChangedEvent;
use crate::core::events::generation_events::generation_enqueue_success_event::GenerationEnqueueSuccessEvent;
use crate::core::state::app_env_configs::app_env_configs::AppEnvConfigs;
use crate::core::state::data_dir::app_data_root::AppDataRoot;
@@ -165,6 +166,8 @@ pub async fn enqueue_image_to_video_command(
if let Err(err) = event.send(&app) {
error!("Failed to emit event: {:?}", err); // Fail open.
}
CreditsBalanceChangedEvent{}.send_infallible(&app);
Ok(EnqueueImageToVideoSuccessResponse {}.into())
}
@@ -11,6 +11,7 @@ use crate::core::commands::response::failure_response_wrapper::{CommandErrorResp
use crate::core::commands::response::shorthand::Response;
use crate::core::commands::response::success_response_wrapper::SerializeMarker;
use crate::core::events::basic_sendable_event_trait::BasicSendableEvent;
use crate::core::events::functional_events::credits_balance_changed_event::CreditsBalanceChangedEvent;
use crate::core::events::generation_events::common::{GenerationAction, GenerationServiceProvider};
use crate::core::events::generation_events::generation_enqueue_success_event::GenerationEnqueueSuccessEvent;
use crate::core::events::sendable_event_trait::SendableEvent;
@@ -216,6 +217,8 @@ pub async fn enqueue_text_to_image_command(
if let Err(err) = event.send(&app) {
error!("Failed to emit event: {:?}", err); // Fail open.
}
CreditsBalanceChangedEvent{}.send_infallible(&app);
Ok(EnqueueTextToImageSuccessResponse {}.into())
}
@@ -40,3 +40,14 @@ impl From<&str> for CommandErrorResponseWrapper<(), ()> {
}
}
}
impl From<String> for CommandErrorResponseWrapper<(), ()> {
fn from(value: String) -> Self {
CommandErrorResponseWrapper {
status: CommandErrorStatus::BadRequest, // NB: Default to 500 error.
error_message: Some(value),
error_type: None,
error_details: None,
}
}
}
@@ -0,0 +1,17 @@
use crate::core::events::basic_sendable_event_trait::{BasicEventStatus, BasicSendableEvent};
use enums::tauri::ux::tauri_event_name::TauriEventName;
use serde_derive::Serialize;
use tokens::tokens::media_files::MediaFileToken;
use url::Url;
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct CreditsBalanceChangedEvent {
// NB: We don't know how much was added or removed, just that it changed.
// The frontend should re-query the balance
}
impl BasicSendableEvent for CreditsBalanceChangedEvent {
const FRONTEND_EVENT_NAME: TauriEventName = TauriEventName::CreditsBalanceChangedEvent;
const EVENT_STATUS: BasicEventStatus = BasicEventStatus::Success;
}
@@ -1,6 +1,8 @@
pub mod canvas_background_removal_complete_event;
pub mod credits_balance_changed_event;
pub mod image_edit_complete_event;
pub mod refresh_account_state_event;
pub mod show_provider_billing_modal_event;
pub mod show_provider_login_modal_event;
pub mod subscription_plan_changed_event;
pub mod text_to_image_generation_complete_event;
@@ -0,0 +1,18 @@
use crate::core::events::basic_sendable_event_trait::{BasicEventStatus, BasicSendableEvent};
use enums::tauri::ux::tauri_event_name::TauriEventName;
use serde_derive::Serialize;
use tokens::tokens::media_files::MediaFileToken;
use url::Url;
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct SubscriptionPlanChangedEvent {
// NB: We don't know what plan was changed (subscribed, upgraded, canceled, etc.),
// just that it changed. The actual fulfillment is async anyway.
// The frontend should re-query the subscription plan after a short delay.
}
impl BasicSendableEvent for SubscriptionPlanChangedEvent {
const FRONTEND_EVENT_NAME: TauriEventName = TauriEventName::SubscriptionPlanChangedEvent;
const EVENT_STATUS: BasicEventStatus = BasicEventStatus::Success;
}
+52 -32
View File
@@ -45,6 +45,14 @@ use crate::services::sora::commands::sora_logout_command::sora_logout_command;
use crate::services::sora::state::sora_credential_manager::SoraCredentialManager;
use crate::services::sora::state::sora_task_queue::SoraTaskQueue;
use crate::services::sora::threads::sora_task_polling_thread::sora_task_polling_thread;
use crate::services::storyteller::commands::storyteller_get_credits_command::storyteller_get_credits_command;
use crate::services::storyteller::commands::storyteller_get_subscription_command::storyteller_get_subscription_command;
use crate::services::storyteller::commands::stripe_checkout::storyteller_open_credits_purchase_command::storyteller_open_credits_purchase_command;
use crate::services::storyteller::commands::stripe_checkout::storyteller_open_subscription_purchase_command::storyteller_open_subscription_purchase_command;
use crate::services::storyteller::commands::stripe_customer_portal::storyteller_open_customer_portal_cancel_plan_command::storyteller_open_customer_portal_cancel_plan_command;
use crate::services::storyteller::commands::stripe_customer_portal::storyteller_open_customer_portal_manage_plan_command::storyteller_open_customer_portal_manage_plan_command;
use crate::services::storyteller::commands::stripe_customer_portal::storyteller_open_customer_portal_switch_plan_command::storyteller_open_customer_portal_switch_plan_command;
use crate::services::storyteller::commands::stripe_customer_portal::storyteller_open_customer_portal_update_payment_method_command::storyteller_open_customer_portal_update_payment_method_command;
use crate::services::storyteller::state::storyteller_credential_manager::StorytellerCredentialManager;
use log::error;
@@ -96,7 +104,7 @@ pub fn run() {
println!("Initializing backend runtime...");
tauri::Builder::default()
let builder = tauri::Builder::default()
.plugin(tauri_plugin_dialog::init())
.plugin(tauri_plugin_http::init())
.plugin(tauri_plugin_upload::init())
@@ -152,36 +160,48 @@ pub fn run() {
.manage(midjourney_creds_manager)
.manage(sora_creds_manager)
.manage(sora_task_queue)
.manage(storyteller_creds_manager_3)
.invoke_handler(tauri::generate_handler![
check_sora_session_command,
enqueue_contextual_edit_image_command,
enqueue_image_bg_removal_command,
enqueue_image_inpaint_command,
enqueue_image_to_3d_object_command,
enqueue_image_to_video_command,
enqueue_text_to_image_command,
fal_background_removal_command,
fal_hunyuan_image_to_3d_command,
fal_kling_image_to_video_command,
flip_image,
get_app_info_command,
get_app_preferences_command,
get_fal_api_key_command,
get_provider_order_command,
load_without_cors_command,
open_sora_login_command,
midjourney_clear_credentials_command,
midjourney_get_credential_info_command,
midjourney_open_login_command,
platform_info_command,
set_fal_api_key_command,
set_provider_order_command,
sora_image_generation_command,
sora_image_remix_command,
sora_logout_command,
update_app_preferences_command,
])
.run(tauri::generate_context!("tauri.conf.json"))
.manage(storyteller_creds_manager_3);
// TODO: Break this out into another module, because RustRover/IntelliJ lags with these macros.
// My first attempt at naively doing this didn't work because the macros can't find their codegen'd targets.
let builder = builder.invoke_handler(tauri::generate_handler![
check_sora_session_command,
enqueue_contextual_edit_image_command,
enqueue_image_bg_removal_command,
enqueue_image_inpaint_command,
enqueue_image_to_3d_object_command,
enqueue_image_to_video_command,
enqueue_text_to_image_command,
fal_background_removal_command,
fal_hunyuan_image_to_3d_command,
fal_kling_image_to_video_command,
flip_image,
get_app_info_command,
get_app_preferences_command,
get_fal_api_key_command,
get_provider_order_command,
load_without_cors_command,
midjourney_clear_credentials_command,
midjourney_get_credential_info_command,
midjourney_open_login_command,
open_sora_login_command,
platform_info_command,
set_fal_api_key_command,
set_provider_order_command,
sora_image_generation_command,
sora_image_remix_command,
sora_logout_command,
storyteller_get_credits_command,
storyteller_get_subscription_command,
storyteller_open_credits_purchase_command,
storyteller_open_customer_portal_cancel_plan_command,
storyteller_open_customer_portal_manage_plan_command,
storyteller_open_customer_portal_switch_plan_command,
storyteller_open_customer_portal_update_payment_method_command,
storyteller_open_subscription_purchase_command,
update_app_preferences_command,
]);
builder.run(tauri::generate_context!("tauri.conf.json"))
.expect("error while running tauri application");
}
@@ -0,0 +1,4 @@
pub mod storyteller_get_credits_command;
pub mod storyteller_get_subscription_command;
pub mod stripe_checkout;
pub mod stripe_customer_portal;
@@ -0,0 +1,74 @@
use crate::core::commands::enqueue::image_edit::enqueue_contextual_edit_image_command::{ContextualImageEditModel, EditImageQuality, EditImageSize};
use crate::core::commands::response::shorthand::ResponseOrErrorMessage;
use crate::core::state::app_env_configs::app_env_configs::AppEnvConfigs;
use crate::core::state::data_dir::app_data_root::AppDataRoot;
use crate::core::state::provider_priority::Provider;
use crate::services::midjourney::state::midjourney_credential_manager::MidjourneyCredentialManager;
use crate::services::midjourney::windows::open_midjourney_login_window::open_midjourney_login_window;
use crate::services::sora::windows::sora_login_window::open_sora_login_window::open_sora_login_window;
use crate::services::storyteller::state::storyteller_credential_manager::StorytellerCredentialManager;
use crate::services::storyteller::windows::open_storyteller_billing_window::{open_storyteller_billing_window, OpenStorytellerBillingWindowArgs, BillingWindowCase};
use artcraft_api_defs::stripe_artcraft::create_subscription_checkout::PlanBillingCadence;
use enums::common::artcraft_credits_pack_slug::ArtcraftCreditsPackSlug;
use enums::common::artcraft_subscription_slug::ArtcraftSubscriptionSlug;
use enums::common::payments_namespace::PaymentsNamespace;
use enums::tauri::ux::tauri_command_caller::TauriCommandCaller;
use errors::AnyhowResult;
use log::{error, info};
use serde_derive::{Deserialize, Serialize};
use storyteller_client::credits::get_session_credits::get_session_credits;
use tauri::{AppHandle, State};
use crate::core::commands::providers::get_provider_order_command::GetProviderOrderResponse;
use crate::core::commands::response::success_response_wrapper::SerializeMarker;
// TODO(bt,2025-09-12): Cache credits and clear cache on generate calls.
#[derive(Serialize)]
pub struct GetCreditsResponse {
pub free_credits: u64,
pub monthly_credits: u64,
pub banked_credits: u64,
pub sum_total_credits: u64,
}
impl SerializeMarker for GetCreditsResponse {}
#[tauri::command]
pub async fn storyteller_get_credits_command(
app_env_configs: State<'_, AppEnvConfigs>,
storyteller_creds_manager: State<'_, StorytellerCredentialManager>,
) -> ResponseOrErrorMessage<GetCreditsResponse> {
info!("storyteller_get_credits_command called");
let credits = get_credits(
&app_env_configs,
&storyteller_creds_manager)
.await
.map_err(|err| {
error!("Error getting credits: {:?}", err);
format!("Error getting credits: {:?}", err)
})?;
Ok(credits.into())
}
async fn get_credits(
app_env_configs: &AppEnvConfigs,
storyteller_creds_manager: &StorytellerCredentialManager,
) -> AnyhowResult<GetCreditsResponse> {
let maybe_creds = storyteller_creds_manager.get_credentials()?;
let response = get_session_credits(
&app_env_configs.storyteller_host,
maybe_creds.as_ref(),
PaymentsNamespace::Artcraft,
).await?;
Ok(GetCreditsResponse {
free_credits: response.free_credits,
monthly_credits: response.monthly_credits,
banked_credits: response.banked_credits,
sum_total_credits: response.sum_total_credits,
})
}

Some files were not shown because too many files have changed in this diff Show More