ServicesController.php 132 KB

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