Browse Source

refactor: 处理冲突

antshop
root 5 years ago
parent
commit
be8bbe7858
  1. 77
      backend/modules/file/logic/file/FileManager.php
  2. 5
      backend/modules/goods/controllers/CategoryController.php
  3. 16
      backend/modules/goods/controllers/GoodsController.php
  4. 5
      backend/modules/goods/controllers/ShopCategoryController.php
  5. 256
      backend/modules/goods/logic/goods/GoodsManager.php
  6. 26
      backend/modules/goods/migrations/m191207_004848_add_columns_is_taking_is_express_express_type_uniform_postage_in_table_atg_goods.php
  7. 40
      backend/modules/goods/models/ars/Goods.php
  8. 4
      backend/modules/goods/models/ars/GoodsSku.php
  9. 6
      backend/modules/goods/views/goods/create.php
  10. 60
      backend/modules/goods/views/goods/express.php
  11. 6
      backend/modules/goods/views/goods/picture.php
  12. 6
      backend/modules/goods/views/goods/update.php
  13. 275
      backend/modules/shop/controllers/ExpressTemplateController.php
  14. 32
      backend/modules/shop/migrations/m191205_092426_drop_columns_province_city_area_basic_price_basic_count_extra_count_extra_price_in_table_ats_express_template.php
  15. 36
      backend/modules/shop/migrations/m191205_092942_create_table_ats_express_area.php
  16. 101
      backend/modules/shop/models/ars/ExpressArea.php
  17. 27
      backend/modules/shop/models/ars/ExpressTemplate.php
  18. 187
      backend/modules/shop/models/searchs/ExpressAreaSearch.php
  19. 41
      backend/modules/shop/models/searchs/ExpressTemplateSearch.php
  20. 145
      backend/modules/shop/views/express-template/_form.php
  21. 36
      backend/modules/shop/views/express-template/create.php
  22. 51
      backend/modules/shop/views/express-template/express_area_create.php
  23. 156
      backend/modules/shop/views/express-template/express_area_form.php
  24. 33
      backend/modules/shop/views/express-template/express_area_list.php
  25. 52
      backend/modules/shop/views/express-template/express_area_update.php
  26. 94
      backend/modules/shop/views/express-template/express_area_view.php
  27. 36
      backend/modules/shop/views/express-template/update.php
  28. 65
      vendor/iron/grid/GridView.php

77
backend/modules/file/logic/file/FileManager.php

@ -5,17 +5,20 @@ namespace backend\modules\file\logic\file;
use backend\modules\file\models\ars\File; use backend\modules\file\models\ars\File;
use backend\modules\file\models\ars\TemFile; use backend\modules\file\models\ars\TemFile;
use yii\web\HttpException;
use yii;
class FileManager class FileManager
{ {
//数据表ats_file和ats_tem_file的类型字段type //数据表ats_file和ats_tem_file的类型字段type
const TYPE_NONE = 0;//不存在
const TYPE_IMAGE = 1;//图片 const TYPE_IMAGE = 1;//图片
const TYPE_VIDEO = 2;//影视 const TYPE_VIDEO = 2;//影视
const TYPE_EXCEL = 3;//excel表单 const TYPE_EXCEL = 3;//excel表单
const TYPE_WORD = 4;//word文本 const TYPE_WORD = 4;//word文本
const TYPE_TXT = 5;//txt文本 const TYPE_TXT = 5;//txt文本
public static $extension = [
private $extension = [
self::TYPE_IMAGE => ['jpg', 'png', 'jpeg'], self::TYPE_IMAGE => ['jpg', 'png', 'jpeg'],
self::TYPE_VIDEO => ['mp4'], self::TYPE_VIDEO => ['mp4'],
self::TYPE_EXCEL => [], self::TYPE_EXCEL => [],
@ -24,54 +27,56 @@ class FileManager
]; ];
/** /**
* @param $array
* @param $keyword * @param $keyword
* @return array
* 根据文件拓展名在$extension中查找对应的文件类型,若不存在则返回false
* @return int|string
* 根据文件拓展名在$extension中查找对应的文件类型,若不存在则返回self::TYPE_NONE
*/ */
public function searchType($array, $keyword)
public function searchType($keyword)
{ {
foreach($array as $key => $value){
foreach ($value as $k => $v) {
if($v == $keyword){
return ['status' => true, 'info' => '操作成功', 'type' => $key];
}
foreach($this->extension as $key => $type){
if (in_array($keyword, $type)) {
return $key;
} }
} }
return ['status' => false, 'info' => '操作失败'];
return self::TYPE_NONE;
} }
/** /**
* @param $temFIleIdArr
* @param $temFileIdArr
* @param $ownId * @param $ownId
* @param $ownType * @param $ownType
* @return array
* @return array|bool
* @throws \Exception
* 根据临时文件id将临时文件保存在文件中 * 根据临时文件id将临时文件保存在文件中
*/ */
public function saveTemFileToFile($temFIleIdArr, $ownId, $ownType)
public function saveTemFileToFile($temFileIdArr, $ownId, $ownType)
{ {
if(!$temFIleIdArr || !$ownId) {
return ['status' => false, 'info' => '参数错误'];
if(empty($temFileIdArr) || !$ownId) {
return false;
} }
$firstFileId = 0;
foreach ($temFIleIdArr as $key => $value) {
$temFile = TemFile::findOne($value);
$tra = Yii::$app->db->beginTransaction();
try {
$firstFileId = 0;
foreach ($temFileIdArr as $key => $value) {
$temFile = TemFile::findOne($value);
if(!$temFile) {
return ['status' => false, 'info' => '存在查找不到的文件'];
}
if (!$temFile) {
throw new \Exception('存在查找不到的文件');
}
$res = self::saveNewFile($temFile, $ownId, $ownType);
if(!$res['status']) {
return ['status' => false, 'info' => '存在文件保存失败'];
}
if($key == 0) {
$firstFileId = $res['file_id'];
$res = self::saveNewFile($temFile, $ownId, $ownType);
if ($key == 0) {
$firstFileId = $res['file_id'];
}
} }
}
return ['status' => true, 'info' => '保存成功', 'first_file_id' => $firstFileId];
$tra->commit();
return ['status' => true, 'info' => '保存成功', 'first_file_id' => $firstFileId];
} catch (\Exception $e) {
$tra->rollBack();
throw new \Exception($e->getMessage());
}
} }
/** /**
@ -79,6 +84,7 @@ class FileManager
* @param $ownId * @param $ownId
* @param $ownType * @param $ownType
* @return array * @return array
* @throws HttpException
* 创建新的文件 * 创建新的文件
*/ */
private function saveNewFile($temFile, $ownId, $ownType) private function saveNewFile($temFile, $ownId, $ownType)
@ -93,13 +99,14 @@ class FileManager
if($newFile->save()) { if($newFile->save()) {
return ['status' => true, 'info' => '操作成功', 'file_id' => $newFile->id]; return ['status' => true, 'info' => '操作成功', 'file_id' => $newFile->id];
} else { } else {
return ['status' => false, 'info' => '操作失败'];
throw new HttpException('500', 'File保存失败');
} }
} }
/** /**
* @param $fileIdArr * @param $fileIdArr
* @return array
* @return bool
* @throws HttpException
* 删除file表中的文件 * 删除file表中的文件
*/ */
public function deleteFile($fileIdArr) public function deleteFile($fileIdArr)
@ -109,12 +116,12 @@ class FileManager
$fileModel = File::findOne($value); $fileModel = File::findOne($value);
if($fileModel){ if($fileModel){
$fileModel->is_delete = File::IS_DELETE_YES; $fileModel->is_delete = File::IS_DELETE_YES;
if($fileModel->save()){
return ['status' => false, 'info' => '操作失败'];
if(!$fileModel->save()){
throw new HttpException('500', '文件删除失败');
} }
} }
} }
} }
return ['status' => true, 'info' => '操作成功'];
return true;
} }
} }

5
backend/modules/goods/controllers/CategoryController.php

@ -201,10 +201,7 @@ class CategoryController extends Controller
$model->user_id = Yii::$app->user->identity->id; $model->user_id = Yii::$app->user->identity->id;
$model->name = $file_name; $model->name = $file_name;
$file_manager = new \backend\modules\file\logic\file\FileManager(); $file_manager = new \backend\modules\file\logic\file\FileManager();
$type_res = $file_manager->searchType(\backend\modules\file\logic\file\FileManager::$extension, pathinfo($data['path'])['extension']);
if ($type_res['status']) {
$model->type = $type_res['type'];
}
$model->type = $file_manager->searchType(pathinfo($data['path'])['extension']);
$model->alias = $data['alias']; $model->alias = $data['alias'];
$model->path = $data['path']; $model->path = $data['path'];
$model->save(); $model->save();

16
backend/modules/goods/controllers/GoodsController.php

