OrderService.php 22 KB

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