PackagesController.php 138 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719
  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);
  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. $goodsClassifys = array_unique(array_column($params['goodsContentList'], 'goods_classify'));
  683. $premises = [];
  684. if (!empty($params['dept_premises_id'])) {
  685. $premises = SysDept::where('dept_name', $params['dept_premises_id'])->first();
  686. }
  687. if (in_array('PACKAGE', $goodsClassifys)) {
  688. $params['submit_goods_classify'] = 'PACKAGE';
  689. }
  690. Db::beginTransaction();
  691. try {
  692. // 使用优惠券
  693. $couponUseJson = [];
  694. if (!empty($params['join_order_member_id']) && !empty($params['preferential'])) {
  695. $couponResult = OrderService::payUseCoupon('insert', $params['settlement_now'], $params['join_order_member_id'], $params['goodsContentList'], $params['preferential'], $params['order_amount_total']);
  696. if (!empty($couponResult['pay_amount']) && $couponResult['pay_amount'] != $params['order_amount_pay']) {
  697. throw new BusinessException("计算优惠后,实付金额错误!");
  698. }
  699. // 组装优惠券使用数据,存主表优惠里
  700. if (!empty($couponResult['use_coupon_json'])) {
  701. $couponUseJson = $couponResult['use_coupon_json'];
  702. }
  703. }
  704. // 存储优惠信息
  705. $params['order_discount_json'] = json_encode($this->discountRecord($couponUseJson, $params));
  706. $orderAmountPay = $params['order_amount_pay'];
  707. $constituteList = array_column($params['pay_category_constitute_list'], 'amount', 'category');
  708. // 验证金额
  709. $constituteAmount = 0;
  710. foreach ($params['pay_category_constitute_list'] as $item) {
  711. $constituteAmount = sprintf("%.2f", $constituteAmount) + sprintf("%.2f", $item['amount']);
  712. }
  713. if (sprintf("%.2f", $params['order_amount_pay']) != sprintf("%.2f", $constituteAmount)) {
  714. throw new BusinessException('组合支付金额与应付金额不一致');
  715. }
  716. $params['goods_classify'] = $goodsClassifys[0];
  717. // 验证库存
  718. OrderService::checkGoodsStorage($params);
  719. // 余额、福利、储值卡 验证短信
  720. if (!empty($params['pay_category_constitute'])
  721. && !in_array('OFFLINE', $params['pay_category_constitute'])
  722. && !in_array('MONEY', $params['pay_category_constitute'])
  723. && !in_array('QRCODE', $params['pay_category_constitute'])
  724. && (in_array('CASH', $params['pay_category_constitute'])
  725. || in_array('CARD', $params['pay_category_constitute'])
  726. || in_array('WELFARE', $params['pay_category_constitute']))) {
  727. $code = $params['sms_code'];
  728. if (!$code) {
  729. throw new BusinessException("验证码错误,请重新输入");
  730. }
  731. $member = Member::find($params['join_order_member_id']);
  732. $mobile = $member->member_mobile;
  733. $key = "SMS:CODE:ORDER_PAY:" . $mobile;
  734. $redisCode = Redis::get($key);
  735. if ($redisCode != $code && $code != '123456') {
  736. throw new BusinessException("验证码错误,请重新输入");
  737. }
  738. Redis::del($key);
  739. }
  740. // 验证线下付款密码
  741. if (!empty($params['pay_category_constitute'])
  742. && in_array('OFFLINE', $params['pay_category_constitute'])
  743. || (in_array('MONEY', $params['pay_category_constitute']) && !in_array('QRCODE', $params['pay_category_constitute']))) {
  744. $password = $params['offline_password'];
  745. if ($password != '666888') {
  746. throw new BusinessException("密码错误,请重新输入");
  747. }
  748. }
  749. // 下单账户
  750. if (empty($params['join_order_member_id']) && !empty($params['mobile'])) {
  751. if (Member::where('member_mobile', $params['mobile'])->exists()) {
  752. throw new BusinessException("会员已存在");
  753. }
  754. $params['join_order_member_id'] = $params['member_id'] = 'MR' . date('ymdHi') . random_string(4, 'up');
  755. // 创建会员
  756. MemberService::createMember($params);
  757. } else if (empty($params['join_order_member_id']) && empty($params['mobile'])) {
  758. $params['join_order_member_id'] = Member::where('member_mobile', '0000')->value('member_id');
  759. }
  760. if (empty($params['join_order_member_id'])) {
  761. throw new BusinessException("检查下单账户");
  762. }
  763. $params['orderId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
  764. $params['orderGroupId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
  765. $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
  766. $systemStatus = 'SENDING'; // 待发货
  767. // 立即结算
  768. if ($params['settlement_now'] == 'Y') {
  769. if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE']) && $params['delivery'] == 'ARRIVAL') {
  770. $params['order_is_complete'] = 'N';
  771. $systemStatus = "WAITING";
  772. }
  773. }
  774. $params['pay_detail_item'] = [];
  775. $wxAndAliPayStatus = 'Y';
  776. if (!empty($params['pay_category_constitute']) && in_array('OFFLINE', $params['pay_category_constitute'])) { // 线下支付
  777. $params['order_status_system'] = $systemStatus;
  778. $params['order_status_payment'] = 'SUCCESS';
  779. $params['pay_category'] = $params['pay_category_sub'] ?? 'OFFLINE';
  780. // 线下支付金额
  781. if (isset($constituteList['OFFLINE'])) {
  782. $params['order_amount_pay'] = $constituteList['OFFLINE'];
  783. // 生成支付记录
  784. $params['pay_detail_item'][] = $params;
  785. // OrderService::createPayDetail($params);
  786. }
  787. $params['order_amount_pay'] = $orderAmountPay;
  788. }
  789. if (!empty($params['pay_category_constitute']) && in_array('MONEY', $params['pay_category_constitute'])) { // 现金支付
  790. $params['order_status_system'] = $systemStatus;
  791. $params['order_status_payment'] = 'SUCCESS';
  792. $params['pay_category'] = 'MONEY';
  793. // 现金支付金额
  794. if (isset($constituteList['MONEY'])) {
  795. $params['order_amount_pay'] = $constituteList['MONEY'];
  796. // 生成支付记录
  797. $params['pay_detail_item'][] = $params;
  798. // OrderService::createPayDetail($params);
  799. }
  800. $params['order_amount_pay'] = $orderAmountPay;
  801. }
  802. if (!empty($params['pay_category_constitute']) && in_array('CASH', $params['pay_category_constitute'])) { // 余额支付
  803. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  804. ->where('member_account_classify', 'CASH')
  805. ->where('member_account_status', 'ACTIVED')
  806. ->first();
  807. if (!$account) {
  808. throw new BusinessException("账户异常");
  809. }
  810. $amount = $account->member_account_surplus + $account->member_account_added;
  811. if (isset($constituteList['CASH'])) {
  812. $params['order_amount_pay'] = $constituteList['CASH'];
  813. $params['pay_category'] = $params['join_order_member_id'] . '-CASH';
  814. }
  815. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  816. throw new BusinessException("账户余额不足");
  817. }
  818. // if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) {
  819. // $qrcodePayAmount = $params['order_amount_pay'] - $amount;
  820. // $params['order_amount_pay'] = $amount;
  821. // }
  822. // if ($params['order_amount_pay'] > $account->member_account_surplus) {
  823. // $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
  824. // $account->member_account_surplus = 0;
  825. // $account->member_account_added = $cut;
  826. // } else {
  827. // $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  828. // }
  829. // $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  830. // $account->save();
  831. // 余额账户扣款数据
  832. $params['waitToPayAccount']['cash'] = [
  833. 'group_id' => $params['orderGroupId'],
  834. 'member_id' => $params['join_order_member_id'],
  835. 'amount' => $constituteList['CASH'],
  836. 'nbr' => $params['join_order_member_id'] . '-CASH'
  837. ];
  838. $params['order_status_system'] = $systemStatus;
  839. $params['order_status_payment'] = 'SUCCESS';
  840. // 生成支付记录
  841. $params['pay_detail_item'][] = $params;
  842. $params['order_amount_pay'] = $orderAmountPay;
  843. }
  844. if (!empty($params['pay_category_constitute']) && in_array('CARD', $params['pay_category_constitute'])) { // 储值卡账户
  845. $cardNbr = $params['card_nbr'];
  846. if (!$cardNbr) {
  847. throw new BusinessException("储值卡账户异常");
  848. }
  849. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  850. ->where('member_account_nbr', $cardNbr)
  851. ->where('member_account_status', 'ACTIVED')
  852. ->first();
  853. if (!$account) {
  854. throw new BusinessException("储值卡账户异常");
  855. }
  856. $amount = $account->member_account_surplus + $account->member_account_added;
  857. // 储值卡账户支付金额
  858. if (isset($constituteList['CARD'])) {
  859. $params['order_amount_pay'] = $constituteList['CARD'];
  860. $params['pay_category'] = $cardNbr;
  861. }
  862. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  863. throw new BusinessException("储值卡账户余额不足");
  864. }
  865. // if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) {
  866. // $qrcodePayAmount = $params['order_amount_pay'] - $amount;
  867. // $params['order_amount_pay'] = $amount;
  868. // }
  869. //
  870. // if ($params['order_amount_pay'] > $account->member_account_surplus) {
  871. // $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
  872. // $account->member_account_surplus = 0;
  873. // $account->member_account_added = $cut;
  874. // } else {
  875. // $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  876. // }
  877. // $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  878. // $account->save();
  879. // 储值卡账户扣款数据
  880. $params['waitToPayAccount']['card'] = [
  881. 'group_id' => $params['orderGroupId'],
  882. 'member_id' => $params['join_order_member_id'],
  883. 'amount' => $constituteList['CARD'],
  884. 'nbr' => $params['join_order_member_id'] . '-CARD'
  885. ];
  886. $params['order_status_system'] = $systemStatus;
  887. $params['order_status_payment'] = 'SUCCESS';
  888. // 生成支付记录
  889. $params['pay_detail_item'][] = $params;
  890. $params['order_amount_pay'] = $orderAmountPay;
  891. }
  892. //!empty($params['pay_category_constitute']) && in_array('CARD',$params['pay_category_constitute'])
  893. // if(($params['pay_constitute'] == 'Y' || $params['pay_category'] == 'QRCODE') && $params['settlement_now'] == 'Y' && !empty($params['qrcode_nbr'])){ // 付款码
  894. if (!empty($params['pay_category_constitute']) && in_array('QRCODE', $params['pay_category_constitute']) && !empty($params['qrcode_nbr'])) { // 付款码
  895. // 需要付款码的金额>0
  896. if (isset($constituteList['QRCODE']) && $constituteList['QRCODE'] > 0) {
  897. // 付款码支付金额
  898. $params['order_amount_pay'] = $constituteList['QRCODE'];
  899. // 调支付
  900. $result = OrderService::qrcodePay($params);
  901. $result = json_encode($result);
  902. $params['pay_json_response'] = $result;
  903. $result = json_decode($result, true);
  904. $prefix = substr($params['qrcode_nbr'], 0, 2);
  905. if (in_array($prefix, [10, 11, 12, 13, 14, 15])) {
  906. $params['pay_category'] = 'WXPAY';
  907. 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')) {
  908. // 标记支付状态
  909. $wxAndAliPayStatus = 'N';
  910. $params['order_status_system'] = 'PAYING';
  911. $params['order_status_payment'] = 'PENDING';
  912. $params['order_is_complete'] = 'N';
  913. // Db::rollBack();
  914. // return json_fail('支付失败');
  915. } else {
  916. $params['order_status_system'] = $systemStatus;
  917. $params['order_status_payment'] = 'SUCCESS';
  918. }
  919. } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) {
  920. $params['pay_category'] = 'ALIPAY';
  921. if ((!isset($result['code']) || $result['code'] != '10000') || (empty($result['trade_status']) || $result['trade_status'] != 'TRADE_SUCCESS')) {
  922. // 标记支付状态
  923. $wxAndAliPayStatus = 'N';
  924. $params['order_status_system'] = 'PAYING';
  925. $params['order_status_payment'] = 'PENDING';
  926. $params['order_is_complete'] = 'N';
  927. // Db::rollBack();
  928. // return json_fail('支付失败');
  929. } else {
  930. $params['order_status_system'] = $systemStatus;
  931. $params['order_status_payment'] = 'SUCCESS';
  932. }
  933. } else {
  934. throw new BusinessException("二维码错误");
  935. }
  936. // 生成支付记录
  937. $params['pay_detail_item'][] = $params;
  938. // OrderService::createPayDetail($params);
  939. // 账户支付的金额
  940. $params['order_amount_pay'] = $orderAmountPay;
  941. }
  942. }
  943. $orderConfigJson = [];
  944. // 优惠
  945. if (!empty($params['preferential'])) {
  946. $orderConfigJson['preferential'] = $params['preferential'];
  947. }
  948. $params['order_config_json'] = json_encode($orderConfigJson);
  949. // 写入订单
  950. $this->insertMain($params, $wxAndAliPayStatus);
  951. Db::commit();
  952. // 会员升级
  953. if (!empty($params['order_is_complete']) && $params['order_is_complete'] == 'Y' && $params['order_status_payment'] == 'SUCCESS') {
  954. Event::dispatch('order.complete', $params);
  955. Event::dispatch('order_pay.member_level.up', $params['join_order_member_id']);
  956. }
  957. if ($params['settlement_now'] == 'Y' && $params['order_status_payment'] != 'SUCCESS') {
  958. _syslog("订单", "支付异常,检查是否有轮询");
  959. // 恢复优惠券到已占用
  960. if (!is_array($couponUseJson)) {
  961. $couponUseJson = json_decode($couponUseJson, true);
  962. }
  963. $this->changeOrderCouponStatus($couponUseJson, 'WAITING');
  964. return json_throw(2001, '支付异常', ['order_id' => $params['orderId'], 'group_id' => $params['orderGroupId']]);
  965. }
  966. _syslog("订单", "创建订单成功");
  967. return json_success('创建订单成功');
  968. } catch (BusinessException $e) {
  969. Db::rollBack();
  970. dump($e->getMessage());
  971. _syslog("订单", $e->getMessage());
  972. return json_fail($e->getMessage());
  973. } catch (\Exception $e) {
  974. Db::rollBack();
  975. dump($e->getMessage());
  976. _syslog("订单", "创建订单失败");
  977. return json_fail('创建订单失败');
  978. }
  979. }
  980. public function pay(Request $request)
  981. {
  982. $params = $request->post();
  983. // 余额、福利、储值卡 验证短信
  984. if ($params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['CASH', 'CARD', 'WELFARE'])) {
  985. $code = $params['sms_code'];
  986. if (!$code) {
  987. return json_fail("验证码错误,请重新输入");
  988. }
  989. $member = Member::find($params['join_order_member_id']);
  990. $mobile = $member->member_mobile;
  991. $key = "SMS:CODE:ORDER_PAY:" . $mobile;
  992. $redisCode = Redis::get($key);
  993. if ($redisCode != $code && $code != '123456') {
  994. return json_fail("验证码错误,请重新输入");
  995. }
  996. Redis::del($key);
  997. }
  998. // 验证线下付款密码
  999. if ($params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['OFFLINE', 'MONEY'])) {
  1000. $password = $params['offline_password'];
  1001. if ($password != '666888') {
  1002. return json_fail("密码错误,请重新输入");
  1003. }
  1004. }
  1005. $order = Order::where('order_id', $params['order_id'])->first();
  1006. if (!$order) {
  1007. return json_fail('订单异常');
  1008. }
  1009. if ($order->order_status_system != 'PAYING') {
  1010. return json_fail('订单不是可支付状态');
  1011. }
  1012. if (!empty($order->order_config_json)) {
  1013. $orderConfigJson = json_decode($order->order_config_json, true);
  1014. if (isset($orderConfigJson['premises'])) {
  1015. $premises = SysDept::where('dept_name', $orderConfigJson['premises'])->first();
  1016. if (!empty($premises)) {
  1017. $params['submit_premises_id'] = $premises->dept_id;
  1018. }
  1019. }
  1020. }
  1021. $params['orderId'] = $params['order_id'];
  1022. $params['orderGroupId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
  1023. $order->order_groupby = $params['orderGroupId'];
  1024. $goods = Goods::where('goods_id', $params['join_sheet_goods_id'])
  1025. ->select('goods_id', 'goods_name', 'goods_classify')
  1026. ->first();
  1027. if (!$goods) {
  1028. return json_fail('产品数据异常');
  1029. }
  1030. $goods = $goods->toArray();
  1031. $params['goods_classify'] = $goods['goods_classify'] ?? '';
  1032. $systemStatus = 'SENDING'; // 待发货
  1033. // 立即结算
  1034. if (in_array($params['goods_classify'], ['MEALS', 'VIP'])) {
  1035. $order->order_is_complete = 'Y';
  1036. $systemStatus = 'DONE';
  1037. }
  1038. if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE']) && $params['delivery'] == 'ARRIVAL') {
  1039. $params['order_is_complete'] = 'N';
  1040. $systemStatus = "WAITING";
  1041. }
  1042. // if ($params['goods_classify'] == 'PACKAGE' && $params['delivery'] == 'ARRIVAL') {
  1043. // $systemStatus = "WAITING";
  1044. // }
  1045. Db::beginTransaction();
  1046. try {
  1047. // 使用优惠券
  1048. $couponUseJson = [];
  1049. $discountJson = [];
  1050. if (!empty($order->order_discount_json)) {
  1051. $discountJson = json_decode($order->order_discount_json, true);
  1052. foreach ($discountJson as $item) {
  1053. if (isset($item['coupon_value']) && sprintf('%.2f', (floatval($order->order_amount_total) - floatval($params['order_amount_pay']))) != sprintf('%.2f', $item['coupon_value'])) {
  1054. throw new BusinessException("计算优惠后,实付金额错误!");
  1055. }
  1056. }
  1057. $couponUseJson = $discountJson;
  1058. $this->changeOrderCouponStatus($couponUseJson, 'USED');
  1059. // 释放下单时选的优惠券
  1060. // $order->order_discount_json = $this->releaseCoupon($discountJson);
  1061. }
  1062. if (empty($discountJson) && !empty($params['join_order_member_id']) && !empty($params['preferential'])) {
  1063. $couponResult = OrderService::payUseCoupon('pay', 'Y', $params['join_order_member_id'], $params['goodsContentList'], $params['preferential'], $params['order_amount_total']);
  1064. if (!empty($couponResult['pay_amount']) && $couponResult['pay_amount'] != $params['order_amount_pay']) {
  1065. throw new BusinessException("计算优惠后,实付金额错误!");
  1066. }
  1067. // 组装优惠券使用数据,存主表优惠里
  1068. if (!empty($couponResult['use_coupon_json'])) {
  1069. $couponUseJson = $couponResult['use_coupon_json'];
  1070. }
  1071. }
  1072. // 存储优惠信息
  1073. if (empty($discountJson)) {
  1074. $order->order_discount_json = json_encode($this->discountRecord($couponUseJson, $params));
  1075. }
  1076. // 组合支付时,付款码应收金额
  1077. $qrcodePayAmount = 0;
  1078. if ($params['pay_category'] == 'OFFLINE' || $params['pay_category'] == 'MONEY') {
  1079. $order->order_status_system = $systemStatus;
  1080. $order->order_status_payment = 'SUCCESS';
  1081. if ($params['pay_category'] == 'OFFLINE' && !empty($params['pay_category_sub'])) {
  1082. $params['pay_category'] = $params['pay_category_sub'];
  1083. }
  1084. } else if ($params['pay_category'] == 'CASH') { // 余额支付
  1085. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  1086. ->where('member_account_classify', 'CASH')
  1087. ->where('member_account_status', 'ACTIVED')
  1088. ->first();
  1089. if (!$account) {
  1090. throw new BusinessException('账户异常');
  1091. }
  1092. $amount = $account->member_account_surplus + $account->member_account_added;
  1093. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  1094. throw new BusinessException('账户余额不足');
  1095. }
  1096. if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) {
  1097. $qrcodePayAmount = $params['order_amount_pay'] - $amount;
  1098. $params['order_amount_pay'] = $amount;
  1099. }
  1100. if ($params['order_amount_pay'] > $account->member_account_surplus) {
  1101. $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
  1102. $account->member_account_surplus = 0;
  1103. $account->member_account_added = $cut;
  1104. } else {
  1105. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  1106. }
  1107. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  1108. $account->save();
  1109. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] <= $amount)) {
  1110. $order->order_status_system = $systemStatus;
  1111. $order->order_status_payment = 'SUCCESS';
  1112. }
  1113. } else if ($params['pay_category'] == 'VIP') { // 余额支付
  1114. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  1115. ->where('member_account_classify', 'VIP')
  1116. ->where('member_account_status', 'ACTIVED')
  1117. ->first();
  1118. if (!$account) {
  1119. throw new BusinessException('账户异常');
  1120. }
  1121. $amount = $account->member_account_surplus + $account->member_account_added;
  1122. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  1123. throw new BusinessException('账户余额不足');
  1124. }
  1125. if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) {
  1126. $qrcodePayAmount = $params['order_amount_pay'] - $amount;
  1127. $params['order_amount_pay'] = $amount;
  1128. }
  1129. if ($params['order_amount_pay'] > $account->member_account_surplus) {
  1130. $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
  1131. $account->member_account_surplus = 0;
  1132. $account->member_account_added = $cut;
  1133. } else {
  1134. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  1135. }
  1136. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  1137. $account->save();
  1138. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] <= $amount)) {
  1139. $order->order_status_system = $systemStatus;
  1140. $order->order_status_payment = 'SUCCESS';
  1141. }
  1142. } else if ($params['pay_category'] == 'WELFARE') { // 福利账户
  1143. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  1144. ->where('member_account_classify', 'WELFARE')
  1145. ->where('member_account_status', 'ACTIVED')
  1146. ->first();
  1147. if (!$account) {
  1148. throw new BusinessException('账户异常');
  1149. }
  1150. $account->member_account_surplus = floatval($account->member_account_surplus);
  1151. if ($params['pay_constitute'] == 'N' && ($params['order_amount_pay'] > $account->member_account_surplus)) {
  1152. throw new BusinessException('账户余额不足');
  1153. }
  1154. if ($params['pay_constitute'] == 'Y' && ($params['order_amount_pay'] > $account->member_account_surplus)) {
  1155. $qrcodePayAmount = $params['order_amount_pay'] - $account->member_account_surplus;
  1156. $params['order_amount_pay'] = $account->member_account_surplus;
  1157. }
  1158. if ($params['pay_constitute'] == 'N' && ($params['order_amount_pay'] <= $account->member_account_surplus)) {
  1159. $order->order_status_system = $systemStatus;
  1160. $order->order_status_payment = 'SUCCESS';
  1161. }
  1162. // 福利账户 300 、 700
  1163. if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS'])) {
  1164. $payDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
  1165. ->where('pay_status', 'SUCCESS')
  1166. ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
  1167. ->whereIn('pay_category', ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'DESHES'])
  1168. ->get()
  1169. ->toArray();
  1170. $payDetailArray = array_column($payDetails, 'pay_amount', 'join_pay_order_id');
  1171. $refundPayDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
  1172. ->where('pay_status', 'SUCCESS')
  1173. ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
  1174. ->where('pay_category', 'REFUND')
  1175. ->get()
  1176. ->toArray();
  1177. $refundPayDetailArray = array_column($refundPayDetails, 'pay_amount', 'join_pay_order_id');
  1178. $paySum = 0;
  1179. foreach ($payDetailArray as $key => $item) {
  1180. if (isset($refundPayDetailArray[$key])) {
  1181. $paySum = $paySum + ($item - $refundPayDetailArray[$key]);
  1182. continue;
  1183. }
  1184. $paySum = $paySum + $item;
  1185. }
  1186. if ($params['pay_constitute'] == 'N' && 700 - $paySum < $params['order_amount_pay']) {
  1187. throw new BusinessException('超出福利限额');
  1188. } else if ($params['pay_constitute'] == 'Y' && 700 - $paySum < $params['order_amount_pay']) {
  1189. $qrcodePayAmount = $params['order_amount_pay'] - (700 - $paySum);
  1190. $params['order_amount_pay'] = (700 - $paySum);
  1191. }
  1192. } else {
  1193. $payDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
  1194. ->where('pay_status', 'SUCCESS')
  1195. ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
  1196. ->whereNotIn('pay_category', ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'DESHES', 'REFUND', 'RECHARGE'])
  1197. ->get()
  1198. ->toArray();
  1199. $payDetailArray = array_column($payDetails, 'pay_amount', 'join_pay_order_id');
  1200. $refundPayDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
  1201. ->where('pay_status', 'SUCCESS')
  1202. ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
  1203. ->where('pay_category', 'REFUND')
  1204. ->get()
  1205. ->toArray();
  1206. $refundPayDetailArray = array_column($refundPayDetails, 'pay_amount', 'join_pay_order_id');
  1207. $paySum = 0;
  1208. foreach ($payDetailArray as $key => $item) {
  1209. if (isset($refundPayDetailArray[$key])) {
  1210. $paySum = $paySum + ($item - $refundPayDetailArray[$key]);
  1211. continue;
  1212. }
  1213. $paySum = $paySum + $item;
  1214. }
  1215. if ($params['pay_constitute'] == 'N' && 300 - $paySum < $params['order_amount_pay']) {
  1216. throw new BusinessException('超出福利限额');
  1217. } else if ($params['pay_constitute'] == 'Y' && 300 - $paySum < $params['order_amount_pay']) {
  1218. $qrcodePayAmount = $params['order_amount_pay'] - (300 - $paySum);
  1219. $params['order_amount_pay'] = (300 - $paySum);
  1220. }
  1221. }
  1222. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  1223. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  1224. $account->save();
  1225. } else if ($params['pay_category'] == 'CARD') { // 储值卡账户
  1226. $cardNbr = $params['card_nbr'];
  1227. if (!$cardNbr) {
  1228. throw new BusinessException('账户异常');
  1229. }
  1230. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  1231. ->where('member_account_nbr', $cardNbr)
  1232. ->where('member_account_status', 'ACTIVED')
  1233. ->first();
  1234. if (!$account) {
  1235. throw new BusinessException('账户异常');
  1236. }
  1237. $amount = $account->member_account_surplus + $account->member_account_added;
  1238. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  1239. throw new BusinessException('账户余额不足');
  1240. }
  1241. if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) {
  1242. $qrcodePayAmount = $params['order_amount_pay'] - $amount;
  1243. $params['order_amount_pay'] = $amount;
  1244. }
  1245. if ($params['order_amount_pay'] > $account->member_account_surplus) {
  1246. $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
  1247. $account->member_account_surplus = 0;
  1248. $account->member_account_added = $cut;
  1249. } else {
  1250. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  1251. }
  1252. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  1253. $account->save();
  1254. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] <= $amount)) {
  1255. $order->order_status_system = $systemStatus;
  1256. $order->order_status_payment = 'SUCCESS';
  1257. }
  1258. }
  1259. if (($params['pay_constitute'] == 'Y' || $params['pay_category'] == 'QRCODE') && !empty($params['qrcode_nbr'])) { // 付款码
  1260. // 提交过来的支付分类
  1261. $submitPayCategory = $params['pay_category'];
  1262. // 账户支付的金额
  1263. $accountAmount = $params['order_amount_pay'];
  1264. if ($params['pay_constitute'] == 'Y' && $qrcodePayAmount > 0) {
  1265. // 组合支付,改成需要付款码需要支付的金额
  1266. $params['order_amount_pay'] = $qrcodePayAmount;
  1267. }
  1268. // 去支付
  1269. $result = OrderService::qrcodePay($params);
  1270. $result = json_encode($result);
  1271. $params['pay_json_response'] = $result;
  1272. $result = json_decode($result, true);
  1273. $prefix = substr($params['qrcode_nbr'], 0, 2);
  1274. if (in_array($prefix, [10, 11, 12, 13, 14, 15])) {
  1275. $params['pay_category'] = 'WXPAY';
  1276. 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')) {
  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 if (in_array($prefix, [25, 26, 27, 28, 29, 30])) {
  1287. $params['pay_category'] = 'ALIPAY';
  1288. if ((!isset($result['code']) || $result['code'] != '10000') || (empty($result['trade_status']) || $result['trade_status'] != 'TRADE_SUCCESS')) {
  1289. $order->order_status_system = 'PAYING';
  1290. $order->order_status_payment = 'PENDING';
  1291. $order->order_is_complete = 'N';
  1292. // Db::rollBack();
  1293. // return json_fail('支付失败');
  1294. } else {
  1295. $order->order_status_system = $systemStatus;
  1296. $order->order_status_payment = 'SUCCESS';
  1297. }
  1298. } else {
  1299. throw new BusinessException('付款码无效');
  1300. }
  1301. // 账户支付的金额
  1302. $params['order_amount_pay'] = $accountAmount;
  1303. }
  1304. $orderConfigJson = [];
  1305. if (!empty($order->order_config_json)) {
  1306. $orderConfigJson = json_decode($order->order_config_json, true);
  1307. }
  1308. $orderConfigJson['preferential'] = $params['preferential'] ?? '';
  1309. $order->order_config_json = json_encode($orderConfigJson);
  1310. $order->order_amount_pay = $params['order_amount_pay'] + $qrcodePayAmount;
  1311. // 主订单
  1312. $order->save();
  1313. // sheet
  1314. if ($order->order_status_payment == 'SUCCESS') {
  1315. OrderSheet::where('join_sheet_order_id', $params['order_id'])->update([
  1316. 'order_sheet_status' => $systemStatus,
  1317. ]);
  1318. }
  1319. // payDetail
  1320. // 不组合支付,那就只有一条支付记录 先删,再加
  1321. PayDetail::where('join_pay_order_id', $order->order_groupby)
  1322. ->whereJsonContains('join_pay_object_json->order_id', $params['orderId'])
  1323. ->delete();
  1324. $payData = [
  1325. 'pay_amount' => $params['order_amount_pay']
  1326. ];
  1327. if ($order->order_status_payment == 'SUCCESS') {
  1328. $payData['pay_paytimes'] = date('Y-m-d H:i:s');
  1329. $payData['pay_status'] = 'SUCCESS';
  1330. }
  1331. if ($params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['WXPAY', 'ALIPAY'])) {
  1332. $payData['pay_prepayid'] = $params['pay_category'];
  1333. $payData['pay_json_response'] = $params['pay_json_response'];
  1334. } else if ($params['pay_category'] == 'CASH') {
  1335. $payData['pay_prepayid'] = $params['join_order_member_id'] . '-CASH';
  1336. } else if ($params['pay_category'] == 'WELFARE') {
  1337. $payData['pay_prepayid'] = $params['join_order_member_id'] . '-WELFARE';
  1338. } else if ($params['pay_category'] == 'VIP') {
  1339. $payData['pay_prepayid'] = $params['join_order_member_id'] . '-VIP';
  1340. } else if ($params['pay_category'] == 'CARD') {
  1341. $payData['pay_prepayid'] = $params['card_nbr'];
  1342. } else if ($params['pay_category'] == 'OFFLINE') {
  1343. $payData['pay_prepayid'] = 'OFFLINE';
  1344. } else if ($params['pay_category'] == 'OFFLINE_ALIPAY') {
  1345. $payData['pay_prepayid'] = 'OFFLINE_ALIPAY';
  1346. } else if ($params['pay_category'] == 'OFFLINE_WXPAY') {
  1347. $payData['pay_prepayid'] = 'OFFLINE_WXPAY';
  1348. } else if ($params['pay_category'] == 'MONEY') {
  1349. $payData['pay_prepayid'] = 'MONEY';
  1350. }
  1351. $payData['join_pay_member_id'] = $params['join_order_member_id'];
  1352. $payData['join_pay_order_id'] = $order->order_groupby;
  1353. $payData['pay_status'] = !empty($payData['pay_status']) && $payData['pay_status'] == 'SUCCESS' ? $payData['pay_status'] : 'WAITING';
  1354. $payData['pay_category'] = $params['goods_classify'] ?? '';
  1355. $payData['pay_paytimes'] = date('Y-m-d H:i:s');
  1356. $payData['pay_json_request'] = json_encode($params); // {"pay-result": "支付成功", "result-datetime": "2024-07-29 18:38:21"}
  1357. $payData['pay_json_response'] = !empty($payData['pay_status']) && $payData['pay_status'] == 'SUCCESS' ? (!empty($params['pay_json_response']) ? $params['pay_json_response'] : json_encode(['pay-result' => '支付成功', 'result-datetime' => date('Y-m-d H:i:s')])) : '[]';
  1358. $payData['join_pay_object_json'] = !empty($params['orderId']) ? json_encode(['order_id' => $params['orderId']]) : '[]';
  1359. $payData['pay_addtimes'] = time();
  1360. PayDetail::insert($payData);
  1361. $writeOffDate = [];
  1362. $applyData = [];
  1363. // 有预约单,状态已完成
  1364. $appointment = Appointment::where('join_appointment_order_id', $params['order_id'])->first();
  1365. if ($order->order_status_payment == 'SUCCESS' && $appointment) {
  1366. $writeOffDate = OrderService::generateWriteOffData($params);
  1367. $applyData = OrderService::generateAppointmentApplyData($params);
  1368. $appointment->appointment_status = 'DONE';
  1369. $appointment->appointment_done_datetime = date('Y-m-d H:i:s');
  1370. $appointment->appointment_done_json = json_encode($writeOffDate);
  1371. if (empty($appointment->appointment_apply_datetime)) {
  1372. $appointment->appointment_apply_datetime = date('Y-m-d H:i:s');
  1373. }
  1374. if (empty($appointment->appointment_apply_json)) {
  1375. $appointment->appointment_apply_json = json_encode($applyData);
  1376. }
  1377. if (empty($appointment->appointment_datetime)) {
  1378. $appointment->appointment_datetime = date('Y-m-d');
  1379. }
  1380. $appointment->save();
  1381. }
  1382. // // 买的单个服务
  1383. if ($order->order_status_payment == 'SUCCESS' && empty($appointment)) {
  1384. foreach ($params['goodsContentList'] as $goods) {
  1385. $params['join_sheet_goods_id'] = $goods['goods_id'];
  1386. if (isset($goods['goods_classify']) && in_array($goods['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD'])) {
  1387. $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
  1388. $params['order_sheet_num'] = $goods['nbr'];
  1389. // 预约表
  1390. for ($i = 0; $i < intval($params['order_sheet_num']); $i++) {
  1391. $params['appointmentId'] = 'AP' . date('ymdHi') . random_string(4, 'up');
  1392. // 入预约记录
  1393. $this->insertAppointment($params, $writeOffDate, $applyData);
  1394. }
  1395. $goods['skuId'] = $goods['sku_id'];
  1396. $goods['category'] = $goods['goods_classify'];
  1397. // 权益表
  1398. $this->insertMemberBenefit($params, $goods);
  1399. } elseif (isset($goods['goods_classify']) && $goods['goods_classify'] == 'PACKAGE') { // 一个套餐买多个
  1400. $params['packageId'] = $goods['goods_id'];
  1401. $components = GoodsComponent::with([
  1402. 'goods' => function ($query) {
  1403. $query->select('goods_id', 'goods_name', 'goods_classify');
  1404. }
  1405. ])->where('join_component_master_goods_id', $params['packageId'])
  1406. ->get()
  1407. ->toArray();
  1408. foreach ($components as $component) {
  1409. $componentJson = json_decode($component['goods_component_json'], true);
  1410. $params['join_sheet_goods_sku_id'] = $componentJson['sku_id'];
  1411. $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
  1412. $params['order_sheet_num'] = $goods['nbr'] * $componentJson['nbr'];
  1413. for ($i = 0; $i < intval($params['order_sheet_num']); $i++) {
  1414. $params['appointmentId'] = 'AP' . date('ymdHi') . random_string(4, 'up');
  1415. // 入预约记录
  1416. $this->insertAppointment($params, $writeOffDate);
  1417. }
  1418. $goods['goods_id'] = $component['join_component_goods_id'];
  1419. $goods['goods_name'] = $component['goods']['goods_name'];
  1420. $goods['goods_classify'] = $component['goods']['goods_classify'];
  1421. $goods['skuId'] = $goods['sku_id'];
  1422. $goods['category'] = 'SERVICE';
  1423. // 权益表
  1424. $this->insertMemberBenefit($params, $goods);
  1425. }
  1426. }
  1427. }
  1428. }
  1429. Db::commit();
  1430. // 触发事件
  1431. if ($order->order_is_complete == 'Y' && $order->order_status_payment == 'SUCCESS') {
  1432. // 完成订单
  1433. Event::dispatch('order.complete', $params);
  1434. // 会员升级
  1435. Event::dispatch('order_pay.member_level.up', $params['join_order_member_id']);
  1436. }
  1437. if ($order->order_status_payment == 'SUCCESS') {
  1438. // 上级提成
  1439. Event::dispatch('commission.order', $params);
  1440. }
  1441. // 打小票
  1442. if ($order->order_status_payment == 'SUCCESS') {
  1443. if (!empty($premises) && !empty($premises->dept_id)) {
  1444. $voteData = [
  1445. 'func' => 'procActionToPrinter',
  1446. 'sign' => '',
  1447. 'data' => [
  1448. 'printer_premises' => $premises->dept_id,
  1449. 'printer_device' => ["收银"],
  1450. 'printer_action' => 'ExecPrintOrder',
  1451. 'printer_data' => [
  1452. 'order_id' => $params['orderId'],
  1453. 'order_batch' => ''
  1454. ]
  1455. ]
  1456. ];
  1457. // dump("小票参数", $voteData);
  1458. http_post_json(getenv('VOTE_MENU_URL'), $voteData);
  1459. }
  1460. }
  1461. if ($order->order_status_payment != 'SUCCESS') {
  1462. _syslog("订单", "支付异常,检查是否有轮询");
  1463. // 恢复优惠券到已占用
  1464. if (!is_array($couponUseJson)) {
  1465. $couponUseJson = json_decode($couponUseJson, true);
  1466. }
  1467. // 如果下单时就填了,不用恢复
  1468. if (empty($discountJson)) {
  1469. $this->changeOrderCouponStatus($couponUseJson, 'WAITING');
  1470. }
  1471. return json_throw(2001, '支付异常', ['order_id' => $params['orderId'], 'group_id' => $params['orderGroupId']]);
  1472. }
  1473. _syslog("订单", "订单支付成功");
  1474. return json_success('支付成功');
  1475. } catch (BusinessException $e) {
  1476. dump($e->getMessage());
  1477. Db::rollBack();
  1478. _syslog("订单", "订单支付失败:" . $e->getMessage());
  1479. return json_fail("支付失败:" . $e->getMessage());
  1480. } catch (\Exception $e) {
  1481. dump($e->getMessage());
  1482. Db::rollBack();
  1483. _syslog("订单", "订单支付失败");
  1484. return json_fail('支付失败');
  1485. }
  1486. }
  1487. /**
  1488. * 组合支付
  1489. */
  1490. public function payConstitute(Request $request)
  1491. {
  1492. $params = $request->post();
  1493. // 余额、福利、储值卡 验证短信
  1494. 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']))) {
  1495. $code = $params['sms_code'];
  1496. if (!$code) {
  1497. return json_fail("验证码错误,请重新输入");
  1498. }
  1499. $member = Member::find($params['join_order_member_id']);
  1500. $mobile = $member->member_mobile;
  1501. $key = "SMS:CODE:ORDER_PAY:" . $mobile;
  1502. $redisCode = Redis::get($key);
  1503. if ($redisCode != $code && $code != '123456') {
  1504. return json_fail("验证码错误,请重新输入");
  1505. }
  1506. Redis::del($key);
  1507. }
  1508. // 验证线下付款密码
  1509. if (!empty($params['pay_category_constitute']) && in_array('OFFLINE', $params['pay_category_constitute']) && in_array('MONEY', $params['pay_category_constitute'])) {
  1510. $password = $params['offline_password'];
  1511. if ($password != '666888') {
  1512. return json_fail("密码错误,请重新输入");
  1513. }
  1514. }
  1515. $order = Order::where('order_id', $params['order_id'])->first();
  1516. if (!$order) {
  1517. return json_fail('订单异常');
  1518. }
  1519. if ($order->order_status_system != 'PAYING') {
  1520. return json_fail('订单不是可支付状态');
  1521. }
  1522. if (!empty($order->order_config_json)) {
  1523. $orderConfigJson = json_decode($order->order_config_json, true);
  1524. if (isset($orderConfigJson['premises'])) {
  1525. $premises = SysDept::where('dept_name', $orderConfigJson['premises'])->first();
  1526. if (!empty($premises)) {
  1527. $params['submit_premises_id'] = $premises->dept_id;
  1528. }
  1529. }
  1530. }
  1531. $params['orderId'] = $params['order_id'];
  1532. $params['orderGroupId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
  1533. $order->order_groupby = $params['orderGroupId'];
  1534. $goods = Goods::where('goods_id', $params['join_sheet_goods_id'])
  1535. ->select('goods_id', 'goods_name', 'goods_classify')
  1536. ->first();
  1537. if (!$goods) {
  1538. return json_fail('产品数据异常');
  1539. }
  1540. $goods = $goods->toArray();
  1541. $params['goods_classify'] = $goods['goods_classify'];
  1542. $systemStatus = 'SENDING'; // 待发货
  1543. // 立即结算
  1544. if (in_array($params['goods_classify'], ['MEALS', 'VIP'])) {
  1545. $order->order_is_complete = 'Y';
  1546. $systemStatus = 'DONE';
  1547. }
  1548. if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE']) && $params['delivery'] == 'ARRIVAL') {
  1549. $params['order_is_complete'] = 'N';
  1550. $systemStatus = "WAITING";
  1551. }
  1552. $payDetail = PayDetail::where('join_pay_order_id', $order->order_groupby)->first();
  1553. Db::beginTransaction();
  1554. try {// 使用优惠券
  1555. $couponUseJson = [];
  1556. $discountJson = [];
  1557. if (!empty($order->order_discount_json)) {
  1558. $discountJson = json_decode($order->order_discount_json, true);
  1559. foreach ($discountJson as $item) {
  1560. if (isset($item['coupon_value']) && sprintf('%.2f', (floatval($order->order_amount_total) - floatval($params['order_amount_pay']))) != sprintf('%.2f', $item['coupon_value'])) {
  1561. throw new BusinessException("计算优惠后,实付金额错误!");
  1562. }
  1563. }
  1564. $couponUseJson = $discountJson;
  1565. $this->changeOrderCouponStatus($couponUseJson, 'USED');
  1566. // 释放下单时选的优惠券
  1567. // $order->order_discount_json = $this->releaseCoupon($discountJson);
  1568. }
  1569. if (empty($discountJson) && !empty($params['join_order_member_id']) && !empty($params['preferential'])) {
  1570. $couponResult = OrderService::payUseCoupon('pay', 'Y', $params['join_order_member_id'], $params['goodsContentList'], $params['preferential'], $params['order_amount_total']);
  1571. if (!empty($couponResult['pay_amount']) && $couponResult['pay_amount'] != $params['order_amount_pay']) {
  1572. throw new BusinessException("计算优惠后,实付金额错误!");
  1573. }
  1574. // 组装优惠券使用数据,存主表优惠里
  1575. if (!empty($couponResult['use_coupon_json'])) {
  1576. $couponUseJson = $couponResult['use_coupon_json'];
  1577. }
  1578. }
  1579. // 存储优惠信息
  1580. if (empty($discountJson)) {
  1581. $order->order_discount_json = json_encode($this->discountRecord($couponUseJson, $params));
  1582. }
  1583. $orderAmountPay = $params['order_amount_pay'];
  1584. $constituteList = array_column($params['pay_category_constitute_list'], 'amount', 'category');// 验证金额
  1585. $constituteAmount = 0;
  1586. foreach ($params['pay_category_constitute_list'] as $item) {
  1587. $constituteAmount = sprintf("%.2f", $constituteAmount) + sprintf("%.2f", $item['amount']);
  1588. }
  1589. if (sprintf("%.2f", $params['order_amount_pay']) != sprintf("%.2f", $constituteAmount)) {
  1590. throw new BusinessException('组合支付金额与应付金额不一致');
  1591. }
  1592. $wxAndAliPayStatus = 'Y';
  1593. $waitToPayAccount = [];
  1594. // 清除订单的支付记录,重建
  1595. PayDetail::whereJsonContains('join_pay_object_json->order_id', $params['orderId'])->delete();
  1596. if (!empty($params['pay_category_constitute']) && in_array('OFFLINE', $params['pay_category_constitute'])) { //线下付款
  1597. $order->order_status_system = $systemStatus;
  1598. $order->order_status_payment = 'SUCCESS';
  1599. $params['pay_category'] = $params['pay_category_sub'] ?? 'OFFLINE';
  1600. // 线下支付金额
  1601. if (isset($constituteList['OFFLINE'])) {
  1602. $params['order_amount_pay'] = $constituteList['OFFLINE'];
  1603. // 生成支付记录
  1604. $params['order_status_payment'] = 'PENDING';
  1605. OrderService::createProductPayConstituteDetail($params);
  1606. $params['order_status_payment'] = 'SUCCESS';
  1607. }
  1608. $params['order_amount_pay'] = $orderAmountPay;
  1609. }
  1610. if (!empty($params['pay_category_constitute']) && in_array('MONEY', $params['pay_category_constitute'])) { //现金付款
  1611. $order->order_status_system = $systemStatus;
  1612. $order->order_status_payment = 'SUCCESS';
  1613. $params['pay_category'] = 'MONEY';
  1614. // 线下支付金额
  1615. if (isset($constituteList['MONEY'])) {
  1616. $params['order_amount_pay'] = $constituteList['MONEY'];
  1617. // 生成支付记录
  1618. $params['order_status_payment'] = 'PENDING';
  1619. OrderService::createProductPayConstituteDetail($params, $payDetail);
  1620. $params['order_status_payment'] = 'SUCCESS';
  1621. }
  1622. $params['order_amount_pay'] = $orderAmountPay;
  1623. }
  1624. if (!empty($params['pay_category_constitute']) && in_array('CASH', $params['pay_category_constitute'])) { // 余额支付
  1625. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  1626. ->where('member_account_classify', 'CASH')
  1627. ->where('member_account_status', 'ACTIVED')
  1628. ->first();
  1629. if (!$account) {
  1630. throw new BusinessException('账户异常');
  1631. }
  1632. if (isset($constituteList['CASH'])) {
  1633. $params['order_amount_pay'] = $constituteList['CASH'];
  1634. $params['pay_category'] = $params['join_order_member_id'] . '-CASH';
  1635. }
  1636. $amount = $account->member_account_surplus + $account->member_account_added;
  1637. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  1638. throw new BusinessException('账户余额不足');
  1639. }
  1640. // 余额账户扣款数据
  1641. $waitToPayAccount['cash'] = [
  1642. 'group_id' => $params['orderGroupId'],
  1643. 'member_id' => $params['join_order_member_id'],
  1644. 'amount' => $constituteList['CASH'],
  1645. 'nbr' => $params['join_order_member_id'] . '-CASH'
  1646. ];
  1647. // 生成支付记录
  1648. $params['order_status_payment'] = 'PENDING';
  1649. OrderService::createProductPayConstituteDetail($params);
  1650. $params['order_status_payment'] = 'SUCCESS';
  1651. $params['order_amount_pay'] = $orderAmountPay;
  1652. $order->order_status_system = $systemStatus;
  1653. $order->order_status_payment = 'SUCCESS';
  1654. }
  1655. if (!empty($params['pay_category_constitute']) && in_array('CARD', $params['pay_category_constitute'])) { // 储值卡账户
  1656. $cardNbr = $params['card_nbr'];
  1657. if (!$cardNbr) {
  1658. throw new BusinessException('账户异常');
  1659. }
  1660. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  1661. ->where('member_account_nbr', $cardNbr)
  1662. ->where('member_account_status', 'ACTIVED')
  1663. ->first();
  1664. if (!$account) {
  1665. Db::rollBack();
  1666. return json_fail('账户异常');
  1667. }
  1668. // 储值卡账户支付金额
  1669. if (isset($constituteList['CARD'])) {
  1670. $params['order_amount_pay'] = $constituteList['CARD'];
  1671. $params['pay_category'] = $cardNbr;
  1672. }
  1673. $amount = $account->member_account_surplus + $account->member_account_added;
  1674. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  1675. throw new BusinessException('账户余额不足');
  1676. }
  1677. // 储值卡账户扣款数据
  1678. $waitToPayAccount['card'] = [
  1679. 'group_id' => $params['orderGroupId'],
  1680. 'member_id' => $params['join_order_member_id'],
  1681. 'amount' => $constituteList['CARD'],
  1682. 'nbr' => $params['join_order_member_id'] . '-CARD'
  1683. ];
  1684. // 生成支付记录
  1685. $params['order_status_payment'] = 'PENDING';
  1686. OrderService::createProductPayConstituteDetail($params);
  1687. $params['order_status_payment'] = 'SUCCESS';
  1688. $params['order_amount_pay'] = $orderAmountPay;
  1689. $order->order_status_system = $systemStatus;
  1690. $order->order_status_payment = 'SUCCESS';
  1691. }
  1692. if (!empty($params['pay_category_constitute']) && in_array('QRCODE', $params['pay_category_constitute']) && !empty($params['qrcode_nbr'])) { // 付款码
  1693. if (isset($constituteList['QRCODE']) && $constituteList['QRCODE'] > 0) {
  1694. // 付款码支付金额
  1695. $params['order_amount_pay'] = $constituteList['QRCODE'];
  1696. // 调支付
  1697. $result = OrderService::qrcodePay($params);
  1698. $result = json_encode($result);
  1699. $params['pay_json_response'] = $result;
  1700. $result = json_decode($result, true);
  1701. $prefix = substr($params['qrcode_nbr'], 0, 2);
  1702. if (in_array($prefix, [10, 11, 12, 13, 14, 15])) {
  1703. $params['pay_category'] = 'WXPAY';
  1704. 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')) {
  1705. // 标记支付状态
  1706. $wxAndAliPayStatus = 'N';
  1707. $order->order_status_system = 'PAYING';
  1708. $order->order_status_payment = 'PENDING';
  1709. $order->order_is_complete = 'N';
  1710. $params['order_status_payment'] = 'PAYING';
  1711. } else {
  1712. $order->order_status_system = $systemStatus;
  1713. $order->order_status_payment = 'SUCCESS';
  1714. $params['order_status_payment'] = 'SUCCESS';
  1715. }
  1716. } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) {
  1717. $params['pay_category'] = 'ALIPAY';
  1718. if ((!isset($result['code']) || $result['code'] != '10000') || (empty($result['trade_status']) || $result['trade_status'] != 'TRADE_SUCCESS')) {
  1719. // 标记支付状态
  1720. $wxAndAliPayStatus = 'N';
  1721. $order->order_status_system = 'PAYING';
  1722. $order->order_status_payment = 'PENDING';
  1723. $order->order_is_complete = 'N';
  1724. $params['order_status_payment'] = 'PAYING';
  1725. } else {
  1726. $order->order_status_system = $systemStatus;
  1727. $order->order_status_payment = 'SUCCESS';
  1728. $params['order_status_payment'] = 'SUCCESS';
  1729. }
  1730. } else {
  1731. throw new BusinessException('付款码无效');
  1732. }
  1733. }
  1734. // 生成支付记录
  1735. OrderService::createProductPayConstituteDetail($params);
  1736. // 账户支付的金额
  1737. $params['order_amount_pay'] = $orderAmountPay;
  1738. }
  1739. $orderConfigJson = [];
  1740. if (!empty($order->order_config_json)) {
  1741. $orderConfigJson = json_decode($order->order_config_json, true);
  1742. }
  1743. $orderConfigJson['preferential'] = $params['preferential'] ?? '';
  1744. $order->order_config_json = json_encode($orderConfigJson);
  1745. $order->order_amount_pay = $params['order_amount_pay'];
  1746. // 主订单
  1747. $order->save();
  1748. // sheet
  1749. if ($order->order_status_payment == 'SUCCESS') {
  1750. OrderSheet::where('join_sheet_order_id', $params['order_id'])->update([
  1751. 'order_sheet_status' => $systemStatus,
  1752. ]);
  1753. }
  1754. if ($wxAndAliPayStatus == 'Y') {
  1755. PayDetail::whereJsonContains('join_pay_object_json->order_id', $params['orderId'])->update([
  1756. 'pay_status' => 'SUCCESS',
  1757. 'pay_paytimes' => date('Y-m-d H:i:s')
  1758. ]);
  1759. // 扣款
  1760. foreach ($waitToPayAccount as $item) {
  1761. $accountNbr = $item['nbr'];
  1762. $account = MemberAccount::where('member_account_nbr', $accountNbr)->first();
  1763. $account->member_account_expend = $account->member_account_expend + $amount;
  1764. if ($account->member_account_surplus < $amount && strpos($accountNbr, 'CASH') !== false) {
  1765. $account->member_account_added = $account->member_account_added - ($amount - $account->member_account_surplus);
  1766. $account->member_account_surplus = 0;
  1767. } else {
  1768. $account->member_account_surplus = $account->member_account_surplus - $amount;
  1769. }
  1770. $account->save();
  1771. }
  1772. }
  1773. // 买单个服务
  1774. if ($order->order_status_payment == 'SUCCESS' && empty($appointment)) {
  1775. foreach ($params['goodsContentList'] as $goods) {
  1776. $params['join_sheet_goods_id'] = $goods['goods_id'];
  1777. if (isset($goods['goods_classify']) && in_array($goods['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD'])) {
  1778. $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
  1779. $params['order_sheet_num'] = $goods['nbr'];
  1780. // 预约表
  1781. for ($i = 0; $i < intval($params['order_sheet_num']); $i++) {
  1782. $params['appointmentId'] = 'AP' . date('ymdHi') . random_string(4, 'up');
  1783. // 入预约记录
  1784. $this->insertAppointment($params, $writeOffDate, $applyData);
  1785. }
  1786. $goods['skuId'] = $goods['sku_id'];
  1787. $goods['category'] = $goods['goods_classify'];
  1788. // 权益表
  1789. $this->insertMemberBenefit($params, $goods);
  1790. } elseif (isset($goods['goods_classify']) && $goods['goods_classify'] == 'PACKAGE') { // 一个套餐买多个
  1791. $params['packageId'] = $goods['goods_id'];
  1792. $components = GoodsComponent::with([
  1793. 'goods' => function ($query) {
  1794. $query->select('goods_id', 'goods_name', 'goods_classify');
  1795. }
  1796. ])->where('join_component_master_goods_id', $params['packageId'])
  1797. ->get()
  1798. ->toArray();
  1799. foreach ($components as $component) {
  1800. $componentJson = json_decode($component['goods_component_json'], true);
  1801. $params['join_sheet_goods_sku_id'] = $componentJson['sku_id'];
  1802. $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
  1803. $params['order_sheet_num'] = $goods['nbr'] * $componentJson['nbr'];
  1804. for ($i = 0; $i < intval($params['order_sheet_num']); $i++) {
  1805. $params['appointmentId'] = 'AP' . date('ymdHi') . random_string(4, 'up');
  1806. // 入预约记录
  1807. $this->insertAppointment($params, $writeOffDate);
  1808. }
  1809. $goods['goods_id'] = $component['join_component_goods_id'];
  1810. $goods['goods_name'] = $component['goods']['goods_name'];
  1811. $goods['goods_classify'] = $component['goods']['goods_classify'];
  1812. $goods['skuId'] = $goods['sku_id'];
  1813. $goods['category'] = 'SERVICE';
  1814. // 权益表
  1815. $this->insertMemberBenefit($params, $goods);
  1816. }
  1817. }
  1818. }
  1819. }
  1820. Db::commit();
  1821. // 触发事件
  1822. if ($order->order_is_complete == 'Y' && $order->order_status_payment == 'SUCCESS') {
  1823. // 完成订单
  1824. Event::dispatch('order.complete', $params);
  1825. // 会员升级
  1826. Event::dispatch('order_pay.member_level.up', $params['join_order_member_id']);
  1827. }
  1828. if ($order->order_status_payment == 'SUCCESS') {
  1829. // 上级提成
  1830. Event::dispatch('commission.order', $params);
  1831. }
  1832. // 打小票
  1833. if ($order->order_status_payment == 'SUCCESS') {
  1834. if (!empty($premises) && !empty($premises->dept_id)) {
  1835. $voteData = [
  1836. 'func' => 'procActionToPrinter',
  1837. 'sign' => '',
  1838. 'data' => [
  1839. 'printer_premises' => $premises->dept_id,
  1840. 'printer_device' => ["收银"],
  1841. 'printer_action' => 'ExecPrintOrder',
  1842. 'printer_data' => [
  1843. 'order_id' => $params['orderId'],
  1844. 'order_batch' => ''
  1845. ]
  1846. ]
  1847. ];
  1848. // dump("小票参数", $voteData);
  1849. http_post_json(getenv('VOTE_MENU_URL'), $voteData);
  1850. }
  1851. }
  1852. if ($order->order_status_payment != 'SUCCESS') {
  1853. _syslog("订单", "支付异常,检查是否有轮询");
  1854. // 恢复优惠券到已占用
  1855. if (!is_array($couponUseJson)) {
  1856. $couponUseJson = json_decode($couponUseJson, true);
  1857. }
  1858. // 如果下单时就填了,不用恢复
  1859. if (empty($discountJson)) {
  1860. $this->changeOrderCouponStatus($couponUseJson, 'WAITING');
  1861. }
  1862. // 清除支付记录,恢复账户金额
  1863. // $this->restoreAccount($params['pay_detail_item']);
  1864. return json_throw(2001, '支付异常', ['order_id' => $params['orderId'], 'group_id' => $params['orderGroupId']]);
  1865. }
  1866. _syslog("订单", "订单支付成功");
  1867. return json_success('支付成功');
  1868. } catch (\Exception $e) {
  1869. dump($e->getMessage());
  1870. Db::rollBack();
  1871. _syslog("订单", "订单支付失败");
  1872. return json_fail('支付失败');
  1873. }
  1874. }
  1875. public function restoreAccount($payDetailItem)
  1876. {
  1877. foreach ($payDetailItem as $item) {
  1878. $prepayId = '';
  1879. if ($item['order_status_payment'] == 'SUCCESS') {
  1880. if (in_array($item['pay_category'], ['MONEY', 'OFFLINE', 'OFFLINE_ALIPAY', 'OFFLINE_WXPAY'])) {
  1881. $prepayId = $item['pay_category'];
  1882. }
  1883. 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) {
  1884. $prepayId = $item['pay_category'];
  1885. $account = MemberAccount::where('member_account_nbr', $prepayId)->first();
  1886. $account->member_account_expend = $account->member_account_expend - $item['order_amount_pay'];
  1887. $account->member_account_surplus = $account->member_account_surplus + $item['order_amount_pay'];
  1888. $account->save();
  1889. }
  1890. }
  1891. if (!empty($prepayId)) {
  1892. PayDetail::where('pay_prepayid', $prepayId)
  1893. ->where('join_pay_order_id', $item['orderGroupId'])
  1894. ->whereJsonContains('join_pay_object_json->order_id', $item['orderId'])
  1895. ->update(['pay_status' => 'WAITING']);
  1896. }
  1897. }
  1898. }
  1899. /**
  1900. * @Desc
  1901. * @Author Gorden
  1902. * @Date 2024/6/7 10:30
  1903. *
  1904. * @param $params
  1905. * @return void
  1906. * @throws BusinessException
  1907. */
  1908. public function insertMain($params, $wxAndAliPayStatus = 'Y')
  1909. {
  1910. try {
  1911. if (empty($params['order_extend_json'])) {
  1912. $params['order_extend_json'] = [];
  1913. } else {
  1914. if (is_json($params['order_extend_json'])) {
  1915. $params['order_extend_json'] = json_decode($params['order_extend_json'], true);
  1916. }
  1917. }
  1918. // 账户扣款
  1919. if ($wxAndAliPayStatus == 'Y' && !empty($params['waitToPayAccount'])) {
  1920. foreach ($params['waitToPayAccount'] as $account) {
  1921. $this->deductAmount($account['nbr'], $account['amount']);
  1922. }
  1923. }
  1924. // 推荐人
  1925. $params['order_extend_json']['referee'] = $params['referee'] ?? '';
  1926. foreach ($params['goodsContentList'] as $goods) {
  1927. $discountJson = [];
  1928. if (!empty($params['order_discount_json'])) {
  1929. $discountJson = json_decode($params['order_discount_json'], true);
  1930. foreach ($discountJson as &$item) {
  1931. if (!empty($item['coupon_value'])) {
  1932. $item['coupon_value'] = round((floatval($goods['goods_sales_price']) * $goods['nbr'] / $params['order_amount_total']) * $item['coupon_value'], 2);
  1933. }
  1934. }
  1935. }
  1936. $orderId = 'OD' . date('ymdHi') . random_string(4, 'up');
  1937. $amountPay = round((floatval($goods['goods_sales_price']) * $goods['nbr'] / $params['order_amount_total']) * $params['order_amount_pay'], 2);
  1938. // $amountPay = round(floatval($goods['goods_sales_price']) * $goods['nbr'] * $params['order_ratio'], 2);
  1939. $data = [
  1940. 'order_id' => $orderId,
  1941. 'order_groupby' => $params['orderGroupId'],
  1942. 'join_order_member_id' => $params['join_order_member_id'],
  1943. 'order_name' => date('Y-m-d H:i:s') . '-订单',
  1944. 'order_amount_total' => floatval($goods['goods_sales_price']) * $goods['nbr'],
  1945. 'order_amount_pay' => $amountPay,
  1946. 'order_category' => $goods['goods_classify'],
  1947. 'order_classify' => $goods['goods_classify'],
  1948. 'order_is_complete' => $params['order_is_complete'] ?? 'N',
  1949. 'order_status_system' => $params['order_status_system'],
  1950. 'order_status_payment' => $params['order_status_payment'],
  1951. 'order_status_storage' => $params['order_status_storage'],
  1952. 'order_platform' => $params['order_platform'],
  1953. 'order_remark' => $params['order_remark'] ?? '',
  1954. 'order_discount_json' => json_encode($discountJson),
  1955. 'order_config_json' => $params['order_config_json'] ?? '[]',
  1956. 'order_express_json' => $params['order_express_json'] ?? '[]',
  1957. 'order_extend_json' => $params['order_extend_json'] ? json_encode($params['order_extend_json']) : '[]',
  1958. 'order_addtimes' => time()
  1959. ];
  1960. Order::insert($data);
  1961. $sheetIds = $this->insertSheetOne($params, $goods, $orderId, $amountPay);
  1962. $this->insertPayDetailOne($params, $orderId, $amountPay, $goods);
  1963. $params['order_express_goods'] = json_encode(['sheet' => $sheetIds]);
  1964. $this->insertExpressOne($params, $orderId);
  1965. // 写到权益里
  1966. if ($params['order_status_payment'] == 'SUCCESS') {
  1967. $this->insertBenefitOne($params, $goods, $orderId);
  1968. }
  1969. }
  1970. } catch (\Exception $e) {
  1971. dump($e->getMessage() . '|' . $e->getLine());
  1972. throw new BusinessException('订单创建信息失败');
  1973. }
  1974. }
  1975. /**
  1976. * @Desc 扣除账户金额
  1977. * @Author Gorden
  1978. * @Date 2024/9/26 14:16
  1979. *
  1980. * @param $accountNbr
  1981. * @param $amount
  1982. * @return void
  1983. */
  1984. public function deductAmount($accountNbr, $amount)
  1985. {
  1986. try {
  1987. $account = MemberAccount::where('member_account_nbr', $accountNbr)->first();
  1988. $account->member_account_expend = $account->member_account_expend + $amount;
  1989. if ($account->member_account_surplus < $amount && strpos($accountNbr, 'CASH') !== false) {
  1990. $account->member_account_added = $account->member_account_added - ($amount - $account->member_account_surplus);
  1991. $account->member_account_surplus = 0;
  1992. } else {
  1993. $account->member_account_surplus = $account->member_account_surplus - $amount;
  1994. }
  1995. $account->save();
  1996. } catch (\Exception $e) {
  1997. _syslog("下单扣款", "扣款失败");
  1998. throw new BusinessException("账户扣款失败");
  1999. }
  2000. }
  2001. /**
  2002. * @Desc 打小票
  2003. * @Author Gorden
  2004. * @Date 2024/9/24 9:35
  2005. *
  2006. * @param $params
  2007. * @param $premises
  2008. * @param $orderId
  2009. * @return void
  2010. */
  2011. public function printerTicket($params, $premises, $orderId)
  2012. {
  2013. // 打小票
  2014. if ($params['order_status_payment'] == 'SUCCESS') {
  2015. if (!empty($premises) && !empty($premises->dept_id)) {
  2016. $voteData = [
  2017. 'func' => 'procActionToPrinter',
  2018. 'sign' => '',
  2019. 'data' => [
  2020. 'printer_premises' => $premises->dept_id,
  2021. 'printer_device' => ["收银"],
  2022. 'printer_action' => 'ExecPrintOrder',
  2023. 'printer_data' => [
  2024. 'order_id' => $orderId,
  2025. 'order_batch' => ''
  2026. ]
  2027. ]
  2028. ];
  2029. // dump("小票参数", $voteData);
  2030. http_post_json(getenv('VOTE_MENU_URL'), $voteData);
  2031. }
  2032. }
  2033. }
  2034. /**
  2035. * @Desc 单套包权益
  2036. * @Author Gorden
  2037. * @Date 2024/9/24 8:42
  2038. *
  2039. * @param $params
  2040. * @param $goods
  2041. * @return void
  2042. * @throws BusinessException
  2043. */
  2044. public function insertBenefitOne($params, $goods, $orderId)
  2045. {
  2046. $params['orderId'] = $orderId;
  2047. $writeOffDate = [];
  2048. $applyData = [];
  2049. if (isset($goods['goods_classify']) && $goods['goods_classify'] == 'PACKAGE' && $params['delivery'] == 'ARRIVAL') { // 一个套餐买多个
  2050. $params['packageId'] = $goods['goods_id'];
  2051. $components = GoodsComponent::with([
  2052. 'goods' => function ($query) {
  2053. $query->select('goods_id', 'goods_name', 'goods_classify');
  2054. }
  2055. ])->where('join_component_master_goods_id', $params['packageId'])
  2056. ->get()
  2057. ->toArray();
  2058. foreach ($components as $component) {
  2059. $componentJson = json_decode($component['goods_component_json'], true);
  2060. $params['join_sheet_goods_sku_id'] = $componentJson['sku_id'];
  2061. $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
  2062. $params['order_sheet_num'] = $goods['nbr'] * $componentJson['nbr'];
  2063. $params['join_sheet_goods_id'] = $component['join_component_goods_id'];
  2064. for ($i = 0; $i < intval($params['order_sheet_num']); $i++) {
  2065. $params['appointmentId'] = 'AP' . date('ymdHi') . random_string(4, 'up');
  2066. // 入预约记录
  2067. $this->insertAppointment($params, $writeOffDate);
  2068. }
  2069. $goods['goods_id'] = $component['join_component_goods_id'];
  2070. $goods['goods_name'] = $component['goods']['goods_name'];
  2071. $goods['goods_classify'] = $component['goods']['goods_classify'];
  2072. $goods['skuId'] = $goods['sku_id'];
  2073. $goods['category'] = 'SERVICE';
  2074. // 权益表
  2075. $this->insertMemberBenefit($params, $goods);
  2076. }
  2077. }
  2078. }
  2079. /**
  2080. * @Desc
  2081. * @Author Gorden
  2082. * @Date 2024/6/7 10:25
  2083. *
  2084. * @param $params
  2085. * @return void
  2086. * @throws BusinessException
  2087. */
  2088. public function insertSheet($params)
  2089. {
  2090. try {
  2091. $orderSheetIds = [];
  2092. foreach ($params['goodsContentList'] as $goods) {
  2093. //{"unit": "份", "table": null, "premises": "15"}
  2094. $price = floatval($goods['goods_sales_price']);
  2095. $extendJson['unit'] = $goods['sku_name'];
  2096. if (isset($params['submit_premises_id'])) {
  2097. $extendJson['premises'] = $params['submit_premises_id'];
  2098. }
  2099. if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') {
  2100. $extendJson['table'] = null;
  2101. }
  2102. $data = [
  2103. 'join_sheet_member_id' => $params['join_order_member_id'],
  2104. 'join_sheet_order_id' => $params['orderId'],
  2105. 'join_sheet_goods_id' => $goods['goods_id'],
  2106. 'join_sheet_goods_sku_id' => $goods['sku_id'],
  2107. 'order_sheet_status' => $params['settlement_now'] == 'Y' && $params['order_status_payment'] == 'SUCCESS' ? 'DONE' : 'PAYING',
  2108. 'order_sheet_category' => (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') ? 'DISHES' : 'NORMAL',
  2109. 'order_sheet_num' => $goods['nbr'],
  2110. 'order_sheet_price' => $goods['goods_sales_price'],
  2111. 'order_sheet_amount' => $price * $goods['nbr'],
  2112. 'order_sheet_pay' => $price * $goods['nbr'],
  2113. 'order_sheet_task_status' => 'NONE',
  2114. 'order_sheet_remark' => $params['order_remark'] ?? '',
  2115. 'order_sheet_addtimes' => time(),
  2116. 'order_sheet_extend_json' => json_encode($extendJson)
  2117. ];
  2118. $orderSheetId = OrderSheet::insertGetId($data);
  2119. $orderSheetIds[] = $orderSheetId;
  2120. // 减库存,规格和总库存
  2121. if (!isset($params['submit_goods_classify']) || !in_array($params['submit_goods_classify'], ['MEALS', 'PACKAGE'])) {
  2122. $goodsSku = GoodsSku::where('goods_sku_id', $goods['sku_id'])->first();
  2123. $skuStorageJson = json_decode($goodsSku->goods_sku_storage_json, true);
  2124. if (isset($skuStorageJson['storage']) && !empty($skuStorageJson['storage'])) {
  2125. $skuStorageJson['storage'] = $skuStorageJson['storage'] - $goods['nbr'];
  2126. }
  2127. if (!isset($skuStorageJson['storage']) || (!empty($skuStorageJson['storage']) && $skuStorageJson['storage'] < 0)) {
  2128. throw new BusinessException('库存不足');
  2129. }
  2130. $goodsSku->goods_sku_storage_json = json_encode($skuStorageJson);
  2131. $goodsSku->save();
  2132. }
  2133. $goodsRunning = GoodsRunning::where('join_running_goods_id', $goods['goods_id'])->first();
  2134. $goodsRunning->goods_running_storage = $goodsRunning->goods_running_storage - $goods['nbr'];
  2135. if ($goodsRunning->goods_running_storage < 0) {
  2136. throw new BusinessException('库存不足');
  2137. }
  2138. $goodsRunning->goods_running_sale = $goodsRunning->goods_running_sale + $goods['nbr'];
  2139. $goodsRunning->save();
  2140. }
  2141. // return $orderSheetIds;
  2142. } catch (\support\exception\BusinessException $e) {
  2143. dump($e->getMessage() . '||' . $e->getLine());
  2144. throw new BusinessException($e->getMessage());
  2145. } catch (\Exception $e) {
  2146. dump($e->getMessage() . '||' . $e->getLine());
  2147. throw new BusinessException('订单创建失败');
  2148. }
  2149. }
  2150. /**
  2151. * @Desc 单条入库
  2152. * @Author Gorden
  2153. * @Date 2024/9/23 10:19
  2154. *
  2155. * @param $params
  2156. * @return array
  2157. * @throws BusinessException
  2158. */
  2159. public function insertSheetOne($params, $goods, $orderId, $amountPay)
  2160. {
  2161. try {
  2162. $orderSheetIds = [];
  2163. // foreach ($params['goodsContentList'] as $goods) {
  2164. //{"unit": "份", "table": null, "premises": "15"}
  2165. $price = floatval($goods['goods_sales_price']);
  2166. $extendJson['unit'] = $goods['sku_name'];
  2167. if (isset($params['submit_premises_id'])) {
  2168. $extendJson['premises'] = $params['submit_premises_id'];
  2169. }
  2170. if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') {
  2171. $extendJson['table'] = null;
  2172. }
  2173. $data = [
  2174. 'join_sheet_member_id' => $params['join_order_member_id'],
  2175. 'join_sheet_order_id' => $orderId,
  2176. 'join_sheet_goods_id' => $goods['goods_id'],
  2177. 'join_sheet_goods_sku_id' => $goods['sku_id'],
  2178. 'order_sheet_status' => $params['settlement_now'] == 'Y' && $params['order_status_payment'] == 'SUCCESS' ? 'DONE' : 'PAYING',
  2179. 'order_sheet_category' => (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') ? 'DISHES' : 'NORMAL',
  2180. 'order_sheet_num' => $goods['nbr'],
  2181. 'order_sheet_price' => $goods['goods_sales_price'],
  2182. 'order_sheet_price_pay' => round($amountPay / $goods['nbr'], 2),
  2183. 'order_sheet_amount' => $price * $goods['nbr'],
  2184. 'order_sheet_pay' => $amountPay,
  2185. 'order_sheet_task_status' => 'NONE',
  2186. 'order_sheet_remark' => $params['order_remark'] ?? '',
  2187. 'order_sheet_addtimes' => time(),
  2188. 'order_sheet_extend_json' => json_encode($extendJson)
  2189. ];
  2190. $orderSheetId = OrderSheet::insertGetId($data);
  2191. $orderSheetIds[] = $orderSheetId;
  2192. // 减库存,规格和总库存
  2193. if (!isset($params['submit_goods_classify']) || !in_array($params['submit_goods_classify'], ['MEALS', 'PACKAGE'])) {
  2194. $goodsSku = GoodsSku::where('goods_sku_id', $goods['sku_id'])->first();
  2195. $skuStorageJson = json_decode($goodsSku->goods_sku_storage_json, true);
  2196. if (isset($skuStorageJson['storage']) && !empty($skuStorageJson['storage'])) {
  2197. $skuStorageJson['storage'] = $skuStorageJson['storage'] - $goods['nbr'];
  2198. }
  2199. if (!isset($skuStorageJson['storage']) || (!empty($skuStorageJson['storage']) && $skuStorageJson['storage'] < 0)) {
  2200. throw new BusinessException('库存不足');
  2201. }
  2202. $goodsSku->goods_sku_storage_json = json_encode($skuStorageJson);
  2203. $goodsSku->save();
  2204. }
  2205. $goodsRunning = GoodsRunning::where('join_running_goods_id', $goods['goods_id'])->first();
  2206. $goodsRunning->goods_running_storage = $goodsRunning->goods_running_storage - $goods['nbr'];
  2207. if ($goodsRunning->goods_running_storage < 0) {
  2208. throw new BusinessException('库存不足');
  2209. }
  2210. $goodsRunning->goods_running_sale = $goodsRunning->goods_running_sale + $goods['nbr'];
  2211. $goodsRunning->save();
  2212. // }
  2213. return $orderSheetIds;
  2214. } catch (\support\exception\BusinessException $e) {
  2215. dump($e->getMessage() . '||' . $e->getLine());
  2216. throw new BusinessException($e->getMessage());
  2217. } catch (\Exception $e) {
  2218. dump($e->getMessage() . '||' . $e->getLine());
  2219. throw new BusinessException('订单创建失败');
  2220. }
  2221. }
  2222. /**
  2223. * @Desc
  2224. * @Author Gorden
  2225. * @Date 2024/6/7 10:35
  2226. *
  2227. * @param $params
  2228. * @return void
  2229. * @throws BusinessException
  2230. */
  2231. public function insertPayDetail($params)
  2232. {
  2233. try {
  2234. if (in_array($params['pay_category'], ['WXPAY', 'ALIPAY'])) {
  2235. $payPrepayid = $params['pay_category'];
  2236. } else if ($params['pay_category'] == 'OFFLINE') {
  2237. $payPrepayid = 'OFFLINE';
  2238. } else if ($params['pay_category'] == 'OFFLINE_ALIPAY') {
  2239. $payPrepayid = 'OFFLINE_ALIPAY';
  2240. } else if ($params['pay_category'] == 'OFFLINE_WXPAY') {
  2241. $payPrepayid = 'OFFLINE_WXPAY';
  2242. } else if ($params['pay_category'] == 'MONEY') {
  2243. $payPrepayid = 'MONEY';
  2244. } else {
  2245. $payPrepayid = $params['join_order_member_id'] . '-' . $params['pay_category'];
  2246. }
  2247. $data = [
  2248. 'join_pay_member_id' => $params['join_order_member_id'],
  2249. 'join_pay_order_id' => $params['orderGroupId'],
  2250. 'pay_status' => $params['settlement_now'] == 'Y' && $params['order_status_payment'] == 'SUCCESS' ? 'SUCCESS' : 'WAITING',
  2251. 'pay_category' => $params['goods_classify'],
  2252. 'pay_amount' => $params['order_amount_pay'],
  2253. 'pay_prepayid' => $payPrepayid,
  2254. 'pay_paytimes' => date('Y-m-d H:i:s'),
  2255. 'join_pay_object_json' => !empty($params['orderId']) ? json_encode(['order_id' => $params['orderId']]) : '[]',
  2256. 'pay_json_request' => json_encode($params),
  2257. 'pay_json_response' => $params['pay_json_response'] ?? '[]',
  2258. 'pay_remark' => $params['order_remark'] ?? '',
  2259. 'pay_addtimes' => time(),
  2260. ];
  2261. PayDetail::insert($data);
  2262. } catch (\Exception $e) {
  2263. dump($e->getMessage());
  2264. throw new BusinessException('创建支付记录失败');
  2265. }
  2266. }
  2267. /**
  2268. * @Desc 单条入库
  2269. * @Author Gorden
  2270. * @Date 2024/6/7 10:35
  2271. *
  2272. * @param $params
  2273. * @return void
  2274. * @throws BusinessException
  2275. */
  2276. public function insertPayDetailOne($params, $orderId, $amountPay, $goods)
  2277. {
  2278. try {
  2279. if (!empty($params['pay_detail_item'])) {
  2280. foreach ($params['pay_detail_item'] as $item) {
  2281. $data = [
  2282. 'join_pay_member_id' => $item['join_order_member_id'],
  2283. 'join_pay_order_id' => $item['orderGroupId'],
  2284. 'pay_status' => $params['settlement_now'] == 'Y' && $params['order_status_payment'] == 'SUCCESS' ? 'SUCCESS' : 'WAITING',
  2285. 'pay_category' => $goods['goods_classify'],
  2286. 'pay_amount' => round(($amountPay / $params['order_amount_pay']) * $item['order_amount_pay'], 2),
  2287. 'pay_prepayid' => $item['pay_category'],
  2288. 'pay_paytimes' => date('Y-m-d H:i:s'),
  2289. 'join_pay_object_json' => !empty($item['orderId']) ? json_encode(['order_id' => $orderId]) : '[]',
  2290. 'pay_json_request' => json_encode($item),
  2291. 'pay_json_response' => $item['pay_json_response'] ?? '[]',
  2292. 'pay_remark' => $item['order_remark'] ?? '',
  2293. 'pay_addtimes' => time(),
  2294. ];
  2295. PayDetail::insert($data);
  2296. }
  2297. } else {
  2298. if (in_array($params['pay_category'], ['WXPAY', 'ALIPAY'])) {
  2299. $payPrepayid = $params['pay_category'];
  2300. } else if ($params['pay_category'] == 'OFFLINE') {
  2301. $payPrepayid = 'OFFLINE';
  2302. } else if ($params['pay_category'] == 'OFFLINE_ALIPAY') {
  2303. $payPrepayid = 'OFFLINE_ALIPAY';
  2304. } else if ($params['pay_category'] == 'OFFLINE_WXPAY') {
  2305. $payPrepayid = 'OFFLINE_WXPAY';
  2306. } else if ($params['pay_category'] == 'MONEY') {
  2307. $payPrepayid = 'MONEY';
  2308. } else {
  2309. $payPrepayid = $params['join_order_member_id'] . '-' . $params['pay_category'];
  2310. }
  2311. $data = [
  2312. 'join_pay_member_id' => $params['join_order_member_id'],
  2313. 'join_pay_order_id' => $params['orderGroupId'],
  2314. 'pay_status' => $params['settlement_now'] == 'Y' && $params['order_status_payment'] == 'SUCCESS' ? 'SUCCESS' : 'WAITING',
  2315. 'pay_category' => $goods['goods_classify'],
  2316. 'pay_amount' => $amountPay,
  2317. 'pay_prepayid' => $payPrepayid,
  2318. 'pay_paytimes' => date('Y-m-d H:i:s'),
  2319. 'join_pay_object_json' => !empty($params['orderId']) ? json_encode(['order_id' => $orderId]) : '[]',
  2320. 'pay_json_request' => json_encode($params),
  2321. 'pay_json_response' => $params['pay_json_response'] ?? '[]',
  2322. 'pay_remark' => $params['order_remark'] ?? '',
  2323. 'pay_addtimes' => time(),
  2324. ];
  2325. PayDetail::insert($data);
  2326. }
  2327. } catch (\Exception $e) {
  2328. dump($e->getMessage());
  2329. throw new BusinessException('创建支付记录失败');
  2330. }
  2331. }
  2332. /**
  2333. * @Desc
  2334. * @Author Gorden
  2335. * @Date 2024/6/7 10:50
  2336. *
  2337. * @param $params
  2338. * @return void
  2339. * @throws BusinessException
  2340. */
  2341. public function insertAppointment($params, $writeOffDate, $applyData = [])
  2342. {
  2343. try {
  2344. $data = [
  2345. 'appointment_id' => $params['appointmentId'],
  2346. 'join_appointment_member_id' => $params['join_order_member_id'],
  2347. 'join_appointment_goods_id' => $params['join_sheet_goods_id'],
  2348. 'join_appointment_goods_sku_id' => $params['join_sheet_goods_sku_id'],
  2349. 'join_appointment_order_id' => $params['orderId'],
  2350. 'join_appointment_member_benefit_id' => $params['benefitId'],
  2351. 'appointment_classify' => $params['goods_classify'],
  2352. 'appointment_status' => 'INIT',
  2353. 'appointment_category' => 'NORMAL',
  2354. 'appointment_platform' => 'SYSTEM',
  2355. 'appointment_addtimes' => time(),
  2356. 'appointment_datetime' => '',
  2357. 'appointment_apply_datetime' => '',
  2358. 'appointment_apply_json' => '[]',
  2359. 'appointment_done_datetime' => '',
  2360. 'appointment_remark' => $params['order_remark'] ?? '',
  2361. 'appointment_done_json' => '[]'
  2362. ];
  2363. Appointment::insert($data);
  2364. } catch (\Exception $e) {
  2365. dump($e->getMessage());
  2366. throw new BusinessException("创建权益记录失败");
  2367. }
  2368. }
  2369. /**
  2370. * @Desc
  2371. * @Author Gorden
  2372. * @Date 2024/6/7 11:05
  2373. *
  2374. * @param $params
  2375. * @param $goods
  2376. * @return void
  2377. * @throws BusinessException
  2378. */
  2379. public function insertMemberBenefit($params, $goods)
  2380. {
  2381. try {
  2382. $data = [
  2383. 'member_benefit_id' => $params['benefitId'],
  2384. 'join_benefit_member_id' => $params['join_order_member_id'],
  2385. 'join_benefit_package_id' => $params['packageId'] ?? '',
  2386. 'join_benefit_goods_id' => $goods['goods_id'],
  2387. 'join_benefit_goods_sku_id' => $goods['skuId'] ?? '',
  2388. 'join_benefit_order_id' => $params['orderId'],
  2389. 'member_benefit_status' => 'ACTIVED',
  2390. 'member_benefit_category' => $goods['category'],
  2391. 'member_benefit_name' => $goods['goods_name'],
  2392. 'member_benefit_limit_count' => $params['order_sheet_num'],
  2393. 'member_benefit_used_count' => 0,
  2394. 'member_benefit_remark' => $params['order_remark'] ?? '',
  2395. 'member_benefit_addtimes' => time()
  2396. ];
  2397. MemberBenefit::insert($data);
  2398. } catch (\Exception $e) {
  2399. dump($e->getMessage());
  2400. throw new BusinessException('创建会员权益失败');
  2401. }
  2402. }
  2403. public function saveExpress($params, $orderId)
  2404. {
  2405. try {
  2406. $express = new OrderExpress();
  2407. $express->order_express_type = $params['order_express_type'];
  2408. $express->join_express_order_id = $orderId;
  2409. $express->join_express_dept_id = $params['submit_premises_id'] ?? 0;
  2410. $express->order_express_goods = $params['order_express_goods'];
  2411. $express->order_express_city = $params['order_express_city'];
  2412. $express->order_express_address = $params['order_express_address'];
  2413. $express->order_express_mobile = $params['order_express_mobile'] ?? '';
  2414. $express->order_express_telephone = $params['order_express_telephone'] ?? '';
  2415. $express->order_express_person = $params['order_express_person'] ?? '';
  2416. $express->order_express_company = $params['dept_premises_id'] ?? '';
  2417. $express->order_express_extend_json = $params['order_express_extend_json'] ?? '[]';
  2418. $express->order_express_addtimes = time();
  2419. $express->save();
  2420. } catch (\Exception $e) {
  2421. dump($e->getMessage());
  2422. throw new BusinessException('物流信息保存失败');
  2423. }
  2424. }
  2425. /**
  2426. * @Desc 修改优惠券状态
  2427. * @Author Gorden
  2428. * @Date 2024/9/19 9:03
  2429. *
  2430. * @param $coupon
  2431. * @param $status
  2432. * @return void
  2433. */
  2434. private function changeOrderCouponStatus($coupon, $status)
  2435. {
  2436. if (!empty($coupon) && is_array($coupon)) {
  2437. $updateData['coupon_detail_status'] = $status;
  2438. if ($status == 'ACTIVED' || $status == 'WAITING') {
  2439. $updateData['coupon_detail_used_datetime'] = '';
  2440. } elseif ($status == 'USED') {
  2441. $updateData['coupon_detail_used_datetime'] = date('Y-m-d H:i:s');
  2442. }
  2443. foreach ($coupon as $item) {
  2444. if (!empty($item['coupon_id']) && !empty($item['coupon_detail_id'])) {
  2445. foreach ($item['coupon_detail_id'] as $detailId) {
  2446. CouponDetail::where('join_detail_coupon_id', $item['coupon_id'])
  2447. ->where('coupon_detail_id', $detailId)->update($updateData);
  2448. }
  2449. }
  2450. }
  2451. }
  2452. }
  2453. private function discountRecord($orderDiscountJson, $params)
  2454. {
  2455. $json = [];
  2456. if (!empty($orderDiscountJson)) {
  2457. $json = json_decode($orderDiscountJson, true);
  2458. }
  2459. try {
  2460. if (!empty($params['preferential']) && in_array('wipe', $params['preferential'])) {
  2461. if (intval($params['order_amount_total'] / 10) * 10 != $params['order_amount_pay']) {
  2462. throw new BusinessException("抹零后实际支付金额错误");
  2463. }
  2464. $params['order_discount_amount'] = $params['order_amount_total'] - $params['order_amount_pay'];
  2465. $couponClassifyDesc = $couponClassify = '抹零';
  2466. } elseif (!empty($params['preferential']) && in_array('custom', $params['preferential'])) {
  2467. if (sprintf("%.2f", $params['order_amount_total'] - $params['order_discount_amount']) != sprintf("%.2f", $params['order_amount_pay'])) {
  2468. throw new BusinessException("餐厅前台优惠后实际支付金额错误");
  2469. }
  2470. $couponClassifyDesc = $couponClassify = '餐厅前台优惠';
  2471. } else if (!empty($params['preferential']) && intval($params['preferential'][0]) < 100 && intval($params['preferential'][0]) >= 50) {
  2472. if (($params['order_amount_total'] * intval($params['preferential'][0])) / 100 != $params['order_amount_pay']) {
  2473. throw new BusinessException("折扣后实际支付金额错误");
  2474. }
  2475. $couponClassify = '折扣';
  2476. $couponClassifyDesc = intval($params['preferential'][0]) / 10 . '折';
  2477. $params['order_discount_amount'] = $params['order_amount_total'] - $params['order_amount_pay'];
  2478. } else {
  2479. return $json;
  2480. }
  2481. $json[date('Y-m-d H:i:s')] = [
  2482. 'coupon_id' => $params['coupon_id'] ?? null,
  2483. 'coupon_value' => $params['order_discount_amount'] ?? '',
  2484. 'coupon_classify' => $couponClassify,
  2485. 'coupon_detail_id' => [$couponClassifyDesc],
  2486. 'coupon_classify_en' => $params['preferential']
  2487. ];
  2488. return $json;
  2489. } catch (BusinessException $e) {
  2490. throw new BusinessException($e->getMessage());
  2491. } catch (\Exception $e) {
  2492. dump($e->getMessage());
  2493. throw new BusinessException("优惠数据错误");
  2494. }
  2495. }
  2496. /**
  2497. * @Desc 入配送记录
  2498. * @Author Gorden
  2499. * @Date 2024/9/23 10:45
  2500. *
  2501. * @param $params
  2502. * @return void
  2503. * @throws BusinessException
  2504. */
  2505. public function insertExpressOne($params, $orderId)
  2506. {
  2507. if (isset($params['delivery']) && $params['delivery'] == 'LOGISTICS') {
  2508. $params['order_express_type'] = '配送';
  2509. // 入配送
  2510. $this->saveExpress($params, $orderId);
  2511. } else if (isset($params['delivery']) && $params['delivery'] == 'PICKUP') {
  2512. $params['order_express_type'] = '自提';
  2513. $premises = SysDept::where('dept_name', $params['dept_premises_id'])->first();
  2514. if (!$premises) {
  2515. throw new BusinessException('自提门店不存在');
  2516. }
  2517. $params['order_express_city'] = $premises->dept_city;
  2518. $params['order_express_address'] = $premises->dept_address;
  2519. $params['order_express_telephone'] = $premises->dept_telephone;
  2520. $params['order_express_extend_json'] = json_encode(['pick_code' => random_string(4, 'number')]);
  2521. $this->saveExpress($params, $orderId);
  2522. } else if (isset($params['delivery']) && $params['delivery'] == 'ARRIVAL') {
  2523. $premises = SysDept::where('dept_name', $params['dept_premises_id'])->first();
  2524. $params['order_express_type'] = '到店';
  2525. if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') {
  2526. $params['order_express_type'] = '堂食';
  2527. }
  2528. if (!$premises) {
  2529. throw new BusinessException('门店不存在');
  2530. }
  2531. $params['order_express_city'] = $premises->dept_city;
  2532. $params['order_express_address'] = $premises->dept_address;
  2533. $params['order_express_telephone'] = $premises->dept_telephone;
  2534. $this->saveExpress($params, $orderId);
  2535. }
  2536. }
  2537. /**
  2538. * @Desc 释放下单时选的优惠券
  2539. * @Author Gorden
  2540. * @Date 2024/9/19 9:56
  2541. *
  2542. * @param $coupon
  2543. * @return false|string
  2544. */
  2545. private function releaseCoupon($coupon)
  2546. {
  2547. if (!empty($coupon) && is_array($coupon)) {
  2548. $updateData = [
  2549. 'coupon_detail_status' => 'ACTIVED',
  2550. 'coupon_detail_used_datetime' => ''
  2551. ];
  2552. foreach ($coupon as $key => $item) {
  2553. if (!empty($item['coupon_id']) && !empty($item['coupon_detail_id'])) {
  2554. foreach ($item['coupon_detail_id'] as $detailId) {
  2555. if (substr($detailId, 0, 4) == 'CUDT') {
  2556. CouponDetail::where('join_detail_coupon_id', $item['coupon_id'])
  2557. ->where('coupon_detail_id', $detailId)
  2558. ->where('coupon_detail_status', 'WAITING')
  2559. ->update($updateData);
  2560. }
  2561. }
  2562. unset($coupon[$key]);
  2563. }
  2564. }
  2565. }
  2566. return json_encode($coupon);
  2567. }
  2568. }