@ -11,6 +11,7 @@ use Yii;
use backend\modules\goods\models\ars\Goods; use backend\modules\goods\models\ars\Goods;
use backend\modules\goods\models\searchs\GoodsSearch; use backend\modules\goods\models\searchs\GoodsSearch;
use yii\web\Controller; use yii\web\Controller;
use yii\web\HttpException;
use yii\web\NotFoundHttpException; use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter; use yii\filters\VerbFilter;
use backend\modules\goods\logic\goods\GoodsManager; use backend\modules\goods\logic\goods\GoodsManager;
@ -96,7 +97,13 @@ class GoodsController extends Controller
$model = new Goods(); $model = new Goods();
$model->is_sale = Goods::IS_SALE_YES; $model->is_sale = Goods::IS_SALE_YES;
$model->stock = -1; $model->stock = -1;
$model->is_taking = Goods::IS_TAKING_NO;
$model->is_express = Goods::IS_EXPRESS_YES;
$model->express_type = Goods::EXPRESS_TYPE_EXPRESS_TEMPLAGE;
if ($model->load(Yii::$app->request->post()) && $model->validate()) { if ($model->load(Yii::$app->request->post()) && $model->validate()) {
if ($model->uniform_postage) {
$model->uniform_postage *= 100;
}
//商品封面图和商品详情图上传保存处理 //商品封面图和商品详情图上传保存处理
$res = GoodsManager::updateGoods(Yii::$app->request->post(), $model); $res = GoodsManager::updateGoods(Yii::$app->request->post(), $model);
if ($res['status']) { if ($res['status']) {
@ -126,12 +133,16 @@ class GoodsController extends Controller
$cover_image_old_id_str = $model->image; $cover_image_old_id_str = $model->image;
$detail_image_old_id_str = $model->detailImageId; $detail_image_old_id_str = $model->detailImageId;
if ($model->load(Yii::$app->request->post()) && $model->validate()) { if ($model->load(Yii::$app->request->post()) && $model->validate()) {
if ($model->uniform_postage) {
$model->uniform_postage *= 100;
}
//商品封面图和商品详情图上传保存处理 //商品封面图和商品详情图上传保存处理
$res = GoodsManager::updateGoods(Yii::$app->request->post(), $model, $cover_image_old_id_str, $detail_image_old_id_str); $res = GoodsManager::updateGoods(Yii::$app->request->post(), $model, $cover_image_old_id_str, $detail_image_old_id_str);
if ($res['status']) { if ($res['status']) {
return $this->redirect('index'); return $this->redirect('index');
} }
} }
$model->uniform_postage /= 100;
$attributeModel = GoodsManager::getAttribute($id); $attributeModel = GoodsManager::getAttribute($id);
$checkAttr = GoodsManager::getSkuInfo($id); $checkAttr = GoodsManager::getSkuInfo($id);
$filterAttributeModel = GoodsManager::getFilterAttribute($id); $filterAttributeModel = GoodsManager::getFilterAttribute($id);
@ -211,10 +222,7 @@ class GoodsController extends Controller
$model->user_id = Yii::$app->user->identity->id; $model->user_id = Yii::$app->user->identity->id;
$model->name = $file_name; $model->name = $file_name;
$file_manager = new \backend\modules\file\logic\file\FileManager(); $file_manager = new \backend\modules\file\logic\file\FileManager();
$type_res = $file_manager->searchType(\backend\modules\file\logic\file\FileManager::$extension, pathinfo($data['path'])['extension']);
if ($type_res['status']) {
$model->type = $type_res['type'];
}
$model->type = $file_manager->searchType(pathinfo($data['path'])['extension']);
$model->alias = $data['alias']; $model->alias = $data['alias'];
$model->path = $data['path']; $model->path = $data['path'];
$model->save(); $model->save();

5
backend/modules/goods/controllers/ShopCategoryController.php

@ -212,10 +212,7 @@ class ShopCategoryController extends Controller
$model->user_id = Yii::$app->user->identity->id; $model->user_id = Yii::$app->user->identity->id;
$model->name = $file_name; $model->name = $file_name;
$file_manager = new \backend\modules\file\logic\file\FileManager(); $file_manager = new \backend\modules\file\logic\file\FileManager();
$type_res = $file_manager->searchType(\backend\modules\file\logic\file\FileManager::$extension, pathinfo($data['path'])['extension']);
if ($type_res['status']) {
$model->type = $type_res['type'];
}
$model->type = $file_manager->searchType(pathinfo($data['path'])['extension']);
$model->alias = $data['alias']; $model->alias = $data['alias'];
$model->path = $data['path']; $model->path = $data['path'];
$model->save(); $model->save();

256
backend/modules/goods/logic/goods/GoodsManager.php

@ -10,6 +10,7 @@ use backend\modules\goods\models\ars\GoodsSku;
use backend\modules\goods\models\ars\Goods; use backend\modules\goods\models\ars\Goods;
use backend\modules\goods\models\ars\FilterAttr; use backend\modules\goods\models\ars\FilterAttr;
use backend\modules\goods\models\ars\Category; use backend\modules\goods\models\ars\Category;
use yii\web\HttpException;
class GoodsManager class GoodsManager
{ {
@ -19,36 +20,44 @@ class GoodsManager
* @param array $oldFileIdArr * @param array $oldFileIdArr
* @param int $fileType * @param int $fileType
* @return array * @return array
* @throws \Exception
* 保存新文件,删除不需要的文件操作 * 保存新文件,删除不需要的文件操作
*/ */
public static function saveFile($newFileIdArr, $goodsModel, $oldFileIdArr = [], $fileType = 1) public static function saveFile($newFileIdArr, $goodsModel, $oldFileIdArr = [], $fileType = 1)
{ {
//需要新建的文件id
$createFileIdArr = array_diff($newFileIdArr, $oldFileIdArr);
$tra = Yii::$app->db->beginTransaction();
try {
//需要新建的文件id
$createFileIdArr = array_diff($newFileIdArr, $oldFileIdArr);
//创建文件
$class = new \backend\modules\file\logic\file\FileManager();
$createFileRes = $class->saveTemFileToFile($createFileIdArr, $goodsModel->id, $fileType);
//创建文件
$class = new \backend\modules\file\logic\file\FileManager();
$createFileRes = $class->saveTemFileToFile($createFileIdArr, $goodsModel->id, $fileType);
//需要删除的文件id
$delFileIdArr = array_diff($oldFileIdArr, $newFileIdArr);
//需要删除的文件id
$delFileIdArr = array_diff($oldFileIdArr, $newFileIdArr);
//删除文件
$class->deleteFile($delFileIdArr);
//删除文件
$class->deleteFile($delFileIdArr);
//记录第一张图片id
$firstFileId = 0;
//记录第一张图片id
$firstFileId = 0;
//查看修改数组是否为空
if (!$newFileIdArr[0]) {
$firstFileId = null;
}else {
if ($createFileRes['status']) {
$firstFileId = $createFileRes['first_file_id'];
//查看修改数组是否为空
if (!$newFileIdArr[0]) {
$firstFileId = null;
} else {
if ($createFileRes['status']) {
$firstFileId = $createFileRes['first_file_id'];
}
} }
}
return ['status' => true, 'info' => '操作成功', 'first_file_id' => $firstFileId];
$tra->commit();
return ['status' => true, 'info' => '操作成功', 'first_file_id' => $firstFileId];
} catch (\Exception $e) {
$tra->rollBack();
throw new \Exception($e->getMessage());
}
} }
/** /**
@ -57,7 +66,7 @@ class GoodsManager
* @param null $coverImageOldIdStr * @param null $coverImageOldIdStr
* @param null $detailImageOldIdStr * @param null $detailImageOldIdStr
* @return array * @return array
* @throws \Throwable
* @throws \Exception
* 创建修改商品操作 * 创建修改商品操作
*/ */
public static function updateGoods($data, $model, $coverImageOldIdStr = null, $detailImageOldIdStr = null) public static function updateGoods($data, $model, $coverImageOldIdStr = null, $detailImageOldIdStr = null)
@ -67,19 +76,15 @@ class GoodsManager
$tra = Yii::$app->db->beginTransaction(); $tra = Yii::$app->db->beginTransaction();
try { try {
if (!$model->save()) { if (!$model->save()) {
throw new Exception('');
throw new \Exception('商品保存失败');
} }
$saveCoverImageRes = self::saveFile(explode(',', $model->coverImageId), $model, explode(',', $coverImageOldIdStr)); $saveCoverImageRes = self::saveFile(explode(',', $model->coverImageId), $model, explode(',', $coverImageOldIdStr));
$saveDetailImageRes = self::saveFile(explode(',', $model->detailImageId), $model, explode(',', $detailImageOldIdStr), File::OWN_TYPE_GOODS_DETAILS); $saveDetailImageRes = self::saveFile(explode(',', $model->detailImageId), $model, explode(',', $detailImageOldIdStr), File::OWN_TYPE_GOODS_DETAILS);
if ($saveCoverImageRes['status'] && $saveDetailImageRes['status']) {
if($saveCoverImageRes['first_file_id'] !== 0) {
$model->image = $saveCoverImageRes['first_file_id'];
if (!$model->save()) {
throw new Exception('图片保存失败');
}
if($saveCoverImageRes['first_file_id'] !== 0) {
$model->image = $saveCoverImageRes['first_file_id'];
if (!$model->save()) {
throw new \Exception('图片保存失败');
} }
} else {
throw new Exception('图片保存失败');
} }
self::addAttributeOperating(['id' => $model->id, 'attribute' => $attribute]); self::addAttributeOperating(['id' => $model->id, 'attribute' => $attribute]);
self::addFilterAttributeOperating(['id' => $model->id, 'filterAttribute' => $filterAttribute]); self::addFilterAttributeOperating(['id' => $model->id, 'filterAttribute' => $filterAttribute]);
@ -87,60 +92,71 @@ class GoodsManager
return ['status' => true]; return ['status' => true];
} catch (\yii\base\Exception $e) { } catch (\yii\base\Exception $e) {
$tra->rollBack(); $tra->rollBack();
return ['status' => false, 'info' => $e->getMessage()];
throw new \Exception($e->getMessage());
} }
} }
/** /**
* @param $data * @param $data
* @return bool * @return bool
* @throws Exception
* @throws \Exception
* 创建修改商品属性操作 * 创建修改商品属性操作
*/ */
public static function addAttributeOperating($data)
private static function addAttributeOperating($data)
{ {
if (!$data['attribute']) {
return true;
}
$data['attribute'] = json_decode($data['attribute'], true);
$oldAttr = [];
$goodsAttr = GoodsAttr::find()->where(['goods_id' => $data['id'], 'is_delete' => GoodsAttr::IS_DELETE_NO])->all();
if ($goodsAttr) { //如果商品有旧的属性
if(count($data['attribute']) == 0 && is_array($data['attribute'])) { //如果传上来的是空数组,删除该商品下的全部属性
self::delAttribute($goodsAttr);
$tra = Yii::$app->db->beginTransaction();
try {
if (!$data['attribute']) {
$tra->commit();
return true; return true;
} }
foreach ($goodsAttr as $key => $value) { //把旧的商品属性保存到一个数组
$oldAttr[$value->id] = $value->attr_value;
$data['attribute'] = json_decode($data['attribute'], true);
$oldAttr = [];
$goodsAttr = GoodsAttr::find()->where(['goods_id' => $data['id'], 'is_delete' => GoodsAttr::IS_DELETE_NO])->all();
if ($goodsAttr) { //如果商品有旧的属性
if (count($data['attribute']) == 0 && is_array($data['attribute'])) { //如果传上来的是空数组,删除该商品下的全部属性
self::delAttribute($goodsAttr);
$tra->commit();
return true;
}
foreach ($goodsAttr as $key => $value) { //把旧的商品属性保存到一个数组
$oldAttr[$value->id] = $value->attr_value;
}
} }
}
$newAttr = self::addAttribute($data['attribute'], $data['id']); //添加新的商品属性
$delAttr = array_diff(array_keys($oldAttr), array_keys($newAttr)); //找出需要删除的goodsAttrId
if (!$delAttr) {
return true;
}
foreach ($delAttr as $value) {
$model = GoodsAttr::find()->where(['id' => $value, 'is_delete' => GoodsAttr::IS_DELETE_NO])->One();
if ($model) {
$model->is_delete = GoodsAttr::IS_DELETE_YES;
if (!$model->save()) {
throw new Exception('goodsAttribute delete false');
$newAttr = self::addAttribute($data['attribute'], $data['id']); //添加新的商品属性
$delAttr = array_diff(array_keys($oldAttr), array_keys($newAttr)); //找出需要删除的goodsAttrId
if (!$delAttr) {
$tra->commit();
return true;
}
foreach ($delAttr as $value) {
$model = GoodsAttr::find()->where(['id' => $value, 'is_delete' => GoodsAttr::IS_DELETE_NO])->One();
if ($model) {
$model->is_delete = GoodsAttr::IS_DELETE_YES;
if (!$model->save()) {
throw new \Exception('goodsAttribute delete false');
}
} }
} }
$tra->commit();
return true;
} catch (\Exception $e) {
$tra->rollBack();
throw new \Exception($e->getMessage());
} }
} }
/** /**
* @param $goodsAttr * @param $goodsAttr
* @throws Exception
* @throws \Exception
* 删除商品属性 * 删除商品属性
*/ */
public static function delAttribute($goodsAttr)
private static function delAttribute($goodsAttr)
{ {
foreach ($goodsAttr as $key => $value) { foreach ($goodsAttr as $key => $value) {
$value->is_delete = GoodsAttr::IS_DELETE_YES; $value->is_delete = GoodsAttr::IS_DELETE_YES;
if (!$value->save()) { if (!$value->save()) {
throw new Exception('goods attribute delete false');
throw new \Exception('goods attribute delete false');
} }
} }
} }
@ -149,10 +165,10 @@ class GoodsManager
* @param $attribute * @param $attribute
* @param $goodsId * @param $goodsId
* @return array * @return array
* @throws Exception
* @throws \Exception
* 保存商品属性 * 保存商品属性
*/ */
public static function addAttribute($attribute, $goodsId)
private static function addAttribute($attribute, $goodsId)
{ {
$newAttr = []; $newAttr = [];
if (!$attribute) { if (!$attribute) {
@ -169,7 +185,7 @@ class GoodsManager
$goodsAttrModel->goods_id = $goodsId; $goodsAttrModel->goods_id = $goodsId;
$goodsAttrModel->attr_value = $v; $goodsAttrModel->attr_value = $v;
if (!$goodsAttrModel->save()) { if (!$goodsAttrModel->save()) {
throw new Exception('goodsAttribute save false');
throw new \Exception('goodsAttribute save false');
} }
$newAttr[$goodsAttrModel->id] = $goodsAttrModel->attr_value; //新增的数据 $newAttr[$goodsAttrModel->id] = $goodsAttrModel->attr_value; //新增的数据
} }
@ -306,29 +322,18 @@ class GoodsManager
if ($attribute && $attribute->type == Attribute::TYPE_ATTR) { if ($attribute && $attribute->type == Attribute::TYPE_ATTR) {
$ret['name'] = $attribute->name; $ret['name'] = $attribute->name;
$ret['id'] = $attribute->id; $ret['id'] = $attribute->id;
$ret['attrValue'] = self::getAttrValue($attribute->id, $id);
$ret['attrValue'] = GoodsAttr::find()
->select(['id', 'attr_value'])
->where(['goods_id' => $id])
->andWhere(['attr_id' => $attribute->id])
->asArray()
->all();
$attributes[] = $ret; $attributes[] = $ret;
} }
} }
return $attributes; return $attributes;
} }
/**
* @param $attrId
* @param $goodsId
* @return GoodsAttr[]|GoodsSku[]|array|File[]|\backend\modules\file\models\ars\TemFile[]|\yii\db\ActiveRecord[]
* 获取属性值
*/
public static function getAttrValue($attrId, $goodsId)
{
return GoodsAttr::find()
->select(['id', 'attr_value'])
->where(['goods_id' => $goodsId])
->andWhere(['attr_id' => $attrId])
->asArray()
->all();
}
/** /**
* @param $type * @param $type
* @param $goodsId * @param $goodsId
@ -356,45 +361,53 @@ class GoodsManager
/** /**
* @param $sku * @param $sku
* @throws \yii\db\Exception
* @param $type
* @param $goodsId
* @throws \Exception
* 添加或更新sku数据 * 添加或更新sku数据
*/ */
public static function AddOrUpdateData($sku, $type, $goodsId) public static function AddOrUpdateData($sku, $type, $goodsId)
{ {
$goodsModel = Goods::findOne($goodsId);
if ($sku['id'] > 0) {
$goodsSku = GoodsSku::findOne($sku['id']);
$attrId = array_filter(explode(',', $goodsSku->goods_attr));
$attr = GoodsAttr::findOne($attrId[0]);
} else {
$goodsSku = new GoodsSku();
$attr = new GoodsAttr();
}
if (!$attr || !$goodsSku || !$goodsModel) {
throw new \yii\db\Exception('系统异常');
}
if ($type == Goods::SKU_MODE_MANUAL) {
$attr->attr_value = $sku['value'];
if (!$attr->save()) {
throw new \yii\db\Exception('手动属性修改失败');
$tra = Yii::$app->db->beginTransaction();
try {
$goodsModel = Goods::findOne($goodsId);
if ($sku['id'] > 0) {
$goodsSku = GoodsSku::findOne($sku['id']);
$attrId = array_filter(explode(',', $goodsSku->goods_attr));
$attr = GoodsAttr::findOne($attrId[0]);
} else {
$goodsSku = new GoodsSku();
$attr = new GoodsAttr();
} }
$goodsSku->goods_attr = (string)$attr->id;
$goodsSku->is_manaul = 1;
} else {
$goodsSku->goods_attr = implode(',', array_filter($sku['value']));
}
$goodsSku->goods_id = $goodsId;
$goodsSku->price = $sku['price'];
$goodsSku->stock = $sku['stock'];
$goodsSku->weight = $sku['weight'];
$goodsSku->goods_sn = $goodsModel->sn;
if (!$goodsSku->save()) {
throw new \yii\db\Exception('保存失败,请检查是否有重复规格');
}
$goods = Goods::findOne($goodsId);
$goods->sku_mode = $type;
if (!$goods->save()) {
throw new \yii\db\Exception('商品sku类型修改失败');
if (!$attr || !$goodsSku || !$goodsModel) {
throw new \Exception('参数错误');
}
if ($type == Goods::SKU_MODE_MANUAL) {
$attr->attr_value = $sku['value'];
if (!$attr->save()) {
throw new \Exception('手动属性修改失败');
}
$goodsSku->goods_attr = (string)$attr->id;
$goodsSku->is_manaul = 1;
} else {
$goodsSku->goods_attr = implode(',', array_filter($sku['value']));
}
$goodsSku->goods_id = $goodsId;
$goodsSku->price = $sku['price'];
$goodsSku->stock = $sku['stock'];
$goodsSku->weight = $sku['weight'];
$goodsSku->goods_sn = $goodsModel->sn;
if (!$goodsSku->save()) {
throw new \Exception('保存失败,请检查是否有重复规格');
}
$goods = Goods::findOne($goodsId);
$goods->sku_mode = $type;
if (!$goods->save()) {
throw new \Exception('商品sku类型修改失败');
}
} catch (\Exception $e) {
$tra->rollBack();
throw new \Exception($e->getMessage());
} }
} }
@ -433,9 +446,10 @@ class GoodsManager
* @param $data * @param $data
* @return bool * @return bool
* @throws Exception * @throws Exception
* @throws HttpException
* 创建修改商品筛选属性操作 * 创建修改商品筛选属性操作
*/ */
public static function addFilterAttributeOperating($data)
private static function addFilterAttributeOperating($data)
{ {
if (!$data['filterAttribute']) { if (!$data['filterAttribute']) {
return true; return true;
@ -462,7 +476,7 @@ class GoodsManager
if ($model) { if ($model) {
$model->is_delete = FilterAttr::IS_DELETE_YES; $model->is_delete = FilterAttr::IS_DELETE_YES;
if (!$model->save()) { if (!$model->save()) {
throw new Exception('goodsAttribute delete false');
throw new \Exception('goodsAttribute delete false');
} }
} }
} }
@ -470,15 +484,15 @@ class GoodsManager
/** /**
* @param $goodsFilterAttr * @param $goodsFilterAttr
* @throws Exception
* @throws HttpException
* 删除商品筛选属性 * 删除商品筛选属性
*/ */
public static function delFilterAttribute($goodsFilterAttr)
private static function delFilterAttribute($goodsFilterAttr)
{ {
foreach ($goodsFilterAttr as $key => $value) { foreach ($goodsFilterAttr as $key => $value) {
$value->is_delete = FilterAttr::IS_DELETE_YES; $value->is_delete = FilterAttr::IS_DELETE_YES;
if (!$value->save()) { if (!$value->save()) {
throw new Exception('goods attribute delete false');
throw new \Exception('goods attribute delete false');
} }
} }
} }
@ -487,10 +501,10 @@ class GoodsManager
* @param $attribute * @param $attribute
* @param $goodsId * @param $goodsId
* @return array * @return array
* @throws Exception
* @throws \Exception
* 保存商品筛选属性 * 保存商品筛选属性
*/ */
public static function addFilterAttribute($attribute, $goodsId)
private static function addFilterAttribute($attribute, $goodsId)
{ {
$newAttr = []; $newAttr = [];
if (!$attribute) { if (!$attribute) {
@ -507,7 +521,7 @@ class GoodsManager
$goodsFilterAttrModel->goods_id = $goodsId; $goodsFilterAttrModel->goods_id = $goodsId;
$goodsFilterAttrModel->attr_value = $v; $goodsFilterAttrModel->attr_value = $v;
if (!$goodsFilterAttrModel->save()) { if (!$goodsFilterAttrModel->save()) {
throw new Exception('goodsAttribute save false');
throw new \Exception('goodsAttribute save false');
} }
$newAttr[$goodsFilterAttrModel->id] = $goodsFilterAttrModel->attr_value; //新增的数据 $newAttr[$goodsFilterAttrModel->id] = $goodsFilterAttrModel->attr_value; //新增的数据
} }
@ -549,7 +563,7 @@ class GoodsManager
/** /**
* @param $goodsModel * @param $goodsModel
* @return bool * @return bool
*
* 判断该商品的sku是否存在已选属性,存在则返回true,表示不得删除
*/ */
public static function judgeGoodsCategory($goodsModel) public static function judgeGoodsCategory($goodsModel)
{ {

26
backend/modules/goods/migrations/m191207_004848_add_columns_is_taking_is_express_express_type_uniform_postage_in_table_atg_goods.php

@ -0,0 +1,26 @@
<?php
use yii\db\Migration;
/**
* Class m191207_004848_add_columns_is_taking_is_express_express_type_uniform_postage_in_table_atg_goods
*/
class m191207_004848_add_columns_is_taking_is_express_express_type_uniform_postage_in_table_atg_goods extends Migration
{
public function up()
{
$this->addColumn('atg_goods', 'is_taking', $this->tinyInteger(1)->defaultValue(0)->notNull()->comment('是否自提'));
$this->addColumn('atg_goods', 'is_express', $this->tinyInteger(1)->defaultValue(0)->notNull()->comment('是否快递发货'));
$this->addColumn('atg_goods', 'express_type', $this->tinyInteger(2)->defaultValue(0)->comment('快递运费方式'));
$this->addColumn('atg_goods', 'uniform_postage', $this->integer(20)->defaultValue(0)->comment('统一邮费'));
}
public function down()
{
$this->dropColumn('atg_goods', 'is_taking');
$this->dropColumn('atg_goods', 'is_express');
$this->dropColumn('atg_goods', 'express_type');
$this->dropColumn('atg_goods', 'uniform_postage');
return true;
}
}

40
backend/modules/goods/models/ars/Goods.php

@ -47,6 +47,10 @@ use backend\modules\goods\models\ars\Supplier;
* @property int $created_at 创建时间 * @property int $created_at 创建时间
* @property int $updated_at 更新时间 * @property int $updated_at 更新时间
* @property int $sku_mode sku类型 * @property int $sku_mode sku类型
* @property int $is_taking 是否自提
* @property int $is_express 是否快递发货
* @property int $express_type 快递运费方式
* @property int $uniform_postage 统一邮费
*/ */
class Goods extends \yii\db\ActiveRecord class Goods extends \yii\db\ActiveRecord
{ {
@ -62,9 +66,31 @@ class Goods extends \yii\db\ActiveRecord
//该商品是否开放销售is_sale //该商品是否开放销售is_sale
const IS_SALE_NO = 0;//否 const IS_SALE_NO = 0;//否
const IS_SALE_YES = 1;//是 const IS_SALE_YES = 1;//是
//sku类型
//类型sku
const SKU_MODE_ATTR = 1;//SKU类型属性 const SKU_MODE_ATTR = 1;//SKU类型属性
const SKU_MODE_MANUAL = 2;//SKU类型手写 const SKU_MODE_MANUAL = 2;//SKU类型手写
//是否自提is_taking
const IS_TAKING_NO = 0; //否
const IS_TAKING_YES = 1; //是
//是否快递发货is_express
const IS_EXPRESS_NO = 0; //否
const IS_EXPRESS_YES = 1; //是
//快递运费计算方式express_type
const EXPRESS_TYPE_UNIFORM_POSTAGE = 1; //统一邮费
const EXPRESS_TYPE_EXPRESS_TEMPLAGE = 2; //运费模板
public static $isTaking = [
self::IS_TAKING_NO => '否',
self::IS_TAKING_YES => '是'
];
public static $isExpress = [
self::IS_EXPRESS_NO => '否',
self::IS_EXPRESS_YES => '是'
];
public static $expressType = [
self::EXPRESS_TYPE_UNIFORM_POSTAGE => '统一邮费',
self::EXPRESS_TYPE_EXPRESS_TEMPLAGE => '运费模板'
];
public static $isSale = [ public static $isSale = [
self::IS_SALE_NO => '不在售', self::IS_SALE_NO => '不在售',
self::IS_SALE_YES => '在售' self::IS_SALE_YES => '在售'
@ -84,7 +110,7 @@ class Goods extends \yii\db\ActiveRecord
public function rules() public function rules()
{ {
return [ return [
[['pid', 'cat_id', 'brand_id', 'shop_cat_id', 'supplier_id', 'weight', 'length', 'width', 'height', 'diameter', 'sold_count', 'limit_count', 'stock', 'stock_warn', 'market_price', 'price', 'image', 'model_id', 'is_sale', 'sort_order', 'bouns_points', 'experience_points', 'is_delete', 'express_template', 'sku_mode'], 'integer'],
[['pid', 'cat_id', 'brand_id', 'shop_cat_id', 'supplier_id', 'weight', 'length', 'width', 'height', 'diameter', 'sold_count', 'limit_count', 'stock', 'stock_warn', 'market_price', 'price', 'image', 'model_id', 'is_sale', 'sort_order', 'bouns_points', 'experience_points', 'is_delete', 'express_template', 'sku_mode', 'is_taking', 'is_express', 'express_type'], 'integer'],
[['cat_id', 'brand_id', 'shop_cat_id', 'name'], 'required'], [['cat_id', 'brand_id', 'shop_cat_id', 'name'], 'required'],
[['sn'], 'checkExist'], [['sn'], 'checkExist'],
[['description', 'coverImageId', 'detailImageId'], 'string'], [['description', 'coverImageId', 'detailImageId'], 'string'],
@ -93,7 +119,8 @@ class Goods extends \yii\db\ActiveRecord
[['code'], 'string', 'max' => 50], [['code'], 'string', 'max' => 50],
[['unit'], 'string', 'max' => 16], [['unit'], 'string', 'max' => 16],
[['brief'], 'string', 'max' => 255], [['brief'], 'string', 'max' => 255],
[['weight', 'length', 'width', 'height', 'diameter', 'sold_count', 'market_price', 'price'], 'checkNegative'],
[['weight', 'length', 'width', 'height', 'diameter', 'sold_count', 'market_price', 'price', 'uniform_postage'], 'checkNegative'],
[['uniform_postage'], 'safe']
]; ];
} }
@ -164,9 +191,14 @@ class Goods extends \yii\db\ActiveRecord
'bouns_points' => '奖励积分', 'bouns_points' => '奖励积分',
'experience_points' => '经验值', 'experience_points' => '经验值',
'is_delete' => '是否删除,1为已删除', 'is_delete' => '是否删除,1为已删除',
'express_template' => '配送详情id',
'express_template' => '配送详情',
'created_at' => '创建时间', 'created_at' => '创建时间',
'updated_at' => '更新时间', 'updated_at' => '更新时间',
'sku_mode' => 'sku类型',
'is_taking' => '是否自提',
'is_express' => '是否快递发货',
'express_type' => '快递运费方式',
'uniform_postage' => '统一邮费',
]; ];
} }

4
backend/modules/goods/models/ars/GoodsSku.php

@ -6,7 +6,7 @@ use Yii;
use yii\behaviors\TimestampBehavior; use yii\behaviors\TimestampBehavior;
/** /**
* This is the model class for table "goods_goods_sku".
* This is the model class for table "atg_goods_sku".
* *
* @property int $id * @property int $id
* @property int $goods_id 商品id * @property int $goods_id 商品id
@ -38,7 +38,7 @@ class GoodsSku extends \yii\db\ActiveRecord
*/ */
public static function tableName() public static function tableName()
{ {
return 'goods_goods_sku';
return 'atg_goods_sku';
} }
/** /**

6
backend/modules/goods/views/goods/create.php

@ -42,6 +42,12 @@ Yii::$app->params['bsVersion'] = '4.x';
'attrValue' => [], 'attrValue' => [],
]), ]),
], ],
[
'label' => '<i class="fas fa-shipping-fast"></i> 物流信息',
'content' => $this->render('express', ['model' => $model,
'form' => $form,
]),
],
[ [
'label' => '<i class="fas fa-ad"></i> 详情上传', 'label' => '<i class="fas fa-ad"></i> 详情上传',
'content' => $this->render('new_editor', ['model' => $model, 'content' => $this->render('new_editor', ['model' => $model,

60
backend/modules/goods/views/goods/express.php

@ -0,0 +1,60 @@
<?php
use yii\helpers\Url;
use blobt\widgets\Icheck;
use backend\modules\goods\models\ars\Goods;
use linyao\widgets\Select2;
use backend\modules\shop\models\ars\ExpressTemplate;
/* @var $this yii\web\View */
/* @var $model backend\modules\goods\models\ars\Goods */
/* @var $form yii\widgets\ActiveForm */
?>
<?= $form->field($model, 'is_taking')->widget(Icheck::className(), ['items' => Goods::$isTaking, 'type' => 'radio']) ?>
<?= $form->field($model, 'is_express')->widget(Icheck::className(), ['items' => Goods::$isExpress, 'type' => 'radio']) ?>
<fieldset id="isExpress" style="display: <?= $model->is_express == Goods::IS_EXPRESS_NO ? 'none' : 'block' ?>">
<?= $form->field($model, 'express_type')->widget(Icheck::className(), ['items' => Goods::$expressType, 'type' => 'radio']) ?>
<fieldset id="uniformPostage" style="display: <?= $model->express_type == Goods::EXPRESS_TYPE_UNIFORM_POSTAGE ? 'block' : 'none' ?>">
<?= $form->field($model, 'uniform_postage')->textInput() ?>
</fieldset>
<fieldset id="expressTemplate" style="display: <?= $model->express_type == Goods::EXPRESS_TYPE_EXPRESS_TEMPLAGE ? 'block' : 'none' ?>">
<?= $form->field($model, 'express_template')->widget(Select2::className(), ["items" => ExpressTemplate::modelColumn()]) ?>
</fieldset>
</fieldset>
<?php
$js =<<<JS
$("input:radio[name='Goods[is_express]']").on('ifChecked', function(event){
if ($(this).val() === '1') {
$("#isExpress").show();
} else {
$("#isExpress").hide();
}
})
$("input:radio[name='Goods[express_type]']").on('ifChecked', function(event){
if ($(this).val() === '1') {
$("#uniformPostage").show();
$("#expressTemplate").hide();
} else {
$("#expressTemplate").show();
$("#uniformPostage").hide();
}
})
$("#goods-uniform_postage").blur(function(){
if(isNaN($(this).val())){
$(this).val("0.00")
}
if($(this).val().indexOf('-') != -1){
$(this).val("0.00")
}
var basicPrice = $(this).val();
$(this).val(basicPrice.toString().match(/^\d+(?:\.\d{0,2})?/));
})
JS;
$this->registerJs($js);
?>

6
backend/modules/goods/views/goods/picture.php

@ -15,9 +15,8 @@ use yii\helpers\Url;
'maxCount' => 1, 'maxCount' => 1,
'fillInAttribute' => 'coverImageId', 'fillInAttribute' => 'coverImageId',
'model' => $model, 'model' => $model,
'ruleVerify' => $model->ruleVerify,
'previewConfig' => [ 'previewConfig' => [
'url' => Url::to(['image-file', 'fileidstr' => $model->coverImageId]),
'url' => Url::to(['image-file', 'fileidstr' => $model->coverImageId, 'ruleverify' => $model->ruleVerify]),
], ],
])->label('商品封面图') ?> ])->label('商品封面图') ?>
@ -30,8 +29,7 @@ use yii\helpers\Url;
'maxCount' => 5, 'maxCount' => 5,
'fillInAttribute' => 'detailImageId', 'fillInAttribute' => 'detailImageId',
'model' => $model, 'model' => $model,
'ruleVerify' => $model->ruleVerify,
'previewConfig' => [ 'previewConfig' => [
'url' => Url::to(['image-file', 'fileidstr' => $model->detailImageId]),
'url' => Url::to(['image-file', 'fileidstr' => $model->detailImageId, 'ruleverify' => $model->ruleVerify]),
], ],
])->label('商品详情图') ?> ])->label('商品详情图') ?>

