PackagesController.php 141 KB

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