OrderDeleteForm.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. <?php
  2. namespace common\models\forms;
  3. use common\helpers\Cache;
  4. use common\helpers\Date;
  5. use common\components\Model;
  6. use common\helpers\Form;
  7. use common\helpers\user\Balance;
  8. use common\helpers\user\Cash;
  9. use common\helpers\user\Info;
  10. use common\libs\logging\operate\AdminOperate;
  11. use common\models\DealType;
  12. use common\models\DecOrder;
  13. use common\models\Order;
  14. use common\models\OrderGoods;
  15. use common\models\Period;
  16. use common\models\ReceiveAddress;
  17. use common\models\Region;
  18. use common\models\ShopGoods;
  19. use common\models\User;
  20. use common\models\UserNetwork;
  21. use yii\base\Exception;
  22. /**
  23. * 删除订单
  24. */
  25. class OrderDeleteForm extends Model
  26. {
  27. public $orderSn;
  28. /**
  29. * @var Order
  30. */
  31. private $_model;
  32. /**
  33. * @inheritdoc
  34. */
  35. public function rules()
  36. {
  37. return [
  38. [['orderSn'], 'trim'],
  39. [['orderSn'], 'required'],
  40. [['orderSn'], 'checkOrderType'],
  41. ];
  42. }
  43. public function attributeLabels()
  44. {
  45. return [
  46. 'orderSn' => '订单号',
  47. ];
  48. }
  49. /**
  50. * 指定校验场景
  51. * @return array
  52. */
  53. public function scenarios()
  54. {
  55. $parentScenarios = parent::scenarios();
  56. $customScenarios = [
  57. // // 管理员发货
  58. // 'adminDelivery' => ['sn', 'expressCompany', 'orderTrackNo'],
  59. // // 会员确认收货
  60. // 'userConfirm' => ['sn', 'expressCompany', 'orderTrackNo'],
  61. // // 管理员修改订单状态
  62. // 'adminStatus' => ['sn', 'status'],
  63. // // 管理员修改备注
  64. // 'adminRemark' => ['sn', 'remark'],
  65. // // 会员下单
  66. // 'userOrder' => ['type','addressId', 'payType','goodsId','goodsNum', 'remark', 'payPassword'],
  67. // // 帮会员复消下单
  68. // 'reconsumeOrder' => ['type','userName', 'payType','goodsId','goodsNum', 'remark', 'payPassword','consignee','acceptMobile','province','city','county','detailaddress'],
  69. ];
  70. return array_merge($parentScenarios, $customScenarios);
  71. }
  72. public function returnOrder() {
  73. if(!$this->validate()){
  74. return null;
  75. }
  76. $sn = $this->orderSn;
  77. // 获取订单详情
  78. $orderInfo = Order::findUseDbCalc()
  79. ->select('ID,DEC_SN,USER_ID,ORDER_TYPE,IS_DELETE')
  80. ->where("SN=:SN", [':SN' => $sn])
  81. ->asArray()
  82. ->one();
  83. // 如果会员已经是锁定状态了,删除订单的时候,是否还要退还金额
  84. $db = \Yii::$app->db;
  85. $transaction = $db->beginTransaction();
  86. try {
  87. // 如果是注册订单,则删除订单并退还金额,然后再冻结用户
  88. if ($orderInfo['ORDER_TYPE'] == 'ZC') {
  89. // 锁定用户
  90. $userModel = User::findOne(['ID' => $orderInfo['USER_ID']]);
  91. $userModel->STATUS = 0;
  92. $userModel->STATUS_AT = Date::nowTime();
  93. if(!$userModel->save(false)) {
  94. $transaction->rollBack();
  95. throw new Exception('锁定会员失败,删除订单失败');
  96. }
  97. } else {
  98. // 如果是复消单,则删除订单并退还金额
  99. }
  100. // 公共的退钱,删除订单操作
  101. $delOrder = Order::updateAll(['PV_PSS'=>0, 'PV_PSS_TOTAL'=>0], 'USER_ID=:USER_ID', ['USER_ID'=>$oldParentUid]);
  102. $transaction->commit();
  103. } catch(Exception $e) {
  104. $transaction->rollBack();
  105. $this->addError('add', $e->getMessage());
  106. return null;
  107. }
  108. }
  109. /**
  110. * 判断支付方式
  111. * @param $attribute
  112. */
  113. public function isPayType($attribute){
  114. if(!array_key_exists($this->payType, ShopGoods::payTypes())){
  115. $this->addError($attribute, '支付方式错误');
  116. return;
  117. }
  118. }
  119. // 判断订单类型
  120. public function checkOrderType($attribute) {
  121. $sn = $this->orderSn;
  122. $orderDetail = Order::findUseDbCalc()
  123. ->select('ID,DEC_SN,USER_ID,ORDER_TYPE,IS_DELETE')
  124. ->where("SN=:SN", [':SN' => $sn])
  125. ->asArray()
  126. ->one();
  127. if (empty($orderDetail)) {
  128. $this->addError($attribute, '未找到订单信息,订单编号为:'.$this->orderSn);
  129. return ;
  130. }
  131. if ($orderDetail['IS_DELETE'] == 1) {
  132. $this->addError($attribute, '订单已被删除,订单编号为'.$this->orderSn);
  133. return ;
  134. }
  135. // 已挂网或者挂网中的业绩期订单,不能进行删除操作
  136. $periodNum = $orderDetail['PERIOD_NUM'];
  137. $periodObj = Period::findOneAsArray(['PERIOD_NUM'=>$periodNum]);
  138. if (empty($periodObj)) {
  139. $this->addError($attribute, '订单对应业绩期不存在,订单编号为'.$this->orderSn.' 业绩期为:'.$periodNum);
  140. return ;
  141. }
  142. if ($periodObj['IS_SENT'] == 1) {
  143. $this->addError($attribute, '订单对应业绩期已挂网,订单编号为'.$this->orderSn.' 业绩期为:'.$periodNum);
  144. return ;
  145. }
  146. if ($periodObj['IS_SENDING'] == 1) {
  147. $this->addError($attribute, '订单对应业绩期正在挂网,订单编号为'.$this->orderSn.' 业绩期为:'.$periodNum);
  148. return ;
  149. }
  150. if ($orderDetail['ORDER_TYPE'] == 'ZC') {
  151. $decDetail = DecOrder::findUseDbCalc()
  152. ->select('TO_USER_ID,DETAIL_TYPE,UPGRADE_TYPE,IS_DEL')
  153. ->where("ORDER_SN=:ORDER_SN", [':ORDER_SN' => $sn])
  154. ->asArray()
  155. ->one();
  156. if (empty($decDetail)) {
  157. $this->addError($attribute, '未获取到对应报单信息,订单编号为:'.$this->orderSn);
  158. return ;
  159. }
  160. if ($decDetail['IS_DEL'] == 1) {
  161. $this->addError($attribute, '对应报单信息已被删除,订单编号为:'.$this->orderSn);
  162. return ;
  163. }
  164. // 如果是注册订单,则判断是否是升级单,如果是升级单,则不能进行删除
  165. if ($decDetail['DETAIL_TYPE'] == 2) {
  166. $this->addError($attribute, '升级单无法删除,订单编号为:'.$this->orderSn);
  167. return ;
  168. } else {
  169. // 如果是注册单,但是这个用户存在升级单,则也不能进行删除
  170. $hasUpgradeOrder = DecOrder::findUseDbCalc()
  171. ->select('TO_USER_ID,DETAIL_TYPE,UPGRADE_TYPE,IS_DEL')
  172. ->where("TO_USER_ID=:TO_USER_ID AND IS_DEL=0 AND DETAIL_TYPE=2", [':TO_USER_ID' => $decDetail['TO_USER_ID']])
  173. ->asArray()
  174. ->one();
  175. if (!empty($hasUpgradeOrder)) {
  176. $this->addError($attribute, '此注册报单用户,存在升级单,无法删除,订单编号为:'.$this->orderSn);
  177. return ;
  178. }
  179. // 删除注册单,判断是否有复消单,如果存在复消单,需要先删除复消单
  180. $hasFxOrder = Order::findUseDbCalc()
  181. ->select('SN')
  182. ->where("USER_ID=:USER_ID AND IS_DELETE=0 AND ORDER_TYPE='FX'", [':USER_ID' => $decDetail['TO_USER_ID']])
  183. ->asArray()
  184. ->one();
  185. if (!empty($hasFxOrder)) {
  186. $this->addError($attribute, '此注册报单用户,存在复消单,无法删除,订单编号为:'.$this->orderSn);
  187. return ;
  188. }
  189. }
  190. }
  191. return true;
  192. }
  193. /**
  194. * 校验类型
  195. * @param $attribute
  196. */
  197. public function isStatus($attribute){
  198. if(!in_array($this->type, \Yii::$app->params['orderStatus'])){
  199. $this->addError($attribute, '类型错误');
  200. return ;
  201. }
  202. if ($this->scenario == 'adminStatus'){
  203. if ($this->status == $this->_model['STATUS']) {
  204. $this->addError($attribute, '订单状态没有改变');
  205. return ;
  206. }
  207. if($this->status == \Yii::$app->params['orderStatus']['notPaid'] && $this->_model['STATUS'] >= \Yii::$app->params['orderStatus']['delivery']) {
  208. $this->addError($attribute, '订单已经进入物流状态不能改为未支付');
  209. return ;
  210. }
  211. elseif($this->status == \Yii::$app->params['orderStatus']['paid'] && $this->_model['STATUS'] >= \Yii::$app->params['orderStatus']['cancel']) {
  212. $this->addError($attribute, '订单已失效不能处理');
  213. return ;
  214. }
  215. elseif($this->status == \Yii::$app->params['orderStatus']['delivery']) {
  216. $this->addError($attribute, '订单不能单独处理为物流状态');
  217. return ;
  218. }
  219. elseif($this->status == \Yii::$app->params['orderStatus']['complete'] && $this->_model['STATUS'] > \Yii::$app->params['orderStatus']['cancel']) {
  220. $this->addError($attribute, '订单已失效不能处理');
  221. return ;
  222. }
  223. elseif($this->status == \Yii::$app->params['orderStatus']['cancel']) {
  224. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['complete']) {
  225. $this->addError($attribute, '订单已完成不能取消');
  226. return ;
  227. }
  228. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['del']) {
  229. $this->addError($attribute, '订单已删除不能取消');
  230. return ;
  231. }
  232. }
  233. elseif($this->status == \Yii::$app->params['orderStatus']['del']) {
  234. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['complete']) {
  235. $this->addError($attribute, '订单已完成不能删除');
  236. return ;
  237. }
  238. }
  239. }
  240. }
  241. /**
  242. * 帮会员复销
  243. * @return bool|null
  244. * @throws Exception
  245. * @throws \yii\db\Exception
  246. */
  247. public function reconsumeAdd(){
  248. if(!$this->validate()){
  249. return null;
  250. }
  251. $ids = $this->goodsId;
  252. $totalAmount = 0;
  253. $totalPv = 0;
  254. $goodsType = ShopGoods::GOODS_TYPE;
  255. foreach ($this->goodsNum as $k => $v) {
  256. if ($v) {
  257. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  258. if($goods['STORE_NUMS']>0){
  259. if ($goods['TYPE'] == 1 || $goods['TYPE'] == 2) {
  260. $discount = $goodsType[$goods['TYPE']]['discount'];
  261. $realPrice = $goods['SELL_PRICE'] * $discount/100;
  262. $realPv = $goods['PRICE_PV'] * $discount/100;
  263. } else {
  264. $discount = $goods['SELL_DISCOUNT'];
  265. $realPrice = $goods['SELL_PRICE'] * $discount;
  266. $realPv = $goods['PRICE_PV'] * $discount;
  267. }
  268. $totalAmount += $realPrice * intval($v);
  269. $totalPv += $realPv * intval($v);
  270. $this->_orderGoods[] = [
  271. 'GOODS_ID' => $goods['ID'],
  272. 'PRICE' => $goods['SELL_PRICE'],
  273. 'PV' => $goods['PRICE_PV'],
  274. 'REAL_PRICE' => $realPrice,
  275. 'REAL_PV' => $realPv,
  276. 'POINT' => $goods['POINT'],
  277. 'BUY_NUMS' => intval($v),
  278. 'SKU_CODE' => $goods['GOODS_NO'],
  279. 'GOODS_TITLE' => $goods['GOODS_NAME']
  280. ];
  281. }
  282. }
  283. }
  284. $this->_decAmount = $totalAmount;
  285. $this->_decPv = $totalPv;
  286. $this->_freight = ($totalAmount>=300) ? 0 : 15;
  287. $this->_payAmount = $this->_decAmount + $this->_freight;
  288. $db = \Yii::$app->db;
  289. $transaction = $db->beginTransaction();
  290. try {
  291. $loginUserId = \Yii::$app->user->id;
  292. //是否开启伞下会员限制
  293. $isResaleUmbrella = Cache::getSystemConfig()['isResaleUmbrella']['VALUE'];
  294. if($isResaleUmbrella){
  295. $userId = Info::getUserIdByUserName($this->userName);
  296. $userNetwork = UserNetwork::find()->where("USER_ID=:USER_ID AND INSTR(PARENT_UIDS,'{$loginUserId}')>0", ['USER_ID'=>$userId])->count();
  297. if(!$userNetwork){
  298. throw new Exception($this->userName.'不是您的伞下会员,不能为其复消!');
  299. }
  300. }
  301. //判断用户余额是否充足
  302. if($this->payType=='cash') {
  303. if (Cash::getAvailableBalance($loginUserId) < $this->_payAmount) {
  304. throw new Exception('余额不足,无法购买商品');
  305. }
  306. }else{
  307. if ($this->_payAmount > Balance::getBalanceReconsumePoints($loginUserId)) {
  308. throw new Exception('复消积分不足,无法购买商品');
  309. }
  310. }
  311. //写入订单
  312. if (!$orderResult = $this->addUserOrder()) {
  313. throw new Exception(Form::formatErrorsForApi($orderResult->getErrors()));
  314. }
  315. $transaction->commit();
  316. }catch (\Exception $e){
  317. $transaction->rollBack();
  318. $this->addError('add', $e->getMessage());
  319. return null;
  320. }
  321. return true;
  322. }
  323. /**
  324. * 帮会员复消的订单
  325. */
  326. public function addUserOrder(){
  327. $periodObj = Period::instance();
  328. $nowPeriodNum = $periodObj->getNowPeriodNum();
  329. $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
  330. //帮复消会员Id(登陆会员)
  331. $loginUserId = \Yii::$app->user->id;
  332. $loginUserName = Info::getUserNameByUserId($loginUserId);
  333. //订单会员Id
  334. $userId = Info::getUserIdByUserName($this->userName);
  335. // 加入订单信息
  336. $warehouse = Region::getWarehouseByCode($this->province);//仓库
  337. if(!$warehouse){
  338. throw new Exception('地区暂时不支持配送,具体联系客服');
  339. }
  340. $ordNo = $this->_generateSn();
  341. $orderModel = new Order();
  342. $orderModel->SN = 'OS'.$ordNo;
  343. $orderModel->DEC_SN = 'DS'.$ordNo;
  344. $orderModel->ORDER_TYPE = $this->type;
  345. $orderModel->USER_ID = $userId;
  346. $orderModel->USER_NAME = $this->userName;
  347. $orderModel->ORDER_AMOUNT = $this->_decAmount;
  348. $orderModel->PV = $this->_decPv;
  349. $orderModel->PAY_AMOUNT = $this->_payAmount;
  350. $orderModel->PAY_PV = $this->_decPv;
  351. $orderModel->PAY_AT = Date::nowTime();
  352. $orderModel->PAY_TYPE = $this->payType;
  353. $orderModel->PERIOD_NUM = $nowPeriodNum;
  354. $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  355. $orderModel->FREIGHT = $this->_freight;
  356. $orderModel->PAY_FREIGHT = $this->_freight;
  357. $orderModel->CONSIGNEE = $this->consignee;
  358. $orderModel->MOBILE = $this->acceptMobile;
  359. $orderModel->PROVINCE = $this->province;
  360. $orderModel->CITY = $this->city;
  361. $orderModel->COUNTY = $this->county;
  362. $orderModel->ADDRESS = $this->detailaddress;
  363. $orderModel->FRONT_REMARK = $this->remark;
  364. $orderModel->WAREHOUSE = $warehouse;
  365. $orderModel->STATUS = 1;
  366. $orderModel->CREATED_AT = Date::nowTime();
  367. $orderModel->CREATE_USER = $loginUserName;
  368. if(!$orderModel->save()){
  369. $this->addErrors($orderModel->getErrors());
  370. return false;
  371. }
  372. // 加入商品到订单商品表
  373. foreach($this->_orderGoods as $key=>$value){
  374. $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN;
  375. $this->_orderGoods[$key]['P_CALC_MONTH'] = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  376. }
  377. OrderGoods::batchInsert($this->_orderGoods);
  378. //扣除会员余额/积分
  379. if($this->payType=='cash') {
  380. Cash::changeUserCash($loginUserId, 'CASH', -abs($this->_payAmount), ['REMARK' => '会员复销余额支付']);
  381. }else{
  382. Balance::changeUserBonus($loginUserId,'reconsume_points', -abs($this->_payAmount),['DEAL_TYPE_ID' => DealType::RECONSUME_POINTS_EXCHANGE, 'REMARK' => '会员复销积分兑换']);
  383. }
  384. return $orderModel;
  385. }
  386. /**
  387. * 生成流水号
  388. * @return string
  389. */
  390. private function _generateSn() {
  391. return Date::today('Ymd') . $this->_random(10, 1);
  392. }
  393. /**
  394. * 生成随机数
  395. * @param $length
  396. * @param int $numeric
  397. * @return string
  398. */
  399. private function _random($length, $numeric = 0) {
  400. $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
  401. $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
  402. $hash = '';
  403. $max = strlen($seed) - 1;
  404. for ($i = 0; $i < $length; $i++) {
  405. $hash .= $seed[mt_rand(0, $max)];
  406. }
  407. return $hash;
  408. }
  409. }