├── LICENSE
├── README.md
├── READMEIMG
├── 211690962797_.pic.jpg
├── q2.png
├── qo.png
├── rela1.png
└── vv.png
├── pom.xml
└── src
└── main
├── java
└── com
│ └── github
│ └── qcalculator
│ ├── core
│ ├── aware
│ │ └── CalculatorRouter.java
│ ├── discount
│ │ ├── Calculator.java
│ │ └── impl
│ │ │ └── AbstractCalculator.java
│ ├── enums
│ │ ├── GoodsType.java
│ │ ├── GroupRelation.java
│ │ └── ItemIdType.java
│ ├── model
│ │ ├── common
│ │ │ ├── CalcResult.java
│ │ │ ├── CalcStage.java
│ │ │ ├── CalcState.java
│ │ │ ├── DiscountConfig.java
│ │ │ ├── DiscountContext.java
│ │ │ ├── DiscountGroup.java
│ │ │ ├── DiscountWrapper.java
│ │ │ └── Item.java
│ │ └── goods
│ │ │ ├── GoodsInfo.java
│ │ │ └── GoodsItem.java
│ ├── permutation
│ │ └── Permutation.java
│ ├── precompute
│ │ ├── PreCompute.java
│ │ └── PreComputeHolder.java
│ └── utils
│ │ ├── DiscountGroupUtil.java
│ │ ├── IdGenerator.java
│ │ └── LimitingUtil.java
│ └── demo
│ ├── App.java
│ └── biz
│ ├── Flowable.java
│ ├── TestController.java
│ ├── calc
│ ├── ManjianCalc.java
│ └── ZhekouCalc.java
│ ├── constant
│ └── Constant.java
│ └── precompute
│ └── PreGroupBy.java
└── resources
└── calculator-core.properties
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 | ## Stateless高性能优惠叠加计算框架
17 |
18 | #### RT:
19 | 6000QPS下,RT的表现,可以说比较惊人了
20 |
21 |
22 |
23 |
24 | #### 背景:
25 |
26 | 优惠是营销转化链路的重要抓手,对刺激用户消费起到至关重要的作用,目前市场上的优惠主要包含活动(如拼多多的砍一刀、天猫农场、新用户首购、复购、积分等)和券(如折扣券、代金券、商品券、买A赠B等),复杂的优惠规则让用户很难自行计算优惠叠加的顺序,或许用户在复杂的优惠规则中降低购买商品的欲望,对于参加了多个活动、有多个优惠券情况尤为明显。
27 |
28 | 优惠的计算顺序可以分为平行式和渐进式,其中平行式优惠之间没有依赖关系,而渐进式优惠之间则存在依赖关系,即下一个优惠取决于上一步的优惠结果,假设小明消费了100元,有一个8折优惠券和一个满100-20的优惠券,则这2个优惠的使用顺序有以下两种情况:
29 |
30 |
31 |
32 |
33 |
34 | `Q-calculator`采用很多新颖的算法实现了高性能求解优惠最优排列。
35 |
36 |
37 |
38 | #### 核心计算类 Permutation<T extends GoodsItem>
39 |
40 | `Permutation`是一个抽象类,是`Q-calculator`的核心,在`Permutation`中使用了很多优化策略来保证性能,这些策略包括:
41 |
42 | - 预存的排列数结果集
43 |
44 | 这么设计的原因是在业务场景中需要频繁的计算排列,对于某个长度的序列,其排列结果是固定的。在`Permutation`类中的`PERMUTATIONS`属性存放了7以内的排列数结果集,这里使用了`Byte`来存储,因此占用的内存空间非常小。
45 | ```Java
46 | private final static Map>> PERMUTATIONS = Maps.newHashMap();
47 |
48 | ```
49 | 这个动作在类加载即完成,如果对7不满意,可以调整`SUPPORTEDSIZE`的大小,7是我们在实现中摸出来的兼顾业务和性能的参数,大家可以根据自己的需要来调整。
50 |
51 | ```Java
52 | public final static int SUPPORTEDSIZE = 7;
53 |
54 | static{
55 | //前置计算 1-SUPPORTEDSIZE 之间所有排列组合
56 | for(byte i=1;i<=SUPPORTEDSIZE;i++){
57 | PERMUTATIONS.put((int)i,Collections2.permutations(IntStream.range(0,i).boxed().map(x->(byte)x.intValue()).collect(Collectors.toList())));
58 | }
59 | }
60 |
61 | ```
62 |
63 | - $A_n^3$ 级别缓存
64 |
65 | 相对于传统的`Key-Value`结构,求解 $A_n^n$ 问题的缓存需要特殊设计,对一个优惠集合而言 $A_n^3$ 意味着缓存 n x (n-1) x (n-2) 条数据,默认n为7则需要缓存210条数据,兼顾内存大小和缓存带来的性能收益, $A_n^3$ 是最为合适的。
66 |
67 | `Permutation`的成员变量`cache`来实现高性能缓存。
68 |
69 | ```Java
70 | private final Map> cache = Maps.newHashMap();
71 | ```
72 | 可能你已经注意到,`cache`的键是`Integer`类型的,的确,通常`String`会更常用,然而在万次计算的场景下,`String`的拼接已经成了瓶颈。
73 | 为了实现高性能的键,`Permutation`通过位移对`Byte`数组的前3位进行扰动,确保键的唯一性和性能。
74 |
75 | ```Java
76 | private static Integer calcKey(List a){
77 | return a.size()>=3?(a.get(0) << 6)+ (a.get(1) << 3) + a.get(2):0;
78 | }
79 | ```
80 |
81 | `Permutation`提供了保存点来实现 $A_n^3$ 级别缓存,`CalcState` 记录了计算到第3步的状态,包括当前订单优惠金额和计算过程、已享用优惠的商品等,这些属性的保存和回放`Permutation`已经帮你做好了,`Permutation`额外提供了抽象的保存和回放方法来满足你的个性化诉求。
82 |
83 | ```Java
84 | /**
85 | * 业务将状态记录到保存点
86 | * @param state 保存点对象
87 | */
88 | protected abstract void makeSnapshot(CalcState state,DiscountContext context);
89 |
90 | /**
91 | * 业务返回保存点状态
92 | * @param state 保存点对象
93 | */
94 | protected abstract void backToSnapshot(CalcState state,DiscountContext context);
95 | ```
96 |
97 | 优惠计算是有优先级的,必须保证属性`calculateGroup`值小的在前面运算,当`backToSnapshot`发生时,需要额外判断缓存中最后一个优惠和当前准备计算优惠之间的关系,若不满足则直接跳出。`checkIfWakeUpJump`方法将在缓存被使用后立刻判断是否需要继续下去。
98 |
99 | #### 上下文类 DiscountContext<T extends GoodsItem>
100 |
101 | `DiscountContext`是上下文,也是`Permutation`的成员变量,`DiscountContext`同样包含很多优化策略:
102 |
103 | - CalcStage数组
104 |
105 | 在变更最频繁也是最重要的计算步骤对象`CalcStage`使用数组存储,该数组随着上下文创建而创建,在`Permutation`中使用
106 |
107 | ```Java
108 | Arrays.fill(arr,null);
109 | ```
110 |
111 | 将该数组清空并让它投入下一次计算,这样一次全排列过程中,数组只会被创建一次,避免了频繁创建数组带来的性能损耗。
112 |
113 | - 预计算
114 |
115 | `DiscountContext`的初始化方法是静态的`create`方法,该方法将商品和优惠进行绑定,同时执行一些用户自定义的逻辑,我们称之为`预计算`,预计算的结果会被保存在`DiscountContext`的`preCompute`属性,可以在后续的计算中直接取用,一劳永逸,避免了在后续的高速迭代中做相同的事情,比如商品分组、求和等等。
116 |
117 | #### 预计算 PreCompute<T extends GoodsItem>
118 |
119 | 预计算提供了接口,要使用预计算首先需要实现PreCompute接口
120 |
121 | ```Java
122 | public interface PreCompute {
123 | /**
124 | * 判断符合条件的活动类型,符合才会执行preComputeItems
125 | */
126 | Set matchTypes();
127 |
128 | /**
129 | * 对商品做一些复杂集合操作
130 | * @param items 当前参与优惠的商品
131 | * @param discount 当前优惠
132 | * @param preCompute 存储计算的结果
133 | */
134 | void preComputeItems(List items, DiscountWrapper discount, Map preCompute);
135 | }
136 | ```
137 |
138 | 此外需要在资源目录下建立`calculator-core.properties`文件,配置内容如下
139 |
140 | ```Java
141 | precompute.path=你要扫描的包
142 | ```
143 | `PreComputeHolder`将处理所有的`PreCompute`实现类,只有`matchTypes`匹配的情况下`preComputeItems`方法才会被执行。
144 |
145 | ```Java
146 | public class PreComputeHolder {
147 | public static Set COMPUTES= Sets.newHashSet();
148 | private final static String PATH = "precompute.path";
149 |
150 | static{
151 | Properties properties = new Properties();
152 | try {
153 | properties = PropertiesLoaderUtils.loadProperties(new FileSystemResource(Objects.requireNonNull(PreComputeHolder.class.getClassLoader().getResource("calculator-core.properties")).getPath()));
154 | } catch (Exception ignore) {
155 | }
156 | String path = properties.getProperty(PATH);
157 | if(StringUtils.isNotBlank(path)){
158 | Reflections reflections = new Reflections(path);
159 | Set> subTypes = reflections.getSubTypesOf(PreCompute.class);
160 | for(Class extends PreCompute> clazz:subTypes){
161 | try {
162 | COMPUTES.add(clazz.newInstance());
163 | } catch (Exception ignore) {
164 | }
165 | }
166 | }
167 | }
168 | }
169 | ```
170 |
171 | #### 计算器 Calculator
172 |
173 | `Calculator`是单个优惠的计算接口,它有`calcWrap`一个方法,负责具体的优惠计算,但`calcWarp`需要承担一些内部的事情,因此我们提供了抽象类`AbstractCalculator`实现了`calcWrap`,并最终暴露了一个更简单的`calc`方法给使用者。
174 |
175 | `AbstractCalculator`的内容如下,`calcWrap`方法负责创建`CalcStage`,维护`CalcStage`数组等内部工作,这对使用者来说是透明的,使用者实现`calc`就好。
176 |
177 | ```Java
178 | public abstract class AbstractCalculator implements Calculator {
179 | public long calcWrap(DiscountContext context, DiscountWrapper discountWrapper, Map records, byte idx, int i) {
180 | CalcStage stage = new CalcStage();
181 | CalcResult cr = context.getCalcResult();
182 | long price= cr.getCurPrice();
183 | stage.setBeforeCalcPrice(price);
184 | price = calc(context, discountWrapper,records, price, stage);
185 | if(price<0){
186 | return price;
187 | }
188 | stage.setAfterCalcPrice(price);
189 | stage.setIndex(idx);
190 | stage.setStageType(discountWrapper.getType());
191 | cr.setCurPrice(price);
192 | if(stage.getBeforeCalcPrice()>stage.getAfterCalcPrice()) {
193 | cr.getCurStages()[i] = stage;
194 | }
195 | return price;
196 | }
197 |
198 | /**
199 | * 返回该优惠下的最终要支付的金额,若不符合则返回 prevStagePrice
200 | * @param context 上下文
201 | * @param discountWrapper 优惠信息
202 | * @param records 记录享受过优惠的单品,key是calculateId,这里只提供容器,添加和判断规则由使用者自行决定
203 | * @param prevStagePrice 上一步计算的订单的价格
204 | * @param curStage 当前stage
205 | * @return
206 | */
207 | public abstract long calc(DiscountContext context, DiscountWrapper discountWrapper, Map records, long prevStagePrice, CalcStage curStage);
208 |
209 | }
210 |
211 | ```
212 | 最终用户继承`AbstractCalculator`,需要在`Component`注解中指定一个值,而`CalculatorRouter`将通过这个值来路由到具体的优惠计算器。这个值和`DiscountWrapper`中的`type`属性是对应的。
213 |
214 | ```Java
215 | @Component("manjian")
216 | public class ManjianCalc extends AbstractCalculator {
217 | ......
218 | }
219 | ```
220 |
221 |
222 | #### 共享互斥协议 DiscountGroup
223 |
224 | 共享互斥协议是一个数组,数组中最多有2个对象,最少1个对象,若只有1个对象,则该对象必然为共享组,即组内优惠可以叠加使用
225 | ```JavaScript
226 | [
227 | {
228 | "relation": "share",
229 | "items":
230 | [
231 | {
232 | "type": "activity0",
233 | "id": "11"
234 | }
235 | ,
236 | {
237 | "type": "activity4",
238 | "id": "13"
239 | }
240 | ,
241 | {
242 | "type": "coupon1",
243 | "id": "14"
244 | }
245 | ]
246 | }]
247 | ```
248 | 相应地,数组中包含2个对象,则第1个对象的`relation`可以为`share`或者`exclude`,第二个对象的`relation`必须为`exclude`
249 |
250 | ```JavaScript
251 | [
252 | {
253 | "relation": "share",
254 | "items":
255 | [
256 | {
257 | "type": "activity0",
258 | "id": "11"
259 | },
260 | {
261 | "type": "card3",
262 | "id":"12"
263 | }
264 | ]
265 | },
266 | {
267 | "relation": "exclude",
268 | "items":
269 | [
270 | {
271 | "type": "card1",
272 | "id": "18"
273 | },
274 | {
275 | "type": "coupon1",
276 | "id": "22"
277 | }
278 | ]
279 | }
280 | ]
281 | ```
282 | 最终将转化为共享组,比如上面的协议将转化为下面2个共享组
283 |
284 | `activity0-card3-card1`
285 | `activity0-card3-coupon1`
286 |
287 | 工具类 `DiscountGroupUtil` 提供了协议转共享组的方法,由于共享组可能很长,所以先和用户当前订单可享的优惠进行一个交叉过滤,为了提升过滤的性能,要将当前可用优惠转成二级`Map`,这个`Map`的外层键是协议中的`type`,第二层键是协议中的`id`。
288 |
289 | ```Java
290 | public static List,Set>> transform(List> groups, Map> inMap);
291 | ```
292 | 为了保证算力,我们将用户本单可享的优惠分别装在2个集合中,左侧集合的大小为`SUPPORTEDSIZE`,也就是算力之内的、重点保障的优惠,而右侧的集合则尽力而为去叠加即可。
293 | 从稳定性角度来讲,我们需要给计算次数做一个统计,并在压测中摸清楚阈值,我们提供了`LimitingUtil.count`统计进入`calc`方法的次数,显然在没有开启缓存的情况下,计算次数为 $A_n^n$ x n,在开启缓存的情况下,计算次数为 $A_n^n$ x (n-3) + $A_n^3$
294 |
295 | #### CASE
296 |
297 | 可以在`com.github.qcalculator.discount.demo`找到调用的具体case
298 |
299 |
300 |
301 |
302 |
303 |
--------------------------------------------------------------------------------
/READMEIMG/211690962797_.pic.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CyrilFeng/Q-calculator/ccece53668d33dfaef4afd28392ed9c29a1f2e27/READMEIMG/211690962797_.pic.jpg
--------------------------------------------------------------------------------
/READMEIMG/q2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CyrilFeng/Q-calculator/ccece53668d33dfaef4afd28392ed9c29a1f2e27/READMEIMG/q2.png
--------------------------------------------------------------------------------
/READMEIMG/qo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CyrilFeng/Q-calculator/ccece53668d33dfaef4afd28392ed9c29a1f2e27/READMEIMG/qo.png
--------------------------------------------------------------------------------
/READMEIMG/rela1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CyrilFeng/Q-calculator/ccece53668d33dfaef4afd28392ed9c29a1f2e27/READMEIMG/rela1.png
--------------------------------------------------------------------------------
/READMEIMG/vv.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CyrilFeng/Q-calculator/ccece53668d33dfaef4afd28392ed9c29a1f2e27/READMEIMG/vv.png
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
5 |
6 | com.github.qcalculator
7 | 4.0.0
8 | jar
9 | calculator-core
10 | calculator
11 | 1.0-SNAPSHOT
12 |
13 |
14 | org.springframework.boot
15 | spring-boot-starter-parent
16 | 2.2.6.RELEASE
17 |
18 |
19 |
20 |
21 | UTF-8
22 | 1.8
23 | 1.8
24 |
25 |
26 |
27 |
28 |
29 | org.reflections
30 | reflections
31 | 0.10.2
32 |
33 |
34 | org.mapstruct
35 | mapstruct
36 | 1.5.5.Final
37 |
38 |
39 | org.apache.commons
40 | commons-lang3
41 | 3.12.0
42 |
43 |
44 | com.alibaba
45 | fastjson
46 | 1.2.80
47 |
48 |
49 | org.apache.commons
50 | commons-collections4
51 | 4.4
52 |
53 |
54 | com.google.guava
55 | guava
56 | 31.1-jre
57 |
58 |
59 | org.projectlombok
60 | lombok
61 | 1.18.24
62 |
63 |
64 | org.springframework.boot
65 | spring-boot-starter-web
66 | 2.2.6.RELEASE
67 |
68 |
69 | org.springframework.boot
70 | spring-boot-starter-test
71 | 2.2.6.RELEASE
72 |
73 |
74 | net.logstash.logback
75 | logstash-logback-encoder
76 | 4.9
77 |
78 |
79 |
80 |
81 |
82 | org.apache.maven.plugins
83 | maven-compiler-plugin
84 | 3.8.1
85 |
86 | 1.8
87 | 1.8
88 |
89 |
90 | org.mapstruct
91 | mapstruct-processor
92 | 1.5.5.Final
93 |
94 |
95 | org.projectlombok
96 | lombok
97 | 1.18.24
98 |
99 |
100 | org.projectlombok
101 | lombok-mapstruct-binding
102 | 0.2.0
103 |
104 |
105 |
106 |
107 |
108 |
109 |
110 |
111 |
--------------------------------------------------------------------------------
/src/main/java/com/github/qcalculator/core/aware/CalculatorRouter.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2022 CyrilFeng
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 |
18 | package com.github.qcalculator.core.aware;
19 | import com.github.qcalculator.core.discount.Calculator;
20 | import org.springframework.beans.BeansException;
21 | import org.springframework.context.ApplicationContext;
22 | import org.springframework.context.ApplicationContextAware;
23 | import org.springframework.stereotype.Component;
24 | import java.util.Map;
25 |
26 | /**
27 |
28 | * 根据注解路由到目标Calculator
29 | * @author: CyrilFeng
30 | * @date: 2022/8
31 | */
32 | @Component
33 | @SuppressWarnings("all")
34 | public class CalculatorRouter implements ApplicationContextAware {
35 |
36 | private Map map;
37 |
38 | @Override
39 | public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
40 | map = applicationContext.getBeansOfType(Calculator.class);
41 | }
42 |
43 |
44 | public Map getMap() {
45 | return map;
46 | }
47 |
48 | public Calculator getService(String key) {
49 | return map.get(key);
50 | }
51 |
52 | }
53 |
--------------------------------------------------------------------------------
/src/main/java/com/github/qcalculator/core/discount/Calculator.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2022 CyrilFeng
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.github.qcalculator.core.discount;
18 | import com.github.qcalculator.core.model.common.DiscountContext;
19 | import com.github.qcalculator.core.model.common.DiscountWrapper;
20 | import com.github.qcalculator.core.model.goods.GoodsItem;
21 |
22 | import java.util.Map;
23 |
24 | /**
25 | * 优惠计算器接口
26 | * @author: CyrilFeng
27 | * @date: 2022/8
28 | */
29 | public interface Calculator {
30 |
31 | /**
32 | * 优惠计算引擎的内部方法
33 | * @param context 上下文
34 | * @param discountWrapper 当前优惠信息
35 | * @param records 参与优惠的商品记录,用于过滤
36 | * @param idx 活动的index
37 | * @param i 当前计算的索引下标,它和idx的区别在于比如有数组[9,4,6,5],则i为数组下标 i=1 时对应的idx是4
38 | */
39 | long calcWrap(DiscountContext context, DiscountWrapper discountWrapper, Map records, byte idx, int i);
40 | }
41 |
--------------------------------------------------------------------------------
/src/main/java/com/github/qcalculator/core/discount/impl/AbstractCalculator.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2022 CyrilFeng
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.github.qcalculator.core.discount.impl;
18 | import com.github.qcalculator.core.discount.Calculator;
19 | import com.github.qcalculator.core.model.common.CalcStage;
20 | import com.github.qcalculator.core.model.common.DiscountContext;
21 | import com.github.qcalculator.core.model.common.DiscountWrapper;
22 | import com.github.qcalculator.core.model.goods.GoodsItem;
23 | import com.github.qcalculator.core.model.common.CalcResult;
24 |
25 | import java.util.Map;
26 |
27 | /**
28 | * 抽象计算器类,每种类型优惠做一个实现类,负责创建 stage,维护CalcStage[]数组等内部工作,这对使用者是透明的
29 | * @author: CyrilFeng
30 | * @date: 2022/8
31 | */
32 | public abstract class AbstractCalculator implements Calculator {
33 |
34 | public long calcWrap(DiscountContext context, DiscountWrapper discountWrapper, Map records, byte idx, int i) {
35 | CalcStage stage = new CalcStage();
36 | CalcResult cr = context.getCalcResult();
37 | long price= cr.getCurPrice();
38 | stage.setBeforeCalcPrice(price);
39 | price = calc(context, discountWrapper,records, price, stage);
40 | if(price<0){
41 | return price;
42 | }
43 | stage.setAfterCalcPrice(price);
44 | stage.setIndex(idx);
45 | stage.setStageType(discountWrapper.getType());
46 | cr.setCurPrice(price);
47 | if(stage.getBeforeCalcPrice()>stage.getAfterCalcPrice()) {
48 | cr.getCurStages()[i] = stage;
49 | }
50 | return price;
51 | }
52 |
53 | /**
54 | * 返回该优惠下的最终要支付的金额,若不符合则返回 prevStagePrice
55 | * @param context 上下文
56 | * @param discountWrapper 优惠信息
57 | * @param records 记录享受过优惠的单品,key是calculateId,这里只提供容器,添加和判断规则由使用者自行决定
58 | * @param prevStagePrice 上一步计算出的订单的价格
59 | * @param curStage 当前stage
60 | * @return
61 | */
62 | public abstract long calc(DiscountContext context, DiscountWrapper discountWrapper, Map records, long prevStagePrice, CalcStage curStage);
63 |
64 | }
65 |
--------------------------------------------------------------------------------
/src/main/java/com/github/qcalculator/core/enums/GoodsType.java:
--------------------------------------------------------------------------------
1 | package com.github.qcalculator.core.enums;
2 |
3 | public enum GoodsType {
4 | ALL(0,"所有商品可参与"),
5 | SELECT(1,"指定某些商品参与"),
6 | INVERT(2,"指定某些商品不参与");
7 |
8 | private int code;
9 | private String desc;
10 |
11 | GoodsType(int code, String desc) {
12 | this.code = code;
13 | this.desc = desc;
14 | }
15 |
16 | public int getCode() {
17 | return code;
18 | }
19 |
20 | public void setCode(int code) {
21 | this.code = code;
22 | }
23 |
24 | public String getDesc() {
25 | return desc;
26 | }
27 |
28 | public void setDesc(String desc) {
29 | this.desc = desc;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/com/github/qcalculator/core/enums/GroupRelation.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2022 CyrilFeng
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.github.qcalculator.core.enums;
18 |
19 | /**
20 | * 组内关系枚举
21 | * 组内关系枚举
22 | * @author: CyrilFeng
23 | * @date: 2022/8
24 | */
25 | public enum GroupRelation {
26 |
27 | SHARE("share"),
28 | EXCLUDE("exclude");
29 |
30 | private String type;
31 |
32 | GroupRelation(String type) {
33 | this.type = type;
34 | }
35 |
36 | public String getType() {
37 | return type;
38 | }
39 |
40 | public void setType(String type) {
41 | this.type = type;
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/main/java/com/github/qcalculator/core/enums/ItemIdType.java:
--------------------------------------------------------------------------------
1 | package com.github.qcalculator.core.enums;
2 |
3 | public enum ItemIdType {
4 | ITEM(0,"商品ID"),
5 | SKU(1,"SKUID"),
6 | CATEGORY(2,"类目Id");
7 |
8 | private int code;
9 | private String desc;
10 |
11 | ItemIdType(int code, String desc) {
12 | this.code = code;
13 | this.desc = desc;
14 | }
15 |
16 | public int getCode() {
17 | return code;
18 | }
19 |
20 | public void setCode(int code) {
21 | this.code = code;
22 | }
23 |
24 | public String getDesc() {
25 | return desc;
26 | }
27 |
28 | public void setDesc(String desc) {
29 | this.desc = desc;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/com/github/qcalculator/core/model/common/CalcResult.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2022 CyrilFeng
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.github.qcalculator.core.model.common;
18 |
19 | import com.fasterxml.jackson.annotation.JsonIgnore;
20 | import lombok.Data;
21 | import java.io.Serializable;
22 |
23 |
24 | /**
25 | * 优惠计算结果
26 | * @author: CyrilFeng
27 | * @date: 2022/8
28 | */
29 | @Data
30 | public class CalcResult implements Serializable {
31 |
32 | private CalcResult() {
33 | }
34 |
35 | /**
36 | * 最优实付金额
37 | */
38 | private long finalPrice;
39 |
40 | /**
41 | * 最优优惠计算过程
42 | */
43 | private CalcStage[] stages;
44 |
45 | /**
46 | * 当前序列计算的实付金额
47 | */
48 | @JsonIgnore
49 | private transient long curFinalPrice;
50 |
51 | /**
52 | * 当前序列优惠计算过程
53 | */
54 | @JsonIgnore
55 | private transient CalcStage[] curStages;
56 |
57 | /**
58 | * 实时计算价格
59 | */
60 | @JsonIgnore
61 | private transient long curPrice;
62 |
63 | public static CalcResult create(int n){
64 | CalcResult c=new CalcResult();
65 | c.stages=new CalcStage[n];
66 | c.curStages=new CalcStage[n];
67 | return c;
68 | }
69 |
70 | }
71 |
--------------------------------------------------------------------------------
/src/main/java/com/github/qcalculator/core/model/common/CalcStage.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2022 CyrilFeng
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.github.qcalculator.core.model.common;
18 |
19 | import lombok.*;
20 | import java.io.Serializable;
21 | import java.util.Map;
22 |
23 | /**
24 | * 单个具体优惠计算明细,可以当成日志来用,用于计算过程的追溯
25 | * @author: CyrilFeng
26 | * @date: 2022/8
27 | */
28 | @Data
29 | public class CalcStage implements Serializable {
30 |
31 | /**
32 | * 优惠前价格
33 | */
34 | private long beforeCalcPrice;
35 |
36 | /**
37 | * 优惠后价格
38 | */
39 | private long afterCalcPrice;
40 |
41 | /**
42 | * 优惠类型
43 | */
44 | private String stageType;
45 |
46 | /**
47 | * 优惠索引
48 | */
49 | private byte index;
50 |
51 | /**
52 | * 扩展属性
53 | */
54 | private Map extra;
55 |
56 | }
57 |
--------------------------------------------------------------------------------
/src/main/java/com/github/qcalculator/core/model/common/CalcState.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2022 CyrilFeng
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.github.qcalculator.core.model.common;
18 | import com.github.qcalculator.core.model.goods.GoodsItem;
19 | import lombok.Data;
20 | import java.io.Serializable;
21 | import java.util.Map;
22 |
23 | /**
24 | * 保存点,用于缓存,入计算到第3个节点时可以将所有状态写入CalcState
25 | * @author: CyrilFeng
26 | * @date: 2022/8
27 | */
28 | @Data
29 | public class CalcState implements Serializable {
30 |
31 | /**
32 | * 截止到保存点计算的最终优惠价格
33 | */
34 | private long curPrice;
35 |
36 | /**
37 | * 截止到保存点计算的CalcStage
38 | */
39 | private CalcStage[] curStages;
40 |
41 | /**
42 | * 截止到保存点的商品列表
43 | */
44 | private Map goodsItems;
45 |
46 | /**
47 | * 截止到保存点的已计算商品列表
48 | */
49 | private Map records;
50 |
51 | /**
52 | * 截止到保存点的扩展信息
53 | */
54 | private Map extra;
55 | }
56 |
--------------------------------------------------------------------------------
/src/main/java/com/github/qcalculator/core/model/common/DiscountConfig.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2022 CyrilFeng
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.github.qcalculator.core.model.common;
18 | import lombok.Data;
19 | import java.io.Serializable;
20 | import java.util.List;
21 | import java.util.Map;
22 |
23 | /**
24 | * 优惠配置信息
25 | * @author: CyrilFeng
26 | * @date: 2022/7
27 | */
28 | @Data
29 | public class DiscountConfig implements Serializable {
30 |
31 | /**
32 | * 当前优惠的优先级(如10 - 单商品组, 20 - 整单组)
33 | */
34 | private int calculateGroup;
35 |
36 | /**
37 | * 商品限制 (0 - 所有商品可参与,1 - 指定某些商品参与, 2- 指定某些商品不参与)
38 | */
39 | private int goodsType;
40 |
41 | /**
42 | * 下一个属性 itemIds 存放的内容是啥,(0 - 商品ID, 1 - SKUID, 2 - 类目Id)
43 | */
44 | private int itemIdType;
45 |
46 | /**
47 | * 同上
48 | */
49 | private List itemIds;
50 |
51 | /**
52 | * 活动信息扩展信息
53 | */
54 | private Map extra;
55 |
56 | }
57 |
--------------------------------------------------------------------------------
/src/main/java/com/github/qcalculator/core/model/common/DiscountContext.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2022 CyrilFeng
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.github.qcalculator.core.model.common;
18 | import com.github.qcalculator.core.enums.GoodsType;
19 | import com.github.qcalculator.core.enums.ItemIdType;
20 | import com.github.qcalculator.core.model.goods.GoodsItem;
21 | import com.github.qcalculator.core.precompute.PreCompute;
22 | import com.github.qcalculator.core.precompute.PreComputeHolder;
23 | import com.google.common.collect.Lists;
24 | import com.google.common.collect.Maps;
25 | import lombok.Data;
26 | import org.apache.commons.collections4.CollectionUtils;
27 | import java.io.Serializable;
28 | import java.util.List;
29 | import java.util.Map;
30 | import java.util.stream.Collectors;
31 |
32 | /**
33 | * 优惠上下文,包含一些初始化工作、预计算等等
34 | * @author: CyrilFeng
35 | * @date: 2022/8
36 | */
37 | @Data
38 | public class DiscountContext implements Serializable {
39 |
40 | private DiscountContext() {
41 | }
42 |
43 | /**
44 | * 原始价格
45 | */
46 | private long originalPrice;
47 |
48 | /**
49 | * 优惠的计算结果
50 | */
51 | private CalcResult calcResult;
52 |
53 |
54 | /**
55 | * 当前订单参与计算的商品
56 | */
57 | private List goodsItems;
58 |
59 | /**
60 | * 当前订单可用优惠的配置
61 | */
62 | private List discountWrappers;
63 |
64 | /**
65 | * 优惠维度进行商品分组,这样每个计算器只取自己相关的商品
66 | */
67 | private Map> discountItemGroup;
68 |
69 | /**
70 | * 记录享受过优惠的单品,key是calculateId
71 | */
72 | private Map records;
73 |
74 | /**
75 | * 存储预计算的结果
76 | */
77 | private Map preCompute;
78 |
79 | /**
80 | * 扩展字段
81 | */
82 | private Map extra;
83 |
84 |
85 | /**
86 | * 构造一个上下文
87 | * @param originalPrice 订单原始价格
88 | * @param goodsItems 可用商品列表
89 | * @param discountWrappers 可用优惠列表
90 | * @return
91 | */
92 | public static DiscountContext create(long originalPrice, List goodsItems, List discountWrappers) {
93 | DiscountContext c=new DiscountContext<>();
94 | c.originalPrice = originalPrice;
95 | c.records = Maps.newHashMap();
96 | c.discountItemGroup= Maps.newHashMap();
97 | c.calcResult=CalcResult.create(discountWrappers.size());
98 | c.calcResult.setFinalPrice(originalPrice);
99 | c.goodsItems = goodsItems;
100 | c.discountWrappers=discountWrappers;
101 | c.preCompute = Maps.newHashMap();
102 | //预处理优惠
103 | for(DiscountWrapper discount:discountWrappers) {
104 | initDiscount(c, discount);
105 | }
106 | return c;
107 | }
108 |
109 |
110 | /**
111 | * 对某个优惠进行初始化工作,包括商品的筛选、预计算逻辑
112 | * @param c 上下文
113 | * @param discount 当前优惠的信息
114 | */
115 | private static void initDiscount(DiscountContext c,DiscountWrapper discount){
116 | DiscountConfig conf = discount.getDiscountConfig();
117 | List list = Lists.newArrayList(c.goodsItems);
118 | if(GoodsType.ALL.getCode() ==conf.getGoodsType()){
119 | //不限制
120 | list=list.stream().sorted().collect(Collectors.toList());
121 | }else if(GoodsType.SELECT.getCode()==conf.getGoodsType()){
122 | if(ItemIdType.ITEM.getCode() ==conf.getItemIdType()){
123 | list = list.stream().filter(x->conf.getItemIds().
124 | contains(x.getGoodsId())).sorted().collect(Collectors.toList());
125 | } else if (ItemIdType.SKU.getCode()==conf.getItemIdType()) {
126 | list = list.stream().filter(x->conf.getItemIds().
127 | contains(x.getSkuId())).sorted().collect(Collectors.toList());
128 | } else{
129 | list = list.stream().filter(x-> CollectionUtils.intersection(
130 | conf.getItemIds(), x.getCategoryIds()).size()>0).sorted().collect(Collectors.toList());
131 | }
132 | }else{
133 | //指定不参与
134 | if(ItemIdType.ITEM.getCode()==conf.getItemIdType()){
135 | list=list.stream().filter(x->!conf.getItemIds().
136 | contains(x.getGoodsId())).sorted().collect(Collectors.toList());
137 | } else if (ItemIdType.SKU.getCode()==conf.getItemIdType()) {
138 | list = list.stream().filter(x->!conf.getItemIds().
139 | contains(x.getSkuId())).sorted().collect(Collectors.toList());
140 | } else{
141 | list=list.stream().filter(x-> CollectionUtils.intersection(
142 | conf.getItemIds(), x.getCategoryIds()).size()==0).sorted().collect(Collectors.toList());
143 | }
144 | }
145 | c.discountItemGroup.put(discount.getId(), list);
146 | runPreCompute(c,discount,list);
147 | }
148 |
149 | /**
150 | * 预计算
151 | * @param c 上下文
152 | * @param discount 当前的优惠信息
153 | * @param list 当前优惠匹配的商品列表
154 | */
155 | @SuppressWarnings("unchecked")
156 | private static void runPreCompute(DiscountContext c,DiscountWrapper discount,List list){
157 | list = Lists.newArrayList(list);
158 | for(PreCompute e: PreComputeHolder.COMPUTES){
159 | if(e.matchTypes().contains(discount.getType())){
160 | e.preComputeItems(list,discount,c.preCompute);
161 | }
162 | }
163 | }
164 |
165 | }
166 |
--------------------------------------------------------------------------------
/src/main/java/com/github/qcalculator/core/model/common/DiscountGroup.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2022 CyrilFeng
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.github.qcalculator.core.model.common;
18 | import com.google.common.collect.Lists;
19 | import lombok.*;
20 | import org.apache.commons.collections4.CollectionUtils;
21 | import org.apache.commons.collections4.MapUtils;
22 | import org.apache.commons.lang3.StringUtils;
23 | import java.io.Serializable;
24 | import java.util.Iterator;
25 | import java.util.List;
26 | import java.util.Map;
27 |
28 | /**
29 | * 共享互斥组
30 | * @author: CyrilFeng
31 | * @date: 2022/8
32 | */
33 | @Data
34 | public class DiscountGroup implements Serializable {
35 |
36 | private String relation;
37 | private List items;
38 |
39 | /**
40 | * 根据用户可用的优惠,对组内信息进行过滤
41 | * @param inMap
42 | * @return
43 | */
44 | public List filterItems(Map> inMap){
45 | //inMap 外层key为type,内层key为id,value为DiscountWrapper
46 | if(CollectionUtils.isEmpty(items)|| MapUtils.isEmpty(inMap)){
47 | return null;
48 | }
49 | //构建items副本
50 | List itemsCopy = Lists.newArrayList(items);
51 | Iterator it = itemsCopy.iterator();
52 | while(it.hasNext()){
53 | Item item = it.next();
54 | if(!inMap.containsKey(item.getType())){
55 | it.remove();
56 | continue;
57 | }
58 | if(StringUtils.isNotBlank(item.getId())){
59 | //理论上m不可能为空
60 | Map m = inMap.get(item.getType());
61 | if(MapUtils.isNotEmpty(m)){
62 | if(!m.containsKey(item.getId())){
63 | it.remove();
64 | }
65 | }
66 | }
67 | }
68 | return itemsCopy;
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/src/main/java/com/github/qcalculator/core/model/common/DiscountWrapper.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2022 CyrilFeng
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.github.qcalculator.core.model.common;
18 | import lombok.Data;
19 | import java.io.Serializable;
20 | import java.util.Objects;
21 |
22 | /**
23 | * 优惠类
24 | * @author: CyrilFeng
25 | * @date: 2022/7
26 | */
27 | @Data
28 | public class DiscountWrapper implements Serializable,Comparable {
29 |
30 | /**
31 | * 优惠的具体类型,CalculatorRouter会根据这个type在Calculator的实现类中扫描
32 | */
33 | private String type;
34 |
35 | /**
36 | * 优惠的ID
37 | */
38 | private String id;
39 |
40 | /**
41 | * 优惠的名称
42 | */
43 | private String name;
44 |
45 | /**
46 | * 是否是必须使用的优惠
47 | */
48 | private boolean mustUse;
49 |
50 | /**
51 | * 优惠的配置信息
52 | */
53 | private DiscountConfig discountConfig;
54 |
55 |
56 | public static DiscountWrapper of(String type,String id,String name,boolean mustUse,DiscountConfig discountConfig){
57 | DiscountWrapper wrapper = new DiscountWrapper();
58 | wrapper.setType(type);
59 | wrapper.setId(id);
60 | wrapper.setName(name);
61 | wrapper.setMustUse(mustUse);
62 | wrapper.setDiscountConfig(discountConfig);
63 | return wrapper;
64 | }
65 |
66 | @Override
67 | public boolean equals(Object o) {
68 | if (this == o) return true;
69 | if (o == null || getClass() != o.getClass()) return false;
70 | DiscountWrapper wrapper = (DiscountWrapper) o;
71 | return type.equals(wrapper.type) && id.equals(wrapper.id);
72 | }
73 |
74 | @Override
75 | public int hashCode() {
76 | return Objects.hash(type, id);
77 | }
78 |
79 | @Override
80 | public int compareTo(DiscountWrapper o) {
81 | return (this.type+this.id).compareTo(o.getType()+o.getId());
82 | }
83 |
84 | }
85 |
--------------------------------------------------------------------------------
/src/main/java/com/github/qcalculator/core/model/common/Item.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2022 CyrilFeng
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.github.qcalculator.core.model.common;
18 | import lombok.*;
19 | import java.io.Serializable;
20 |
21 | /**
22 | * 共享互斥关系中的元素
23 | * @author: CyrilFeng
24 | * @date: 2022/8
25 | */
26 | @AllArgsConstructor
27 | @NoArgsConstructor
28 | @Getter
29 | @Setter
30 | @ToString
31 | @EqualsAndHashCode
32 | public class Item implements Serializable {
33 | /**
34 | * 优惠类型,和DiscountWrapper中的type保持一致
35 | */
36 | private String type;
37 |
38 | /**
39 | * 优惠的ID,和DiscountWrapper中的id保持一致
40 | */
41 | private String id;
42 | }
43 |
--------------------------------------------------------------------------------
/src/main/java/com/github/qcalculator/core/model/goods/GoodsInfo.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2022 Shiyafeng
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.github.qcalculator.core.model.goods;
18 |
19 | import com.google.common.collect.Maps;
20 | import lombok.Data;
21 | import java.io.Serializable;
22 | import java.util.List;
23 | import java.util.Map;
24 |
25 | /**
26 | * 商品信息
27 | * @author: longlian
28 | * @date: 2022/7
29 | */
30 | @Data
31 | public class GoodsInfo implements Serializable,Cloneable {
32 |
33 | /**
34 | * 商品ID
35 | */
36 | private Long goodsId;
37 |
38 | /**
39 | * 商品的SKUID
40 | */
41 | private Long skuId;
42 |
43 | /**
44 | * 商品分类ID,一个商品可能出现在多个品类中
45 | */
46 | private List categoryIds;
47 |
48 | /**
49 | * 购买数量
50 | */
51 | private int num;
52 |
53 | /**
54 | * 商品价格,用于计算(单位:分)
55 | */
56 | private long salePrice;
57 |
58 | /**
59 | * 商品名
60 | */
61 | private String name;
62 |
63 | /**
64 | * 商品扩展属性
65 | */
66 | private Map goodsExtra = Maps.newHashMap();
67 |
68 |
69 | public static GoodsInfo of(Long goodsId,Long skuId,List categoryIds,int num,long salePrice,String name,Map goodsExtra){
70 | GoodsInfo goodsInfo = new GoodsInfo();
71 | goodsInfo.setGoodsId(goodsId);
72 | goodsInfo.setCategoryIds(categoryIds);
73 | goodsInfo.setNum(num);
74 | goodsInfo.setSkuId(skuId);
75 | goodsInfo.setSalePrice(salePrice);
76 | goodsInfo.setName(name);
77 | goodsInfo.setGoodsExtra(goodsExtra);
78 | return goodsInfo;
79 | }
80 |
81 | @Override
82 | public GoodsInfo clone() throws CloneNotSupportedException {
83 | return (GoodsInfo)super.clone();
84 | }
85 | }
86 |
--------------------------------------------------------------------------------
/src/main/java/com/github/qcalculator/core/model/goods/GoodsItem.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2022 CyrilFeng
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.github.qcalculator.core.model.goods;
18 |
19 | import com.github.qcalculator.core.utils.IdGenerator;
20 | import com.google.common.collect.Lists;
21 | import com.google.common.collect.Maps;
22 | import lombok.*;
23 | import java.io.Serializable;
24 | import java.util.List;
25 | import java.util.Map;
26 | import java.util.Objects;
27 | import java.util.function.Consumer;
28 |
29 | /**
30 | * 拆分后的商品,比如一个商品GoodsInfo买了2件则会产出2个GoodsItem
31 | * @author: CyrilFeng
32 | * @date: 2022/7
33 | */
34 | @Data
35 | public class GoodsItem extends GoodsInfo implements Serializable, Comparable,Cloneable {
36 |
37 | /**
38 | * 根据基本信息构造具体的计算商品,复制属性,以及单商品唯一id
39 | * @param calculateId
40 | * @param goodsInfo
41 | */
42 | public GoodsItem (long calculateId, GoodsInfo goodsInfo) {
43 | this.calculateId = calculateId;
44 | this.setGoodsId(goodsInfo.getGoodsId());
45 | this.setCategoryIds(goodsInfo.getCategoryIds());
46 | this.setName(goodsInfo.getName());
47 | this.setSkuId(goodsInfo.getSkuId());
48 | this.setSalePrice(goodsInfo.getSalePrice());
49 | }
50 |
51 | /**
52 | * 引擎计算时使用的id,每个单独商品一个
53 | */
54 | private Long calculateId;
55 |
56 | /**
57 | * 商品扩展属性
58 | */
59 | private Map extra = Maps.newHashMap();
60 |
61 | /**
62 | * 根据商品信息(数量),生成计算时候需要的具体商品(单个)
63 | * @param goodsInfo 商品信息
64 | * @param idGenerator id生成器
65 | * @param consumer 在创建商品的同时对extra中的内容进行初始化
66 | */
67 | @SuppressWarnings("unchecked")
68 | public static List generateItems(GoodsInfo goodsInfo, IdGenerator idGenerator, Consumer consumer) {
69 | if (Objects.isNull(goodsInfo)) {
70 | return Lists.newArrayList();
71 | }
72 | List goodsItems = Lists.newArrayList();
73 | for (int i = 0; i < goodsInfo.getNum(); i++) {
74 | T item = (T)new GoodsItem(idGenerator.nextId(),goodsInfo);
75 | consumer.accept(item);
76 | goodsItems.add(item);
77 | }
78 | return goodsItems;
79 | }
80 |
81 | @Override
82 | public boolean equals(Object o) {
83 | if (this == o) {
84 | return true;
85 | }
86 | if (o == null || getClass() != o.getClass()) {
87 | return false;
88 | }
89 | GoodsItem goodsItem = (GoodsItem) o;
90 | return Objects.equals(calculateId,goodsItem.calculateId);
91 | }
92 |
93 | @Override
94 | public int hashCode() {
95 | return Objects.hash(calculateId);
96 | }
97 |
98 | @Override
99 | public int compareTo(GoodsItem o) {
100 | return this.getCalculateId().compareTo(o.getCalculateId());
101 | }
102 |
103 | @Override
104 | public GoodsItem clone() throws CloneNotSupportedException {
105 | return (GoodsItem)super.clone();
106 | }
107 |
108 | }
109 |
--------------------------------------------------------------------------------
/src/main/java/com/github/qcalculator/core/permutation/Permutation.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2022 CyrilFeng
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.github.qcalculator.core.permutation;
18 |
19 | import com.github.qcalculator.core.aware.CalculatorRouter;
20 | import com.github.qcalculator.core.discount.Calculator;
21 | import com.github.qcalculator.core.model.common.*;
22 | import com.github.qcalculator.core.model.goods.GoodsItem;
23 | import com.google.common.collect.Collections2;
24 | import com.google.common.collect.Maps;
25 | import com.google.common.collect.Sets;
26 | import org.apache.commons.collections4.CollectionUtils;
27 | import java.util.*;
28 | import java.util.stream.Collectors;
29 | import java.util.stream.IntStream;
30 |
31 |
32 | /**
33 | * 全排列计算引擎
34 | * @author: CyrilFeng
35 | * @date: 2022/8
36 | */
37 |
38 | @SuppressWarnings("all")
39 | public abstract class Permutation {
40 |
41 | /**
42 | * 根据注解路由到目标Calculator
43 | */
44 | private CalculatorRouter calculatorRouter;
45 |
46 | /**
47 | * 上下文
48 | */
49 | private DiscountContext context;
50 |
51 | /**
52 | * 必须使用的优惠,比如用户手动选择的优惠
53 | */
54 | private final Set mustUseSet = Sets.newHashSet();
55 |
56 | /**
57 | * 缓存,key是calcKey生成的数字,value是保存点
58 | */
59 | private final Map> cache = Maps.newHashMap();
60 |
61 | /**
62 | * 将calculatorRouter绑定到当前Permutation
63 | * @param calculatorRouter 路由器
64 | * @return
65 | */
66 | public Permutation build(CalculatorRouter calculatorRouter){
67 | this.calculatorRouter=calculatorRouter;
68 | return this;
69 | }
70 |
71 | /**
72 | * 1-SUPPORTEDSIZE 之间所有排列组合的记录
73 | */
74 | private final static Map>> PERMUTATIONS = Maps.newHashMap();
75 |
76 | /**
77 | * 最大支持的共享组长度
78 | */
79 | public final static int SUPPORTEDSIZE = 7;
80 |
81 | static{
82 | //前置计算 1-SUPPORTEDSIZE 之间所有排列组合
83 | for(byte i=1;i<=SUPPORTEDSIZE;i++){
84 | PERMUTATIONS.put((int)i,Collections2.permutations(IntStream.range(0,i).boxed()
85 | .map(x->(byte)x.intValue()).collect(Collectors.toList())));
86 | }
87 | }
88 |
89 |
90 | /**
91 | * 计算最优解
92 | * @param context 上下文
93 | * @return
94 | */
95 | public void perm(DiscountContext context){
96 | int size=context.getDiscountWrappers().size();
97 | this.context = context;
98 | loadMustUseDiscount();
99 | if(size==0){
100 | return ;
101 | }
102 | Collection> list = PERMUTATIONS.get(size);
103 | for(List a:list) {
104 | boolean isBetter = executeCalc(this.context, a);
105 | if (isBetter) {
106 | //若出现比当前结果更优的结果则替换
107 | updateRecord(this.context.getCalcResult());
108 | }
109 | }
110 | cache.clear();
111 | mustUseSet.clear();
112 | }
113 |
114 | private void loadMustUseDiscount(){
115 | for(int i=0;i a){
126 | return a.size()>=3?(a.get(0) << 6)+ (a.get(1) << 3) + a.get(2):0;
127 | }
128 |
129 | /**
130 | * 若出现比当前结果更优的结果则替换
131 | * @param result 当前的计算结果
132 | */
133 | private void updateRecord(CalcResult result){
134 | result.setFinalPrice(result.getCurFinalPrice());
135 | System.arraycopy(result.getCurStages(),0,result.getStages(),0,result.getStages().length);
136 | }
137 |
138 | private void cacheSnapshot(List a,int i,Integer k){
139 | if(enableOptimize(a)&&i==2&&!cache.containsKey(k)){
140 | cache.put(k,makeSnapshot());
141 | }
142 | }
143 |
144 | private void initInner(boolean canOptimize,Integer k){
145 | if(canOptimize){
146 | //若可优化则还原之前的保存点
147 | backToSnapshot(k);
148 | }else{
149 | //若不可优化则老老实实初始化
150 | initCtx();
151 | }
152 | }
153 |
154 | private boolean calcInner(Calculator calculator,DiscountWrapper wrapper,List a,int i){
155 | long price = calculator.calcWrap(context, wrapper, context.getRecords(), a.get(i), i);
156 | if (price < 0) {
157 | return false;
158 | }
159 | if(inextOrder){
163 | //优先级不符合则跳出
164 | return false;
165 | }
166 | }
167 | return true;
168 | }
169 |
170 | /**
171 | * 根据数组顺序执行计算器
172 | */
173 | public boolean executeCalc(DiscountContext context,List a){
174 | Integer k = calcKey(a);
175 | boolean canOptimize = enableOptimize(a)&&cache.containsKey(k);
176 | initInner(canOptimize,k);
177 | for(int i=canOptimize?3:0;i calculator = (Calculator) calculatorRouter.getService(wrapper.getType());
180 | //路由目标的计算器实现
181 | if(canOptimize&&checkIfWakeUpJump(context.getDiscountWrappers().get(a.get(2)),wrapper)){
182 | //还原保存点后,比较保存点的最后一个优惠节点和当前优惠的优先级,如不符合则跳出
183 | break;
184 | }
185 | if(Objects.nonNull(calculator)){
186 | //执行计算器
187 | if(!calcInner(calculator,wrapper,a,i)){
188 | return false;
189 | }
190 | //优惠长度为5、6、7 将开启优化,只缓存走到第3个节点的部分
191 | cacheSnapshot(a,i,k);
192 | }
193 | }
194 | long curPrice = context.getCalcResult().getCurPrice();
195 | context.getCalcResult().setCurFinalPrice(curPrice);
196 | CalcStage[] stages = context.getCalcResult().getCurStages();
197 | return curPricewrapper.getDiscountConfig().getCalculateGroup();
209 | }
210 |
211 |
212 | /**
213 | * 全排列计算后判断位置是否匹配
214 | * @param stages 当前stage数组
215 | * @param pos 必须使用的优惠索引
216 | * @return
217 | */
218 | private boolean isMustUse(CalcStage[] stages,Set pos){
219 | int c=0;
220 | for(CalcStage stage:stages){
221 | if(Objects.isNull(stage)){
222 | continue;
223 | }
224 | if(pos.contains(stage.getIndex())){
225 | c++;
226 | }
227 | }
228 | return c==pos.size();
229 | }
230 |
231 |
232 | /**
233 | * 初始化上下文,清理上一排列留下的脏数据
234 | */
235 | private void initCtx(){
236 | context.getCalcResult().setCurPrice(context.getOriginalPrice());
237 | CalcStage[] curArr =context.getCalcResult().getCurStages();
238 | //每次排列计算前初始化curStages为null
239 | Arrays.fill(curArr,null);
240 | //每次排列计算前reset usedList 中的单品价格,并清空
241 | context.getGoodsItems().forEach(this::resetItems);
242 | //清空黑名单
243 | context.getRecords().clear();
244 | //初始化Context
245 | resetContext(context);
246 | }
247 |
248 | /**
249 | * 构建保存点
250 | */
251 | private CalcState makeSnapshot(){
252 | CalcState state = new CalcState<>();
253 | state.setCurPrice(context.getCalcResult().getCurPrice());
254 | state.setCurStages(copyStage(context.getCalcResult().getCurStages()));
255 | state.setRecords(copyRecord(context.getRecords()));
256 | makeSnapshot(state,context);
257 | return state;
258 | }
259 |
260 |
261 | /**
262 | * 返回保存点
263 | * @param k 缓存的key
264 | */
265 | private void backToSnapshot(Integer k){
266 | CalcState state=(CalcState)cache.get(k);
267 | context.getCalcResult().setCurPrice(state.getCurPrice());
268 | context.getCalcResult().setCurStages(copyStage(state.getCurStages()));
269 | context.setRecords(copyRecord(state.getRecords()));
270 | backToSnapshot(state,context);
271 | }
272 |
273 |
274 | /**
275 | * 复制stages
276 | * @param curStages 当前stages
277 | */
278 | private CalcStage[] copyStage(CalcStage[] curStages){
279 | CalcStage[] cs=new CalcStage[curStages.length];
280 | System.arraycopy(curStages,0,cs,0,curStages.length);
281 | return cs;
282 | }
283 |
284 | /**
285 | * clone商品当前状态,转成map便于查找
286 | * @param goods 商品列表
287 | * @return
288 | */
289 | protected Map copyGoods(List goods){
290 | Map map=Maps.newHashMap();
291 | for(T good:goods){
292 | try {
293 | map.put(good.getCalculateId(),(T)good.clone());
294 | } catch (Exception ignore) {
295 | }
296 | }
297 | return map;
298 | }
299 |
300 | /**
301 | * 复制享受过优惠的商品记录,只用到calculateId,因此不对对象进行clone
302 | * @param records 享受过优惠的商品记录
303 | */
304 | private Map copyRecord(Map records){
305 | return Maps.newHashMap(records);
306 | }
307 |
308 | /**
309 | * 相同最优解的处理逻辑,交给业务来实现
310 | * @param stages 最终的stage数组
311 | * @param curStages 当前的stage数组
312 | * @return
313 | */
314 | protected abstract boolean sameOptimumCondition(CalcStage[] curStages);
315 |
316 | /**
317 | * context参数的重置逻辑,交给业务来实现
318 | * @param context 上下文
319 | */
320 | protected abstract void resetContext(DiscountContext context);
321 |
322 | /**
323 | * 开启缓存的条件,如 a.size>4
324 | * @param a 优惠排列
325 | */
326 | protected abstract boolean enableOptimize(List a);
327 |
328 | /**
329 | * 商品参数的重置逻辑,交给业务来实现
330 | * @param item 单品
331 | */
332 | protected abstract void resetItems(T item);
333 |
334 | /**
335 | * 业务将状态记录到保存点
336 | * @param state 保存点对象
337 | */
338 | protected abstract void makeSnapshot(CalcState state,DiscountContext context);
339 |
340 | /**
341 | * 业务返回保存点状态
342 | * @param state 保存点对象
343 | */
344 | protected abstract void backToSnapshot(CalcState state,DiscountContext context);
345 | }
346 |
--------------------------------------------------------------------------------
/src/main/java/com/github/qcalculator/core/precompute/PreCompute.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2022 CyrilFeng
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.github.qcalculator.core.precompute;
18 |
19 | import com.github.qcalculator.core.model.common.DiscountWrapper;
20 | import com.github.qcalculator.core.model.goods.GoodsItem;
21 |
22 | import java.util.List;
23 | import java.util.Map;
24 | import java.util.Set;
25 |
26 | /**
27 | * 预计算,把一些耗时操作放在Context中操作
28 | * @author: CyrilFeng
29 | * @date: 2022/8
30 | */
31 | public interface PreCompute {
32 |
33 | /**
34 | * 判断符合条件的活动类型,符合才会执行preComputeItems
35 | */
36 | Set matchTypes();
37 |
38 | /**
39 | * 对商品做一些复杂集合操作
40 | * @param items 当前参与优惠的商品
41 | * @param discount 当前优惠
42 | * @param preCompute 存储计算的结果
43 | */
44 | void preComputeItems(List items, DiscountWrapper discount, Map preCompute);
45 | }
46 |
--------------------------------------------------------------------------------
/src/main/java/com/github/qcalculator/core/precompute/PreComputeHolder.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2022 CyrilFeng
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.github.qcalculator.core.precompute;
18 | import com.google.common.collect.Sets;
19 | import org.apache.commons.lang3.StringUtils;
20 | import org.reflections.Reflections;
21 | import org.springframework.core.io.FileSystemResource;
22 | import org.springframework.core.io.support.PropertiesLoaderUtils;
23 | import java.util.Objects;
24 | import java.util.Properties;
25 | import java.util.Set;
26 |
27 | /**
28 | * PreCompute实现类的加载器,会扫描calculator-core文件中的precompute.path属性
29 | * @author: CyrilFeng
30 | * @date: 2022/8
31 | */
32 | @SuppressWarnings("all")
33 | public class PreComputeHolder {
34 | public static Set COMPUTES= Sets.newHashSet();
35 | private final static String PATH = "precompute.path";
36 |
37 | static{
38 | Properties properties = new Properties();
39 | try {
40 | properties = PropertiesLoaderUtils.loadProperties(new FileSystemResource(Objects.requireNonNull(PreComputeHolder.class.getClassLoader().getResource("calculator-core.properties")).getPath()));
41 | } catch (Exception ignore) {
42 | }
43 | String path = properties.getProperty(PATH);
44 | if(StringUtils.isNotBlank(path)){
45 | Reflections reflections = new Reflections(path);
46 | Set> subTypes = reflections.getSubTypesOf(PreCompute.class);
47 | for(Class extends PreCompute> clazz:subTypes){
48 | try {
49 | COMPUTES.add(clazz.newInstance());
50 | } catch (Exception ignore) {
51 | }
52 | }
53 | }
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/src/main/java/com/github/qcalculator/core/utils/DiscountGroupUtil.java:
--------------------------------------------------------------------------------
1 |
2 |
3 | package com.github.qcalculator.core.utils;
4 | import com.github.qcalculator.core.model.common.DiscountGroup;
5 | import com.github.qcalculator.core.model.common.DiscountWrapper;
6 | import com.github.qcalculator.core.model.common.Item;
7 | import com.github.qcalculator.core.permutation.Permutation;
8 | import com.google.common.collect.Lists;
9 | import com.google.common.collect.Maps;
10 | import com.google.common.collect.Sets;
11 | import com.google.common.util.concurrent.AtomicLongMap;
12 | import org.apache.commons.collections4.CollectionUtils;
13 | import org.apache.commons.collections4.MapUtils;
14 | import org.apache.commons.lang3.tuple.Pair;
15 | import java.util.*;
16 | import java.util.stream.Collectors;
17 |
18 |
19 | public class DiscountGroupUtil {
20 |
21 | private static final String EXCLUDE="exclude";
22 |
23 | /**
24 | * 返回所有共享组
25 | * Pair的left是长度不超过 Permutation.SUPPORTEDSIZE 的内容,right是第 Permutation.SUPPORTEDSIZE+1
26 | * 种优惠即其他优惠(若有),即不参与全排列的优惠
27 | * @param groups
28 | * @param inMap
29 | * @return
30 | */
31 | public static List,Set>> transform(List> groups, Map> inMap) {
32 | List,Set>> resultList = Lists.newArrayList();
33 | List> list = mergeGroups(groups,inMap);
34 | if(CollectionUtils.isEmpty(list)){
35 | return Lists.newArrayList();
36 | }
37 | for(List items:list){
38 | Set discountWrappers = items.stream().map(x->{
39 | if(inMap.containsKey(x.getType())){
40 | Map m=inMap.get(x.getType());
41 | if(m.containsKey(x.getId())){
42 | return m.get(x.getId());
43 | }
44 | }
45 | return null;
46 | }).filter(Objects::nonNull).collect(Collectors.toSet());
47 | if(CollectionUtils.isNotEmpty(discountWrappers) && discountWrappers.size()>=2){
48 | if(discountWrappers.size()> Permutation.SUPPORTEDSIZE) {
49 | resultList.add(balanceLR(discountWrappers));
50 | }else{
51 | resultList.add(Pair.of(discountWrappers, Sets.newHashSet()));
52 | }
53 | }
54 | }
55 | //优先计算短的共享组
56 | return resultList.stream().sorted(Comparator.comparing(x->x.getLeft().size(),Collections.reverseOrder())).collect(Collectors.toList());
57 | }
58 |
59 | /**
60 | * 保证mustuse的优惠进入left集合
61 | * @param discountWrappers 当前可用优惠
62 | */
63 | private static Pair,Set> balanceLR(Set discountWrappers){
64 | Set left=Sets.newHashSet();
65 | Set right=Sets.newHashSet();
66 | for(DiscountWrapper wrapper:discountWrappers){
67 | if(wrapper.isMustUse()){
68 | left.add(wrapper);
69 | }else{
70 | right.add(wrapper);
71 | }
72 | }
73 | if(left.size() it = right.iterator();
76 | while (c>0&&it.hasNext()){
77 | DiscountWrapper w = it.next();
78 | left.add(w);
79 | it.remove();
80 | c--;
81 | }
82 | }else if(left.size()>Permutation.SUPPORTEDSIZE){
83 | int c = left.size()-Permutation.SUPPORTEDSIZE;
84 | Iterator it = left.iterator();
85 | while (c>0&&it.hasNext()){
86 | DiscountWrapper w = it.next();
87 | right.add(w);
88 | it.remove();
89 | c--;
90 | }
91 | }
92 | return Pair.of(left,right);
93 | }
94 |
95 | /**
96 | * 合并规则转化为共享组
97 | * @param groups 所有规则大组
98 | * @param inMap 实际可用优惠
99 | */
100 | private static List> mergeGroups(List> groups,Map> inMap){
101 | if(CollectionUtils.isEmpty(groups) || MapUtils.isEmpty(inMap)){
102 | return null;
103 | }
104 | //resultList 接收最终的结果
105 | List> resultList = Lists.newArrayList();
106 | //ctx 全局计数器,对于独立共享组多次被使用进行删除(唯一需要去重的场景)
107 | AtomicLongMap ctx = AtomicLongMap.create();
108 | //索引,存放可能需要删除的key
109 | Map idxMap = Maps.newHashMap();
110 | for(List list:groups){
111 | mergeGroup(list,inMap,ctx,idxMap,resultList);
112 | }
113 | Map map = ctx.asMap();
114 | List orderedList = Lists.newArrayList();
115 | for(Map.Entry e:map.entrySet()){
116 | Integer idx = idxMap.get(e.getKey());
117 | if(Objects.nonNull(idx)&&e.getValue()>1){
118 | orderedList.add(idx);
119 | }
120 | }
121 | orderedList.sort(Collections.reverseOrder());
122 | //从后往前删除,否则索引会出问题
123 | for(Integer i:orderedList){
124 | resultList.remove(i.intValue());
125 | }
126 | return resultList.stream().filter(CollectionUtils::isNotEmpty).collect(Collectors.toList());
127 | }
128 |
129 | private static void mergeGroup(List groups,Map> inMap,
130 | AtomicLongMap ctx,Map idxMap,
131 | List> resultList){
132 | if(CollectionUtils.isEmpty(groups)){
133 | return ;
134 | }
135 | List xList = groups.get(0).filterItems(inMap);
136 | if(CollectionUtils.isEmpty(xList)){
137 | return ;
138 | }
139 | if(groups.size()==1){
140 | //必然是共享组
141 | //存入全局上下文,去重时使用,这里累计次数,若次数大于1,需要在最外层移除此共享组
142 | String key = uniqueKey(xList);
143 | ctx.incrementAndGet(key);
144 | //记录索引,以便删除
145 | idxMap.put(key,resultList.size());
146 | resultList.add(xList);
147 | }else{
148 | //yList必然是互斥的
149 | List yList = groups.get(1).filterItems(inMap);
150 | if(Objects.equals(EXCLUDE,groups.get(0).getRelation())){
151 | //产品设计规避了重复的情况,无需去重
152 | for(Item item:xList){
153 | for(Item item1:yList){
154 | resultList.add(Lists.newArrayList(item,item1));
155 | }
156 | }
157 | }else{
158 | //存入全局上下文,去重时使用,这里累计次数,若次数大于1,需要在最外层移除此共享组
159 | String k = uniqueKey(xList);
160 | for(Item item:yList){
161 | ctx.incrementAndGet(k);
162 | List xCopy = Lists.newArrayList(xList);
163 | xCopy.add(item);
164 | resultList.add(xCopy);
165 | }
166 | }
167 | }
168 | }
169 |
170 | private static String uniqueKey(List list){
171 | return list.stream().map(i->i.getType()+i.getId()).sorted().collect(Collectors.joining());
172 | }
173 |
174 | }
175 |
--------------------------------------------------------------------------------
/src/main/java/com/github/qcalculator/core/utils/IdGenerator.java:
--------------------------------------------------------------------------------
1 |
2 |
3 | package com.github.qcalculator.core.utils;
4 |
5 | /**
6 | * ID生成器,用于生成每次计算的商品id
7 | * 非线程安全,不可在多线程共享。 每次计算创建一个,用于生成具体每一个商品的唯一ID
8 | * @author: longlian
9 | * @date: 2022/7
10 | */
11 | public class IdGenerator {
12 |
13 | /**
14 | * 新建一个对象,默认构造
15 | */
16 | public static IdGenerator getInstance() {
17 | return new IdGenerator();
18 | }
19 |
20 | /**
21 | * 当前ID,默认从1开始
22 | */
23 | private long currentId = 1;
24 |
25 | /**
26 | * 按序列生成一个ID
27 | */
28 | public long nextId() {
29 | return currentId++;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/com/github/qcalculator/core/utils/LimitingUtil.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2022 CyrilFeng
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.github.qcalculator.core.utils;
18 |
19 | import java.util.ArrayList;
20 | import java.util.List;
21 |
22 | /**
23 | * 统计计算次数的工具,在机器负载较大时,作为放弃后面计算的条件
24 | * @author: CyrilFeng
25 | * @date: 2022/8
26 | */
27 | public class LimitingUtil {
28 |
29 | /**
30 | * 统计计算次数
31 | * 根据性能压测结果,对于多个共享组来说是必要的
32 | * @param length 共享组的长度
33 | */
34 | public static int count(int length){
35 | switch (length){
36 | case 1:return 1;
37 | //下面的计算公式是 x!*x
38 | case 2:return 4;
39 | case 3:return 18;
40 | //下面的计算公式是 x!*(x-3)+p(x,3)
41 | case 4:return 48;
42 | case 5:return 300;
43 | case 6:return 2280;
44 | case 7:return 20370;
45 | default:return 0;
46 | }
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/main/java/com/github/qcalculator/demo/App.java:
--------------------------------------------------------------------------------
1 | package com.github.qcalculator.demo;
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("com.github.qcalculator")
9 | public class App
10 | {
11 | public static void main( String[] args )
12 | {
13 | SpringApplication.run(App.class,args);
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/main/java/com/github/qcalculator/demo/biz/Flowable.java:
--------------------------------------------------------------------------------
1 | package com.github.qcalculator.demo.biz;
2 |
3 | import com.github.qcalculator.core.model.common.CalcStage;
4 | import com.github.qcalculator.core.model.common.CalcState;
5 | import com.github.qcalculator.core.model.common.DiscountContext;
6 | import com.github.qcalculator.core.model.goods.GoodsItem;
7 | import com.github.qcalculator.core.permutation.Permutation;
8 | import com.github.qcalculator.demo.biz.constant.Constant;
9 |
10 | import java.util.List;
11 |
12 | public class Flowable extends Permutation {
13 | @Override
14 | protected boolean enableOptimize(List a) {
15 | return false;
16 | }
17 |
18 | @Override
19 | protected boolean sameOptimumCondition(CalcStage[] curStages) {
20 | return false;
21 | }
22 |
23 | @Override
24 | protected void resetContext(DiscountContext context) {
25 |
26 | }
27 |
28 | @Override
29 | protected void resetItems(GoodsItem item) {
30 | item.getExtra().put(Constant.UPDATEABLEPRICE,item.getSalePrice());
31 | }
32 |
33 | @Override
34 | protected void makeSnapshot(CalcState state, DiscountContext context) {
35 |
36 | }
37 |
38 | @Override
39 | protected void backToSnapshot(CalcState state, DiscountContext context) {
40 |
41 | }
42 |
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/src/main/java/com/github/qcalculator/demo/biz/TestController.java:
--------------------------------------------------------------------------------
1 | package com.github.qcalculator.demo.biz;
2 |
3 | import com.github.qcalculator.core.enums.GroupRelation;
4 | import com.github.qcalculator.core.model.common.*;
5 | import com.github.qcalculator.core.model.goods.GoodsInfo;
6 | import com.github.qcalculator.core.model.goods.GoodsItem;
7 | import com.github.qcalculator.core.utils.DiscountGroupUtil;
8 | import com.github.qcalculator.core.utils.IdGenerator;
9 | import com.github.qcalculator.core.utils.LimitingUtil;
10 | import com.github.qcalculator.demo.biz.constant.Constant;
11 | import com.github.qcalculator.core.aware.CalculatorRouter;
12 | import com.google.common.collect.ImmutableMap;
13 | import com.google.common.collect.Lists;
14 | import org.apache.commons.lang3.tuple.Pair;
15 | import org.springframework.stereotype.Controller;
16 | import org.springframework.web.bind.annotation.RequestMapping;
17 | import org.springframework.web.bind.annotation.ResponseBody;
18 |
19 | import java.util.*;
20 | import java.util.stream.Collectors;
21 |
22 | @Controller
23 | public class TestController {
24 |
25 | private final CalculatorRouter calculatorRouter;
26 |
27 | public TestController(CalculatorRouter calculatorRouter) {
28 | this.calculatorRouter = calculatorRouter;
29 | }
30 |
31 | @RequestMapping("test")
32 | @ResponseBody
33 | public Object test() {
34 | //mock商品
35 | List items = mockItems();
36 | //mock组关系并转化为共享组
37 | List,Set>> pairs = transform(mockGroups());
38 | //全局最优计算过程
39 | List globalStages=Lists.newArrayList();
40 | int count = 0;
41 | //订单总金额
42 | long totalPrice = items.stream().mapToLong(GoodsInfo::getSalePrice).sum();
43 | long globalPrice = totalPrice;
44 | //构建计算流
45 | Flowable flowable = (Flowable) new Flowable().build(calculatorRouter);
46 | for(Pair,Set> set:pairs) {
47 | //统计算力
48 | count += LimitingUtil.count(set.getLeft().size());
49 | if(count>100000){
50 | break;
51 | }
52 | List wrappers = Lists.newArrayList(set.getLeft());
53 | DiscountContext ctx = DiscountContext.create(totalPrice, Lists.newArrayList(items), wrappers);
54 | flowable.perm(ctx);
55 | if(ctx.getCalcResult().getFinalPrice() < globalPrice) {
56 | globalStages = Arrays.asList(ctx.getCalcResult().getStages());
57 | globalPrice = ctx.getCalcResult().getFinalPrice();
58 | }
59 | }
60 | return Pair.of(globalPrice,globalStages);
61 | }
62 |
63 | private List> mockGroups(){
64 | List> groups = Lists.newArrayList();
65 | DiscountGroup group = new DiscountGroup();
66 | group.setRelation(GroupRelation.SHARE.getType());
67 | group.setItems(Lists.newArrayList(new Item("zhekou","1"),new Item("manjian","2"),new Item("manzeng","3")));
68 | groups.add(Lists.newArrayList(group));
69 | return groups;
70 | }
71 |
72 | private List mockItems(){
73 | IdGenerator idGenerator = IdGenerator.getInstance();
74 | GoodsInfo goodsInfo = GoodsInfo.of(1001L,2001L,null,4,20 * 100,"产品1",null);
75 | GoodsInfo goodsInfo2 = GoodsInfo.of(1001L,2002L,null,2,10 * 100,"产品1",null);
76 | List items = GoodsItem.generateItems(goodsInfo,idGenerator,x->x.getExtra().put(Constant.UPDATEABLEPRICE,x.getSalePrice()));
77 | items.addAll(GoodsItem.generateItems(goodsInfo2,idGenerator,x->x.getExtra().put(Constant.UPDATEABLEPRICE,x.getSalePrice())));
78 | return items;
79 | }
80 |
81 | private List,Set>> transform(List> groups){
82 | List wrapperList = Lists.newArrayList(
83 | DiscountWrapper.of("zhekou", "1", "折扣", false, new DiscountConfig()),
84 | DiscountWrapper.of("manjian", "2", "满减", false, new DiscountConfig())
85 | );
86 | Map> inMap = wrapperList.stream().collect(Collectors.toMap(DiscountWrapper::getType, x->ImmutableMap.of(x.getId(),x)));
87 | return DiscountGroupUtil.transform(groups,inMap);
88 | }
89 |
90 | }
91 |
--------------------------------------------------------------------------------
/src/main/java/com/github/qcalculator/demo/biz/calc/ManjianCalc.java:
--------------------------------------------------------------------------------
1 | package com.github.qcalculator.demo.biz.calc;
2 |
3 | import com.github.qcalculator.core.discount.impl.AbstractCalculator;
4 | import com.github.qcalculator.core.model.common.CalcStage;
5 | import com.github.qcalculator.core.model.common.DiscountContext;
6 | import com.github.qcalculator.core.model.common.DiscountWrapper;
7 | import com.github.qcalculator.core.model.goods.GoodsItem;
8 | import com.github.qcalculator.demo.biz.constant.Constant;
9 | import com.google.common.collect.Lists;
10 | import org.springframework.stereotype.Component;
11 | import java.util.List;
12 | import java.util.Map;
13 |
14 | @Component("manjian")
15 | public class ManjianCalc extends AbstractCalculator {
16 |
17 | @Override
18 | public long calc(DiscountContext context, DiscountWrapper discountWrapper, Map records, long prevStagePrice, CalcStage curStage) {
19 | List items = Lists.newArrayList(context.getDiscountItemGroup().get(discountWrapper.getId()));
20 | if(prevStagePrice>=100*100) {
21 | prevStagePrice = prevStagePrice - 20 * 100;
22 | }
23 | //均摊
24 | for(GoodsItem item:items){
25 | item.getExtra().put(Constant.UPDATEABLEPRICE,(long)item.getExtra().get(Constant.UPDATEABLEPRICE)-(long)(20*100/items.size()));
26 | }
27 | return prevStagePrice;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/main/java/com/github/qcalculator/demo/biz/calc/ZhekouCalc.java:
--------------------------------------------------------------------------------
1 | package com.github.qcalculator.demo.biz.calc;
2 |
3 | import com.github.qcalculator.core.discount.impl.AbstractCalculator;
4 | import com.github.qcalculator.core.model.common.CalcStage;
5 | import com.github.qcalculator.core.model.common.DiscountContext;
6 | import com.github.qcalculator.core.model.common.DiscountWrapper;
7 | import com.github.qcalculator.core.model.goods.GoodsItem;
8 | import com.github.qcalculator.demo.biz.constant.Constant;
9 | import com.google.common.collect.Lists;
10 | import org.apache.commons.collections4.CollectionUtils;
11 | import org.springframework.stereotype.Component;
12 | import java.util.Collection;
13 | import java.util.List;
14 | import java.util.Map;
15 |
16 | @Component("zhekou")
17 | @SuppressWarnings("unchecked")
18 | public class ZhekouCalc extends AbstractCalculator {
19 |
20 | @Override
21 | public long calc(DiscountContext context, DiscountWrapper discountWrapper, Map records, long prevStagePrice, CalcStage curStage) {
22 | List items = Lists.newArrayList(context.getDiscountItemGroup().get(discountWrapper.getId()));
23 | Map> map = (Map>)context.getPreCompute().get("GroupBySkuIdPreCompute");
24 | long maxPrice = 0L;
25 | Collection group = CollectionUtils.EMPTY_COLLECTION;
26 | for(Collection c:map.values()){
27 | long tmp = (long)c.iterator().next().getExtra().get(Constant.UPDATEABLEPRICE);
28 | if(tmp>maxPrice){
29 | maxPrice=tmp;
30 | group = c;
31 | }
32 | }
33 | long discount = (long)(maxPrice*group.size()*0.2);
34 | //均摊
35 | for (GoodsItem item : group) {
36 | item.getExtra().put(Constant.UPDATEABLEPRICE, (long) item.getExtra().get(Constant.UPDATEABLEPRICE) - discount / items.size());
37 | }
38 | return prevStagePrice-discount;
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/main/java/com/github/qcalculator/demo/biz/constant/Constant.java:
--------------------------------------------------------------------------------
1 | package com.github.qcalculator.demo.biz.constant;
2 |
3 | public class Constant {
4 |
5 | public static final String UPDATEABLEPRICE = "updateablePrice";
6 |
7 | }
8 |
--------------------------------------------------------------------------------
/src/main/java/com/github/qcalculator/demo/biz/precompute/PreGroupBy.java:
--------------------------------------------------------------------------------
1 | package com.github.qcalculator.demo.biz.precompute;
2 |
3 | import com.github.qcalculator.core.model.common.DiscountWrapper;
4 | import com.github.qcalculator.core.model.goods.GoodsInfo;
5 | import com.github.qcalculator.core.model.goods.GoodsItem;
6 | import com.github.qcalculator.core.precompute.PreCompute;
7 | import com.google.common.collect.Sets;
8 | import java.util.List;
9 | import java.util.Map;
10 | import java.util.Set;
11 | import java.util.stream.Collectors;
12 |
13 | public class PreGroupBy implements PreCompute {
14 | @Override
15 | public Set matchTypes() {
16 | return Sets.newHashSet("zhekou");
17 | }
18 |
19 | @Override
20 | public void preComputeItems(List items, DiscountWrapper discount, Map preCompute) {
21 | preCompute.put("GroupBySkuIdPreCompute",items.stream().collect(Collectors.groupingBy
22 | (GoodsInfo::getSkuId,Collectors.collectingAndThen(Collectors.toList(),
23 | e->e.stream().sorted().collect(Collectors.toList())))));
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/resources/calculator-core.properties:
--------------------------------------------------------------------------------
1 | precompute.path=com.github.qcalculator.demo.biz
--------------------------------------------------------------------------------