Commit 42755d97 by lizhilin

更新

parent 97542556
...@@ -16,7 +16,6 @@ ...@@ -16,7 +16,6 @@
class MerchantStore extends RowAction class MerchantStore extends RowAction
{ {
protected $type = 0;
protected $title = ''; protected $title = '';
...@@ -26,9 +25,8 @@ class MerchantStore extends RowAction ...@@ -26,9 +25,8 @@ class MerchantStore extends RowAction
* 接收参数 * 接收参数
* @type 1:增加库存 2:减少库存 * @type 1:增加库存 2:减少库存
*/ */
public function __construct($type = 0, $title = '', $goods_id = 0) public function __construct($title = '', $goods_id = 0)
{ {
$this->type = $type;
$this->goods_id = $goods_id; $this->goods_id = $goods_id;
parent::__construct($title); parent::__construct($title);
$this->title = $title; $this->title = $title;
...@@ -44,7 +42,7 @@ public function __construct($type = 0, $title = '', $goods_id = 0) ...@@ -44,7 +42,7 @@ public function __construct($type = 0, $title = '', $goods_id = 0)
*/ */
public function title() public function title()
{ {
return '<i class="feather icon-stop-circle"></i> ' . $this->title . $this->type . ''; return '<i class="feather icon-stop-circle"></i> ' . $this->title . '';
} }
/** /**
* Handle the action request. * Handle the action request.
...@@ -56,7 +54,6 @@ public function title() ...@@ -56,7 +54,6 @@ public function title()
public function handle(Request $request) public function handle(Request $request)
{ {
$id = $this->getKey() ?? 0; $id = $this->getKey() ?? 0;
$type = $request->get('type');
return $this->response()->success('成功')->refresh(); return $this->response()->success('成功')->refresh();
} }
...@@ -72,22 +69,13 @@ public function render() ...@@ -72,22 +69,13 @@ public function render()
$goodObj = Good::where("id", $this->goods_id)->first(); $goodObj = Good::where("id", $this->goods_id)->first();
//获取商品规格信息 //获取商品规格信息
if ($this->type == 1) { $gid = $this->goods_id;
$gid = $this->goods_id; $dataList = GoodSku::where("goods_id", $gid)->get();
$dataList = GoodSku::where("goods_id", $gid)->get(); foreach ($dataList as $kk => $vv) {
foreach ($dataList as $kk => $vv) { $dataList[$kk]['attr_id'] = $vv->id;
$dataList[$kk]['attr_id'] = $vv->id; //获取商户库存信息
//获取商户库存信息 $merStock = MerchantGoodSku::where(['goods_id' => $gid, 'attr_id' => $vv->id])->sum('stock');
$merStock = MerchantGoodSku::where(['goods_id' => $gid, 'attr_id' => $vv->id])->sum('stock'); $dataList[$kk]['stock'] = $vv->stock - $merStock;
$dataList[$kk]['stock'] = $vv->stock - $merStock;
}
} else {
$dataList = MerchantGoodSku::where("mgs_id", $mgs_id)->get();
foreach ($dataList as $kk => $vv) {
$skuObj = GoodSku::find($vv['attr_id']);
$dataList[$kk]['attr_id'] = $vv['attr_id'];
$dataList[$kk]['attr_val'] = $skuObj->attr_val;
}
} }
$dataArr = $dataList ? $dataList->toArray() : []; $dataArr = $dataList ? $dataList->toArray() : [];
...@@ -95,12 +83,8 @@ public function render() ...@@ -95,12 +83,8 @@ public function render()
$html = ''; $html = '';
foreach ($dataArr as $kk => $vv) { foreach ($dataArr as $kk => $vv) {
$html .= '<tr>'; $html .= '<tr>';
if ($this->type == 2) {
$html .= '<input type="hidden" name="sskuid[]" value="' . $vv['id'] . '">';
}
$html .= '<input type="hidden" name="goods_id" value="' . $this->goods_id . '">'; $html .= '<input type="hidden" name="goods_id" value="' . $this->goods_id . '">';
$html .= '<input type="hidden" name="mgs_id" value="' . $mgs_id . '">'; $html .= '<input type="hidden" name="mgs_id" value="' . $mgs_id . '">';
$html .= '<input type="hidden" name="typeid" value="' . $this->type . '">';
$html .= '<td style="text-align:center;vertical-align: middle;">' . $goodObj->goods_name . '<input type="hidden" name="attr_id[]" value="' . $vv['attr_id'] . '"></td>'; $html .= '<td style="text-align:center;vertical-align: middle;">' . $goodObj->goods_name . '<input type="hidden" name="attr_id[]" value="' . $vv['attr_id'] . '"></td>';
$html .= '<td style="text-align:center;vertical-align: middle;">' . $vv['attr_val'] . '</td>'; $html .= '<td style="text-align:center;vertical-align: middle;">' . $vv['attr_val'] . '</td>';
$html .= '<td ><input type="text" name="stock[]" value="" class="form-control field_remark _normal_" placeholder=""></td>'; $html .= '<td ><input type="text" name="stock[]" value="" class="form-control field_remark _normal_" placeholder=""></td>';
...@@ -141,12 +125,11 @@ public function render() ...@@ -141,12 +125,11 @@ public function render()
// </div> // </div>
// </form> // </form>
// '); // ');
->body(MerchantStoreForms::make(['id' => $this->type])) ->body(MerchantStoreForms::make(['id' => $mgs_id]))
->onShown( ->onShown(
<<<js <<<js
$(document).ready(function () { $(document).ready(function () {
console.log('{$html}'); console.log('{$html}');
$("#storeTitle").html('{$this->title}');
$("#tabletr").html('"+ $html +"'); $("#tabletr").html('"+ $html +"');
}); });
js js
......
<?php
namespace App\Admin\Actions;
use Dcat\Admin\Actions\Response;
use App\Admin\Forms\MerchantSubStoreForms;
use App\Models\Good;
use Dcat\Admin\Grid\RowAction;
use Dcat\Admin\Traits\HasPermissions;
use Illuminate\Contracts\Auth\Authenticatable;
//use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Dcat\Admin\Widgets\Modal;
use App\Models\GoodSku;
use App\Models\MerchantGoodSku;
class MerchantSubStore extends RowAction
{
protected $title = '';
protected $goods_id = 0;
/**
* 接收参数
* @type 1:增加库存 2:减少库存
*/
public function __construct($title = '', $goods_id = 0)
{
$this->goods_id = $goods_id;
parent::__construct($title);
$this->title = $title;
}
/**
* @return string
*/
//protected $title = '<i class="feather icon-stop-circle"> 增加库存 </i>';
/**
* 按钮文本
*
* @return string|void
*/
public function title()
{
return '<i class="feather icon-stop-circle"></i> ' . $this->title . '';
}
/**
* Handle the action request.
*
* @param Request $request
*
* @return Response
*/
public function handle(Request $request)
{
$id = $this->getKey() ?? 0;
return $this->response()->success('成功')->refresh();
}
/**
* 渲染模态框.
* @return Modal
*/
public function render()
{
$mgs_id = $this->getKey() ?? 0;
$goodObj = Good::where("id", $this->goods_id)->first();
//获取商品规格信息
$dataList = MerchantGoodSku::where("mgs_id", $mgs_id)->get();
foreach ($dataList as $kk => $vv) {
$skuObj = GoodSku::find($vv['attr_id']);
$dataList[$kk]['attr_id'] = $vv['attr_id'];
$dataList[$kk]['attr_val'] = $skuObj->attr_val;
}
$dataArr = $dataList ? $dataList->toArray() : [];
$html = '';
foreach ($dataArr as $kk => $vv) {
$html .= '<tr>';
$html .= '<input type="hidden" name="sskuid[]" value="' . $vv['id'] . '">';
$html .= '<input type="hidden" name="goods_id" value="' . $this->goods_id . '">';
$html .= '<input type="hidden" name="mgs_id" value="' . $mgs_id . '">';
$html .= '<td style="text-align:center;vertical-align: middle;">' . $goodObj->goods_name . '<input type="hidden" name="attr_id[]" value="' . $vv['attr_id'] . '"></td>';
$html .= '<td style="text-align:center;vertical-align: middle;">' . $vv['attr_val'] . '</td>';
$html .= '<td ><input type="text" name="stock[]" value="" class="form-control field_remark _normal_" placeholder=""></td>';
$html .= '<td style="text-align:center;vertical-align: middle;">' . $vv['stock'] . '</td>';
$html .= '</tr>';
}
// 这里直接创建一个modal框 model的内容由工具表单提供,这里也需要创建一个工具表单才行
//
return Modal::make()
->lg()
->title($this->title)
->button($this->title)
->body(MerchantSubStoreForms::make(['id' => $mgs_id]))
->onShown(
<<<js
$(document).ready(function () {
console.log('{$html}');
$("#tabletr2").html('"+ $html +"');
});
js
);
//->button("<button class='btn btn-sm btn-primary'>$this->title</button>"); // 这个button就是对应上面的按钮
}
/**
* @return string|array|void
*/
public function confirm()
{
// return ['Confirm?', 'contents'];
}
/**
* @param Model|Authenticatable|HasPermissions|null $user
*
* @return bool
*/
protected function authorize($user): bool
{
return true;
}
/**
* @return array
*/
protected function parameters()
{
return [];
}
}
...@@ -184,8 +184,9 @@ protected function form() ...@@ -184,8 +184,9 @@ protected function form()
'field16' => '', 'field16' => '',
]; ];
$form->keyValue('tags', '标签')->default($fieldArr) $form->keyValue('tags', '标签')->default($fieldArr)
->setKeyLabel('键 (field开头拼上数字)') ->setKeyLabel('键 (field开头拼上数字,商品列表页filed1-9,商品详情页field10-19)')
->setValueLabel('值'); ->setValueLabel('值')
;
//->disableCreateButton(); //->disableCreateButton();
//->disableDelete(); //->disableDelete();
})->tab('详情', function (Form $form) { })->tab('详情', function (Form $form) {
......
...@@ -13,7 +13,8 @@ ...@@ -13,7 +13,8 @@
use App\Models\Store; use App\Models\Store;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Dcat\Admin\Http\Controllers\AdminController; use Dcat\Admin\Http\Controllers\AdminController;
use App\Admin\Actions\MerchantStore as MerchantStoreActions; use App\Admin\Actions\MerchantStore as MerchantAddStore;
use App\Admin\Actions\MerchantSubStore;
use Dcat\Admin\Admin; use Dcat\Admin\Admin;
use Dcat\Admin\Layout\Content; use Dcat\Admin\Layout\Content;
use Illuminate\Http\Request; use Illuminate\Http\Request;
...@@ -63,11 +64,11 @@ protected function grid() ...@@ -63,11 +64,11 @@ protected function grid()
$grid->actions(function (Grid\Displayers\Actions $actions) { $grid->actions(function (Grid\Displayers\Actions $actions) {
//当前status //当前status
$status = $actions->row->status; //$status = $actions->row->status;
if ($status == 0) { //if ($status == 0) {
$actions->append(new MerchantStoreActions(1, '增加库存', $actions->row->goods_id)); $actions->append(new MerchantAddStore('增加库存', $actions->row->goods_id));
$actions->append(new MerchantStoreActions(2, '减少库存', $actions->row->goods_id)); $actions->append(new MerchantSubStore('减少库存', $actions->row->goods_id));
} //}
}); });
}); });
} }
......
...@@ -69,18 +69,19 @@ protected function form() ...@@ -69,18 +69,19 @@ protected function form()
{ {
$form = Form::make(new StoreAdminUsers(), function (Form $form) { $form = Form::make(new StoreAdminUsers(), function (Form $form) {
$form->display('id'); $form->display('id');
//$form->ignore(['merchant_id', 'store_id']); // 忽略password字段 //$form->ignore(['pwd']); // 忽略password字段
$form->text('name')->required(); $form->text('name')->required();
$form->text('username'); $form->text('username');
if ($form->isCreating()) { if ($form->isCreating()) {
$form->password('password', '密码')->saving(function ($password) { $form->password('password', '密码')->saving(function ($password) {
return bcrypt($password); return bcrypt($password);
})->help('字母数字组合,长度大于5个字符'); })->help('字母数字组合,长度大于5个字符');
} else { // } else {
// $form->password('password', '密码')->customFormat(function ($v) { // $form->text('password', '密码')->help('密码为空则不修改');
// return $v; // $form->password = '';
// }) }
// ->help('密码为空则不修改'); if ($form->isEditing()) {
$form->text('pwd', '密码')->help('密码为空则不修改');
} }
$form->hidden('role_id')->default(2); $form->hidden('role_id')->default(2);
...@@ -88,18 +89,18 @@ protected function form() ...@@ -88,18 +89,18 @@ protected function form()
$form->select('merchant_id', '商家名称') $form->select('merchant_id', '商家名称')
->options(Merchant::whereNull('deleted_at')->get()->pluck('name', 'id')) ->options(Merchant::whereNull('deleted_at')->get()->pluck('name', 'id'))
//->rules('required') //->rules('required')
->load('store_id', '/get-store-list') ->load('store_id', '/get-store-list');
->saving(function (Form $form, $data) { // ->saving(function (Form $form, $data) {
// 当编辑记录时,设置选中的父分类和子分类 // // 当编辑记录时,设置选中的父分类和子分类
if ($form->isEditing()) { // if ($form->isEditing()) {
$form->html('<script> // $form->html('<script>
$(document).ready(function() { // $(document).ready(function() {
$("#merchant_id").val(' . $data->merchant_id . '); // 设置父分类的选中值 // $("#merchant_id").val(' . $data->merchant_id . '); // 设置父分类的选中值
$("#store_id").trigger("change"); // 触发事件加载子级选项 // $("#store_id").trigger("change"); // 触发事件加载子级选项
}); // });
</script>'); // </script>');
} // }
}); // });
$form->select('store_id', '门店名称'); $form->select('store_id', '门店名称');
$form->disableCreatingCheck(); $form->disableCreatingCheck();
...@@ -109,47 +110,18 @@ protected function form() ...@@ -109,47 +110,18 @@ protected function form()
$form->disableViewButton(); $form->disableViewButton();
}); });
// 判断是否处于创建模式
if ($form->isCreating()) {
}
// 判断是否处于编辑模式
if ($form->isEditing()) {
// 如果是编辑模式,执行相关操作
$form->select('merchant_id', '显示名称')
->options([
1 => '选项1',
2 => '选项2',
3 => '选项3',
])
->value(function () {
// 获取模型对
return 1;
});
}
//副表保存规格 //副表保存规格
// $form->saved( $form->saved(
// function (Form $form, $result) { function (Form $form, $result) {
// $store_admin_users_id = $form->getKey(); $store_admin_users_id = $form->getKey();
// $merchant_id = $form->model()->merchant_id; $pwd = $form->model()->pwd;
// $store_id = $form->model()->store_id; //更新信息
// //更新信息 if ($pwd) {
// $verifier = DB::table('verifier')->where("store_admin_users_id", $store_admin_users_id)->first(); $data = ['password' => bcrypt($pwd), 'pwd' => ''];
// $time = time(); DB::table('store_admin_users')->where("id", $store_admin_users_id)->update($data);
// if (!$verifier) { }
// $v_id = DB::table('verifier')->insertGetId( }
// ['store_admin_users_id' => $store_admin_users_id, 'merchant_id' => $merchant_id, 'store_id' => $store_id, 'created_at' => date('Y-m-d H:i:s', $time), 'updated_at' => date('Y-m-d H:i:s', $time)] );
// );
// } else {
// $verifier->merchant_id = $merchant_id;
// $verifier->store_id = $store_id;
// $verifier->save();
// }
// }
// );
return $form; return $form;
} }
......
...@@ -28,12 +28,11 @@ class MerchantStoreForms extends Form implements LazyRenderable ...@@ -28,12 +28,11 @@ class MerchantStoreForms extends Form implements LazyRenderable
*/ */
public function handle(array $input) public function handle(array $input)
{ {
$typeid = (int)$_POST['typeid']; //1:增加 2:编辑
$goods_id = (int)$_POST['goods_id']; $goods_id = (int)$_POST['goods_id'];
$mgs_id = (int)$_POST['mgs_id']; $mgs_id = (int)$_POST['mgs_id'];
$attr_ids = $_POST['attr_id']; $attr_ids = $_POST['attr_id'];
$stocks = $_POST['stock']; $stocks = $_POST['stock'];
$sskuids = isset($_POST['sskuid']) ? $_POST['sskuid'] : [];
if (!$goods_id || !$mgs_id || !$attr_ids || !$stocks) { if (!$goods_id || !$mgs_id || !$attr_ids || !$stocks) {
return $this->response()->error('参数错误')->refresh(); return $this->response()->error('参数错误')->refresh();
} }
...@@ -41,57 +40,37 @@ public function handle(array $input) ...@@ -41,57 +40,37 @@ public function handle(array $input)
$msgObj = MerchantGoodsStore::find($mgs_id); $msgObj = MerchantGoodsStore::find($mgs_id);
$merchant_id = $msgObj->merchant_id; $merchant_id = $msgObj->merchant_id;
$logData = []; $logData = [];
if ($typeid == 1) {
foreach ($attr_ids as $kk => $vv) {
$gskuObj = GoodSku::find($vv);
$stockNum = ($gskuObj->stock >= $stocks[$kk] && $stocks[$kk]) ? (int)$stocks[$kk] : 0;
//$tmp['stock'] = $stockNum;
//查下库存记录是否存在
$skuObj = MerchantGoodSku::where(['mgs_id' => $mgs_id, 'goods_id' => $goods_id, 'attr_id' => $vv])->first();
if ($skuObj) {
$skuObj->stock += $stockNum;
$skuObj->save();
} else {
$skuObj = new MerchantGoodSku();
$skuObj->mgs_id = $mgs_id;
$skuObj->merchant_id = $merchant_id;
$skuObj->goods_id = $goods_id;
$skuObj->attr_id = $vv;
$skuObj->stock = $stockNum;
$skuObj->save();
}
//记录操作日志 foreach ($attr_ids as $kk => $vv) {
$logData[$kk]['mgs_id'] = $mgs_id; $gskuObj = GoodSku::find($vv); //商品信息
$logData[$kk]['goods_id'] = $goods_id; //获取商户库存信息
$logData[$kk]['attr_id'] = $gskuObj->id; $merStock = MerchantGoodSku::where(['goods_id' => $goods_id, 'attr_id' => $vv])->sum('stock');
$logData[$kk]['change'] = $stockNum; $surplusStock = $gskuObj->stock - $merStock; //可供库存数量
$logData[$kk]['created_at'] = date('Y-m-d H:i:s'); $stockNum = ($surplusStock >= $stocks[$kk] && $stocks[$kk]) ? (int)$stocks[$kk] : 0;
$this->addStoreLog($logData);
} //查下库存记录是否存在
} else { $skuObj = MerchantGoodSku::where(['mgs_id' => $mgs_id, 'goods_id' => $goods_id, 'attr_id' => $vv])->first();
if (!$sskuids) { if ($skuObj) {
return $this->response()->error('参数错误')->refresh(); $skuObj->stock += $stockNum;
} $skuObj->save();
foreach ($sskuids as $kk => $vv) { } else {
//商家规格数据 $skuObj = new MerchantGoodSku();
$skuObj = MerchantGoodSku::find($vv); $skuObj->mgs_id = $mgs_id;
$store_num = (int)$stocks[$kk]; //减少库存数 $skuObj->merchant_id = $merchant_id;
$diffnum = $skuObj->stock - $store_num; //减少差值 $skuObj->goods_id = $goods_id;
if ($store_num && $diffnum >= 0) { $skuObj->attr_id = $vv;
$skuObj->stock = $diffnum; $skuObj->stock = $stockNum;
$skuObj->save(); $skuObj->save();
//记录操作日志
$logData[$kk]['mgs_id'] = $mgs_id;
$logData[$kk]['attr_id'] = $skuObj->attr_id;
$logData[$kk]['goods_id'] = $goods_id;
$logData[$kk]['change'] = -$store_num;
$logData[$kk]['created_at'] = date('Y-m-d H:i:s');
$this->addStoreLog($logData);
}
} }
}
//记录操作日志
$logData[$kk]['mgs_id'] = $mgs_id;
$logData[$kk]['goods_id'] = $goods_id;
$logData[$kk]['attr_id'] = $gskuObj->id;
$logData[$kk]['change'] = $stockNum;
$logData[$kk]['created_at'] = date('Y-m-d H:i:s');
}
$this->addStoreLog($logData);
return $this return $this
->response() ->response()
...@@ -123,7 +102,7 @@ public function form() ...@@ -123,7 +102,7 @@ public function form()
<tr> <tr>
<th width="23%" style="text-align:center;">商品名称</th> <th width="23%" style="text-align:center;">商品名称</th>
<th width="23%" style="text-align:center;">商品规格</th> <th width="23%" style="text-align:center;">商品规格</th>
<th width="23%" style="text-align:center;" id="storeTitle"></th> <th width="23%" style="text-align:center;">增加库存</th>
<th width="23%" style="text-align:center;">剩余库存</th> <th width="23%" style="text-align:center;">剩余库存</th>
</tr> </tr>
</thead> </thead>
...@@ -143,13 +122,6 @@ public function form() ...@@ -143,13 +122,6 @@ public function form()
} }
public function render2()
{
// // 构建表单
return view('admin.mstore');
//return parent::render();
}
/** /**
* The data of the form. * The data of the form.
* *
......
<?php
namespace App\Admin\Forms;
use App\Models\GoodSku;
use App\Models\MerchantGoodsStore;
use App\Models\MerchantGoodSku;
use Dcat\Admin\Widgets\Form;
use Dcat\Admin\Layout\Row;
use Dcat\Admin\Form\NestedForm;
use Dcat\Admin\Widgets\Table;
use Dcat\Admin\Widgets\Tool;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Illuminate\Support\Facades\DB;
//
class MerchantSubStoreForms extends Form implements LazyRenderable
{
use LazyWidget;
protected $modalId = 'show-current-user';
/**
* Handle the form request.
*
* @param array $input
*
* @return mixed
*/
public function handle(array $input)
{
$goods_id = (int)$_POST['goods_id'];
$mgs_id = (int)$_POST['mgs_id'];
$attr_ids = $_POST['attr_id'];
$stocks = $_POST['stock'];
$sskuids = isset($_POST['sskuid']) ? $_POST['sskuid'] : [];
if (!$goods_id || !$mgs_id || !$attr_ids || !$stocks) {
return $this->response()->error('参数错误')->refresh();
}
if (!$sskuids) {
return $this->response()->error('参数错误')->refresh();
}
$logData = [];
foreach ($sskuids as $kk => $vv) {
//商家规格数据
$skuObj = MerchantGoodSku::find($vv);
$store_num = (int)$stocks[$kk]; //减少库存数
$diffnum = $skuObj->stock - $store_num; //减少差值
if ($store_num && $diffnum >= 0) {
$skuObj->stock = $diffnum;
$skuObj->save();
//记录操作日志
$logData[$kk]['mgs_id'] = $mgs_id;
$logData[$kk]['attr_id'] = $skuObj->attr_id;
$logData[$kk]['goods_id'] = $goods_id;
$logData[$kk]['change'] = -$store_num;
$logData[$kk]['created_at'] = date('Y-m-d H:i:s');
}
}
$this->addStoreLog($logData);
return $this
->response()
->success('Processed successfully.')
->refresh();
}
private function addStoreLog($data = [])
{
if (!$data) {
return true;
}
DB::table('merchant_store_sku_log')->insert($data);
}
/**
* Build a form here.
*/
public function form()
{
//$this->text('name')->required();
// 异步加载的字段
$this->html('<div class="row">
<div class="col-md-12">
<table class="table">
<thead>
<tr>
<th width="23%" style="text-align:center;">商品名称</th>
<th width="23%" style="text-align:center;">商品规格</th>
<th width="23%" style="text-align:center;">减少库存</th>
<th width="23%" style="text-align:center;">剩余库存</th>
</tr>
</thead>
<tbody id="tabletr2">
</tbody>
</table>
</div>
</div>');
}
/**
* The data of the form.
*
* @return array
*/
public function default()
{
return [
'name' => '6785678567',
'email' => 'John.Doe@gmail.com',
];
}
}
...@@ -76,5 +76,5 @@ ...@@ -76,5 +76,5 @@
$router->get('city', 'CityController@getList'); //城市选择-联动 $router->get('city', 'CityController@getList'); //城市选择-联动
$router->get('get-store-list', 'MerchantStoreController@getList'); //门店选择-联动 $router->get('get-store-list', 'MerchantGoodsStoreController@getList'); //门店选择-联动
}); });
...@@ -193,7 +193,6 @@ public function getDetail(Request $request) ...@@ -193,7 +193,6 @@ public function getDetail(Request $request)
} }
$skufield = $goods->sku ? json_decode($goods->sku, true) : []; $skufield = $goods->sku ? json_decode($goods->sku, true) : [];
$attrsKey = isset($skufield['attrs']) ? array_keys($skufield['attrs']) : [];
$attrsVal = isset($skufield['attrs']) ? array_values($skufield['attrs']) : []; $attrsVal = isset($skufield['attrs']) ? array_values($skufield['attrs']) : [];
$skuOneData = isset($skufield['sku'][0]) ? $skufield['sku'][0] : []; $skuOneData = isset($skufield['sku'][0]) ? $skufield['sku'][0] : [];
$attr_txt = ''; $attr_txt = '';
...@@ -213,6 +212,8 @@ public function getDetail(Request $request) ...@@ -213,6 +212,8 @@ public function getDetail(Request $request)
$market_price = isset($skuOneData['market_price']) ? sprintf("%.2f", $skuOneData['market_price']) : ''; $market_price = isset($skuOneData['market_price']) ? sprintf("%.2f", $skuOneData['market_price']) : '';
$dg_price = isset($skuOneData['cg_price']) ? sprintf("%.2f", $skuOneData['cg_price']) : ''; $dg_price = isset($skuOneData['cg_price']) ? sprintf("%.2f", $skuOneData['cg_price']) : '';
$stock = isset($skuOneData['stock']) ? $skuOneData['stock'] : 0; $stock = isset($skuOneData['stock']) ? $skuOneData['stock'] : 0;
//标签
$tags = $goods->tags ? json_decode($goods->tags, true) : [];
$data = [ $data = [
'id' => $goods->id, 'id' => $goods->id,
...@@ -226,7 +227,8 @@ public function getDetail(Request $request) ...@@ -226,7 +227,8 @@ public function getDetail(Request $request)
'attr' => $attr, 'attr' => $attr,
'attr_txt' => trim($attr_txt, ", "), 'attr_txt' => trim($attr_txt, ", "),
'is_collect' => 0, 'is_collect' => 0,
//'goods_desc' => $goods->goods_desc ?? '' 'tags' => $tags,
'goods_desc' => $goods->goods_desc ?? ''
]; ];
return $this->JsonResponse($data); return $this->JsonResponse($data);
} }
......
...@@ -183,23 +183,30 @@ public function CreateOrder(Request $request) ...@@ -183,23 +183,30 @@ public function CreateOrder(Request $request)
} }
//商品信息 //商品信息
$goods_id = $cartRow['goods_id']; $goods_id = $cartRow['goods_id'];
$attr_id = $cartRow['attr_id'];
$goodsObj = GoodModel::find($goods_id); $goodsObj = GoodModel::find($goods_id);
$skuObj = GoodSku::find($attr_id);
if (!$goodsObj || !$skuObj) {
unset($shoppingCart[$key]);
continue;
}
$goods_price = $merchant_id ? $skuObj->cg_price : $skuObj->market_price;
$goods_img = isset($goodsObj->cover_img) ? $goodsObj->cover_img : ''; $goods_img = isset($goodsObj->cover_img) ? $goodsObj->cover_img : '';
$goods_name .= $goodsObj->goods_name . "、"; $goods_name .= $goodsObj->goods_name . "、";
$tmp = []; $tmp = [];
$tmp['goods_id'] = $goods_id; $tmp['goods_id'] = $goods_id;
$tmp['goods_number'] = $cartRow['num']; $tmp['goods_number'] = $cartRow['num'];
$tmp['goods_price'] = $cartRow['goods_price']; $tmp['goods_price'] = $goods_price;
$tmp['goods_attr'] = $cartRow['attr_txt']; $tmp['goods_attr'] = $cartRow['attr_txt'];
$tmp['attr_id'] = $cartRow['attr_id']; $tmp['attr_id'] = $attr_id;
$tmp['goods_name'] = $goodsObj->goods_name; $tmp['goods_name'] = $goodsObj->goods_name;
$tmp['goods_img'] = $goods_img; $tmp['goods_img'] = $goods_img;
$tmp['merchant_id'] = $merchant_id; $tmp['merchant_id'] = $merchant_id;
$tmp['created_at'] = date("Y-m-d H:i:s"); $tmp['created_at'] = date("Y-m-d H:i:s");
array_push($orderGoods, $tmp); array_push($orderGoods, $tmp);
//总价 //总价
$total_price += ((float)$cartRow['goods_price'] * (int)$cartRow['num']); $total_price += ((float)$goods_price * (int)$cartRow['num']);
//删除购物车商品 //删除购物车商品
unset($shoppingCart[$key]); unset($shoppingCart[$key]);
} }
...@@ -250,11 +257,49 @@ private function getOrderSn() ...@@ -250,11 +257,49 @@ private function getOrderSn()
//'20231229875256'; //'20231229875256';
$order_sn = date('Ymd') . mt_rand(1000, 9999) . substr(implode("", array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8); $order_sn = date('Ymd') . mt_rand(1000, 9999) . substr(implode("", array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
$rowObj = OrderInfoModel::where('order_sn', $order_sn)->first(); $rowObj = OrderInfoModel::where('order_sn', $order_sn)->first();
$flag = $rowObj ? 1 : 0; $flag = $rowObj ? 0 : 1;
} while ($flag > 0); } while ($flag < 1);
return $order_sn; return $order_sn;
} }
//订单支付
public function pay(Request $request)
{
$order_id = $request->order_id ?? 0;
$openid = $request->user()->openid;
DB::beginTransaction();
try {
$res = '';
$order = OrderInfoModel::find($order_id);
if ($order->pay_cs > 0) {
$order_record = $order->order_record ?? $order->order_sn;
$order->order_sn = $this->getOrderSn();
$order->order_record = $order_record . "|" . $order->order_sn;
$order->save();
}
$orderGoodsObj = OrderGoods::where("order_id", $order_id)->first();
$order_title = $orderGoodsObj ? $orderGoodsObj->goods_name : '';
$res = Pay::pay($order_title, $order->order_sn, $order->order_amount, $openid);
$order->pay_cs += 1;
$order->save();
DB::commit();
return $this->JsonResponse($res);
} catch (\Exception $exception) {
Log::add('拉起微信支付失败', $exception->getMessage());
return $this->JsonResponse('', '拉起微信支付失败', 201);
}
}
//付款回调
public function payNotify(Request $request)
{
$fields = $request->query->all();
return $this->JsonResponse(Pay::payNotify($fields));
}
// 已完成:用户点击确认收货或发货后3天,自动变更为已完成状态 // 已完成:用户点击确认收货或发货后3天,自动变更为已完成状态
// 售后:已完成状态下48小时内展示申请售后按钮,可申请售后,如超过48小时,则不展示申请售后按钮 // 售后:已完成状态下48小时内展示申请售后按钮,可申请售后,如超过48小时,则不展示申请售后按钮
...@@ -358,22 +403,38 @@ public function delOrder(Request $request) ...@@ -358,22 +403,38 @@ public function delOrder(Request $request)
return $this->JsonResponse(''); return $this->JsonResponse('');
} }
//确认收货(订单完成--可申请售后) //确认收货(订单完成)
public function completeOrder(Request $request) // public function completeOrder(Request $request)
// {
// $order_id = $request->order_id ?? null;
// if (!$order_id) {
// return $this->JsonResponse('', '参数错误', 201);
// }
// $model = OrderInfoModel::find($order_id);
// if ($model->user_id != $request->user()->id) {
// return $this->JsonResponse('', '非本人订单', 201);
// }
// $model->shipping_status = 2;
// $model->order_status = 2;
// $model->received_at = date("Y-m-d H:i:s");
// $model->save();
// return $this->JsonResponse('');
// }
//扫码核销
public function scanCodeVerifi(Request $request)
{ {
$order_id = $request->order_id ?? null; $code = $request->code ?? '';
if (!$order_id) { $orderObj = OrderInfoModel::where('verification_code', $code)->first();
if (!$orderObj) {
return $this->JsonResponse('', '参数错误', 201); return $this->JsonResponse('', '参数错误', 201);
} }
if (!$orderObj->verification_at) {
$model = OrderInfoModel::find($order_id); $orderObj->order_status = 3;
if ($model->user_id != $request->user()->id) { $orderObj->verification_at = date("Y-m-d H:i:s");
return $this->JsonResponse('', '非本人订单', 201); $orderObj->save();
} }
$model->shipping_status = 2;
$model->order_status = 2;
$model->received_at = date("Y-m-d H:i:s");
$model->save();
return $this->JsonResponse(''); return $this->JsonResponse('');
} }
......
...@@ -30,7 +30,7 @@ public function getList(Request $request) ...@@ -30,7 +30,7 @@ public function getList(Request $request)
if ($listData->toArray()) { if ($listData->toArray()) {
foreach ($listData as $kk => $vv) { foreach ($listData as $kk => $vv) {
$data['list'][] = [ $data['list'][] = [
'title' => $vv->title, 'title' => isset(OrderDivideRecord::COMMISSION_TYPE[$vv->sh_type]) ? OrderDivideRecord::COMMISSION_TYPE[$vv->sh_type] : '',
'created_at' => date("Y-m-d H:i:s", strtotime($vv->created_at)), 'created_at' => date("Y-m-d H:i:s", strtotime($vv->created_at)),
'divide_price' => $vv->divide_price 'divide_price' => $vv->divide_price
]; ];
......
...@@ -45,10 +45,10 @@ public function addShoppingCart(Request $request) ...@@ -45,10 +45,10 @@ public function addShoppingCart(Request $request)
$attr_sn = md5($attrStr); $attr_sn = md5($attrStr);
$goodsAttrObj = GoodSku::where("goods_id", $goods_id)->where("attr_sn", $attr_sn)->first(); $goodsAttrObj = GoodSku::where("goods_id", $goods_id)->where("attr_sn", $attr_sn)->first();
Log::add('添加购物车商品规格', $goodsAttrObj->toArray());
if (!$goodsAttrObj) { if (!$goodsAttrObj) {
return $this->JsonResponse('', '该规格参数有误,选择其它规格', 500); return $this->JsonResponse('', '该规格参数有误,选择其它规格', 500);
} }
Log::add('添加购物车商品规格', $goodsAttrObj->toArray());
$attr_id = $goodsAttrObj->id; $attr_id = $goodsAttrObj->id;
$attr_txt = $goodsAttrObj->attr_val; $attr_txt = $goodsAttrObj->attr_val;
$goods_price = $merchant_id ? $goodsAttrObj->cg_price : $goodsAttrObj->market_price; $goods_price = $merchant_id ? $goodsAttrObj->cg_price : $goodsAttrObj->market_price;
......
...@@ -4,8 +4,6 @@ ...@@ -4,8 +4,6 @@
use App\Command\Log; use App\Command\Log;
use App\Models\OrderDivideRecord; use App\Models\OrderDivideRecord;
use App\Models\Service;
use App\Models\StoreInfo;
use Illuminate\Bus\Queueable; use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique; use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Contracts\Queue\ShouldQueue;
...@@ -48,35 +46,11 @@ public function handle() ...@@ -48,35 +46,11 @@ public function handle()
try { try {
$this->order->order_status = 4; //已完成 $this->order->order_status = 4; //已完成
$this->order->save(); $this->order->save();
//佣金分配 //佣金分配
OrderDivideRecord::divide($this->order->id); OrderDivideRecord::divide($this->order->id);
// switch ($this->order->business_id) {
// case 0:
// $this->order->store_order->status = 2;
// $this->order->store_order->over_time = date('Y-m-d H:i:s');
// $this->order->store_order->save();
// $store = StoreInfo::where(['store_id' => $this->order->store_order->store_id])->first();
// $store->total_revenue += $this->order->pay_money;
// $store->balance += $this->order->pay_money;
// $store->save();
// dispatch(new AutoCommentOrder($this->order, (3 * 24 * 3600)));
// break;
// case 1:
// case 2:
// case 3:
// case 4:
// case 5:
// $fcbl = Service::find($this->order->service_id)->fenmo ?? 0;
// //订单佣金分配
// Employee::divide($this->order->id, $this->order->em_id, $this->order->pay_money, $fcbl);
// dispatch(new AutoCommentOrder($this->order, (3 * 24 * 3600)));
// break;
// default:
// break;
// }
DB::commit(); DB::commit();
//dispatch(new AutoCommentOrder($this->order, (3 * 24 * 3600)));
Log::add('订单自动完成', $this->order->toArray()); Log::add('订单自动完成', $this->order->toArray());
} catch (\Exception $exception) { } catch (\Exception $exception) {
DB::rollBack(); DB::rollBack();
......
...@@ -13,6 +13,12 @@ class OrderDivideRecord extends Model ...@@ -13,6 +13,12 @@ class OrderDivideRecord extends Model
use SoftDeletes; use SoftDeletes;
protected $table = 'order_divide_record'; protected $table = 'order_divide_record';
public const COMMISSION_TYPE = [
1 => '直推佣金',
2 => '间推佣金',
3 => '用户取货佣金',
];
//收益分配 //收益分配
public static function divide($order_id) public static function divide($order_id)
......
<?php
namespace App\Models;
use App\Command\Log;
use EasyWeChat\Factory;
use Illuminate\Support\Facades\DB;
class Pay
{
private static function getConfig()
{
return $config = [
// 必要配置
'app_id' => env('WX_XCX_APPID'),
'mch_id' => env('WX_XCX_MCH_ID'),
'key' => env('WX_XCX_MCH_KEY'), // API v2 密钥 (注意: 是v2密钥 是v2密钥 是v2密钥)
// 如需使用敏感接口(如退款、发送红包等)需要配置 API 证书路径(登录商户平台下载 API 证书)
'cert_path' => public_path() . '/cert/apiclient_cert.pem', // XXX: 绝对路径!!!!
'key_path' => public_path() . '/cert/apiclient_key.pem', // XXX: 绝对路径!!!!
'notify_url' => '/', // 你也可以在下单时单独设置来想覆盖它
];
}
public static function pay($body, $order_sn, $order_price, $openid)
{
$orderPrice = intval(strval($order_price * 100));
$app = Factory::payment(self::getConfig());
$jssdk = $app->jssdk;
$result = $app->order->unify([
'body' => $body,
'out_trade_no' => $order_sn,
// 'total_fee' => $order_price*100,
'total_fee' => $orderPrice,
// 'spbill_create_ip' => '123.12.12.123', // 可选,如不传该参数,SDK 将会自动获取相应 IP 地址
//'notify_url' => 'https://pay.weixin.qq.com/wxpay/pay.action', // 支付结果通知网址,如果不设置则会使用配置里的默认地址
'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
'openid' => $openid,
'notify_url' => env('API_URL') . '/pay-notify',
]);
Log::add('订单支付_', $result);
if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
$prepayId = $result['prepay_id'];
$config = $jssdk->sdkConfig($prepayId);
return $config;
}
if ($result['return_code'] == 'FAIL' && array_key_exists('return_msg', $result)) {
throw new \Exception($result['return_msg']);
}
throw new \Exception($result['err_code_des']);
}
public static function payNotify($fields = [])
{
$app = Factory::payment(self::getConfig());
$response = $app->handlePaidNotify(function ($message, $fail) {
$orderObj = OrderInfo::where(['order_sn' => $message['out_trade_no']])->first();
if (!$orderObj) {
$fail('订单不存在');
}
Log::add('--支付回调--', $message);
//支付完成后的业务逻辑[result_code] => SUCCESS
if ($orderObj->pay_status == 1) {
return true;
}
if ($message['result_code'] == "SUCCESS") {
DB::beginTransaction();
try {
//更新订单
$orderObj->order_status = 1;
$orderObj->pay_status = 1;
$orderObj->save();
//更新商品销量、库存
$goodsList = OrderGoods::where("order_id", $orderObj->id)->get();
foreach ($goodsList as $item) {
$gid = $item->goods_id;
$attr_id = $item->attr_id;
$mer_id = $item->merchant_id;
$goods_number = $item->goods_number;
//更新商品规格库存
$attrObj = GoodSku::find($attr_id);
$attr_stock = ($attrObj->stock - $goods_number) > 0 ? $attrObj->stock - $goods_number : 0;
$attrObj->stock = $attr_stock;
$attrObj->save();
//商户规格库存
$mgsObj = MerchantGoodSku::where(['goods_id' => $gid, 'attr_id' => $attr_id, 'merchant_id' => $mer_id])->first();
if ($mer_id && $mgsObj) {
$changeStock = ($mgsObj->stock >= $attr_stock) ? $mgsObj->stock - $attr_stock : 0;
$mgsObj->stock = $changeStock;
$mgsObj->save();
}
}
//支付记录
$pay_cord = new PaymentRecord();
$cordLog = $pay_cord->where(['order_sn' => $message['out_trade_no']])->first();
if (!$cordLog) {
$total_fee = $message['total_fee'];
$pay_money = round($total_fee / 100, 2);
$pay_cord->order_sn = $message['out_trade_no'];
$pay_cord->other_order = $message['transaction_id'];
$pay_cord->money = $pay_money;
$pay_cord->uid = $orderObj->user_id;
$pay_cord->save();
}
DB::commit();
//return true;
} catch (\Exception $e) {
Log::add('付款回调失败', $e);
return false;
}
}
return true;
});
//Log::add('响应结果', $response);
//Log::add('响应结果内容', $response->getContent());
$response->send();
return $response;
}
public static function refund($wxOrder_no, $orderPrice, $refundPrice)
{
$app = Factory::payment(self::getConfig());
$refund_no = date('YmdHis') . rand(100000, 999999);
$orderPrice = intval(strval($orderPrice * 100));
$refundPrice = intval(strval($refundPrice * 100));
$result = $app->refund->byTransactionId($wxOrder_no, $refund_no, $orderPrice, $refundPrice, [
// 可在此处传入其他参数,详细参数见微信支付文档
'refund_desc' => '订单退款',
'notify_url' => env('API_URL') . '/refund-notify',
]);
// echo '<pre>';
// print_r($result);
Log::add('订单退款', $result);
if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
//退款成功的操作
return $result;
}
if ($result['return_code'] == 'FAIL' && array_key_exists('return_msg', $result)) {
throw new \Exception($result['return_msg']);
}
throw new \Exception($result['err_code_des']);
}
public static function refundNotify($fields)
{
$app = Factory::payment(self::getConfig());
$response = $app->handleRefundedNotify(function ($message, $fail) use ($fields) {
return true;
});
return $response;
}
}
<?php
namespace App\Models;
use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Database\Eloquent\Model;
class PaymentRecord extends Model
{
use HasDateTimeFormatter;
protected $table = 'payment_record';
public function user()
{
return $this->belongsTo(User::class, 'uid');
}
}
...@@ -29,6 +29,7 @@ ...@@ -29,6 +29,7 @@
"qcloudsms/qcloudsms_php": "^0.1.4", "qcloudsms/qcloudsms_php": "^0.1.4",
"simplesoftwareio/simple-qrcode": "^4.2", "simplesoftwareio/simple-qrcode": "^4.2",
"slowlyo/dcat-diy-form": "^2.2", "slowlyo/dcat-diy-form": "^2.2",
"overtrue/wechat": "~5.0",
"zhy/dcat-admin-sku": "dev-master" "zhy/dcat-admin-sku": "dev-master"
}, },
"require-dev": { "require-dev": {
......
...@@ -70,6 +70,8 @@ ...@@ -70,6 +70,8 @@
Route::get('comment-list', 'CommentController@getList'); //评价列表 Route::get('comment-list', 'CommentController@getList'); //评价列表
Route::any('pay-notify', 'OrderController@payNotify'); //付款回调
Route::get('send/config/update', 'SystemController@update'); Route::get('send/config/update', 'SystemController@update');
Route::middleware('auth:sanctum')->group(function () { Route::middleware('auth:sanctum')->group(function () {
...@@ -122,6 +124,8 @@ ...@@ -122,6 +124,8 @@
Route::post('cance-order', 'OrderController@canceOrder'); //取消订单 Route::post('cance-order', 'OrderController@canceOrder'); //取消订单
Route::post('pay', 'OrderController@pay'); //统一支付
Route::get('address-list', 'UserController@getUserAddress'); //获取收货地址列表 Route::get('address-list', 'UserController@getUserAddress'); //获取收货地址列表
Route::post('set-address', 'UserController@setUserAddress'); //设置收货地址 Route::post('set-address', 'UserController@setUserAddress'); //设置收货地址
...@@ -146,6 +150,8 @@ ...@@ -146,6 +150,8 @@
Route::post('income-add', 'IncomeController@add'); //去提现 Route::post('income-add', 'IncomeController@add'); //去提现
Route::post('scan-code', 'OrderController@scanCodeVerifi'); //扫码核销
Route::get('merchant-order-collect', 'OrderController@orderCollect'); //商户端首页统计 Route::get('merchant-order-collect', 'OrderController@orderCollect'); //商户端首页统计
}); });
}); });
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment