OrderService.php 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187
  1. <?php
  2. namespace app\api\service;
  3. use app\common\model\ActivityProductModel;
  4. use app\common\model\AdminModel;
  5. use app\common\model\ConfigModel;
  6. use app\common\model\CreditCardConfigModel;
  7. use app\common\model\CustomerModel;
  8. use app\common\model\CustomerZueCoinModel;
  9. use app\common\model\OrderAnnualFeeModel;
  10. use app\common\model\OrderModel;
  11. use app\common\model\OrderPaymentModel;
  12. use app\common\model\OrderProceedsModel;
  13. use app\common\model\OrderProductModel;
  14. use app\common\model\PaymentChannelModel;
  15. use app\common\model\ProductModel;
  16. use app\common\model\StoreModel;
  17. use app\common\model\StoreProductModel;
  18. use app\common\model\ZueCoinRecordModel;
  19. use app\exception\BaseException;
  20. use think\facade\Db;
  21. class OrderService extends \app\BaseService
  22. {
  23. private $storeModel;
  24. private $orderModel;
  25. private $productModel;
  26. private $orderAnnualFeeModel;
  27. private $orderPaymentModel;
  28. private $orderProductModel;
  29. private $orderProceedsModel;
  30. private $activityProductModel;
  31. private $storeProductModel;
  32. private $configModel;
  33. private $adminModel;
  34. private $customerModel;
  35. private $paymentChannelModel;
  36. private $creditCardModel;
  37. private $zueCoinModel;
  38. private $zueCoinRecordModel;
  39. public function __construct()
  40. {
  41. $this->storeModel = new StoreModel();
  42. $this->orderModel = new OrderModel();
  43. $this->productModel = new ProductModel();
  44. $this->configModel = new ConfigModel();
  45. $this->storeProductModel = new StoreProductModel();
  46. $this->orderAnnualFeeModel = new OrderAnnualFeeModel();
  47. $this->orderPaymentModel = new OrderPaymentModel();
  48. $this->orderProductModel = new OrderProductModel();
  49. $this->orderProceedsModel = new OrderProceedsModel();
  50. $this->activityProductModel = new ActivityProductModel();
  51. $this->adminModel = new AdminModel();
  52. $this->customerModel = new CustomerModel();
  53. $this->paymentChannelModel = new PaymentChannelModel();
  54. $this->creditCardModel = new CreditCardConfigModel();
  55. $this->zueCoinModel = new CustomerZueCoinModel();
  56. $this->zueCoinRecordModel = new ZueCoinRecordModel();
  57. }
  58. /**
  59. * @param $params
  60. * @param array $store_products_params
  61. * @return \SResult
  62. * @throws \think\db\exception\DataNotFoundException
  63. * @throws \think\db\exception\DbException
  64. * @throws \think\db\exception\ModelNotFoundException
  65. */
  66. public function create($params, array $store_products_params) {
  67. // 客户
  68. $customer = $this->customerModel->findById($params['customer_id']);
  69. if (!$customer)
  70. return $this->fail(lang("The Customer does not exist"));
  71. // 门店
  72. $store = $this->storeModel->findById($params['store_id']);
  73. if (!$store)
  74. return $this->fail(lang("The store does not exist"));
  75. // 顾问 or 老师 ids
  76. $user_ids = [];
  77. // 门店商品ids
  78. $store_product_ids = [];
  79. for ($i = 0; $i < count($store_products_params); $i++) {
  80. $store_products_param = $store_products_params[$i];
  81. $ids = [];
  82. if(isset($store_products_param->adviser_1_id)) array_push($ids, $store_products_param->adviser_1_id);
  83. if(isset($store_products_param->adviser_2_id)) array_push($ids, $store_products_param->adviser_2_id);
  84. if(isset($store_products_param->teacher_1_id)) array_push($ids, $store_products_param->teacher_1_id);
  85. if(isset($store_products_param->teacher_2_id)) array_push($ids, $store_products_param->teacher_2_id);
  86. $user_ids = array_unique(array_merge($user_ids, $ids));
  87. array_push($store_product_ids, $store_products_param->store_product_id);
  88. }
  89. // Adviser|Teacher
  90. $users = $this->adminModel->findByIds($user_ids)->toArray();
  91. if(count($users) != count($user_ids))
  92. return $this->fail(lang("The Adviser|Teacher does not exist"));
  93. $fmt_users = array_reduce($users, function ($result, $item) {
  94. $result[$item['id']] = $item;
  95. return $result;
  96. }, []);
  97. // 门店商品
  98. $store_products = $this->storeProductModel->fetchRelationsByOrder($store_product_ids)->toArray();
  99. if(count($store_products) != count($store_product_ids))
  100. return $this->fail(lang("The Product does not exist"));
  101. // 商品信息
  102. $products = array_map(function ($p) {
  103. return $p['product'] ? $p['product'] : null;
  104. }, $store_products);
  105. if(in_array(null, $products))
  106. return $this->fail(lang("The Product does not exist"));
  107. $config = $this->configModel->findConfig();
  108. $activityProducts = $this->activityProductModel->fetchByProductIds(array_map(function ($data) {
  109. return $data['id'];
  110. }, $products))->toArray();
  111. $fmt_store_products = [];
  112. foreach ($store_products as &$item) {
  113. $aProducts = array_filter($activityProducts, function ($aProduct) use ($item) {
  114. return $aProduct['product_id'] == $item['product_id'];
  115. });
  116. $res = compare($item['product']['real_price'] ?? 0, $aProducts);
  117. $item['activity'] = $res['item'];
  118. $item['product']['origin_price'] = $item['product']['real_price'];
  119. $item['product']['real_price'] = fixed2Float($res['min_num'] > 0 ? $res['min_num'] : 0);
  120. $sales_tax_rate = $item['product']['sales_tax_rate'] > 0 ? $item['product']['sales_tax_rate'] : $config->sales_tax_rate;
  121. $sales_tax = fixed2Float($sales_tax_rate > 0 && $item['product']['real_price'] > 0 ? ($item['product']['real_price'] * ($sales_tax_rate / 100)) : 0);
  122. $item['product']['sales_tax_rate'] = $sales_tax_rate;
  123. $item['product']['sales_tax'] = $sales_tax;
  124. $fmt_store_products[$item['id']] = $item;
  125. }
  126. $order_products = [];
  127. //项目总额
  128. $rental_amount = 0;
  129. $product_amount = 0;
  130. // 总消费税
  131. $total_sales_tax = 0;
  132. $advisor_ids = [];
  133. $product_names = [];
  134. $total_annual_fee = 0;
  135. $order_no = $this->orderModel->genOrderNo($store->id, $store->abbr);
  136. for ($i = 0; $i < count($store_products_params); $i++) {
  137. $store_products_param = $store_products_params[$i];
  138. $store_product = $fmt_store_products[$store_products_param->store_product_id];
  139. if($store_product['now_stock'] < $store_products_param->quantity)
  140. return $this->fail(lang("inventory shortage"));
  141. array_push($advisor_ids, $store_products_param->adviser_1_id);
  142. if(isset($store_products_param->adviser_2_id)) {
  143. array_push($advisor_ids, $store_products_param->adviser_2_id);
  144. }
  145. for ($j = 0; $j < $store_products_param->quantity; $j++) {
  146. array_push($product_names, $store_product['product']['name']);
  147. array_push($order_products, [
  148. 'order_id' => 0,
  149. 'order_no' => $order_no,
  150. 'customer_id' => $customer->id,
  151. 'product_id' => $store_product['product']['id'],
  152. 'product_category_id' => $store_product['product']['category_id'],
  153. 'is_serve' => $store_product['product']['is_serve'],
  154. 'store_product_id' => $store_product['id'],
  155. 'product_name' => $store_product['product']['name'],
  156. 'adviser_1_id' => isset($store_products_param->adviser_1_id) ? $store_products_param->adviser_1_id : null,
  157. 'adviser_1_name' => isset($store_products_param->adviser_1_id) ? $fmt_users[$store_products_param->adviser_1_id]['nickname'] : null,
  158. 'adviser_2_id' => isset($store_products_param->adviser_2_id) ? $store_products_param->adviser_2_id : null,
  159. 'adviser_2_name' => isset($store_products_param->adviser_2_id) ? $fmt_users[$store_products_param->adviser_2_id]['nickname'] : null,
  160. 'teacher_1_id' => isset($store_products_param->teacher_1_id) ? $store_products_param->teacher_1_id : null,
  161. 'teacher_1_name' => isset($store_products_param->teacher_1_id) ? $fmt_users[$store_products_param->teacher_1_id]['nickname'] : null,
  162. 'teacher_2_id' => isset($store_products_param->teacher_2_id) ? $store_products_param->teacher_2_id : null,
  163. 'teacher_2_name' => isset($store_products_param->teacher_2_id) ? $fmt_users[$store_products_param->teacher_2_id]['nickname'] : null,
  164. 'is_upload_numerology' => $store_product['product']['is_upload_numerology'],
  165. 'is_upload' => 0,
  166. 'report' => null,
  167. 'is_gather_annuity' => $store_product['product']['is_gather_annuity'],
  168. 'annuity' => $store_product['product']['annuity'],
  169. 'real_price' => $store_product['product']['real_price'],
  170. 'service_charge' => 0,
  171. 'reduce_price' => $store_product['activity'] ? $store_product['product']['origin_price'] - $store_product['product']['real_price'] : 0,
  172. 'reduce_type' => $store_product['activity'] ? $store_product['activity']['type'] : 0,
  173. 'sales_tax_rate' => $store_product['product']['sales_tax_rate'],
  174. 'sales_tax' => $store_product['product']['sales_tax'],
  175. 'transaction_price' => fixed2Float($store_product['product']['real_price'] + $store_product['product']['sales_tax'] + $store_product['product']['annuity']),
  176. 'zue_coin' => 0,
  177. 'create_time' => time(),
  178. 'update_time' => time(),
  179. ]);
  180. $product_amount += $store_product['product']['real_price'];
  181. $total_sales_tax += $store_product['product']['sales_tax'];
  182. if($store_product['product']['is_gather_annuity'] == 1) {
  183. $total_annual_fee += $store_product['product']['annuity'];
  184. $rental_amount += ($store_product['product']['real_price'] + $store_product['product']['sales_tax'] + $store_product['product']['annuity']);
  185. } else {
  186. $rental_amount += ($store_product['product']['real_price'] + $store_product['product']['sales_tax']);
  187. }
  188. }
  189. }
  190. $order = $this->orderModel->create([
  191. 'no' => $order_no,
  192. 'customer_id' => $customer->id,
  193. 'customer_name' => "{$customer->name_en}|{$customer->name_zh}",
  194. 'obj_names' => join(',',array_unique($product_names)),
  195. 'rental_amount' => $rental_amount,
  196. 'receivable_amount' => $rental_amount,
  197. 'receive_amount' => 0,
  198. 'imposed_amount' => $rental_amount,
  199. 'product_amount' => $product_amount,
  200. 'total_sales_tax' => $total_sales_tax,
  201. 'service_charge_amount' => 0,
  202. 'total_annual_fee' => $total_annual_fee,
  203. 'type' => 2,
  204. 'store_id' => $store->id,
  205. 'advisor_ids' => join(',', array_unique($advisor_ids)),
  206. 'create_time' => time(),
  207. 'update_time' => time()
  208. ]);
  209. foreach ($order_products as &$order_product) $order_product['order_id'] = $order->id;
  210. Db::startTrans();
  211. try {
  212. Db::table('erp_order_product')->insertAll($order_products);
  213. Db::commit();
  214. } catch (\Exception $e) {
  215. Db::rollback();
  216. Db::table('erp_order')->delete($order->id);
  217. return $this->fail(lang($e->getMessage()));
  218. }
  219. return $this->ok($order);
  220. }
  221. /**
  222. * @param $params
  223. * @param $channels
  224. * @return \SResult
  225. * @throws \app\exception\BaseException
  226. * @throws \think\db\exception\DataNotFoundException
  227. * @throws \think\db\exception\DbException
  228. * @throws \think\db\exception\ModelNotFoundException
  229. */
  230. public function payment($params, $channels) {
  231. $order = $this->orderModel->findById($params);
  232. if(!$order)
  233. return $this->fail(lang("Order does not exist"));
  234. if($order->type == 1)
  235. return $this->fail('订单状态为历史订单!不支持付款');
  236. // 客户
  237. $customer = $this->customerModel->findById($order->customer_id);
  238. if (!$customer)
  239. return $this->fail(lang("The Customer does not exist"));
  240. $pay_channels = $this->paymentChannelModel->where('is_delete', 0)->select()->toArray();
  241. $fmt_pay_channels = array_reduce($pay_channels, function ($result, $item) {
  242. $result[$item['id']] = $item;
  243. return $result;
  244. },[]);
  245. $credit_card_configs = $this->creditCardModel->findAll()->toArray();
  246. $fmt_credit_card_configs = array_reduce($credit_card_configs, function ($result, $item) {
  247. $result[$item['id']] = $item;
  248. return $result;
  249. },[]);
  250. // 本次总计支付费用
  251. $total_fee = 0;
  252. // 本次信用卡支付手续费
  253. $service_charge = 0;
  254. // 本次御龙币
  255. $zue_coin = 0;
  256. $order_payments = [];
  257. $record_channel_names = [];
  258. for ($i = 0; $i < count($channels); $i++) {
  259. $channel = $channels[$i];
  260. $fmt_pay_channel = $fmt_pay_channels[$channel->channel_id];
  261. if (!$fmt_pay_channel)
  262. return $this->fail("支付渠道错误!");
  263. array_push($record_channel_names, '['.$fmt_pay_channel['name'].']');
  264. $item = [
  265. 'order_id' => $order->id,
  266. 'channel_id' => $channel->channel_id,
  267. 'channel_name' => $fmt_pay_channel['name'],
  268. 'create_time' => time(),
  269. 'update_time' => time(),
  270. ];
  271. if ($fmt_pay_channel['type'] == 1) { // 正常支付
  272. predicate(isset($channel->fee) && $channel->fee > 0, '支付费用未填写');
  273. $item['fee'] = $channel->fee;
  274. $total_fee += $channel->fee;
  275. if ($fmt_pay_channel['is_upload_code']) {
  276. predicate(isset($channel->code),'必须上传付款编号');
  277. $item['code'] = $channel->code;
  278. }
  279. array_push($order_payments, $item);
  280. } else if($fmt_pay_channel['type'] == 2) { // 御龙币支付
  281. predicate(isset($channel->fee) && $channel->fee > 0, '支付费用未填写');
  282. $item['fee'] = $channel->fee;
  283. // TODO: 御龙币需求未明确
  284. array_push($order_payments, $item);
  285. $zue_coin += $channel->fee;
  286. } else {
  287. for ($j = 0; $j < count($channel->credit_card); $j++) {
  288. $credit_card = $channel->credit_card[$j];
  289. $fmt_credit_card_config = $fmt_credit_card_configs[$credit_card->credit_card_id];
  290. if (!$fmt_credit_card_config)
  291. return $this->fail("信用卡支付渠道错误!");
  292. predicate(isset($credit_card->fee) && $credit_card->fee > 0, '支付费用未填写');
  293. $total_fee += $credit_card->fee;
  294. $el = [
  295. 'order_id' => $order->id,
  296. 'channel_id' => $channel->channel_id,
  297. 'channel_name' => $fmt_pay_channel['name'],
  298. 'fee' => $credit_card->fee,
  299. 'credit_card_id' => $credit_card->credit_card_id,
  300. 'credit_card_name' => $fmt_credit_card_config['bank'],
  301. 'create_time' => time(),
  302. 'update_time' => time(),
  303. ];
  304. if ($fmt_pay_channel['is_upload_code']) {
  305. predicate(isset($credit_card->code),'必须填写付款编号');
  306. $el['code'] = $credit_card->code;
  307. }
  308. if ($fmt_credit_card_config['is_stage'] == 1) {
  309. predicate(isset($credit_card->stage_num),'必须选择分期数');
  310. $el['stage_num'] = $credit_card->stage_num;
  311. $config = [
  312. '6' => $fmt_credit_card_config['stage_6'],
  313. '9' => $fmt_credit_card_config['stage_9'],
  314. '12' => $fmt_credit_card_config['stage_12'],
  315. '24' => $fmt_credit_card_config['stage_24'],
  316. '36' => $fmt_credit_card_config['stage_36'],
  317. ];
  318. $now_config = $config[$credit_card->stage_num];
  319. predicate($now_config[0] == 1,'该分期未启用!');
  320. if ($now_config[1] > 0) { // 收取手续费
  321. $el['service_charge_rate'] = $now_config[1];
  322. $now_service_charge = $el['fee'] * ($now_config[1] / 100);
  323. $el['service_charge'] = $now_service_charge;
  324. $service_charge += $now_service_charge;
  325. }
  326. }
  327. array_push($order_payments, $el);
  328. }
  329. }
  330. }
  331. // 信用卡手续费
  332. $total_service_charge_amount = ($order->service_charge_amount + $service_charge);
  333. // 总共需要收取这么多费用; (商品的价格 + 商品税费 + 年费 + 信用卡手续费) - 御龙币抵扣的费用
  334. $imposed_amount = fixed2Float($order->product_amount + $order->total_sales_tax + $order->total_annual_fee + $total_service_charge_amount);
  335. $order_use_zue_coin = $order->zue_coin;
  336. $order_use_zue_coin_amount = $order->zue_coin_amount;
  337. $change_zue_coin_record = null;
  338. $zue_coin_model = $this->zueCoinModel->findByCustomerId($customer->id);
  339. $zue_coin_exchange_rate = 0;
  340. if($zue_coin > 0) {
  341. if(!$zue_coin_model)
  342. return $this->fail("当前客户御龙币账户余额: 0");
  343. if ($zue_coin > $zue_coin_model->zue_coin)
  344. return $this->fail("当前客户御龙币账户余额:{$zue_coin_model->zue_coin}");
  345. $zue_coin_config = $fmt_pay_channels['11'];
  346. if(!$zue_coin_config)
  347. return $this->fail("御龙币设置不存在!");
  348. $zue_coin_exchange_rate = $zue_coin_config['zue_coin_exchange_rate'] ?? 0; // 兑换比例
  349. $zue_coin_consume_rate = $zue_coin_config['zue_coin_consume_rate'] ?? 0; // 报销比例
  350. if($zue_coin_exchange_rate == 0 || $zue_coin_consume_rate == 0) {
  351. return $this->fail("该笔订单不支持御龙币支付");
  352. }
  353. // 1.计算出该订单能使用多少御龙币
  354. // 2.结合之前已使用的御龙币 算出还能使用多少御龙币
  355. // 3.判断当前御龙币是否符合兑换数额
  356. // 4.进行扣除并记录
  357. // 根据御龙币的设置 总共能报销这么多钱
  358. $max_consume_amount = fixed2Float($imposed_amount * ($zue_coin_consume_rate / 100));
  359. // 根据御龙币的设置 最大的报销的御龙币
  360. $max_consume_zue_coin = fixed2Float($max_consume_amount / $zue_coin_exchange_rate);
  361. if ($max_consume_zue_coin - ($order->zue_coin + $zue_coin) < 0) {
  362. return $this->fail("最多能使用御龙币: {$max_consume_zue_coin}, 当前已使用{$order->zue_coin}");
  363. }
  364. // 根据当前订单支付情况 得出现在最大的报销金额;
  365. $now_max_consume_amount = $order->imposed_amount < $max_consume_amount ? $order->imposed_amount : $max_consume_amount;
  366. // 当前最多还能使用多少御龙币
  367. $now_can_consume_zue_coin = fixed2Float($now_max_consume_amount / $zue_coin_exchange_rate);
  368. // 判断当前还能使用
  369. if ($now_can_consume_zue_coin - $zue_coin < 0)
  370. return $this->fail("当前剩余可使用的: {$now_can_consume_zue_coin}");
  371. // 总共使用了这么多御龙币
  372. $order_use_zue_coin += $zue_coin;
  373. // 总共兑换了这么多钱
  374. $order_use_zue_coin_amount = fixed2Float($order_use_zue_coin * $zue_coin_exchange_rate);
  375. $change_zue_coin_record = [
  376. 'zue_coin_id' => $zue_coin_model->id,
  377. 'order_id' => $order->id,
  378. 'origin' => $zue_coin_model->zue_coin,
  379. 'change' => -$zue_coin,
  380. 'after' => $zue_coin_model->zue_coin - $zue_coin,
  381. 'reason' => 1,
  382. 'create_time' => time(),
  383. 'update_time' => time(),
  384. ];
  385. }
  386. // 总计费用 - 御龙币抵消费用;
  387. $imposed_amount -= $order_use_zue_coin_amount;
  388. // 总计实收金额
  389. $receive_amount = fixed2Float($order->receive_amount + $total_fee);
  390. if (round($receive_amount) > round($imposed_amount)) return $this->fail("实收金额大于待收金额! 当前已付款: {$order->receive_amount} / {$order->receivable_amount} (商品总价:{$order->product_amount} + 商品总消费税:{$order->total_sales_tax} + 第一年年费:{$order->total_annual_fee} + 信用卡总手续费:{$order->service_charge_amount})");
  391. $order_annual_fees = [];
  392. $update_store_products = [];
  393. $update_order_products = [];
  394. if (round($receive_amount) == round($imposed_amount)) { // 减库存
  395. $order_products = $this->orderProductModel->findByOrderId($order->id)->toArray();
  396. $store_products = $this->storeProductModel->findByIds(array_map(function ($r) {return $r['store_product_id'];}, $order_products))->toArray();
  397. $fmt_store_products = array_reduce($store_products, function ($result, $item) {
  398. $result[$item['id']] = $item;
  399. return $result;
  400. },[]);
  401. // 商品本身的价格 | 年费 | 消费税
  402. $total_ = $order->product_amount + $order->total_annual_fee + $order->total_sales_tax;
  403. // 信用卡手续费 每一块钱所占的比例
  404. $item_service_charge_rate = ($order->service_charge_amount + $service_charge) / $total_;
  405. // 每一个御龙币所占的比例
  406. $item_zue_coin_rate = $order_use_zue_coin / $total_;
  407. foreach ($order_products as $order_product) {
  408. predicate($fmt_store_products[$order_product['store_product_id']]['now_stock'] > 0, lang('inventory shortage'));
  409. $fmt_store_products[$order_product['store_product_id']]['now_stock'] -= 1;
  410. if (isset($update_store_products[$order_product['store_product_id']])) {
  411. $update_store_products[$order_product['store_product_id']]['reduce_num'] += 1;
  412. } else {
  413. $update_store_products[$order_product['store_product_id']] = ['id' => $order_product['store_product_id'], 'reduce_num' => 1];
  414. }
  415. if ($order_product['is_gather_annuity'] && $order_product['annuity'] > 0) {
  416. $adviser_ids = [];
  417. if($order_product['adviser_1_id']) {
  418. array_push($adviser_ids, $order_product['adviser_1_id']);
  419. }
  420. if($order_product['adviser_2_id']) {
  421. array_push($adviser_ids, $order_product['adviser_2_id']);
  422. }
  423. array_push($order_annual_fees, [
  424. 'order_id' => $order->id,
  425. 'customer_id' => $customer->id,
  426. 'customer_name' => "{$customer->name_en}|{$customer->name_zh}",
  427. 'customer_mobile' => $customer->mobile,
  428. 'customer_create_username' => $customer->create_username,
  429. 'index' => 1,
  430. 'order_product_id' => $order_product['id'],
  431. 'order_product_name' => $order_product['product_name'],
  432. 'fee' => $order_product['annuity'],
  433. 'is_pay' => 1,
  434. 'start_time' => time(),
  435. 'end_time' => time() + (365 * 24 * 60 * 60),
  436. 'order_create_time' => strtotime($order->create_time),
  437. 'adviser_ids' => join(',', $adviser_ids),
  438. 'store_id' => $order->store_id,
  439. 'create_time' => time(),
  440. 'update_time' => time()
  441. ]);
  442. }
  443. $now = $order_product['real_price'] + $order_product['annuity'] + $order_product['sales_tax'];
  444. $item_service_charge = fixed2Float($now * $item_service_charge_rate);
  445. $item_zue_coin = fixed2Float($now * $item_zue_coin_rate);
  446. $item_zue_coin_amount = fixed2Float($item_zue_coin * $zue_coin_exchange_rate);
  447. $transaction_price = fixed2Float($now + $item_service_charge - $item_zue_coin_amount);
  448. array_push($update_order_products, [
  449. 'id' => $order_product['id'],
  450. 'service_charge' => $item_service_charge,
  451. 'zue_coin' => $item_zue_coin,
  452. 'zue_coin_amount' => $item_zue_coin_amount,
  453. 'transaction_price' => $transaction_price,
  454. 'is_pay' => 1
  455. ]);
  456. }
  457. }
  458. Db::startTrans();
  459. try {
  460. $update_order = [
  461. 'rental_amount' => $imposed_amount + $order_use_zue_coin_amount,
  462. 'receivable_amount' => $imposed_amount,
  463. 'receive_amount' => $receive_amount,
  464. 'imposed_amount' => $imposed_amount - $receive_amount,
  465. 'service_charge_amount' => $order->service_charge_amount + $service_charge,
  466. 'zue_coin' => $order_use_zue_coin,
  467. 'zue_coin_amount' => $order_use_zue_coin_amount,
  468. 'remarks' => $params['remarks'] ?? null
  469. ];
  470. if (round($receive_amount) == round($imposed_amount)) { // 支付满了
  471. $update_order['type'] = 1;
  472. if(count($update_order_products) > 0) {
  473. foreach ($update_order_products as $item) {
  474. Db::table('erp_order_product')->where('id', $item['id'])->update($item);
  475. }
  476. }
  477. if(count($order_annual_fees) > 0) {
  478. Db::table('erp_order_annual_fee')->insertAll($order_annual_fees);
  479. }
  480. if(count($update_store_products) > 0) {
  481. foreach ($update_store_products as $update) {
  482. Db::table('erp_store_product')->where('id', $update['id'])->dec('now_stock',1)->update();
  483. Db::table('erp_store_product')->where('id', $update['id'])->inc('sale_stock',1)->update();
  484. }
  485. }
  486. }
  487. Db::table('erp_order_proceeds')->save([
  488. 'order_id' => $order->id,
  489. 'channels' => join(' ',$record_channel_names),
  490. 'fee' => $total_fee,
  491. 'admin_id' => $params['admin_id'],
  492. 'admin_name' => $params['admin_name'],
  493. 'create_time' => time(),
  494. 'update_time' => time(),
  495. ]);
  496. if ($zue_coin > 0 && $change_zue_coin_record != null) {
  497. Db::table('erp_zue_coin_record')->save($change_zue_coin_record);
  498. Db::table('erp_customer_zue_coin')->where('id', $change_zue_coin_record['zue_coin_id'])->dec('zue_coin', $zue_coin)->update();
  499. }
  500. if(count($order_payments) > 0) {
  501. Db::table('erp_order_payment')->insertAll(array_map(function ($data) {
  502. return [
  503. "order_id" => isset($data['order_id']) ? $data['order_id'] : null,
  504. "channel_id" => isset($data['channel_id']) ? $data['channel_id'] : null,
  505. "channel_name" => isset($data['channel_name']) ? $data['channel_name']: null,
  506. "fee" => isset($data['fee']) ? $data['fee'] : null,
  507. "credit_card_id" => isset($data['credit_card_id']) ? $data['credit_card_id'] : null,
  508. "credit_card_name" => isset($data['credit_card_name']) ? $data['credit_card_name'] : null,
  509. "create_time" => isset($data['create_time']) ? $data['create_time'] : null,
  510. "update_time" => isset($data['update_time']) ? $data['update_time'] : null,
  511. "code" => isset($data['code']) ? $data['code'] : null,
  512. "stage_num" => isset($data['stage_num']) ? $data['stage_num'] : null,
  513. "service_charge_rate" => isset($data['service_charge_rate']) ? $data['service_charge_rate'] : null,
  514. "service_charge" => isset($data['service_charge']) ? $data['service_charge'] : null
  515. ];
  516. }, $order_payments));
  517. }
  518. Db::table('erp_order')->where('id', $order->id)->update($update_order);
  519. Db::commit();
  520. } catch (\Exception $e) {
  521. Db::rollback();
  522. return $this->fail(lang($e->getMessage()));
  523. }
  524. return $this->ok(true);
  525. }
  526. /**
  527. * @param $params
  528. * @return array
  529. * @throws \think\db\exception\DbException
  530. */
  531. public function fetch($params) {
  532. $verify = AuthService::verify($params['admin_id'],$params['type'] == 1 ? 10003 : 10004);
  533. $res = $this->orderModel->search($params, $verify);
  534. $items = $res['data'];
  535. return [array_map(function ($item) {
  536. return [
  537. "id" => $item['id'],
  538. "no" => $item['no'],
  539. "customer_id" => $item['customer_id'],
  540. "customer_name" => $item['customer_name'],
  541. "obj_names" => $item['obj_names'],
  542. "rental_amount" => $item['rental_amount'],
  543. "receivable_amount" => $item['receivable_amount'],
  544. "receive_amount" => $item['receive_amount'],
  545. "imposed_amount" => $item['imposed_amount'],
  546. "product_amount" => $item['product_amount'],
  547. "total_sales_tax" => $item['total_sales_tax'],
  548. "service_charge_amount" => $item['service_charge_amount'],
  549. "total_annual_fee" => $item['total_annual_fee'],
  550. "zue_coin" => $item['zue_coin'],
  551. "zue_coin_amount" => $item['zue_coin_amount'],
  552. "type" => $item['type'],
  553. "store_id" => $item['store_id'],
  554. "advisor_ids" => $item['advisor_ids'],
  555. "remarks" => $item['remarks'],
  556. "create_time" => $item['create_time'],
  557. "advisers" => join('/',array_unique(array_reduce($item['products'], function ($result, $item) {
  558. array_push($result, $item['adviser_1_name']);
  559. if($item['adviser_2_id'] > 0)
  560. array_push($result, $item['adviser_2_name']);
  561. return $result;
  562. }, []))),
  563. "teachers" => join('/', array_unique(array_reduce($item['products'], function ($result, $item) {
  564. if($item['teacher_1_id'] > 0)
  565. array_push($result, $item['teacher_1_name']);
  566. if($item['teacher_2_id'] > 0)
  567. array_push($result, $item['teacher_2_name']);
  568. return $result;
  569. }, []))),
  570. "payments" => join(' ', array_unique(array_reduce($item['payments'], function ($result, $item) {
  571. array_push($result, '['.$item['channel_name'].']');
  572. return $result;
  573. }, []))),
  574. "stage_num" => array_reduce($item['payments'], function ($result, $item) {
  575. if($item['stage_num'] && $item['stage_num'] > $result) {
  576. $result = $item['stage_num'];
  577. }
  578. return $result;
  579. }, 0),
  580. 'is_need_upload' => $item['type'] == 1 && in_array(true, array_map(function ($product) {
  581. return $product['is_upload_numerology'] == 1 && $product['is_upload'] == 0;
  582. }, $item['products'])),
  583. ];
  584. }, $items), $res['total']];
  585. }
  586. /**
  587. * @param $params
  588. * @return array
  589. * @throws \think\db\exception\DbException
  590. */
  591. public function fetchByCustomerId($params) {
  592. $res = $this->orderModel->fetchByCustomerId($params['customer_id'], $params['page'] ?? 1, $params['size'] ?? 20);
  593. $items = $res['data'];
  594. return [array_map(function ($item) {
  595. return [
  596. "id" => $item['id'],
  597. "no" => $item['no'],
  598. "customer_id" => $item['customer_id'],
  599. "customer_name" => $item['customer_name'],
  600. "obj_names" => $item['obj_names'],
  601. "rental_amount" => $item['rental_amount'],
  602. "receivable_amount" => $item['receivable_amount'],
  603. "receive_amount" => $item['receive_amount'],
  604. "imposed_amount" => $item['imposed_amount'],
  605. "product_amount" => $item['product_amount'],
  606. "total_sales_tax" => $item['total_sales_tax'],
  607. "service_charge_amount" => $item['service_charge_amount'],
  608. "total_annual_fee" => $item['total_annual_fee'],
  609. "zue_coin" => $item['zue_coin'],
  610. "zue_coin_amount" => $item['zue_coin_amount'],
  611. "type" => $item['type'],
  612. "store_id" => $item['store_id'],
  613. "advisor_ids" => $item['advisor_ids'],
  614. "remarks" => $item['remarks'],
  615. "create_time" => $item['create_time'],
  616. "advisers" => join('/',array_unique(array_reduce($item['products'], function ($result, $item) {
  617. array_push($result, $item['adviser_1_name']);
  618. if($item['adviser_2_id'] > 0)
  619. array_push($result, $item['adviser_2_name']);
  620. return $result;
  621. }, []))),
  622. "teachers" => join('/', array_unique(array_reduce($item['products'], function ($result, $item) {
  623. if($item['teacher_1_id'] > 0)
  624. array_push($result, $item['teacher_1_name']);
  625. if($item['teacher_2_id'] > 0)
  626. array_push($result, $item['teacher_2_name']);
  627. return $result;
  628. }, []))),
  629. "stage_num" => array_reduce($item['payments'], function ($result, $item) {
  630. if($item['stage_num'] && $item['stage_num'] > $result) {
  631. $result = $item['stage_num'];
  632. }
  633. return $result;
  634. }, 0),
  635. 'is_need_upload' => $item['type'] == 1 && in_array(true, array_map(function ($product) {
  636. return $product['is_upload_numerology'] == 1 && $product['is_upload'] == 0;
  637. }, $item['products'])),
  638. ];
  639. }, $items), $res['total']];
  640. }
  641. public function fetchOrderProducts($order_id, $page = 1, $size = 10) {
  642. $res = $this->orderProductModel->fetchByOrderId($order_id, $page, $size);
  643. return [$res->items(),$res->total()];
  644. }
  645. public function upload_numerology($order_product_id, $report) {
  646. $order_product = $this->orderProductModel->findById($order_product_id);
  647. if (!$order_product) return $this->fail('订单商品不存在,无法上传命理报告!');
  648. if (!$order_product->is_pay) return $this->fail('订单未支付,无法上传商品');
  649. $order_product->is_upload = 1;
  650. $order_product->report = $report;
  651. $order_product->save();
  652. return $this->ok($order_product);
  653. }
  654. public function fetchWaitGatherAnnualFee($admin_id, $text = null, $start_time = null, $end_time = null, $page = 1, $size = 10) {
  655. $res = $this->orderAnnualFeeModel->fetchByAdviser($admin_id, $text, $start_time, $end_time, $page, $size);
  656. return [$res[0]->items(),$res[0]->total(), $res[1]];
  657. }
  658. public function paymentAnnualFee($annual_fee_id) {
  659. $annual_fee = $this->orderAnnualFeeModel->findById($annual_fee_id);
  660. if(!$annual_fee_id) {
  661. return $this->fail('年费记录不存在!');
  662. }
  663. if($annual_fee->is_pay == 1)
  664. return $this->fail('该条年费记录已经支付!');
  665. $annual_fee->is_pay = 1;
  666. $annual_fee->update_time = time();
  667. $annual_fee->save();
  668. return $this->ok($annual_fee);
  669. }
  670. public function fetchOrderByReturn($admin_id, $store_id, $no = null, $customer_name = null, $page = 1, $size = 10) {
  671. $verify = AuthService::verify($admin_id, 10005);
  672. $res = $this->orderModel->fetchOrderByReturn($admin_id, $store_id, $no, $customer_name, $page, $size, $verify);
  673. return [$res->items(),$res->total()];
  674. }
  675. public function findByOrderNo($admin_id, $order_no) {
  676. $order = $this->orderModel->findByOrderNo($admin_id, $order_no);
  677. if(!$order)
  678. return $this->fail(lang("Order does not exist"));
  679. return $this->ok($order);
  680. }
  681. /**
  682. * @param $admin_id
  683. * @param $order_id
  684. * @param array $order_product_ids
  685. * @return \SResult
  686. * @throws \think\db\exception\DataNotFoundException
  687. * @throws \think\db\exception\DbException
  688. * @throws \think\db\exception\ModelNotFoundException
  689. */
  690. public function returnOrderProduct($admin_id, $order_id, array $order_product_ids) {
  691. // $verify = AuthService::verify($admin_id, 10005);
  692. $order = $this->orderModel->findById($order_id);
  693. if (!$order) return $this->fail(lang("Order does not exist"));
  694. if ($order->type == 2) return $this->fail(lang("The status of the order does not support return or exchange"));
  695. $return_order_products = $this->orderProductModel->findByIds($order_product_ids)->toArray();
  696. if (count($order_product_ids) != count($return_order_products)) return $this->fail(lang("The order item was incorrectly selected"));
  697. $all_order_products = $this->orderProductModel->findByOrderId($order->id)->toArray();
  698. $merge_order_products = array_reduce($all_order_products,
  699. function ($result, $item) use($order_product_ids) {
  700. if(!in_array($item['id'],$order_product_ids))
  701. array_push($result, $item);
  702. return $result;
  703. }, []);
  704. $obj_names = array_map(function ($data) {return $data['product_name'];}, $merge_order_products);
  705. $advisor_ids = array_reduce($merge_order_products, function ($result, $item) {
  706. if ($item['adviser_1_id'])
  707. array_push($result, $item['adviser_1_id']);
  708. if ($item['adviser_2_id'])
  709. array_push($result, $item['adviser_2_id']);
  710. return $result;
  711. },[]);
  712. $zue_coin_config = $this->paymentChannelModel->findById(11);
  713. if(!$zue_coin_config)
  714. return $this->fail("御龙币设置不存在!");
  715. $zue_coin_exchange_rate = $zue_coin_config['zue_coin_exchange_rate'] ?? 0; // 兑换比例
  716. //商品本金
  717. $total_product_amount = $order->product_amount;
  718. // 整体税费
  719. $total_sales_tax = $order->total_sales_tax;
  720. // 总体信用卡服务费
  721. $total_service_amount = $order->service_charge_amount;
  722. // 总体年费
  723. $total_annual_fee = $order->total_annual_fee;
  724. // 总体御龙币
  725. $total_zue_coin = $order->zue_coin;
  726. // 御龙币兑换的金额
  727. $total_zue_coin_amount = $order->zue_coin_amount;
  728. // 御龙币当时的兑换比例
  729. $zue_coin_exchange_rate = $order->zue_coin_amount > 0 && $order->zue_coin > 0 ? fixed2Float($order->zue_coin_amount / $order->zue_coin) : $zue_coin_exchange_rate;
  730. // 总计退还多少钱
  731. $total_return_amount = 0;
  732. // 商品库存
  733. $return_now_stocks = [];
  734. foreach ($return_order_products as $return_order_product) {
  735. // 减少御龙币
  736. $total_zue_coin -= $return_order_product['zue_coin'];
  737. $total_zue_coin_amount -= ($return_order_product['zue_coin'] * $zue_coin_exchange_rate);
  738. // 减少年费
  739. $total_annual_fee -= $return_order_product['annuity'];
  740. // 减少信用卡服务费
  741. $total_service_amount -= $return_order_product['service_charge'];
  742. // 减少税费
  743. $total_sales_tax -= $return_order_product['sales_tax'];
  744. // 减少本金
  745. $total_product_amount -= $return_order_product['real_price'];
  746. $total_return_amount -= $return_order_product['transaction_price'];
  747. if(isset($return_now_stocks[$return_order_product['store_product_id']])) {
  748. $return_now_stocks[$return_order_product['store_product_id']] += 1;
  749. } else {
  750. $return_now_stocks[$return_order_product['store_product_id']] = 1;
  751. }
  752. }
  753. $total_order_rental_amount = fixed2Float( $total_product_amount + $total_sales_tax + $total_service_amount + $total_annual_fee);
  754. $total_receivable_amount = fixed2Float($total_product_amount + $total_sales_tax + $total_service_amount + $total_annual_fee - ($total_zue_coin * $zue_coin_exchange_rate));
  755. $total_receive_amount = $total_receivable_amount;
  756. $annual_fees = $this->orderAnnualFeeModel->fetchByOrderProductId($order_product_ids);
  757. Db::startTrans();
  758. try {
  759. // 退还御龙币
  760. $return_zue_coin = $order->zue_coin - $total_zue_coin;
  761. if ($return_zue_coin > 0) {
  762. $customer_zue_coin = $this->zueCoinModel->findByCustomerId($order->customer_id);
  763. if(!$customer_zue_coin) {
  764. throw new BaseException('御龙币账户记录不存在',1012);
  765. }
  766. Db::table('erp_customer_zue_coin')->where('id', '=', $customer_zue_coin->id)->inc('zue_coin', $return_zue_coin)->update();
  767. Db::table('erp_zue_coin_record')->save([
  768. 'zue_coin_id' => $customer_zue_coin->id,
  769. 'order_id' => $order->id,
  770. 'origin' => $customer_zue_coin->zue_coin,
  771. 'change' => $return_zue_coin,
  772. 'after' => $customer_zue_coin->zue_coin + $return_zue_coin,
  773. 'reason' => 3,
  774. 'create_time' => time(),
  775. 'update_time' => time(),
  776. ]);
  777. }
  778. // 退还年费
  779. if (count($annual_fees) > 0)
  780. Db::table('erp_order_annual_fee')->where('id', 'in', array_map(function ($data) {return $data['id'];}, $annual_fees))->update(['is_delete' => 1, 'delete_time' => time()]);
  781. // 更新订单
  782. if (count($return_order_products) == count($all_order_products)){
  783. Db::table('erp_order')->where('id', $order->id)->update(['is_delete' => 1]);
  784. } else {
  785. Db::table('erp_order')->where('id', $order->id)->update([
  786. 'rental_amount' => $total_order_rental_amount,
  787. 'receivable_amount' => $total_receivable_amount,
  788. 'receive_amount' => $total_receive_amount,
  789. 'product_amount' => $total_product_amount,
  790. 'total_sales_tax' => $total_sales_tax,
  791. 'service_charge_amount' => $total_service_amount,
  792. 'total_annual_fee' => $total_annual_fee,
  793. 'zue_coin' => $total_zue_coin,
  794. 'zue_coin_amount' => $total_zue_coin_amount,
  795. 'obj_names' => join(',', array_unique($obj_names)),
  796. 'advisor_ids' => join(',', array_unique($advisor_ids)),
  797. ]);
  798. }
  799. // 插入退款记录
  800. Db::table('erp_order_payment')->save([
  801. 'order_id' => $order->id,
  802. 'channel_id' => 0,
  803. 'channel_name' => "Exchange a purchase",
  804. 'fee' => $total_return_amount,
  805. 'create_time' => time(),
  806. 'update_time' => time(),
  807. ]);
  808. // 退还商品库存
  809. $return_stock_keys = array_keys($return_now_stocks);
  810. foreach ($return_stock_keys as $key) {
  811. Db::table("erp_store_product")
  812. ->where('id', $key)
  813. ->inc('now_stock', $return_now_stocks[$key])
  814. ->dec('sale_stock', $return_now_stocks[$key])
  815. ->update();
  816. }
  817. // 删除订单商品
  818. Db::table('erp_order_product')->where('id', 'in', $order_product_ids)->update(['is_delete' => 1, 'delete_time' => time()]);
  819. Db::commit();
  820. } catch (\Exception $e) {
  821. Db::rollback();
  822. return $this->fail(lang($e->getMessage()));
  823. }
  824. return $this->ok(true);
  825. }
  826. /**
  827. * @param $admin_id
  828. * @param $admin_name
  829. * @param $order_id
  830. * @param $origin_order_product_ids
  831. * @param $append_store_product_ids
  832. * @return \SResult
  833. * @throws \think\db\exception\DataNotFoundException
  834. * @throws \think\db\exception\DbException
  835. * @throws \think\db\exception\ModelNotFoundException
  836. */
  837. public function exchange($admin_id, $admin_name, $order_id, $origin_order_product_ids, $append_store_product_ids) {
  838. // $verify = AuthService::verify($admin_id, 10005);
  839. $order = $this->orderModel->findById($order_id);
  840. if (!$order) return $this->fail(lang("Order does not exist"));
  841. if ($order->type == 2) return $this->fail(lang("The status of the order does not support return or exchange"));
  842. $return_order_products = $this->orderProductModel->findByIds($origin_order_product_ids)->toArray();
  843. if (count($origin_order_product_ids) != count($return_order_products)) return $this->fail(lang("The order item was incorrectly selected"));
  844. $all_order_products = $this->orderProductModel->findByOrderId($order->id)->toArray();
  845. $merge_order_products = array_reduce($all_order_products,
  846. function ($result, $item) use($origin_order_product_ids) {
  847. if(!in_array($item['id'], $origin_order_product_ids))
  848. array_push($result, $item);
  849. return $result;
  850. }, []);
  851. $obj_names = array_map(function ($data) {return $data['product_name'];}, $merge_order_products);
  852. $advisor_ids = array_reduce($merge_order_products, function ($result, $item) {
  853. if ($item['adviser_1_id'])
  854. array_push($result, $item['adviser_1_id']);
  855. if ($item['adviser_2_id'])
  856. array_push($result, $item['adviser_2_id']);
  857. return $result;
  858. },[]);
  859. $zue_coin_config = $this->paymentChannelModel->findById(11);
  860. if(!$zue_coin_config)
  861. return $this->fail("御龙币设置不存在!");
  862. $zue_coin_exchange_rate = $zue_coin_config['zue_coin_exchange_rate'] ?? 0; // 兑换比例
  863. //商品本金
  864. $total_product_amount = $order->product_amount;
  865. // 整体税费
  866. $total_sales_tax = $order->total_sales_tax;
  867. // 总体信用卡服务费
  868. $total_service_amount = $order->service_charge_amount;
  869. // 总体年费
  870. $total_annual_fee = $order->total_annual_fee;
  871. // 总体御龙币
  872. $total_zue_coin = $order->zue_coin;
  873. // 御龙币兑换的金额
  874. $total_zue_coin_amount = $order->zue_coin_amount;
  875. // 御龙币当时的兑换比例
  876. $zue_coin_exchange_rate = $order->zue_coin_amount > 0 && $order->zue_coin > 0 ? fixed2Float($order->zue_coin_amount / $order->zue_coin) : $zue_coin_exchange_rate;
  877. // 差价
  878. $diff_amount = 0;
  879. // 商品库存
  880. $return_now_stocks = [];
  881. // 减操作
  882. foreach ($return_order_products as $return_order_product) {
  883. // 减少御龙币
  884. $total_zue_coin -= $return_order_product['zue_coin'];
  885. $total_zue_coin_amount -= ($return_order_product['zue_coin'] * $zue_coin_exchange_rate);
  886. // 减少年费
  887. $total_annual_fee -= $return_order_product['annuity'];
  888. // 减少信用卡服务费
  889. $total_service_amount -= $return_order_product['service_charge'];
  890. // 减少税费
  891. $total_sales_tax -= $return_order_product['sales_tax'];
  892. // 减少本金
  893. $total_product_amount -= $return_order_product['real_price'];
  894. $diff_amount -= $return_order_product['transaction_price'];
  895. if(isset($return_now_stocks[$return_order_product['store_product_id']])) {
  896. $return_now_stocks[$return_order_product['store_product_id']] += 1;
  897. } else {
  898. $return_now_stocks[$return_order_product['store_product_id']] = 1;
  899. }
  900. }
  901. /////////////// 加操作
  902. // 客户
  903. $customer = $this->customerModel->findById($order->customer_id);
  904. if (!$customer)
  905. return $this->fail(lang("The Customer does not exist"));
  906. // 门店商品
  907. $store_products = $this->storeProductModel->fetchRelationsByOrder($append_store_product_ids)->toArray();
  908. if(count($store_products) != count($append_store_product_ids))
  909. return $this->fail(lang("The Product does not exist"));
  910. // 商品信息
  911. $products = array_map(function ($p) {
  912. return $p['product'] ? $p['product'] : null;
  913. }, $store_products);
  914. if(in_array(null, $products))
  915. return $this->fail(lang("The Product does not exist"));
  916. $config = $this->configModel->findConfig();
  917. $activityProducts = $this->activityProductModel->fetchByProductIds(array_map(function ($data) {
  918. return $data['id'];
  919. }, $products))->toArray();
  920. $fmt_store_products = [];
  921. foreach ($store_products as &$item) {
  922. $aProducts = array_filter($activityProducts, function ($aProduct) use ($item) {
  923. return $aProduct['product_id'] == $item['product_id'];
  924. });
  925. $res = compare($item['product']['real_price'] ?? 0, $aProducts);
  926. $item['activity'] = $res['item'];
  927. $item['product']['origin_price'] = $item['product']['real_price'];
  928. $item['product']['real_price'] = fixed2Float($res['min_num'] > 0 ? $res['min_num'] : 0);
  929. $sales_tax_rate = $item['product']['sales_tax_rate'] > 0 ? $item['product']['sales_tax_rate'] : $config->sales_tax_rate;
  930. $sales_tax = fixed2Float($sales_tax_rate > 0 && $item['product']['real_price'] > 0 ? ($item['product']['real_price'] * ($sales_tax_rate / 100)) : 0);
  931. $item['product']['sales_tax_rate'] = $sales_tax_rate;
  932. $item['product']['sales_tax'] = $sales_tax;
  933. $fmt_store_products[$item['id']] = $item;
  934. }
  935. $order_products = [];
  936. $order_annual_fees = [];
  937. for ($j = 0; $j < count($store_products); $j++) {
  938. $store_product = $store_products[$j];
  939. array_push($obj_names, $store_product['product']['name']);
  940. array_push($advisor_ids, $admin_id);
  941. array_push($order_products, [
  942. 'order_id' => $order->id,
  943. 'order_no' => $order->no,
  944. 'customer_id' => $order->customer_id,
  945. 'product_id' => $store_product['product']['id'],
  946. 'product_category_id' => $store_product['product']['category_id'],
  947. 'is_serve' => $store_product['product']['is_serve'],
  948. 'store_product_id' => $store_product['id'],
  949. 'product_name' => $store_product['product']['name'],
  950. 'adviser_1_id' => $admin_id,
  951. 'adviser_1_name' => $admin_name,
  952. 'adviser_2_id' => null,
  953. 'adviser_2_name' => null,
  954. 'teacher_1_id' => null,
  955. 'teacher_1_name' => null,
  956. 'teacher_2_id' => null,
  957. 'teacher_2_name' => null,
  958. 'is_upload_numerology' => $store_product['product']['is_upload_numerology'],
  959. 'is_upload' => 0,
  960. 'report' => null,
  961. 'is_gather_annuity' => $store_product['product']['is_gather_annuity'],
  962. 'annuity' => $store_product['product']['annuity'],
  963. 'real_price' => $store_product['product']['real_price'],
  964. 'service_charge' => 0,
  965. 'reduce_price' => $store_product['activity'] ? $store_product['product']['origin_price'] - $store_product['product']['real_price'] : 0,
  966. 'reduce_type' => $store_product['activity'] ? $store_product['activity']['type'] : 0,
  967. 'sales_tax_rate' => $store_product['product']['sales_tax_rate'],
  968. 'sales_tax' => $store_product['product']['sales_tax'],
  969. 'transaction_price' => fixed2Float($store_product['product']['real_price'] + $store_product['product']['sales_tax'] + $store_product['product']['annuity']),
  970. 'zue_coin' => 0,
  971. 'is_pay' => 1,
  972. 'create_time' => time(),
  973. 'update_time' => time(),
  974. ]);
  975. array_push($order_annual_fees, $store_product['product']['is_gather_annuity'] && $store_product['product']['annuity'] > 0 ? [
  976. 'order_id' => $order->id,
  977. 'customer_id' => $order->customer_id,
  978. 'customer_name' => $order->customer_name,
  979. 'customer_mobile' => $customer->mobile,
  980. 'customer_create_username' => $customer->create_username,
  981. 'index' => 1,
  982. 'order_product_id' => -1,
  983. 'order_product_name' => $store_product['product']['name'],
  984. 'fee' => $store_product['product']['annuity'],
  985. 'is_pay' => 1,
  986. 'start_time' => time(),
  987. 'end_time' => time() + (365 * 24 * 60 * 60),
  988. 'order_create_time' => strtotime($order->create_time),
  989. 'adviser_ids' => $admin_id,
  990. 'store_id' => $order->store_id,
  991. 'create_time' => time(),
  992. 'update_time' => time()
  993. ] : null);
  994. $total_product_amount += $store_product['product']['real_price'];
  995. $total_sales_tax += $store_product['product']['sales_tax'];
  996. if($store_product['product']['is_gather_annuity'] == 1)
  997. $total_annual_fee += $store_product['product']['annuity'];
  998. $diff_amount += fixed2Float($store_product['product']['real_price'] + $store_product['product']['sales_tax'] + $store_product['product']['annuity']);
  999. }
  1000. $total_order_rental_amount = fixed2Float( $total_product_amount + $total_sales_tax + $total_service_amount + $total_annual_fee);
  1001. $total_receivable_amount = fixed2Float($total_product_amount + $total_sales_tax + $total_service_amount + $total_annual_fee - ($total_zue_coin * $zue_coin_exchange_rate));
  1002. $total_receive_amount = $total_receivable_amount;
  1003. $annual_fees = $this->orderAnnualFeeModel->fetchByOrderProductId($origin_order_product_ids);
  1004. Db::startTrans();
  1005. try {
  1006. // 退还御龙币
  1007. $return_zue_coin = $order->zue_coin - $total_zue_coin;
  1008. if ($return_zue_coin > 0) {
  1009. $customer_zue_coin = $this->zueCoinModel->findByCustomerId($order->customer_id);
  1010. if(!$customer_zue_coin) {
  1011. throw new BaseException('御龙币账户记录不存在',1012);
  1012. }
  1013. Db::table('erp_customer_zue_coin')->where('id', '=', $customer_zue_coin->id)->inc('zue_coin', $return_zue_coin)->update();
  1014. Db::table('erp_zue_coin_record')->save([
  1015. 'zue_coin_id' => $customer_zue_coin->id,
  1016. 'order_id' => $order->id,
  1017. 'origin' => $customer_zue_coin->zue_coin,
  1018. 'change' => $return_zue_coin,
  1019. 'after' => $customer_zue_coin->zue_coin + $return_zue_coin,
  1020. 'reason' => 3,
  1021. 'create_time' => time(),
  1022. 'update_time' => time(),
  1023. ]);
  1024. }
  1025. // 退还年费
  1026. if (count($annual_fees) > 0)
  1027. Db::table('erp_order_annual_fee')->where('id', 'in', array_map(function ($data) {return $data['id'];}, $annual_fees))->update(['is_delete' => 1, 'delete_time' => time()]);
  1028. // 插入退款记录
  1029. Db::table('erp_order_payment')->save([
  1030. 'order_id' => $order->id,
  1031. 'channel_id' => 0,
  1032. 'channel_name' => "Exchange a purchase",
  1033. 'fee' => $diff_amount,
  1034. 'create_time' => time(),
  1035. 'update_time' => time(),
  1036. ]);
  1037. // 退还商品库存
  1038. $return_stock_keys = array_keys($return_now_stocks);
  1039. foreach ($return_stock_keys as $key) {
  1040. Db::table("erp_store_product")
  1041. ->where('id', $key)
  1042. ->inc('now_stock', $return_now_stocks[$key])
  1043. ->dec('sale_stock', $return_now_stocks[$key])
  1044. ->update();
  1045. }
  1046. // 删除订单商品
  1047. Db::table('erp_order_product')->where('id', 'in', $origin_order_product_ids)->update(['is_delete' => 1, 'delete_time' => time()]);
  1048. // 新增商品
  1049. for ($i = 0; $i < count($order_products); $i++) {
  1050. $order_product = $order_products[$i];
  1051. $order_annual_fee = $order_annual_fees[$i];
  1052. $last_id = Db::table('erp_order_product')->insert($order_product, true);
  1053. if($order_annual_fee != null) {
  1054. $order_annual_fee['order_product_id'] = $last_id;
  1055. Db::table('erp_order_annual_fee')->save($order_annual_fee);
  1056. }
  1057. Db::table("erp_store_product")
  1058. ->where('id', $order_product['store_product_id'])
  1059. ->dec('now_stock', 1)
  1060. ->inc('sale_stock', 1)
  1061. ->update();
  1062. }
  1063. // 更新订单
  1064. Db::table('erp_order')->where('id', $order->id)->update([
  1065. 'rental_amount' => $total_order_rental_amount,
  1066. 'receivable_amount' => $total_receivable_amount,
  1067. 'receive_amount' => $total_receive_amount,
  1068. 'product_amount' => $total_product_amount,
  1069. 'total_sales_tax' => $total_sales_tax,
  1070. 'service_charge_amount' => $total_service_amount,
  1071. 'total_annual_fee' => $total_annual_fee,
  1072. 'zue_coin' => $total_zue_coin,
  1073. 'zue_coin_amount' => $total_zue_coin_amount,
  1074. 'obj_names' => join(',', array_unique($obj_names)),
  1075. 'advisor_ids' => join(',', array_unique($advisor_ids)),
  1076. ]);
  1077. Db::commit();
  1078. } catch (\Exception $e) {
  1079. Db::rollback();
  1080. return $this->fail(lang($e->getMessage()));
  1081. }
  1082. return $this->ok(true);
  1083. }
  1084. public function findOrderByOrderId($order_id) {
  1085. return $this->orderModel->findById($order_id);
  1086. }
  1087. public function fetchOrderPayments($order_id) {
  1088. return $this->orderPaymentModel->findByOrderId($order_id);
  1089. }
  1090. }