6
backend/modules/goods/views/goods/update.php

@ -44,6 +44,12 @@ Yii::$app->params['bsVersion'] = '4.x';
'goodsModel' => $model, 'goodsModel' => $model,
]), ]),
], ],
[
'label' => '<i class="fas fa-shipping-fast"></i> 物流信息',
'content' => $this->render('express', ['model' => $model,
'form' => $form,
]),
],
[ [
'label' => '<i class="fas fa-ad"></i> 详情上传', 'label' => '<i class="fas fa-ad"></i> 详情上传',
'content' => $this->render('new_editor', ['model' => $model, 'content' => $this->render('new_editor', ['model' => $model,

275
backend/modules/shop/controllers/ExpressTemplateController.php

@ -2,17 +2,20 @@
namespace backend\modules\shop\controllers; namespace backend\modules\shop\controllers;
use backend\modules\shop\models\ars\City;
use backend\modules\shop\models\ars\Province;
use backend\modules\shop\models\ars\City;
use backend\modules\shop\models\ars\Province;
use backend\modules\shop\models\searchs\ExpressAreaSearch;
use Yii; use Yii;
use backend\modules\shop\models\ars\ExpressTemplate;
use backend\modules\shop\models\searchs\ExpressTemplateSearch;
use yii\caching\Cache;
use backend\modules\shop\models\ars\ExpressTemplate;
use backend\modules\shop\models\searchs\ExpressTemplateSearch;
use yii\web\Controller; use yii\web\Controller;
use yii\web\NotFoundHttpException; use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter; use yii\filters\VerbFilter;
use yii\web\Response; use yii\web\Response;
use yii\widgets\ActiveForm; use yii\widgets\ActiveForm;
use backend\modules\shop\models\ars\ExpressArea;
use backend\modules\goods\models\ars\Goods;
/** /**
* ExpressTemplateController implements the CRUD actions for ExpressTemplate model. * ExpressTemplateController implements the CRUD actions for ExpressTemplate model.
@ -71,52 +74,13 @@ class ExpressTemplateController extends Controller
public function actionCreate() public function actionCreate()
{ {
$model = new ExpressTemplate(); $model = new ExpressTemplate();
$model->calculation_type = ExpressTemplate::CALCULATION_TYPE_NUMBER;
$model->basic_count = 1;
$model->basic_price = '0.00';
if (Yii::$app->request->isPost) {
$data = Yii::$app->request->post('ExpressTemplate');
if (Yii::$app->request->isAjax) {
$model->load($data, '');
Yii::$app->response->format = Response::FORMAT_JSON;
$data = ActiveForm::validate($model);
$data['status'] = 2;
return $data;
}
if (Yii::$app->request->post('area') == null) {
return $this->redirect(Yii::$app->request->referrer . '?status=1');
}
$cityIds = array_keys(Yii::$app->request->post('area'));
$data['city'] = implode(',', $cityIds);
$model->load($data, '');
$model->basic_price *= 100;
$model->extra_price *= 100;
if ($model->calculation_type == ExpressTemplate::CALCULATION_TYPE_WEIGHT) {
$model->basic_count *= 10;
$model->extra_count *= 10;
} else {
$model->basic_count *= 1;
$model->extra_count *= 1;
}
$model->save();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect('index'); return $this->redirect('index');
} }
$data = [];
$provinces = Province::find()->cache(0)->all();
foreach ($provinces as $k => $v) {
$data[$k]['province'] = $v->name;
$cities = City::find()->cache(0)
->where(['province_id' => $v->province_id])
->all();
foreach ($cities as $city) {
$data[$k]['city'][] = ['id' => $city->city_id, 'name' => $city->name];
}
}
return $this->render('create', [ return $this->render('create', [
'model' => $model, 'model' => $model,
'data' => $data
]); ]);
} }
@ -130,36 +94,13 @@ class ExpressTemplateController extends Controller
public function actionUpdate($id) public function actionUpdate($id)
{ {
$model = $this->findModel($id); $model = $this->findModel($id);
$model->basic_price /= 100;
$model->extra_price /= 100;
if ($model->calculation_type == ExpressTemplate::CALCULATION_TYPE_WEIGHT) {
$model->basic_count /= 10;
$model->extra_count /= 10;
}
$data = Yii::$app->request->post('ExpressTemplate');
if ($data) {
if (Yii::$app->request->post('area') == null) {
return $this->redirect(Yii::$app->request->referrer . '&status=1');
}
$cityIds = array_keys(Yii::$app->request->post('area'));
$data['city'] = implode(',', $cityIds);
$model->load($data, '');
$model->save();
return $this->render('view', ['model' => ExpressTemplate::findOne($model->id)]);
}
$data = [];
$provinces = Province::find()->cache(0)->all();
foreach ($provinces as $k => $v) {
$data[$k]['province'] = $v->name;
$cities = City::find()->cache(0)
->where(['province_id' => $v->province_id])
->all();
foreach ($cities as $city) {
$data[$k]['city'][] = ['id' => $city->city_id, 'name' => $city->name];
}
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect('index');
} }
return $this->render('update', [ return $this->render('update', [
'model' => $model, 'data' => $data, 'cities' => explode(',', $model->city)
'model' => $model,
]); ]);
} }
@ -172,7 +113,13 @@ class ExpressTemplateController extends Controller
*/ */
public function actionDelete($id) public function actionDelete($id)
{ {
$this->findModel($id)->delete();
if (Goods::find()->where(['express_template' => $id])->count() == 0) {
$expressTemplateModel = $this->findModel($id);
ExpressArea::deleteAll(['express_template' => $expressTemplateModel->id]);
$expressTemplateModel->delete();
} else {
Yii::$app->session->setFlash('error', '该模板已被使用');
}
return $this->redirect(['index']); return $this->redirect(['index']);
} }
@ -213,4 +160,184 @@ class ExpressTemplateController extends Controller
'columns' => $searchModel->columns() 'columns' => $searchModel->columns()
]); ]);
} }
/**
* @return string
* 运费区域列表
*/
public function actionExpressAreaList($id)
{
$expressTemplate = ExpressTemplate::findOne($id);
$searchModel = new ExpressAreaSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams, $id);
return $this->render('express_area_list', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'columns' => $searchModel->columns(),
'expressTemplate' => $expressTemplate
]);
}
/**
* @return array|mixed|string|Response
* 运费区域模板区域创建方法
*/
public function actionExpressAreaCreate()
{
$expressTemplateId = Yii::$app->request->get('expressTemplateId');
$expressTemplateModel = ExpressTemplate::findOne($expressTemplateId);
$model = new ExpressArea();
$model->basic_count = 1;
$model->basic_price = '0.00';
$model->express_template = $expressTemplateModel->id;
if (Yii::$app->request->isPost) {
$data = Yii::$app->request->post('ExpressArea');
if (Yii::$app->request->isAjax) {
$model->load($data, '');
Yii::$app->response->format = Response::FORMAT_JSON;
$data = ActiveForm::validate($model);
$data['status'] = 2;
return $data;
}
if (Yii::$app->request->post('area') == null) {
return $this->redirect(Yii::$app->request->referrer . '?status=1');
}
$cityIds = array_keys(Yii::$app->request->post('area'));
$data['city'] = implode(',', $cityIds);
$model->load($data, '');
$model->basic_price *= 100;
$model->extra_price *= 100;
if ($expressTemplateModel->calculation_type == ExpressTemplate::CALCULATION_TYPE_WEIGHT) {
$model->basic_count *= 10;
$model->extra_count *= 10;
} else {
$model->basic_count *= 1;
$model->extra_count *= 1;
}
$model->save();
return $this->redirect('express-area-list?id='.$model->express_template);
}
$data = [];
$expressAreas = ExpressArea::find()->select(['city'])->where(['express_template' => $expressTemplateModel->id])->all();
$expressAresCityIdArr = [];
if ($expressAreas) {
foreach ($expressAreas as $expressAreaCity) {
$cityIdArr = explode(',', $expressAreaCity->city);
$expressAresCityIdArr = array_unique(array_merge($cityIdArr, $expressAresCityIdArr));
}
}
$provinces = Province::find()->cache(0)->all();
$j = 0;
foreach ($provinces as $k => $v) {
$cities = City::find()
->where(['province_id' => $v->province_id])
->andWhere(['not in', 'city_id', $expressAresCityIdArr])
->all();
if ($cities) {
$data[$j]['province'] = $v->name;
foreach ($cities as $city) {
$data[$j]['city'][] = ['id' => $city->city_id, 'name' => $city->name];
}
$j++;
}
}
if (empty($data)) {
Yii::$app->session->setFlash('error', '已无地区选择');
return $this->redirect('express-area-list?id='.$expressTemplateModel->id);
}
return $this->render('express_area_create', [
'model' => $model,
'data' => $data,
'expressTemplateModel' => $expressTemplateModel
]);
}
/**
* @return array|mixed|string|Response
* 运费区域模板区域更新方法
*/
public function actionExpressAreaUpdate($id)
{
$model = ExpressArea::findOne($id);
$expressTemplateModel = ExpressTemplate::findOne($model->express_template);
$model->basic_price /= 100;
$model->extra_price /= 100;
if ($expressTemplateModel->calculation_type == ExpressTemplate::CALCULATION_TYPE_WEIGHT) {
$model->basic_count /= 10;
$model->extra_count /= 10;
}
$data = Yii::$app->request->post('ExpressArea');
if ($data) {
if (Yii::$app->request->post('area') == null) {
return $this->redirect(Yii::$app->request->referrer . '&status=1');
}
$cityIds = array_keys(Yii::$app->request->post('area'));
$data['city'] = implode(',', $cityIds);
$model->load($data, '');
$model->basic_price *= 100;
$model->extra_price *= 100;
if ($expressTemplateModel->calculation_type == ExpressTemplate::CALCULATION_TYPE_WEIGHT) {
$model->basic_count *= 10;
$model->extra_count *= 10;
} else {
$model->basic_count *= 1;
$model->extra_count *= 1;
}
$model->save();
return $this->redirect('express-area-list?id='.$model->express_template);
}
$data = [];
$expressAreas = ExpressArea::find()->select(['city'])->where(['express_template' => $expressTemplateModel->id])->andWhere(['!=', 'id', $id])->all();
$expressAresCityIdArr = [];
if ($expressAreas) {
foreach ($expressAreas as $expressAreaCity) {
$cityIdArr = explode(',', $expressAreaCity->city);
$expressAresCityIdArr = array_unique(array_merge($cityIdArr, $expressAresCityIdArr));
}
}
$provinces = Province::find()->cache(0)->all();
$j = 0;
foreach ($provinces as $k => $v) {
$cities = City::find()
->where(['province_id' => $v->province_id])
->andWhere(['not in', 'city_id', $expressAresCityIdArr])
->all();
if ($cities) {
$data[$j]['province'] = $v->name;
foreach ($cities as $city) {
$data[$j]['city'][] = ['id' => $city->city_id, 'name' => $city->name];
}
$j++;
}
}
return $this->render('express_area_update', [
'model' => $model, 'data' => $data, 'cities' => explode(',', $model->city), 'expressTemplateModel' => $expressTemplateModel
]);
}
/**
* @param $id
* @return string
* 运费区域模板区域查看方法
*/
public function actionExpressAreaView($id)
{
$expressAreaModel = ExpressArea::findOne($id);
$expressTemplateModel = ExpressTemplate::findOne($expressAreaModel->express_template);
return $this->render('express_area_view', [
'model' => $expressAreaModel,
'expressTemplateModel' => $expressTemplateModel
]);
}
public function actionExpressAreaDelete($id)
{
$expressAreaModel = ExpressArea::findOne($id);
$expressTemplateId = $expressAreaModel->express_template;
$expressAreaModel->delete();
return $this->redirect('express-area-list?id='.$expressTemplateId);
}
} }

32
backend/modules/shop/migrations/m191205_092426_drop_columns_province_city_area_basic_price_basic_count_extra_count_extra_price_in_table_ats_express_template.php

@ -0,0 +1,32 @@
<?php
use yii\db\Migration;
/**
* Class m191205_092426_drop_columns_province_city_area_basic_price_basic_count_extra_count_extra_price_in_table_ats_express_template
*/
class m191205_092426_drop_columns_province_city_area_basic_price_basic_count_extra_count_extra_price_in_table_ats_express_template extends Migration
{
public function up()
{
$this->dropColumn('ats_express_template', 'province');
$this->dropColumn('ats_express_template', 'city');
$this->dropColumn('ats_express_template', 'area');
$this->dropColumn('ats_express_template', 'extra_price');
$this->dropColumn('ats_express_template', 'basic_price');
$this->dropColumn('ats_express_template', 'basic_count');
$this->dropColumn('ats_express_template', 'extra_count');
}
public function down()
{
$this->addColumn('ats_express_template', 'province', $this->text()->comment('省份'));
$this->addColumn('ats_express_template', 'city', $this->text()->comment('城市'));
$this->addColumn('ats_express_template', 'area', $this->text()->comment('区域'));
$this->addColumn('ats_express_template', 'extra_price', $this->integer(20)->defaultValue(null)->comment('续重运费'));
$this->addColumn('ats_express_template', 'basic_price', $this->integer(20)->defaultValue(null)->comment('基本运费'));
$this->addColumn('ats_express_template', 'basic_count', $this->integer(20)->defaultValue(null)->comment('基本数量'));
$this->addColumn('ats_express_template', 'extra_count', $this->integer(20)->defaultValue(null)->comment('续重数量'));
return true;
}
}

