ApproachOrderForm.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  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\PayStack;
  8. use common\helpers\user\Balance;
  9. use common\helpers\user\Cash;
  10. use common\helpers\user\Info;
  11. use common\libs\logging\operate\AdminOperate;
  12. use common\models\ApproachOrder;
  13. use common\models\ApproachOrderGoods;
  14. use common\models\DealType;
  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\UserNetwork;
  23. use yii\base\Exception;
  24. /**
  25. * Login form
  26. */
  27. class ApproachOrderForm extends Model
  28. {
  29. public $sn;
  30. public $expressCompany;
  31. public $orderTrackNo;
  32. public $status;
  33. public $remark;
  34. public $type;
  35. public $addressId;
  36. public $payType;
  37. public $goodsId;
  38. public $goodsNum;
  39. public $payPassword;
  40. public $email;
  41. public $userName;
  42. public $consignee;
  43. public $acceptMobile;
  44. public $province;
  45. public $city;
  46. public $county;
  47. public $detailaddress;
  48. private $_address;
  49. private $_decAmount;
  50. private $_decPv;
  51. private $_freight;
  52. private $_payAmount;
  53. private $_orderGoods;
  54. /**
  55. * @var ApproachOrder
  56. */
  57. private $_model;
  58. public function init() {
  59. parent::init();
  60. $this->adminOperateLogger = new AdminOperate([
  61. 'fetchClass' => ApproachOrder::class,
  62. ]);
  63. }
  64. /**
  65. * @inheritdoc
  66. */
  67. public function rules()
  68. {
  69. return [
  70. [['sn', 'expressCompany', 'orderTrackNo', 'status', 'remark','type','addressId','payType','goodsId','goodsNum', 'payPassword','userName','consignee','acceptMobile','province','city','county','detailaddress','email'], 'trim'],
  71. [['sn', 'expressCompany', 'orderTrackNo', 'status', 'remark','type','addressId','payType','goodsId','goodsNum', 'payPassword','userName','consignee','acceptMobile','province','city','county','detailaddress','email'], 'required'],
  72. [['status'], 'isStatus'],
  73. [['addressId'], 'isAddress'],
  74. [['payType'], 'isPayType'],
  75. [['payPassword'], 'validatePassword'],
  76. ];
  77. }
  78. public function attributeLabels()
  79. {
  80. return [
  81. 'sn' => 'SN',//订单号
  82. 'expressCompany' => 'ExpressCompany',//快递公司
  83. 'orderTrackNo' => 'courier number',//快递单号
  84. 'status' => 'status',//状态
  85. 'remark' => 'remark',//备注
  86. 'type' => 'order type',//订单类型
  87. 'addressId' => 'addressId',//收货地址
  88. 'payType' => 'payType',//支付方式
  89. 'goodsId' => 'Product ID',
  90. 'goodsNum' => 'Product quantity',//
  91. 'userName' => '复消会员编号',//复消会员编号
  92. 'consignee' => '收货人',//收货人
  93. 'acceptMobile' => '收货电话',//收货电话
  94. 'province' => '省',
  95. 'city' => '市',
  96. 'county' => '区',
  97. 'detailaddress' => '收货详细地址',//收货详细地址
  98. 'email' => 'Email',
  99. ];
  100. }
  101. /**
  102. * 指定校验场景
  103. * @return array
  104. */
  105. public function scenarios()
  106. {
  107. $parentScenarios = parent::scenarios();
  108. $customScenarios = [
  109. // 管理员修改订单状态
  110. 'adminStatus' => ['sn', 'status'],
  111. // 管理员修改订单状态
  112. 'verifyPayStack' => ['sn', 'remark'],
  113. // 会员下单
  114. 'userOrder' => ['type','addressId', 'payType','goodsId','goodsNum', 'remark', 'payPassword', 'email'],
  115. ];
  116. return array_merge($parentScenarios, $customScenarios);
  117. }
  118. /**
  119. * 校验之前
  120. * @return bool
  121. */
  122. public function beforeValidate()
  123. {
  124. $parentValidate = parent::beforeValidate();
  125. if ($this->sn) {
  126. $this->_model = ApproachOrder::findOne(['SN' => $this->sn]);
  127. if (!$this->_model){
  128. $this->addError('sn', '订单不存在');
  129. return false;
  130. }
  131. }
  132. if ($this->scenario == 'verifyPayStack'){
  133. if ($this->_model['STATUS'] != \Yii::$app->params['orderStatus']['notPaid']['value']) {
  134. $this->addError('sn', '订单支付状态错误');
  135. return false;
  136. }
  137. }
  138. return $parentValidate;
  139. }
  140. /**
  141. * 判断收货地址是否存在
  142. * @param $attribute
  143. */
  144. public function isAddress($attribute){
  145. if (!$receiveAddress = ReceiveAddress::find()->where(' ID=:ID', [':ID' => $this->addressId])->asArray()->one()) {
  146. $this->addError($attribute, '收货地址不存在');
  147. } else {
  148. $this->_address = $receiveAddress;
  149. }
  150. }
  151. /**
  152. * 校验支付密码
  153. * @param $attribute
  154. * @param $params
  155. */
  156. public function validatePassword($attribute, $params) {
  157. if (!User::validatePayPassword(\Yii::$app->user->id, $this->payPassword)) {
  158. $this->addError($attribute, '支付密码不正确');
  159. }
  160. }
  161. /**
  162. * 判断支付方式
  163. * @param $attribute
  164. */
  165. public function isPayType($attribute)
  166. {
  167. if ($this->payType != 'pay_stack'){
  168. $this->addError($attribute, '只允许PayStack方式支付');
  169. return;
  170. }
  171. // 一个订单只能包含一类商品
  172. $goods = ShopGoods::find()->select('ID,CATEGORY_TYPE')->where(['in', 'ID', $this->goodsId])->andWhere(['STATUS' => 1])->asArray()->all();
  173. $goodsCategoryType = array_unique(array_column($goods, 'CATEGORY_TYPE'));
  174. if (count($goodsCategoryType) != 1) {
  175. $this->addError($attribute, 'Order cannot contain multiple product categories');//订单不能包含多种商品分类
  176. return;
  177. }
  178. // 购买方式
  179. $sellTypeLabelMap = array_column(ShopGoods::SALE_TYPE, NULL, 'label');
  180. if (!array_key_exists($this->payType, $sellTypeLabelMap)) {
  181. $this->addError($attribute, '不支持PayStack方式支付');
  182. return;
  183. }
  184. // 所选支付方式必须是商品分类支持的类型
  185. $categoryType = array_column(ShopGoods::CATEGORY_TYPE, NULL, 'id');
  186. // 商品类型
  187. $currCategoryType = $goodsCategoryType[0];
  188. if (!array_key_exists($currCategoryType, $categoryType)) {
  189. $this->addError($attribute, '商品分类错误');
  190. return;
  191. }
  192. $sellType = $categoryType[$currCategoryType]['sell_type'] ?? [];
  193. if (!$sellType || !in_array($this->payType, array_column($sellType, 'label'))) {
  194. $this->addError($attribute, '支付方式错误3');
  195. }
  196. }
  197. /**
  198. * 校验类型
  199. * @param $attribute
  200. */
  201. public function isStatus($attribute){
  202. if(!in_array($this->type, \Yii::$app->params['orderStatus'])){
  203. $this->addError($attribute, '类型错误');
  204. return ;
  205. }
  206. if ($this->scenario == 'adminStatus'){
  207. if ($this->status == $this->_model['STATUS']) {
  208. $this->addError($attribute, '订单状态没有改变');
  209. return ;
  210. }
  211. if($this->status == \Yii::$app->params['orderStatus']['notPaid'] && $this->_model['STATUS'] >= \Yii::$app->params['orderStatus']['delivery']) {
  212. $this->addError($attribute, '订单已经进入物流状态不能改为未支付');
  213. return ;
  214. }
  215. elseif($this->status == \Yii::$app->params['orderStatus']['paid'] && $this->_model['STATUS'] >= \Yii::$app->params['orderStatus']['cancel']) {
  216. $this->addError($attribute, '订单已失效不能处理');
  217. return ;
  218. }
  219. elseif($this->status == \Yii::$app->params['orderStatus']['delivery']) {
  220. $this->addError($attribute, '订单不能单独处理为物流状态');
  221. return ;
  222. }
  223. elseif($this->status == \Yii::$app->params['orderStatus']['complete'] && $this->_model['STATUS'] > \Yii::$app->params['orderStatus']['cancel']) {
  224. $this->addError($attribute, '订单已失效不能处理');
  225. return ;
  226. }
  227. elseif($this->status == \Yii::$app->params['orderStatus']['cancel']) {
  228. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['complete']) {
  229. $this->addError($attribute, '订单已完成不能取消');
  230. return ;
  231. }
  232. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['del']) {
  233. $this->addError($attribute, '订单已删除不能取消');
  234. return ;
  235. }
  236. }
  237. elseif($this->status == \Yii::$app->params['orderStatus']['del']) {
  238. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['complete']) {
  239. $this->addError($attribute, '订单已完成不能删除');
  240. return ;
  241. }
  242. }
  243. }
  244. }
  245. /**
  246. * 校验PayStack支付,更新订单状态.同步到正式订单.
  247. * @throws Exception
  248. */
  249. public function verifyPayStack()
  250. {
  251. if (!$this->validate()) {
  252. return null;
  253. }
  254. // 调用PayStack支付校验
  255. $payload = PayStack::transactionVerify($this->remark['reference']);
  256. if ($payload['status'] !== true) {
  257. throw new Exception(Form::formatErrorsForApi($payload['message']));
  258. }
  259. if ($payload['data']['amount'] != $this->_model->PAY_AMOUNT * 100) {
  260. throw new Exception(Form::formatErrorsForApi('支付金额与订单金额不符'));
  261. }
  262. $db = \Yii::$app->db;
  263. $transaction = $db->beginTransaction();
  264. try {
  265. // 更新准订单状态为已支付
  266. $this->_model->STATUS = \Yii::$app->params['orderStatus']['paid']['value'];
  267. $this->_model->REMARK = json_encode($this->remark);
  268. $this->_model->PAY_AT = Date::nowTime();
  269. if (!$this->_model->save()) {
  270. throw new Exception(Form::formatErrorsForApi($this->_model->getErrors()));
  271. }
  272. // 同步准订单到正式订单
  273. Order::insertOne($this->_model->toArray());
  274. OrderGoods::batchInsert(ApproachOrderGoods::findAllAsArray('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]));
  275. $transaction->commit();
  276. } catch (Exception $e) {
  277. $transaction->rollBack();
  278. $this->addError('edit', $e->getMessage());
  279. return null;
  280. }
  281. return $this->_model;
  282. }
  283. /**
  284. * 复销
  285. * @throws Exception
  286. * @throws \yii\db\Exception
  287. */
  288. public function add(){
  289. if(!$this->validate()){
  290. return null;
  291. }
  292. $ids = $this->goodsId;
  293. $totalAmount = 0;
  294. $totalPv = 0;
  295. $goodsType = ShopGoods::GOODS_TYPE;
  296. foreach ($this->goodsNum as $k => $v) {
  297. if ($v) {
  298. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  299. if($goods['STORE_NUMS']>0){
  300. if ($goods['TYPE'] == 1 || $goods['TYPE'] == 2) {
  301. $discount = $goodsType[$goods['TYPE']]['discount'];
  302. $realPrice = $goods['SELL_PRICE'] * $discount/100;
  303. $realPv = $goods['PRICE_PV'] * $discount/100;
  304. } else {
  305. $discount = $goods['SELL_DISCOUNT'];
  306. $realPrice = $goods['SELL_PRICE'] * $discount;
  307. $realPv = $goods['PRICE_PV'] * $discount;
  308. }
  309. $totalAmount += $realPrice * intval($v);
  310. $totalPv += $realPv * intval($v);
  311. $this->_orderGoods[] = [
  312. 'GOODS_ID' => $goods['ID'],
  313. 'PRICE' => $goods['SELL_PRICE'],
  314. 'PV' => $goods['PRICE_PV'],
  315. 'REAL_PRICE' => $realPrice,
  316. 'REAL_PV' => $realPv,
  317. 'POINT' => $goods['POINT'],
  318. 'BUY_NUMS' => intval($v),
  319. 'SKU_CODE' => $goods['GOODS_NO'],
  320. 'GOODS_TITLE' => $goods['GOODS_NAME'],
  321. 'CATEGORY_TYPE' => $goods['CATEGORY_TYPE'],
  322. 'PAY_TYPE' => $this->payType,
  323. 'EMAIL' => $this->email,
  324. ];
  325. }
  326. }
  327. }
  328. $this->_decAmount = $totalAmount;
  329. $this->_decPv = $totalPv;
  330. $this->_freight = ($totalAmount>=300) ? 0 : 15;
  331. if($this->_address['PROVINCE']==1){
  332. $this->_freight = 0;
  333. }
  334. $this->_payAmount = $this->_decAmount + $this->_freight;
  335. $db = \Yii::$app->db;
  336. $transaction = $db->beginTransaction();
  337. try {
  338. //写入订单
  339. if (!$orderResult = $this->addOrder()) {
  340. throw new Exception(Form::formatErrorsForApi($orderResult->getErrors()));
  341. }
  342. $transaction->commit();
  343. return $orderResult;
  344. }catch (\Exception $e){
  345. $transaction->rollBack();
  346. $this->addError('add', $e->getMessage());
  347. return null;
  348. }
  349. }
  350. /**
  351. * 复销订单
  352. * @throws Exception
  353. */
  354. public function addOrder()
  355. {
  356. $periodObj = Period::instance();
  357. $nowPeriodNum = $periodObj->getNowPeriodNum();
  358. $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
  359. $userId = \Yii::$app->user->id;
  360. $userName = Info::getUserNameByUserId($userId);
  361. $userRealName = Info::getUserRealNameByUserId($userId);
  362. $userMobile = Info::getUserMobileByUserId($userId);
  363. $userEmail = Info::getUserEmailByUserId($userId);
  364. // 加入订单信息
  365. if ($this->_address['PROVINCE'] != 1) {
  366. $warehouse = Region::getWarehouseByCode($this->_address['PROVINCE']);//仓库
  367. if (!$warehouse) {
  368. // throw new Exception('地区2暂时不支持配送,具体联系客服');
  369. }
  370. }else{
  371. $warehouse = '01';
  372. }
  373. $_hasPV = $this->_decPv;
  374. $ordNo = $this->_generateSn();
  375. $orderModel = new ApproachOrder();
  376. $orderModel->SN = 'OS' . $ordNo;
  377. $orderModel->DEC_SN = 'DS' . $ordNo;
  378. $orderModel->ORDER_TYPE = $this->type;
  379. $orderModel->USER_ID = $userId;
  380. $orderModel->USER_NAME = $userName;
  381. $orderModel->ORDER_AMOUNT = $this->_decAmount;
  382. $orderModel->PV = $_hasPV;
  383. $orderModel->PAY_AMOUNT = $this->_payAmount;
  384. $orderModel->PAY_PV = $_hasPV; // 兑换积分不能算业绩
  385. $orderModel->PAY_AT = 0;
  386. $orderModel->PAY_TYPE = $this->payType;
  387. $orderModel->PERIOD_NUM = $nowPeriodNum;
  388. $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  389. $orderModel->FREIGHT = $this->_freight;
  390. $orderModel->PAY_FREIGHT = $this->_freight;
  391. $orderModel->CONSIGNEE = $this->_address['CONSIGNEE'];
  392. $orderModel->MOBILE = $this->_address['MOBILE'];
  393. $orderModel->PROVINCE = $this->_address['PROVINCE'];
  394. $orderModel->CITY = $this->_address['CITY'];
  395. $orderModel->COUNTY = $this->_address['COUNTY'];
  396. $orderModel->ADDRESS = $this->_address['ADDRESS'];
  397. $orderModel->FRONT_REMARK = $this->remark;
  398. $orderModel->WAREHOUSE = $warehouse;
  399. $orderModel->STATUS = \Yii::$app->params['orderStatus']['notPaid']['value'];
  400. $orderModel->CREATED_AT = Date::nowTime();
  401. $orderModel->CREATE_USER = $userName;
  402. $orderModel->EMAIL = $userEmail;
  403. if($this->_address['PROVINCE']==1){
  404. $orderModel->EXPRESS_TYPE = 1;
  405. $orderModel->CONSIGNEE = $userRealName;
  406. $orderModel->MOBILE = $userMobile;
  407. $orderModel->PROVINCE = 1;
  408. $orderModel->CITY = 1;
  409. $orderModel->COUNTY = 1;
  410. $orderModel->ADDRESS = '';
  411. }
  412. if(!$orderModel->save()){
  413. $this->addErrors($orderModel->getErrors());
  414. return false;
  415. }
  416. // 加入商品到订单商品表
  417. foreach($this->_orderGoods as $key=>$value) {
  418. $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN;
  419. $this->_orderGoods[$key]['P_CALC_MONTH'] = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  420. }
  421. ApproachOrderGoods::batchInsert($this->_orderGoods);
  422. // TODO: 记录流水
  423. return $orderModel;
  424. }
  425. /**
  426. * 生成流水号
  427. * @return string
  428. */
  429. private function _generateSn() {
  430. return Date::today('Ymd') . $this->_random(10, 1);
  431. }
  432. /**
  433. * 生成随机数
  434. * @param $length
  435. * @param int $numeric
  436. * @return string
  437. */
  438. private function _random($length, $numeric = 0) {
  439. $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
  440. $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
  441. $hash = '';
  442. $max = strlen($seed) - 1;
  443. for ($i = 0; $i < $length; $i++) {
  444. $hash .= $seed[mt_rand(0, $max)];
  445. }
  446. return $hash;
  447. }
  448. }