ServicesController.php 130 KB

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