PackagesController.php 134 KB

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