Compare commits

...

73 Commits

Author SHA1 Message Date
linyaostalker 370a1fa63e refactor:删除无用模块文件 5 years ago
linyaostalker 28daca1d9a refactor:更改自定义菜单资源注册文件名字 5 years ago
linyaostalker 6db6431fdc refactor:修改自定义菜单操作界面修改 5 years ago
linyaostalker 513cb4359f feat:backend添加微信公众号模块,菜单增加自定义菜单栏目 5 years ago
linyaostalker 85e8daa55f feat:开发微信公众号资源注册方法 5 years ago
linyaostalker ac3b7b8f69 feat:开发后台自定义操作界面 5 years ago
linyaostalker 35ffe88e71 feat:创建微信公众号参数设置表 5 years ago
linyaostalker 056d7beca2 feat:开发处理前端自定义菜单数据方法,开发处理数据模型保存的报错信息方法,开发递归处理前端数据,开发拼接数据为微信菜单格式方法, 5 years ago
linyaostalker cb92924616 refactor:开发自定义菜单控制器方法 5 years ago
linyaostalker 9f079992f8 refactor:修改微信公众号模块文件命名空间 5 years ago
linyaostalker 8a1f705392 refactor:删除无用的测试图片 5 years ago
linyaostalker 4d43318dde refactor:修改登陆机制 5 years ago
linyaostalker 8061afbe55 feat:在backend注册微信公众号模块 5 years ago
linyaostalker 3f20dd42fc feat:创建微信公众号模块,开发图片资源注册引用方法,开发微信公众号自定义菜单操作页面及操作方法 5 years ago
linyaostalker 9ad275687c 增加后台操作微信公众号自定义菜单组件 5 years ago
linyaostalker 83d6afae0d feat:创建新分支wechat_public_account,合并order分支 5 years ago
ww519441258 60998c77b4 feat: 退款模块、物流模块 5 years ago
linyaostalker 94064c819b refactor:删除没用的react组件代码文件 5 years ago
linyaostalker 18216af064 feat:自提点后台列表增加名称检索字段 5 years ago
linyaostalker 0b14c1335d refactor:重构gridview的filter模块样式 5 years ago
linyaostalker 6b476b1d6e feat:供应商管理增加供应商名称和手机号码检索字段 5 years ago
linyaostalker 2a99c1d01c feat:品牌管理列表增加品牌名检索 5 years ago
linyaostalker c946c7db2e feat:前端商品分类列表增加类别名称检索 5 years ago
linyaostalker 3d2afc611e refactor:规格管理列表增加规格名称检索 5 years ago
ww519441258 23817a928b refactor: 部分退款功能重构 5 years ago
ww519441258 aad1a772b3 feat: 退款功能 5 years ago
ww519441258 0901cd9814 feat: 异步回调与转发回调功能 5 years ago
ww519441258 26c141d10b feat: 微信支付回调功能、生成支付参数功能,校验回调数据功能 5 years ago
ww519441258 d487a6809b feat: setup easyWechat 5 years ago
ww519441258 152a7b8d6b feat: wxPaymentLogic 5 years ago
travis e325943617 feat: 微信支付api 5 years ago
travis 0f3083cb56 refactor: 合并kernel 5 years ago
travis 3ef4994931 refactor: 部分发货逻辑代码 5 years ago
travis a952452834 fix: 保存发货商品信息 5 years ago
travis 1064aa0cd6 fix: 商品发货功能 5 years ago
travis 46c26a3b4a feat: 后台已发货商品显示优化 5 years ago
iron dda038297b refactor: 备注修改 5 years ago
iron 395a3fb755 feat: 订单运费计算,自动添加默认地址,库存判断 5 years ago
travis 0d4afa024e feat: 订单列表search 5 years ago
travis 5269d6f002 refactor: 部分发货功能重构 5 years ago
travis 600bc7154c refactor: 发货功能重构 5 years ago
root 3f53377e2e Merge branch 'antshop' into kernel 5 years ago
iron f1930e5fdc fix: 调试修复运费计算的问题 5 years ago
root e0e174bdb4 Merge branch 'antshop' into kernel 5 years ago
iron 0eed19172d feat: 增加订单保存前的运费计算和grid调整 5 years ago
root 94643aa063 Merge branch 'antshop' into kernel 5 years ago
iron c7c8ec09d4 feat: 运费计算逻辑 5 years ago
travis 41996eb93d feat: 优化发货列表显示 5 years ago
travis 0045513a52 feat: 发货列表修改功能 5 years ago
travis 8e14d803fe fix: 部分发货功能修改 5 years ago
travis 50581f75c8 fix: 订单发货商品js 5 years ago
root 9a0ddc3713 feat: 修改订单,购物车,商品,评论等业务逻辑 5 years ago
travis f7752a6466 refactor: 订单发货商品js修改为注册方式引入 5 years ago
travis 310ff82d34 feat: 订单发货按钮显示优化 5 years ago
travis 733ceeee62 feat: 订单收货信息显示修改 5 years ago
travis b235255687 style: 代码调整 5 years ago
travis 46d83ccd64 feat: 部分发货功能 5 years ago
travis 14c09ea63c feat: 优化订单显示 5 years ago
travis 132f25f284 refactor: 发货商品数据功能 5 years ago
travis 436144dbe8 feat: 发货功能第一版(部分发货待完善) 5 years ago
travis 843832fc29 feat: order const 5 years ago
travis 9dbda08d88 feat: 发货列表 5 years ago
travis 77a0e0bf8c fix: order dropdown 5 years ago
travis 13db38ab4a feat: 优化订单列表 5 years ago
travis 632c117c78 feat: 订单列表 5 years ago
root f97120a968 feat: 增加地址api并增加查看详情和删除操作的权限判断 5 years ago
root ba9c2fadba Merge branch 'antshop' into kernel 5 years ago
root 0dd6d123a1 refactor: 合并后台分支 5 years ago
root 51ef23749a feat: 前端用户登录验证和业务逻辑 5 years ago
root b555453cfc feat: 商品,购物车,订单的业务逻辑 5 years ago
root 6291bc6756 Merge branch 'antshop' into kernel 5 years ago
root 4ffe9b1ff9 feat: 合并分支增加商品模块 5 years ago
root 1dc563ea70 feat: 测试与云的交互 5 years ago
  1. 2
      .gitignore
  2. 1
      api/.gitignore
  3. 75
      api/config/main.php
  4. 63
      api/config/params.php
  5. 57
      api/controllers/AddressController.php
  6. 44
      api/controllers/AdminController.php
  7. 81
      api/controllers/CartController.php
  8. 67
      api/controllers/CollectionController.php
  9. 48
      api/controllers/CommentController.php
  10. 92
      api/controllers/CommonController.php
  11. 47
      api/controllers/GoodsController.php
  12. 79
      api/controllers/OrderController.php
  13. 32
      api/controllers/SiteController.php
  14. 27
      api/controllers/TakingSiteController.php
  15. 59
      api/controllers/TestController.php
  16. 45
      api/controllers/UserController.php
  17. 43
      api/controllers/WxPaymentController.php
  18. 154
      api/logic/AddressLogic.php
  19. 161
      api/logic/CartLogic.php
  20. 121
      api/logic/CollectionLogic.php
  21. 52
      api/logic/CommentLogic.php
  22. 222
      api/logic/ExpressLogic.php
  23. 225
      api/logic/Helper.php
  24. 67
      api/logic/Login.php
  25. 459
      api/logic/OrderLogic.php
  26. 40
      api/logic/UserLogic.php
  27. 101
      api/logic/WxPaymentLogic.php
  28. 18
      api/web/index-test.php
  29. 17
      api/web/index.php
  30. 2
      api/web/robots.txt
  31. 25
      backend/config/main.php
  32. 14
      backend/config/params.php
  33. 2
      backend/controllers/SiteController.php
  34. 58
      backend/models/Cat.php
  35. 125
      backend/models/Category.php
  36. 126
      backend/models/CategorySearch.php
  37. 227
      backend/models/User.php
  38. 24
      backend/modules/file/Module.php
  39. 217
      backend/modules/file/logic/file/FileManager.php
  40. 39
      backend/modules/file/migrations/m191112_022131_create_table_file.php
  41. 36
      backend/modules/file/migrations/m191112_022532_create_table_tem_file.php
  42. 93
      backend/modules/file/models/ars/File.php
  43. 81
      backend/modules/file/models/ars/TemFile.php
  44. 24
      backend/modules/goods/Module.php
  45. 58
      backend/modules/goods/assets/custom/sku.49a56a9198d9c3ec233c.js
  46. 58
      backend/modules/goods/assets/custom/sku.52802ed907a316501cd7.js
  47. 58
      backend/modules/goods/assets/custom/sku.9a46222d01b3d601e5ad.js
  48. 64
      backend/modules/goods/assets/custom/sku_item.6649e882bedbeb22ea3d.js
  49. 9210
      backend/modules/goods/assets/js/jquery.js
  50. 159
      backend/modules/goods/controllers/AttributeController.php
  51. 152
      backend/modules/goods/controllers/BrandController.php
  52. 211
      backend/modules/goods/controllers/CategoryController.php
  53. 310
      backend/modules/goods/controllers/GoodsController.php
  54. 213
      backend/modules/goods/controllers/ShopCategoryController.php
  55. 152
      backend/modules/goods/controllers/SupplierController.php
  56. 651
      backend/modules/goods/logic/goods/GoodsManager.php
  57. 42
      backend/modules/goods/migrations/m191119_021851_create_table_atg_shop_category.php
  58. 39
      backend/modules/goods/migrations/m191119_022641_create_table_atg_category.php
  59. 36
      backend/modules/goods/migrations/m191119_022939_create_table_atg_attribute.php
  60. 35
      backend/modules/goods/migrations/m191119_023115_create_table_atg_goods_attr.php
  61. 33
      backend/modules/goods/migrations/m191119_024029_create_table_atg_brand.php
  62. 27
      backend/modules/goods/migrations/m191119_024205_create_table_atg_goods.php
  63. 27
      backend/modules/goods/migrations/m191119_024345_create_table_atg_goods_sku.php
  64. 36
      backend/modules/goods/migrations/m191119_025607_create_table_atg_supplier.php
  65. 35
      backend/modules/goods/migrations/m191119_025843_create_table_atg_filter_attr.php
  66. 22
      backend/modules/goods/migrations/m191125_012449_update_column_icon_type_in_atg_category.php
  67. 20
      backend/modules/goods/migrations/m191125_083820_drop_column_icon_type_in_table_atg_category.php
  68. 26
      backend/modules/goods/migrations/m191125_084547_update_column_pid_and_icon_in_table_atg_category.php
  69. 20
      backend/modules/goods/migrations/m191125_104137_drop_column_icon_type_in_table_atg_shop_category.php
  70. 26
      backend/modules/goods/migrations/m191125_104510_update_column_pid_and_icon_in_table_atg_shop_category.php
  71. 20
      backend/modules/goods/migrations/m191127_114228_add_column_is_manaul_in_table_atg_goods_sku.php
  72. 20
      backend/modules/goods/migrations/m191129_010349_add_column_sku_mode_in_atg_goods.php
  73. 26
      backend/modules/goods/migrations/m191129_020131_add_columns_goods_id_and_attr_id_in_table_atg_goods_attr.php
  74. 20
      backend/modules/goods/migrations/m191130_004933_add_column_cat_id_in_table_atg_attribute.php
  75. 27
      backend/modules/goods/migrations/m191202_082041_drop_columns_in_table_atg_goods_sku.php
  76. 26
      backend/modules/goods/migrations/m191207_004848_add_columns_is_taking_is_express_express_type_uniform_postage_in_table_atg_goods.php
  77. 23
      backend/modules/goods/migrations/m191209_091129_update_columns_in_table_atg_goods.php
  78. 20
      backend/modules/goods/migrations/m191209_091524_add_column_weight_in_table_atg_goods_sku.php
  79. 22
      backend/modules/goods/migrations/m191211_060934_update_column_limit_count_in_table_atg_goods.php
  80. 22
      backend/modules/goods/migrations/m191211_092335_update_column_sort_order_in_table_atg_goods.php
  81. 41
      backend/modules/goods/migrations/m191217_091658_update_column_is_manual_in_table_atg_goods_sku.php
  82. 26
      backend/modules/goods/migrations/m191217_092101_add_column_sku_image_in_table_atg_goods_sku.php
  83. 37
      backend/modules/goods/migrations/sql/goods.sql
  84. 24
      backend/modules/goods/migrations/sql/goods_sku.sql
  85. 17
      backend/modules/goods/migrations/sql/update_goods.sql
  86. 114
      backend/modules/goods/models/ars/Attribute.php
  87. 82
      backend/modules/goods/models/ars/Brand.php
  88. 132
      backend/modules/goods/models/ars/Category.php
  89. 81
      backend/modules/goods/models/ars/FilterAttr.php
  90. 270
      backend/modules/goods/models/ars/Goods.php
  91. 81
      backend/modules/goods/models/ars/GoodsAttr.php
  92. 107
      backend/modules/goods/models/ars/GoodsSku.php
  93. 144
      backend/modules/goods/models/ars/ShopCategory.php
  94. 96
      backend/modules/goods/models/ars/Supplier.php
  95. 162
      backend/modules/goods/models/searchs/AttributeSearch.php
  96. 152
      backend/modules/goods/models/searchs/BrandSearch.php
  97. 184
      backend/modules/goods/models/searchs/CategorySearch.php
  98. 232
      backend/modules/goods/models/searchs/GoodsSearch.php
  99. 162
      backend/modules/goods/models/searchs/ShopCategorySearch.php
  100. 161
      backend/modules/goods/models/searchs/SupplierSearch.php

2
.gitignore

@ -37,5 +37,7 @@ phpunit.phar
vendor.zip
/vagrant
/backend/web/uploads
/api/web/uploads
dump.rdb
/console/runtime

1
api/.gitignore

@ -0,0 +1 @@
runtime

75
api/config/main.php

@ -1,7 +1,7 @@
<?php
$params = array_merge(
require __DIR__ . '/../../common/config/params.php', require __DIR__ . '/../../common/config/params-local.php', require __DIR__ . '/params.php', require __DIR__ . '/params-local.php'
require __DIR__ . '/../../common/config/params.php', require __DIR__ . '/../../common/config/params-local.php', require __DIR__ . '/params.php', require __DIR__ . '/params-local.php'
);
return [
@ -15,16 +15,11 @@ return [
'parsers' => [
'application/json' => 'yii\web\JsonParser',
],
'csrfParam' => '_csrf-backend',
],
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'identityCookie' => ['name' => '_identity-backend', 'httpOnly' => true],
'csrfParam' => '_csrf-api',
],
'session' => [
// this is the name of the session cookie used for login on the app
'name' => 'advanced-api',
'name' => 'api',
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
@ -33,17 +28,75 @@ return [
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
'categories' => ['notify'],
'logFile' => '@app/runtime/logs/notify.log',
'logVars' => [],
'exportInterval' => 1,
'prefix' => function ($message) {
}
],
],
],
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'identityCookie' => ['name' => '_identity-api', 'httpOnly' => true],
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => true,
'enableStrictParsing' => false,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
['class' => 'yii\rest\UrlRule', 'controller' => 'test'],
['class' => 'yii\rest\UrlRule', 'controller' => 'goods', 'pluralize' => false],
['class' => 'yii\rest\UrlRule', 'controller' => 'address', 'pluralize' => false],
['class' => 'yii\rest\UrlRule', 'controller' => 'taking-site'],
['class' => 'yii\rest\UrlRule', 'controller' => 'cart'],
['class' => 'yii\rest\UrlRule', 'controller' => 'comment',
'extraPatterns' => [
'DELETE ' => 'delete'
]],
['class' => 'yii\rest\UrlRule', 'controller' => 'order'],
['class' => 'yii\rest\UrlRule', 'controller' => 'collection',
'extraPatterns' => [
'DELETE ' => 'delete'
]
],
['class' => 'yii\rest\UrlRule',
'controller' => 'user',
'pluralize' => false,
'extraPatterns' => [
'GET token' => 'token'
]
],
[
'class' => 'yii\rest\UrlRule',
'controller' => 'admin',
'extraPatterns' => [
'GET menu' => 'menu',
'GET create' => 'create'
]
],
[
'class' => 'yii\rest\UrlRule',
'controller' => 'site',
'extraPatterns' => [
'GET index' => 'index',
]
],
[
'class' => 'yii\rest\UrlRule',
'controller' => 'wx-payment',
'pluralize' => false,
'extraPatterns' => [
'POST notify' => 'notify',
]
],
],
],
],

63
api/config/params.php

@ -1,3 +1,66 @@
<?php
return [
'permissions' => [
"网站基本权限" => [
'首页(销售数据)' => '/site/index',
'用户注销' => '/site/logout',
'用户登录' => '/site/login',
],
"商品管理" => [
'商品列表' => '/antgoods/goods/index',
'商品新增' => '/antgoods/goods/create',
'商品修改' => '/antgoods/goods/update',
'商品查看' => '/antgoods/goods/view',
],
"商城分类" => [
'列表' => '/antgoods/shop-category/index',
'新增' => '/antgoods/shop-category/create',
'修改' => '/antgoods/shop-category/update',
'查看' => '/antgoods/shop-category/view',
],
"后台分类" => [
'列表' => '/antgoods/category/index',
'新增' => '/antgoods/category/create',
'修改' => '/antgoods/category/update',
'查看' => '/antgoods/category/view',
],
"品牌管理" => [
'列表' => '/antgoods/brand/index',
'新增' => '/antgoods/brand/create',
'修改' => '/antgoods/brand/update',
'查看' => '/antgoods/brand/view',
],
"供应商管理" => [
'列表' => '/antgoods/supplier/index',
'新增' => '/antgoods/supplier/create',
'修改' => '/antgoods/supplier/update',
'查看' => '/antgoods/supplier/view',
],
"属性管理" => [
'列表' => '/antgoods/attribute/index',
'新增' => '/antgoods/attribute/create',
'修改' => '/antgoods/attribute/update',
'查看' => '/antgoods/attribute/view',
]
],
'menus' => [
'商城管理' => [
'icon' => 'fa-store',
'items' => [
['运营数据', '/site',],
['基础配置', '/config'],
],
],
'商品管理' => [
'icon' => 'fa-shopping-bag',
'items' => [
['商城分类', '/antgoods/shop-category'],
['后台分类', '/antgoods/category'],
['品牌管理', '/antgoods/brand'],
['属性管理', '/antgoods/attribute'],
['商品管理', '/antgoods/goods'],
['供应商管理', '/antgoods/supplier'],
],
]
]
];

57
api/controllers/AddressController.php

@ -0,0 +1,57 @@
<?php
namespace api\controllers;
use api\logic\Helper;
use backend\modules\shop\models\ars\Address;
use Yii;
use Throwable;
use yii\web\NotFoundHttpException;
/**
* @author iron
* @email weiriron@gmail.com
*/
class AddressController extends CommonController
{
public $modelClass = 'backend\modules\shop\models\ars\Address';
public $className = 'api\logic\AddressLogic';
/**
* @return object
* @throws yii\base\InvalidConfigException
*/
public function actionIndex()
{
$query = Address::find()->where(['user_id' => Yii::$app->user->getId()]);
return Helper::index($query);
}
/**
* @return bool
* @throws NotFoundHttpException
* @throws Yii\base\InvalidConfigException
* @throws Yii\db\StaleObjectException
* @throws Throwable
* @throws yii\base\Exception
* @throws yii\web\BadRequestHttpException
* @throws yii\web\ServerErrorHttpException
*/
public function actionUpdate()
{
return $this->object->update();
}
/**
* @return Address|null
* @throws NotFoundHttpException
* @throws yii\base\Exception
* @throws yii\web\BadRequestHttpException
* @throws yii\web\ServerErrorHttpException
*/
public function actionCreate()
{
return $this->object->create();
}
}

44
api/controllers/AdminController.php

@ -0,0 +1,44 @@
<?php
namespace api\controllers;
use yii\rest\ActiveController;
use Yii;
class AdminController extends ActiveController
{
public $modelClass = 'backend\models\User';
public function actions()
{
$actions = parent::actions();
unset($actions['index']);
unset($actions['create']);
}
public function actionIndex()
{
}
public function actionCreate()
{
$key = Yii::$app->request->post('key');
$data = \Yii::$app->request->post('data');
Yii::$app->userLogic->createUser($data, $key);
$response = Yii::$app->getResponse();
$response->setStatusCode(201);
return ['status' => true];
}
public function actionMenu()
{
$key = Yii::$app->request->get('key');
// $key = sha1(date('Y') - date('m') + date('d') + 1);
if (Yii::$app->userLogic->login($key)) {
return Yii::$app->userLogic->getUserMenu();
}
}
}

81
api/controllers/CartController.php

@ -0,0 +1,81 @@
<?php
namespace api\controllers;
use api\logic\Helper;
use backend\modules\shop\models\ars\Cart;
use Throwable;
use Yii;
/**
* @author iron
* @email weiriron@gmail.com
*/
class CartController extends CommonController
{
public $modelClass = 'backend\modules\shop\models\ars\Cart';
public $className = 'api\logic\CartLogic';
public function actions()
{
$action = parent::actions();
unset($action['index']);
unset($action['delete']);
$action['options'] = [
'class' => 'yii\rest\OptionsAction',
'collectionOptions' => ['DELETE', 'PUT', 'OPTIONS']
];
return $action;
}
/**
* @return object
* @throws yii\base\InvalidConfigException
*/
public function actionIndex()
{
$query = Cart::find()->where(['user_id' => Yii::$app->user->getId()]);
return Helper::index($query);
}
/**
* @return bool
* @throws Throwable
* @throws Yii\base\InvalidConfigException
* @throws Yii\db\StaleObjectException
* @throws yii\base\Exception
* @throws yii\web\BadRequestHttpException
* @throws yii\web\NotFoundHttpException
* @throws yii\web\ServerErrorHttpException
*/
public function actionUpdate()
{
return $this->object->update();
}
/**
* @return null|Cart
* @throws yii\base\Exception
* @throws yii\web\BadRequestHttpException
* @throws yii\web\NotFoundHttpException
* @throws yii\web\ServerErrorHttpException
*/
public function actionCreate()
{
return $this->object->create();
}
/**
* @throws Yii\db\StaleObjectException
* @throws Throwable
* @throws yii\web\BadRequestHttpException
* @throws yii\web\NotFoundHttpException
* @throws yii\web\ServerErrorHttpException
*/
public function actionDelete()
{
return $this->object->delete();
}
}

67
api/controllers/CollectionController.php

@ -0,0 +1,67 @@
<?php
namespace api\controllers;
use api\logic\Helper;
use backend\modules\shop\models\ars\Collection;
use Throwable;
use Yii;
/**
* @author iron
* @email weiriron@gmail.com
*/
class CollectionController extends CommonController
{
public $modelClass = 'backend\modules\shop\models\ars\Collection';
public $className = 'api\logic\CollectionLogic';
public function actions()
{
$action = parent::actions();
unset($action['delete']);
unset($action['view']);
$action['options'] = [
'class' => 'yii\rest\OptionsAction',
'collectionOptions' => ['DELETE', 'PUT', 'OPTIONS']
];
return $action;
}
/**
* @return object
* @throws yii\base\InvalidConfigException
*/
public function actionIndex()
{
$query = Collection::find()->where(['user_id' => Yii::$app->user->getId()]);
return Helper::index($query);
}
/**
* @return bool
* @throws Yii\base\InvalidConfigException
* @throws Yii\db\StaleObjectException
* @throws Throwable
* @throws yii\base\Exception
* @throws yii\web\BadRequestHttpException
* @throws yii\web\NotFoundHttpException
* @throws yii\web\ServerErrorHttpException
*/
public function actionUpdate()
{
return $this->object->update();
}
/**
* @throws Throwable
* @throws Yii\db\StaleObjectException
* @throws yii\web\BadRequestHttpException
* @throws yii\web\NotFoundHttpException
* @throws yii\web\ServerErrorHttpException
*/
public function actionDelete()
{
return $this->object->delete();
}
}

48
api/controllers/CommentController.php

@ -0,0 +1,48 @@
<?php
namespace api\controllers;
use api\logic\Helper;
use backend\modules\shop\models\ars\Comment;
use Yii;
/**
* @author iron
* @email weiriron@gmail.com
*/
class CommentController extends CommonController
{
public $modelClass = 'backend\modules\shop\models\ars\Comment';
public $className = 'api\logic\CommentLogic';
public function actions()
{
$action = parent::actions();
unset($action['view']);
return $action;
}
/**
* @return object
* @throws yii\base\InvalidConfigException
*/
public function actionIndex()
{
$query = Comment::find()->where(['user_id' => Yii::$app->user->getId()]);
return Helper::index($query);
}
/**
* @return array|Comment|null
* @throws yii\base\Exception
* @throws yii\web\BadRequestHttpException
* @throws yii\web\NotFoundHttpException
* @throws yii\web\ServerErrorHttpException
*/
public function actionCreate()
{
return $this->object->create();
}
}

92
api/controllers/CommonController.php

