OrderForm.php 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119
  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\LoggerTool;
  8. use common\helpers\PayStack;
  9. use common\helpers\user\Balance;
  10. use common\helpers\user\Cash;
  11. use common\helpers\user\Info;
  12. use common\libs\logging\operate\AdminOperate;
  13. use common\models\Countries;
  14. use common\models\CurrencyConversions;
  15. use common\models\DealType;
  16. use common\models\FreeTemplate;
  17. use common\models\Instalment;
  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\ShopGoodsNature;
  25. use common\models\User;
  26. use common\models\UserNetwork;
  27. use common\models\RemainPv;
  28. use common\models\FlowRemainPv;
  29. use Yii;
  30. use yii\base\Exception;
  31. /**
  32. * Login form
  33. */
  34. class OrderForm extends Model
  35. {
  36. public $sn;
  37. public $expressCompany;
  38. public $orderTrackNo;
  39. public $status;
  40. public $remark;
  41. public $type;
  42. public $addressId;
  43. public $payType;
  44. public $goodsId;
  45. public $goodsNum;
  46. public $payPassword;
  47. public $email;
  48. public $exchangeRate;
  49. public $userName;
  50. public $decUserName;
  51. public $consignee;
  52. public $acceptMobile;
  53. public $province;
  54. public $city;
  55. public $lgaName;
  56. public $cityName;
  57. public $county;
  58. public $detailaddress;
  59. private $_address;
  60. private $_decAmount;
  61. private $_decPv;
  62. private $_freight;
  63. private $_payAmount;
  64. private $_orderGoods;
  65. private $_standardAmount;
  66. private $_decAmountStandard;
  67. private $_exchangeRate;
  68. private $_remainPv;
  69. private $_realPv;
  70. /**
  71. * @var Order
  72. */
  73. private $_model;
  74. public function init() {
  75. parent::init();
  76. $this->adminOperateLogger = new AdminOperate([
  77. 'fetchClass' => Order::class,
  78. ]);
  79. }
  80. /**
  81. * @inheritdoc
  82. */
  83. public function rules()
  84. {
  85. return [
  86. [['sn', 'expressCompany', 'orderTrackNo', 'status', 'remark','type','addressId','payType','goodsId','goodsNum', 'payPassword','userName','consignee','acceptMobile','province'/*,'city','county'*/,'cityName','lgaName','detailaddress','email'], 'trim'],
  87. [['sn', 'expressCompany', 'orderTrackNo', 'status', 'remark','type','addressId','payType','goodsId','goodsNum', 'payPassword','consignee','acceptMobile','province','city','county','detailaddress'/*,'email'*/], 'required'],
  88. [['status'], 'isStatus'],
  89. [['addressId'], 'isAddress'],
  90. [['payType'], 'isPayType'],
  91. [['payPassword'], 'validatePassword'],
  92. ];
  93. }
  94. public function attributeLabels()
  95. {
  96. return [
  97. 'sn' => Yii::t('app', 'orderSn'),
  98. 'expressCompany' => Yii::t('app', 'expressCompany'),
  99. 'orderTrackNo' => Yii::t('app', 'orderTrackNo'),
  100. 'status' => Yii::t('app', 'state'),
  101. 'remark' => Yii::t('app', 'remark'),
  102. 'type' => Yii::t('app', 'orderType'),
  103. 'addressId' => Yii::t('app', 'shippingAddress'),
  104. 'payType' => Yii::t('app', 'payType'),
  105. 'goodsId' => Yii::t('app', 'productID'),
  106. 'goodsNum' => Yii::t('app', 'quantity'),
  107. 'userName' => Yii::t('app', 'repeatSalesMemberNo'),
  108. 'consignee' => Yii::t('app', 'consignee'),
  109. 'acceptMobile' => Yii::t('app', 'acceptMobile'),
  110. 'province' => Yii::t('app', 'province'),
  111. 'city' => Yii::t('app', 'city'),
  112. 'county' => Yii::t('app', 'county'),
  113. 'lgaName' =>Yii::t('app', 'lgaName'),
  114. 'cityName' => Yii::t('app', 'cityName'),
  115. 'detailaddress' => Yii::t('app', 'detailAddress'),
  116. 'email' => Yii::t('app', 'email'),
  117. ];
  118. }
  119. /**
  120. * 指定校验场景
  121. * @return array
  122. */
  123. public function scenarios()
  124. {
  125. $parentScenarios = parent::scenarios();
  126. $customScenarios = [
  127. // 管理员发货
  128. 'adminDelivery' => ['sn', 'expressCompany', 'orderTrackNo'],
  129. // 会员确认收货
  130. 'userConfirm' => ['sn', 'expressCompany', 'orderTrackNo'],
  131. // 管理员修改订单状态
  132. 'adminStatus' => ['sn', 'status'],
  133. // 管理员修改备注
  134. 'adminRemark' => ['sn', 'remark'],
  135. // 会员下单
  136. 'userOrder' => ['type','addressId', 'payType','goodsId','goodsNum', 'remark', 'payPassword'],
  137. // 帮会员复消下单
  138. 'reconsumeOrder' => ['type','userName', 'payType','goodsId','goodsNum', 'remark', 'payPassword','consignee','acceptMobile','province','cityName','lgaName','detailaddress'],
  139. // 管理员退款
  140. 'adminRefund' => ['sn'],
  141. ];
  142. return array_merge($parentScenarios, $customScenarios);
  143. }
  144. /**
  145. * 校验之前
  146. * @return bool
  147. */
  148. public function beforeValidate()
  149. {
  150. $parentValidate = parent::beforeValidate();
  151. if ($this->sn) {
  152. $this->_model = Order::findOne(['SN'=>$this->sn]);
  153. if (!$this->_model){
  154. $this->addError('sn', Yii::t('app', 'orderDoesNotExist'));
  155. return false;
  156. }
  157. }
  158. if ($this->scenario == 'adminDelivery'){
  159. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['cancel']) {
  160. $this->addError('sn', Yii::t('app', 'orderHasBeenCancelCanNotDeliver'));
  161. return false;
  162. }
  163. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['del']) {
  164. $this->addError('sn', Yii::t('app', 'orderHasBeenDeleteCanNotDeliver'));
  165. return false;
  166. }
  167. }
  168. if ($this->scenario == 'adminRefund'){
  169. if ($this->_model['STATUS'] != \Yii::$app->params['orderStatus']['paid']['value']) {
  170. $this->addError('sn', Yii::t('app', 'orderPayStatusDoesNotSupportRefund'));
  171. return false;
  172. }
  173. if ($this->_model['DELIVERY_STATUS'] != \Yii::$app->params['deliveryStatus']['notDelivery']['value']) {
  174. $this->addError('sn', Yii::t('app', 'orderLogisticsStatusDoesNotSupportRefund'));
  175. return false;
  176. }
  177. if ($this->_model['PAY_TYPE'] != 'pay_stack') {
  178. $this->addError('sn', Yii::t('app', 'orderPayTypeDoesNotSupportRefund'));
  179. return false;
  180. }
  181. if (!$this->_model['REMARK']) {
  182. $this->addError('sn', Yii::t('app', 'paymentInfoDoesNotExists'));
  183. return false;
  184. }
  185. }
  186. return $parentValidate;
  187. }
  188. /**
  189. * 校验支付密码
  190. * @param $attribute
  191. * @param $params
  192. */
  193. public function validatePassword($attribute, $params) {
  194. if (!User::validatePayPassword(\Yii::$app->user->id, $this->payPassword)) {
  195. $this->addError($attribute, Yii::t('app', 'paymentPasswordError'));
  196. }
  197. }
  198. /**
  199. * 判断收货地址是否存在
  200. * @param $attribute
  201. */
  202. public function isAddress($attribute){
  203. if (!$receiveAddress = ReceiveAddress::find()->where(' ID=:ID', [':ID' => $this->addressId])->asArray()->one()) {
  204. $this->addError($attribute, Yii::t('app', 'shippingDoesNotExist'));
  205. } else {
  206. $this->_address = $receiveAddress;
  207. }
  208. }
  209. /**
  210. * 判断支付方式
  211. * @param $attribute
  212. * @throws Exception
  213. */
  214. public function isPayType($attribute){
  215. if(!array_key_exists($this->payType, ShopGoods::payTypes())){
  216. $this->addError($attribute, Yii::t('app', 'payTypeError'));
  217. return;
  218. }
  219. // 一个订单只能包含一类商品
  220. $goods = ShopGoods::find()->select('ID,CATEGORY_TYPE')->where(['in', 'ID', $this->goodsId])->andWhere(['STATUS' => 1])->asArray()->all();
  221. if (!$goods) {
  222. throw new Exception(Yii::t('app', 'productsDoesSoldOut'));
  223. return;
  224. }
  225. $goodsCategoryType = array_unique(array_column($goods, 'CATEGORY_TYPE'));
  226. if (count($goodsCategoryType) > 1) {
  227. $this->addError($attribute, Yii::t('app', 'orderCanNotHasMoreClassification'));
  228. return;
  229. }
  230. // 购买方式
  231. $sellTypeLabelMap = array_column(ShopGoods::getSaleType(), NULL, 'label');
  232. if (!array_key_exists($this->payType, $sellTypeLabelMap)) {
  233. $this->addError($attribute, Yii::t('app', 'payTypeError'));
  234. return;
  235. }
  236. // 所选支付方式必须是商品分类支持的类型
  237. $categoryType = array_column(ShopGoods::CATEGORY_TYPE, NULL, 'id');
  238. // 商品类型
  239. $currCategoryType = $goodsCategoryType[0];
  240. if (!array_key_exists($currCategoryType, $categoryType)) {
  241. $this->addError($attribute, Yii::t('app', 'shopGoodClassificationError'));
  242. return;
  243. }
  244. $sellType = $categoryType[$currCategoryType]['sell_type'] ?? [];
  245. if (!$sellType || !in_array($this->payType, array_column($sellType, 'label'))) {
  246. $this->addError($attribute, Yii::t('app', 'payTypeError'));
  247. return;
  248. }
  249. }
  250. /**
  251. * 校验类型
  252. * @param $attribute
  253. */
  254. public function isStatus($attribute){
  255. if(!in_array($this->type, \Yii::$app->params['orderStatus'])){
  256. $this->addError($attribute, Yii::t('app', 'orderStatusTypeError'));
  257. return ;
  258. }
  259. if ($this->scenario == 'adminStatus'){
  260. if ($this->status == $this->_model['STATUS']) {
  261. $this->addError($attribute, Yii::t('app', 'orderStatusDoesNotChange'));
  262. return ;
  263. }
  264. if($this->status == \Yii::$app->params['orderStatus']['notPaid'] && $this->_model['STATUS'] >= \Yii::$app->params['orderStatus']['delivery']) {
  265. $this->addError($attribute, Yii::t('app', 'orderHasBeenLogisticsStatusDoesNotChangedUnpaid'));
  266. return ;
  267. }
  268. elseif($this->status == \Yii::$app->params['orderStatus']['paid'] && $this->_model['STATUS'] >= \Yii::$app->params['orderStatus']['cancel']) {
  269. $this->addError($attribute, Yii::t('app', 'orderHasBeenInvalidCanNotProcess'));
  270. return ;
  271. }
  272. elseif($this->status == \Yii::$app->params['orderStatus']['delivery']) {
  273. $this->addError($attribute, Yii::t('app', 'orderCanNotBeenChangedLogistics'));
  274. return ;
  275. }
  276. elseif($this->status == \Yii::$app->params['orderStatus']['complete'] && $this->_model['STATUS'] > \Yii::$app->params['orderStatus']['cancel']) {
  277. $this->addError($attribute, Yii::t('app', 'orderHasBeenInvalidCanNotProcess'));
  278. return ;
  279. }
  280. elseif($this->status == \Yii::$app->params['orderStatus']['cancel']) {
  281. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['complete']) {
  282. $this->addError($attribute, Yii::t('app', 'orderHasBeenFinishedCanNotCancel'));
  283. return ;
  284. }
  285. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['del']) {
  286. $this->addError($attribute, Yii::t('app', 'orderHasBeenDeletedCanNotCancel'));
  287. return ;
  288. }
  289. }
  290. elseif($this->status == \Yii::$app->params['orderStatus']['del']) {
  291. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['complete']) {
  292. $this->addError($attribute, Yii::t('app', 'orderHasBeenFinishedCanNotDelete'));
  293. return ;
  294. }
  295. }
  296. }
  297. }
  298. /**
  299. * 管理员发货
  300. * @return Order|null
  301. * @throws \yii\db\Exception
  302. */
  303. public function adminDelivery(){
  304. if(!$this->validate()){
  305. return null;
  306. }
  307. $db = \Yii::$app->db;
  308. $transaction = $db->beginTransaction();
  309. try {
  310. $period = Period::instance();
  311. $this->_model->DELIVERY_STATUS = \Yii::$app->params['deliveryStatus']['delivered']['value'];
  312. $this->_model->DELIVERY_PERIOD = $period->getNowPeriodNum();
  313. $this->_model->DELIVERY_AT = Date::nowTime();
  314. $this->_model->EXPRESS_COMPANY = $this->expressCompany;
  315. $this->_model->ORDER_TRACK_NO = $this->orderTrackNo;
  316. $this->_model->STATUS = \Yii::$app->params['orderStatus']['delivery']['value'];
  317. if(!$this->_model->save()){
  318. throw new Exception(Form::formatErrorsForApi($this->_model->getErrors()));
  319. }
  320. $transaction->commit();
  321. } catch (Exception $e) {
  322. $transaction->rollBack();
  323. $this->addError('edit', $e->getMessage());
  324. return null;
  325. }
  326. return $this->_model;
  327. }
  328. /**
  329. * 校验支付
  330. * @return Order|null
  331. * @throws Exception
  332. */
  333. public function verifyPayStack(): ?Order
  334. {
  335. if(!$this->validate()){
  336. return null;
  337. }
  338. // 调用PayStack支付校验
  339. $payload = PayStack::transactionVerify($this->remark['reference']);
  340. if ($payload['status'] !== true) {
  341. throw new Exception(Form::formatErrorsForApi($payload['message']));
  342. }
  343. if ($payload['data']['amount'] != $this->_model->PAY_AMOUNT * 100) {
  344. throw new Exception(Form::formatErrorsForApi(Yii::t('app', 'payAmountNotEqualOrderAmount')));
  345. }
  346. $db = \Yii::$app->db;
  347. $transaction = $db->beginTransaction();
  348. try {
  349. $this->_model->STATUS = \Yii::$app->params['orderStatus']['paid']['value'];
  350. $this->_model->REMARK = json_encode($this->remark);
  351. $this->_model->PAY_AT = Date::nowTime();
  352. if (!$this->_model->save()) {
  353. throw new Exception(Form::formatErrorsForApi($this->_model->getErrors()));
  354. }
  355. $transaction->commit();
  356. } catch (Exception $e) {
  357. $transaction->rollBack();
  358. $this->addError('edit', $e->getMessage());
  359. return null;
  360. }
  361. return $this->_model;
  362. }
  363. /**
  364. * 订单退款
  365. * @return Order|null
  366. * @throws Exception
  367. */
  368. public function adminRefund()
  369. {
  370. if(!$this->validate()){
  371. return null;
  372. }
  373. // 支付信息存在于remark中
  374. $remark = $this->_model->REMARK ? json_decode($this->_model->REMARK, true) : [];
  375. $reference = $remark['reference'] ?? '';
  376. if (!$reference) {
  377. throw new Exception(Form::formatErrorsForApi(Yii::t('app', 'paymentInfoDoesNotExists')));
  378. }
  379. // 退款金额. 订单支付金额 * 100
  380. $amount = $this->_model->PAY_AMOUNT * 100;
  381. // 调用PayStack支付校验
  382. $payload = PayStack::transactionRefund($reference, $amount);
  383. if ($payload['status'] !== true) {
  384. throw new Exception(Form::formatErrorsForApi($payload['message']));
  385. }
  386. $db = \Yii::$app->db;
  387. $transaction = $db->beginTransaction();
  388. try {
  389. $this->_model->STATUS = \Yii::$app->params['orderStatus']['refund']['value'];
  390. $this->_model->REMARK = json_encode([
  391. 'payment' => $remark,
  392. 'refund' => $payload['data']
  393. ]
  394. );
  395. if (!$this->_model->save()) {
  396. throw new Exception(Form::formatErrorsForApi($this->_model->getErrors()));
  397. }
  398. $transaction->commit();
  399. } catch (Exception $e) {
  400. $transaction->rollBack();
  401. $this->addError('edit', $e->getMessage());
  402. return null;
  403. }
  404. return $this->_model;
  405. }
  406. /**
  407. * BV分期
  408. *
  409. *
  410. */
  411. private function _pvSplit($oPv){
  412. $sysConfig = Cache::getSystemConfig();
  413. $mesureUpCondition = $sysConfig['monthPcsPvFxCondition']['VALUE'];
  414. if($oPv>$mesureUpCondition){
  415. $currentPv = $oPv % $mesureUpCondition + $mesureUpCondition;
  416. $remainPv = $oPv - $currentPv;
  417. }else{
  418. $currentPv = $oPv;
  419. $remainPv = 0;
  420. }
  421. return [
  422. 'current' => $currentPv,
  423. 'remain' => $remainPv
  424. ];
  425. }
  426. /**
  427. * 复销
  428. * @throws Exception
  429. * @throws \yii\db\Exception
  430. */
  431. public function add(){
  432. if(!$this->validate()){
  433. return null;
  434. }
  435. $ids = $this->goodsId;
  436. $totalAmount = 0;
  437. $totalPv = 0;
  438. $totalRealPv = 0;
  439. $totalAmountStandard = 0;
  440. $goodsType = ShopGoods::getGoodType();
  441. $this->_remainPv = 0;
  442. $hasInstalment = 0;
  443. $loginUserId = \Yii::$app->user->id;
  444. $user = User::getEnCodeInfo(\Yii::$app->user->id);
  445. foreach ($this->goodsNum as $k => $v) {
  446. if ($v) {
  447. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  448. if (!$goods) {
  449. throw new Exception(Yii::t('app', 'productsDoesSoldOut'));
  450. }
  451. $goodsNature = ShopGoodsNature::findOneAsArray('GOODS_ID=:GOODS_ID AND COUNTRY_ID=:COUNTRY_ID',
  452. [':GOODS_ID' => $ids[$k], ':COUNTRY_ID' => $user['COUNTRY_ID']]);
  453. if (!$goodsNature) {
  454. throw new Exception(Yii::t('app', 'productsDoesSoldOut'));
  455. }
  456. // 汇率
  457. $this->exchangeRate = CurrencyConversions::getToUSDRate($goodsNature['LOCAL_CURRENCY_ID']);
  458. if($goods['STORE_NUMS']>0){
  459. if ($goods['TYPE'] == 1 || $goods['TYPE'] == 2) {
  460. $discount = $goodsType[$goods['TYPE']]['discount'];
  461. $realPrice = $goodsNature['SELL_PRICE'] * $discount/100;
  462. $realPv = $goods['PRICE_PV'] * $discount/100;
  463. $realPriceStandard = $goods['SELL_PRICE_STANDARD'] * $discount/100;
  464. } else {
  465. $discount = $goods['SELL_DISCOUNT'];
  466. $realPrice = $goodsNature['SELL_PRICE'] * $discount;
  467. $realPv = $goods['PRICE_PV'] * $discount;
  468. $realPriceStandard = $goods['SELL_PRICE_STANDARD'] * $discount;
  469. }
  470. if($goods['PV_SPLIT']==1){ // 当商品为PV分期时
  471. $pvSplit = $this->_pvSplit($realPv);
  472. $currentPv = $pvSplit['current'];
  473. $remainPv = $pvSplit['remain'];
  474. $totalPv += $currentPv * intval($v);
  475. $totalRealPv += $realPv * intval($v);
  476. $this->_remainPv += $remainPv * intval($v);
  477. }else{
  478. $currentPv = $goods['PRICE_PV'];
  479. $totalPv += $realPv * intval($v);
  480. $totalRealPv += $realPv * intval($v);
  481. $remainPv = 0;
  482. $this->_remainPv += 0;
  483. }
  484. $totalAmount += $realPrice * intval($v);
  485. $totalAmountStandard += $realPriceStandard * intval($v);
  486. // if($this->payType=='cash') {
  487. // $discount = $goodsType[$goods['TYPE']]['discount'];
  488. // $realPrice = $goods['SELL_PRICE'] * $discount/100;
  489. // $realPv = $goods['PRICE_PV'] * $discount/100;
  490. // $totalAmount += $realPrice * intval($v);
  491. // $totalPv += $realPv * intval($v);
  492. // }else{
  493. // $realPrice = $goods['SELL_PRICE'];
  494. // $realPv = $goods['PRICE_PV'];
  495. // $totalAmount += $realPrice * intval($v);
  496. // $totalPv += $realPv * intval($v);
  497. // }
  498. $this->_orderGoods[] = [
  499. 'GOODS_ID' => $goods['ID'],
  500. 'PRICE' => $goodsNature['SELL_PRICE'],
  501. 'PV' => $currentPv, // $goods['PRICE_PV'],
  502. 'REAL_PRICE' => $realPrice,
  503. 'REAL_PV' => $realPv,
  504. 'REMAIN_PV' => $remainPv,
  505. 'POINT' => $goods['POINT'],
  506. 'BUY_NUMS' => intval($v),
  507. 'SKU_CODE' => $goods['GOODS_NO'],
  508. 'GOODS_TITLE' => $goods['GOODS_NAME'],
  509. 'CATEGORY_TYPE' => $goods['CATEGORY_TYPE'],
  510. 'PAY_TYPE' => $this->payType,
  511. 'EMAIL' => $this->email,
  512. 'STANDARD_PRICE' => $goods['SELL_PRICE_STANDARD'],
  513. 'REAL_STANDARD_PRICE' => $realPriceStandard,
  514. 'EXCHANGE_RATE' => $this->exchangeRate,
  515. 'TAX_RATE' => $goodsNature['TAX_RATE'],
  516. ];
  517. }
  518. if($goods['INSTALMENT']>0){ // 如果有分期付款商品,检查用户的分期付款状态
  519. if($v>1){ // 不可以购买多个
  520. throw new Exception(Yii::t('app', 'allowOnlyOne'));
  521. }
  522. $userStage = Instalment::getStage($loginUserId);
  523. $userInstalmentInfo = Instalment::getInfo($loginUserId);
  524. // 分期的总期数
  525. $instalment = intval(Cache::getSystemConfig()['instalment']['VALUE'] ?? 3);
  526. // 分期商品的期数不能大于总分期数限制
  527. if (intval($goods['INSTALMENT']) > $instalment) {
  528. throw new Exception(Yii::t('app', 'instalmentGoodsNoError'));
  529. }
  530. if ($userStage != $instalment){
  531. if ($userInstalmentInfo){
  532. if($userInstalmentInfo['STAGE']>0 && $userInstalmentInfo['ORDER_TYPE']!='FX'){
  533. throw new Exception(Yii::t('app', 'canNotBuy'));
  534. }
  535. }
  536. if ($userStage + 1 != $goods['INSTALMENT']){ // 若用户分期阶段+1不等于商品的分期阶段,则报异常
  537. throw new Exception(Yii::t('app', 'canNotBuy'));
  538. }
  539. if ($userStage + 1 > $instalment){ // 若用户分期阶段+1大于总分期阶段,则报异常
  540. throw new Exception(Yii::t('app', 'canNotBuy'));
  541. }
  542. } else {
  543. if ($goods['INSTALMENT'] != 1) {
  544. throw new Exception(Yii::t('app', 'canNotBuy'));
  545. }
  546. }
  547. $hasInstalment = $goods['INSTALMENT'];
  548. }
  549. }
  550. }
  551. // 运费模板
  552. $freeTemplate = FreeTemplate::getByCountryId($user['COUNTRY_ID']);
  553. // 运费
  554. $freight = $freeTemplate['freight'] ?? 0;
  555. // 普通商品免运费阈值
  556. $freeShipping = $freeTemplate['free_shipping'] ?? 0;
  557. $this->_decAmount = $totalAmount;
  558. $this->_decPv = $totalPv;
  559. $this->_realPv = $totalRealPv;
  560. $this->_freight = ($totalAmount >= $freeShipping) ? 0 : $freight;
  561. if($this->_address['PROVINCE']==1){
  562. $this->_freight = 0;
  563. }
  564. $this->_payAmount = $this->_decAmount + $this->_freight;
  565. $this->_decAmountStandard = $totalAmountStandard;
  566. $this->_standardAmount = $this->_decAmountStandard + $this->_freight;
  567. $db = \Yii::$app->db;
  568. $transaction = $db->beginTransaction();
  569. try {
  570. //判断用户余额是否充足
  571. $result = $this->getBalanceAdequate($this->payType, $this->_payAmount);
  572. if ($result['code'] !== 200) {
  573. throw new Exception($result['message']);
  574. }
  575. /**
  576. * 2022-04-28
  577. * York
  578. * 支付后减少库存
  579. */
  580. foreach ($this->goodsNum as $k => $v){
  581. if ($v){
  582. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  583. if (!$goods) {
  584. throw new Exception(Yii::t('app', 'productsDoesSoldOut'));
  585. }
  586. if ($goods['STORE_NUMS'] >= $this->goodsNum[$k]){
  587. $data = ShopGoods::find()->where(['ID' => $ids[$k]])->one();
  588. $goods_store_nums = $data->STORE_NUMS - $this->goodsNum[$k];
  589. $data->STORE_NUMS = $goods_store_nums;
  590. $data->update();
  591. //下单后库存小于等于0 商品下架
  592. if($goods_store_nums <= 0){
  593. $data->STATUS = 0;
  594. $data->UPDATED_AT = Date::nowTime();
  595. $data->update();
  596. }
  597. }else{
  598. throw new Exception($goods['GOODS_NAME'] . Yii::t('app', 'insufficientInventory'));
  599. }
  600. }
  601. }
  602. //写入订单
  603. if (!$orderResult = $this->addOrder()) {
  604. throw new Exception(Form::formatErrorsForApi($orderResult->getErrors()));
  605. }
  606. if ($hasInstalment){ // 如果有分期付款的商品,写入信息至分期付款表
  607. $instalmentModel = Instalment::findOne(['USER_ID'=>$loginUserId]);
  608. if(!$instalmentModel) {
  609. $instalmentModel = new Instalment();
  610. }
  611. $instalmentModel->USER_ID = $loginUserId;
  612. $instalmentModel->STAGE = $hasInstalment;
  613. $instalmentModel->ORDER_TYPE = 'FX';
  614. $instalmentModel->UPDATE_TIME = time();
  615. $instalmentModel->save();
  616. }
  617. $transaction->commit();
  618. return $orderResult;
  619. }catch (\Exception $e){
  620. $transaction->rollBack();
  621. $this->addError('add', $e->getMessage());
  622. return null;
  623. }
  624. }
  625. /**
  626. * 判断对应账户余额是否充足.
  627. * @param $payType string 支付方式.
  628. * @param $payAmount numeric 支付金额
  629. * @return array|int[]
  630. */
  631. public function getBalanceAdequate(string $payType, $payAmount): array
  632. {
  633. $loginUserId = \Yii::$app->user->id;
  634. if ($payType == 'cash') {
  635. if (Cash::getAvailableBalance($loginUserId) < $payAmount) {
  636. return ['code' => 500, 'message' => Yii::t('app', 'cashDoesNotAdequate')];
  637. }
  638. } else if ($payType =='exchange') {
  639. if ($payAmount > Balance::getBalanceExchangePoints($loginUserId)) {
  640. return ['code' => 500, 'message' => Yii::t('app', 'exchangePointDoesNotAdequate')];
  641. }
  642. } else if ($payType == 'tourism_points') {
  643. if ($payAmount > Balance::getBalanceTourism($loginUserId)) {
  644. return ['code' => 500, 'message' => Yii::t('app', 'travelPointDoesNotAdequate')];
  645. }
  646. } else if ($payType == 'garage_points') {
  647. if ($payAmount > Balance::getBalanceGarage($loginUserId)) {
  648. return ['code' => 500, 'message' => Yii::t('app', 'carFundPointDoesNotAdequate')];
  649. }
  650. // } else{
  651. // if ($payAmount > Balance::getBalanceReconsumePoints($loginUserId)) {
  652. // return ['code' => 500, 'message' => '复消积分不足,无法购买商品'];
  653. // }
  654. }
  655. return ['code' => 200];
  656. }
  657. /**
  658. * 复销订单
  659. * @throws Exception
  660. */
  661. public function addOrder(){
  662. $periodObj = Period::instance();
  663. $nowPeriodNum = $periodObj->getNowPeriodNum();
  664. $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
  665. $userId = \Yii::$app->user->id;
  666. $user = User::getEnCodeInfo(\Yii::$app->user->id);
  667. $userName = Info::getUserNameByUserId($userId);
  668. $userRealName = Info::getUserRealNameByUserId($userId);
  669. $userMobile = Info::getUserMobileByUserId($userId);
  670. $userEmail = Info::getUserEmailByUserId($userId);
  671. $country = Countries::getById($user['COUNTRY_ID']);
  672. // 加入订单信息
  673. if ($this->_address['PROVINCE'] != 1) {
  674. $warehouse = Region::getWarehouseByCode($this->_address['PROVINCE']);//仓库
  675. if (!$warehouse) {
  676. throw new Exception(Yii::t('app', 'deliveryTemporarilyNotSupported'));
  677. }
  678. }else{
  679. $warehouse = '01';
  680. }
  681. $_hasPV = in_array($this->payType, ['exchange', 'tourism_points', 'garage_points']) ? 0 : $this->_decPv;
  682. $_hasRealPV = in_array($this->payType, ['exchange', 'tourism_points', 'garage_points']) ? 0 : $this->_realPv;
  683. $ordNo = $this->_generateSn();
  684. $orderModel = new Order();
  685. $orderModel->SN = 'OS'.$ordNo;
  686. $orderModel->DEC_SN = 'DS'.$ordNo;
  687. $orderModel->ORDER_TYPE = $this->type;
  688. $orderModel->USER_ID = $userId;
  689. $orderModel->USER_NAME = $userName;
  690. $orderModel->DEC_USER_ID = $this->decUserName;;
  691. $orderModel->ORDER_AMOUNT = $this->_decAmount;
  692. $orderModel->PV = $_hasPV;
  693. $orderModel->PAY_AMOUNT = $this->_payAmount;
  694. $orderModel->PAY_PV = $_hasRealPV; // 兑换积分不能算业绩
  695. $orderModel->REMAIN_PV = $this->_remainPv;
  696. $orderModel->PAY_AT = Date::nowTime();
  697. $orderModel->PAY_TYPE = $this->payType;
  698. $orderModel->PERIOD_NUM = $nowPeriodNum;
  699. $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  700. $orderModel->FREIGHT = $this->_freight;
  701. $orderModel->PAY_FREIGHT = $this->_freight;
  702. $orderModel->CONSIGNEE = $this->_address['CONSIGNEE'];
  703. $orderModel->MOBILE = $this->_address['MOBILE'];
  704. $orderModel->PROVINCE = $this->_address['PROVINCE'];
  705. // $orderModel->CITY = $this->_address['CITY'];
  706. // $orderModel->COUNTY = $this->_address['COUNTY'];
  707. $orderModel->LGA_NAME = $this->_address['LGA_NAME'];
  708. $orderModel->CITY_NAME = $this->_address['CITY_NAME'];
  709. $orderModel->ADDRESS = $this->_address['ADDRESS'];
  710. $orderModel->FRONT_REMARK = $this->remark;
  711. $orderModel->WAREHOUSE = $warehouse;
  712. $orderModel->STATUS = \Yii::$app->params['orderStatus']['paid']['value'];
  713. $orderModel->CREATED_AT = Date::nowTime();
  714. $orderModel->CREATE_USER = $userName;
  715. $orderModel->EMAIL = $userEmail ?? '';
  716. $orderModel->ORDER_AMOUNT_STANDARD = $this->_decAmountStandard;
  717. $orderModel->PAY_AMOUNT_STANDARD = $this->_standardAmount;
  718. $orderModel->EXCHANGE_RATE = $this->exchangeRate;
  719. $orderModel->COUNTRY_ID = $user['COUNTRY_ID'];
  720. $orderModel->CURRENCY_ID = $country['LOCAL_CURRENCY_ID'] ?? 0;
  721. if($this->_address['PROVINCE']==1){
  722. $orderModel->EXPRESS_TYPE = 1;
  723. $orderModel->CONSIGNEE = $userRealName;
  724. $orderModel->MOBILE = $userMobile;
  725. $orderModel->PROVINCE = 1;
  726. $orderModel->CITY = 1;
  727. $orderModel->COUNTY = 1;
  728. $orderModel->LGA_NAME = $this->_address['LGA_NAME'];
  729. $orderModel->CITY_NAME = $this->_address['CITY_NAME'];
  730. $orderModel->ADDRESS = 'Self Pick-up';
  731. }
  732. if(!$orderModel->save()){
  733. $this->addErrors($orderModel->getErrors());
  734. return false;
  735. }
  736. // 加入商品到订单商品表
  737. foreach($this->_orderGoods as $key=>$value){
  738. // 增加判断,如果订单是兑换券购买,则AR_ORDER_GOODS中的REAL_PV真实PV应该是0
  739. if (in_array($orderModel->PAY_TYPE, ['exchange', 'tourism_points', 'garage_points'])) {
  740. $this->_orderGoods[$key]['REAL_PV'] = 0;
  741. }
  742. $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN;
  743. $this->_orderGoods[$key]['P_CALC_MONTH'] = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  744. }
  745. OrderGoods::batchInsert($this->_orderGoods);
  746. //扣除会员余额/积分
  747. if($this->payType=='cash') {
  748. Cash::changeUserCash(\Yii::$app->user->id, 'CASH', -abs($this->_payAmount), ['REMARK' => 'Members reselling balance payment', 'ORDER_SN' => $orderModel->SN]); // 会员复销余额支付
  749. } else if ($this->payType=='exchange') {
  750. Balance::changeUserBonus(\Yii::$app->user->id,'exchange_points', -abs($this->_payAmount),['DEAL_TYPE_ID' => DealType::EXCHANGE_POINTS_EXCHANGE,'REMARK' => '会员兑换积分兑换', 'ORDER_SN' => $orderModel->SN]);
  751. } else if ($this->payType == 'tourism_points') {
  752. Balance::changeUserBonus(\Yii::$app->user->id, 'tourism_points', -abs($this->_payAmount), ['DEAL_TYPE_ID' => DealType::TOURISM_POINTS_EXCHANGE,'REMARK' => '会员旅游换积分兑换', 'ORDER_SN' => $orderModel->SN]);
  753. } else if ($this->payType == 'garage_points') {
  754. Balance::changeUserBonus(\Yii::$app->user->id, 'garage_points', -abs($this->_payAmount), ['DEAL_TYPE_ID' => DealType::GARAGE_POINTS_EXCHANGE,'REMARK' => '会员名车积分兑换', 'ORDER_SN' => $orderModel->SN]);
  755. } else if ($this->payType == 'villa_points') {
  756. Balance::changeUserBonus(\Yii::$app->user->id, 'villa_points', -abs($this->_payAmount), ['DEAL_TYPE_ID' => DealType::VILLA_POINTS_EXCHANGE,'REMARK' => '会员房奖积分兑换', 'ORDER_SN' => $orderModel->SN]);
  757. } else if ($this->payType == 'reconsume_points') {
  758. Balance::changeUserBonus(\Yii::$app->user->id,'reconsume_points', -abs($this->_payAmount),['DEAL_TYPE_ID' => DealType::RECONSUME_POINTS_EXCHANGE,'REMARK' => '会员复销积分兑换', 'ORDER_SN' => $orderModel->SN]);
  759. }
  760. return $orderModel;
  761. }
  762. /**
  763. * 帮会员复销
  764. * @return bool|null
  765. * @throws Exception
  766. * @throws \yii\db\Exception
  767. */
  768. public function reconsumeAdd(){
  769. if(!$this->validate()){
  770. return null;
  771. }
  772. $ids = $this->goodsId;
  773. $totalAmount = 0;
  774. $totalPv = 0;
  775. $goodsType = ShopGoods::getGoodType();
  776. $hasInstalment = 0;
  777. $userId = Info::getUserIdByUserName($this->userName);
  778. $exchangeRate = floatval(Cache::getSystemConfig()['exchangeRate']['VALUE'] ?? 0); // 汇率
  779. foreach ($this->goodsNum as $k => $v) {
  780. if ($v) {
  781. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  782. if (!$goods) {
  783. throw new Exception('Products does not exists!');
  784. }
  785. if($goods['STORE_NUMS']>0){
  786. if ($goods['TYPE'] == 1 || $goods['TYPE'] == 2) {
  787. $discount = $goodsType[$goods['TYPE']]['discount'];
  788. $realPrice = $goods['SELL_PRICE'] * $discount/100;
  789. $realPv = $goods['PRICE_PV'] * $discount/100;
  790. $realPriceStandard = $goods['SELL_PRICE_STANDARD'] * $discount/100;
  791. } else {
  792. $discount = $goods['SELL_DISCOUNT'];
  793. $realPrice = $goods['SELL_PRICE'] * $discount;
  794. $realPv = $goods['PRICE_PV'] * $discount;
  795. $realPriceStandard = $goods['SELL_PRICE_STANDARD'] * $discount;
  796. }
  797. $totalAmount += $realPrice * intval($v);
  798. $totalPv += $realPv * intval($v);
  799. $this->_orderGoods[] = [
  800. 'GOODS_ID' => $goods['ID'],
  801. 'PRICE' => $goods['SELL_PRICE'],
  802. 'PV' => $goods['PRICE_PV'],
  803. 'REAL_PRICE' => $realPrice,
  804. 'REAL_PV' => $realPv,
  805. 'POINT' => $goods['POINT'],
  806. 'BUY_NUMS' => intval($v),
  807. 'SKU_CODE' => $goods['GOODS_NO'],
  808. 'GOODS_TITLE' => $goods['GOODS_NAME'],
  809. 'STANDARD_PRICE' => $goods['SELL_PRICE_STANDARD'],
  810. 'TAX_RATE' => $goods['TAX_RATE'],
  811. 'CATEGORY_TYPE' => $goods['CATEGORY_TYPE'],
  812. 'PAY_TYPE' => $this->payType ?? '',
  813. 'EMAIL' => $this->email ?? '',
  814. 'REAL_STANDARD_PRICE' => $realPriceStandard,
  815. 'EXCHANGE_RATE' => $exchangeRate,
  816. ];
  817. }
  818. if($goods['INSTALMENT']>0){ // 如果有分期付款商品,检查用户的分期付款状态
  819. if($v>1){ // 不可以购买多个
  820. throw new Exception(Yii::t('app', 'allowOnlyOne'));
  821. }
  822. $userStage = Instalment::getStage($userId);
  823. $userInstalmentInfo = Instalment::getInfo($userId);
  824. // 分期的总期数
  825. $instalment = intval(Cache::getSystemConfig()['instalment']['VALUE'] ?? 3);
  826. // 分期商品的期数不能大于总分期数限制
  827. if (intval($goods['INSTALMENT']) > $instalment) {
  828. throw new Exception(Yii::t('app', 'instalmentGoodsNoError'));
  829. }
  830. if ($userStage == $instalment){
  831. if ($goods['INSTALMENT'] != 1) {
  832. throw new Exception(Yii::t('app', 'canNotBuy'));
  833. }
  834. }else{
  835. if($userInstalmentInfo){
  836. if($userInstalmentInfo['STAGE']>0 && $userInstalmentInfo['ORDER_TYPE']!='FX'){
  837. throw new Exception(Yii::t('app', 'canNotBuy'));
  838. }
  839. }
  840. if($userStage + 1 != $goods['INSTALMENT']){ // 若用户分期阶段+1不等于商品的分期阶段,则报异常
  841. throw new Exception(Yii::t('app', 'canNotBuy'));
  842. }
  843. if ($userStage + 1 > $instalment){ // 若用户分期阶段+1大于总分期阶段,则报异常
  844. throw new Exception(Yii::t('app', 'canNotBuy'));
  845. }
  846. }
  847. $hasInstalment = $goods['INSTALMENT'];
  848. }
  849. }
  850. }
  851. $this->_decAmount = $totalAmount;
  852. $this->_decPv = $totalPv;
  853. $this->_freight = ($totalAmount>=300) ? 0 : 15;
  854. $this->_payAmount = $this->_decAmount + $this->_freight;
  855. $db = \Yii::$app->db;
  856. $transaction = $db->beginTransaction();
  857. try {
  858. $loginUserId = \Yii::$app->user->id;
  859. //是否开启伞下会员限制
  860. $isResaleUmbrella = Cache::getSystemConfig()['isResaleUmbrella']['VALUE'];
  861. if($isResaleUmbrella){
  862. $userId = Info::getUserIdByUserName($this->userName);
  863. $userNetwork = UserNetwork::find()->where("USER_ID=:USER_ID AND INSTR(PARENT_UIDS,'{$loginUserId}')>0", ['USER_ID'=>$userId])->count();
  864. if(!$userNetwork){
  865. throw new Exception($this->userName . Yii::t('app', 'doesNotYourSubMemberCanNotReconsume'));
  866. }
  867. }
  868. //判断用户余额是否充足
  869. if($this->payType=='cash') {
  870. if (Cash::getAvailableBalance($loginUserId) < $this->_payAmount) {
  871. throw new Exception(Yii::t('app', 'cashDoesNotAdequate'));
  872. }
  873. }else{
  874. if ($this->_payAmount > Balance::getBalanceReconsumePoints($loginUserId)) {
  875. throw new Exception(Yii::t('app', 'exchangePointDoesNotAdequate'));
  876. }
  877. }
  878. /**
  879. * 2022-04-28
  880. * York
  881. * 支付后减少库存
  882. */
  883. foreach ($this->goodsNum as $k => $v){
  884. if ($v){
  885. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  886. if (!$goods) {
  887. throw new Exception(Yii::t('app', 'productsDoesSoldOut'));
  888. }
  889. if ($goods['STORE_NUMS'] >= $this->goodsNum[$k]){
  890. $data = ShopGoods::find()->where(['ID' => $ids[$k]])->one();
  891. $goods_store_nums = $data->STORE_NUMS - $this->goodsNum[$k];
  892. $data->STORE_NUMS = $goods_store_nums;
  893. $data->update();
  894. //下单后库存小于等于0 商品下架
  895. if($goods_store_nums <= 0){
  896. $data->STATUS = 0;
  897. $data->UPDATED_AT = Date::nowTime();
  898. $data->update();
  899. }
  900. }else{
  901. throw new Exception($goods['GOODS_NAME'] . Yii::t('app', 'insufficientInventory'));
  902. }
  903. }
  904. }
  905. //写入订单
  906. if (!$orderResult = $this->addUserOrder()) {
  907. throw new Exception(Form::formatErrorsForApi($orderResult->getErrors()));
  908. }
  909. if ($hasInstalment){ // 如果有分期付款的商品,写入信息至分期付款表
  910. $instalmentModel = Instalment::findOne(['USER_ID'=>$userId]);
  911. if(!$instalmentModel) {
  912. $instalmentModel = new Instalment();
  913. }
  914. $instalmentModel->USER_ID = $userId;
  915. $instalmentModel->STAGE = $hasInstalment;
  916. $instalmentModel->ORDER_TYPE = 'FX';
  917. $instalmentModel->UPDATE_TIME = time();
  918. $instalmentModel->save();
  919. }
  920. $transaction->commit();
  921. }catch (\Exception $e){
  922. $transaction->rollBack();
  923. $this->addError('add', $e->getMessage());
  924. return null;
  925. }
  926. return true;
  927. }
  928. /**
  929. * 帮会员复消的订单
  930. */
  931. public function addUserOrder(){
  932. $periodObj = Period::instance();
  933. $nowPeriodNum = $periodObj->getNowPeriodNum();
  934. $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
  935. //帮复消会员Id(登陆会员)
  936. $loginUserId = \Yii::$app->user->id;
  937. $loginUserName = Info::getUserNameByUserId($loginUserId);
  938. //订单会员Id
  939. $userId = Info::getUserIdByUserName($this->userName);
  940. $email = Info::getEmailByUserId($this->userName);
  941. // 加入订单信息
  942. // if($this->province!=1){
  943. // $warehouse = Region::getWarehouseByCode($this->province);//仓库
  944. // if(!$warehouse){
  945. // throw new Exception(Yii::t('app', 'deliveryTemporarilyNotSupported'));
  946. // }
  947. // }else{
  948. $warehouse = '01';
  949. // }
  950. $ordNo = $this->_generateSn();
  951. $orderModel = new Order();
  952. $orderModel->SN = 'OS'.$ordNo;
  953. $orderModel->DEC_SN = 'DS'.$ordNo;
  954. $orderModel->ORDER_TYPE = $this->type;
  955. $orderModel->ORDER_CATEGORY = 'STUDIO';
  956. $orderModel->USER_ID = $userId;
  957. $orderModel->USER_NAME = $this->userName;
  958. $orderModel->ORDER_AMOUNT = $this->_decAmount;
  959. $orderModel->PV = $this->_decPv;
  960. $orderModel->PAY_AMOUNT = $this->_payAmount;
  961. $orderModel->PAY_PV = $this->_decPv;
  962. $orderModel->PAY_AT = Date::nowTime();
  963. $orderModel->PAY_TYPE = $this->payType;
  964. $orderModel->PERIOD_NUM = $nowPeriodNum;
  965. $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  966. $orderModel->FREIGHT = $this->_freight;
  967. $orderModel->PAY_FREIGHT = $this->_freight;
  968. $orderModel->CONSIGNEE = $this->consignee;
  969. $orderModel->MOBILE = $this->acceptMobile;
  970. $orderModel->PROVINCE = $this->province[0];
  971. $orderModel->LGA_NAME = $this->lgaName;
  972. $orderModel->CITY_NAME = $this->cityName;
  973. $orderModel->ADDRESS = $this->detailaddress;
  974. $orderModel->FRONT_REMARK = $this->remark;
  975. $orderModel->WAREHOUSE = $warehouse;
  976. $orderModel->STATUS = 1;
  977. $orderModel->CREATED_AT = Date::nowTime();
  978. $orderModel->CREATE_USER = $loginUserName;
  979. $orderModel->EMAIL = $email;
  980. if(!$orderModel->save()){
  981. throw new Exception(Form::formatErrorsForApi($orderModel->getErrors()));
  982. }
  983. // 加入商品到订单商品表
  984. foreach($this->_orderGoods as $key=>$value){
  985. $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN;
  986. $this->_orderGoods[$key]['P_CALC_MONTH'] = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  987. }
  988. OrderGoods::batchInsert($this->_orderGoods);
  989. //扣除会员余额/积分
  990. if($this->payType=='cash') {
  991. Cash::changeUserCash($loginUserId, 'CASH', -abs($this->_payAmount), ['REMARK' => Yii::t('app', 'membersResellingBalancePayment')]);
  992. }else{
  993. Balance::changeUserBonus($loginUserId,'reconsume_points', -abs($this->_payAmount),['DEAL_TYPE_ID' => DealType::RECONSUME_POINTS_EXCHANGE, 'REMARK' => Yii::t('app', 'membersExchangePointPayment')]);
  994. }
  995. return $orderModel;
  996. }
  997. /**
  998. * 生成流水号
  999. * @return string
  1000. */
  1001. private function _generateSn() {
  1002. return Date::today('Ymd') . $this->_random(10, 1);
  1003. }
  1004. /**
  1005. * 生成随机数
  1006. * @param $length
  1007. * @param int $numeric
  1008. * @return string
  1009. */
  1010. private function _random($length, $numeric = 0) {
  1011. $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
  1012. $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
  1013. $hash = '';
  1014. $max = strlen($seed) - 1;
  1015. for ($i = 0; $i < $length; $i++) {
  1016. $hash .= $seed[mt_rand(0, $max)];
  1017. }
  1018. return $hash;
  1019. }
  1020. public function addFakeOrder($userId, $periodNum){
  1021. $userName = Info::getUserNameByUserId($userId);
  1022. $sysConfig = Cache::getSystemConfig();
  1023. $mesureUpCondition = $sysConfig['monthPcsPvFxCondition']['VALUE']; // 月达标条件 NG默认30
  1024. $ordNo = $this->_generateSn();
  1025. $orderModel = new Order();
  1026. $orderModel->SN = 'OS'.$ordNo;
  1027. $orderModel->DEC_SN = 'DS'.$ordNo;
  1028. $orderModel->USER_ID = $userId;
  1029. $orderModel->USER_NAME = $userName;
  1030. $orderModel->PERIOD_NUM = $periodNum;
  1031. $orderModel->CREATE_USER = 'AUTO';
  1032. $orderModel->ORDER_TYPE = 'FX';
  1033. $orderModel->STATUS = 1;
  1034. $orderModel->PV = $mesureUpCondition;
  1035. $orderModel->PAY_PV = $mesureUpCondition;
  1036. $orderModel->P_CALC_MONTH = '1970-01-01';
  1037. $orderModel->CREATED_AT = Date::nowTime();
  1038. $orderModel->EXPRESS_TYPE = 1;
  1039. $orderModel->IS_AUTO = 1;
  1040. if(!$orderModel->save()){
  1041. $this->addErrors($orderModel->getErrors());
  1042. return false;
  1043. }
  1044. return $orderModel;
  1045. }
  1046. }