36
backend/modules/shop/migrations/m191205_092942_create_table_ats_express_area.php

@ -0,0 +1,36 @@
<?php
use yii\db\Migration;
/**
* Class m191205_092942_create_table_ats_express_area
*/
class m191205_092942_create_table_ats_express_area extends Migration
{
public function up()
{
$tableOptions = 'CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE=InnoDB COMMENT="快递区域价格表"';
$this->createTable('ats_express_area', [
'id' => $this->primaryKey(),
'province' => $this->text()->comment('省份'),
'city' => $this->text()->comment('城市'),
'area' => $this->text()->comment('区域'),
'express_template' => $this->integer(11)->defaultValue(null)->comment('运费模板id'),
'extra_price' => $this->integer(20)->defaultValue(null)->comment('续重运费'),
'basic_price' => $this->integer(20)->defaultValue(null)->comment('基本运费'),
'basic_count' => $this->integer(20)->defaultValue(null)->comment('基本数量'),
'extra_count' => $this->integer(20)->defaultValue(null)->comment('续重数量'),
'updated_at'=>$this->integer(11)->defaultValue(null)->comment('更新时间'),
'created_at'=>$this->integer(11)->defaultValue(null)->comment('创建时间'),
],$tableOptions);
}
/**
* {@inheritdoc}
*/
public function down()
{
$this->dropTable('ats_express_area');
return true;
}
}

101
backend/modules/shop/models/ars/ExpressArea.php

@ -0,0 +1,101 @@
<?php
namespace backend\modules\shop\models\ars;
use Yii;
use yii\behaviors\TimestampBehavior;
/**
* This is the model class for table "ats_express_area".
*
* @property int $id
* @property string $province 省份
* @property string $city 城市
* @property string $area 区域
* @property int $express_template 运费模板id
* @property int $extra_price 续重运费
* @property int $basic_price 基本运费
* @property int $basic_count 基本数量
* @property int $extra_count 续重数量
* @property int $updated_at 更新时间
* @property int $created_at 创建时间
*/
class ExpressArea extends \yii\db\ActiveRecord
{
public static $formList = [
1 => [
"basic_count"=>"基本重量(KG)",
"basic_price"=>"基本运费(元)",
"extra_count"=>"续重重量(KG)",
"extra_price"=>"续重运费(元)"
],
2 => [
"basic_count"=>"基本数量(件)",
"basic_price"=>"基本运费(元)",
"extra_count"=>"续重数量(件)",
"extra_price"=>"续重运费(元)"
]
];
/**
* {@inheritdoc}
*/
public static function tableName()
{
return 'ats_express_area';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['province', 'city', 'area'], 'string'],
[['express_template'], 'integer'],
[['extra_price', 'basic_price', 'basic_count', 'extra_count'], 'safe'],
[['extra_price', 'basic_price', 'basic_count', 'extra_count'], 'number'],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'id',
'province' => '省份',
'city' => '城市',
'area' => '区域',
'express_template' => '运费模板id',
'extra_price' => '续重运费',
'basic_price' => '基本运费',
'basic_count' => '基本数量',
'extra_count' => '续重数量',
'updated_at' => '更新时间',
'created_at' => '创建时间',
];
}
/**
* @author linyao
* @email 602604991@qq.com
* @created Nov 8, 2019
*
* 行为存储创建时间和更新时间
*/
public function behaviors()
{
return [
[
'class' => TimestampBehavior::className(),
'createdAtAttribute' => 'created_at',
'updatedAtAttribute' => 'updated_at',
'value' => function() {
return time();
},
],
];
}
}

27
backend/modules/shop/models/ars/ExpressTemplate.php

@ -10,15 +10,8 @@ use yii\behaviors\TimestampBehavior;
* *
* @property int $id * @property int $id
* @property string $name 名称 * @property string $name 名称
* @property string $province 省份
* @property string $city 城市
* @property string $area 区域
* @property int $extra_price 续重运费
* @property int $updated_at 更新时间 * @property int $updated_at 更新时间
* @property int $created_at 创建时间 * @property int $created_at 创建时间
* @property int $basic_price 基本运费
* @property int $basic_count 基本数量
* @property int $extra_count 续重数量
* @property int $calculation_type 计算方式 * @property int $calculation_type 计算方式
*/ */
class ExpressTemplate extends \yii\db\ActiveRecord class ExpressTemplate extends \yii\db\ActiveRecord
@ -46,10 +39,8 @@ class ExpressTemplate extends \yii\db\ActiveRecord
{ {
return [ return [
[['name'], 'required'], [['name'], 'required'],
[['province', 'city', 'area'], 'string'],
[['calculation_type'], 'integer'], [['calculation_type'], 'integer'],
[['name'], 'string', 'max' => 255],
[['extra_price', 'basic_price', 'basic_count', 'extra_count'], 'safe']
[['name'], 'string', 'max' => 255]
]; ];
} }
@ -61,15 +52,8 @@ class ExpressTemplate extends \yii\db\ActiveRecord
return [ return [
'id' => 'id', 'id' => 'id',
'name' => '名称', 'name' => '名称',
'province' => '省份',
'city' => '城市',
'area' => '区域',
'extra_price' => '续重运费',
'updated_at' => '更新时间', 'updated_at' => '更新时间',
'created_at' => '创建时间', 'created_at' => '创建时间',
'basic_price' => '基本运费',
'basic_count' => '基本数量',
'extra_count' => '续重数量',
'calculation_type' => '计算方式', 'calculation_type' => '计算方式',
]; ];
} }
@ -95,4 +79,13 @@ class ExpressTemplate extends \yii\db\ActiveRecord
], ],
]; ];
} }
/**
* @return array
* 数据键值对
*/
public static function modelColumn()
{
return $column = self::find()->select(['name'])->indexBy('id')->column();
}
} }

187
backend/modules/shop/models/searchs/ExpressAreaSearch.php

@ -0,0 +1,187 @@
<?php
namespace backend\modules\shop\models\searchs;
use backend\modules\shop\models\ars\City;
use backend\modules\shop\models\ars\Province;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use yii\helpers\ArrayHelper;
use backend\modules\shop\models\ars\ExpressArea;
use yii;
use yii\bootstrap4\Html;
/**
* ExpressAreaSearch represents the model behind the search form of `backend\modules\shop\models\ars\ExpressArea`.
*/
class ExpressAreaSearch extends ExpressArea
{
/**
* @return array
* 增加创建时间查询字段
*/
public function attributes()
{
return ArrayHelper::merge(['created_at_range'], parent::attributes());
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['id', 'express_template', 'extra_price', 'basic_price', 'basic_count', 'extra_count', 'updated_at', 'created_at'], 'integer'],
[['province', 'city', 'area'], 'safe'],
['created_at_range','safe'],
];
}
/**
* {@inheritdoc}
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* @return array
* 列格式
*/
public function columns()
{
return [
[
'class' => 'blobt\grid\CheckboxColumn',
'width' => '2%',
'align' => 'center'
],
'id',
['attribute' => 'city',
'value' => function ($model) {
$expressAreas = ExpressArea::findOne($model->id);
$expressAresCityIdArr = explode(',', $expressAreas->city);
$cities = [];
$provinces = Province::find()->cache(0)->all();
foreach ($provinces as $k => $v) {
$cityId = City::find()
->select(['city_id'])
->where(['province_id' => $v->province_id])
->column();
if (empty(array_diff($cityId, $expressAresCityIdArr))) {
$cities[] = $v->name;
}else{
foreach (\backend\modules\shop\models\ars\City::find()->andWhere(['in', 'city_id', array_diff($cityId, array_diff($cityId, $expressAresCityIdArr))])->all() as $city) {
$cities[] = $city->name;
}
}
}
return implode(' , ', $cities);
},
],
[
'class' => 'iron\grid\ActionColumn',
'align' => 'center',
'config' => [
[
'name' => 'express-area-view',
'icon' => 'list',
'title' => '详情',
],
[
'name' => 'express-area-update',
'icon' => 'pencil',
'title' => '修改'
],
[
'name' => 'express-area-delete',
'icon' => 'trash',
'title' => '删除',
'contents' => '确定删除?'
]
],
],
];
}
/**
* @param $params
* @return ActiveDataProvider
* 不分页的所有数据
*/
public function allData($params)
{
$query = ExpressArea::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => false,
'sort' => false
]);
$this->load($params);
return $this->filter($query, $dataProvider);
}
/**
* Creates data provider instance with search query applied
*
* @param array $params
*
* @return ActiveDataProvider
*/
public function search($params, $expressTemplateId)
{
$query = ExpressArea::find()->where(['express_template' => $expressTemplateId]);
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => [
'pageSizeLimit' => [1, 200]
],
'sort' => [
'defaultOrder' => [
'id' => SORT_DESC,
]
],
]);
$this->load($params);
return $this->filter($query, $dataProvider);
}
/**
* @param $query
* @param $dataProvider
* @return ActiveDataProvider
* 条件筛选
*/
private function filter($query, $dataProvider){
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'id' => $this->id,
'express_template' => $this->express_template,
'extra_price' => $this->extra_price,
'basic_price' => $this->basic_price,
'basic_count' => $this->basic_count,
'extra_count' => $this->extra_count,
'updated_at' => $this->updated_at,
'created_at' => $this->created_at,
]);
$query->andFilterWhere(['like', 'province', $this->province])
->andFilterWhere(['like', 'city', $this->city])
->andFilterWhere(['like', 'area', $this->area]);
if ($this->created_at_range) {
$arr = explode(' ~ ', $this->created_at_range);
$start = strtotime($arr[0]);
$end = strtotime($arr[1]) + 3600 * 24;
$query->andFilterWhere(['between', 'created_at', $start, $end]);
}
return $dataProvider;
}
}

41
backend/modules/shop/models/searchs/ExpressTemplateSearch.php

