Mall.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. <?php
  2. /**
  3. * @link:http://www.gdqijianshi.com/
  4. * @copyright: Copyright (c) 2020 广东七件事集团
  5. * 基础model
  6. * Author: zal
  7. * Date: 2020-04-08
  8. * Time: 15:12
  9. */
  10. namespace common\models\mall;
  11. use backend\models\AdminRole;
  12. use common\enums\AppEnum;
  13. use common\enums\RedisKeyEnum;
  14. use common\enums\StatusEnum;
  15. use common\events\mall\MallCreateEvent;
  16. use common\helpers\Base64Helper;
  17. use common\helpers\StringHelper;
  18. use common\models\addons\MallAddonsComboRelation;
  19. use common\models\backend\Admin;
  20. use common\models\base\BaseActiveRecord;
  21. use common\models\common\MallSetting;
  22. use common\models\rbac\AuthItem;
  23. use common\models\rbac\AuthItemChild;
  24. use common\models\rbac\AuthRole;
  25. use PHPUnit\Util\Exception;
  26. use Yii;
  27. /**
  28. * This is the model class for table "{{%mall}}".
  29. *
  30. *
  31. * @property integer $id
  32. * @property integer $created_at
  33. * @property integer $updated_at
  34. * @property integer $expired_at
  35. * @property string $name
  36. * @property string $contact_tel
  37. * @property integer $admin_id
  38. * @property integer $is_recycle
  39. * @property integer $is_disable
  40. * @property integer $status
  41. * @property integer $is_show_copyright
  42. * @property Admin $admin
  43. * @property MallSetting[] $option
  44. */
  45. class Mall extends BaseActiveRecord
  46. {
  47. public $options;
  48. /** @var int 是否回收 0否 */
  49. const IS_RECYLE_NO = 0;
  50. /** @var int 是否回收 1是 */
  51. const IS_RECYLE_YES = 1;
  52. /** @var int 是否禁用 0否 */
  53. const IS_DISABLE_ON = 0;
  54. /** @var int 是否回收 1是 */
  55. const IS_DISABLE_OFF = 1;
  56. /**
  57. * {@inheritdoc}
  58. */
  59. public static function tableName()
  60. {
  61. return '{{%mall}}';
  62. }
  63. /**
  64. * {@inheritdoc}
  65. */
  66. public function rules()
  67. {
  68. return [
  69. [['created_at', 'updated_at', 'expired_at'], 'safe'],
  70. [['admin_id', 'is_recycle', 'is_disable','status','is_show_copyright','is_compliance'], 'integer'],
  71. [['name','contact_tel'], 'string', 'max' => 20],
  72. [['mall_sign'], 'string', 'max' => 255],
  73. ];
  74. }
  75. /**
  76. * {@inheritdoc}
  77. */
  78. public function attributeLabels()
  79. {
  80. return [
  81. 'id' => 'ID',
  82. 'name' => '商城名称',
  83. 'contact_tel' => '客服电话',
  84. 'admin_id' => '管理员ID',
  85. 'is_recycle' => '是否回收',
  86. 'is_disable' => '是否禁用',
  87. 'expired_at' => '过期时间',
  88. 'created_at' => '创建时间',
  89. 'updated_at' => '更新时间',
  90. 'status' => '状态',
  91. 'is_show_copyright' => '是否显示版权:1;显示;0不显示',
  92. 'is_compliance' => '合规模式:1;是;0否',
  93. ];
  94. }
  95. public function getAdmin()
  96. {
  97. return $this->hasOne(Admin::class, ['id' => 'admin_id']);
  98. }
  99. public function getMallHost()
  100. {
  101. return $this->hasOne(MallHost::class, ['mall_id' => 'id']);
  102. }
  103. /**
  104. * 获取有效商城列表
  105. * @Author bing
  106. * @DateTime 2020-12-23 19:42:28
  107. * @param boolean $is_array
  108. * @return mixed|void
  109. * @copyright: Copyright (c) 2020 广东七件事集团
  110. */
  111. public static function getEnableMallList($is_array = true, $cond = [])
  112. {
  113. $default_cond = [['=','status',StatusEnum::ENABLED],['=','is_recycle',StatusEnum::DISABLED]];
  114. $cond = array_merge($default_cond,$cond);
  115. $query = self::find();
  116. self::paramPack(['where'=>$cond],$query);
  117. $data = $query->asArray($is_array)->all();
  118. return $data;
  119. }
  120. public static function getAllMallIds()
  121. {
  122. return self::find()->select('id')->column();
  123. }
  124. public function getAdonsComboRelation()
  125. {
  126. return $this->hasOne(MallAddonsComboRelation::class, ['mall_id' => 'id'])->select('id,addons_combo_id,mall_id');
  127. }
  128. public static function getEnableMallIds()
  129. {
  130. return self::find()->where(array('status' => StatusEnum::ENABLED, 'is_recycle' => 0,))->select('id')->column();
  131. }
  132. /**
  133. * @Author: ltm
  134. * @DateTime: 2022/1/10 0010 9:57
  135. * @Copyright: copyright (c) 2021 广东七件事集团
  136. * @param $data
  137. * @return bool
  138. */
  139. public function beforeSave($insert){
  140. $old_name = $this->getOldAttribute('name');
  141. if($this->name != $old_name){
  142. Yii::$app->db->createCommand()->update(
  143. MallSetting::tableName(),
  144. ['value'=> $this->name, 'updated_at' => time()],
  145. ['mall_id' => $this->id,'group' => 'basic','name' =>'name']
  146. )->execute();
  147. }
  148. return parent::beforeSave($insert);
  149. }
  150. /**
  151. * 保存数据
  152. * @param array $params
  153. * @return bool|Mall
  154. */
  155. public static function setData(array $params)
  156. {
  157. $t = Yii::$app->db->beginTransaction();
  158. try {
  159. if (!empty($params['id'])) {
  160. $model = self::findOne(['id' => $params['id']]);
  161. if (empty($model)) throw new Exception('服务不存在或已删除');
  162. } else {
  163. $model = new self();
  164. $model->loadDefaultValues();
  165. $params['admin_id'] = 0;
  166. if(!empty(Yii::$app->user->identity))$params['admin_id'] = Yii::$app->user->identity->getId();
  167. }
  168. if (!$model->load($params, '') || !$model->save()) throw new Exception($model->getErrorMessage());
  169. if(empty($params['id'])) {
  170. while (true){
  171. $mall_sign = StringHelper::createRandomString(3);
  172. $res = Mall::findOne(['mall_sign'=>$mall_sign]);
  173. if(empty($res)) break;
  174. }
  175. if ($model->name == '商城系统') $model->name = $model->name.$model->id;
  176. $model->mall_sign = $mall_sign;
  177. $model->save();
  178. //创建商城
  179. //添加角色
  180. $param =[];
  181. $model_auth_role = new AuthRole();
  182. $param['title'] = '管理员';
  183. $param['app_id'] = AppEnum::BACKEND;
  184. $param['pid'] = 0;
  185. $param['sort'] = 1;
  186. $param['is_default'] = 1;
  187. $param['status'] = 1;
  188. $param['mall_id'] = $model->id;
  189. $model_auth_role->attributes = $param;
  190. $res = $model_auth_role->save();
  191. if($res==false) throw new Exception('创建默认角色错误');
  192. //添加默认权限
  193. $values_arr = [];
  194. $item_list = AuthItem::findAll(['cate_id'=> AppEnum::MALL,'status'=>StatusEnum::ENABLED]);
  195. foreach ($item_list as $val){
  196. $info = [
  197. $model_auth_role->id,
  198. $val['id'],
  199. AppEnum::BACKEND,
  200. $val['name'],
  201. $val['is_addon'],
  202. $val['addons_name'],
  203. time(),
  204. time()
  205. ];
  206. $values_arr[] = $info;
  207. }
  208. $item_list = AuthItem::findAll(['is_addon'=> 1,'status'=>StatusEnum::ENABLED]);
  209. foreach ($item_list as $val){
  210. $info = [
  211. $model_auth_role->id,
  212. $val['id'],
  213. AppEnum::BACKEND,
  214. $val['name'],
  215. $val['is_addon'],
  216. $val['addons_name'],
  217. time(),
  218. time()
  219. ];
  220. $values_arr[] = $info;
  221. }
  222. $fields = ['role_id', 'item_id', 'app_id', 'name', 'is_addon', 'addons_name','created_at', 'updated_at'];
  223. Yii::$app->db->createCommand()->batchInsert(
  224. AuthItemChild::tableName(),
  225. $fields,
  226. $values_arr
  227. )->execute();
  228. //添加账号
  229. $param =[];
  230. $param['title'] = '管理员';
  231. $param['remark'] = $params['remark']??'';
  232. $param['mall_id'] = $model->id;
  233. $param['username'] =$params['mobile'];
  234. $param['account'] = $params['mobile'];
  235. $param['mobile'] = $params['mobile'];
  236. $param['is_default'] = 1;
  237. $param['mch_id'] = 0;//预留
  238. $param['store_id'] = 0;//预留
  239. $param['role_id'] = $model_auth_role->id;
  240. $param['admin_type'] = Admin::ADMIN_TYPE_OPERATE;
  241. $param['source'] = $params['source']??0;
  242. $param['reference_id'] = $params['reference_id']??0;
  243. if (empty($params['password'])) {
  244. $password = substr($params['mobile'],-6,6);
  245. $param['password'] = Yii::$app->security->generatePasswordHash($password);
  246. } else {
  247. $param['password'] = Yii::$app->security->generatePasswordHash($params['password']);
  248. }
  249. $model_admin = new Admin();
  250. $model_admin->attributes = $param;
  251. $res = $model_admin->save();
  252. if($res==false) throw new Exception($model_admin->getErrorMessage().'创建默认账号错误');
  253. //添加账号与角色关联
  254. $res = AdminRole::setData(['id' => '', 'role_id' => $param['role_id'], 'admin_id' => $model_admin->id]);
  255. if ($res === false) throw new Exception(AdminRole::getStaticError());
  256. } else {
  257. // 修改密码
  258. if (!empty($params['password'])) {
  259. $admin = Admin::getDefaultByMallId($model->id);
  260. $res = $admin->setNewPassword($params['password']);
  261. if ($res === false) throw new Exception('修改密码失败');
  262. }
  263. }
  264. if(isset($params['is_recycle']) && !$params['is_recycle'])Admin::updateAll(['status' => StatusEnum::ENABLED],['id'=>$model->admin_id]);
  265. if(!empty($params['id'])&&!empty($params['status'])&&$params['status']==StatusEnum::DELETE){
  266. Admin::updateAll(['status'=>StatusEnum::DELETE],['mall_id'=>$params['id']]);
  267. }
  268. // 当用户在回收站恢复是恢复其对于管理员账号
  269. if(is_numeric($params['is_recycle']) && $params['id'] && $params['is_recycle']==0) {
  270. $admin_model = Admin::findOne(['mall_id' => $model->id]);
  271. $admin_model->status = StatusEnum::ENABLED;
  272. $admin_model->save();
  273. }
  274. $t->commit();
  275. $cache_key = RedisKeyEnum::suffix(RedisKeyEnum::BACKEND_MALL,$model['mall_sign'],true);
  276. !empty($params['is_disable'])&&$params['is_disable']==1?Yii::$app->cache->delete($cache_key):Yii::$app->cache->set($cache_key, $model->toArray());
  277. if(empty($params['id'])){
  278. // 异步初始化商城
  279. $event = new MallCreateEvent($model->id);
  280. $init['id'] = $model->id;
  281. $init['operator_id'] = $params['operator_id'];
  282. $init['operator_username'] = $params['operator_username'];
  283. $init['addons_combo_id'] = $params['addons_combo_id'] ?? 0;
  284. $init['is_sync_mall_data'] = $params['is_sync_mall_data'] ?? 0;
  285. Yii::$app->services->events->dispatch($event,$init,$event->listeners);
  286. }
  287. return $model;
  288. } catch (Exception $e) {
  289. $t->rollBack();
  290. self::$static_error = $e->getMessage();
  291. return false;
  292. }
  293. }
  294. /**
  295. * @desc:获取商城信息,优先读取缓存
  296. * @Author: hua
  297. * @Date: 2022/1/13
  298. * @Time: 14:44
  299. * @Copyright: copyright (c) 2021 广东七件事集团
  300. * @param $mall_sign
  301. * @return mixed|void
  302. */
  303. public static function getMallInfo($mall_sign){
  304. $cache_key = RedisKeyEnum::suffix(RedisKeyEnum::BACKEND_MALL,$mall_sign,true);
  305. $data = Yii::$app->cache->get($cache_key);
  306. if(empty($data)) $data = Mall::getOne([['mall_sign' => $mall_sign], ['status' => StatusEnum::ENABLED]],true);
  307. return $data;
  308. }
  309. /**
  310. * 获取总页数
  311. * @Author: lun
  312. * @DateTime: 2023/4/15 0015 17:50
  313. * @Copyright: copyright (c) 2021 广东七件事集团
  314. * @param $params
  315. * @return false|float|int
  316. */
  317. public static function getMallTotalPage($params)
  318. {
  319. $query = self::find();
  320. self::paramPack($params, $query);
  321. $count = $query->count();
  322. return $count == 0 ? 0 : ceil($count / $params['limit']);
  323. }
  324. /**
  325. * 获取有期限的商城
  326. *
  327. * @return array|static[]
  328. */
  329. public static function getTimeLimitMall()
  330. {
  331. $condition = [
  332. 'and',
  333. ['>', 'expired_at', '0'],
  334. ['=', 'status', '1'],
  335. ];
  336. return static::find()->where($condition)->all();
  337. }
  338. /**
  339. * 获取商城是否过期
  340. *
  341. * @param integer $mall_id
  342. * @return boolean
  343. */
  344. public static function getIsExpired(int $mall_id)
  345. {
  346. $key = sprintf('mall_is_expired:%s', $mall_id);
  347. $redis = Yii::$app->redis;
  348. if (($is_sxpired = $redis->get($key)) !== null) return (boolean) $is_sxpired;
  349. $condition = [
  350. 'and',
  351. ['=', 'id', $mall_id],
  352. ['>', 'expired_at', '0'],
  353. ['=', 'status', '1'],
  354. ['<', 'expired_at', time()],
  355. ];
  356. $is_sxpired = static::find()->where($condition)->select('id')->exists();
  357. $redis->setex($key, 10, $is_sxpired);
  358. return $is_sxpired;
  359. }
  360. /**
  361. * 获取商城总数
  362. * @return bool|int|string|null
  363. */
  364. public static function getMallCount()
  365. {
  366. return static::find()->where(['status' => [StatusEnum::ENABLED], 'is_recycle' => 0])->count();
  367. }
  368. }