PackagesController.php 136 KB

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