GoodsController.php 133 KB

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