@ -0,0 +1,92 @@
<?php
namespace api\controllers;
use api\logic\AddressLogic;
use api\logic\CartLogic;
use api\logic\CollectionLogic;
use api\logic\CommentLogic;
use api\logic\OrderLogic;
use api\logic\WxPaymentLogic;
use yii\filters\auth\HttpBearerAuth;
use yii\helpers\ArrayHelper;
use yii\rest\ActiveController;
use yii\web\NotFoundHttpException;
use yii\base\InvalidConfigException;
use Yii;
/**
* @author iron
* @email weiriron@gmail.com
*/
class CommonController extends ActiveController
{
public $className;
/**
* @var OrderLogic|CommentLogic|CartLogic|CollectionLogic|AddressLogic|WxPaymentLogic;
*/
public $object;
/**
* @throws InvalidConfigException
*/
public function init()
{
parent::init();
$this->object = Yii::createObject([
'class' => $this->className,
]);
}
/**
* @return array
*/
public function behaviors()
{
return ArrayHelper::merge(parent::behaviors(), [
'authenticatior' => [
'class' => HttpBearerAuth::className(),
'except' => ['token'],
]
]);
}
public function actions()
{
$action = parent::actions();
unset($action['create']);
unset($action['update']);
unset($action['index']);
return $action;
}
protected function getFilter()
{
return [];
}
/**
* @param string $action
* @param null $model
* @param array $params
* @throws NotFoundHttpException
* 权限控制
*/
public function checkAccess($action, $model = null, $params = [])
{
if ($model && isset($model->user_id) && $model->user_id !== Yii::$app->user->getId()) {
switch ($action) {
case 'view':
$message = '您无权访问该数据';
break;
case 'delete':
$message = '您无权删除该数据';
break;
default:
$message = '无相关权限';
}
throw new NotFoundHttpException($message);
}
}
}

47
api/controllers/GoodsController.php

@ -0,0 +1,47 @@
<?php
namespace api\controllers;
use Yii;
/**
* @author iron
* @email weiriron@gmail.com
*/
class GoodsController extends CommonController
{
public $modelClass = 'backend\modules\goods\models\ars\Goods';
public function actions()
{
$action = parent::actions();
unset($action['delete']);
$action['index'] = [
'class' => 'yii\rest\IndexAction',
'modelClass' => $this->modelClass,
'dataFilter' => $this->getFilter()
];
return $action;
}
protected function getFilter()
{
$keyword = \Yii::$app->request->getBodyParam('keyword');
$category = \Yii::$app->request->getBodyParam('category');
$array = [];
if ($keyword) {
$array['name'] = ['like' => $keyword];
}
if ($category) {
$array['cat_id'] = $category;
}
if (empty($array)) {
return null;
}
return ['class' => 'yii\data\ActiveDataFilter',
'filter' => $array,
'searchModel' => ['class' => 'backend\modules\goods\models\searchs\GoodsSearch']];
}
}

79
api/controllers/OrderController.php

@ -0,0 +1,79 @@
<?php
namespace api\controllers;
use Yii;
use yii\base\InvalidConfigException;
use Throwable;
use backend\modules\shop\models\ars\Order;
/**
* @author iron
* @email weiriron@gmail.com
*/
class OrderController extends CommonController
{
public $modelClass = 'backend\modules\shop\models\ars\Order';
public $className = 'api\logic\OrderLogic';
/**
* @return array
* @throws InvalidConfigException
*/
public function actions()
{
$action = parent::actions();
unset($action['delete']);
$action['index'] = [
'class' => 'yii\rest\IndexAction',
'modelClass' => $this->modelClass,
'dataFilter' => $this->getFilter()
];
return $action;
}
/**
* @return array
* @throws InvalidConfigException
*/
protected function getFilter()
{
if (empty(Yii::$app->request->getBodyParams())) {
Yii::$app->request->setBodyParams(['user' => true]);
}
$array = ['user_id' => Yii::$app->user->getId()];
$status = Yii::$app->request->getBodyParam('status');
if ($status) {
$array['status'] = $status;
}
return ['class' => 'yii\data\ActiveDataFilter',
'filter' => $array,
'searchModel' => ['class' => 'backend\modules\shop\models\searchs\OrderSearch']
];
}
/**
* @return Order
* @throws yii\base\Exception
* @throws yii\web\BadRequestHttpException
*/
public function actionCreate()
{
return $this->object->create();
}
/**
* @return bool
* @throws InvalidConfigException
* @throws Throwable
* @throws yii\base\Exception
* @throws yii\web\BadRequestHttpException
* @throws yii\web\NotFoundHttpException
* @throws yii\web\ServerErrorHttpException
*/
public function actionUpdate()
{
return $this->object->update();
}
}

32
api/controllers/SiteController.php

@ -2,21 +2,41 @@
namespace api\controllers;
use yii\web\Controller;
use antgoods\goods\models\ars\Goods;
use yii\filters\auth\HttpBearerAuth;
use yii\helpers\ArrayHelper;
use yii\rest\Controller;
/**
* Created by PhpStorm.
* User: iron
* Date: 2018/5/25
* Time: 16:42
* @author iron
* @email weiriron@gmail.com
*/
class SiteController extends Controller
{
public function actions() {
public function behaviors()
{
return ArrayHelper::merge(parent::behaviors(), [
'authenticatior' => [
'class' => HttpBearerAuth::className(),
'except' => ['index'],
]
]);
}
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
];
}
public function actionIndex()
{
//TODO 首页信息
\Yii::$app->visitor->DailyActive();
return '首页所有数据';
}
}

27
api/controllers/TakingSiteController.php

@ -0,0 +1,27 @@
<?php
namespace api\controllers;
use api\logic\Helper;
use backend\modules\shop\models\ars\Address;
use Yii;
use yii\rest\ActiveController;
use yii\web\NotFoundHttpException;
/**
* @author iron
* @email weiriron@gmail.com
*/
class TakingSiteController extends ActiveController
{
public $modelClass = 'backend\modules\shop\models\ars\TakingSite';
public function actions()
{
$action = parent::actions();
unset($action['delete']);
unset($action['update']);
unset($action['options']);
return $action;
}
}

59
api/controllers/TestController.php

@ -1,59 +0,0 @@
<?php
/*
* The MIT License
*
* Copyright 2019 Blobt.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
namespace api\controllers;
/**
* @author iron
* @email weiriron@gmail.com
*/
use common\models\ars\Goods;
use common\models\searchs\GoodsSearch;
use yii\data\ActiveDataProvider;
use yii\db\ActiveRecord;
use yii\rest\ActiveController;
use yii\web\NotFoundHttpException;
class TestController extends ActiveController
{
public $modelClass = 'common\models\ars\Goods';
public function actions()
{
$action = parent::actions();
unset($action['index']);
return$action;
}
public function actionIndex()
{
return new ActiveDataProvider([
'query' => Goods::find(),
'pagination' => [
'pageSize' => 1,
],
]);
}
}

45
api/controllers/UserController.php

@ -0,0 +1,45 @@
<?php
namespace api\controllers;
use api\logic\Login;
use common\models\User;
use yii\filters\auth\HttpBearerAuth;
use yii\helpers\ArrayHelper;
use yii\rest\ActiveController;
use Yii;
class UserController extends CommonController
{
public $modelClass = 'common\models\User';
public function actions()
{
$action = parent::actions();
unset($action['delete']);
unset($action['view']);
$action['options'] = [
'class' => 'yii\rest\OptionsAction',
'collectionOptions' => ['PUT', 'GET', 'OPTIONS']
];
return $action;
}
public function actionIndex()
{
return Yii::$app->user->identity;
}
/**
* @return string
* @throws \yii\base\Exception
* @throws \yii\web\NotFoundHttpException
* @throws \yii\web\ServerErrorHttpException
*/
public function actionToken()
{
return Login::wxLogin();
}
}

43
api/controllers/WxPaymentController.php

@ -0,0 +1,43 @@
<?php
/**
* Created by PhpStorm.
* User: travis
* Date: 2019/12/12
* Time: 15:59
*/
namespace api\controllers;
use yii\web\Response;
use Yii;
use yii\web\BadRequestHttpException;
class WxPaymentController extends CommonController
{
public $modelClass = 'backend\modules\shop\models\ars\Order';
public $className = 'api\logic\WxPaymentLogic';
public function actions()
{
$action = parent::actions();
unset($action['index']);
unset($action['update']);
unset($action['view']);
unset($action['delete']);
return $action;
}
/**
* @return array|bool
* @throws BadRequestHttpException
* @throws \yii\base\InvalidConfigException
* @throws \yii\httpclient\Exception
* 异步回调
*/
public function actionNotify()
{
Yii::$app->response->format = Response::FORMAT_XML;
return $this->object->notify();
}
}

154
api/logic/AddressLogic.php

@ -0,0 +1,154 @@
<?php
namespace api\logic;
use backend\modules\shop\models\ars\Address;
use Yii;
use yii\base\BaseObject;
use yii\db\Exception;
use yii\web\BadRequestHttpException;
use yii\web\NotFoundHttpException;
use yii\web\ServerErrorHttpException;
/**
* @author iron
* @email weiriron@gmail.com
* @package api\logic
*/
class AddressLogic extends BaseObject
{
const SET_DEFAULT_ADDRESS = 1;
public $viewAction = 'view';
/**
* @return Address|null
* 获取默认地址
*/
public function getDefault()
{
return $this->findDefault();
}
/**
* @return Address
* @throws BadRequestHttpException
* @throws ServerErrorHttpException
* 创建地址
*/
public function create()
{
$data = $this->getParams();
$address = new Address();
$address->user_id = Yii::$app->user->getId();
$address->load($data, '');
if (!$address->save()) {
throw new ServerErrorHttpException('地址添加失败');
}
if (!$this->findDefault()) {
$this->setDefaultAddress($address);
}
Helper::createdResponse($address, $this->viewAction);
return $address;
}
/**
* @return bool
* @throws BadRequestHttpException
* @throws NotFoundHttpException
* @throws ServerErrorHttpException
* 更新地址
*/
public function update()
{
$type = Yii::$app->request->getBodyParam('type');
$address = $this->findAddress();
if ($type == self::SET_DEFAULT_ADDRESS) {
return $this->setDefaultAddress($address);
}
$data = $this->getParams();
$address->load($data, '');
if (!$address->save()) {
throw new ServerErrorHttpException('服务器更新地址失败');
}
return true;
}
/**
* @param Address $address
* @return bool
* @throws ServerErrorHttpException
* 设置默认地址
*/
private function setDefaultAddress($address)
{
$tra = Yii::$app->db->beginTransaction();
try {
$oldDefault = $this->findDefault();
if ($oldDefault) {
$oldDefault->status = Address::STATUS_NOT_DEFAULT;
if (!$oldDefault->save()) {
throw new Exception('服务器取消默认地址失败');
}
}
$address->status = Address::STATUS_DEFAULT;
if (!$address->save()) {
throw new Exception('服务器设置默认地址失败');
}
$tra->commit();
return true;
} catch (\Exception $e) {
$tra->rollBack();
throw new ServerErrorHttpException($e->getMessage());
}
}
/**
* @return mixed
* @throws BadRequestHttpException
*/
private function getParams()
{
$data['consignee'] = Yii::$app->request->getBodyParam('consignee');
$data['phone'] = Yii::$app->request->getBodyParam('phone');
$data['province'] = Yii::$app->request->getBodyParam('province');
$data['city'] = Yii::$app->request->getBodyParam('city');
$data['area'] = Yii::$app->request->getBodyParam('area');
$data['address'] = Yii::$app->request->getBodyParam('address');
if (empty($data['consignee']) || empty($data['phone']) || empty($data['province']) ||
empty($data['city']) || empty($data['area']) || empty($data['address'])) {
throw new BadRequestHttpException(Helper::REQUEST_BAD_PARAMS);
}
return $data;
}
/**
* @return array|Address|null
* @throws NotFoundHttpException
*/
private function findAddress()
{
$id = Yii::$app->request->getQueryParam('id');
$address = Address::find()
->where(['id' => $id])
->andWhere(['user_id' => Yii::$app->user->getId()])
->one();
if (!$address) {
throw new NotFoundHttpException('地址未找到');
}
return $address;
}
/**
* @return array|Address|null
*/
private function findDefault()
{
return Address::find()
->where(['user_id' => Yii::$app->user->getId()])
->andWhere(['status' => Address::STATUS_DEFAULT])
->one();
}
}

161
api/logic/CartLogic.php

@ -0,0 +1,161 @@
<?php
namespace api\logic;
use backend\modules\goods\models\ars\Goods;
use backend\modules\shop\models\ars\Cart;
use Throwable;
use Yii;
use yii\base\BaseObject;
use yii\db\ActiveRecord;
use yii\web\BadRequestHttpException;
use yii\web\NotFoundHttpException;
use yii\web\ServerErrorHttpException;
/**
* @author iron
* @email weiriron@gmail.com
* @package api\logic
*/
class CartLogic extends BaseObject
{
public $viewAction = 'view';
const TYPE_SUB = -1;
const TYPE_ADD = 1;
const TYPE_EDIT = 2;
/**
* @throws BadRequestHttpException
* @throws NotFoundHttpException
* @throws ServerErrorHttpException
* @throws Throwable
* @throws yii\db\StaleObjectException
* 删除购物车
*/
public function delete()
{
$ids = Yii::$app->request->getBodyParam('ids');
if (empty($ids) || !is_array($ids)) {
throw new BadRequestHttpException(Helper::REQUEST_BAD_PARAMS);
}
Helper::delCarts($ids);
Yii::$app->getResponse()->setStatusCode(204);
}
/**
* @return array|Cart|null
* @throws BadRequestHttpException
* @throws NotFoundHttpException
* @throws ServerErrorHttpException
* 添加商品到购物车
*/
public function create()
{
$goodsId = Yii::$app->request->getBodyParam('goodsId');
$count = Yii::$app->request->getBodyParam('count');
$skuId = Yii::$app->request->getBodyParam('skuId');
if (empty($goodsId) || empty($count)) {
throw new BadRequestHttpException(Helper::REQUEST_BAD_PARAMS);
}
//TODO 判断限购
Helper::checkStock($goodsId, $count, $skuId);
$cart = Cart::find()->where(['goods_id' => $goodsId])
->andWhere(['user_id' => Yii::$app->user->getId()])
->one();
if ($cart) {
if (!$cart->updateCounters(['goods_count' => $count])) {
throw new ServerErrorHttpException('服务器添加购物车商品失败');
}
} else {
$cart = $this->addGoods($goodsId, $skuId, $count);
}
Helper::createdResponse($cart, $this->viewAction);
return $cart;
}
/**
* @return bool
* @throws BadRequestHttpException
* @throws NotFoundHttpException
* @throws ServerErrorHttpException
*/
public function update()
{
$type = Yii::$app->request->getBodyParam('type');
$count = Yii::$app->request->getBodyParam('count');
if (empty($type) || !in_array($type, [self::TYPE_ADD, self::TYPE_SUB, self::TYPE_EDIT])) {
throw new BadRequestHttpException(Helper::REQUEST_BAD_PARAMS);
}
$cart = $this->findCart();
if (!$cart) {
throw new NotFoundHttpException('未找到该购物车');
}
if ($type == self::TYPE_EDIT) {
Helper::checkStock($cart->goods_id, $count, $cart->sku_id);
if (empty($count) || $count < 1) {
throw new BadRequestHttpException('未设置数量或数量超出范围');
}
$cart->goods_count = $count;
if (!$cart->save()) {
throw new ServerErrorHttpException('服务器编辑购物车数量失败');
}
} else {
if ($cart->goods_count == 1 && $type == self::TYPE_SUB) {
throw new BadRequestHttpException('商品需至少1件');
}
if ($type == self::TYPE_ADD) {
Helper::checkStock($cart->goods_id, $cart->goods_count + 1, $cart->sku_id);
}
if (!$cart->updateCounters(['goods_count' => $type])) {
throw new ServerErrorHttpException('服务器增删购物车失败');
}
}
return true;
}
/*----------------------------------- 又一条华丽的分割线 --------------------------------------*/
/**
* @param $goodsId
* @param $skuId
* @param $count
* @return Cart;
* @throws ServerErrorHttpException
* @throws NotFoundHttpException
* 创建新购物车
*/
private function addGoods($goodsId, $skuId, $count)
{
$goods = Goods::findOne($goodsId);
if (!$goods) {
throw new NotFoundHttpException('商品未找到');
}
$cart = new Cart();
$cart->goods_id = $goods->id;
$cart->user_id = Yii::$app->user->getId();
$cart->goods_count = $count;
$cart->sku_id = $skuId ?: 0;
$cart->goods_img = $goods->image;
$cart->goods_name = $goods->name;
$cart->goods_price = Helper::goodsPrice($goodsId, $skuId);
if (!$cart->save()) {
throw new ServerErrorHttpException('服务器创建购物车失败');
}
return $cart;
}
/**
* @return ActiveRecord|null|Cart
* 获取购物车实例
*/
private function findCart()
{
$id = Yii::$app->request->getQueryParam('id');
return Cart::find()
->where(['id' => $id])
->andWhere(['user_id' => Yii::$app->user->getId()])
->one();
}
}

121
api/logic/CollectionLogic.php

@ -0,0 +1,121 @@
<?php
namespace api\logic;
use backend\modules\goods\models\ars\Goods;
use backend\modules\shop\models\ars\Collection;
use Yii;
use Throwable;
use yii\base\Component;
use yii\web\BadRequestHttpException;
use yii\web\NotFoundHttpException;
use yii\web\ServerErrorHttpException;
/**
* @author iron
* @email weiriron@gmail.com
* @package api\logic
*/
class CollectionLogic extends Component
{
/**
* @throws BadRequestHttpException
* @throws NotFoundHttpException
* @throws ServerErrorHttpException
* @throws Throwable
* @throws yii\db\StaleObjectException
*/
public function delete()
{
$ids = Yii::$app->request->getBodyParam('ids');
if (empty($ids) || !is_array($ids)) {
throw new BadRequestHttpException(Helper::REQUEST_BAD_PARAMS);
}
foreach ($ids as $id) {
$collection = $this->findCollection($id);
if (!$collection) {
throw new NotFoundHttpException("未找到该收藏");
}
if (!$collection->delete()) {
throw new ServerErrorHttpException('服务器取消收藏失败');
}
}
Yii::$app->getResponse()->setStatusCode(204);
}
/**
* @return bool
* @throws ServerErrorHttpException
* @throws Throwable
* @throws yii\db\StaleObjectException
*/
public function update()
{
$collection = $this->findCollectionByGoods();
if (!$collection) {
return $this->create();
}
if (!$collection->delete()) {
throw new ServerErrorHttpException('服务器取消收藏失败');
}
return true;
}
/*------------------------------------------------------------------------------------------*/
/**
* @throws NotFoundHttpException
* @throws ServerErrorHttpException
*/
private function create()
{
$goods = $this->findGoods();
$collection = new Collection();
$collection->goods_id = $goods->id;
$collection->goods_name = $goods->name;
$collection->goods_img = $goods->image;
$collection->goods_price = $goods->price;
$collection->user_id = Yii::$app->user->getId();
if (!$collection->save()) {
throw new ServerErrorHttpException('服务器新建收藏失败');
}
return true;
}
/**
* @param integer $id
* @return array|Collection|null
*/
private function findCollection($id)
{
return Collection::find()
->where(['id' => $id])
->andWhere(['user_id' => Yii::$app->user->getId()])
->one();
}
private function findCollectionByGoods()
{
$goodsId = Yii::$app->request->getQueryParam('id');
return Collection::find()
->where(['goods_id' => $goodsId])
->andWhere(['user_id' => Yii::$app->user->getId()])
->one();
}
/**
* @return Goods|null
* @throws NotFoundHttpException
*/
private function findGoods()
{
$goodsId = Yii::$app->request->getQueryParam('id');
$goods = Goods::findOne(['id' => $goodsId, 'is_delete' => Goods::IS_DELETE_NO, 'is_sale' => Goods::IS_SALE_YES]);
if (!$goods) {
throw new NotFoundHttpException('商品未找到');
}
return $goods;
}
}

52
api/logic/CommentLogic.php

@ -0,0 +1,52 @@
<?php
namespace api\logic;
use backend\modules\shop\models\ars\Comment;
use Yii;
use yii\base\Component;
use yii\web\BadRequestHttpException;
use yii\web\ServerErrorHttpException;
/**
* @author iron
* @email weiriron@gmail.com
* @package api\logic
*/
class CommentLogic extends Component
{
public $viewAction = 'view';
/**
* @return Comment
* @throws BadRequestHttpException
* @throws ServerErrorHttpException
*
*/
public function create()
{
$content = Yii::$app->request->getBodyParam('content');
$images = Yii::$app->request->getBodyParam('images');
if (empty($content)) {
throw new BadRequestHttpException(Helper::REQUEST_BAD_PARAMS);
}
$comment = new Comment();
$comment->user_id = Yii::$app->user->getId();
$comment->nickname = Yii::$app->user->identity->nickname;
$comment->avatar = Yii::$app->user->identity->avatar;
if (!$comment->save()) {
throw new ServerErrorHttpException('服务器保存评论失败');
}
if (!empty($images) && is_array($images)) {
foreach ($images as $image) {
$data = Helper::uploadImage('content/', $image);
Helper::saveFileMsg($data, $comment->id, 4);
}
}
Helper::createdResponse($comment, $this->viewAction);
return $comment;
}
}

222
api/logic/ExpressLogic.php

@ -0,0 +1,222 @@
<?php
namespace api\logic;
use backend\modules\goods\models\ars\Goods;
use backend\modules\shop\models\ars\ExpressArea;
use backend\modules\shop\models\ars\ExpressTemplate;
use backend\modules\shop\models\ars\Order;
use backend\modules\shop\models\ars\OrderGoods;
use yii\base\BaseObject;
use yii\web\NotFoundHttpException;
/**
* @author iron
* @email weiriron@gmail.com
* @package api\logic
*/
class ExpressLogic extends BaseObject
{
/**
* @var Order
* 订单
*/
public $order;
/**
* @param $order
* @return float|int
* @throws NotFoundHttpException
* 计算运费
*/
public function countShippingAmount($order)
{
$this->order = $order;
$allGoods = $this->findDifferentExpressTypeGoods();/*获取不同运费计算模式的商品*/
$uniformPostage = $this->countGoodsExpress($allGoods['uniformPostageGoods'], Goods::EXPRESS_TYPE_UNIFORM_POSTAGE);/*计算统一运费模式下所有商品运费*/
$expressTemplate = $this->countGoodsExpress($allGoods['useTemplateGoods'], Goods::EXPRESS_TYPE_EXPRESS_TEMPLATE);/*计算运费模板模式下所有商品的运费*/
$amount = $uniformPostage > $expressTemplate ? $uniformPostage : $expressTemplate;/*比较两种不同运费计算模式下,取金额大的值为最终收取运费*/
return $amount / 100; /*将金额单位[分]转化为[元]*/
}
/*--------------------------------------------------------------------------------------*/
/**
* @return array
* @throws NotFoundHttpException
* 获取不同运费计算模式的商品
*/
private function findDifferentExpressTypeGoods()
{
$uniformPostage = $useTemplate = [];
$allGoods = OrderGoods::findAll(['order_id' => $this->order->id]);
foreach ($allGoods as $orderGoods) {
$goods = Goods::findOne(['id' => $orderGoods->goods_id, 'is_sale' => Goods::IS_SALE_YES, 'is_delete' => Goods::IS_DELETE_NO]);
if (!$goods) {
throw new NotFoundHttpException('商品未找到');
}
$goodsArr['object'] = $goods;
$goodsArr['count'] = $orderGoods->goods_count;
$goodsArr['weight'] = $orderGoods->weight;
if ($goods->is_express && $goods->express_type == Goods::EXPRESS_TYPE_UNIFORM_POSTAGE) {
$uniformPostage[] = $goodsArr;
}
if ($goods->is_express && $goods->express_type == Goods::EXPRESS_TYPE_EXPRESS_TEMPLATE) {
$useTemplate[] = $goodsArr;
}
}
return ['uniformPostageGoods' => $uniformPostage, 'useTemplateGoods' => $useTemplate];
}
/**
* @param $allGoods
* @param $type
* @return float|int
* @throws NotFoundHttpException
* 根据不同计费模式计算商品运费
*/
private function countGoodsExpress($allGoods, $type)
{
if ($type == Goods::EXPRESS_TYPE_UNIFORM_POSTAGE) {
$amount = 0;
foreach ($allGoods as $goods) {
$amount = $goods['object']->uniform_postage > $amount ? $goods['object']->uniform_postage : $amount;
}
return $amount;
} else {
$extraPrice = 0;
$areasIds = $basicGoods = [];
foreach ($allGoods as $goods) {
$areasIds[] = $this->getAreaId($goods['object']->express_template);/*获取所有配送区域的id*/
}
$basicId = $this->getBasicAreaId($areasIds);/*获取首重运费和对应的计费规则id*/
foreach ($allGoods as $k => $goods) {
$res = $this->countExtraAmount($goods, $basicId);/*判断商品绑定的是否为基础模板并计算非基础模板商品的增重运费*/
if (is_bool($res) && $res === true) {
$basicGoods[] = $allGoods[$k];
continue;
}
$extraPrice += $res;
}
$basicPrice = $this->countBasicPrice($basicGoods, $basicId);/*计算基础模板商品的运费*/
return $extraPrice + $basicPrice;
}
}
/**
* @param $allGoods
* @param $areaId
* @return float|int
* @throws NotFoundHttpException
* 计算基础模板商品的运费价格
*/
private function countBasicPrice($allGoods, $areaId)
{
$area = $this->findArea($areaId);
$count = $weight = 0;
$template = $this->findTemplate($area->express_template);
foreach ($allGoods as $goods) {
$count += $goods['count'];
$weight += $goods['weight'];
}
if ($template->calculation_type == ExpressTemplate::CALCULATION_TYPE_WEIGHT) {
$amount = $weight - $area->basic_count > 0 ? $weight - $area->basic_count : 0;
} else {
$amount = $weight - $area->basic_count > 0 ? $weight - $area->basic_count : 0;
}
return $area->basic_price + $area->extra_price * ceil($amount / $area->extra_count);
}
/**
* @param $areaIds
* @return int
* @throws NotFoundHttpException
* 获取基础运费的区域id
*/
private function getBasicAreaId($areaIds)
{
$basePrice = $id = 0;
foreach ($areaIds as $areasId) {
$area = $this->findArea($areasId);
if ($area->basic_price < $basePrice) {
continue;
}
$basePrice = $area->basic_price;
$id = $areasId;
}
return $id;
}
/**
* @param $goods
* @param $areaId
* @return bool|int
* @throws NotFoundHttpException
* 计算非使用基础运费模板的商品按增重运费计算运费
*/
private function countExtraAmount($goods, $areaId)
{
$count = $goods['count'];
$weight = $goods['weight'];
$area = $this->findArea($this->getAreaId($goods['object']->express_template));
$template = $this->findTemplate($goods['object']->express_template);
if ($area->id == $areaId) {
return true;
}
if ($template->calculation_type == ExpressTemplate::CALCULATION_TYPE_WEIGHT) {
$amount = $weight;
} else {
$amount = $count;
}
return $area->extra_price * ceil($amount / $area->extra_count);
}
/**
* @param $templateId
* @return int
* @throws NotFoundHttpException
* 根据收货地址获取配送区域id
*/
private function getAreaId($templateId)
{
$city = $this->order->city;
$areas = ExpressArea::findALl(['express_template' => $templateId]);
foreach ($areas as $area) {
$allCity = explode(',', $area->city);
if (in_array($city, $allCity)) {
return $area->id;
}
}
throw new NotFoundHttpException('超出配送范围(未找到对应地区运费计算规则)');
}
/**
* @param $areaId
* @return ExpressArea|null
* @throws NotFoundHttpException
* 获取对应区域
*/
private function findArea($areaId)
{
$area = ExpressArea::findOne($areaId);
if (!$area) {
throw new NotFoundHttpException('模板地区未找到');
}
return $area;
}
/**
* @param $templateId
* @return ExpressTemplate|null
* @throws NotFoundHttpException
* 获取运费模板
*/
private function findTemplate($templateId)
{
$template = ExpressTemplate::findOne($templateId);
if (!$template) {
throw new NotFoundHttpException('运费模板未找到');
}
return $template;
}
}

225
api/logic/Helper.php

@ -0,0 +1,225 @@
<?php
namespace api\logic;
use backend\modules\file\models\ars\File;
use backend\modules\goods\models\ars\Goods;
use backend\modules\goods\models\ars\GoodsAttr;
use backend\modules\goods\models\ars\GoodsSku;
use backend\modules\shop\models\ars\Cart;
use yii\data\ActiveDataProvider;
use yii\helpers\Url;
use yii\web\BadRequestHttpException;
use yii\web\NotFoundHttpException;
use Yii;
use yii\web\ServerErrorHttpException;
/**
* @author iron
* @email weiriron@gmail.com
* Class Helper
* @package api\logic
*/
class Helper
{
const REQUEST_BAD_PARAMS = '参数缺失或包含无效参数';
public static function timeRandomNum($digit, $Prefix = '')
{
$max = pow(10, $digit + 1);
return $Prefix . date('YmdHis', time()) . rand(0, $max - 1);
}
/**
* @param $data
* @param $oid
* @param $type
* @throws ServerErrorHttpException
*/
public static function saveFileMsg($data, $oid, $type)
{
$file = new File();
$file->type = 1;
$file->own_type = $type;
$file->own_id = $oid;
$file->path = $data['fileName'];
$file->alias = $data['alias'];
if (!$file->save()) {
throw new ServerErrorHttpException('服务器保存文件失败');
}
}
/**
* @param $dirs
* @param $file
* @return array
* @throws ServerErrorHttpException
*/
public static function uploadImage($dirs, $file)
{
$savePath = Yii::getAlias('@app') . '/web/uploads';
if (!is_dir($savePath)) {
mkdir($savePath, 0755);
}
foreach ($dirs as $dir) {
$savePath .= "/$dir";
if (!is_dir($savePath)) {
mkdir($savePath, 0755);
}
}
$fileName = time() . rand(0, 9999) . '.' . $file->extension;
$path = $savePath . $fileName;
if (!$file->saveAs($path)) {
throw new ServerErrorHttpException('服务器保存图片失败');
}
return ['fileName' => '/uploads/' . $dirs . '/' . $fileName, 'alias' => $file->baseName . $file->extension];
}
/**
* @param $array
* @return string
*/
public static function errorMessageStr($array): string
{
$data = [];
foreach ($array as $k => $v) {
$data[] = implode(' ', $v);
}
return implode(' ', $data);
}
/**
* @param array $ids 购物车id 数组
* @throws NotFoundHttpException
* @throws ServerErrorHttpException
* @throws \Throwable
* @throws \yii\db\StaleObjectException
*/
public static function delCarts($ids)
{
foreach ($ids as $id) {
$cart = Cart::find()
->where(['id' => $id])
->andWhere(['user_id' => Yii::$app->user->getId()])
->one();
if (!$cart) {
throw new NotFoundHttpException("未找到该购物车");
}
if (!$cart->delete()) {
throw new ServerErrorHttpException('服务器删除购物车失败');
}
}
}
/**
* @param $goodsId
* @param $count
* @param null $skuId
* @return bool true代表无限库存,false代表有限库存需要进行增删库存操作
* 判断库存
* @throws NotFoundHttpException
* @throws BadRequestHttpException
*/
public static function checkStock($goodsId, $count, $skuId = null)
{
$sku = GoodsSku::findOne($skuId);
$goods = Goods::findOne($goodsId);
if (!$goods) {
throw new NotFoundHttpException('商品未找到');
}
if ($goods->stock == Goods::UNLIMITED_STOCK) {
return true;
}
if ($sku && $sku->stock == Goods::UNLIMITED_STOCK) {
return true;
}
$stock = $sku ? $sku->stock : $goods->stock;
if ($stock < $count) {
throw new BadRequestHttpException("{$goods->name}库存不足");
}
return false;
}
/**
* @param $model
* @param $view
* post的返回头设置
*/
public static function createdResponse($model, $view)
{
$response = Yii::$app->getResponse()->setStatusCode(201);
$id = implode(',', array_values($model->getPrimaryKey(true)));
$response->getHeaders()->set('Location', Url::toRoute([$view, 'id' => $id], true));
}
/**
* @param $goodsId
* @param $skuId
* @return int
* @throws NotFoundHttpException
* 计算商品价格
*/
public static function goodsPrice($goodsId, $skuId)
{
$goods = Goods::findOne($goodsId);
if (!$goods) {
throw new NotFoundHttpException('商品未找到');
}
$price = $goods->price;
$sku = GoodsSku::findOne($skuId);
if ($sku) {
$price = $sku->price;
}
return $price;
}
/**
* @param $skuId
* @return string
* @throws NotFoundHttpException
* 获取拼接后的sku值
*/
public static function skuValue($skuId)
{
$sku = GoodsSku::findOne($skuId);
if (!$sku) {
return '';
}
$data = [];
$goodsAttr = array_filter(explode(',', $sku->goods_attr));
if (empty($goodsAttr)) {
throw new NotFoundHttpException('sku无对应商品属性');
}
foreach ($goodsAttr as $k => $v) {
$attr = GoodsAttr::findOne($v);
if (!$attr) {
throw new NotFoundHttpException('商品属性未找到');
}
$data[] = $attr->attr_value;
}
return implode(',', $data);
}
/**
* @param $query
* @return object
* @throws \yii\base\InvalidConfigException
* 获取数据
*/
public static function index($query)
{
$requestParams = Yii::$app->request->getBodyParams();
return Yii::createObject([
'class' => ActiveDataProvider::className(),
'query' => $query,
'pagination' => [
'params' => $requestParams,
],
'sort' => [
'params' => $requestParams,
],
]);
}
}

67
api/logic/Login.php

@ -0,0 +1,67 @@
<?php
namespace api\logic;
use common\models\User;
use yii\base\Exception;
use Yii;
use yii\web\BadRequestHttpException;
use yii\web\NotFoundHttpException;
use yii\web\ServerErrorHttpException;
class Login
{
const EXPIRE_TIME = 7 * 60 * 60 * 24;
/**
* @return string
* @throws Exception
* @throws NotFoundHttpException
* @throws ServerErrorHttpException
*/
public static function wxLogin()
{
$user = self::getWxUser();
Yii::$app->user->login($user, static::EXPIRE_TIME);
$user->expire_at = time() + static::EXPIRE_TIME;
$user->access_token = Yii::$app->security->generateRandomString();
if (!$user->save()) {
throw new ServerErrorHttpException('更新登录信息失败');
}
return $user->access_token;
}
/**
* @return array|User|null
* @throws BadRequestHttpException
* @throws NotFoundHttpException
*/
protected static function getWxUser()
{
$openid = Yii::$app->request->getBodyParam('openid');
if (!$openid) {
throw new BadRequestHttpException('缺少参数openid');
}
$user = User::find()
->where(['status' => User::STATUS_ACTIVE])
->andWhere(['wx_openid' => $openid])
->one();
if (!$user) {
throw new NotFoundHttpException('用户未找到');
}
return $user;
}
public function miniProgramLogin()
{
}
protected function getMiniUser()
{
}
}

459
api/logic/OrderLogic.php

@ -0,0 +1,459 @@
<?php
namespace api\logic;
use backend\modules\goods\models\ars\Goods;
use backend\modules\goods\models\ars\GoodsSku;
use backend\modules\shop\models\ars\Address;
use backend\modules\shop\models\ars\Cart;
use backend\modules\shop\models\ars\Order;
use backend\modules\shop\models\ars\OrderGoods;
use backend\modules\shop\models\ars\TakingSite;
use yii\base\Component;
use Throwable;
use Yii;
use yii\db\ActiveRecord;
use yii\base\Exception;
use yii\web\BadRequestHttpException;
use yii\web\NotFoundHttpException;
use yii\web\ServerErrorHttpException;
/**
* @author iron
* @email weiriron@gmail.com
* @package api\logic
*/
class OrderLogic extends Component
{
public $viewAction = 'view';
/*订单操作类型*/
const TYPE_CONFIRM = 1;
const TYPE_CANCEL = 2;
const TYPE_TAKE = 3;
const TYPE_CHANGE_SHIPPING_TYPE = 4;
const TYPE_CHANGE_ADDRESS = 5;
const TYPE_CHANGE_TAKING_SITE = 6;
/*仓库类型*/
const TYPE_ADD_STOCK = 1;
const TYPE_SUB_STOCK = -1;
/**
* @return Order
* @throws BadRequestHttpException
* @throws Exception
* 创建订单
*/
public function create()
{
//立即购物需传参数
$goodsId = Yii::$app->request->getBodyParam('goodsId');/*int 商品id*/
$count = Yii::$app->request->getBodyParam('count');/*int 数量*/
$skuId = Yii::$app->request->getBodyParam('skuId');/*int 商品sku id*/
//购物车提交订单需传参数
$cartIds = Yii::$app->request->getBodyParam('cartIds');/*array 购物车商品id*/
if ((empty($cartIds) && empty($goodsId)) || ($goodsId && empty($count))) {
throw new BadRequestHttpException(Helper::REQUEST_BAD_PARAMS);
}
$tra = Yii::$app->db->beginTransaction();
try {
$order = new Order();
$order->user_id = Yii::$app->user->getId();
$order->type = Order::TYPE_SHOPPING;
$order->order_sn = Helper::timeRandomNum(3, 'W');
if (!$order->save()) {
throw new ServerErrorHttpException('服务器创建订单失败');
}
if ($goodsId && $count) {
$this->addGoods($order->id, $goodsId, $skuId, $count);/*添加订单商品*/
} else {
$this->addGoodsByCart($cartIds, $order->id);/*通过购物车添加订单商品*/
}
$this->getShippingType($order);
$this->saveGoodsInfo($order);/*保存订单商品信息*/
if (!$order->save()) {
throw new Exception('服务器创建订单失败');
}
$tra->commit();
Helper::createdResponse($order, $this->viewAction);
return $order;
} catch (Exception $e) {
$tra->rollBack();
throw $e;
}
}
/**
* @return bool
* @throws Exception
* @throws Throwable
* @throws yii\base\InvalidConfigException
* 根据操作类型更新订单
*/
public function update()
{
$data = Yii::$app->request->getBodyParams();
$type = Yii::$app->request->getBodyParam('type');
$order = $this->findOrder();
$tra = Yii::$app->db->beginTransaction();
try {
switch ($type) {
case self::TYPE_CONFIRM :
$this->confirm($order, $data);
break;
case self::TYPE_CANCEL:
$this->cancel($order);
break;
case self::TYPE_TAKE:
$this->take($order);
break;
case self::TYPE_CHANGE_SHIPPING_TYPE:
$this->switchShippingType($order, $data);
break;
case self::TYPE_CHANGE_ADDRESS:
$this->changeAddress($order, $data);
break;
case self::TYPE_CHANGE_TAKING_SITE:
$this->changeTakingSite($order, $data);
break;
default:
throw new BadRequestHttpException(Helper::REQUEST_BAD_PARAMS);
}
if (!$order->save()) {
throw new ServerErrorHttpException('服务器更新订单失败');
}
$tra->commit();
return true;
} catch (Exception $e) {
$tra->rollBack();
throw $e;
}
}
/*----------------------------------------- 华丽的分割线 -----------------------------------------*/
/**
* @param $order
* @return int
* @throws BadRequestHttpException
* @throws NotFoundHttpException
*/
private function getShippingType($order)
{
$allOrderGoods = $this->findOrderGoods($order->id);
$goods = $this->findGoods($allOrderGoods[0]->goods_id);
if ($goods->is_express) {
return Order::SHIPPING_TYPE_EXPRESS;
}
if ($goods->is_taking) {
return Order::SHIPPING_TYPE_PICKED_UP;
}
throw new BadRequestHttpException('配送方式异常');
}
/**
* @param Order $order
* @param array $data
* @throws BadRequestHttpException
* @throws NotFoundHttpException
* 添加地址到订单
*/
private function changeAddress($order, $data)
{
if (!isset($data['address_id'])) {
throw new BadRequestHttpException(Helper::REQUEST_BAD_PARAMS);
}
if ($order->shipping_type !== Order::SHIPPING_TYPE_EXPRESS) {
throw new BadRequestHttpException('配送方式异常');
}
if ($order->status !== Order::STATUS_UNCONFIRMED) {
throw new BadRequestHttpException('该状态下不允许更改配送方式');
}
$address = Address::findOne(['id' => $data['address_id'], 'user_id' => Yii::$app->user->getId()]);
if (!$address) {
throw new NotFoundHttpException('收货地址未找到');
}
$order->consignee = $address->consignee;
$order->phone = $address->phone;
$order->city = $address->city;
$order->area = $address->area;
$order->province = $address->province;
$order->address = $address->address;
}
/**
* @param Order $order
* @param array $data
* @throws BadRequestHttpException
* @throws NotFoundHttpException
* 修改自提点
*/
private function changeTakingSite($order, $data)
{
if (!isset($data['taking_site_id']) || empty($data['taking_site_id'])) {
throw new BadRequestHttpException(Helper::REQUEST_BAD_PARAMS);
}
if ($order->shipping_type !== Order::SHIPPING_TYPE_PICKED_UP) {
throw new BadRequestHttpException('配送方式异常');
}
if ($order->status !== Order::STATUS_UNCONFIRMED) {
throw new BadRequestHttpException('该状态下不允许更改提货地址方式');
}
$site = TakingSite::findOne($data['taking_site_id']);
if (!$site) {
throw new NotFoundHttpException('自提点未找到');
}
$order->taking_site = $data['taking_site_id'];
}
/**
* @param Order $order
* @param array $data
* @throws BadRequestHttpException
* 切换配送方式
*/
private function switchShippingType($order, $data)
{
if (!isset($data['shipping_type']) ||
!in_array($data['shipping_type'], [Order::SHIPPING_TYPE_PICKED_UP, Order::SHIPPING_TYPE_EXPRESS])) {
throw new BadRequestHttpException(Helper::REQUEST_BAD_PARAMS);
}
if ($order->status !== Order::STATUS_UNCONFIRMED) {
throw new BadRequestHttpException('该状态下不允许更改配送方式');
}
$order->shipping_type = $data['shipping_type'];
}
/**
* @param Order $order
* @param array $data
* @throws BadRequestHttpException
* @throws NotFoundHttpException
* @throws ServerErrorHttpException
* @throws Throwable
* @throws yii\db\StaleObjectException
* 确定订单
*/
private function confirm($order, $data)
{
if ($order->status !== Order::STATUS_UNCONFIRMED) {
throw new BadRequestHttpException('订单状态异常');
}
if ($order->shipping_type === Order::SHIPPING_TYPE_PICKED_UP) {
if ($data['consignee'] ?? false || $data['phone'] ?? false) {
throw new BadRequestHttpException(Helper::REQUEST_BAD_PARAMS);
}
$order->consignee = $data['consignee'];
$order->phone = $data['phone'];
}
if (empty($order->consignee)) {
throw new BadRequestHttpException('需先填写收件人信息');
}
if (isset($data['remarks'])) {
$order->remarks = $data['remarks'];
}
Helper::delCarts($this->getCartsIds($order)); //删除购物车对应商品
$order->status = Order::STATUS_NONPAYMENT;
$this->updateStock($order, self::TYPE_SUB_STOCK);
}
/**
* @param $order
* @return array
* 获取订单商品对应购物车商品id
*/
private function getCartsIds($order)
{
$allGoods = $this->findOrderGoods($order->id);
$ids = [];
foreach ($allGoods as $goods) {
$cart = Cart::findOne(['goods_id' => $goods->goods_id, 'user_id' => Yii::$app->user->getId()]);
if ($cart) {
$ids[] = $cart->id;
}
}
return $ids;
}
/**
* @param Order $order
* @throws BadRequestHttpException
* @throws NotFoundHttpException
* @throws ServerErrorHttpException
* 取消订单
*/
private function cancel($order)
{
if ($order->status !== Order::STATUS_NONPAYMENT) {
throw new BadRequestHttpException('该状态下无法取消订单');
}
$order->status = Order::STATUS_CANCEL;
$this->updateStock($order, self::TYPE_ADD_STOCK);/*更新库存*/
}
/**
* @param Order $order
* @throws BadRequestHttpException
* 确认收货
*/
private function take($order)
{
if ($order->status !== Order::STATUS_SHIPMENT_ALL) {
throw new BadRequestHttpException('该状态下无法确认收货');
}
$order->status = Order::STATUS_FINISH;
}
/**
* @param $id
* @param $type
* @throws BadRequestHttpException
* @throws NotFoundHttpException
* @throws ServerErrorHttpException
* 更新库存
*/
private function updateStock($id, $type)
{
$allOrderGoods = $this->findOrderGoods($id);
foreach ($allOrderGoods as $orderGoods) {
/*检查库存*/
if (Helper::checkStock($orderGoods->goods_id, $orderGoods->goods_count, $orderGoods->sku_id)) {
return;
}
if ($orderGoods->sku_id) {
$goods = GoodsSku::findOne($orderGoods->sku_id);
} else {
$goods = $this->findGoods($orderGoods->goods_id);
}
if ($type) {
$count = $orderGoods->goods_count;
} else {
$count = -$orderGoods->goods_count;
}
if (!$goods->updateCounters(['stock' => $count])) {
throw new ServerErrorHttpException('更新库存失败');
}
}
}
/**
* @param array $cartIds 购物车商品id
* @param int $id 订单id
* @throws Exception
* @throws NotFoundHttpException
* 通过购物车添加商品
*/
private function addGoodsByCart($cartIds, $id)
{
foreach ($cartIds as $cartId) {
$cart = Cart::findOne($cartId);
if (!$cart) {
throw new NotFoundHttpException('购物车未找到');
}
$this->addGoods($id, $cart->goods_id, $cart->sku_id, $cart->goods_count);
}
}
/**
* @param Order $order
* 保存商品总价格和总数量信息到
*/
private function saveGoodsInfo($order)
{
$orderGoods = $this->findOrderGoods($order->id);
foreach ($orderGoods as $goods) {
$order->goods_amount += $goods->price;
$order->goods_count += $goods->goods_count;
}
}
/**
* @param $id
* @param int $goodsId
* @param $skuId
* @param $count
* @throws Exception
* @throws NotFoundHttpException
* 添加商品到订单
*/
private function addGoods($id, $goodsId, $skuId, $count)
{
$goods = $this->findGoods($goodsId);
$orderGoods = new OrderGoods();
$orderGoods->order_id = $id;
$orderGoods->goods_id = $goodsId;
$orderGoods->sku_id = $skuId ?: 0;
$orderGoods->sku_value = Helper::skuValue($skuId);
$orderGoods->weight = $skuId ? $this->skuWeight($skuId) : $goods->weight;
$orderGoods->goods_count = $count;
$orderGoods->goods_img = $goods->image;
$orderGoods->goods_name = $goods->name;
$orderGoods->price = Helper::goodsPrice($goodsId, $skuId);
Helper::checkStock($goodsId, $count, $skuId); /*检查库存*/
if (!$orderGoods->save()) {
throw new Exception('服务器添加订单商品失败');
}
}
/**
* @param $skuId
* @return int
* @throws NotFoundHttpException
* 获取sku重量
*/
private function skuWeight($skuId)
{
$sku = GoodsSku::findOne($skuId);
if (!$sku) {
throw new NotFoundHttpException('sku未找到');
}
return $sku->weight;
}
/**
* @return array|Order|null
* 根据id获取订单
*/
private function findOrder()
{
$id = Yii::$app->request->getQueryParam('id');
return Order::find()
->where(['id' => $id])
->andWhere(['user_id' => Yii::$app->user->getId()])
->one();
}
/**
* @param $id
* @return array|ActiveRecord[]|OrderGoods[]
* 根据订单 id 获取所有订单商品
*/
private function findOrderGoods($id)
{
return OrderGoods::find()
->where(['order_id' => $id])
->all();
}
/**
* @param $goodsId
* @return array|Goods|null
* @throws NotFoundHttpException
*/
private function findGoods($goodsId)
{
$goods = Goods::find()
->where(['id' => $goodsId])
->andWhere(['is_delete' => Goods::IS_DELETE_NO])
->andWhere(['is_sale' => Goods::IS_SALE_YES])
->one();
if (!$goods) {
throw new NotFoundHttpException("商品[{$goodsId}]未找到");
}
return $goods;
}
}

40
api/logic/UserLogic.php

@ -0,0 +1,40 @@
<?php
namespace api\logic;
use common\models\DailyActiveUser;
use yii\base\Component;
use Yii;
/**
* @author iron
* @email weiriron@gmail.com
* Class CartLogic
* @package api\logic
*/
class UserLogic extends Component
{
public function DailyActive()
{
$date = date('Y-m-d', time());
$DAU = DailyActiveUser::find()
->where(['date' => $date])
->one();
if ($DAU) {
$ids = $DAU->user_ids;
if (in_array(Yii::$app->user->id, $ids)) {
return;
}
array_push($ids, Yii::$app->user->id);
$DAU->user_id = $ids;
$DAU->count += 1;
} else {
$DAU = new DailyActiveUser();
$DAU->user_ids = array(Yii::$app->user->getId());
$DAU->date = $date;
}
$DAU->save();
}
}

101
api/logic/WxPaymentLogic.php

@ -0,0 +1,101 @@
<?php
/**
* Created by PhpStorm.
* User: travis
* Date: 2019/12/12
* Time: 6:20
*/
namespace api\logic;
use backend\modules\payment\logic\WxPaymentManager;
use yii\helpers\Json;
use yii\httpclient\Client;
use yii\web\BadRequestHttpException;
use backend\modules\shop\models\ars\PaymentLog;
use yii\db\Exception;
use Yii;
class WxPaymentLogic extends WxPaymentManager
{
/**
* @return array|bool
* @throws BadRequestHttpException
* @throws \yii\base\InvalidConfigException
* @throws \yii\httpclient\Exception
* 微信支付回调
*/
public function notify()
{
$notifyData = Json::decode(Json::encode(simplexml_load_string(Yii::$app->request->getRawBody(), 'SimpleXMLElement', LIBXML_NOCDATA)));
Yii::info($notifyData, "notify");
if (!$this->checkSign($notifyData)) {
throw new BadRequestHttpException(Helper::REQUEST_BAD_PARAMS);
}
$tra = Yii::$app->db->beginTransaction('SERIALIZABLE');
try {
if ($notifyData->result_code != 'SUCCESS' || $notifyData->return_code != 'SUCCESS') {
throw new BadRequestHttpException('result_code or return_code is false');
}
$paymentLog = PaymentLog::findOne(['order_id' => $notifyData->out_trade_no]);
$this->notifyUrl = Yii::$app->request->hostInfo . $paymentLog->notify_url;
$paymentLog->mch_id = $notifyData->mch_id;
$paymentLog->wx_payment_id = $notifyData->transaction_id; //交易号
$paymentLog->status = self::STATUS_PAYMENT_SUCCESS;
$paymentLog->payment_at = time();
if (!$paymentLog->save()) {
throw new Exception(Helper::errorMessageStr($paymentLog->errors));
}
if (!$tra->commit()) {
throw new Exception('保存数据失败');
}
/*转发回调信息*/
$this->forwardNotify($notifyData, true);
return ['return_code' => 'SUCCESS', 'return_msg' => 'OK'];//回传成功信息到微信服务器
} catch (Exception $e) {
$tra->rollBack();
$this->forwardNotify($notifyData, false);
Yii::info($e->getMessage(), 'notify');
return false;
} catch (BadRequestHttpException $e) {
$tra->rollBack();
$this->forwardNotify($notifyData, false);
Yii::info($e->getMessage(), 'notify');
return false;
}
}
/**
* @param $notifyData
* @param $status
* @return bool
* @throws \yii\base\InvalidConfigException
* @throws \yii\httpclient\Exception
* 转发异步回调信息
*/
protected function forwardNotify($notifyData, $status)
{
$notify = [
'notify' => [
'status' => $status,
'notify' => $notifyData
]
];
$client = new Client();
$response = $client->createRequest()
->setMethod('POST')
->setUrl($this->notifyUrl)
->addHeaders(['content-type' => 'application/json'])
->setContent(Json::encode($notify))
->send();
if ($response->isOk) {
return true;
} else {
return false;
}
}
}

18
api/web/index-test.php

@ -0,0 +1,18 @@
<?php
// NOTE: Make sure this file is not accessible when deployed to production
if (!in_array(@$_SERVER['REMOTE_ADDR'], ['127.0.0.1', '::1'])) {
die('You are not allowed to access this file.');
}
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'test');
require __DIR__ . '/../../vendor/autoload.php';
require __DIR__ . '/../../vendor/yiisoft/yii2/Yii.php';
require __DIR__ . '/../../common/config/bootstrap.php';
require __DIR__ . '/../config/bootstrap.php';
$config = require __DIR__ . '/../config/test-local.php';
(new yii\web\Application($config))->run();

17
api/web/index.php

@ -0,0 +1,17 @@
<?php
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');
require __DIR__ . '/../../vendor/autoload.php';
require __DIR__ . '/../../vendor/yiisoft/yii2/Yii.php';
require __DIR__ . '/../../common/config/bootstrap.php';
require __DIR__ . '/../config/bootstrap.php';
$config = yii\helpers\ArrayHelper::merge(
require __DIR__ . '/../../common/config/main.php',
require __DIR__ . '/../../common/config/main-local.php',
require __DIR__ . '/../config/main.php',
require __DIR__ . '/../config/main-local.php'
);
(new yii\web\Application($config))->run();

2
api/web/robots.txt

@ -0,0 +1,2 @@
User-agent: *
Disallow: /

25
backend/config/main.php

@ -1,7 +1,7 @@
<?php
$params = array_merge(
require __DIR__ . '/../../common/config/params.php', require __DIR__ . '/../../common/config/params-local.php', require __DIR__ . '/params.php', require __DIR__ . '/params-local.php'
require __DIR__ . '/../../common/config/params.php', require __DIR__ . '/../../common/config/params-local.php', require __DIR__ . '/params.php', require __DIR__ . '/params-local.php'
);
return [
@ -10,14 +10,8 @@ return [
'controllerNamespace' => 'backend\controllers',
'bootstrap' => ['log'],
'modules' => [
'goods' => [
'class' => '\backend\modules\goods\Module',
],
'file' => [
'class' => '\backend\modules\file\Module',
],
'shop' => [
'class' => '\backend\modules\shop\Module',
'wx-public-account' => [
'class' => '\backend\modules\wx_public_account\Module',
],
],
'components' => [
@ -53,6 +47,16 @@ return [
'prefix' => function ($message) {
}
],
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
'categories' => ['refund_log'],
'logFile' => '@app/runtime/logs/refund_log.log',
'logVars' => [],
'exportInterval' => 1,
'prefix' => function ($message) {
}
],
],
],
'errorHandler' => [
@ -67,5 +71,8 @@ return [
'file' => ['class' => 'backend\logic\file\FileManager'],
'goods' => ['class' => 'goods\goods\logic\goods\GoodsManager'],
],
// 'as access' => [
// 'class' => 'iron\components\AccessControl',
// ],
'params' => $params,
];

14
backend/config/params.php

@ -1,4 +1,18 @@
<?php
return [
'adminEmail' => 'admin@example.com',
'logistics' => [
'SELF' => '商家配送',
'shunfeng' => '顺丰速运',
'suteng' => '速腾快递',
'shentong' => '申通快递',
'zhongtong' => '中通快递',
'yuantong' => '圆通快递',
'huitong' => '百世快递(原汇通)',
'yunda' => '韵达快递',
'yousu' => 'UC优速快递',
'gnxb' => '邮政小包',
'youzhengguonei' => '邮政包裹/平邮/挂号信',
'jingdong' => '京东快递',
],
];

2
backend/controllers/SiteController.php

@ -89,7 +89,7 @@ class SiteController extends Controller {
$model->password = '';
return $this->render('login', [
'model' => $model,
'model' => $model,
]);
}
}

58
backend/models/Cat.php

@ -1,58 +0,0 @@
<?php
namespace backend\models;
use Yii;
/**
* This is the model class for table "cat".
*
* @property int $id
* @property string $cat_name
* @property string $icon
* @property int $icon_type
* @property string $description
* @property int $sort_order
* @property int $created_at
* @property int $updated_at
*/
class Cat extends \yii\db\ActiveRecord
{
/**
* {@inheritdoc}
*/
public static function tableName()
{
return 'cat';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['cat_name'], 'required'],
[['icon_type', 'sort_order', 'created_at', 'updated_at'], 'integer'],
[['description'], 'string'],
[['cat_name', 'icon'], 'string', 'max' => 64],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'cat_name' => 'Cat Name',
'icon' => 'Icon',
'icon_type' => 'Icon Type',
'description' => 'Description',
'sort_order' => 'Sort Order',
'created_at' => 'Created At',
'updated_at' => 'Updated At',
];
}
}

125
backend/models/Category.php

@ -1,125 +0,0 @@
<?php
namespace backend\models;
use iron\wegets\Upload;
use Yii;
use yii\behaviors\TimestampBehavior;
/**
* This is the model class for table "category".
*
* @property int $id
* @property string $cat_name
* @property string $icon
* @property int $icon_type
* @property string $description
* @property int $sort_order
* @property int $created_at
* @property int $updated_at
*/
class Category extends \yii\db\ActiveRecord
{
const ICON_TYPE_BOOSTARAP = 1;
const ICON_TYPE_AWESOME = 2;
public static $iconType = [
self::ICON_TYPE_BOOSTARAP => "boostrap",
self::ICON_TYPE_AWESOME => "awesome"
];
/**
* {@inheritdoc}
*/
public static function tableName()
{
return 'category';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['icon_type', 'cat_name', 'created_at'], 'required'],
[['icon_type', 'sort_order', 'created_at', 'updated_at'], 'integer'],
[['description'], 'string'],
[['cat_name', 'icon'], 'string', 'max' => 64],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'cat_name' => '类名',
'icon' => 'Icon',
'icon_type' => '图标类型',
'description' => '描述',
'sort_order' => 'Sort Order',
'created_at' => '添加日期',
'updated_at' => 'Updated At',
];
}
/**
* @return array
* 列格式
*/
public static function columns()
{
return [
[
'class' => 'blobt\grid\CheckboxColumn',
'width' => '2%',
'align' => 'center'
],
[
'attribute' => 'id',
'width' => '10%',
'align' => 'center'
],
[
'attribute' => 'created_at',
'width' => '10%',
'format' => 'date'
],
[
'attribute' => 'cat_name',
'width' => '10%',
],
[
'attribute' => 'icon',
'width' => '10%',
],
[
'attribute' => 'icon_type',
'width' => '10%',
'showConstText' => true
],
[
'attribute' => 'description',
'enableSorting' => false,
'format' => 'ntext',
'width' => '20%',
],
[
'class' => 'iron\grid\ActionColumn',
'align' => 'center',
],
];
}
public function behaviors()
{
return [
TimestampBehavior::className()
];
}
}

126
backend/models/CategorySearch.php

@ -1,126 +0,0 @@
<?php
namespace backend\models;
use backend\models\Category;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use yii\helpers\ArrayHelper;
/**
* CategorySearch represents the model behind the search form of `\backend\models\Category`.
*/
class CategorySearch extends Category
{
/**
* @return array
* 增加创建时间查询字段
*/
public function attributes()
{
return ArrayHelper::merge(['created_at_range'], parent::attributes());
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['id', 'icon_type', 'sort_order', 'created_at', 'updated_at'], 'integer'],
[['cat_name', 'icon', 'description', 'created_at_range'], 'safe'],
];
}
/**
* {@inheritdoc}
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* @param $params
* @return ActiveDataProvider
* 不分页的所有数据
*/
public function allData($params)
{
$query = Category::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)
{
$query = Category::find();
// 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,
'icon_type' => $this->icon_type,
'sort_order' => $this->sort_order,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
]);
$query->andFilterWhere(['like', 'cat_name', $this->cat_name])
->andFilterWhere(['like', 'icon', $this->icon])
->andFilterWhere(['like', 'description', $this->description]);
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;
}
}

227
backend/models/User.php

@ -0,0 +1,227 @@
<?php
namespace backend\models;
use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;
/**
* User model
*
* @property integer $id
* @property string $username
* @property string $password_hash
* @property string $password_reset_token
* @property string $verification_token
* @property string $email
* @property string $auth_key
* @property integer $status
* @property integer $created_at
* @property integer $updated_at
* @property string $password write-only password
*/
class User extends ActiveRecord implements IdentityInterface
{
const STATUS_DELETED = 0;
const STATUS_ACTIVE = 10;
/**
* {@inheritdoc}
*/
public static function tableName()
{
return '{{auth_user}}';
}
/**
* {@inheritdoc}
*/
public function behaviors()
{
return [
[
'class' => TimestampBehavior::className(),
'createdAtAttribute' => 'created_at',
'updatedAtAttribute' => 'updated_at',
'value' => function () {
return time();
},
],
];
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],
];
}
public function beforeSave($insert)
{
if ($insert) {
$this->email = $this->username . '@example.com';
$this->generateAuthKey();
$this->setPassword(Yii::$app->security->generateRandomString());
}
return parent::beforeSave($insert);
}
/**
* {@inheritdoc}
*/
public static function findIdentity($id)
{
return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
}
/**
* {@inheritdoc}
*/
public static function findIdentityByAccessToken($token, $type = null)
{
throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
}
/**
* Finds user by username
*
* @param string $username
* @return static|null
*/
public static function findByUsername($username)
{
return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]);
}
/**
* Finds user by password reset token
*
* @param string $token password reset token
* @return static|null
*/
public static function findByPasswordResetToken($token)
{
if (!static::isPasswordResetTokenValid($token)) {
return null;
}
return static::findOne([
'password_reset_token' => $token,
'status' => self::STATUS_ACTIVE,
]);
}
/**
* Finds user by verification email token
*
* @param string $token verify email token
* @return static|null
*/
public static function findByVerificationToken($token)
{
return static::findOne([
'verification_token' => $token,
'status' => self::STATUS_INACTIVE
]);
}
/**
* Finds out if password reset token is valid
*
* @param string $token password reset token
* @return bool
*/
public static function isPasswordResetTokenValid($token)
{
if (empty($token)) {
return false;
}
$timestamp = (int)substr($token, strrpos($token, '_') + 1);
$expire = Yii::$app->params['user.passwordResetTokenExpire'];
return $timestamp + $expire >= time();
}
/**
* {@inheritdoc}
*/
public function getId()
{
return $this->getPrimaryKey();
}
/**
* {@inheritdoc}
*/
public function getAuthKey()
{
return $this->auth_key;
}
/**
* {@inheritdoc}
*/
public function validateAuthKey($authKey)
{
return $this->getAuthKey() === $authKey;
}
/**
* Validates password
*
* @param string $password password to validate
* @return bool if password provided is valid for current user
*/
public function validatePassword($password)
{
return Yii::$app->security->validatePassword($password, $this->password_hash);
}
/**
* Generates password hash from password and sets it to the model
*
* @param string $password
*/
public function setPassword($password)
{
$this->password_hash = Yii::$app->security->generatePasswordHash($password);
}
/**
* Generates "remember me" authentication key
*/
public function generateAuthKey()
{
$this->auth_key = Yii::$app->security->generateRandomString();
}
/**
* Generates new password reset token
*/
public function generatePasswordResetToken()
{
$this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
}
public function generateEmailVerificationToken()
{
$this->verification_token = Yii::$app->security->generateRandomString() . '_' . time();
}
/**
* Removes password reset token
*/
public function removePasswordResetToken()
{
$this->password_reset_token = null;
}
}

24
backend/modules/file/Module.php

@ -1,24 +0,0 @@
<?php
namespace backend\modules\file;
/**
* file module definition class
*/
class Module extends \yii\base\Module
{
/**
* {@inheritdoc}
*/
public $controllerNamespace = 'backend\modules\file\controllers';
/**
* {@inheritdoc}
*/
public function init()
{
parent::init();
// custom initialization code goes here
}
}

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

@ -1,217 +0,0 @@
<?php
namespace backend\modules\file\logic\file;
use backend\modules\file\models\ars\File;
use backend\modules\file\models\ars\TemFile;
use Exception;
use yii\web\HttpException;
use yii;
use yii\web\ServerErrorHttpException;
use backend\modules\goods\logic\goods\GoodsManager;
class FileManager
{
//数据表ats_file和ats_tem_file的类型字段type
const TYPE_NONE = 0;//不存在
const TYPE_IMAGE = 1;//图片
const TYPE_VIDEO = 2;//影视
const TYPE_EXCEL = 3;//excel表单
const TYPE_WORD = 4;//word文本
const TYPE_TXT = 5;//txt文本
public static $extension = [
self::TYPE_IMAGE => ['jpg', 'png', 'jpeg'],
self::TYPE_VIDEO => ['mp4'],
self::TYPE_EXCEL => [],
self::TYPE_WORD => ['docx'],
self::TYPE_TXT => ['txt'],
];
/**
* @param $keyword
* @return int|string
* 根据文件拓展名在$extension中查找对应的文件类型,若不存在则返回self::TYPE_NONE
*/
public static function searchType($keyword)
{
foreach(self::$extension as $key => $type){
if (in_array($keyword, $type)) {
return $key;
}
}
return self::TYPE_NONE;
}
/**
* @param $temFileIdArr
* @param $ownId
* @param $ownType
* @return array|bool
* @throws HttpException
* @throws ServerErrorHttpException
* 根据临时文件id将临时文件保存在文件中
*/
public function saveTemFileToFile($temFileIdArr, $ownId, $ownType)
{
if(empty($temFileIdArr) || !$ownId) {
return false;
}
$tra = Yii::$app->db->beginTransaction();
try {
$firstFileId = 0;
foreach ($temFileIdArr as $key => $value) {
$temFile = TemFile::findOne($value);
if ($temFile) {
$res = self::saveNewFile($temFile, $ownId, $ownType);
if ($key == 0) {
$firstFileId = $res['file_id'];
}
}
}
$tra->commit();
return ['status' => true, 'info' => '保存成功', 'first_file_id' => $firstFileId];
} catch (yii\db\Exception $e) {
$tra->rollBack();
throw new ServerErrorHttpException($e->getMessage());
}
}
/**
* @param TemFile|$temFile
* @param $ownId
* @param $ownType
* @return array
* @throws HttpException
* 创建新的文件
*/
private function saveNewFile($temFile, $ownId, $ownType)
{
$newFile = new File();
$newFile->name = $temFile->name;
$newFile->type = $temFile->type;
$newFile->own_id = $ownId;
$newFile->own_type = $ownType;
$newFile->alias = $temFile->alias;
$newFile->path = $temFile->path;
if($newFile->save()) {
return ['status' => true, 'info' => '操作成功', 'file_id' => $newFile->id];
} else {
throw new HttpException('500', 'File保存失败');
}
}
/**
* @param $fileIdArr
* @return bool
* @throws HttpException
* 删除file表中的文件
*/
public function deleteFile($fileIdArr)
{
if($fileIdArr){
foreach ($fileIdArr as $key => $value) {
$fileModel = File::findOne($value);
if($fileModel){
$fileModel->is_delete = File::IS_DELETE_YES;
if(!$fileModel->save()){
throw new HttpException('500', '文件删除失败');
}
}
}
}
return true;
}
/**
* @param yii\base\Model|$dataModel //数据模型
* @param $fileIdStrName //表单中临时保存的文件id字符串组合(以,隔开)
* @param string $fileNameInModel //需要保存到数据库中的数据表字段名称
* @param $fileOldIdStr //数据库中已经保存的文件id字符串组合(以,隔开)
* @param $fileType //File模型中定义的own_type常量
* @return bool
* @throws Exception
* 数据模型保存文件操作
*/
public static function saveFileInModel($dataModel, $fileIdStrName, $fileOldIdStr, $fileType, $fileNameInModel = '')
{
if (is_array($dataModel)) {
throw new ServerErrorHttpException('数据模型不得为数组');
}
$dataModel->save();
$saveFileRes = GoodsManager::saveFile(explode(',', $dataModel->$fileIdStrName), $dataModel, explode(',', $fileOldIdStr), $fileType);
if ($fileNameInModel && $saveFileRes['status'] && $saveFileRes['first_file_id'] !== 0) {
$dataModel->$fileNameInModel = $saveFileRes['first_file_id'];
if (!$dataModel->save()) {
throw new ServerErrorHttpException('dataModel保存失败');
}
}
return true;
}
/**
* @param $fileName
* @param $formData
* @return int
* 保存临时文件操作
*/
public static function saveTemFile($fileName, $formData)
{
$temFileModel = new TemFile();
$temFileModel->user_id = Yii::$app->user->identity->id;
$temFileModel->name = $fileName;
$temFileModel->type = FileManager::searchType(pathinfo($formData['path'])['extension']);
$temFileModel->alias = $formData['alias'];
$temFileModel->path = $formData['path'];
$temFileModel->save();
return $temFileModel->id;
}
/**
* @param $data //ajax接收的数据
* @return string
* 上传插件点击删除按钮时处理文件id字符串(以,分隔)
*/
public static function dealFileIdStrInDel($data)
{
$imgIdArr = explode(',', $data['imgid']);
if(isset($data['data']['alias'])) {
$temFile = TemFile::findOne(['alias' => $data['data']['alias']]);
if ($temFile) {
$imgIdArr = array_diff($imgIdArr, [$temFile->id]);
}
}else{
foreach ($data as $key => $value) {
$temFile = File::findOne(['alias' => $value]);
if ($temFile) {
$imgIdArr = array_diff($imgIdArr, [$temFile->id]);
}
}
}
return implode(',', $imgIdArr);
}
/**
* @param $fileIdStr
* @return false|string
* 加载已有的文件数据
*/
public static function loadExitFile($fileIdStr)
{
$fileIdArr = explode(',', $fileIdStr);
$files = File::find()->where(['id' => $fileIdArr])->all();
$fileInfo = array();
if($files) {
foreach ($files as $key => $file) {
$fileInfo[$key]['name'] = $file->alias;
$fileInfo[$key]['path'] = Yii::$app->request->hostInfo . '/' . $file->path;
$fileInfo[$key]['size'] = filesize($file->path);
}
}
return json_encode($fileInfo);
}
}

39
backend/modules/file/migrations/m191112_022131_create_table_file.php

@ -1,39 +0,0 @@
<?php
use yii\db\Migration;
/**
* Class m191112_022131_create_table_file
*/
class m191112_022131_create_table_file extends Migration
{
/**
* {@inheritdoc}
*/
public function up()
{
$tableOptions = 'CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE=InnoDB COMMENT="文件表"';
$this->createTable('ats_file', [
'id' => $this->primaryKey(),
'pid'=>$this->integer(11)->defaultValue(null)->comment('父级id'),
'name'=>$this->string(255)->defaultValue(null)->comment('名称'),
'type'=>$this->tinyInteger(1)->defaultValue(0)->comment('类型'),
'own_type'=>$this->tinyInteger(1)->defaultValue(0)->comment('拥有者类型'),
'own_id'=>$this->integer(11)->defaultValue(null)->comment('拥有者id'),
'alias'=>$this->string(50)->defaultValue(null)->comment('别名'),
'path'=>$this->string(255)->defaultValue(null)->comment('地址'),
'is_delete'=>$this->tinyInteger(1)->defaultValue(0)->comment('是否删除,1为已删除'),
'updated_at'=>$this->integer(11)->defaultValue(null)->comment('更新时间'),
'created_at'=>$this->integer(11)->defaultValue(null)->comment('创建时间'),
],$tableOptions);
}
/**
* {@inheritdoc}
*/
public function down()
{
$this->dropTable('ats_file');
return true;
}
}

36
backend/modules/file/migrations/m191112_022532_create_table_tem_file.php

@ -1,36 +0,0 @@
<?php
use yii\db\Migration;
/**
* Class m191112_022532_create_table_tem_file
*/
class m191112_022532_create_table_tem_file extends Migration
{
/**
* {@inheritdoc}
*/
public function up()
{
$tableOptions = 'CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE=InnoDB COMMENT="临时文件表"';
$this->createTable('ats_tem_file', [
'id' => $this->primaryKey(),
'user_id'=>$this->integer(11)->defaultValue(null)->comment('父级id'),
'name'=>$this->string(255)->defaultValue(null)->comment('名称'),
'type'=>$this->tinyInteger(1)->defaultValue(0)->comment('类型'),
'alias'=>$this->string(50)->defaultValue(null)->comment('别名'),
'path'=>$this->string(255)->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_tem_file');
return true;
}
}

93
backend/modules/file/models/ars/File.php

@ -1,93 +0,0 @@
<?php
namespace backend\modules\file\models\ars;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
/**
* This is the model class for table "ats_file".
*
* @property int $id
* @property int $pid 父级id
* @property string $name 名称
* @property int $type 类型
* @property int $own_type 拥有者类型
* @property int $own_id 拥有者id
* @property string $alias 别名
* @property string $path 地址
* @property int $is_delete 是否删除,1为已删除
* @property int $updated_at 更新时间
* @property int $created_at 创建时间
*/
class File extends ActiveRecord
{
//own_type
const OWN_TYPE_GOODS_INDEX = 1;//商品首页
const OWN_TYPE_GOODS_DETAILS = 2;//商品详情
const OWN_TYPE_CATEGORY_ICON = 3;//类目图标
//is_delete
const IS_DELETE_YES = 1;//已删除
const IS_DELETE_NO = 0;//未删除
/**
* {@inheritdoc}
*/
public static function tableName()
{
return 'ats_file';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['pid', 'type', 'own_type', 'own_id', 'is_delete'], 'integer'],
[['name', 'path'], 'string', 'max' => 255],
[['alias'], 'string', 'max' => 50],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'id',
'pid' => '父级id',
'name' => '名称',
'type' => '类型',
'own_type' => '拥有者类型',
'own_id' => '拥有者id',
'alias' => '别名',
'path' => '地址',
'is_delete' => '是否删除,1为已删除',
'updated_at' => '更新时间',
'created_at' => '创建时间',
];
}
/**
* @author linyao
* @email 602604991@qq.com
* @created Nov 8, 2019
*
* 行为存储创建时间和更新时间
*/
public function behaviors()
{
return [
[
'class' => TimestampBehavior::class,
'createdAtAttribute' => 'created_at',
'updatedAtAttribute' => 'updated_at',
'value' => function() {
return time();
},
],
];
}
}

81
backend/modules/file/models/ars/TemFile.php

@ -1,81 +0,0 @@
<?php
namespace backend\modules\file\models\ars;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
/**
* This is the model class for table "ats_tem_file".
*
* @property int $id
* @property int $user_id 父级id
* @property string $name 名称
* @property int $type 类型
* @property string $alias 别名
* @property string $path 地址
* @property int $updated_at 更新时间
* @property int $created_at 创建时间
*/
class TemFile extends ActiveRecord
{
/**
* {@inheritdoc}
*/
public static function tableName()
{
return 'ats_tem_file';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['user_id', 'type'], 'integer'],
[['name', 'path'], 'string', 'max' => 255],
[['alias'], 'string', 'max' => 50],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'id',
'user_id' => '父级id',
'name' => '名称',
'type' => '类型',
'alias' => '别名',
'path' => '地址',
'updated_at' => '更新时间',
'created_at' => '创建时间',
];
}
/**
* @author linyao
* @email 602604991@qq.com
* @created Nov 8, 2019
*
* 行为存储创建时间和更新时间
*/
public function behaviors()
{
return [
[
'class' => TimestampBehavior::class,
'createdAtAttribute' => 'created_at',
'updatedAtAttribute' => 'updated_at',
'value' => function() {
return time();
},
],
];
}
}

24
backend/modules/goods/Module.php

@ -1,24 +0,0 @@
<?php
namespace backend\modules\goods;
/**
* goods module definition class
*/
class Module extends \yii\base\Module
{
/**
* {@inheritdoc}
*/
public $controllerNamespace = 'backend\modules\goods\controllers';
/**
* {@inheritdoc}
*/
public function init()
{
parent::init();
// custom initialization code goes here
}
}

58
backend/modules/goods/assets/custom/sku.49a56a9198d9c3ec233c.js
File diff suppressed because it is too large
View File

58
backend/modules/goods/assets/custom/sku.52802ed907a316501cd7.js
File diff suppressed because it is too large
View File

58
backend/modules/goods/assets/custom/sku.9a46222d01b3d601e5ad.js
File diff suppressed because it is too large
View File

64
backend/modules/goods/assets/custom/sku_item.6649e882bedbeb22ea3d.js
File diff suppressed because it is too large
View File

9210
backend/modules/goods/assets/js/jquery.js
File diff suppressed because it is too large
View File

159
backend/modules/goods/controllers/AttributeController.php

