12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847 |
- <?php
- namespace app\admin\controller\order;
- use app\admin\service\coupon\CouponDetailService;
- use app\admin\service\coupon\CouponService;
- use app\admin\service\member\MemberService;
- use app\admin\service\order\OrderService;
- use app\admin\service\order\OrderSheetService;
- use app\admin\service\order\PayDetailService;
- use app\admin\validate\order\OrderValidate;
- use app\controller\Curd;
- use app\model\Appointment;
- use app\model\Card;
- use app\model\ClientConfig;
- use app\model\Coupon;
- use app\model\CouponDetail;
- use app\model\Goods;
- use app\model\GoodsComponent;
- use app\model\GoodsRunning;
- use app\model\GoodsSku;
- use app\model\Member;
- use app\model\MemberAccount;
- use app\model\MemberBenefit;
- use app\model\MemberRole;
- use app\model\Order;
- use app\model\OrderExpress;
- use app\model\OrderReturn;
- use app\model\OrderSheet;
- use app\model\PayDetail;
- use app\model\Supplier;
- use app\model\SysDept;
- use app\model\SysUser;
- use support\Db;
- use support\exception\BusinessException;
- use support\Log;
- use support\Redis;
- use support\Request;
- use support\Response;
- use Tinywan\Jwt\JwtToken;
- use Webman\Event\Event;
- use Yansongda\Pay\Pay;
- class CardController extends Curd
- {
- public function __construct()
- {
- $this->model = new Order();
- $this->validate = true;
- $this->validateClass = new OrderValidate();
- }
- /**
- * @Desc 列表
- * @Author Gorden
- * @Date 2024/3/28 15:01
- *
- * @param Request $request
- * @return Response
- * @throws \support\exception\BusinessException
- */
- public function select(Request $request): Response
- {
- $timeType = $request->get('time_type', 'add');
- [$where, $format, $limit, $field, $order] = $this->selectInput($request);
- $where['order_classify'] = 'CARD';
- if (!empty($where['order_addtimes']) && $timeType == 'add') {
- $where['order_addtimes'][0] = strtotime($where['order_addtimes'][0]);
- $where['order_addtimes'][1] = strtotime($where['order_addtimes'][1]);
- }
- $order = $request->get('order', 'desc');
- $orderId = $request->get('orderId');
- $field = $field ?? 'order_addtimes';
- $orderIds = [];
- if (!empty($orderId)) {
- $orderIds = Order::where('order_id', 'like', '%' . $orderId . '%')
- ->where('order_classify', 'CARD')
- ->pluck('order_id')
- ->toArray();
- }
- $goodsName = trim($request->get('goods_name', ''));
- if (!empty($goodsName)) {
- $goodsIds = Goods::where('goods_classify', 'CARD')
- ->where('goods_name', 'like', '%' . $goodsName . '%')
- ->pluck('goods_id')
- ->toArray();
- $goodsOrderIds = OrderSheet::whereIn('join_sheet_goods_id', $goodsIds)->pluck('join_sheet_order_id')->toArray();
- if (!empty($where['order_id'])) {
- $orderIds = array_intersect($orderIds, $goodsOrderIds);
- } else {
- $orderIds = $goodsOrderIds;
- }
- }
- // 付款时间
- $payOrderIds = [];
- if ($timeType == 'pay' && !empty($where['order_addtimes'])) {
- $payTimeStart = strtotime($where['order_addtimes'][0]);
- $payTimeEnd = strtotime($where['order_addtimes'][1]);
- unset($where['order_addtimes']);
- $payOrderIds = PayDetailService::getPayOrderId($payTimeStart, $payTimeEnd, ['CARD']);
- }
- if ((!empty($orderId) || !empty($goodsName)) && $timeType == 'pay') {
- $orderIds = array_intersect($orderIds, $payOrderIds);
- $where['order_id'] = ['in', implode(',', $orderIds)];
- } elseif (!empty($orderId) || !empty($goodsName)) {
- $where['order_id'] = ['in', implode(',', $orderIds)];
- } elseif ($timeType == 'pay') {
- $where['order_id'] = ['in', implode(',', $payOrderIds)];
- }
- $query = $this->doSelect($where, $field, $order);
- return $this->doFormat($query, $format, $limit);
- }
- protected function doSelect(array $where, string $field = null, string $order = 'desc')
- {
- $model = $this->model->with([
- 'sheets' => function ($query) {
- $query->select('join_sheet_order_id', 'order_sheet_id', 'join_sheet_goods_id', 'order_sheet_num', 'order_sheet_price');
- },
- 'member' => function ($query) {
- $query->select('member_id', 'member_mobile', 'join_invite_member_id');
- },
- 'cert' => function ($query) {
- $query->select('join_cert_member_id', 'member_cert_name');
- },
- ])->leftJoin('order_return', 'order_return.join_return_order_id', '=', 'order.order_id')
- ->leftJoin('order_express', 'order_express.join_express_order_id', '=', 'order.order_id');
- foreach ($where as $column => $value) {
- if (is_array($value)) {
- if ($value[0] === 'like' || $value[0] === 'not like') {
- $model = $model->where($column, $value[0], "%$value[1]%");
- } elseif (in_array($value[0], ['>', '=', '<', '<>'])) {
- $model = $model->where($column, $value[0], $value[1]);
- } elseif ($value[0] == 'in' && !empty($value[1])) {
- $valArr = $value[1];
- if (is_string($value[1])) {
- $valArr = explode(",", trim($value[1]));
- }
- $model = $model->whereIn($column, $valArr);
- } elseif ($value[0] == 'not in' && !empty($value[1])) {
- $valArr = $value[1];
- if (is_string($value[1])) {
- $valArr = explode(",", trim($value[1]));
- }
- $model = $model->whereNotIn($column, $valArr);
- } elseif ($value[0] == 'null') {
- $model = $model->whereNull($column);
- } elseif ($value[0] == 'not null') {
- $model = $model->whereNotNull($column);
- } elseif ($value[0] !== '' || $value[1] !== '') {
- $model = $model->whereBetween($column, $value);
- }
- } else {
- $model = $model->where($column, $value);
- }
- }
- if ($field) {
- $model = $model->orderBy($field, $order);
- }
- $model = $model->select('order.*', 'order_express.join_express_order_id', 'order_express.order_express_type', 'order_return.orders_return_id', 'order_return.join_return_order_id', 'order_return.order_return_status', 'order_return.order_return_apply_json', 'order_return.order_return_remark');
- return $model;
- }
- public function afterQuery($items)
- {
- foreach ($items as &$item) {
- $sheetDeng = '';
- $item['sheet'] = $item['sheets'][0] ?? [];
- if (!empty($item['sheet'])) {
- $goods = Goods::where('goods_id', $item['sheet']['join_sheet_goods_id'])->first();
- $item['sheet']['goods_name'] = ($goods && $goods->goods_name) ? $goods->goods_name . $sheetDeng : '';
- $item['sheet']['goods_classify'] = $goods->goods_classify ?? '';
- $item['sheet']['order_sheet_num'] = intval($item['sheet']['order_sheet_num']);
- }
- unset($item['sheets']);
- if (isset($item['orders_return_id'])) {
- $item['return'] = [
- 'orders_return_id' => $item['orders_return_id'],
- 'join_return_order_id' => $item['join_return_order_id'],
- 'order_return_status' => $item['order_return_status'],
- 'order_return_apply_json' => $item['order_return_apply_json'],
- 'order_return_remark' => $item['order_return_remark']
- ];
- }
- if (isset($item['join_express_order_id'])) {
- $item['express'] = [
- 'join_express_order_id' => $item['join_express_order_id'],
- 'order_express_type' => $item['order_express_type']
- ];
- unset($item['join_express_order_id'], $item['order_express_type']);
- }
- if (!empty($item['member']['join_invite_member_id'])) {
- $inviteMember = Member::with([
- 'cert' => function ($query) {
- $query->select('join_cert_member_id', 'member_cert_name');
- }
- ])->where('member_id', $item['member']['join_invite_member_id'])
- ->first();
- $inviteMobile = $inviteMember['member_mobile'] ?? '';
- $inviteCertName = !empty($inviteMember['cert']) && !empty($inviteMember['cert']['member_cert_name']) ? $inviteMember['cert']['member_cert_name'] : '';
- $item['invite_name'] = MemberService::getMemberCertName($inviteMobile, $inviteCertName, '');
- }
- $item['payDetail'] = PayDetailService::getPayWay($item['order_groupby'], $item['order_id']);
- }
- return $items;
- }
- /**
- * @Desc 获取卡列表
- * @Author Gorden
- * @Date 2024/11/22 15:33
- *
- * @param Request $request
- * @return Response
- */
- public function getCardList(Request $request)
- {
- $orderId = $request->get('order_id');
- $goodsId = OrderSheet::where('join_sheet_order_id', $orderId)->value('join_sheet_goods_id');
- $goods = Goods::where('goods_id', $goodsId)->select('goods_attribute_json')->first();
- $cards = [];
- if (!empty($goods->goods_attribute_json)) {
- $goodsAttributeJson = json_decode($goods->goods_attribute_json, true);
- if (!empty($goodsAttributeJson['card_main_id'])) {
- $cards = Card::where('join_card_main_id', $goodsAttributeJson['card_main_id'])
- ->where('card_status', 'WAITING')
- ->where('is_issue', 'Y')
- ->pluck('card_id')
- ->toArray();
- }
- }
- return json_success('success', $cards);
- }
- /**
- * @Desc 下单+支付
- * @Author Gorden
- * @Date 2024/9/23 16:15
- *
- * @param Request $request
- * @return Response
- */
- public function insert(Request $request): Response
- {
- $params = $request->post();
- // 判断餐品是否连带着服务或实体
- $goodsClassifys = array_unique(array_column($params['goodsContentList'], 'goods_classify'));
- $premises = [];
- if (!empty($params['dept_premises_id'])) {
- $premises = SysDept::where('dept_name', $params['dept_premises_id'])->first();
- }
- try {
- // 下单账户
- if (empty($params['join_order_member_id']) && !empty($params['mobile'])) {
- if (Member::where('member_mobile', $params['mobile'])->exists()) {
- throw new BusinessException('会员已存在');
- }
- $params['join_order_member_id'] = $params['member_id'] = 'MR' . date('ymdHi') . random_string(4, 'up');
- // 创建会员
- MemberService::createMember($params);
- } else if (empty($params['join_order_member_id']) && empty($params['mobile'])) {
- $params['join_order_member_id'] = Member::where('member_mobile', '0000')->value('member_id');
- }
- if (empty($params['join_order_member_id'])) {
- throw new BusinessException('检查下单账户');
- }
- // 带着优惠券,要发券
- if (!empty($params['custom_member_id'])) {
- // 把券从000000加到真实账户
- CouponDetailService::transCoupon('000000', $params['join_order_member_id']);
- }
- } catch (BusinessException $e) {
- Log::error('创建订单失败', ['msg' => $e->getMessage()]);
- _syslog("订单", $e->getMessage());
- return json_fail($e->getMessage());
- } catch (\Exception $e) {
- Log::error('创建订单失败', ['msg' => $e->getMessage()]);
- _syslog("订单", "创建订单失败");
- return json_fail('创建订单失败');
- }
- $params['goods_classify'] = $goodsClassifys[0];
- Db::beginTransaction();
- try {
- // 使用优惠券
- $couponUseJson = [];
- if (!empty($params['join_order_member_id']) && !empty($params['preferential'])) {
- $couponResult = OrderService::payUseCoupon('insert', $params['settlement_now'], $params['join_order_member_id'], $params['goodsContentList'], $params['preferential'], $params['order_amount_total']);
- if (!empty($couponResult['pay_amount']) && $couponResult['pay_amount'] != $params['order_amount_pay']) {
- throw new BusinessException("计算优惠后,实付金额错误!");
- }
- // 组装优惠券使用数据,存主表优惠里
- if (!empty($couponResult['use_coupon_json'])) {
- $couponUseJson = $couponResult['use_coupon_json'];
- }
- }
- // 存储优惠信息
- $params['order_discount_json'] = json_encode($this->discountRecord($couponUseJson, $params));
- // 验证库存
- foreach ($params['goodsContentList'] as $goods) {
- $goodsRunning = GoodsRunning::where('join_running_goods_id', $goods['goods_id'])->first();
- dump($goodsRunning);
- $goodsRunning->goods_running_storage = $goodsRunning->goods_running_storage - $goods['nbr'];
- if ($goodsRunning->goods_running_storage < 0) {
- throw new BusinessException('库存不足');
- }
- }
- // 验证线下付款密码
- if ($params['settlement_now'] == 'Y' && $params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['OFFLINE', 'MONEY'])) {
- $password = $params['offline_password'];
- if ($password != '666888') {
- throw new BusinessException('密码错误,请重新输入');
- }
- }
- $qrcodePayAmount = 0;
- $params['orderId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
- $params['orderGroupId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
- $systemStatus = 'SENDING'; // 待发货
- if ($params['settlement_now'] == 'Y' && ($params['pay_category'] == 'OFFLINE' || $params['pay_category'] == 'MONEY')) {
- if ($params['pay_category'] == 'OFFLINE' && !empty($params['pay_category_sub'])) {
- $params['pay_category'] = $params['pay_category_sub'];
- }
- $params['order_status_system'] = $systemStatus;
- $params['order_status_payment'] = 'SUCCESS';
- }
- if (($params['pay_constitute'] == 'Y' || $params['pay_category'] == 'QRCODE') && $params['settlement_now'] == 'Y' && !empty($params['qrcode_nbr'])) { // 付款码
- if ($params['pay_constitute'] == 'Y' && $qrcodePayAmount <= 0) {
- $params['order_status_system'] = $systemStatus;
- $params['order_status_payment'] = 'SUCCESS';
- }
- // 不组合或者组合后需要付款码的金额>0
- if ($params['pay_constitute'] == 'N' || ($params['pay_constitute'] == 'Y' && $qrcodePayAmount > 0)) {
- $result = OrderService::qrcodePay($params);
- $result = json_encode($result);
- $params['pay_json_response'] = $result;
- $result = json_decode($result, true);
- $prefix = substr($params['qrcode_nbr'], 0, 2);
- if (in_array($prefix, [10, 11, 12, 13, 14, 15])) {
- $params['pay_category'] = 'WXPAY';
- 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')) {
- $params['order_status_system'] = 'PAYING';
- $params['order_status_payment'] = 'PENDING';
- $params['order_is_complete'] = 'N';
- } else {
- $params['order_status_system'] = $systemStatus;
- $params['order_status_payment'] = 'SUCCESS';
- }
- } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) {
- $params['pay_category'] = 'ALIPAY';
- if ((!isset($result['code']) || $result['code'] != '10000') || (empty($result['trade_status']) || $result['trade_status'] != 'TRADE_SUCCESS')) {
- $params['order_status_system'] = 'PAYING';
- $params['order_status_payment'] = 'PENDING';
- $params['order_is_complete'] = 'N';
- } else {
- $params['order_status_system'] = $systemStatus;
- $params['order_status_payment'] = 'SUCCESS';
- }
- } else {
- throw new BusinessException('付款码无效');
- }
- }
- }
- $orderConfigJson = [];
- // 优惠
- if (!empty($params['preferential'])) {
- $orderConfigJson['preferential'] = $params['preferential'];
- }
- // 配送方式
- if (isset($params['delivery']) && ($params['delivery'] == 'PICKUP' || $params['delivery'] == 'ARRIVAL')) { // 自提/ 到店
- $orderConfigJson['premises'] = $params['dept_premises_id'];
- }
- if (isset($params['delivery']) && in_array($params['delivery'], ['PICKUP', 'ARRIVAL']) && !empty($params['dept_premises_id'])) {
- $params['submit_premises_id'] = $premises->dept_id;
- }
- $params['order_config_json'] = json_encode($orderConfigJson);
- // 写入订单
- $this->insertMain($params);
- Db::commit();
- // 触发事件
- if (!empty($params['order_is_complete']) && $params['order_is_complete'] == 'Y' && $params['order_status_payment'] == 'SUCCESS') {
- Event::dispatch('order.complete', $params);
- }
- // 触发事件
- if ($params['order_status_payment'] == 'SUCCESS') {
- // 上级提成
- OrderService::splitOrderCommission($params);
- // 入收支明细表
- $params['inout_category'] = '购买储值卡';
- Event::dispatch('statistics.inout.in', $params);
- }
- if ($params['settlement_now'] == 'Y' && $params['order_status_payment'] != 'SUCCESS') {
- _syslog("订单", "支付异常,检查是否有轮询");
- return json_throw(2001, '支付异常', ['order_id' => $params['orderId'], 'group_id' => $params['orderGroupId']]);
- }
- _syslog("订单", "创建订单成功");
- return json_success('创建订单成功');
- } catch (BusinessException $e) {
- Db::rollBack();
- Log::error('创建订单失败', ['msg' => $e->getMessage()]);
- _syslog("订单", $e->getMessage());
- return json_fail($e->getMessage());
- } catch (\Exception $e) {
- Db::rollBack();
- Log::error('创建订单失败', ['msg' => $e->getMessage()]);
- _syslog("订单", "创建订单失败");
- return json_fail('创建订单失败');
- }
- }
- public function pay(Request $request)
- {
- $params = $request->post();
- // 余额、福利、储值卡 验证短信
- if ($params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['CASH', 'CARD', 'WELFARE'])) {
- $code = $params['sms_code'];
- if (!$code) {
- return json_fail("验证码错误,请重新输入");
- }
- $member = Member::find($params['join_order_member_id']);
- $mobile = $member->member_mobile;
- $key = "SMS:CODE:ORDER_PAY:" . $mobile;
- $redisCode = Redis::get($key);
- if ($redisCode != $code && $code != '123654879') {
- return json_fail("验证码错误,请重新输入");
- }
- Redis::del($key);
- }
- // 验证线下付款密码
- if ($params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['OFFLINE', 'MONEY'])) {
- $password = $params['offline_password'];
- if ($password != '666888') {
- return json_fail("密码错误,请重新输入");
- }
- }
- $order = Order::where('order_id', $params['order_id'])->first();
- $oldOrderStatus = $order->order_status_system;
- if (!$order) {
- return json_fail('订单异常');
- }
- if ($order->order_status_system != 'PAYING') {
- return json_fail('订单不是可支付状态');
- }
- if (!empty($order->order_config_json)) {
- $orderConfigJson = json_decode($order->order_config_json, true);
- if (isset($orderConfigJson['premises'])) {
- $premises = SysDept::where('dept_name', $orderConfigJson['premises'])->first();
- if (!empty($premises)) {
- $params['submit_premises_id'] = $premises->dept_id;
- }
- }
- }
- $params['orderId'] = $params['order_id'];
- $params['orderGroupId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
- $order->order_groupby = $params['orderGroupId'];
- $goods = Goods::where('goods_id', $params['join_sheet_goods_id'])
- ->select('goods_id', 'goods_name', 'goods_classify')
- ->first();
- if (!$goods) {
- return json_fail('产品数据异常');
- }
- $goods = $goods->toArray();
- $params['goods_classify'] = $goods['goods_classify'] ?? '';
- $systemStatus = 'SENDING'; // 待发货
- // 立即结算
- if (in_array($params['goods_classify'], ['MEALS', 'VIP'])) {
- $order->order_is_complete = 'Y';
- $systemStatus = 'DONE';
- }
- if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE']) && $params['delivery'] == 'ARRIVAL') {
- $params['order_is_complete'] = 'N';
- $systemStatus = "WAITING";
- }
- Db::beginTransaction();
- try {
- // 使用优惠券
- $couponUseJson = [];
- $discountJson = [];
- if (!empty($order->order_discount_json)) {
- $discountJson = json_decode($order->order_discount_json, true);
- foreach ($discountJson as $item) {
- if (isset($item['coupon_value']) && sprintf('%.2f', (floatval($order->order_amount_total) - floatval($params['order_amount_pay']))) != sprintf('%.2f', $item['coupon_value'])) {
- throw new BusinessException("计算优惠后,实付金额错误!");
- }
- }
- $couponUseJson = $discountJson;
- $this->changeOrderCouponStatus($couponUseJson, 'USED');
- }
- if (empty($discountJson) && !empty($params['join_order_member_id']) && !empty($params['preferential'])) {
- $couponResult = OrderService::payUseCoupon('pay', 'Y', $params['join_order_member_id'], $params['goodsContentList'], $params['preferential'], $params['order_amount_total']);
- if (!empty($couponResult['pay_amount']) && $couponResult['pay_amount'] != $params['order_amount_pay']) {
- throw new BusinessException("计算优惠后,实付金额错误!");
- }
- // 组装优惠券使用数据,存主表优惠里
- if (!empty($couponResult['use_coupon_json'])) {
- $couponUseJson = $couponResult['use_coupon_json'];
- }
- }
- // 存储优惠信息
- if (empty($discountJson)) {
- $order->order_discount_json = json_encode($this->discountRecord($couponUseJson, $params));
- }
- // 组合支付时,付款码应收金额
- $qrcodePayAmount = 0;
- if ($params['pay_category'] == 'OFFLINE' || $params['pay_category'] == 'MONEY') {
- $order->order_status_system = $systemStatus;
- $order->order_status_payment = 'SUCCESS';
- if ($params['pay_category'] == 'OFFLINE' && !empty($params['pay_category_sub'])) {
- $params['pay_category'] = $params['pay_category_sub'];
- }
- } else if ($params['pay_category'] == 'CASH') { // 余额支付
- $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
- ->where('member_account_classify', 'CASH')
- ->where('member_account_status', 'ACTIVED')
- ->first();
- if (!$account) {
- throw new BusinessException('账户异常');
- }
- $amount = $account->member_account_surplus + $account->member_account_added;
- if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
- throw new BusinessException('账户余额不足');
- }
- if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) {
- $qrcodePayAmount = $params['order_amount_pay'] - $amount;
- $params['order_amount_pay'] = $amount;
- }
- if ($params['order_amount_pay'] > $account->member_account_surplus) {
- $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
- $account->member_account_surplus = 0;
- $account->member_account_added = $cut;
- } else {
- $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
- }
- $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
- $account->member_account_update_user_id = JwtToken::getCurrentId();
- $account->member_account_updatetimes = time();
- $account->save();
- if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] <= $amount)) {
- $order->order_status_system = $systemStatus;
- $order->order_status_payment = 'SUCCESS';
- }
- } else if ($params['pay_category'] == 'VIP') { // 余额支付
- $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
- ->where('member_account_classify', 'VIP')
- ->where('member_account_status', 'ACTIVED')
- ->first();
- if (!$account) {
- throw new BusinessException('账户异常');
- }
- $amount = $account->member_account_surplus + $account->member_account_added;
- if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
- throw new BusinessException('账户余额不足');
- }
- if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) {
- $qrcodePayAmount = $params['order_amount_pay'] - $amount;
- $params['order_amount_pay'] = $amount;
- }
- if ($params['order_amount_pay'] > $account->member_account_surplus) {
- $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
- $account->member_account_surplus = 0;
- $account->member_account_added = $cut;
- } else {
- $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
- }
- $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
- $account->member_account_update_user_id = JwtToken::getCurrentId();
- $account->member_account_updatetimes = time();
- $account->save();
- if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] <= $amount)) {
- $order->order_status_system = $systemStatus;
- $order->order_status_payment = 'SUCCESS';
- }
- } else if ($params['pay_category'] == 'WELFARE') { // 福利账户
- $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
- ->where('member_account_classify', 'WELFARE')
- ->where('member_account_status', 'ACTIVED')
- ->first();
- if (!$account) {
- throw new BusinessException('账户异常');
- }
- $account->member_account_surplus = floatval($account->member_account_surplus);
- if ($params['pay_constitute'] == 'N' && ($params['order_amount_pay'] > $account->member_account_surplus)) {
- throw new BusinessException('账户余额不足');
- }
- if ($params['pay_constitute'] == 'Y' && ($params['order_amount_pay'] > $account->member_account_surplus)) {
- $qrcodePayAmount = $params['order_amount_pay'] - $account->member_account_surplus;
- $params['order_amount_pay'] = $account->member_account_surplus;
- }
- if ($params['pay_constitute'] == 'N' && ($params['order_amount_pay'] <= $account->member_account_surplus)) {
- $order->order_status_system = $systemStatus;
- $order->order_status_payment = 'SUCCESS';
- }
- // 福利账户 300 、 700
- if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS'])) {
- $payDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
- ->where('pay_status', 'SUCCESS')
- ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
- ->whereIn('pay_category', ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'DESHES'])
- ->get()
- ->toArray();
- $payDetailArray = array_column($payDetails, 'pay_amount', 'join_pay_order_id');
- $refundPayDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
- ->where('pay_status', 'SUCCESS')
- ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
- ->where('pay_category', 'REFUND')
- ->get()
- ->toArray();
- $refundPayDetailArray = array_column($refundPayDetails, 'pay_amount', 'join_pay_order_id');
- $paySum = 0;
- foreach ($payDetailArray as $key => $item) {
- if (isset($refundPayDetailArray[$key])) {
- $paySum = $paySum + ($item - $refundPayDetailArray[$key]);
- continue;
- }
- $paySum = $paySum + $item;
- }
- if ($params['pay_constitute'] == 'N' && 700 - $paySum < $params['order_amount_pay']) {
- throw new BusinessException('超出福利限额');
- } else if ($params['pay_constitute'] == 'Y' && 700 - $paySum < $params['order_amount_pay']) {
- $qrcodePayAmount = $params['order_amount_pay'] - (700 - $paySum);
- $params['order_amount_pay'] = (700 - $paySum);
- }
- } else {
- $payDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
- ->where('pay_status', 'SUCCESS')
- ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
- ->whereNotIn('pay_category', ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'DESHES', 'REFUND', 'RECHARGE'])
- ->get()
- ->toArray();
- $payDetailArray = array_column($payDetails, 'pay_amount', 'join_pay_order_id');
- $refundPayDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
- ->where('pay_status', 'SUCCESS')
- ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
- ->where('pay_category', 'REFUND')
- ->get()
- ->toArray();
- $refundPayDetailArray = array_column($refundPayDetails, 'pay_amount', 'join_pay_order_id');
- $paySum = 0;
- foreach ($payDetailArray as $key => $item) {
- if (isset($refundPayDetailArray[$key])) {
- $paySum = $paySum + ($item - $refundPayDetailArray[$key]);
- continue;
- }
- $paySum = $paySum + $item;
- }
- if ($params['pay_constitute'] == 'N' && 300 - $paySum < $params['order_amount_pay']) {
- throw new BusinessException('超出福利限额');
- } else if ($params['pay_constitute'] == 'Y' && 300 - $paySum < $params['order_amount_pay']) {
- $qrcodePayAmount = $params['order_amount_pay'] - (300 - $paySum);
- $params['order_amount_pay'] = (300 - $paySum);
- }
- }
- $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
- $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
- $account->member_account_update_user_id = JwtToken::getCurrentId();
- $account->member_account_updatetimes = time();
- $account->save();
- } else if ($params['pay_category'] == 'CARD') { // 储值卡账户
- $cardNbr = $params['card_id'];
- if (!$cardNbr) {
- throw new BusinessException('账户异常');
- }
- $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
- ->where('member_account_nbr', $cardNbr)
- ->where('member_account_status', 'ACTIVED')
- ->first();
- if (!$account) {
- throw new BusinessException('账户异常');
- }
- $amount = $account->member_account_surplus + $account->member_account_added;
- if ($params['order_amount_pay'] > $amount) {
- throw new BusinessException('账户余额不足');
- }
- if ($params['order_amount_pay'] > $account->member_account_surplus) {
- $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
- $account->member_account_surplus = 0;
- $account->member_account_added = $cut;
- } else {
- $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
- }
- $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
- $account->member_account_update_user_id = JwtToken::getCurrentId();
- $account->member_account_updatetimes = time();
- $account->save();
- $order->order_status_system = $systemStatus;
- $order->order_status_payment = 'SUCCESS';
- }
- if (($params['pay_constitute'] == 'Y' || $params['pay_category'] == 'QRCODE') && !empty($params['qrcode_nbr'])) { // 付款码
- // 提交过来的支付分类
- $submitPayCategory = $params['pay_category'];
- // 账户支付的金额
- $accountAmount = $params['order_amount_pay'];
- if ($params['pay_constitute'] == 'Y' && $qrcodePayAmount > 0) {
- // 组合支付,改成需要付款码需要支付的金额
- $params['order_amount_pay'] = $qrcodePayAmount;
- }
- // 去支付
- $result = OrderService::qrcodePay($params);
- $result = json_encode($result);
- $params['pay_json_response'] = $result;
- $result = json_decode($result, true);
- $prefix = substr($params['qrcode_nbr'], 0, 2);
- if (in_array($prefix, [10, 11, 12, 13, 14, 15])) {
- $params['pay_category'] = 'WXPAY';
- 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')) {
- $order->order_status_system = $oldOrderStatus;
- $order->order_status_payment = 'PENDING';
- $order->order_is_complete = 'N';
- // Db::rollBack();
- // return json_fail('支付失败');
- } else {
- $order->order_status_system = $systemStatus;
- $order->order_status_payment = 'SUCCESS';
- }
- } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) {
- $params['pay_category'] = 'ALIPAY';
- if ((!isset($result['code']) || $result['code'] != '10000') || (empty($result['trade_status']) || $result['trade_status'] != 'TRADE_SUCCESS')) {
- $order->order_status_system = $oldOrderStatus;
- $order->order_status_payment = 'PENDING';
- $order->order_is_complete = 'N';
- // Db::rollBack();
- // return json_fail('支付失败');
- } else {
- $order->order_status_system = $systemStatus;
- $order->order_status_payment = 'SUCCESS';
- }
- } else {
- throw new BusinessException('付款码无效');
- }
- // 账户支付的金额
- $params['order_amount_pay'] = $accountAmount;
- }
- $orderConfigJson = [];
- if (!empty($order->order_config_json)) {
- $orderConfigJson = json_decode($order->order_config_json, true);
- }
- $orderConfigJson['preferential'] = $params['preferential'] ?? '';
- $order->order_config_json = json_encode($orderConfigJson);
- $order->order_amount_pay = $params['order_amount_pay'] + $qrcodePayAmount;
- // 主订单
- $order->save();
- // sheet
- if ($order->order_status_payment == 'SUCCESS') {
- OrderSheet::where('join_sheet_order_id', $params['order_id'])->update([
- 'order_sheet_status' => $systemStatus,
- ]);
- }
- // payDetail
- // 不组合支付,那就只有一条支付记录 先删,再加
- PayDetail::where('join_pay_order_id', $order->order_groupby)
- ->whereJsonContains('join_pay_object_json->order_id', $params['orderId'])
- ->delete();
- $payData = [
- 'pay_amount' => $params['order_amount_pay']
- ];
- if ($order->order_status_payment == 'SUCCESS') {
- $payData['pay_paytimes'] = date('Y-m-d H:i:s');
- $payData['pay_status'] = 'SUCCESS';
- }
- if ($params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['WXPAY', 'ALIPAY'])) {
- $payData['pay_prepayid'] = $params['pay_category'];
- $payData['pay_json_response'] = $params['pay_json_response'];
- } else if ($params['pay_category'] == 'CASH') {
- $payData['pay_prepayid'] = $params['join_order_member_id'] . '-CASH';
- } else if ($params['pay_category'] == 'WELFARE') {
- $payData['pay_prepayid'] = $params['join_order_member_id'] . '-WELFARE';
- } else if ($params['pay_category'] == 'VIP') {
- $payData['pay_prepayid'] = $params['join_order_member_id'] . '-VIP';
- } else if ($params['pay_category'] == 'CARD') {
- $payData['pay_prepayid'] = $params['card_id'];
- } else if ($params['pay_category'] == 'OFFLINE') {
- $payData['pay_prepayid'] = 'OFFLINE';
- } else if ($params['pay_category'] == 'OFFLINE_ALIPAY') {
- $payData['pay_prepayid'] = 'OFFLINE_ALIPAY';
- } else if ($params['pay_category'] == 'OFFLINE_WXPAY') {
- $payData['pay_prepayid'] = 'OFFLINE_WXPAY';
- } else if ($params['pay_category'] == 'MONEY') {
- $payData['pay_prepayid'] = 'MONEY';
- }
- $payData['join_pay_member_id'] = $params['join_order_member_id'];
- $payData['join_pay_order_id'] = $order->order_groupby;
- $payData['pay_status'] = !empty($payData['pay_status']) && $payData['pay_status'] == 'SUCCESS' ? $payData['pay_status'] : 'WAITING';
- $payData['pay_category'] = $params['goods_classify'] ?? '';
- $payData['pay_paytimes'] = date('Y-m-d H:i:s');
- $payData['pay_json_request'] = json_encode($params); // {"pay-result": "支付成功", "result-datetime": "2024-07-29 18:38:21"}
- $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')])) : '[]';
- $payData['join_pay_object_json'] = !empty($params['orderId']) ? json_encode(['order_id' => $params['orderId']]) : '[]';
- $payData['pay_addtimes'] = time();
- PayDetail::insert($payData);
- Db::commit();
- // 触发事件
- if ($order->order_is_complete == 'Y' && $order->order_status_payment == 'SUCCESS') {
- // 完成订单
- Event::dispatch('order.complete', $params);
- }
- if ($order->order_status_payment == 'SUCCESS') {
- // 加销售量
- OrderSheetService::addGoodsSales($params['orderId']);
- // 上级提成
- Event::dispatch('commission.order', $params);
- // 入收支明细表
- $params['inout_category'] = '标准订单';
- Event::dispatch('statistics.inout.in', $params);
- }
- // 打小票
- if ($order->order_status_payment == 'SUCCESS') {
- if (!empty($premises) && !empty($premises->dept_id)) {
- $voteData = [
- 'func' => 'procActionToPrinter',
- 'sign' => '',
- 'data' => [
- 'printer_premises' => $premises->dept_id,
- 'printer_device' => ["收银"],
- 'printer_action' => 'ExecPrintOrder',
- 'printer_data' => [
- 'order_id' => $params['orderId'],
- 'order_batch' => ''
- ]
- ]
- ];
- http_post_json(getenv('VOTE_MENU_URL'), $voteData);
- }
- }
- if ($order->order_status_payment != 'SUCCESS') {
- _syslog("订单", "支付异常,检查是否有轮询");
- // 恢复优惠券到已占用
- if (!is_array($couponUseJson)) {
- $couponUseJson = json_decode($couponUseJson, true);
- }
- // 如果下单时就填了,不用恢复
- if (empty($discountJson)) {
- $this->changeOrderCouponStatus($couponUseJson, 'WAITING');
- }
- return json_throw(2001, '支付异常', ['order_id' => $params['orderId'], 'group_id' => $params['orderGroupId']]);
- }
- _syslog("订单", "订单支付成功");
- return json_success('支付成功');
- } catch (BusinessException $e) {
- Db::rollBack();
- _syslog("订单", "订单支付失败:" . $e->getMessage());
- Log::error('订单支付失败', ['msg' => $e->getMessage()]);
- return json_fail("支付失败:" . $e->getMessage());
- } catch (\Exception $e) {
- Db::rollBack();
- _syslog("订单", "订单支付失败");
- Log::error('订单支付失败', ['msg' => $e->getMessage()]);
- return json_fail('支付失败');
- }
- }
- /**
- * @Desc
- * @Author Gorden
- * @Date 2024/6/7 10:30
- *
- * @param $params
- * @return void
- * @throws BusinessException
- */
- public function insertMain($params, $wxAndAliPayStatus = 'Y')
- {
- try {
- if (empty($params['order_extend_json'])) {
- $params['order_extend_json'] = [];
- } else {
- if (is_json($params['order_extend_json'])) {
- $params['order_extend_json'] = json_decode($params['order_extend_json'], true);
- }
- }
- // 账户扣款
- if ($wxAndAliPayStatus == 'Y' && !empty($params['waitToPayAccount'])) {
- foreach ($params['waitToPayAccount'] as $account) {
- $this->deductAmount($account['nbr'], $account['amount']);
- }
- }
- // 推荐人
- $params['order_extend_json']['referee'] = $params['referee'] ?? '';
- $orderAmount = [];
- foreach ($params['goodsContentList'] as $goods) {
- $amountPay = round((floatval($goods['goods_sales_price']) * $goods['nbr'] / $params['order_amount_total']) * $params['order_amount_pay'], 2);
- $discountJson = [];
- if (!empty($params['order_discount_json'])) {
- $discountJson = json_decode($params['order_discount_json'], true);
- foreach ($discountJson as &$item) {
- if (!empty($item['coupon_id'])) {
- $orderAmount = OrderService::countAndAmount($params['goodsContentList'], $item['coupon_id']);
- $payAmountUseCoupon = $params['order_amount_pay'] - ($params['order_amount_total'] - $orderAmount['amount']);
- if (in_array($goods['goods_id'], $orderAmount['goodsIds'])) {
- $amountPay = round((floatval($goods['goods_sales_price']) * $goods['nbr'] / $orderAmount['amount']) * $payAmountUseCoupon, 2);
- }
- } else {
- $orderAmount['amount'] = $params['order_amount_total'];
- $amountPay = round((floatval($goods['goods_sales_price']) * $goods['nbr'] / $params['order_amount_total']) * $params['order_amount_pay'], 2);
- }
- if (!empty($item['coupon_value'])) {
- $item['coupon_value'] = round((floatval($goods['goods_sales_price']) * $goods['nbr'] / $orderAmount['amount']) * $item['coupon_value'], 2);
- }
- }
- }
- $orderId = 'OD' . date('ymdHi') . random_string(4, 'up');
- $data = [
- 'order_id' => $orderId,
- 'order_groupby' => $params['orderGroupId'],
- 'join_order_member_id' => $params['join_order_member_id'],
- 'order_name' => date('Y-m-d H:i:s') . '-订单',
- 'order_amount_total' => floatval($goods['goods_sales_price']) * $goods['nbr'],
- 'order_amount_pay' => $amountPay,
- 'order_category' => $goods['goods_classify'],
- 'order_classify' => $goods['goods_classify'],
- 'order_is_complete' => $params['order_is_complete'] ?? 'N',
- 'order_status_system' => $params['order_status_system'],
- 'order_status_payment' => $params['order_status_payment'],
- 'order_status_storage' => $params['order_status_storage'],
- 'order_platform' => $params['order_platform'],
- 'order_remark' => $params['order_remark'] ?? '',
- 'order_discount_json' => (!empty($orderAmount['goodsIds']) && in_array($goods['goods_id'], $orderAmount['goodsIds'])) || (empty($orderAmount['goodsIds']) && !empty($orderAmount['amount'])) ? json_encode($discountJson) : '[]',
- 'order_config_json' => $params['order_config_json'] ?? '[]',
- 'order_express_json' => $params['order_express_json'] ?? '[]',
- 'order_extend_json' => $params['order_extend_json'] ? json_encode($params['order_extend_json']) : '[]',
- 'order_addtimes' => time(),
- 'order_add_user_id' => JwtToken::getCurrentId()
- ];
- Order::insert($data);
- $sheetIds = $this->insertSheetOne($params, $goods, $orderId, $amountPay);
- $this->insertPayDetailOne($params, $orderId, $amountPay, $goods);
- $params['order_express_goods'] = json_encode(['sheet' => $sheetIds]);
- $this->insertExpressOne($params, $orderId);
- }
- } catch (\Exception $e) {
- dump($e->getMessage());
- throw new BusinessException('订单创建信息失败');
- }
- }
- /**
- * @Desc
- * @Author Gorden
- * @Date 2024/6/7 10:25
- *
- * @param $params
- * @return void
- * @throws BusinessException
- */
- public function insertSheet($params)
- {
- try {
- $orderSheetIds = [];
- foreach ($params['goodsContentList'] as $goods) {
- //{"unit": "份", "table": null, "premises": "15"}
- $price = floatval($goods['goods_sales_price']);
- $extendJson['unit'] = $goods['sku_name'];
- if (isset($params['submit_premises_id'])) {
- $extendJson['premises'] = $params['submit_premises_id'];
- }
- if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') {
- $extendJson['table'] = null;
- }
- $orderSheetStatus = 'PAYING';
- if ($params['settlement_now'] == 'Y' && $params['order_status_payment'] == 'SUCCESS') {
- if (floatval($params['order_amount_pay']) >= floatval($params['order_amount_total'])) {
- $orderSheetStatus = 'DONE';
- } else {
- $orderSheetStatus = 'BEING';
- }
- }
- $data = [
- 'join_sheet_member_id' => $params['join_order_member_id'],
- 'join_sheet_order_id' => $params['orderId'],
- 'join_sheet_goods_id' => $goods['goods_id'],
- 'join_sheet_goods_sku_id' => $goods['sku_id'],
- 'order_sheet_status' => $orderSheetStatus,
- 'order_sheet_category' => 'CARD',
- 'order_sheet_num' => $goods['nbr'],
- 'order_sheet_price' => $goods['goods_sales_price'],
- 'order_sheet_price_pay' => $goods['goods_sales_price'],
- 'order_sheet_amount' => $price * $goods['nbr'],
- 'order_sheet_pay' => $price * $goods['nbr'],
- 'order_sheet_task_status' => 'NONE',
- 'order_sheet_remark' => $params['order_remark'] ?? '',
- 'order_sheet_addtimes' => time(),
- 'order_sheet_extend_json' => json_encode($extendJson)
- ];
- $orderSheetId = OrderSheet::insertGetId($data);
- $orderSheetIds[] = $orderSheetId;
- // 减库存,规格和总库存
- $goodsRunning = GoodsRunning::where('join_running_goods_id', $goods['goods_id'])->first();
- $goodsRunning->goods_running_storage = $goodsRunning->goods_running_storage - $goods['nbr'];
- if ($goodsRunning->goods_running_storage < 0) {
- throw new BusinessException('库存不足');
- }
- if ($params['order_status_payment'] == 'SUCCESS') {
- $goodsRunning->goods_running_sale = $goodsRunning->goods_running_sale + $goods['nbr'];
- }
- $goodsRunning->save();
- }
- return $orderSheetIds;
- } catch (\support\exception\BusinessException $e) {
- dump($e->getMessage() . '||' . $e->getLine());
- throw new BusinessException($e->getMessage());
- } catch (\Exception $e) {
- dump($e->getMessage() . '||' . $e->getLine());
- throw new BusinessException('订单创建失败');
- }
- }
- /**
- * @Desc
- * @Author Gorden
- * @Date 2024/6/7 10:35
- *
- * @param $params
- * @return void
- * @throws BusinessException
- */
- public function insertPayDetail($params)
- {
- try {
- if (in_array($params['pay_category'], ['WXPAY', 'ALIPAY'])) {
- $payPrepayid = $params['pay_category'];
- } else if ($params['pay_category'] == 'OFFLINE') {
- $payPrepayid = 'OFFLINE';
- } else if ($params['pay_category'] == 'OFFLINE_ALIPAY') {
- $payPrepayid = 'OFFLINE_ALIPAY';
- } else if ($params['pay_category'] == 'OFFLINE_WXPAY') {
- $payPrepayid = 'OFFLINE_WXPAY';
- } else if ($params['pay_category'] == 'MONEY') {
- $payPrepayid = 'MONEY';
- } else {
- $payPrepayid = $params['join_order_member_id'] . '-' . $params['pay_category'];
- }
- $data = [
- 'join_pay_member_id' => $params['join_order_member_id'],
- 'join_pay_order_id' => $params['orderGroupId'],
- 'pay_status' => $params['settlement_now'] == 'Y' && $params['order_status_payment'] == 'SUCCESS' ? 'SUCCESS' : 'WAITING',
- 'pay_category' => $params['goods_classify'],
- 'pay_amount' => $params['order_amount_pay'],
- 'pay_prepayid' => $payPrepayid,
- 'pay_paytimes' => date('Y-m-d H:i:s'),
- 'join_pay_object_json' => !empty($params['orderId']) ? json_encode(['order_id' => $params['orderId']]) : '[]',
- 'pay_json_request' => json_encode($params),
- 'pay_json_response' => $params['pay_json_response'] ?? '[]',
- 'pay_remark' => $params['order_remark'] ?? '',
- 'pay_addtimes' => time(),
- ];
- PayDetail::insert($data);
- } catch (\Exception $e) {
- dump($e->getMessage());
- throw new BusinessException('创建支付记录失败');
- }
- }
- /**
- * @Desc 订单商品详情
- * @Author Gorden
- * @Date 2024/3/29 8:50
- *
- * @param Request $request
- * @return Response
- */
- public function sheet(Request $request)
- {
- try {
- $orderId = $request->get('order_id');
- $orderSheet = OrderSheet::with([
- 'member' => function ($query) {
- $query->select('member_id', 'member_mobile', 'member_is_owner', 'join_member_role_id', 'member_is_vip', 'member_is_partner', 'member_is_referrer', 'join_invite_member_id', 'member_is_franchisee');
- },
- 'goods' => function ($query) {
- $query->select('goods_id', 'goods_name', 'goods_cover', 'goods_market_price', 'goods_sales_price', 'goods_classify', 'goods_if_express');
- },
- 'memberInfo',
- 'cert',
- 'sku' => function ($query) {
- $query->where('goods_sku_status', 'ON')
- ->select('goods_sku_id', 'join_sku_goods_id', 'goods_sku_specs_json', 'goods_sku_sales_price');
- },
- 'skus',
- 'refund' => function ($query) {
- $query->select('join_return_order_id', 'order_return_status');
- }
- ])->where('join_sheet_order_id', $orderId)
- ->orderBy('order_sheet_id', 'DESC')
- ->get()
- ->toArray();
- $order = Order::where('order_id', $orderId)->first();
- $express = OrderExpress::where('join_express_order_id', $orderId)->first();
- $sheetAmount = 0;
- foreach ($orderSheet as &$item) {
- $sheetAmount += $item['order_sheet_amount'];
- $item['goods']['goods_cover'] = getenv('STORAGE_DOMAIN') . $item['goods']['goods_cover'];
- if (!empty($item['goods']) && $item['goods']['goods_classify'] == 'PACKAGE') {
- $components = GoodsComponent::with('goods')
- ->where('join_component_master_goods_id', $item['goods']['goods_id'])
- ->select('join_component_master_goods_id', 'join_component_goods_id', 'goods_component_price',
- 'goods_component_price', 'goods_component_json')
- ->get()
- ->toArray();
- $goodsArr = [];
- foreach ($components as $component) {
- $configJson = !empty($component['goods_component_json']) ? json_decode($component['goods_component_json'], true) : [];
- if (!empty($component['goods'])) {
- $supplierName = Supplier::where('supplier_id', $component['goods']['join_goods_supplier_id'])->value('supplier_name');
- $benefit = MemberBenefit::where('join_benefit_member_id', $item['join_sheet_member_id'])
- ->where('join_benefit_goods_id', $component['goods']['goods_id'])
- ->where('join_benefit_order_id', $orderId)
- ->first();
- $goodsArr[] = [
- 'goods_name' => $component['goods']['goods_name'],
- 'goods_cover' => getenv('STORAGE_DOMAIN') . $component['goods']['goods_cover'],
- 'supplier_name' => $supplierName,
- 'nbr' => $configJson['nbr'] ?? 0,
- 'used' => !empty($benefit->member_benefit_used_count) ? intval($benefit->member_benefit_used_count) : ''
- ];
- }
- }
- $item['goods']['components'] = $goodsArr;
- }
- if (!empty($item['sku'])) {
- if (!empty($item['sku']['goods_sku_specs_json'])) {
- $specsJson = json_decode($item['sku']['goods_sku_specs_json'], true);
- $skuName = '';
- foreach ($specsJson as $specsKey => $skuSpecs) {
- if (is_array($skuSpecs)) {
- $skuName = $skuName . ' ' . implode(' ', $skuSpecs) . ';';
- } else {
- $skuName = $skuName . ' ' . $skuSpecs . ';';
- }
- }
- $item['sku']['goods_sku_title'] = rtrim($skuName, ';');
- }
- }
- if (!empty($item['skus'])) {
- foreach ($item['skus'] as $key => $skus) {
- if (!empty($skus['goods_sku_specs_json'])) {
- $item['skus'][$key]['goods_sku_specs_json'] = json_decode($skus['goods_sku_specs_json']);
- $skuName = '';
- foreach ($item['skus'][$key]['goods_sku_specs_json'] as $specsKey => $skuSpecs) {
- $keyStr = ($specsKey == '规格') ? '' : ($specsKey . ':');
- if (is_array($skuSpecs)) {
- $skuName = $skuName . $keyStr . ' ' . implode(' ', $skuSpecs) . '; ';
- } else {
- $skuName = $skuName . $keyStr . ' ' . $skuSpecs . '; ';
- }
- }
- $item['skus'][$key]['sku_name'] = rtrim($skuName, '; ');
- }
- }
- } else {
- $item['skus'] = [];
- }
- if (in_array($item['goods']['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE']) && $order->order_status_system == 'DONE') {
- $item['appontment'] = [];
- $appontments = Appointment::where('join_appointment_order_id', $orderId)
- ->where('appointment_status', 'DONE')
- ->select('appointment_status', 'appointment_id', 'appointment_done_datetime', 'appointment_done_json', 'appointment_apply_json')
- ->get()
- ->toArray();
- foreach ($appontments as $appontment) {
- $doneJson = [];
- $username = '';
- if (!empty($appontment['appointment_done_json'])) {
- $doneJson = json_decode($appontment['appointment_done_json'], true);
- if (isset($doneJson['charge'])) {
- $username = SysUser::where('user_id', $doneJson['charge']['charge_user_id'])->value('user_name');
- }
- }
- $person = 1;
- if (!empty($appontment->appointment_apply_json)) {
- $applyJson = json_decode($appontment->appointment_apply_json, true);
- if (isset($applyJson['person'])) {
- $person = $applyJson['person'];
- }
- }
- $item['appontment'][] = [
- 'member' => ($item['cert'] ? $item['cert']['member_cert_name'] . '-' : '') . ($item['member'] ? $item['member']['member_mobile'] : ''),
- 'goods_name' => $item['goods']['goods_name'],
- 'premisses' => isset($doneJson['charge']) ? $doneJson['charge']['charge_premises'] : '',
- 'username' => $username,
- 'nbr' => $person,
- 'done_time' => $appontment['appointment_done_datetime'],
- 'appointment_status' => $appontment['appointment_status'],
- ];
- }
- }
- if (!empty($item['order_sheet_extend_json']) && !$express) {
- $extendJson = json_decode($item['order_sheet_extend_json'], true);
- if (isset($extendJson['address_id'])) {
- $address = ClientConfig::where('client_config_id', $extendJson['address_id'])->first();
- if (!empty($address)) {
- $valJson = json_decode($address->client_config_val_json, true);
- $express = [
- 'order_express_address' => $valJson['address'] . ($valJson['numbers'] ?? ''),
- 'order_express_city' => $valJson['city'],
- 'order_express_mobile' => $valJson['mobile'],
- 'order_express_person' => $valJson['person']
- ];
- }
- }
- }
- $item['member']['level'] = '普通会员';
- if (!empty($item['member']['join_member_role_id'])) {
- $item['member']['level'] = MemberRole::where('member_role_id', $item['member']['join_member_role_id'])->value('member_role_name');
- }
- $item['member_info']['member_info_nickname'] = MemberService::getNickname(!empty($item['member_info']) ? $item['member_info']['member_info_nickname'] : '', (!empty($item['member']) ? $item['member']['member_mobile'] : ''));
- $item['member_info']['member_info_headimg'] = MemberService::getAvatarUrl(!empty($item['member_info']) && !empty($item['member_info']['member_info_headimg']) ? $item['member_info']['member_info_headimg'] : '');
- // 推荐人
- if (!empty($item['member']['join_invite_member_id'])) {
- $inviteMember = Member::with([
- 'cert' => function ($query) {
- $query->select('join_cert_member_id', 'member_cert_name');
- }
- ])->where('member_id', $item['member']['join_invite_member_id'])
- ->first();
- $inviteMobile = $inviteMember['member_mobile'] ?? '';
- $inviteCertName = !empty($inviteMember['cert']) && !empty($inviteMember['cert']['member_cert_name']) ? $inviteMember['cert']['member_cert_name'] : '';
- $order->invite_name = MemberService::getMemberCertName($inviteMobile, $inviteCertName, '');
- }
- }
- $order->sheet_amount = number_format($sheetAmount, 2);
- $payDetails = PayDetail::whereJsonContains('join_pay_object_json->order_id', $order->order_id)
- ->where('pay_category', 'CARD')
- ->where('pay_status', 'SUCCESS')
- ->select('pay_id', 'pay_category', 'pay_prepayid', 'pay_paytimes', 'pay_status', 'pay_amount', 'pay_extend_json')
- ->orderBy('pay_addtimes', 'DESC')
- ->get();
- $order->pay_amount_total = 0;
- foreach ($payDetails as &$payDetail) {
- $categoryArray = explode('-', $payDetail->pay_prepayid);
- if (isset($categoryArray[1])) {
- $payDetail->pay_category = $categoryArray[1];
- } else if (in_array($categoryArray[0], ['WXPAY', 'ALIPAY', 'OFFLINE', 'OFFLINE_ALIPAY', 'OFFLINE_WXPAY', 'MONEY'])) {
- $payDetail->pay_category = $categoryArray[0];
- }
- if (!empty($payDetail->pay_extend_json)) {
- $payExtendJson = json_decode($payDetail->pay_extend_json, true);
- $order->cancel_times = $payExtendJson['cancel_times'] ?? '';
- if (isset($payExtendJson['ticket'])) {
- $payDetail->ticket = str_replace('/thumb', '', getenv("STORAGE_DOMAIN") . $payExtendJson['ticket']);
- }
- }
- $order->pay_amount_total += $payDetail->pay_amount;
- }
- $refund = OrderReturn::where('join_return_order_id', $orderId)
- ->select('order_return_status', 'order_return_apply_datetime', 'order_return_apply_json', 'order_return_accept_datetime', 'order_return_refund_json', 'order_return_extend_json')
- ->first();
- if (!empty($refund->order_return_refund_json)) {
- $returnRefundJson = json_decode($refund->order_return_refund_json, true);
- if (isset($returnRefundJson['user_id'])) {
- $userName = SysUser::where('user_id', $returnRefundJson['user_id'])->value('user_name');
- $returnRefundJson['person'] = $userName;
- unset($returnRefundJson['user_id']);
- }
- $refund->order_return_refund_json = json_encode($returnRefundJson);
- }
- if (!empty($order->order_config_json)) {
- $orderConfigJson = json_decode($order->order_config_json, true);
- if (isset($orderConfigJson['reach'])) {
- $order->reach = $orderConfigJson['reach'];
- }
- if (isset($orderConfigJson['table'])) {
- $order->table = $orderConfigJson['table'];
- }
- if (isset($orderConfigJson['eat'])) {
- $order->eat = $orderConfigJson['eat'];
- }
- if (isset($orderConfigJson['express'])) {
- $order->express = $orderConfigJson['express'];
- }
- if (isset($orderConfigJson['premises'])) {
- $order->premises = $orderConfigJson['premises'];
- }
- if (isset($orderConfigJson['tableid'])) {
- $order->dept_table_id = $orderConfigJson['tableid'];
- }
- }
- if (!empty($order->order_extend_json)) {
- $orderExtendJson = json_decode($order->order_extend_json, true);
- $order->referee = $orderExtendJson['referee'] ?? '';
- if (isset($orderExtendJson['cancel_times'])) {
- $order->cancel_times = $orderExtendJson['cancel_times'];
- }
- if (isset($orderExtendJson['free_remark'])) {
- $order->free_remark = $orderExtendJson['free_remark'];
- }
- if (isset($orderExtendJson['dept_id'])) {
- $order->dept_id = $orderExtendJson['dept_id'];
- }
- if (isset($orderExtendJson['dept_name'])) {
- $order->premises = $orderExtendJson['dept_name'];
- }
- if (isset($orderExtendJson['referee'])) {
- $order->invite_name = $orderExtendJson['referee'];
- }
- }
- $discount = ['coupon_name' => '', 'classify' => '', 'value' => 0];
- if (!empty($order->order_discount_json)) {
- $orderDiscountJson = json_decode($order->order_discount_json, true);
- foreach ($orderDiscountJson as $discountItem) {
- if (!empty($discountItem['coupon_id'])) {
- $coupon = Coupon::where('coupon_id', $discountItem['coupon_id'])
- ->select('coupon_name', 'coupon_classify', 'coupon_category', 'coupon_value', 'coupon_minimum_limit')
- ->first();
- if (!$coupon) {
- continue;
- }
- $classify = CouponService::couponClassifyInfo($coupon->coupon_classify, $coupon->coupon_category, $coupon->coupon_value, $coupon->coupon_minimum_limit);
- $discount['coupon_name'] .= $coupon->coupon_classify . ':' . $coupon->coupon_name . '(优惠¥' . sprintf("%.2f", $discountItem['coupon_value']) . '), ';
- }
- if ($discountItem['coupon_classify'] == '退款') {
- continue;
- }
- if (empty($discountItem['coupon_id']) && !empty($discountItem['coupon_classify'])) {
- if (!empty($discountItem['coupon_detail_id'])) {
- $discount['classify'] .= $discountItem['coupon_detail_id'][0] . '(优惠¥' . sprintf("%.2f", $discountItem['coupon_value']) . '), ';
- } else {
- $discount['classify'] .= $discountItem['coupon_classify'] . '(优惠¥' . sprintf("%.2f", $discountItem['coupon_value']) . '), ';
- }
- }
- if (!empty($discountItem['coupon_value'])) {
- $discount['value'] += $discountItem['coupon_value'];
- }
- }
- if (!empty($discount['coupon_name'])) {
- $discount['coupon_name'] = rtrim($discount['coupon_name'], ', ');
- }
- if (!empty($discount['classify'])) {
- $discount['classify'] = rtrim($discount['classify'], ', ');
- }
- }
- $discount['value'] = sprintf("%.2f", $discount['value']);
- $order->discount = $discount;
- $order->premises = $order->premises ?? '';
- $data = [
- 'order' => $order,
- 'refund' => json_decode(json_encode($refund)),
- 'sheet' => json_decode(json_encode($orderSheet)),
- 'express' => json_decode(json_encode($express)),
- 'payDetails' => json_decode(json_encode($payDetails))
- ];
- return json_success('', $data);
- } catch (\Exception $e) {
- dump($e->getMessage());
- }
- }
- /**
- * @Desc 获取分期的订单
- * @Author Gorden
- * @Date 2024/9/10 15:14
- *
- * @param Request $request
- * @return Response
- */
- public function getPaidOrder(Request $request)
- {
- $memberId = $request->get('member_id');
- if (!$memberId) {
- return json_fail('参数异常');
- }
- $order = Order::where('join_order_member_id', $memberId)
- ->where('order_category', 'CARD')
- ->where('order_status_system', 'PAYING')
- ->select('order_id', 'order_amount_total', 'order_amount_paid', 'order_amount_pay', 'order_extend_json')
- ->first();
- return json_success('', $order);
- }
- /**
- * @Desc 上传支付凭证
- * @Author Gorden
- * @Date 2024/9/12 10:14
- *
- * @param Request $request
- * @return Response
- */
- public function uploadTicket(Request $request)
- {
- $payId = $request->post('pay_id');
- $url = $request->post('url');
- if (!$payId || !$url) {
- return json_fail("参数异常");
- }
- $url = str_replace(getenv("STORAGE_DOMAIN"), '', $url);
- try {
- $payDetail = PayDetail::where('pay_id', $payId)->first();
- if (!$payDetail) {
- return json_fail('数据异常');
- }
- $extendJson = [];
- if (!empty($payDetail->pay_extend_json)) {
- $extendJson = json_decode($payDetail->pay_extend_json, true);
- }
- $extendJson['ticket'] = $url;
- $payDetail->pay_extend_json = json_encode($extendJson);
- dump($payDetail->save());
- return json_success('success');
- } catch (\Exception $e) {
- return json_fail("上传附件失败");
- }
- }
- /**
- * @Desc 查询订单状态
- * @Author Gorden
- * @Date 2024/8/19 11:55
- *
- * @param Request $request
- * @return Response|void
- */
- public function getOrderPayStatus(Request $request)
- {
- $groupId = $request->get('group_id');
- if (!$groupId) {
- return json_fail('参数异常');
- }
- $order = Order::where('order_groupby', $groupId)->first();
- if (empty($order)) {
- return json_fail('订单不存在');
- }
- $order = $order->toArray();
- $sheet = OrderSheet::where('join_sheet_order_id', $order['order_id'])
- ->select('order_sheet_id', 'join_sheet_goods_id', 'join_sheet_goods_sku_id')
- ->first();
- $payDetailType = PayDetail::where('join_pay_order_id', $groupId)->pluck('pay_prepayid')->toArray();
- try {
- Db::beginTransaction();
- $payStatus = 'N';
- $payAmount = 0;
- if (in_array('WXPAY', $payDetailType)) {
- $result = Pay::wechat(config('payment.wxpay'))->find($groupId, 'pos');
- $result = json_decode(json_encode($result), true);
- // $result = '{"return_code":"SUCCESS","return_msg":"OK","result_code":"SUCCESS","mch_id":"1680393367","appid":"wxc6274da7198e3eb4","openid":"o3JAn6Ii_bAlxS-jbNEC4WnPhdwM","is_subscribe":"N","trade_type":"MICROPAY","trade_state":"SUCCESS","bank_type":"OTHERS","total_fee":"50","fee_type":"CNY","cash_fee":"1000","cash_fee_type":"CNY","transaction_id":"4200067718202409250802875650","out_trade_no":"OD24092518408RV7","attach":[],"time_end":"20240925184009","trade_state_desc":"支付成功","nonce_str":"OeGOkjch4eaV5qIt","sign":"6DCB3BFC594EBC018A2BEE2C3DFEA4E3"}';
- // $result = json_decode($result, true);
- if (!empty($result['return_code']) && $result['return_code'] == 'SUCCESS' && !empty($result['result_code']) && $result['result_code'] == 'SUCCESS' && !empty($result['trade_state']) && $result['trade_state'] == 'SUCCESS') {
- $payStatus = 'Y';
- $payAmount = ($result['total_fee'] / 100);
- $orderUpdateData['order_status_payment'] = 'PENDING';
- $orderUpdateData['order_amount_paid'] = $order['order_amount_paid'] + $payAmount;
- $orderUpdateData['order_amount_pay'] = $order['order_amount_pay'] + $payAmount;
- if ($order['order_amount_paid'] + $payAmount >= $order['order_amount_total']) {
- $orderUpdateData['order_status_payment'] = 'SUCCESS';
- $orderUpdateData['order_status_system'] = 'DONE';
- $orderUpdateData['order_is_complete'] = 'Y';
- }
- // 主订单
- Order::where('order_groupby', $groupId)->update($orderUpdateData);
- // Sheet
- OrderSheet::where('join_sheet_order_id', $order['order_id'])->where('order_sheet_status', 'PAYING')->update(['order_sheet_status' => 'DONE']);
- // 支付记录
- PayDetail::where('join_pay_order_id', $order['order_groupby'])->where('pay_prepayid', 'WXPAY')->update([
- 'pay_status' => 'SUCCESS',
- 'pay_paytimes' => date('Y-m-d H:i:s'),
- 'pay_json_response' => json_encode($result)
- ]);
- }
- } else if (in_array('ALIPAY', $payDetailType)) {
- $result = Pay::alipay(config('payment.alipay'))->find($groupId);
- $result = json_decode(json_encode($result), true);
- // $result = '{"code":"10000","msg":"Success","buyer_logon_id":"138******93","buyer_pay_amount":"5.87","fund_bill_list":[{"amount":"5.69","fund_channel":"ALIPAYACCOUNT"},{"amount":"0.18","fund_channel":"COUPON"},{"amount":"0.13","fund_channel":"DISCOUNT"}],"invoice_amount":"5.69","out_trade_no":"OD2409251550Q07A","point_amount":"0.00","receipt_amount":"0.01","send_pay_date":"2024-09-25 15:50:22","total_amount":"0.01","trade_no":"2024092523001439431419750998","trade_status":"TRADE_SUCCESS","buyer_open_id":"04309N2aVhSZz4cKwN_DN2DQa7ekM3z5n8kscQHsmIZOJsf"}';
- // $result = json_decode($result, true);
- if (!empty($result['code']) && $result['code'] == '10000' && !empty($result['trade_status']) && $result['trade_status'] == 'TRADE_SUCCESS') {
- $payStatus = 'Y';
- $payAmount = $result['total_amount'];
- $orderUpdateData['order_status_payment'] = 'PENDING';
- $orderUpdateData['order_amount_paid'] = $order['order_amount_paid'] + $payAmount;
- $orderUpdateData['order_amount_pay'] = $order['order_amount_pay'] + $payAmount;
- if ($order['order_amount_paid'] + $payAmount >= $order['order_amount_total']) {
- $orderUpdateData['order_status_payment'] = 'SUCCESS';
- $orderUpdateData['order_status_system'] = 'DONE';
- $orderUpdateData['order_is_complete'] = 'Y';
- }
- // 主订单
- Order::where('order_groupby', $groupId)->update($orderUpdateData);
- // Sheet
- OrderSheet::where('join_sheet_order_id', $order['order_id'])->where('order_sheet_status', 'PAYING')->update(['order_sheet_status' => 'DONE']);
- // 支付记录
- PayDetail::where('join_pay_order_id', $order['order_groupby'])->where('pay_prepayid', 'ALIPAY')->update([
- 'pay_status' => 'SUCCESS',
- 'pay_paytimes' => date('Y-m-d H:i:s'),
- 'pay_json_response' => json_encode($result)
- ]);
- }
- }
- if ($payStatus == 'Y') {
- Db::commit();
- // 入收支明细表
- $params['orderId'] = $order['order_id'];
- $params['inout_category'] = '购买储值卡';
- Event::dispatch('statistics.inout.in', $params);
- return json_success('success');
- }
- Db::rollBack();
- return json_fail('没有查询到记录');
- } catch (BusinessException $e) {
- Db::rollBack();
- _syslog("支付轮询", '订单支付异常:' . $e->getMessage());
- return json_fail($e->getMessage());
- } catch (\Exception $e) {
- dump($e->getMessage());
- Db::rollBack();
- return json_fail('查询失败');
- }
- }
- /**
- * @Desc 单条入库
- * @Author Gorden
- * @Date 2024/9/23 10:19
- *
- * @param $params
- * @return array
- * @throws BusinessException
- */
- public function insertSheetOne($params, $goods, $orderId, $amountPay)
- {
- try {
- $orderSheetIds = [];
- // foreach ($params['goodsContentList'] as $goods) {
- //{"unit": "份", "table": null, "premises": "15"}
- $price = floatval($goods['goods_sales_price']);
- $extendJson['unit'] = $goods['sku_name'];
- if (isset($params['submit_premises_id'])) {
- $extendJson['premises'] = $params['submit_premises_id'];
- }
- if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') {
- $extendJson['table'] = null;
- }
- $data = [
- 'join_sheet_member_id' => $params['join_order_member_id'],
- 'join_sheet_order_id' => $orderId,
- 'join_sheet_goods_id' => $goods['goods_id'],
- 'join_sheet_goods_sku_id' => $goods['sku_id'],
- 'order_sheet_status' => $params['settlement_now'] == 'Y' && $params['order_status_payment'] == 'SUCCESS' ? 'DONE' : 'PAYING',
- 'order_sheet_category' => (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') ? 'DISHES' : 'NORMAL',
- 'order_sheet_num' => $goods['nbr'],
- 'order_sheet_price' => $goods['goods_sales_price'],
- 'order_sheet_price_pay' => round($amountPay / $goods['nbr'], 2),
- 'order_sheet_amount' => $price * $goods['nbr'],
- 'order_sheet_pay' => $amountPay,
- 'order_sheet_task_status' => 'NONE',
- 'order_sheet_remark' => $params['order_remark'] ?? '',
- 'order_sheet_addtimes' => time(),
- 'order_sheet_extend_json' => json_encode($extendJson)
- ];
- $orderSheetId = OrderSheet::insertGetId($data);
- $orderSheetIds[] = $orderSheetId;
- // 减库存,规格和总库存
- $goodsRunning = GoodsRunning::where('join_running_goods_id', $goods['goods_id'])->first();
- $goodsRunning->goods_running_storage = $goodsRunning->goods_running_storage - $goods['nbr'];
- if ($goodsRunning->goods_running_storage < 0) {
- throw new BusinessException('库存不足');
- }
- if ($params['order_status_payment'] == 'SUCCESS') {
- $goodsRunning->goods_running_sale = $goodsRunning->goods_running_sale + $goods['nbr'];
- }
- $goodsRunning->save();
- // }
- return $orderSheetIds;
- } catch (\support\exception\BusinessException $e) {
- dump($e->getMessage() . '||' . $e->getLine());
- throw new BusinessException($e->getMessage());
- } catch (\Exception $e) {
- dump($e->getMessage() . '||' . $e->getLine());
- throw new BusinessException('订单创建失败');
- }
- }
- public function saveExpress($params, $orderId)
- {
- try {
- $express = new OrderExpress();
- $express->order_express_type = $params['order_express_type'];
- $express->join_express_order_id = $orderId;
- $express->join_express_dept_id = $params['submit_premises_id'] ?? 0;
- $express->order_express_goods = $params['order_express_goods'];
- $express->order_express_city = $params['order_express_city'];
- $express->order_express_address = $params['order_express_address'];
- $express->order_express_mobile = $params['order_express_mobile'] ?? '';
- $express->order_express_telephone = $params['order_express_telephone'] ?? '';
- $express->order_express_person = $params['order_express_person'] ?? '';
- $express->order_express_company = $params['dept_premises_id'] ?? '';
- $express->order_express_extend_json = $params['order_express_extend_json'] ?? '[]';
- $express->order_express_addtimes = time();
- $express->save();
- } catch (\Exception $e) {
- dump($e->getMessage());
- throw new BusinessException('物流信息保存失败');
- }
- }
- /**
- * @Desc 单条入库
- * @Author Gorden
- * @Date 2024/6/7 10:35
- *
- * @param $params
- * @return void
- * @throws BusinessException
- */
- public function insertPayDetailOne($params, $orderId, $amountPay, $goods)
- {
- try {
- if (!empty($params['pay_detail_item'])) {
- foreach ($params['pay_detail_item'] as $item) {
- $data = [
- 'join_pay_member_id' => $item['join_order_member_id'],
- 'join_pay_order_id' => $item['orderGroupId'],
- 'pay_status' => $item['settlement_now'] == 'Y' && $item['order_status_payment'] == 'SUCCESS' ? 'SUCCESS' : 'WAITING',
- 'pay_category' => $goods['goods_classify'],
- 'pay_amount' => round(($amountPay / $params['order_amount_pay']) * $item['order_amount_pay'], 2),
- 'pay_prepayid' => $item['pay_category'],
- 'pay_paytimes' => date('Y-m-d H:i:s'),
- 'join_pay_object_json' => !empty($item['orderId']) ? json_encode(['order_id' => $orderId]) : '[]',
- 'pay_json_request' => json_encode($item),
- 'pay_json_response' => $item['pay_json_response'] ?? '[]',
- 'pay_remark' => $item['order_remark'] ?? '',
- 'pay_addtimes' => time(),
- ];
- PayDetail::insert($data);
- }
- } else {
- if (in_array($params['pay_category'], ['WXPAY', 'ALIPAY'])) {
- $payPrepayid = $params['pay_category'];
- } else if ($params['pay_category'] == 'OFFLINE') {
- $payPrepayid = 'OFFLINE';
- } else if ($params['pay_category'] == 'OFFLINE_ALIPAY') {
- $payPrepayid = 'OFFLINE_ALIPAY';
- } else if ($params['pay_category'] == 'OFFLINE_WXPAY') {
- $payPrepayid = 'OFFLINE_WXPAY';
- } else if ($params['pay_category'] == 'MONEY') {
- $payPrepayid = 'MONEY';
- } else if ($params['pay_category'] == 'CARD') {
- $payPrepayid = $params['card_id'];
- } else {
- $payPrepayid = $params['join_order_member_id'] . '-' . $params['pay_category'];
- }
- $data = [
- 'join_pay_member_id' => $params['join_order_member_id'],
- 'join_pay_order_id' => $params['orderGroupId'],
- 'pay_status' => $params['settlement_now'] == 'Y' && $params['order_status_payment'] == 'SUCCESS' ? 'SUCCESS' : 'WAITING',
- 'pay_category' => $goods['goods_classify'],
- 'pay_amount' => $amountPay,
- 'pay_prepayid' => $payPrepayid,
- 'pay_paytimes' => date('Y-m-d H:i:s'),
- 'join_pay_object_json' => !empty($params['orderId']) ? json_encode(['order_id' => $orderId]) : '[]',
- 'pay_json_request' => json_encode($params),
- 'pay_json_response' => $params['pay_json_response'] ?? '[]',
- 'pay_remark' => $params['order_remark'] ?? '',
- 'pay_addtimes' => time(),
- ];
- PayDetail::insert($data);
- }
- } catch (\Exception $e) {
- dump($e->getMessage());
- throw new BusinessException('创建支付记录失败');
- }
- }
- /**
- * @Desc 入配送记录
- * @Author Gorden
- * @Date 2024/9/23 10:45
- *
- * @param $params
- * @return void
- * @throws BusinessException
- */
- public function insertExpressOne($params, $orderId)
- {
- if (isset($params['delivery']) && $params['delivery'] == 'LOGISTICS') {
- $params['order_express_type'] = '配送';
- // 入配送
- $this->saveExpress($params, $orderId);
- } else if (isset($params['delivery']) && $params['delivery'] == 'PICKUP') {
- $params['order_express_type'] = '自提';
- $premises = SysDept::where('dept_name', $params['dept_premises_id'])->first();
- if (!$premises) {
- throw new BusinessException('自提门店不存在');
- }
- $params['order_express_city'] = $premises->dept_city;
- $params['order_express_address'] = $premises->dept_address;
- $params['order_express_telephone'] = $premises->dept_telephone;
- $params['order_express_extend_json'] = json_encode(['pick_code' => random_string(4, 'number')]);
- $this->saveExpress($params, $orderId);
- } else if (isset($params['delivery']) && $params['delivery'] == 'ARRIVAL') {
- $premises = SysDept::where('dept_name', $params['dept_premises_id'])->first();
- $params['order_express_type'] = '到店';
- if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') {
- $params['order_express_type'] = '堂食';
- }
- if (!$premises) {
- throw new BusinessException('门店不存在');
- }
- $params['order_express_city'] = $premises->dept_city;
- $params['order_express_address'] = $premises->dept_address;
- $params['order_express_telephone'] = $premises->dept_telephone;
- $this->saveExpress($params, $orderId);
- }
- }
- private function discountRecord($orderDiscountJson, $params)
- {
- $json = [];
- if (!empty($orderDiscountJson)) {
- $json = json_decode($orderDiscountJson, true);
- }
- try {
- if (!empty($params['preferential']) && in_array('wipe', $params['preferential'])) {
- if (intval($params['order_amount_total'] / 10) * 10 != $params['order_amount_pay']) {
- throw new BusinessException("抹零后实际支付金额错误");
- }
- $params['order_discount_amount'] = $params['order_amount_total'] - $params['order_amount_pay'];
- $couponClassifyDesc = $couponClassify = '抹零';
- } elseif (!empty($params['preferential']) && in_array('custom', $params['preferential'])) {
- if (sprintf("%.2f", $params['order_amount_total'] - $params['order_discount_amount']) != sprintf("%.2f", $params['order_amount_pay'])) {
- throw new BusinessException("餐厅前台优惠后实际支付金额错误");
- }
- $couponClassifyDesc = $couponClassify = '餐厅前台优惠';
- } else if (!empty($params['preferential']) && intval($params['preferential'][0]) < 100 && intval($params['preferential'][0]) >= 50) {
- if (($params['order_amount_total'] * intval($params['preferential'][0])) / 100 != $params['order_amount_pay']) {
- throw new BusinessException("折扣后实际支付金额错误");
- }
- $couponClassify = '折扣';
- $couponClassifyDesc = intval($params['preferential'][0]) / 10 . '折';
- $params['order_discount_amount'] = $params['order_amount_total'] - $params['order_amount_pay'];
- } else {
- return $json;
- }
- $json[date('Y-m-d H:i:s')] = [
- 'coupon_id' => $params['coupon_id'] ?? null,
- 'coupon_value' => $params['order_discount_amount'] ?? '',
- 'coupon_classify' => $couponClassify,
- 'coupon_detail_id' => [$couponClassifyDesc],
- 'coupon_classify_en' => $params['preferential']
- ];
- return $json;
- } catch (BusinessException $e) {
- throw new BusinessException($e->getMessage());
- } catch (\Exception $e) {
- dump($e->getMessage());
- throw new BusinessException("优惠数据错误");
- }
- }
- /**
- * @Desc 修改优惠券状态
- * @Author Gorden
- * @Date 2024/9/19 9:03
- *
- * @param $coupon
- * @param $status
- * @return void
- */
- private function changeOrderCouponStatus($coupon, $status)
- {
- if (!empty($coupon) && is_array($coupon)) {
- $updateData['coupon_detail_status'] = $status;
- if ($status == 'ACTIVED' || $status == 'WAITING') {
- $updateData['coupon_detail_used_datetime'] = '';
- } elseif ($status == 'USED') {
- $updateData['coupon_detail_used_datetime'] = date('Y-m-d H:i:s');
- }
- foreach ($coupon as $item) {
- if (!empty($item['coupon_id']) && !empty($item['coupon_detail_id'])) {
- foreach ($item['coupon_detail_id'] as $detailId) {
- CouponDetail::where('join_detail_coupon_id', $item['coupon_id'])
- ->where('coupon_detail_id', $detailId)->update($updateData);
- }
- }
- }
- }
- }
- }
|