123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263 |
- <?php
- namespace app\admin\controller\order;
- use app\admin\service\order\OrderService;
- use app\admin\validate\coupon\CouponValidate;
- use app\admin\validate\device\DeviceValidate;
- use app\admin\validate\order\OrderExpressValidate;
- use app\admin\validate\order\OrderValidate;
- use app\common\payment\AppUtil;
- use app\common\payment\Tlpay;
- use app\controller\Curd;
- use app\model\Appointment;
- use app\model\ClientConfig;
- use app\model\Coupon;
- use app\model\Device;
- use app\model\Goods;
- use app\model\GoodsComponent;
- 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\Premises;
- use app\model\Supplier;
- use app\model\SysDept;
- use app\model\SysSerial;
- use app\model\SysUser;
- use Payment\Common\PayException;
- use support\Db;
- use support\exception\BusinessException;
- use support\Redis;
- use support\Request;
- use support\Response;
- use function Qiniu\Http\Middleware\compose;
- class WholeController 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
- {
- [$where, $format, $limit, $field, $order] = $this->selectInput($request);
- if (!empty($where['order_addtimes'])) {
- $where['order_addtimes'][0] = strtotime($where['order_addtimes'][0]);
- $where['order_addtimes'][1] = strtotime($where['order_addtimes'][1]);
- }
- $order = $request->get('order', 'desc');
- $field = $field ?? 'order_addtimes';
- if (!empty($where['order_status_system']) && in_array($where['order_status_system'],['PENDING','WAITING','SENDING','RECVING','SIGNED','CONFIRM'])){
- $where['order_is_complete'] = 'N';
- }
- if (!empty($where['order_status_system']) && $where['order_status_system'] == 'RETURN') {
- unset($where['order_status_system']);
- unset($where['order_is_complete']);
- $where['order_category'] = 'RETURN';
- }
- $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([
- 'sheet' => function ($query) {
- $query->select('join_sheet_order_id', 'order_sheet_id', 'join_sheet_goods_id');
- },
- 'member' => function ($query) {
- $query->select('member_id', 'member_mobile');
- },
- 'cert' => function ($query) {
- $query->select('join_cert_member_id', 'member_cert_name');
- },
- 'return' => function($query){
- $query->select('orders_return_id','join_return_order_id', 'order_return_status');
- },
- 'express' => function($query){
- $query->select('join_express_order_id','order_express_type');
- }
- ]);
- 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);
- }
- return $model;
- }
- public function afterQuery($items)
- {
- foreach ($items as &$item) {
- if (!empty($item['sheet'])) {
- $goods = Goods::where('goods_id', $item['sheet']['join_sheet_goods_id'])->first();
- $item['sheet']['goods_name'] = $goods->goods_name ?? '';
- $item['sheet']['goods_classify'] = $goods->goods_classify ?? '';
- }
- }
- return $items;
- }
- /**
- * @Desc 订单商品详情
- * @Author Gorden
- * @Date 2024/3/29 8:50
- *
- * @param Request $request
- * @return Response
- */
- public function sheet(Request $request)
- {
- $orderId = $request->get('order_id');
- $orderSheet = OrderSheet::with([
- 'member' => function ($query) {
- $query->select('member_id', 'member_mobile', 'member_is_owner', 'join_member_role_id');
- },
- 'goods' => function ($query) {
- $query->select('goods_id', 'goods_name', 'goods_cover', 'goods_market_price', 'goods_sales_price', 'goods_classify', 'goods_if_express');
- },
- 'memberInfo',
- 'cert',
- 'skus' => function ($query) {
- $query->where('goods_sku_status', 'ON')
- ->select('goods_sku_id', 'join_sku_goods_id', 'goods_sku_specs_json', 'goods_sku_sales_price');
- },
- 'refund'=>function($query){
- $query->select('join_return_order_id','order_return_status');
- }
- ])->where('join_sheet_order_id', $orderId)
- ->get()
- ->toArray();
- $express = OrderExpress::where('join_express_order_id', $orderId)->first();
- $premises = '';
- if($express && $express->order_express_type == '自提'){
- $premises = $express->order_express_company;
- }
- // if (!empty($express->order_express_code)){
- // $expressCode = explode(':',$express->order_express_code);
- // if(count($expressCode) == 2){
- // $express->order_express_company = $expressCode[0];
- // $express->order_express_code = $expressCode[1];
- // }
- // }
- foreach ($orderSheet as &$item) {
- $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');
- $goodsArr[] = [
- 'goods_name' => $component['goods']['goods_name'],
- 'goods_cover' => getenv('STORAGE_DOMAIN') . $component['goods']['goods_cover'],
- 'supplier_name' => $supplierName,
- 'nbr' => $configJson['nbr'] ?? 0,
- ];
- }
- }
- $item['goods']['components'] = $goodsArr;
- }
- if (!empty($item['skus'])) {
- foreach ($item['skus'] as $k => $sku) {
- if (!empty($sku['goods_sku_specs_json'])) {
- $specsJson = json_decode($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['skus'][$k]['goods_sku_title'] = rtrim($skuName, ';');
- }
- }
- }
- if ($item['goods']['goods_classify'] == 'SERVICE') {
- $benifit = MemberBenefit::where('join_benefit_member_id', $item['join_sheet_member_id'])
- ->where('join_benefit_order_id', $orderId)
- ->first();
- if(!empty($benifit)){
- $item['benefit'] = [
- 'total' => intval($benifit->member_benefit_limit_count),
- 'used' => intval($benifit->member_benefit_used_count),
- 'cut' => $benifit->member_benefit_limit_count - $benifit->member_benefit_used_count,
- ];
- $appontments = Appointment::where('join_appointment_member_benefit_id', $benifit->member_benefit_id)
- ->where('appointment_status', 'DONE')
- ->select('appointment_id', 'appointment_done_datetime', 'appointment_done_json')
- ->get()
- ->toArray();
- $item['appontment'] = [];
- 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');
- }
- }
- $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' => 1,
- 'done_time' => $appontment['appointment_done_datetime']
- ];
- }
- }
- }
- 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');
- }
- }
- $order = Order::where('order_id', $orderId)->first();
- $payDetail = PayDetail::where('join_pay_order_id', $order->order_groupby)
- ->select('pay_id', 'pay_category', 'pay_prepayid','pay_paytimes','pay_status')
- ->first();
- if(!empty($payDetail->pay_prepayid)){
- $categoryArray = explode('-',$payDetail->pay_prepayid);
- if (isset($categoryArray[1])){
- $payDetail->pay_category = $categoryArray[1];
- }else if(in_array($categoryArray[0],['A01','W06'])){
- $payDetail->pay_category = $categoryArray[0];
- }else{
- if (MemberAccount::where('member_account_nbr',$categoryArray[0])->where('member_account_classify','CARD')->exists()){
- $payDetail->pay_category = 'CARD';
- }else{
- $payDetail->pay_category = 'CASH';
- }
- }
- }else if(!empty($payDetail)){
- $payDetail->pay_category = 'CASH';
- }
- 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['express'])){
- // $order->express = $orderConfigJson['express'];
- // }
- // if(isset($orderConfigJson['premises'])){
- // $order->premises = $orderConfigJson['premises'];
- // }
- }
- $order->premises = $premises;
- $data = [
- 'order' => $order,
- 'sheet' => $orderSheet,
- 'express' => $express,
- 'payDetail' => $payDetail
- ];
- return json_success('', $data);
- }
- public function update(Request $request): Response
- {
- $params = $request->post();
- try {
- Db::beginTransaction();
- // 修改主订单
- // $this->updateMain($params);
- // 修改物流
- $this->updateExpress($params);
- Db::commit();
- return json_success('修改订单成功');
- } catch (\Exception $e) {
- Db::rollBack();
- return json_fail('修改订单失败');
- }
- }
- public function updateExpress($params){
- $express = OrderExpress::where('join_express_order_id',$params['order_id'])->first();
- if(!$express){
- throw new BusinessException('物流信息异常');
- }
- if($params['delivery'] == 'PICKUP'){
- $premises = SysDept::where('dept_category','营业场所')->where('dept_name',$params['dept_premises_id'])->first();
- $express->order_express_type = '自提';
- $express->order_express_city = str_replace(',',' ',$premises->dept_city);
- $express->order_express_address = $premises->dept_address;
- $express->order_express_mobile = '';
- $express->order_express_person = '';
- $express->order_express_telephone = $premises->dept_telephone ?? '';
- $express->order_express_company = $params['dept_premises_id'];
- }else if($params['delivery'] == 'LOGISTICS'){
- $express->order_express_type = '配送';
- $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_person = $params['order_express_person'] ?? '';
- $express->order_express_telephone = '';
- $express->order_express_company = '';
- }
- try{
- if(($params['delivery'] == 'PICKUP') || ($params['delivery'] == 'LOGISTICS')){
- $express->save();
- }
- }catch(\Exception $e){
- dump($e->getTrace());
- throw new BusinessException('修改配送方式失败');
- }
- }
- public function delete(Request $request): Response
- {
- $params = $request->post();
- try {
- Db::beginTransaction();
- $order = Order::where('order_id', $params['order_id'])
- ->where('order_status_system','CANCEL')
- ->orWhere(function($query){
- $query->whereIn('order_status_system', ['WAITING', 'SENDING'])->where('order_category', 'SYSTEM');
- })
- ->first();
- if (!$order) {
- return json_fail('此订单不允许删除');
- }
- $payDetail = PayDetail::where('join_pay_order_id', $order->order_groupby)->first();
- if ($payDetail->pay_category == 'CASH') {
- $memberAccount = MemberAccount::where('join_account_member_id', $payDetail->join_pay_member_id)
- ->where('member_account_classify', 'CASH')
- ->first();
- $memberAccount->member_account_expend = $memberAccount->member_account_expend - $payDetail->pay_amount;
- $memberAccount->member_account_surplus = $memberAccount->member_account_surplus + $payDetail->pay_amount;
- $memberAccount->save();
- }
- // 删支付记录
- $payDetail->delete();
- // 删收货信息
- OrderExpress::where('join_express_order_id', $params['order_id'])->delete();
- // 删订单详情
- OrderSheet::where('join_sheet_order_id', $params['order_id'])->delete();
- // 删主订单
- $order->delete();
- Db::commit();
- return json_success('删除订单成功');
- } catch (\Exception $e) {
- dump($e->getMessage());
- Db::rollBack();
- return json_fail('删除订单失败');
- }
- }
- public function insert(Request $request): Response
- {
- $params = $request->post();
- try {
- Db::beginTransaction();
- // 余额支付
- 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) {
- return json_fail('账户异常');
- }
- $amount = $account->member_account_surplus + $account->member_account_added;
- if (!$account || $params['order_sheet_pay'] > $amount) {
- return json_fail('账户余额不足');
- }
- if ($params['order_sheet_pay'] > $account->member_account_surplus) {
- $cut = $account->member_account_added - ($params['order_sheet_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_sheet_pay'];
- }
- $account->member_account_expend = $account->member_account_expend + $params['order_sheet_pay'];
- $account->save();
- }
- $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'];
- $writeOffDate = [];
- // 服务已完成,生成核销数据
- if ($params['order_status_system'] == 'DONE' && in_array($goods['goods_classify'], ['SERVICE', 'PACKAGE'])) {
- $writeOffDate = OrderService::generateWriteOffData($params);
- }
- $params['orderId'] = 'OD' . date('YmdHis') . random_string(6, 'up');
- $params['orderGroupId'] = 'OD' . date('YmdHis') . random_string(6, 'up');
- $params['benefitId'] = 'BF' . date('YmdHis') . random_string(6, 'up');
- // 配送方式
- // if ($params['delivery'] == 'PICKUP') { // 自提
- // // $params['order_config_json'] = json_encode([
- // // // 'express' => 'S',
- // // 'premises' => $params['dept_premises_id']
- // // ]);
- // } else if ($params['delivery'] == 'LOGISTICS') {
- // // $params['order_express_json'] = json_encode([
- // // 'express' => 'Y',
- // // ]);
- // }
- // 写入主订单
- $this->insertMain($params);
- // 订单详情
- $sheetId = $this->insertSheet($params);
- // 支付记录
- $this->insertPayDetail($params);
- $params['order_express_goods'] = json_encode(['sheet' => [$sheetId]]);
- if ($params['delivery'] == 'LOGISTICS') {
- $params['order_express_type'] = '配送';
- // 入配送
- $this->saveExpress($params);
- }else if($params['delivery'] == 'PICKUP'){
- $premises = SysDept::where('dept_name', $params['dept_premises_id'])->first();
- $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);
- }
- // 买的单个服务
- if ($goods['goods_classify'] == 'SERVICE') {
- // 预约表
- for ($i = 0; $i < intval($params['order_sheet_num']); $i++) {
- $params['appointmentId'] = 'AP' . date('YmdHis') . random_string(6, 'up');
- // 入预约记录
- $this->insertAppointment($params, $writeOffDate);
- }
- $goods['skuId'] = $params['join_sheet_goods_sku_id'];
- $goods['category'] = 'SERVICE';
- // 权益表
- $this->insertMemberBenefit($params, $goods);
- } elseif ($goods['goods_classify'] == 'PACKAGE') { // 一个套餐买多个
- $params['packageId'] = $params['join_sheet_goods_id'];
- $components = GoodsComponent::with([
- 'goods' => function ($query) {
- $query->select('goods_id', 'goods_name', 'goods_classify');
- }
- ])->where('join_component_master_goods_id', $params['join_sheet_goods_id'])
- ->get()
- ->toArray();
- $orderSheetNum = $params['order_sheet_num'];
- foreach ($components as $component) {
- $params['order_sheet_num'] = $orderSheetNum;
- $componentJson = json_decode($component['goods_component_json'], true);
- $params['join_sheet_goods_sku_id'] = $componentJson['sku_id'];
- $params['join_sheet_goods_id'] = $component['join_component_goods_id'];
- $params['benefitId'] = 'BF' . date('YmdHis') . random_string(6, 'up');
- $params['order_sheet_num'] = $params['order_sheet_num'] * $componentJson['nbr'];
- for ($i = 0; $i < intval($params['order_sheet_num']); $i++) {
- $params['appointmentId'] = 'AP' . date('YmdHis') . random_string(8, 'up');
- // 入预约记录
- $this->insertAppointment($params, $writeOffDate);
- }
- $goods['goods_id'] = $component['join_component_goods_id'];
- $goods['goods_name'] = $component['goods']['goods_name'];
- $goods['goods_classify'] = $component['goods']['goods_classify'];
- $goods['skuId'] = $params['join_sheet_goods_sku_id'];
- $goods['category'] = 'SERVICE';
- // 权益表
- $this->insertMemberBenefit($params, $goods);
- }
- }
- Db::commit();
- return json_success('创建订单成功');
- } catch (\Exception $e) {
- Db::rollBack();
- dump($e->getMessage());
- return json_fail('创建订单失败');
- }
- }
- /**
- * @Desc
- * @Author Gorden
- * @Date 2024/6/7 10:30
- *
- * @param $params
- * @return void
- * @throws BusinessException
- */
- public function insertMain($params)
- {
- try {
- $data = [
- 'order_id' => $params['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' => $params['order_sheet_amount'],
- 'order_amount_pay' => $params['order_sheet_pay'],
- 'order_category' => 'SYSTEM',
- '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_remark' => $params['order_remark'] ?? '',
- 'order_config_json' =>$params['order_config_json'] ?? '[]',
- 'order_express_json' => $params['order_express_json'] ?? '[]',
- 'order_addtimes' => time()
- ];
- Order::insert($data);
- } 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 {
- $data = [
- 'join_sheet_member_id' => $params['join_order_member_id'],
- 'join_sheet_order_id' => $params['orderId'],
- 'join_sheet_goods_id' => $params['join_sheet_goods_id'],
- 'join_sheet_goods_sku_id' => $params['join_sheet_goods_sku_id'],
- 'order_sheet_status' => 'DONE',
- 'order_sheet_category' => 'NORMAL',
- 'order_sheet_num' => $params['order_sheet_num'],
- 'order_sheet_price' => $params['order_sheet_price'],
- 'order_sheet_amount' => $params['order_sheet_amount'],
- 'order_sheet_pay' => $params['order_sheet_pay'],
- 'order_sheet_remark' => $params['order_remark'] ?? '',
- 'order_sheet_addtimes' => time()
- ];
- return OrderSheet::insertGetId($data);
- } catch (\Exception $e) {
- throw new BusinessException('订单创建失败');
- }
- }
- /**
- * @Desc
- * @Author Gorden
- * @Date 2024/6/7 10:35
- *
- * @param $params
- * @return void
- * @throws BusinessException
- */
- public function insertPayDetail($params)
- {
- try {
- $data = [
- 'join_pay_member_id' => $params['join_order_member_id'],
- 'join_pay_order_id' => $params['orderGroupId'],
- 'pay_status' => 'SUCCESS',
- 'pay_category' => $params['pay_category'],
- 'pay_amount' => $params['order_sheet_pay'],
- 'pay_prepayid' => $params['join_order_member_id'].'-'.$params['pay_category'],
- 'pay_paytimes' => date('Y-m-d H:i:s'),
- 'pay_remark' => $params['order_remark'] ?? '',
- 'pay_addtimes' => time()
- ];
- PayDetail::insert($data);
- } catch (\Exception $e) {
- dump(111);
- dump($e->getMessage());
- throw new BusinessException('创建支付记录失败');
- }
- }
- /**
- * @Desc
- * @Author Gorden
- * @Date 2024/6/7 10:50
- *
- * @param $params
- * @return void
- * @throws BusinessException
- */
- public function insertAppointment($params, $writeOffDate)
- {
- try {
- $data = [
- 'appointment_id' => $params['appointmentId'],
- 'join_appointment_member_id' => $params['join_order_member_id'],
- 'join_appointment_goods_id' => $params['join_sheet_goods_id'],
- 'join_appointment_goods_sku_id' => $params['join_sheet_goods_sku_id'],
- 'join_appointment_order_id' => $params['orderId'],
- 'join_appointment_member_benefit_id' => $params['benefitId'],
- 'appointment_classify' => $params['goods_classify'],
- 'appointment_status' => $params['order_status_system'] == 'DONE' ? 'DONE' : 'INIT',
- 'appointment_category' => 'NORMAL',
- 'appointment_addtimes' => time(),
- 'appointment_done_datetime' => $params['order_status_system'] == 'DONE' ? date('Y-m-d H:i:s') : '',
- 'appointment_remark' => $params['order_remark'] ?? '',
- 'appointment_done_json' => $params['order_status_system'] == 'DONE' && $writeOffDate ? json_encode($writeOffDate) : '[]'
- ];
- Appointment::insert($data);
- } catch (\Exception $e) {
- dump($e->getMessage());
- throw new BusinessException("创建权益记录失败");
- }
- }
- /**
- * @Desc
- * @Author Gorden
- * @Date 2024/6/7 11:05
- *
- * @param $params
- * @param $goods
- * @return void
- * @throws BusinessException
- */
- public function insertMemberBenefit($params, $goods)
- {
- try {
- $data = [
- 'member_benefit_id' => $params['benefitId'],
- 'join_benefit_member_id' => $params['join_order_member_id'],
- 'join_benefit_package_id' => $params['packageId'] ?? '',
- 'join_benefit_goods_id' => $goods['goods_id'],
- 'join_benefit_goods_sku_id' => $goods['skuId'] ?? '',
- 'join_benefit_order_id' => $params['orderId'],
- 'member_benefit_status' => 'ACTIVED',
- 'member_benefit_category' => $goods['category'],
- 'member_benefit_name' => $goods['goods_name'],
- 'member_benefit_limit_count' => $params['order_sheet_num'],
- 'member_benefit_used_count' => $params['order_status_system'] == 'DONE' ? $params['order_sheet_num'] : 0,
- 'member_benefit_remark' => $params['order_remark'] ?? '',
- 'member_benefit_addtimes' => time()
- ];
- MemberBenefit::insert($data);
- } catch (\Exception $e) {
- dump($e->getMessage());
- throw new BusinessException('创建会员权益失败');
- }
- }
- /**
- * 修改主订单
- */
- public function updateMain($params)
- {
- $params['order_express_goods'] = json_encode(['sheet' => [$params['sheet_id']]]);
- if ($params['delivery'] == 'PICKUP') { // 自提
- $params['order_config_json'] = json_encode([
- // 'express' => 'S',
- // 'premises' => $params['dept_premises_id']
- ]);
- } else if ($params['delivery'] == 'LOGISTICS') {
- // $params['order_express_json'] = json_encode([
- // 'express' => 'Y',
- // ]);
- $params['orderId'] = $params['order_id'];
- $this->saveExpress($params);
- }
- try {
- Order::where('order_id', $params['order_id'])->update(['order_config_json' => $params['order_config_json'] ?? '[]']);
- } catch (\Exception $e) {
- throw new BusinessException('修改订单失败');
- }
- }
- public function delivery(Request $request)
- {
- if (!Order::where('order_id', $request->post('order_id'))->where('order_status_system', 'SENDING')->exists()) {
- return json_fail('订单状态异常');
- }
- // 验证
- $validate = new OrderExpressValidate();
- if (!$validate->scene('delivery')->check($request->post())) {
- return json_fail($validate->getError());
- }
- $params = $request->post();
- try {
- Db::beginTransaction();
- if ($params['express_type'] == '自提') {
- $premises = SysDept::where('dept_name', $params['order_express_premises'])->first();
- if (!$premises) {
- return json_fail("门店不存在,请重新填写");
- }
- $params['order_express_city'] = str_replace(',', ' ', $premises->dept_city);
- $params['order_express_address'] = $premises->dept_address;
- $params['order_express_code'] = '';
- $params['order_express_addtimes'] = strtotime($params['order_express_addtimes']);
- $orderData = [
- 'order_status_system' => 'CONFIRM',
- 'order_status_storage' => 'EXPRESSING'
- ];
- // 7天后自动完成
- $redis = Redis::connection();
- $key = Order::AUTOMATIC_COMPLETE_PREFIX . date('Ymd', strtotime("+7 days"));
- $redis->sadd($key, $params['order_id']);
- $model = new OrderExpress();
- } else {
- $orderData = [
- 'order_status_system' => 'RECVING',
- 'order_status_storage' => 'EXPRESSING'
- ];
- // 15天后自动确认收货
- $redis = Redis::connection();
- $key = Order::AUTOMATIC_RECEIPT_PREFIX . date('Ymd', strtotime("+15 days"));
- $redis->sadd($key, $params['order_id']);
- $model = OrderExpress::where('join_express_order_id', $params['order_id'])->first();
- if (!$model) {
- $model = new OrderExpress();
- // $sheet = OrderSheet::where('join_sheet_order_id', $request->post('order_id'))
- // ->select('join_sheet_goods_id')
- // ->first();
- // if(!empty($sheet->order_sheet_extend_json)){
- // $extendJson = json_decode($sheet->order_sheet_extend_json,true);
- // $address = ClientConfig::where('client_config_id',$extendJson['address_id'])->first();
- // $params['']
- // }
- }
- }
- // 该订单状态
- Order::where('order_id', $request->post('order_id'))->update($orderData);
- // 入配送记录表
- $model->join_express_order_id = $params['order_id'];
- if (isset($params['order_express_goods'])) {
- $model->order_express_goods = $params['order_express_goods'];
- }
- if (isset($params['order_express_company'])) {
- $model->order_express_company = $params['order_express_company'];
- }
- if (isset($params['order_express_code'])) {
- $model->order_express_code = $params['order_express_code'];
- }
- if (isset($params['order_express_city'])) {
- $model->order_express_city = $params['order_express_city'];
- }
- if (isset($params['order_express_address'])) {
- $model->order_express_address = $params['order_express_address'];
- }
- if (isset($params['order_express_mobile'])) {
- $model->order_express_mobile = $params['order_express_mobile'];
- }
- if (isset($params['order_express_telephone'])) {
- $model->order_express_telephone = $params['order_express_telephone'];
- }
- if (isset($params['order_express_person'])) {
- $model->order_express_person = $params['order_express_person'];
- }
- $model->order_express_remark = $params['order_express_remark'] ?? null;
- $model->order_express_addtimes = $params['order_express_addtimes'] ?? time();
- $model->save();
- Db::commit();
- return json_success('发货成功');
- } catch (\Exception $e) {
- Db::rollBack();
- dump($e->getMessage());
- return json_fail('发货失败');
- }
- }
- public function writeOff(Request $request)
- {
- $memberId = $request->post('member_id', '');
- $benefitId = $request->post('benefit_id', '');
- $nbr = $request->post('nbr');
- $times = $request->post('times', '');
- $code = $request->post('sms_code', '');
- if (!$memberId || !$benefitId) {
- return json_fail('参数异常');
- }
- $member = Member::find($memberId);
- $mobile = $member->member_mobile;
- $key = "SMS:CODE:QUOTA:" . $mobile;
- $redisCode = Redis::get($key);
- if ($redisCode != $code) {
- return json_fail("验证码错误,请重新输入");
- }
- Redis::del($key);
- $benefit = MemberBenefit::where('member_benefit_id', $benefitId)
- ->where('join_benefit_member_id', $memberId)
- ->first();
- if ($benefit->member_benefit_limit_count - $benefit->member_benefit_used_count < $nbr) {
- return json_fail('可核销数量不足');
- }
- if (!$times) {
- $times = date('Y-m-d H:i:s');
- } else {
- $times = date('Y-m-d H:i:s', strtotime($times));
- }
- try {
- Db::beginTransaction();
- // 减额度
- $benefit->member_benefit_used_count = $benefit->member_benefit_used_count + $nbr;
- // 用完了
- if ($benefit->member_benefit_limit_count <= $benefit->member_benefit_used_count) {
- $benefit->member_benefit_status = 'DONE';
- if (!empty($benefit->join_benefit_order_id)) {
- Order::where('order_id', $benefit->join_benefit_order_id)->update(['order_status_system' => 'DONE']);
- }
- }
- $benefit->save();
- // 记录核销
- $params = [
- 'dept_premises_id' => $request->post('dept_premises_id'),
- 'order_remark' => $request->post('remark'),
- 'write_off_member_id' => $request->post('write_off_member_id'),
- 'join_order_member_id' => $memberId
- ];
- $writeOffData = OrderService::generateWriteOffData($params);
- $appointments = Appointment::where('join_appointment_member_benefit_id', $benefitId)
- ->where('appointment_status', 'INIT')
- ->limit($nbr)
- ->get();
- foreach ($appointments as $appointment) {
- Appointment::where('appointment_id', $appointment->appointment_id)->update([
- 'appointment_status' => 'DONE',
- 'appointment_datetime' => $times,
- 'appointment_apply_datetime' => $times,
- 'appointment_doing_datetime' => $times,
- 'appointment_done_datetime' => $times,
- 'appointment_done_json' => json_encode($writeOffData)
- ]);
- }
- Db::commit();
- return json_success('核销成功');
- } catch (\Exception $e) {
- dump($e->getMessage());
- Db::rollBack();
- return json_fail('核销失败');
- }
- }
- public function writeOffDishes(Request $request)
- {
- $orderId = $request->post('order_id','');
- $memberId = $request->post('member_id', '');
- $times = $request->post('times', '');
- $code = $request->post('sms_code', '');
- if (!$memberId || !$orderId) {
- return json_fail('参数异常');
- }
- if (!$times) {
- $times = date('Y-m-d H:i:s');
- } else {
- $times = date('Y-m-d H:i:s', strtotime($times));
- }
- try {
- Db::beginTransaction();
- // 记录核销
- $params = [
- 'dept_premises_id' => $request->post('dept_premises_id'),
- 'order_remark' => $request->post('remark'),
- 'write_off_member_id' => $request->post('write_off_member_id'),
- 'join_order_member_id' => $memberId
- ];
- $writeOffData['charge'] = OrderService::generateWriteOffData($params);
- $writeOffData['charge']['order_id'] = $orderId;
- $writeOffData['charge']['member_id'] = $memberId;
- $writeOffData['charge']['order_code'] = random_string(10,'number');
- $writeOffData['express'] = 'N';
-
- Order::where('order_id',$orderId)->update([
- 'order_express_json'=>json_encode($writeOffData),
- 'order_is_complete'=>'Y',
- 'order_status_system'=>'DONE'
- ]);
- Db::commit();
- return json_success('核销成功');
- } catch (\Exception $e) {
- dump($e->getMessage());
- Db::rollBack();
- return json_fail('核销失败');
- }
- }
- public function myOrder(Request $request)
- {
- $memberId = $request->get('member_id', '');
- if (!$memberId) {
- return json_fail('查询错误');
- }
- $sheet = OrderSheet::with([
- 'goods' => function ($query) {
- $query->select('goods_id', 'goods_name', 'goods_cover');
- },
- 'order' => function ($query) {
- $query->select('order_id', 'order_status_system', 'order_status_payment', 'order_status_storage');
- },
- 'refund' => function ($query) {
- $query->select('join_return_order_id', 'orders_return_id', 'order_return_status');
- },
- ])->where('join_sheet_member_id', $memberId)
- ->orderBy('order_sheet_addtimes', 'desc')
- ->get()
- ->toArray();
- foreach ($sheet as &$item) {
- if (!empty($item->goods->goods_cover)) {
- $item->goods->goods_cover = getenv('STORAGE_DOMAIN') . $item->goods->goods_cover;
- }
- }
- // 预约单
- $appointments = Db::table('appointment')
- // ->leftJoin('member', 'member.member_id', '=', 'appointment.join_appointment_member_id')
- // ->leftJoin('member_cert', 'member_cert.join_cert_member_id', '=', 'appointment.join_appointment_member_id')
- // ->leftJoin('member_info', 'member_info.join_info_member_id', '=', 'appointment.join_appointment_member_id')
- ->leftJoin('goods', 'goods.goods_id', '=', 'appointment.join_appointment_goods_id')
- // ->leftJoin('order', 'order.order_id', '=', 'appointment.join_appointment_order_id')
- ->leftJoin('member_benefit', 'member_benefit.member_benefit_id', '=', 'appointment.join_appointment_member_benefit_id')
- // ->leftJoin('goods_sku', 'goods_sku.goods_sku_id', '=', 'appointment.join_appointment_goods_sku_id')
- ->where('join_appointment_member_id', $memberId)
- ->whereIn('appointment_status',['WAITING','PENDING','DOING','DONE','CANCEL','REVOKE'])
- ->select('appointment.*',
- // 'member.member_mobile',
- // 'member_cert.member_cert_name',
- // 'member_info.member_info_nickname',
- 'goods.goods_name', 'goods.goods_sales_price',
- // 'order.order_name', 'goods_sku.goods_sku_specs_json', 'order.order_amount_total', 'order.order_amount_pay',
- // 'order.order_category', 'order.order_status_system', 'order.order_status_payment', 'order.order_status_storage',
- // 'order.order_addtimes',
- 'member_benefit.member_benefit_name'
- )
- ->orderBy('appointment.appointment_addtimes', 'desc')
- ->get();
- foreach ($appointments as &$row) {
- if ($row->appointment_category == 'NOFEE') {
- $row->member_benefit_name = "后付费预约";
- }
- $row->appointment_addtimes = date('Y-m-d H:i:s', $row->appointment_addtimes);
- }
- return json_success('', ['order' => $sheet, 'appointment' => $appointments]);
- }
- public function saveExpress($params)
- {
- try {
- $express = new OrderExpress();
- $express->order_express_type = $params['order_express_type'];
- $express->join_express_order_id = $params['orderId'];
- $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_addtimes = time();
- $express->save();
- } catch (\Exception $e) {
- dump($e->getMessage());
- throw new BusinessException('物流信息保存失败');
- }
- }
- // TODO 确认收货(完成订单)
- public function confirm($id)
- {
- $order = Order::where('order_id', $id)->first();
- if (empty($order)) {
- return json_fail("暂无数据");
- }
- Db::beginTransaction();
- try {
- // 主订单
- Order::where('order_id', $id)->update(['order_status_system' => 'CONFIRM']);
- } catch (\Exception $e) {
- }
- }
- public function doRefund(Request $request)
- {
- $orderId = $request->post('order_id', '');
- // $returnId = $request->post('return_id', '');
- $amount = $request->post('refund_amount', 0);
- $password = $request->post('refund_password', '');
- if (!$orderId || !$amount || !$password) {
- return json_fail('参数异常');
- }
- if ($password != '123456'){
- return json_fail('支付密码错误');
- }
- $return = OrderReturn::where('join_return_order_id', $orderId)
- ->first();
- if (!$return) {
- return json_fail("退款订单异常");
- }
- $order = Order::where('order_id', $return->join_return_order_id)->first();
- if (!$order) {
- return json_fail("订单异常");
- }
- if ($order->order_is_complete == 'Y' || $order->order_is_complete == 'R') {
- return json_fail('订单已完成,无法退款');
- }
- if ($amount > $order->order_amount_pay) {
- return json_fail('退款金额不能超过订单金额');
- }
- $payDetail = PayDetail::where('join_pay_order_id', $order->order_groupby)->where('pay_status', 'SUCCESS')->first();
- if (!$payDetail) {
- return json_fail("支付信息异常异常");
- }
- $res = '[]';
- $data = '[]';
- try {
- Db::beginTransaction();
- // 订单主表
- Order::where('order_id', $return->join_return_order_id)->update(['order_is_complete' => 'R']);
- // return 表
- $return->order_return_status = 'DONE';
- $return->order_return_refund_json = json_encode(['amount'=>$amount]);
- $return->save();
- // 区分账户余额支付和通联支付
- if (in_array($payDetail->pay_prepayid, ['W06', 'A01'])) {
- $responseJson = [];
- if (!empty($payDetail->pay_json_response)) {
- $responseJson = json_decode($payDetail->pay_json_response, true);
- if (!isset($responseJson['trxid'])) {
- throw new PayException("支付信息异常");
- }
- }
- $data = [
- 'randomstr' => random_string(32),
- 'reqsn' => $return->join_return_order_id,
- 'oldtrxid' => $responseJson['trxid'],
- 'trxamt' => $amount * 100,
- ];
- $tlpay = new Tlpay();
- $res = $tlpay->refund($data);
-
- $resArray = json_decode($res, true);
- if (AppUtil::validSign($resArray)) {
- if ($resArray['retcode'] != 'SUCCESS' || $resArray['trxstatus'] != '0000') {
- throw new PayException('退款失败,原因:' . $resArray['errmsg']);
- }
- }
- }
- $payType = explode('-', $payDetail->pay_prepayid);
- // 余额支付
- if (isset($payType[1]) && $payType[1] == 'CASH') {
- $account = MemberAccount::where('join_account_member_id', $order->join_order_member_id)
- ->where('member_account_classify', 'CASH')
- ->first();
- $account->member_account_expend = $account->member_account_expend - $amount;
- $account->member_account_surplus = $account->member_account_surplus + $amount;
- $account->save();
- $data = [
- 'type' => 'REFUND',
- 'member_id' => $order->join_order_member_id,
- 'order_id' => $return->join_return_order_id,
- 'return_id' => $return->orders_return_id
- ];
- $res = json_encode([
- 'status' => 'SUCCESS'
- ]);
- }
- // 卡支付
- if (count($payType) == 1 && !in_array($payDetail->pay_prepayid, ['W06', 'A01'])) {
- $account = MemberAccount::where('join_account_member_id', $order->join_order_member_id)
- ->where('member_account_nbr', $payType[0])
- ->where('member_account_classify', 'CARD')
- ->first();
- $account->member_account_expend = $account->member_account_expend - $amount;
- $account->member_account_surplus = $account->member_account_surplus + $amount;
- $account->save();
- $data = [
- 'type' => 'REFUND',
- 'nbr' => $account->member_account_nbr,
- 'member_id' => $order->join_order_member_id,
- 'order_id' => $return->join_return_order_id,
- 'return_id' => $return->orders_return_id
- ];
- $res = json_encode([
- 'status' => 'SUCCESS'
- ]);
- }
- // 生成payDetail
- $payDetailData = [
- 'join_pay_member_id' => $order->join_order_member_id,
- 'join_pay_order_id' => $order->order_groupby,
- 'pay_status' => 'SUCCESS',
- 'pay_category' => 'REFUND',
- 'pay_amount' => $amount,
- 'pay_paytimes' => date('Y-m-d H:i:s'),
- 'pay_json_request' => json_encode($data),
- 'pay_json_response' => $res,
- 'pay_prepayid' => $payType[0].(!empty($payType[1]) ? '-'.$payType[1] : ''),
- 'pay_addtimes' => time()
- ];
- PayDetail::insert($payDetailData);
- Db::commit();
- _syslog("退款", "发起退款", json_decode($res), $data);
- return json_success("退款成功");
- } catch (PayException $e) {
- Db::rollBack();
- _syslog("退款", "发起退款", $e->getMessage(), $data);
- return json_fail($e->getMessage());
- } catch (\Exception $e) {
- Db::rollBack();
- dump($e->getTrace());
- _syslog("退款", "发起退款", $e->getMessage(), $data);
- return json_fail("数据更新失败");
- }
- }
- }
|