@ -1,159 +0,0 @@
<?php
namespace backend\modules\goods\controllers;
use backend\modules\goods\logic\goods\GoodsManager;
use Yii;
use backend\modules\goods\models\ars\Attribute;
use backend\modules\goods\models\searchs\AttributeSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use iron\widget\Excel;
/**
* AttributeController implements the CRUD actions for Attribute model.
*/
class AttributeController extends Controller
{
/**
* {@inheritdoc}
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
/**
* Lists all Attribute models.
* @return mixed
*/
public function actionIndex()
{
$searchModel = new AttributeSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'columns' => $searchModel->columns()
]);
}
/**
* Displays a single Attribute model.
* @param integer $id
* @return mixed
* @throws NotFoundHttpException if the model cannot be found
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new Attribute model.
* If creation is successful, the browser will be redirected to the 'view' page.
* @return mixed
*/
public function actionCreate()
{
$model = new Attribute();
$model->sort_order = 0;
$model->cat_id = 0;
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
if (GoodsManager::updateAttribute($model)) {
return $this->redirect(['index']);
}
}
return $this->render('create', [
'model' => $model,
]);
}
/**
* Updates an existing Attribute model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id
* @return mixed
* @throws NotFoundHttpException if the model cannot be found
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
if (GoodsManager::updateAttribute($model)) {
return $this->redirect(['index']);
}
}
return $this->render('update', [
'model' => $model,
]);
}
/**
* Deletes an existing Attribute model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* @param integer $id
* @return mixed
* @throws NotFoundHttpException if the model cannot be found
*/
public function actionDelete($id)
{
$model = $this->findModel($id);
$model->is_delete = Attribute::IS_DELETE_YES;
$model->save();
return $this->redirect(['index']);
}
/**
* Finds the Attribute model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $id
* @return Attribute the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Attribute::findOne($id)) !== null) {
return $model;
}
throw new NotFoundHttpException('The requested page does not exist.');
}
/**
* @author iron
* 文件导出
*/
public function actionExport()
{
$searchModel = new AttributeSearch();
$params = Yii::$app->request->queryParams;
if ($params['page-type'] == 'all') {
$dataProvider = $searchModel->allData($params);
} else {
$dataProvider = $searchModel->search($params);
}
Excel::export([
'models' => $dataProvider->getModels(),
'format' => 'Xlsx',
'asAttachment' => true,
'fileName' =>'Attributes'. "-" .date('Y-m-d H/i/s', time()),
'columns' => $searchModel->columns()
]);
}
}

152
backend/modules/goods/controllers/BrandController.php

@ -1,152 +0,0 @@
<?php
namespace backend\modules\goods\controllers;
use Yii;
use backend\modules\goods\models\ars\Brand;
use backend\modules\goods\models\searchs\BrandSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use iron\widget\Excel;
/**
* BrandController implements the CRUD actions for Brand model.
*/
class BrandController extends Controller
{
/**
* {@inheritdoc}
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
/**
* Lists all Brand models.
* @return mixed
*/
public function actionIndex()
{
$searchModel = new BrandSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'columns' => $searchModel->columns()
]);
}
/**
* Displays a single Brand model.
* @param integer $id
* @return mixed
* @throws NotFoundHttpException if the model cannot be found
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new Brand model.
* If creation is successful, the browser will be redirected to the 'view' page.
* @return mixed
*/
public function actionCreate()
{
$model = new Brand();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect('index');
}
return $this->render('create', [
'model' => $model,
]);
}
/**
* Updates an existing Brand model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id
* @return mixed
* @throws NotFoundHttpException if the model cannot be found
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect('index');
}
return $this->render('update', [
'model' => $model,
]);
}
/**
* Deletes an existing Brand model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* @param integer $id
* @return mixed
* @throws NotFoundHttpException if the model cannot be found
*/
public function actionDelete($id)
{
$model = $this->findModel($id);
$model->is_delete = Brand::IS_DELETE_YES;
$model->save();
return $this->redirect(['index']);
}
/**
* Finds the Brand model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $id
* @return Brand the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Brand::findOne($id)) !== null) {
return $model;
}
throw new NotFoundHttpException('The requested page does not exist.');
}
/**
* @author iron
* 文件导出
*/
public function actionExport()
{
$searchModel = new BrandSearch();
$params = Yii::$app->request->queryParams;
if ($params['page-type'] == 'all') {
$dataProvider = $searchModel->allData($params);
} else {
$dataProvider = $searchModel->search($params);
}
Excel::export([
'models' => $dataProvider->getModels(),
'format' => 'Xlsx',
'asAttachment' => true,
'fileName' =>'Brands'. "-" .date('Y-m-d H/i/s', time()),
'columns' => $searchModel->columns()
]);
}
}

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

@ -1,211 +0,0 @@
<?php
namespace backend\modules\goods\controllers;
use backend\modules\file\models\ars\File;
use Exception;
use Yii;
use backend\modules\goods\models\ars\Category;
use backend\modules\goods\models\searchs\CategorySearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use backend\modules\file\logic\file\FileManager;
use yii\web\Response;
use iron\widget\Excel;
/**
* CategoryController implements the CRUD actions for Category model.
*/
class CategoryController extends Controller
{
/**
* {@inheritdoc}
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
public function actions()
{
return [
'upload' => [
'class' => 'iron\actions\UploadAction',
'path' => 'xls/',
'maxSize' => 20480,
]
];
}
/**
* Lists all Category models.
* @return mixed
*/
public function actionIndex()
{
$searchModel = new CategorySearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'columns' => $searchModel->columns()
]);
}
/**
* Displays a single Category model.
* @param integer $id
* @return mixed
* @throws NotFoundHttpException if the model cannot be found
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* @return string|Response
* @throws Exception
*/
public function actionCreate()
{
$model = new Category();
$model->is_show = Category::IS_SHOW_DISPLAY;
$model->sort_order = 0;
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
//类目图片上传保存处理
$res = FileManager::saveFileInModel($model, 'iconImageId', '', File::OWN_TYPE_CATEGORY_ICON, 'icon');
if ($res) {
return $this->redirect('index');
}
}
return $this->render('create', [
'model' => $model,
]);
}
/**
* Updates an existing Category model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id
* @return mixed
* @throws NotFoundHttpException if the model cannot be found
* @throws Exception
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
$model->iconImageId = $model->icon;
//记录已保存的类目图片id,用于修改
$icon_image_old_id_arr = $model->icon;
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
//类目图片上传保存处理
$res = FileManager::saveFileInModel($model, 'iconImageId', $icon_image_old_id_arr, File::OWN_TYPE_CATEGORY_ICON, 'icon');
if ($res) {
return $this->redirect('index');
}
}
return $this->render('update', [
'model' => $model,
]);
}
/**
* Deletes an existing Category model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* @param integer $id
* @return mixed
* @throws NotFoundHttpException if the model cannot be found
*/
public function actionDelete($id)
{
$model = $this->findModel($id);
$model->is_delete = Category::IS_DELETE_YES;
$model->save();
return $this->redirect(['index']);
}
/**
* Finds the Category model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $id
* @return Category the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Category::findOne($id)) !== null) {
return $model;
}
throw new NotFoundHttpException('The requested page does not exist.');
}
/**
* @author iron
* 文件导出
*/
public function actionExport()
{
$searchModel = new CategorySearch();
$params = Yii::$app->request->queryParams;
if ($params['page-type'] == 'all') {
$dataProvider = $searchModel->allData($params);
} else {
$dataProvider = $searchModel->search($params);
}
Excel::export([
'models' => $dataProvider->getModels(),
'format' => 'Xlsx',
'asAttachment' => true,
'fileName' =>'Categories'. "-" .date('Y-m-d H/i/s', time()),
'columns' => $searchModel->columns()
]);
}
/**
* 处理文件上传成功后回调保存到临时文件表中,并返回临时文件id
*/
public function actionSaveFile()
{
$data = Yii::$app->request->get('data');
$fileName = Yii::$app->request->get('fileName')[0];
if ($data['status'] == true) {
return FileManager::saveTemFile($fileName, $data);
}
return false;
}
/**
* @return string
* 点击删除按钮时同时删除字符串中的id
*/
public function actionImgIdDel()
{
$data = Yii::$app->request->get();
return FileManager::dealFileIdStrInDel($data);
}
/**
* @return bool|false|string
* 加载已有的文件
*/
public function actionImageFile()
{
$fileIdStr = Yii::$app->request->get('fileIdStr');
return FileManager::loadExitFile($fileIdStr);
}
}

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

@ -1,310 +0,0 @@
<?php
namespace backend\modules\goods\controllers;
use backend\modules\file\logic\file\FileManager;
use backend\modules\goods\models\ars\FilterAttr;
use backend\modules\goods\models\ars\GoodsAttr;
use backend\modules\shop\logic\ShopManager;
use Exception;
use Throwable;
use Yii;
use backend\modules\goods\models\ars\Goods;
use backend\modules\goods\models\searchs\GoodsSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use backend\modules\goods\logic\goods\GoodsManager;
use backend\modules\file\models\ars\File;
use backend\modules\goods\models\ars\Attribute;
use iron\widget\Excel;
/**
* GoodsController implements the CRUD actions for Goods model.
*/
class GoodsController extends Controller
{
/**
* {@inheritdoc}
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
public function actions()
{
return [
'upload' => [
'class' => 'iron\actions\UploadAction',
'path' => 'xls/',
'maxSize' => 20480,
],
'ueditor' => [
'class' => 'common\widgets\ueditor\UeditorAction',
'config' => [
//上传图片配置
'imageUrlPrefix' => "", /* 图片访问路径前缀 */
'imagePathFormat' => "/uploads/origin/introduce/" . md5(time() . rand(000, 999)), /* 上传保存路径,可以自定义保存路径和文件名格式 */
]
],
];
}
/**
* Lists all Goods models.
* @return mixed
*/
public function actionIndex()
{
$searchModel = new GoodsSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'columns' => $searchModel->columns()
]);
}
/**
* Displays a single Goods model.
* @param integer $id
* @return mixed
* @throws NotFoundHttpException if the model cannot be found
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new Goods model.
* If creation is successful, the browser will be redirected to the 'view' page.
* @return mixed
* @throws Exception
*/
public function actionCreate()
{
$model = new Goods();
$model->is_sale = Goods::IS_SALE_YES;
$model->stock = -1;
$model->is_taking = Goods::IS_TAKING_NO;
$model->is_express = Goods::IS_EXPRESS_YES;
$model->express_type = Goods::EXPRESS_TYPE_EXPRESS_TEMPLATE;
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
//商品封面图和商品详情图上传保存处理
$res = GoodsManager::updateGoods(Yii::$app->request->post(), $model);
if ($res) {
return $this->redirect('index');
}
}
return $this->render('create', [
'model' => $model,
]);
}
/**
* Updates an existing Goods model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id
* @return mixed
* @throws NotFoundHttpException if the model cannot be found
* @throws Exception
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
$model->coverImageId = $model->image;
$model->detailImageId = implode(',', File::find()->select('id')->where(['is_delete' => File::IS_DELETE_NO, 'own_id' => $model->id, 'own_type' => File::OWN_TYPE_GOODS_DETAILS])->column());
//记录已保存的商品图片id,用于修改
$cover_image_old_id_str = $model->image;
$detail_image_old_id_str = $model->detailImageId;
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
//商品封面图和商品详情图上传保存处理
$res = GoodsManager::updateGoods(Yii::$app->request->post(), $model, $cover_image_old_id_str, $detail_image_old_id_str);
if ($res) {
return $this->redirect('index');
}
}
$model->uniform_postage /= ShopManager::proportionalConversion(ShopManager::UNIT_TYPE_MONEY);
$model->market_price /= ShopManager::proportionalConversion(ShopManager::UNIT_TYPE_MONEY);
$model->price /= ShopManager::proportionalConversion(ShopManager::UNIT_TYPE_MONEY);
$goodsAttributes = GoodsAttr::find()->where(['goods_id' => $id, 'is_delete' => GoodsAttr::IS_DELETE_NO])->andWhere(['!=', 'attr_id', 0])->all();
$attributeModel = GoodsManager::getAttribute($goodsAttributes);
$checkAttr = GoodsManager::getSkuInfo($id);
$goodsFilterAttributes = FilterAttr::find()->where(['goods_id' => $id, 'is_delete' => FilterAttr::IS_DELETE_NO])->andWhere(['!=', 'attr_id', 0])->all();
$filterAttributeModel = GoodsManager::getAttribute($goodsFilterAttributes);
$judgeGoodsCategory = GoodsManager::judgeGoodsCategory($model);
return $this->render('update', [
'model' => $model,
'attributeModel' => $attributeModel,
'attrValue' => $checkAttr,
'filterAttributeModel' => $filterAttributeModel,
'judgeGoodsCategory' => $judgeGoodsCategory,
]);
}
/**
* Deletes an existing Goods model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* @param integer $id
* @return mixed
* @throws NotFoundHttpException if the model cannot be found
*/
public function actionDelete($id)
{
$model = $this->findModel($id);
$model->is_delete = Goods::IS_DELETE_YES;
$model->save();
return $this->redirect(['index']);
}
/**
* Finds the Goods model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $id
* @return Goods the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Goods::findOne($id)) !== null) {
return $model;
}
throw new NotFoundHttpException('The requested page does not exist.');
}
/**
* @author iron
* 文件导出
*/
public function actionExport()
{
$searchModel = new GoodsSearch();
$params = Yii::$app->request->queryParams;
if ($params['page-type'] == 'all') {
$dataProvider = $searchModel->allData($params);
} else {
$dataProvider = $searchModel->search($params);
}
Excel::export([
'models' => $dataProvider->getModels(),
'format' => 'Xlsx',
'asAttachment' => true,
'fileName' =>'Goods'. "-" .date('Y-m-d H/i/s', time()),
'columns' => $searchModel->columns()
]);
}
/**
* 处理文件上传成功后回调保存到临时文件表中,并返回临时文件id
*/
public function actionSaveFile()
{
$data = Yii::$app->request->get('data');
$fileName = Yii::$app->request->get('fileName')[0];
if ($data['status'] == true) {
return FileManager::saveTemFile($fileName, $data);
}
return false;
}
/**
* @return string
* 点击删除按钮时同时删除字符串中的id
*/
public function actionImgIdDel()
{
$data = Yii::$app->request->get();
return FileManager::dealFileIdStrInDel($data);
}
/**
* @return bool|false|string
* 加载已有的文件
*/
public function actionImageFile()
{
$fileIdStr = Yii::$app->request->get('fileIdStr');
return FileManager::loadExitFile($fileIdStr);
}
/**
* @param $id
* @return string
* 商品编辑sku
*/
public function actionEditSku($id)
{
$sku = GoodsManager::getCreatedSku($id);
$attributes = GoodsManager::getAttrs($id);
return $this->render('sku_edit', [
'attributes' => $attributes,
'sku' => $sku,]);
}
/**
* @return array
* @throws Throwable
* 添加sku
*/
public function actionAddSku()
{
$data = [];
Yii::$app->response->format = 'json';
$res = Yii::$app->request->post('sku');
$goodsId = Yii::$app->request->post('goodsId');
$tra = Yii::$app->db->beginTransaction();
try {
$data['originalIds'] = GoodsManager::getOriginalIds($res['type'], $goodsId);
$data['acceptIds'] = [];
foreach ($res['data'] as $sku) {
GoodsManager::AddOrUpdateData($sku, $res['type'], $goodsId);
if ($sku['id'] > 0) {
$data['acceptIds'][] = $sku['id'];
}
}
GoodsManager::deleteSku($res['type'], $data, $goodsId);
$tra->commit();
return ['status' => true];
} catch (Exception $e) {
$tra->rollBack();
return ['status' => false, 'info' => $e->getMessage()];
}
}
public function actionSwitch()
{
Yii::$app->response->format = 'json';
$data = [];
$type = Yii::$app->request->get('type');
$id = Yii::$app->request->get('goodsId');
$data['sku'] = GoodsManager::getCreatedSku($id, $type);
$data['attributes'] = GoodsManager::getAttrs($id);
return $data;
}
/**
* @return false|string
* 根据商品分类获取商品属性
*/
public function actionFilterAttribute()
{
$catId = Yii::$app->request->get('catId')??0;
$allAttr = Attribute::find()->where(['type' => Attribute::TYPE_ATTR, 'is_delete' => Attribute::IS_DELETE_NO])->andWhere(['cat_id' => [0,$catId]])->asArray()->all();
return json_encode($allAttr);
}
}

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

@ -1,213 +0,0 @@
<?php
namespace backend\modules\goods\controllers;
use backend\modules\file\logic\file\FileManager;
use backend\modules\file\models\ars\File;
use Exception;
use Yii;
use backend\modules\goods\models\ars\ShopCategory;
use backend\modules\goods\models\searchs\ShopCategorySearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use iron\widget\Excel;
/**
* ShopcategoryController implements the CRUD actions for ShopCategory model.
*/
class ShopCategoryController extends Controller
{
/**
* {@inheritdoc}
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
public function actions()
{
return [
'upload' => [
'class' => 'iron\actions\UploadAction',
'path' => 'xls/',
'maxSize' => 20480,
]
];
}
/**
* Lists all ShopCategory models.
* @return mixed
*/
public function actionIndex()
{
$searchModel = new ShopCategorySearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'columns' => $searchModel->columns()
]);
}
/**
* Displays a single ShopCategory model.
* @param integer $id
* @return mixed
* @throws NotFoundHttpException if the model cannot be found
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new ShopCategory model.
* If creation is successful, the browser will be redirected to the 'view' page.
* @return mixed
* @throws Exception
*/
public function actionCreate()
{
$model = new ShopCategory();
$model->is_show = ShopCategory::IS_SHOW_HIDE;
$model->sort_order = 0;
if ($model->load(Yii::$app->request->post())) {
//类目图片上传保存处理
$res = FileManager::saveFileInModel($model, 'iconImageId', '', File::OWN_TYPE_CATEGORY_ICON, 'icon');
if ($res) {
return $this->redirect('index');
}
}
return $this->render('create', [
'model' => $model,
]);
}
/**
* Updates an existing ShopCategory model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id
* @return mixed
* @throws NotFoundHttpException if the model cannot be found
* @throws Exception
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->filter_attr != null) {
$model->filter_attr = explode(',', $model->filter_attr);
}
$model->iconImageId = $model->icon;
$icon_image_old_id_arr = $model->icon;//记录已保存的类目图片id,用于修改
if ($model->load(Yii::$app->request->post())) {
//类目图片上传保存处理
$res = FileManager::saveFileInModel($model, 'iconImageId', $icon_image_old_id_arr, File::OWN_TYPE_CATEGORY_ICON, 'icon');
if ($res) {
return $this->redirect('index');
}
}
return $this->render('update', [
'model' => $model,
]);
}
/**
* Deletes an existing ShopCategory model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* @param integer $id
* @return mixed
* @throws NotFoundHttpException if the model cannot be found
*/
public function actionDelete($id)
{
$model = $this->findModel($id);
$model->is_delete = ShopCategory::IS_DELETE_YES;
$model->save();
return $this->redirect(['index']);
}
/**
* Finds the ShopCategory model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $id
* @return ShopCategory the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = ShopCategory::findOne($id)) !== null) {
return $model;
}
throw new NotFoundHttpException('The requested page does not exist.');
}
/**
* @author iron
* 文件导出
*/
public function actionExport()
{
$searchModel = new ShopCategorySearch();
$params = Yii::$app->request->queryParams;
if ($params['page-type'] == 'all') {
$dataProvider = $searchModel->allData($params);
} else {
$dataProvider = $searchModel->search($params);
}
Excel::export([
'models' => $dataProvider->getModels(),
'format' => 'Xlsx',
'asAttachment' => true,
'fileName' =>'Shop Categories'. "-" .date('Y-m-d H/i/s', time()),
'columns' => $searchModel->columns()
]);
}
/**
* 处理文件上传成功后回调保存到临时文件表中,并返回临时文件id
*/
public function actionSaveFile()
{
$data = Yii::$app->request->get('data');
$fileName = Yii::$app->request->get('fileName')[0];
if ($data['status'] == true) {
return FileManager::saveTemFile($fileName, $data);
}
return false;
}
/**
* @return string
* 点击删除按钮时同时删除字符串中的id
*/
public function actionImgIdDel()
{
$data = Yii::$app->request->get();
return FileManager::dealFileIdStrInDel($data);
}
/**
* @return bool|false|string
* 加载已有的文件
*/
public function actionImageFile()
{
$fileIdStr = Yii::$app->request->get('fileIdStr');
return FileManager::loadExitFile($fileIdStr);
}
}

152
backend/modules/goods/controllers/SupplierController.php

@ -1,152 +0,0 @@
<?php
namespace backend\modules\goods\controllers;
use Yii;
use backend\modules\goods\models\ars\Supplier;
use backend\modules\goods\models\searchs\SupplierSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use iron\widget\Excel;
/**
* SupplierController implements the CRUD actions for Supplier model.
*/
class SupplierController extends Controller
{
/**
* {@inheritdoc}
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
/**
* Lists all Supplier models.
* @return mixed
*/
public function actionIndex()
{
$searchModel = new SupplierSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'columns' => $searchModel->columns()
]);
}
/**
* Displays a single Supplier model.
* @param integer $id
* @return mixed
* @throws NotFoundHttpException if the model cannot be found
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new Supplier model.
* If creation is successful, the browser will be redirected to the 'view' page.
* @return mixed
*/
public function actionCreate()
{
$model = new Supplier();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect('index');
}
return $this->render('create', [
'model' => $model,
]);
}
/**
* Updates an existing Supplier model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id
* @return mixed
* @throws NotFoundHttpException if the model cannot be found
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect('index');
}
return $this->render('update', [
'model' => $model,
]);
}
/**
* Deletes an existing Supplier model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* @param integer $id
* @return mixed
* @throws NotFoundHttpException if the model cannot be found
*/
public function actionDelete($id)
{
$model = $this->findModel($id);
$model->is_delete = Supplier::IS_DELETE_YES;
$model->save();
return $this->redirect(['index']);
}
/**
* Finds the Supplier model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $id
* @return Supplier the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Supplier::findOne($id)) !== null) {
return $model;
}
throw new NotFoundHttpException('The requested page does not exist.');
}
/**
* @author iron
* 文件导出
*/
public function actionExport()
{
$searchModel = new SupplierSearch();
$params = Yii::$app->request->queryParams;
if ($params['page-type'] == 'all') {
$dataProvider = $searchModel->allData($params);
} else {
$dataProvider = $searchModel->search($params);
}
Excel::export([
'models' => $dataProvider->getModels(),
'format' => 'Xlsx',
'asAttachment' => true,
'fileName' =>'Suppliers'. "-" .date('Y-m-d H/i/s', time()),
'columns' => $searchModel->columns()
]);
}
}

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

@ -1,651 +0,0 @@
<?php
namespace backend\modules\goods\logic\goods;
use backend\modules\file\models\ars\File;
use backend\modules\goods\models\ars\Category;
use backend\modules\goods\models\ars\ShopCategory;
use Throwable;
use Yii;
use yii\db\Exception;
use backend\modules\goods\models\ars\GoodsAttr;
use backend\modules\goods\models\ars\Attribute;
use backend\modules\goods\models\ars\GoodsSku;
use backend\modules\goods\models\ars\Goods;
use backend\modules\goods\models\ars\FilterAttr;
use yii\db\StaleObjectException;
use backend\modules\file\logic\file\FileManager;
use yii\web\ServerErrorHttpException;
use backend\modules\shop\logic\ShopManager;
class GoodsManager
{
/**
* @param $newFileIdArr
* @param $hostObject
* @param array $oldFileIdArr
* @param int $fileType
* @return array
* @throws \Exception
* 保存新文件,删除不需要的文件操作
*/
public static function saveFile($newFileIdArr, $hostObject, $oldFileIdArr = [], $fileType = File::OWN_TYPE_GOODS_INDEX)
{
$tra = Yii::$app->db->beginTransaction();
try {
//需要新建的文件id
$createFileIdArr = array_diff($newFileIdArr, $oldFileIdArr);
//创建文件
$class = new FileManager();
$createFileRes = $class->saveTemFileToFile($createFileIdArr, $hostObject->id, $fileType);
//需要删除的文件id
$delFileIdArr = array_diff($oldFileIdArr, $newFileIdArr);
//删除文件
$class->deleteFile($delFileIdArr);
//记录第一张图片id
$firstFileId = 0;
//查看修改数组是否为空
if (!$newFileIdArr[0]) {
$firstFileId = null;
} else {
if ($createFileRes['status']) {
$firstFileId = $createFileRes['first_file_id'];
}
}
$tra->commit();
return ['status' => true, 'info' => '操作成功', 'first_file_id' => $firstFileId];
} catch (Exception $e) {
$tra->rollBack();
throw new ServerErrorHttpException($e->getMessage());
}
}
/**
* @param $formData
* @param Goods|$goodsModel
* @param null $coverImageOldIdStr
* @param null $detailImageOldIdStr
* @return bool
* @throws \Exception 创建修改商品操作
*/
public static function updateGoods($formData, $goodsModel, $coverImageOldIdStr = null, $detailImageOldIdStr = null)
{
$attribute = $formData['attribute'];
$filterAttribute = $formData['filterattribute'];
$goodsModel->uniform_postage *= ShopManager::proportionalConversion(ShopManager::UNIT_TYPE_MONEY);
$goodsModel->market_price *= ShopManager::proportionalConversion(ShopManager::UNIT_TYPE_MONEY);
$goodsModel->price *= ShopManager::proportionalConversion(ShopManager::UNIT_TYPE_MONEY);
$tra = Yii::$app->db->beginTransaction();
try {
FileManager::saveFileInModel($goodsModel, 'coverImageId', $coverImageOldIdStr, File::OWN_TYPE_GOODS_INDEX, 'image');
FileManager::saveFileInModel($goodsModel, 'detailImageId', $detailImageOldIdStr, File::OWN_TYPE_GOODS_DETAILS);
self::addAttributeOperating(['id' => $goodsModel->id, 'attribute' => $attribute]);
self::addFilterAttributeOperating(['id' => $goodsModel->id, 'filterAttribute' => $filterAttribute]);
$tra->commit();
return true;
} catch (\yii\base\Exception $e) {
$tra->rollBack();
throw new \Exception($e->getMessage());
}
}
/**
* @param $data
* @return bool
* @throws \Exception
* 创建修改商品属性操作
*/
private static function addAttributeOperating($data)
{
$tra = Yii::$app->db->beginTransaction();
try {
if (!$data['attribute']) {
$tra->commit();
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->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) {
$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
* @throws \Exception
* 删除商品属性
*/
private static function delAttribute($goodsAttr)
{
foreach ($goodsAttr as $key => $value) {
$value->is_delete = GoodsAttr::IS_DELETE_YES;
if (!$value->save()) {
throw new \Exception('goods attribute delete false');
}
}
}
/**
* @param $attribute
* @param $goodsId
* @return array
* @throws \Exception
* 保存商品属性
*/
private static function addAttribute($attribute, $goodsId)
{
$newAttr = [];
if (!$attribute) {
return [];
}
foreach ($attribute as $value) {
foreach ($value['value'] as $k => $v) {
$goodsAttrModel = new GoodsAttr();
$goodsAttrModel->attr_id = $value['id'];
$attr = GoodsAttr::find()->where(['goods_id' => $goodsId, 'attr_id' => $value['id'], 'attr_value' => $v, 'is_delete' => GoodsAttr::IS_DELETE_NO])->one();
if ($attr) {
$newAttr[$attr->id] = $attr->attr_value; //原有的数据
} else {
$goodsAttrModel->goods_id = $goodsId;
$goodsAttrModel->attr_value = $v;
if (!$goodsAttrModel->save()) {
throw new \Exception('goodsAttribute save false');
}
$newAttr[$goodsAttrModel->id] = $goodsAttrModel->attr_value; //新增的数据
}
}
}
return $newAttr;
}
/**
* @param $attributes
* @return array
* 获取属性信息
*/
public static function getAttribute($attributes)
{
$filter = array();
$attributeModel = array();
if (!$attributes) {
return $attributeModel;
}
foreach ($attributes as $key => $value) {
$attribute = Attribute::findOne($value->attr_id);
if (!in_array($attribute->name, $filter)) {
$filter[] = $attribute->name;
$attribute = ['name' => $attribute->name, 'id' => $attribute->id, 'value' => [$value->attr_value]];
$attributeModel[] = $attribute;
} else {
foreach ($attributeModel as $k => $v) {
if ($v['name'] == $attribute->name) {
$attributeModel[$k]['value'][] = $value->attr_value;
}
}
}
}
return $attributeModel;
}
/**
* @param $id
* @return array
* 获取sku信息
*/
public static function getSkuInfo($id)
{
$skus = GoodsSku::find()->where(['goods_id' => $id, 'is_delete' => GoodsSku::IS_DELETE_NO])->all();
$attrId = [];
foreach ($skus as $sku) {
$attrId = array_merge(explode(',', $sku->goods_attr), $attrId);
}
$attrs = GoodsAttr::find()->where(['id' => $attrId, 'is_delete' => GoodsAttr::IS_DELETE_NO])->andWhere(['!=', 'attr_id', 0])->all();
$checkAttr = [];
$filterAttr = [];
foreach ($attrs as $value) {
$attr = Attribute::findOne(['id' => $value->attr_id, 'is_delete' => Attribute::IS_DELETE_NO]);
if (!in_array($attr->name, $filterAttr)) {
$filterAttr[] = $attr->name;
$newAttr = ['id' => $attr->id, 'name' => $attr->name, 'value' => [$value->attr_value]];
$checkAttr[] = $newAttr;
} else {
foreach ($checkAttr as $key => $item) {
if ($item['name'] == $attr->name) { //如果attr_id与$filter的attr_id相符,入栈
$checkAttr[$key]['value'][] = $value->attr_value;
}
}
}
}
return $checkAttr;
}
/**
* @param $id
* @param int $type
* @return mixed
* 已创建sku信息
*/
public static function getCreatedSku($id, $type = 0)
{
$goods = Goods::findOne($id);
$data['type'] = $type ?: $goods->sku_mode;
$data['data'] = [];
if ($data['type'] == Goods::SKU_MODE_ATTR) {
$sku = GoodsSku::find()
->where(['goods_id' => $id, 'is_manual' => 0])
->all();
} else {
$sku = GoodsSku::find()
->where(['goods_id' => $id, 'is_manual' => 1])
->all();
}
foreach ($sku as $value) {
$data['data'][] = self::getAttrInfo($data['type'], $value);
}
return $data;
}
/**
* @param $type
* @param $sku
* @return array
* 获取商品详情
*/
public static function getAttrInfo($type, $sku)
{
$data = [];
if ($type == Goods::SKU_MODE_ATTR) {
$data['value'] = array_filter(explode(',', $sku->goods_attr));
} else {
$attr = explode(',', $sku->goods_attr);
$goodsAttr = GoodsAttr::findOne($attr[0]);
$data['value'] = $goodsAttr->attr_value;
}
$data['id'] = $sku->id;
$data['price'] = $sku->price;
$data['stock'] = $sku->stock;
$data['weight'] = $sku->weight/ShopManager::proportionalConversion(ShopManager::UNIT_TYPE_WEIGHT);
return $data;
}
/**
* @param $id
* @return array
* 获取商品属性
*/
public static function getAttrs($id)
{
$attrId = GoodsAttr::find()->where(['goods_id' => $id, 'is_delete' => GoodsAttr::IS_DELETE_NO])
->andWhere(['>', 'attr_id', 0])
->select('attr_id')
->distinct()
->all();
$attributes = [];
foreach ($attrId as $v) {
$attribute = Attribute::findOne($v);
if ($attribute && $attribute->type == Attribute::TYPE_ATTR) {
$ret['name'] = $attribute->name;
$ret['id'] = $attribute->id;
$ret['attrValue'] = GoodsAttr::find()
->select(['id', 'attr_value'])
->where(['goods_id' => $id, 'is_delete' => GoodsAttr::IS_DELETE_NO])
->andWhere(['attr_id' => $attribute->id])
->asArray()
->all();
$attributes[] = $ret;
}
}
return $attributes;
}
/**
* @param $type
* @param $goodsId
* @return array
* 获取已存储的商品sku的id
*/
public static function getOriginalIds($type, $goodsId)
{
$ids = [];
if ($type == Goods::SKU_MODE_MANUAL) {
$query = GoodsSku::find()
->where(['is_manual' => 1]);
} else {
$query = GoodsSku::find()
->where(['is_manual' => 0]);
}
$sku = $query
->andWhere(['goods_id' => $goodsId])
->all();
foreach ($sku as $value) {
$ids[] = $value->id;
}
return $ids;
}
/**
* @param $sku
* @param $type
* @param $goodsId
* @throws \Exception
* 添加或更新sku数据
*/
public static function AddOrUpdateData($sku, $type, $goodsId)
{
$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();
}
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_manual = 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']*1000;
$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类型修改失败');
}
$tra->commit();
} catch (\Exception $e) {
$tra->rollBack();
throw new \Exception($e->getMessage());
}
}
/**
* @param $type
* @param $data
* @param $goodsId
* @return bool
* @throws Throwable
* @throws StaleObjectException
* 删除sku
*/
public static function deleteSku($type, $data, $goodsId)
{
if (!$data['originalIds']) {
return true;
}
if ($type == Goods::SKU_MODE_MANUAL) {
$query = GoodsSku::find()
->where(['is_manual' => 1]);
} else {
$query = GoodsSku::find()
->where(['is_manual' => 0]);
}
$sku = $query
->andWhere(['goods_id' => $goodsId])
->andWhere(['in', 'id', $data['originalIds']])
->andWhere(['not in', 'id', $data['acceptIds']])
->all();
foreach ($sku as $value) {
$value->delete();
}
return true;
}
/**
* @param $data
* @return bool
* @throws \Exception
* 创建修改商品筛选属性操作
*/
private static function addFilterAttributeOperating($data)
{
if (!$data['filterAttribute']) {
return true;
}
$data['filterAttribute'] = json_decode($data['filterAttribute'], true);
$oldFilterAttr = [];
$goodsFilterAttr = FilterAttr::find()->where(['goods_id' => $data['id'], 'is_delete' => FilterAttr::IS_DELETE_NO])->all();
if ($goodsFilterAttr) { //如果商品有旧的属性
if(count($data['filterAttribute']) == 0 && is_array($data['filterAttribute'])) { //如果传上来的是空数组,删除该商品下的全部属性
self::delFilterAttribute($goodsFilterAttr);
return true;
}
foreach ($goodsFilterAttr as $key => $value) { //把旧的商品属性保存到一个数组
$oldFilterAttr[$value->id] = $value->attr_value;
}
}
$newAttr = self::addFilterAttribute($data['filterAttribute'], $data['id']); //添加新的商品属性
$delAttr = array_diff(array_keys($oldFilterAttr), array_keys($newAttr)); //找出需要删除的goodsAttrId
if (!$delAttr) {
return true;
}
foreach ($delAttr as $value) {
$model = FilterAttr::find()->where(['id' => $value, 'is_delete' => FilterAttr::IS_DELETE_NO])->One();
if ($model) {
$model->is_delete = FilterAttr::IS_DELETE_YES;
if (!$model->save()) {
throw new \Exception('goodsAttribute delete false');
}
}
}
return true;
}
/**
* @param $goodsFilterAttr
* @throws \Exception
* 删除商品筛选属性
*/
private static function delFilterAttribute($goodsFilterAttr)
{
foreach ($goodsFilterAttr as $key => $value) {
$value->is_delete = FilterAttr::IS_DELETE_YES;
if (!$value->save()) {
throw new \Exception('goods attribute delete false');
}
}
}
/**
* @param $attribute
* @param $goodsId
* @return array
* @throws \Exception
* 保存商品筛选属性
*/
private static function addFilterAttribute($attribute, $goodsId)
{
$newAttr = [];
if (!$attribute) {
return [];
}
foreach ($attribute as $value) {
foreach ($value['value'] as $k => $v) {
$goodsFilterAttrModel = new FilterAttr();
$goodsFilterAttrModel->attr_id = $value['id'];
$attr = FilterAttr::find()->where(['goods_id' => $goodsId, 'attr_id' => $value['id'], 'attr_value' => $v, 'is_delete' => FilterAttr::IS_DELETE_NO])->one();
if ($attr) {
$newAttr[$attr->id] = $attr->attr_value; //原有的数据
} else {
$goodsFilterAttrModel->goods_id = $goodsId;
$goodsFilterAttrModel->attr_value = $v;
if (!$goodsFilterAttrModel->save()) {
throw new \Exception('goodsAttribute save false');
}
$newAttr[$goodsFilterAttrModel->id] = $goodsFilterAttrModel->attr_value; //新增的数据
}
}
}
return $newAttr;
}
/**
* @param $goodsModel
* @return bool
* 判断该商品的sku是否存在已选属性,存在则返回true,表示不得删除
*/
public static function judgeGoodsCategory($goodsModel)
{
$skus = GoodsSku::find()->where(['goods_id' => $goodsModel->id, 'is_delete' => GoodsSku::IS_DELETE_NO])->all();
$attrId = [];
foreach ($skus as $sku) {
$attrId = array_merge(explode(',', $sku->goods_attr), $attrId);
}
$goodsAttr = array_unique(GoodsAttr::find()->select(['attr_id'])->where(['id' => $attrId, 'is_delete' => GoodsAttr::IS_DELETE_NO])->andWhere(['!=', 'attr_id', 0])->column());
$attrArr = array_unique(Attribute::find()->select(['cat_id'])->where(['is_delete' => Attribute::IS_DELETE_NO, 'id' => $goodsAttr])->column());
if (in_array($goodsModel->cat_id, $attrArr)) {
return true; //存在,则返回true,表示后台分类不得修改
}
return false; //否则返回false,表示后台分类可以修改
}
/**
* @param Attribute|$attrModel
* @return bool
* 编辑规格属性
*/
public static function updateAttribute($attrModel)
{
$attrModel->value = str_replace(',', ',', $attrModel->value);
$attrValue = explode(',', $attrModel->value);
if (count($attrValue) != count(array_unique($attrValue))) {
Yii::$app->getSession()->setFlash('error', '不能有相同的属性值');
return false;
}
if (!$attrModel->save()) {
Yii::$app->getSession()->setFlash('error', '保存失败');
return false;
}
return true;
}
/**
* 根据pid的父级关系,给字段|___做层级标记
* @param $data
* @param int $pid
* @param int $lev
* @return array
*/
public static function btree($data, $pid = 0, $lev = 0)
{
$tree = [];
foreach ($data as $k => $value) {
if ($value['pid'] == $pid) {
$value['name'] = str_repeat('|___', $lev) . $value['name'];
$tree[] = $value;
$tree = array_merge($tree, self::btree($data, $value['id'], $lev + 1));
}
}
return $tree;
}
/**
* 构建下拉数组
* @param $dataArr
* @param int $needDefault
* @return array
*/
public static function constructDropList($dataArr, $needDefault = 1)
{
$data = [];
if ($needDefault) {
$data[0] = '一级分类';
}
foreach ($dataArr as $k => $v) {
$data[$v['id']] = $v['name'];
}
return $data;
}
/**
* 获取分类中所有下级id
* @param int $ownId
* @param array $idArr
* @return array
*/
public static function subCategoryId($ownId = 0, $idArr = [])
{
$idArr[] = $ownId;
if ($ownId) {
$subCategoryModel = Category::find()->where(['pid' => $ownId])->all();
if ($subCategoryModel) {
foreach ($subCategoryModel as $subCategory) {
$idArr = self::subCategoryId($subCategory->id, $idArr);
}
}
}
return $idArr;
}
/**
* 获取分类中所有下级id
* @param int $ownId
* @param array $idArr
* @return array
*/
public static function subShopCategoryId($ownId = 0, $idArr = [])
{
$idArr[] = $ownId;
if ($ownId) {
$subShopCategoryModel = ShopCategory::find()->where(['pid' => $ownId])->all();
if ($subShopCategoryModel) {
foreach ($subShopCategoryModel as $subShopCategory) {
$idArr = self::subShopCategoryId($subShopCategory->id, $idArr);
}
}
}
return $idArr;
}
}

42
backend/modules/goods/migrations/m191119_021851_create_table_atg_shop_category.php

@ -1,42 +0,0 @@
<?php
use yii\db\Migration;
/**
* Class m191119_021851_create_table_atg_shop_category
*/
class m191119_021851_create_table_atg_shop_category extends Migration
{
/**
* {@inheritdoc}
*/
public function up()
{
$tableOptions = 'CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE=InnoDB COMMENT="前端商品类别表"';
$this->createTable('atg_shop_category', [
'id' => $this->primaryKey(),
'name'=>$this->string(60)->notNull()->comment('类别名称'),
'pid'=>$this->integer(11)->defaultValue(null)->comment('父级id'),
'goods_count'=>$this->integer(11)->defaultValue(0)->comment('商品数量'),
'keywords'=>$this->string(100)->defaultValue(null)->comment('关键字'),
'desc'=>$this->string(255)->defaultValue(null)->comment('描述'),
'sort_order'=>$this->smallInteger(3)->defaultValue(0)->comment('排序'),
'icon_type'=>$this->tinyInteger(1)->defaultValue(null)->comment('图标类型'),
'icon'=>$this->string(64)->defaultValue(null)->comment('图标'),
'filter_attr'=>$this->text()->comment('筛选属性'),
'is_show'=>$this->tinyInteger(1)->defaultValue(0)->comment('是否显示,1为不显示'),
'is_delete'=>$this->tinyInteger(1)->defaultValue(0)->comment('是否删除,1为已删除'),
'created_at'=>$this->integer(11)->defaultValue(null)->comment('创建时间'),
'updated_at'=>$this->integer(11)->defaultValue(null)->comment('更新时间'),
],$tableOptions);
}
/**
* {@inheritdoc}
*/
public function down()
{
$this->dropTable('atg_shop_category');
return true;
}
}

39
backend/modules/goods/migrations/m191119_022641_create_table_atg_category.php

@ -1,39 +0,0 @@
<?php
use yii\db\Migration;
/**
* Class m191119_022641_create_table_atg_category
*/
class m191119_022641_create_table_atg_category extends Migration
{
/**
* {@inheritdoc}
*/
public function up()
{
$tableOptions = 'CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE=InnoDB COMMENT="后台商品类别表"';
$this->createTable('atg_category', [
'id' => $this->primaryKey(),
'name'=>$this->string(60)->notNull()->comment('类别名称'),
'pid'=>$this->integer(11)->defaultValue(null)->comment('父级id'),
'goods_count'=>$this->integer(11)->defaultValue(0)->comment('商品数量'),
'sort_order'=>$this->smallInteger(3)->defaultValue(0)->comment('排序'),
'icon_type'=>$this->tinyInteger(1)->defaultValue(null)->comment('图标类型'),
'icon'=>$this->string(64)->defaultValue(null)->comment('图标'),
'is_show'=>$this->tinyInteger(1)->defaultValue(0)->comment('是否显示,1为不显示'),
'is_delete'=>$this->tinyInteger(1)->defaultValue(0)->comment('是否删除,1为已删除'),
'created_at'=>$this->integer(11)->defaultValue(null)->comment('创建时间'),
'updated_at'=>$this->integer(11)->defaultValue(null)->comment('更新时间'),
],$tableOptions);
}
/**
* {@inheritdoc}
*/
public function down()
{
$this->dropTable('atg_category');
return true;
}
}

36
backend/modules/goods/migrations/m191119_022939_create_table_atg_attribute.php

@ -1,36 +0,0 @@
<?php
use yii\db\Migration;
/**
* Class m191119_022939_create_table_atg_attribute
*/
class m191119_022939_create_table_atg_attribute extends Migration
{
/**
* {@inheritdoc}
*/
public function up()
{
$tableOptions = 'CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE=InnoDB COMMENT="属性表"';
$this->createTable('atg_attribute', [
'id' => $this->primaryKey(),
'name'=>$this->string(50)->notNull()->comment('属性名'),
'value'=>$this->text()->notNull()->comment('属性值'),
'type'=>$this->smallInteger(2)->defaultValue(null)->comment('类型'),
'sort_order'=>$this->smallInteger(3)->defaultValue(null)->comment('排序'),
'is_delete'=>$this->tinyInteger(1)->defaultValue(0)->comment('是否删除,1为已删除'),
'created_at'=>$this->integer(11)->defaultValue(null)->comment('创建时间'),
'updated_at'=>$this->integer(11)->defaultValue(null)->comment('更新时间'),
],$tableOptions);
}
/**
* {@inheritdoc}
*/
public function down()
{
$this->dropTable('atg_attribute');
return true;
}
}

35
backend/modules/goods/migrations/m191119_023115_create_table_atg_goods_attr.php

@ -1,35 +0,0 @@
<?php
use yii\db\Migration;
/**
* Class m191119_023115_create_table_atg_goods_attr
*/
class m191119_023115_create_table_atg_goods_attr extends Migration
{
/**
* {@inheritdoc}
*/
public function up()
{
$tableOptions = 'CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE=InnoDB COMMENT="商品属性表"';
$this->createTable('atg_goods_attr', [
'id' => $this->primaryKey(),
'goods_id'=>$this->integer(11)->notNull()->comment('商品id'),
'attr_id'=>$this->integer(11)->notNull()->comment('属性id'),
'attr_value'=>$this->string(50)->notNull()->comment('属性名'),
'is_delete'=>$this->tinyInteger(1)->defaultValue(0)->comment('是否删除,1为已删除'),
'created_at'=>$this->integer(11)->defaultValue(null)->comment('创建时间'),
'updated_at'=>$this->integer(11)->defaultValue(null)->comment('更新时间'),
],$tableOptions);
}
/**
* {@inheritdoc}
*/
public function down()
{
$this->dropTable('atg_goods_attr');
return true;
}
}

33
backend/modules/goods/migrations/m191119_024029_create_table_atg_brand.php

@ -1,33 +0,0 @@
<?php
use yii\db\Migration;
/**
* Class m191119_024029_create_table_atg_brand
*/
class m191119_024029_create_table_atg_brand extends Migration
{
/**
* {@inheritdoc}
*/
public function up()
{
$tableOptions = 'CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE=InnoDB COMMENT="品牌表"';
$this->createTable('atg_brand', [
'id' => $this->primaryKey(),
'name'=>$this->string(50)->notNull()->comment('品牌名'),
'is_delete'=>$this->tinyInteger(1)->defaultValue(0)->comment('是否删除,1为已删除'),
'created_at'=>$this->integer(11)->defaultValue(null)->comment('创建时间'),
'updated_at'=>$this->integer(11)->defaultValue(null)->comment('更新时间'),
],$tableOptions);
}
/**
* {@inheritdoc}
*/
public function down()
{
$this->dropTable('atg_brand');
return true;
}
}

27
backend/modules/goods/migrations/m191119_024205_create_table_atg_goods.php

@ -1,27 +0,0 @@
<?php
use yii\db\Migration;
/**
* Class m191119_024205_create_table_atg_goods
*/
class m191119_024205_create_table_atg_goods extends Migration
{
/**
* {@inheritdoc}
*/
public function up()
{
$sql = file_get_contents(__DIR__."/sql/goods.sql");
$this->execute($sql);
}
/**
* {@inheritdoc}
*/
public function down()
{
$this->dropTable("atg_goods");
return true;
}
}

27
backend/modules/goods/migrations/m191119_024345_create_table_atg_goods_sku.php

@ -1,27 +0,0 @@
<?php
use yii\db\Migration;
/**
* Class m191119_024345_create_table_atg_goods_sku
*/
class m191119_024345_create_table_atg_goods_sku extends Migration
{
/**
* {@inheritdoc}
*/
public function up()
{
$sql = file_get_contents(__DIR__."/sql/goods_sku.sql");
$this->execute($sql);
}
/**
* {@inheritdoc}
*/
public function down()
{
$this->dropTable("atg_goods_sku");
return true;
}
}

36
backend/modules/goods/migrations/m191119_025607_create_table_atg_supplier.php

@ -1,36 +0,0 @@
<?php
use yii\db\Migration;
/**
* Class m191119_025607_create_table_atg_supplier
*/
class m191119_025607_create_table_atg_supplier extends Migration
{
/**
* {@inheritdoc}
*/
public function up()
{
$tableOptions = 'CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE=InnoDB COMMENT="供应商表"';
$this->createTable('atg_supplier', [
'id' => $this->primaryKey(),
'name'=>$this->string(50)->notNull()->comment('供应商名称'),
'full_name'=>$this->string(50)->notNull()->comment('供应商全称'),
'phone'=>$this->string(20)->notNull()->comment('手机号码'),
'address'=>$this->string(50)->notNull()->comment('地址'),
'is_delete'=>$this->tinyInteger(1)->defaultValue(0)->comment('是否删除,1为已删除'),
'created_at'=>$this->integer(11)->defaultValue(null)->comment('创建时间'),
'updated_at'=>$this->integer(11)->defaultValue(null)->comment('更新时间'),
],$tableOptions);
}
/**
* {@inheritdoc}
*/
public function down()
{
$this->dropTable('atg_supplier');
return true;
}
}

35
backend/modules/goods/migrations/m191119_025843_create_table_atg_filter_attr.php

@ -1,35 +0,0 @@
<?php
use yii\db\Migration;
/**
* Class m191119_025843_create_table_atg_filter_attr
*/
class m191119_025843_create_table_atg_filter_attr extends Migration
{
/**
* {@inheritdoc}
*/
public function up()
{
$tableOptions = 'CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE=InnoDB COMMENT="筛选属性表"';
$this->createTable('atg_filter_attr', [
'id' => $this->primaryKey(),
'goods_id'=>$this->integer(11)->notNull()->comment('商品id'),
'attr_id'=>$this->integer(11)->notNull()->comment('属性id'),
'attr_value'=>$this->string(50)->notNull()->comment('属性值'),
'is_delete'=>$this->tinyInteger(1)->defaultValue(0)->comment('是否删除,1为已删除'),
'created_at'=>$this->integer(11)->defaultValue(null)->comment('创建时间'),
'updated_at'=>$this->integer(11)->defaultValue(null)->comment('更新时间'),
],$tableOptions);
}
/**
* {@inheritdoc}
*/
public function down()
{
$this->dropTable('atg_filter_attr');
return true;
}
}

22
backend/modules/goods/migrations/m191125_012449_update_column_icon_type_in_atg_category.php

@ -1,22 +0,0 @@
<?php
use yii\db\Migration;
/**
* Class m191125_012449_update_column_icon_type_in_atg_category
*/
class m191125_012449_update_column_icon_type_in_atg_category extends Migration
{
public function up()
{
$this->dropColumn('atg_category', 'icon_type');
$this->addColumn('atg_category', 'icon_type', $this->tinyInteger(1)->defaultValue(1)->comment('图标类型'));
}
public function down()
{
$this->dropColumn('atg_category', 'icon_type');
$this->addColumn('atg_category', 'icon_type', $this->tinyInteger(1)->defaultValue(null)->comment('图标类型'));
return true;
}
}

20
backend/modules/goods/migrations/m191125_083820_drop_column_icon_type_in_table_atg_category.php

@ -1,20 +0,0 @@
<?php
use yii\db\Migration;
/**
* Class m191125_083820_drop_column_icon_type_in_table_atg_category
*/
class m191125_083820_drop_column_icon_type_in_table_atg_category extends Migration
{
public function up()
{
$this->dropColumn('atg_category', 'icon_type');
}
public function down()
{
$this->addColumn('atg_category', 'icon_type', $this->tinyInteger(1)->defaultValue(null)->comment('图标类型'));
return true;
}
}

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

@ -1,26 +0,0 @@
<?php
use yii\db\Migration;
/**
* Class m191125_084547_update_column_pid_and_icon_in_table_atg_category
*/
class m191125_084547_update_column_pid_and_icon_in_table_atg_category extends Migration
{
public function up()
{
$this->dropColumn('atg_category', 'icon');
$this->addColumn('atg_category', 'icon', $this->integer(11)->defaultValue(null)->comment('图标'));
$this->dropColumn('atg_category', 'pid');
$this->addColumn('atg_category', 'pid', $this->integer(11)->defaultValue(0)->comment('父级id'));
}
public function down()
{
$this->dropColumn('atg_category', 'icon');
$this->addColumn('atg_category', 'icon', $this->string(64)->defaultValue(null)->comment('图标'));
$this->dropColumn('atg_category', 'pid');
$this->addColumn('atg_category', 'pid', $this->integer(11)->defaultValue(null)->comment('父级id'));
return true;
}
}

20
backend/modules/goods/migrations/m191125_104137_drop_column_icon_type_in_table_atg_shop_category.php

@ -1,20 +0,0 @@
<?php
use yii\db\Migration;
/**
* Class m191125_104137_drop_column_icon_type_in_table_atg_shop_category
*/
class m191125_104137_drop_column_icon_type_in_table_atg_shop_category extends Migration
{
public function up()
{
$this->dropColumn('atg_shop_category', 'icon_type');
}
public function down()
{
$this->addColumn('atg_shop_category', 'icon_type', $this->tinyInteger(1)->defaultValue(null)->comment('图标类型'));
return true;
}
}

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

@ -1,26 +0,0 @@
<?php
use yii\db\Migration;
/**
* Class m191125_104510_update_column_pid_and_icon_in_table_atg_shop_category
*/
class m191125_104510_update_column_pid_and_icon_in_table_atg_shop_category extends Migration
{
public function up()
{
$this->dropColumn('atg_shop_category', 'icon');
$this->addColumn('atg_shop_category', 'icon', $this->integer(11)->defaultValue(null)->comment('图标'));
$this->dropColumn('atg_shop_category', 'pid');
$this->addColumn('atg_shop_category', 'pid', $this->integer(11)->defaultValue(0)->comment('父级id'));
}
public function down()
{
$this->dropColumn('atg_shop_category', 'icon');
$this->addColumn('atg_shop_category', 'icon', $this->string(64)->defaultValue(null)->comment('图标'));
$this->dropColumn('atg_shop_category', 'pid');
$this->addColumn('atg_shop_category', 'pid', $this->integer(11)->defaultValue(null)->comment('父级id'));
return true;
}
}

20
backend/modules/goods/migrations/m191127_114228_add_column_is_manaul_in_table_atg_goods_sku.php

@ -1,20 +0,0 @@
<?php
use yii\db\Migration;
/**
* Class m191127_114228_add_column_is_manaul_in_table_atg_goods_sku
*/
class m191127_114228_add_column_is_manaul_in_table_atg_goods_sku extends Migration
{
public function up()
{
$this->addColumn('atg_goods_sku', 'is_manaul', $this->tinyInteger(1)->notNull()->defaultValue(0)->comment('是否手动'));
}
public function down()
{
$this->dropColumn('atg_goods_sku', 'is_manaul');
return true;
}
}

20
backend/modules/goods/migrations/m191129_010349_add_column_sku_mode_in_atg_goods.php

@ -1,20 +0,0 @@
<?php
use yii\db\Migration;
/**
* Class m191129_010349_add_column_sku_mode_in_atg_goods
*/
class m191129_010349_add_column_sku_mode_in_atg_goods extends Migration
{
public function up()
{
$this->addColumn('atg_goods', 'sku_mode', $this->tinyInteger(1)->notNull()->defaultValue(1)->comment('sku类型'));
}
public function down()
{
$this->dropColumn('atg_goods', 'sku_mode');
return true;
}
}

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

@ -1,26 +0,0 @@
<?php
use yii\db\Migration;
/**
* Class m191129_020131_add_columns_goods_id_and_attr_id_in_table_atg_goods_attr
*/
class m191129_020131_add_columns_goods_id_and_attr_id_in_table_atg_goods_attr extends Migration
{
public function up()
{
$this->dropColumn('atg_goods_attr', 'goods_id');
$this->dropColumn('atg_goods_attr', 'attr_id');
$this->addColumn('atg_goods_attr', 'goods_id', $this->integer(11)->notNull()->defaultValue(0)->comment('商品id'));
$this->addColumn('atg_goods_attr', 'attr_id', $this->integer(11)->notNull()->defaultValue(0)->comment('属性id'));
}
public function down()
{
$this->dropColumn('atg_goods_attr', 'goods_id');
$this->dropColumn('atg_goods_attr', 'attr_id');
$this->addColumn('atg_goods_attr', 'goods_id', $this->integer(11)->notNull()->comment('商品id'));
$this->addColumn('atg_goods_attr', 'attr_id', $this->integer(11)->notNull()->comment('属性id'));
return true;
}
}

20
backend/modules/goods/migrations/m191130_004933_add_column_cat_id_in_table_atg_attribute.php

@ -1,20 +0,0 @@
<?php
use yii\db\Migration;
/**
* Class m191130_004933_add_column_cat_id_in_table_atg_attribute
*/
class m191130_004933_add_column_cat_id_in_table_atg_attribute extends Migration
{
public function up()
{
$this->addColumn('atg_attribute', 'cat_id', $this->integer(11)->notNull()->defaultValue(0)->comment('后台商品分类id'));
}
public function down()
{
$this->dropColumn('atg_attribute', 'cat_id');
return true;
}
}

27
backend/modules/goods/migrations/m191202_082041_drop_columns_in_table_atg_goods_sku.php

@ -1,27 +0,0 @@
<?php
use yii\db\Migration;
/**
* Class m191202_082041_drop_columns_in_table_atg_goods_sku
*/
class m191202_082041_drop_columns_in_table_atg_goods_sku extends Migration
{
public function up()
{
$this->dropColumn('atg_goods_sku', 'weight');
$this->dropColumn('atg_goods_sku', 'length');
$this->dropColumn('atg_goods_sku', 'width');
$this->dropColumn('atg_goods_sku', 'height');
$this->dropColumn('atg_goods_sku', 'diameter');
}
public function down()
{
$this->addColumn('atg_goods_sku', 'weight', $this->integer(8)->defaultValue(null)->comment('重量'));
$this->addColumn('atg_goods_sku', 'length', $this->integer(8)->defaultValue(null)->comment('长度'));
$this->addColumn('atg_goods_sku', 'width', $this->integer(8)->defaultValue(null)->comment('宽度'));
$this->addColumn('atg_goods_sku', 'height', $this->integer(8)->defaultValue(null)->comment('高度'));
$this->addColumn('atg_goods_sku', 'diameter', $this->integer(8)->defaultValue(null)->comment('直径'));
}
}

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

@ -1,26 +0,0 @@
<?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;
}
}

23
backend/modules/goods/migrations/m191209_091129_update_columns_in_table_atg_goods.php

@ -1,23 +0,0 @@
<?php
use yii\db\Migration;
/**
* Class m191209_091129_update_columns_in_table_atg_goods
*/
class m191209_091129_update_columns_in_table_atg_goods extends Migration
{
public function up()
{
$sql = file_get_contents(__DIR__."/sql/update_goods.sql");
$this->execute($sql);
}
/**
* {@inheritdoc}
*/
public function down()
{
return true;
}
}

20
backend/modules/goods/migrations/m191209_091524_add_column_weight_in_table_atg_goods_sku.php

@ -1,20 +0,0 @@
<?php
use yii\db\Migration;
/**
* Class m191209_091524_add_column_weight_in_table_atg_goods_sku
*/
class m191209_091524_add_column_weight_in_table_atg_goods_sku extends Migration
{
public function up()
{
$this->addColumn('atg_goods_sku', 'weight', $this->integer(8)->defaultValue("0")->unsigned()->comment('重量'));
}
public function down()
{
$this->dropColumn('atg_goods_sku', 'weight');
return true;
}
}

22
backend/modules/goods/migrations/m191211_060934_update_column_limit_count_in_table_atg_goods.php

@ -1,22 +0,0 @@
<?php
use yii\db\Migration;
/**
* Class m191211_060934_update_column_limit_count_in_table_atg_goods
*/
class m191211_060934_update_column_limit_count_in_table_atg_goods extends Migration
{
public function up()
{
$this->dropColumn('atg_goods', 'limit_count');
$this->addColumn('atg_goods', 'limit_count', $this->integer(11)->defaultValue("0")->comment("限购数量"));
}
public function down()
{
$this->dropColumn('atg_goods', 'limit_count');
$this->addColumn('atg_goods', 'limit_count', $this->integer(11)->defaultValue(null)->comment("限购数量"));
return true;
}
}

22
backend/modules/goods/migrations/m191211_092335_update_column_sort_order_in_table_atg_goods.php

@ -1,22 +0,0 @@
<?php
use yii\db\Migration;
/**
* Class m191211_092335_update_column_sort_order_in_table_atg_goods
*/
class m191211_092335_update_column_sort_order_in_table_atg_goods extends Migration
{
public function up()
{
$this->dropColumn('atg_goods', 'sort_order');
$this->addColumn('atg_goods', 'sort_order', $this->smallInteger(3)->defaultValue("999")->comment('排序'));
}
public function down()
{
$this->dropColumn('atg_goods', 'sort_order');
$this->addColumn('atg_goods', 'sort_order', $this->smallInteger(3)->defaultValue(null)->comment('排序'));
return true;
}
}

41
backend/modules/goods/migrations/m191217_091658_update_column_is_manual_in_table_atg_goods_sku.php

@ -1,41 +0,0 @@
<?php
use yii\db\Migration;
/**
* Class m191217_091658_update_column_is_manual_in_table_atg_goods_sku
*/
class m191217_091658_update_column_is_manual_in_table_atg_goods_sku extends Migration
{
/**
* {@inheritdoc}
*/
public function safeUp()
{
$this->dropColumn('atg_goods_sku', 'is_manaul');
$this->addColumn('atg_goods_sku', 'is_manual', $this->tinyInteger(1)->notNull()->defaultValue(0)->comment('是否手动'));
}
/**
* {@inheritdoc}
*/
public function safeDown()
{
return true;
}
/*
// Use up()/down() to run migration code without a transaction.
public function up()
{
}
public function down()
{
echo "m191217_091658_update_column_is_manual_in_table_atg_goods_sku cannot be reverted.\n";
return false;
}
*/
}

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

@ -1,26 +0,0 @@
<?php
use yii\db\Migration;
/**
* Class m191217_092101_add_column_sku_image_in_table_atg_goods_sku
*/
class m191217_092101_add_column_sku_image_in_table_atg_goods_sku extends Migration
{
/**
* {@inheritdoc}
*/
public function safeUp()
{
$this->addColumn('atg_goods_sku', 'sku_image', $this->integer(11)->notNull()->defaultValue("0")->comment('sku图片id'));
}
/**
* {@inheritdoc}
*/
public function safeDown()
{
$this->dropColumn('atg_goods_sku', 'sku_image');
return true;
}
}

37
backend/modules/goods/migrations/sql/goods.sql

@ -1,37 +0,0 @@
DROP TABLE IF EXISTS `atg_goods`;
CREATE TABLE `atg_goods` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`pid` int(11) DEFAULT NULL COMMENT '父级id',
`cat_id` int(11) NOT NULL COMMENT '后台商品类别id',
`brand_id` int(11) NOT NULL COMMENT '品牌id',
`shop_cat_id` int(11) NOT NULL COMMENT '前端商品类别id',
`name` varchar(120) NOT NULL COMMENT '商品名称',
`sn` varchar(60) DEFAULT NULL COMMENT '商品唯一货号',
`code` varchar(50) DEFAULT NULL COMMENT '商品货码',
`supplier_id` int(11) DEFAULT NULL COMMENT '供应商id',
`weight` mediumint(8) DEFAULT NULL unique COMMENT '重量',
`length` mediumint(8) DEFAULT NULL unique COMMENT '长度',
`width` mediumint(8) DEFAULT NULL unique COMMENT '宽度',
`height` mediumint(8) DEFAULT NULL unique COMMENT '高度',
`diameter` mediumint(8) DEFAULT NULL unique COMMENT '直径',
`unit` varchar(16) DEFAULT NULL COMMENT '单位',
`sold_count` int(10) DEFAULT NULL unique COMMENT '已售数量',
`limit_count` int(10) DEFAULT NULL COMMENT '限购数量',
`stock` int(10) DEFAULT NULL COMMENT '库存',
`stock_warn` int(10) DEFAULT NULL COMMENT '库存警告',
`market_price` int(20) DEFAULT NULL unique COMMENT '市场价',
`price` int(20) DEFAULT NULL unique COMMENT '销售价',
`brief` varchar(255) DEFAULT NULL COMMENT '简介',
`description` text COMMENT '详细介绍',
`image` int(11) DEFAULT NULL COMMENT '图片id',
`model_id` int(11) DEFAULT NULL COMMENT '模型id',
`is_sale` tinyint(1) DEFAULT '0' COMMENT '该商品是否开放销售,1为是,0为否',
`sort_order` smallint(3) DEFAULT NULL COMMENT '排序',
`bouns_points` mediumint(8) DEFAULT NULL COMMENT '奖励积分',
`experience_points` mediumint(8) DEFAULT NULL COMMENT '经验值',
`is_delete` tinyint(1) DEFAULT '0' COMMENT '是否删除,1为已删除',
`express_template` int(11) DEFAULT NULL COMMENT '配送详情id',
`created_at` int(10) DEFAULT '0' COMMENT '创建时间',
`updated_at` int(10) DEFAULT '0' COMMENT '更新时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='商品表';

24
backend/modules/goods/migrations/sql/goods_sku.sql

@ -1,24 +0,0 @@
DROP TABLE IF EXISTS `atg_goods_sku`;
CREATE TABLE `atg_goods_sku` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`goods_id` int(11) NOT NULL COMMENT '商品id',
`goods_code` varchar(50) DEFAULT NULL COMMENT '商品条码',
`goods_sn` varchar(60) NOT NULL COMMENT '商品唯一货号',
`goods_attr` varchar(60) DEFAULT NULL COMMENT '属性匹配',
`weight` mediumint(8) DEFAULT NULL COMMENT '重量',
`length` mediumint(8) DEFAULT NULL COMMENT '长度',
`width` mediumint(8) DEFAULT NULL COMMENT '宽度',
`height` mediumint(8) DEFAULT NULL COMMENT '高度',
`diameter` mediumint(8) DEFAULT NULL COMMENT '直径',
`sold_count` int(10) DEFAULT NULL COMMENT '已售数量',
`stock` int(10) DEFAULT NULL COMMENT '库存',
`market_price` int(20) DEFAULT NULL COMMENT '市场价',
`price` int(20) DEFAULT NULL COMMENT '销售价',
`model_id` int(11) DEFAULT NULL COMMENT '模型id',
`is_sale` tinyint(1) DEFAULT '0' COMMENT '该商品是否开放销售,1为是,0为否',
`sort_order` smallint(3) DEFAULT '0' COMMENT '排序',
`is_delete` tinyint(1) DEFAULT '0' COMMENT '是否删除,1为已删除',
`created_at` int(10) DEFAULT '0' COMMENT '创建时间',
`updated_at` int(10) DEFAULT '0' COMMENT '更新时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='商品sku表';

17
backend/modules/goods/migrations/sql/update_goods.sql

@ -1,17 +0,0 @@
ALTER TABLE `atg_goods` DROP `weight`;
ALTER TABLE `atg_goods` DROP `length`;
ALTER TABLE `atg_goods` DROP `width`;
ALTER TABLE `atg_goods` DROP `height`;
ALTER TABLE `atg_goods` DROP `diameter`;
ALTER TABLE `atg_goods` DROP `sold_count`;
ALTER TABLE `atg_goods` DROP `market_price`;
ALTER TABLE `atg_goods` DROP `price`;
ALTER TABLE `atg_goods` ADD COLUMN `weight` mediumint(8) UNSIGNED DEFAULT NULL COMMENT '重量';
ALTER TABLE `atg_goods` ADD COLUMN `length` mediumint(8) UNSIGNED DEFAULT NULL COMMENT '长度';
ALTER TABLE `atg_goods` ADD COLUMN `width` mediumint(8) UNSIGNED DEFAULT NULL COMMENT '宽度';
ALTER TABLE `atg_goods` ADD COLUMN `height` mediumint(8) UNSIGNED DEFAULT NULL COMMENT '高度';
ALTER TABLE `atg_goods` ADD COLUMN `diameter` mediumint(8) UNSIGNED DEFAULT NULL COMMENT '直径';
ALTER TABLE `atg_goods` ADD COLUMN `sold_count` int(10) UNSIGNED DEFAULT NULL COMMENT '已售数量';
ALTER TABLE `atg_goods` ADD COLUMN `market_price` int(20) UNSIGNED DEFAULT NULL COMMENT '市场价';
ALTER TABLE `atg_goods` ADD COLUMN `price` int(20) UNSIGNED DEFAULT NULL COMMENT '销售价';

114
backend/modules/goods/models/ars/Attribute.php

@ -1,114 +0,0 @@
<?php
namespace backend\modules\goods\models\ars;
use Yii;
use yii\behaviors\TimestampBehavior;
use backend\modules\goods\models\ars\Category;
/**
* This is the model class for table "atg_attribute".
*
* @property int $id
* @property string $name 属性名
* @property string $value 属性值
* @property int $type 类型
* @property int $sort_order 排序
* @property int $is_delete 是否删除,1为已删除
* @property int $created_at 创建时间
* @property int $updated_at 更新时间
* @property int $cat_id 后台商品分类id
*/
class Attribute extends \yii\db\ActiveRecord
{
//是否删除is_delete
const IS_DELETE_NO = 0;//未删除
const IS_DELETE_YES = 1;//已删除
//类型type
const TYPE_ATTR = 1;//商品sku属性
/**
* {@inheritdoc}
*/
public static function tableName()
{
return 'atg_attribute';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['name', 'value'], 'required'],
[['value'], 'string'],
[['type', 'sort_order', 'is_delete', 'cat_id'], 'integer'],
[['name'], 'string', 'max' => 50],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'id',
'name' => '规格名称',
'value' => '规格内容(每项以逗号隔开)',
'type' => '类型',
'sort_order' => '排序',
'is_delete' => '是否删除,1为已删除',
'created_at' => '创建时间',
'updated_at' => '更新时间',
'cat_id' => '后台商品分类',
];
}
/**
* @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();
},
],
];
}
/**
* @return array
* 数据键值对
*/
public static function modelColumn()
{
return $column = self::find()->select(['name'])->where(['is_delete' => self::IS_DELETE_NO])->indexBy('id')->column();
}
public function beforeSave($insert)
{
if (!$this->type) {
$this->type = self::TYPE_ATTR;
}
if (!$this->sort_order) {
$this->sort_order = "999";
}
return parent::beforeSave($insert); // TODO: Change the autogenerated stub
}
public function getCategory()
{
return $this->hasOne(Category::className(), ['id' => 'cat_id']);
}
}

82
backend/modules/goods/models/ars/Brand.php

@ -1,82 +0,0 @@
<?php
namespace backend\modules\goods\models\ars;
use Yii;
use yii\behaviors\TimestampBehavior;
/**
* This is the model class for table "atg_brand".
*
* @property int $id
* @property string $name 品牌名
* @property int $is_delete 是否删除,1为已删除
* @property int $created_at 创建时间
* @property int $updated_at 更新时间
*/
class Brand extends \yii\db\ActiveRecord
{
//是否删除is_delete
const IS_DELETE_NO = 0;//未删除
const IS_DELETE_YES = 1;//已删除
/**
* {@inheritdoc}
*/
public static function tableName()
{
return 'atg_brand';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['name'], 'required'],
[['is_delete'], 'integer'],
[['name'], 'string', 'max' => 50],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'id',
'name' => '品牌名',
'is_delete' => '是否删除,1为已删除',
'created_at' => '创建时间',
'updated_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();
},
],
];
}
public static function modelColumn()
{
return $column = self::find()->select(['name'])->where(['is_delete' => self::IS_DELETE_NO])->indexBy('id')->column();
}
}

132
backend/modules/goods/models/ars/Category.php

@ -1,132 +0,0 @@
<?php
namespace backend\modules\goods\models\ars;
use Yii;
use yii\behaviors\TimestampBehavior;
use backend\modules\file\models\ars\File;
use backend\modules\goods\logic\goods\GoodsManager;
/**
* This is the model class for table "atg_category".
*
* @property int $id
* @property string $name 类别名称
* @property int $pid 父级id
* @property int $goods_count 商品数量
* @property int $sort_order 排序
* @property int $icon 图标
* @property int $is_show 是否显示,1为不显示
* @property int $is_delete 是否删除,1为已删除
* @property int $created_at 创建时间
* @property int $updated_at 更新时间
*/
class Category extends \yii\db\ActiveRecord
{
public $iconImageId;
public $iconImagePath;
//是否显示is_show
const IS_SHOW_DISPLAY = 0;//显示
const IS_SHOW_HIDE = 1;//隐藏
//是否删除is_delete
const IS_DELETE_NO = 0;//未删除
const IS_DELETE_YES = 1;//已删除
public static $isShow = [
self::IS_SHOW_DISPLAY => '显示',
self::IS_SHOW_HIDE => '隐藏'
];
/**
* {@inheritdoc}
*/
public static function tableName()
{
return 'atg_category';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['name'], 'required'],
[['pid', 'goods_count', 'sort_order', 'is_show', 'is_delete', 'icon'], 'integer'],
[['name'], 'string', 'max' => 60],
[['iconImageId'], 'string'],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'id',
'name' => '类别名称',
'pid' => '父级',
'goods_count' => '商品数量',
'sort_order' => '排序',
'icon' => '图标',
'is_show' => '是否显示',
'is_delete' => '是否删除,1为已删除',
'created_at' => '创建时间',
'updated_at' => '更新时间',
];
}
/**
* @author linyao
* @email 602604991@qq.com
* @created Nov 8, 2019
*
* 行为存储创建时间和更新时间
*/
public function behaviors()
{
return [
[
'class' => TimestampBehavior::class,
'createdAtAttribute' => 'created_at',
'updatedAtAttribute' => 'updated_at',
'value' => function() {
return time();
},
],
];
}
/**
* @param int $ownId
* @param int $needDefault
* @return array
* 数据键值对
*/
public static function modelColumn($ownId = 0, $needDefault = 1)
{
$query = self::find()->where(['is_delete' => self::IS_DELETE_NO]);
if ($ownId) {
$query->andWhere(['not in', 'id', GoodsManager::subCategoryId($ownId)]);
}
$data = $query->asArray()->all();
$data = GoodsManager::btree($data);
$data = GoodsManager::constructDropList($data, $needDefault);
return $data;
}
public function getIconFile()
{
return $this->hasOne(File::className(), ['id' => 'icon']);
}
public function beforeSave($insert)
{
if (!$this->sort_order) {
$this->sort_order = "999";
}
return parent::beforeSave($insert); // TODO: Change the autogenerated stub
}
}

81
backend/modules/goods/models/ars/FilterAttr.php

@ -1,81 +0,0 @@
<?php
namespace backend\modules\goods\models\ars;
use Yii;
use yii\behaviors\TimestampBehavior;
/**
* This is the model class for table "atg_filter_attr".
*
* @property int $id
* @property int $goods_id 商品id
* @property int $attr_id 属性id
* @property string $attr_value 属性值
* @property int $is_delete 是否删除,1为已删除
* @property int $created_at 创建时间
* @property int $updated_at 更新时间
*/
class FilterAttr extends \yii\db\ActiveRecord
{
//是否删除is_delete
const IS_DELETE_NO = 0;//未删除
const IS_DELETE_YES = 1;//已删除
/**
* {@inheritdoc}
*/
public static function tableName()
{
return 'atg_filter_attr';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['goods_id', 'attr_id', 'attr_value'], 'required'],
[['goods_id', 'attr_id', 'is_delete'], 'integer'],
[['attr_value'], 'string', 'max' => 50],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'id',
'goods_id' => '商品id',
'attr_id' => '属性id',
'attr_value' => '属性值',
'is_delete' => '是否删除,1为已删除',
'created_at' => '创建时间',
'updated_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();
},
],
];
}
}

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