@ -26,8 +26,8 @@ class ExpressTemplateSearch extends ExpressTemplate
public function rules() public function rules()
{ {
return [ return [
[['id', 'calculation_type', 'basic_price', 'basic_count', 'extra_price', 'extra_count', 'updated_at', 'created_at'], 'integer'],
[['name', 'province', 'city', 'area'], 'safe'],
[['id', 'calculation_type', 'updated_at', 'created_at'], 'integer'],
[['name'], 'safe'],
['created_at_range','safe'], ['created_at_range','safe'],
]; ];
} }
@ -52,11 +52,35 @@ class ExpressTemplateSearch extends ExpressTemplate
'width' => '2%', 'width' => '2%',
'align' => 'center' 'align' => 'center'
], ],
'id',
'name',
'id',
'name',
[
'attribute' => 'calculation_type',
'value' => function ($model) {
return ExpressTemplate::$calculationType[$model->calculation_type];
}
],
[ [
'class' => 'iron\grid\ActionColumn', 'class' => 'iron\grid\ActionColumn',
'align' => 'center', 'align' => 'center',
'config' => [
[
'name' => 'update',
'icon' => 'pencil',
'title' => '修改'
],
[
'name' => 'express-area-list',
'icon' => 'hard-drive',
'title' => '配送区域'
],
[
'name' => 'delete',
'icon' => 'trash',
'title' => '删除',
'contents' => '确定删除?'
]
],
], ],
]; ];
} }
@ -122,18 +146,11 @@ class ExpressTemplateSearch extends ExpressTemplate
$query->andFilterWhere([ $query->andFilterWhere([
'id' => $this->id, 'id' => $this->id,
'calculation_type' => $this->calculation_type, 'calculation_type' => $this->calculation_type,
'basic_price' => $this->basic_price,
'basic_count' => $this->basic_count,
'extra_price' => $this->extra_price,
'extra_count' => $this->extra_count,
'updated_at' => $this->updated_at, 'updated_at' => $this->updated_at,
'created_at' => $this->created_at, 'created_at' => $this->created_at,
]); ]);
$query->andFilterWhere(['like', 'name', $this->name])
->andFilterWhere(['like', 'province', $this->province])
->andFilterWhere(['like', 'city', $this->city])
->andFilterWhere(['like', 'area', $this->area]);
$query->andFilterWhere(['like', 'name', $this->name]);
if ($this->created_at_range) { if ($this->created_at_range) {
$arr = explode(' ~ ', $this->created_at_range); $arr = explode(' ~ ', $this->created_at_range);
$start = strtotime($arr[0]); $start = strtotime($arr[0]);

145
backend/modules/shop/views/express-template/_form.php

@ -2,144 +2,31 @@
use blobt\widgets\Icheck; use blobt\widgets\Icheck;
use backend\modules\shop\models\ars\ExpressTemplate; use backend\modules\shop\models\ars\ExpressTemplate;
use yii\bootstrap4\ActiveForm;
use yii\bootstrap4\Html;
/* @var $this yii\web\View */ /* @var $this yii\web\View */
/* @var $model backend\modules\shop\models\ars\ExpressTemplate */ /* @var $model backend\modules\shop\models\ars\ExpressTemplate */
/* @var $form yii\widgets\ActiveForm */ /* @var $form yii\widgets\ActiveForm */
?> ?>
<?php
$status = Yii::$app->request->get('status');
if ($status == 1) {
?>
<div class="alert alert-warning alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span
aria-hidden="true">&times;</span></button>
<p style="color: #2e2e2e">必须至少选择一个城市为配送区域</p>
</div>
<?php } ?>
<?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'calculation_type')->widget(Icheck::className(), ["items" => ExpressTemplate::$calculationType, 'type' => "radio"]) ?>
<?= $form->field($model, 'basic_count')->textInput() ?>
<?= $form->field($model, 'basic_price')->textInput() ?>
<?= $form->field($model, 'extra_count')->textInput() ?>
<?= $form->field($model, 'extra_price')->textInput() ?>
<div class="order-form">
<?php
$js=<<<JS
const formList = [//切换时,class对应的标题
{
"field-expresstemplate-basic_count":"基本重量(KG)",
"field-expresstemplate-basic_price":"基本运费(元)",
"field-expresstemplate-extra_count":"续重重量(KG)",
"field-expresstemplate-extra_price":"续重运费(元)"
},
{
"field-expresstemplate-basic_count":"基本数量(件)",
"field-expresstemplate-basic_price":"基本运费(元)",
"field-expresstemplate-extra_count":"续重数量(件)",
"field-expresstemplate-extra_price":"续重运费(元)"
}
]
const udfVal = [//初始值
[0.1,"0.00"],
[1,"0.00"]
]
var calType = 1;//初始的计算方式0:计重 1:计件
function updateTypeChangeCalType(type){//当切换计算方式
<?php $form = ActiveForm::begin(); ?>
$.each(formList[type],function(index,value){ //更改文字标题
$("." + index).children("label").html(value)
});
<?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>
$("#expresstemplate-basic_count").val(udfVal[type][0])//重置初始值
$("#expresstemplate-basic_price").val(udfVal[type][1])
$("#expresstemplate-extra_count").val(0)
$("#expresstemplate-extra_price").val(udfVal[type][1])
calType = type;
}
function changeCalType(type){//当切换计算方式
$.each(formList[type],function(index,value){ //更改文字标题
$("." + index).children("label").html(value)
});
<?php
if ($isCreate) {
echo $form->field($model, 'calculation_type')->widget(Icheck::className(), ["items" => ExpressTemplate::$calculationType, 'type' => "radio"]);
}
?>
if(!$("#expresstemplate-basic_count").val()){
$("#expresstemplate-basic_count").val(udfVal[type][0])//重置初始值
}
if(!$("#expresstemplate-basic_price").val()){
$("#expresstemplate-basic_price").val(udfVal[type][1])
}
if(!$("#expresstemplate-extra_count").val()){
$("#expresstemplate-extra_count").val(0)
}
if(!$("#expresstemplate-extra_price").val()){
$("#expresstemplate-extra_price").val(udfVal[type][1])
}
calType = type;
}
$(document).ready(function(){
$("#expresstemplate-basic_count").blur(function(){
if (calType == 0) {
if($(this).val() < 0.1){
$(this).val(0.1)
}
var basiccount = $(this).val();
$(this).val(Math.floor(basiccount * 10) / 10);
} else{
if($(this).val() < 1){
$(this).val(1)
}
var basiccount = $(this).val();
$(this).val(Math.floor(basiccount * 1) / 1);
}
})
$("#expresstemplate-basic_price").blur(function(){
if($(this).val().indexOf('-') != -1){
$(this).val("0.00")
}
var basicPrice = $(this).val();
$(this).val(basicPrice.toString().match(/^\d+(?:\.\d{0,2})?/));
})
$("#expresstemplate-extra_count").blur(function(){
if (calType == 0) {
if($(this).val() < 0){
$(this).val(0)
}
var basiccount = $(this).val();
$(this).val(Math.floor(basiccount * 10) / 10);
} else{
if($(this).val() < 0){
$(this).val(0)
}
var basiccount = $(this).val();
$(this).val(Math.floor(basiccount * 1) / 1);
}
})
$("#expresstemplate-extra_price").blur(function(){
if($(this).val().indexOf('-') != -1){
$(this).val("0.00")
}
var basicPrice = $(this).val();
$(this).val(basicPrice.toString().match(/^\d+(?:\.\d{0,2})?/));
})
<div class="form-group">
<?= Html::submitButton('保存', ['class' => 'btn btn-success']) ?>
<?= Html::a('返回', ['index'], ['class' => 'btn btn-info']) ?>
</div>
$("input:radio[name='ExpressTemplate[calculation_type]']").on('ifChecked', function(event){
updateTypeChangeCalType($(this).val()-1)
})
changeCalType(calType)
})
JS;
$this->registerJs($js)
<?php ActiveForm::end(); ?>
?>
</div>

36
backend/modules/shop/views/express-template/create.php

@ -13,38 +13,10 @@ $this->params['breadcrumbs'][] = $this->title;
Yii::$app->params['bsVersion'] = '4.x'; Yii::$app->params['bsVersion'] = '4.x';
?> ?>
<div class="express-template-create"> <div class="express-template-create">
<div class="express-template-form">
<?php
$form = ActiveForm::begin(['options' => ['class' => 'container-fluid']]);
<?= $this->render('_form', [
'model' => $model,
'isCreate' => true
]) ?>
echo TabsX::widget([
'bordered' => true,
'items' => [
[
'label' => '<i class="fas fa-user"></i> 基本信息',
'content' => $this->render('_form', [
'model' => $model,
'form' => $form,
]),
],
[
'label' => '<i class="fas fa-globe"></i> 选择配送区域',
'content' => $this->render('area', ['data' => $data, 'form' => $form, 'cities' => []
]),
],
],
'position' => TabsX::POS_ABOVE,
'encodeLabels' => false
]);
?>
<div class="form-group">
<?= Html::submitButton('保存', ['class' => 'btn btn-success']) ?>
<?= Html::a('返回', ['index'], ['class' => 'btn btn-info']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
</div> </div>

51
backend/modules/shop/views/express-template/express_area_create.php

@ -0,0 +1,51 @@
<?php
use yii\bootstrap4\Html;
use yii\bootstrap4\ActiveForm;
use kartik\tabs\TabsX;
/* @var $this yii\web\View */
/* @var $model backend\modules\shop\models\ars\ExpressTemplate */
$this->title = '创建区域运费模板';
$this->params['breadcrumbs'][] = ['label' => '运费区域模板', 'url' => ['express_area_list', ['id' => $expressTemplateModel->id]]];
$this->params['breadcrumbs'][] = $this->title;
Yii::$app->params['bsVersion'] = '4.x';
?>
<div class="express-template-create">
<div class="express-template-form">
<?php
$form = ActiveForm::begin(['options' => ['class' => 'container-fluid']]);
echo TabsX::widget([
'bordered' => true,
'items' => [
[
'label' => '<i class="fas fa-user"></i> 基本信息',
'content' => $this->render('express_area_form', [
'model' => $model,
'form' => $form,
'expressTemplateModel' => $expressTemplateModel
]),
],
[
'label' => '<i class="fas fa-globe"></i> 选择配送区域',
'content' => $this->render('area', ['data' => $data, 'form' => $form, 'cities' => []
]),
],
],
'position' => TabsX::POS_ABOVE,
'encodeLabels' => false
]);
?>
<div class="form-group">
<?= Html::submitButton('保存', ['class' => 'btn btn-success']) ?>
<?= Html::a('返回', ['express-area-list', 'id' => $expressTemplateModel->id], ['class' => 'btn btn-info']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>

156
backend/modules/shop/views/express-template/express_area_form.php

@ -0,0 +1,156 @@
<?php
use blobt\widgets\Icheck;
use backend\modules\shop\models\ars\ExpressTemplate;
/* @var $this yii\web\View */
/* @var $model backend\modules\shop\models\ars\ExpressTemplate */
/* @var $form yii\widgets\ActiveForm */
?>
<?php
$status = Yii::$app->request->get('status');
if ($status == 1) {
?>
<div class="alert alert-warning alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span
aria-hidden="true">&times;</span></button>
<p style="color: #2e2e2e">必须至少选择一个城市为配送区域</p>
</div>
<?php } ?>
<?= $form->field($model, 'express_template')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'basic_count')->textInput() ?>
<?= $form->field($model, 'basic_price')->textInput() ?>
<?= $form->field($model, 'extra_count')->textInput() ?>
<?= $form->field($model, 'extra_price')->textInput() ?>
<?php
$js=<<<JS
const formList = [//切换时,class对应的标题
{
"field-expressarea-basic_count":"基本重量(KG)",
"field-expressarea-basic_price":"基本运费(元)",
"field-expressarea-extra_count":"续重重量(KG)",
"field-expressarea-extra_price":"续重运费(元)"
},
{
"field-expressarea-basic_count":"基本数量(件)",
"field-expressarea-basic_price":"基本运费(元)",
"field-expressarea-extra_count":"续重数量(件)",
"field-expressarea-extra_price":"续重运费(元)"
}
]
const udfVal = [//初始值
[0.1,"0.00"],
[1,"0.00"]
]
var calType = {$expressTemplateModel->calculation_type}-1;//初始的计算方式0:计重 1:计件
function updateTypeChangeCalType(type){//当切换计算方式
$.each(formList[type],function(index,value){ //更改文字标题
$("." + index).children("label").html(value)
});
$("#expressarea-basic_count").val(udfVal[type][0])//重置初始值
$("#expressarea-basic_price").val(udfVal[type][1])
$("#expressarea-extra_count").val(0)
$("#expressarea-extra_price").val(udfVal[type][1])
calType = type;
}
function changeCalType(type){//当切换计算方式
$.each(formList[type],function(index,value){ //更改文字标题
$("." + index).children("label").html(value)
});
if(!$("#expressarea-basic_count").val()){
$("#expressarea-basic_count").val(udfVal[type][0])//重置初始值
}
if(!$("#expressarea-basic_price").val()){
$("#expressarea-basic_price").val(udfVal[type][1])
}
if(!$("#expressarea-extra_count").val()){
$("#expressarea-extra_count").val(0)
}
if(!$("#expressarea-extra_price").val()){
$("#expressarea-extra_price").val(udfVal[type][1])
}
calType = type;
}
$(document).ready(function(){
$("#expressarea-basic_count").blur(function(){
if(isNaN($(this).val())){
$(this).val(1)
}
if (calType == 0) {
if($(this).val() < 0.1){
$(this).val(1)
}
var basiccount = $(this).val();
// $(this).val(Math.floor(basiccount * 10) / 10);
$(this).val(basiccount.toString().match(/^\d+(?:\.\d{0,1})?/));
} else{
if($(this).val() < 1){
$(this).val(1)
}
var basiccount = $(this).val();
$(this).val(Math.floor(basiccount * 1) / 1);
}
})
$("#expressarea-basic_price").blur(function(){
if(isNaN($(this).val())){
$(this).val("0.00")
}
if($(this).val().indexOf('-') != -1){
$(this).val("0.00")
}
var basicPrice = $(this).val();
$(this).val(basicPrice.toString().match(/^\d+(?:\.\d{0,2})?/));
})
$("#expressarea-extra_count").blur(function(){
if(isNaN($(this).val())){
$(this).val(0)
}
if (calType == 0) {
if($(this).val() < 0){
$(this).val(0)
}
var basiccount = $(this).val();
$(this).val(Math.floor(basiccount * 10) / 10);
} else{
if($(this).val() < 0){
$(this).val(0)
}
var basiccount = $(this).val();
$(this).val(Math.floor(basiccount * 1) / 1);
}
})
$("#expressarea-extra_price").blur(function(){
if(isNaN($(this).val())){
$(this).val("0.00")
}
if($(this).val().indexOf('-') != -1){
$(this).val("0.00")
}
var basicPrice = $(this).val();
$(this).val(basicPrice.toString().match(/^\d+(?:\.\d{0,2})?/));
})
$("input:radio[name='ExpressArea[calculation_type]']").on('ifChecked', function(event){
updateTypeChangeCalType($(this).val()-1)
})
changeCalType(calType)
})
JS;
$this->registerJs($js)
?>

33
backend/modules/shop/views/express-template/express_area_list.php

@ -0,0 +1,33 @@
<?php
use yii\helpers\Html;
use iron\grid\GridView;
/* @var $this yii\web\View */
/* @var $searchModel backend\modules\shop\models\searchs\ExpressAreaSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */
$this->title = '运费区域模板:'.$expressTemplate->name;
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="row">
<div class="col-12">
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filter' => $this->render("_search", ['model' => $searchModel]),
'batch' => [
[
"label" => "删除",
"url" => "express-area/deletes"
],
],
'columns' => $columns,
'batchTemplate' => '',
'create' => '',
'export' => '',
'content' => Html::a('创建', ['express-area-create', 'expressTemplateId' => $expressTemplate->id], ['class' => 'btn btn-default']).
Html::a('返回', ['index'], ['class' => 'btn btn-default'])
]);
?>
</div>
</div>

