├── .gitignore ├── LICENSE ├── README.md ├── README.zh-cn.md ├── api ├── build.gradle └── src │ ├── main │ └── java │ │ └── reengineering │ │ └── ddd │ │ └── accounting │ │ └── api │ │ ├── AccountsApi.java │ │ ├── ApiTemplates.java │ │ ├── CustomerApi.java │ │ ├── CustomersApi.java │ │ ├── Pagination.java │ │ ├── SourceEvidencesApi.java │ │ └── representation │ │ ├── CustomerModel.java │ │ ├── SalesSettlementRequest.java │ │ ├── SourceEvidenceJsonReader.java │ │ ├── SourceEvidenceModel.java │ │ ├── SourceEvidenceReader.java │ │ ├── SourceEvidenceRequest.java │ │ └── TransactionModel.java │ └── test │ ├── java │ └── reengineering │ │ └── ddd │ │ └── accounting │ │ └── api │ │ ├── ApiTest.java │ │ ├── CustomerAccountTransactionsApiTest.java │ │ ├── CustomerSourceEvidencesApiTest.java │ │ ├── CustomersApiTest.java │ │ ├── EntityList.java │ │ ├── config │ │ ├── HAL.java │ │ ├── Jersey.java │ │ └── TestApplication.java │ │ └── representation │ │ └── SourceEvidenceReaderTest.java │ └── resources │ └── application.yml ├── build.gradle ├── buildSrc ├── build.gradle └── src │ └── main │ └── groovy │ └── reengineering.ddd.gradle ├── domain ├── build.gradle └── src │ ├── main │ └── java │ │ └── reengineering │ │ └── ddd │ │ ├── accounting │ │ ├── description │ │ │ ├── AccountDescription.java │ │ │ ├── CustomerDescription.java │ │ │ ├── SalesSettlementDescription.java │ │ │ ├── SourceEvidenceDescription.java │ │ │ ├── TransactionDescription.java │ │ │ └── basic │ │ │ │ ├── Amount.java │ │ │ │ ├── Currency.java │ │ │ │ └── Ref.java │ │ └── model │ │ │ ├── Account.java │ │ │ ├── AccountNotFoundException.java │ │ │ ├── Customer.java │ │ │ ├── Customers.java │ │ │ ├── SalesSettlement.java │ │ │ ├── SourceEvidence.java │ │ │ └── Transaction.java │ │ └── archtype │ │ ├── Entity.java │ │ ├── HasMany.java │ │ ├── HasOne.java │ │ └── Many.java │ └── test │ └── java │ └── reengineering │ └── ddd │ └── accounting │ ├── description │ └── basic │ │ └── AmountTest.java │ └── model │ ├── CustomerTest.java │ └── SalesSettlementTest.java ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── main ├── build.gradle └── src │ └── main │ ├── java │ └── reengineering │ │ └── ddd │ │ └── accounting │ │ ├── Application.java │ │ ├── config │ │ ├── HAL.java │ │ ├── Jersey.java │ │ └── MyBatis.java │ │ └── test │ │ ├── TestDataMapper.java │ │ └── TestDataRunner.java │ └── resources │ └── application.yml ├── persistent └── mybatis │ ├── build.gradle │ └── src │ ├── main │ ├── java │ │ └── reengineering │ │ │ └── ddd │ │ │ ├── accounting │ │ │ └── mybatis │ │ │ │ ├── ModelMapper.java │ │ │ │ └── associations │ │ │ │ ├── AccountTransactions.java │ │ │ │ ├── CustomerAccounts.java │ │ │ │ ├── CustomerSourceEvidences.java │ │ │ │ ├── Customers.java │ │ │ │ └── SourceEvidenceTransactions.java │ │ │ └── mybatis │ │ │ ├── database │ │ │ └── EntityList.java │ │ │ ├── memory │ │ │ ├── EntityList.java │ │ │ └── Reference.java │ │ │ └── support │ │ │ ├── IdHolder.java │ │ │ ├── InjectableObjectFactory.java │ │ │ └── ObjectFactoryConverter.java │ └── resources │ │ ├── db │ │ └── migration │ │ │ ├── V01__create_customers.sql │ │ │ ├── V02__create_source_evidences.sql │ │ │ ├── V03__create_sales_settlements.sql │ │ │ ├── V04__create_accounts.sql │ │ │ └── V05__create_transactions.sql │ │ └── mybatis │ │ └── mapper │ │ ├── Description.xml │ │ ├── Model.xml │ │ └── ModelMapper.xml │ └── test │ ├── java │ └── reengineering │ │ └── ddd │ │ └── accounting │ │ ├── AssociationsTest.java │ │ ├── FlywayConfig.java │ │ ├── ModelMapperTest.java │ │ ├── TestApplication.java │ │ ├── TestDataMapper.java │ │ └── TestDataSetup.java │ └── resources │ └── application.yml ├── public ├── Smart Domain Pattern.pdf ├── api.jpg ├── association.jpg ├── lifecycle.jpg └── model.jpg └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/**/build/ 6 | !**/src/test/**/build/ 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | .sts4-cache 16 | bin/ 17 | !**/src/main/**/bin/ 18 | !**/src/test/**/bin/ 19 | 20 | ### IntelliJ IDEA ### 21 | .idea 22 | *.iws 23 | *.iml 24 | *.ipr 25 | out/ 26 | !**/src/main/**/out/ 27 | !**/src/test/**/out/ 28 | 29 | ### NetBeans ### 30 | /nbproject/private/ 31 | /nbbuild/ 32 | /dist/ 33 | /nbdist/ 34 | /.nb-gradle/ 35 | 36 | ### VS Code ### 37 | .vscode/ 38 | 39 | .DS_Store 40 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Re-engineering Domain Driven Design 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [中文版](README.zh-cn.md) 2 | 3 | # Business Background 4 | 5 | This is a simple accounting system, which keeps transactions to different accounts based on business documents. 6 | For example, sales settlement is such a business document. Based on what's in the details, it may require to keep 7 | transactions in cash account, credit account and in transit account. 8 | 9 | The model shown as below: 10 | 11 | ![Model](public/model.jpg?raw=true "Model") 12 | 13 | # Smart Domain Architecture Pattern 14 | 15 | A brief introduction to Smart Domain Architecture can be found [here](public/Smart%20Domain%20Pattern.pdf?raw=true) 16 | 17 | To apply the Smart Domain architecture pattern as the implementation pattern of domain 18 | driven design, first, you should explicitly model the associations 19 | between entities. Remember, you have to provide a root association. Customers in this example: 20 | 21 | ![Association](public/association.jpg?raw=true "Associations") 22 | 23 | All association objects are just plain interfaces. For my personal taste, I used inner interfaces. You can find detailed 24 | codes in module domain: 25 | 26 | ```java 27 | public class Customer implements Entity { 28 | private SourceEvidences sourceEvidences; 29 | 30 | private Accounts accounts; 31 | 32 | public HasMany> sourceEvidences() { 33 | return sourceEvidences; 34 | } 35 | 36 | public HasMany accounts() { 37 | return accounts; 38 | } 39 | 40 | public interface SourceEvidences extends HasMany> { 41 | SourceEvidence add(SourceEvidenceDescription description); 42 | } 43 | 44 | public interface Accounts extends HasMany { 45 | void update(Account account, Account.AccountChange change); 46 | } 47 | } 48 | 49 | public class Account implements Entity { 50 | private Transactions transactions; 51 | 52 | public HasMany transactions() { 53 | return transactions; 54 | } 55 | 56 | public interface Transactions extends HasMany { 57 | Transaction add(Account account, SourceEvidence evidence, TransactionDescription description); 58 | } 59 | } 60 | 61 | public interface SourceEvidence extends Entity { 62 | HasMany transactions(); 63 | 64 | interface Transactions extends HasMany { 65 | } 66 | } 67 | ``` 68 | 69 | Notice, I used a wider interface inside the entity, but a narrower interface for outside reader model. Thus, would allow 70 | me to encapsulate association manipulation logic within entity. 71 | 72 | ## Expose API over model 73 | 74 | After build the object model, now it is time to expose the model via REST API. It is really easy to design the API on top 75 | of the model: 76 | 77 | ![API](public/api.jpg?raw=true "API") 78 | 79 | Implement the root association(Customers) as JAX-RS root resource: 80 | 81 | ```java 82 | @Path("/customers") 83 | public class CustomersApi { 84 | private Customers customers; 85 | 86 | @Inject 87 | public CustomersApi(Customers customers) { 88 | this.customers = customers; 89 | } 90 | 91 | @Path("{id}") 92 | public CustomerApi findById(@PathParam("id") String id) { 93 | return customers.findById(id).map(CustomerApi::new).orElse(null); 94 | } 95 | } 96 | ``` 97 | 98 | Entity can be implemented as sub-resource: 99 | 100 | ```java 101 | public class CustomerApi { 102 | private Customer customer; 103 | 104 | public CustomerApi(Customer customer) { 105 | this.customer = customer; 106 | } 107 | 108 | @GET 109 | public CustomerModel get(@Context UriInfo info) { 110 | return new CustomerModel(customer, info); 111 | } 112 | 113 | @Path("source-evidences") 114 | public SourceEvidencesApi sourceEvidences(@Context ResourceContext context) { 115 | return context.initResource(new SourceEvidencesApi(customer)); 116 | } 117 | 118 | @Path("accounts") 119 | public AccountsApi accounts() { 120 | return new AccountsApi(customer); 121 | } 122 | } 123 | ``` 124 | 125 | As well as association objects. As shown in the code below, it is a sub-resource for Customer.SourceEvidences interface: 126 | 127 | ```java 128 | public class SourceEvidencesApi { 129 | private Customer customer; 130 | 131 | @Inject 132 | private SourceEvidenceReader reader; 133 | 134 | public SourceEvidencesApi(Customer customer) { 135 | this.customer = customer; 136 | } 137 | 138 | @GET 139 | @Path("{evidence-id}") 140 | public SourceEvidenceModel findById(@PathParam("evidence-id") String id, 141 | @Context UriInfo info) { 142 | return customer.sourceEvidences().findByIdentity(id).map(evidence -> SourceEvidenceModel.of(customer, evidence, info)) 143 | .orElseThrow(() -> new WebApplicationException(Response.Status.NOT_FOUND)); 144 | } 145 | 146 | @GET 147 | public CollectionModel findAll(@Context UriInfo info, @DefaultValue("0") @QueryParam("page") int page) { 148 | return new Pagination<>(customer.sourceEvidences().findAll(), 40).page(page, 149 | evidence -> SourceEvidenceModel.simple(customer, evidence, info), 150 | p -> sourceEvidences(info).queryParam("page", p).build(customer.getIdentity())); 151 | } 152 | 153 | @POST 154 | public Response create(String json, @Context UriInfo info) { 155 | SourceEvidence evidence = customer.add(reader.read(json) 156 | .orElseThrow(() -> new WebApplicationException(Response.Status.NOT_ACCEPTABLE)).description()); 157 | return Response.created(ApiTemplates.sourceEvidence(info).build(customer.getIdentity(), evidence.getIdentity())).build(); 158 | } 159 | } 160 | ``` 161 | You can check out the api module for more information. Particularly, in api test, I didn't use any database. All the logic 162 | were tested over the abstraction of association objects. 163 | 164 | ### Implementing Association Objects 165 | 166 | Last but not least, implementing association objects with proper lifecycle semantic. Take the association between source evidence 167 | and transaction for example, it could be an in memory association, which means that every time source evidence read into 168 | memory, the associated transactions will be read as well. Or you can call it **aggregated** lifecycle. 169 | 170 | Meanwhile, the association between account and transactions may better be from database, since account may record tons of transactions. 171 | Or you can call it **reference** lifecycle: 172 | 173 | ![生命周期](public/lifecycle.jpg?raw=true "生命周期") 174 | 175 | This may be counterintuitive. Many DDD practitioners may say account-transaction should be an aggregation, and source evidence-transaction 176 | may be a reference. We represent the conceptual aggregation relationship by URI: the primary URI(self link) of account is 177 | /customers/{cid}/accounts/{aid}/transactions/{tid}, not /customers/{cid}/source-evidences/{sid}/transactions/{tid}. 178 | 179 | **Confusing aggregation relationship with lifecycle is a persistent problem with domain-driven design**. 180 | 181 | Aggregated lifecycle implemented by package reengineering.ddd.mybatis.memory: 182 | 183 | ```java 184 | import reengineering.ddd.mybatis.memory.EntityList; 185 | 186 | public class SourceEvidenceTransactions extends EntityList implements SourceEvidence.Transactions { 187 | } 188 | ``` 189 | 190 | Reference lifecycle implemented by package reengineering.ddd.mybatis.database: 191 | 192 | ```java 193 | import reengineering.ddd.mybatis.database.EntityList; 194 | 195 | public class AccountTransactions extends EntityList implements Account.Transactions { 196 | 197 | } 198 | ``` 199 | 200 | In this example, association object were implemented by MyBatis. You can find the code in module persistent/mybatis. 201 | -------------------------------------------------------------------------------- /README.zh-cn.md: -------------------------------------------------------------------------------- 1 | # 业务背景 2 | 3 | 这是一个简单的记账系统。系统会根据业务单据,按照不同的账目记录流水。比如,对于销售结算单,可能需要根据明细, 4 | 分别向现金账户、信用账户、在途账户等账户中,记录流水。 5 | 6 | 业务模型如下: 7 | ![模型](public/model.jpg?raw=true "模型") 8 | 9 | # Smart Domain架构模式 10 | 11 | 关于Smart Domain架构模式[这里](public/Smart%20Domain%20Pattern.pdf?raw=true)有个简单的介绍。 12 | 13 | ## 通过关联对象构建模型 14 | 15 | 应用Smart Domain架构模式,作为领域驱动设计的实现模式。首先将模型图中的关联关系建模为关联对象。 16 | 注意,需要额外引入一个根关联对象。在这个模型中是Customers: 17 | 18 | ![关联](public/association.jpg?raw=true "关联") 19 | 20 | 关联对象用接口表示。出于我个人的口味,我使用了内部接口。具体的代码在domain模块中: 21 | 22 | ```java 23 | public class Customer implements Entity { 24 | private SourceEvidences sourceEvidences; 25 | 26 | private Accounts accounts; 27 | 28 | public HasMany> sourceEvidences() { 29 | return sourceEvidences; 30 | } 31 | 32 | public HasMany accounts() { 33 | return accounts; 34 | } 35 | 36 | public interface SourceEvidences extends HasMany> { 37 | SourceEvidence add(SourceEvidenceDescription description); 38 | } 39 | 40 | public interface Accounts extends HasMany { 41 | void update(Account account, Account.AccountChange change); 42 | } 43 | } 44 | 45 | public class Account implements Entity { 46 | private Transactions transactions; 47 | 48 | public HasMany transactions() { 49 | return transactions; 50 | } 51 | 52 | public interface Transactions extends HasMany { 53 | Transaction add(Account account, SourceEvidence evidence, TransactionDescription description); 54 | } 55 | } 56 | 57 | public interface SourceEvidence extends Entity { 58 | HasMany transactions(); 59 | 60 | interface Transactions extends HasMany { 61 | } 62 | } 63 | ``` 64 | 65 | 注意,我是用了宽接口(可修改)而对外仅仅暴露窄接口(只读)。这样可以让我将修改逻辑封装到实体对象之内。 66 | 67 | ## 将模型映射为API 68 | 69 | 在构建了模型之后,可以将模型映射为API,通过关联关系,表示URI: 70 | 71 | ![API](public/api.jpg?raw=true "API") 72 | 73 | 然后使用JAX-RS将根关联对象转成root resource: 74 | 75 | ```java 76 | @Path("/customers") 77 | public class CustomersApi { 78 | private Customers customers; 79 | 80 | @Inject 81 | public CustomersApi(Customers customers) { 82 | this.customers = customers; 83 | } 84 | 85 | @Path("{id}") 86 | public CustomerApi findById(@PathParam("id") String id) { 87 | return customers.findById(id).map(CustomerApi::new).orElse(null); 88 | } 89 | } 90 | ``` 91 | 92 | 实体转成sub-resources: 93 | ```java 94 | public class CustomerApi { 95 | private Customer customer; 96 | 97 | public CustomerApi(Customer customer) { 98 | this.customer = customer; 99 | } 100 | 101 | @GET 102 | public CustomerModel get(@Context UriInfo info) { 103 | return new CustomerModel(customer, info); 104 | } 105 | 106 | @Path("source-evidences") 107 | public SourceEvidencesApi sourceEvidences(@Context ResourceContext context) { 108 | return context.initResource(new SourceEvidencesApi(customer)); 109 | } 110 | 111 | @Path("accounts") 112 | public AccountsApi accounts() { 113 | return new AccountsApi(customer); 114 | } 115 | } 116 | ``` 117 | 118 | 关联对象可以转成sub-resource,如下代码所示,实际是对于Customer.SourceEvidences的API化: 119 | ```java 120 | public class SourceEvidencesApi { 121 | private Customer customer; 122 | 123 | @Inject 124 | private SourceEvidenceReader reader; 125 | 126 | public SourceEvidencesApi(Customer customer) { 127 | this.customer = customer; 128 | } 129 | 130 | @GET 131 | @Path("{evidence-id}") 132 | public SourceEvidenceModel findById(@PathParam("evidence-id") String id, 133 | @Context UriInfo info) { 134 | return customer.sourceEvidences().findByIdentity(id).map(evidence -> SourceEvidenceModel.of(customer, evidence, info)) 135 | .orElseThrow(() -> new WebApplicationException(Response.Status.NOT_FOUND)); 136 | } 137 | 138 | @GET 139 | public CollectionModel findAll(@Context UriInfo info, @DefaultValue("0") @QueryParam("page") int page) { 140 | return new Pagination<>(customer.sourceEvidences().findAll(), 40).page(page, 141 | evidence -> SourceEvidenceModel.simple(customer, evidence, info), 142 | p -> sourceEvidences(info).queryParam("page", p).build(customer.getIdentity())); 143 | } 144 | 145 | @POST 146 | public Response create(String json, @Context UriInfo info) { 147 | SourceEvidence evidence = customer.add(reader.read(json) 148 | .orElseThrow(() -> new WebApplicationException(Response.Status.NOT_ACCEPTABLE)).description()); 149 | return Response.created(ApiTemplates.sourceEvidence(info).build(customer.getIdentity(), evidence.getIdentity())).build(); 150 | } 151 | } 152 | ``` 153 | API的具体代码都在api模块中。可以看到,在测试中,并没有使用数据库,而是依赖关联对象的抽象,完成api的测试。 154 | 155 | ### 实现关联对象 156 | 157 | 最后,根据需要提供关联对象的实现,并提供恰当的生命周期语义:Source Evidence和Transaction之间是内存直接关联。也就是说,每次读取Source Evidence时, 158 | 同时也会将关联的Transaction对象读入,也就是遵守聚合生命周期。而Account可能因为存在大量的Transaction,并不需要一起读入。也就是说,遵守引用 159 | 生命周期: 160 | 161 | ![生命周期](public/lifecycle.jpg?raw=true "生命周期") 162 | 163 | Transaction的不同生命周期,可能极度违反直觉。因为从业务概念上讲,Account应该聚合Transaction才对。这种业务上的聚合关系,我们通过URI来表示。 164 | 也就是对于Transaction而言,它的URI是/customers/{cid}/accounts/{aid}/transactions/{tid}。 而不是/customers/{cid}/source-evidences/{sid}/transactions/{tid}。 165 | **将业务聚合与生命周期混为一谈,是领域驱动设计的顽疾。** 166 | 167 | 聚合的生命周期由reengineering.ddd.mybatis.memory包提供: 168 | 169 | ```java 170 | import reengineering.ddd.mybatis.memory.EntityList; 171 | 172 | public class SourceEvidenceTransactions extends EntityList implements SourceEvidence.Transactions { 173 | } 174 | ``` 175 | 176 | 引用的生命周期由reengineering.ddd.mybatis.database提供: 177 | 178 | ```java 179 | import reengineering.ddd.mybatis.database.EntityList; 180 | 181 | public class AccountTransactions extends EntityList implements Account.Transactions { 182 | 183 | } 184 | ``` 185 | 186 | 所有的关联对象都使用MyBatis实现,代码在persistent/mybatis模块中。 187 | 188 | 189 | 190 | 191 | 192 | 193 | -------------------------------------------------------------------------------- /api/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'reengineering.ddd' 3 | id 'java-library' 4 | id 'org.springframework.boot' version '2.7.0' 5 | id 'io.spring.dependency-management' version '1.0.11.RELEASE' 6 | } 7 | 8 | dependencies { 9 | implementation project(':domain') 10 | implementation 'javax.inject:javax.inject:1' 11 | implementation 'jakarta.ws.rs:jakarta.ws.rs-api:2.1.6' 12 | implementation 'org.springframework.hateoas:spring-hateoas:1.5.0' 13 | implementation 'com.fasterxml.jackson.core:jackson-annotations:2.13.3' 14 | implementation 'com.fasterxml.jackson.core:jackson-databind:2.13.3' 15 | 16 | testImplementation 'org.springframework.boot:spring-boot-starter-hateoas' 17 | testImplementation 'org.springframework.boot:spring-boot-starter-jersey' 18 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 19 | testImplementation 'io.rest-assured:rest-assured' 20 | } -------------------------------------------------------------------------------- /api/src/main/java/reengineering/ddd/accounting/api/AccountsApi.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting.api; 2 | 3 | import org.springframework.hateoas.CollectionModel; 4 | import org.springframework.hateoas.Link; 5 | import org.springframework.hateoas.PagedModel; 6 | import reengineering.ddd.accounting.api.representation.TransactionModel; 7 | import reengineering.ddd.accounting.model.Account; 8 | import reengineering.ddd.accounting.model.Customer; 9 | import reengineering.ddd.accounting.model.Transaction; 10 | import reengineering.ddd.archtype.Many; 11 | 12 | import javax.ws.rs.*; 13 | import javax.ws.rs.core.Context; 14 | import javax.ws.rs.core.Response; 15 | import javax.ws.rs.core.UriInfo; 16 | import java.net.MalformedURLException; 17 | import java.util.ArrayList; 18 | import java.util.List; 19 | import java.util.stream.Collectors; 20 | 21 | import static reengineering.ddd.accounting.api.ApiTemplates.accountTransactions; 22 | 23 | public class AccountsApi { 24 | private Customer customer; 25 | 26 | public AccountsApi(Customer customer) { 27 | this.customer = customer; 28 | } 29 | 30 | @GET 31 | @Path("{account-id}/transactions") 32 | public CollectionModel findAll(@PathParam("account-id") String id, @Context UriInfo info, @DefaultValue("0") @QueryParam("page") int page) { 33 | Account account = customer.accounts().findByIdentity(id).orElseThrow(() -> new WebApplicationException(Response.Status.NOT_FOUND)); 34 | return new Pagination<>(account.transactions().findAll(), 40).page(page, 35 | tx -> TransactionModel.withEvidenceLink(customer, tx, info), 36 | p -> accountTransactions(info).queryParam("page", p).build(customer.getIdentity(), account.getIdentity())); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /api/src/main/java/reengineering/ddd/accounting/api/ApiTemplates.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting.api; 2 | 3 | import javax.ws.rs.core.UriBuilder; 4 | import javax.ws.rs.core.UriInfo; 5 | 6 | public class ApiTemplates { 7 | public static UriBuilder customer(UriInfo info) { 8 | return info.getBaseUriBuilder().path(CustomersApi.class).path(CustomersApi.class, "findById"); 9 | 10 | } 11 | 12 | public static UriBuilder sourceEvidences(UriInfo info) { 13 | return customer(info).path(CustomerApi.class, "sourceEvidences"); 14 | } 15 | 16 | public static UriBuilder sourceEvidence(UriInfo info) { 17 | return sourceEvidences(info).path(SourceEvidencesApi.class, "findById"); 18 | } 19 | 20 | public static UriBuilder accounts(UriInfo info) { 21 | return customer(info).path(CustomerApi.class, "accounts"); 22 | } 23 | 24 | public static UriBuilder accountTransactions(UriInfo info) { 25 | return accounts(info).path(AccountsApi.class, "findAll"); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /api/src/main/java/reengineering/ddd/accounting/api/CustomerApi.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting.api; 2 | 3 | import org.springframework.hateoas.Link; 4 | import reengineering.ddd.accounting.api.representation.CustomerModel; 5 | import reengineering.ddd.accounting.model.Customer; 6 | 7 | import javax.ws.rs.GET; 8 | import javax.ws.rs.Path; 9 | import javax.ws.rs.container.ResourceContext; 10 | import javax.ws.rs.core.Context; 11 | import javax.ws.rs.core.UriInfo; 12 | import java.net.URI; 13 | 14 | public class CustomerApi { 15 | private Customer customer; 16 | 17 | public CustomerApi(Customer customer) { 18 | this.customer = customer; 19 | } 20 | 21 | @GET 22 | public CustomerModel get(@Context UriInfo info) { 23 | return new CustomerModel(customer, info); 24 | } 25 | 26 | @Path("source-evidences") 27 | public SourceEvidencesApi sourceEvidences(@Context ResourceContext context) { 28 | return context.initResource(new SourceEvidencesApi(customer)); 29 | } 30 | 31 | @Path("accounts") 32 | public AccountsApi accounts() { 33 | return new AccountsApi(customer); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /api/src/main/java/reengineering/ddd/accounting/api/CustomersApi.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting.api; 2 | 3 | import reengineering.ddd.accounting.model.Customers; 4 | 5 | import javax.inject.Inject; 6 | import javax.ws.rs.Path; 7 | import javax.ws.rs.PathParam; 8 | 9 | @Path("/customers") 10 | public class CustomersApi { 11 | private Customers customers; 12 | 13 | @Inject 14 | public CustomersApi(Customers customers) { 15 | this.customers = customers; 16 | } 17 | 18 | @Path("{id}") 19 | public CustomerApi findById(@PathParam("id") String id) { 20 | return customers.findById(id).map(CustomerApi::new).orElse(null); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /api/src/main/java/reengineering/ddd/accounting/api/Pagination.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting.api; 2 | 3 | import org.springframework.hateoas.CollectionModel; 4 | import org.springframework.hateoas.Link; 5 | import org.springframework.hateoas.PagedModel; 6 | import reengineering.ddd.archtype.Entity; 7 | import reengineering.ddd.archtype.Many; 8 | 9 | import javax.ws.rs.WebApplicationException; 10 | import javax.ws.rs.core.Response; 11 | import java.net.MalformedURLException; 12 | import java.net.URI; 13 | import java.util.ArrayList; 14 | import java.util.List; 15 | import java.util.Map; 16 | import java.util.function.Function; 17 | 18 | public class Pagination> { 19 | private final int total; 20 | private Many many; 21 | 22 | private int pageSize; 23 | 24 | public Pagination(Many many, int pageSize) { 25 | this.many = many; 26 | this.total = many.size(); 27 | this.pageSize = pageSize; 28 | } 29 | 30 | public CollectionModel page(int page, Function toModel, Function toUri) { 31 | if (!withInRange(page)) throw new WebApplicationException(Response.Status.NOT_FOUND); 32 | 33 | PagedModel.PageMetadata metadata = new PagedModel.PageMetadata(pageSize, page, total); 34 | Many current = many.subCollection(page * pageSize, Math.min(total, (page + 1) * pageSize)); 35 | 36 | Map pages = Map.of("self", page, "prev", page - 1, "next", page + 1); 37 | 38 | return PagedModel.of(current.stream().map(toModel).toList(), metadata).add( 39 | pages.entrySet().stream().filter(e -> withInRange(e.getValue())) 40 | .map(e -> Link.of(getFile(toUri.apply(e.getValue())), e.getKey())).toList()); 41 | } 42 | 43 | private String getFile(URI uri) { 44 | try { 45 | return uri.toURL().getFile(); 46 | } catch (MalformedURLException e) { 47 | throw new WebApplicationException(e); 48 | } 49 | } 50 | 51 | private boolean withInRange(int page) { 52 | return page >= 0 && page * pageSize <= total; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /api/src/main/java/reengineering/ddd/accounting/api/SourceEvidencesApi.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting.api; 2 | 3 | import org.springframework.hateoas.CollectionModel; 4 | import org.springframework.hateoas.Link; 5 | import reengineering.ddd.accounting.api.representation.SourceEvidenceModel; 6 | import reengineering.ddd.accounting.api.representation.SourceEvidenceReader; 7 | import reengineering.ddd.accounting.api.representation.TransactionModel; 8 | import reengineering.ddd.accounting.model.Account; 9 | import reengineering.ddd.accounting.model.Customer; 10 | import reengineering.ddd.accounting.model.SourceEvidence; 11 | import reengineering.ddd.archtype.Many; 12 | 13 | import javax.inject.Inject; 14 | import javax.ws.rs.*; 15 | import javax.ws.rs.core.Context; 16 | import javax.ws.rs.core.Response; 17 | import javax.ws.rs.core.UriInfo; 18 | import java.util.stream.Collectors; 19 | 20 | import static reengineering.ddd.accounting.api.ApiTemplates.accountTransactions; 21 | import static reengineering.ddd.accounting.api.ApiTemplates.sourceEvidences; 22 | 23 | public class SourceEvidencesApi { 24 | private Customer customer; 25 | 26 | @Inject 27 | private SourceEvidenceReader reader; 28 | 29 | public SourceEvidencesApi(Customer customer) { 30 | this.customer = customer; 31 | } 32 | 33 | @GET 34 | @Path("{evidence-id}") 35 | public SourceEvidenceModel findById(@PathParam("evidence-id") String id, 36 | @Context UriInfo info) { 37 | return customer.sourceEvidences().findByIdentity(id).map(evidence -> SourceEvidenceModel.of(customer, evidence, info)) 38 | .orElseThrow(() -> new WebApplicationException(Response.Status.NOT_FOUND)); 39 | } 40 | 41 | @GET 42 | public CollectionModel findAll(@Context UriInfo info, @DefaultValue("0") @QueryParam("page") int page) { 43 | return new Pagination<>(customer.sourceEvidences().findAll(), 40).page(page, 44 | evidence -> SourceEvidenceModel.simple(customer, evidence, info), 45 | p -> sourceEvidences(info).queryParam("page", p).build(customer.getIdentity())); 46 | } 47 | 48 | @POST 49 | public Response create(String json, @Context UriInfo info) { 50 | SourceEvidence evidence = customer.add(reader.read(json) 51 | .orElseThrow(() -> new WebApplicationException(Response.Status.NOT_ACCEPTABLE)).description()); 52 | return Response.created(ApiTemplates.sourceEvidence(info).build(customer.getIdentity(), evidence.getIdentity())).build(); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /api/src/main/java/reengineering/ddd/accounting/api/representation/CustomerModel.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting.api.representation; 2 | 3 | import com.fasterxml.jackson.annotation.JsonProperty; 4 | import com.fasterxml.jackson.annotation.JsonUnwrapped; 5 | import org.springframework.hateoas.Link; 6 | import org.springframework.hateoas.RepresentationModel; 7 | import reengineering.ddd.accounting.api.ApiTemplates; 8 | import reengineering.ddd.accounting.description.CustomerDescription; 9 | import reengineering.ddd.accounting.model.Customer; 10 | 11 | import javax.ws.rs.core.UriInfo; 12 | 13 | import static reengineering.ddd.accounting.api.ApiTemplates.*; 14 | 15 | public class CustomerModel extends RepresentationModel { 16 | @JsonProperty 17 | private String id; 18 | @JsonUnwrapped 19 | private CustomerDescription description; 20 | 21 | public CustomerModel(Customer customer, UriInfo info) { 22 | this.id = customer.getIdentity(); 23 | this.description = customer.getDescription(); 24 | add(Link.of(customer(info).build(customer.getIdentity()).getPath(), "self")); 25 | add(Link.of(sourceEvidences(info).build(customer.getIdentity()).getPath(), "source-evidences")); 26 | customer.accounts().findAll().forEach(a -> 27 | add(Link.of(accountTransactions(info).build(customer.getIdentity(), a.getIdentity()).getPath(), "account-" + a.getIdentity() + "-transactions"))); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /api/src/main/java/reengineering/ddd/accounting/api/representation/SalesSettlementRequest.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting.api.representation; 2 | 3 | import com.fasterxml.jackson.annotation.JsonTypeName; 4 | import com.fasterxml.jackson.annotation.JsonUnwrapped; 5 | import reengineering.ddd.accounting.description.SalesSettlementDescription; 6 | 7 | @JsonTypeName("sales-settlement") 8 | public class SalesSettlementRequest implements SourceEvidenceRequest { 9 | @JsonUnwrapped 10 | private SalesSettlementDescription description; 11 | 12 | @Override 13 | public SalesSettlementDescription description() { 14 | return description; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /api/src/main/java/reengineering/ddd/accounting/api/representation/SourceEvidenceJsonReader.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting.api.representation; 2 | 3 | import com.fasterxml.jackson.core.JsonProcessingException; 4 | import com.fasterxml.jackson.databind.ObjectMapper; 5 | 6 | import javax.inject.Inject; 7 | import java.util.Optional; 8 | 9 | public class SourceEvidenceJsonReader implements SourceEvidenceReader { 10 | private ObjectMapper mapper; 11 | 12 | @Inject 13 | public SourceEvidenceJsonReader(ObjectMapper mapper) { 14 | this.mapper = mapper; 15 | } 16 | 17 | @Override 18 | public Optional> read(String json) { 19 | try { 20 | return Optional.of(mapper.readValue(json, SourceEvidenceRequest.class)); 21 | } catch (JsonProcessingException e) { 22 | return Optional.empty(); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /api/src/main/java/reengineering/ddd/accounting/api/representation/SourceEvidenceModel.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting.api.representation; 2 | 3 | import com.fasterxml.jackson.annotation.JsonInclude; 4 | import com.fasterxml.jackson.annotation.JsonProperty; 5 | import com.fasterxml.jackson.annotation.JsonUnwrapped; 6 | import org.springframework.hateoas.Link; 7 | import org.springframework.hateoas.RepresentationModel; 8 | import org.springframework.hateoas.server.core.Relation; 9 | import reengineering.ddd.accounting.api.ApiTemplates; 10 | import reengineering.ddd.accounting.description.SourceEvidenceDescription; 11 | import reengineering.ddd.accounting.model.Customer; 12 | import reengineering.ddd.accounting.model.SourceEvidence; 13 | 14 | import javax.ws.rs.core.UriInfo; 15 | import java.util.List; 16 | import java.util.stream.Collectors; 17 | 18 | @Relation(collectionRelation = "evidences") 19 | @JsonInclude(JsonInclude.Include.NON_NULL) 20 | public class SourceEvidenceModel extends RepresentationModel { 21 | @JsonProperty 22 | private String id; 23 | 24 | @JsonUnwrapped 25 | private SourceEvidenceDescription description; 26 | 27 | @JsonProperty 28 | private List transactions; 29 | 30 | private SourceEvidenceModel(Customer customer, SourceEvidence evidence, SourceEvidenceDescription description, List transactions, UriInfo info) { 31 | this.id = evidence.getIdentity(); 32 | this.description = description; 33 | this.transactions = transactions; 34 | add(Link.of(ApiTemplates.sourceEvidence(info).build(customer.getIdentity(), evidence.getIdentity()).getPath(), "self")); 35 | 36 | } 37 | 38 | public static SourceEvidenceModel simple(Customer customer, SourceEvidence evidence, UriInfo info) { 39 | return new SourceEvidenceModel(customer, evidence, null, null, info); 40 | } 41 | 42 | public static SourceEvidenceModel of(Customer customer, SourceEvidence evidence, UriInfo info) { 43 | return new SourceEvidenceModel(customer, evidence, evidence.getDescription(), evidence.transactions().findAll().stream().map(tx -> 44 | new TransactionModel(customer, tx, info)).collect(Collectors.toList()), info); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /api/src/main/java/reengineering/ddd/accounting/api/representation/SourceEvidenceReader.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting.api.representation; 2 | 3 | import java.util.Optional; 4 | 5 | public interface SourceEvidenceReader { 6 | Optional> read(String json); 7 | } 8 | -------------------------------------------------------------------------------- /api/src/main/java/reengineering/ddd/accounting/api/representation/SourceEvidenceRequest.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting.api.representation; 2 | 3 | import com.fasterxml.jackson.annotation.JsonSubTypes; 4 | import com.fasterxml.jackson.annotation.JsonTypeInfo; 5 | import reengineering.ddd.accounting.description.SourceEvidenceDescription; 6 | 7 | @JsonTypeInfo( 8 | use = JsonTypeInfo.Id.NAME, 9 | include = JsonTypeInfo.As.PROPERTY, 10 | property = "type") 11 | @JsonSubTypes({ 12 | @JsonSubTypes.Type(SalesSettlementRequest.class) 13 | }) 14 | public interface SourceEvidenceRequest { 15 | Description description(); 16 | } 17 | -------------------------------------------------------------------------------- /api/src/main/java/reengineering/ddd/accounting/api/representation/TransactionModel.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting.api.representation; 2 | 3 | import com.fasterxml.jackson.annotation.JsonProperty; 4 | import com.fasterxml.jackson.annotation.JsonUnwrapped; 5 | import org.springframework.hateoas.Link; 6 | import org.springframework.hateoas.RepresentationModel; 7 | import org.springframework.hateoas.server.core.Relation; 8 | import reengineering.ddd.accounting.api.ApiTemplates; 9 | import reengineering.ddd.accounting.description.TransactionDescription; 10 | import reengineering.ddd.accounting.model.Customer; 11 | import reengineering.ddd.accounting.model.Transaction; 12 | 13 | import javax.ws.rs.core.UriInfo; 14 | 15 | @Relation(collectionRelation = "transactions") 16 | public class TransactionModel extends RepresentationModel { 17 | @JsonProperty 18 | private String id; 19 | @JsonUnwrapped 20 | private TransactionDescription description; 21 | 22 | public TransactionModel(Customer customer, Transaction transaction, UriInfo info) { 23 | this.id = transaction.getIdentity(); 24 | this.description = transaction.getDescription(); 25 | } 26 | 27 | public static TransactionModel withEvidenceLink(Customer customer, Transaction transaction, UriInfo info) { 28 | return new TransactionModel(customer, transaction, info).add(Link.of(ApiTemplates.sourceEvidence(info).build(customer.getIdentity(), transaction.sourceEvidence().getIdentity()).getPath(), "source-evidence")); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /api/src/test/java/reengineering/ddd/accounting/api/ApiTest.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting.api; 2 | 3 | import io.restassured.RestAssured; 4 | import org.junit.jupiter.api.BeforeEach; 5 | import org.springframework.beans.factory.annotation.Value; 6 | import org.springframework.boot.test.context.SpringBootTest; 7 | import reengineering.ddd.accounting.api.config.TestApplication; 8 | 9 | import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; 10 | 11 | @SpringBootTest(webEnvironment = RANDOM_PORT, classes = TestApplication.class) 12 | public class ApiTest { 13 | @Value("${local.server.port}") 14 | private int port; 15 | @Value("${server.servlet.context-path}") 16 | private String contextPath; 17 | 18 | @BeforeEach 19 | public void setup() { 20 | RestAssured.port = port; 21 | RestAssured.basePath = contextPath; 22 | } 23 | 24 | protected String uri(String path) { 25 | return String.format("http://localhost:%d%s", port, path); 26 | } 27 | } 28 | 29 | -------------------------------------------------------------------------------- /api/src/test/java/reengineering/ddd/accounting/api/CustomerAccountTransactionsApiTest.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting.api; 2 | 3 | import org.junit.jupiter.api.BeforeEach; 4 | import org.junit.jupiter.api.Test; 5 | import org.mockito.Mock; 6 | import org.springframework.boot.test.mock.mockito.MockBean; 7 | import org.springframework.hateoas.MediaTypes; 8 | import reengineering.ddd.accounting.description.AccountDescription; 9 | import reengineering.ddd.accounting.description.CustomerDescription; 10 | import reengineering.ddd.accounting.description.TransactionDescription; 11 | import reengineering.ddd.accounting.description.basic.Amount; 12 | import reengineering.ddd.accounting.description.basic.Currency; 13 | import reengineering.ddd.accounting.model.*; 14 | import reengineering.ddd.archtype.Many; 15 | 16 | import java.math.BigDecimal; 17 | import java.time.LocalDateTime; 18 | import java.util.Optional; 19 | 20 | import static io.restassured.RestAssured.given; 21 | import static org.hamcrest.Matchers.is; 22 | import static org.mockito.ArgumentMatchers.any; 23 | import static org.mockito.ArgumentMatchers.eq; 24 | import static org.mockito.Mockito.mock; 25 | import static org.mockito.Mockito.when; 26 | 27 | public class CustomerAccountTransactionsApiTest extends ApiTest { 28 | @MockBean 29 | private Customers customers; 30 | private Customer customer; 31 | @Mock 32 | private Customer.Accounts accounts; 33 | 34 | private Account account; 35 | 36 | @Mock 37 | private Account.Transactions transactions; 38 | 39 | @Mock 40 | private SourceEvidence evidence; 41 | 42 | private Transaction transaction; 43 | 44 | @Mock 45 | private Many allTransactions; 46 | 47 | @BeforeEach 48 | public void before() { 49 | customer = new Customer("john.smith", new CustomerDescription("John Smith", "john.smith@email.com"), mock(Customer.SourceEvidences.class), accounts); 50 | when(customers.findById(eq(customer.getIdentity()))).thenReturn(Optional.of(customer)); 51 | 52 | account = new Account("CASH-01", new AccountDescription(new Amount(new BigDecimal("0"), Currency.CNY)), transactions); 53 | when(evidence.getIdentity()).thenReturn("EV-001"); 54 | when(transactions.findAll()).thenReturn(allTransactions); 55 | 56 | transaction = new Transaction("TX-01", new TransactionDescription(Amount.cny("1000"), LocalDateTime.now()), () -> account, () -> evidence); 57 | } 58 | 59 | @Test 60 | public void should_return_404_if_account_not_found() { 61 | when(accounts.findByIdentity(eq("CASH-01"))).thenReturn(Optional.empty()); 62 | 63 | given().accept(MediaTypes.HAL_JSON.toString()) 64 | .when().get("/customers/" + customer.getIdentity() + "/accounts/CASH-01/transactions") 65 | .then().statusCode(404); 66 | } 67 | 68 | @Test 69 | public void should_return_transactions_in_account() { 70 | when(accounts.findByIdentity(eq("CASH-01"))).thenReturn(Optional.of(account)); 71 | when(allTransactions.size()).thenReturn(1); 72 | when(allTransactions.subCollection(eq(0), eq(1))).thenReturn(new EntityList<>(transaction)); 73 | 74 | given().accept(MediaTypes.HAL_JSON.toString()) 75 | .when().get("/customers/" + customer.getIdentity() + "/accounts/CASH-01/transactions") 76 | .then().statusCode(200) 77 | .body("_links.self.href", is("/api/customers/" + customer.getIdentity() + "/accounts/CASH-01/transactions?page=0")) 78 | .body("page.size", is(40)) 79 | .body("page.totalElements", is(1)) 80 | .body("page.totalPages", is(1)) 81 | .body("page.number", is(0)) 82 | .body("_embedded.transactions.size()", is(1)) 83 | .body("_embedded.transactions[0].id", is(transaction.getIdentity())) 84 | .body("_embedded.transactions[0].amount.value", is(transaction.getDescription().amount().value().intValue())) 85 | .body("_embedded.transactions[0].amount.currency", is(transaction.getDescription().amount().currency().toString())) 86 | .body("_embedded.transactions[0]._links.source-evidence.href", is("/api/customers/" + customer.getIdentity() + "/source-evidences/EV-001")); 87 | } 88 | 89 | @Test 90 | public void should_return_page_links_if_more_than_one_page_exists() { 91 | when(accounts.findByIdentity(eq("CASH-01"))).thenReturn(Optional.of(account)); 92 | when(allTransactions.size()).thenReturn(4000); 93 | when(allTransactions.subCollection(eq(0), eq(40))).thenReturn(new EntityList<>(transaction)); 94 | 95 | given().accept(MediaTypes.HAL_JSON.toString()) 96 | .when().get("/customers/" + customer.getIdentity() + "/accounts/CASH-01/transactions") 97 | .then().statusCode(200) 98 | .body("_links.next.href", is("/api/customers/" + customer.getIdentity() + "/accounts/CASH-01/transactions?page=1")) 99 | .body("_links.self.href", is("/api/customers/" + customer.getIdentity() + "/accounts/CASH-01/transactions?page=0")); 100 | } 101 | 102 | @Test 103 | public void should_return_404_if_not_in_page_range() { 104 | when(accounts.findByIdentity(eq("CASH-01"))).thenReturn(Optional.of(account)); 105 | when(allTransactions.size()).thenReturn(0); 106 | 107 | given().accept(MediaTypes.HAL_JSON.toString()) 108 | .when().get("/customers/" + customer.getIdentity() + "/accounts/CASH-01/transactions?page=1") 109 | .then().statusCode(404); 110 | 111 | given().accept(MediaTypes.HAL_JSON.toString()) 112 | .when().get("/customers/" + customer.getIdentity() + "/accounts/CASH-01/transactions?page=-1") 113 | .then().statusCode(404); 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /api/src/test/java/reengineering/ddd/accounting/api/CustomerSourceEvidencesApiTest.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting.api; 2 | 3 | import org.junit.jupiter.api.BeforeEach; 4 | import org.junit.jupiter.api.Test; 5 | import org.mockito.Mock; 6 | import org.springframework.boot.test.mock.mockito.MockBean; 7 | import org.springframework.hateoas.MediaTypes; 8 | import reengineering.ddd.accounting.api.representation.SourceEvidenceReader; 9 | import reengineering.ddd.accounting.api.representation.SourceEvidenceRequest; 10 | import reengineering.ddd.accounting.description.AccountDescription; 11 | import reengineering.ddd.accounting.description.CustomerDescription; 12 | import reengineering.ddd.accounting.description.SourceEvidenceDescription; 13 | import reengineering.ddd.accounting.description.TransactionDescription; 14 | import reengineering.ddd.accounting.description.basic.Amount; 15 | import reengineering.ddd.accounting.description.basic.Currency; 16 | import reengineering.ddd.accounting.model.*; 17 | import reengineering.ddd.archtype.HasMany; 18 | import reengineering.ddd.archtype.Many; 19 | 20 | import javax.ws.rs.core.HttpHeaders; 21 | import java.math.BigDecimal; 22 | import java.time.LocalDateTime; 23 | import java.util.Optional; 24 | 25 | import static io.restassured.RestAssured.given; 26 | import static org.hamcrest.Matchers.is; 27 | import static org.mockito.ArgumentMatchers.eq; 28 | import static org.mockito.ArgumentMatchers.same; 29 | import static org.mockito.Mockito.mock; 30 | import static org.mockito.Mockito.when; 31 | 32 | public class CustomerSourceEvidencesApiTest extends ApiTest { 33 | @MockBean 34 | private Customers customers; 35 | private Customer customer; 36 | @Mock 37 | private Customer.SourceEvidences sourceEvidences; 38 | 39 | @MockBean 40 | private SourceEvidenceReader reader; 41 | 42 | @Mock 43 | private SourceEvidence evidence; 44 | 45 | @Mock 46 | private Many> evidences; 47 | 48 | @Mock 49 | private HasMany transactions; 50 | 51 | @Mock 52 | private Account.Transactions accountTransactions; 53 | 54 | @BeforeEach 55 | public void before() { 56 | customer = new Customer("john.smith", new CustomerDescription("John Smith", "john.smith@email.com"), sourceEvidences, mock(Customer.Accounts.class)); 57 | when(customers.findById(eq(customer.getIdentity()))).thenReturn(Optional.of(customer)); 58 | 59 | when(evidence.getIdentity()).thenReturn("EV-001"); 60 | when(evidence.getDescription()).thenReturn(new EvidenceDescription("ORD-001")); 61 | when(evidence.transactions()).thenReturn(transactions); 62 | 63 | Account account = new Account("CASH-01", new AccountDescription(new Amount(new BigDecimal("0"), Currency.CNY)), accountTransactions); 64 | when(transactions.findAll()).thenReturn(new EntityList<>(new Transaction("TX-01", new TransactionDescription(Amount.cny("1000"), LocalDateTime.now()), () -> account, () -> evidence))); 65 | } 66 | 67 | @Test 68 | public void should_return_all_source_evidences_with_only_links() { 69 | when(sourceEvidences.findAll()).thenReturn(evidences); 70 | when(evidences.size()).thenReturn(1); 71 | when(evidences.subCollection(eq(0), eq(1))).thenReturn(new EntityList<>(evidence)); 72 | 73 | given().accept(MediaTypes.HAL_JSON.toString()) 74 | .when().get("/customers/" + customer.getIdentity() + "/source-evidences") 75 | .then().statusCode(200) 76 | .body("_links.self.href", is("/api/customers/" + customer.getIdentity() + "/source-evidences?page=0")) 77 | .body("_embedded.evidences.size()", is(1)) 78 | .body("_embedded.evidences[0].id", is("EV-001")) 79 | .body("_embedded.evidences[0]._links.self.href", is("/api/customers/" + customer.getIdentity() + "/source-evidences/EV-001")); 80 | } 81 | 82 | @Test 83 | public void should_return_all_source_evidences_as_pages() { 84 | when(sourceEvidences.findAll()).thenReturn(evidences); 85 | when(evidences.size()).thenReturn(4000); 86 | when(evidences.subCollection(eq(0), eq(40))).thenReturn(new EntityList<>(evidence)); 87 | 88 | given().accept(MediaTypes.HAL_JSON.toString()) 89 | .when().get("/customers/" + customer.getIdentity() + "/source-evidences") 90 | .then().statusCode(200) 91 | .body("_links.self.href", is("/api/customers/" + customer.getIdentity() + "/source-evidences?page=0")) 92 | .body("_links.next.href", is("/api/customers/" + customer.getIdentity() + "/source-evidences?page=1")) 93 | .body("_embedded.evidences.size()", is(1)) 94 | .body("_embedded.evidences[0].id", is("EV-001")) 95 | .body("_embedded.evidences[0]._links.self.href", is("/api/customers/" + customer.getIdentity() + "/source-evidences/EV-001")); 96 | } 97 | 98 | 99 | @Test 100 | public void should_return_404_if_no_source_evidence_matched_by_id() { 101 | when(sourceEvidences.findByIdentity("EV-001")).thenReturn(Optional.empty()); 102 | 103 | given().accept(MediaTypes.HAL_JSON.toString()) 104 | .when().get("/customers/" + customer.getIdentity() + "/source-evidences/EV-001") 105 | .then().statusCode(404); 106 | } 107 | 108 | @Test 109 | public void should_return_source_evidence_matched_by_id() { 110 | when(sourceEvidences.findByIdentity("EV-001")).thenReturn(Optional.of(evidence)); 111 | 112 | given().accept(MediaTypes.HAL_JSON.toString()) 113 | .when().get("/customers/" + customer.getIdentity() + "/source-evidences/EV-001") 114 | .then().statusCode(200) 115 | .body("id", is("EV-001")) 116 | .body("orderId", is("ORD-001")) 117 | .body("transactions.size()", is(1)) 118 | .body("transactions[0].id", is("TX-01")) 119 | .body("transactions[0].amount.value", is(1000)) 120 | .body("transactions[0].amount.currency", is("CNY")) 121 | .body("_links.self.href", is("/api/customers/" + customer.getIdentity() + "/source-evidences/EV-001")); 122 | } 123 | 124 | @Test 125 | public void should_return_406_if_source_evidence_not_allowed() { 126 | String unsupported = "{\"type\": \"unsupported\"}"; 127 | when(reader.read(eq(unsupported))).thenReturn(Optional.empty()); 128 | given().accept(MediaTypes.HAL_JSON.toString()) 129 | .body(unsupported) 130 | .when().post("/customers/" + customer.getIdentity() + "/source-evidences") 131 | .then().statusCode(406); 132 | } 133 | 134 | @Test 135 | public void should_return_201_if_source_evidence_created() { 136 | String supported = "{\"type\": \"supported\"}"; 137 | EvidenceDescription description = new EvidenceDescription("ORD-001"); 138 | 139 | SourceEvidenceRequest request = mock(SourceEvidenceRequest.class); 140 | SourceEvidence evidence = mock(SourceEvidence.class); 141 | 142 | when(request.description()).thenReturn(description); 143 | when(evidence.getIdentity()).thenReturn("EV-001"); 144 | when(sourceEvidences.add(same(description))).thenReturn(evidence); 145 | 146 | when(reader.read(eq(supported))).thenReturn(Optional.of(request)); 147 | given().accept(MediaTypes.HAL_JSON.toString()) 148 | .body(supported) 149 | .when().post("/customers/" + customer.getIdentity() + "/source-evidences") 150 | .then().statusCode(201) 151 | .header(HttpHeaders.LOCATION, is(uri("/api/customers/" + customer.getIdentity() + "/source-evidences/EV-001"))); 152 | } 153 | 154 | record EvidenceDescription(String orderId) implements SourceEvidenceDescription { 155 | } 156 | } 157 | 158 | 159 | -------------------------------------------------------------------------------- /api/src/test/java/reengineering/ddd/accounting/api/CustomersApiTest.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting.api; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.mock.mockito.MockBean; 5 | import org.springframework.hateoas.MediaTypes; 6 | import reengineering.ddd.accounting.description.AccountDescription; 7 | import reengineering.ddd.accounting.description.CustomerDescription; 8 | import reengineering.ddd.accounting.description.basic.Amount; 9 | import reengineering.ddd.accounting.model.Account; 10 | import reengineering.ddd.accounting.model.Customer; 11 | import reengineering.ddd.accounting.model.Customers; 12 | 13 | import java.util.Optional; 14 | 15 | import static io.restassured.RestAssured.given; 16 | import static org.hamcrest.Matchers.is; 17 | import static org.mockito.ArgumentMatchers.eq; 18 | import static org.mockito.Mockito.mock; 19 | import static org.mockito.Mockito.when; 20 | 21 | public class CustomersApiTest extends ApiTest { 22 | @MockBean 23 | private Customers customers; 24 | 25 | @Test 26 | public void should_return_404_if_customer_not_exist() { 27 | when(customers.findById(eq("inexist"))).thenReturn(Optional.empty()); 28 | 29 | given().accept(MediaTypes.HAL_JSON.toString()) 30 | .when().get("/customers/inexist").then().statusCode(404); 31 | } 32 | 33 | @Test 34 | public void should_return_customer_if_customer_exists() { 35 | Customer.Accounts accounts = mock(Customer.Accounts.class); 36 | Account.Transactions transactions = mock(Account.Transactions.class); 37 | 38 | Customer customer = new Customer("john.smith", 39 | new CustomerDescription("John Smith", "john.smith@email.com"), 40 | mock(Customer.SourceEvidences.class), accounts); 41 | 42 | when(customers.findById(eq(customer.getIdentity()))).thenReturn(Optional.of(customer)); 43 | when(accounts.findAll()).thenReturn(new EntityList<>( 44 | new Account("1", new AccountDescription(Amount.cny("100.00")), transactions), 45 | new Account("2", new AccountDescription(Amount.cny("100.00")), transactions) 46 | )); 47 | 48 | given().accept(MediaTypes.HAL_JSON.toString()) 49 | .when().get("/customers/" + customer.getIdentity()) 50 | .then().statusCode(200) 51 | .body("id", is(customer.getIdentity())) 52 | .body("name", is(customer.getDescription().name())) 53 | .body("email", is(customer.getDescription().email())) 54 | .body("_links.self.href", is("/api/customers/" + customer.getIdentity())) 55 | .body("_links.account-1-transactions.href", is("/api/customers/" + customer.getIdentity() + "/accounts/1/transactions")) 56 | .body("_links.account-2-transactions.href", is("/api/customers/" + customer.getIdentity() + "/accounts/2/transactions")) 57 | .body("_links.source-evidences.href", is("/api/customers/" + customer.getIdentity() + "/source-evidences")); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /api/src/test/java/reengineering/ddd/accounting/api/EntityList.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting.api; 2 | 3 | import reengineering.ddd.archtype.Entity; 4 | import reengineering.ddd.archtype.Many; 5 | 6 | import java.util.Iterator; 7 | import java.util.List; 8 | 9 | class EntityList> implements Many { 10 | private List list; 11 | 12 | public EntityList(List list) { 13 | this.list = list; 14 | } 15 | 16 | public EntityList(E... entities) { 17 | this(List.of(entities)); 18 | } 19 | 20 | @Override 21 | public int size() { 22 | return list.size(); 23 | } 24 | 25 | @Override 26 | public Many subCollection(int from, int to) { 27 | return new EntityList<>(list.subList(from, to)); 28 | } 29 | 30 | @Override 31 | public Iterator iterator() { 32 | return list.iterator(); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /api/src/test/java/reengineering/ddd/accounting/api/config/HAL.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting.api.config; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import org.springframework.beans.factory.InitializingBean; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.context.annotation.Configuration; 7 | import org.springframework.hateoas.mediatype.MessageResolver; 8 | import org.springframework.hateoas.mediatype.hal.CurieProvider; 9 | import org.springframework.hateoas.mediatype.hal.Jackson2HalModule; 10 | import org.springframework.hateoas.server.LinkRelationProvider; 11 | import reengineering.ddd.accounting.api.representation.SourceEvidenceJsonReader; 12 | import reengineering.ddd.accounting.api.representation.SourceEvidenceReader; 13 | 14 | import javax.inject.Inject; 15 | 16 | @Configuration 17 | public class HAL implements InitializingBean { 18 | 19 | private ObjectMapper mapper; 20 | private LinkRelationProvider provider; 21 | private MessageResolver resolver; 22 | 23 | @Inject 24 | public HAL(ObjectMapper mapper, LinkRelationProvider provider, MessageResolver resolver) { 25 | this.mapper = mapper; 26 | this.provider = provider; 27 | this.resolver = resolver; 28 | } 29 | 30 | @Override 31 | public void afterPropertiesSet() { 32 | mapper.registerModule(new Jackson2HalModule()); 33 | mapper.setHandlerInstantiator(new Jackson2HalModule.HalHandlerInstantiator(provider, CurieProvider.NONE, resolver)); 34 | } 35 | 36 | @Bean 37 | public SourceEvidenceReader reader() { 38 | return new SourceEvidenceJsonReader(mapper); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /api/src/test/java/reengineering/ddd/accounting/api/config/Jersey.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting.api.config; 2 | 3 | import org.glassfish.jersey.server.ResourceConfig; 4 | import org.glassfish.jersey.server.ServerProperties; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.hateoas.config.EnableHypermediaSupport; 7 | import reengineering.ddd.accounting.api.CustomersApi; 8 | 9 | import java.util.Map; 10 | 11 | import static org.springframework.hateoas.config.EnableHypermediaSupport.HypermediaType.HAL; 12 | 13 | @Configuration 14 | @EnableHypermediaSupport(type = HAL) 15 | public class Jersey extends ResourceConfig { 16 | public Jersey() { 17 | setProperties(Map.of(ServerProperties.RESPONSE_SET_STATUS_OVER_SEND_ERROR, true)); 18 | register(CustomersApi.class); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /api/src/test/java/reengineering/ddd/accounting/api/config/TestApplication.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting.api.config; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.context.annotation.Bean; 6 | import reengineering.ddd.accounting.api.representation.SourceEvidenceReader; 7 | 8 | @SpringBootApplication 9 | public class TestApplication { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(TestApplication.class, args); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /api/src/test/java/reengineering/ddd/accounting/api/representation/SourceEvidenceReaderTest.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting.api.representation; 2 | 3 | import com.fasterxml.jackson.core.JsonProcessingException; 4 | import com.fasterxml.jackson.databind.ObjectMapper; 5 | import org.junit.jupiter.api.BeforeEach; 6 | import org.junit.jupiter.api.Test; 7 | import reengineering.ddd.accounting.description.SalesSettlementDescription; 8 | import reengineering.ddd.accounting.description.basic.Amount; 9 | import reengineering.ddd.accounting.description.basic.Currency; 10 | import reengineering.ddd.accounting.description.basic.Ref; 11 | 12 | import java.math.BigDecimal; 13 | import java.util.List; 14 | 15 | import static org.junit.jupiter.api.Assertions.assertEquals; 16 | 17 | public class SourceEvidenceReaderTest { 18 | private SourceEvidenceReader reader; 19 | private ObjectMapper mapper = new ObjectMapper(); 20 | 21 | @BeforeEach 22 | public void before() { 23 | reader = new SourceEvidenceJsonReader(mapper); 24 | } 25 | 26 | @Test 27 | public void should_read_sales_settlement_from_json() throws JsonProcessingException { 28 | SourceEvidenceRequest request = reader.read("{\"type\":\"sales-settlement\",\"order\":{\"id\":\"ORD-001\"},\"total\":{\"value\":1000.00,\"currency\":\"CNY\"},\"account\":{\"id\":\"CASH-001\"},\"details\":[{\"amount\":{\"value\":1000.00,\"currency\":\"CNY\"}}]}\n").get(); 29 | 30 | SalesSettlementDescription description = (SalesSettlementDescription) request.description(); 31 | 32 | assertEquals(new Ref<>("ORD-001"), description.getOrder()); 33 | assertEquals(new Amount(new BigDecimal("1000.00"), Currency.CNY), description.getTotal()); 34 | assertEquals(new Ref<>("CASH-001"), description.getAccount()); 35 | 36 | List details = description.getDetails(); 37 | assertEquals(1, details.size()); 38 | assertEquals(new Amount(new BigDecimal("1000.00"), Currency.CNY), details.get(0).getAmount()); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /api/src/test/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8080 3 | servlet: 4 | context-path: /api 5 | spring: 6 | main: 7 | banner-mode: "off" 8 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /buildSrc/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'groovy-gradle-plugin' 3 | } -------------------------------------------------------------------------------- /buildSrc/src/main/groovy/reengineering.ddd.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | id 'jacoco' 4 | } 5 | 6 | group = 'reengineering.ddd' 7 | version = '0.1.0' 8 | 9 | sourceCompatibility = '18' 10 | 11 | repositories { 12 | mavenCentral() 13 | } 14 | 15 | dependencies { 16 | testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.2' 17 | testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.2' 18 | } 19 | 20 | jacoco { 21 | toolVersion = "0.8.8" 22 | } 23 | 24 | test { 25 | useJUnitPlatform() 26 | finalizedBy jacocoTestReport 27 | } 28 | 29 | jacocoTestReport { 30 | dependsOn test 31 | } 32 | 33 | -------------------------------------------------------------------------------- /domain/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'reengineering.ddd' 3 | } 4 | 5 | dependencies { 6 | testImplementation 'org.mockito:mockito-core:4.6.1' 7 | } -------------------------------------------------------------------------------- /domain/src/main/java/reengineering/ddd/accounting/description/AccountDescription.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting.description; 2 | 3 | import reengineering.ddd.accounting.description.basic.Amount; 4 | 5 | public record AccountDescription(Amount current) { 6 | 7 | } 8 | -------------------------------------------------------------------------------- /domain/src/main/java/reengineering/ddd/accounting/description/CustomerDescription.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting.description; 2 | 3 | public record CustomerDescription(String name, String email) { 4 | } 5 | -------------------------------------------------------------------------------- /domain/src/main/java/reengineering/ddd/accounting/description/SalesSettlementDescription.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting.description; 2 | 3 | import reengineering.ddd.accounting.description.basic.Amount; 4 | import reengineering.ddd.accounting.description.basic.Ref; 5 | 6 | import java.util.List; 7 | 8 | public class SalesSettlementDescription implements SourceEvidenceDescription { 9 | private Ref order; 10 | 11 | private Amount total; 12 | 13 | private Ref account; 14 | 15 | private List details; 16 | 17 | private SalesSettlementDescription() { 18 | } 19 | 20 | public SalesSettlementDescription(Ref order, Amount total, Ref account, Detail... details) { 21 | this.order = order; 22 | this.total = total; 23 | this.account = account; 24 | this.details = List.of(details); 25 | } 26 | 27 | public Ref getOrder() { 28 | return order; 29 | } 30 | 31 | public Amount getTotal() { 32 | return total; 33 | } 34 | 35 | public Ref getAccount() { 36 | return account; 37 | } 38 | 39 | public List getDetails() { 40 | return details; 41 | } 42 | 43 | public static class Detail { 44 | private Amount amount; 45 | 46 | public Detail(Amount amount) { 47 | this.amount = amount; 48 | } 49 | 50 | private Detail() { 51 | } 52 | 53 | public Amount getAmount() { 54 | return amount; 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /domain/src/main/java/reengineering/ddd/accounting/description/SourceEvidenceDescription.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting.description; 2 | 3 | public interface SourceEvidenceDescription { 4 | } 5 | -------------------------------------------------------------------------------- /domain/src/main/java/reengineering/ddd/accounting/description/TransactionDescription.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting.description; 2 | 3 | import reengineering.ddd.accounting.description.basic.Amount; 4 | 5 | import java.time.LocalDateTime; 6 | 7 | public record TransactionDescription(Amount amount, LocalDateTime createdAt) { 8 | } 9 | -------------------------------------------------------------------------------- /domain/src/main/java/reengineering/ddd/accounting/description/basic/Amount.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting.description.basic; 2 | 3 | import java.math.BigDecimal; 4 | import java.util.Arrays; 5 | import java.util.Set; 6 | import java.util.stream.Collectors; 7 | 8 | public record Amount(BigDecimal value, Currency currency) { 9 | public static Amount cny(String value) { 10 | return new Amount(new BigDecimal(value), Currency.CNY); 11 | } 12 | public static Amount usd(String value) { 13 | return new Amount(new BigDecimal(value), Currency.USD); 14 | } 15 | 16 | public static Amount sum(Amount... amounts) { 17 | Currency[] currencies = Arrays.stream(amounts).map(Amount::currency).collect(Collectors.toSet()) 18 | .toArray(Currency[]::new); 19 | if (currencies.length > 1) throw new IllegalArgumentException(); 20 | BigDecimal sum = Arrays.stream(amounts).map(Amount::value).reduce(new BigDecimal(0), BigDecimal::add); 21 | return new Amount(sum, currencies[0]); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /domain/src/main/java/reengineering/ddd/accounting/description/basic/Currency.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting.description.basic; 2 | 3 | public enum Currency { 4 | CNY, USD 5 | } 6 | -------------------------------------------------------------------------------- /domain/src/main/java/reengineering/ddd/accounting/description/basic/Ref.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting.description.basic; 2 | 3 | public record Ref(Identity id) { 4 | } 5 | -------------------------------------------------------------------------------- /domain/src/main/java/reengineering/ddd/accounting/model/Account.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting.model; 2 | 3 | import reengineering.ddd.accounting.description.AccountDescription; 4 | import reengineering.ddd.accounting.description.TransactionDescription; 5 | import reengineering.ddd.accounting.description.basic.Amount; 6 | import reengineering.ddd.archtype.Entity; 7 | import reengineering.ddd.archtype.HasMany; 8 | 9 | import java.util.List; 10 | 11 | public class Account implements Entity { 12 | private String identity; 13 | private AccountDescription description; 14 | 15 | private Transactions transactions; 16 | 17 | private Account() { 18 | } 19 | 20 | public Account(String identity, AccountDescription description, Transactions transactions) { 21 | this.identity = identity; 22 | this.description = description; 23 | this.transactions = transactions; 24 | } 25 | 26 | @Override 27 | public String getIdentity() { 28 | return identity; 29 | } 30 | 31 | @Override 32 | public AccountDescription getDescription() { 33 | return description; 34 | } 35 | 36 | public HasMany transactions() { 37 | return transactions; 38 | } 39 | 40 | public AccountChange add(SourceEvidence evidence, List descriptions) { 41 | Amount changeTotal = Amount.sum(descriptions.stream().map(it -> transactions.add(this, evidence, it)) 42 | .map(it -> it.getDescription().amount()).toArray(Amount[]::new)); 43 | description = new AccountDescription(Amount.sum(description.current(), changeTotal)); 44 | return new AccountChange(changeTotal); 45 | } 46 | 47 | public interface Transactions extends HasMany { 48 | Transaction add(Account account, SourceEvidence evidence, TransactionDescription description); 49 | } 50 | 51 | public record AccountChange(Amount total) { 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /domain/src/main/java/reengineering/ddd/accounting/model/AccountNotFoundException.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting.model; 2 | 3 | public class AccountNotFoundException extends RuntimeException { 4 | private String account; 5 | 6 | public AccountNotFoundException(String account) { 7 | super(account + " not found"); 8 | this.account = account; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /domain/src/main/java/reengineering/ddd/accounting/model/Customer.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting.model; 2 | 3 | import reengineering.ddd.accounting.description.CustomerDescription; 4 | import reengineering.ddd.accounting.description.SourceEvidenceDescription; 5 | import reengineering.ddd.accounting.description.TransactionDescription; 6 | import reengineering.ddd.archtype.Entity; 7 | import reengineering.ddd.archtype.HasMany; 8 | 9 | import java.util.List; 10 | import java.util.Map; 11 | 12 | public class Customer implements Entity { 13 | private String identity; 14 | private CustomerDescription description; 15 | 16 | private SourceEvidences sourceEvidences; 17 | 18 | private Accounts accounts; 19 | 20 | public Customer(String identity, CustomerDescription description, 21 | SourceEvidences sourceEvidences, Accounts accounts) { 22 | this.identity = identity; 23 | this.description = description; 24 | this.sourceEvidences = sourceEvidences; 25 | this.accounts = accounts; 26 | } 27 | 28 | private Customer() { 29 | } 30 | 31 | public String getIdentity() { 32 | return identity; 33 | } 34 | 35 | public CustomerDescription getDescription() { 36 | return description; 37 | } 38 | 39 | public HasMany> sourceEvidences() { 40 | return sourceEvidences; 41 | } 42 | 43 | public HasMany accounts() { 44 | return accounts; 45 | } 46 | 47 | public SourceEvidence add(SourceEvidenceDescription description) { 48 | SourceEvidence evidence = sourceEvidences.add(description); 49 | Map> transactions = evidence.toTransactions(); 50 | for (String accountId : transactions.keySet()) { 51 | Account account = accounts.findByIdentity(accountId).orElseThrow(() -> new AccountNotFoundException(accountId)); 52 | accounts.update(account, account.add(evidence, transactions.get(accountId))); 53 | } 54 | return evidence; 55 | } 56 | 57 | public interface SourceEvidences extends HasMany> { 58 | SourceEvidence add(SourceEvidenceDescription description); 59 | } 60 | 61 | public interface Accounts extends HasMany { 62 | void update(Account account, Account.AccountChange change); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /domain/src/main/java/reengineering/ddd/accounting/model/Customers.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting.model; 2 | 3 | import java.util.Optional; 4 | 5 | public interface Customers { 6 | Optional findById(String id); 7 | } 8 | -------------------------------------------------------------------------------- /domain/src/main/java/reengineering/ddd/accounting/model/SalesSettlement.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting.model; 2 | 3 | import reengineering.ddd.accounting.description.SalesSettlementDescription; 4 | import reengineering.ddd.accounting.description.TransactionDescription; 5 | import reengineering.ddd.archtype.HasMany; 6 | 7 | import java.time.LocalDateTime; 8 | import java.util.List; 9 | import java.util.Map; 10 | 11 | public class SalesSettlement implements SourceEvidence { 12 | private String identity; 13 | private SalesSettlementDescription description; 14 | 15 | private HasMany transactions; 16 | 17 | public SalesSettlement() { 18 | } 19 | 20 | public SalesSettlement(String identity, SalesSettlementDescription description, HasMany transactions) { 21 | this.identity = identity; 22 | this.description = description; 23 | this.transactions = transactions; 24 | } 25 | 26 | @Override 27 | public String getIdentity() { 28 | return identity; 29 | } 30 | 31 | @Override 32 | public SalesSettlementDescription getDescription() { 33 | return description; 34 | } 35 | 36 | @Override 37 | public HasMany transactions() { 38 | return transactions; 39 | } 40 | 41 | @Override 42 | public Map> toTransactions() { 43 | return Map.of(getDescription().getAccount().id(), 44 | getDescription().getDetails().stream().map(detail -> new TransactionDescription(detail.getAmount(), LocalDateTime.now())).toList()); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /domain/src/main/java/reengineering/ddd/accounting/model/SourceEvidence.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting.model; 2 | 3 | import reengineering.ddd.accounting.description.SourceEvidenceDescription; 4 | import reengineering.ddd.accounting.description.TransactionDescription; 5 | import reengineering.ddd.archtype.HasMany; 6 | import reengineering.ddd.archtype.Entity; 7 | 8 | import java.util.List; 9 | import java.util.Map; 10 | 11 | public interface SourceEvidence extends Entity { 12 | 13 | interface Transactions extends HasMany { 14 | } 15 | 16 | HasMany transactions(); 17 | 18 | Map> toTransactions(); 19 | } 20 | -------------------------------------------------------------------------------- /domain/src/main/java/reengineering/ddd/accounting/model/Transaction.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting.model; 2 | 3 | import reengineering.ddd.accounting.description.TransactionDescription; 4 | import reengineering.ddd.archtype.Entity; 5 | import reengineering.ddd.archtype.HasOne; 6 | 7 | public class Transaction implements Entity { 8 | private String identity; 9 | private TransactionDescription description; 10 | 11 | private HasOne> sourceEvidence; 12 | 13 | private HasOne account; 14 | 15 | private Transaction() { 16 | } 17 | 18 | public Transaction(String identity, TransactionDescription description, 19 | HasOne account, HasOne> sourceEvidence) { 20 | this.identity = identity; 21 | this.description = description; 22 | this.account = account; 23 | this.sourceEvidence = sourceEvidence; 24 | } 25 | 26 | @Override 27 | public String getIdentity() { 28 | return identity; 29 | } 30 | 31 | @Override 32 | public TransactionDescription getDescription() { 33 | return description; 34 | } 35 | 36 | public SourceEvidence sourceEvidence() { 37 | return sourceEvidence.get(); 38 | } 39 | 40 | public Account account() { 41 | return account.get(); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /domain/src/main/java/reengineering/ddd/archtype/Entity.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.archtype; 2 | 3 | public interface Entity { 4 | Identity getIdentity(); 5 | 6 | Description getDescription(); 7 | } 8 | -------------------------------------------------------------------------------- /domain/src/main/java/reengineering/ddd/archtype/HasMany.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.archtype; 2 | 3 | import java.util.Optional; 4 | 5 | public interface HasMany> { 6 | Many findAll(); 7 | 8 | Optional findByIdentity(ID identifier); 9 | } 10 | -------------------------------------------------------------------------------- /domain/src/main/java/reengineering/ddd/archtype/HasOne.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.archtype; 2 | 3 | public interface HasOne> { 4 | E get(); 5 | } 6 | -------------------------------------------------------------------------------- /domain/src/main/java/reengineering/ddd/archtype/Many.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.archtype; 2 | 3 | import java.util.stream.Stream; 4 | import java.util.stream.StreamSupport; 5 | 6 | public interface Many> extends Iterable { 7 | int size(); 8 | 9 | Many subCollection(int from, int to); 10 | 11 | default Stream stream() { 12 | return StreamSupport.stream(spliterator(), false); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /domain/src/test/java/reengineering/ddd/accounting/description/basic/AmountTest.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting.description.basic; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.assertEquals; 6 | import static org.junit.jupiter.api.Assertions.assertThrows; 7 | 8 | public class AmountTest { 9 | 10 | @Test 11 | public void should_sum_amount() { 12 | assertEquals(Amount.cny("600.00"), Amount.sum(Amount.cny("100.00"), Amount.cny("200.00"), Amount.cny("300.00"))); 13 | } 14 | 15 | @Test 16 | public void should_throw_exception_if_different_currencies_given() { 17 | assertThrows(IllegalArgumentException.class, () -> 18 | Amount.sum(Amount.cny("100.00"), Amount.usd("100.00"))); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /domain/src/test/java/reengineering/ddd/accounting/model/CustomerTest.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting.model; 2 | 3 | import org.junit.jupiter.api.BeforeEach; 4 | import org.junit.jupiter.api.Test; 5 | import reengineering.ddd.accounting.description.AccountDescription; 6 | import reengineering.ddd.accounting.description.CustomerDescription; 7 | import reengineering.ddd.accounting.description.SourceEvidenceDescription; 8 | import reengineering.ddd.accounting.description.TransactionDescription; 9 | import reengineering.ddd.accounting.description.basic.Amount; 10 | import reengineering.ddd.archtype.Many; 11 | 12 | import java.time.LocalDateTime; 13 | import java.util.*; 14 | 15 | import static org.junit.jupiter.api.Assertions.*; 16 | import static org.mockito.ArgumentMatchers.eq; 17 | import static org.mockito.ArgumentMatchers.same; 18 | import static org.mockito.Mockito.*; 19 | 20 | public class CustomerTest { 21 | 22 | private Customer.SourceEvidences evidences; 23 | 24 | private Customer.Accounts accounts; 25 | 26 | private SourceEvidenceDescription description; 27 | 28 | private SourceEvidence evidence; 29 | 30 | @BeforeEach 31 | public void before() { 32 | evidences = mock(Customer.SourceEvidences.class); 33 | accounts = mock(Customer.Accounts.class); 34 | description = mock(SourceEvidenceDescription.class); 35 | evidence = mock(SourceEvidence.class); 36 | } 37 | 38 | @Test 39 | public void should_write_transactions_to_account_from_source_evidence() { 40 | TransactionDescription cash1Tx1 = new TransactionDescription(Amount.cny("1000.00"), LocalDateTime.now()); 41 | TransactionDescription cash1Tx2 = new TransactionDescription(Amount.cny("2000.00"), LocalDateTime.now()); 42 | 43 | TransactionDescription cash2Tx1 = new TransactionDescription(Amount.cny("3000.00"), LocalDateTime.now()); 44 | TransactionDescription cash2Tx2 = new TransactionDescription(Amount.cny("4000.00"), LocalDateTime.now()); 45 | 46 | TransactionList cash1Tx = new TransactionList(); 47 | TransactionList cash2Tx = new TransactionList(); 48 | Account cash01 = new Account("CASH-01", new AccountDescription(Amount.cny("0.00")), cash1Tx); 49 | Account cash02 = new Account("CASH-02", new AccountDescription(Amount.cny("0.00")), cash2Tx); 50 | 51 | when(evidences.add(same(description))).thenReturn(evidence); 52 | when(evidence.toTransactions()).thenReturn(Map.of("CASH-01", List.of(cash1Tx1, cash1Tx2), "CASH-02", List.of(cash2Tx1, cash2Tx2))); 53 | when(accounts.findByIdentity(eq("CASH-01"))).thenReturn(Optional.of(cash01)); 54 | when(accounts.findByIdentity(eq("CASH-02"))).thenReturn(Optional.of(cash02)); 55 | 56 | Customer customer = new Customer("id", new CustomerDescription("John Smith", "john.smith@email.com"), evidences, accounts); 57 | assertSame(evidence, customer.add(description)); 58 | assertEquals(2, cash1Tx.descriptions.size()); 59 | assertEquals(2, cash2Tx.descriptions.size()); 60 | 61 | assertEquals(Amount.cny("3000.00"), cash01.getDescription().current()); 62 | assertEquals(Amount.cny("7000.00"), cash02.getDescription().current()); 63 | 64 | verify(accounts, times(1)).update(eq(cash01), eq(new Account.AccountChange(Amount.cny("3000.00")))); 65 | verify(accounts, times(1)).update(eq(cash02), eq(new Account.AccountChange(Amount.cny("7000.00")))); 66 | } 67 | 68 | @Test 69 | public void should_throw_exception_if_account_not_found() { 70 | TransactionDescription cash1Tx1 = new TransactionDescription(Amount.cny("1000.00"), LocalDateTime.now()); 71 | 72 | when(evidences.add(same(description))).thenReturn(evidence); 73 | when(evidence.toTransactions()).thenReturn(Map.of("CASH-01", List.of(cash1Tx1))); 74 | when(accounts.findByIdentity(eq("CASH-01"))).thenReturn(Optional.empty()); 75 | 76 | Customer customer = new Customer("id", new CustomerDescription("John Smith", "john.smith@email.com"), evidences, accounts); 77 | assertThrows(AccountNotFoundException.class, () -> customer.add(description)); 78 | } 79 | 80 | static class TransactionList implements Account.Transactions { 81 | List descriptions = new ArrayList<>(); 82 | 83 | @Override 84 | public Many findAll() { 85 | throw new UnsupportedOperationException(); 86 | } 87 | 88 | @Override 89 | public Optional findByIdentity(String identifier) { 90 | throw new UnsupportedOperationException(); 91 | } 92 | 93 | @Override 94 | public Transaction add(Account account, SourceEvidence evidence, TransactionDescription description) { 95 | descriptions.add(description); 96 | return new Transaction(String.valueOf(new Random().nextInt(100000)), description, null, null); 97 | } 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /domain/src/test/java/reengineering/ddd/accounting/model/SalesSettlementTest.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting.model; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.mockito.Mockito; 5 | import reengineering.ddd.accounting.description.SalesSettlementDescription; 6 | import reengineering.ddd.accounting.description.TransactionDescription; 7 | import reengineering.ddd.accounting.description.basic.Amount; 8 | import reengineering.ddd.accounting.description.basic.Ref; 9 | import reengineering.ddd.archtype.HasMany; 10 | 11 | import java.util.List; 12 | import java.util.Map; 13 | 14 | import static org.junit.jupiter.api.Assertions.assertEquals; 15 | import static org.junit.jupiter.api.Assertions.assertTrue; 16 | 17 | public class SalesSettlementTest { 18 | @Test 19 | public void should_generate_transaction_based_on_details() { 20 | SalesSettlement salesSettlement = new SalesSettlement("SS-001", new SalesSettlementDescription(new Ref<>("ORD-001"), 21 | Amount.cny("1000.00"), new Ref<>("CASH-001"), 22 | new SalesSettlementDescription.Detail(Amount.cny("700.00")), 23 | new SalesSettlementDescription.Detail(Amount.cny("300.00")) 24 | ), Mockito.mock(HasMany.class)); 25 | 26 | Map> transactions = salesSettlement.toTransactions(); 27 | 28 | assertTrue(transactions.containsKey("CASH-001")); 29 | assertEquals(1, transactions.size()); 30 | 31 | List descriptions = transactions.get("CASH-001"); 32 | assertEquals(2, descriptions.size()); 33 | assertEquals(Amount.cny("700.00"), descriptions.get(0).amount()); 34 | assertEquals(Amount.cny("300.00"), descriptions.get(1).amount()); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Re-engineering-Domain-Driven-Design/Accounting/ffe0a3648c275b0e930aca1fae13060bb2bdfd1b/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Use "xargs" to parse quoted args. 209 | # 210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 211 | # 212 | # In Bash we could simply go: 213 | # 214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 215 | # set -- "${ARGS[@]}" "$@" 216 | # 217 | # but POSIX shell has neither arrays nor command substitution, so instead we 218 | # post-process each arg (as a line of input to sed) to backslash-escape any 219 | # character that might be a shell metacharacter, then use eval to reverse 220 | # that process (while maintaining the separation between arguments), and wrap 221 | # the whole thing up as a single "set" statement. 222 | # 223 | # This will of course break if any of these variables contains a newline or 224 | # an unmatched quote. 225 | # 226 | 227 | eval "set -- $( 228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 229 | xargs -n1 | 230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 231 | tr '\n' ' ' 232 | )" '"$@"' 233 | 234 | exec "$JAVACMD" "$@" 235 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /main/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'reengineering.ddd' 3 | id 'org.springframework.boot' version '2.7.0' 4 | id 'io.spring.dependency-management' version '1.0.11.RELEASE' 5 | } 6 | 7 | dependencies { 8 | implementation project(':domain') 9 | implementation project(':persistent:mybatis') 10 | implementation project(':api') 11 | 12 | implementation 'org.springframework.boot:spring-boot-starter-hateoas' 13 | implementation 'org.springframework.boot:spring-boot-starter-jersey' 14 | implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.2.2' 15 | implementation 'com.h2database:h2' 16 | implementation 'org.flywaydb:flyway-core' 17 | 18 | } 19 | -------------------------------------------------------------------------------- /main/src/main/java/reengineering/ddd/accounting/Application.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class Application { 8 | public static void main(String[] args) { 9 | SpringApplication.run(Application.class, args); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /main/src/main/java/reengineering/ddd/accounting/config/HAL.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting.config; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import org.springframework.beans.factory.InitializingBean; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.context.annotation.Configuration; 7 | import org.springframework.hateoas.mediatype.MessageResolver; 8 | import org.springframework.hateoas.mediatype.hal.CurieProvider; 9 | import org.springframework.hateoas.mediatype.hal.Jackson2HalModule; 10 | import org.springframework.hateoas.server.LinkRelationProvider; 11 | import reengineering.ddd.accounting.api.representation.SourceEvidenceJsonReader; 12 | import reengineering.ddd.accounting.api.representation.SourceEvidenceReader; 13 | 14 | import javax.inject.Inject; 15 | 16 | @Configuration 17 | public class HAL implements InitializingBean { 18 | 19 | private ObjectMapper mapper; 20 | private LinkRelationProvider provider; 21 | private MessageResolver resolver; 22 | 23 | @Inject 24 | public HAL(ObjectMapper mapper, LinkRelationProvider provider, MessageResolver resolver) { 25 | this.mapper = mapper; 26 | this.provider = provider; 27 | this.resolver = resolver; 28 | } 29 | 30 | @Override 31 | public void afterPropertiesSet() { 32 | mapper.registerModule(new Jackson2HalModule()); 33 | mapper.setHandlerInstantiator(new Jackson2HalModule.HalHandlerInstantiator(provider, CurieProvider.NONE, resolver)); 34 | } 35 | 36 | @Bean 37 | public SourceEvidenceReader reader() { 38 | return new SourceEvidenceJsonReader(mapper); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /main/src/main/java/reengineering/ddd/accounting/config/Jersey.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting.config; 2 | 3 | import org.glassfish.jersey.server.ResourceConfig; 4 | import org.glassfish.jersey.server.ServerProperties; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.hateoas.config.EnableHypermediaSupport; 7 | import reengineering.ddd.accounting.api.CustomersApi; 8 | 9 | import java.util.Map; 10 | 11 | import static org.springframework.hateoas.config.EnableHypermediaSupport.HypermediaType.HAL; 12 | 13 | @Configuration 14 | @EnableHypermediaSupport(type = HAL) 15 | public class Jersey extends ResourceConfig { 16 | public Jersey() { 17 | setProperties(Map.of(ServerProperties.RESPONSE_SET_STATUS_OVER_SEND_ERROR, true)); 18 | register(CustomersApi.class); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /main/src/main/java/reengineering/ddd/accounting/config/MyBatis.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting.config; 2 | 3 | 4 | import org.springframework.context.annotation.ComponentScan; 5 | import org.springframework.context.annotation.Configuration; 6 | 7 | @Configuration 8 | @ComponentScan({"reengineering.ddd.accounting.mybatis", "reengineering.ddd.mybatis.support"}) 9 | public class MyBatis { 10 | } 11 | -------------------------------------------------------------------------------- /main/src/main/java/reengineering/ddd/accounting/test/TestDataMapper.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting.test; 2 | 3 | import org.apache.ibatis.annotations.Insert; 4 | import org.apache.ibatis.annotations.Mapper; 5 | import org.apache.ibatis.annotations.Param; 6 | 7 | @Mapper 8 | public interface TestDataMapper { 9 | @Insert("INSERT INTO customers(id, name, email) VALUES(#{id}, #{name}, #{email})") 10 | void insertCustomer(@Param("id") String id, @Param("name") String name, @Param("email") String email); 11 | 12 | @Insert("INSERT INTO accounts(id, customer_id, current_amount, current_currency) VALUES(#{id}, #{customer_id}, #{current_amount}, #{current_currency})") 13 | void insertAccount(@Param("id") String id, @Param("customer_id") String customerId, @Param("current_amount") double amount, @Param("current_currency") String currency); 14 | } 15 | -------------------------------------------------------------------------------- /main/src/main/java/reengineering/ddd/accounting/test/TestDataRunner.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting.test; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.boot.CommandLineRunner; 6 | import org.springframework.stereotype.Component; 7 | import reengineering.ddd.accounting.description.SalesSettlementDescription; 8 | import reengineering.ddd.accounting.description.basic.Amount; 9 | import reengineering.ddd.accounting.description.basic.Ref; 10 | import reengineering.ddd.accounting.model.Customer; 11 | import reengineering.ddd.accounting.model.Customers; 12 | 13 | import javax.inject.Inject; 14 | import java.util.Random; 15 | 16 | @Component 17 | public class TestDataRunner implements CommandLineRunner { 18 | 19 | private Logger logger = LoggerFactory.getLogger(TestDataRunner.class); 20 | 21 | 22 | private TestDataMapper mapper; 23 | private Customers customers; 24 | 25 | @Inject 26 | public TestDataRunner(TestDataMapper mapper, Customers customers) { 27 | this.mapper = mapper; 28 | this.customers = customers; 29 | } 30 | 31 | @Override 32 | public void run(String... args) throws Exception { 33 | logger.info("Insert test data"); 34 | 35 | String customerId = "1"; 36 | String accountId = "1"; 37 | 38 | mapper.insertCustomer(customerId, "John Smith", "john.smith@email.com"); 39 | mapper.insertAccount(accountId, customerId, 100.00, "CNY"); 40 | 41 | Customer customer = customers.findById(customerId).get(); 42 | 43 | for (var evidence = 0; evidence < 1000; evidence++) { 44 | var description = new SalesSettlementDescription(new Ref<>("ORD-" + new Random().nextInt()), 45 | Amount.cny("500.00"), new Ref<>(accountId), 46 | new SalesSettlementDescription.Detail(Amount.cny("100.00")), 47 | new SalesSettlementDescription.Detail(Amount.cny("100.00")), 48 | new SalesSettlementDescription.Detail(Amount.cny("100.00")), 49 | new SalesSettlementDescription.Detail(Amount.cny("100.00")), 50 | new SalesSettlementDescription.Detail(Amount.cny("100.00")) 51 | ); 52 | 53 | customer.add(description); 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /main/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8080 3 | servlet: 4 | context-path: /api 5 | spring: 6 | main: 7 | banner-mode: "off" 8 | datasource: 9 | driver-class-name: org.h2.Driver 10 | url: jdbc:h2:mem:accounting;MODE=MySQL 11 | username: sa 12 | password: sa 13 | mybatis: 14 | mapper-locations: classpath:mybatis/mapper/**/*.xml 15 | configuration: 16 | object-factory: reengineering.ddd.mybatis.support.InjectableObjectFactory 17 | logging: 18 | level: 19 | root: info 20 | 21 | 22 | -------------------------------------------------------------------------------- /persistent/mybatis/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'reengineering.ddd' 3 | id 'java-library' 4 | id 'org.springframework.boot' version '2.7.0' 5 | id 'io.spring.dependency-management' version '1.0.11.RELEASE' 6 | } 7 | 8 | dependencies { 9 | implementation project(':domain') 10 | implementation 'javax.inject:javax.inject:1' 11 | implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.2.2' 12 | implementation 'org.flywaydb:flyway-core' 13 | implementation 'javassist:javassist:3.12.1.GA' 14 | 15 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 16 | testImplementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter-test:2.2.2' 17 | testImplementation 'com.h2database:h2' 18 | } -------------------------------------------------------------------------------- /persistent/mybatis/src/main/java/reengineering/ddd/accounting/mybatis/ModelMapper.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting.mybatis; 2 | 3 | import org.apache.ibatis.annotations.Mapper; 4 | import org.apache.ibatis.annotations.Param; 5 | import reengineering.ddd.accounting.description.SourceEvidenceDescription; 6 | import reengineering.ddd.accounting.description.TransactionDescription; 7 | import reengineering.ddd.accounting.model.Account; 8 | import reengineering.ddd.accounting.model.Customer; 9 | import reengineering.ddd.accounting.model.SourceEvidence; 10 | import reengineering.ddd.accounting.model.Transaction; 11 | import reengineering.ddd.mybatis.support.IdHolder; 12 | 13 | import java.util.List; 14 | 15 | @Mapper 16 | public interface ModelMapper { 17 | Customer findCustomerById(String id); 18 | 19 | List> findSourceEvidencesByCustomerId(@Param("customer_id") String customerId, 20 | @Param("from") int from, 21 | @Param("size") int size); 22 | 23 | 24 | SourceEvidence findSourceEvidenceByCustomerAndId(@Param("customer_id") String customerId, @Param("id") String id); 25 | 26 | List findTransactionsByAccountId(@Param("account_id") String accountId, 27 | @Param("from") int from, 28 | @Param("size") int size); 29 | 30 | List findTransactionsBySourceEvidenceId(String evidenceId); 31 | 32 | Transaction findTransactionByAccountAndId(@Param("account_id") String accountId, @Param("id") String transactionId); 33 | 34 | Transaction findTransactionByEvidenceAndId(@Param("evidence_id") String evidenceId, @Param("id") String transactionId); 35 | 36 | void insertTransaction(@Param("holder") IdHolder id, 37 | @Param("account_id") String accountId, 38 | @Param("evidence_id") String evidenceId, 39 | @Param("description") TransactionDescription transactionDescription); 40 | 41 | void insertSourceEvidence(@Param("holder") IdHolder id, @Param("customer_id") String customerId, @Param("description") SourceEvidenceDescription description); 42 | 43 | void insertSourceEvidenceDescription(@Param("id") String id, @Param("description") SourceEvidenceDescription description); 44 | 45 | void updateAccount(@Param("customer_id") String customerId, @Param("id") String accountId, @Param("change") Account.AccountChange change); 46 | 47 | int countTransactionsInAccount(String accountId); 48 | 49 | int countSourceEvidencesByCustomer(String customerId); 50 | 51 | int countTransactionsBySourceEvidence(String sourceEvidenceId); 52 | } 53 | -------------------------------------------------------------------------------- /persistent/mybatis/src/main/java/reengineering/ddd/accounting/mybatis/associations/AccountTransactions.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting.mybatis.associations; 2 | 3 | import reengineering.ddd.accounting.description.TransactionDescription; 4 | import reengineering.ddd.accounting.model.Account; 5 | import reengineering.ddd.accounting.model.SourceEvidence; 6 | import reengineering.ddd.accounting.model.Transaction; 7 | import reengineering.ddd.accounting.mybatis.ModelMapper; 8 | import reengineering.ddd.mybatis.database.EntityList; 9 | import reengineering.ddd.mybatis.support.IdHolder; 10 | 11 | import javax.inject.Inject; 12 | import java.util.List; 13 | 14 | public class AccountTransactions extends EntityList implements Account.Transactions { 15 | private String accountId; 16 | 17 | @Inject 18 | private ModelMapper mapper; 19 | 20 | @Override 21 | protected List findEntities(int from, int to) { 22 | return mapper.findTransactionsByAccountId(accountId, from, to - from); 23 | } 24 | 25 | @Override 26 | protected Transaction findEntity(String id) { 27 | return mapper.findTransactionByAccountAndId(accountId, id); 28 | } 29 | 30 | @Override 31 | public int size() { 32 | return mapper.countTransactionsInAccount(accountId); 33 | } 34 | 35 | @Override 36 | public Transaction add(Account account, SourceEvidence evidence, TransactionDescription description) { 37 | IdHolder holder = new IdHolder(); 38 | mapper.insertTransaction(holder, account.getIdentity(), evidence.getIdentity(), description); 39 | return mapper.findTransactionByAccountAndId(accountId, holder.id()); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /persistent/mybatis/src/main/java/reengineering/ddd/accounting/mybatis/associations/CustomerAccounts.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting.mybatis.associations; 2 | 3 | import reengineering.ddd.accounting.model.Account; 4 | import reengineering.ddd.accounting.model.Customer; 5 | import reengineering.ddd.accounting.mybatis.ModelMapper; 6 | import reengineering.ddd.mybatis.memory.EntityList; 7 | 8 | import javax.inject.Inject; 9 | 10 | public class CustomerAccounts extends EntityList implements Customer.Accounts { 11 | 12 | @Inject 13 | private ModelMapper mapper; 14 | 15 | private String customerId; 16 | 17 | @Override 18 | public void update(Account account, Account.AccountChange change) { 19 | mapper.updateAccount(customerId, account.getIdentity(), change); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /persistent/mybatis/src/main/java/reengineering/ddd/accounting/mybatis/associations/CustomerSourceEvidences.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting.mybatis.associations; 2 | 3 | import reengineering.ddd.accounting.description.SourceEvidenceDescription; 4 | import reengineering.ddd.accounting.model.Customer; 5 | import reengineering.ddd.accounting.model.SourceEvidence; 6 | import reengineering.ddd.accounting.mybatis.ModelMapper; 7 | import reengineering.ddd.mybatis.database.EntityList; 8 | import reengineering.ddd.mybatis.support.IdHolder; 9 | 10 | import javax.inject.Inject; 11 | import java.util.List; 12 | 13 | public class CustomerSourceEvidences extends EntityList> implements Customer.SourceEvidences { 14 | private String customerId; 15 | 16 | @Inject 17 | private ModelMapper mapper; 18 | 19 | @Override 20 | protected List> findEntities(int from, int to) { 21 | return mapper.findSourceEvidencesByCustomerId(customerId, from, to - from); 22 | } 23 | 24 | @Override 25 | protected SourceEvidence findEntity(String id) { 26 | return mapper.findSourceEvidenceByCustomerAndId(customerId, id); 27 | } 28 | 29 | @Override 30 | public SourceEvidence add(SourceEvidenceDescription description) { 31 | IdHolder holder = new IdHolder(); 32 | mapper.insertSourceEvidence(holder, customerId, description); 33 | mapper.insertSourceEvidenceDescription(holder.id(), description); 34 | return mapper.findSourceEvidenceByCustomerAndId(customerId, holder.id()); 35 | } 36 | 37 | @Override 38 | public int size() { 39 | return mapper.countSourceEvidencesByCustomer(customerId); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /persistent/mybatis/src/main/java/reengineering/ddd/accounting/mybatis/associations/Customers.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting.mybatis.associations; 2 | 3 | import org.springframework.stereotype.Component; 4 | import reengineering.ddd.accounting.model.Customer; 5 | import reengineering.ddd.accounting.mybatis.ModelMapper; 6 | 7 | import javax.inject.Inject; 8 | import java.util.Optional; 9 | 10 | 11 | @Component 12 | public class Customers implements reengineering.ddd.accounting.model.Customers { 13 | private ModelMapper mapper; 14 | 15 | @Inject 16 | public Customers(ModelMapper mapper) { 17 | this.mapper = mapper; 18 | } 19 | 20 | @Override 21 | public Optional findById(String id) { 22 | return Optional.ofNullable(mapper.findCustomerById(id)); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /persistent/mybatis/src/main/java/reengineering/ddd/accounting/mybatis/associations/SourceEvidenceTransactions.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting.mybatis.associations; 2 | 3 | import reengineering.ddd.accounting.model.SourceEvidence; 4 | import reengineering.ddd.accounting.model.Transaction; 5 | import reengineering.ddd.mybatis.memory.EntityList; 6 | 7 | public class SourceEvidenceTransactions extends EntityList implements SourceEvidence.Transactions { 8 | } 9 | -------------------------------------------------------------------------------- /persistent/mybatis/src/main/java/reengineering/ddd/mybatis/database/EntityList.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.mybatis.database; 2 | 3 | import reengineering.ddd.archtype.Entity; 4 | import reengineering.ddd.archtype.HasMany; 5 | import reengineering.ddd.archtype.Many; 6 | 7 | import java.util.Iterator; 8 | import java.util.List; 9 | import java.util.Optional; 10 | 11 | public abstract class EntityList> implements Many, HasMany { 12 | @Override 13 | public final Many findAll() { 14 | return this; 15 | } 16 | 17 | @Override 18 | public final Optional findByIdentity(Id identifier) { 19 | return Optional.ofNullable(findEntity(identifier)); 20 | } 21 | 22 | @Override 23 | public final Many subCollection(int from, int to) { 24 | return new reengineering.ddd.mybatis.memory.EntityList<>(findEntities(from, to)); 25 | } 26 | 27 | @Override 28 | public final Iterator iterator() { 29 | return new BatchIterator(); 30 | } 31 | 32 | private class BatchIterator implements Iterator { 33 | 34 | private Iterator iterator; 35 | private int size; 36 | private int current = 0; 37 | 38 | public BatchIterator() { 39 | this.size = size(); 40 | this.iterator = nextBatch(); 41 | } 42 | 43 | private Iterator nextBatch() { 44 | return subCollection(current, Math.min(current + batchSize(), size)).iterator(); 45 | } 46 | 47 | @Override 48 | public boolean hasNext() { 49 | return current < size; 50 | } 51 | 52 | @Override 53 | public E next() { 54 | if (!iterator.hasNext()) iterator = nextBatch(); 55 | current++; 56 | return iterator.next(); 57 | } 58 | } 59 | 60 | protected int batchSize() { 61 | return 100; 62 | } 63 | 64 | protected abstract List findEntities(int from, int to); 65 | 66 | protected abstract E findEntity(Id id); 67 | } 68 | -------------------------------------------------------------------------------- /persistent/mybatis/src/main/java/reengineering/ddd/mybatis/memory/EntityList.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.mybatis.memory; 2 | 3 | import reengineering.ddd.archtype.Entity; 4 | import reengineering.ddd.archtype.HasMany; 5 | import reengineering.ddd.archtype.Many; 6 | 7 | import java.util.ArrayList; 8 | import java.util.Iterator; 9 | import java.util.List; 10 | import java.util.Optional; 11 | 12 | public class EntityList> implements Many, HasMany { 13 | private List list = new ArrayList<>(); 14 | 15 | public EntityList() { 16 | } 17 | 18 | public EntityList(List list) { 19 | this.list = list; 20 | } 21 | 22 | @Override 23 | public int size() { 24 | return list.size(); 25 | } 26 | 27 | @Override 28 | public Many subCollection(int from, int to) { 29 | return new EntityList<>(list.subList(from, to)); 30 | } 31 | 32 | @Override 33 | public Iterator iterator() { 34 | return list.iterator(); 35 | } 36 | 37 | @Override 38 | public Many findAll() { 39 | return this; 40 | } 41 | 42 | @Override 43 | public Optional findByIdentity(Id identifier) { 44 | return stream().filter(it -> it.getIdentity().equals(identifier)).findFirst(); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /persistent/mybatis/src/main/java/reengineering/ddd/mybatis/memory/Reference.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.mybatis.memory; 2 | 3 | import reengineering.ddd.archtype.Entity; 4 | import reengineering.ddd.archtype.HasOne; 5 | 6 | public class Reference> implements HasOne { 7 | private E entity; 8 | 9 | @Override 10 | public E get() { 11 | return entity; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /persistent/mybatis/src/main/java/reengineering/ddd/mybatis/support/IdHolder.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.mybatis.support; 2 | 3 | public class IdHolder { 4 | private Long id; 5 | 6 | public String id() { 7 | return id.toString(); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /persistent/mybatis/src/main/java/reengineering/ddd/mybatis/support/InjectableObjectFactory.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.mybatis.support; 2 | 3 | import org.apache.ibatis.reflection.factory.DefaultObjectFactory; 4 | import org.springframework.beans.BeansException; 5 | import org.springframework.context.ApplicationContext; 6 | import org.springframework.context.ApplicationContextAware; 7 | import org.springframework.stereotype.Component; 8 | 9 | import java.util.List; 10 | 11 | @Component 12 | public class InjectableObjectFactory extends DefaultObjectFactory implements ApplicationContextAware { 13 | 14 | private ApplicationContext context; 15 | 16 | @Override 17 | public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { 18 | this.context = applicationContext; 19 | } 20 | 21 | @Override 22 | public T create(Class type) { 23 | T object = super.create(type); 24 | this.context.getAutowireCapableBeanFactory().autowireBean(object); 25 | return object; 26 | } 27 | 28 | @Override 29 | public T create(Class type, List> constructorArgTypes, List constructorArgs) { 30 | T object = super.create(type, constructorArgTypes, constructorArgs); 31 | this.context.getAutowireCapableBeanFactory().autowireBean(object); 32 | return object; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /persistent/mybatis/src/main/java/reengineering/ddd/mybatis/support/ObjectFactoryConverter.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.mybatis.support; 2 | 3 | import org.apache.ibatis.reflection.factory.ObjectFactory; 4 | import org.springframework.beans.BeansException; 5 | import org.springframework.boot.context.properties.ConfigurationPropertiesBinding; 6 | import org.springframework.context.ApplicationContext; 7 | import org.springframework.context.ApplicationContextAware; 8 | import org.springframework.core.convert.converter.Converter; 9 | import org.springframework.stereotype.Component; 10 | 11 | @Component 12 | @ConfigurationPropertiesBinding 13 | public class ObjectFactoryConverter implements Converter, ApplicationContextAware { 14 | 15 | private ApplicationContext context; 16 | 17 | @Override 18 | public ObjectFactory convert(String source) { 19 | try { 20 | ObjectFactory factory = (ObjectFactory) Class.forName(source).getDeclaredConstructor().newInstance(); 21 | if (factory instanceof ApplicationContextAware applicationContextAware) 22 | applicationContextAware.setApplicationContext(context); 23 | return factory; 24 | } catch (Exception e) { 25 | return null; 26 | } 27 | } 28 | 29 | @Override 30 | public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { 31 | this.context = applicationContext; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /persistent/mybatis/src/main/resources/db/migration/V01__create_customers.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE `customers` 2 | ( 3 | `id` BIGINT NOT NULL PRIMARY KEY, 4 | `name` VARCHAR(255) NOT NULL, 5 | `email` VARCHAR(255) NOT NULL 6 | ); 7 | 8 | -------------------------------------------------------------------------------- /persistent/mybatis/src/main/resources/db/migration/V02__create_source_evidences.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE `source_evidences` 2 | ( 3 | `id` BIGINT AUTO_INCREMENT NOT NULL PRIMARY KEY, 4 | `customer_id` BIGINT NOT NULL, 5 | `type` VARCHAR(255) NOT NULL 6 | ); 7 | 8 | -------------------------------------------------------------------------------- /persistent/mybatis/src/main/resources/db/migration/V03__create_sales_settlements.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE `sales_settlements` 2 | ( 3 | `id` BIGINT NOT NULL PRIMARY KEY, 4 | `order_id` VARCHAR(255) NOT NULL, 5 | `account_id` VARCHAR(255) NOT NULL, 6 | `total_amount` DECIMAL(12, 2) NOT NULL, 7 | `total_currency` VARCHAR(255) NOT NULL 8 | ); 9 | 10 | CREATE TABLE `sales_settlement_details` 11 | ( 12 | `id` BIGINT AUTO_INCREMENT NOT NULL PRIMARY KEY, 13 | `sales_settlement_id` BIGINT NOT NULL, 14 | `amount` DECIMAL(12, 2) NOT NULL, 15 | `currency` VARCHAR(255) NOT NULL 16 | ); 17 | -------------------------------------------------------------------------------- /persistent/mybatis/src/main/resources/db/migration/V04__create_accounts.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE `accounts` 2 | ( 3 | `id` BIGINT NOT NULL PRIMARY KEY, 4 | `customer_id` BIGINT NOT NULL, 5 | `current_amount` DECIMAL(12, 2) NOT NULL, 6 | `current_currency` VARCHAR(255) NOT NULL 7 | ); -------------------------------------------------------------------------------- /persistent/mybatis/src/main/resources/db/migration/V05__create_transactions.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE `transactions` 2 | ( 3 | `id` BIGINT AUTO_INCREMENT NOT NULL PRIMARY KEY, 4 | `account_id` BIGINT NOT NULL, 5 | `source_evidence_id` BIGINT NOT NULL, 6 | `amount` DECIMAL(12, 2) NOT NULL, 7 | `currency` VARCHAR(255) NOT NULL, 8 | `created_at` TIMESTAMP NOT NULL 9 | 10 | ) -------------------------------------------------------------------------------- /persistent/mybatis/src/main/resources/mybatis/mapper/Description.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 28 | 29 | 30 | 31 | 33 | 34 | 35 | 36 | 37 | 40 | 41 | 42 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /persistent/mybatis/src/main/resources/mybatis/mapper/Model.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 73 | 74 | -------------------------------------------------------------------------------- /persistent/mybatis/src/main/resources/mybatis/mapper/ModelMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 15 | 16 | 35 | 36 | 55 | 56 | 75 | 76 | 94 | 95 | 114 | 115 | 134 | 135 | 137 | insert into transactions (account_id, source_evidence_id, amount, currency, created_at) 138 | values (#{account_id}, #{evidence_id}, 139 | #{description.amount.value}, #{description.amount.currency}, #{description.createdAt}); 140 | 141 | 142 | 144 | 145 | insert into source_evidences (customer_id, `type`) 146 | values (#{customer_id}, 147 | 148 | 149 | 'sales-settlement' 150 | 151 | 152 | ); 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | update accounts 165 | set current_amount = current_amount + #{change.total.value} 166 | where customer_id = #{customer_id} 167 | and id = #{id}; 168 | 169 | 170 | 171 | insert into sales_settlements (id, order_id, account_id, total_amount, total_currency) 172 | values (#{id}, #{description.order.id}, #{description.account.id}, #{description.total.value}, 173 | #{description.total.currency}); 174 | insert into sales_settlement_details(sales_settlement_id, amount, currency) values 175 | 176 | (#{id}, #{detail.amount.value}, #{detail.amount.currency}) 177 | 178 | 179 | 180 | 185 | 186 | 191 | 192 | 197 | 198 | 199 | -------------------------------------------------------------------------------- /persistent/mybatis/src/test/java/reengineering/ddd/accounting/AssociationsTest.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting; 2 | 3 | import org.junit.jupiter.api.BeforeEach; 4 | import org.junit.jupiter.api.Test; 5 | import org.junit.jupiter.api.extension.ExtendWith; 6 | import org.mybatis.spring.boot.test.autoconfigure.MybatisTest; 7 | import org.springframework.context.annotation.Import; 8 | import reengineering.ddd.accounting.description.basic.Amount; 9 | import reengineering.ddd.accounting.model.*; 10 | import reengineering.ddd.accounting.mybatis.associations.Customers; 11 | import reengineering.ddd.archtype.Many; 12 | 13 | import javax.inject.Inject; 14 | import java.util.Iterator; 15 | import java.util.Optional; 16 | 17 | import static org.junit.jupiter.api.Assertions.assertEquals; 18 | import static org.junit.jupiter.api.Assertions.assertTrue; 19 | 20 | @MybatisTest 21 | @Import(FlywayConfig.class) 22 | @ExtendWith(TestDataSetup.class) 23 | public class AssociationsTest { 24 | 25 | @Inject 26 | private Customers customers; 27 | 28 | private String customerId = "1"; 29 | private String accountId = "1"; 30 | 31 | private Customer customer; 32 | 33 | @BeforeEach 34 | public void setup() { 35 | customer = customers.findById(customerId).get(); 36 | } 37 | 38 | 39 | @Test 40 | public void should_find_customer_by_id() { 41 | assertEquals("1", customer.getIdentity()); 42 | assertEquals("John Smith", customer.getDescription().name()); 43 | assertEquals("john.smith@email.com", customer.getDescription().email()); 44 | } 45 | 46 | @Test 47 | public void should_not_find_customer_if_not_exist() { 48 | assertTrue(customers.findById("-1").isEmpty()); 49 | } 50 | 51 | @Test 52 | public void should_get_accounts() { 53 | assertEquals(1, customer.accounts().findAll().size()); 54 | } 55 | 56 | @Test 57 | public void should_find_account_by_id() { 58 | assertTrue(customer.accounts().findByIdentity(accountId).isPresent()); 59 | } 60 | 61 | @Test 62 | public void should_not_find_account_if_not_exist() { 63 | assertTrue(customer.accounts().findByIdentity("-1").isEmpty()); 64 | } 65 | 66 | @Test 67 | public void should_get_transactions_in_account() { 68 | Account account = customer.accounts().findByIdentity(accountId).get(); 69 | assertEquals(5000, account.transactions().findAll().size()); 70 | } 71 | 72 | @Test 73 | public void should_find_transaction_from_account() { 74 | Account account = customer.accounts().findByIdentity(accountId).get(); 75 | String transactionId = account.transactions().findAll().iterator().next().getIdentity(); 76 | Transaction transaction = account.transactions().findByIdentity(transactionId).get(); 77 | 78 | assertEquals(Amount.cny("100.00"), transaction.getDescription().amount()); 79 | SalesSettlement evidence = (SalesSettlement) transaction.sourceEvidence(); 80 | assertEquals(Amount.cny("500.00"), evidence.getDescription().getTotal()); 81 | } 82 | 83 | @Test 84 | public void should_not_find_transaction_from_account_if_not_exist() { 85 | Account account = customer.accounts().findByIdentity(accountId).get(); 86 | assertTrue(account.transactions().findByIdentity("-1").isEmpty()); 87 | } 88 | 89 | @Test 90 | public void should_find_transactions_in_account() { 91 | Account account = customer.accounts().findByIdentity(accountId).get(); 92 | 93 | Many transactions = account.transactions().findAll().subCollection(0, 100); 94 | assertEquals(100, transactions.size()); 95 | } 96 | 97 | @Test 98 | public void should_iterate_over_all_transaction_in_account() { 99 | Account account = customer.accounts().findByIdentity(accountId).get(); 100 | 101 | Iterator iterator = account.transactions().findAll().iterator(); 102 | int count = 0; 103 | while (iterator.hasNext()) { 104 | iterator.next(); 105 | count++; 106 | } 107 | 108 | assertEquals(5000, count); 109 | } 110 | 111 | @Test 112 | public void should_get_source_evidences_of_customer() { 113 | assertEquals(1000, customer.sourceEvidences().findAll().size()); 114 | } 115 | 116 | @Test 117 | public void should_find_source_evidences_of_customer() { 118 | Many> evidences = customer.sourceEvidences().findAll().subCollection(0, 100); 119 | assertEquals(100, evidences.size()); 120 | } 121 | 122 | @Test 123 | public void should_find_source_evidence_of_customer() { 124 | String identity = customer.sourceEvidences().findAll().iterator().next().getIdentity(); 125 | SourceEvidence sourceEvidence = customer.sourceEvidences().findByIdentity(identity).get(); 126 | 127 | assertEquals(5, sourceEvidence.transactions().findAll().size()); 128 | assertEquals(3, sourceEvidence.transactions().findAll().subCollection(0, 3).size()); 129 | } 130 | 131 | @Test 132 | public void should_not_find_source_evidence_of_customer_if_not_exist() { 133 | Optional> sourceEvidence = customer.sourceEvidences().findByIdentity("-1"); 134 | assertTrue(sourceEvidence.isEmpty()); 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /persistent/mybatis/src/test/java/reengineering/ddd/accounting/FlywayConfig.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting; 2 | 3 | import org.springframework.boot.autoconfigure.flyway.FlywayMigrationStrategy; 4 | import org.springframework.boot.test.context.TestConfiguration; 5 | import org.springframework.context.annotation.Bean; 6 | 7 | @TestConfiguration 8 | public class FlywayConfig { 9 | @Bean 10 | public static FlywayMigrationStrategy cleanMigrateStrategy() { 11 | 12 | return flyway -> { 13 | flyway.clean(); 14 | flyway.migrate(); 15 | }; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /persistent/mybatis/src/test/java/reengineering/ddd/accounting/ModelMapperTest.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting; 2 | 3 | import org.junit.jupiter.api.BeforeEach; 4 | import org.junit.jupiter.api.Test; 5 | import org.mybatis.spring.boot.test.autoconfigure.MybatisTest; 6 | import reengineering.ddd.accounting.description.SalesSettlementDescription; 7 | import reengineering.ddd.accounting.description.TransactionDescription; 8 | import reengineering.ddd.accounting.description.basic.Amount; 9 | import reengineering.ddd.accounting.description.basic.Ref; 10 | import reengineering.ddd.accounting.model.*; 11 | import reengineering.ddd.accounting.mybatis.ModelMapper; 12 | import reengineering.ddd.archtype.Many; 13 | import reengineering.ddd.mybatis.support.IdHolder; 14 | 15 | import javax.inject.Inject; 16 | import java.time.LocalDateTime; 17 | import java.util.List; 18 | import java.util.Random; 19 | 20 | import static org.junit.jupiter.api.Assertions.assertEquals; 21 | import static org.junit.jupiter.api.Assertions.assertTrue; 22 | 23 | @MybatisTest 24 | public class ModelMapperTest { 25 | @Inject 26 | private ModelMapper mapper; 27 | @Inject 28 | private TestDataMapper testData; 29 | 30 | private String detailId = id(); 31 | private String customerId = id(); 32 | private String orderId = "ORD-001"; 33 | private String accountId = id(); 34 | private String evidenceId = id(); 35 | private String transactionId = id(); 36 | private LocalDateTime createdAt = LocalDateTime.now(); 37 | 38 | private static String id() { 39 | return String.valueOf(new Random().nextInt(100000)); 40 | } 41 | 42 | @BeforeEach 43 | public void before() { 44 | testData.insertCustomer(customerId, "John Smith", "john.smith@email.com"); 45 | testData.insertAccount(accountId, customerId, 100.00, "CNY"); 46 | testData.insertTransaction(transactionId, accountId, evidenceId, 100.00, "CNY", createdAt); 47 | testData.insertSourceEvidence(evidenceId, customerId, "sales-settlement"); 48 | testData.insertSalesSettlement(evidenceId, orderId, accountId, 100.00, "CNY"); 49 | testData.insertSalesSettlementDetail(detailId, evidenceId, 100.00, "CNY"); 50 | } 51 | 52 | @Test 53 | public void should_find_customer_by_id() { 54 | Customer customer = mapper.findCustomerById(customerId); 55 | assertEquals(customerId, customer.getIdentity()); 56 | assertEquals("John Smith", customer.getDescription().name()); 57 | assertEquals("john.smith@email.com", customer.getDescription().email()); 58 | } 59 | 60 | @Test 61 | public void should_assign_source_evidences_association() { 62 | Customer customer = mapper.findCustomerById(customerId); 63 | 64 | Many> evidences = customer.sourceEvidences().findAll(); 65 | 66 | assertEquals(1, evidences.size()); 67 | } 68 | 69 | @Test 70 | public void should_assign_accounts_association() { 71 | Customer customer = mapper.findCustomerById(customerId); 72 | assertEquals(1, customer.accounts().findAll().size()); 73 | 74 | Account customerAccount = customer.accounts().findByIdentity(accountId).get(); 75 | assertEquals(Amount.cny("100.00"), customerAccount.getDescription().current()); 76 | } 77 | 78 | @Test 79 | public void should_read_sales_settlements_as_source_evidences() { 80 | List> evidences = mapper.findSourceEvidencesByCustomerId(customerId, 0, 100); 81 | assertEquals(1, evidences.size()); 82 | 83 | SalesSettlement salesSettlement = (SalesSettlement) evidences.get(0); 84 | assertEquals(evidenceId, salesSettlement.getIdentity()); 85 | assertEquals(orderId, salesSettlement.getDescription().getOrder().id()); 86 | assertEquals(accountId, salesSettlement.getDescription().getAccount().id()); 87 | assertEquals(Amount.cny("100.00"), salesSettlement.getDescription().getTotal()); 88 | 89 | assertEquals(1, salesSettlement.getDescription().getDetails().size()); 90 | 91 | SalesSettlementDescription.Detail detail = salesSettlement.getDescription().getDetails().get(0); 92 | assertEquals(Amount.cny("100.00"), detail.getAmount()); 93 | } 94 | 95 | @Test 96 | public void should_read_sales_settlement_as_source_evidence() { 97 | SalesSettlement salesSettlement = (SalesSettlement) mapper.findSourceEvidenceByCustomerAndId(customerId, evidenceId); 98 | 99 | assertEquals(evidenceId, salesSettlement.getIdentity()); 100 | assertEquals(orderId, salesSettlement.getDescription().getOrder().id()); 101 | assertEquals(accountId, salesSettlement.getDescription().getAccount().id()); 102 | assertEquals(Amount.cny("100.00"), salesSettlement.getDescription().getTotal()); 103 | 104 | assertEquals(1, salesSettlement.getDescription().getDetails().size()); 105 | 106 | SalesSettlementDescription.Detail detail = salesSettlement.getDescription().getDetails().get(0); 107 | assertEquals(Amount.cny("100.00"), detail.getAmount()); 108 | } 109 | 110 | @Test 111 | public void should_find_transactions_by_account_id() { 112 | List transactions = mapper.findTransactionsByAccountId(accountId, 0, 100); 113 | 114 | assertEquals(1, transactions.size()); 115 | Transaction transaction = transactions.get(0); 116 | 117 | assertEquals(Amount.cny("100.00"), transaction.getDescription().amount()); 118 | assertEquals(createdAt, transaction.getDescription().createdAt()); 119 | 120 | SourceEvidence evidence = transaction.sourceEvidence(); 121 | assertEquals(evidenceId, evidence.getIdentity()); 122 | assertTrue(evidence instanceof SalesSettlement); 123 | 124 | assertEquals(accountId, transaction.account().getIdentity()); 125 | } 126 | 127 | @Test 128 | public void should_find_transactions_by_source_evidence_id() { 129 | List transactions = mapper.findTransactionsBySourceEvidenceId(evidenceId); 130 | 131 | assertEquals(1, transactions.size()); 132 | Transaction transaction = transactions.get(0); 133 | 134 | assertEquals(Amount.cny("100.00"), transaction.getDescription().amount()); 135 | assertEquals(createdAt, transaction.getDescription().createdAt()); 136 | 137 | SourceEvidence evidence = transaction.sourceEvidence(); 138 | assertEquals(evidenceId, evidence.getIdentity()); 139 | assertTrue(evidence instanceof SalesSettlement); 140 | 141 | assertEquals(accountId, transaction.account().getIdentity()); 142 | } 143 | 144 | @Test 145 | public void should_find_transaction_from_account() { 146 | Customer customer = mapper.findCustomerById(customerId); 147 | Account account = customer.accounts().findByIdentity(accountId).get(); 148 | 149 | Many transactions = account.transactions().findAll(); 150 | 151 | assertEquals(1, transactions.size()); 152 | assertEquals(transactionId, transactions.stream().toList().get(0).getIdentity()); 153 | } 154 | 155 | @Test 156 | public void should_find_transaction_from_source_evidences() { 157 | SourceEvidence evidence = mapper.findSourceEvidencesByCustomerId(customerId, 0, 100).get(0); 158 | 159 | Many transactions = evidence.transactions().findAll(); 160 | 161 | assertEquals(1, transactions.size()); 162 | assertEquals(transactionId, transactions.stream().toList().get(0).getIdentity()); 163 | } 164 | 165 | @Test 166 | public void should_find_account_transaction_by_account_and_transaction_id() { 167 | Transaction transaction = mapper.findTransactionByAccountAndId(accountId, transactionId); 168 | assertEquals(transactionId, transaction.getIdentity()); 169 | assertEquals(Amount.cny("100.00"), transaction.getDescription().amount()); 170 | assertEquals(createdAt, transaction.getDescription().createdAt()); 171 | } 172 | 173 | @Test 174 | public void should_find_account_transaction_by_evidence_transaction_id() { 175 | Transaction transaction = mapper.findTransactionByEvidenceAndId(evidenceId, transactionId); 176 | assertEquals(transactionId, transaction.getIdentity()); 177 | assertEquals(Amount.cny("100.00"), transaction.getDescription().amount()); 178 | assertEquals(createdAt, transaction.getDescription().createdAt()); 179 | } 180 | 181 | @Test 182 | public void should_add_transaction_to_database() { 183 | IdHolder holder = new IdHolder(); 184 | LocalDateTime created = LocalDateTime.now(); 185 | mapper.insertTransaction(holder, accountId, evidenceId, new TransactionDescription(Amount.cny("400.00"), created)); 186 | 187 | Transaction transaction = mapper.findTransactionByAccountAndId(accountId, holder.id()); 188 | assertEquals(Amount.cny("400.00"), transaction.getDescription().amount()); 189 | assertEquals(created, transaction.getDescription().createdAt()); 190 | } 191 | 192 | @Test 193 | public void should_insert_sales_settlement() { 194 | IdHolder holder = new IdHolder(); 195 | SalesSettlementDescription description = new SalesSettlementDescription(new Ref<>(orderId), 196 | Amount.cny("1000.00"), new Ref<>(accountId), new SalesSettlementDescription.Detail(Amount.cny("1000.00"))); 197 | 198 | mapper.insertSourceEvidence(holder, customerId, description); 199 | mapper.insertSourceEvidenceDescription(holder.id(), description); 200 | 201 | SalesSettlement evidence = (SalesSettlement) mapper.findSourceEvidenceByCustomerAndId(customerId, holder.id()); 202 | assertEquals(Amount.cny("1000.00"), evidence.getDescription().getTotal()); 203 | 204 | assertEquals(1, evidence.getDescription().getDetails().size()); 205 | SalesSettlementDescription.Detail detail = evidence.getDescription().getDetails().get(0); 206 | assertEquals(Amount.cny("1000.00"), detail.getAmount()); 207 | } 208 | 209 | @Test 210 | public void should_update_account_amount() { 211 | mapper.updateAccount(customerId, accountId, new Account.AccountChange(Amount.cny("100.00"))); 212 | 213 | Account account = mapper.findCustomerById(customerId).accounts().findByIdentity(accountId).get(); 214 | assertEquals(Amount.cny("200.00"), account.getDescription().current()); 215 | } 216 | 217 | @Test 218 | public void should_count_transaction_in_accounts() { 219 | assertEquals(1, mapper.countTransactionsInAccount(accountId)); 220 | } 221 | } 222 | -------------------------------------------------------------------------------- /persistent/mybatis/src/test/java/reengineering/ddd/accounting/TestApplication.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.context.annotation.ComponentScan; 6 | 7 | @SpringBootApplication 8 | @ComponentScan({"reengineering.ddd.accounting.mybatis", "reengineering.ddd.mybatis.support"}) 9 | public class TestApplication { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(TestApplication.class, args); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /persistent/mybatis/src/test/java/reengineering/ddd/accounting/TestDataMapper.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting; 2 | 3 | import org.apache.ibatis.annotations.Insert; 4 | import org.apache.ibatis.annotations.Mapper; 5 | import org.apache.ibatis.annotations.Param; 6 | 7 | import java.time.LocalDateTime; 8 | 9 | @Mapper 10 | public interface TestDataMapper { 11 | @Insert("INSERT INTO customers(id, name, email) VALUES(#{id}, #{name}, #{email})") 12 | void insertCustomer(@Param("id") String id, @Param("name") String name, @Param("email") String email); 13 | 14 | @Insert("INSERT INTO source_evidences(id, customer_id, type) VALUES(#{id}, #{customer_id}, #{type})") 15 | void insertSourceEvidence(@Param("id") String id, @Param("customer_id") String customerId, @Param("type") String type); 16 | 17 | @Insert("INSERT INTO sales_settlements(id, order_id, account_id, total_amount, total_currency) VALUES(#{id}, #{order_id}, #{account_id}, #{total_amount}, #{total_currency})") 18 | void insertSalesSettlement(@Param("id") String id, @Param("order_id") String orderId, @Param("account_id") String accountId, @Param("total_amount") double amount, @Param("total_currency") String currency); 19 | 20 | @Insert("INSERT INTO sales_settlement_details(id, sales_settlement_id, amount, currency) VALUES(#{id}, #{sales_settlement_id}, #{amount}, #{currency})") 21 | void insertSalesSettlementDetail(@Param("id") String id, @Param("sales_settlement_id") String salesSettlementId, @Param("amount") double amount, @Param("currency") String currency); 22 | 23 | @Insert("INSERT INTO accounts(id, customer_id, current_amount, current_currency) VALUES(#{id}, #{customer_id}, #{current_amount}, #{current_currency})") 24 | void insertAccount(@Param("id") String id, @Param("customer_id") String customerId, @Param("current_amount") double amount, @Param("current_currency") String currency); 25 | 26 | @Insert("INSERT INTO transactions(id, account_id, source_evidence_id, amount, currency, created_at) VALUES(#{id}, #{account_id}, #{source_evidence_id}, #{amount}, #{currency}, #{created_at})") 27 | void insertTransaction(@Param("id") String id, @Param("account_id") String accountId, @Param("source_evidence_id") String evidenceId, @Param("amount") double amount, @Param("currency") String currency, @Param("created_at") LocalDateTime createdAt); 28 | } 29 | -------------------------------------------------------------------------------- /persistent/mybatis/src/test/java/reengineering/ddd/accounting/TestDataSetup.java: -------------------------------------------------------------------------------- 1 | package reengineering.ddd.accounting; 2 | 3 | import org.junit.jupiter.api.extension.BeforeAllCallback; 4 | import org.junit.jupiter.api.extension.ExtensionContext; 5 | import org.springframework.context.ApplicationContext; 6 | import org.springframework.test.context.junit.jupiter.SpringExtension; 7 | import reengineering.ddd.accounting.description.SalesSettlementDescription; 8 | import reengineering.ddd.accounting.description.basic.Amount; 9 | import reengineering.ddd.accounting.description.basic.Ref; 10 | import reengineering.ddd.accounting.model.Customer; 11 | import reengineering.ddd.accounting.model.Customers; 12 | 13 | import java.util.Random; 14 | 15 | public class TestDataSetup implements BeforeAllCallback { 16 | 17 | @Override 18 | public void beforeAll(ExtensionContext context) throws Exception { 19 | ApplicationContext springContext = SpringExtension.getApplicationContext(context); 20 | TestDataMapper testData = springContext.getBean(TestDataMapper.class); 21 | Customers customers = springContext.getBean(Customers.class); 22 | 23 | String customerId = "1"; 24 | String accountId = "1"; 25 | 26 | testData.insertCustomer(customerId, "John Smith", "john.smith@email.com"); 27 | testData.insertAccount(accountId, customerId, 100.00, "CNY"); 28 | 29 | Customer customer = customers.findById(customerId).get(); 30 | 31 | for (var evidence = 0; evidence < 1000; evidence++) { 32 | var description = new SalesSettlementDescription(new Ref<>("ORD-" + new Random().nextInt()), 33 | Amount.cny("500.00"), new Ref<>(accountId), 34 | new SalesSettlementDescription.Detail(Amount.cny("100.00")), 35 | new SalesSettlementDescription.Detail(Amount.cny("100.00")), 36 | new SalesSettlementDescription.Detail(Amount.cny("100.00")), 37 | new SalesSettlementDescription.Detail(Amount.cny("100.00")), 38 | new SalesSettlementDescription.Detail(Amount.cny("100.00")) 39 | ); 40 | 41 | customer.add(description); 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /persistent/mybatis/src/test/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | main: 3 | banner-mode: "off" 4 | datasource: 5 | driver-class-name: org.h2.Driver 6 | url: jdbc:h2:mem:accounting;MODE=MySQL 7 | username: sa 8 | password: sa 9 | mybatis: 10 | mapper-locations: classpath:mybatis/mapper/**/*.xml 11 | configuration: 12 | object-factory: reengineering.ddd.mybatis.support.InjectableObjectFactory 13 | logging: 14 | level: 15 | root: info 16 | 17 | 18 | -------------------------------------------------------------------------------- /public/Smart Domain Pattern.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Re-engineering-Domain-Driven-Design/Accounting/ffe0a3648c275b0e930aca1fae13060bb2bdfd1b/public/Smart Domain Pattern.pdf -------------------------------------------------------------------------------- /public/api.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Re-engineering-Domain-Driven-Design/Accounting/ffe0a3648c275b0e930aca1fae13060bb2bdfd1b/public/api.jpg -------------------------------------------------------------------------------- /public/association.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Re-engineering-Domain-Driven-Design/Accounting/ffe0a3648c275b0e930aca1fae13060bb2bdfd1b/public/association.jpg -------------------------------------------------------------------------------- /public/lifecycle.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Re-engineering-Domain-Driven-Design/Accounting/ffe0a3648c275b0e930aca1fae13060bb2bdfd1b/public/lifecycle.jpg -------------------------------------------------------------------------------- /public/model.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Re-engineering-Domain-Driven-Design/Accounting/ffe0a3648c275b0e930aca1fae13060bb2bdfd1b/public/model.jpg -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'accounting' 2 | include 'domain', 'api', 'persistent:mybatis', 'main' 3 | --------------------------------------------------------------------------------