ServicesController.php 131 KB

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