DeclarationUpgradeForm.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. <?php
  2. namespace common\models\forms;
  3. use common\components\Model;
  4. use common\helpers\Cache;
  5. use common\helpers\Date;
  6. use common\helpers\Form;
  7. use common\helpers\user\Cash;
  8. use common\helpers\user\Info;
  9. use common\models\Config;
  10. use common\models\DeclarationLevel;
  11. use common\models\DeclarationPackage;
  12. use common\models\DecLevelLog;
  13. use common\models\DecOrder;
  14. use common\models\EmployLevel;
  15. use common\models\Order;
  16. use common\models\OrderGoods;
  17. use common\models\Period;
  18. use common\models\ReceiveAddress;
  19. use common\models\Region;
  20. use common\models\ShopGoods;
  21. use common\models\User;
  22. use common\models\UserInfo;
  23. use common\models\UserNetwork;
  24. use yii\base\Exception;
  25. /**
  26. * 升级管理,进行升级
  27. */
  28. class DeclarationUpgradeForm extends Model
  29. {
  30. public $type;
  31. public $decLv;
  32. public $decWay;
  33. public $packageId;
  34. public $goodsId;
  35. public $goodsNum;
  36. public $insertUserName;
  37. public $consignee;
  38. public $acceptMobile;
  39. public $province;
  40. public $city;
  41. public $county;
  42. public $lgaName;
  43. public $cityName;
  44. public $address;
  45. public $nowPerf;
  46. public $nextPerf;
  47. public $decUserName;
  48. public $remark;
  49. // 传过来的全部数据
  50. public $allData;
  51. private $_decId;
  52. public $_insertUserId;
  53. private $_decAmount;
  54. private $_decPv;
  55. private $_orderGoods;
  56. const TYPE_ZC = 'ZC';
  57. private $_userForm = null;
  58. // 全部的安置网上级
  59. private $_tempNetworkParentUser = [];
  60. /**
  61. * @inheritdoc
  62. */
  63. public function rules()
  64. {
  65. return [
  66. [['remark','type','decLv','decWay','packageId','goodsId', 'goodsNum', 'insertUserName','consignee','acceptMobile','province',/*'city','county',*/'lgaName','cityName','address','nowPerf','nextPerf'], 'trim'],
  67. [['type','decLv','decWay','insertUserName','nowPerf','province',/*'city','county',*/'address','acceptMobile'], 'required'],
  68. [['decUserName'], 'issetDec'], // 必须是报单中心
  69. [['decWay'], 'hasProduct'],// 必须选择商品
  70. [['decLv'], 'alreadyMaxDec'], //判断要升级用户是否已经是最高级
  71. ];
  72. }
  73. public function attributeLabels()
  74. {
  75. return [
  76. 'type' => 'Upgrade type',//升级类型
  77. 'decLv' => 'Upgrade level',//升级级别
  78. 'decWay' => 'Declaration method',//报单方式
  79. 'packageId' => 'Upgrade package',//升级套餐
  80. 'goodsId' => 'Product ID',//商品ID
  81. 'goodsNum' => 'Product quantity',//商品数量
  82. 'insertUserName' => 'Member number to be upgraded',//要升级的会员编号
  83. 'consignee' => 'consignee',//收货人
  84. 'acceptMobile' => 'The phone number of Consignee',//收货人手机
  85. 'province' => 'Receiving Province',//收货省
  86. 'city' => 'Receiving City',//收货市
  87. 'county' => 'Receiving area / county',//收货区县
  88. 'lgaName' => 'Local Government Area',
  89. 'cityName' => 'City',
  90. 'address' => 'Receiving detailed address',//收货详细地址
  91. ];
  92. }
  93. /**
  94. * 添加报单
  95. * @param $allData
  96. * @return bool|null
  97. * @throws Exception
  98. * @throws \yii\db\Exception
  99. */
  100. public function add($allData){
  101. if(!$this->validate()){
  102. return null;
  103. }
  104. $loginUserId = \Yii::$app->user->id;
  105. // 首购单
  106. if($this->type == self::TYPE_ZC){
  107. //报单商品及PV判断
  108. $decLevelConfig = Cache::getDecLevelConfig();
  109. $decLevel = $decLevelConfig[$this->decLv];
  110. $toDecLevel = $this->decLv;
  111. if(!$this->decLv){
  112. throw new Exception('Please select upgrade level');//请选择升级级别
  113. }
  114. $baseInfo = Info::baseInfoZhByUserName($this->insertUserName);
  115. $userId = $baseInfo['ID'];
  116. $userDecPvSum = User::sumDevPvByUserId($userId); // 用户所有报单PV总和
  117. if ($userDecPvSum != $this->nowPerf) {
  118. throw new Exception('Please contact the customer service personnel to check the performance of upgraded members');//请联系客服人员核对升级会员业绩
  119. }
  120. // 获取用户是否是观察期
  121. $observe = Config::getConfigByType('observe'); // 获取观察期配置信息
  122. $observeLimit = $observe['observePeriodLimit']['value']; // 月份限制
  123. $isObserve = User::checkIsObserve($baseInfo['CREATED_AT'], $observeLimit); // 判断用户是否再观察期中
  124. $diffPerf = $isObserve ? $this->nowPerf : 0; // 观察期内升级要加上用户累计的PV,全额则基础PV为0,全额购买
  125. if ($this->decWay != 2) {
  126. throw new Exception('The upgrade method is incorrect. Please contact the customer service personnel');//升级方式不正确,请联系客服人员
  127. }
  128. if($this->decWay==1) {
  129. // 先不加套餐升级方式
  130. // $decPackage = DeclarationPackage::findOneAsArray('ID=:ID', [':ID'=>$this->packageId]);
  131. // $this->_decAmount = $decPackage['AMOUNT'];
  132. // $this->_decPv = $decPackage['PV'];
  133. // $this->_orderGoods[] = [
  134. // 'GOODS_ID' => $this->packageId,
  135. // 'PRICE' => $this->_decAmount,
  136. // 'REAL_PRICE' => $this->_decAmount,
  137. // 'PV' => $this->_decPv,
  138. // 'REAL_PV' => $this->_decPv,
  139. // 'BUY_NUMS' => 1,
  140. // 'SKU_CODE' => $decPackage['PACKAGE_NO'],
  141. // 'GOODS_TITLE' => $decPackage['PACKAGE_NAME']
  142. // ];
  143. } else {
  144. $ids = $this->goodsId;
  145. $totalAmount = 0;
  146. $totalPv = 0;
  147. foreach ($this->goodsNum as $k => $v) {
  148. if ($v) {
  149. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  150. if($goods['STORE_NUMS']>0){
  151. $totalAmount += $goods['SELL_PRICE'] * intval($v);
  152. $totalPv += $goods['PRICE_PV'] * intval($v);
  153. $this->_orderGoods[] = [
  154. 'GOODS_ID' => $goods['ID'],
  155. 'PRICE' => $goods['SELL_PRICE'],
  156. 'REAL_PRICE' => $goods['SELL_PRICE'],
  157. 'PV' => $goods['PRICE_PV'],
  158. 'REAL_PV' => $goods['PRICE_PV'],
  159. 'POINT' => $goods['POINT'],
  160. 'BUY_NUMS' => intval($v),
  161. 'SKU_CODE' => $goods['GOODS_NO'],
  162. 'GOODS_TITLE' => $goods['GOODS_NAME']
  163. ];
  164. }
  165. }
  166. }
  167. // 这里特殊是用户原报单PV之和+用户购买的商品总PV
  168. $checkPv = $totalPv + $diffPerf;
  169. if($checkPv < $decLevel['PERF']) {
  170. throw new Exception('Total PV cannot be less than the selected level PV');//总PV不能小于所选级别PV
  171. }
  172. foreach ($decLevelConfig as $key=>$val){
  173. if($checkPv>=$val['PERF']){
  174. $toDecLevel = $key;
  175. }
  176. }
  177. if($this->decLv!=$toDecLevel){
  178. throw new Exception('The total PV cannot exceed the PV value of the next level under the selected level');//总PV不能超过已选级别下一个级别的PV值
  179. }
  180. $this->_decAmount = $totalAmount;
  181. $this->_decPv = $totalPv;
  182. }
  183. //看现金余额是否充足
  184. if (Cash::getAvailableBalance($loginUserId) < $this->_decAmount){
  185. throw new Exception('The applicant is short of cash and cannot complete the declaration');//报单人现金不足,无法完成报单
  186. }
  187. $baseInfo = Info::baseInfoZhByUserName($this->insertUserName);
  188. $this->_insertUserId = $baseInfo['ID']; // 被报单人,通过insername 查找用户id
  189. $insertConId = $baseInfo['CON_UID'];
  190. $insertRecId = $baseInfo['REC_UID'];
  191. if(!($decResult = $this->addDecOrder($insertConId,$insertRecId, $baseInfo['DEC_LV'],$isObserve,$this->remark))) {
  192. throw new Exception("operation failed");//操作失败
  193. }
  194. }
  195. return true;
  196. }
  197. /**
  198. * 添加报单订单
  199. * @return bool|UserInfo|null
  200. * @throws \yii\db\Exception
  201. */
  202. public function addDecOrder($insertConId,$insertRecId,$oriDecLv,$isObserve,$remark=''){
  203. $warehouse = Region::getWarehouseByCode($this->province);//仓库
  204. if(!$warehouse){
  205. throw new Exception('Delivery is temporarily not supported in the region. Contact customer service for details');//地区暂时不支持配送,具体联系客服
  206. }
  207. $upgradeType = $isObserve ? 1 : 2; // 1补差 2全额
  208. $periodObj = Period::instance();
  209. $nowPeriodNum = $periodObj->getNowPeriodNum();
  210. $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
  211. $ord = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 10);
  212. // 加入报单信息
  213. $db = \Yii::$app->db;
  214. $transaction = $db->beginTransaction();
  215. try {
  216. $decOrderModel = new DecOrder();
  217. $decOrderModel->DEC_SN = 'DS'.$ord;
  218. $decOrderModel->ORDER_SN = 'OS'.$ord;
  219. $decOrderModel->TYPE = $this->type;
  220. $decOrderModel->USER_ID = \Yii::$app->user->id; // 报单人
  221. $decOrderModel->TO_USER_ID = $this->_insertUserId; // 被报单人
  222. $decOrderModel->DEC_AMOUNT = $this->_decAmount;
  223. $decOrderModel->DEC_PV = $this->_decPv;
  224. $decOrderModel->PERIOD_NUM = $nowPeriodNum;
  225. $decOrderModel->CALC_MONTH = $nowCalcMonth;
  226. $decOrderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  227. $decOrderModel->PAID_WALLET = 'cash';
  228. $decOrderModel->CON_USER_ID = $insertConId;
  229. $decOrderModel->REC_USER_ID = $insertRecId;
  230. $decOrderModel->DEC_ID = $this->_decId;
  231. $decOrderModel->IS_DEL = 0;
  232. $decOrderModel->DETAIL_TYPE = 2;
  233. $decOrderModel->CREATED_AT = Date::nowTime();
  234. $decOrderModel->UPGRADE_TYPE = $upgradeType;
  235. $decOrderModel->REMARK = $remark;
  236. $decOrderModel->ORI_LV = $oriDecLv; // 变更前的级别
  237. $decOrderModel->UPGRADE_LV = $this->decLv; // 变更后的级别
  238. if(!$decOrderModel->save()){
  239. $transaction->rollBack();
  240. throw new Exception(Form::formatErrorsForApi($decOrderModel->getErrors()));
  241. }
  242. $orderModel = new Order();
  243. $orderModel->SN = 'OS'.$ord;
  244. $orderModel->DEC_SN = 'DS'.$ord;
  245. $orderModel->ORDER_TYPE = $this->type;
  246. $orderModel->USER_ID = $this->_insertUserId;
  247. $orderModel->USER_NAME = $this->insertUserName; // 要升级的用户
  248. $orderModel->ORDER_AMOUNT = $this->_decAmount;
  249. $orderModel->PV = $this->_decPv;
  250. $orderModel->PAY_AMOUNT = $this->_decAmount;
  251. $orderModel->PAY_PV = $this->_decPv;
  252. $orderModel->PAY_AT = Date::nowTime();
  253. $orderModel->PAY_TYPE = 'cash';
  254. $orderModel->PERIOD_NUM = $nowPeriodNum;
  255. $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  256. $orderModel->FREIGHT = 0;
  257. $orderModel->PAY_FREIGHT = 0;
  258. $orderModel->CONSIGNEE = $this->consignee;
  259. $orderModel->MOBILE = $this->acceptMobile;
  260. $orderModel->PROVINCE = $this->province;
  261. // $orderModel->CITY = $this->city;
  262. // $orderModel->COUNTY = intval($this->county) ?? 0;
  263. $orderModel->LGA_NAME = $this->lgaName;
  264. $orderModel->CITY_NAME = $this->cityName;
  265. $orderModel->ADDRESS = $this->address;
  266. $orderModel->WAREHOUSE = $warehouse;
  267. $orderModel->STATUS = 1;
  268. $orderModel->CREATED_AT = Date::nowTime();
  269. $orderModel->CREATE_USER = Info::getUserNameByUserId(\Yii::$app->user->id);
  270. if(!$orderModel->save()){
  271. $transaction->rollBack();
  272. throw new Exception(Form::formatErrorsForApi($orderModel->getErrors()));
  273. }
  274. /**
  275. * 2022-05-10
  276. * York
  277. */
  278. foreach ($this->goodsNum as $k => $v) {
  279. if ($v) {
  280. $goods = ShopGoods::findOneAsArray('ID=:ID',[':ID'=> $this->goodsId[$k]]);
  281. $storenums = $goods['STORE_NUMS'] - $this->goodsNum[$k];
  282. if($goods['STATUS']==1){
  283. if($goods['STORE_NUMS'] >=$this->goodsNum[$k]){
  284. $data = ShopGoods::find()->where(['ID' => $this->goodsId[$k]])->one();
  285. $data->STORE_NUMS = $storenums;
  286. $data->update();
  287. if ($storenums==0){
  288. $data->STATUS = 0;
  289. $data->UPDATED_AT = Date::nowTime();
  290. $data->update();
  291. }
  292. }else{
  293. // throw new Exception("商品".$goods['GOODS_NAME']."库存不足");
  294. throw new Exception("product".$goods['GOODS_NAME']."Insufficient inventory");
  295. }
  296. }else{
  297. // throw new Exception("商品".$goods['GOODS_NAME']."已下架");
  298. throw new Exception("product".$goods['GOODS_NAME']."Removed from the shelf");
  299. }
  300. }
  301. }
  302. // exit();
  303. // 加入商品到订单商品表
  304. foreach($this->_orderGoods as $key=>$value){
  305. $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN;
  306. $this->_orderGoods[$key]['P_CALC_MONTH'] = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  307. }
  308. OrderGoods::batchInsert($this->_orderGoods);
  309. //写入收货地址信息
  310. $addressModel = new ReceiveAddress();
  311. $addressModel->USER_ID = $this->_insertUserId;
  312. $addressModel->USER_NAME = $this->insertUserName;
  313. $addressModel->CONSIGNEE = $this->consignee;
  314. $addressModel->MOBILE = $this->acceptMobile;
  315. $addressModel->PROVINCE = $this->province;
  316. // $addressModel->CITY = $this->city;
  317. // $addressModel->COUNTY = intval($this->county) ?? 0;
  318. $addressModel->LGA_NAME = $this->lgaName;
  319. $addressModel->CITY_NAME = $this->cityName;
  320. $addressModel->ADDRESS = $this->address;
  321. $addressModel->IS_DEFAULT = 0;
  322. // print_r($addressModel);
  323. if(!$addressModel->save()){
  324. $transaction->rollBack();
  325. throw new Exception(Form::formatErrorsForApi($addressModel->getErrors()));
  326. }
  327. // 扣报单人现金钱包
  328. // Cash::changeUserCash(\Yii::$app->user->id, 'CASH', -abs($this->_decAmount), ['REMARK' =>'为'.$this->insertUserName.'升级报单']);
  329. Cash::changeUserCash(\Yii::$app->user->id, 'CASH', -abs($this->_decAmount), ['REMARK' =>'by'.$this->insertUserName.'Upgrade entry']);
  330. // 为被升级人进行升级操作
  331. $decLevelLog = new DecLevelLog();
  332. $decLog = [
  333. 'userId' => $this->_insertUserId,//会员ID
  334. 'fromId' => $oriDecLv, // 变动前的级别
  335. 'levelId' => $this->decLv,// 变动后的级别
  336. 'actionId' => \Yii::$app->user->id,
  337. 'remark' => $this->remark,
  338. 'lvPv' => $this->_decPv
  339. ];
  340. $modifyDecLv = $decLevelLog->frontendChange($decLog);
  341. if (empty($modifyDecLv)) {
  342. $transaction->rollBack();
  343. throw new Exception("Failed to upgrade for member");//为会员升级失败
  344. }
  345. $transaction->commit();
  346. } catch(Exception $e) {
  347. $transaction->rollBack();
  348. throw new Exception($e->getMessage());
  349. return false;
  350. }
  351. return $modifyDecLv;
  352. }
  353. /**
  354. * 判断报单中心是否存在
  355. * @param $attribute
  356. */
  357. public function issetDec($attribute){
  358. $decUser = User::find()
  359. ->select('ID')
  360. ->where('IS_DEC=1 AND USER_NAME=:USER_NAME', [':USER_NAME' => $this->decUserName])
  361. ->asArray()
  362. ->one();
  363. if (!$decUser) {
  364. $this->addError($attribute, 'Entry center does not exist');//报单中心不存在
  365. return false;
  366. } else {
  367. // 判断报单中心是否在新加入会员的安置网上级中
  368. $this->loopFindParentToNetwork($this->insertUserName);
  369. //反转数组,in_array搜索错误
  370. //in_array($this->decUserName, $this->_tempNetworkParentUser[$this->insertUserName]);
  371. $flipParent = array_flip(array_filter($this->_tempNetworkParentUser[$this->insertUserName]));
  372. if (!isset($flipParent[$this->decUserName])) {
  373. // $this->addError($attribute, '为' . $this->insertUserName . '升级报单,报单中心' . $this->decUserName . '不在' . $this->insertUserName . '的安置网上级中');
  374. $this->addError($attribute, 'by' . $this->insertUserName . 'Upgrade declaration, declaration Center' . $this->decUserName . 'be not in' . $this->insertUserName . 'Online level of resettlement');
  375. return ;
  376. }
  377. $this->_decId = $decUser['ID'];
  378. }
  379. }
  380. // 判断是否已选择商品或套餐
  381. public function hasProduct($attribute) {
  382. if ($this->decWay==1 && empty($this->packageId)) {
  383. $this->addError($attribute, 'Purchase package upgrade, please select package');//购买套餐升级,请选择套餐
  384. return false;
  385. }
  386. if ($this->decWay!=1 && empty($this->goodsId)) {
  387. $this->addError($attribute, 'Purchase product upgrade, please select product');//购买商品升级,请选择商品'
  388. return false;
  389. }
  390. return true;
  391. }
  392. // 判断要升级的会员,是否已是最高级别
  393. public function alreadyMaxDec($attribute) {
  394. $baseInfo = Info::baseInfoZhByUserName($this->insertUserName);
  395. $userDecId = $baseInfo['DEC_LV'];// 用户当前的级别
  396. $maxPerfInfo = DeclarationLevel::getMaxDecPref();
  397. $maxDecId = $maxPerfInfo['ID']; // 级别配置中最高级别ID
  398. if ($maxDecId == $userDecId) {
  399. $this->addError($attribute, 'It is already the highest level and no upgrade is required');//已是最高级别,无需升级
  400. return false;
  401. }
  402. return true;
  403. }
  404. /**
  405. * 寻找被升级人的上级
  406. * @param null $conUserName
  407. * @return bool
  408. */
  409. private function loopFindParentToNetwork($conUserName = null) {
  410. if($conUserName == null ){
  411. $conUserName = $this->insertUserName;
  412. }
  413. $baseUser = Info::getBaseUserByUserName($conUserName);
  414. $userNetworkInfo = UserNetwork::findOneAsArray('USER_ID=:USER_ID', [':USER_ID' => $baseUser['ID']]);
  415. unset($baseUser);
  416. $allParentUserIdsArr = explode(',', $userNetworkInfo['PARENT_UIDS']);
  417. unset($userNetworkInfo);
  418. $allParentUserIds = array_reverse($allParentUserIdsArr);
  419. unset($allParentUserIdsArr);
  420. if($allParentUserIds){
  421. foreach($allParentUserIds as $parentUserId) {
  422. $parentBaseUser = Info::getBaseUserById($parentUserId);
  423. $this->_tempNetworkParentUser[$this->insertUserName][] = $parentBaseUser['USER_NAME'] ;
  424. unset($parentUserId, $parentBaseUser);
  425. }
  426. }
  427. unset($allParentUserIds);
  428. return true;
  429. }
  430. // /**
  431. // * 删单
  432. // * @return bool
  433. // * @throws \yii\db\Exception
  434. // */
  435. // public function delete(){
  436. // if(!$this->validate()){
  437. // return false;
  438. // }
  439. // $transaction = \Yii::$app->db->beginTransaction();
  440. // try {
  441. // $oneOrder = $this->_oneOrder;
  442. // // 首购单要删除会员
  443. // if($this->type == self::TYPE_ZC){
  444. // UserInfo::deleteUser($oneOrder['TO_USER_ID']);
  445. // }
  446. // // 如果是复销单的话,还需要考虑给会员的复销池减去金额
  447. // elseif($this->type == self::TYPE_FX){
  448. // Reconsume::changePoolPV($oneOrder['TO_USER_ID'], -abs($oneOrder['DEC_PV']), ['REMARK'=>'删单扣除', 'DEAL_TYPE'=>Reconsume::TYPE_AUDIT_PV]);
  449. // }
  450. // $transaction->commit();
  451. // } catch (Exception $e) {
  452. // $transaction->rollBack();
  453. // $this->addError('delete', $e->getMessage());
  454. // return false;
  455. // }
  456. // return true;
  457. // }
  458. }