PackagesController.php 138 KB

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