@ -1,270 +0,0 @@
<?php
namespace backend\modules\goods\models\ars;
use Yii;
use yii\behaviors\TimestampBehavior;
use backend\modules\goods\models\ars\Category;
use backend\modules\goods\models\ars\ShopCategory;
use backend\modules\file\models\ars\File;
use backend\modules\goods\models\ars\Brand;
use backend\modules\goods\models\ars\Supplier;
/**
* This is the model class for table "atg_goods".
*
* @property int $id
* @property int $pid 父级id
* @property int $cat_id 后台商品类别id
* @property int $brand_id 品牌id
* @property int $shop_cat_id 前端商品类别id
* @property string $name 商品名称
* @property string $sn 商品唯一货号
* @property string $code 商品货码
* @property int $supplier_id 供应商id
* @property int $weight 重量
* @property int $length 长度
* @property int $width 宽度
* @property int $height 高度
* @property int $diameter 直径
* @property string $unit 单位
* @property int $sold_count 总销量
* @property int $limit_count 限购数量
* @property int $stock 库存
* @property int $stock_warn 库存警告
* @property int $market_price 市场价
* @property int $price 销售价
* @property string $brief 简介
* @property string $description 详细介绍
* @property int $image 图片id
* @property int $model_id 模型id
* @property int $is_sale 该商品是否开放销售,1为是,0为否
* @property int $sort_order 排序
* @property int $bouns_points 奖励积分
* @property int $experience_points 经验值
* @property int $is_delete 是否删除,1为已删除
* @property int $express_template 配送详情id
* @property int $created_at 创建时间
* @property int $updated_at 更新时间
* @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
{
//商品封面图
public $coverImagePath;
public $coverImageId;
//商品详情图
public $detailImagePath;
public $detailImageId;
//是否删除is_delete
const IS_DELETE_NO = 0;//未删除
const IS_DELETE_YES = 1;//已删除
//该商品是否开放销售is_sale
const IS_SALE_NO = 0;//否
const IS_SALE_YES = 1;//是
//类型sku
const SKU_MODE_ATTR = 1;//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_TEMPLATE = 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_TEMPLATE => '运费模板'
];
public static $isSale = [
self::IS_SALE_NO => '不在售',
self::IS_SALE_YES => '在售'
];
public $ruleVerify = 0;//规则验证是否通过
/**
* {@inheritdoc}
*/
public static function tableName()
{
return 'atg_goods';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['pid', 'cat_id', 'brand_id', 'shop_cat_id', 'supplier_id', 'weight', 'length', 'width', 'height', 'diameter', 'sold_count', 'limit_count', 'stock', 'stock_warn', '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'],
[['sn'], 'checkExist'],
[['description', 'coverImageId', 'detailImageId'], 'string'],
[['name'], 'string', 'max' => 120],
[['sn'], 'string', 'max' => 60],
[['code'], 'string', 'max' => 50],
[['unit'], 'string', 'max' => 16],
[['brief'], 'string', 'max' => 255],
[['weight', 'length', 'width', 'height', 'diameter', 'sold_count', 'market_price', 'price', 'uniform_postage'], 'checkNegative'],
[['uniform_postage', 'market_price', 'price'], 'safe']
];
}
/**
* @param $attribute
* @param $params
* 验证是否为负数
*/
public function checkNegative($attribute, $params)
{
if ($this->$attribute < 0) {
$this->addError($attribute, "不得为负数");
}
}
/**
* @param $attribute
* @param $params
* 验证商品编号唯一
*/
public function checkExist($attribute, $params)
{
$goods = self::find()->where([$attribute => $this->$attribute, 'is_delete' => 0])->one();
if ($this->isNewRecord) {
if ($goods) {
$this->addError($attribute, "该商品编号已经存在");
}
} else {
if ($goods && $goods->id != $this->id) {
$this->addError($attribute, "该商品编号已经存在");
}
}
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'id',
'pid' => '父级id',
'cat_id' => '后台商品类别',
'brand_id' => '品牌',
'shop_cat_id' => '前端商品类别',
'name' => '商品名称',
'sn' => '商品唯一货号',
'code' => '商品货码',
'supplier_id' => '供应商',
'weight' => '重量',
'length' => '长度',
'width' => '宽度',
'height' => '高度',
'diameter' => '直径',
'unit' => '单位',
'sold_count' => '总销量',
'limit_count' => '限购数量',
'stock' => '库存',
'stock_warn' => '库存警告',
'market_price' => '市场价',
'price' => '销售价',
'brief' => '简介',
'description' => '详细介绍',
'image' => '首页图片',
'model_id' => '模型id',
'is_sale' => '销售状态',
'sort_order' => '排序',
'bouns_points' => '奖励积分',
'experience_points' => '经验值',
'is_delete' => '是否删除,1为已删除',
'express_template' => '配送详情',
'created_at' => '创建时间',
'updated_at' => '更新时间',
'sku_mode' => 'sku类型',
'is_taking' => '是否自提',
'is_express' => '是否快递发货',
'express_type' => '快递运费方式',
'uniform_postage' => '统一邮费',
];
}
/**
* @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();
},
],
];
}
/**
* @param bool $insert
* @return bool
* 自动填入参数
*/
public function beforeSave($insert)
{
if (!$this->sn) {
$this->sn = time() . rand(1111, 9999);
}
if (!$this->limit_count) {
$this->limit_count = 0;
}
if (!$this->sort_order) {
$this->sort_order = "999";
}
return parent::beforeSave($insert); // TODO: Change the autogenerated stub
}
public function getCategory()
{
return $this->hasOne(Category::className(), ['id' => 'cat_id']);
}
public function getShopCategory()
{
return $this->hasOne(ShopCategory::className(), ['id' => 'shop_cat_id']);
}
public function getImageFile()
{
return $this->hasOne(File::className(), ['id' => 'image']);
}
public function getBrand()
{
return $this->hasOne(Brand::className(), ['id' => 'brand_id']);
}
public function getSupplier()
{
return $this->hasOne(Supplier::className(), ['id' => 'supplier_id']);
}
}

81
backend/modules/goods/models/ars/GoodsAttr.php

@ -1,81 +0,0 @@
<?php
namespace backend\modules\goods\models\ars;
use Yii;
use yii\behaviors\TimestampBehavior;
/**
* This is the model class for table "atg_goods_attr".
*
* @property int $id
* @property int $goods_id 商品id
* @property int $attr_id 属性id
* @property string $attr_value 属性名
* @property int $is_delete 是否删除,1为已删除
* @property int $created_at 创建时间
* @property int $updated_at 更新时间
*/
class GoodsAttr extends \yii\db\ActiveRecord
{
//是否删除is_delete
const IS_DELETE_NO = 0;//未删除
const IS_DELETE_YES = 1;//已删除
/**
* {@inheritdoc}
*/
public static function tableName()
{
return 'atg_goods_attr';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['attr_value'], 'required'],
[['goods_id', 'attr_id', 'is_delete'], 'integer'],
[['attr_value'], 'string', 'max' => 50],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'id',
'goods_id' => '商品id',
'attr_id' => '属性id',
'attr_value' => '属性名',
'is_delete' => '是否删除,1为已删除',
'created_at' => '创建时间',
'updated_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();
},
],
];
}
}

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

@ -1,107 +0,0 @@
<?php
namespace backend\modules\goods\models\ars;
use Yii;
use yii\behaviors\TimestampBehavior;
/**
* This is the model class for table "atg_goods_sku".
*
* @property int $id
* @property int $goods_id 商品id
* @property string $goods_code 商品条码
* @property string $goods_sn 商品唯一货号
* @property string $goods_attr 属性匹配
* @property int $sold_count 已售数量
* @property int $stock 库存
* @property int $market_price 市场价
* @property int $price 销售价
* @property int $model_id 模型id
* @property int $is_sale 该商品是否开放销售,1为是,0为否
* @property int $sort_order 排序
* @property int $is_delete 是否删除,1为已删除
* @property int $created_at 创建时间
* @property int $updated_at 更新时间
* @property int $is_manual 是否手动
* @property int $weight 重量
* @property int $sku_image sku图片id
*/
class GoodsSku extends \yii\db\ActiveRecord
{
//是否手动is_manual
const IS_MANUAL_YES = 1; //是手动
const IS_MANUAL_NO = 0; //不是手动
//是否删除is_delete
const IS_DELETE_NO = 0;//未删除
const IS_DELETE_YES = 1;//已删除
/**
* {@inheritdoc}
*/
public static function tableName()
{
return 'atg_goods_sku';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['goods_id', 'goods_sn'], 'required'],
[['goods_id', 'sold_count', 'stock', 'market_price', 'price', 'model_id', 'is_sale', 'sort_order', 'is_delete', 'is_manual', 'sku_image'], 'integer'],
[['goods_code'], 'string', 'max' => 50],
[['goods_sn', 'goods_attr'], 'string', 'max' => 60],
[['weight'], 'safe']
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'id',
'goods_id' => '商品id',
'goods_code' => '商品条码',
'goods_sn' => '商品唯一货号',
'goods_attr' => '属性匹配',
'sold_count' => '已售数量',
'stock' => '库存',
'market_price' => '市场价',
'price' => '销售价',
'model_id' => '模型id',
'is_sale' => '该商品是否开放销售,1为是,0为否',
'sort_order' => '排序',
'is_delete' => '是否删除,1为已删除',
'created_at' => '创建时间',
'updated_at' => '更新时间',
'weight' => '重量',
'sku_image' => 'sku图片id',
];
}
/**
* @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();
},
],
];
}
}

144
backend/modules/goods/models/ars/ShopCategory.php

@ -1,144 +0,0 @@
<?php
namespace backend\modules\goods\models\ars;
use backend\modules\goods\logic\goods\GoodsManager;
use Yii;
use yii\behaviors\TimestampBehavior;
use backend\modules\file\models\ars\File;
use yii\db\ActiveQuery;
/**
* This is the model class for table "atg_shop_category".
*
* @property int $id
* @property string $name 类别名称
* @property int $pid 父级id
* @property int $goods_count 商品数量
* @property string $keywords 关键字
* @property string $desc 描述
* @property int $sort_order 排序
* @property string $icon 图标
* @property string $filter_attr 筛选属性
* @property int $is_show 是否显示,1为不显示
* @property int $is_delete 是否删除,1为已删除
* @property int $created_at 创建时间
* @property int $updated_at 更新时间
*/
class ShopCategory extends \yii\db\ActiveRecord
{
public $iconImageId;
public $iconImagePath;
//是否显示is_show
const IS_SHOW_DISPLAY = 0;//显示
const IS_SHOW_HIDE = 1;//隐藏
//是否删除is_delete
const IS_DELETE_NO = 0;//未删除
const IS_DELETE_YES = 1;//已删除
public static $isShow = [
self::IS_SHOW_DISPLAY => '显示',
self::IS_SHOW_HIDE => '隐藏'
];
/**
* {@inheritdoc}
*/
public static function tableName()
{
return 'atg_shop_category';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['name'], 'required'],
[['pid', 'goods_count', 'sort_order', 'icon', 'is_show', 'is_delete', 'iconImageId'], 'integer'],
[['filter_attr'], 'safe'],
[['name'], 'string', 'max' => 60],
[['keywords'], 'string', 'max' => 100],
[['desc'], 'string', 'max' => 255],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'id',
'name' => '类别名称',
'pid' => '父级',
'goods_count' => '商品数量',
'keywords' => '关键字',
'desc' => '描述',
'sort_order' => '排序',
'icon' => '图标',
'filter_attr' => '筛选属性',
'is_show' => '是否显示',
'is_delete' => '是否删除',
'created_at' => '创建时间',
'updated_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();
},
],
];
}
/**
* @param int $ownId
* @param int $needDefault
* @return array 数据键值对
* 数据键值对
*/
public static function modelColumn($ownId = 0, $needDefault = 1)
{
$query = self::find()->where(['is_delete' => self::IS_DELETE_NO]);
if ($ownId) {
$query->andWhere(['not in', 'id', GoodsManager::subShopCategoryId($ownId)]);
}
$data = $query->asArray()->all();
$data = GoodsManager::btree($data);
$data = GoodsManager::constructDropList($data, $needDefault);
return $data;
}
public function getIconFile()
{
return $this->hasOne(File::className(), ['id' => 'icon']);
}
public function beforeSave($insert)
{
if ($this->filter_attr != null && is_array($this->filter_attr)) {
$this->filter_attr = implode(',', $this->filter_attr);
}
if (!$this->sort_order) {
$this->sort_order = "999";
}
return parent::beforeSave($insert); // TODO: Change the autogenerated stub
}
}

96
backend/modules/goods/models/ars/Supplier.php

@ -1,96 +0,0 @@
<?php
namespace backend\modules\goods\models\ars;
use Yii;
use yii\behaviors\TimestampBehavior;
/**
* This is the model class for table "atg_supplier".
*
* @property int $id
* @property string $name 供应商名称
* @property string $full_name 供应商全称
* @property string $phone 手机号码
* @property string $address 地址
* @property int $is_delete 是否删除,1为已删除
* @property int $created_at 创建时间
* @property int $updated_at 更新时间
*/
class Supplier extends \yii\db\ActiveRecord
{
//是否删除is_delete
const IS_DELETE_NO = 0;//未删除
const IS_DELETE_YES = 1;//已删除
/**
* {@inheritdoc}
*/
public static function tableName()
{
return 'atg_supplier';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['name', 'full_name', 'phone', 'address'], 'required'],
[['is_delete'], 'integer'],
[['name', 'full_name', 'address'], 'string', 'max' => 50],
[['phone'], 'string', 'max' => 20],
['phone', 'filter', 'filter' => 'trim'],
['phone','match','pattern'=>'/^[1][34578][0-9]{9}$/'],
['phone', 'unique', 'targetClass' => '\backend\modules\goods\models\ars\Supplier', 'message' => '手机号已被使用'],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'id',
'name' => '供应商名称',
'full_name' => '供应商全称',
'phone' => '手机号码',
'address' => '地址',
'is_delete' => '是否删除,1为已删除',
'created_at' => '创建时间',
'updated_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();
},
],
];
}
/**
* @return array
* 数据键值对
*/
public static function modelColumn()
{
return $column = self::find()->select(['name'])->where(['is_delete' => self::IS_DELETE_NO])->indexBy('id')->column();
}
}

162
backend/modules/goods/models/searchs/AttributeSearch.php

@ -1,162 +0,0 @@
<?php
namespace backend\modules\goods\models\searchs;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use yii\helpers\ArrayHelper;
use backend\modules\goods\models\ars\Attribute;
/**
* AttributeSearch represents the model behind the search form of `backend\modules\goods\models\ars\Attribute`.
*/
class AttributeSearch extends Attribute
{
/**
* @return array
* 增加创建时间查询字段
*/
public function attributes()
{
return ArrayHelper::merge(['created_at_range'], parent::attributes());
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['id', 'type', 'sort_order', 'is_delete', 'created_at', 'updated_at'], 'integer'],
[['name', 'value'], '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',
'name',
'value',
'sort_order',
['attribute' => 'cat_id',
'value' => function ($model){
return $model->cat_id ? $model->category->name : '无限制';
},
],
[
'class' => 'iron\grid\ActionColumn',
'align' => 'center',
'config' => [
[
'name' => 'update',
'icon' => 'pencil',
'title' => '修改'
],
[
'name' => 'delete',
'icon' => 'trash',
'title' => '删除',
'contents' => '确定删除?'
]
],
],
];
}
/**
* @param $params
* @return ActiveDataProvider
* 不分页的所有数据
*/
public function allData($params)
{
$query = Attribute::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)
{
$query = Attribute::find()->where(['is_delete' => Attribute::IS_DELETE_NO]);
// 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){
$query->andFilterWhere(['is_delete' => Attribute::IS_DELETE_NO]);
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,
'type' => $this->type,
'sort_order' => $this->sort_order,
'is_delete' => $this->is_delete,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
]);
$query->andFilterWhere(['like', 'name', $this->name])
->andFilterWhere(['like', 'value', $this->value]);
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;
}
}

152
backend/modules/goods/models/searchs/BrandSearch.php

@ -1,152 +0,0 @@
<?php
namespace backend\modules\goods\models\searchs;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use yii\helpers\ArrayHelper;
use backend\modules\goods\models\ars\Brand;
/**
* BrandSearch represents the model behind the search form of `backend\modules\goods\models\ars\Brand`.
*/
class BrandSearch extends Brand
{
/**
* @return array
* 增加创建时间查询字段
*/
public function attributes()
{
return ArrayHelper::merge(['created_at_range'], parent::attributes());
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['id', 'is_delete', 'created_at', 'updated_at'], 'integer'],
[['name'], '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',
'name',
[
'class' => 'iron\grid\ActionColumn',
'align' => 'center',
'config' => [
[
'name' => 'update',
'icon' => 'pencil',
'title' => '修改'
],
[
'name' => 'delete',
'icon' => 'trash',
'title' => '删除',
'contents' => '确定删除?'
]
],
],
];
}
/**
* @param $params
* @return ActiveDataProvider
* 不分页的所有数据
*/
public function allData($params)
{
$query = Brand::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)
{
$query = Brand::find()->where(['is_delete' => Brand::IS_DELETE_NO]);
// 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){
$query->andFilterWhere(['is_delete' => Brand::IS_DELETE_NO]);
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,
'is_delete' => $this->is_delete,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
]);
$query->andFilterWhere(['like', 'name', $this->name]);
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;
}
}

184
backend/modules/goods/models/searchs/CategorySearch.php

@ -1,184 +0,0 @@
<?php
namespace backend\modules\goods\models\searchs;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use yii\helpers\ArrayHelper;
use backend\modules\goods\models\ars\Category;
use yii\bootstrap4\Html;
/**
* CategorySearch represents the model behind the search form of `backend\modules\goods\models\ars\Category`.
*/
class CategorySearch extends Category
{
/**
* @return array
* 增加创建时间查询字段
*/
public function attributes()
{
return ArrayHelper::merge(['created_at_range'], parent::attributes());
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['id', 'pid', 'goods_count', 'sort_order', 'is_show', 'is_delete', 'created_at', 'updated_at', 'icon'], 'integer'],
[['name'], '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',
'name',
'pid',
[
'attribute' => 'pid',
'value' => function ($model) {
$parentsCategory = Category::findOne($model->pid);
if ($parentsCategory) {
return $parentsCategory->name;
} else {
return '一级分类';
}
}
],
['attribute' => 'icon',
'contentOptions' => [
'align' => 'center',
],
'width'=>'10%',
'format' => 'raw',
'value' => function ($model) {
return $model->iconFile ?
Html::img(['/'.$model->iconFile->path], ['style' => 'width:80px'])
: '<div class="table_not_setting">未设置</div>';
}
],
'sort_order',
[
'class' => 'iron\grid\ActionColumn',
'align' => 'center',
'config' => [
[
'name' => 'update',
'icon' => 'pencil',
'title' => '修改'
],
[
'name' => 'delete',
'icon' => 'trash',
'title' => '删除',
'contents' => '确定删除?'
]
],
],
];
}
/**
* @param $params
* @return ActiveDataProvider
* 不分页的所有数据
*/
public function allData($params)
{
$query = Category::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)
{
$query = Category::find()->where(['is_delete' => Category::IS_DELETE_NO]);
// 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){
$query->andFilterWhere(['is_delete' => Category::IS_DELETE_NO]);
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,
'pid' => $this->pid,
'goods_count' => $this->goods_count,
'sort_order' => $this->sort_order,
'is_show' => $this->is_show,
'is_delete' => $this->is_delete,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
'icon' => $this->icon,
]);
$query->andFilterWhere(['like', 'name', $this->name]);
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;
}
}

232
backend/modules/goods/models/searchs/GoodsSearch.php

@ -1,232 +0,0 @@
<?php
namespace backend\modules\goods\models\searchs;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use yii\helpers\ArrayHelper;
use backend\modules\goods\models\ars\Goods;
use yii\bootstrap4\Html;
use backend\modules\shop\logic\ShopManager;
/**
* GoodsSearch represents the model behind the search form of `backend\modules\goods\models\ars\Goods`.
*/
class GoodsSearch extends Goods
{
/**
* @return array
* 增加创建时间查询字段
*/
public function attributes()
{
return ArrayHelper::merge(['created_at_range'], parent::attributes());
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['id', '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', 'created_at', 'updated_at'], 'integer'],
[['name', 'sn', 'code', 'unit', 'brief', 'description'], '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'
],
['attribute' => 'image',
'contentOptions' => [
'align' => 'center',
],
'width'=>'10%',
'format' => 'raw',
'value' => function ($model) {
return $model->imageFile ?
Html::img(['/'.$model->imageFile->path], ['style' => 'width:80px'])
: '<div class="table_not_setting">未设置</div>';
}
],
'id',
'name',
[
'attribute' => 'market_price',
'value' => function ($model) {
return sprintf("%1\$.2f",$model->market_price / ShopManager::proportionalConversion(ShopManager::UNIT_TYPE_MONEY));
}
],
[
'attribute' => 'price',
'value' => function ($model) {
return sprintf("%1\$.2f",$model->price / ShopManager::proportionalConversion(ShopManager::UNIT_TYPE_MONEY));
}
],
[
'attribute' => 'stock',
'width' => '5%',
'value' => function ($model) {
if ($model->stock == -1) {
return '未开启';
} else {
return $model->stock;
}
},
],
['attribute' => 'is_sale',
'width' => '5%',
'value' =>
function ($model) {
return $model->is_sale==Goods::IS_SALE_YES ? '在售' : '不在售';
},
],
'sort_order',
[
'class' => 'iron\grid\ActionColumn',
'align' => 'center',
'config' => [
[
'name' => 'update',
'icon' => 'pencil',
'title' => '修改'
],
[
'name' => 'edit-sku',
'icon' => 'hard-drive',
'title' => '商品sku'
],
[
'name' => 'delete',
'icon' => 'trash',
'title' => '删除',
'contents' => '确定删除?'
]
],
],
];
}
/**
* @param $params
* @return ActiveDataProvider
* 不分页的所有数据
*/
public function allData($params)
{
$query = Goods::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)
{
$query = Goods::find()->where(['is_delete' => Goods::IS_DELETE_NO]);
// 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){
$query->andFilterWhere(['is_delete' => Goods::IS_DELETE_NO]);
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,
'pid' => $this->pid,
'cat_id' => $this->cat_id,
'brand_id' => $this->brand_id,
'shop_cat_id' => $this->shop_cat_id,
'supplier_id' => $this->supplier_id,
'weight' => $this->weight,
'length' => $this->length,
'width' => $this->width,
'height' => $this->height,
'diameter' => $this->diameter,
'sold_count' => $this->sold_count,
'limit_count' => $this->limit_count,
'stock' => $this->stock,
'stock_warn' => $this->stock_warn,
'market_price' => $this->market_price,
'price' => $this->price,
'image' => $this->image,
'model_id' => $this->model_id,
'is_sale' => $this->is_sale,
'sort_order' => $this->sort_order,
'bouns_points' => $this->bouns_points,
'experience_points' => $this->experience_points,
'is_delete' => $this->is_delete,
'express_template' => $this->express_template,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
]);
$query->andFilterWhere(['like', 'name', $this->name])
->andFilterWhere(['like', 'sn', $this->sn])
->andFilterWhere(['like', 'code', $this->code])
->andFilterWhere(['like', 'unit', $this->unit])
->andFilterWhere(['like', 'brief', $this->brief])
->andFilterWhere(['like', 'description', $this->description]);
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;
}
}

162
backend/modules/goods/models/searchs/ShopCategorySearch.php

@ -1,162 +0,0 @@
<?php
namespace backend\modules\goods\models\searchs;
use yii\base\Model;
use yii\bootstrap4\Html;
use yii\data\ActiveDataProvider;
use yii\helpers\ArrayHelper;
use backend\modules\goods\models\ars\ShopCategory;
/**
* ShopCategorySearch represents the model behind the search form of `backend\modules\goods\models\ars\ShopCategory`.
*/
class ShopCategorySearch extends ShopCategory
{
/**
* @return array
* 增加创建时间查询字段
*/
public function attributes()
{
return ArrayHelper::merge(['created_at_range'], parent::attributes());
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['id', 'pid', 'goods_count', 'sort_order', 'is_show', 'is_delete', 'created_at', 'updated_at', 'icon'], 'integer'],
[['name', 'keywords', 'desc', 'filter_attr'], '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',
'name',
['attribute' => 'icon',
'contentOptions' => [
'align' => 'center',
],
'width'=>'10%',
'format' => 'raw',
'value' => function ($model) {
return $model->iconFile ?
Html::img(['/'.$model->iconFile->path], ['style' => 'width:80px'])
: '<div class="table_not_setting">未设置</div>';
}
],
'sort_order',
[
'class' => 'iron\grid\ActionColumn',
'align' => 'center',
],
];
}
/**
* @param $params
* @return ActiveDataProvider
* 不分页的所有数据
*/
public function allData($params)
{
$query = ShopCategory::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)
{
$query = ShopCategory::find()
->where(['is_delete' => ShopCategory::IS_DELETE_NO]);
// 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,
'pid' => $this->pid,
'goods_count' => $this->goods_count,
'sort_order' => $this->sort_order,
'icon' => $this->icon,
'is_show' => $this->is_show,
'is_delete' => $this->is_delete,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
]);
$query->andFilterWhere(['like', 'name', $this->name])
->andFilterWhere(['like', 'keywords', $this->keywords])
->andFilterWhere(['like', 'desc', $this->desc])
->andFilterWhere(['like', 'filter_attr', $this->filter_attr]);
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;
}
}

161
backend/modules/goods/models/searchs/SupplierSearch.php

@ -1,161 +0,0 @@
<?php
namespace backend\modules\goods\models\searchs;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use yii\helpers\ArrayHelper;
use backend\modules\goods\models\ars\Supplier;
/**
* SupplierSearch represents the model behind the search form of `backend\modules\goods\models\ars\Supplier`.
*/
class SupplierSearch extends Supplier
{
/**
* @return array
* 增加创建时间查询字段
*/
public function attributes()
{
return ArrayHelper::merge(['created_at_range'], parent::attributes());
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['id', 'is_delete', 'created_at', 'updated_at'], 'integer'],
[['name', 'full_name', 'phone', 'address'], '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',
'name',
'full_name',
'phone',
'address',
//'is_delete',
//'created_at',
//'updated_at',
[
'class' => 'iron\grid\ActionColumn',
'align' => 'center',
'config' => [
[
'name' => 'update',
'icon' => 'pencil',
'title' => '修改'
],
[
'name' => 'delete',
'icon' => 'trash',
'title' => '删除',
'contents' => '确定删除?'
]
],
],
];
}
/**
* @param $params
* @return ActiveDataProvider
* 不分页的所有数据
*/
public function allData($params)
{
$query = Supplier::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)
{
$query = Supplier::find()->where(['is_delete' => Supplier::IS_DELETE_NO]);
// 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){
$query->andFilterWhere(['is_delete' => Supplier::IS_DELETE_NO]);
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,
'is_delete' => $this->is_delete,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
]);
$query->andFilterWhere(['like', 'name', $this->name])
->andFilterWhere(['like', 'full_name', $this->full_name])
->andFilterWhere(['like', 'phone', $this->phone])
->andFilterWhere(['like', 'address', $this->address]);
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;
}
}

Some files were not shown because too many files changed in this diff

Loading…
Cancel
Save