52
backend/modules/shop/views/express-template/express_area_update.php

@ -0,0 +1,52 @@
<?php
use yii\bootstrap4\Html;
use yii\bootstrap4\ActiveForm;
use kartik\tabs\TabsX;
/* @var $this yii\web\View */
/* @var $model backend\modules\shop\models\ars\ExpressTemplate */
$this->title = '编辑区域运费模板';
$this->params['breadcrumbs'][] = ['label' => '运费模板', 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => '区域运费模板:'.$expressTemplateModel->name, 'url' => ['express-area-list', 'id' => $expressTemplateModel->id]];
$this->params['breadcrumbs'][] = '编辑区域运费模板';
Yii::$app->params['bsVersion'] = '4.x';
?>
<div class="express-template-update">
<div class="express-template-form">
<?php
$form = ActiveForm::begin(['options' => ['class' => 'container-fluid']]);
echo TabsX::widget([
'bordered' => true,
'items' => [
[
'label' => '<i class="fas fa-user"></i> 基本信息',
'content' => $this->render('express_area_form', [
'model' => $model,
'form' => $form,
'expressTemplateModel' => $expressTemplateModel
]),
],
[
'label' => '<i class="fas fa-globe"></i> 选择配送区域',
'content' => $this->render('area', ['data' => $data, 'form' => $form, 'cities' => $cities
]),
],
],
'position' => TabsX::POS_ABOVE,
'encodeLabels' => false
]);
?>
<div class="form-group">
<?= Html::submitButton('保存', ['class' => 'btn btn-success']) ?>
<?= Html::a('返回', ['express-area-list', 'id' => $expressTemplateModel->id], ['class' => 'btn btn-info']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>

94
backend/modules/shop/views/express-template/express_area_view.php

@ -0,0 +1,94 @@
<?php
use backend\modules\shop\models\ars\City;
use backend\modules\shop\models\ars\ExpressArea;
use backend\modules\shop\models\ars\Province;
use yii\helpers\Html;
use yii\widgets\DetailView;
use backend\modules\shop\models\ars\ExpressTemplate;
/* @var $this yii\web\View */
/* @var $model backend\modules\shop\models\ars\ExpressTemplate */
$this->title = $model->id;
$this->params['breadcrumbs'][] = ['label' => '运费模板', 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => '运费区域模板:'.$expressTemplateModel->name, 'url' => ['express-area-list?id='.$expressTemplateModel->id]];
$this->params['breadcrumbs'][] = $this->title;
\yii\web\YiiAsset::register($this);
?>
<div class="express-template-view">
<p>
<?= Html::a('返回列表', ['express-area-list?id='.$expressTemplateModel->id], ['class' => 'btn btn-success']) ?>
</p>
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'id',
[
'attribute' => 'basic_count',
'label' => ExpressArea::$formList[$expressTemplateModel->calculation_type]['basic_count'],
'value' => function ($model) {
$expressTemplateModel = ExpressTemplate::findOne($model->express_template);
if ($expressTemplateModel->calculation_type == ExpressTemplate::CALCULATION_TYPE_WEIGHT) {
return $model->basic_count /= 10;
} else {
return $model->basic_count;
}
}
],
[
'attribute' => 'basic_price',
'label' => ExpressArea::$formList[$expressTemplateModel->calculation_type]['basic_price'],
'value' => function ($model) {
return $model->basic_price /= 100;
}
],
[
'attribute' => 'extra_count',
'label' => ExpressArea::$formList[$expressTemplateModel->calculation_type]['extra_count'],
'value' => function ($model) {
$expressTemplateModel = ExpressTemplate::findOne($model->express_template);
if ($expressTemplateModel->calculation_type == ExpressTemplate::CALCULATION_TYPE_WEIGHT) {
return $model->extra_count /= 10;
} else {
return $model->extra_count;
}
}
],
[
'attribute' => 'extra_price',
'label' => ExpressArea::$formList[$expressTemplateModel->calculation_type]['extra_price'],
'value' => function ($model) {
return $model->extra_price /= 100;
}
],
'updated_at:datetime',
'created_at:datetime',
['attribute' => 'city',
'value' => function ($model) {
$expressAreas = ExpressArea::findOne($model->id);
$expressAresCityIdArr = explode(',', $expressAreas->city);
$cities = [];
$provinces = Province::find()->cache(0)->all();
foreach ($provinces as $k => $v) {
$cityId = City::find()
->select(['city_id'])
->where(['province_id' => $v->province_id])
->column();
if (empty(array_diff($cityId, $expressAresCityIdArr))) {
$cities[] = $v->name;
}else{
foreach (\backend\modules\shop\models\ars\City::find()->andWhere(['in', 'city_id', array_diff($cityId, array_diff($cityId, $expressAresCityIdArr))])->all() as $city) {
$cities[] = $city->name;
}
}
}
return implode(' , ', $cities);
},
],
],
]) ?>
</div>

36
backend/modules/shop/views/express-template/update.php

@ -14,38 +14,10 @@ $this->params['breadcrumbs'][] = 'Update ';
Yii::$app->params['bsVersion'] = '4.x'; Yii::$app->params['bsVersion'] = '4.x';
?> ?>
<div class="express-template-update"> <div class="express-template-update">
<div class="express-template-form">
<?php
$form = ActiveForm::begin(['options' => ['class' => 'container-fluid']]);
<?= $this->render('_form', [
'model' => $model,
'isCreate' => false
]) ?>
echo TabsX::widget([
'bordered' => true,
'items' => [
[
'label' => '<i class="fas fa-user"></i> 基本信息',
'content' => $this->render('_form', [
'model' => $model,
'form' => $form,
]),
],
[
'label' => '<i class="fas fa-globe"></i> 选择配送区域',
'content' => $this->render('area', ['data' => $data, 'form' => $form, 'cities' => $cities
]),
],
],
'position' => TabsX::POS_ABOVE,
'encodeLabels' => false
]);
?>
<div class="form-group">
<?= Html::submitButton('保存', ['class' => 'btn btn-success']) ?>
<?= Html::a('返回', ['index'], ['class' => 'btn btn-info']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
</div> </div>

65
vendor/iron/grid/GridView.php

@ -219,16 +219,12 @@ class GridView extends BaseListView
<div class="row"> <div class="row">
<div class="col-sm-12 col-md-6"> <div class="col-sm-12 col-md-6">
{batch} {batch}
<a href="{url}/create" class="btn btn-default"><i class="fas fa-plus-square mr-2"></i>添加</a>
{create}
<!-- <a href="#" data-url='export' class="export btn btn-default"><i class="fa fa-file-excel-o"></i>导出</a>--> <!-- <a href="#" data-url='export' class="export btn btn-default"><i class="fa fa-file-excel-o"></i>导出</a>-->
<div class="btn-group">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false"><i class="fas fa-file-upload mr-2"></i>导出</button>
<ul class="dropdown-menu" role="menu">
<li> <a class="dropdown-item export-page" href="#" data-url="{url}/export">本页</a></li>
<li> <a class="dropdown-item export-all" href="#" data-url="{url}/export">全部</a></li>
</ul>
</div>
{export}
<!-- <button type="button" id="export" class="btn btn-default"><i class="fa fa-file-excel-o"></i>导出</button>--> <!-- <button type="button" id="export" class="btn btn-default"><i class="fa fa-file-excel-o"></i>导出</button>-->
{content}
</div> </div>
<div class="col-sm-12 col-md-6"> <div class="col-sm-12 col-md-6">
{filter} {filter}
@ -263,6 +259,26 @@ HTML;
</ul> </ul>
</div> </div>
HTML; HTML;
public $export =<<<HTML
<div class="btn-group">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false"><i class="fas fa-file-upload mr-2"></i>导出</button>
<ul class="dropdown-menu" role="menu">
<li> <a class="dropdown-item export-page" href="#" data-url="{url}/export">本页</a></li>
<li> <a class="dropdown-item export-all" href="#" data-url="{url}/export">全部</a></li>
</ul>
</div>
HTML;
public $create =<<<HTML
<a href="{url}/create" class="btn btn-default"><i class="fas fa-plus-square mr-2"></i>添加</a>
HTML;
/**
* @var
* 表单头部内容
*/
public $content;
/** /**
* 初始化 grid view. * 初始化 grid view.
@ -447,6 +463,12 @@ SCRIPT;
return $this->renderBatch(); return $this->renderBatch();
case '{url}': case '{url}':
return Yii::$app->request->url; return Yii::$app->request->url;
case '{export}':
return $this->renderExport();
case '{create}':
return $this->renderCreate();
case '{content}':
return $this->renderContent();
default: default:
return false; return false;
} }
@ -696,4 +718,31 @@ SCRIPT;
]); ]);
} }
/**
* 渲染导出部分
* @return string
*/
protected function renderExport()
{
return $this->export;
}
/**
* 渲染创建部分
* @return string
*/
protected function renderCreate()
{
return $this->create;
}
/**
* 渲染表单头部内容
* @return string
*/
protected function renderContent()
{
return Html::tag('div', $this->content, ['class' => 'btn-group']);
}
} }
Loading…
Cancel
Save