ServicesController.php 131 KB

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