OrderService.php 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910
  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. if(!$zue_coin_model)
  340. return $this->fail("当前客户御龙币账户余额: 0");
  341. if ($zue_coin > $zue_coin_model->zue_coin)
  342. return $this->fail("当前客户御龙币账户余额:{$zue_coin_model->zue_coin}");
  343. $zue_coin_config = $fmt_pay_channels['11'];
  344. if(!$zue_coin_config)
  345. return $this->fail("御龙币设置不存在!");
  346. $zue_coin_exchange_rate = $zue_coin_config['zue_coin_exchange_rate'] ?? 0; // 兑换比例
  347. $zue_coin_consume_rate = $zue_coin_config['zue_coin_consume_rate'] ?? 0; // 报销比例
  348. if($zue_coin > 0) {
  349. if($zue_coin_exchange_rate == 0 || $zue_coin_consume_rate == 0) {
  350. return $this->fail("该笔订单不支持御龙币支付");
  351. }
  352. // 1.计算出该订单能使用多少御龙币
  353. // 2.结合之前已使用的御龙币 算出还能使用多少御龙币
  354. // 3.判断当前御龙币是否符合兑换数额
  355. // 4.进行扣除并记录
  356. // 根据御龙币的设置 总共能报销这么多钱
  357. $max_consume_amount = fixed2Float($imposed_amount * ($zue_coin_consume_rate / 100));
  358. // 根据御龙币的设置 最大的报销的御龙币
  359. $max_consume_zue_coin = fixed2Float($max_consume_amount / $zue_coin_exchange_rate);
  360. if ($max_consume_zue_coin - ($order->zue_coin + $zue_coin) < 0) {
  361. return $this->fail("最多能使用御龙币: {$max_consume_zue_coin}, 当前已使用{$order->zue_coin}");
  362. }
  363. // 根据当前订单支付情况 得出现在最大的报销金额;
  364. $now_max_consume_amount = $order->imposed_amount < $max_consume_amount ? $order->imposed_amount : $max_consume_amount;
  365. // 当前最多还能使用多少御龙币
  366. $now_can_consume_zue_coin = fixed2Float($now_max_consume_amount / $zue_coin_exchange_rate);
  367. // 判断当前还能使用
  368. if ($now_can_consume_zue_coin - $zue_coin < 0)
  369. return $this->fail("当前剩余可使用的: {$now_can_consume_zue_coin}");
  370. // 总共使用了这么多御龙币
  371. $order_use_zue_coin += $zue_coin;
  372. // 总共兑换了这么多钱
  373. $order_use_zue_coin_amount = fixed2Float($order_use_zue_coin * $zue_coin_exchange_rate);
  374. $change_zue_coin_record = [
  375. 'zue_coin_id' => $zue_coin_model->id,
  376. 'order_id' => $order->id,
  377. 'origin' => $zue_coin_model->zue_coin,
  378. 'change' => -$zue_coin,
  379. 'after' => $zue_coin_model->zue_coin - $zue_coin,
  380. 'reason' => 1,
  381. 'create_time' => time(),
  382. 'update_time' => time(),
  383. ];
  384. }
  385. // 总计费用 - 御龙币抵消费用;
  386. $imposed_amount -= $order_use_zue_coin_amount;
  387. // 总计实收金额
  388. $receive_amount = fixed2Float($order->receive_amount + $total_fee);
  389. 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})");
  390. $order_annual_fees = [];
  391. $update_store_products = [];
  392. $update_order_products = [];
  393. if (round($receive_amount) == round($imposed_amount)) { // 减库存
  394. $order_products = $this->orderProductModel->findByOrderId($order->id)->toArray();
  395. $store_products = $this->storeProductModel->findByIds(array_map(function ($r) {return $r['store_product_id'];}, $order_products))->toArray();
  396. $fmt_store_products = array_reduce($store_products, function ($result, $item) {
  397. $result[$item['id']] = $item;
  398. return $result;
  399. },[]);
  400. // 商品本身的价格 | 年费 | 消费税
  401. $total_ = $order->product_amount + $order->total_annual_fee + $order->total_sales_tax;
  402. // 信用卡手续费 每一块钱所占的比例
  403. $item_service_charge_rate = ($order->service_charge_amount + $service_charge) / $total_;
  404. // 每一个御龙币所占的比例
  405. $item_zue_coin_rate = $order_use_zue_coin / $total_;
  406. foreach ($order_products as $order_product) {
  407. predicate($fmt_store_products[$order_product['store_product_id']]['now_stock'] > 0, lang('inventory shortage'));
  408. $fmt_store_products[$order_product['store_product_id']]['now_stock'] -= 1;
  409. if (isset($update_store_products[$order_product['store_product_id']])) {
  410. $update_store_products[$order_product['store_product_id']]['reduce_num'] += 1;
  411. } else {
  412. $update_store_products[$order_product['store_product_id']] = ['id' => $order_product['store_product_id'], 'reduce_num' => 1];
  413. }
  414. if ($order_product['is_gather_annuity']) {
  415. array_push($order_annual_fees, [
  416. 'order_id' => $order->id,
  417. 'customer_id' => $customer->id,
  418. 'customer_name' => "{$customer->name_en}|{$customer->name_zh}",
  419. 'customer_mobile' => $customer->mobile,
  420. 'customer_create_username' => $customer->create_username,
  421. 'index' => 1,
  422. 'order_product_id' => $order_product['id'],
  423. 'order_product_name' => $order_product['product_name'],
  424. 'fee' => $order_product['annuity'],
  425. 'is_pay' => 1,
  426. 'start_time' => time(),
  427. 'end_time' => time() + (365 * 24 * 60 * 60),
  428. 'order_create_time' => strtotime($order->create_time),
  429. 'adviser_1_id' => $order_product['adviser_1_id'],
  430. 'store_id' => $order->store_id,
  431. 'create_time' => time(),
  432. 'update_time' => time()
  433. ]);
  434. }
  435. $now = $order_product['real_price'] + $order_product['annuity'] + $order_product['sales_tax'];
  436. $item_service_charge = fixed2Float($now * $item_service_charge_rate);
  437. $item_zue_coin = fixed2Float($now * $item_zue_coin_rate);
  438. $item_zue_coin_amount = fixed2Float($item_zue_coin * $zue_coin_exchange_rate);
  439. $transaction_price = fixed2Float($now + $item_service_charge - $item_zue_coin_amount);
  440. array_push($update_order_products, [
  441. 'id' => $order_product['id'],
  442. 'service_charge' => $item_service_charge,
  443. 'zue_coin' => $item_zue_coin,
  444. 'zue_coin_amount' => $item_zue_coin_amount,
  445. 'transaction_price' => $transaction_price,
  446. 'is_pay' => 1
  447. ]);
  448. }
  449. }
  450. Db::startTrans();
  451. try {
  452. $update_order = [
  453. 'rental_amount' => $imposed_amount + $order_use_zue_coin_amount,
  454. 'receivable_amount' => $imposed_amount,
  455. 'receive_amount' => $receive_amount,
  456. 'imposed_amount' => $imposed_amount - $receive_amount,
  457. 'service_charge_amount' => $order->service_charge_amount + $service_charge,
  458. 'zue_coin' => $order_use_zue_coin,
  459. 'zue_coin_amount' => $order_use_zue_coin_amount,
  460. 'remarks' => $params['remarks']
  461. ];
  462. if (round($receive_amount) == round($imposed_amount)) { // 支付满了
  463. $update_order['type'] = 1;
  464. if(count($update_order_products) > 0) {
  465. foreach ($update_order_products as $item) {
  466. Db::table('erp_order_product')->where('id', $item['id'])->update($item);
  467. }
  468. }
  469. if(count($order_annual_fees) > 0) {
  470. Db::table('erp_order_annual_fee')->insertAll($order_annual_fees);
  471. }
  472. if(count($update_store_products) > 0) {
  473. foreach ($update_store_products as $update) {
  474. Db::table('erp_store_product')->where('id', $update['id'])->dec('now_stock',1)->update();
  475. Db::table('erp_store_product')->where('id', $update['id'])->inc('sale_stock',1)->update();
  476. }
  477. }
  478. }
  479. Db::table('erp_order_proceeds')->save([
  480. 'order_id' => $order->id,
  481. 'channels' => join(' ',$record_channel_names),
  482. 'fee' => $total_fee,
  483. 'admin_id' => $params['admin_id'],
  484. 'admin_name' => $params['admin_name'],
  485. 'create_time' => time(),
  486. 'update_time' => time(),
  487. ]);
  488. if ($zue_coin > 0 && $change_zue_coin_record != null) {
  489. Db::table('erp_zue_coin_record')->save($change_zue_coin_record);
  490. Db::table('erp_customer_zue_coin')->where('id', $change_zue_coin_record['zue_coin_id'])->dec('zue_coin', $zue_coin)->update();
  491. }
  492. if(count($order_payments) > 0) {
  493. Db::table('erp_order_payment')->insertAll(array_map(function ($data) {
  494. return [
  495. "order_id" => isset($data['order_id']) ? $data['order_id'] : null,
  496. "channel_id" => isset($data['channel_id']) ? $data['channel_id'] : null,
  497. "channel_name" => isset($data['channel_name']) ? $data['channel_name']: null,
  498. "fee" => isset($data['fee']) ? $data['fee'] : null,
  499. "credit_card_id" => isset($data['credit_card_id']) ? $data['credit_card_id'] : null,
  500. "credit_card_name" => isset($data['credit_card_name']) ? $data['credit_card_name'] : null,
  501. "create_time" => isset($data['create_time']) ? $data['create_time'] : null,
  502. "update_time" => isset($data['update_time']) ? $data['update_time'] : null,
  503. "code" => isset($data['code']) ? $data['code'] : null,
  504. "stage_num" => isset($data['stage_num']) ? $data['stage_num'] : null,
  505. "service_charge_rate" => isset($data['service_charge_rate']) ? $data['service_charge_rate'] : null,
  506. "service_charge" => isset($data['service_charge']) ? $data['service_charge'] : null
  507. ];
  508. }, $order_payments));
  509. }
  510. Db::table('erp_order')->where('id', $order->id)->update($update_order);
  511. Db::commit();
  512. } catch (\Exception $e) {
  513. Db::rollback();
  514. return $this->fail(lang($e->getMessage()));
  515. }
  516. return $this->ok(true);
  517. }
  518. /**
  519. * @param $params
  520. * @return array
  521. * @throws \think\db\exception\DbException
  522. */
  523. public function fetch($params) {
  524. $verify = AuthService::verify($params['admin_id'],$params['type'] == 1 ? 10003 : 10004);
  525. $res = $this->orderModel->search($params, $verify);
  526. $items = $res['data'];
  527. return [array_map(function ($item) {
  528. return [
  529. "id" => $item['id'],
  530. "no" => $item['no'],
  531. "customer_id" => $item['customer_id'],
  532. "customer_name" => $item['customer_name'],
  533. "obj_names" => $item['obj_names'],
  534. "rental_amount" => $item['rental_amount'],
  535. "receivable_amount" => $item['receivable_amount'],
  536. "receive_amount" => $item['receive_amount'],
  537. "imposed_amount" => $item['imposed_amount'],
  538. "product_amount" => $item['product_amount'],
  539. "total_sales_tax" => $item['total_sales_tax'],
  540. "service_charge_amount" => $item['service_charge_amount'],
  541. "total_annual_fee" => $item['total_annual_fee'],
  542. "zue_coin" => $item['zue_coin'],
  543. "zue_coin_amount" => $item['zue_coin_amount'],
  544. "type" => $item['type'],
  545. "store_id" => $item['store_id'],
  546. "advisor_ids" => $item['advisor_ids'],
  547. "remarks" => $item['remarks'],
  548. "create_time" => $item['create_time'],
  549. "advisers" => join('/',array_unique(array_reduce($item['products'], function ($result, $item) {
  550. array_push($result, $item['adviser_1_name']);
  551. if($item['adviser_2_id'] > 0)
  552. array_push($result, $item['adviser_2_name']);
  553. return $result;
  554. }, []))),
  555. "teachers" => join('/', array_unique(array_reduce($item['products'], function ($result, $item) {
  556. if($item['teacher_1_id'] > 0)
  557. array_push($result, $item['teacher_1_name']);
  558. if($item['teacher_2_id'] > 0)
  559. array_push($result, $item['teacher_2_name']);
  560. return $result;
  561. }, []))),
  562. "payments" => join(' ', array_unique(array_reduce($item['payments'], function ($result, $item) {
  563. array_push($result, '['.$item['channel_name'].']');
  564. return $result;
  565. }, []))),
  566. "stage_num" => array_reduce($item['payments'], function ($result, $item) {
  567. if($item['stage_num'] && $item['stage_num'] > $result) {
  568. $result = $item['stage_num'];
  569. }
  570. return $result;
  571. }, 0),
  572. 'is_need_upload' => $item['type'] == 1 && in_array(true, array_map(function ($product) {
  573. return $product['is_upload_numerology'] == 1 && $product['is_upload'] == 0;
  574. }, $item['products'])),
  575. ];
  576. }, $items), $res['total']];
  577. }
  578. /**
  579. * @param $params
  580. * @return array
  581. * @throws \think\db\exception\DbException
  582. */
  583. public function fetchByCustomerId($params) {
  584. $res = $this->orderModel->fetchByCustomerId($params['customer_id'], $params['page'] ?? 1, $params['size'] ?? 20);
  585. $items = $res['data'];
  586. return [array_map(function ($item) {
  587. return [
  588. "id" => $item['id'],
  589. "no" => $item['no'],
  590. "customer_id" => $item['customer_id'],
  591. "customer_name" => $item['customer_name'],
  592. "obj_names" => $item['obj_names'],
  593. "rental_amount" => $item['rental_amount'],
  594. "receivable_amount" => $item['receivable_amount'],
  595. "receive_amount" => $item['receive_amount'],
  596. "imposed_amount" => $item['imposed_amount'],
  597. "product_amount" => $item['product_amount'],
  598. "total_sales_tax" => $item['total_sales_tax'],
  599. "service_charge_amount" => $item['service_charge_amount'],
  600. "total_annual_fee" => $item['total_annual_fee'],
  601. "zue_coin" => $item['zue_coin'],
  602. "zue_coin_amount" => $item['zue_coin_amount'],
  603. "type" => $item['type'],
  604. "store_id" => $item['store_id'],
  605. "advisor_ids" => $item['advisor_ids'],
  606. "remarks" => $item['remarks'],
  607. "create_time" => $item['create_time'],
  608. "advisers" => join('/',array_unique(array_reduce($item['products'], function ($result, $item) {
  609. array_push($result, $item['adviser_1_name']);
  610. if($item['adviser_2_id'] > 0)
  611. array_push($result, $item['adviser_2_name']);
  612. return $result;
  613. }, []))),
  614. "teachers" => join('/', array_unique(array_reduce($item['products'], function ($result, $item) {
  615. if($item['teacher_1_id'] > 0)
  616. array_push($result, $item['teacher_1_name']);
  617. if($item['teacher_2_id'] > 0)
  618. array_push($result, $item['teacher_2_name']);
  619. return $result;
  620. }, []))),
  621. "stage_num" => array_reduce($item['payments'], function ($result, $item) {
  622. if($item['stage_num'] && $item['stage_num'] > $result) {
  623. $result = $item['stage_num'];
  624. }
  625. return $result;
  626. }, 0),
  627. 'is_need_upload' => $item['type'] == 1 && in_array(true, array_map(function ($product) {
  628. return $product['is_upload_numerology'] == 1 && $product['is_upload'] == 0;
  629. }, $item['products'])),
  630. ];
  631. }, $items), $res['total']];
  632. }
  633. public function fetchOrderProducts($order_id, $page = 1, $size = 10) {
  634. $res = $this->orderProductModel->fetchByOrderId($order_id, $page, $size);
  635. return [$res->items(),$res->total()];
  636. }
  637. public function upload_numerology($order_product_id, $report) {
  638. $order_product = $this->orderProductModel->findById($order_product_id);
  639. if (!$order_product) return $this->fail('订单商品不存在,无法上传命理报告!');
  640. if (!$order_product->is_pay) return $this->fail('订单未支付,无法上传商品');
  641. $order_product->is_upload = 1;
  642. $order_product->report = $report;
  643. $order_product->save();
  644. return $this->ok($order_product);
  645. }
  646. public function fetchWaitGatherAnnualFee($admin_id, $text = null, $start_time = null, $end_time = null, $page = 1, $size = 10) {
  647. $res = $this->orderAnnualFeeModel->fetchByAdviser($admin_id, $text, $start_time, $end_time, $page, $size);
  648. return [$res->items(),$res->total()];
  649. }
  650. public function paymentAnnualFee($annual_fee_id) {
  651. $annual_fee = $this->orderAnnualFeeModel->findById($annual_fee_id);
  652. if(!$annual_fee_id) {
  653. return $this->fail('年费记录不存在!');
  654. }
  655. if($annual_fee->is_pay == 1)
  656. return $this->fail('该条年费记录已经支付!');
  657. $annual_fee->is_pay = 1;
  658. $annual_fee->update_time = time();
  659. $annual_fee->save();
  660. return $this->ok($annual_fee);
  661. }
  662. public function fetchOrderByReturn($admin_id, $store_id, $no = null, $customer_name = null, $page = 1, $size = 10) {
  663. $verify = AuthService::verify($admin_id, 10005);
  664. $res = $this->orderModel->fetchOrderByReturn($admin_id, $store_id, $no, $customer_name, $page, $size, $verify);
  665. return [$res->items(),$res->total()];
  666. }
  667. public function findByOrderNo($admin_id, $order_no) {
  668. $order = $this->orderModel->findByOrderNo($admin_id, $order_no);
  669. if(!$order)
  670. return $this->fail(lang("Order does not exist"));
  671. return $this->ok($order);
  672. }
  673. /**
  674. * @param $admin_id
  675. * @param $order_id
  676. * @param array $order_product_ids
  677. * @return \SResult
  678. * @throws \think\db\exception\DataNotFoundException
  679. * @throws \think\db\exception\DbException
  680. * @throws \think\db\exception\ModelNotFoundException
  681. */
  682. public function returnOrderProduct($admin_id, $order_id, array $order_product_ids) {
  683. // $verify = AuthService::verify($admin_id, 10005);
  684. $order = $this->orderModel->findById($order_id);
  685. if (!$order) return $this->fail(lang("Order does not exist"));
  686. if ($order->type == 2) return $this->fail(lang("The status of the order does not support return or exchange"));
  687. $return_order_products = $this->orderProductModel->findByIds($order_product_ids)->toArray();
  688. if (count($order_product_ids) != count($return_order_products)) return $this->fail(lang("The order item was incorrectly selected"));
  689. $all_order_products = $this->orderProductModel->findByOrderId($order->id)->toArray();
  690. $merge_order_products = array_reduce($all_order_products,
  691. function ($result, $item) use($order_product_ids) {
  692. if(!in_array($item['id'],$order_product_ids))
  693. array_push($result, $item);
  694. return $result;
  695. }, []);
  696. $obj_names = array_map(function ($data) {return $data['product_name'];}, $merge_order_products);
  697. $advisor_ids = array_reduce($merge_order_products, function ($result, $item) {
  698. if ($item['adviser_1_id'])
  699. array_push($result, $item['adviser_1_id']);
  700. if ($item['adviser_2_id'])
  701. array_push($result, $item['adviser_2_id']);
  702. return $result;
  703. },[]);
  704. //商品本金
  705. $total_product_amount = $order->product_amount;
  706. // 整体税费
  707. $total_sales_tax = $order->total_sales_tax;
  708. // 总体信用卡服务费
  709. $total_service_amount = $order->service_charge_amount;
  710. // 总体年费
  711. $total_annual_fee = $order->total_annual_fee;
  712. // 总体御龙币
  713. $total_zue_coin = $order->zue_coin;
  714. // 御龙币兑换的金额
  715. $total_zue_coin_amount = $order->zue_coin_amount;
  716. // 御龙币当时的兑换比例
  717. $zue_coin_exchange_rate = fixed2Float($order->zue_coin_amount / $order->zue_coin);
  718. // 总计退还多少钱
  719. $total_return_amount = 0;
  720. // 商品库存
  721. $return_now_stocks = [];
  722. foreach ($return_order_products as $return_order_product) {
  723. // 减少御龙币
  724. $total_zue_coin -= $return_order_product['zue_coin'];
  725. $total_zue_coin_amount -= ($return_order_product['zue_coin'] * $zue_coin_exchange_rate);
  726. // 减少年费
  727. $total_annual_fee -= $return_order_product['annuity'];
  728. // 减少信用卡服务费
  729. $total_service_amount -= $return_order_product['service_charge'];
  730. // 减少税费
  731. $total_sales_tax -= $return_order_product['sales_tax'];
  732. // 减少本金
  733. $total_product_amount -= $return_order_product['real_price'];
  734. $total_return_amount += $return_order_product['transaction_price'];
  735. if(isset($return_now_stocks[$return_order_product['store_product_id']])) {
  736. $return_now_stocks[$return_order_product['store_product_id']] += 1;
  737. } else {
  738. $return_now_stocks[$return_order_product['store_product_id']] = 1;
  739. }
  740. }
  741. $total_order_rental_amount = fixed2Float( $total_product_amount + $total_sales_tax + $total_service_amount + $total_annual_fee);
  742. $total_receivable_amount = fixed2Float($total_product_amount + $total_sales_tax + $total_service_amount + $total_annual_fee - ($total_zue_coin * $zue_coin_exchange_rate));
  743. $total_receive_amount = $total_receivable_amount;
  744. $annual_fees = $this->orderAnnualFeeModel->fetchByOrderProductId($order_product_ids);
  745. Db::startTrans();
  746. try {
  747. // 退还御龙币
  748. $return_zue_coin = $order->zue_coin - $total_zue_coin;
  749. if ($return_zue_coin > 0) {
  750. $customer_zue_coin = $this->zueCoinModel->findByCustomerId($order->customer_id);
  751. if(!$customer_zue_coin) {
  752. throw new BaseException('御龙币账户记录不存在',1012);
  753. }
  754. Db::table('erp_customer_zue_coin')->where('id', '=', $customer_zue_coin->id)->inc('zue_coin', $return_zue_coin)->update();
  755. Db::table('erp_zue_coin_record')->save([
  756. 'zue_coin_id' => $customer_zue_coin->id,
  757. 'order_id' => $order->id,
  758. 'origin' => $customer_zue_coin->zue_coin,
  759. 'change' => $return_zue_coin,
  760. 'after' => $customer_zue_coin->zue_coin + $return_zue_coin,
  761. 'reason' => 3,
  762. 'create_time' => time(),
  763. 'update_time' => time(),
  764. ]);
  765. }
  766. // 退还年费
  767. if (count($annual_fees) > 0)
  768. 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()]);
  769. // 更新订单
  770. if (count($return_order_products) == count($all_order_products)){
  771. Db::table('erp_order')->where('id', $order->id)->update(['is_delete' => 1]);
  772. } else {
  773. Db::table('erp_order')->where('id', $order->id)->update([
  774. 'rental_amount' => $total_order_rental_amount,
  775. 'receivable_amount' => $total_receivable_amount,
  776. 'receive_amount' => $total_receive_amount,
  777. 'product_amount' => $total_product_amount,
  778. 'total_sales_tax' => $total_sales_tax,
  779. 'service_charge_amount' => $total_service_amount,
  780. 'total_annual_fee' => $total_annual_fee,
  781. 'zue_coin' => $total_zue_coin,
  782. 'zue_coin_amount' => $total_zue_coin_amount,
  783. 'obj_names' => join(',', array_unique($obj_names)),
  784. 'advisor_ids' => join(',', array_unique($advisor_ids)),
  785. ]);
  786. }
  787. // 插入退款记录
  788. Db::table('erp_order_payment')->save([
  789. 'order_id' => $order->id,
  790. 'channel_id' => 0,
  791. 'channel_name' => "Exchange a purchase",
  792. 'fee' => -$total_return_amount,
  793. 'create_time' => time(),
  794. 'update_time' => time(),
  795. ]);
  796. // 退还商品库存
  797. $return_stock_keys = array_keys($return_now_stocks);
  798. foreach ($return_stock_keys as $key) {
  799. Db::table("erp_store_product")
  800. ->where('id', $key)
  801. ->inc('now_stock', $return_now_stocks[$key])
  802. ->dec('sale_stock', $return_now_stocks[$key])
  803. ->update();
  804. }
  805. // 删除订单商品
  806. Db::table('erp_order_product')->where('id', 'in', $order_product_ids)->update(['is_delete' => 1, 'delete_time' => time()]);
  807. Db::commit();
  808. } catch (\Exception $e) {
  809. Db::rollback();
  810. return $this->fail(lang($e->getMessage()));
  811. }
  812. return $this->ok(true);
  813. }
  814. public function exchange($admin_id, $order_id, $origin_order_product_ids, $append_product_ids) {
  815. return $this->ok(true);
  816. }
  817. }