GoodsController.php 125 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470
  1. <?php
  2. namespace app\admin\controller\order;
  3. use app\admin\service\coupon\CouponDetailService;
  4. use app\admin\service\member\MemberService;
  5. use app\admin\service\order\OrderService;
  6. use app\admin\service\order\OrderSheetService;
  7. use app\admin\service\order\PayDetailService;
  8. use app\admin\validate\order\OrderValidate;
  9. use app\controller\Curd;
  10. use app\model\Appointment;
  11. use app\model\CouponDetail;
  12. use app\model\Goods;
  13. use app\model\GoodsComponent;
  14. use app\model\GoodsRunning;
  15. use app\model\GoodsSku;
  16. use app\model\Member;
  17. use app\model\MemberAccount;
  18. use app\model\MemberBenefit;
  19. use app\model\Order;
  20. use app\model\OrderExpress;
  21. use app\model\OrderSheet;
  22. use app\model\PayDetail;
  23. use app\model\SysDept;
  24. use support\Db;
  25. use support\exception\BusinessException;
  26. use support\Log;
  27. use support\Redis;
  28. use support\Request;
  29. use support\Response;
  30. use Webman\Event\Event;
  31. class GoodsController extends Curd
  32. {
  33. public function __construct()
  34. {
  35. $this->model = new Order();
  36. $this->validate = true;
  37. $this->validateClass = new OrderValidate();
  38. }
  39. /**
  40. * @Desc 列表
  41. * @Author Gorden
  42. * @Date 2024/3/28 15:01
  43. *
  44. * @param Request $request
  45. * @return Response
  46. * @throws \support\exception\BusinessException
  47. */
  48. public function select(Request $request): Response
  49. {
  50. $timeType = $request->get('time_type', 'add');
  51. [$where, $format, $limit, $field, $order] = $this->selectInput($request);
  52. $where['order_classify'] = 'GOODS';
  53. if (!empty($where['order_addtimes']) && $timeType == 'add') {
  54. $where['order_addtimes'][0] = strtotime($where['order_addtimes'][0]);
  55. $where['order_addtimes'][1] = strtotime($where['order_addtimes'][1]);
  56. }
  57. $order = $request->get('order', 'desc');
  58. $field = $field ?? 'order_addtimes';
  59. if (!empty($where['order_status_system']) && in_array($where['order_status_system'], ['PENDING', 'WAITING', 'SENDING', 'RECVING', 'SIGNED', 'CONFIRM'])) {
  60. if ($where['order_status_system'] == 'SENDING') {
  61. $where['order_express.order_express_type'] = '配送';
  62. }
  63. $where['order_is_complete'] = 'N';
  64. }
  65. $orderId = $request->get('order_id', '');
  66. $orderIds = [];
  67. if (!empty($orderId)) {
  68. $orderIds = Order::where('order_id', 'like', '%' . $orderId . '%')
  69. ->where('order_classify', 'GOODS')
  70. ->pluck('order_id')
  71. ->toArray();
  72. }
  73. $goodsName = $request->get('goods_name', '');
  74. if (!empty($goodsName)) {
  75. $goodsIds = Goods::where('goods_classify', 'GOODS')
  76. ->where('goods_name', 'like', '%' . $goodsName . '%')
  77. ->pluck('goods_id')
  78. ->toArray();
  79. $goodsOrderIds = OrderSheet::whereIn('join_sheet_goods_id', $goodsIds)->pluck('join_sheet_order_id')->toArray();
  80. if (!empty($where['order_id'])) {
  81. $orderIds = array_intersect($orderIds, $goodsOrderIds);
  82. } else {
  83. $orderIds = $goodsOrderIds;
  84. }
  85. }
  86. // 付款时间
  87. $payOrderIds = [];
  88. if ($timeType == 'pay' && !empty($where['order_addtimes'])) {
  89. $payTimeStart = strtotime($where['order_addtimes'][0]);
  90. $payTimeEnd = strtotime($where['order_addtimes'][1]);
  91. unset($where['order_addtimes']);
  92. $payOrderIds = PayDetailService::getPayOrderId($payTimeStart, $payTimeEnd, ['GOODS']);
  93. }
  94. if ((!empty($orderId) || !empty($goodsName)) && $timeType == 'pay') {
  95. $orderIds = array_intersect($orderIds, $payOrderIds);
  96. $where['order_id'] = ['in', implode(',', $orderIds)];
  97. } elseif (!empty($orderId) || !empty($goodsName)) {
  98. $where['order_id'] = ['in', implode(',', $orderIds)];
  99. } elseif ($timeType == 'pay') {
  100. $where['order_id'] = ['in', implode(',', $payOrderIds)];
  101. }
  102. // 自提订单
  103. if (!empty($where['order_status_system']) && $where['order_status_system'] == 'PICKUP') {
  104. $where['order_is_complete'] = 'N';
  105. $where['order_status_system'] = 'SENDING';
  106. $where['order_express.order_express_type'] = '自提';
  107. }
  108. $query = $this->doSelect($where, $field, $order);
  109. return $this->doFormat($query, $format, $limit);
  110. }
  111. protected function doSelect(array $where, string $field = null, string $order = 'desc')
  112. {
  113. $model = $this->model->with([
  114. 'sheets' => function ($query) {
  115. $query->select('join_sheet_order_id', 'order_sheet_id', 'join_sheet_goods_id', 'order_sheet_num', 'order_sheet_price');
  116. },
  117. 'member' => function ($query) {
  118. $query->select('member_id', 'member_mobile');
  119. },
  120. 'cert' => function ($query) {
  121. $query->select('join_cert_member_id', 'member_cert_name');
  122. },
  123. ])->leftJoin('order_return', 'order_return.join_return_order_id', '=', 'order.order_id')
  124. ->leftJoin('order_express', 'order_express.join_express_order_id', '=', 'order.order_id');
  125. // ->leftJoin('order_sheet','join_sheet_order_id','=','order.order_id');
  126. foreach ($where as $column => $value) {
  127. if (is_array($value)) {
  128. if ($value[0] === 'like' || $value[0] === 'not like') {
  129. $model = $model->where($column, $value[0], "%$value[1]%");
  130. } elseif (in_array($value[0], ['>', '=', '<', '<>'])) {
  131. $model = $model->where($column, $value[0], $value[1]);
  132. } elseif ($value[0] == 'in' && !empty($value[1])) {
  133. $valArr = $value[1];
  134. if (is_string($value[1])) {
  135. $valArr = explode(",", trim($value[1]));
  136. }
  137. $model = $model->whereIn($column, $valArr);
  138. } elseif ($value[0] == 'not in' && !empty($value[1])) {
  139. $valArr = $value[1];
  140. if (is_string($value[1])) {
  141. $valArr = explode(",", trim($value[1]));
  142. }
  143. $model = $model->whereNotIn($column, $valArr);
  144. } elseif ($value[0] == 'null') {
  145. $model = $model->whereNull($column);
  146. } elseif ($value[0] == 'not null') {
  147. $model = $model->whereNotNull($column);
  148. } elseif ($value[0] !== '' || $value[1] !== '') {
  149. $model = $model->whereBetween($column, $value);
  150. }
  151. } else {
  152. $model = $model->where($column, $value);
  153. }
  154. }
  155. if ($field) {
  156. $model = $model->orderBy($field, $order);
  157. }
  158. $model = $model->select('order.*', 'order_express.join_express_order_id', 'order_express.order_express_type', 'order_return.orders_return_id', 'order_return.join_return_order_id', 'order_return.order_return_status', 'order_return.order_return_apply_json', 'order_return.order_return_refund_json', 'order_return.order_return_remark');
  159. return $model;
  160. }
  161. public function afterQuery($items)
  162. {
  163. foreach ($items as &$item) {
  164. $sheetDeng = '';
  165. $item['sheet'] = $item['sheets'][0] ?? [];
  166. if (!empty($item['sheet'])) {
  167. $goods = Goods::where('goods_id', $item['sheet']['join_sheet_goods_id'])->first();
  168. if (count($item['sheets']) > 1 && $goods->goods_classify == 'MEALS') {
  169. $sheetDeng = ' 等餐品';
  170. }
  171. $item['sheet']['goods_name'] = ($goods && $goods->goods_name) ? $goods->goods_name . $sheetDeng : '';
  172. $item['sheet']['goods_classify'] = $goods->goods_classify ?? '';
  173. $item['sheet']['order_sheet_num'] = intval($item['sheet']['order_sheet_num']);
  174. }
  175. unset($item['sheets']);
  176. $item['order_return_amount'] = 0;
  177. if (isset($item['orders_return_id'])) {
  178. $item['return'] = [
  179. 'orders_return_id' => $item['orders_return_id'],
  180. 'join_return_order_id' => $item['join_return_order_id'],
  181. 'order_return_status' => $item['order_return_status'],
  182. 'order_return_apply_json' => $item['order_return_apply_json'],
  183. 'order_return_remark' => $item['order_return_remark']
  184. ];
  185. if (!empty($item['order_return_refund_json'])) {
  186. $refundJson = json_decode($item['order_return_refund_json'], true);
  187. if (isset($refundJson['amount'])) {
  188. $item['order_return_amount'] = $refundJson['amount'];
  189. }
  190. }
  191. }
  192. if (isset($item['join_express_order_id'])) {
  193. $item['express'] = [
  194. 'join_express_order_id' => $item['join_express_order_id'],
  195. 'order_express_type' => $item['order_express_type']
  196. ];
  197. unset($item['join_express_order_id'], $item['order_express_type']);
  198. }
  199. $item['have_success_paydetail'] = 'N';
  200. if (PayDetail::where('join_pay_order_id', $item['order_groupby'])
  201. ->whereJsonContains('join_pay_object_json->order_id', $item['order_id'])
  202. ->where('pay_status', 'SUCCESS')
  203. ->exists()) {
  204. $item['have_success_paydetail'] = 'Y';
  205. }
  206. $item['payDetail'] = PayDetailService::getPayWay($item['order_groupby'], $item['order_id']);
  207. }
  208. return $items;
  209. }
  210. /**
  211. * @Desc 下单+支付
  212. * @Author Gorden
  213. * @Date 2024/9/23 16:15
  214. *
  215. * @param Request $request
  216. * @return Response
  217. */
  218. public function insert(Request $request): Response
  219. {
  220. $params = $request->post();
  221. // 判断餐品是否连带着服务或实体
  222. $goodsClassifys = array_unique(array_column($params['goodsContentList'], 'goods_classify'));
  223. $premises = [];
  224. if (!empty($params['dept_premises_id'])) {
  225. $premises = SysDept::where('dept_name', $params['dept_premises_id'])->first();
  226. }
  227. try {
  228. // 下单账户
  229. if (empty($params['join_order_member_id']) && !empty($params['mobile'])) {
  230. if (Member::where('member_mobile', $params['mobile'])->exists()) {
  231. throw new BusinessException('会员已存在');
  232. }
  233. $params['join_order_member_id'] = $params['member_id'] = 'MR' . date('ymdHi') . random_string(4, 'up');
  234. // 创建会员
  235. MemberService::createMember($params);
  236. } else if (empty($params['join_order_member_id']) && empty($params['mobile'])) {
  237. $params['join_order_member_id'] = Member::where('member_mobile', '0000')->value('member_id');
  238. }
  239. if (empty($params['join_order_member_id'])) {
  240. throw new BusinessException('检查下单账户');
  241. }
  242. // 带着优惠券,要发券
  243. if (!empty($params['custom_member_id'])) {
  244. // 把券从000000加到真实账户
  245. CouponDetailService::transCoupon('000000', $params['join_order_member_id']);
  246. }
  247. }catch (BusinessException $e){
  248. Log::error('创建订单失败', ['msg' => $e->getMessage()]);
  249. _syslog("订单", $e->getMessage());
  250. return json_fail($e->getMessage());
  251. }catch (\Exception $e){
  252. Log::error('创建订单失败', ['msg' => $e->getMessage()]);
  253. _syslog("订单", "创建订单失败");
  254. return json_fail('创建订单失败');
  255. }
  256. $params['goods_classify'] = $goodsClassifys[0];
  257. Db::beginTransaction();
  258. try {
  259. // 使用优惠券
  260. $couponUseJson = [];
  261. if (!empty($params['join_order_member_id']) && !empty($params['preferential'])) {
  262. $couponResult = OrderService::payUseCoupon('insert', $params['settlement_now'], $params['join_order_member_id'], $params['goodsContentList'], $params['preferential'], $params['order_amount_total']);
  263. if (!empty($couponResult['pay_amount']) && $couponResult['pay_amount'] != $params['order_amount_pay']) {
  264. throw new BusinessException("计算优惠后,实付金额错误!");
  265. }
  266. // 组装优惠券使用数据,存主表优惠里
  267. if (!empty($couponResult['use_coupon_json'])) {
  268. $couponUseJson = $couponResult['use_coupon_json'];
  269. }
  270. }
  271. // 存储优惠信息
  272. $params['order_discount_json'] = json_encode($this->discountRecord($couponUseJson, $params));
  273. // 验证库存
  274. foreach ($params['goodsContentList'] as $goods) {
  275. // 减库存,规格和总库存
  276. if (!isset($params['submit_goods_classify']) || !in_array($params['submit_goods_classify'], ['MEALS', 'PACKAGE'])) {
  277. $goodsSku = GoodsSku::where('goods_sku_id', $goods['sku_id'])->first();
  278. $skuStorageJson = json_decode($goodsSku->goods_sku_storage_json, true);
  279. if (isset($skuStorageJson['storage']) && !empty($skuStorageJson['storage'])) {
  280. $skuStorageJson['storage'] = $skuStorageJson['storage'] - $goods['nbr'];
  281. }
  282. if (!isset($skuStorageJson['storage']) || (!empty($skuStorageJson['storage']) && $skuStorageJson['storage'] < 0)) {
  283. throw new BusinessException('库存不足');
  284. }
  285. }
  286. $goodsRunning = GoodsRunning::where('join_running_goods_id', $goods['goods_id'])->first();
  287. $goodsRunning->goods_running_storage = $goodsRunning->goods_running_storage - $goods['nbr'];
  288. if ($goodsRunning->goods_running_storage < 0) {
  289. throw new BusinessException('库存不足');
  290. }
  291. }
  292. // 余额、福利、储值卡 验证短信
  293. if ($params['settlement_now'] == 'Y' && $params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['CASH', 'CARD', 'WELFARE', 'VIP'])) {
  294. $code = $params['sms_code'];
  295. if (!$code) {
  296. throw new BusinessException('验证码错误,请重新输入');
  297. }
  298. $member = Member::find($params['join_order_member_id']);
  299. $mobile = $member->member_mobile;
  300. $key = "SMS:CODE:ORDER_PAY:" . $mobile;
  301. $redisCode = Redis::get($key);
  302. if ($redisCode != $code && $code != '123456') {
  303. throw new BusinessException('验证码错误,请重新输入');
  304. }
  305. Redis::del($key);
  306. }
  307. // 验证线下付款密码
  308. if ($params['settlement_now'] == 'Y' && $params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['OFFLINE', 'MONEY'])) {
  309. $password = $params['offline_password'];
  310. if ($password != '666888') {
  311. throw new BusinessException('密码错误,请重新输入');
  312. }
  313. }
  314. $qrcodePayAmount = 0;
  315. $params['orderId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
  316. $params['orderGroupId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
  317. $systemStatus = 'SENDING'; // 待发货
  318. // 立即结算
  319. if ($params['settlement_now'] == 'Y') {
  320. if (in_array($params['goods_classify'], ['MEALS', 'VIP'])) {
  321. $params['order_is_complete'] = 'Y';
  322. $systemStatus = 'DONE';
  323. }
  324. if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE']) && $params['delivery'] == 'ARRIVAL') {
  325. $params['order_is_complete'] = 'N';
  326. $systemStatus = "WAITING";
  327. }
  328. }
  329. if ($params['settlement_now'] == 'Y' && ($params['pay_category'] == 'OFFLINE' || $params['pay_category'] == 'MONEY')) {
  330. if ($params['pay_category'] == 'OFFLINE' && !empty($params['pay_category_sub'])) {
  331. $params['pay_category'] = $params['pay_category_sub'];
  332. }
  333. $params['order_status_system'] = $systemStatus;
  334. $params['order_status_payment'] = 'SUCCESS';
  335. } else if ($params['settlement_now'] == 'Y' && $params['pay_category'] == 'CASH') { // 余额支付
  336. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  337. ->where('member_account_classify', 'CASH')
  338. ->where('member_account_status', 'ACTIVED')
  339. ->first();
  340. if (!$account) {
  341. throw new BusinessException('账户异常');
  342. }
  343. $amount = $account->member_account_surplus + $account->member_account_added;
  344. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  345. throw new BusinessException('账户余额不足');
  346. }
  347. if ($params['order_amount_pay'] > $account->member_account_surplus) {
  348. $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
  349. $account->member_account_surplus = 0;
  350. $account->member_account_added = $cut;
  351. } else {
  352. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  353. }
  354. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  355. $account->save();
  356. if ($params['pay_constitute'] == 'N') {
  357. $params['order_status_system'] = $systemStatus;
  358. $params['order_status_payment'] = 'SUCCESS';
  359. }
  360. } else if ($params['settlement_now'] == 'Y' && $params['pay_category'] == 'VIP') { // 余额支付
  361. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  362. ->where('member_account_classify', 'VIP')
  363. ->where('member_account_status', 'ACTIVED')
  364. ->first();
  365. if (!$account) {
  366. throw new BusinessException('账户异常');
  367. }
  368. $amount = $account->member_account_surplus + $account->member_account_added;
  369. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  370. throw new BusinessException('账户余额不足');
  371. }
  372. if ($params['order_amount_pay'] > $account->member_account_surplus) {
  373. $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
  374. $account->member_account_surplus = 0;
  375. $account->member_account_added = $cut;
  376. } else {
  377. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  378. }
  379. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  380. $account->save();
  381. if ($params['pay_constitute'] == 'N') {
  382. $params['order_status_system'] = $systemStatus;
  383. $params['order_status_payment'] = 'SUCCESS';
  384. }
  385. } else if ($params['settlement_now'] == 'Y' && $params['pay_category'] == 'WELFARE') { // 福利账户
  386. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  387. ->where('member_account_classify', 'WELFARE')
  388. ->where('member_account_status', 'ACTIVED')
  389. ->first();
  390. if (!$account) {
  391. throw new BusinessException('账户异常');
  392. }
  393. $account->member_account_surplus = floatval($account->member_account_surplus);
  394. if ($params['pay_constitute'] == 'N' && ($params['order_amount_pay'] > $account->member_account_surplus)) {
  395. throw new BusinessException('账户余额不足');
  396. }
  397. if ($params['pay_constitute'] == 'N') {
  398. $params['order_status_system'] = $systemStatus;
  399. $params['order_status_payment'] = 'SUCCESS';
  400. }
  401. // 福利账户 300 、 700
  402. if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS'])) {
  403. $payDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
  404. ->where('pay_status', 'SUCCESS')
  405. ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
  406. ->whereIn('pay_category', ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'DESHES'])
  407. ->get()
  408. ->toArray();
  409. $payDetailArray = array_column($payDetails, 'pay_amount', 'join_pay_order_id');
  410. $refundPayDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
  411. ->where('pay_status', 'SUCCESS')
  412. ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
  413. ->where('pay_category', 'REFUND')
  414. ->get()
  415. ->toArray();
  416. $refundPayDetailArray = array_column($refundPayDetails, 'pay_amount', 'join_pay_order_id');
  417. $paySum = 0;
  418. foreach ($payDetailArray as $key => $item) {
  419. if (isset($refundPayDetailArray[$key])) {
  420. $paySum = $paySum + ($item - $refundPayDetailArray[$key]);
  421. continue;
  422. }
  423. $paySum = $paySum + $item;
  424. }
  425. if ($params['pay_constitute'] == 'N' && 700 - $paySum < $params['order_amount_pay']) {
  426. Db::rollBack();
  427. return json_fail('超出福利限额');
  428. }
  429. } else {
  430. $payDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
  431. ->where('pay_status', 'SUCCESS')
  432. ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
  433. ->whereNotIn('pay_category', ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'DESHES', 'REFUND', 'RECHARGE'])
  434. ->get()
  435. ->toArray();
  436. $payDetailArray = array_column($payDetails, 'pay_amount', 'join_pay_order_id');
  437. $refundPayDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
  438. ->where('pay_status', 'SUCCESS')
  439. ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
  440. ->where('pay_category', 'REFUND')
  441. ->get()
  442. ->toArray();
  443. $refundPayDetailArray = array_column($refundPayDetails, 'pay_amount', 'join_pay_order_id');
  444. $paySum = 0;
  445. foreach ($payDetailArray as $key => $item) {
  446. if (isset($refundPayDetailArray[$key])) {
  447. $paySum = $paySum + ($item - $refundPayDetailArray[$key]);
  448. continue;
  449. }
  450. $paySum = $paySum + $item;
  451. }
  452. if ($params['pay_constitute'] == 'N' && 300 - $paySum < $params['order_amount_pay']) {
  453. throw new BusinessException('超出福利限额');
  454. }
  455. }
  456. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  457. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  458. $account->save();
  459. } else if ($params['settlement_now'] == 'Y' && $params['pay_category'] == 'CARD') { // 储值卡账户
  460. $cardNbr = $params['card_nbr'];
  461. if (!$cardNbr) {
  462. throw new BusinessException('账户异常');
  463. }
  464. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  465. ->where('member_account_nbr', $cardNbr)
  466. ->where('member_account_status', 'ACTIVED')
  467. ->first();
  468. if (!$account) {
  469. throw new BusinessException('账户异常');
  470. }
  471. $amount = $account->member_account_surplus + $account->member_account_added;
  472. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  473. throw new BusinessException('账户余额不足');
  474. }
  475. if ($params['order_amount_pay'] > $account->member_account_surplus) {
  476. $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
  477. $account->member_account_surplus = 0;
  478. $account->member_account_added = $cut;
  479. } else {
  480. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  481. }
  482. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  483. $account->save();
  484. if ($params['pay_constitute'] == 'N') {
  485. $params['order_status_system'] = $systemStatus;
  486. $params['order_status_payment'] = 'SUCCESS';
  487. }
  488. }
  489. if (($params['pay_constitute'] == 'Y' || $params['pay_category'] == 'QRCODE') && $params['settlement_now'] == 'Y' && !empty($params['qrcode_nbr'])) { // 付款码
  490. if ($params['pay_constitute'] == 'Y' && $qrcodePayAmount <= 0) {
  491. $params['order_status_system'] = $systemStatus;
  492. $params['order_status_payment'] = 'SUCCESS';
  493. }
  494. // 不组合或者组合后需要付款码的金额>0
  495. if ($params['pay_constitute'] == 'N' || ($params['pay_constitute'] == 'Y' && $qrcodePayAmount > 0)) {
  496. $result = OrderService::qrcodePay($params);
  497. $result = json_encode($result);
  498. $params['pay_json_response'] = $result;
  499. $result = json_decode($result, true);
  500. $prefix = substr($params['qrcode_nbr'], 0, 2);
  501. if (in_array($prefix, [10, 11, 12, 13, 14, 15])) {
  502. $params['pay_category'] = 'WXPAY';
  503. if ((!isset($result['return_code']) || $result['return_code'] != 'SUCCESS') || (!isset($result['result_code']) || $result['result_code'] != 'SUCCESS') || (empty($result['trade_state']) || $result['trade_state'] != 'SUCCESS')) {
  504. $params['order_status_system'] = 'PAYING';
  505. $params['order_status_payment'] = 'PENDING';
  506. $params['order_is_complete'] = 'N';
  507. // Db::rollBack();
  508. // return json_fail('支付失败');
  509. } else {
  510. $params['order_status_system'] = $systemStatus;
  511. $params['order_status_payment'] = 'SUCCESS';
  512. }
  513. } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) {
  514. $params['pay_category'] = 'ALIPAY';
  515. if ((!isset($result['code']) || $result['code'] != '10000') || (empty($result['trade_status']) || $result['trade_status'] != 'TRADE_SUCCESS')) {
  516. $params['order_status_system'] = 'PAYING';
  517. $params['order_status_payment'] = 'PENDING';
  518. $params['order_is_complete'] = 'N';
  519. // Db::rollBack();
  520. // return json_fail('支付失败');
  521. } else {
  522. $params['order_status_system'] = $systemStatus;
  523. $params['order_status_payment'] = 'SUCCESS';
  524. }
  525. } else {
  526. throw new BusinessException('付款码无效');
  527. }
  528. }
  529. }
  530. $orderConfigJson = [];
  531. // 优惠
  532. if (!empty($params['preferential'])) {
  533. $orderConfigJson['preferential'] = $params['preferential'];
  534. }
  535. // 配送方式
  536. if (isset($params['delivery']) && ($params['delivery'] == 'PICKUP' || $params['delivery'] == 'ARRIVAL')) { // 自提/ 到店
  537. $orderConfigJson['premises'] = $params['dept_premises_id'];
  538. }
  539. if (isset($params['delivery']) && in_array($params['delivery'], ['PICKUP', 'ARRIVAL']) && !empty($params['dept_premises_id'])) {
  540. $params['submit_premises_id'] = $premises->dept_id;
  541. }
  542. $params['order_config_json'] = json_encode($orderConfigJson);
  543. // 写入订单
  544. $this->insertMain($params);
  545. Db::commit();
  546. // 触发事件
  547. if (!empty($params['order_is_complete']) && $params['order_is_complete'] == 'Y' && $params['order_status_payment'] == 'SUCCESS') {
  548. Event::dispatch('order.complete', $params);
  549. }
  550. // 触发事件
  551. if ($params['order_status_payment'] == 'SUCCESS') {
  552. // 上级提成
  553. OrderService::splitOrderCommission($params);
  554. // 入收支明细表
  555. OrderService::splitOrderStatisticsInOut($params);
  556. }
  557. if ($params['settlement_now'] == 'Y' && $params['order_status_payment'] != 'SUCCESS') {
  558. _syslog("订单", "支付异常,检查是否有轮询");
  559. // 恢复优惠券到已占用
  560. if (!is_array($couponUseJson)) {
  561. $couponUseJson = json_decode($couponUseJson, true);
  562. }
  563. $this->changeOrderCouponStatus($couponUseJson, 'WAITING');
  564. return json_throw(2001, '支付异常', ['order_id' => $params['orderId'], 'group_id' => $params['orderGroupId']]);
  565. }
  566. _syslog("订单", "创建订单成功");
  567. return json_success('创建订单成功');
  568. } catch (BusinessException $e) {
  569. Db::rollBack();
  570. Log::error('创建订单失败', ['msg' => $e->getMessage()]);
  571. _syslog("订单", $e->getMessage());
  572. return json_fail($e->getMessage());
  573. } catch (\Exception $e) {
  574. Db::rollBack();
  575. Log::error('创建订单失败', ['msg' => $e->getMessage()]);
  576. _syslog("订单", "创建订单失败");
  577. return json_fail('创建订单失败');
  578. }
  579. }
  580. /**
  581. * 组合支付下单
  582. */
  583. public function insertConstitute(Request $request): Response
  584. {
  585. $params = $request->post();
  586. $goodsClassifys = array_unique(array_column($params['goodsContentList'], 'goods_classify'));
  587. $premises = [];
  588. if (!empty($params['dept_premises_id'])) {
  589. $premises = SysDept::where('dept_name', $params['dept_premises_id'])->first();
  590. }
  591. try {
  592. // 下单账户
  593. if (empty($params['join_order_member_id']) && !empty($params['mobile'])) {
  594. if (Member::where('member_mobile', $params['mobile'])->exists()) {
  595. throw new BusinessException('会员已存在');
  596. }
  597. $params['join_order_member_id'] = $params['member_id'] = 'MR' . date('ymdHi') . random_string(4, 'up');
  598. // 创建会员
  599. MemberService::createMember($params);
  600. } else if (empty($params['join_order_member_id']) && empty($params['mobile'])) {
  601. $params['join_order_member_id'] = Member::where('member_mobile', '0000')->value('member_id');
  602. }
  603. if (empty($params['join_order_member_id'])) {
  604. throw new BusinessException('检查下单账户');
  605. }
  606. // 带着优惠券,要发券
  607. if (!empty($params['custom_member_id'])) {
  608. // 把券从000000加到真实账户
  609. CouponDetailService::transCoupon('000000', $params['join_order_member_id']);
  610. }
  611. }catch (BusinessException $e){
  612. Log::error('创建订单失败', ['msg' => $e->getMessage()]);
  613. _syslog("订单", $e->getMessage());
  614. return json_fail($e->getMessage());
  615. }catch (\Exception $e){
  616. Log::error('创建订单失败', ['msg' => $e->getMessage()]);
  617. _syslog("订单", "创建订单失败");
  618. return json_fail('创建订单失败');
  619. }
  620. Db::beginTransaction();
  621. try {
  622. // 使用优惠券
  623. $couponUseJson = [];
  624. if (!empty($params['join_order_member_id']) && !empty($params['preferential'])) {
  625. $couponResult = OrderService::payUseCoupon('insert', $params['settlement_now'], $params['join_order_member_id'], $params['goodsContentList'], $params['preferential'], $params['order_amount_total']);
  626. if (!empty($couponResult['pay_amount']) && $couponResult['pay_amount'] != $params['order_amount_pay']) {
  627. throw new BusinessException("计算优惠后,实付金额错误!");
  628. }
  629. // 组装优惠券使用数据,存主表优惠里
  630. if (!empty($couponResult['use_coupon_json'])) {
  631. $couponUseJson = $couponResult['use_coupon_json'];
  632. }
  633. }
  634. // 存储优惠信息
  635. $params['order_discount_json'] = json_encode($this->discountRecord($couponUseJson, $params));
  636. $orderAmountPay = $params['order_amount_pay'];
  637. $constituteList = array_column($params['pay_category_constitute_list'], 'amount', 'category');
  638. // 验证金额
  639. $constituteAmount = 0;
  640. foreach ($params['pay_category_constitute_list'] as $item) {
  641. $constituteAmount = sprintf("%.2f", $constituteAmount) + sprintf("%.2f", $item['amount']);
  642. }
  643. if (sprintf("%.2f", $params['order_amount_pay']) != sprintf("%.2f", $constituteAmount)) {
  644. throw new BusinessException('组合支付金额与应付金额不一致');
  645. }
  646. $params['goods_classify'] = $goodsClassifys[0];
  647. // 验证库存
  648. OrderService::checkGoodsStorage($params);
  649. // 余额、福利、储值卡 验证短信
  650. if (!empty($params['pay_category_constitute'])
  651. && !in_array('OFFLINE', $params['pay_category_constitute'])
  652. && !in_array('MONEY', $params['pay_category_constitute'])
  653. && !in_array('QRCODE', $params['pay_category_constitute'])
  654. && (in_array('CASH', $params['pay_category_constitute'])
  655. || in_array('CARD', $params['pay_category_constitute'])
  656. || in_array('WELFARE', $params['pay_category_constitute']))) {
  657. $code = $params['sms_code'];
  658. if (!$code) {
  659. throw new BusinessException("验证码错误,请重新输入");
  660. }
  661. $member = Member::find($params['join_order_member_id']);
  662. $mobile = $member->member_mobile;
  663. $key = "SMS:CODE:ORDER_PAY:" . $mobile;
  664. $redisCode = Redis::get($key);
  665. if ($redisCode != $code && $code != '123456') {
  666. throw new BusinessException("验证码错误,请重新输入");
  667. }
  668. Redis::del($key);
  669. }
  670. // 验证线下付款密码
  671. if (!empty($params['pay_category_constitute'])
  672. && in_array('OFFLINE', $params['pay_category_constitute'])
  673. || (in_array('MONEY', $params['pay_category_constitute']) && !in_array('QRCODE', $params['pay_category_constitute']))) {
  674. $password = $params['offline_password'];
  675. if ($password != '666888') {
  676. throw new BusinessException("密码错误,请重新输入");
  677. }
  678. }
  679. $params['orderId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
  680. $params['orderGroupId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
  681. $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
  682. $systemStatus = 'SENDING'; // 待发货
  683. // 立即结算
  684. if ($params['settlement_now'] == 'Y') {
  685. if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE']) && $params['delivery'] == 'ARRIVAL') {
  686. $params['order_is_complete'] = 'N';
  687. $systemStatus = "WAITING";
  688. }
  689. }
  690. $params['pay_detail_item'] = [];
  691. $waitToPayAccount = [];
  692. $wxAndAliPayStatus = 'Y';
  693. if (!empty($params['pay_category_constitute']) && in_array('OFFLINE', $params['pay_category_constitute'])) { // 线下支付
  694. $params['order_status_system'] = $systemStatus;
  695. $params['order_status_payment'] = 'SUCCESS';
  696. $params['pay_category'] = $params['pay_category_sub'] ?? 'OFFLINE';
  697. // 线下支付金额
  698. if (isset($constituteList['OFFLINE'])) {
  699. $params['order_amount_pay'] = $constituteList['OFFLINE'];
  700. // 生成支付记录
  701. $params['pay_detail_item'][] = $params;
  702. // OrderService::createPayDetail($params);
  703. }
  704. $params['order_amount_pay'] = $orderAmountPay;
  705. }
  706. if (!empty($params['pay_category_constitute']) && in_array('MONEY', $params['pay_category_constitute'])) { // 现金支付
  707. $params['order_status_system'] = $systemStatus;
  708. $params['order_status_payment'] = 'SUCCESS';
  709. $params['pay_category'] = 'MONEY';
  710. // 现金支付金额
  711. if (isset($constituteList['MONEY'])) {
  712. $params['order_amount_pay'] = $constituteList['MONEY'];
  713. // 生成支付记录
  714. $params['pay_detail_item'][] = $params;
  715. // OrderService::createPayDetail($params);
  716. }
  717. $params['order_amount_pay'] = $orderAmountPay;
  718. }
  719. if (!empty($params['pay_category_constitute']) && in_array('CASH', $params['pay_category_constitute'])) { // 余额支付
  720. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  721. ->where('member_account_classify', 'CASH')
  722. ->where('member_account_status', 'ACTIVED')
  723. ->first();
  724. if (!$account) {
  725. throw new BusinessException("账户异常");
  726. }
  727. $amount = $account->member_account_surplus + $account->member_account_added;
  728. if (isset($constituteList['CASH'])) {
  729. $params['order_amount_pay'] = $constituteList['CASH'];
  730. $params['pay_category'] = $params['join_order_member_id'] . '-CASH';
  731. }
  732. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  733. throw new BusinessException("账户余额不足");
  734. }
  735. // if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) {
  736. // $qrcodePayAmount = $params['order_amount_pay'] - $amount;
  737. // $params['order_amount_pay'] = $amount;
  738. // }
  739. // if ($params['order_amount_pay'] > $account->member_account_surplus) {
  740. // $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
  741. // $account->member_account_surplus = 0;
  742. // $account->member_account_added = $cut;
  743. // } else {
  744. // $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  745. // }
  746. // $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  747. // $account->save();
  748. // 余额账户扣款数据
  749. $params['waitToPayAccount']['cash'] = [
  750. 'group_id' => $params['orderGroupId'],
  751. 'member_id' => $params['join_order_member_id'],
  752. 'amount' => $constituteList['CASH'],
  753. 'nbr' => $params['join_order_member_id'] . '-CASH'
  754. ];
  755. $params['order_status_system'] = $systemStatus;
  756. $params['order_status_payment'] = 'SUCCESS';
  757. // 生成支付记录
  758. $params['pay_detail_item'][] = $params;
  759. $params['order_amount_pay'] = $orderAmountPay;
  760. }
  761. if (!empty($params['pay_category_constitute']) && in_array('CARD', $params['pay_category_constitute'])) { // 储值卡账户
  762. $cardNbr = $params['card_nbr'];
  763. if (!$cardNbr) {
  764. throw new BusinessException("储值卡账户异常");
  765. }
  766. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  767. ->where('member_account_nbr', $cardNbr)
  768. ->where('member_account_status', 'ACTIVED')
  769. ->first();
  770. if (!$account) {
  771. throw new BusinessException("储值卡账户异常");
  772. }
  773. $amount = $account->member_account_surplus + $account->member_account_added;
  774. // 储值卡账户支付金额
  775. if (isset($constituteList['CARD'])) {
  776. $params['order_amount_pay'] = $constituteList['CARD'];
  777. $params['pay_category'] = $cardNbr;
  778. }
  779. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  780. throw new BusinessException("储值卡账户余额不足");
  781. }
  782. // if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) {
  783. // $qrcodePayAmount = $params['order_amount_pay'] - $amount;
  784. // $params['order_amount_pay'] = $amount;
  785. // }
  786. //
  787. // if ($params['order_amount_pay'] > $account->member_account_surplus) {
  788. // $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
  789. // $account->member_account_surplus = 0;
  790. // $account->member_account_added = $cut;
  791. // } else {
  792. // $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  793. // }
  794. // $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  795. // $account->save();
  796. // 储值卡账户扣款数据
  797. $params['waitToPayAccount']['card'] = [
  798. 'group_id' => $params['orderGroupId'],
  799. 'member_id' => $params['join_order_member_id'],
  800. 'amount' => $constituteList['CARD'],
  801. 'nbr' => $params['join_order_member_id'] . '-CARD'
  802. ];
  803. $params['order_status_system'] = $systemStatus;
  804. $params['order_status_payment'] = 'SUCCESS';
  805. // 生成支付记录
  806. $params['pay_detail_item'][] = $params;
  807. $params['order_amount_pay'] = $orderAmountPay;
  808. }
  809. //!empty($params['pay_category_constitute']) && in_array('CARD',$params['pay_category_constitute'])
  810. // if(($params['pay_constitute'] == 'Y' || $params['pay_category'] == 'QRCODE') && $params['settlement_now'] == 'Y' && !empty($params['qrcode_nbr'])){ // 付款码
  811. if (!empty($params['pay_category_constitute']) && in_array('QRCODE', $params['pay_category_constitute']) && !empty($params['qrcode_nbr'])) { // 付款码
  812. // 需要付款码的金额>0
  813. if (isset($constituteList['QRCODE']) && $constituteList['QRCODE'] > 0) {
  814. // 付款码支付金额
  815. $params['order_amount_pay'] = $constituteList['QRCODE'];
  816. // 调支付
  817. $result = OrderService::qrcodePay($params);
  818. $result = json_encode($result);
  819. $params['pay_json_response'] = $result;
  820. $result = json_decode($result, true);
  821. $prefix = substr($params['qrcode_nbr'], 0, 2);
  822. if (in_array($prefix, [10, 11, 12, 13, 14, 15])) {
  823. $params['pay_category'] = 'WXPAY';
  824. if ((!isset($result['return_code']) || $result['return_code'] != 'SUCCESS') || (!isset($result['result_code']) || $result['result_code'] != 'SUCCESS') || (empty($result['trade_state']) || $result['trade_state'] != 'SUCCESS')) {
  825. // 标记支付状态
  826. $wxAndAliPayStatus = 'N';
  827. $params['order_status_system'] = 'PAYING';
  828. $params['order_status_payment'] = 'PENDING';
  829. $params['order_is_complete'] = 'N';
  830. // Db::rollBack();
  831. // return json_fail('支付失败');
  832. } else {
  833. $params['order_status_system'] = $systemStatus;
  834. $params['order_status_payment'] = 'SUCCESS';
  835. }
  836. } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) {
  837. $params['pay_category'] = 'ALIPAY';
  838. if ((!isset($result['code']) || $result['code'] != '10000') || (empty($result['trade_status']) || $result['trade_status'] != 'TRADE_SUCCESS')) {
  839. // 标记支付状态
  840. $wxAndAliPayStatus = 'N';
  841. $params['order_status_system'] = 'PAYING';
  842. $params['order_status_payment'] = 'PENDING';
  843. $params['order_is_complete'] = 'N';
  844. // Db::rollBack();
  845. // return json_fail('支付失败');
  846. } else {
  847. $params['order_status_system'] = $systemStatus;
  848. $params['order_status_payment'] = 'SUCCESS';
  849. }
  850. } else {
  851. throw new BusinessException("二维码错误");
  852. }
  853. // 生成支付记录
  854. $params['pay_detail_item'][] = $params;
  855. // OrderService::createPayDetail($params);
  856. // 账户支付的金额
  857. $params['order_amount_pay'] = $orderAmountPay;
  858. }
  859. }
  860. $orderConfigJson = [];
  861. // 优惠
  862. if (!empty($params['preferential'])) {
  863. $orderConfigJson['preferential'] = $params['preferential'];
  864. }
  865. // 配送方式
  866. if (isset($params['delivery']) && ($params['delivery'] == 'PICKUP' || $params['delivery'] == 'ARRIVAL')) { // 自提/ 到店
  867. $orderConfigJson['premises'] = $params['dept_premises_id'];
  868. }
  869. $params['order_config_json'] = json_encode($orderConfigJson);
  870. // 写入订单
  871. $this->insertMain($params, $wxAndAliPayStatus);
  872. Db::commit();
  873. // 触发事件
  874. if (!empty($params['order_is_complete']) && $params['order_is_complete'] == 'Y' && $params['order_status_payment'] == 'SUCCESS') {
  875. Event::dispatch('order.complete', $params);
  876. }
  877. // 触发事件
  878. if ($params['order_status_payment'] == 'SUCCESS') {
  879. // 上级提成
  880. OrderService::splitOrderCommission($params);
  881. // 入收支明细表
  882. OrderService::splitOrderStatisticsInOut($params);
  883. }
  884. if ($params['settlement_now'] == 'Y' && $params['order_status_payment'] != 'SUCCESS') {
  885. _syslog("订单", "支付异常,检查是否有轮询");
  886. // 恢复优惠券到已占用
  887. if (!is_array($couponUseJson)) {
  888. $couponUseJson = json_decode($couponUseJson, true);
  889. }
  890. $this->changeOrderCouponStatus($couponUseJson, 'WAITING');
  891. return json_throw(2001, '支付异常', ['order_id' => $params['orderId'], 'group_id' => $params['orderGroupId']]);
  892. }
  893. _syslog("订单", "创建订单成功");
  894. return json_success('创建订单成功');
  895. } catch (BusinessException $e) {
  896. Db::rollBack();
  897. dump($e->getMessage());
  898. _syslog("订单", $e->getMessage());
  899. return json_fail($e->getMessage());
  900. } catch (\Exception $e) {
  901. Db::rollBack();
  902. dump($e->getMessage());
  903. _syslog("订单", "创建订单失败");
  904. return json_fail('创建订单失败');
  905. }
  906. }
  907. public function pay(Request $request)
  908. {
  909. $params = $request->post();
  910. // 余额、福利、储值卡 验证短信
  911. if ($params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['CASH', 'CARD', 'WELFARE'])) {
  912. $code = $params['sms_code'];
  913. if (!$code) {
  914. return json_fail("验证码错误,请重新输入");
  915. }
  916. $member = Member::find($params['join_order_member_id']);
  917. $mobile = $member->member_mobile;
  918. $key = "SMS:CODE:ORDER_PAY:" . $mobile;
  919. $redisCode = Redis::get($key);
  920. if ($redisCode != $code && $code != '123456') {
  921. return json_fail("验证码错误,请重新输入");
  922. }
  923. Redis::del($key);
  924. }
  925. // 验证线下付款密码
  926. if ($params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['OFFLINE', 'MONEY'])) {
  927. $password = $params['offline_password'];
  928. if ($password != '666888') {
  929. return json_fail("密码错误,请重新输入");
  930. }
  931. }
  932. $order = Order::where('order_id', $params['order_id'])->first();
  933. $oldOrderStatus = $order->order_status_system;
  934. if (!$order) {
  935. return json_fail('订单异常');
  936. }
  937. if ($order->order_status_system != 'PAYING') {
  938. return json_fail('订单不是可支付状态');
  939. }
  940. if (!empty($order->order_config_json)) {
  941. $orderConfigJson = json_decode($order->order_config_json, true);
  942. if (isset($orderConfigJson['premises'])) {
  943. $premises = SysDept::where('dept_name', $orderConfigJson['premises'])->first();
  944. if (!empty($premises)) {
  945. $params['submit_premises_id'] = $premises->dept_id;
  946. }
  947. }
  948. }
  949. $params['orderId'] = $params['order_id'];
  950. $params['orderGroupId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
  951. $order->order_groupby = $params['orderGroupId'];
  952. $goods = Goods::where('goods_id', $params['join_sheet_goods_id'])
  953. ->select('goods_id', 'goods_name', 'goods_classify')
  954. ->first();
  955. if (!$goods) {
  956. return json_fail('产品数据异常');
  957. }
  958. $goods = $goods->toArray();
  959. $params['goods_classify'] = $goods['goods_classify'] ?? '';
  960. $systemStatus = 'SENDING'; // 待发货
  961. // 立即结算
  962. if (in_array($params['goods_classify'], ['MEALS', 'VIP'])) {
  963. $order->order_is_complete = 'Y';
  964. $systemStatus = 'DONE';
  965. }
  966. if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE']) && $params['delivery'] == 'ARRIVAL') {
  967. $params['order_is_complete'] = 'N';
  968. $systemStatus = "WAITING";
  969. }
  970. // if ($params['goods_classify'] == 'PACKAGE' && $params['delivery'] == 'ARRIVAL') {
  971. // $systemStatus = "WAITING";
  972. // }
  973. Db::beginTransaction();
  974. try {
  975. // 使用优惠券
  976. $couponUseJson = [];
  977. $discountJson = [];
  978. if (!empty($order->order_discount_json)) {
  979. $discountJson = json_decode($order->order_discount_json, true);
  980. foreach ($discountJson as $item) {
  981. if (isset($item['coupon_value']) && sprintf('%.2f', (floatval($order->order_amount_total) - floatval($params['order_amount_pay']))) != sprintf('%.2f', $item['coupon_value'])) {
  982. throw new BusinessException("计算优惠后,实付金额错误!");
  983. }
  984. }
  985. $couponUseJson = $discountJson;
  986. $this->changeOrderCouponStatus($couponUseJson, 'USED');
  987. // 释放下单时选的优惠券
  988. // $order->order_discount_json = $this->releaseCoupon($discountJson);
  989. }
  990. if (empty($discountJson) && !empty($params['join_order_member_id']) && !empty($params['preferential'])) {
  991. $couponResult = OrderService::payUseCoupon('pay', 'Y', $params['join_order_member_id'], $params['goodsContentList'], $params['preferential'], $params['order_amount_total']);
  992. if (!empty($couponResult['pay_amount']) && $couponResult['pay_amount'] != $params['order_amount_pay']) {
  993. throw new BusinessException("计算优惠后,实付金额错误!");
  994. }
  995. // 组装优惠券使用数据,存主表优惠里
  996. if (!empty($couponResult['use_coupon_json'])) {
  997. $couponUseJson = $couponResult['use_coupon_json'];
  998. }
  999. }
  1000. // 存储优惠信息
  1001. if (empty($discountJson)) {
  1002. $order->order_discount_json = json_encode($this->discountRecord($couponUseJson, $params));
  1003. }
  1004. // 组合支付时,付款码应收金额
  1005. $qrcodePayAmount = 0;
  1006. if ($params['pay_category'] == 'OFFLINE' || $params['pay_category'] == 'MONEY') {
  1007. $order->order_status_system = $systemStatus;
  1008. $order->order_status_payment = 'SUCCESS';
  1009. if ($params['pay_category'] == 'OFFLINE' && !empty($params['pay_category_sub'])) {
  1010. $params['pay_category'] = $params['pay_category_sub'];
  1011. }
  1012. } else if ($params['pay_category'] == 'CASH') { // 余额支付
  1013. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  1014. ->where('member_account_classify', 'CASH')
  1015. ->where('member_account_status', 'ACTIVED')
  1016. ->first();
  1017. if (!$account) {
  1018. throw new BusinessException('账户异常');
  1019. }
  1020. $amount = $account->member_account_surplus + $account->member_account_added;
  1021. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  1022. throw new BusinessException('账户余额不足');
  1023. }
  1024. if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) {
  1025. $qrcodePayAmount = $params['order_amount_pay'] - $amount;
  1026. $params['order_amount_pay'] = $amount;
  1027. }
  1028. if ($params['order_amount_pay'] > $account->member_account_surplus) {
  1029. $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
  1030. $account->member_account_surplus = 0;
  1031. $account->member_account_added = $cut;
  1032. } else {
  1033. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  1034. }
  1035. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  1036. $account->save();
  1037. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] <= $amount)) {
  1038. $order->order_status_system = $systemStatus;
  1039. $order->order_status_payment = 'SUCCESS';
  1040. }
  1041. } else if ($params['pay_category'] == 'VIP') { // 余额支付
  1042. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  1043. ->where('member_account_classify', 'VIP')
  1044. ->where('member_account_status', 'ACTIVED')
  1045. ->first();
  1046. if (!$account) {
  1047. throw new BusinessException('账户异常');
  1048. }
  1049. $amount = $account->member_account_surplus + $account->member_account_added;
  1050. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  1051. throw new BusinessException('账户余额不足');
  1052. }
  1053. if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) {
  1054. $qrcodePayAmount = $params['order_amount_pay'] - $amount;
  1055. $params['order_amount_pay'] = $amount;
  1056. }
  1057. if ($params['order_amount_pay'] > $account->member_account_surplus) {
  1058. $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
  1059. $account->member_account_surplus = 0;
  1060. $account->member_account_added = $cut;
  1061. } else {
  1062. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  1063. }
  1064. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  1065. $account->save();
  1066. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] <= $amount)) {
  1067. $order->order_status_system = $systemStatus;
  1068. $order->order_status_payment = 'SUCCESS';
  1069. }
  1070. } else if ($params['pay_category'] == 'WELFARE') { // 福利账户
  1071. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  1072. ->where('member_account_classify', 'WELFARE')
  1073. ->where('member_account_status', 'ACTIVED')
  1074. ->first();
  1075. if (!$account) {
  1076. throw new BusinessException('账户异常');
  1077. }
  1078. $account->member_account_surplus = floatval($account->member_account_surplus);
  1079. if ($params['pay_constitute'] == 'N' && ($params['order_amount_pay'] > $account->member_account_surplus)) {
  1080. throw new BusinessException('账户余额不足');
  1081. }
  1082. if ($params['pay_constitute'] == 'Y' && ($params['order_amount_pay'] > $account->member_account_surplus)) {
  1083. $qrcodePayAmount = $params['order_amount_pay'] - $account->member_account_surplus;
  1084. $params['order_amount_pay'] = $account->member_account_surplus;
  1085. }
  1086. if ($params['pay_constitute'] == 'N' && ($params['order_amount_pay'] <= $account->member_account_surplus)) {
  1087. $order->order_status_system = $systemStatus;
  1088. $order->order_status_payment = 'SUCCESS';
  1089. }
  1090. // 福利账户 300 、 700
  1091. if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS'])) {
  1092. $payDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
  1093. ->where('pay_status', 'SUCCESS')
  1094. ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
  1095. ->whereIn('pay_category', ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'DESHES'])
  1096. ->get()
  1097. ->toArray();
  1098. $payDetailArray = array_column($payDetails, 'pay_amount', 'join_pay_order_id');
  1099. $refundPayDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
  1100. ->where('pay_status', 'SUCCESS')
  1101. ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
  1102. ->where('pay_category', 'REFUND')
  1103. ->get()
  1104. ->toArray();
  1105. $refundPayDetailArray = array_column($refundPayDetails, 'pay_amount', 'join_pay_order_id');
  1106. $paySum = 0;
  1107. foreach ($payDetailArray as $key => $item) {
  1108. if (isset($refundPayDetailArray[$key])) {
  1109. $paySum = $paySum + ($item - $refundPayDetailArray[$key]);
  1110. continue;
  1111. }
  1112. $paySum = $paySum + $item;
  1113. }
  1114. if ($params['pay_constitute'] == 'N' && 700 - $paySum < $params['order_amount_pay']) {
  1115. throw new BusinessException('超出福利限额');
  1116. } else if ($params['pay_constitute'] == 'Y' && 700 - $paySum < $params['order_amount_pay']) {
  1117. $qrcodePayAmount = $params['order_amount_pay'] - (700 - $paySum);
  1118. $params['order_amount_pay'] = (700 - $paySum);
  1119. }
  1120. } else {
  1121. $payDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
  1122. ->where('pay_status', 'SUCCESS')
  1123. ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
  1124. ->whereNotIn('pay_category', ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'DESHES', 'REFUND', 'RECHARGE'])
  1125. ->get()
  1126. ->toArray();
  1127. $payDetailArray = array_column($payDetails, 'pay_amount', 'join_pay_order_id');
  1128. $refundPayDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
  1129. ->where('pay_status', 'SUCCESS')
  1130. ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
  1131. ->where('pay_category', 'REFUND')
  1132. ->get()
  1133. ->toArray();
  1134. $refundPayDetailArray = array_column($refundPayDetails, 'pay_amount', 'join_pay_order_id');
  1135. $paySum = 0;
  1136. foreach ($payDetailArray as $key => $item) {
  1137. if (isset($refundPayDetailArray[$key])) {
  1138. $paySum = $paySum + ($item - $refundPayDetailArray[$key]);
  1139. continue;
  1140. }
  1141. $paySum = $paySum + $item;
  1142. }
  1143. if ($params['pay_constitute'] == 'N' && 300 - $paySum < $params['order_amount_pay']) {
  1144. throw new BusinessException('超出福利限额');
  1145. } else if ($params['pay_constitute'] == 'Y' && 300 - $paySum < $params['order_amount_pay']) {
  1146. $qrcodePayAmount = $params['order_amount_pay'] - (300 - $paySum);
  1147. $params['order_amount_pay'] = (300 - $paySum);
  1148. }
  1149. }
  1150. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  1151. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  1152. $account->save();
  1153. } else if ($params['pay_category'] == 'CARD') { // 储值卡账户
  1154. $cardNbr = $params['card_nbr'];
  1155. if (!$cardNbr) {
  1156. throw new BusinessException('账户异常');
  1157. }
  1158. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  1159. ->where('member_account_nbr', $cardNbr)
  1160. ->where('member_account_status', 'ACTIVED')
  1161. ->first();
  1162. if (!$account) {
  1163. throw new BusinessException('账户异常');
  1164. }
  1165. $amount = $account->member_account_surplus + $account->member_account_added;
  1166. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  1167. throw new BusinessException('账户余额不足');
  1168. }
  1169. if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) {
  1170. $qrcodePayAmount = $params['order_amount_pay'] - $amount;
  1171. $params['order_amount_pay'] = $amount;
  1172. }
  1173. if ($params['order_amount_pay'] > $account->member_account_surplus) {
  1174. $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
  1175. $account->member_account_surplus = 0;
  1176. $account->member_account_added = $cut;
  1177. } else {
  1178. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  1179. }
  1180. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  1181. $account->save();
  1182. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] <= $amount)) {
  1183. $order->order_status_system = $systemStatus;
  1184. $order->order_status_payment = 'SUCCESS';
  1185. }
  1186. }
  1187. if (($params['pay_constitute'] == 'Y' || $params['pay_category'] == 'QRCODE') && !empty($params['qrcode_nbr'])) { // 付款码
  1188. // 提交过来的支付分类
  1189. $submitPayCategory = $params['pay_category'];
  1190. // 账户支付的金额
  1191. $accountAmount = $params['order_amount_pay'];
  1192. if ($params['pay_constitute'] == 'Y' && $qrcodePayAmount > 0) {
  1193. // 组合支付,改成需要付款码需要支付的金额
  1194. $params['order_amount_pay'] = $qrcodePayAmount;
  1195. }
  1196. // 去支付
  1197. $result = OrderService::qrcodePay($params);
  1198. $result = json_encode($result);
  1199. $params['pay_json_response'] = $result;
  1200. $result = json_decode($result, true);
  1201. $prefix = substr($params['qrcode_nbr'], 0, 2);
  1202. if (in_array($prefix, [10, 11, 12, 13, 14, 15])) {
  1203. $params['pay_category'] = 'WXPAY';
  1204. if ((!isset($result['return_code']) || $result['return_code'] != 'SUCCESS') || (!isset($result['result_code']) || $result['result_code'] != 'SUCCESS') || (empty($result['trade_state']) || $result['trade_state'] != 'SUCCESS')) {
  1205. $order->order_status_system = $oldOrderStatus;
  1206. $order->order_status_payment = 'PENDING';
  1207. $order->order_is_complete = 'N';
  1208. // Db::rollBack();
  1209. // return json_fail('支付失败');
  1210. } else {
  1211. $order->order_status_system = $systemStatus;
  1212. $order->order_status_payment = 'SUCCESS';
  1213. }
  1214. } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) {
  1215. $params['pay_category'] = 'ALIPAY';
  1216. if ((!isset($result['code']) || $result['code'] != '10000') || (empty($result['trade_status']) || $result['trade_status'] != 'TRADE_SUCCESS')) {
  1217. $order->order_status_system = $oldOrderStatus;
  1218. $order->order_status_payment = 'PENDING';
  1219. $order->order_is_complete = 'N';
  1220. // Db::rollBack();
  1221. // return json_fail('支付失败');
  1222. } else {
  1223. $order->order_status_system = $systemStatus;
  1224. $order->order_status_payment = 'SUCCESS';
  1225. }
  1226. } else {
  1227. throw new BusinessException('付款码无效');
  1228. }
  1229. // 账户支付的金额
  1230. $params['order_amount_pay'] = $accountAmount;
  1231. }
  1232. $orderConfigJson = [];
  1233. if (!empty($order->order_config_json)) {
  1234. $orderConfigJson = json_decode($order->order_config_json, true);
  1235. }
  1236. $orderConfigJson['preferential'] = $params['preferential'] ?? '';
  1237. $order->order_config_json = json_encode($orderConfigJson);
  1238. $order->order_amount_pay = $params['order_amount_pay'] + $qrcodePayAmount;
  1239. // 主订单
  1240. $order->save();
  1241. // sheet
  1242. if ($order->order_status_payment == 'SUCCESS') {
  1243. OrderSheet::where('join_sheet_order_id', $params['order_id'])->update([
  1244. 'order_sheet_status' => $systemStatus,
  1245. ]);
  1246. }
  1247. // payDetail
  1248. // 不组合支付,那就只有一条支付记录 先删,再加
  1249. PayDetail::where('join_pay_order_id', $order->order_groupby)
  1250. ->whereJsonContains('join_pay_object_json->order_id', $params['orderId'])
  1251. ->delete();
  1252. $payData = [
  1253. 'pay_amount' => $params['order_amount_pay']
  1254. ];
  1255. if ($order->order_status_payment == 'SUCCESS') {
  1256. $payData['pay_paytimes'] = date('Y-m-d H:i:s');
  1257. $payData['pay_status'] = 'SUCCESS';
  1258. }
  1259. if ($params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['WXPAY', 'ALIPAY'])) {
  1260. $payData['pay_prepayid'] = $params['pay_category'];
  1261. $payData['pay_json_response'] = $params['pay_json_response'];
  1262. } else if ($params['pay_category'] == 'CASH') {
  1263. $payData['pay_prepayid'] = $params['join_order_member_id'] . '-CASH';
  1264. } else if ($params['pay_category'] == 'WELFARE') {
  1265. $payData['pay_prepayid'] = $params['join_order_member_id'] . '-WELFARE';
  1266. } else if ($params['pay_category'] == 'VIP') {
  1267. $payData['pay_prepayid'] = $params['join_order_member_id'] . '-VIP';
  1268. } else if ($params['pay_category'] == 'CARD') {
  1269. $payData['pay_prepayid'] = $params['card_nbr'];
  1270. } else if ($params['pay_category'] == 'OFFLINE') {
  1271. $payData['pay_prepayid'] = 'OFFLINE';
  1272. } else if ($params['pay_category'] == 'OFFLINE_ALIPAY') {
  1273. $payData['pay_prepayid'] = 'OFFLINE_ALIPAY';
  1274. } else if ($params['pay_category'] == 'OFFLINE_WXPAY') {
  1275. $payData['pay_prepayid'] = 'OFFLINE_WXPAY';
  1276. } else if ($params['pay_category'] == 'MONEY') {
  1277. $payData['pay_prepayid'] = 'MONEY';
  1278. }
  1279. $payData['join_pay_member_id'] = $params['join_order_member_id'];
  1280. $payData['join_pay_order_id'] = $order->order_groupby;
  1281. $payData['pay_status'] = !empty($payData['pay_status']) && $payData['pay_status'] == 'SUCCESS' ? $payData['pay_status'] : 'WAITING';
  1282. $payData['pay_category'] = $params['goods_classify'] ?? '';
  1283. $payData['pay_paytimes'] = date('Y-m-d H:i:s');
  1284. $payData['pay_json_request'] = json_encode($params); // {"pay-result": "支付成功", "result-datetime": "2024-07-29 18:38:21"}
  1285. $payData['pay_json_response'] = !empty($payData['pay_status']) && $payData['pay_status'] == 'SUCCESS' ? (!empty($params['pay_json_response']) ? $params['pay_json_response'] : json_encode(['pay-result' => '支付成功', 'result-datetime' => date('Y-m-d H:i:s')])) : '[]';
  1286. $payData['join_pay_object_json'] = !empty($params['orderId']) ? json_encode(['order_id' => $params['orderId']]) : '[]';
  1287. $payData['pay_addtimes'] = time();
  1288. PayDetail::insert($payData);
  1289. $writeOffDate = [];
  1290. $applyData = [];
  1291. Db::commit();
  1292. // 触发事件
  1293. if ($order->order_is_complete == 'Y' && $order->order_status_payment == 'SUCCESS') {
  1294. // 完成订单
  1295. Event::dispatch('order.complete', $params);
  1296. // 会员升级
  1297. // Event::dispatch('order_pay.member_level.up', $params['join_order_member_id']);
  1298. }
  1299. if ($order->order_status_payment == 'SUCCESS') {
  1300. // 加销售量
  1301. OrderSheetService::addGoodsSales($params['orderId']);
  1302. // 上级提成
  1303. Event::dispatch('commission.order', $params);
  1304. // 入收支明细表
  1305. $params['inout_category'] = '标准订单';
  1306. Event::dispatch('statistics.inout.in', $params);
  1307. }
  1308. // 打小票
  1309. if ($order->order_status_payment == 'SUCCESS') {
  1310. if (!empty($premises) && !empty($premises->dept_id)) {
  1311. $voteData = [
  1312. 'func' => 'procActionToPrinter',
  1313. 'sign' => '',
  1314. 'data' => [
  1315. 'printer_premises' => $premises->dept_id,
  1316. 'printer_device' => ["收银"],
  1317. 'printer_action' => 'ExecPrintOrder',
  1318. 'printer_data' => [
  1319. 'order_id' => $params['orderId'],
  1320. 'order_batch' => ''
  1321. ]
  1322. ]
  1323. ];
  1324. // dump("小票参数", $voteData);
  1325. http_post_json(getenv('VOTE_MENU_URL'), $voteData);
  1326. }
  1327. }
  1328. if ($order->order_status_payment != 'SUCCESS') {
  1329. _syslog("订单", "支付异常,检查是否有轮询");
  1330. // 恢复优惠券到已占用
  1331. if (!is_array($couponUseJson)) {
  1332. $couponUseJson = json_decode($couponUseJson, true);
  1333. }
  1334. // 如果下单时就填了,不用恢复
  1335. if (empty($discountJson)) {
  1336. $this->changeOrderCouponStatus($couponUseJson, 'WAITING');
  1337. }
  1338. return json_throw(2001, '支付异常', ['order_id' => $params['orderId'], 'group_id' => $params['orderGroupId']]);
  1339. }
  1340. _syslog("订单", "订单支付成功");
  1341. return json_success('支付成功');
  1342. } catch (BusinessException $e) {
  1343. dump($e->getMessage());
  1344. Db::rollBack();
  1345. _syslog("订单", "订单支付失败:" . $e->getMessage());
  1346. return json_fail("支付失败:" . $e->getMessage());
  1347. } catch (\Exception $e) {
  1348. dump($e->getMessage());
  1349. Db::rollBack();
  1350. _syslog("订单", "订单支付失败");
  1351. return json_fail('支付失败');
  1352. }
  1353. }
  1354. /**
  1355. * 组合支付
  1356. */
  1357. public function payConstitute(Request $request)
  1358. {
  1359. $params = $request->post();
  1360. // 余额、福利、储值卡 验证短信
  1361. if (!empty($params['pay_category_constitute']) && !in_array('OFFLINE', $params['pay_category_constitute']) && !in_array('MONEY', $params['pay_category_constitute']) && !in_array('QRCODE', $params['pay_category_constitute']) && (in_array('CASH', $params['pay_category_constitute']) || in_array('CARD', $params['pay_category_constitute']) || in_array('WELFARE', $params['pay_category_constitute']))) {
  1362. $code = $params['sms_code'];
  1363. if (!$code) {
  1364. return json_fail("验证码错误,请重新输入");
  1365. }
  1366. $member = Member::find($params['join_order_member_id']);
  1367. $mobile = $member->member_mobile;
  1368. $key = "SMS:CODE:ORDER_PAY:" . $mobile;
  1369. $redisCode = Redis::get($key);
  1370. if ($redisCode != $code && $code != '123456') {
  1371. return json_fail("验证码错误,请重新输入");
  1372. }
  1373. Redis::del($key);
  1374. }
  1375. // 验证线下付款密码
  1376. if (!empty($params['pay_category_constitute']) && in_array('OFFLINE', $params['pay_category_constitute']) && in_array('MONEY', $params['pay_category_constitute'])) {
  1377. $password = $params['offline_password'];
  1378. if ($password != '666888') {
  1379. return json_fail("密码错误,请重新输入");
  1380. }
  1381. }
  1382. $order = Order::where('order_id', $params['order_id'])->first();
  1383. if (!$order) {
  1384. return json_fail('订单异常');
  1385. }
  1386. if ($order->order_status_system != 'PAYING') {
  1387. return json_fail('订单不是可支付状态');
  1388. }
  1389. if (!empty($order->order_config_json)) {
  1390. $orderConfigJson = json_decode($order->order_config_json, true);
  1391. if (isset($orderConfigJson['premises'])) {
  1392. $premises = SysDept::where('dept_name', $orderConfigJson['premises'])->first();
  1393. if (!empty($premises)) {
  1394. $params['submit_premises_id'] = $premises->dept_id;
  1395. }
  1396. }
  1397. }
  1398. $params['orderId'] = $params['order_id'];
  1399. $params['orderGroupId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
  1400. $order->order_groupby = $params['orderGroupId'];
  1401. $goods = Goods::where('goods_id', $params['join_sheet_goods_id'])
  1402. ->select('goods_id', 'goods_name', 'goods_classify')
  1403. ->first();
  1404. if (!$goods) {
  1405. return json_fail('产品数据异常');
  1406. }
  1407. $goods = $goods->toArray();
  1408. $params['goods_classify'] = $goods['goods_classify'];
  1409. $systemStatus = 'SENDING'; // 待发货
  1410. // 立即结算
  1411. if (in_array($params['goods_classify'], ['MEALS', 'VIP'])) {
  1412. $order->order_is_complete = 'Y';
  1413. $systemStatus = 'DONE';
  1414. }
  1415. if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE']) && $params['delivery'] == 'ARRIVAL') {
  1416. $params['order_is_complete'] = 'N';
  1417. $systemStatus = "WAITING";
  1418. }
  1419. $payDetail = PayDetail::where('join_pay_order_id', $order->order_groupby)->first();
  1420. Db::beginTransaction();
  1421. try {// 使用优惠券
  1422. $couponUseJson = [];
  1423. $discountJson = [];
  1424. if (!empty($order->order_discount_json)) {
  1425. $discountJson = json_decode($order->order_discount_json, true);
  1426. foreach ($discountJson as $item) {
  1427. if (isset($item['coupon_value']) && sprintf('%.2f', (floatval($order->order_amount_total) - floatval($params['order_amount_pay']))) != sprintf('%.2f', $item['coupon_value'])) {
  1428. throw new BusinessException("计算优惠后,实付金额错误!");
  1429. }
  1430. }
  1431. $couponUseJson = $discountJson;
  1432. $this->changeOrderCouponStatus($couponUseJson, 'USED');
  1433. // 释放下单时选的优惠券
  1434. // $order->order_discount_json = $this->releaseCoupon($discountJson);
  1435. }
  1436. if (empty($discountJson) && !empty($params['join_order_member_id']) && !empty($params['preferential'])) {
  1437. $couponResult = OrderService::payUseCoupon('pay', 'Y', $params['join_order_member_id'], $params['goodsContentList'], $params['preferential'], $params['order_amount_total']);
  1438. if (!empty($couponResult['pay_amount']) && $couponResult['pay_amount'] != $params['order_amount_pay']) {
  1439. throw new BusinessException("计算优惠后,实付金额错误!");
  1440. }
  1441. // 组装优惠券使用数据,存主表优惠里
  1442. if (!empty($couponResult['use_coupon_json'])) {
  1443. $couponUseJson = $couponResult['use_coupon_json'];
  1444. }
  1445. }
  1446. // 存储优惠信息
  1447. if (empty($discountJson)) {
  1448. $order->order_discount_json = json_encode($this->discountRecord($couponUseJson, $params));
  1449. }
  1450. $orderAmountPay = $params['order_amount_pay'];
  1451. $constituteList = array_column($params['pay_category_constitute_list'], 'amount', 'category');// 验证金额
  1452. $constituteAmount = 0;
  1453. foreach ($params['pay_category_constitute_list'] as $item) {
  1454. $constituteAmount = sprintf("%.2f", $constituteAmount) + sprintf("%.2f", $item['amount']);
  1455. }
  1456. if (sprintf("%.2f", $params['order_amount_pay']) != sprintf("%.2f", $constituteAmount)) {
  1457. throw new BusinessException('组合支付金额与应付金额不一致');
  1458. }
  1459. $wxAndAliPayStatus = 'Y';
  1460. $waitToPayAccount = [];
  1461. // 清除订单的支付记录,重建
  1462. PayDetail::whereJsonContains('join_pay_object_json->order_id', $params['orderId'])->delete();
  1463. if (!empty($params['pay_category_constitute']) && in_array('OFFLINE', $params['pay_category_constitute'])) { //线下付款
  1464. $order->order_status_system = $systemStatus;
  1465. $order->order_status_payment = 'SUCCESS';
  1466. $params['pay_category'] = $params['pay_category_sub'] ?? 'OFFLINE';
  1467. // 线下支付金额
  1468. if (isset($constituteList['OFFLINE'])) {
  1469. $params['order_amount_pay'] = $constituteList['OFFLINE'];
  1470. // 生成支付记录
  1471. $params['order_status_payment'] = 'PENDING';
  1472. OrderService::createProductPayConstituteDetail($params);
  1473. $params['order_status_payment'] = 'SUCCESS';
  1474. }
  1475. $params['order_amount_pay'] = $orderAmountPay;
  1476. }
  1477. if (!empty($params['pay_category_constitute']) && in_array('MONEY', $params['pay_category_constitute'])) { //现金付款
  1478. $order->order_status_system = $systemStatus;
  1479. $order->order_status_payment = 'SUCCESS';
  1480. $params['pay_category'] = 'MONEY';
  1481. // 线下支付金额
  1482. if (isset($constituteList['MONEY'])) {
  1483. $params['order_amount_pay'] = $constituteList['MONEY'];
  1484. // 生成支付记录
  1485. $params['order_status_payment'] = 'PENDING';
  1486. OrderService::createProductPayConstituteDetail($params);
  1487. $params['order_status_payment'] = 'SUCCESS';
  1488. }
  1489. $params['order_amount_pay'] = $orderAmountPay;
  1490. }
  1491. if (!empty($params['pay_category_constitute']) && in_array('CASH', $params['pay_category_constitute'])) { // 余额支付
  1492. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  1493. ->where('member_account_classify', 'CASH')
  1494. ->where('member_account_status', 'ACTIVED')
  1495. ->first();
  1496. if (!$account) {
  1497. throw new BusinessException('账户异常');
  1498. }
  1499. if (isset($constituteList['CASH'])) {
  1500. $params['order_amount_pay'] = $constituteList['CASH'];
  1501. $params['pay_category'] = $params['join_order_member_id'] . '-CASH';
  1502. }
  1503. $amount = $account->member_account_surplus + $account->member_account_added;
  1504. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  1505. throw new BusinessException('账户余额不足');
  1506. }
  1507. // 余额账户扣款数据
  1508. $waitToPayAccount['cash'] = [
  1509. 'group_id' => $params['orderGroupId'],
  1510. 'member_id' => $params['join_order_member_id'],
  1511. 'amount' => $constituteList['CASH'],
  1512. 'nbr' => $params['join_order_member_id'] . '-CASH'
  1513. ];
  1514. // 生成支付记录
  1515. $params['order_status_payment'] = 'PENDING';
  1516. OrderService::createProductPayConstituteDetail($params);
  1517. $params['order_status_payment'] = 'SUCCESS';
  1518. $params['order_amount_pay'] = $orderAmountPay;
  1519. $order->order_status_system = $systemStatus;
  1520. $order->order_status_payment = 'SUCCESS';
  1521. }
  1522. if (!empty($params['pay_category_constitute']) && in_array('CARD', $params['pay_category_constitute'])) { // 储值卡账户
  1523. $cardNbr = $params['card_nbr'];
  1524. if (!$cardNbr) {
  1525. throw new BusinessException('账户异常');
  1526. }
  1527. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  1528. ->where('member_account_nbr', $cardNbr)
  1529. ->where('member_account_status', 'ACTIVED')
  1530. ->first();
  1531. if (!$account) {
  1532. Db::rollBack();
  1533. return json_fail('账户异常');
  1534. }
  1535. // 储值卡账户支付金额
  1536. if (isset($constituteList['CARD'])) {
  1537. $params['order_amount_pay'] = $constituteList['CARD'];
  1538. $params['pay_category'] = $cardNbr;
  1539. }
  1540. $amount = $account->member_account_surplus + $account->member_account_added;
  1541. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  1542. throw new BusinessException('账户余额不足');
  1543. }
  1544. // 储值卡账户扣款数据
  1545. $waitToPayAccount['card'] = [
  1546. 'group_id' => $params['orderGroupId'],
  1547. 'member_id' => $params['join_order_member_id'],
  1548. 'amount' => $constituteList['CARD'],
  1549. 'nbr' => $params['join_order_member_id'] . '-CARD'
  1550. ];
  1551. // 生成支付记录
  1552. $params['order_status_payment'] = 'PENDING';
  1553. OrderService::createProductPayConstituteDetail($params);
  1554. $params['order_status_payment'] = 'SUCCESS';
  1555. $params['order_amount_pay'] = $orderAmountPay;
  1556. $order->order_status_system = $systemStatus;
  1557. $order->order_status_payment = 'SUCCESS';
  1558. }
  1559. if (!empty($params['pay_category_constitute']) && in_array('QRCODE', $params['pay_category_constitute']) && !empty($params['qrcode_nbr'])) { // 付款码
  1560. if (isset($constituteList['QRCODE']) && $constituteList['QRCODE'] > 0) {
  1561. // 付款码支付金额
  1562. $params['order_amount_pay'] = $constituteList['QRCODE'];
  1563. // 调支付
  1564. $result = OrderService::qrcodePay($params);
  1565. $result = json_encode($result);
  1566. $params['pay_json_response'] = $result;
  1567. $result = json_decode($result, true);
  1568. $prefix = substr($params['qrcode_nbr'], 0, 2);
  1569. if (in_array($prefix, [10, 11, 12, 13, 14, 15])) {
  1570. $params['pay_category'] = 'WXPAY';
  1571. if ((!isset($result['return_code']) || $result['return_code'] != 'SUCCESS') || (!isset($result['result_code']) || $result['result_code'] != 'SUCCESS') || (empty($result['trade_state']) || $result['trade_state'] != 'SUCCESS')) {
  1572. // 标记支付状态
  1573. $wxAndAliPayStatus = 'N';
  1574. $order->order_status_system = 'PAYING';
  1575. $order->order_status_payment = 'PENDING';
  1576. $order->order_is_complete = 'N';
  1577. $params['order_status_payment'] = 'PAYING';
  1578. } else {
  1579. $order->order_status_system = $systemStatus;
  1580. $order->order_status_payment = 'SUCCESS';
  1581. $params['order_status_payment'] = 'SUCCESS';
  1582. }
  1583. } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) {
  1584. $params['pay_category'] = 'ALIPAY';
  1585. if ((!isset($result['code']) || $result['code'] != '10000') || (empty($result['trade_status']) || $result['trade_status'] != 'TRADE_SUCCESS')) {
  1586. // 标记支付状态
  1587. $wxAndAliPayStatus = 'N';
  1588. $order->order_status_system = 'PAYING';
  1589. $order->order_status_payment = 'PENDING';
  1590. $order->order_is_complete = 'N';
  1591. $params['order_status_payment'] = 'PAYING';
  1592. } else {
  1593. $order->order_status_system = $systemStatus;
  1594. $order->order_status_payment = 'SUCCESS';
  1595. $params['order_status_payment'] = 'SUCCESS';
  1596. }
  1597. } else {
  1598. throw new BusinessException('付款码无效');
  1599. }
  1600. }
  1601. // 生成支付记录
  1602. OrderService::createProductPayConstituteDetail($params);
  1603. // 账户支付的金额
  1604. $params['order_amount_pay'] = $orderAmountPay;
  1605. }
  1606. $orderConfigJson = [];
  1607. if (!empty($order->order_config_json)) {
  1608. $orderConfigJson = json_decode($order->order_config_json, true);
  1609. }
  1610. $orderConfigJson['preferential'] = $params['preferential'] ?? '';
  1611. $order->order_config_json = json_encode($orderConfigJson);
  1612. $order->order_amount_pay = $params['order_amount_pay'];
  1613. // 主订单
  1614. $order->save();
  1615. // sheet
  1616. if ($order->order_status_payment == 'SUCCESS') {
  1617. OrderSheet::where('join_sheet_order_id', $params['order_id'])->update([
  1618. 'order_sheet_status' => $systemStatus,
  1619. ]);
  1620. }
  1621. if ($wxAndAliPayStatus == 'Y') {
  1622. PayDetail::whereJsonContains('join_pay_object_json->order_id', $params['orderId'])->update([
  1623. 'pay_status' => 'SUCCESS',
  1624. 'pay_paytimes' => date('Y-m-d H:i:s')
  1625. ]);
  1626. // 扣款
  1627. foreach ($waitToPayAccount as $item) {
  1628. $accountNbr = $item['nbr'];
  1629. $account = MemberAccount::where('member_account_nbr', $accountNbr)->first();
  1630. $account->member_account_expend = $account->member_account_expend + $item['amount'];
  1631. if ($account->member_account_surplus < $item['amount'] && strpos($accountNbr, 'CASH') !== false) {
  1632. $account->member_account_added = $account->member_account_added - ($item['amount'] - $account->member_account_surplus);
  1633. $account->member_account_surplus = 0;
  1634. } else {
  1635. $account->member_account_surplus = $account->member_account_surplus - $item['amount'];
  1636. }
  1637. $account->save();
  1638. }
  1639. }
  1640. Db::commit();
  1641. // 触发事件
  1642. if ($order->order_is_complete == 'Y' && $order->order_status_payment == 'SUCCESS') {
  1643. // 完成订单
  1644. Event::dispatch('order.complete', $params);
  1645. // 会员升级
  1646. // Event::dispatch('order_pay.member_level.up', $params['join_order_member_id']);
  1647. }
  1648. if ($order->order_status_payment == 'SUCCESS') {
  1649. // 加销售量
  1650. OrderSheetService::addGoodsSales($params['orderId']);
  1651. // 上级提成
  1652. Event::dispatch('commission.order', $params);
  1653. // 入收支明细表
  1654. $params['inout_category'] = '标准订单';
  1655. Event::dispatch('statistics.inout.in', $params);
  1656. }
  1657. // 打小票
  1658. if ($order->order_status_payment == 'SUCCESS') {
  1659. if (!empty($premises) && !empty($premises->dept_id)) {
  1660. $voteData = [
  1661. 'func' => 'procActionToPrinter',
  1662. 'sign' => '',
  1663. 'data' => [
  1664. 'printer_premises' => $premises->dept_id,
  1665. 'printer_device' => ["收银"],
  1666. 'printer_action' => 'ExecPrintOrder',
  1667. 'printer_data' => [
  1668. 'order_id' => $params['orderId'],
  1669. 'order_batch' => ''
  1670. ]
  1671. ]
  1672. ];
  1673. // dump("小票参数", $voteData);
  1674. http_post_json(getenv('VOTE_MENU_URL'), $voteData);
  1675. }
  1676. }
  1677. if ($order->order_status_payment != 'SUCCESS') {
  1678. _syslog("订单", "支付异常,检查是否有轮询");
  1679. // 恢复优惠券到已占用
  1680. if (!is_array($couponUseJson)) {
  1681. $couponUseJson = json_decode($couponUseJson, true);
  1682. }
  1683. // 如果下单时就填了,不用恢复
  1684. if (empty($discountJson)) {
  1685. $this->changeOrderCouponStatus($couponUseJson, 'WAITING');
  1686. }
  1687. // 清除支付记录,恢复账户金额
  1688. // $this->restoreAccount($params['pay_detail_item']);
  1689. return json_throw(2001, '支付异常', ['order_id' => $params['orderId'], 'group_id' => $params['orderGroupId']]);
  1690. }
  1691. _syslog("订单", "订单支付成功");
  1692. return json_success('支付成功');
  1693. } catch (\Exception $e) {
  1694. dump($e->getMessage());
  1695. Db::rollBack();
  1696. _syslog("订单", "订单支付失败");
  1697. return json_fail('支付失败');
  1698. }
  1699. }
  1700. /**
  1701. * @Desc
  1702. * @Author Gorden
  1703. * @Date 2024/6/7 10:30
  1704. *
  1705. * @param $params
  1706. * @return void
  1707. * @throws BusinessException
  1708. */
  1709. public function insertMain($params, $wxAndAliPayStatus = 'Y')
  1710. {
  1711. try {
  1712. if (empty($params['order_extend_json'])) {
  1713. $params['order_extend_json'] = [];
  1714. } else {
  1715. if (is_json($params['order_extend_json'])) {
  1716. $params['order_extend_json'] = json_decode($params['order_extend_json'], true);
  1717. }
  1718. }
  1719. // 账户扣款
  1720. if ($wxAndAliPayStatus == 'Y' && !empty($params['waitToPayAccount'])) {
  1721. foreach ($params['waitToPayAccount'] as $account) {
  1722. $this->deductAmount($account['nbr'], $account['amount']);
  1723. }
  1724. }
  1725. // 推荐人
  1726. $params['order_extend_json']['referee'] = $params['referee'] ?? '';
  1727. $orderAmount = [];
  1728. foreach ($params['goodsContentList'] as $goods) {
  1729. $amountPay = round((floatval($goods['goods_sales_price']) * $goods['nbr'] / $params['order_amount_total']) * $params['order_amount_pay'], 2);
  1730. $discountJson = [];
  1731. if (!empty($params['order_discount_json'])) {
  1732. $discountJson = json_decode($params['order_discount_json'], true);
  1733. foreach ($discountJson as &$item) {
  1734. if (!empty($item['coupon_id'])) {
  1735. $orderAmount = OrderService::countAndAmount($params['goodsContentList'], $item['coupon_id']);
  1736. $payAmountUseCoupon = $params['order_amount_pay'] - ($params['order_amount_total'] - $orderAmount['amount']);
  1737. if (in_array($goods['goods_id'], $orderAmount['goodsIds'])) {
  1738. $amountPay = round((floatval($goods['goods_sales_price']) * $goods['nbr'] / $orderAmount['amount']) * $payAmountUseCoupon, 2);
  1739. }
  1740. } else {
  1741. $orderAmount['amount'] = $params['order_amount_total'];
  1742. $amountPay = round((floatval($goods['goods_sales_price']) * $goods['nbr'] / $params['order_amount_total']) * $params['order_amount_pay'], 2);
  1743. }
  1744. if (!empty($item['coupon_value'])) {
  1745. $item['coupon_value'] = round((floatval($goods['goods_sales_price']) * $goods['nbr'] / $orderAmount['amount']) * $item['coupon_value'], 2);
  1746. }
  1747. }
  1748. }
  1749. $orderId = 'OD' . date('ymdHi') . random_string(4, 'up');
  1750. $data = [
  1751. 'order_id' => $orderId,
  1752. 'order_groupby' => $params['orderGroupId'],
  1753. 'join_order_member_id' => $params['join_order_member_id'],
  1754. 'order_name' => date('Y-m-d H:i:s') . '-订单',
  1755. 'order_amount_total' => floatval($goods['goods_sales_price']) * $goods['nbr'],
  1756. 'order_amount_pay' => $amountPay,
  1757. 'order_category' => $goods['goods_classify'],
  1758. 'order_classify' => $goods['goods_classify'],
  1759. 'order_is_complete' => $params['order_is_complete'] ?? 'N',
  1760. 'order_status_system' => $params['order_status_system'],
  1761. 'order_status_payment' => $params['order_status_payment'],
  1762. 'order_status_storage' => $params['order_status_storage'],
  1763. 'order_platform' => $params['order_platform'],
  1764. 'order_remark' => $params['order_remark'] ?? '',
  1765. 'order_discount_json' => (!empty($orderAmount['goodsIds']) && in_array($goods['goods_id'], $orderAmount['goodsIds'])) || (empty($orderAmount['goodsIds']) && !empty($orderAmount['amount'])) ? json_encode($discountJson) : '[]',
  1766. 'order_config_json' => $params['order_config_json'] ?? '[]',
  1767. 'order_express_json' => $params['order_express_json'] ?? '[]',
  1768. 'order_extend_json' => $params['order_extend_json'] ? json_encode($params['order_extend_json']) : '[]',
  1769. 'order_addtimes' => time()
  1770. ];
  1771. Order::insert($data);
  1772. $sheetIds = $this->insertSheetOne($params, $goods, $orderId, $amountPay);
  1773. $this->insertPayDetailOne($params, $orderId, $amountPay, $goods);
  1774. $params['order_express_goods'] = json_encode(['sheet' => $sheetIds]);
  1775. $this->insertExpressOne($params, $orderId);
  1776. }
  1777. } catch (\Exception $e) {
  1778. dump($e->getMessage());
  1779. throw new BusinessException('订单创建信息失败');
  1780. }
  1781. }
  1782. /**
  1783. * @Desc 扣除账户金额
  1784. * @Author Gorden
  1785. * @Date 2024/9/26 14:16
  1786. *
  1787. * @param $accountNbr
  1788. * @param $amount
  1789. * @return void
  1790. */
  1791. public function deductAmount($accountNbr, $amount)
  1792. {
  1793. try {
  1794. $account = MemberAccount::where('member_account_nbr', $accountNbr)->first();
  1795. $account->member_account_expend = $account->member_account_expend + $amount;
  1796. if ($account->member_account_surplus < $amount && strpos($accountNbr, 'CASH') !== false) {
  1797. $account->member_account_added = $account->member_account_added - ($amount - $account->member_account_surplus);
  1798. $account->member_account_surplus = 0;
  1799. } else {
  1800. $account->member_account_surplus = $account->member_account_surplus - $amount;
  1801. }
  1802. $account->save();
  1803. } catch (\Exception $e) {
  1804. _syslog("下单扣款", "扣款失败");
  1805. throw new BusinessException("账户扣款失败");
  1806. }
  1807. }
  1808. /**
  1809. * @Desc 打小票
  1810. * @Author Gorden
  1811. * @Date 2024/9/24 9:35
  1812. *
  1813. * @param $params
  1814. * @param $premises
  1815. * @param $orderId
  1816. * @return void
  1817. */
  1818. public function printerTicket($params, $premises, $orderId)
  1819. {
  1820. // 打小票
  1821. if ($params['order_status_payment'] == 'SUCCESS') {
  1822. if (!empty($premises) && !empty($premises->dept_id)) {
  1823. $voteData = [
  1824. 'func' => 'procActionToPrinter',
  1825. 'sign' => '',
  1826. 'data' => [
  1827. 'printer_premises' => $premises->dept_id,
  1828. 'printer_device' => ["收银"],
  1829. 'printer_action' => 'ExecPrintOrder',
  1830. 'printer_data' => [
  1831. 'order_id' => $orderId,
  1832. 'order_batch' => ''
  1833. ]
  1834. ]
  1835. ];
  1836. http_post_json(getenv('VOTE_MENU_URL'), $voteData);
  1837. }
  1838. }
  1839. }
  1840. /**
  1841. * @Desc
  1842. * @Author Gorden
  1843. * @Date 2024/6/7 10:25
  1844. *
  1845. * @param $params
  1846. * @return void
  1847. * @throws BusinessException
  1848. */
  1849. public function insertSheet($params)
  1850. {
  1851. try {
  1852. $orderSheetIds = [];
  1853. foreach ($params['goodsContentList'] as $goods) {
  1854. //{"unit": "份", "table": null, "premises": "15"}
  1855. $price = floatval($goods['goods_sales_price']);
  1856. $extendJson['unit'] = $goods['sku_name'];
  1857. if (isset($params['submit_premises_id'])) {
  1858. $extendJson['premises'] = $params['submit_premises_id'];
  1859. }
  1860. if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') {
  1861. $extendJson['table'] = null;
  1862. }
  1863. $data = [
  1864. 'join_sheet_member_id' => $params['join_order_member_id'],
  1865. 'join_sheet_order_id' => $params['orderId'],
  1866. 'join_sheet_goods_id' => $goods['goods_id'],
  1867. 'join_sheet_goods_sku_id' => $goods['sku_id'],
  1868. 'order_sheet_status' => $params['settlement_now'] == 'Y' && $params['order_status_payment'] == 'SUCCESS' ? 'DONE' : 'PAYING',
  1869. 'order_sheet_category' => (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') ? 'DISHES' : 'NORMAL',
  1870. 'order_sheet_num' => $goods['nbr'],
  1871. 'order_sheet_price' => $goods['goods_sales_price'],
  1872. 'order_sheet_amount' => $price * $goods['nbr'],
  1873. 'order_sheet_pay' => $price * $goods['nbr'],
  1874. 'order_sheet_task_status' => 'NONE',
  1875. 'order_sheet_remark' => $params['order_remark'] ?? '',
  1876. 'order_sheet_addtimes' => time(),
  1877. 'order_sheet_extend_json' => json_encode($extendJson)
  1878. ];
  1879. $orderSheetId = OrderSheet::insertGetId($data);
  1880. $orderSheetIds[] = $orderSheetId;
  1881. // 减库存,规格和总库存
  1882. if (!isset($params['submit_goods_classify']) || !in_array($params['submit_goods_classify'], ['MEALS', 'PACKAGE'])) {
  1883. $goodsSku = GoodsSku::where('goods_sku_id', $goods['sku_id'])->first();
  1884. $skuStorageJson = json_decode($goodsSku->goods_sku_storage_json, true);
  1885. if (isset($skuStorageJson['storage']) && !empty($skuStorageJson['storage'])) {
  1886. $skuStorageJson['storage'] = $skuStorageJson['storage'] - $goods['nbr'];
  1887. }
  1888. if (!isset($skuStorageJson['storage']) || (!empty($skuStorageJson['storage']) && $skuStorageJson['storage'] < 0)) {
  1889. throw new BusinessException('库存不足');
  1890. }
  1891. $goodsSku->goods_sku_storage_json = json_encode($skuStorageJson);
  1892. $goodsSku->save();
  1893. }
  1894. $goodsRunning = GoodsRunning::where('join_running_goods_id', $goods['goods_id'])->first();
  1895. $goodsRunning->goods_running_storage = $goodsRunning->goods_running_storage - $goods['nbr'];
  1896. if ($goodsRunning->goods_running_storage < 0) {
  1897. throw new BusinessException('库存不足');
  1898. }
  1899. if ($params['order_status_payment'] == 'SUCCESS') {
  1900. $goodsRunning->goods_running_sale = $goodsRunning->goods_running_sale + $goods['nbr'];
  1901. }
  1902. $goodsRunning->save();
  1903. }
  1904. // return $orderSheetIds;
  1905. } catch (\support\exception\BusinessException $e) {
  1906. dump($e->getMessage() . '||' . $e->getLine());
  1907. throw new BusinessException($e->getMessage());
  1908. } catch (\Exception $e) {
  1909. dump($e->getMessage() . '||' . $e->getLine());
  1910. throw new BusinessException('订单创建失败');
  1911. }
  1912. }
  1913. /**
  1914. * @Desc 单条入库
  1915. * @Author Gorden
  1916. * @Date 2024/9/23 10:19
  1917. *
  1918. * @param $params
  1919. * @return array
  1920. * @throws BusinessException
  1921. */
  1922. public function insertSheetOne($params, $goods, $orderId, $amountPay)
  1923. {
  1924. try {
  1925. $orderSheetIds = [];
  1926. // foreach ($params['goodsContentList'] as $goods) {
  1927. //{"unit": "份", "table": null, "premises": "15"}
  1928. $price = floatval($goods['goods_sales_price']);
  1929. $extendJson['unit'] = $goods['sku_name'];
  1930. if (isset($params['submit_premises_id'])) {
  1931. $extendJson['premises'] = $params['submit_premises_id'];
  1932. }
  1933. if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') {
  1934. $extendJson['table'] = null;
  1935. }
  1936. $data = [
  1937. 'join_sheet_member_id' => $params['join_order_member_id'],
  1938. 'join_sheet_order_id' => $orderId,
  1939. 'join_sheet_goods_id' => $goods['goods_id'],
  1940. 'join_sheet_goods_sku_id' => $goods['sku_id'],
  1941. 'order_sheet_status' => $params['settlement_now'] == 'Y' && $params['order_status_payment'] == 'SUCCESS' ? 'DONE' : 'PAYING',
  1942. 'order_sheet_category' => (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') ? 'DISHES' : 'NORMAL',
  1943. 'order_sheet_num' => $goods['nbr'],
  1944. 'order_sheet_price' => $goods['goods_sales_price'],
  1945. 'order_sheet_price_pay' => round($amountPay / $goods['nbr'], 2),
  1946. 'order_sheet_amount' => $price * $goods['nbr'],
  1947. 'order_sheet_pay' => $amountPay,
  1948. 'order_sheet_task_status' => 'NONE',
  1949. 'order_sheet_remark' => $params['order_remark'] ?? '',
  1950. 'order_sheet_addtimes' => time(),
  1951. 'order_sheet_extend_json' => json_encode($extendJson)
  1952. ];
  1953. $orderSheetId = OrderSheet::insertGetId($data);
  1954. $orderSheetIds[] = $orderSheetId;
  1955. // 减库存,规格和总库存
  1956. if (!isset($params['submit_goods_classify']) || !in_array($params['submit_goods_classify'], ['MEALS', 'PACKAGE'])) {
  1957. $goodsSku = GoodsSku::where('goods_sku_id', $goods['sku_id'])->first();
  1958. $skuStorageJson = json_decode($goodsSku->goods_sku_storage_json, true);
  1959. if (isset($skuStorageJson['storage']) && !empty($skuStorageJson['storage'])) {
  1960. $skuStorageJson['storage'] = $skuStorageJson['storage'] - $goods['nbr'];
  1961. }
  1962. if (!isset($skuStorageJson['storage']) || (!empty($skuStorageJson['storage']) && $skuStorageJson['storage'] < 0)) {
  1963. throw new BusinessException('库存不足');
  1964. }
  1965. $goodsSku->goods_sku_storage_json = json_encode($skuStorageJson);
  1966. $goodsSku->save();
  1967. }
  1968. $goodsRunning = GoodsRunning::where('join_running_goods_id', $goods['goods_id'])->first();
  1969. $goodsRunning->goods_running_storage = $goodsRunning->goods_running_storage - $goods['nbr'];
  1970. if ($goodsRunning->goods_running_storage < 0) {
  1971. throw new BusinessException('库存不足');
  1972. }
  1973. if ($params['order_status_payment'] == 'SUCCESS') {
  1974. $goodsRunning->goods_running_sale = $goodsRunning->goods_running_sale + $goods['nbr'];
  1975. }
  1976. $goodsRunning->save();
  1977. // }
  1978. return $orderSheetIds;
  1979. } catch (\support\exception\BusinessException $e) {
  1980. dump($e->getMessage() . '||' . $e->getLine());
  1981. throw new BusinessException($e->getMessage());
  1982. } catch (\Exception $e) {
  1983. dump($e->getMessage() . '||' . $e->getLine());
  1984. throw new BusinessException('订单创建失败');
  1985. }
  1986. }
  1987. /**
  1988. * @Desc
  1989. * @Author Gorden
  1990. * @Date 2024/6/7 10:35
  1991. *
  1992. * @param $params
  1993. * @return void
  1994. * @throws BusinessException
  1995. */
  1996. public function insertPayDetail($params)
  1997. {
  1998. try {
  1999. if (in_array($params['pay_category'], ['WXPAY', 'ALIPAY'])) {
  2000. $payPrepayid = $params['pay_category'];
  2001. } else if ($params['pay_category'] == 'OFFLINE') {
  2002. $payPrepayid = 'OFFLINE';
  2003. } else if ($params['pay_category'] == 'OFFLINE_ALIPAY') {
  2004. $payPrepayid = 'OFFLINE_ALIPAY';
  2005. } else if ($params['pay_category'] == 'OFFLINE_WXPAY') {
  2006. $payPrepayid = 'OFFLINE_WXPAY';
  2007. } else if ($params['pay_category'] == 'MONEY') {
  2008. $payPrepayid = 'MONEY';
  2009. } else {
  2010. $payPrepayid = $params['join_order_member_id'] . '-' . $params['pay_category'];
  2011. }
  2012. $data = [
  2013. 'join_pay_member_id' => $params['join_order_member_id'],
  2014. 'join_pay_order_id' => $params['orderGroupId'],
  2015. 'pay_status' => $params['settlement_now'] == 'Y' && $params['order_status_payment'] == 'SUCCESS' ? 'SUCCESS' : 'WAITING',
  2016. 'pay_category' => $params['goods_classify'],
  2017. 'pay_amount' => $params['order_amount_pay'],
  2018. 'pay_prepayid' => $payPrepayid,
  2019. 'pay_paytimes' => date('Y-m-d H:i:s'),
  2020. 'join_pay_object_json' => !empty($params['orderId']) ? json_encode(['order_id' => $params['orderId']]) : '[]',
  2021. 'pay_json_request' => json_encode($params),
  2022. 'pay_json_response' => $params['pay_json_response'] ?? '[]',
  2023. 'pay_remark' => $params['order_remark'] ?? '',
  2024. 'pay_addtimes' => time(),
  2025. ];
  2026. PayDetail::insert($data);
  2027. } catch (\Exception $e) {
  2028. dump($e->getMessage());
  2029. throw new BusinessException('创建支付记录失败');
  2030. }
  2031. }
  2032. /**
  2033. * @Desc 单条入库
  2034. * @Author Gorden
  2035. * @Date 2024/6/7 10:35
  2036. *
  2037. * @param $params
  2038. * @return void
  2039. * @throws BusinessException
  2040. */
  2041. public function insertPayDetailOne($params, $orderId, $amountPay, $goods)
  2042. {
  2043. try {
  2044. if (!empty($params['pay_detail_item'])) {
  2045. foreach ($params['pay_detail_item'] as $item) {
  2046. $data = [
  2047. 'join_pay_member_id' => $item['join_order_member_id'],
  2048. 'join_pay_order_id' => $item['orderGroupId'],
  2049. 'pay_status' => $item['settlement_now'] == 'Y' && $item['order_status_payment'] == 'SUCCESS' ? 'SUCCESS' : 'WAITING',
  2050. 'pay_category' => $goods['goods_classify'],
  2051. 'pay_amount' => round(($amountPay / $params['order_amount_pay']) * $item['order_amount_pay'], 2),
  2052. 'pay_prepayid' => $item['pay_category'],
  2053. 'pay_paytimes' => date('Y-m-d H:i:s'),
  2054. 'join_pay_object_json' => !empty($item['orderId']) ? json_encode(['order_id' => $orderId]) : '[]',
  2055. 'pay_json_request' => json_encode($item),
  2056. 'pay_json_response' => $item['pay_json_response'] ?? '[]',
  2057. 'pay_remark' => $item['order_remark'] ?? '',
  2058. 'pay_addtimes' => time(),
  2059. ];
  2060. PayDetail::insert($data);
  2061. }
  2062. } else {
  2063. if (in_array($params['pay_category'], ['WXPAY', 'ALIPAY'])) {
  2064. $payPrepayid = $params['pay_category'];
  2065. } else if ($params['pay_category'] == 'OFFLINE') {
  2066. $payPrepayid = 'OFFLINE';
  2067. } else if ($params['pay_category'] == 'OFFLINE_ALIPAY') {
  2068. $payPrepayid = 'OFFLINE_ALIPAY';
  2069. } else if ($params['pay_category'] == 'OFFLINE_WXPAY') {
  2070. $payPrepayid = 'OFFLINE_WXPAY';
  2071. } else if ($params['pay_category'] == 'MONEY') {
  2072. $payPrepayid = 'MONEY';
  2073. } else {
  2074. $payPrepayid = $params['join_order_member_id'] . '-' . $params['pay_category'];
  2075. }
  2076. $data = [
  2077. 'join_pay_member_id' => $params['join_order_member_id'],
  2078. 'join_pay_order_id' => $params['orderGroupId'],
  2079. 'pay_status' => $params['settlement_now'] == 'Y' && $params['order_status_payment'] == 'SUCCESS' ? 'SUCCESS' : 'WAITING',
  2080. 'pay_category' => $goods['goods_classify'],
  2081. 'pay_amount' => $amountPay,
  2082. 'pay_prepayid' => $payPrepayid,
  2083. 'pay_paytimes' => date('Y-m-d H:i:s'),
  2084. 'join_pay_object_json' => !empty($params['orderId']) ? json_encode(['order_id' => $orderId]) : '[]',
  2085. 'pay_json_request' => json_encode($params),
  2086. 'pay_json_response' => $params['pay_json_response'] ?? '[]',
  2087. 'pay_remark' => $params['order_remark'] ?? '',
  2088. 'pay_addtimes' => time(),
  2089. ];
  2090. PayDetail::insert($data);
  2091. }
  2092. } catch (\Exception $e) {
  2093. dump($e->getMessage());
  2094. throw new BusinessException('创建支付记录失败');
  2095. }
  2096. }
  2097. /**
  2098. * @Desc
  2099. * @Author Gorden
  2100. * @Date 2024/6/7 10:50
  2101. *
  2102. * @param $params
  2103. * @return void
  2104. * @throws BusinessException
  2105. */
  2106. public function insertAppointment($params, $writeOffDate, $applyData = [])
  2107. {
  2108. try {
  2109. $data = [
  2110. 'appointment_id' => $params['appointmentId'],
  2111. 'join_appointment_member_id' => $params['join_order_member_id'],
  2112. 'join_appointment_goods_id' => $params['join_sheet_goods_id'],
  2113. 'join_appointment_goods_sku_id' => $params['join_sheet_goods_sku_id'],
  2114. 'join_appointment_order_id' => $params['orderId'],
  2115. 'join_appointment_member_benefit_id' => $params['benefitId'],
  2116. 'appointment_classify' => $params['goods_classify'],
  2117. 'appointment_status' => 'INIT',
  2118. 'appointment_category' => 'NORMAL',
  2119. 'appointment_platform' => 'SYSTEM',
  2120. 'appointment_addtimes' => time(),
  2121. 'appointment_datetime' => '',
  2122. 'appointment_apply_datetime' => '',
  2123. 'appointment_apply_json' => '[]',
  2124. 'appointment_done_datetime' => '',
  2125. 'appointment_remark' => $params['order_remark'] ?? '',
  2126. 'appointment_done_json' => '[]'
  2127. ];
  2128. Appointment::insert($data);
  2129. } catch (\Exception $e) {
  2130. dump($e->getMessage());
  2131. throw new BusinessException("创建权益记录失败");
  2132. }
  2133. }
  2134. /**
  2135. * @Desc
  2136. * @Author Gorden
  2137. * @Date 2024/6/7 11:05
  2138. *
  2139. * @param $params
  2140. * @param $goods
  2141. * @return void
  2142. * @throws BusinessException
  2143. */
  2144. public function insertMemberBenefit($params, $goods)
  2145. {
  2146. try {
  2147. $data = [
  2148. 'member_benefit_id' => $params['benefitId'],
  2149. 'join_benefit_member_id' => $params['join_order_member_id'],
  2150. 'join_benefit_package_id' => $params['packageId'] ?? '',
  2151. 'join_benefit_goods_id' => $goods['goods_id'],
  2152. 'join_benefit_goods_sku_id' => $goods['skuId'] ?? '',
  2153. 'join_benefit_order_id' => $params['orderId'],
  2154. 'member_benefit_status' => 'ACTIVED',
  2155. 'member_benefit_category' => $goods['category'],
  2156. 'member_benefit_name' => $goods['goods_name'],
  2157. 'member_benefit_limit_count' => $params['order_sheet_num'],
  2158. 'member_benefit_used_count' => 0,
  2159. 'member_benefit_remark' => $params['order_remark'] ?? '',
  2160. 'member_benefit_addtimes' => time()
  2161. ];
  2162. MemberBenefit::insert($data);
  2163. } catch (\Exception $e) {
  2164. dump($e->getMessage());
  2165. throw new BusinessException('创建会员权益失败');
  2166. }
  2167. }
  2168. public function saveExpress($params, $orderId)
  2169. {
  2170. try {
  2171. $express = new OrderExpress();
  2172. $express->order_express_type = $params['order_express_type'];
  2173. $express->join_express_order_id = $orderId;
  2174. $express->join_express_dept_id = $params['submit_premises_id'] ?? 0;
  2175. $express->order_express_goods = $params['order_express_goods'];
  2176. $express->order_express_city = $params['order_express_city'];
  2177. $express->order_express_address = $params['order_express_address'];
  2178. $express->order_express_mobile = $params['order_express_mobile'] ?? '';
  2179. $express->order_express_telephone = $params['order_express_telephone'] ?? '';
  2180. $express->order_express_person = $params['order_express_person'] ?? '';
  2181. $express->order_express_company = $params['dept_premises_id'] ?? '';
  2182. $express->order_express_extend_json = $params['order_express_extend_json'] ?? '[]';
  2183. $express->order_express_addtimes = time();
  2184. $express->save();
  2185. } catch (\Exception $e) {
  2186. dump($e->getMessage());
  2187. throw new BusinessException('物流信息保存失败');
  2188. }
  2189. }
  2190. /**
  2191. * @Desc 修改优惠券状态
  2192. * @Author Gorden
  2193. * @Date 2024/9/19 9:03
  2194. *
  2195. * @param $coupon
  2196. * @param $status
  2197. * @return void
  2198. */
  2199. private function changeOrderCouponStatus($coupon, $status)
  2200. {
  2201. if (!empty($coupon) && is_array($coupon)) {
  2202. $updateData['coupon_detail_status'] = $status;
  2203. if ($status == 'ACTIVED' || $status == 'WAITING') {
  2204. $updateData['coupon_detail_used_datetime'] = '';
  2205. } elseif ($status == 'USED') {
  2206. $updateData['coupon_detail_used_datetime'] = date('Y-m-d H:i:s');
  2207. }
  2208. foreach ($coupon as $item) {
  2209. if (!empty($item['coupon_id']) && !empty($item['coupon_detail_id'])) {
  2210. foreach ($item['coupon_detail_id'] as $detailId) {
  2211. CouponDetail::where('join_detail_coupon_id', $item['coupon_id'])
  2212. ->where('coupon_detail_id', $detailId)->update($updateData);
  2213. }
  2214. }
  2215. }
  2216. }
  2217. }
  2218. private function discountRecord($orderDiscountJson, $params)
  2219. {
  2220. $json = [];
  2221. if (!empty($orderDiscountJson)) {
  2222. $json = json_decode($orderDiscountJson, true);
  2223. }
  2224. try {
  2225. if (!empty($params['preferential']) && in_array('wipe', $params['preferential'])) {
  2226. if (intval($params['order_amount_total'] / 10) * 10 != $params['order_amount_pay']) {
  2227. throw new BusinessException("抹零后实际支付金额错误");
  2228. }
  2229. $params['order_discount_amount'] = $params['order_amount_total'] - $params['order_amount_pay'];
  2230. $couponClassifyDesc = $couponClassify = '抹零';
  2231. } elseif (!empty($params['preferential']) && in_array('custom', $params['preferential'])) {
  2232. if (sprintf("%.2f", $params['order_amount_total'] - $params['order_discount_amount']) != sprintf("%.2f", $params['order_amount_pay'])) {
  2233. throw new BusinessException("餐厅前台优惠后实际支付金额错误");
  2234. }
  2235. $couponClassifyDesc = $couponClassify = '餐厅前台优惠';
  2236. } else if (!empty($params['preferential']) && intval($params['preferential'][0]) < 100 && intval($params['preferential'][0]) >= 50) {
  2237. if (($params['order_amount_total'] * intval($params['preferential'][0])) / 100 != $params['order_amount_pay']) {
  2238. throw new BusinessException("折扣后实际支付金额错误");
  2239. }
  2240. $couponClassify = '折扣';
  2241. $couponClassifyDesc = intval($params['preferential'][0]) / 10 . '折';
  2242. $params['order_discount_amount'] = $params['order_amount_total'] - $params['order_amount_pay'];
  2243. } else {
  2244. return $json;
  2245. }
  2246. $json[date('Y-m-d H:i:s')] = [
  2247. 'coupon_id' => $params['coupon_id'] ?? null,
  2248. 'coupon_value' => $params['order_discount_amount'] ?? '',
  2249. 'coupon_classify' => $couponClassify,
  2250. 'coupon_detail_id' => [$couponClassifyDesc],
  2251. 'coupon_classify_en' => $params['preferential']
  2252. ];
  2253. return $json;
  2254. } catch (BusinessException $e) {
  2255. throw new BusinessException($e->getMessage());
  2256. } catch (\Exception $e) {
  2257. dump($e->getMessage());
  2258. throw new BusinessException("优惠数据错误");
  2259. }
  2260. }
  2261. /**
  2262. * @Desc 入配送记录
  2263. * @Author Gorden
  2264. * @Date 2024/9/23 10:45
  2265. *
  2266. * @param $params
  2267. * @return void
  2268. * @throws BusinessException
  2269. */
  2270. public function insertExpressOne($params, $orderId)
  2271. {
  2272. if (isset($params['delivery']) && $params['delivery'] == 'LOGISTICS') {
  2273. $params['order_express_type'] = '配送';
  2274. // 入配送
  2275. $this->saveExpress($params, $orderId);
  2276. } else if (isset($params['delivery']) && $params['delivery'] == 'PICKUP') {
  2277. $params['order_express_type'] = '自提';
  2278. $premises = SysDept::where('dept_name', $params['dept_premises_id'])->first();
  2279. if (!$premises) {
  2280. throw new BusinessException('自提门店不存在');
  2281. }
  2282. $params['order_express_city'] = $premises->dept_city;
  2283. $params['order_express_address'] = $premises->dept_address;
  2284. $params['order_express_telephone'] = $premises->dept_telephone;
  2285. $params['order_express_extend_json'] = json_encode(['pick_code' => random_string(4, 'number')]);
  2286. $this->saveExpress($params, $orderId);
  2287. } else if (isset($params['delivery']) && $params['delivery'] == 'ARRIVAL') {
  2288. $premises = SysDept::where('dept_name', $params['dept_premises_id'])->first();
  2289. $params['order_express_type'] = '到店';
  2290. if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') {
  2291. $params['order_express_type'] = '堂食';
  2292. }
  2293. if (!$premises) {
  2294. throw new BusinessException('门店不存在');
  2295. }
  2296. $params['order_express_city'] = $premises->dept_city;
  2297. $params['order_express_address'] = $premises->dept_address;
  2298. $params['order_express_telephone'] = $premises->dept_telephone;
  2299. $this->saveExpress($params, $orderId);
  2300. }
  2301. }
  2302. /**
  2303. * @Desc 释放下单时选的优惠券
  2304. * @Author Gorden
  2305. * @Date 2024/9/19 9:56
  2306. *
  2307. * @param $coupon
  2308. * @return false|string
  2309. */
  2310. private function releaseCoupon($coupon)
  2311. {
  2312. if (!empty($coupon) && is_array($coupon)) {
  2313. $updateData = [
  2314. 'coupon_detail_status' => 'ACTIVED',
  2315. 'coupon_detail_used_datetime' => ''
  2316. ];
  2317. foreach ($coupon as $key => $item) {
  2318. if (!empty($item['coupon_id']) && !empty($item['coupon_detail_id'])) {
  2319. foreach ($item['coupon_detail_id'] as $detailId) {
  2320. if (substr($detailId, 0, 4) == 'CUDT') {
  2321. CouponDetail::where('join_detail_coupon_id', $item['coupon_id'])
  2322. ->where('coupon_detail_id', $detailId)
  2323. ->where('coupon_detail_status', 'WAITING')
  2324. ->update($updateData);
  2325. }
  2326. }
  2327. unset($coupon[$key]);
  2328. }
  2329. }
  2330. }
  2331. return json_encode($coupon);
  2332. }
  2333. }