PackagesController.php 136 KB

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