Merge pull request 'feat: load billing adapters' (#125) from load-billing-adapter into master
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
Reviewed-on: #125
This commit is contained in:
commit
d801894b0f
229 changed files with 11490 additions and 522 deletions
1
.gitignore
vendored
1
.gitignore
vendored
|
@ -9,3 +9,4 @@ devenv.local.nix
|
|||
|
||||
# pre-commit
|
||||
.pre-commit-config.yaml
|
||||
rustc-ice-*.txt
|
||||
|
|
|
@ -0,0 +1,19 @@
|
|||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "INSERT INTO cqrs_identity_store_query (\n version, name, address, store_id, owner, deleted\n ) VALUES (\n $1, $2, $3, $4, $5, $6\n );",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Int8",
|
||||
"Text",
|
||||
"Text",
|
||||
"Uuid",
|
||||
"Uuid",
|
||||
"Bool"
|
||||
]
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "7c8fdc12c2a80c166d1696913273cb7da1a5ffefa1b09705eb4ba8abe94ae135"
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "SELECT EXISTS (\n SELECT 1\n FROM cqrs_identity_store_query\n WHERE\n name = $1\n AND\n deleted = false\n );",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "exists",
|
||||
"type_info": "Bool"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Text"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
null
|
||||
]
|
||||
},
|
||||
"hash": "840678753d65298539ef0a07bf7ea24f735604de370130c8752f6e64b0a39659"
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "SELECT EXISTS (\n SELECT 1\n FROM cqrs_identity_store_query\n WHERE\n store_id = $1\n );",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "exists",
|
||||
"type_info": "Bool"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Uuid"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
null
|
||||
]
|
||||
},
|
||||
"hash": "a02ae03e94d928feece2996fbd344ddf4b1459c1487ed7dffd57fb5ea7cf97aa"
|
||||
}
|
|
@ -0,0 +1,46 @@
|
|||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "SELECT \n name, address, store_id, owner, deleted\n FROM\n cqrs_identity_store_query\n WHERE\n store_id = $1;",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "name",
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"ordinal": 1,
|
||||
"name": "address",
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"ordinal": 2,
|
||||
"name": "store_id",
|
||||
"type_info": "Uuid"
|
||||
},
|
||||
{
|
||||
"ordinal": 3,
|
||||
"name": "owner",
|
||||
"type_info": "Uuid"
|
||||
},
|
||||
{
|
||||
"ordinal": 4,
|
||||
"name": "deleted",
|
||||
"type_info": "Bool"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Uuid"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "a5b2bc2a46dfc083c6dc9b12945ac9eb5204f79e1742b827cfb1048f061351df"
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "SELECT \n store_id, version\n FROM\n cqrs_identity_store_query\n WHERE\n store_id = $1;",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "store_id",
|
||||
"type_info": "Uuid"
|
||||
},
|
||||
{
|
||||
"ordinal": 1,
|
||||
"name": "version",
|
||||
"type_info": "Int8"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Uuid"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "aa9219ef478854cc7e2afad1e80a5d5a49d01bc8c44e578baad926f5f163c0d2"
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "UPDATE\n cqrs_identity_store_query\n SET\n version = $1,\n name = $2,\n address = $3,\n owner = $4,\n deleted = $5;",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Int8",
|
||||
"Text",
|
||||
"Text",
|
||||
"Uuid",
|
||||
"Bool"
|
||||
]
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "b640ed9c2d601b3a78f3cac4b9a4c0c23a5cc8a7d51a270bdab73182b12e204c"
|
||||
}
|
515
Cargo.lock
generated
515
Cargo.lock
generated
File diff suppressed because it is too large
Load diff
|
@ -5,7 +5,7 @@ edition = "2021"
|
|||
|
||||
[workspace]
|
||||
exclude = ["utils/db-migrations"] #, "utils/cache-bust"]
|
||||
members = [".", "mailpit_client"]
|
||||
members = [".", "mailpit_client", "twilio_client", "web_ui"]
|
||||
|
||||
[dependencies]
|
||||
actix-identity = "0.8.0"
|
||||
|
@ -36,7 +36,9 @@ tracing = { version = "0.1.40", features = ["log"] }
|
|||
tracing-actix-web = "0.7.10"
|
||||
url = { version = "2.5.0", features = ["serde"] }
|
||||
uuid = { version = "1.10.0", features = ["v4", "serde"] }
|
||||
validator = { version = "0.18.1", features = ["derive"] }
|
||||
validator = { version = "0.19.0", features = ["derive"] }
|
||||
twilio_client = { path = "./twilio_client" }
|
||||
web_ui = { path = "./web_ui" }
|
||||
|
||||
[dev-dependencies]
|
||||
#reqwest = { version = "0.12.4", features = ["json"] }
|
||||
|
|
4
Makefile
4
Makefile
|
@ -96,6 +96,10 @@ test: ## Run tests
|
|||
--all-features \
|
||||
--no-fail-fast -- --skip test_server_env_override \
|
||||
--skip test_meili_env_override
|
||||
cd ./twilio_client && cargo test --all-features \
|
||||
--no-fail-fast
|
||||
cd ./web_ui && cargo test --all-features \
|
||||
--no-fail-fast
|
||||
cargo test --all-features \
|
||||
--no-fail-fast -- test_server_env_override test_meili_env_override
|
||||
|
||||
|
|
|
@ -33,3 +33,8 @@ reply_to="Vanikam Support <vanikam@example.com>"
|
|||
[meili]
|
||||
#url = "http://localhost:7700"
|
||||
#api_key = ""
|
||||
|
||||
|
||||
[phone]
|
||||
twilio_account_id = ""
|
||||
twilio_auth_token = ""
|
||||
|
|
16
migrations/20241223105314_cqrs_identity_store_query.sql.sql
Normal file
16
migrations/20241223105314_cqrs_identity_store_query.sql.sql
Normal file
|
@ -0,0 +1,16 @@
|
|||
--- SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
|
||||
--
|
||||
-- SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
CREATE TABLE IF NOT EXISTS cqrs_identity_store_query
|
||||
(
|
||||
version bigint CHECK (version >= 0) NOT NULL,
|
||||
|
||||
name TEXT NOT NULL,
|
||||
address TEXT,
|
||||
owner UUID NOT NULL,
|
||||
store_id UUID NOT NULL UNIQUE,
|
||||
deleted BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
|
||||
PRIMARY KEY (store_id)
|
||||
);
|
|
@ -1,37 +0,0 @@
|
|||
thread 'rustc' panicked at compiler/rustc_middle/src/query/on_disk_cache.rs:736:21:
|
||||
Failed to convert DefPathHash DefPathHash(Fingerprint(9597590199268592635, 17791879502897349522))
|
||||
stack backtrace:
|
||||
0: 0x7fbfbb48d025 - std::backtrace::Backtrace::create::hbc256ff4bc983c0b
|
||||
1: 0x7fbfb9c8c865 - std::backtrace::Backtrace::force_capture::h1ebb6042c5b424a8
|
||||
2: 0x7fbfb8db2217 - std[11ac8361619e45fd]::panicking::update_hook::<alloc[1ed43557cf619c2]::boxed::Box<rustc_driver_impl[8c32a9dec5e4d0f0]::install_ice_hook::{closure#0}>>::{closure#0}
|
||||
3: 0x7fbfb9ca3ee8 - std::panicking::rust_panic_with_hook::ha6cfc51100acb1ab
|
||||
4: 0x7fbfb9ca3cb7 - std::panicking::begin_panic_handler::{{closure}}::he56e1efe5ba67ce1
|
||||
5: 0x7fbfb9ca1699 - std::sys::backtrace::__rust_end_short_backtrace::hcc7bf1345a5f7ae3
|
||||
6: 0x7fbfb9ca3984 - rust_begin_unwind
|
||||
7: 0x7fbfb6ad55c3 - core::panicking::panic_fmt::h146c2ef4416c8c7b
|
||||
8: 0x7fbfba61abc5 - <rustc_middle[62c17eb200ed25ef]::query::on_disk_cache::CacheDecoder as rustc_span[e2902ef3f031f316]::SpanDecoder>::decode_span
|
||||
9: 0x7fbfba94bc1c - rustc_query_system[4b3461eb5f3eee8]::query::plumbing::try_execute_query::<rustc_query_impl[2b1ee272ecafb82c]::DynamicConfig<rustc_query_system[4b3461eb5f3eee8]::query::caches::DefIdCache<rustc_middle[62c17eb200ed25ef]::query::erase::Erased<[u8; 8usize]>>, false, false, false>, rustc_query_impl[2b1ee272ecafb82c]::plumbing::QueryCtxt, true>
|
||||
10: 0x7fbfba94929a - rustc_query_impl[2b1ee272ecafb82c]::query_impl::def_span::get_query_incr::__rust_end_short_backtrace
|
||||
11: 0x7fbfbaa190c0 - rustc_middle[62c17eb200ed25ef]::query::plumbing::query_get_at::<rustc_query_system[4b3461eb5f3eee8]::query::caches::DefIdCache<rustc_middle[62c17eb200ed25ef]::query::erase::Erased<[u8; 8usize]>>>
|
||||
12: 0x7fbfbacaaf7d - <rustc_hir_analysis[198913e0276c9380]::coherence::inherent_impls_overlap::InherentOverlapChecker>::check_for_duplicate_items_in_impl
|
||||
13: 0x7fbfbb39e280 - rustc_hir_analysis[198913e0276c9380]::coherence::inherent_impls_overlap::crate_inherent_impls_overlap_check
|
||||
14: 0x7fbfbb39dc6d - rustc_query_impl[2b1ee272ecafb82c]::plumbing::__rust_begin_short_backtrace::<rustc_query_impl[2b1ee272ecafb82c]::query_impl::crate_inherent_impls_overlap_check::dynamic_query::{closure#2}::{closure#0}, rustc_middle[62c17eb200ed25ef]::query::erase::Erased<[u8; 1usize]>>
|
||||
15: 0x7fbfbb39d1fd - rustc_query_system[4b3461eb5f3eee8]::query::plumbing::try_execute_query::<rustc_query_impl[2b1ee272ecafb82c]::DynamicConfig<rustc_query_system[4b3461eb5f3eee8]::query::caches::SingleCache<rustc_middle[62c17eb200ed25ef]::query::erase::Erased<[u8; 1usize]>>, false, false, false>, rustc_query_impl[2b1ee272ecafb82c]::plumbing::QueryCtxt, true>
|
||||
16: 0x7fbfbb39c867 - rustc_query_impl[2b1ee272ecafb82c]::query_impl::crate_inherent_impls_overlap_check::get_query_incr::__rust_end_short_backtrace
|
||||
17: 0x7fbfba5bb6f3 - rustc_hir_analysis[198913e0276c9380]::check_crate
|
||||
18: 0x7fbfba5b1351 - rustc_interface[d7e86b952eb641e5]::passes::run_required_analyses
|
||||
19: 0x7fbfbb1bac1e - rustc_interface[d7e86b952eb641e5]::passes::analysis
|
||||
20: 0x7fbfbb1babf1 - rustc_query_impl[2b1ee272ecafb82c]::plumbing::__rust_begin_short_backtrace::<rustc_query_impl[2b1ee272ecafb82c]::query_impl::analysis::dynamic_query::{closure#2}::{closure#0}, rustc_middle[62c17eb200ed25ef]::query::erase::Erased<[u8; 1usize]>>
|
||||
21: 0x7fbfbb39cecd - rustc_query_system[4b3461eb5f3eee8]::query::plumbing::try_execute_query::<rustc_query_impl[2b1ee272ecafb82c]::DynamicConfig<rustc_query_system[4b3461eb5f3eee8]::query::caches::SingleCache<rustc_middle[62c17eb200ed25ef]::query::erase::Erased<[u8; 1usize]>>, false, false, false>, rustc_query_impl[2b1ee272ecafb82c]::plumbing::QueryCtxt, true>
|
||||
22: 0x7fbfbb39cb7a - rustc_query_impl[2b1ee272ecafb82c]::query_impl::analysis::get_query_incr::__rust_end_short_backtrace
|
||||
23: 0x7fbfbb1b30bc - rustc_interface[d7e86b952eb641e5]::interface::run_compiler::<core[dcc560a250502550]::result::Result<(), rustc_span[e2902ef3f031f316]::ErrorGuaranteed>, rustc_driver_impl[8c32a9dec5e4d0f0]::run_compiler::{closure#0}>::{closure#1}
|
||||
24: 0x7fbfbb2c0504 - std[11ac8361619e45fd]::sys::backtrace::__rust_begin_short_backtrace::<rustc_interface[d7e86b952eb641e5]::util::run_in_thread_with_globals<rustc_interface[d7e86b952eb641e5]::util::run_in_thread_pool_with_globals<rustc_interface[d7e86b952eb641e5]::interface::run_compiler<core[dcc560a250502550]::result::Result<(), rustc_span[e2902ef3f031f316]::ErrorGuaranteed>, rustc_driver_impl[8c32a9dec5e4d0f0]::run_compiler::{closure#0}>::{closure#1}, core[dcc560a250502550]::result::Result<(), rustc_span[e2902ef3f031f316]::ErrorGuaranteed>>::{closure#0}, core[dcc560a250502550]::result::Result<(), rustc_span[e2902ef3f031f316]::ErrorGuaranteed>>::{closure#0}::{closure#0}, core[dcc560a250502550]::result::Result<(), rustc_span[e2902ef3f031f316]::ErrorGuaranteed>>
|
||||
25: 0x7fbfbb2c0b70 - <<std[11ac8361619e45fd]::thread::Builder>::spawn_unchecked_<rustc_interface[d7e86b952eb641e5]::util::run_in_thread_with_globals<rustc_interface[d7e86b952eb641e5]::util::run_in_thread_pool_with_globals<rustc_interface[d7e86b952eb641e5]::interface::run_compiler<core[dcc560a250502550]::result::Result<(), rustc_span[e2902ef3f031f316]::ErrorGuaranteed>, rustc_driver_impl[8c32a9dec5e4d0f0]::run_compiler::{closure#0}>::{closure#1}, core[dcc560a250502550]::result::Result<(), rustc_span[e2902ef3f031f316]::ErrorGuaranteed>>::{closure#0}, core[dcc560a250502550]::result::Result<(), rustc_span[e2902ef3f031f316]::ErrorGuaranteed>>::{closure#0}::{closure#0}, core[dcc560a250502550]::result::Result<(), rustc_span[e2902ef3f031f316]::ErrorGuaranteed>>::{closure#1} as core[dcc560a250502550]::ops::function::FnOnce<()>>::call_once::{shim:vtable#0}
|
||||
26: 0x7fbfbb2c0f6b - std::sys::pal::unix::thread::Thread::new::thread_start::h1921d0f3a7850262
|
||||
27: 0x7fbfbcbf8272 - start_thread
|
||||
28: 0x7fbfbcc73dcc - clone3
|
||||
29: 0x0 - <unknown>
|
||||
|
||||
|
||||
rustc version: 1.83.0-nightly (0ee7cb5e3 2024-09-10)
|
||||
platform: x86_64-unknown-linux-gnu
|
|
@ -1,37 +0,0 @@
|
|||
thread 'rustc' panicked at compiler/rustc_middle/src/query/on_disk_cache.rs:736:21:
|
||||
Failed to convert DefPathHash DefPathHash(Fingerprint(9597590199268592635, 17791879502897349522))
|
||||
stack backtrace:
|
||||
0: 0x77c2cca8d025 - std::backtrace::Backtrace::create::hbc256ff4bc983c0b
|
||||
1: 0x77c2cb28c865 - std::backtrace::Backtrace::force_capture::h1ebb6042c5b424a8
|
||||
2: 0x77c2ca3b2217 - std[11ac8361619e45fd]::panicking::update_hook::<alloc[1ed43557cf619c2]::boxed::Box<rustc_driver_impl[8c32a9dec5e4d0f0]::install_ice_hook::{closure#0}>>::{closure#0}
|
||||
3: 0x77c2cb2a3ee8 - std::panicking::rust_panic_with_hook::ha6cfc51100acb1ab
|
||||
4: 0x77c2cb2a3cb7 - std::panicking::begin_panic_handler::{{closure}}::he56e1efe5ba67ce1
|
||||
5: 0x77c2cb2a1699 - std::sys::backtrace::__rust_end_short_backtrace::hcc7bf1345a5f7ae3
|
||||
6: 0x77c2cb2a3984 - rust_begin_unwind
|
||||
7: 0x77c2c80d55c3 - core::panicking::panic_fmt::h146c2ef4416c8c7b
|
||||
8: 0x77c2cbc1abc5 - <rustc_middle[62c17eb200ed25ef]::query::on_disk_cache::CacheDecoder as rustc_span[e2902ef3f031f316]::SpanDecoder>::decode_span
|
||||
9: 0x77c2cbf4bc1c - rustc_query_system[4b3461eb5f3eee8]::query::plumbing::try_execute_query::<rustc_query_impl[2b1ee272ecafb82c]::DynamicConfig<rustc_query_system[4b3461eb5f3eee8]::query::caches::DefIdCache<rustc_middle[62c17eb200ed25ef]::query::erase::Erased<[u8; 8usize]>>, false, false, false>, rustc_query_impl[2b1ee272ecafb82c]::plumbing::QueryCtxt, true>
|
||||
10: 0x77c2cbf4929a - rustc_query_impl[2b1ee272ecafb82c]::query_impl::def_span::get_query_incr::__rust_end_short_backtrace
|
||||
11: 0x77c2cc0190c0 - rustc_middle[62c17eb200ed25ef]::query::plumbing::query_get_at::<rustc_query_system[4b3461eb5f3eee8]::query::caches::DefIdCache<rustc_middle[62c17eb200ed25ef]::query::erase::Erased<[u8; 8usize]>>>
|
||||
12: 0x77c2cc2aaf7d - <rustc_hir_analysis[198913e0276c9380]::coherence::inherent_impls_overlap::InherentOverlapChecker>::check_for_duplicate_items_in_impl
|
||||
13: 0x77c2cc99e280 - rustc_hir_analysis[198913e0276c9380]::coherence::inherent_impls_overlap::crate_inherent_impls_overlap_check
|
||||
14: 0x77c2cc99dc6d - rustc_query_impl[2b1ee272ecafb82c]::plumbing::__rust_begin_short_backtrace::<rustc_query_impl[2b1ee272ecafb82c]::query_impl::crate_inherent_impls_overlap_check::dynamic_query::{closure#2}::{closure#0}, rustc_middle[62c17eb200ed25ef]::query::erase::Erased<[u8; 1usize]>>
|
||||
15: 0x77c2cc99d1fd - rustc_query_system[4b3461eb5f3eee8]::query::plumbing::try_execute_query::<rustc_query_impl[2b1ee272ecafb82c]::DynamicConfig<rustc_query_system[4b3461eb5f3eee8]::query::caches::SingleCache<rustc_middle[62c17eb200ed25ef]::query::erase::Erased<[u8; 1usize]>>, false, false, false>, rustc_query_impl[2b1ee272ecafb82c]::plumbing::QueryCtxt, true>
|
||||
16: 0x77c2cc99c867 - rustc_query_impl[2b1ee272ecafb82c]::query_impl::crate_inherent_impls_overlap_check::get_query_incr::__rust_end_short_backtrace
|
||||
17: 0x77c2cbbbb6f3 - rustc_hir_analysis[198913e0276c9380]::check_crate
|
||||
18: 0x77c2cbbb1351 - rustc_interface[d7e86b952eb641e5]::passes::run_required_analyses
|
||||
19: 0x77c2cc7bac1e - rustc_interface[d7e86b952eb641e5]::passes::analysis
|
||||
20: 0x77c2cc7babf1 - rustc_query_impl[2b1ee272ecafb82c]::plumbing::__rust_begin_short_backtrace::<rustc_query_impl[2b1ee272ecafb82c]::query_impl::analysis::dynamic_query::{closure#2}::{closure#0}, rustc_middle[62c17eb200ed25ef]::query::erase::Erased<[u8; 1usize]>>
|
||||
21: 0x77c2cc99cecd - rustc_query_system[4b3461eb5f3eee8]::query::plumbing::try_execute_query::<rustc_query_impl[2b1ee272ecafb82c]::DynamicConfig<rustc_query_system[4b3461eb5f3eee8]::query::caches::SingleCache<rustc_middle[62c17eb200ed25ef]::query::erase::Erased<[u8; 1usize]>>, false, false, false>, rustc_query_impl[2b1ee272ecafb82c]::plumbing::QueryCtxt, true>
|
||||
22: 0x77c2cc99cb7a - rustc_query_impl[2b1ee272ecafb82c]::query_impl::analysis::get_query_incr::__rust_end_short_backtrace
|
||||
23: 0x77c2cc7b30bc - rustc_interface[d7e86b952eb641e5]::interface::run_compiler::<core[dcc560a250502550]::result::Result<(), rustc_span[e2902ef3f031f316]::ErrorGuaranteed>, rustc_driver_impl[8c32a9dec5e4d0f0]::run_compiler::{closure#0}>::{closure#1}
|
||||
24: 0x77c2cc8c0504 - std[11ac8361619e45fd]::sys::backtrace::__rust_begin_short_backtrace::<rustc_interface[d7e86b952eb641e5]::util::run_in_thread_with_globals<rustc_interface[d7e86b952eb641e5]::util::run_in_thread_pool_with_globals<rustc_interface[d7e86b952eb641e5]::interface::run_compiler<core[dcc560a250502550]::result::Result<(), rustc_span[e2902ef3f031f316]::ErrorGuaranteed>, rustc_driver_impl[8c32a9dec5e4d0f0]::run_compiler::{closure#0}>::{closure#1}, core[dcc560a250502550]::result::Result<(), rustc_span[e2902ef3f031f316]::ErrorGuaranteed>>::{closure#0}, core[dcc560a250502550]::result::Result<(), rustc_span[e2902ef3f031f316]::ErrorGuaranteed>>::{closure#0}::{closure#0}, core[dcc560a250502550]::result::Result<(), rustc_span[e2902ef3f031f316]::ErrorGuaranteed>>
|
||||
25: 0x77c2cc8c0b70 - <<std[11ac8361619e45fd]::thread::Builder>::spawn_unchecked_<rustc_interface[d7e86b952eb641e5]::util::run_in_thread_with_globals<rustc_interface[d7e86b952eb641e5]::util::run_in_thread_pool_with_globals<rustc_interface[d7e86b952eb641e5]::interface::run_compiler<core[dcc560a250502550]::result::Result<(), rustc_span[e2902ef3f031f316]::ErrorGuaranteed>, rustc_driver_impl[8c32a9dec5e4d0f0]::run_compiler::{closure#0}>::{closure#1}, core[dcc560a250502550]::result::Result<(), rustc_span[e2902ef3f031f316]::ErrorGuaranteed>>::{closure#0}, core[dcc560a250502550]::result::Result<(), rustc_span[e2902ef3f031f316]::ErrorGuaranteed>>::{closure#0}::{closure#0}, core[dcc560a250502550]::result::Result<(), rustc_span[e2902ef3f031f316]::ErrorGuaranteed>>::{closure#1} as core[dcc560a250502550]::ops::function::FnOnce<()>>::call_once::{shim:vtable#0}
|
||||
26: 0x77c2cc8c0f6b - std::sys::pal::unix::thread::Thread::new::thread_start::h1921d0f3a7850262
|
||||
27: 0x77c2ce089272 - start_thread
|
||||
28: 0x77c2ce104dcc - clone3
|
||||
29: 0x0 - <unknown>
|
||||
|
||||
|
||||
rustc version: 1.83.0-nightly (0ee7cb5e3 2024-09-10)
|
||||
platform: x86_64-unknown-linux-gnu
|
|
@ -1,37 +0,0 @@
|
|||
thread 'rustc' panicked at compiler/rustc_middle/src/query/on_disk_cache.rs:736:21:
|
||||
Failed to convert DefPathHash DefPathHash(Fingerprint(9597590199268592635, 17791879502897349522))
|
||||
stack backtrace:
|
||||
0: 0x704a8948d025 - std::backtrace::Backtrace::create::hbc256ff4bc983c0b
|
||||
1: 0x704a87c8c865 - std::backtrace::Backtrace::force_capture::h1ebb6042c5b424a8
|
||||
2: 0x704a86db2217 - std[11ac8361619e45fd]::panicking::update_hook::<alloc[1ed43557cf619c2]::boxed::Box<rustc_driver_impl[8c32a9dec5e4d0f0]::install_ice_hook::{closure#0}>>::{closure#0}
|
||||
3: 0x704a87ca3ee8 - std::panicking::rust_panic_with_hook::ha6cfc51100acb1ab
|
||||
4: 0x704a87ca3cb7 - std::panicking::begin_panic_handler::{{closure}}::he56e1efe5ba67ce1
|
||||
5: 0x704a87ca1699 - std::sys::backtrace::__rust_end_short_backtrace::hcc7bf1345a5f7ae3
|
||||
6: 0x704a87ca3984 - rust_begin_unwind
|
||||
7: 0x704a84ad55c3 - core::panicking::panic_fmt::h146c2ef4416c8c7b
|
||||
8: 0x704a8861abc5 - <rustc_middle[62c17eb200ed25ef]::query::on_disk_cache::CacheDecoder as rustc_span[e2902ef3f031f316]::SpanDecoder>::decode_span
|
||||
9: 0x704a8894bc1c - rustc_query_system[4b3461eb5f3eee8]::query::plumbing::try_execute_query::<rustc_query_impl[2b1ee272ecafb82c]::DynamicConfig<rustc_query_system[4b3461eb5f3eee8]::query::caches::DefIdCache<rustc_middle[62c17eb200ed25ef]::query::erase::Erased<[u8; 8usize]>>, false, false, false>, rustc_query_impl[2b1ee272ecafb82c]::plumbing::QueryCtxt, true>
|
||||
10: 0x704a8894929a - rustc_query_impl[2b1ee272ecafb82c]::query_impl::def_span::get_query_incr::__rust_end_short_backtrace
|
||||
11: 0x704a88a190c0 - rustc_middle[62c17eb200ed25ef]::query::plumbing::query_get_at::<rustc_query_system[4b3461eb5f3eee8]::query::caches::DefIdCache<rustc_middle[62c17eb200ed25ef]::query::erase::Erased<[u8; 8usize]>>>
|
||||
12: 0x704a88caaf7d - <rustc_hir_analysis[198913e0276c9380]::coherence::inherent_impls_overlap::InherentOverlapChecker>::check_for_duplicate_items_in_impl
|
||||
13: 0x704a8939e280 - rustc_hir_analysis[198913e0276c9380]::coherence::inherent_impls_overlap::crate_inherent_impls_overlap_check
|
||||
14: 0x704a8939dc6d - rustc_query_impl[2b1ee272ecafb82c]::plumbing::__rust_begin_short_backtrace::<rustc_query_impl[2b1ee272ecafb82c]::query_impl::crate_inherent_impls_overlap_check::dynamic_query::{closure#2}::{closure#0}, rustc_middle[62c17eb200ed25ef]::query::erase::Erased<[u8; 1usize]>>
|
||||
15: 0x704a8939d1fd - rustc_query_system[4b3461eb5f3eee8]::query::plumbing::try_execute_query::<rustc_query_impl[2b1ee272ecafb82c]::DynamicConfig<rustc_query_system[4b3461eb5f3eee8]::query::caches::SingleCache<rustc_middle[62c17eb200ed25ef]::query::erase::Erased<[u8; 1usize]>>, false, false, false>, rustc_query_impl[2b1ee272ecafb82c]::plumbing::QueryCtxt, true>
|
||||
16: 0x704a8939c867 - rustc_query_impl[2b1ee272ecafb82c]::query_impl::crate_inherent_impls_overlap_check::get_query_incr::__rust_end_short_backtrace
|
||||
17: 0x704a885bb6f3 - rustc_hir_analysis[198913e0276c9380]::check_crate
|
||||
18: 0x704a885b1351 - rustc_interface[d7e86b952eb641e5]::passes::run_required_analyses
|
||||
19: 0x704a891bac1e - rustc_interface[d7e86b952eb641e5]::passes::analysis
|
||||
20: 0x704a891babf1 - rustc_query_impl[2b1ee272ecafb82c]::plumbing::__rust_begin_short_backtrace::<rustc_query_impl[2b1ee272ecafb82c]::query_impl::analysis::dynamic_query::{closure#2}::{closure#0}, rustc_middle[62c17eb200ed25ef]::query::erase::Erased<[u8; 1usize]>>
|
||||
21: 0x704a8939cecd - rustc_query_system[4b3461eb5f3eee8]::query::plumbing::try_execute_query::<rustc_query_impl[2b1ee272ecafb82c]::DynamicConfig<rustc_query_system[4b3461eb5f3eee8]::query::caches::SingleCache<rustc_middle[62c17eb200ed25ef]::query::erase::Erased<[u8; 1usize]>>, false, false, false>, rustc_query_impl[2b1ee272ecafb82c]::plumbing::QueryCtxt, true>
|
||||
22: 0x704a8939cb7a - rustc_query_impl[2b1ee272ecafb82c]::query_impl::analysis::get_query_incr::__rust_end_short_backtrace
|
||||
23: 0x704a891b30bc - rustc_interface[d7e86b952eb641e5]::interface::run_compiler::<core[dcc560a250502550]::result::Result<(), rustc_span[e2902ef3f031f316]::ErrorGuaranteed>, rustc_driver_impl[8c32a9dec5e4d0f0]::run_compiler::{closure#0}>::{closure#1}
|
||||
24: 0x704a892c0504 - std[11ac8361619e45fd]::sys::backtrace::__rust_begin_short_backtrace::<rustc_interface[d7e86b952eb641e5]::util::run_in_thread_with_globals<rustc_interface[d7e86b952eb641e5]::util::run_in_thread_pool_with_globals<rustc_interface[d7e86b952eb641e5]::interface::run_compiler<core[dcc560a250502550]::result::Result<(), rustc_span[e2902ef3f031f316]::ErrorGuaranteed>, rustc_driver_impl[8c32a9dec5e4d0f0]::run_compiler::{closure#0}>::{closure#1}, core[dcc560a250502550]::result::Result<(), rustc_span[e2902ef3f031f316]::ErrorGuaranteed>>::{closure#0}, core[dcc560a250502550]::result::Result<(), rustc_span[e2902ef3f031f316]::ErrorGuaranteed>>::{closure#0}::{closure#0}, core[dcc560a250502550]::result::Result<(), rustc_span[e2902ef3f031f316]::ErrorGuaranteed>>
|
||||
25: 0x704a892c0b70 - <<std[11ac8361619e45fd]::thread::Builder>::spawn_unchecked_<rustc_interface[d7e86b952eb641e5]::util::run_in_thread_with_globals<rustc_interface[d7e86b952eb641e5]::util::run_in_thread_pool_with_globals<rustc_interface[d7e86b952eb641e5]::interface::run_compiler<core[dcc560a250502550]::result::Result<(), rustc_span[e2902ef3f031f316]::ErrorGuaranteed>, rustc_driver_impl[8c32a9dec5e4d0f0]::run_compiler::{closure#0}>::{closure#1}, core[dcc560a250502550]::result::Result<(), rustc_span[e2902ef3f031f316]::ErrorGuaranteed>>::{closure#0}, core[dcc560a250502550]::result::Result<(), rustc_span[e2902ef3f031f316]::ErrorGuaranteed>>::{closure#0}::{closure#0}, core[dcc560a250502550]::result::Result<(), rustc_span[e2902ef3f031f316]::ErrorGuaranteed>>::{closure#1} as core[dcc560a250502550]::ops::function::FnOnce<()>>::call_once::{shim:vtable#0}
|
||||
26: 0x704a892c0f6b - std::sys::pal::unix::thread::Thread::new::thread_start::h1921d0f3a7850262
|
||||
27: 0x704a8ac0b272 - start_thread
|
||||
28: 0x704a8ac86dcc - clone3
|
||||
29: 0x0 - <unknown>
|
||||
|
||||
|
||||
rustc version: 1.83.0-nightly (0ee7cb5e3 2024-09-10)
|
||||
platform: x86_64-unknown-linux-gnu
|
|
@ -1,3 +1,4 @@
|
|||
// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
pub mod web;
|
||||
|
|
168
src/billing/adapters/input/web/bill.rs
Normal file
168
src/billing/adapters/input/web/bill.rs
Normal file
|
@ -0,0 +1,168 @@
|
|||
// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
use actix_identity::Identity;
|
||||
use actix_web::{get, http::header::ContentType, post, web, HttpRequest, HttpResponse, Responder};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use url::Url;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::errors::*;
|
||||
use super::types;
|
||||
use crate::billing::domain::add_store_command::AddStoreCommandBuilder;
|
||||
use crate::billing::domain::{add_bill_command::*, bill_updated_event, commands::BillingCommand};
|
||||
use crate::utils::uuid::WebGetUUIDInterfaceObj;
|
||||
|
||||
pub fn services(cfg: &mut web::ServiceConfig) {
|
||||
cfg.service(add_bill_submit_handler);
|
||||
cfg.service(add_bill_page_handler);
|
||||
cfg.service(add_store_page_handler);
|
||||
cfg.service(add_store_submit_handler);
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
|
||||
struct WebAddBillPayload {
|
||||
store_id: Uuid,
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[get("/billing/store/add")]
|
||||
#[tracing::instrument(name = "add store page handler", skip())]
|
||||
//async fn add_bill_page_handler(_: Identity) -> WebJsonRepsonse<impl Responder> {
|
||||
async fn add_store_page_handler() -> WebJsonRepsonse<impl Responder> {
|
||||
let page = r#"
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Document</title>
|
||||
</head>
|
||||
<body>
|
||||
<form action="/billing/store/add" method="post">
|
||||
<button type="submit">
|
||||
Create Store
|
||||
</button>
|
||||
</form>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
"#;
|
||||
|
||||
Ok(HttpResponse::Ok()
|
||||
.insert_header(ContentType::html())
|
||||
.body(page))
|
||||
}
|
||||
|
||||
const UUID: Uuid = uuid::uuid!("67e55044-10b1-426f-9247-bb680e5fe0c8");
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[post("/billing/store/add")]
|
||||
#[tracing::instrument(
|
||||
name = "add store handler",
|
||||
skip(billing_cqrs_exec, billing_store_cqrs_view, uuid_generator)
|
||||
)]
|
||||
async fn add_store_submit_handler(
|
||||
billing_cqrs_exec: types::WebBillingCqrsExec,
|
||||
billing_store_cqrs_view: types::WebBillingStoreCqrsView,
|
||||
uuid_generator: WebGetUUIDInterfaceObj,
|
||||
req: HttpRequest,
|
||||
// id: Identity,
|
||||
) -> WebJsonRepsonse<impl Responder> {
|
||||
// let user_id = Uuid::parse_str(&id.id().unwrap()).unwrap();
|
||||
let user_id = UUID;
|
||||
|
||||
let store_uuid = UUID;
|
||||
let store_uuid_str = store_uuid.to_string();
|
||||
let cmd = AddStoreCommandBuilder::default()
|
||||
.name("foo".into())
|
||||
.owner(user_id)
|
||||
.store_id(UUID)
|
||||
.address(None)
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
billing_cqrs_exec
|
||||
.execute(&store_uuid_str, BillingCommand::AddStore(cmd))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let store = billing_store_cqrs_view
|
||||
.load(&store_uuid_str)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
|
||||
Ok(HttpResponse::Ok().json(store))
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[get("/billing/bill/add")]
|
||||
#[tracing::instrument(name = "add bill page handler", skip())]
|
||||
//async fn add_bill_page_handler(_: Identity) -> WebJsonRepsonse<impl Responder> {
|
||||
async fn add_bill_page_handler() -> WebJsonRepsonse<impl Responder> {
|
||||
let page = r#"
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Document</title>
|
||||
</head>
|
||||
<body>
|
||||
Token Refreshed
|
||||
<form action="/billing/bill/add" method="post">
|
||||
<label> Store ID <input type="text" name="store_id" id="store_id" /></label>
|
||||
<button type="submit">
|
||||
Refresh Token
|
||||
</button>
|
||||
</form>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
"#;
|
||||
|
||||
Ok(HttpResponse::Ok()
|
||||
.insert_header(ContentType::html())
|
||||
.body(page))
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[post("/billing/bill/add")]
|
||||
#[tracing::instrument(
|
||||
name = "add bill handler",
|
||||
skip(billing_cqrs_exec, billing_bill_cqrs_view,)
|
||||
)]
|
||||
async fn add_bill_submit_handler(
|
||||
billing_cqrs_exec: types::WebBillingCqrsExec,
|
||||
billing_bill_cqrs_view: types::WebBillingBillCqrsView,
|
||||
req: HttpRequest,
|
||||
// id: Identity,
|
||||
payload: web::Form<WebAddBillPayload>,
|
||||
) -> WebJsonRepsonse<impl Responder> {
|
||||
// let user_id = Uuid::parse_str(&id.id().unwrap()).unwrap();
|
||||
let user_id = Uuid::new_v4();
|
||||
|
||||
let bill_uuid = Uuid::new_v4();
|
||||
let bill_uuid_str = bill_uuid.to_string();
|
||||
let cmd = AddBillCommandBuilder::default()
|
||||
.adding_by(user_id)
|
||||
.bill_id(bill_uuid)
|
||||
.store_id(payload.store_id)
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
billing_cqrs_exec
|
||||
.execute(&bill_uuid_str, BillingCommand::AddBill(cmd))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let bill = billing_bill_cqrs_view
|
||||
.load(&bill_uuid_str)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
|
||||
Ok(HttpResponse::Ok().json(bill))
|
||||
}
|
75
src/billing/adapters/input/web/errors.rs
Normal file
75
src/billing/adapters/input/web/errors.rs
Normal file
|
@ -0,0 +1,75 @@
|
|||
// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
use actix_web::http::StatusCode;
|
||||
use actix_web::{HttpResponse, ResponseError};
|
||||
use derive_more::Display;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::billing::application::services::errors::*;
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq)]
|
||||
struct ErrorResponse {
|
||||
error: String,
|
||||
}
|
||||
|
||||
impl From<WebError> for ErrorResponse {
|
||||
fn from(value: WebError) -> Self {
|
||||
ErrorResponse {
|
||||
error: serde_json::to_string(&value).unwrap_or_else(|_| {
|
||||
log::error!("Unable to serialize error");
|
||||
"Unable to serialize error".into()
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Display, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum WebError {
|
||||
InternalError,
|
||||
BillNotFound,
|
||||
StoreNotFound,
|
||||
LineItemNotFound,
|
||||
BadRequest,
|
||||
}
|
||||
|
||||
impl From<BillingError> for WebError {
|
||||
fn from(v: BillingError) -> Self {
|
||||
match v {
|
||||
BillingError::BillIDNotFound => Self::BillNotFound,
|
||||
BillingError::InternalError => Self::InternalError,
|
||||
BillingError::DuplicateStoreName => Self::InternalError,
|
||||
BillingError::DuplicateBillID => Self::InternalError,
|
||||
BillingError::DuplicateLineItemID => Self::InternalError,
|
||||
BillingError::DuplicateStoreID => Self::InternalError,
|
||||
BillingError::StoreIDNotFound => Self::StoreNotFound,
|
||||
BillingError::LineItemIDNotFound => Self::LineItemNotFound,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ResponseError for WebError {
|
||||
fn status_code(&self) -> StatusCode {
|
||||
match self {
|
||||
Self::InternalError => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Self::StoreNotFound => StatusCode::NOT_FOUND,
|
||||
Self::LineItemNotFound => StatusCode::NOT_FOUND,
|
||||
Self::BillNotFound => StatusCode::NOT_FOUND,
|
||||
Self::BadRequest => StatusCode::BAD_REQUEST,
|
||||
}
|
||||
}
|
||||
|
||||
fn error_response(&self) -> actix_web::HttpResponse {
|
||||
let e: ErrorResponse = self.clone().into();
|
||||
match self {
|
||||
Self::InternalError => HttpResponse::InternalServerError().json(e),
|
||||
Self::StoreNotFound => HttpResponse::NotFound().json(e),
|
||||
Self::LineItemNotFound => HttpResponse::NotFound().json(e),
|
||||
Self::BillNotFound => HttpResponse::BadRequest().json(e),
|
||||
Self::BadRequest => HttpResponse::BadRequest().json(e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub type WebJsonRepsonse<V> = Result<V, WebError>;
|
28
src/billing/adapters/input/web/mod.rs
Normal file
28
src/billing/adapters/input/web/mod.rs
Normal file
|
@ -0,0 +1,28 @@
|
|||
// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use actix_web::web;
|
||||
|
||||
use crate::billing::adapters::types;
|
||||
|
||||
mod bill;
|
||||
mod errors;
|
||||
mod routes;
|
||||
|
||||
pub use errors::WebJsonRepsonse;
|
||||
|
||||
pub use routes::RoutesRepository;
|
||||
|
||||
pub fn load_ctx() -> impl FnOnce(&mut web::ServiceConfig) {
|
||||
let routes = types::WebBillingRoutesRepository::new(Arc::new(RoutesRepository::default()));
|
||||
|
||||
let f = move |cfg: &mut web::ServiceConfig| {
|
||||
cfg.app_data(routes);
|
||||
cfg.configure(bill::services);
|
||||
};
|
||||
|
||||
Box::new(f)
|
||||
}
|
67
src/billing/adapters/input/web/routes.rs
Normal file
67
src/billing/adapters/input/web/routes.rs
Normal file
|
@ -0,0 +1,67 @@
|
|||
// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
use url::Url;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub struct RoutesRepository {
|
||||
add_bill: String,
|
||||
update_bill: String,
|
||||
delete_bill: String,
|
||||
compute_total_price_for_bill: String,
|
||||
|
||||
add_line_item: String,
|
||||
update_line_item: String,
|
||||
delete_line_item: String,
|
||||
}
|
||||
|
||||
impl Default for RoutesRepository {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
add_bill: "/billing/bill/add".into(),
|
||||
update_bill: "/billing/bill/{bill_uuid}".into(),
|
||||
delete_bill: "/billing/bill/{bill_uuid}".into(),
|
||||
compute_total_price_for_bill: "/billing/bill/{bill_uuid}/compute-total".into(),
|
||||
|
||||
add_line_item: "/billing/bill/{bill_id}/line_item/add".into(),
|
||||
update_line_item: "/billing/bill/{bill_id}/line_item/{line_item_uuid}".into(),
|
||||
delete_line_item: "/billing/bill/{bill_id}/line_item/{line_item_uuid}".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl RoutesRepository {
|
||||
pub fn update_bill(&self, bill_id: Uuid) -> String {
|
||||
self.update_bill
|
||||
.replace("{bill_uuid}", &bill_id.to_string())
|
||||
}
|
||||
|
||||
pub fn delete_bill(&self, bill_id: Uuid) -> String {
|
||||
self.delete_bill
|
||||
.replace("{bill_uuid}", &bill_id.to_string())
|
||||
}
|
||||
|
||||
pub fn compute_total_price_for_bill(&self, bill_id: Uuid) -> String {
|
||||
self.compute_total_price_for_bill
|
||||
.replace("{bill_uuid}", &bill_id.to_string())
|
||||
}
|
||||
|
||||
pub fn add_line_item(&self, bill_id: Uuid) -> String {
|
||||
self.add_line_item
|
||||
.replace("{bill_uuid}", &bill_id.to_string())
|
||||
}
|
||||
|
||||
pub fn update_line_item(&self, bill_id: Uuid, line_item_uuid: Uuid) -> String {
|
||||
self.update_line_item
|
||||
.replace("{bill_uuid}", &bill_id.to_string())
|
||||
.replace("{line_item_uuid}", &line_item_uuid.to_string())
|
||||
}
|
||||
|
||||
pub fn delete_line_item(&self, bill_id: Uuid, line_item_uuid: Uuid) -> String {
|
||||
self.delete_line_item
|
||||
.replace("{bill_uuid}", &bill_id.to_string())
|
||||
.replace("{line_item_uuid}", &line_item_uuid.to_string())
|
||||
}
|
||||
}
|
|
@ -1,6 +1,93 @@
|
|||
// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
use std::sync::Arc;
|
||||
|
||||
use actix_web::web::{self, Data};
|
||||
use cqrs_es::{persist::ViewRepository, EventEnvelope, Query, View};
|
||||
use postgres_es::PostgresCqrs;
|
||||
use sqlx::postgres::PgPool;
|
||||
|
||||
use crate::billing::{
|
||||
application::{
|
||||
port::output::db::{
|
||||
bill_id_exists::BillIDExistsDBPortObj,
|
||||
get_line_items_for_bill_id::GetLineItemsForBillIDDBPortObj,
|
||||
line_item_id_exists::LineItemIDExistsDBPortObj, next_token_id::NextTokenIDDBPortObj,
|
||||
store_id_exists::StoreIDExistsDBPortObj, store_name_exists::StoreNameExistsDBPortObj,
|
||||
},
|
||||
services::{BillingServices, BillingServicesObj},
|
||||
},
|
||||
domain::{bill_aggregate::Bill, line_item_aggregate::LineItem, store_aggregate::Store},
|
||||
};
|
||||
use crate::settings::Settings;
|
||||
use output::db::postgres::{bill_view, line_item_view, store_view, BillingDBPostgresAdapter};
|
||||
|
||||
mod input;
|
||||
mod output;
|
||||
mod types;
|
||||
|
||||
pub fn load_adapters(pool: PgPool, settings: Settings) -> impl FnOnce(&mut web::ServiceConfig) {
|
||||
// init DB
|
||||
let db = BillingDBPostgresAdapter::new(pool.clone());
|
||||
let db_bill_id_exists: BillIDExistsDBPortObj = Arc::new(db.clone());
|
||||
let db_line_item_id_exists: LineItemIDExistsDBPortObj = Arc::new(db.clone());
|
||||
let db_store_id_exists: StoreIDExistsDBPortObj = Arc::new(db.clone());
|
||||
let db_store_name_exists: StoreNameExistsDBPortObj = Arc::new(db.clone());
|
||||
let db_get_line_items_for_bill_id: GetLineItemsForBillIDDBPortObj = Arc::new(db.clone());
|
||||
let db_next_token_id: NextTokenIDDBPortObj = Arc::new(db.clone());
|
||||
|
||||
// init services
|
||||
|
||||
let services: BillingServicesObj = Arc::new(BillingServices::new(
|
||||
db_bill_id_exists.clone(),
|
||||
db_line_item_id_exists.clone(),
|
||||
db_store_id_exists.clone(),
|
||||
db_store_name_exists.clone(),
|
||||
db_get_line_items_for_bill_id.clone(),
|
||||
db_next_token_id.clone(),
|
||||
));
|
||||
|
||||
let (bill_cqrs_exec, bill_cqrs_query) = bill_view::init_cqrs(db.clone(), services.clone());
|
||||
let (store_cqrs_exec, store_cqrs_query) = store_view::init_cqrs(db.clone(), services.clone());
|
||||
let (line_item_cqrs_exec, line_item_cqrs_query) =
|
||||
line_item_view::init_cqrs(db.clone(), services.clone());
|
||||
|
||||
let billing_cqrs_exec = types::WebBillingCqrsExec::new(Arc::new(
|
||||
types::BillingCqrsExecBuilder::default()
|
||||
.bill(bill_cqrs_exec)
|
||||
.line_item(line_item_cqrs_exec)
|
||||
.store(store_cqrs_exec)
|
||||
.build()
|
||||
.unwrap(),
|
||||
));
|
||||
|
||||
let f = move |cfg: &mut web::ServiceConfig| {
|
||||
cfg.configure(input::web::load_ctx());
|
||||
|
||||
cfg.app_data(Data::new(bill_cqrs_query.clone()));
|
||||
cfg.app_data(Data::new(store_cqrs_query.clone()));
|
||||
cfg.app_data(Data::new(line_item_cqrs_query.clone()));
|
||||
|
||||
cfg.app_data(billing_cqrs_exec);
|
||||
};
|
||||
|
||||
Box::new(f)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::db::migrate::*;
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn billing_load_adapters() {
|
||||
let settings = crate::settings::tests::get_settings().await;
|
||||
settings.create_db().await;
|
||||
|
||||
let db = crate::db::sqlx_postgres::Postgres::init(&settings.database.url).await;
|
||||
db.migrate().await;
|
||||
|
||||
load_adapters(db.pool.clone(), settings.clone());
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
mod postgres;
|
||||
pub(crate) mod postgres;
|
||||
|
|
|
@ -3,16 +3,20 @@
|
|||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
use std::str::FromStr;
|
||||
use std::sync::Arc;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use cqrs_es::persist::{PersistenceError, ViewContext, ViewRepository};
|
||||
use cqrs_es::{EventEnvelope, Query, View};
|
||||
use postgres_es::PostgresCqrs;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use time::OffsetDateTime;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::errors::*;
|
||||
use super::BillingDBPostgresAdapter;
|
||||
use crate::billing::adapters::types::{BillingBillCqrsExec, BillingBillCqrsView};
|
||||
use crate::billing::application::services::BillingServicesObj;
|
||||
use crate::billing::domain::bill_aggregate::{Bill, BillBuilder};
|
||||
use crate::billing::domain::events::BillingEvent;
|
||||
use crate::types::currency::{self, Currency, PriceBuilder};
|
||||
|
@ -311,12 +315,24 @@ impl Query<Bill> for BillingDBPostgresAdapter {
|
|||
}
|
||||
}
|
||||
|
||||
pub fn init_cqrs(
|
||||
db: BillingDBPostgresAdapter,
|
||||
services: BillingServicesObj,
|
||||
) -> (BillingBillCqrsExec, BillingBillCqrsView) {
|
||||
let queries: Vec<Box<dyn Query<Bill>>> = vec![Box::new(db.clone())];
|
||||
|
||||
let pool = db.pool.clone();
|
||||
|
||||
(
|
||||
Arc::new(postgres_es::postgres_cqrs(pool.clone(), queries, services)),
|
||||
Arc::new(db.clone()),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
use postgres_es::PostgresCqrs;
|
||||
|
||||
use crate::{
|
||||
billing::{
|
||||
application::services::{
|
||||
|
|
|
@ -1,8 +1,8 @@
|
|||
// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
use std::str::FromStr;
|
||||
use std::sync::Arc;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use cqrs_es::persist::{PersistenceError, ViewContext, ViewRepository};
|
||||
|
@ -13,6 +13,8 @@ use uuid::Uuid;
|
|||
|
||||
use super::errors::*;
|
||||
use super::BillingDBPostgresAdapter;
|
||||
use crate::billing::adapters::types::{BillingLineItemCqrsExec, BillingLineItemCqrsView};
|
||||
use crate::billing::application::services::BillingServicesObj;
|
||||
use crate::billing::domain::events::BillingEvent;
|
||||
use crate::billing::domain::line_item_aggregate::*;
|
||||
use crate::types::currency::*;
|
||||
|
@ -363,6 +365,20 @@ impl Query<LineItem> for BillingDBPostgresAdapter {
|
|||
}
|
||||
}
|
||||
|
||||
pub fn init_cqrs(
|
||||
db: BillingDBPostgresAdapter,
|
||||
services: BillingServicesObj,
|
||||
) -> (BillingLineItemCqrsExec, BillingLineItemCqrsView) {
|
||||
let queries: Vec<Box<dyn Query<LineItem>>> = vec![Box::new(db.clone())];
|
||||
|
||||
let pool = db.pool.clone();
|
||||
|
||||
(
|
||||
Arc::new(postgres_es::postgres_cqrs(pool.clone(), queries, services)),
|
||||
Arc::new(db.clone()),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
|
|
@ -8,19 +8,19 @@ use sqlx::postgres::PgPool;
|
|||
use crate::db::{migrate::RunMigrations, sqlx_postgres::Postgres};
|
||||
|
||||
mod bill_id_exists;
|
||||
mod bill_view;
|
||||
pub(crate) mod bill_view;
|
||||
mod errors;
|
||||
mod get_line_items_for_bill_id;
|
||||
mod line_item_id_exists;
|
||||
mod line_item_view;
|
||||
pub(crate) mod line_item_view;
|
||||
mod next_token_id;
|
||||
mod store_id_exists;
|
||||
mod store_name_exists;
|
||||
mod store_view;
|
||||
pub(crate) mod store_view;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct BillingDBPostgresAdapter {
|
||||
pool: PgPool,
|
||||
pub(crate) pool: PgPool,
|
||||
}
|
||||
|
||||
impl BillingDBPostgresAdapter {
|
||||
|
|
|
@ -1,6 +1,7 @@
|
|||
// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
use std::sync::Arc;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use cqrs_es::persist::{PersistenceError, ViewContext, ViewRepository};
|
||||
|
@ -10,6 +11,8 @@ use uuid::Uuid;
|
|||
|
||||
use super::errors::*;
|
||||
use super::BillingDBPostgresAdapter;
|
||||
use crate::billing::adapters::types::{BillingStoreCqrsExec, BillingStoreCqrsView};
|
||||
use crate::billing::application::services::BillingServicesObj;
|
||||
use crate::billing::domain::events::BillingEvent;
|
||||
use crate::billing::domain::store_aggregate::*;
|
||||
use crate::utils::parse_aggregate_id::parse_aggregate_id;
|
||||
|
@ -216,6 +219,20 @@ impl Query<Store> for BillingDBPostgresAdapter {
|
|||
}
|
||||
}
|
||||
|
||||
pub fn init_cqrs(
|
||||
db: BillingDBPostgresAdapter,
|
||||
services: BillingServicesObj,
|
||||
) -> (BillingStoreCqrsExec, BillingStoreCqrsView) {
|
||||
let queries: Vec<Box<dyn Query<Store>>> = vec![Box::new(db.clone())];
|
||||
|
||||
let pool = db.pool.clone();
|
||||
|
||||
(
|
||||
Arc::new(postgres_es::postgres_cqrs(pool.clone(), queries, services)),
|
||||
Arc::new(db.clone()),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
mod db;
|
||||
pub(crate) mod db;
|
||||
|
|
81
src/billing/adapters/types.rs
Normal file
81
src/billing/adapters/types.rs
Normal file
|
@ -0,0 +1,81 @@
|
|||
// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
#![allow(dead_code)]
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use actix_web::web::Data;
|
||||
use async_trait::async_trait;
|
||||
use cqrs_es::{persist::ViewRepository, AggregateError};
|
||||
use derive_builder::Builder;
|
||||
use mockall::predicate::*;
|
||||
use mockall::*;
|
||||
use postgres_es::PostgresCqrs;
|
||||
|
||||
use crate::billing::{
|
||||
adapters::{
|
||||
input::web::RoutesRepository,
|
||||
output::db::postgres::{
|
||||
bill_view::BillView, line_item_view::LineItemView, store_view::StoreView,
|
||||
BillingDBPostgresAdapter,
|
||||
},
|
||||
},
|
||||
application::services::{errors::BillingError, BillingServicesObj},
|
||||
domain::{
|
||||
bill_aggregate::Bill, commands::BillingCommand, line_item_aggregate::LineItem,
|
||||
store_aggregate::Store,
|
||||
},
|
||||
};
|
||||
|
||||
pub type WebBillingRoutesRepository = Data<Arc<RoutesRepository>>;
|
||||
|
||||
pub type WebBillingServiceObj = Data<BillingServicesObj>;
|
||||
|
||||
pub type BillingBillCqrsExec = Arc<PostgresCqrs<Bill>>;
|
||||
pub type BillingBillCqrsView = Arc<dyn ViewRepository<BillView, Bill>>;
|
||||
pub type WebBillingBillCqrsView = Data<BillingBillCqrsView>;
|
||||
|
||||
pub type BillingLineItemCqrsExec = Arc<PostgresCqrs<LineItem>>;
|
||||
pub type BillingLineItemCqrsView = Arc<dyn ViewRepository<LineItemView, LineItem>>;
|
||||
pub type WebBillingLineItemCqrsView = Data<BillingLineItemCqrsView>;
|
||||
|
||||
pub type BillingStoreCqrsExec = Arc<PostgresCqrs<Store>>;
|
||||
pub type BillingStoreCqrsView = Arc<dyn ViewRepository<StoreView, Store>>;
|
||||
pub type WebBillingStoreCqrsView = Data<BillingStoreCqrsView>;
|
||||
|
||||
pub type WebBillingCqrsExec = Data<Arc<dyn BillingCqrsExecutor>>;
|
||||
|
||||
#[automock]
|
||||
#[async_trait]
|
||||
pub trait BillingCqrsExecutor {
|
||||
async fn execute(
|
||||
&self,
|
||||
aggregate_id: &str,
|
||||
command: BillingCommand,
|
||||
) -> Result<(), AggregateError<BillingError>>;
|
||||
}
|
||||
|
||||
#[derive(Clone, Builder)]
|
||||
pub struct BillingCqrsExec {
|
||||
bill: BillingBillCqrsExec,
|
||||
line_item: BillingLineItemCqrsExec,
|
||||
store: BillingStoreCqrsExec,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl BillingCqrsExecutor for BillingCqrsExec {
|
||||
async fn execute(
|
||||
&self,
|
||||
aggregate_id: &str,
|
||||
command: BillingCommand,
|
||||
) -> Result<(), AggregateError<BillingError>> {
|
||||
self.bill.execute(aggregate_id, command.clone()).await?;
|
||||
self.line_item
|
||||
.execute(aggregate_id, command.clone())
|
||||
.await?;
|
||||
self.store.execute(aggregate_id, command).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
|
@ -1,6 +1,7 @@
|
|||
// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
use std::sync::Arc;
|
||||
|
||||
use derive_builder::Builder;
|
||||
use mockall::predicate::*;
|
||||
|
@ -20,6 +21,23 @@ pub mod update_line_item_service;
|
|||
pub mod update_store_service;
|
||||
// TODO: 2. reset token number for store_id cronjob
|
||||
|
||||
use add_bill_service::AddBillServiceBuilder;
|
||||
use add_line_item_service::AddLineItemServiceBuilder;
|
||||
use add_store_service::AddStoreServiceBuilder;
|
||||
use compute_bill_total_price_service::ComputeBillTotalPriceBillServiceBuilder;
|
||||
use delete_bill_service::DeleteBillServiceBuilder;
|
||||
use delete_line_item_service::DeleteLineItemServiceBuilder;
|
||||
use update_bill_service::UpdateBillServiceBuilder;
|
||||
use update_line_item_service::UpdateLineItemServiceBuilder;
|
||||
use update_store_service::UpdateStoreServiceBuilder;
|
||||
|
||||
use crate::billing::application::port::output::db::{
|
||||
bill_id_exists::BillIDExistsDBPortObj,
|
||||
get_line_items_for_bill_id::GetLineItemsForBillIDDBPortObj,
|
||||
line_item_id_exists::LineItemIDExistsDBPortObj, next_token_id::NextTokenIDDBPortObj,
|
||||
store_id_exists::StoreIDExistsDBPortObj, store_name_exists::StoreNameExistsDBPortObj,
|
||||
};
|
||||
|
||||
#[automock]
|
||||
pub trait BillingServicesInterface: Send + Sync {
|
||||
fn add_bill(&self) -> add_bill_service::AddBillServiceObj;
|
||||
|
@ -35,6 +53,8 @@ pub trait BillingServicesInterface: Send + Sync {
|
|||
) -> compute_bill_total_price_service::ComputeBillTotalPriceBillServiceObj;
|
||||
}
|
||||
|
||||
pub type BillingServicesObj = std::sync::Arc<dyn BillingServicesInterface>;
|
||||
|
||||
#[derive(Clone, Builder)]
|
||||
pub struct BillingServices {
|
||||
add_bill: add_bill_service::AddBillServiceObj,
|
||||
|
@ -81,3 +101,109 @@ impl BillingServicesInterface for BillingServices {
|
|||
self.compute_total_price_for_bill.clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl BillingServices {
|
||||
pub fn new(
|
||||
db_bill_id_exists: BillIDExistsDBPortObj,
|
||||
db_line_item_id_exists: LineItemIDExistsDBPortObj,
|
||||
db_store_id_exists: StoreIDExistsDBPortObj,
|
||||
db_store_name_exists: StoreNameExistsDBPortObj,
|
||||
db_get_line_items_for_bill_id: GetLineItemsForBillIDDBPortObj,
|
||||
db_next_token_id: NextTokenIDDBPortObj,
|
||||
) -> Self {
|
||||
let services = BillingServicesBuilder::default()
|
||||
.add_bill(Arc::new(
|
||||
AddBillServiceBuilder::default()
|
||||
.db_next_token_id(db_next_token_id.clone())
|
||||
.db_bill_id_exists(db_bill_id_exists.clone())
|
||||
.build()
|
||||
.unwrap(),
|
||||
))
|
||||
.add_store(Arc::new(
|
||||
AddStoreServiceBuilder::default()
|
||||
.db_store_id_exists(db_store_id_exists.clone())
|
||||
.db_store_name_exists(db_store_name_exists.clone())
|
||||
.build()
|
||||
.unwrap(),
|
||||
))
|
||||
.update_store(Arc::new(
|
||||
UpdateStoreServiceBuilder::default()
|
||||
.db_store_id_exists(db_store_id_exists.clone())
|
||||
.db_store_name_exists(db_store_name_exists.clone())
|
||||
.build()
|
||||
.unwrap(),
|
||||
))
|
||||
.add_line_item(Arc::new(
|
||||
AddLineItemServiceBuilder::default()
|
||||
.db_line_item_id_exists(db_line_item_id_exists.clone())
|
||||
.db_bill_id_exists(db_bill_id_exists.clone())
|
||||
.build()
|
||||
.unwrap(),
|
||||
))
|
||||
.update_line_item(Arc::new(
|
||||
UpdateLineItemServiceBuilder::default()
|
||||
.db_line_item_id_exists(db_line_item_id_exists.clone())
|
||||
.db_bill_id_exists(db_bill_id_exists.clone())
|
||||
.build()
|
||||
.unwrap(),
|
||||
))
|
||||
.delete_line_item(Arc::new(
|
||||
DeleteLineItemServiceBuilder::default()
|
||||
.db_line_item_id_exists(db_line_item_id_exists.clone())
|
||||
.build()
|
||||
.unwrap(),
|
||||
))
|
||||
.update_bill(Arc::new(
|
||||
UpdateBillServiceBuilder::default()
|
||||
.db_bill_id_exists(db_bill_id_exists.clone())
|
||||
.build()
|
||||
.unwrap(),
|
||||
))
|
||||
.delete_bill(Arc::new(
|
||||
DeleteBillServiceBuilder::default()
|
||||
.db_bill_id_exists(db_bill_id_exists.clone())
|
||||
.build()
|
||||
.unwrap(),
|
||||
))
|
||||
.compute_total_price_for_bill(Arc::new(
|
||||
ComputeBillTotalPriceBillServiceBuilder::default()
|
||||
.db_bill_id_exists(db_bill_id_exists.clone())
|
||||
.db_get_line_items_for_bill_id(db_get_line_items_for_bill_id)
|
||||
.build()
|
||||
.unwrap(),
|
||||
))
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
services
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{
|
||||
billing::application::port::output::db::{
|
||||
bill_id_exists::mock_bill_id_exists_db_port_true,
|
||||
get_line_items_for_bill_id::mock_get_line_items_for_bill_id_db_port_no_line_items,
|
||||
line_item_id_exists::mock_line_item_id_exists_db_port_true,
|
||||
next_token_id::mock_next_token_id_db_port,
|
||||
store_id_exists::mock_store_id_exists_db_port_true,
|
||||
store_name_exists::mock_store_name_exists_db_port_true,
|
||||
},
|
||||
db::migrate::*,
|
||||
tests::bdd::IS_NEVER_CALLED,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn billing_services_builder_works() {
|
||||
BillingServices::new(
|
||||
mock_bill_id_exists_db_port_true(IS_NEVER_CALLED),
|
||||
mock_line_item_id_exists_db_port_true(IS_NEVER_CALLED),
|
||||
mock_store_id_exists_db_port_true(IS_NEVER_CALLED),
|
||||
mock_store_name_exists_db_port_true(IS_NEVER_CALLED),
|
||||
mock_get_line_items_for_bill_id_db_port_no_line_items(IS_NEVER_CALLED),
|
||||
mock_next_token_id_db_port(IS_NEVER_CALLED),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -2,6 +2,6 @@
|
|||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
mod adapters;
|
||||
pub(crate) mod adapters;
|
||||
mod application;
|
||||
mod domain;
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
pub mod web;
|
||||
|
|
189
src/identity/adapters/input/web/employee.rs
Normal file
189
src/identity/adapters/input/web/employee.rs
Normal file
|
@ -0,0 +1,189 @@
|
|||
// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
use actix_identity::Identity;
|
||||
use actix_web::{get, http::header::ContentType, post, web, HttpRequest, HttpResponse, Responder};
|
||||
use derive_builder::Builder;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use url::Url;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::errors::*;
|
||||
use super::types;
|
||||
//use crate::utils::uuid::WebGetUUIDInterfaceObj;
|
||||
|
||||
pub fn services(cfg: &mut web::ServiceConfig) {
|
||||
cfg.service(login_ui_handler);
|
||||
cfg.service(login_form_submission_handler);
|
||||
cfg.service(resend_login_otp_handler);
|
||||
|
||||
cfg.service(register_ui_handler);
|
||||
cfg.service(register_form_submission_handler);
|
||||
cfg.service(resend_verification_otp_handler);
|
||||
|
||||
cfg.service(exit_organization_ui_handler);
|
||||
cfg.service(exit_organization_form_submission_handler);
|
||||
}
|
||||
|
||||
// login handlers
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[get("/employee/login")]
|
||||
#[tracing::instrument(name = "login UI handler", skip())]
|
||||
async fn login_ui_handler() -> WebJsonRepsonse<impl Responder> {
|
||||
use web_ui::identity::employee_login::*;
|
||||
|
||||
let page = EmployeeLoginPage::page();
|
||||
Ok(HttpResponse::Ok()
|
||||
.insert_header(ContentType::html())
|
||||
.body(page))
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
|
||||
struct EmployeeLoginPayload {
|
||||
country_code: usize,
|
||||
phone_number: u64,
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[post("/employee/login")]
|
||||
#[tracing::instrument(
|
||||
name = "Login form submission handler"
|
||||
skip(id, req, payload, identity_cqrs_exec)
|
||||
)]
|
||||
async fn login_form_submission_handler(
|
||||
identity_cqrs_exec: types::WebIdentityCqrsExec,
|
||||
req: HttpRequest,
|
||||
id: Identity,
|
||||
payload: web::Form<EmployeeLoginPayload>,
|
||||
) -> WebJsonRepsonse<impl Responder> {
|
||||
let store = "";
|
||||
|
||||
Ok(HttpResponse::Ok().json(store))
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[post("/employee/login/resend_otp")]
|
||||
#[tracing::instrument(
|
||||
name = "Resend login OTP handler",
|
||||
skip(req, identity_cqrs_exec, payload)
|
||||
)]
|
||||
async fn resend_login_otp_handler(
|
||||
identity_cqrs_exec: types::WebIdentityCqrsExec,
|
||||
req: HttpRequest,
|
||||
payload: web::Form<EmployeeLoginPayload>,
|
||||
) -> WebJsonRepsonse<impl Responder> {
|
||||
let store = "";
|
||||
|
||||
Ok(HttpResponse::Ok().json(store))
|
||||
}
|
||||
|
||||
// register handlers
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[get("/employee/register")]
|
||||
#[tracing::instrument(name = "register UI handler", skip())]
|
||||
async fn register_ui_handler() -> WebJsonRepsonse<impl Responder> {
|
||||
use web_ui::identity::employee_register::*;
|
||||
|
||||
let page = EmployeeRegisterPage::page();
|
||||
Ok(HttpResponse::Ok()
|
||||
.insert_header(ContentType::html())
|
||||
.body(page))
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
|
||||
struct EmployeeRegisterPayload {
|
||||
first_name: String,
|
||||
last_name: String,
|
||||
|
||||
country_code: usize,
|
||||
phone_number: u64,
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[post("/employee/register")]
|
||||
#[tracing::instrument(
|
||||
name = "Register form submission handler"
|
||||
skip(id, req, payload, identity_cqrs_exec)
|
||||
)]
|
||||
async fn register_form_submission_handler(
|
||||
identity_cqrs_exec: types::WebIdentityCqrsExec,
|
||||
req: HttpRequest,
|
||||
id: Identity,
|
||||
payload: web::Form<EmployeeRegisterPayload>,
|
||||
) -> WebJsonRepsonse<impl Responder> {
|
||||
let store = "";
|
||||
|
||||
Ok(HttpResponse::Ok().json(store))
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[post("/employee/phone/verify/resend_otp")]
|
||||
#[tracing::instrument(name = "Resend verification OTP", skip(id, req, identity_cqrs_exec))]
|
||||
async fn resend_verification_otp_handler(
|
||||
identity_cqrs_exec: types::WebIdentityCqrsExec,
|
||||
req: HttpRequest,
|
||||
id: Identity,
|
||||
) -> WebJsonRepsonse<impl Responder> {
|
||||
let store = "";
|
||||
|
||||
Ok(HttpResponse::Ok().json(store))
|
||||
}
|
||||
|
||||
// Delete user handlers
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[get("/employee/organization/exit")]
|
||||
#[tracing::instrument(name = "Exit organizationUI handler", skip())]
|
||||
async fn exit_organization_ui_handler() -> WebJsonRepsonse<impl Responder> {
|
||||
use web_ui::identity::employee_exit_organization::*;
|
||||
|
||||
let page = EmployeeExitOrganizationPage::page();
|
||||
Ok(HttpResponse::Ok()
|
||||
.insert_header(ContentType::html())
|
||||
.body(page))
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[post("/employee/organization/exit")]
|
||||
#[tracing::instrument(
|
||||
name = "Exit organization form submission handler"
|
||||
skip(id, req, identity_cqrs_exec)
|
||||
)]
|
||||
async fn exit_organization_form_submission_handler(
|
||||
identity_cqrs_exec: types::WebIdentityCqrsExec,
|
||||
req: HttpRequest,
|
||||
id: Identity,
|
||||
) -> WebJsonRepsonse<impl Responder> {
|
||||
let store = "";
|
||||
|
||||
Ok(HttpResponse::Ok().json(store))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
use crate::identity::adapters::input::web::RoutesRepository;
|
||||
use crate::tests::actix_web_test_utils::page_test_runner;
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn identity_web_employee_login_ui_works() {
|
||||
let routes = RoutesRepository::default();
|
||||
page_test_runner(&routes.employee_login).await;
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn identity_web_employee_register_ui_works() {
|
||||
let routes = RoutesRepository::default();
|
||||
page_test_runner(&routes.employee_register).await;
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn identity_web_employee_exit_organization_ui_works() {
|
||||
let routes = RoutesRepository::default();
|
||||
page_test_runner(&routes.employee_exit_organization).await;
|
||||
}
|
||||
}
|
134
src/identity/adapters/input/web/errors.rs
Normal file
134
src/identity/adapters/input/web/errors.rs
Normal file
|
@ -0,0 +1,134 @@
|
|||
// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
use actix_web::http::StatusCode;
|
||||
use actix_web::{HttpResponse, ResponseError};
|
||||
use derive_more::Display;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::identity::application::services::errors::*;
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq)]
|
||||
struct ErrorResponse {
|
||||
error: String,
|
||||
}
|
||||
|
||||
impl From<WebError> for ErrorResponse {
|
||||
fn from(value: WebError) -> Self {
|
||||
ErrorResponse {
|
||||
error: serde_json::to_string(&value).unwrap_or_else(|_| {
|
||||
log::error!("Unable to serialize error");
|
||||
"Unable to serialize error".into()
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Display, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum WebError {
|
||||
InternalError,
|
||||
BadRequest,
|
||||
|
||||
DuplicateUsername,
|
||||
VerificationOTPNotFound,
|
||||
VerificationSecretNotFound,
|
||||
PhoneNumberVerificationFailed,
|
||||
LoginOTPNotFound,
|
||||
LoginFailed,
|
||||
DuplicateEmail,
|
||||
DuplicateEmployeeID,
|
||||
DuplicatePhoneNumber,
|
||||
DuplicateVerificationOTP,
|
||||
PhoneNumberNotFound,
|
||||
EmployeeNotFound,
|
||||
InviteNotFound,
|
||||
StoreNotFound,
|
||||
DuplicateStoreName,
|
||||
StoreIDNotFound,
|
||||
DuplicateStoreID,
|
||||
}
|
||||
|
||||
impl From<IdentityError> for WebError {
|
||||
fn from(v: IdentityError) -> Self {
|
||||
match v {
|
||||
IdentityError::InternalError => Self::InternalError,
|
||||
IdentityError::StoreIDNotFound => Self::StoreNotFound,
|
||||
IdentityError::DuplicateUsername => Self::DuplicateUsername,
|
||||
IdentityError::VerificationOTPNotFound => Self::VerificationOTPNotFound,
|
||||
IdentityError::VerificationSecretNotFound => Self::VerificationSecretNotFound,
|
||||
IdentityError::PhoneNumberVerificationFailed => Self::PhoneNumberNotFound,
|
||||
IdentityError::LoginOTPNotFound => Self::LoginOTPNotFound,
|
||||
IdentityError::LoginFailed => Self::LoginFailed,
|
||||
IdentityError::DuplicateEmail => Self::DuplicateEmail,
|
||||
IdentityError::DuplicateEmployeeID => Self::DuplicateEmployeeID,
|
||||
IdentityError::DuplicatePhoneNumber => Self::DuplicatePhoneNumber,
|
||||
IdentityError::DuplicateVerificationOTP => Self::DuplicateVerificationOTP,
|
||||
IdentityError::PhoneNumberNotFound => Self::PhoneNumberNotFound,
|
||||
IdentityError::EmployeeNotFound => Self::EmployeeNotFound,
|
||||
IdentityError::InviteNotFound => Self::InviteNotFound,
|
||||
IdentityError::StoreNotFound => Self::StoreNotFound,
|
||||
IdentityError::DuplicateStoreName => Self::DuplicateStoreName,
|
||||
IdentityError::StoreIDNotFound => Self::StoreIDNotFound,
|
||||
IdentityError::DuplicateStoreID => Self::DuplicateStoreID,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ResponseError for WebError {
|
||||
fn status_code(&self) -> StatusCode {
|
||||
match self {
|
||||
Self::InternalError => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Self::BadRequest => StatusCode::BAD_REQUEST,
|
||||
|
||||
Self::StoreIDNotFound => StatusCode::NOT_FOUND,
|
||||
Self::DuplicateUsername => StatusCode::BAD_REQUEST,
|
||||
Self::VerificationOTPNotFound => StatusCode::UNAUTHORIZED,
|
||||
Self::VerificationSecretNotFound => StatusCode::UNAUTHORIZED,
|
||||
Self::PhoneNumberVerificationFailed => StatusCode::UNAUTHORIZED,
|
||||
Self::LoginOTPNotFound => StatusCode::UNAUTHORIZED,
|
||||
Self::LoginFailed => StatusCode::UNAUTHORIZED,
|
||||
Self::DuplicateEmail => StatusCode::BAD_REQUEST,
|
||||
Self::DuplicateEmployeeID => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Self::DuplicatePhoneNumber => StatusCode::BAD_REQUEST,
|
||||
Self::DuplicateVerificationOTP => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Self::PhoneNumberNotFound => StatusCode::UNAUTHORIZED, // (?)
|
||||
Self::EmployeeNotFound => StatusCode::NOT_FOUND,
|
||||
Self::InviteNotFound => StatusCode::NOT_FOUND,
|
||||
Self::StoreNotFound => StatusCode::NOT_FOUND,
|
||||
Self::DuplicateStoreName => StatusCode::BAD_REQUEST,
|
||||
Self::StoreIDNotFound => StatusCode::NOT_FOUND,
|
||||
Self::DuplicateStoreID => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
}
|
||||
}
|
||||
|
||||
fn error_response(&self) -> actix_web::HttpResponse {
|
||||
let e: ErrorResponse = self.clone().into();
|
||||
match self {
|
||||
Self::InternalError => HttpResponse::InternalServerError().json(e),
|
||||
Self::BadRequest => HttpResponse::BadRequest().json(e),
|
||||
|
||||
Self::StoreNotFound => HttpResponse::NotFound().json(e),
|
||||
Self::StoreIDNotFound => HttpResponse::NotFound().json(e),
|
||||
Self::DuplicateUsername => HttpResponse::BadRequest().json(e),
|
||||
Self::VerificationOTPNotFound => HttpResponse::Unauthorized().json(e),
|
||||
Self::VerificationSecretNotFound => HttpResponse::Unauthorized().json(e),
|
||||
Self::PhoneNumberVerificationFailed => HttpResponse::Unauthorized().json(e),
|
||||
Self::LoginOTPNotFound => HttpResponse::Unauthorized().json(e),
|
||||
Self::LoginFailed => HttpResponse::Unauthorized().json(e),
|
||||
Self::DuplicateEmail => HttpResponse::BadRequest().json(e),
|
||||
Self::DuplicateEmployeeID => HttpResponse::InternalServerError().json(e),
|
||||
Self::DuplicatePhoneNumber => HttpResponse::BadRequest().json(e),
|
||||
Self::DuplicateVerificationOTP => HttpResponse::InternalServerError().json(e),
|
||||
Self::PhoneNumberNotFound => HttpResponse::Unauthorized().json(e), // (?)
|
||||
Self::EmployeeNotFound => HttpResponse::NotFound().json(e),
|
||||
Self::InviteNotFound => HttpResponse::NotFound().json(e),
|
||||
Self::StoreNotFound => HttpResponse::NotFound().json(e),
|
||||
Self::DuplicateStoreName => HttpResponse::BadRequest().json(e),
|
||||
Self::StoreIDNotFound => HttpResponse::NotFound().json(e),
|
||||
Self::DuplicateStoreID => HttpResponse::InternalServerError().json(e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub type WebJsonRepsonse<V> = Result<V, WebError>;
|
30
src/identity/adapters/input/web/mod.rs
Normal file
30
src/identity/adapters/input/web/mod.rs
Normal file
|
@ -0,0 +1,30 @@
|
|||
// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use actix_web::web;
|
||||
|
||||
use crate::identity::adapters::types;
|
||||
|
||||
mod employee;
|
||||
mod errors;
|
||||
mod owner;
|
||||
mod routes;
|
||||
|
||||
pub use errors::WebJsonRepsonse;
|
||||
|
||||
pub use routes::RoutesRepository;
|
||||
|
||||
pub fn load_ctx() -> impl FnOnce(&mut web::ServiceConfig) {
|
||||
let routes = types::WebIdentityRoutesRepository::new(Arc::new(RoutesRepository::default()));
|
||||
|
||||
let f = move |cfg: &mut web::ServiceConfig| {
|
||||
cfg.app_data(routes);
|
||||
cfg.configure(owner::services);
|
||||
cfg.configure(employee::services);
|
||||
};
|
||||
|
||||
Box::new(f)
|
||||
}
|
420
src/identity/adapters/input/web/owner.rs
Normal file
420
src/identity/adapters/input/web/owner.rs
Normal file
|
@ -0,0 +1,420 @@
|
|||
// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
use actix_identity::Identity;
|
||||
use actix_web::{get, http::header::ContentType, post, web, HttpRequest, HttpResponse, Responder};
|
||||
use derive_builder::Builder;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use url::Url;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::errors::*;
|
||||
use super::types;
|
||||
//use crate::utils::uuid::WebGetUUIDInterfaceObj;
|
||||
|
||||
pub fn services(cfg: &mut web::ServiceConfig) {
|
||||
cfg.service(login_ui_handler);
|
||||
cfg.service(login_form_submission_handler);
|
||||
|
||||
cfg.service(register_ui_handler);
|
||||
cfg.service(register_form_submission_handler);
|
||||
|
||||
cfg.service(update_email_ui_handler);
|
||||
cfg.service(update_email_form_submission_handler);
|
||||
|
||||
cfg.service(change_password_ui_handler);
|
||||
cfg.service(change_password_form_submission_handler);
|
||||
|
||||
cfg.service(delete_user_ui_handler);
|
||||
cfg.service(delete_user_form_submission_handler);
|
||||
|
||||
cfg.service(verify_email_ui_handler);
|
||||
cfg.service(verify_email_form_submission_handler);
|
||||
cfg.service(resend_verification_email);
|
||||
|
||||
cfg.service(add_store_ui_handler);
|
||||
cfg.service(add_store_form_submission_handler);
|
||||
|
||||
cfg.service(update_store_ui_handler);
|
||||
cfg.service(update_store_form_submission_handler);
|
||||
}
|
||||
|
||||
// login handlers
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[get("/owner/login")]
|
||||
#[tracing::instrument(name = "login UI handler", skip())]
|
||||
async fn login_ui_handler() -> WebJsonRepsonse<impl Responder> {
|
||||
use web_ui::identity::owner_login::*;
|
||||
|
||||
let page = OwnerLoginPage::page();
|
||||
|
||||
Ok(HttpResponse::Ok()
|
||||
.insert_header(ContentType::html())
|
||||
.body(page))
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
|
||||
struct OwnerLoginPayload {
|
||||
email: String,
|
||||
password: String,
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[post("/owner/login")]
|
||||
#[tracing::instrument(
|
||||
name = "Login form submission handler"
|
||||
skip(id, req, payload, identity_cqrs_exec)
|
||||
)]
|
||||
async fn login_form_submission_handler(
|
||||
identity_cqrs_exec: types::WebIdentityCqrsExec,
|
||||
req: HttpRequest,
|
||||
id: Identity,
|
||||
payload: web::Form<OwnerLoginPayload>,
|
||||
) -> WebJsonRepsonse<impl Responder> {
|
||||
let store = "";
|
||||
|
||||
Ok(HttpResponse::Ok().json(store))
|
||||
}
|
||||
|
||||
// register handlers
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[get("/owner/register")]
|
||||
#[tracing::instrument(name = "register UI handler", skip())]
|
||||
async fn register_ui_handler() -> WebJsonRepsonse<impl Responder> {
|
||||
use web_ui::identity::owner_register::*;
|
||||
|
||||
let page = OwnerRegisterPage::page();
|
||||
|
||||
Ok(HttpResponse::Ok()
|
||||
.insert_header(ContentType::html())
|
||||
.body(page))
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
|
||||
struct OwnerRegisterPayload {
|
||||
password: String,
|
||||
confirm_password: String,
|
||||
first_name: String,
|
||||
last_name: String,
|
||||
email: String,
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[post("/owner/register")]
|
||||
#[tracing::instrument(
|
||||
name = "Register form submission handler"
|
||||
skip(id, req, payload, identity_cqrs_exec)
|
||||
)]
|
||||
async fn register_form_submission_handler(
|
||||
identity_cqrs_exec: types::WebIdentityCqrsExec,
|
||||
req: HttpRequest,
|
||||
id: Identity,
|
||||
payload: web::Form<OwnerRegisterPayload>,
|
||||
) -> WebJsonRepsonse<impl Responder> {
|
||||
let store = "";
|
||||
|
||||
Ok(HttpResponse::Ok().json(store))
|
||||
}
|
||||
|
||||
// update email handlers
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[get("/owner/user/email/update")]
|
||||
#[tracing::instrument(name = "Update email UI handler", skip())]
|
||||
async fn update_email_ui_handler() -> WebJsonRepsonse<impl Responder> {
|
||||
use web_ui::identity::owner_update_email::*;
|
||||
|
||||
let page = OwnerUpdateEmailPage::page();
|
||||
|
||||
Ok(HttpResponse::Ok()
|
||||
.insert_header(ContentType::html())
|
||||
.body(page))
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
|
||||
struct OwnerUpdateEmailPayload {
|
||||
password: String,
|
||||
new_email: String,
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[post("/owner/user/email/update")]
|
||||
#[tracing::instrument(
|
||||
name = "Update email form submission handler"
|
||||
skip(id, req, payload, identity_cqrs_exec)
|
||||
)]
|
||||
async fn update_email_form_submission_handler(
|
||||
identity_cqrs_exec: types::WebIdentityCqrsExec,
|
||||
req: HttpRequest,
|
||||
id: Identity,
|
||||
payload: web::Form<OwnerUpdateEmailPayload>,
|
||||
) -> WebJsonRepsonse<impl Responder> {
|
||||
let store = "";
|
||||
|
||||
Ok(HttpResponse::Ok().json(store))
|
||||
}
|
||||
|
||||
// change password handlers
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[get("/owner/user/password/change")]
|
||||
#[tracing::instrument(name = "Change password UI handler", skip())]
|
||||
async fn change_password_ui_handler() -> WebJsonRepsonse<impl Responder> {
|
||||
use web_ui::identity::owner_change_password::*;
|
||||
|
||||
let page = OwnerChangePasswordPage::page();
|
||||
|
||||
Ok(HttpResponse::Ok()
|
||||
.insert_header(ContentType::html())
|
||||
.body(page))
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
|
||||
struct OwnerChangePasswordPayload {
|
||||
current_password: String,
|
||||
new_password: String,
|
||||
confirm_new_password: String,
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[post("/owner/user/email/update")]
|
||||
#[tracing::instrument(
|
||||
name = "Change password form submission handler"
|
||||
skip(id, req, payload, identity_cqrs_exec)
|
||||
)]
|
||||
async fn change_password_form_submission_handler(
|
||||
identity_cqrs_exec: types::WebIdentityCqrsExec,
|
||||
req: HttpRequest,
|
||||
id: Identity,
|
||||
payload: web::Form<OwnerChangePasswordPayload>,
|
||||
) -> WebJsonRepsonse<impl Responder> {
|
||||
let store = "";
|
||||
|
||||
Ok(HttpResponse::Ok().json(store))
|
||||
}
|
||||
|
||||
// Delete user handlers
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[get("/owner/user/delete")]
|
||||
#[tracing::instrument(name = "Delete user UI handler", skip())]
|
||||
async fn delete_user_ui_handler() -> WebJsonRepsonse<impl Responder> {
|
||||
use web_ui::identity::owner_delete_user::*;
|
||||
|
||||
let page = OwnerDeleteUserPage::page();
|
||||
|
||||
Ok(HttpResponse::Ok()
|
||||
.insert_header(ContentType::html())
|
||||
.body(page))
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
|
||||
struct OwnerDeleteUser {
|
||||
password: String,
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[post("/owner/user/delete")]
|
||||
#[tracing::instrument(
|
||||
name = "Delete user form submission handler"
|
||||
skip(id, req, payload, identity_cqrs_exec)
|
||||
)]
|
||||
async fn delete_user_form_submission_handler(
|
||||
identity_cqrs_exec: types::WebIdentityCqrsExec,
|
||||
req: HttpRequest,
|
||||
id: Identity,
|
||||
payload: web::Form<OwnerChangePasswordPayload>,
|
||||
) -> WebJsonRepsonse<impl Responder> {
|
||||
let store = "";
|
||||
|
||||
Ok(HttpResponse::Ok().json(store))
|
||||
}
|
||||
|
||||
// Verify email handler
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[get("/owner/user/email/verify")]
|
||||
#[tracing::instrument(name = "Verify email UI handler", skip())]
|
||||
async fn verify_email_ui_handler() -> WebJsonRepsonse<impl Responder> {
|
||||
use web_ui::identity::owner_verify_email::*;
|
||||
|
||||
let page = OwnerVerifyEmailPage::page();
|
||||
|
||||
Ok(HttpResponse::Ok()
|
||||
.insert_header(ContentType::html())
|
||||
.body(page))
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[post("/owner/user/email/verify")]
|
||||
#[tracing::instrument(
|
||||
name = "Verify email form submission handler"
|
||||
skip(id, req, identity_cqrs_exec)
|
||||
)]
|
||||
async fn verify_email_form_submission_handler(
|
||||
identity_cqrs_exec: types::WebIdentityCqrsExec,
|
||||
req: HttpRequest,
|
||||
id: Identity,
|
||||
) -> WebJsonRepsonse<impl Responder> {
|
||||
let store = "";
|
||||
|
||||
Ok(HttpResponse::Ok().json(store))
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[get("/owner/user/email/verify/resend")]
|
||||
#[tracing::instrument(
|
||||
name = "Resend verification email handler",
|
||||
skip(req, identity_cqrs_exec)
|
||||
)]
|
||||
async fn resend_verification_email(
|
||||
identity_cqrs_exec: types::WebIdentityCqrsExec,
|
||||
req: HttpRequest,
|
||||
// id: Identity,
|
||||
) -> WebJsonRepsonse<impl Responder> {
|
||||
let store = "";
|
||||
|
||||
Ok(HttpResponse::Ok().json(store))
|
||||
}
|
||||
|
||||
// add store handler
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[get("/owner/store")]
|
||||
#[tracing::instrument(name = "Add store UI handler", skip())]
|
||||
async fn add_store_ui_handler() -> WebJsonRepsonse<impl Responder> {
|
||||
use web_ui::identity::owner_add_store::*;
|
||||
|
||||
let page = OwnerAddStorePage::page();
|
||||
|
||||
Ok(HttpResponse::Ok()
|
||||
.insert_header(ContentType::html())
|
||||
.body(page))
|
||||
}
|
||||
|
||||
#[derive(Clone, Builder, Debug, Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd)]
|
||||
pub struct OnwerAddStorePayload {
|
||||
name: String,
|
||||
address: Option<String>,
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[post("/owner/store")]
|
||||
#[tracing::instrument(
|
||||
name = "Add store form submission handler"
|
||||
skip(id, req, identity_cqrs_exec)
|
||||
)]
|
||||
async fn add_store_form_submission_handler(
|
||||
identity_cqrs_exec: types::WebIdentityCqrsExec,
|
||||
req: HttpRequest,
|
||||
id: Identity,
|
||||
paylod: web::Form<OnwerAddStorePayload>,
|
||||
) -> WebJsonRepsonse<impl Responder> {
|
||||
let store = "";
|
||||
|
||||
Ok(HttpResponse::Ok().json(store))
|
||||
}
|
||||
|
||||
// Update store handler
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[get("/owner/store/update")]
|
||||
#[tracing::instrument(name = "Add store UI handler", skip())]
|
||||
async fn update_store_ui_handler() -> WebJsonRepsonse<impl Responder> {
|
||||
use web_ui::identity::owner_update_store::*;
|
||||
|
||||
let page = OwnerUpdateStorePage::page();
|
||||
|
||||
Ok(HttpResponse::Ok()
|
||||
.insert_header(ContentType::html())
|
||||
.body(page))
|
||||
}
|
||||
|
||||
#[derive(Clone, Builder, Debug, Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd)]
|
||||
pub struct OnwerUpdatetorePayload {
|
||||
name: String,
|
||||
address: Option<String>,
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[post("/owner/store/update")]
|
||||
#[tracing::instrument(
|
||||
name = "Update store form submission handler"
|
||||
skip(id, req, identity_cqrs_exec)
|
||||
)]
|
||||
async fn update_store_form_submission_handler(
|
||||
identity_cqrs_exec: types::WebIdentityCqrsExec,
|
||||
req: HttpRequest,
|
||||
id: Identity,
|
||||
paylod: web::Form<OnwerUpdatetorePayload>,
|
||||
) -> WebJsonRepsonse<impl Responder> {
|
||||
let store = "";
|
||||
|
||||
Ok(HttpResponse::Ok().json(store))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
use crate::identity::adapters::input::web::RoutesRepository;
|
||||
use crate::tests::actix_web_test_utils::page_test_runner;
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn identity_web_owner_login_ui_works() {
|
||||
let routes = RoutesRepository::default();
|
||||
|
||||
page_test_runner(&routes.owner_login).await;
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn identity_web_owner_register_ui_works() {
|
||||
let routes = RoutesRepository::default();
|
||||
page_test_runner(&routes.owner_register).await;
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn identity_web_owner_delete_ui_works() {
|
||||
let routes = RoutesRepository::default();
|
||||
page_test_runner(&routes.owner_delete).await;
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn identity_web_owner_verify_email_ui_works() {
|
||||
let routes = RoutesRepository::default();
|
||||
page_test_runner(&routes.owner_verify_email).await;
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn identity_web_owner_resend_verification_email_ui_works() {
|
||||
let routes = RoutesRepository::default();
|
||||
page_test_runner(&routes.owner_resend_verification_email).await;
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn identity_web_owner_update_email_ui_works() {
|
||||
let routes = RoutesRepository::default();
|
||||
page_test_runner(&routes.owner_update_email).await;
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn identity_web_owner_change_password_ui_works() {
|
||||
let routes = RoutesRepository::default();
|
||||
page_test_runner(&routes.owner_change_password).await;
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn identity_web_owner_add_store_ui_works() {
|
||||
let routes = RoutesRepository::default();
|
||||
page_test_runner(&routes.owner_add_store).await;
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn identity_web_owner_update_store_ui_works() {
|
||||
let routes = RoutesRepository::default();
|
||||
page_test_runner(&routes.owner_update_store).await;
|
||||
}
|
||||
}
|
86
src/identity/adapters/input/web/routes.rs
Normal file
86
src/identity/adapters/input/web/routes.rs
Normal file
|
@ -0,0 +1,86 @@
|
|||
// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
use url::Url;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub struct RoutesRepository {
|
||||
pub owner_login: String,
|
||||
pub owner_register: String,
|
||||
pub owner_delete: String,
|
||||
pub owner_verify_email: String,
|
||||
pub owner_resend_verification_email: String,
|
||||
// owner_set_admin: String,
|
||||
pub owner_update_email: String,
|
||||
pub owner_change_password: String,
|
||||
|
||||
pub owner_add_store: String,
|
||||
pub owner_update_store: String,
|
||||
|
||||
pub employee_exit_organization: String,
|
||||
pub employee_login: String,
|
||||
pub employee_register: String,
|
||||
pub employee_resend_login_otp: String,
|
||||
pub employee_resend_verification_otp: String,
|
||||
pub employee_verify_phone_number: String,
|
||||
}
|
||||
|
||||
impl Default for RoutesRepository {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
owner_login: "/owner/login".into(),
|
||||
owner_register: "/owner/register".into(),
|
||||
owner_delete: "/owner/user/delete".into(),
|
||||
owner_verify_email: "/owner/user/email/verify".into(),
|
||||
owner_resend_verification_email: "/owner/user/email/verify/resend".into(),
|
||||
owner_update_email: "/owner/user/email/update".into(),
|
||||
owner_change_password: "/owner/user/password/change".into(),
|
||||
//owner_set_admin: "/owner/user/promote/admin".into(),
|
||||
owner_add_store: "/owner/store".into(),
|
||||
owner_update_store: "/owner/store/update".into(),
|
||||
|
||||
employee_login: "/employee/login".into(),
|
||||
employee_register: "/employee/register".into(),
|
||||
employee_resend_login_otp: "/employee/login/resend_otp".into(),
|
||||
employee_resend_verification_otp: "/employee/user/phone/verify/resend_otp".into(),
|
||||
employee_verify_phone_number: "/employee/user/phone/verify".into(),
|
||||
employee_exit_organization: "/employee/organization/exit".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl RoutesRepository {
|
||||
// pub fn update_bill(&self, bill_id: Uuid) -> String {
|
||||
// self.update_bill
|
||||
// .replace("{bill_uuid}", &bill_id.to_string())
|
||||
// }
|
||||
|
||||
// pub fn delete_bill(&self, bill_id: Uuid) -> String {
|
||||
// self.delete_bill
|
||||
// .replace("{bill_uuid}", &bill_id.to_string())
|
||||
// }
|
||||
|
||||
// pub fn compute_total_price_for_bill(&self, bill_id: Uuid) -> String {
|
||||
// self.compute_total_price_for_bill
|
||||
// .replace("{bill_uuid}", &bill_id.to_string())
|
||||
// }
|
||||
|
||||
// pub fn add_line_item(&self, bill_id: Uuid) -> String {
|
||||
// self.add_line_item
|
||||
// .replace("{bill_uuid}", &bill_id.to_string())
|
||||
// }
|
||||
|
||||
// pub fn update_line_item(&self, bill_id: Uuid, line_item_uuid: Uuid) -> String {
|
||||
// self.update_line_item
|
||||
// .replace("{bill_uuid}", &bill_id.to_string())
|
||||
// .replace("{line_item_uuid}", &line_item_uuid.to_string())
|
||||
// }
|
||||
|
||||
// pub fn delete_line_item(&self, bill_id: Uuid, line_item_uuid: Uuid) -> String {
|
||||
// self.delete_line_item
|
||||
// .replace("{bill_uuid}", &bill_id.to_string())
|
||||
// .replace("{line_item_uuid}", &line_item_uuid.to_string())
|
||||
// }
|
||||
}
|
|
@ -2,5 +2,99 @@
|
|||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use actix_web::web::{self, Data};
|
||||
use cqrs_es::{persist::ViewRepository, EventEnvelope, Query, View};
|
||||
use postgres_es::PostgresCqrs;
|
||||
use sqlx::postgres::PgPool;
|
||||
|
||||
use crate::identity::{
|
||||
application::services::{IdentityServices, IdentityServicesObj},
|
||||
domain::{aggregate::User, employee_aggregate::Employee, store_aggregate::Store},
|
||||
};
|
||||
use crate::settings::Settings;
|
||||
use output::{
|
||||
db::postgres::{employee_view, store_view, user_view, DBOutPostgresAdapter},
|
||||
mailer::lettre::LettreMailer,
|
||||
phone::twilio::Phone,
|
||||
};
|
||||
|
||||
mod input;
|
||||
pub mod output;
|
||||
mod types;
|
||||
|
||||
pub fn load_adapters(pool: PgPool, settings: Settings) -> impl FnOnce(&mut web::ServiceConfig) {
|
||||
// init DB
|
||||
let db = DBOutPostgresAdapter::new(pool.clone());
|
||||
let mailer = LettreMailer::new(&settings);
|
||||
let phone = Phone::new(&settings);
|
||||
|
||||
let services: IdentityServicesObj = IdentityServices::new(
|
||||
Arc::new(db.clone()),
|
||||
Arc::new(db.clone()),
|
||||
Arc::new(db.clone()),
|
||||
Arc::new(db.clone()),
|
||||
Arc::new(db.clone()),
|
||||
Arc::new(db.clone()),
|
||||
Arc::new(db.clone()),
|
||||
Arc::new(db.clone()),
|
||||
Arc::new(db.clone()),
|
||||
Arc::new(db.clone()),
|
||||
Arc::new(db.clone()),
|
||||
Arc::new(db.clone()),
|
||||
Arc::new(db.clone()),
|
||||
Arc::new(db.clone()),
|
||||
Arc::new(db.clone()),
|
||||
Arc::new(db.clone()),
|
||||
Arc::new(db.clone()),
|
||||
Arc::new(mailer.clone()),
|
||||
Arc::new(phone.clone()),
|
||||
Arc::new(phone.clone()),
|
||||
crate::utils::uuid::GenerateUUID::new(),
|
||||
crate::utils::random_string::GenerateRandomString::new(),
|
||||
crate::utils::random_number::GenerateRandomNumber::new(),
|
||||
);
|
||||
|
||||
let (user_cqrs_exec, user_cqrs_query) = user_view::init_cqrs(db.clone(), services.clone());
|
||||
let (store_cqrs_exec, store_cqrs_query) = store_view::init_cqrs(db.clone(), services.clone());
|
||||
let (employee_cqrs_exec, employee_cqrs_query) =
|
||||
employee_view::init_cqrs(db.clone(), services.clone());
|
||||
|
||||
let identity_cqrs_exec = types::WebIdentityCqrsExec::new(Arc::new(
|
||||
types::IdentityCqrsExecBuilder::default()
|
||||
.user(user_cqrs_exec)
|
||||
.employee(employee_cqrs_exec)
|
||||
.store(store_cqrs_exec)
|
||||
.build()
|
||||
.unwrap(),
|
||||
));
|
||||
|
||||
let f = move |cfg: &mut web::ServiceConfig| {
|
||||
cfg.configure(input::web::load_ctx());
|
||||
|
||||
cfg.app_data(Data::new(user_cqrs_query.clone()));
|
||||
cfg.app_data(Data::new(store_cqrs_query.clone()));
|
||||
cfg.app_data(Data::new(employee_cqrs_query.clone()));
|
||||
cfg.app_data(identity_cqrs_exec.clone());
|
||||
};
|
||||
|
||||
Box::new(f)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::db::migrate::*;
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn identity_load_adapters() {
|
||||
let settings = crate::settings::tests::get_settings().await;
|
||||
settings.create_db().await;
|
||||
|
||||
let db = crate::db::sqlx_postgres::Postgres::init(&settings.database.url).await;
|
||||
db.migrate().await;
|
||||
|
||||
load_adapters(db.pool.clone(), settings.clone());
|
||||
}
|
||||
}
|
||||
|
|
|
@ -3,6 +3,7 @@
|
|||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
use std::str::FromStr;
|
||||
use std::sync::Arc;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use cqrs_es::persist::{PersistenceError, ViewContext, ViewRepository};
|
||||
|
@ -13,7 +14,8 @@ use uuid::Uuid;
|
|||
|
||||
use super::errors::*;
|
||||
use super::DBOutPostgresAdapter;
|
||||
use crate::identity::application::services::events::IdentityEvent;
|
||||
use crate::identity::adapters::types::{IdentityEmployeeCqrsExec, IdentityEmployeeCqrsView};
|
||||
use crate::identity::application::services::{events::IdentityEvent, IdentityServicesObj};
|
||||
use crate::identity::domain::employee_aggregate::*;
|
||||
use crate::types::currency::{self, Currency, PriceBuilder};
|
||||
use crate::utils::parse_aggregate_id::parse_aggregate_id;
|
||||
|
@ -100,7 +102,7 @@ impl View<Employee> for EmployeeView {
|
|||
IdentityEvent::PhoneNumberVerified(e) => self.phone_verified = true,
|
||||
IdentityEvent::VerificationOTPResent(e) => (),
|
||||
IdentityEvent::PhoneNumberChanged(e) => unimplemented!(),
|
||||
IdentityEvent::InviteAccepted(e) => self.store_id = Some(*e.store_id()),
|
||||
// IdentityEvent::InviteAccepted(e) => self.store_id = Some(*e.store_id()),
|
||||
IdentityEvent::OrganizationExited(e) => self.store_id = None,
|
||||
|
||||
_ => (),
|
||||
|
@ -287,6 +289,20 @@ impl Query<Employee> for DBOutPostgresAdapter {
|
|||
}
|
||||
}
|
||||
|
||||
pub fn init_cqrs(
|
||||
db: DBOutPostgresAdapter,
|
||||
services: IdentityServicesObj,
|
||||
) -> (IdentityEmployeeCqrsExec, IdentityEmployeeCqrsView) {
|
||||
let queries: Vec<Box<dyn Query<Employee>>> = vec![Box::new(db.clone())];
|
||||
|
||||
let pool = db.pool.clone();
|
||||
|
||||
(
|
||||
Arc::new(postgres_es::postgres_cqrs(pool.clone(), queries, services)),
|
||||
Arc::new(db.clone()),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
|
|
@ -15,6 +15,7 @@ pub mod email_exists;
|
|||
pub mod employee_view;
|
||||
mod errors;
|
||||
pub mod get_verification_secret;
|
||||
pub mod store_view;
|
||||
pub mod user_id_exists;
|
||||
pub mod user_view;
|
||||
pub mod verification_secret_exists;
|
||||
|
@ -31,7 +32,8 @@ pub mod phone_exists;
|
|||
|
||||
//pub mod get_invite;
|
||||
//pub mod invite_id_exists;
|
||||
//pub mod store_id_exists;
|
||||
pub mod store_id_exists;
|
||||
pub mod store_name_exists;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct DBOutPostgresAdapter {
|
||||
|
|
87
src/identity/adapters/output/db/postgres/store_id_exists.rs
Normal file
87
src/identity/adapters/output/db/postgres/store_id_exists.rs
Normal file
|
@ -0,0 +1,87 @@
|
|||
// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::DBOutPostgresAdapter;
|
||||
use crate::identity::application::port::output::db::{errors::*, store_id_exists::*};
|
||||
use crate::identity::domain::store_aggregate::*;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl StoreIDExistsDBPort for DBOutPostgresAdapter {
|
||||
async fn store_id_exists(&self, store_id: &Uuid) -> OutDBPortResult<bool> {
|
||||
let res = sqlx::query!(
|
||||
"SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM cqrs_identity_store_query
|
||||
WHERE
|
||||
store_id = $1
|
||||
);",
|
||||
store_id
|
||||
)
|
||||
.fetch_one(&self.pool)
|
||||
.await?;
|
||||
if let Some(x) = res.exists {
|
||||
Ok(x)
|
||||
} else {
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub mod tests {
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::utils::uuid::tests::UUID;
|
||||
|
||||
use super::*;
|
||||
|
||||
pub async fn create_dummy_store_record(s: &Store, db: &DBOutPostgresAdapter) {
|
||||
sqlx::query!(
|
||||
"INSERT INTO cqrs_identity_store_query
|
||||
(version, name, address, store_id, owner, deleted)
|
||||
VALUES ($1, $2, $3, $4, $5 ,$6);",
|
||||
1,
|
||||
s.name(),
|
||||
s.address().as_ref().map(|s| s.as_str()),
|
||||
s.store_id(),
|
||||
s.owner(),
|
||||
false
|
||||
)
|
||||
.execute(&db.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn test_postgres_store_exists() {
|
||||
let store_id = Uuid::new_v4();
|
||||
let settings = crate::settings::tests::get_settings().await;
|
||||
settings.create_db().await;
|
||||
let db = super::DBOutPostgresAdapter::new(
|
||||
sqlx::postgres::PgPool::connect(&settings.database.url)
|
||||
.await
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
let store = StoreBuilder::default()
|
||||
.name("store_name".into())
|
||||
.owner(UUID)
|
||||
.address(Some("store_address".into()))
|
||||
.store_id(store_id)
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
// state doesn't exist
|
||||
assert!(!db.store_id_exists(store.store_id()).await.unwrap());
|
||||
|
||||
create_dummy_store_record(&store, &db).await;
|
||||
|
||||
// state exists
|
||||
assert!(db.store_id_exists(store.store_id()).await.unwrap());
|
||||
|
||||
settings.drop_db().await;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,81 @@
|
|||
// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
use super::DBOutPostgresAdapter;
|
||||
use crate::identity::application::port::output::db::{errors::*, store_name_exists::*};
|
||||
use crate::identity::domain::store_aggregate::*;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl StoreNameExistsDBPort for DBOutPostgresAdapter {
|
||||
async fn store_name_exists(&self, s: &Store) -> OutDBPortResult<bool> {
|
||||
let res = sqlx::query!(
|
||||
"SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM cqrs_identity_store_query
|
||||
WHERE
|
||||
name = $1
|
||||
AND
|
||||
deleted = false
|
||||
);",
|
||||
s.name(),
|
||||
)
|
||||
.fetch_one(&self.pool)
|
||||
.await?;
|
||||
if let Some(x) = res.exists {
|
||||
Ok(x)
|
||||
} else {
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::utils::uuid::tests::UUID;
|
||||
|
||||
use super::*;
|
||||
use crate::identity::adapters::output::db::postgres::store_id_exists::tests::create_dummy_store_record;
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn test_postgres_store_exists() {
|
||||
let store_id = Uuid::new_v4();
|
||||
let settings = crate::settings::tests::get_settings().await;
|
||||
settings.create_db().await;
|
||||
let db = super::DBOutPostgresAdapter::new(
|
||||
sqlx::postgres::PgPool::connect(&settings.database.url)
|
||||
.await
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
let store = StoreBuilder::default()
|
||||
.name("store_name".into())
|
||||
.owner(UUID)
|
||||
.address(Some("store_address".into()))
|
||||
.store_id(store_id)
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
// state doesn't exist
|
||||
assert!(!db.store_name_exists(&store).await.unwrap());
|
||||
|
||||
create_dummy_store_record(&store, &db).await;
|
||||
|
||||
// state exists
|
||||
assert!(db.store_name_exists(&store).await.unwrap());
|
||||
|
||||
// Set store.deleted = true; now db.store_name_exists must return false
|
||||
sqlx::query!(
|
||||
"UPDATE cqrs_identity_store_query SET deleted = true WHERE store_id = $1;",
|
||||
store.store_id()
|
||||
)
|
||||
.execute(&db.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(!db.store_name_exists(&store).await.unwrap());
|
||||
|
||||
settings.drop_db().await;
|
||||
}
|
||||
}
|
371
src/identity/adapters/output/db/postgres/store_view.rs
Normal file
371
src/identity/adapters/output/db/postgres/store_view.rs
Normal file
|
@ -0,0 +1,371 @@
|
|||
// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
use std::sync::Arc;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use cqrs_es::persist::{PersistenceError, ViewContext, ViewRepository};
|
||||
use cqrs_es::{EventEnvelope, Query, View};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::errors::*;
|
||||
use super::DBOutPostgresAdapter;
|
||||
use crate::identity::adapters::types::{IdentityStoreCqrsExec, IdentityStoreCqrsView};
|
||||
use crate::identity::application::services::{
|
||||
events::IdentityEvent, IdentityCommand, IdentityServicesObj,
|
||||
};
|
||||
use crate::identity::domain::store_aggregate::*;
|
||||
use crate::utils::parse_aggregate_id::parse_aggregate_id;
|
||||
|
||||
pub const NEW_STORE_NON_UUID: &str = "identity_new_store_non_uuid-asdfa";
|
||||
|
||||
// The view for a Store query, for a standard http application this should
|
||||
// be designed to reflect the response dto that will be returned to a user.
|
||||
#[derive(Debug, Default, Serialize, Deserialize)]
|
||||
pub struct StoreView {
|
||||
name: String,
|
||||
address: Option<String>,
|
||||
store_id: Uuid,
|
||||
owner: Uuid,
|
||||
deleted: bool,
|
||||
}
|
||||
|
||||
impl From<StoreView> for Store {
|
||||
fn from(value: StoreView) -> Self {
|
||||
StoreBuilder::default()
|
||||
.name(value.name)
|
||||
.address(value.address)
|
||||
.store_id(value.store_id)
|
||||
.owner(value.owner)
|
||||
.deleted(value.deleted)
|
||||
.build()
|
||||
.unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
// This updates the view with events as they are committed.
|
||||
// The logic should be minimal here, e.g., don't calculate the account balance,
|
||||
// design the events to carry the balance information instead.
|
||||
impl View<Store> for StoreView {
|
||||
fn update(&mut self, event: &EventEnvelope<Store>) {
|
||||
match &event.payload {
|
||||
IdentityEvent::StoreAdded(val) => {
|
||||
self.name = val.name().into();
|
||||
self.address = val.address().clone();
|
||||
self.store_id = *val.store_id();
|
||||
self.owner = *val.owner();
|
||||
self.deleted = false;
|
||||
}
|
||||
IdentityEvent::StoreUpdated(e) => {
|
||||
let val = e.new_store();
|
||||
self.name = val.name().into();
|
||||
self.address = val.address().clone();
|
||||
self.store_id = *val.store_id();
|
||||
self.owner = *val.owner();
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl ViewRepository<StoreView, Store> for DBOutPostgresAdapter {
|
||||
async fn load(&self, store_id: &str) -> Result<Option<StoreView>, PersistenceError> {
|
||||
let store_id = match parse_aggregate_id(store_id, NEW_STORE_NON_UUID)? {
|
||||
Some((val, _)) => return Ok(Some(val)),
|
||||
None => Uuid::parse_str(store_id).unwrap(),
|
||||
};
|
||||
|
||||
let res = sqlx::query_as!(
|
||||
StoreView,
|
||||
"SELECT
|
||||
name, address, store_id, owner, deleted
|
||||
FROM
|
||||
cqrs_identity_store_query
|
||||
WHERE
|
||||
store_id = $1;",
|
||||
store_id
|
||||
)
|
||||
.fetch_one(&self.pool)
|
||||
.await
|
||||
.map_err(PostgresAggregateError::from)?;
|
||||
Ok(Some(res))
|
||||
}
|
||||
|
||||
async fn load_with_context(
|
||||
&self,
|
||||
store_id: &str,
|
||||
) -> Result<Option<(StoreView, ViewContext)>, PersistenceError> {
|
||||
let store_id = match parse_aggregate_id(store_id, NEW_STORE_NON_UUID)? {
|
||||
Some(val) => return Ok(Some(val)),
|
||||
None => Uuid::parse_str(store_id).unwrap(),
|
||||
};
|
||||
|
||||
let res = sqlx::query_as!(
|
||||
StoreView,
|
||||
"SELECT
|
||||
name, address, store_id, owner, deleted
|
||||
FROM
|
||||
cqrs_identity_store_query
|
||||
WHERE
|
||||
store_id = $1;",
|
||||
&store_id,
|
||||
)
|
||||
.fetch_one(&self.pool)
|
||||
.await
|
||||
.map_err(PostgresAggregateError::from)?;
|
||||
|
||||
struct Context {
|
||||
version: i64,
|
||||
store_id: Uuid,
|
||||
}
|
||||
|
||||
let ctx = sqlx::query_as!(
|
||||
Context,
|
||||
"SELECT
|
||||
store_id, version
|
||||
FROM
|
||||
cqrs_identity_store_query
|
||||
WHERE
|
||||
store_id = $1;",
|
||||
store_id
|
||||
)
|
||||
.fetch_one(&self.pool)
|
||||
.await
|
||||
.map_err(PostgresAggregateError::from)?;
|
||||
|
||||
let view_context = ViewContext::new(ctx.store_id.to_string(), ctx.version);
|
||||
Ok(Some((res, view_context)))
|
||||
}
|
||||
|
||||
async fn update_view(
|
||||
&self,
|
||||
view: StoreView,
|
||||
context: ViewContext,
|
||||
) -> Result<(), PersistenceError> {
|
||||
match context.version {
|
||||
0 => {
|
||||
let version = context.version + 1;
|
||||
sqlx::query!(
|
||||
"INSERT INTO cqrs_identity_store_query (
|
||||
version, name, address, store_id, owner, deleted
|
||||
) VALUES (
|
||||
$1, $2, $3, $4, $5, $6
|
||||
);",
|
||||
version,
|
||||
view.name,
|
||||
view.address,
|
||||
view.store_id,
|
||||
view.owner,
|
||||
view.deleted,
|
||||
)
|
||||
.execute(&self.pool)
|
||||
.await
|
||||
.map_err(PostgresAggregateError::from)?;
|
||||
}
|
||||
_ => {
|
||||
let version = context.version + 1;
|
||||
sqlx::query!(
|
||||
"UPDATE
|
||||
cqrs_identity_store_query
|
||||
SET
|
||||
version = $1,
|
||||
name = $2,
|
||||
address = $3,
|
||||
owner = $4,
|
||||
deleted = $5;",
|
||||
version,
|
||||
view.name,
|
||||
view.address,
|
||||
view.owner,
|
||||
view.deleted,
|
||||
)
|
||||
.execute(&self.pool)
|
||||
.await
|
||||
.map_err(PostgresAggregateError::from)?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct SimpleLoggingQuery {}
|
||||
|
||||
// Our simplest query, this is great for debugging but absolutely useless in production.
|
||||
// This query just pretty prints the events as they are processed.
|
||||
#[async_trait]
|
||||
impl Query<Store> for SimpleLoggingQuery {
|
||||
async fn dispatch(&self, aggregate_id: &str, events: &[EventEnvelope<Store>]) {
|
||||
for event in events {
|
||||
let payload = serde_json::to_string_pretty(&event.payload).unwrap();
|
||||
println!("{}-{}\n{}", aggregate_id, event.sequence, payload);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Query<Store> for DBOutPostgresAdapter {
|
||||
async fn dispatch(&self, store_id: &str, events: &[EventEnvelope<Store>]) {
|
||||
let res = self
|
||||
.load_with_context(store_id)
|
||||
.await
|
||||
.unwrap_or_else(|_| Some((StoreView::default(), ViewContext::new(store_id.into(), 0))));
|
||||
let (mut view, view_context): (StoreView, ViewContext) = res.unwrap();
|
||||
for event in events {
|
||||
view.update(event);
|
||||
}
|
||||
self.update_view(view, view_context).await.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init_cqrs(
|
||||
db: DBOutPostgresAdapter,
|
||||
services: IdentityServicesObj,
|
||||
) -> (IdentityStoreCqrsExec, IdentityStoreCqrsView) {
|
||||
let queries: Vec<Box<dyn Query<Store>>> = vec![Box::new(db.clone())];
|
||||
|
||||
let pool = db.pool.clone();
|
||||
|
||||
(
|
||||
Arc::new(postgres_es::postgres_cqrs(pool.clone(), queries, services)),
|
||||
Arc::new(db.clone()),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
use postgres_es::PostgresCqrs;
|
||||
|
||||
use crate::{
|
||||
db::migrate::*,
|
||||
identity::{
|
||||
application::services::{
|
||||
add_store_service::AddStoreServiceBuilder, update_store_service::*,
|
||||
MockIdentityServicesInterface,
|
||||
},
|
||||
domain::add_store_command::*,
|
||||
// domain::commands::IdentityCommand,
|
||||
domain::update_store_command::*,
|
||||
},
|
||||
tests::bdd::*,
|
||||
utils::{random_string::GenerateRandomStringInterface, uuid::tests::UUID},
|
||||
};
|
||||
use std::sync::Arc;
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn pg_query_identity_store_view() {
|
||||
let settings = crate::settings::tests::get_settings().await;
|
||||
//let settings = crate::settings::Settings::new().unwrap();
|
||||
settings.create_db().await;
|
||||
|
||||
let db = crate::db::sqlx_postgres::Postgres::init(&settings.database.url).await;
|
||||
db.migrate().await;
|
||||
let db = DBOutPostgresAdapter::new(db.pool.clone());
|
||||
|
||||
let simple_query = SimpleLoggingQuery {};
|
||||
|
||||
let queries: Vec<Box<dyn Query<Store>>> =
|
||||
vec![Box::new(simple_query), Box::new(db.clone())];
|
||||
|
||||
let mut mock_services = MockIdentityServicesInterface::new();
|
||||
|
||||
let db2 = db.clone();
|
||||
mock_services
|
||||
.expect_add_store()
|
||||
.times(IS_CALLED_ONLY_ONCE.unwrap())
|
||||
.returning(move || {
|
||||
Arc::new(
|
||||
AddStoreServiceBuilder::default()
|
||||
.db_store_id_exists(Arc::new(db2.clone()))
|
||||
.db_store_name_exists(Arc::new(db2.clone()))
|
||||
.build()
|
||||
.unwrap(),
|
||||
)
|
||||
});
|
||||
|
||||
let db2 = db.clone();
|
||||
mock_services
|
||||
.expect_update_store()
|
||||
.times(IS_CALLED_ONLY_ONCE.unwrap())
|
||||
.returning(move || {
|
||||
Arc::new(
|
||||
UpdateStoreServiceBuilder::default()
|
||||
.db_store_id_exists(Arc::new(db2.clone()))
|
||||
.db_store_name_exists(Arc::new(db2.clone()))
|
||||
.build()
|
||||
.unwrap(),
|
||||
)
|
||||
});
|
||||
|
||||
let (cqrs, store_query): (
|
||||
Arc<PostgresCqrs<Store>>,
|
||||
Arc<dyn ViewRepository<StoreView, Store>>,
|
||||
) = (
|
||||
Arc::new(postgres_es::postgres_cqrs(
|
||||
db.pool.clone(),
|
||||
queries,
|
||||
Arc::new(mock_services),
|
||||
)),
|
||||
Arc::new(db.clone()),
|
||||
);
|
||||
|
||||
let rand = crate::utils::random_string::GenerateRandomString {};
|
||||
let cmd = AddStoreCommandBuilder::default()
|
||||
.name(rand.get_random(10))
|
||||
.address(None)
|
||||
.owner(UUID)
|
||||
.store_id(UUID)
|
||||
.build()
|
||||
.unwrap();
|
||||
cqrs.execute(
|
||||
&cmd.store_id().to_string(),
|
||||
IdentityCommand::AddStore(cmd.clone()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let store = store_query
|
||||
.load(&(*cmd.store_id()).to_string())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let store: Store = store.into();
|
||||
assert_eq!(store.name(), cmd.name());
|
||||
assert_eq!(store.address(), cmd.address());
|
||||
assert_eq!(store.owner(), cmd.owner());
|
||||
assert_eq!(store.store_id(), cmd.store_id());
|
||||
assert!(!store.deleted());
|
||||
|
||||
let update_store_cmd = UpdateStoreCommand::new(
|
||||
rand.get_random(10),
|
||||
Some(rand.get_random(10)),
|
||||
UUID,
|
||||
store,
|
||||
UUID,
|
||||
)
|
||||
.unwrap();
|
||||
cqrs.execute(
|
||||
&cmd.store_id().to_string(),
|
||||
IdentityCommand::UpdateStore(update_store_cmd.clone()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let store = store_query
|
||||
.load(&(*cmd.store_id()).to_string())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let store: Store = store.into();
|
||||
assert_eq!(store.name(), update_store_cmd.name());
|
||||
assert_eq!(store.address(), update_store_cmd.address());
|
||||
assert_eq!(store.owner(), update_store_cmd.owner());
|
||||
assert_eq!(store.store_id(), update_store_cmd.old_store().store_id());
|
||||
assert!(!store.deleted());
|
||||
|
||||
settings.drop_db().await;
|
||||
}
|
||||
}
|
|
@ -1,6 +1,7 @@
|
|||
// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
use std::sync::Arc;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use cqrs_es::persist::GenericQuery;
|
||||
|
@ -11,7 +12,8 @@ use uuid::Uuid;
|
|||
|
||||
use super::errors::*;
|
||||
use super::DBOutPostgresAdapter;
|
||||
use crate::identity::application::services::events::IdentityEvent;
|
||||
use crate::identity::adapters::types::{IdentityUserCqrsExec, IdentityUserCqrsView};
|
||||
use crate::identity::application::services::{events::IdentityEvent, IdentityServicesObj};
|
||||
use crate::identity::domain::aggregate::User;
|
||||
use crate::utils::parse_aggregate_id::parse_aggregate_id;
|
||||
|
||||
|
@ -206,7 +208,36 @@ impl Query<User> for SimpleLoggingQuery {
|
|||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Query<User> for DBOutPostgresAdapter {
|
||||
async fn dispatch(&self, user_id: &str, events: &[EventEnvelope<User>]) {
|
||||
let res = self
|
||||
.load_with_context(user_id)
|
||||
.await
|
||||
.unwrap_or_else(|_| Some((UserView::default(), ViewContext::new(user_id.into(), 0))));
|
||||
let (mut view, view_context): (UserView, ViewContext) = res.unwrap();
|
||||
for event in events {
|
||||
view.update(event);
|
||||
}
|
||||
self.update_view(view, view_context).await.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
// Our second query, this one will be handled with Postgres `GenericQuery`
|
||||
// which will serialize and persist our view after it is updated. It also
|
||||
// provides a `load` method to deserialize the view on request.
|
||||
pub type UserQuery = GenericQuery<DBOutPostgresAdapter, UserView, User>;
|
||||
|
||||
pub fn init_cqrs(
|
||||
db: DBOutPostgresAdapter,
|
||||
services: IdentityServicesObj,
|
||||
) -> (IdentityUserCqrsExec, IdentityUserCqrsView) {
|
||||
let queries: Vec<Box<dyn Query<User>>> = vec![Box::new(db.clone())];
|
||||
|
||||
let pool = db.pool.clone();
|
||||
|
||||
(
|
||||
Arc::new(postgres_es::postgres_cqrs(pool.clone(), queries, services)),
|
||||
Arc::new(db.clone()),
|
||||
)
|
||||
}
|
||||
|
|
|
@ -51,7 +51,7 @@ mod tests {
|
|||
let validation_secret = "dafsdfasecret";
|
||||
|
||||
let settings = crate::settings::tests::get_settings().await;
|
||||
let m = LettreMailer::new(&settings).await;
|
||||
let m = LettreMailer::new(&settings);
|
||||
|
||||
m.account_validation_link(email, username, validation_secret)
|
||||
.await
|
||||
|
|
|
@ -16,13 +16,13 @@ pub struct LettreMailer {
|
|||
}
|
||||
|
||||
impl LettreMailer {
|
||||
pub async fn new(s: &Settings) -> Self {
|
||||
pub fn new(s: &Settings) -> Self {
|
||||
let mailer: AsyncSmtpTransport<Tokio1Executor> =
|
||||
AsyncSmtpTransport::<Tokio1Executor>::from_url(s.email.url.as_str())
|
||||
.unwrap()
|
||||
.build();
|
||||
|
||||
assert!(mailer.test_connection().await.unwrap());
|
||||
// assert!(mailer.test_connection().await.unwrap());
|
||||
|
||||
Self {
|
||||
mailer,
|
||||
|
|
|
@ -4,3 +4,4 @@
|
|||
|
||||
pub mod db;
|
||||
pub mod mailer;
|
||||
pub mod phone;
|
||||
|
|
5
src/identity/adapters/output/phone/mod.rs
Normal file
5
src/identity/adapters/output/phone/mod.rs
Normal file
|
@ -0,0 +1,5 @@
|
|||
// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
pub mod twilio;
|
|
@ -0,0 +1,57 @@
|
|||
// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
use lettre::{message::header::ContentType, AsyncTransport, Message};
|
||||
|
||||
use super::*;
|
||||
use crate::identity::application::port::output::phone::{account_login_otp::*, errors::*};
|
||||
use crate::identity::domain::employee_aggregate::PhoneNumber;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl AccountLoginOTPOutPhonePort for Phone {
|
||||
async fn account_login_otp(&self, to: &PhoneNumber, otp: usize) -> OutPhonePortResult<()> {
|
||||
unimplemented!()
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use url::Url;
|
||||
|
||||
use mailpit_client::*;
|
||||
|
||||
use serde::Deserialize;
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn test_phone_account_validation_otp() {
|
||||
// let username = "batman";
|
||||
// let email = "batman@account_validation_otp.example.com";
|
||||
// let validation_secret = "dafsdfasecret";
|
||||
//
|
||||
// let settings = crate::settings::tests::get_settings().await;
|
||||
// let m = Lettrephone::new(&settings);
|
||||
//
|
||||
// m.account_validation_otp(email, username, validation_secret)
|
||||
// .await
|
||||
// .unwrap();
|
||||
//
|
||||
// let mailpit_url =
|
||||
// std::env::var("MAILPIT_URL").expect("Please set mailpit instance URL in MAILPIT_URL");
|
||||
// let mc = MailPitHTTPClientBuilder::default()
|
||||
// .url(Url::parse(&mailpit_url).unwrap())
|
||||
// .build()
|
||||
// .unwrap();
|
||||
//
|
||||
// let mailpit_email = mc.get_email_addressed_to(email).await;
|
||||
//
|
||||
// assert!(mailpit_email.text().contains(validation_secret));
|
||||
// assert!(mailpit_email.text().contains(username));
|
||||
// assert!(mailpit_email
|
||||
// .to()
|
||||
// .iter()
|
||||
// .any(|t| t.address() == email && t.name() == username));
|
||||
//
|
||||
// mc.delete_email(mailpit_email).await;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,57 @@
|
|||
// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
use lettre::{message::header::ContentType, AsyncTransport, Message};
|
||||
|
||||
use super::*;
|
||||
use crate::identity::application::port::output::phone::{account_validation_otp::*, errors::*};
|
||||
use crate::identity::domain::employee_aggregate::PhoneNumber;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl AccountValidationOTPOutPhonePort for Phone {
|
||||
async fn account_validation_otp(&self, to: &PhoneNumber, otp: usize) -> OutPhonePortResult<()> {
|
||||
unimplemented!()
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use url::Url;
|
||||
|
||||
use mailpit_client::*;
|
||||
|
||||
use serde::Deserialize;
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn test_phone_account_validation_otp() {
|
||||
// let username = "batman";
|
||||
// let email = "batman@account_validation_otp.example.com";
|
||||
// let validation_secret = "dafsdfasecret";
|
||||
//
|
||||
// let settings = crate::settings::tests::get_settings().await;
|
||||
// let m = Lettrephone::new(&settings);
|
||||
//
|
||||
// m.account_validation_otp(email, username, validation_secret)
|
||||
// .await
|
||||
// .unwrap();
|
||||
//
|
||||
// let mailpit_url =
|
||||
// std::env::var("MAILPIT_URL").expect("Please set mailpit instance URL in MAILPIT_URL");
|
||||
// let mc = MailPitHTTPClientBuilder::default()
|
||||
// .url(Url::parse(&mailpit_url).unwrap())
|
||||
// .build()
|
||||
// .unwrap();
|
||||
//
|
||||
// let mailpit_email = mc.get_email_addressed_to(email).await;
|
||||
//
|
||||
// assert!(mailpit_email.text().contains(validation_secret));
|
||||
// assert!(mailpit_email.text().contains(username));
|
||||
// assert!(mailpit_email
|
||||
// .to()
|
||||
// .iter()
|
||||
// .any(|t| t.address() == email && t.name() == username));
|
||||
//
|
||||
// mc.delete_email(mailpit_email).await;
|
||||
}
|
||||
}
|
1
src/identity/adapters/output/phone/twilio/errors.rs
Normal file
1
src/identity/adapters/output/phone/twilio/errors.rs
Normal file
|
@ -0,0 +1 @@
|
|||
|
29
src/identity/adapters/output/phone/twilio/mod.rs
Normal file
29
src/identity/adapters/output/phone/twilio/mod.rs
Normal file
|
@ -0,0 +1,29 @@
|
|||
// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
use std::sync::Arc;
|
||||
|
||||
use twilio_client::{TwilioClient, TwilioClientBuilder};
|
||||
|
||||
use crate::settings::Settings;
|
||||
|
||||
mod account_login_otp;
|
||||
mod account_validation_otp;
|
||||
mod errors;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Phone {
|
||||
tx: TwilioClient,
|
||||
}
|
||||
|
||||
impl Phone {
|
||||
pub fn new(s: &Settings) -> Self {
|
||||
let tx = TwilioClientBuilder::default()
|
||||
.auth_token(s.phone.twilio_auth_token.clone())
|
||||
.account_id(s.phone.twilio_account_id.clone())
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
Self { tx }
|
||||
}
|
||||
}
|
74
src/identity/adapters/types.rs
Normal file
74
src/identity/adapters/types.rs
Normal file
|
@ -0,0 +1,74 @@
|
|||
// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
#![allow(dead_code)]
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use actix_web::web::Data;
|
||||
use async_trait::async_trait;
|
||||
use cqrs_es::{persist::ViewRepository, AggregateError};
|
||||
use derive_builder::Builder;
|
||||
use mockall::predicate::*;
|
||||
use mockall::*;
|
||||
use postgres_es::PostgresCqrs;
|
||||
|
||||
use crate::identity::{
|
||||
adapters::{
|
||||
input::web::RoutesRepository,
|
||||
output::db::postgres::{
|
||||
employee_view::EmployeeView, store_view::StoreView, user_view::UserView,
|
||||
DBOutPostgresAdapter,
|
||||
},
|
||||
},
|
||||
application::services::{errors::IdentityError, IdentityCommand, IdentityServicesObj},
|
||||
domain::{aggregate::User, employee_aggregate::Employee, store_aggregate::Store},
|
||||
};
|
||||
|
||||
pub type WebIdentityRoutesRepository = Data<Arc<RoutesRepository>>;
|
||||
|
||||
pub type IdentityUserCqrsExec = Arc<PostgresCqrs<User>>;
|
||||
pub type IdentityUserCqrsView = Arc<dyn ViewRepository<UserView, User>>;
|
||||
pub type WebIdentityUserCqrsView = Data<IdentityUserCqrsView>;
|
||||
|
||||
pub type IdentityStoreCqrsExec = Arc<PostgresCqrs<Store>>;
|
||||
pub type IdentityStoreCqrsView = Arc<dyn ViewRepository<StoreView, Store>>;
|
||||
pub type WebIdentityStoreCqrsView = Data<IdentityStoreCqrsView>;
|
||||
|
||||
pub type IdentityEmployeeCqrsExec = Arc<PostgresCqrs<Employee>>;
|
||||
pub type IdentityEmployeeCqrsView = Arc<dyn ViewRepository<StoreView, Store>>;
|
||||
pub type WebIdentityEmployeeCqrsView = Data<IdentityStoreCqrsView>;
|
||||
|
||||
pub type WebIdentityCqrsExec = Data<Arc<dyn IdentityCqrsExecutor>>;
|
||||
|
||||
#[automock]
|
||||
#[async_trait]
|
||||
pub trait IdentityCqrsExecutor {
|
||||
async fn execute(
|
||||
&self,
|
||||
aggregate_id: &str,
|
||||
command: IdentityCommand,
|
||||
) -> Result<(), AggregateError<IdentityError>>;
|
||||
}
|
||||
|
||||
#[derive(Clone, Builder)]
|
||||
pub struct IdentityCqrsExec {
|
||||
user: IdentityUserCqrsExec,
|
||||
store: IdentityStoreCqrsExec,
|
||||
employee: IdentityEmployeeCqrsExec,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl IdentityCqrsExecutor for IdentityCqrsExec {
|
||||
async fn execute(
|
||||
&self,
|
||||
aggregate_id: &str,
|
||||
command: IdentityCommand,
|
||||
) -> Result<(), AggregateError<IdentityError>> {
|
||||
self.user.execute(aggregate_id, command.clone()).await?;
|
||||
self.store.execute(aggregate_id, command.clone()).await?;
|
||||
self.employee.execute(aggregate_id, command).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
|
@ -18,4 +18,7 @@ pub enum OutDBPortError {
|
|||
PhoneNumberNotFound,
|
||||
EmpLoginOTPNotFound,
|
||||
EmpVerificationOTPNotFound,
|
||||
DuplicateStoreName,
|
||||
DuplicateStoreID,
|
||||
StoreIDNotFound,
|
||||
}
|
||||
|
|
|
@ -17,7 +17,7 @@ pub use tests::*;
|
|||
#[automock]
|
||||
#[async_trait::async_trait]
|
||||
pub trait GetInviteOutDBPort: Send + Sync {
|
||||
async fn get_invite(&self, invitge_id: Uuid) -> OutDBPortResult<Option<Uuid>>;
|
||||
async fn get_invite(&self, invite_id: Uuid) -> OutDBPortResult<Option<Uuid>>;
|
||||
}
|
||||
|
||||
pub type GetInviteOutDBPortObj = std::sync::Arc<dyn GetInviteOutDBPort>;
|
||||
|
|
|
@ -12,13 +12,14 @@ pub mod email_exists;
|
|||
pub mod emp_id_exists;
|
||||
pub mod errors;
|
||||
pub mod get_emp_id_from_phone_number;
|
||||
pub mod get_invite;
|
||||
//pub mod get_invite;
|
||||
pub mod get_login_otp;
|
||||
pub mod get_verification_otp;
|
||||
pub mod get_verification_secret;
|
||||
pub mod invite_id_exists;
|
||||
//pub mod invite_id_exists;
|
||||
pub mod phone_exists;
|
||||
pub mod store_id_exists;
|
||||
pub mod store_name_exists;
|
||||
pub mod user_id_exists;
|
||||
//pub mod verification_otp_exists;
|
||||
pub mod verification_secret_exists;
|
||||
|
|
54
src/identity/application/port/output/db/store_name_exists.rs
Normal file
54
src/identity/application/port/output/db/store_name_exists.rs
Normal file
|
@ -0,0 +1,54 @@
|
|||
// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
use mockall::predicate::*;
|
||||
use mockall::*;
|
||||
|
||||
use crate::identity::domain::store_aggregate::Store;
|
||||
|
||||
use super::errors::*;
|
||||
#[cfg(test)]
|
||||
#[allow(unused_imports)]
|
||||
pub use tests::*;
|
||||
|
||||
#[automock]
|
||||
#[async_trait::async_trait]
|
||||
pub trait StoreNameExistsDBPort: Send + Sync {
|
||||
async fn store_name_exists(&self, s: &Store) -> OutDBPortResult<bool>;
|
||||
}
|
||||
|
||||
pub type StoreNameExistsDBPortObj = std::sync::Arc<dyn StoreNameExistsDBPort>;
|
||||
|
||||
#[cfg(test)]
|
||||
pub mod tests {
|
||||
use super::*;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
pub fn mock_store_name_exists_db_port_false(times: Option<usize>) -> StoreNameExistsDBPortObj {
|
||||
let mut m = MockStoreNameExistsDBPort::new();
|
||||
if let Some(times) = times {
|
||||
m.expect_store_name_exists()
|
||||
.times(times)
|
||||
.returning(|_| Ok(false));
|
||||
} else {
|
||||
m.expect_store_name_exists().returning(|_| Ok(false));
|
||||
}
|
||||
|
||||
Arc::new(m)
|
||||
}
|
||||
|
||||
pub fn mock_store_name_exists_db_port_true(times: Option<usize>) -> StoreNameExistsDBPortObj {
|
||||
let mut m = MockStoreNameExistsDBPort::new();
|
||||
if let Some(times) = times {
|
||||
m.expect_store_name_exists()
|
||||
.times(times)
|
||||
.returning(|_| Ok(true));
|
||||
} else {
|
||||
m.expect_store_name_exists().returning(|_| Ok(true));
|
||||
}
|
||||
|
||||
Arc::new(m)
|
||||
}
|
||||
}
|
|
@ -30,7 +30,7 @@ pub mod tests {
|
|||
|
||||
use std::sync::Arc;
|
||||
|
||||
pub fn mock_account_validation_link_db_port(
|
||||
pub fn mock_account_validation_link_mailer_port(
|
||||
times: Option<usize>,
|
||||
) -> AccountValidationLinkOutMailerPortObj {
|
||||
let mut m = MockAccountValidationLinkOutMailerPort::new();
|
||||
|
|
152
src/identity/application/services/add_store_service.rs
Normal file
152
src/identity/application/services/add_store_service.rs
Normal file
|
@ -0,0 +1,152 @@
|
|||
// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use derive_builder::Builder;
|
||||
use mockall::predicate::*;
|
||||
use mockall::*;
|
||||
|
||||
use super::errors::*;
|
||||
use crate::identity::{
|
||||
application::port::output::db::{store_id_exists::*, store_name_exists::*},
|
||||
domain::{
|
||||
add_store_command::*,
|
||||
store_added_event::{StoreAddedEvent, StoreAddedEventBuilder},
|
||||
store_aggregate::*,
|
||||
},
|
||||
};
|
||||
|
||||
#[automock]
|
||||
#[async_trait::async_trait]
|
||||
pub trait AddStoreUseCase: Send + Sync {
|
||||
async fn add_store(&self, cmd: AddStoreCommand) -> IdentityResult<StoreAddedEvent>;
|
||||
}
|
||||
|
||||
pub type AddStoreServiceObj = Arc<dyn AddStoreUseCase>;
|
||||
|
||||
#[derive(Clone, Builder)]
|
||||
pub struct AddStoreService {
|
||||
db_store_id_exists: StoreIDExistsDBPortObj,
|
||||
db_store_name_exists: StoreNameExistsDBPortObj,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl AddStoreUseCase for AddStoreService {
|
||||
async fn add_store(&self, cmd: AddStoreCommand) -> IdentityResult<StoreAddedEvent> {
|
||||
if self
|
||||
.db_store_id_exists
|
||||
.store_id_exists(cmd.store_id())
|
||||
.await?
|
||||
{
|
||||
return Err(IdentityError::DuplicateStoreID);
|
||||
}
|
||||
|
||||
let store = StoreBuilder::default()
|
||||
.name(cmd.name().into())
|
||||
.address(cmd.address().as_ref().map(|s| s.to_string()))
|
||||
.owner(*cmd.owner())
|
||||
.store_id(*cmd.store_id())
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
if self.db_store_name_exists.store_name_exists(&store).await? {
|
||||
return Err(IdentityError::DuplicateStoreName);
|
||||
}
|
||||
|
||||
Ok(StoreAddedEventBuilder::default()
|
||||
.name(store.name().into())
|
||||
.address(store.address().as_ref().map(|s| s.to_string()))
|
||||
.owner(*cmd.owner())
|
||||
.store_id(*cmd.store_id())
|
||||
.build()
|
||||
.unwrap())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub mod tests {
|
||||
use super::*;
|
||||
|
||||
use crate::tests::bdd::*;
|
||||
use crate::utils::uuid::tests::*;
|
||||
|
||||
pub fn mock_add_store_service(
|
||||
times: Option<usize>,
|
||||
cmd: AddStoreCommand,
|
||||
) -> AddStoreServiceObj {
|
||||
let mut m = MockAddStoreUseCase::new();
|
||||
|
||||
let res = StoreAddedEventBuilder::default()
|
||||
.name(cmd.name().into())
|
||||
.address(cmd.address().as_ref().map(|s| s.to_string()))
|
||||
.owner(*cmd.owner())
|
||||
.store_id(*cmd.store_id())
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
if let Some(times) = times {
|
||||
m.expect_add_store()
|
||||
.times(times)
|
||||
.returning(move |_| Ok(res.clone()));
|
||||
} else {
|
||||
m.expect_add_store().returning(move |_| Ok(res.clone()));
|
||||
}
|
||||
|
||||
Arc::new(m)
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn test_service_store_id_doesnt_exist() {
|
||||
let name = "foo";
|
||||
let address = "bar";
|
||||
let owner = UUID;
|
||||
|
||||
let cmd = AddStoreCommandBuilder::default()
|
||||
.name(name.into())
|
||||
.address(Some(address.into()))
|
||||
.owner(owner)
|
||||
.store_id(UUID)
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
let s = AddStoreServiceBuilder::default()
|
||||
.db_store_id_exists(mock_store_id_exists_db_port_false(IS_CALLED_ONLY_ONCE))
|
||||
.db_store_name_exists(mock_store_name_exists_db_port_false(IS_CALLED_ONLY_ONCE))
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
let res = s.add_store(cmd.clone()).await.unwrap();
|
||||
assert_eq!(res.name(), cmd.name());
|
||||
assert_eq!(res.address(), cmd.address());
|
||||
assert_eq!(res.owner(), cmd.owner());
|
||||
assert_eq!(res.store_id(), cmd.store_id());
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn test_service_store_name_exists() {
|
||||
let name = "foo";
|
||||
let address = "bar";
|
||||
let owner = UUID;
|
||||
|
||||
let cmd = AddStoreCommandBuilder::default()
|
||||
.name(name.into())
|
||||
.address(Some(address.into()))
|
||||
.owner(owner)
|
||||
.store_id(UUID)
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
let s = AddStoreServiceBuilder::default()
|
||||
.db_store_id_exists(mock_store_id_exists_db_port_false(IS_CALLED_ONLY_ONCE))
|
||||
.db_store_name_exists(mock_store_name_exists_db_port_true(IS_CALLED_ONLY_ONCE))
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
s.add_store(cmd.clone()).await,
|
||||
Err(IdentityError::DuplicateStoreName)
|
||||
);
|
||||
}
|
||||
}
|
|
@ -4,7 +4,7 @@
|
|||
|
||||
use super::*;
|
||||
|
||||
struct DeleteUserService;
|
||||
pub struct DeleteUserService;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl DeleteUserUseCase for DeleteUserService {
|
||||
|
|
|
@ -7,7 +7,6 @@ use mockall::predicate::*;
|
|||
use mockall::*;
|
||||
|
||||
use super::errors::*;
|
||||
use super::*;
|
||||
use crate::identity::application::port::output::{
|
||||
db::{create_verification_otp::*, emp_id_exists::*, phone_exists::*},
|
||||
phone::account_validation_otp::*,
|
||||
|
|
|
@ -29,6 +29,9 @@ pub enum IdentityError {
|
|||
EmployeeNotFound,
|
||||
InviteNotFound,
|
||||
StoreNotFound,
|
||||
DuplicateStoreName,
|
||||
StoreIDNotFound,
|
||||
DuplicateStoreID,
|
||||
}
|
||||
|
||||
pub type IdentityCommandResult<V> = Result<V, IdentityCommandError>;
|
||||
|
@ -74,6 +77,9 @@ impl From<OutDBPortError> for IdentityError {
|
|||
OutDBPortError::PhoneNumberNotFound => Self::PhoneNumberNotFound,
|
||||
OutDBPortError::EmpLoginOTPNotFound => Self::LoginOTPNotFound,
|
||||
OutDBPortError::EmpVerificationOTPNotFound => Self::VerificationOTPNotFound,
|
||||
OutDBPortError::DuplicateStoreName => Self::DuplicateStoreName,
|
||||
OutDBPortError::DuplicateStoreID => Self::DuplicateStoreID,
|
||||
OutDBPortError::StoreIDNotFound => Self::StoreIDNotFound,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -12,9 +12,16 @@ use super::update_email::events::*;
|
|||
use super::update_password::events::*;
|
||||
|
||||
use crate::identity::domain::{
|
||||
employee_logged_in_event::*, employee_registered_event::*, invite_accepted_event::*,
|
||||
login_otp_sent_event::*, organization_exited_event::*, phone_number_changed_event::*,
|
||||
phone_number_verified_event::*, resend_login_otp_event::*, verification_otp_resent_event::*,
|
||||
employee_logged_in_event::*,
|
||||
employee_registered_event::*, //invite_accepted_event::*,
|
||||
login_otp_sent_event::*,
|
||||
organization_exited_event::*,
|
||||
phone_number_changed_event::*,
|
||||
phone_number_verified_event::*,
|
||||
resend_login_otp_event::*,
|
||||
store_added_event::*,
|
||||
store_updated_event::*,
|
||||
verification_otp_resent_event::*,
|
||||
verification_otp_sent_event::*,
|
||||
};
|
||||
|
||||
|
@ -37,8 +44,12 @@ pub enum IdentityEvent {
|
|||
PhoneNumberVerified(PhoneNumberVerifiedEvent),
|
||||
VerificationOTPResent(VerificationOTPResentEvent),
|
||||
PhoneNumberChanged(PhoneNumberChangedEvent),
|
||||
InviteAccepted(InviteAcceptedEvent),
|
||||
// InviteAccepted(InviteAcceptedEvent),
|
||||
OrganizationExited(OrganizationExitedEvent),
|
||||
|
||||
// store events
|
||||
StoreAdded(StoreAddedEvent),
|
||||
StoreUpdated(StoreUpdatedEvent),
|
||||
}
|
||||
|
||||
//TODO: define password type that takes string and converts to hash
|
||||
|
@ -67,8 +78,12 @@ impl DomainEvent for IdentityEvent {
|
|||
IdentityEvent::PhoneNumberVerified { .. } => "EmployeePhoneNumberVerified",
|
||||
IdentityEvent::VerificationOTPResent { .. } => "EmployeeVerificationOTPResent",
|
||||
IdentityEvent::PhoneNumberChanged { .. } => "EmployeePhoneNumberChanged",
|
||||
IdentityEvent::InviteAccepted { .. } => "EmployeeInviteAccepted",
|
||||
// IdentityEvent::InviteAccepted { .. } => "EmployeeInviteAccepted",
|
||||
IdentityEvent::OrganizationExited { .. } => "EmployeeOrganizationExited",
|
||||
|
||||
// store
|
||||
IdentityEvent::StoreAdded { .. } => "IdentityStoreAdded",
|
||||
IdentityEvent::StoreUpdated { .. } => "IdentityStoreUpdated",
|
||||
};
|
||||
|
||||
e.to_string()
|
||||
|
|
|
@ -1,6 +1,8 @@
|
|||
use std::hash::RandomState;
|
||||
// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
use std::sync::Arc;
|
||||
|
||||
use derive_builder::Builder;
|
||||
use mockall::predicate::*;
|
||||
|
@ -8,7 +10,7 @@ use mockall::*;
|
|||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub mod delete_user;
|
||||
pub mod employee_accept_invite_service;
|
||||
//pub mod employee_accept_invite_service;
|
||||
pub mod employee_exit_organization_service;
|
||||
pub mod employee_login_service;
|
||||
pub mod employee_register_service;
|
||||
|
@ -25,10 +27,46 @@ pub mod set_user_admin;
|
|||
pub mod update_email;
|
||||
pub mod update_password;
|
||||
|
||||
pub mod add_store_service;
|
||||
pub mod update_store_service;
|
||||
|
||||
use add_store_service::*;
|
||||
use delete_user::{service::*, *};
|
||||
//use employee_accept_invite_service::*;
|
||||
use employee_exit_organization_service::*;
|
||||
use employee_login_service::*;
|
||||
use employee_register_service::*;
|
||||
use employee_resend_login_otp_service::*;
|
||||
use employee_resend_verification_otp_service::*;
|
||||
use employee_verify_phone_number_service::*;
|
||||
use login::{service::*, *};
|
||||
use mark_user_verified::{service::*, *};
|
||||
use register_user::{service::*, *};
|
||||
use resend_verification_email::{service::*, *};
|
||||
use set_user_admin::{service::*, *};
|
||||
use update_email::{service::*, *};
|
||||
use update_password::{service::*, *};
|
||||
use update_store_service::*;
|
||||
|
||||
use errors::*;
|
||||
use events::*;
|
||||
|
||||
use crate::identity::domain::{
|
||||
accept_invite_command::*, change_phone_number_command::*, employee_login_command::*,
|
||||
employee_register_command::*, exit_organization_command::*, resend_login_otp_command::*,
|
||||
resend_verification_otp_command::*, verify_phone_number_command::*,
|
||||
// accept_invite_command::*,
|
||||
add_store_command::*,
|
||||
change_phone_number_command::*,
|
||||
employee_login_command::*,
|
||||
employee_register_command::*,
|
||||
exit_organization_command::*,
|
||||
resend_login_otp_command::*,
|
||||
resend_verification_otp_command::*,
|
||||
update_store_command::*,
|
||||
verify_phone_number_command::*,
|
||||
};
|
||||
use crate::utils::{
|
||||
random_number::{self, *},
|
||||
random_string::*,
|
||||
uuid::*,
|
||||
};
|
||||
use delete_user::command::*;
|
||||
use login::command::*;
|
||||
|
@ -39,6 +77,18 @@ use set_user_admin::command::*;
|
|||
use update_email::command::*;
|
||||
use update_password::command::*;
|
||||
|
||||
use crate::identity::application::port::output::{
|
||||
db::{
|
||||
create_login_otp::*, create_verification_otp::*, create_verification_secret::*,
|
||||
delete_login_otp::*, delete_verification_otp::*, delete_verification_secret::*,
|
||||
email_exists::*, emp_id_exists::*, get_emp_id_from_phone_number::*, get_login_otp::*,
|
||||
get_verification_otp::*, get_verification_secret::*, phone_exists::*, store_id_exists::*,
|
||||
store_name_exists::*, user_id_exists::*, verification_secret_exists::*,
|
||||
},
|
||||
mailer::account_validation_link::*,
|
||||
phone::{account_login_otp::*, account_validation_otp::*},
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd)]
|
||||
pub enum IdentityCommand {
|
||||
RegisterUser(RegisterUserCommand),
|
||||
|
@ -57,125 +107,348 @@ pub enum IdentityCommand {
|
|||
EmployeeVerifyPhoneNumber(VerifyPhoneNumberCommand),
|
||||
EmployeeResendVerificationOTP(ResendVerificationOTPCommand),
|
||||
EmployeeChangePhoneNumber(ChangePhoneNumberCommand),
|
||||
EmployeeAcceptInvite(AcceptInviteCommand),
|
||||
// EmployeeAcceptInvite(AcceptInviteCommand),
|
||||
EmployeeExitOrganization(ExitOrganizationCommand),
|
||||
|
||||
AddStore(AddStoreCommand),
|
||||
UpdateStore(UpdateStoreCommand),
|
||||
}
|
||||
|
||||
#[automock]
|
||||
pub trait IdentityServicesInterface: Send + Sync {
|
||||
fn delete_user(&self) -> delete_user::DeleteUserServiceObj;
|
||||
fn login(&self) -> login::LoginServiceObj;
|
||||
fn mark_user_verified(&self) -> mark_user_verified::MarkUserVerifiedServiceObj;
|
||||
fn register_user(&self) -> register_user::RegisterUserServiceObj;
|
||||
fn resend_verification_email(
|
||||
&self,
|
||||
) -> resend_verification_email::ResendVerificationEmailServiceObj;
|
||||
fn set_user_admin(&self) -> set_user_admin::SetUserAdminServiceObj;
|
||||
fn update_email(&self) -> update_email::UpdateEmailServiceObj;
|
||||
fn update_password(&self) -> update_password::UpdatePasswordServiceObj;
|
||||
fn delete_user(&self) -> DeleteUserServiceObj;
|
||||
fn login(&self) -> LoginServiceObj;
|
||||
fn mark_user_verified(&self) -> MarkUserVerifiedServiceObj;
|
||||
fn register_user(&self) -> RegisterUserServiceObj;
|
||||
fn resend_verification_email(&self) -> ResendVerificationEmailServiceObj;
|
||||
fn set_user_admin(&self) -> SetUserAdminServiceObj;
|
||||
fn update_email(&self) -> UpdateEmailServiceObj;
|
||||
fn update_password(&self) -> UpdatePasswordServiceObj;
|
||||
|
||||
// employee
|
||||
fn employee_accept_invite_service(
|
||||
&self,
|
||||
) -> employee_accept_invite_service::EmployeeAcceptInviteServiceObj;
|
||||
fn employee_exit_organization_service(
|
||||
&self,
|
||||
) -> employee_exit_organization_service::EmployeeExitOrganizationServiceObj;
|
||||
fn employee_login_service(&self) -> employee_login_service::EmployeeLoginServiceObj;
|
||||
fn employee_register_service(&self) -> employee_register_service::EmployeeRegisterServiceObj;
|
||||
fn employee_resend_login_otp_service(
|
||||
&self,
|
||||
) -> employee_resend_login_otp_service::EmployeeResendLoginOTPServiceObj;
|
||||
fn employee_resend_verification_otp_service(
|
||||
&self,
|
||||
) -> employee_resend_verification_otp_service::EmployeeResendVerificationOTPServiceObj;
|
||||
fn employee_verify_phone_number_service(
|
||||
&self,
|
||||
) -> employee_verify_phone_number_service::EmployeeVerifyPhoneNumberServiceObj;
|
||||
// fn employee_accept_invite_service(&self) -> EmployeeAcceptInviteServiceObj;
|
||||
fn employee_exit_organization_service(&self) -> EmployeeExitOrganizationServiceObj;
|
||||
fn employee_login_service(&self) -> EmployeeLoginServiceObj;
|
||||
fn employee_register_service(&self) -> EmployeeRegisterServiceObj;
|
||||
fn employee_resend_login_otp_service(&self) -> EmployeeResendLoginOTPServiceObj;
|
||||
fn employee_resend_verification_otp_service(&self) -> EmployeeResendVerificationOTPServiceObj;
|
||||
fn employee_verify_phone_number_service(&self) -> EmployeeVerifyPhoneNumberServiceObj;
|
||||
|
||||
// store
|
||||
fn add_store(&self) -> AddStoreServiceObj;
|
||||
fn update_store(&self) -> UpdateStoreServiceObj;
|
||||
}
|
||||
|
||||
pub type IdentityServicesObj = Arc<dyn IdentityServicesInterface>;
|
||||
|
||||
#[derive(Clone, Builder)]
|
||||
pub struct IdentityServices {
|
||||
delete_user: delete_user::DeleteUserServiceObj,
|
||||
login: login::LoginServiceObj,
|
||||
mark_user_verified: mark_user_verified::MarkUserVerifiedServiceObj,
|
||||
register_user: register_user::RegisterUserServiceObj,
|
||||
resend_verification_email: resend_verification_email::ResendVerificationEmailServiceObj,
|
||||
set_user_admin: set_user_admin::SetUserAdminServiceObj,
|
||||
update_email: update_email::UpdateEmailServiceObj,
|
||||
update_password: update_password::UpdatePasswordServiceObj,
|
||||
delete_user: DeleteUserServiceObj,
|
||||
login: LoginServiceObj,
|
||||
mark_user_verified: MarkUserVerifiedServiceObj,
|
||||
register_user: RegisterUserServiceObj,
|
||||
resend_verification_email: ResendVerificationEmailServiceObj,
|
||||
set_user_admin: SetUserAdminServiceObj,
|
||||
update_email: UpdateEmailServiceObj,
|
||||
update_password: UpdatePasswordServiceObj,
|
||||
|
||||
employee_accept_invite_service: employee_accept_invite_service::EmployeeAcceptInviteServiceObj,
|
||||
employee_exit_organization_service:
|
||||
employee_exit_organization_service::EmployeeExitOrganizationServiceObj,
|
||||
employee_login_service: employee_login_service::EmployeeLoginServiceObj,
|
||||
employee_register_service: employee_register_service::EmployeeRegisterServiceObj,
|
||||
employee_resend_login_otp_service:
|
||||
employee_resend_login_otp_service::EmployeeResendLoginOTPServiceObj,
|
||||
employee_resend_verification_otp_service:
|
||||
employee_resend_verification_otp_service::EmployeeResendVerificationOTPServiceObj,
|
||||
employee_verify_phone_number_service:
|
||||
employee_verify_phone_number_service::EmployeeVerifyPhoneNumberServiceObj,
|
||||
// employee_accept_invite_service: EmployeeAcceptInviteServiceObj,
|
||||
employee_exit_organization_service: EmployeeExitOrganizationServiceObj,
|
||||
employee_login_service: EmployeeLoginServiceObj,
|
||||
employee_register_service: EmployeeRegisterServiceObj,
|
||||
employee_resend_login_otp_service: EmployeeResendLoginOTPServiceObj,
|
||||
employee_resend_verification_otp_service: EmployeeResendVerificationOTPServiceObj,
|
||||
employee_verify_phone_number_service: EmployeeVerifyPhoneNumberServiceObj,
|
||||
|
||||
add_store: AddStoreServiceObj,
|
||||
update_store: UpdateStoreServiceObj,
|
||||
}
|
||||
|
||||
impl IdentityServicesInterface for IdentityServices {
|
||||
fn delete_user(&self) -> delete_user::DeleteUserServiceObj {
|
||||
fn delete_user(&self) -> DeleteUserServiceObj {
|
||||
self.delete_user.clone()
|
||||
}
|
||||
fn login(&self) -> login::LoginServiceObj {
|
||||
fn login(&self) -> LoginServiceObj {
|
||||
self.login.clone()
|
||||
}
|
||||
fn mark_user_verified(&self) -> mark_user_verified::MarkUserVerifiedServiceObj {
|
||||
fn mark_user_verified(&self) -> MarkUserVerifiedServiceObj {
|
||||
self.mark_user_verified.clone()
|
||||
}
|
||||
fn register_user(&self) -> register_user::RegisterUserServiceObj {
|
||||
fn register_user(&self) -> RegisterUserServiceObj {
|
||||
self.register_user.clone()
|
||||
}
|
||||
fn resend_verification_email(
|
||||
&self,
|
||||
) -> resend_verification_email::ResendVerificationEmailServiceObj {
|
||||
fn resend_verification_email(&self) -> ResendVerificationEmailServiceObj {
|
||||
self.resend_verification_email.clone()
|
||||
}
|
||||
fn set_user_admin(&self) -> set_user_admin::SetUserAdminServiceObj {
|
||||
fn set_user_admin(&self) -> SetUserAdminServiceObj {
|
||||
self.set_user_admin.clone()
|
||||
}
|
||||
fn update_email(&self) -> update_email::UpdateEmailServiceObj {
|
||||
fn update_email(&self) -> UpdateEmailServiceObj {
|
||||
self.update_email.clone()
|
||||
}
|
||||
fn update_password(&self) -> update_password::UpdatePasswordServiceObj {
|
||||
fn update_password(&self) -> UpdatePasswordServiceObj {
|
||||
self.update_password.clone()
|
||||
}
|
||||
|
||||
// employee
|
||||
fn employee_accept_invite_service(
|
||||
&self,
|
||||
) -> employee_accept_invite_service::EmployeeAcceptInviteServiceObj {
|
||||
self.employee_accept_invite_service.clone()
|
||||
}
|
||||
fn employee_exit_organization_service(
|
||||
&self,
|
||||
) -> employee_exit_organization_service::EmployeeExitOrganizationServiceObj {
|
||||
// fn employee_accept_invite_service(&self) -> EmployeeAcceptInviteServiceObj {
|
||||
// self.employee_accept_invite_service.clone()
|
||||
// }
|
||||
fn employee_exit_organization_service(&self) -> EmployeeExitOrganizationServiceObj {
|
||||
self.employee_exit_organization_service.clone()
|
||||
}
|
||||
fn employee_login_service(&self) -> employee_login_service::EmployeeLoginServiceObj {
|
||||
fn employee_login_service(&self) -> EmployeeLoginServiceObj {
|
||||
self.employee_login_service.clone()
|
||||
}
|
||||
fn employee_register_service(&self) -> employee_register_service::EmployeeRegisterServiceObj {
|
||||
fn employee_register_service(&self) -> EmployeeRegisterServiceObj {
|
||||
self.employee_register_service.clone()
|
||||
}
|
||||
fn employee_resend_login_otp_service(
|
||||
&self,
|
||||
) -> employee_resend_login_otp_service::EmployeeResendLoginOTPServiceObj {
|
||||
fn employee_resend_login_otp_service(&self) -> EmployeeResendLoginOTPServiceObj {
|
||||
self.employee_resend_login_otp_service.clone()
|
||||
}
|
||||
fn employee_resend_verification_otp_service(
|
||||
&self,
|
||||
) -> employee_resend_verification_otp_service::EmployeeResendVerificationOTPServiceObj {
|
||||
fn employee_resend_verification_otp_service(&self) -> EmployeeResendVerificationOTPServiceObj {
|
||||
self.employee_resend_verification_otp_service.clone()
|
||||
}
|
||||
fn employee_verify_phone_number_service(
|
||||
&self,
|
||||
) -> employee_verify_phone_number_service::EmployeeVerifyPhoneNumberServiceObj {
|
||||
fn employee_verify_phone_number_service(&self) -> EmployeeVerifyPhoneNumberServiceObj {
|
||||
self.employee_verify_phone_number_service.clone()
|
||||
}
|
||||
|
||||
fn add_store(&self) -> AddStoreServiceObj {
|
||||
self.add_store.clone()
|
||||
}
|
||||
fn update_store(&self) -> UpdateStoreServiceObj {
|
||||
self.update_store.clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl IdentityServices {
|
||||
pub fn new(
|
||||
out_db_create_login_otp: CreateLoginOTPOutDBPortObj,
|
||||
out_db_create_verification_otp: CreateVerificationOTPOutDBPortObj,
|
||||
out_db_create_verification_secret: CreateVerificationSecretOutDBPortObj,
|
||||
out_db_delete_login_otp: DeleteLoginOTPOutDBPortObj,
|
||||
out_db_delete_verification_otp: DeleteVerificationOTPOutDBPortObj,
|
||||
out_db_delete_verification_secret: DeleteVerificationSecretOutDBPortObj,
|
||||
out_db_email_exists: EmailExistsOutDBPortObj,
|
||||
out_db_emp_id_exists: EmpIDExistsOutDBPortObj,
|
||||
out_db_get_emp_id_from_phone_number: GetEmpIDFromPhoneNumberOutDBPortObj,
|
||||
out_db_get_login_otp: GetLoginOTPOutDBPortObj,
|
||||
out_db_get_verification_otp: GetVerificationOTPOutDBPortObj,
|
||||
out_db_get_verification_secret: GetVerificationSecretOutDBPortObj,
|
||||
out_db_phone_exists: PhoneNumberExistsOutDBPortObj,
|
||||
out_db_store_id_exists: StoreIDExistsDBPortObj,
|
||||
out_db_store_name_exists: StoreNameExistsDBPortObj,
|
||||
out_db_user_id_exists: UserIDExistsOutDBPortObj,
|
||||
out_db_verification_secret_exists: VerificationSecretExistsOutDBPortObj,
|
||||
|
||||
out_mailer_account_validating_link: AccountValidationLinkOutMailerPortObj,
|
||||
|
||||
out_phone_account_validation_otp: AccountValidationOTPOutPhonePortObj,
|
||||
out_phone_account_login_otp: AccountLoginOTPOutPhonePortObj,
|
||||
|
||||
get_uuid: GetUUIDInterfaceObj,
|
||||
random_string: GenerateRandomStringInterfaceObj,
|
||||
random_number: GenerateRandomNumberInterfaceObj,
|
||||
) -> IdentityServicesObj {
|
||||
let delete_user: DeleteUserServiceObj = Arc::new(DeleteUserService);
|
||||
let login: LoginServiceObj = Arc::new(LoginService {});
|
||||
|
||||
let mark_user_verified: MarkUserVerifiedServiceObj = Arc::new(
|
||||
MarkUserVerifiedServiceBuilder::default()
|
||||
.db_verification_secret_exists_adapter(out_db_verification_secret_exists.clone())
|
||||
.db_delete_verification_secret_adapter(out_db_delete_verification_secret.clone())
|
||||
.build()
|
||||
.unwrap(),
|
||||
);
|
||||
let register_user: RegisterUserServiceObj = Arc::new(
|
||||
RegisterUserServiceBuilder::default()
|
||||
.db_email_exists_adapter(out_db_email_exists.clone())
|
||||
.db_user_id_exists_adapter(out_db_user_id_exists.clone())
|
||||
.db_create_verification_secret_adapter(out_db_create_verification_secret.clone())
|
||||
.mailer_account_validation_link_adapter(out_mailer_account_validating_link.clone())
|
||||
.get_uuid(get_uuid.clone())
|
||||
.random_string_adapter(random_string.clone())
|
||||
.build()
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
let resend_verification_email: ResendVerificationEmailServiceObj = Arc::new(
|
||||
ResendVerificationEmailServiceBuilder::default()
|
||||
.db_email_exists_adapter(out_db_email_exists.clone())
|
||||
.db_get_verification_secret_adapter(out_db_get_verification_secret.clone())
|
||||
.mailer_account_validation_link_adapter(out_mailer_account_validating_link.clone())
|
||||
.build()
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
let set_user_admin: SetUserAdminServiceObj = Arc::new(SetUserAdminService);
|
||||
|
||||
let update_email: UpdateEmailServiceObj = Arc::new(
|
||||
UpdateEmailServiceBuilder::default()
|
||||
.db_email_exists_adapter(out_db_email_exists.clone())
|
||||
.db_create_verification_secret_adapter(out_db_create_verification_secret.clone())
|
||||
.mailer_account_validation_link_adapter(out_mailer_account_validating_link.clone())
|
||||
.random_string_adapter(random_string.clone())
|
||||
.build()
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
let update_password: UpdatePasswordServiceObj = Arc::new(UpdatePasswordService);
|
||||
|
||||
// let employee_accept_invite_service: EmployeeAcceptInviteServiceObj = Arc::new(
|
||||
// EmployeeAcceptInviteServiceBuilder::default()
|
||||
// .db_get_invite_adapter(unimplemented!())
|
||||
// .db_emp_id_exists_adapter(out_db_emp_id_exists.clone())
|
||||
// .build()
|
||||
// .unwrap(),
|
||||
// );
|
||||
let employee_exit_organization_service: EmployeeExitOrganizationServiceObj = Arc::new(
|
||||
EmployeeExitOrganizationServiceBuilder::default()
|
||||
.db_emp_id_exists_adapter(out_db_emp_id_exists.clone())
|
||||
.db_store_id_exists_adapter(out_db_store_id_exists.clone())
|
||||
.build()
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
let employee_login_service: EmployeeLoginServiceObj = Arc::new(
|
||||
EmployeeLoginServiceBuilder::default()
|
||||
.db_phone_exists_adapter(out_db_phone_exists.clone())
|
||||
.db_get_emp_id_from_phone_number_adapter(
|
||||
out_db_get_emp_id_from_phone_number.clone(),
|
||||
)
|
||||
.db_create_login_otp_adapter(out_db_create_login_otp.clone())
|
||||
.db_delete_login_otp(out_db_delete_login_otp.clone())
|
||||
.db_get_login_otp(out_db_get_login_otp.clone())
|
||||
.random_number_adapter(random_number.clone())
|
||||
.phone_login_otp_adapter(out_phone_account_login_otp.clone())
|
||||
.build()
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
let employee_register_service: EmployeeRegisterServiceObj = Arc::new(
|
||||
EmployeeRegisterUserServiceBuilder::default()
|
||||
.db_phone_exists_adapter(out_db_phone_exists.clone())
|
||||
.db_emp_id_exists_adapter(out_db_emp_id_exists.clone())
|
||||
.db_create_verification_otp_adapter(out_db_create_verification_otp.clone())
|
||||
.phone_account_validation_otp_adapter(out_phone_account_validation_otp.clone())
|
||||
.random_number_adapter(random_number.clone())
|
||||
.build()
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
let employee_resend_login_otp_service: EmployeeResendLoginOTPServiceObj = Arc::new(
|
||||
EmployeeResendLoginOTPServiceBuilder::default()
|
||||
.db_phone_exists_adapter(out_db_phone_exists.clone())
|
||||
.db_get_emp_id_from_phone_number_adapter(
|
||||
out_db_get_emp_id_from_phone_number.clone(),
|
||||
)
|
||||
.db_get_login_otp(out_db_get_login_otp.clone())
|
||||
.phone_login_otp_adapter(out_phone_account_login_otp.clone())
|
||||
.build()
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
let employee_resend_verification_otp_service: EmployeeResendVerificationOTPServiceObj =
|
||||
Arc::new(
|
||||
EmployeeResendVerificationOTPServiceBuilder::default()
|
||||
.db_phone_exists_adapter(out_db_phone_exists.clone())
|
||||
.db_get_emp_id_from_phone_number_adapter(
|
||||
out_db_get_emp_id_from_phone_number.clone(),
|
||||
)
|
||||
.db_get_verification_otp(out_db_get_verification_otp.clone())
|
||||
.phone_account_validation_otp_adapter(out_phone_account_validation_otp.clone())
|
||||
.build()
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
let employee_verify_phone_number_service: EmployeeVerifyPhoneNumberServiceObj = Arc::new(
|
||||
EmployeeVerifyPhoneNumberServiceBuilder::default()
|
||||
.db_get_emp_id_from_phone_number_adapter(
|
||||
out_db_get_emp_id_from_phone_number.clone(),
|
||||
)
|
||||
.db_delete_verification_otp(out_db_delete_verification_otp.clone())
|
||||
.db_get_verification_otp(out_db_get_verification_otp.clone())
|
||||
.build()
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
let add_store: AddStoreServiceObj = Arc::new(
|
||||
AddStoreServiceBuilder::default()
|
||||
.db_store_id_exists(out_db_store_id_exists.clone())
|
||||
.db_store_name_exists(out_db_store_name_exists.clone())
|
||||
.build()
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
let update_store: UpdateStoreServiceObj = Arc::new(
|
||||
UpdateStoreServiceBuilder::default()
|
||||
.db_store_id_exists(out_db_store_id_exists.clone())
|
||||
.db_store_name_exists(out_db_store_name_exists.clone())
|
||||
.build()
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
Arc::new(Self {
|
||||
delete_user,
|
||||
login,
|
||||
mark_user_verified,
|
||||
register_user,
|
||||
resend_verification_email,
|
||||
set_user_admin,
|
||||
update_email,
|
||||
update_password,
|
||||
|
||||
// employee_accept_invite_service,
|
||||
employee_exit_organization_service,
|
||||
employee_login_service,
|
||||
employee_register_service,
|
||||
employee_resend_login_otp_service,
|
||||
employee_resend_verification_otp_service,
|
||||
employee_verify_phone_number_service,
|
||||
|
||||
add_store,
|
||||
update_store,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use random_number::tests::mock_generate_random_number;
|
||||
|
||||
use crate::{
|
||||
tests::bdd::IS_NEVER_CALLED,
|
||||
utils::{random_string::tests::mock_generate_random_string, uuid::tests::mock_get_uuid},
|
||||
};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn services_init_works() {
|
||||
let s = IdentityServices::new(
|
||||
mock_create_login_otp_db_port(IS_NEVER_CALLED),
|
||||
mock_create_verification_otp_db_port(IS_NEVER_CALLED),
|
||||
mock_create_verification_secret_db_port(IS_NEVER_CALLED),
|
||||
mock_delete_login_otp_db_port(IS_NEVER_CALLED),
|
||||
mock_delete_verification_otp_db_port(IS_NEVER_CALLED),
|
||||
mock_delete_verification_secret_db_port(IS_NEVER_CALLED),
|
||||
mock_email_exists_db_port(IS_NEVER_CALLED, false),
|
||||
mock_emp_id_exists_db_port(IS_NEVER_CALLED, false),
|
||||
mock_get_emp_id_from_phone_number_db_port(IS_NEVER_CALLED),
|
||||
mock_get_login_otp_db_port(IS_NEVER_CALLED),
|
||||
mock_get_verification_otp_db_port(IS_NEVER_CALLED),
|
||||
mock_get_verification_secret_db_port(IS_NEVER_CALLED, "".into()),
|
||||
mock_phone_exists_db_port(IS_NEVER_CALLED, false),
|
||||
mock_store_id_exists_db_port_true(IS_NEVER_CALLED),
|
||||
mock_store_name_exists_db_port_true(IS_NEVER_CALLED),
|
||||
mock_user_id_exists_db_port(IS_NEVER_CALLED, false),
|
||||
mock_verification_secret_exists_db_port(IS_NEVER_CALLED, false),
|
||||
mock_account_validation_link_mailer_port(IS_NEVER_CALLED),
|
||||
mock_account_validation_otp_phone_port(IS_NEVER_CALLED),
|
||||
mock_account_login_otp_phone_port(IS_NEVER_CALLED),
|
||||
mock_get_uuid(IS_NEVER_CALLED),
|
||||
mock_generate_random_string(IS_NEVER_CALLED, "".into()),
|
||||
mock_generate_random_number(IS_NEVER_CALLED, 0),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -127,7 +127,7 @@ mod tests {
|
|||
IS_CALLED_ONLY_ONCE,
|
||||
RETURNS_RANDOM_STRING.into(),
|
||||
))
|
||||
.mailer_account_validation_link_adapter(mock_account_validation_link_db_port(
|
||||
.mailer_account_validation_link_adapter(mock_account_validation_link_mailer_port(
|
||||
IS_CALLED_ONLY_ONCE,
|
||||
))
|
||||
.get_uuid(mock_get_uuid(IS_CALLED_ONLY_ONCE))
|
||||
|
@ -172,7 +172,7 @@ mod tests {
|
|||
IS_NEVER_CALLED,
|
||||
RETURNS_RANDOM_STRING.into(),
|
||||
))
|
||||
.mailer_account_validation_link_adapter(mock_account_validation_link_db_port(
|
||||
.mailer_account_validation_link_adapter(mock_account_validation_link_mailer_port(
|
||||
IS_NEVER_CALLED,
|
||||
))
|
||||
.get_uuid(mock_get_uuid(IS_NEVER_CALLED))
|
||||
|
|
|
@ -77,7 +77,7 @@ mod tests {
|
|||
IS_CALLED_ONLY_ONCE,
|
||||
RETURNS_FALSE,
|
||||
))
|
||||
.mailer_account_validation_link_adapter(mock_account_validation_link_db_port(
|
||||
.mailer_account_validation_link_adapter(mock_account_validation_link_mailer_port(
|
||||
IS_CALLED_ONLY_ONCE,
|
||||
))
|
||||
.build()
|
||||
|
@ -105,7 +105,7 @@ mod tests {
|
|||
secret.into(),
|
||||
))
|
||||
.db_email_exists_adapter(mock_email_exists_db_port(IS_CALLED_ONLY_ONCE, RETURNS_TRUE))
|
||||
.mailer_account_validation_link_adapter(mock_account_validation_link_db_port(
|
||||
.mailer_account_validation_link_adapter(mock_account_validation_link_mailer_port(
|
||||
IS_NEVER_CALLED,
|
||||
))
|
||||
.build()
|
||||
|
|
|
@ -4,7 +4,7 @@
|
|||
|
||||
use super::*;
|
||||
|
||||
struct SetUserAdminService;
|
||||
pub struct SetUserAdminService;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl SetUserAdminUseCase for SetUserAdminService {
|
||||
|
|
|
@ -100,7 +100,7 @@ mod tests {
|
|||
IS_CALLED_ONLY_ONCE,
|
||||
RETURNS_RANDOM_STRING.into(),
|
||||
))
|
||||
.mailer_account_validation_link_adapter(mock_account_validation_link_db_port(
|
||||
.mailer_account_validation_link_adapter(mock_account_validation_link_mailer_port(
|
||||
IS_CALLED_ONLY_ONCE,
|
||||
))
|
||||
.build()
|
||||
|
@ -124,7 +124,7 @@ mod tests {
|
|||
IS_NEVER_CALLED,
|
||||
RETURNS_RANDOM_STRING.into(),
|
||||
))
|
||||
.mailer_account_validation_link_adapter(mock_account_validation_link_db_port(
|
||||
.mailer_account_validation_link_adapter(mock_account_validation_link_mailer_port(
|
||||
IS_NEVER_CALLED,
|
||||
))
|
||||
.build()
|
||||
|
|
|
@ -4,7 +4,7 @@
|
|||
|
||||
use super::*;
|
||||
|
||||
struct UpdatePasswordService;
|
||||
pub struct UpdatePasswordService;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl UpdatePasswordUseCase for UpdatePasswordService {
|
||||
|
|
146
src/identity/application/services/update_store_service.rs
Normal file
146
src/identity/application/services/update_store_service.rs
Normal file
|
@ -0,0 +1,146 @@
|
|||
// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use derive_builder::Builder;
|
||||
use mockall::predicate::*;
|
||||
use mockall::*;
|
||||
|
||||
use super::errors::*;
|
||||
use crate::identity::{
|
||||
application::port::output::db::{store_id_exists::*, store_name_exists::*},
|
||||
domain::{
|
||||
store_aggregate::*, store_updated_event::*, update_store_command::UpdateStoreCommand,
|
||||
},
|
||||
};
|
||||
use crate::utils::uuid::*;
|
||||
|
||||
#[automock]
|
||||
#[async_trait::async_trait]
|
||||
pub trait UpdateStoreUseCase: Send + Sync {
|
||||
async fn update_store(&self, cmd: UpdateStoreCommand) -> IdentityResult<StoreUpdatedEvent>;
|
||||
}
|
||||
|
||||
pub type UpdateStoreServiceObj = Arc<dyn UpdateStoreUseCase>;
|
||||
|
||||
#[derive(Clone, Builder)]
|
||||
pub struct UpdateStoreService {
|
||||
db_store_id_exists: StoreIDExistsDBPortObj,
|
||||
db_store_name_exists: StoreNameExistsDBPortObj,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl UpdateStoreUseCase for UpdateStoreService {
|
||||
async fn update_store(&self, cmd: UpdateStoreCommand) -> IdentityResult<StoreUpdatedEvent> {
|
||||
if !self
|
||||
.db_store_id_exists
|
||||
.store_id_exists(cmd.old_store().store_id())
|
||||
.await?
|
||||
{
|
||||
return Err(IdentityError::StoreIDNotFound);
|
||||
}
|
||||
|
||||
let store = StoreBuilder::default()
|
||||
.name(cmd.name().into())
|
||||
.address(cmd.address().as_ref().map(|s| s.to_string()))
|
||||
.owner(*cmd.owner())
|
||||
.store_id(*cmd.old_store().store_id())
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
if cmd.name() != cmd.old_store().name() {
|
||||
if self.db_store_name_exists.store_name_exists(&store).await? {
|
||||
return Err(IdentityError::DuplicateStoreName);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(StoreUpdatedEventBuilder::default()
|
||||
.added_by_user(*cmd.adding_by())
|
||||
.new_store(store)
|
||||
.old_store(cmd.old_store().clone())
|
||||
.build()
|
||||
.unwrap())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub mod tests {
|
||||
use super::*;
|
||||
|
||||
use crate::identity::domain::store_updated_event::tests::get_store_updated_event_from_command;
|
||||
use crate::identity::domain::update_store_command::tests::get_update_store_cmd;
|
||||
use crate::tests::bdd::*;
|
||||
use crate::utils::uuid::tests::*;
|
||||
|
||||
pub fn mock_update_store_service(
|
||||
times: Option<usize>,
|
||||
cmd: UpdateStoreCommand,
|
||||
) -> UpdateStoreServiceObj {
|
||||
let mut m = MockUpdateStoreUseCase::new();
|
||||
|
||||
let res = get_store_updated_event_from_command(&cmd);
|
||||
|
||||
if let Some(times) = times {
|
||||
m.expect_update_store()
|
||||
.times(times)
|
||||
.returning(move |_| Ok(res.clone()));
|
||||
} else {
|
||||
m.expect_update_store().returning(move |_| Ok(res.clone()));
|
||||
}
|
||||
|
||||
Arc::new(m)
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn test_service() {
|
||||
let cmd = get_update_store_cmd();
|
||||
|
||||
let s = UpdateStoreServiceBuilder::default()
|
||||
.db_store_id_exists(mock_store_id_exists_db_port_true(IS_CALLED_ONLY_ONCE))
|
||||
.db_store_name_exists(mock_store_name_exists_db_port_false(IS_CALLED_ONLY_ONCE))
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
let res = s.update_store(cmd.clone()).await.unwrap();
|
||||
assert_eq!(res.new_store().name(), cmd.name());
|
||||
assert_eq!(res.new_store().address(), cmd.address());
|
||||
assert_eq!(res.new_store().owner(), cmd.owner());
|
||||
assert_eq!(res.new_store().store_id(), cmd.old_store().store_id());
|
||||
assert_eq!(res.old_store(), cmd.old_store());
|
||||
assert_eq!(res.added_by_user(), cmd.adding_by());
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn test_service_store_name_exists() {
|
||||
let cmd = get_update_store_cmd();
|
||||
|
||||
let s = UpdateStoreServiceBuilder::default()
|
||||
.db_store_id_exists(mock_store_id_exists_db_port_true(IS_CALLED_ONLY_ONCE))
|
||||
.db_store_name_exists(mock_store_name_exists_db_port_true(IS_CALLED_ONLY_ONCE))
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
s.update_store(cmd.clone()).await,
|
||||
Err(IdentityError::DuplicateStoreName)
|
||||
);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn test_service_store_id_doesnt_exist() {
|
||||
let cmd = get_update_store_cmd();
|
||||
|
||||
let s = UpdateStoreServiceBuilder::default()
|
||||
.db_store_id_exists(mock_store_id_exists_db_port_false(IS_CALLED_ONLY_ONCE))
|
||||
.db_store_name_exists(mock_store_name_exists_db_port_false(IS_NEVER_CALLED))
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
s.update_store(cmd.clone()).await,
|
||||
Err(IdentityError::StoreIDNotFound)
|
||||
);
|
||||
}
|
||||
}
|
109
src/identity/domain/add_store_command.rs
Normal file
109
src/identity/domain/add_store_command.rs
Normal file
|
@ -0,0 +1,109 @@
|
|||
// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
use derive_builder::Builder;
|
||||
use derive_getters::Getters;
|
||||
use derive_more::{Display, Error};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug, Error, Display, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum AddStoreCommandError {
|
||||
NameIsEmpty,
|
||||
}
|
||||
|
||||
#[derive(
|
||||
Clone, Builder, Debug, Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Getters,
|
||||
)]
|
||||
#[builder(build_fn(validate = "Self::validate"))]
|
||||
pub struct AddStoreCommand {
|
||||
#[builder(setter(custom))]
|
||||
name: String,
|
||||
#[builder(setter(custom))]
|
||||
address: Option<String>,
|
||||
store_id: Uuid,
|
||||
owner: Uuid,
|
||||
}
|
||||
|
||||
impl AddStoreCommandBuilder {
|
||||
pub fn address(&mut self, address: Option<String>) -> &mut Self {
|
||||
self.address = if let Some(address) = address {
|
||||
let address = address.trim();
|
||||
if address.is_empty() {
|
||||
Some(None)
|
||||
} else {
|
||||
Some(Some(address.to_owned()))
|
||||
}
|
||||
} else {
|
||||
Some(None)
|
||||
};
|
||||
self
|
||||
}
|
||||
|
||||
pub fn name(&mut self, name: String) -> &mut Self {
|
||||
self.name = Some(name.trim().to_owned());
|
||||
self
|
||||
}
|
||||
|
||||
fn validate(&self) -> Result<(), String> {
|
||||
let name = self.name.as_ref().unwrap().trim().to_owned();
|
||||
if name.is_empty() {
|
||||
return Err(AddStoreCommandError::NameIsEmpty.to_string());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::tests::bdd::*;
|
||||
use crate::utils::uuid::tests::*;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_cmd() {
|
||||
let name = "foo";
|
||||
let address = "bar";
|
||||
let owner = UUID;
|
||||
|
||||
// address = None
|
||||
let cmd = AddStoreCommandBuilder::default()
|
||||
.name(name.into())
|
||||
.address(None)
|
||||
.owner(owner)
|
||||
.store_id(UUID)
|
||||
.build()
|
||||
.unwrap();
|
||||
// let cmd = AddStoreCommand::new(name.into(), None, owner, UUID).unwrap();
|
||||
assert_eq!(cmd.name(), name);
|
||||
assert_eq!(cmd.address(), &None);
|
||||
assert_eq!(cmd.owner(), &owner);
|
||||
assert_eq!(*cmd.store_id(), UUID);
|
||||
|
||||
// address = Some
|
||||
let cmd = AddStoreCommandBuilder::default()
|
||||
.name(name.into())
|
||||
.address(Some(address.into()))
|
||||
.owner(owner)
|
||||
.store_id(UUID)
|
||||
.build()
|
||||
.unwrap();
|
||||
// let cmd = AddStoreCommand::new(name.into(), Some(address.into()), owner, UUID).unwrap();
|
||||
assert_eq!(cmd.name(), name);
|
||||
assert_eq!(cmd.address(), &Some(address.to_owned()));
|
||||
assert_eq!(cmd.owner(), &owner);
|
||||
assert_eq!(*cmd.store_id(), UUID);
|
||||
|
||||
// AddStoreCommandError::NameIsEmpty
|
||||
|
||||
assert!(AddStoreCommandBuilder::default()
|
||||
.name("".into())
|
||||
.address(Some(address.into()))
|
||||
.owner(owner)
|
||||
.store_id(UUID)
|
||||
.build()
|
||||
.is_err())
|
||||
}
|
||||
}
|
|
@ -128,12 +128,12 @@ impl Aggregate for Employee {
|
|||
.await?,
|
||||
)])
|
||||
}
|
||||
IdentityCommand::EmployeeAcceptInvite(cmd) => Ok(vec![IdentityEvent::InviteAccepted(
|
||||
services
|
||||
.employee_accept_invite_service()
|
||||
.accept_invite(cmd)
|
||||
.await?,
|
||||
)]),
|
||||
// IdentityCommand::EmployeeAcceptInvite(cmd) => Ok(vec![IdentityEvent::InviteAccepted(
|
||||
// services
|
||||
// .employee_accept_invite_service()
|
||||
// .accept_invite(cmd)
|
||||
// .await?,
|
||||
// )]),
|
||||
IdentityCommand::EmployeeExitOrganization(cmd) => {
|
||||
Ok(vec![IdentityEvent::OrganizationExited(
|
||||
services
|
||||
|
@ -158,7 +158,7 @@ impl Aggregate for Employee {
|
|||
IdentityEvent::PhoneNumberVerified(e) => self.phone_verified = true,
|
||||
IdentityEvent::VerificationOTPResent(e) => (),
|
||||
IdentityEvent::PhoneNumberChanged(e) => unimplemented!(),
|
||||
IdentityEvent::InviteAccepted(e) => self.store_id = Some(*e.store_id()),
|
||||
// IdentityEvent::InviteAccepted(e) => self.store_id = Some(*e.store_id()),
|
||||
IdentityEvent::OrganizationExited(e) => self.store_id = None,
|
||||
|
||||
_ => (),
|
||||
|
@ -171,7 +171,7 @@ mod tests {
|
|||
use std::sync::Arc;
|
||||
|
||||
use cqrs_es::test::TestFramework;
|
||||
use employee_accept_invite_service::EmployeeAcceptInviteService;
|
||||
// use employee_accept_invite_service::EmployeeAcceptInviteService;
|
||||
use employee_exit_organization_service::EmployeeExitOrganizationService;
|
||||
use employee_login_service::EmployeeLoginService;
|
||||
use employee_resend_login_otp_service::EmployeeResendLoginOTPService;
|
||||
|
@ -179,13 +179,13 @@ mod tests {
|
|||
use employee_verify_phone_number_service::EmployeeVerifyPhoneNumberService;
|
||||
|
||||
use crate::identity::domain::{
|
||||
accept_invite_command::AcceptInviteCommand,
|
||||
// accept_invite_command::AcceptInviteCommand,
|
||||
employee_logged_in_event::{EmployeeInitLoggedInEvent, EmployeeLoggedInEvent},
|
||||
employee_login_command::{EmployeeFinishLoginCommand, EmployeeInitLoginCommand},
|
||||
employee_register_command::EmployeeRegisterCommand,
|
||||
employee_registered_event::EmployeeRegisteredEvent,
|
||||
exit_organization_command::ExitOrganizationCommand,
|
||||
invite_accepted_event::InviteAcceptedEvent,
|
||||
// invite_accepted_event::InviteAcceptedEvent,
|
||||
organization_exited_event::OrganizationExitedEvent,
|
||||
phone_number_verified_event::PhoneNumberVerifiedEvent,
|
||||
resend_login_otp_command::ResendLoginOTPCommand,
|
||||
|
@ -327,26 +327,26 @@ mod tests {
|
|||
.then_expect_events(vec![expected]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_accept_invite() {
|
||||
let cmd = AcceptInviteCommand::get_cmd();
|
||||
let expected = InviteAcceptedEvent::get_event(&cmd);
|
||||
let expected = IdentityEvent::InviteAccepted(expected);
|
||||
|
||||
let mut services = MockIdentityServicesInterface::new();
|
||||
services
|
||||
.expect_employee_accept_invite_service()
|
||||
.times(IS_CALLED_ONLY_ONCE.unwrap())
|
||||
.return_const(EmployeeAcceptInviteService::mock_service(
|
||||
IS_CALLED_ONLY_ONCE,
|
||||
cmd.clone(),
|
||||
));
|
||||
|
||||
EmployeeTestFramework::with(Arc::new(services))
|
||||
.given_no_previous_events()
|
||||
.when(IdentityCommand::EmployeeAcceptInvite(cmd))
|
||||
.then_expect_events(vec![expected]);
|
||||
}
|
||||
// #[test]
|
||||
// fn test_accept_invite() {
|
||||
// let cmd = AcceptInviteCommand::get_cmd();
|
||||
// let expected = InviteAcceptedEvent::get_event(&cmd);
|
||||
// let expected = IdentityEvent::InviteAccepted(expected);
|
||||
//
|
||||
// let mut services = MockIdentityServicesInterface::new();
|
||||
// services
|
||||
// .expect_employee_accept_invite_service()
|
||||
// .times(IS_CALLED_ONLY_ONCE.unwrap())
|
||||
// .return_const(EmployeeAcceptInviteService::mock_service(
|
||||
// IS_CALLED_ONLY_ONCE,
|
||||
// cmd.clone(),
|
||||
// ));
|
||||
//
|
||||
// EmployeeTestFramework::with(Arc::new(services))
|
||||
// .given_no_previous_events()
|
||||
// .when(IdentityCommand::EmployeeAcceptInvite(cmd))
|
||||
// .then_expect_events(vec![expected]);
|
||||
// }
|
||||
|
||||
#[test]
|
||||
fn test_exit_organization() {
|
||||
|
|
|
@ -5,27 +5,31 @@
|
|||
pub mod aggregate;
|
||||
pub mod employee_aggregate;
|
||||
//pub mod employee_commands;
|
||||
// pub mod store_aggregate;
|
||||
pub mod store_aggregate;
|
||||
// pub mod invite;
|
||||
|
||||
// events
|
||||
pub mod employee_logged_in_event;
|
||||
pub mod employee_registered_event;
|
||||
pub mod invite_accepted_event;
|
||||
//pub mod invite_accepted_event;
|
||||
pub mod login_otp_sent_event;
|
||||
pub mod organization_exited_event;
|
||||
pub mod phone_number_changed_event;
|
||||
pub mod phone_number_verified_event;
|
||||
pub mod resend_login_otp_event;
|
||||
pub mod store_added_event;
|
||||
pub mod store_updated_event;
|
||||
pub mod verification_otp_resent_event;
|
||||
pub mod verification_otp_sent_event;
|
||||
|
||||
// commands
|
||||
pub mod accept_invite_command;
|
||||
//pub mod accept_invite_command;
|
||||
pub mod add_store_command;
|
||||
pub mod change_phone_number_command;
|
||||
pub mod employee_login_command;
|
||||
pub mod employee_register_command;
|
||||
pub mod exit_organization_command;
|
||||
pub mod resend_login_otp_command;
|
||||
pub mod resend_verification_otp_command;
|
||||
pub mod update_store_command;
|
||||
pub mod verify_phone_number_command;
|
||||
|
|
18
src/identity/domain/store_added_event.rs
Normal file
18
src/identity/domain/store_added_event.rs
Normal file
|
@ -0,0 +1,18 @@
|
|||
// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
use derive_builder::Builder;
|
||||
use derive_getters::Getters;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(
|
||||
Clone, Debug, Builder, Serialize, Deserialize, Getters, Eq, PartialEq, Ord, PartialOrd,
|
||||
)]
|
||||
pub struct StoreAddedEvent {
|
||||
name: String,
|
||||
address: Option<String>,
|
||||
owner: Uuid,
|
||||
store_id: Uuid,
|
||||
}
|
148
src/identity/domain/store_aggregate.rs
Normal file
148
src/identity/domain/store_aggregate.rs
Normal file
|
@ -0,0 +1,148 @@
|
|||
// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
use async_trait::async_trait;
|
||||
use cqrs_es::Aggregate;
|
||||
use derive_builder::Builder;
|
||||
use derive_getters::Getters;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::identity::application::services::{errors::*, events::*, *};
|
||||
|
||||
#[derive(
|
||||
Clone, Default, Debug, Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Builder, Getters,
|
||||
)]
|
||||
pub struct Store {
|
||||
name: String,
|
||||
address: Option<String>,
|
||||
owner: Uuid,
|
||||
store_id: Uuid,
|
||||
#[builder(default = "false")]
|
||||
deleted: bool,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Aggregate for Store {
|
||||
type Command = IdentityCommand;
|
||||
type Event = IdentityEvent;
|
||||
type Error = IdentityError;
|
||||
type Services = std::sync::Arc<dyn IdentityServicesInterface>;
|
||||
|
||||
// This identifier should be unique to the system.
|
||||
fn aggregate_type() -> String {
|
||||
"billing.store".to_string()
|
||||
}
|
||||
// The aggregate logic goes here. Note that this will be the _bulk_ of a CQRS system
|
||||
// so expect to use helper functions elsewhere to keep the code clean.
|
||||
async fn handle(
|
||||
&self,
|
||||
command: Self::Command,
|
||||
services: &Self::Services,
|
||||
) -> Result<Vec<Self::Event>, Self::Error> {
|
||||
match command {
|
||||
IdentityCommand::AddStore(cmd) => {
|
||||
let res = services.add_store().add_store(cmd).await?;
|
||||
Ok(vec![IdentityEvent::StoreAdded(res)])
|
||||
}
|
||||
IdentityCommand::UpdateStore(cmd) => {
|
||||
let res = services.update_store().update_store(cmd).await?;
|
||||
Ok(vec![IdentityEvent::StoreUpdated(res)])
|
||||
}
|
||||
|
||||
_ => Ok(Vec::default()),
|
||||
}
|
||||
}
|
||||
|
||||
fn apply(&mut self, event: Self::Event) {
|
||||
match event {
|
||||
IdentityEvent::StoreAdded(e) => {
|
||||
self.name = e.name().into();
|
||||
self.address = e.address().as_ref().map(|s| s.to_string());
|
||||
self.owner = *e.owner();
|
||||
self.store_id = *e.store_id();
|
||||
self.deleted = false;
|
||||
}
|
||||
IdentityEvent::StoreUpdated(e) => *self = e.new_store().clone(),
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
}
|
||||
//
|
||||
//#[cfg(test)]
|
||||
//mod tests {
|
||||
// use std::sync::Arc;
|
||||
//
|
||||
// use cqrs_es::test::TestFramework;
|
||||
// use update_store_service::tests::mock_update_store_service;
|
||||
//
|
||||
// use super::*;
|
||||
// use crate::billing::{
|
||||
// application::services::add_store_service::tests::*,
|
||||
// domain::{
|
||||
// add_store_command::*, commands::IdentityCommand, events::IdentityEvent,
|
||||
// store_added_event::*, store_updated_event::tests::get_store_updated_event_from_command,
|
||||
// update_store_command::tests::get_update_store_cmd,
|
||||
// },
|
||||
// };
|
||||
// use crate::tests::bdd::*;
|
||||
// use crate::utils::uuid::tests::*;
|
||||
//
|
||||
// // A test framework that will apply our events and command
|
||||
// // and verify that the logic works as expected.
|
||||
// type StoreTestFramework = TestFramework<Store>;
|
||||
//
|
||||
// #[test]
|
||||
// fn test_create_store() {
|
||||
// let name = "store_name";
|
||||
// let address = Some("store_address".to_string());
|
||||
// let owner = UUID;
|
||||
// let store_id = UUID;
|
||||
//
|
||||
// let expected = StoreAddedEventBuilder::default()
|
||||
// .name(name.into())
|
||||
// .address(address.clone())
|
||||
// .store_id(store_id)
|
||||
// .owner(owner)
|
||||
// .build()
|
||||
// .unwrap();
|
||||
// let expected = IdentityEvent::StoreAdded(expected);
|
||||
//
|
||||
// let cmd = AddStoreCommandBuilder::default()
|
||||
// .name(name.into())
|
||||
// .address(address.clone())
|
||||
// .owner(owner)
|
||||
// .store_id(UUID)
|
||||
// .build()
|
||||
// .unwrap();
|
||||
//
|
||||
// let mut services = MockIdentityServicesInterface::new();
|
||||
// services
|
||||
// .expect_add_store()
|
||||
// .times(IS_CALLED_ONLY_ONCE.unwrap())
|
||||
// .return_const(mock_add_store_service(IS_CALLED_ONLY_ONCE, cmd.clone()));
|
||||
//
|
||||
// StoreTestFramework::with(Arc::new(services))
|
||||
// .given_no_previous_events()
|
||||
// .when(IdentityCommand::AddStore(cmd))
|
||||
// .then_expect_events(vec![expected]);
|
||||
// }
|
||||
//
|
||||
// #[test]
|
||||
// fn test_update_store() {
|
||||
// let cmd = get_update_store_cmd();
|
||||
// let expected = IdentityEvent::StoreUpdated(get_store_updated_event_from_command(&cmd));
|
||||
//
|
||||
// let mut services = MockIdentityServicesInterface::new();
|
||||
// services
|
||||
// .expect_update_store()
|
||||
// .times(IS_CALLED_ONLY_ONCE.unwrap())
|
||||
// .return_const(mock_update_store_service(IS_CALLED_ONLY_ONCE, cmd.clone()));
|
||||
//
|
||||
// StoreTestFramework::with(Arc::new(services))
|
||||
// .given_no_previous_events()
|
||||
// .when(IdentityCommand::UpdateStore(cmd))
|
||||
// .then_expect_events(vec![expected]);
|
||||
// }
|
||||
//}
|
43
src/identity/domain/store_updated_event.rs
Normal file
43
src/identity/domain/store_updated_event.rs
Normal file
|
@ -0,0 +1,43 @@
|
|||
// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
use derive_builder::Builder;
|
||||
use derive_getters::Getters;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::store_aggregate::*;
|
||||
|
||||
#[derive(
|
||||
Clone, Debug, Builder, Serialize, Deserialize, Getters, Eq, PartialEq, Ord, PartialOrd,
|
||||
)]
|
||||
pub struct StoreUpdatedEvent {
|
||||
added_by_user: Uuid,
|
||||
old_store: Store,
|
||||
new_store: Store,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub mod tests {
|
||||
use crate::identity::domain::update_store_command::UpdateStoreCommand;
|
||||
|
||||
use super::*;
|
||||
|
||||
pub fn get_store_updated_event_from_command(cmd: &UpdateStoreCommand) -> StoreUpdatedEvent {
|
||||
let new_store = StoreBuilder::default()
|
||||
.name(cmd.name().into())
|
||||
.address(cmd.address().as_ref().map(|s| s.to_string()))
|
||||
.owner(*cmd.owner())
|
||||
.store_id(*cmd.old_store().store_id())
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
StoreUpdatedEventBuilder::default()
|
||||
.new_store(new_store)
|
||||
.old_store(cmd.old_store().clone())
|
||||
.added_by_user(*cmd.adding_by())
|
||||
.build()
|
||||
.unwrap()
|
||||
}
|
||||
}
|
127
src/identity/domain/update_store_command.rs
Normal file
127
src/identity/domain/update_store_command.rs
Normal file
|
@ -0,0 +1,127 @@
|
|||
// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
use derive_getters::Getters;
|
||||
use derive_more::{Display, Error};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::store_aggregate::*;
|
||||
|
||||
#[derive(Debug, Error, Display, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum UpdateStoreCommandError {
|
||||
NameIsEmpty,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Getters)]
|
||||
pub struct UpdateStoreCommand {
|
||||
name: String,
|
||||
address: Option<String>,
|
||||
owner: Uuid,
|
||||
old_store: Store,
|
||||
adding_by: Uuid,
|
||||
}
|
||||
|
||||
impl UpdateStoreCommand {
|
||||
pub fn new(
|
||||
name: String,
|
||||
address: Option<String>,
|
||||
owner: Uuid,
|
||||
old_store: Store,
|
||||
adding_by: Uuid,
|
||||
) -> Result<Self, UpdateStoreCommandError> {
|
||||
let address: Option<String> = if let Some(address) = address {
|
||||
let address = address.trim();
|
||||
if address.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(address.to_owned())
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let name = name.trim().to_owned();
|
||||
if name.is_empty() {
|
||||
return Err(UpdateStoreCommandError::NameIsEmpty);
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
name,
|
||||
address,
|
||||
owner,
|
||||
old_store,
|
||||
adding_by,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub mod tests {
|
||||
use crate::utils::uuid::tests::UUID;
|
||||
|
||||
use super::*;
|
||||
|
||||
pub fn get_update_store_cmd() -> UpdateStoreCommand {
|
||||
let name = "foo";
|
||||
let address = "bar";
|
||||
let owner = UUID;
|
||||
let adding_by = UUID;
|
||||
let old_store = Store::default();
|
||||
|
||||
UpdateStoreCommand::new(
|
||||
name.into(),
|
||||
Some(address.into()),
|
||||
owner,
|
||||
old_store.clone(),
|
||||
adding_by,
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_cmd() {
|
||||
let name = "foo";
|
||||
let address = "bar";
|
||||
let owner = UUID;
|
||||
let old_store = Store::default();
|
||||
let adding_by = Uuid::new_v4();
|
||||
|
||||
// address = None
|
||||
let cmd = UpdateStoreCommand::new(name.into(), None, owner, old_store.clone(), adding_by)
|
||||
.unwrap();
|
||||
assert_eq!(cmd.name(), name);
|
||||
assert_eq!(cmd.address(), &None);
|
||||
assert_eq!(cmd.owner(), &owner);
|
||||
assert_eq!(cmd.old_store(), &old_store);
|
||||
assert_eq!(cmd.adding_by(), &adding_by);
|
||||
|
||||
// address = Some
|
||||
let cmd = UpdateStoreCommand::new(
|
||||
name.into(),
|
||||
Some(address.into()),
|
||||
owner,
|
||||
old_store.clone(),
|
||||
adding_by,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(cmd.name(), name);
|
||||
assert_eq!(cmd.address(), &Some(address.to_owned()));
|
||||
assert_eq!(cmd.owner(), &owner);
|
||||
assert_eq!(cmd.old_store(), &old_store);
|
||||
assert_eq!(cmd.adding_by(), &adding_by);
|
||||
|
||||
// UpdateStoreCommandError::NameIsEmpty
|
||||
assert_eq!(
|
||||
UpdateStoreCommand::new(
|
||||
"".into(),
|
||||
Some(address.into()),
|
||||
owner,
|
||||
old_store.clone(),
|
||||
adding_by
|
||||
),
|
||||
Err(UpdateStoreCommandError::NameIsEmpty)
|
||||
)
|
||||
}
|
||||
}
|
|
@ -2,6 +2,6 @@
|
|||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
mod adapters;
|
||||
pub(crate) mod adapters;
|
||||
mod application;
|
||||
mod domain;
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
pub mod web;
|
||||
|
|
114
src/inventory/adapters/input/web/category.rs
Normal file
114
src/inventory/adapters/input/web/category.rs
Normal file
|
@ -0,0 +1,114 @@
|
|||
// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
use actix_identity::Identity;
|
||||
use actix_web::{get, http::header::ContentType, post, web, HttpRequest, HttpResponse, Responder};
|
||||
use derive_builder::Builder;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use url::Url;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::errors::*;
|
||||
use super::types;
|
||||
//use crate::utils::uuid::WebGetUUIDInterfaceObj;
|
||||
|
||||
pub fn services(cfg: &mut web::ServiceConfig) {
|
||||
cfg.service(add_category_ui_handler);
|
||||
cfg.service(add_category_form_submission_handler);
|
||||
cfg.service(update_category_ui_handler);
|
||||
cfg.service(update_category_form_submission_handler);
|
||||
}
|
||||
|
||||
// add_category handlers
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[get("/inventory/category/add")]
|
||||
#[tracing::instrument(name = "add_category UI handler", skip())]
|
||||
async fn add_category_ui_handler() -> WebJsonRepsonse<impl Responder> {
|
||||
use web_ui::inventory::add_category::*;
|
||||
|
||||
let page = AddCategoryPage::page();
|
||||
|
||||
Ok(HttpResponse::Ok()
|
||||
.insert_header(ContentType::html())
|
||||
.body(page))
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
|
||||
struct AddCategoryPayload {
|
||||
password: String,
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[post("/inventory/category/add")]
|
||||
#[tracing::instrument(
|
||||
name = "Add c ategory form submission handler"
|
||||
skip(id, req, payload, inventory_cqrs_exec)
|
||||
)]
|
||||
async fn add_category_form_submission_handler(
|
||||
inventory_cqrs_exec: types::WebInventoryCqrsExec,
|
||||
req: HttpRequest,
|
||||
id: Identity,
|
||||
payload: web::Form<AddCategoryPayload>,
|
||||
) -> WebJsonRepsonse<impl Responder> {
|
||||
let store = "";
|
||||
|
||||
Ok(HttpResponse::Ok().json(store))
|
||||
}
|
||||
|
||||
// update_category handlers
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[get("/inventory/{category_uuid}/update")]
|
||||
#[tracing::instrument(name = "update_category UI handler", skip())]
|
||||
async fn update_category_ui_handler() -> WebJsonRepsonse<impl Responder> {
|
||||
use web_ui::inventory::update_category::*;
|
||||
|
||||
let page = UpdateCategoryPage::page();
|
||||
|
||||
Ok(HttpResponse::Ok()
|
||||
.insert_header(ContentType::html())
|
||||
.body(page))
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
|
||||
struct UpdateCategoryPayload {
|
||||
password: String,
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[post("/inventory/{category_uuid}/update")]
|
||||
#[tracing::instrument(
|
||||
name = "update_category form submission handler"
|
||||
skip(id, req, payload, inventory_cqrs_exec)
|
||||
)]
|
||||
async fn update_category_form_submission_handler(
|
||||
inventory_cqrs_exec: types::WebInventoryCqrsExec,
|
||||
req: HttpRequest,
|
||||
id: Identity,
|
||||
payload: web::Form<UpdateCategoryPayload>,
|
||||
) -> WebJsonRepsonse<impl Responder> {
|
||||
let store = "";
|
||||
|
||||
Ok(HttpResponse::Ok().json(store))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::utils::uuid::tests::UUID;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn inventory_web_add_category_ui_works() {
|
||||
let routes = crate::inventory::adapters::input::web::RoutesRepository::default();
|
||||
crate::tests::actix_web_test_utils::page_test_runner(&routes.add_category).await;
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn inventory_web_update_category_ui_works() {
|
||||
let routes = crate::inventory::adapters::input::web::RoutesRepository::default();
|
||||
crate::tests::actix_web_test_utils::page_test_runner(&routes.update_category(UUID)).await;
|
||||
}
|
||||
}
|
118
src/inventory/adapters/input/web/customization.rs
Normal file
118
src/inventory/adapters/input/web/customization.rs
Normal file
|
@ -0,0 +1,118 @@
|
|||
// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
use actix_identity::Identity;
|
||||
use actix_web::{get, http::header::ContentType, post, web, HttpRequest, HttpResponse, Responder};
|
||||
use derive_builder::Builder;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use url::Url;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::errors::*;
|
||||
use super::types;
|
||||
//use crate::utils::uuid::WebGetUUIDInterfaceObj;
|
||||
|
||||
pub fn services(cfg: &mut web::ServiceConfig) {
|
||||
cfg.service(add_customization_ui_handler);
|
||||
cfg.service(add_customization_form_submission_handler);
|
||||
cfg.service(update_customization_ui_handler);
|
||||
cfg.service(update_customization_form_submission_handler);
|
||||
}
|
||||
|
||||
// add_customization handlers
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[get("/inventory/{category_uuid}/{product_uuid}/customization/add")]
|
||||
#[tracing::instrument(name = "add_customization UI handler", skip())]
|
||||
async fn add_customization_ui_handler() -> WebJsonRepsonse<impl Responder> {
|
||||
use web_ui::inventory::add_customization::*;
|
||||
|
||||
let page = AddCustomizationPage::page();
|
||||
|
||||
Ok(HttpResponse::Ok()
|
||||
.insert_header(ContentType::html())
|
||||
.body(page))
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
|
||||
struct AddCustomizationPayload {
|
||||
password: String,
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[post("/inventory/{category_uuid}/{product_uuid}/customization/add")]
|
||||
#[tracing::instrument(
|
||||
name = "add_customization form submission handler"
|
||||
skip(id, req, payload, inventory_cqrs_exec)
|
||||
)]
|
||||
async fn add_customization_form_submission_handler(
|
||||
inventory_cqrs_exec: types::WebInventoryCqrsExec,
|
||||
req: HttpRequest,
|
||||
id: Identity,
|
||||
payload: web::Form<AddCustomizationPayload>,
|
||||
) -> WebJsonRepsonse<impl Responder> {
|
||||
let store = "";
|
||||
|
||||
Ok(HttpResponse::Ok().json(store))
|
||||
}
|
||||
|
||||
// update_customization handlers
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[get("/inventory/{category_uuid}/{product_uuid}/{customization_uuid}/update")]
|
||||
#[tracing::instrument(name = "update_customization UI handler", skip())]
|
||||
async fn update_customization_ui_handler() -> WebJsonRepsonse<impl Responder> {
|
||||
use web_ui::inventory::update_customization::*;
|
||||
|
||||
let page = UpdateCustomizationPage::page();
|
||||
|
||||
Ok(HttpResponse::Ok()
|
||||
.insert_header(ContentType::html())
|
||||
.body(page))
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
|
||||
struct UpdateCustomizationPayload {
|
||||
password: String,
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[post("/inventory/{category_uuid}/{product_uuid}/{customization_uuid}/update")]
|
||||
#[tracing::instrument(
|
||||
name = "update_customization form submission handler"
|
||||
skip(id, req, payload, inventory_cqrs_exec)
|
||||
)]
|
||||
async fn update_customization_form_submission_handler(
|
||||
inventory_cqrs_exec: types::WebInventoryCqrsExec,
|
||||
req: HttpRequest,
|
||||
id: Identity,
|
||||
payload: web::Form<UpdateCustomizationPayload>,
|
||||
) -> WebJsonRepsonse<impl Responder> {
|
||||
let store = "";
|
||||
|
||||
Ok(HttpResponse::Ok().json(store))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::utils::uuid::tests::UUID;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn inventory_web_add_customization_ui_works() {
|
||||
let routes = crate::inventory::adapters::input::web::RoutesRepository::default();
|
||||
crate::tests::actix_web_test_utils::page_test_runner(&routes.add_customization(UUID, UUID))
|
||||
.await;
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn inventory_web_update_customization_ui_works() {
|
||||
let routes = crate::inventory::adapters::input::web::RoutesRepository::default();
|
||||
crate::tests::actix_web_test_utils::page_test_runner(
|
||||
&routes.update_customization(UUID, UUID, UUID),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
110
src/inventory/adapters/input/web/errors.rs
Normal file
110
src/inventory/adapters/input/web/errors.rs
Normal file
|
@ -0,0 +1,110 @@
|
|||
// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
use actix_web::http::StatusCode;
|
||||
use actix_web::{HttpResponse, ResponseError};
|
||||
use derive_more::Display;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::inventory::application::services::errors::*;
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq)]
|
||||
struct ErrorResponse {
|
||||
error: String,
|
||||
}
|
||||
|
||||
impl From<WebError> for ErrorResponse {
|
||||
fn from(value: WebError) -> Self {
|
||||
ErrorResponse {
|
||||
error: serde_json::to_string(&value).unwrap_or_else(|_| {
|
||||
log::error!("Unable to serialize error");
|
||||
"Unable to serialize error".into()
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Display, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum WebError {
|
||||
InternalError,
|
||||
BadRequest,
|
||||
|
||||
DuplicateCategoryName,
|
||||
DuplicateStoreName,
|
||||
DuplicateProductName,
|
||||
DuplicateCustomizationName,
|
||||
DuplicateCustomizationID,
|
||||
DuplicateStoreID,
|
||||
DuplicateCategoryID,
|
||||
DuplicateProductID,
|
||||
ProductIDNotFound,
|
||||
CategoryIDNotFound,
|
||||
CustomizationIDNotFound,
|
||||
StoreIDNotFound,
|
||||
}
|
||||
|
||||
impl From<InventoryError> for WebError {
|
||||
fn from(v: InventoryError) -> Self {
|
||||
match v {
|
||||
InventoryError::InternalError => Self::InternalError,
|
||||
InventoryError::DuplicateCategoryName => Self::BadRequest,
|
||||
InventoryError::DuplicateStoreName => Self::BadRequest,
|
||||
InventoryError::DuplicateProductName => Self::BadRequest,
|
||||
InventoryError::DuplicateCustomizationName => Self::BadRequest,
|
||||
InventoryError::DuplicateCustomizationID => Self::InternalError,
|
||||
InventoryError::DuplicateStoreID => Self::InternalError,
|
||||
InventoryError::DuplicateCategoryID => Self::InternalError,
|
||||
InventoryError::DuplicateProductID => Self::InternalError,
|
||||
InventoryError::ProductIDNotFound => Self::BadRequest,
|
||||
InventoryError::CategoryIDNotFound => Self::BadRequest,
|
||||
InventoryError::CustomizationIDNotFound => Self::BadRequest,
|
||||
InventoryError::StoreIDNotFound => Self::BadRequest,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ResponseError for WebError {
|
||||
fn status_code(&self) -> StatusCode {
|
||||
match self {
|
||||
Self::InternalError => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Self::BadRequest => StatusCode::BAD_REQUEST,
|
||||
|
||||
Self::DuplicateCategoryName => StatusCode::BAD_REQUEST,
|
||||
Self::DuplicateStoreName => StatusCode::BAD_REQUEST,
|
||||
Self::DuplicateProductName => StatusCode::BAD_REQUEST,
|
||||
Self::DuplicateCustomizationName => StatusCode::BAD_REQUEST,
|
||||
Self::DuplicateCustomizationID => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Self::DuplicateStoreID => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Self::DuplicateCategoryID => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Self::DuplicateProductID => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Self::ProductIDNotFound => StatusCode::BAD_REQUEST,
|
||||
Self::CategoryIDNotFound => StatusCode::BAD_REQUEST,
|
||||
Self::CustomizationIDNotFound => StatusCode::BAD_REQUEST,
|
||||
Self::StoreIDNotFound => StatusCode::BAD_REQUEST,
|
||||
}
|
||||
}
|
||||
|
||||
fn error_response(&self) -> actix_web::HttpResponse {
|
||||
let e: ErrorResponse = self.clone().into();
|
||||
match self {
|
||||
Self::InternalError => HttpResponse::InternalServerError().json(e),
|
||||
Self::BadRequest => HttpResponse::BadRequest().json(e),
|
||||
|
||||
Self::DuplicateCategoryName => HttpResponse::BadRequest().json(e),
|
||||
Self::DuplicateStoreName => HttpResponse::BadRequest().json(e),
|
||||
Self::DuplicateProductName => HttpResponse::BadRequest().json(e),
|
||||
Self::DuplicateCustomizationName => HttpResponse::BadRequest().json(e),
|
||||
Self::DuplicateCustomizationID => HttpResponse::InternalServerError().json(e),
|
||||
Self::DuplicateStoreID => HttpResponse::InternalServerError().json(e),
|
||||
Self::DuplicateCategoryID => HttpResponse::InternalServerError().json(e),
|
||||
Self::DuplicateProductID => HttpResponse::InternalServerError().json(e),
|
||||
Self::ProductIDNotFound => HttpResponse::BadRequest().json(e),
|
||||
Self::CategoryIDNotFound => HttpResponse::BadRequest().json(e),
|
||||
Self::CustomizationIDNotFound => HttpResponse::BadRequest().json(e),
|
||||
Self::StoreIDNotFound => HttpResponse::BadRequest().json(e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub type WebJsonRepsonse<V> = Result<V, WebError>;
|
33
src/inventory/adapters/input/web/mod.rs
Normal file
33
src/inventory/adapters/input/web/mod.rs
Normal file
|
@ -0,0 +1,33 @@
|
|||
// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use actix_web::web;
|
||||
|
||||
use crate::inventory::adapters::types;
|
||||
|
||||
//mod employee;
|
||||
mod category;
|
||||
mod customization;
|
||||
mod errors;
|
||||
mod product;
|
||||
mod routes;
|
||||
|
||||
pub use errors::WebJsonRepsonse;
|
||||
|
||||
pub use routes::RoutesRepository;
|
||||
|
||||
pub fn load_ctx() -> impl FnOnce(&mut web::ServiceConfig) {
|
||||
let routes = types::WebInventoryRoutesRepository::new(Arc::new(RoutesRepository::default()));
|
||||
|
||||
let f = move |cfg: &mut web::ServiceConfig| {
|
||||
cfg.app_data(routes);
|
||||
cfg.configure(customization::services);
|
||||
cfg.configure(product::services);
|
||||
cfg.configure(category::services);
|
||||
};
|
||||
|
||||
Box::new(f)
|
||||
}
|
115
src/inventory/adapters/input/web/product.rs
Normal file
115
src/inventory/adapters/input/web/product.rs
Normal file
|
@ -0,0 +1,115 @@
|
|||
// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
use actix_identity::Identity;
|
||||
use actix_web::{get, http::header::ContentType, post, web, HttpRequest, HttpResponse, Responder};
|
||||
use derive_builder::Builder;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use url::Url;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::errors::*;
|
||||
use super::types;
|
||||
//use crate::utils::uuid::WebGetUUIDInterfaceObj;
|
||||
|
||||
pub fn services(cfg: &mut web::ServiceConfig) {
|
||||
cfg.service(add_product_ui_handler);
|
||||
cfg.service(add_product_form_submission_handler);
|
||||
cfg.service(update_product_ui_handler);
|
||||
cfg.service(update_product_form_submission_handler);
|
||||
}
|
||||
|
||||
// add_product handlers
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[get("/inventory/{category_uuid}/product/add")]
|
||||
#[tracing::instrument(name = "add_product UI handler", skip())]
|
||||
async fn add_product_ui_handler() -> WebJsonRepsonse<impl Responder> {
|
||||
use web_ui::inventory::add_product::*;
|
||||
|
||||
let page = AddProductPage::page();
|
||||
|
||||
Ok(HttpResponse::Ok()
|
||||
.insert_header(ContentType::html())
|
||||
.body(page))
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
|
||||
struct AddProductPagePayload {
|
||||
password: String,
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[post("/inventory/{category_uuid}/product/add")]
|
||||
#[tracing::instrument(
|
||||
name = "add_product form submission handler"
|
||||
skip(id, req, payload, inventory_cqrs_exec)
|
||||
)]
|
||||
async fn add_product_form_submission_handler(
|
||||
inventory_cqrs_exec: types::WebInventoryCqrsExec,
|
||||
req: HttpRequest,
|
||||
id: Identity,
|
||||
payload: web::Form<AddProductPagePayload>,
|
||||
) -> WebJsonRepsonse<impl Responder> {
|
||||
let store = "";
|
||||
|
||||
Ok(HttpResponse::Ok().json(store))
|
||||
}
|
||||
|
||||
// update_product handlers
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[get("/inventory/{category_uuid}/{product_uuid}/update")]
|
||||
#[tracing::instrument(name = "update_product UI handler", skip())]
|
||||
async fn update_product_ui_handler() -> WebJsonRepsonse<impl Responder> {
|
||||
use web_ui::inventory::update_product::*;
|
||||
|
||||
let page = UpdateProductPage::page();
|
||||
|
||||
Ok(HttpResponse::Ok()
|
||||
.insert_header(ContentType::html())
|
||||
.body(page))
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
|
||||
struct UpdateProductPagePayload {
|
||||
password: String,
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[post("/inventory/{category_uuid}/{product_uuid}/update")]
|
||||
#[tracing::instrument(
|
||||
name = "update_product form submission handler"
|
||||
skip(id, req, payload, inventory_cqrs_exec)
|
||||
)]
|
||||
async fn update_product_form_submission_handler(
|
||||
inventory_cqrs_exec: types::WebInventoryCqrsExec,
|
||||
req: HttpRequest,
|
||||
id: Identity,
|
||||
payload: web::Form<UpdateProductPagePayload>,
|
||||
) -> WebJsonRepsonse<impl Responder> {
|
||||
let store = "";
|
||||
|
||||
Ok(HttpResponse::Ok().json(store))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::utils::uuid::tests::UUID;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn inventory_web_add_product_ui_works() {
|
||||
let routes = crate::inventory::adapters::input::web::RoutesRepository::default();
|
||||
crate::tests::actix_web_test_utils::page_test_runner(&routes.add_product(UUID)).await;
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn inventory_web_update_product_ui_works() {
|
||||
let routes = crate::inventory::adapters::input::web::RoutesRepository::default();
|
||||
crate::tests::actix_web_test_utils::page_test_runner(&routes.update_product(UUID, UUID))
|
||||
.await;
|
||||
}
|
||||
}
|
120
src/inventory/adapters/input/web/routes.rs
Normal file
120
src/inventory/adapters/input/web/routes.rs
Normal file
|
@ -0,0 +1,120 @@
|
|||
// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
use url::Url;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub struct RoutesRepository {
|
||||
pub add_category: String,
|
||||
add_product: String,
|
||||
add_customization: String,
|
||||
update_product: String,
|
||||
update_customization: String,
|
||||
update_category: String,
|
||||
}
|
||||
|
||||
impl Default for RoutesRepository {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
add_category: "/inventory/category/add".into(),
|
||||
update_category: "/inventory/{category_uuid}/update".into(),
|
||||
|
||||
add_product: "/inventory/{category_uuid}/product/add".into(),
|
||||
update_product: "/inventory/{category_uuid}/{product_uuid}/update".into(),
|
||||
|
||||
add_customization: "/inventory/{category_uuid}/{product_uuid}/customization/add".into(),
|
||||
update_customization:
|
||||
"/inventory/{category_uuid}/{product_uuid}/{customization_uuid}/update".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl RoutesRepository {
|
||||
pub fn update_category(&self, category_uuid: Uuid) -> String {
|
||||
self.update_category
|
||||
.replace("{category_uuid}", &category_uuid.to_string())
|
||||
}
|
||||
|
||||
pub fn add_product(&self, category_uuid: Uuid) -> String {
|
||||
self.add_product
|
||||
.replace("{category_uuid}", &category_uuid.to_string())
|
||||
}
|
||||
pub fn update_product(&self, category_uuid: Uuid, product_uuid: Uuid) -> String {
|
||||
self.update_product
|
||||
.replace("{category_uuid}", &category_uuid.to_string())
|
||||
.replace("{product_uuid}", &product_uuid.to_string())
|
||||
}
|
||||
|
||||
pub fn add_customization(&self, category_uuid: Uuid, product_uuid: Uuid) -> String {
|
||||
self.add_customization
|
||||
.replace("{category_uuid}", &category_uuid.to_string())
|
||||
.replace("{product_uuid}", &product_uuid.to_string())
|
||||
}
|
||||
|
||||
pub fn update_customization(
|
||||
&self,
|
||||
category_uuid: Uuid,
|
||||
product_uuid: Uuid,
|
||||
customization_uuid: Uuid,
|
||||
) -> String {
|
||||
self.update_customization
|
||||
.replace("{category_uuid}", &category_uuid.to_string())
|
||||
.replace("{product_uuid}", &product_uuid.to_string())
|
||||
.replace("{customization_uuid}", &customization_uuid.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::utils::uuid::tests::UUID;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn inventory_web_route_update_category() {
|
||||
let r = RoutesRepository::default();
|
||||
assert_eq!(r.update_category(UUID), format!("/inventory/{UUID}/update"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inventory_web_route_add_product() {
|
||||
let r = RoutesRepository::default();
|
||||
assert_eq!(
|
||||
r.add_product(UUID),
|
||||
format!("/inventory/{UUID}/product/add")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inventory_web_route_update_product() {
|
||||
let r = RoutesRepository::default();
|
||||
let product_id = Uuid::new_v4();
|
||||
assert_eq!(
|
||||
r.update_product(UUID, product_id),
|
||||
format!("/inventory/{UUID}/{product_id}/update")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inventory_web_route_add_customization() {
|
||||
let r = RoutesRepository::default();
|
||||
let product_id = Uuid::new_v4();
|
||||
assert_eq!(
|
||||
r.add_customization(UUID, product_id),
|
||||
format!("/inventory/{UUID}/{product_id}/customization/add")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inventory_web_route_update_customization() {
|
||||
let r = RoutesRepository::default();
|
||||
let product_id = Uuid::new_v4();
|
||||
let customization_id = Uuid::new_v4();
|
||||
assert_eq!(
|
||||
r.update_customization(UUID, product_id, customization_id),
|
||||
format!("/inventory/{UUID}/{product_id}/{customization_id}/update")
|
||||
);
|
||||
}
|
||||
}
|
|
@ -2,5 +2,91 @@
|
|||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use actix_web::web::{self, Data};
|
||||
use cqrs_es::{persist::ViewRepository, EventEnvelope, Query, View};
|
||||
use postgres_es::PostgresCqrs;
|
||||
use sqlx::postgres::PgPool;
|
||||
|
||||
use crate::inventory::{
|
||||
application::services::{InventoryServices, InventoryServicesObj},
|
||||
domain::{
|
||||
category_aggregate::Category, customization_aggregate::Customization,
|
||||
product_aggregate::Product, store_aggregate::Store,
|
||||
},
|
||||
};
|
||||
use crate::settings::Settings;
|
||||
use output::{
|
||||
db::postgres::{
|
||||
category_view, customization_view, product_view, store_view, InventoryDBPostgresAdapter,
|
||||
},
|
||||
full_text_search::meili::InventoryFTSMeili,
|
||||
};
|
||||
|
||||
mod input;
|
||||
mod output;
|
||||
pub mod output;
|
||||
mod types;
|
||||
|
||||
pub fn load_adapters(pool: PgPool, settings: Settings) -> impl FnOnce(&mut web::ServiceConfig) {
|
||||
let db = InventoryDBPostgresAdapter::new(pool.clone());
|
||||
let fts = InventoryFTSMeili::new(&settings.meili.url, &settings.meili.api_key);
|
||||
|
||||
let services: InventoryServicesObj = InventoryServices::new(
|
||||
Arc::new(db.clone()),
|
||||
Arc::new(db.clone()),
|
||||
Arc::new(db.clone()),
|
||||
Arc::new(db.clone()),
|
||||
Arc::new(db.clone()),
|
||||
Arc::new(db.clone()),
|
||||
Arc::new(db.clone()),
|
||||
Arc::new(db.clone()),
|
||||
Arc::new(db.clone()),
|
||||
Arc::new(fts.clone()),
|
||||
);
|
||||
|
||||
let (category_cqrs_exec, category_cqrs_query) =
|
||||
category_view::init_cqrs(db.clone(), services.clone());
|
||||
let (product_cqrs_exec, product_cqrs_query) =
|
||||
product_view::init_cqrs(db.clone(), services.clone());
|
||||
let (customization_cqrs_exec, customization_cqrs_query) =
|
||||
customization_view::init_cqrs(db.clone(), services.clone());
|
||||
let (store_cqrs_exec, store_cqrs_query) = store_view::init_cqrs(db.clone(), services.clone());
|
||||
let inventory_cqrs_exec = types::WebInventoryCqrsExec::new(Arc::new(
|
||||
types::InventoryCqrsExecBuilder::default()
|
||||
.category(category_cqrs_exec)
|
||||
.product(product_cqrs_exec)
|
||||
.customization(customization_cqrs_exec)
|
||||
.store(store_cqrs_exec)
|
||||
.build()
|
||||
.unwrap(),
|
||||
));
|
||||
|
||||
let f = move |cfg: &mut web::ServiceConfig| {
|
||||
cfg.configure(input::web::load_ctx());
|
||||
cfg.app_data(Data::new(category_cqrs_query.clone()));
|
||||
cfg.app_data(Data::new(product_cqrs_query.clone()));
|
||||
cfg.app_data(Data::new(customization_cqrs_query.clone()));
|
||||
cfg.app_data(Data::new(store_cqrs_query.clone()));
|
||||
cfg.app_data(inventory_cqrs_exec.clone());
|
||||
};
|
||||
|
||||
Box::new(f)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::db::migrate::*;
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn inventory_load_adapters() {
|
||||
let settings = crate::settings::tests::get_settings().await;
|
||||
settings.create_db().await;
|
||||
|
||||
let db = crate::db::sqlx_postgres::Postgres::init(&settings.database.url).await;
|
||||
db.migrate().await;
|
||||
|
||||
load_adapters(db.pool.clone(), settings.clone());
|
||||
}
|
||||
}
|
||||
|
|
|
@ -10,6 +10,8 @@ use uuid::Uuid;
|
|||
|
||||
use super::errors::*;
|
||||
use super::InventoryDBPostgresAdapter;
|
||||
use crate::inventory::adapters::types::{InventoryCategoryCqrsExec, InventoryCategoryCqrsView};
|
||||
use crate::inventory::application::services::InventoryServicesObj;
|
||||
use crate::inventory::domain::category_aggregate::{Category, CategoryBuilder};
|
||||
use crate::inventory::domain::events::InventoryEvent;
|
||||
use crate::utils::parse_aggregate_id::parse_aggregate_id;
|
||||
|
@ -229,6 +231,20 @@ impl Query<Category> for InventoryDBPostgresAdapter {
|
|||
}
|
||||
}
|
||||
|
||||
pub fn init_cqrs(
|
||||
db: InventoryDBPostgresAdapter,
|
||||
services: InventoryServicesObj,
|
||||
) -> (InventoryCategoryCqrsExec, InventoryCategoryCqrsView) {
|
||||
let queries: Vec<Box<dyn Query<Category>>> = vec![Box::new(db.clone())];
|
||||
|
||||
let pool = db.pool.clone();
|
||||
|
||||
(
|
||||
std::sync::Arc::new(postgres_es::postgres_cqrs(pool.clone(), queries, services)),
|
||||
std::sync::Arc::new(db.clone()),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
|
|
@ -12,6 +12,10 @@ use uuid::Uuid;
|
|||
|
||||
use super::errors::*;
|
||||
use super::InventoryDBPostgresAdapter;
|
||||
use crate::inventory::adapters::types::{
|
||||
InventoryCustomizationCqrsExec, InventoryCustomizationCqrsView,
|
||||
};
|
||||
use crate::inventory::application::services::InventoryServicesObj;
|
||||
use crate::inventory::domain::{customization_aggregate::*, events::InventoryEvent};
|
||||
use crate::utils::parse_aggregate_id::parse_aggregate_id;
|
||||
|
||||
|
@ -23,7 +27,7 @@ pub const NEW_CUSTOMIZATION_NON_UUID: &str = "new_customization_non_uuid-asdfa";
|
|||
//}
|
||||
|
||||
#[derive(Debug, Default, Serialize, Deserialize)]
|
||||
struct CustomizationView {
|
||||
pub struct CustomizationView {
|
||||
name: String,
|
||||
product_id: Uuid,
|
||||
customization_id: Uuid,
|
||||
|
@ -224,6 +228,23 @@ impl Query<Customization> for InventoryDBPostgresAdapter {
|
|||
}
|
||||
}
|
||||
|
||||
pub fn init_cqrs(
|
||||
db: InventoryDBPostgresAdapter,
|
||||
services: InventoryServicesObj,
|
||||
) -> (
|
||||
InventoryCustomizationCqrsExec,
|
||||
InventoryCustomizationCqrsView,
|
||||
) {
|
||||
let queries: Vec<Box<dyn Query<Customization>>> = vec![Box::new(db.clone())];
|
||||
|
||||
let pool = db.pool.clone();
|
||||
|
||||
(
|
||||
std::sync::Arc::new(postgres_es::postgres_cqrs(pool.clone(), queries, services)),
|
||||
std::sync::Arc::new(db.clone()),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
|
|
@ -10,18 +10,18 @@ use crate::db::{migrate::RunMigrations, sqlx_postgres::Postgres};
|
|||
|
||||
mod category_id_exists;
|
||||
mod category_name_exists_for_store;
|
||||
mod category_view;
|
||||
pub mod category_view;
|
||||
mod customization_id_exists;
|
||||
mod customization_name_exists_for_product;
|
||||
mod customization_view;
|
||||
pub mod customization_view;
|
||||
mod errors;
|
||||
mod get_category;
|
||||
mod product_id_exists;
|
||||
mod product_name_exists_for_category;
|
||||
mod product_view;
|
||||
pub mod product_view;
|
||||
mod store_id_exists;
|
||||
mod store_name_exists;
|
||||
mod store_view;
|
||||
pub mod store_view;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct InventoryDBPostgresAdapter {
|
||||
|
|
|
@ -12,6 +12,8 @@ use uuid::Uuid;
|
|||
|
||||
use super::errors::*;
|
||||
use super::InventoryDBPostgresAdapter;
|
||||
use crate::inventory::adapters::types::{InventoryProductCqrsExec, InventoryProductCqrsView};
|
||||
use crate::inventory::application::services::InventoryServicesObj;
|
||||
use crate::inventory::domain::events::InventoryEvent;
|
||||
use crate::inventory::domain::product_aggregate::{Product, ProductBuilder};
|
||||
use crate::types::currency::*;
|
||||
|
@ -348,6 +350,20 @@ impl Query<Product> for InventoryDBPostgresAdapter {
|
|||
}
|
||||
}
|
||||
|
||||
pub fn init_cqrs(
|
||||
db: InventoryDBPostgresAdapter,
|
||||
services: InventoryServicesObj,
|
||||
) -> (InventoryProductCqrsExec, InventoryProductCqrsView) {
|
||||
let queries: Vec<Box<dyn Query<Product>>> = vec![Box::new(db.clone())];
|
||||
|
||||
let pool = db.pool.clone();
|
||||
|
||||
(
|
||||
std::sync::Arc::new(postgres_es::postgres_cqrs(pool.clone(), queries, services)),
|
||||
std::sync::Arc::new(db.clone()),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
|
|
@ -10,6 +10,8 @@ use uuid::Uuid;
|
|||
|
||||
use super::errors::*;
|
||||
use super::InventoryDBPostgresAdapter;
|
||||
use crate::inventory::adapters::types::{InventoryStoreCqrsExec, InventoryStoreCqrsView};
|
||||
use crate::inventory::application::services::InventoryServicesObj;
|
||||
use crate::inventory::domain::events::InventoryEvent;
|
||||
use crate::inventory::domain::store_aggregate::{Store, StoreBuilder};
|
||||
use crate::utils::parse_aggregate_id::parse_aggregate_id;
|
||||
|
@ -225,6 +227,20 @@ impl Query<Store> for InventoryDBPostgresAdapter {
|
|||
}
|
||||
}
|
||||
|
||||
pub fn init_cqrs(
|
||||
db: InventoryDBPostgresAdapter,
|
||||
services: InventoryServicesObj,
|
||||
) -> (InventoryStoreCqrsExec, InventoryStoreCqrsView) {
|
||||
let queries: Vec<Box<dyn Query<Store>>> = vec![Box::new(db.clone())];
|
||||
|
||||
let pool = db.pool.clone();
|
||||
|
||||
(
|
||||
std::sync::Arc::new(postgres_es::postgres_cqrs(pool.clone(), queries, services)),
|
||||
std::sync::Arc::new(db.clone()),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
|
|
@ -47,7 +47,9 @@ impl AddProductToStoreFTSPort for InventoryFTSMeili {
|
|||
product: &Product,
|
||||
category: &Category,
|
||||
) -> InventoryFTSResult<()> {
|
||||
let store_index = self.client.index(category.store_id().to_string());
|
||||
let store_index = self
|
||||
.client
|
||||
.index(format!("inventory-{}", category.store_id()));
|
||||
let meili_product = MeiliProduct::new(product, category);
|
||||
store_index
|
||||
.add_documents(&[meili_product], Some("product_id"))
|
||||
|
|
|
@ -2,4 +2,4 @@
|
|||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
mod meili;
|
||||
pub mod meili;
|
||||
|
|
|
@ -2,5 +2,5 @@
|
|||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
mod db;
|
||||
mod full_text_search;
|
||||
pub mod db;
|
||||
pub mod full_text_search;
|
||||
|
|
85
src/inventory/adapters/types.rs
Normal file
85
src/inventory/adapters/types.rs
Normal file
|
@ -0,0 +1,85 @@
|
|||
// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
#![allow(dead_code)]
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use actix_web::web::Data;
|
||||
use async_trait::async_trait;
|
||||
use cqrs_es::{persist::ViewRepository, AggregateError};
|
||||
use derive_builder::Builder;
|
||||
use mockall::predicate::*;
|
||||
use mockall::*;
|
||||
use postgres_es::PostgresCqrs;
|
||||
|
||||
use crate::inventory::{
|
||||
adapters::{
|
||||
input::web::RoutesRepository,
|
||||
output::db::postgres::{
|
||||
category_view::CategoryView, customization_view::CustomizationView,
|
||||
product_view::ProductView, store_view::StoreView, InventoryDBPostgresAdapter,
|
||||
},
|
||||
},
|
||||
application::services::{errors::InventoryError, InventoryServicesObj},
|
||||
domain::{
|
||||
category_aggregate::Category, commands::InventoryCommand,
|
||||
customization_aggregate::Customization, product_aggregate::Product, store_aggregate::Store,
|
||||
},
|
||||
};
|
||||
|
||||
pub type WebInventoryRoutesRepository = Data<Arc<RoutesRepository>>;
|
||||
|
||||
pub type WebInventoryCqrsExec = Data<Arc<dyn InventoryCqrsExecutor>>;
|
||||
|
||||
pub type InventoryCustomizationCqrsExec = Arc<PostgresCqrs<Customization>>;
|
||||
pub type InventoryCustomizationCqrsView = Arc<dyn ViewRepository<CustomizationView, Customization>>;
|
||||
pub type WebInventoryCustomizationCqrsView = Data<InventoryCustomizationCqrsView>;
|
||||
|
||||
pub type InventoryCategoryCqrsExec = Arc<PostgresCqrs<Category>>;
|
||||
pub type InventoryCategoryCqrsView = Arc<dyn ViewRepository<CategoryView, Category>>;
|
||||
pub type WebInventoryCategoryCqrsView = Data<InventoryCategoryCqrsView>;
|
||||
|
||||
pub type InventoryStoreCqrsExec = Arc<PostgresCqrs<Store>>;
|
||||
pub type InventoryStoreCqrsView = Arc<dyn ViewRepository<StoreView, Store>>;
|
||||
pub type WebInventoryStoreCqrsView = Data<InventoryStoreCqrsView>;
|
||||
|
||||
pub type InventoryProductCqrsExec = Arc<PostgresCqrs<Product>>;
|
||||
pub type InventoryProductCqrsView = Arc<dyn ViewRepository<ProductView, Product>>;
|
||||
pub type WebInventoryProductCqrsView = Data<InventoryProductCqrsView>;
|
||||
|
||||
#[automock]
|
||||
#[async_trait]
|
||||
pub trait InventoryCqrsExecutor {
|
||||
async fn execute(
|
||||
&self,
|
||||
aggregate_id: &str,
|
||||
command: InventoryCommand,
|
||||
) -> Result<(), AggregateError<InventoryError>>;
|
||||
}
|
||||
|
||||
#[derive(Clone, Builder)]
|
||||
pub struct InventoryCqrsExec {
|
||||
category: InventoryCategoryCqrsExec,
|
||||
customization: InventoryCustomizationCqrsExec,
|
||||
store: InventoryStoreCqrsExec,
|
||||
product: InventoryProductCqrsExec,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl InventoryCqrsExecutor for InventoryCqrsExec {
|
||||
async fn execute(
|
||||
&self,
|
||||
aggregate_id: &str,
|
||||
command: InventoryCommand,
|
||||
) -> Result<(), AggregateError<InventoryError>> {
|
||||
self.category.execute(aggregate_id, command.clone()).await?;
|
||||
self.customization
|
||||
.execute(aggregate_id, command.clone())
|
||||
.await?;
|
||||
self.store.execute(aggregate_id, command.clone()).await?;
|
||||
self.product.execute(aggregate_id, command.clone()).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
|
@ -1,6 +1,7 @@
|
|||
// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
use std::sync::Arc;
|
||||
|
||||
use derive_builder::Builder;
|
||||
use mockall::predicate::*;
|
||||
|
@ -18,58 +19,209 @@ pub mod update_customization_service;
|
|||
pub mod update_product_service;
|
||||
pub mod update_store_service;
|
||||
|
||||
use add_category_service::*;
|
||||
use add_customization_service::*;
|
||||
use add_product_service::*;
|
||||
use add_store_service::*;
|
||||
use update_category_service::*;
|
||||
use update_customization_service::*;
|
||||
use update_product_service::*;
|
||||
use update_store_service::*;
|
||||
|
||||
use super::port::output::{
|
||||
db::{
|
||||
category_id_exists::*, category_name_exists_for_store::*, customization_id_exists::*,
|
||||
customization_name_exists_for_product::*, get_category::*, product_id_exists::*,
|
||||
product_name_exists_for_category::*, store_id_exists::*, store_name_exists::*,
|
||||
},
|
||||
full_text_search::{add_product_to_store::*, update_product::*},
|
||||
};
|
||||
|
||||
#[automock]
|
||||
pub trait InventoryServicesInterface: Send + Sync {
|
||||
fn add_store(&self) -> add_store_service::AddStoreServiceObj;
|
||||
fn add_category(&self) -> add_category_service::AddCategoryServiceObj;
|
||||
fn add_product(&self) -> add_product_service::AddProductServiceObj;
|
||||
fn add_customization(&self) -> add_customization_service::AddCustomizationServiceObj;
|
||||
fn update_product(&self) -> update_product_service::UpdateProductServiceObj;
|
||||
fn update_customization(&self) -> update_customization_service::UpdateCustomizationServiceObj;
|
||||
fn update_category(&self) -> update_category_service::UpdateCategoryServiceObj;
|
||||
fn update_store(&self) -> update_store_service::UpdateStoreServiceObj;
|
||||
fn add_store(&self) -> AddStoreServiceObj;
|
||||
fn add_category(&self) -> AddCategoryServiceObj;
|
||||
fn add_product(&self) -> AddProductServiceObj;
|
||||
fn add_customization(&self) -> AddCustomizationServiceObj;
|
||||
fn update_product(&self) -> UpdateProductServiceObj;
|
||||
fn update_customization(&self) -> UpdateCustomizationServiceObj;
|
||||
fn update_category(&self) -> UpdateCategoryServiceObj;
|
||||
fn update_store(&self) -> UpdateStoreServiceObj;
|
||||
}
|
||||
|
||||
pub type InventoryServicesObj = Arc<dyn InventoryServicesInterface>;
|
||||
|
||||
#[derive(Clone, Builder)]
|
||||
pub struct InventoryServices {
|
||||
add_store: add_store_service::AddStoreServiceObj,
|
||||
add_category: add_category_service::AddCategoryServiceObj,
|
||||
add_product: add_product_service::AddProductServiceObj,
|
||||
add_customization: add_customization_service::AddCustomizationServiceObj,
|
||||
update_product: update_product_service::UpdateProductServiceObj,
|
||||
update_customization: update_customization_service::UpdateCustomizationServiceObj,
|
||||
update_category: update_category_service::UpdateCategoryServiceObj,
|
||||
update_store: update_store_service::UpdateStoreServiceObj,
|
||||
add_store: AddStoreServiceObj,
|
||||
add_category: AddCategoryServiceObj,
|
||||
add_product: AddProductServiceObj,
|
||||
add_customization: AddCustomizationServiceObj,
|
||||
update_product: UpdateProductServiceObj,
|
||||
update_customization: UpdateCustomizationServiceObj,
|
||||
update_category: UpdateCategoryServiceObj,
|
||||
update_store: UpdateStoreServiceObj,
|
||||
}
|
||||
|
||||
impl InventoryServicesInterface for InventoryServices {
|
||||
fn add_store(&self) -> add_store_service::AddStoreServiceObj {
|
||||
fn add_store(&self) -> AddStoreServiceObj {
|
||||
self.add_store.clone()
|
||||
}
|
||||
fn add_category(&self) -> add_category_service::AddCategoryServiceObj {
|
||||
fn add_category(&self) -> AddCategoryServiceObj {
|
||||
self.add_category.clone()
|
||||
}
|
||||
fn add_product(&self) -> add_product_service::AddProductServiceObj {
|
||||
fn add_product(&self) -> AddProductServiceObj {
|
||||
self.add_product.clone()
|
||||
}
|
||||
|
||||
fn add_customization(&self) -> add_customization_service::AddCustomizationServiceObj {
|
||||
fn add_customization(&self) -> AddCustomizationServiceObj {
|
||||
self.add_customization.clone()
|
||||
}
|
||||
|
||||
fn update_product(&self) -> update_product_service::UpdateProductServiceObj {
|
||||
fn update_product(&self) -> UpdateProductServiceObj {
|
||||
self.update_product.clone()
|
||||
}
|
||||
|
||||
fn update_customization(&self) -> update_customization_service::UpdateCustomizationServiceObj {
|
||||
fn update_customization(&self) -> UpdateCustomizationServiceObj {
|
||||
self.update_customization.clone()
|
||||
}
|
||||
|
||||
fn update_category(&self) -> update_category_service::UpdateCategoryServiceObj {
|
||||
fn update_category(&self) -> UpdateCategoryServiceObj {
|
||||
self.update_category.clone()
|
||||
}
|
||||
|
||||
fn update_store(&self) -> update_store_service::UpdateStoreServiceObj {
|
||||
fn update_store(&self) -> UpdateStoreServiceObj {
|
||||
self.update_store.clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl InventoryServices {
|
||||
pub fn new(
|
||||
out_db_category_id_exists: CategoryIDExistsDBPortObj,
|
||||
out_db_category_name_exists_for_store: CategoryNameExistsForStoreDBPortObj,
|
||||
out_db_customization_id_exists: CustomizationIDExistsDBPortObj,
|
||||
out_db_customization_name_exists_for_product: CustomizationNameExistsForProductDBPortObj,
|
||||
out_db_get_category: GetCategoryDBPortObj,
|
||||
out_db_product_id_exists: ProductIDExistsDBPortObj,
|
||||
out_db_product_name_exists_for_category: ProductNameExistsForCategoryDBPortObj,
|
||||
out_db_store_id_exists: StoreIDExistsDBPortObj,
|
||||
out_db_store_name_exists: StoreNameExistsDBPortObj,
|
||||
|
||||
out_fts_add_product_to_store: AddProductToStoreFTSPortObj,
|
||||
// out_fts_update_product: updateproduct
|
||||
) -> InventoryServicesObj {
|
||||
let add_store = Arc::new(
|
||||
AddStoreServiceBuilder::default()
|
||||
.db_store_id_exists(out_db_store_id_exists.clone())
|
||||
.db_store_name_exists(out_db_store_name_exists.clone())
|
||||
.build()
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
let add_category = Arc::new(
|
||||
AddCategoryServiceBuilder::default()
|
||||
.db_store_id_exists(out_db_store_id_exists.clone())
|
||||
.db_category_name_exists_for_store(out_db_category_name_exists_for_store.clone())
|
||||
.db_category_id_exists(out_db_category_id_exists.clone())
|
||||
.build()
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
let add_product = Arc::new(
|
||||
AddProductServiceBuilder::default()
|
||||
.db_category_id_exists(out_db_category_id_exists.clone())
|
||||
.db_product_name_exists_for_category(
|
||||
out_db_product_name_exists_for_category.clone(),
|
||||
)
|
||||
.db_product_id_exists(out_db_product_id_exists.clone())
|
||||
.db_get_category(out_db_get_category.clone())
|
||||
.fts_add_product(out_fts_add_product_to_store.clone())
|
||||
.build()
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
let add_customization = Arc::new(
|
||||
AddCustomizationServiceBuilder::default()
|
||||
.db_product_id_exists(out_db_product_id_exists.clone())
|
||||
.db_customization_id_exists(out_db_customization_id_exists.clone())
|
||||
.db_customization_name_exists_for_product(
|
||||
out_db_customization_name_exists_for_product.clone(),
|
||||
)
|
||||
.build()
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
let update_product = Arc::new(
|
||||
UpdateProductServiceBuilder::default()
|
||||
.db_category_id_exists(out_db_category_id_exists.clone())
|
||||
.db_product_name_exists_for_category(
|
||||
out_db_product_name_exists_for_category.clone(),
|
||||
)
|
||||
.db_product_id_exists(out_db_product_id_exists.clone())
|
||||
.build()
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
let update_customization = Arc::new(
|
||||
UpdateCustomizationServiceBuilder::default()
|
||||
.db_product_id_exists(out_db_product_id_exists.clone())
|
||||
.db_customization_id_exists(out_db_customization_id_exists.clone())
|
||||
.db_customization_name_exists_for_product(
|
||||
out_db_customization_name_exists_for_product.clone(),
|
||||
)
|
||||
.build()
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
let update_category = Arc::new(
|
||||
UpdateCategoryServiceBuilder::default()
|
||||
.db_store_id_exists(out_db_store_id_exists.clone())
|
||||
.db_category_name_exists_for_store(out_db_category_name_exists_for_store.clone())
|
||||
.db_category_id_exists(out_db_category_id_exists.clone())
|
||||
.build()
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
let update_store = Arc::new(
|
||||
UpdateStoreServiceBuilder::default()
|
||||
.db_store_id_exists(out_db_store_id_exists.clone())
|
||||
.db_store_name_exists(out_db_store_name_exists.clone())
|
||||
.build()
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
Arc::new(Self {
|
||||
add_store,
|
||||
add_category,
|
||||
add_product,
|
||||
add_customization,
|
||||
update_product,
|
||||
update_customization,
|
||||
update_category,
|
||||
update_store,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::tests::bdd::IS_NEVER_CALLED;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn inventory_services_work() {
|
||||
let s = InventoryServices::new(
|
||||
mock_category_id_exists_db_port_true(IS_NEVER_CALLED),
|
||||
mock_category_name_exists_for_store_db_port_true(IS_NEVER_CALLED),
|
||||
mock_customization_id_exists_db_port_true(IS_NEVER_CALLED),
|
||||
mock_customization_name_exists_for_product_db_port_true(IS_NEVER_CALLED),
|
||||
mock_get_category_db_port(IS_NEVER_CALLED),
|
||||
mock_product_id_exists_db_port_true(IS_NEVER_CALLED),
|
||||
mock_product_name_exists_for_category_db_port_true(IS_NEVER_CALLED),
|
||||
mock_store_id_exists_db_port_true(IS_NEVER_CALLED),
|
||||
mock_store_name_exists_db_port_true(IS_NEVER_CALLED),
|
||||
mock_add_product_to_store_fts_port(IS_NEVER_CALLED),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -2,6 +2,6 @@
|
|||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
mod adapters;
|
||||
pub mod adapters;
|
||||
mod application;
|
||||
mod domain;
|
||||
|
|
|
@ -16,6 +16,7 @@ mod inventory;
|
|||
mod ordering;
|
||||
mod settings;
|
||||
#[cfg(test)]
|
||||
#[macro_use]
|
||||
mod tests;
|
||||
mod types;
|
||||
mod utils;
|
||||
|
@ -33,6 +34,7 @@ async fn main() {
|
|||
}
|
||||
|
||||
pretty_env_logger::init();
|
||||
web_ui::init();
|
||||
|
||||
let db = db::sqlx_postgres::Postgres::init(&settings.database.url).await;
|
||||
db.migrate().await;
|
||||
|
@ -58,9 +60,10 @@ async fn main() {
|
|||
.wrap(
|
||||
middleware::DefaultHeaders::new().add(("Permissions-Policy", "interest-cohort=()")),
|
||||
)
|
||||
// .configure(auth::adapter::load_adapters(db.pool.clone(), &settings))
|
||||
.configure(utils::random_string::GenerateRandomString::inject())
|
||||
.configure(utils::uuid::GenerateUUID::inject())
|
||||
.configure(utils::load_adapters::load_adapters(
|
||||
db.pool.clone(),
|
||||
settings.clone(),
|
||||
))
|
||||
})
|
||||
.bind(&socket_addr)
|
||||
.unwrap()
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
pub mod web;
|
||||
|
|
115
src/ordering/adapters/input/web/category.rs
Normal file
115
src/ordering/adapters/input/web/category.rs
Normal file
|
@ -0,0 +1,115 @@
|
|||
// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
use actix_identity::Identity;
|
||||
use actix_web::{get, http::header::ContentType, post, web, HttpRequest, HttpResponse, Responder};
|
||||
use derive_builder::Builder;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use url::Url;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::errors::*;
|
||||
use super::types;
|
||||
//use crate::utils::uuid::WebGetUUIDInterfaceObj;
|
||||
|
||||
pub fn services(cfg: &mut web::ServiceConfig) {
|
||||
cfg.service(add_category_ui_handler);
|
||||
cfg.service(add_category_form_submission_handler);
|
||||
|
||||
cfg.service(update_category_ui_handler);
|
||||
cfg.service(update_category_form_submission_handler);
|
||||
}
|
||||
|
||||
// add_category handlers
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[get("/ordering/menu/category/add")]
|
||||
#[tracing::instrument(name = "add_category UI handler", skip())]
|
||||
async fn add_category_ui_handler() -> WebJsonRepsonse<impl Responder> {
|
||||
use web_ui::ordering::add_category::*;
|
||||
|
||||
let page = AddCategoryPage::page();
|
||||
|
||||
Ok(HttpResponse::Ok()
|
||||
.insert_header(ContentType::html())
|
||||
.body(page))
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
|
||||
struct AddCategoryPayload {
|
||||
password: String,
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[post("/ordering/menu/category/add")]
|
||||
#[tracing::instrument(
|
||||
name = "add_category form submission handler"
|
||||
skip(id, req, payload, ordering_cqrs_exec)
|
||||
)]
|
||||
async fn add_category_form_submission_handler(
|
||||
ordering_cqrs_exec: types::WebOrderingCqrsExec,
|
||||
req: HttpRequest,
|
||||
id: Identity,
|
||||
payload: web::Form<AddCategoryPayload>,
|
||||
) -> WebJsonRepsonse<impl Responder> {
|
||||
let store = "";
|
||||
|
||||
Ok(HttpResponse::Ok().json(store))
|
||||
}
|
||||
|
||||
// update_category handlers
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[get("/ordering/menu/{category_uuid}/update")]
|
||||
#[tracing::instrument(name = "update_category UI handler", skip())]
|
||||
async fn update_category_ui_handler() -> WebJsonRepsonse<impl Responder> {
|
||||
use web_ui::ordering::update_category::*;
|
||||
|
||||
let page = UpdateCategoryPage::page();
|
||||
|
||||
Ok(HttpResponse::Ok()
|
||||
.insert_header(ContentType::html())
|
||||
.body(page))
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
|
||||
struct UpdateCategoryPayload {
|
||||
password: String,
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[post("/ordering/menu/{category_uuid}/update")]
|
||||
#[tracing::instrument(
|
||||
name = "update_category form submission handler"
|
||||
skip(id, req, payload, ordering_cqrs_exec)
|
||||
)]
|
||||
async fn update_category_form_submission_handler(
|
||||
ordering_cqrs_exec: types::WebOrderingCqrsExec,
|
||||
req: HttpRequest,
|
||||
id: Identity,
|
||||
payload: web::Form<UpdateCategoryPayload>,
|
||||
) -> WebJsonRepsonse<impl Responder> {
|
||||
let store = "";
|
||||
|
||||
Ok(HttpResponse::Ok().json(store))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::utils::uuid::tests::UUID;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn ordering_web_add_category_ui_works() {
|
||||
let routes = crate::ordering::adapters::input::web::RoutesRepository::default();
|
||||
crate::tests::actix_web_test_utils::page_test_runner(&routes.add_category).await;
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn ordering_web_update_category_ui_works() {
|
||||
let routes = crate::ordering::adapters::input::web::RoutesRepository::default();
|
||||
crate::tests::actix_web_test_utils::page_test_runner(&routes.update_category(UUID)).await;
|
||||
}
|
||||
}
|
118
src/ordering/adapters/input/web/customization.rs
Normal file
118
src/ordering/adapters/input/web/customization.rs
Normal file
|
@ -0,0 +1,118 @@
|
|||
// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
use actix_identity::Identity;
|
||||
use actix_web::{get, http::header::ContentType, post, web, HttpRequest, HttpResponse, Responder};
|
||||
use derive_builder::Builder;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use url::Url;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::errors::*;
|
||||
use super::types;
|
||||
//use crate::utils::uuid::WebGetUUIDInterfaceObj;
|
||||
|
||||
pub fn services(cfg: &mut web::ServiceConfig) {
|
||||
cfg.service(add_customization_ui_handler);
|
||||
cfg.service(add_customization_form_submission_handler);
|
||||
|
||||
cfg.service(update_customization_ui_handler);
|
||||
cfg.service(update_customization_form_submission_handler);
|
||||
}
|
||||
|
||||
// add_customization handlers
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[get("/ordering/menu/{category_uuid}/{product_uuid}/customization/add")]
|
||||
#[tracing::instrument(name = "add_customization UI handler", skip())]
|
||||
async fn add_customization_ui_handler() -> WebJsonRepsonse<impl Responder> {
|
||||
use web_ui::ordering::add_customization::*;
|
||||
|
||||
let page = AddCustomizationPage::page();
|
||||
|
||||
Ok(HttpResponse::Ok()
|
||||
.insert_header(ContentType::html())
|
||||
.body(page))
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
|
||||
struct AddCustomizationPayload {
|
||||
password: String,
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[post("/ordering/menu/{category_uuid}/{product_uuid}/customization/add")]
|
||||
#[tracing::instrument(
|
||||
name = "add_customization form submission handler"
|
||||
skip(id, req, payload, ordering_cqrs_exec)
|
||||
)]
|
||||
async fn add_customization_form_submission_handler(
|
||||
ordering_cqrs_exec: types::WebOrderingCqrsExec,
|
||||
req: HttpRequest,
|
||||
id: Identity,
|
||||
payload: web::Form<AddCustomizationPayload>,
|
||||
) -> WebJsonRepsonse<impl Responder> {
|
||||
let store = "";
|
||||
|
||||
Ok(HttpResponse::Ok().json(store))
|
||||
}
|
||||
|
||||
// update_customization handlers
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[get("/ordering/menu/{category_uuid}/{product_uuid}/{customization_uuid}/update")]
|
||||
#[tracing::instrument(name = "update_customization UI handler", skip())]
|
||||
async fn update_customization_ui_handler() -> WebJsonRepsonse<impl Responder> {
|
||||
use web_ui::ordering::update_customization::*;
|
||||
|
||||
let page = UpdateCustomizationPage::page();
|
||||
|
||||
Ok(HttpResponse::Ok()
|
||||
.insert_header(ContentType::html())
|
||||
.body(page))
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
|
||||
struct UpdateCustomizationPayload {
|
||||
password: String,
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[post("/ordering/menu/{category_uuid}/{product_uuid}/{customization_uuid}/update")]
|
||||
#[tracing::instrument(
|
||||
name = "update_customization form submission handler"
|
||||
skip(id, req, payload, ordering_cqrs_exec)
|
||||
)]
|
||||
async fn update_customization_form_submission_handler(
|
||||
ordering_cqrs_exec: types::WebOrderingCqrsExec,
|
||||
req: HttpRequest,
|
||||
id: Identity,
|
||||
payload: web::Form<UpdateCustomizationPayload>,
|
||||
) -> WebJsonRepsonse<impl Responder> {
|
||||
let store = "";
|
||||
|
||||
Ok(HttpResponse::Ok().json(store))
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::utils::uuid::tests::UUID;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn ordering_web_add_customization_ui_works() {
|
||||
let routes = crate::ordering::adapters::input::web::RoutesRepository::default();
|
||||
crate::tests::actix_web_test_utils::page_test_runner(&routes.add_customization(UUID, UUID))
|
||||
.await;
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn ordering_web_update_customization_ui_works() {
|
||||
let routes = crate::ordering::adapters::input::web::RoutesRepository::default();
|
||||
crate::tests::actix_web_test_utils::page_test_runner(
|
||||
&routes.update_customization(UUID, UUID, UUID),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue