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