PackagesController.php 133 KB

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