PackagesController.php 134 KB

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