PackagesController.php 137 KB

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