ApproachDeclarationUpgradeForm.php 20 KB

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