OrderService.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  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\OrderAnnualFeeModel;
  9. use app\common\model\OrderModel;
  10. use app\common\model\OrderPaymentModel;
  11. use app\common\model\OrderProceedsModel;
  12. use app\common\model\OrderProductModel;
  13. use app\common\model\PaymentChannelModel;
  14. use app\common\model\ProductModel;
  15. use app\common\model\StoreModel;
  16. use app\common\model\StoreProductModel;
  17. use think\cache\driver\Redis;
  18. use think\facade\Db;
  19. class OrderService extends \app\BaseService
  20. {
  21. private $storeModel;
  22. private $orderModel;
  23. private $productModel;
  24. private $orderAnnualFeeModel;
  25. private $orderPaymentModel;
  26. private $orderProductModel;
  27. private $orderProceedsModel;
  28. private $activityProductModel;
  29. private $storeProductModel;
  30. private $configModel;
  31. private $adminModel;
  32. private $customerModel;
  33. private $paymentChannelModel;
  34. private $creditCardModel;
  35. public function __construct()
  36. {
  37. $this->storeModel = new StoreModel();
  38. $this->orderModel = new OrderModel();
  39. $this->productModel = new ProductModel();
  40. $this->configModel = new ConfigModel();
  41. $this->storeProductModel = new StoreProductModel();
  42. $this->orderAnnualFeeModel = new OrderAnnualFeeModel();
  43. $this->orderPaymentModel = new OrderPaymentModel();
  44. $this->orderProductModel = new OrderProductModel();
  45. $this->orderProceedsModel = new OrderProceedsModel();
  46. $this->activityProductModel = new ActivityProductModel();
  47. $this->adminModel = new AdminModel();
  48. $this->customerModel = new CustomerModel();
  49. $this->paymentChannelModel = new PaymentChannelModel();
  50. $this->creditCardModel = new CreditCardConfigModel();
  51. }
  52. /**
  53. * @param $params
  54. * @param array $store_products_params
  55. * @return \SResult
  56. * @throws \think\db\exception\DataNotFoundException
  57. * @throws \think\db\exception\DbException
  58. * @throws \think\db\exception\ModelNotFoundException
  59. */
  60. public function create($params, array $store_products_params) {
  61. // 客户
  62. $customer = $this->customerModel->findById($params['customer_id']);
  63. if (!$customer)
  64. return $this->fail(lang("The Customer does not exist"));
  65. // 门店
  66. $store = $this->storeModel->findById($params['store_id']);
  67. if (!$store)
  68. return $this->fail(lang("The store does not exist"));
  69. // 顾问 or 老师 ids
  70. $user_ids = [];
  71. // 门店商品ids
  72. $store_product_ids = [];
  73. for ($i = 0; $i < count($store_products_params); $i++) {
  74. $store_products_param = $store_products_params[$i];
  75. $ids = [];
  76. if(isset($store_products_param->adviser_1_id)) array_push($ids, $store_products_param->adviser_1_id);
  77. if(isset($store_products_param->adviser_2_id)) array_push($ids, $store_products_param->adviser_2_id);
  78. if(isset($store_products_param->teacher_id)) array_push($ids, $store_products_param->teacher_id);
  79. $user_ids = array_unique(array_merge($user_ids, $ids));
  80. array_push($store_product_ids, $store_products_param->store_product_id);
  81. }
  82. // Adviser|Teacher
  83. $users = $this->adminModel->findByIds($user_ids)->toArray();
  84. if(count($users) != count($user_ids))
  85. return $this->fail(lang("The Adviser|Teacher does not exist"));
  86. $fmt_users = array_reduce($users, function ($result, $item) {
  87. $result[$item['id']] = $item;
  88. return $result;
  89. }, []);
  90. // 门店商品
  91. $store_products = $this->storeProductModel->fetchRelationsByOrder($store_product_ids)->toArray();
  92. if(count($store_products) != count($store_product_ids))
  93. return $this->fail(lang("The Product does not exist"));
  94. // 商品信息
  95. $products = array_map(function ($p) {
  96. return $p['product'] ? $p['product'] : null;
  97. }, $store_products);
  98. if(in_array(null, $products))
  99. return $this->fail(lang("The Product does not exist"));
  100. $config = $this->configModel->findConfig();
  101. $activityProducts = $this->activityProductModel->fetchByProductIds(array_map(function ($data) {
  102. return $data['id'];
  103. }, $products))->toArray();
  104. $fmt_store_products = [];
  105. foreach ($store_products as &$item) {
  106. $aProducts = array_filter($activityProducts, function ($aProduct) use ($item) {
  107. return $aProduct['product_id'] == $item['product_id'];
  108. });
  109. $res = compare($item['product']['real_price'] ?? 0, $aProducts);
  110. $item['activity'] = $res['item'];
  111. $item['product']['origin_price'] = $item['product']['real_price'];
  112. $item['product']['real_price'] = fixed2Float($res['min_num'] > 0 ? $res['min_num'] : 0);
  113. $sales_tax_rate = $item['product']['sales_tax_rate'] > 0 ? $item['product']['sales_tax_rate'] : $config->sales_tax_rate;
  114. $sales_tax = fixed2Float($sales_tax_rate > 0 && $item['product']['real_price'] > 0 ? ($item['product']['real_price'] * ($sales_tax_rate / 100)) : 0);
  115. $item['product']['sales_tax_rate'] = $sales_tax_rate;
  116. $item['product']['sales_tax'] = $sales_tax;
  117. $fmt_store_products[$item['id']] = $item;
  118. }
  119. $order_products = [];
  120. //项目总额
  121. $rental_amount = 0;
  122. $product_amount = 0;
  123. // 总消费税
  124. $total_sales_tax = 0;
  125. $advisor_1_ids = [];
  126. for ($i = 0; $i < count($store_products_params); $i++) {
  127. $store_products_param = $store_products_params[$i];
  128. $store_product = $fmt_store_products[$store_products_param->store_product_id];
  129. array_push($advisor_1_ids, $store_products_param->adviser_1_id);
  130. for ($j = 0; $j < $store_products_param->quantity; $j++) {
  131. array_push($order_products, [
  132. 'order_id' => 0,
  133. 'product_id' => $store_product['product']['id'],
  134. 'store_product_id' => $store_product['id'],
  135. 'product_name' => $store_product['product']['name'],
  136. 'adviser_1_id' => isset($store_products_param->adviser_1_id) ?? null,
  137. 'adviser_1_name' => isset($store_products_param->adviser_1_id) ? $fmt_users[$store_products_param->adviser_1_id]['nickname'] : null,
  138. 'adviser_2_id' => isset($store_products_param->adviser_2_id) ?? null,
  139. 'adviser_2_name' => isset($store_products_param->adviser_2_id) ? $fmt_users[$store_products_param->adviser_2_id]['nickname'] : null,
  140. 'teacher_id' => isset($store_products_param->teacher_id) ?? null,
  141. 'teacher_name' => isset($store_products_param->teacher_id) ? $fmt_users[$store_products_param->teacher_id]['nickname'] : null,
  142. 'is_upload_numerology' => $store_product['product']['is_upload_numerology'],
  143. 'is_upload' => 0,
  144. 'report' => null,
  145. 'is_gather_annuity' => $store_product['product']['is_gather_annuity'],
  146. 'annuity' => $store_product['product']['annuity'],
  147. 'real_price' => $store_product['product']['real_price'],
  148. 'service_charge' => 0,
  149. 'reduce_price' => $store_product['activity'] ? $store_product['product']['origin_price'] - $store_product['product']['real_price'] : 0,
  150. 'reduce_type' => $store_product['activity'] ? $store_product['activity']['type'] : 0,
  151. 'sales_tax_rate' => $store_product['product']['sales_tax_rate'],
  152. 'sales_tax' => $store_product['product']['sales_tax'],
  153. 'create_time' => time(),
  154. 'update_time' => time(),
  155. ]);
  156. $product_amount += $store_product['product']['real_price'];
  157. $total_sales_tax += $store_product['product']['sales_tax'];
  158. $rental_amount += ($store_product['product']['real_price'] + $store_product['product']['sales_tax']);
  159. }
  160. }
  161. $order = $this->orderModel->create([
  162. 'no' => $this->orderModel->genOrderNo($store->id, $store->abbr),
  163. 'customer_id' => $customer->id,
  164. 'customer_name' => $customer->name_en,
  165. 'rental_amount' => $rental_amount,
  166. 'receivable_amount' => $rental_amount,
  167. 'receive_amount' => 0,
  168. 'imposed_amount' => $rental_amount,
  169. 'product_amount' => $product_amount,
  170. 'total_sales_tax' => $total_sales_tax,
  171. 'service_charge_amount' => 0,
  172. 'type' => 2,
  173. 'store_id' => $store->id,
  174. 'advisor_ids' => join(',', $advisor_1_ids),
  175. 'create_time' => time(),
  176. 'update_time' => time()
  177. ]);
  178. foreach ($order_products as &$order_product) $order_product['order_id'] = $order->id;
  179. Db::startTrans();
  180. try {
  181. Db::table('erp_order_product')->insertAll($order_products);
  182. Db::commit();
  183. } catch (\Exception $e) {
  184. Db::rollback();
  185. Db::table('erp_order')->delete($order->id);
  186. return $this->fail(lang($e->getMessage()));
  187. }
  188. return $this->ok($order);
  189. }
  190. /**
  191. * @param $params
  192. * @param $channels
  193. * @return \SResult
  194. * @throws \app\exception\BaseException
  195. * @throws \think\db\exception\DataNotFoundException
  196. * @throws \think\db\exception\DbException
  197. * @throws \think\db\exception\ModelNotFoundException
  198. */
  199. public function payment($params, $channels) {
  200. $order = $this->orderModel->findById($params);
  201. if(!$order)
  202. return $this->fail('订单不存在!');
  203. if($order->type == 1)
  204. return $this->fail('订单状态为历史订单!不支持付款');
  205. $pay_channels = $this->paymentChannelModel->where('is_delete', 0)->select()->toArray();
  206. $fmt_pay_channels = array_reduce($pay_channels, function ($result, $item) {
  207. $result[$item['id']] = $item;
  208. return $result;
  209. },[]);
  210. $credit_card_configs = $this->creditCardModel->findAll()->toArray();
  211. $fmt_credit_card_configs = array_reduce($credit_card_configs, function ($result, $item) {
  212. $result[$item['id']] = $item;
  213. return $result;
  214. },[]);
  215. // 本次总计支付费用
  216. $total_fee = 0;
  217. // 本次信用卡支付手续费
  218. $service_charge = 0;
  219. // 本次御龙币
  220. $zue_coin = 0;
  221. $order_payments = [];
  222. $record_channel_names = [];
  223. for ($i = 0; $i < count($channels); $i++) {
  224. $channel = $channels[$i];
  225. $fmt_pay_channel = $fmt_pay_channels[$channel->channel_id];
  226. if (!$fmt_pay_channel)
  227. return $this->fail("支付渠道错误!");
  228. array_push($record_channel_names, '['.$fmt_pay_channel['name'].']');
  229. $item = [
  230. 'order_id' => $order->id,
  231. 'channel_id' => $channel->channel_id,
  232. 'create_time' => time(),
  233. 'update_time' => time(),
  234. ];
  235. if ($fmt_pay_channel['type'] == 1) { // 正常支付
  236. predicate(isset($channel->fee) && $channel->fee > 0, '支付费用未填写');
  237. $item['fee'] = $channel->fee;
  238. $total_fee += $channel->fee;
  239. if ($fmt_pay_channel['is_upload_code']) {
  240. predicate(isset($channel->code),'必须上传付款编号');
  241. $item['code'] = $channel->code;
  242. }
  243. array_push($order_payments, $item);
  244. } else if($fmt_pay_channel['type'] == 2) { // 御龙币支付
  245. predicate(isset($channel->fee) && $channel->fee > 0, '支付费用未填写');
  246. $item['fee'] = $channel->fee;
  247. // TODO: 御龙币需求未明确
  248. array_push($order_payments, $item);
  249. } else {
  250. for ($j = 0; $j < count($channel->credit_card); $j++) {
  251. $credit_card = $channel->credit_card[$j];
  252. $fmt_credit_card_config = $fmt_credit_card_configs[$credit_card->credit_card_id];
  253. if (!$fmt_credit_card_config)
  254. return $this->fail("信用卡支付渠道错误!");
  255. predicate(isset($credit_card->fee) && $credit_card->fee > 0, '支付费用未填写');
  256. $total_fee += $credit_card->fee;
  257. $el = [
  258. 'order_id' => $order->id,
  259. 'channel_id' => $channel->channel_id,
  260. 'fee' => $credit_card->fee,
  261. 'credit_card_id' => $credit_card->credit_card_id,
  262. 'credit_card_name' => $fmt_credit_card_config['bank'],
  263. 'create_time' => time(),
  264. 'update_time' => time(),
  265. ];
  266. if ($fmt_pay_channel['is_upload_code']) {
  267. predicate(isset($credit_card->code),'必须填写付款编号');
  268. $el['code'] = $credit_card->code;
  269. }
  270. if ($fmt_credit_card_config['is_stage'] == 1) {
  271. predicate(isset($credit_card->stage_num),'必须选择分期数');
  272. $el['stage_num'] = $credit_card->stage_num;
  273. $config = [
  274. '6' => $fmt_credit_card_config['stage_6'],
  275. '9' => $fmt_credit_card_config['stage_9'],
  276. '12' => $fmt_credit_card_config['stage_12'],
  277. '24' => $fmt_credit_card_config['stage_24'],
  278. '36' => $fmt_credit_card_config['stage_36'],
  279. ];
  280. $now_config = $config[$credit_card->stage_num];
  281. predicate($now_config[0] == 1,'该分期未启用!');
  282. if ($now_config[1] > 0) { // 收取手续费
  283. $el['service_charge_rate'] = $now_config[1];
  284. $now_service_charge = $el['fee'] * ($now_config[1] / 100);
  285. $el['service_charge'] = $now_service_charge;
  286. $service_charge += $now_service_charge;
  287. }
  288. }
  289. array_push($order_payments, $el);
  290. }
  291. }
  292. }
  293. // 总共需要收取这么多费用; (商品的价格 + 手续费 + 税费) - 御龙币抵扣的费用
  294. $imposed_amount = fixed2Float($order->product_amount + ($order->service_charge_amount + $service_charge) + $order->total_sales_tax);
  295. // 总计实收金额
  296. $receive_amount = fixed2Float($order->receive_amount + $total_fee);
  297. if (round($receive_amount) > round($imposed_amount)) return $this->fail("实收金额大于待收金额! 应该支付 {$imposed_amount}");
  298. $order_annual_fees = [];
  299. $update_store_products = [];
  300. if (round($receive_amount) == round($imposed_amount)) { // 减库存
  301. $order_products = $this->orderProductModel->findByOrderId($order->id)->toArray();
  302. $store_products = $this->storeProductModel->findByIds(array_map(function ($r) {return $r['store_product_id'];}, $order_products))->toArray();
  303. $fmt_store_products = array_reduce($store_products, function ($result, $item) {
  304. $result[$item['id']] = $item;
  305. return $result;
  306. },[]);
  307. foreach ($order_products as $order_product) {
  308. predicate($fmt_store_products[$order_product['store_product_id']]['now_stock'] > 0, lang('inventory shortage'));
  309. $fmt_store_products[$order_product['store_product_id']]['now_stock'] -= 1;
  310. if (isset($update_store_products[$order_product['store_product_id']])) {
  311. $update_store_products[$order_product['store_product_id']]['reduce_num'] += 1;
  312. } else {
  313. $update_store_products[$order_product['store_product_id']] = ['id' => $order_product['store_product_id'], 'reduce_num' => 1];
  314. }
  315. if ($order_product['is_gather_annuity']) {
  316. array_push($order_annual_fees, [
  317. 'order_id' => $order->id,
  318. 'order_product_id' => $order_product['product_id'],
  319. 'order_product_name' => $order_product['product_name'],
  320. 'fee' => $order_product['annuity'],
  321. 'is_pay' => 0,
  322. 'start_time' => time(),
  323. 'end_time' => time() + (365 * 24 * 60 * 60),
  324. 'create_time' => time(),
  325. 'update_time' => time(),
  326. ]);
  327. }
  328. }
  329. }
  330. Db::startTrans();
  331. try {
  332. $update_order = [
  333. 'rental_amount' => $imposed_amount,
  334. 'receivable_amount' => $imposed_amount,
  335. 'receive_amount' => $receive_amount,
  336. 'imposed_amount' => $imposed_amount - $receive_amount,
  337. 'service_charge_amount' => $order->service_charge_amount + $service_charge,
  338. ];
  339. if (round($receive_amount) == round($imposed_amount)) { // 支付满了
  340. $update_order['type'] = 2;
  341. Db::table('erp_order_product')->where('order_id', $order->id)->update(['is_pay' => 1]);
  342. if(count($order_annual_fees) > 0) {
  343. Db::table('erp_order_annual_fee')->insertAll($order_annual_fees);
  344. }
  345. if(count($update_store_products) > 0) {
  346. foreach ($update_store_products as $update) {
  347. Db::table('erp_store_product')->where('id', $update['id'])->dec('now_stock',1);
  348. Db::table('erp_store_product')->where('id', $update['id'])->inc('sale_stock',1);
  349. }
  350. }
  351. }
  352. Db::table('erp_order_proceeds')->save([
  353. 'order_id' => $order->id,
  354. 'channels' => join(' ',$record_channel_names),
  355. 'fee' => $total_fee,
  356. 'admin_id' => $params['admin_id'],
  357. 'admin_name' => $params['admin_name'],
  358. 'create_time' => time(),
  359. 'update_time' => time(),
  360. ]);
  361. if(count($order_payments) > 0) {
  362. Db::table('erp_order_payment')->insertAll(array_map(function ($data) {
  363. return [
  364. "order_id" => isset($data['order_id']) ? $data['order_id'] : null,
  365. "channel_id" => isset($data['channel_id']) ? $data['channel_id'] : null,
  366. "fee" => isset($data['fee']) ? $data['fee'] : null,
  367. "credit_card_id" => isset($data['credit_card_id']) ? $data['credit_card_id'] : null,
  368. "credit_card_name" => isset($data['credit_card_name']) ? $data['credit_card_name'] : null,
  369. "create_time" => isset($data['create_time']) ? $data['create_time'] : null,
  370. "update_time" => isset($data['update_time']) ? $data['update_time'] : null,
  371. "code" => isset($data['code']) ? $data['code'] : null,
  372. "stage_num" => isset($data['stage_num']) ? $data['stage_num'] : null,
  373. "service_charge_rate" => isset($data['service_charge_rate']) ? $data['service_charge_rate'] : null,
  374. "service_charge" => isset($data['service_charge']) ? $data['service_charge'] : null
  375. ];
  376. },$order_payments));
  377. }
  378. Db::table('erp_order')->where('id', $order->id)->update($update_order);
  379. Db::commit();
  380. } catch (\Exception $e) {
  381. Db::rollback();
  382. return $this->fail(lang($e->getMessage()));
  383. }
  384. return $this->ok(true);
  385. }
  386. }