GoodsController.php 131 KB

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