MPriceAdjustment.Class.php 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929
  1. <?php
  2. /**
  3. * 调价单管理
  4. * Created by PhpStorm.
  5. * User: phperstar
  6. * Date: 2019/4/16
  7. * Time: 9:41 AM
  8. */
  9. namespace JinDouYun\Model\Price;
  10. use JinDouYun\Cache\PageCache;
  11. use JinDouYun\Cache\PriceCache;
  12. use JinDouYun\Dao\Price\DPriceRangeSheet;
  13. use JinDouYun\Model\Goods\MGoods;
  14. use JinDouYun\Model\GoodsManage\MSku;
  15. use JinDouYun\Model\Stock\MInventory;
  16. use Mall\Framework\Core\ErrorCode;
  17. use Mall\Framework\Core\ResultWrapper;
  18. use Mall\Framework\Core\StatusCode;
  19. use JinDouYun\Model\MBaseModel;
  20. use JinDouYun\Dao\Price\DAreaPrice;
  21. use JinDouYun\Dao\Price\DNationalUnifiedPrice;
  22. use JinDouYun\Dao\Price\DPriceAdjustment;
  23. use JinDouYun\Dao\Price\DLastEffectiveSalePriceAreaType;
  24. class MPriceAdjustment extends MBaseModel
  25. {
  26. /**
  27. * @var int
  28. */
  29. private $onlineUserId;
  30. /**
  31. * @var int
  32. */
  33. private $onlineEnterpriseId;
  34. /**
  35. * @var DPriceAdjustment
  36. */
  37. private $objDPriceAdjustment;
  38. private $objDDistrictPriceCity;
  39. private $objDDistrictPriceProvince;
  40. private $objPriceCache;
  41. /**
  42. * @var DPriceRangeSheet
  43. */
  44. private $objDPriceRangeSheet;
  45. /**
  46. * MPriceAdjustment constructor.
  47. * @param $onlineUserId
  48. * @param $onlineEnterpriseId
  49. * @throws \Exception
  50. */
  51. public function __construct($onlineUserId, $onlineEnterpriseId)
  52. {
  53. $this->onlineUserId = $onlineUserId;
  54. $this->onlineEnterpriseId = $onlineEnterpriseId;
  55. parent::__construct($this->onlineEnterpriseId, $this->onlineUserId);
  56. $this->objPriceCache = new PriceCache($this->onlineEnterpriseId);
  57. $this->objDPriceAdjustment = new DPriceAdjustment();
  58. $this->objDPriceRangeSheet = new DPriceRangeSheet();
  59. $this->objDPriceAdjustment->setTable($this->objDPriceAdjustment->get_Table() . '_' . $this->onlineEnterpriseId . '_' . date('Y') . '_' . ceil(date('m') / 3));
  60. $this->objDPriceAdjustment->setSearchIndex('priceAdjustmentSheet_search')->setType('priceAdjustmentSheet');
  61. }
  62. /**
  63. * 保存调价单
  64. * @param $sheetData
  65. * @return ResultWrapper
  66. */
  67. public function add($sheetData)
  68. {
  69. // 保存调单价数据
  70. $no = createOrderSn(StatusCode::$source['manage'], StatusCode::$orderType['priceAdjustment'], $this->onlineUserId);
  71. foreach ($sheetData as $key => $value) {
  72. $sheetData[$key]['no'] = $no;
  73. }
  74. $dbResult = $this->objDPriceAdjustment->insert($sheetData, true);
  75. if ($dbResult === false) {
  76. return ResultWrapper::fail($this->objDPriceAdjustment->error(), ErrorCode::$dberror);
  77. }
  78. if (is_array($dbResult)) {
  79. foreach ($dbResult as $key => $id) {
  80. if (isset($sheetData[$key])) {
  81. $sheetData[$key]['id'] = $id;
  82. }
  83. }
  84. }
  85. //self::updateEsData($sheetData);
  86. return ResultWrapper::success($dbResult);
  87. }
  88. /**
  89. * 更新ES
  90. * @param $data
  91. * @return mixed
  92. */
  93. public function updateEsData($data)
  94. {
  95. if (empty($data)) return $data;
  96. foreach ($data as $key => $val) {
  97. $esData = [
  98. 'enterpriseId' => $this->onlineEnterpriseId,
  99. 'id' => $val['id'],//自增id,
  100. 'no' => $val['no'],//调价单号,
  101. 'goodsCode' => isset($val['goodsCode']) ? $val['goodsCode'] : createCode(StatusCode::$code['goodsBasic']['prefix'], $val['goodsId'], StatusCode::$code['goodsBasic']['length']),//商品编号
  102. 'goodsName' => $val['goodsName'],//商品名称
  103. 'goodsId' => $val['goodsId'],//商品id
  104. 'saleType' => $val['saleType'],//销售类型 1实物销售 2虚库销售
  105. 'salePriceAreaType' => $val['salePriceAreaType'],//销售价格生效区域类型 1全国统一价 2大区价
  106. 'salePriceType' => $val['salePriceType'],//销售价格类型 1销售价格 2秒杀活动价
  107. 'shopId' => $val['shopId'],//店铺id
  108. 'shopName' => $val['shopName'],//店铺名称
  109. 'cargoOwnerCode' => '',//货主编码
  110. 'createUserId' => $val['createUserId'],//创建人id
  111. 'createUserName' => $val['createUserName'],//创建人姓名
  112. 'effectiveUserName' => isset($val['effectiveUserName']) ? $val['effectiveUserName'] : '',//生效人姓名
  113. 'effectiveUserId' => isset($val['effectiveUserId']) ? $val['effectiveUserId'] : '',//生效人id
  114. 'deleteStatus' => StatusCode::$standard,//删除状态 4删除 5正常
  115. 'effectiveStatus' => isset($val['effectiveStatus']) ? $val['effectiveStatus'] : StatusCode::$auditStatus['auditPass'],//生效状态 1.待审 2审核通过 3未通过 4审核中
  116. 'createTime' => isset($val['createTime']) ? $val['createTime'] : time(),//创建时间
  117. 'updateTime' => isset($val['updateTime']) ? $val['updateTime'] : time(),//修改时间
  118. 'salePrice' => json_decode($val['salePrice'], true),//销售价格
  119. ];
  120. $_id = self::createEsDocumentId($val['id']);
  121. $result = $this->objDPriceAdjustment->addUpSearchIndexDocument($esData, $_id);
  122. if (isset($result['_shards']) && isset($result['_shards']['successful']) && $result['_shards']['successful'] == 1) {
  123. //echo "es操作成功";
  124. //return;
  125. }
  126. //echo "es操作失败";
  127. }
  128. }
  129. /**
  130. * 生成文档id
  131. * @param $id
  132. * @return string
  133. */
  134. private function createEsDocumentId($id)
  135. {
  136. return 'EnterpriseId_' . $this->onlineEnterpriseId . '_id_' . $id;
  137. }
  138. /**
  139. * 最终价格保存
  140. * @param $sheetData
  141. * @return ResultWrapper
  142. * @throws \Exception
  143. */
  144. public function addPrice($sheetData)
  145. {
  146. switch ($sheetData['salePriceAreaType']) {
  147. case StatusCode::$salePriceAreaType['nationalUnifiedPrice']:
  148. return self::saveNationalUnifiedPrice($sheetData);
  149. break;
  150. case StatusCode::$salePriceAreaType['areaPrice']:
  151. return self::saveAreaPrice($sheetData);
  152. break;
  153. /*
  154. case StatusCode::$salePriceAreaType['regionalPrice'];
  155. return self::saveRegionalPrice($sheetData);
  156. break;
  157. case StatusCode::$salePriceAreaType['districtPrice']:
  158. return self::formatPriceData($sheetData);
  159. break; */
  160. }
  161. }
  162. /**
  163. * 价格部分公共字段
  164. */
  165. public function commonField($sheetData)
  166. {
  167. $salePriceData = [
  168. 'no' => $sheetData['no'],
  169. 'goodsId' => $sheetData['goodsId'],
  170. 'shopId' => $sheetData['shopId'],
  171. 'salePriceType' => $sheetData['salePriceType'],
  172. 'salePrice' => $sheetData['salePrice'],
  173. 'updateTime' => $sheetData['createTime'],
  174. ];
  175. return $salePriceData;
  176. }
  177. /**
  178. * 保存物料最终的全国统一价格
  179. * @param $sheetData
  180. * @return ResultWrapper
  181. * @throws \Exception
  182. */
  183. public function saveNationalUnifiedPrice($sheetData)
  184. {
  185. $salePriceData = self::commonField($sheetData);
  186. $objDNationalUnifiedPrice = new DNationalUnifiedPrice();
  187. $objDNationalUnifiedPrice->beginTransaction();
  188. // 按照企业分表
  189. $tableName = 'qianniao_nationalUnifiedPrice_' . $this->onlineEnterpriseId;
  190. $objDNationalUnifiedPrice->setTable($tableName);
  191. // 查询是否已经设置过价格了
  192. $condition = [
  193. 'shopId' => $salePriceData['shopId'],
  194. 'salePriceType' => $salePriceData['salePriceType'],
  195. 'goodsId' => $salePriceData['goodsId'],
  196. ];
  197. $dbResult = $objDNationalUnifiedPrice->get($condition);
  198. if ($dbResult === false) {
  199. $objDNationalUnifiedPrice->rollBack();
  200. return ResultWrapper::fail($objDNationalUnifiedPrice->error(), ErrorCode::$dberror);
  201. }
  202. $salePriceData['salePrice'] = self::formatMerge($dbResult, $salePriceData, StatusCode::$salePriceAreaType['nationalUnifiedPrice']);
  203. $dbResult = $objDNationalUnifiedPrice->replace($salePriceData);
  204. if ($dbResult === false) {
  205. $objDNationalUnifiedPrice->rollBack();
  206. return ResultWrapper::fail($objDNationalUnifiedPrice->error(), ErrorCode::$dberror);
  207. }
  208. //unset($dbResult);
  209. // $objDAreaPrice = new DAreaPrice();
  210. // // 按照企业分表
  211. // $tableName = 'qianniao_areaPrice_' . $this->onlineEnterpriseId;
  212. // $objDAreaPrice->setTable($tableName);
  213. //
  214. // $dbResult = $objDAreaPrice->delete(
  215. // [
  216. // 'shopId' => $sheetData['shopId'],
  217. // 'goodsId' => $sheetData['goodsId'],
  218. // 'salePriceType' => StatusCode::$salePriceType['salePrice']
  219. // ]
  220. // );
  221. // if ($dbResult === false) {
  222. // $objDNationalUnifiedPrice->rollBack();
  223. // return ResultWrapper::fail($objDAreaPrice->error(), ErrorCode::$dberror);
  224. // }
  225. $objDNationalUnifiedPrice->commit();
  226. //self::savePriceRange($salePriceData);
  227. return ResultWrapper::success($dbResult);
  228. }
  229. private function formatMerge($dbResult, $salePriceData, $salePriceAreaType)
  230. {
  231. if (!is_array($salePriceData['salePrice'])) {
  232. $salePriceData['salePrice'] = json_decode($salePriceData['salePrice'], true);
  233. }
  234. // 如果已经存在价格了,按照skuid合并和替换价格
  235. if (!empty($dbResult)) {
  236. $nowSalePrice = json_decode($dbResult['salePrice'], true);
  237. if (empty($nowSalePrice)) {
  238. $salePriceData['salePrice'] = json_encode($salePriceData['salePrice']);
  239. } else {
  240. // 把已经存在价格替换成新的
  241. foreach ($nowSalePrice as $key => $value) {
  242. if (isset($salePriceData['salePrice'][$key])) {
  243. if ($salePriceAreaType == StatusCode::$salePriceAreaType['areaPrice']) {
  244. if (count($salePriceData['salePrice'][$key]) > 1) {
  245. $nowSalePrice[$key] = array_merge($value, $salePriceData['salePrice'][$key]);
  246. } else {
  247. $nowSalePrice[$key] = $salePriceData['salePrice'][$key];
  248. }
  249. } else {
  250. $nowSalePrice[$key] = $salePriceData['salePrice'][$key];
  251. }
  252. }else{
  253. unset($nowSalePrice[$key]);
  254. }
  255. unset($salePriceData['salePrice'][$key]);
  256. }
  257. // 把新的和旧的合并到一起作为最新的价格
  258. if (!empty($salePriceData['salePrice'])) {
  259. $salePriceData['salePrice'] = $salePriceData['salePrice'] + $nowSalePrice;
  260. } else {
  261. $salePriceData['salePrice'] = $nowSalePrice;
  262. }
  263. $salePriceData['salePrice'] = json_encode($salePriceData['salePrice']);
  264. }
  265. }
  266. if (is_array($salePriceData['salePrice'])) {
  267. $salePriceData['salePrice'] = json_encode($salePriceData['salePrice']);
  268. }
  269. return $salePriceData['salePrice'];
  270. }
  271. /**
  272. * 报错物料最终的区域价格
  273. * @param $sheetData
  274. * @return ResultWrapper
  275. * @throws \Exception
  276. */
  277. public function saveAreaPrice($sheetData)
  278. {
  279. $salePriceData = self::commonField($sheetData);
  280. $salePriceData['salePrice'] = json_decode($salePriceData['salePrice'], true);
  281. $objDAreaPrice = new DAreaPrice();
  282. // 按照企业分表
  283. $tableName = 'qianniao_areaPrice_' . $this->onlineEnterpriseId;
  284. $objDAreaPrice->setTable($tableName);
  285. // 查询是否已经设置过价格了
  286. $condition = [
  287. 'shopId' => $salePriceData['shopId'],
  288. 'salePriceType' => $salePriceData['salePriceType'],
  289. 'goodsId' => $salePriceData['goodsId'],
  290. ];
  291. $dbResult = $objDAreaPrice->get($condition);
  292. if ($dbResult === false) {
  293. return ResultWrapper::fail($objDAreaPrice->error(), ErrorCode::$dberror);
  294. }
  295. $salePriceData['salePrice'] = self::formatMerge($dbResult, $salePriceData, StatusCode::$salePriceAreaType['areaPrice']);
  296. $dbResult = $objDAreaPrice->replace($salePriceData);
  297. if ($dbResult === false) {
  298. return ResultWrapper::fail($objDAreaPrice->error(), ErrorCode::$dberror);
  299. } else {
  300. //self::savePriceRange($salePriceData);
  301. return ResultWrapper::success($dbResult);
  302. }
  303. }
  304. /**
  305. * 保存大区最终价格
  306. */
  307. public function saveRegionalPrice($sheetData)
  308. {
  309. $salePriceData = [];
  310. $sheetData['salePriceArea'] = json_decode($sheetData['salePriceArea'], true);
  311. foreach ($sheetData['salePriceArea'] as $k => $v) {
  312. $salePriceData[$k] = self::commonField($sheetData);
  313. $salePriceData[$k]['regionalDepartmentId'] = $v;
  314. $salePriceData[$k]['regionalGroupId'] = $sheetData['regionalGroupId'];
  315. }
  316. $objDRegionalDepartmentPrice = new DRegionalDepartmentPrice();
  317. // 按照店铺分表
  318. $tableName = 'regionalDepartmentPrice_' . $sheetData['shopId'];
  319. $objDRegionalDepartmentPrice->setTable($tableName);
  320. $dbResult = $objDRegionalDepartmentPrice->replace(array_values($salePriceData), true);
  321. if ($dbResult === false) {
  322. return ResultWrapper::fail($objDRegionalDepartmentPrice->error(), ErrorCode::$dberror);
  323. }
  324. return ResultWrapper::success($dbResult);
  325. }
  326. /**
  327. * 保存区县级最终价格
  328. * @param int $cityid 城市id
  329. * @param array $districtPriceCityData 区县价格数据
  330. * @return ResultWrapper
  331. */
  332. public function saveCityPrice($cityid, $districtPriceCityData)
  333. {
  334. // 计算区县分表
  335. $tableName = 'districtPrice_city_' . $cityid;
  336. $this->objDDistrictPriceCity->setTable($tableName);
  337. $dbResult = $this->objDDistrictPriceCity->replace($districtPriceCityData, true);
  338. if ($dbResult === false) {
  339. return ResultWrapper::fail($this->objDDistrictPriceCity->error(), ErrorCode::$dberror);
  340. } else {
  341. return ResultWrapper::success($dbResult);
  342. }
  343. }
  344. /**
  345. * 保存省级最终价格
  346. * @param int $provinceId 省id
  347. * @param array $districtPriceProvincesData 区域价省一级数据
  348. * @return ResultWrapper
  349. */
  350. public function saveProvincesPrice($provinceId, $districtPriceProvincesData)
  351. {
  352. // 计算省份分表
  353. $tableName = 'districtPrice_province_' . $provinceId;
  354. $this->objDDistrictPriceProvince->setTable($tableName);
  355. $dbResult = $this->objDDistrictPriceProvince->replace($districtPriceProvincesData, true);
  356. if ($dbResult === false) {
  357. return ResultWrapper::fail($this->objDDistrictPriceProvince->error(), ErrorCode::$dberror);
  358. } else {
  359. return ResultWrapper::success($dbResult);
  360. }
  361. }
  362. /**
  363. * 组装区县价格数据
  364. * @param array $sheetData 调单价数据
  365. * @return ResultWrapper
  366. */
  367. public function formatPriceData($sheetData)
  368. {
  369. $sheetData['salePriceArea'] = json_decode($sheetData['salePriceArea'], true);
  370. $areaData = self::areaGroup($sheetData['salePriceArea']);
  371. $salePriceData = self::commonField($sheetData);
  372. if (isset($areaData['citys'])) {
  373. // 按照城市分表插入价格数据
  374. foreach ($areaData['citys'] as $key => $value) {
  375. foreach ($value['district'] as $k => $v) {
  376. $salePriceData['districtId'] = $v;
  377. $districtPriceCityData[] = $salePriceData;
  378. }
  379. $result = self::saveCityPrice($key, $districtPriceCityData);
  380. if (!$result->isSuccess()) {
  381. return $result;
  382. }
  383. }
  384. }
  385. if (isset($areaData['provinces'])) {
  386. // 按照省分表插入价格数据
  387. foreach ($areaData['provinces'] as $key => $value) {
  388. unset($salePriceData['districtId']);
  389. $districtPriceProvinceData[] = $salePriceData;
  390. $result = self::saveProvincesPrice($value, $districtPriceProvinceData);
  391. if (!$result->isSuccess()) {
  392. return $result;
  393. }
  394. }
  395. }
  396. return $result;
  397. }
  398. /**
  399. * 切割省市区归组
  400. * @param array $areaDatas 区域数据
  401. * @return array
  402. */
  403. public function areaGroup($areaDatas)
  404. {
  405. $citys = [];
  406. $provinces = [];
  407. foreach ($areaDatas as $key => $value) {
  408. $areaData = explode('-', $value);
  409. // 提取区一级
  410. if ($areaData[2] != 0) {
  411. $citys[$areaData[1]]['district'][] = $areaData[2];
  412. continue;
  413. }
  414. // 提取市一级
  415. if ($areaData[1] != 0) {
  416. $citys[$areaData[1]]['district'][] = 0;
  417. continue;
  418. }
  419. // 提取省一级
  420. if ($areaData[0] != 0) {
  421. $provinces[] = $areaData[0];
  422. }
  423. }
  424. return [
  425. 'citys' => $citys,
  426. 'provinces' => $provinces,
  427. ];
  428. }
  429. /**
  430. * 获取所有调价单
  431. */
  432. public function getAll($params,$export = 0)
  433. {
  434. $pageData = pageToOffset($params['page'], $params['pageSize']);
  435. if ($export) {
  436. $pageData['limit'] = null;
  437. $pageData['offset'] = null;
  438. }
  439. $condition = null;
  440. if ($params['keyword']) {
  441. $condition = "(goodsName like '%" . $params['keyword'] . "%' or goodsCode like '%" . $params['keyword'] . "%' or no like '%" . $params['keyword'] . "%')";
  442. }
  443. if ($params['startTime'] && $params['endTime']) {
  444. if ($condition !== null) {
  445. $condition .= ' and ';
  446. }
  447. $condition .= " createTime >= " . $params['startTime'] . " and createTime <=" . $params['endTime'];
  448. }
  449. if ($params['effectiveStatus']) {
  450. if ($condition !== null) {
  451. $condition .= ' and ';
  452. }
  453. $condition .= " effectiveStatus = " . $params['effectiveStatus'];
  454. }
  455. if (isset($params['goodsId']) && !empty($params['goodsId'])) {
  456. if ($condition !== null) {
  457. $condition .= ' and ';
  458. }
  459. $condition .= " goodsId = " . $params['goodsId'];
  460. }
  461. if (isset($params['shopId']) && !empty($params['shopId'])){
  462. if ($condition !== null) {
  463. $condition .= ' and ';
  464. }
  465. $condition .= " shopId = ".$params['shopId'];
  466. }
  467. $condition = parent::getShopIdQueryParams($condition);
  468. $total = $this->objDPriceAdjustment->count($condition);
  469. $dbResult = $this->objDPriceAdjustment->select($condition, '*', 'id desc', $pageData['limit'], $pageData['offset']);
  470. if ($dbResult === false) {
  471. return ResultWrapper::fail($this->objDPriceAdjustment->error(), ErrorCode::$dberror);
  472. }
  473. $return = [
  474. 'data' => self::format($dbResult),
  475. 'total' => $total,
  476. ];
  477. //商品调价单导出
  478. if($export){
  479. self::exportGoodsPriceSheet($return['data']);
  480. exit;
  481. }
  482. return ResultWrapper::success($return);
  483. }
  484. /**
  485. * 格式化返回数据
  486. */
  487. public function format($data)
  488. {
  489. $skuIds = [];
  490. foreach ($data as $key => &$val) {
  491. if (!is_array($val['salePrice'])) {
  492. $val['salePrice'] = json_decode($val['salePrice'], true);
  493. }
  494. foreach ($val['salePrice'] as $k => &$v) {
  495. if ($val['salePriceAreaType'] == StatusCode::$salePriceAreaType['nationalUnifiedPrice']) {
  496. $v['skuId'] = $k;
  497. }
  498. }
  499. $val['salePrice'] = array_values($val['salePrice']);
  500. foreach ($val['salePrice'] as $row){
  501. $skuIds[] = $row['skuId'];
  502. }
  503. }
  504. $objMSku = new MSku($this->onlineUserId,$this->onlineEnterpriseId);
  505. $skuResult = $objMSku->getSpecNameBySkuId($skuIds);
  506. $allSkuData = [];
  507. if ($skuResult->isSuccess()){
  508. $allSkuData = $skuResult->getData();
  509. }
  510. foreach ($data as &$value){
  511. foreach ($value['salePrice'] as &$row){
  512. $row['unitName'] = isset($allSkuData[$row['skuId']]) ? $allSkuData[$row['skuId']]['unitName'] : '';
  513. $row['specGroup'] = isset($allSkuData[$row['skuId']]) ? $allSkuData[$row['skuId']]['specGroup'] : [];
  514. if (empty($row['specGroup'])){
  515. $value['specType'] = StatusCode::$specType['single'];
  516. }else{
  517. $value['specType'] = StatusCode::$specType['multiple'];
  518. }
  519. }
  520. }
  521. return $data;
  522. }
  523. /**
  524. * 批量生效操作
  525. * @param array $ids 要生效的当局id集合
  526. * @param $params
  527. * @return ResultWrapper
  528. * @throws \Exception
  529. */
  530. public function effective($ids, $params)
  531. {
  532. // 计算调价单分表
  533. $tableName = 'qianniao_priceAdjustmentSheet_' . $this->onlineEnterpriseId . '_' . date('Y', $params['createTime']) . '_' . ceil(date('m', $params['createTime']) / 3);
  534. $this->objDPriceAdjustment->setTable($tableName);
  535. $priceAdjustment = $this->objDPriceAdjustment->get($ids);
  536. if ($priceAdjustment === false) {
  537. return ResultWrapper::fail($this->objDPriceAdjustment->error(), ErrorCode::$dberror);
  538. }
  539. if (empty($priceAdjustment)) {
  540. return ResultWrapper::fail('要生效的调价单不存在', ErrorCode::$contentNotExists);
  541. }
  542. $beginStatus = $this->objDPriceAdjustment->beginTransaction();
  543. // 将调价单变更为生效状态
  544. $dbResult = $this->objDPriceAdjustment->update(
  545. [
  546. 'effectiveStatus' => StatusCode::$auditStatus['auditPass'],
  547. 'effectiveUserName' => isset($params['effectiveUserName']) ? $params['effectiveUserName'] : '',
  548. 'effectiveUserId' => isset($params['effectiveUserId']) ? $params['effectiveUserId'] : '',
  549. ], $ids);
  550. if ($dbResult === false) {
  551. $this->objDPriceAdjustment->rollBack();
  552. return ResultWrapper::fail($this->objDPriceAdjustment->error(), ErrorCode::$dberror);
  553. }
  554. unset($dbResult);
  555. // 将商品最后生效价格区域类型写入记录表中
  556. $objDLastEffectiveSalePriceAreaType = new DLastEffectiveSalePriceAreaType();
  557. $objDLastEffectiveSalePriceAreaType->setTable('qianniao_lastEffectiveSalePriceAreaType_' . $this->onlineEnterpriseId);
  558. $data = [
  559. 'shopId' => $priceAdjustment['shopId'],
  560. 'goodsCode' => $priceAdjustment['goodsCode'],
  561. 'goodsId' => $priceAdjustment['goodsId'],
  562. 'lastEffectiveSalePriceAreaType' => $priceAdjustment['salePriceAreaType'],
  563. 'no' => $priceAdjustment['no'],
  564. 'updateTime' => time(),
  565. ];
  566. $dbResult = $objDLastEffectiveSalePriceAreaType->replace($data);
  567. if ($dbResult === false) {
  568. $this->objDPriceAdjustment->rollBack();
  569. return ResultWrapper::fail($objDLastEffectiveSalePriceAreaType->error(), ErrorCode::$dberror);
  570. }
  571. $result = self::addPrice($priceAdjustment);
  572. if (!$result->isSuccess()) {
  573. $this->objDPriceAdjustment->rollBack();
  574. return ResultWrapper::fail($this->objDPriceAdjustment->error(), ErrorCode::$dberror);
  575. }
  576. unset($result);
  577. // 每编辑一件商品需要清除一下小程序商品首页的缓存;
  578. $objPageCache = new PageCache();
  579. $objPageCache->delPage();
  580. //删除缓存
  581. $this->objPriceCache->delNationSalePrice($priceAdjustment['goodsId']);
  582. //商户商品设置库存成本
  583. $objMInventory = new MInventory($this->onlineEnterpriseId, $this->onlineUserId);
  584. $salePrice = json_decode($priceAdjustment['salePrice'], true);
  585. foreach($salePrice as $skuId => $v){
  586. $params = [
  587. 'costPrice' => $v['salePrice'],
  588. 'skuId' => $skuId,
  589. ];
  590. $modelResult = $objMInventory->updateInventoryCost($params);
  591. if(!$modelResult->isSuccess()){
  592. $this->objDPriceAdjustment->rollBack();
  593. return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
  594. }
  595. }
  596. $beginStatus && $this->objDPriceAdjustment->commit();
  597. return ResultWrapper::success($dbResult);
  598. }
  599. /**
  600. * 计算最低价
  601. */
  602. public function getMinPrice($salePrice)
  603. {
  604. $minPrice = $salePrice['salePrice'];
  605. if ($salePrice['enabledLadder']) {
  606. foreach ($salePrice['ladderPrice'] as $key => $value) {
  607. if ($value['price'] < $minPrice) {
  608. $minPrice = $value['price'];
  609. }
  610. }
  611. }
  612. return $minPrice;
  613. }
  614. /**
  615. * 自从创建调价单且自动生效接口
  616. */
  617. public function addAndEffective($sheetData, $effectiveParams = [])
  618. {
  619. $result = self::add($sheetData);
  620. if (!$result->isSuccess()) {
  621. return ResultWrapper::fail($result->getData(), $result->getErrorCode());
  622. }
  623. $sheetId = $result->getData();
  624. unset($result);
  625. if (empty($effectiveParams)) {
  626. $effectiveParams['createTime'] = time();
  627. }
  628. $result = self::effective($sheetId, $effectiveParams);
  629. if (!$result->isSuccess()) {
  630. return ResultWrapper::fail($result->getData(), $result->getErrorCode());
  631. }
  632. // 每编辑一件商品需要清除一下小程序商品首页的缓存;
  633. $objPageCache = new PageCache();
  634. $objPageCache->delPage();
  635. return ResultWrapper::success($result->getData());
  636. }
  637. /**
  638. * 商品调价单搜索
  639. * @param $selectParams
  640. * @return ResultWrapper
  641. */
  642. public function search($selectParams)
  643. {
  644. $defaultDSL = [
  645. 'from' => $selectParams['offset'],
  646. 'size' => $selectParams['limit'],
  647. 'sort' => [
  648. 'createTime' => [
  649. 'order' => 'desc'
  650. ],
  651. ],
  652. ];
  653. $dsl = [];
  654. $dsl['query']['bool']['must'][] = [
  655. 'term' => ['enterpriseId' => $this->onlineEnterpriseId],
  656. ];
  657. //店铺id
  658. parent::getAccessShopIds();
  659. if (parent::$shopIds) {
  660. $dsl['query']['bool']['filter'][] = [
  661. 'terms' => ['shopId' => parent::$shopIds]
  662. ];
  663. }
  664. //订单编号,收货人,商品名称
  665. if (!empty($selectParams['keyword'])) {
  666. $dsl['query']['bool']['must'][] = [
  667. 'multi_match' => [
  668. 'fields' => ['goodsCode', 'goodsName'],
  669. 'query' => $selectParams['keyword'],
  670. 'fuzziness' => 'AUTO',
  671. ],
  672. ];
  673. }
  674. //生效状态
  675. if (!empty($selectParams['effectiveStatus'])) {
  676. $dsl['query']['bool']['filter'][] =
  677. ['term' => ['effectiveStatus' => $selectParams['effectiveStatus']]];
  678. }
  679. //时间
  680. if (!empty($selectParams['startTime']) && !empty($selectParams['endTime'])) {
  681. $dsl['query']['bool']['must'][] = [
  682. 'range' => [
  683. 'createTime' => [
  684. 'gte' => $selectParams['startTime'],
  685. 'lte' => $selectParams['endTime'],
  686. ]
  687. ]
  688. ];
  689. } else {
  690. if (!empty($selectParams['startTime'])) {
  691. $dsl['query']['bool']['must'][] = [
  692. 'range' => [
  693. 'createTime' => [
  694. 'gte' => $selectParams['startTime'],
  695. ]
  696. ]
  697. ];
  698. }
  699. if (!empty($selectParams['endTime'])) {
  700. $dsl['query']['bool']['must'][] = [
  701. 'range' => [
  702. 'createTime' => [
  703. 'lte' => $selectParams['endTime'],
  704. ]
  705. ]
  706. ];
  707. }
  708. }
  709. $dsl = array_merge($defaultDSL, $dsl);
  710. $result = $this->objDPriceAdjustment->getSearchQueryDsl($dsl);
  711. if (isset($result['status']) && $result['status'] == 400) {
  712. return ResultWrapper::fail('获取数据失败' . $result['error']['reason'], ErrorCode::$apiNotResult);
  713. }
  714. $total = $result['hits']['total'];
  715. $dbResult = $result['hits']['hits'];
  716. $list = [];
  717. foreach ($dbResult as $key => &$value) {
  718. $data = [];
  719. $data = $value['_source'];
  720. $list[] = $data;
  721. }
  722. $return = [
  723. 'data' => self::format($list),
  724. 'total' => ($total) ? intval($total) : 0,
  725. ];
  726. return ResultWrapper::success($return);
  727. }
  728. /**
  729. * 保存商品价格范围
  730. * @param array $data
  731. * @return ResultWrapper
  732. */
  733. public function savePriceRange(array $data)
  734. {
  735. if (empty($data)) {
  736. return ResultWrapper::success([]);
  737. }
  738. $salePrice = json_decode($data['salePrice'],true);
  739. $allSalePrice = array_column($salePrice,'salePrice');
  740. $sale = [
  741. 'minSalePrice' => min($allSalePrice),
  742. 'maxSalePrice' => max($allSalePrice),
  743. ];
  744. $add = [
  745. 'goodsCode' => isset($data['goodsCode']) ? $data['goodsCode'] : '',
  746. 'goodsName' => isset($data['goodsName']) ? $data['goodsName'] : '',
  747. 'goodsId' => $data['goodsId'],
  748. 'shopId' => $data['shopId'],
  749. 'createTime' => time(),
  750. 'salePrice' => json_encode($sale),
  751. ];
  752. $this->objDPriceRangeSheet->setTable($this->objDPriceRangeSheet->get_Table() . '_' . $this->onlineEnterpriseId);
  753. $result = $this->objDPriceRangeSheet->replace($add);
  754. if ($result === false) {
  755. return ResultWrapper::fail($this->objDPriceRangeSheet->error(), ErrorCode::$dberror);
  756. }
  757. return ResultWrapper::success(true);
  758. }
  759. /**
  760. * 商品调价单导出方法
  761. * @param $priceSheetData
  762. */
  763. private static function exportGoodsPriceSheet($priceSheetData)
  764. {
  765. //导出到本地
  766. header("Content-type:application/vnd.ms-excel");
  767. header("Content-Disposition:filename=商品调价单明细表记录.csv");
  768. header('Cache-Control: max-age=0');
  769. $fp = fopen('php://output', 'a');
  770. $head = ['调价单编码','商品名称','调价日期','调整后价格规格','调整市场价格','阶梯价','销售价','调整人','相关店铺', '状态']; //定义标题
  771. foreach ($head as $i => $v) {
  772. $head[$i] = mb_convert_encoding($v, 'GBK', 'utf-8'); //将中文标题转换编码,否则乱码
  773. }
  774. fputcsv($fp, $head);
  775. $limit = 10000;
  776. $num = 0;//计数器
  777. foreach ($priceSheetData as $v) {
  778. $marketPrice = []; //市场价格
  779. $ladderPrice = ''; //阶梯价
  780. $salePrice = []; //销售价
  781. $unitName = []; //调整规格
  782. $specValueName = [];//副规格
  783. if(!empty($v['salePrice'])){
  784. foreach ($v['salePrice'] as $value){
  785. $marketPrice[] = $value['marketPrice'];
  786. $ladderPrice = $value['ladderPrice'];
  787. $salePrice[] = $value['salePrice'];
  788. if(!empty($value['specGroup'])){
  789. foreach ($value['specGroup'] as $vv){
  790. $specValueName = $vv['specValueName'];
  791. }
  792. }
  793. $unitName[] = $value['unitName'].';'.$specValueName;//调整规格
  794. }
  795. }
  796. //循环数据
  797. $num++;
  798. if ($num == $limit) {
  799. ob_flush();//释放内存
  800. flush();
  801. }
  802. $rows['no'] = isset($v['no']) ? $v['no'] : '';//调价单编码
  803. $rows['goodsName'] = isset($v['goodsName']) ? $v['goodsName'] : '';//商品名称
  804. $rows['createTime'] = isset($v['createTime']) ? date('Y-m-d H:i:s',$v['createTime']) : '';//调价时间
  805. $rows['unitName'] = implode("\n",$unitName);//调整规格
  806. $rows['price'] = implode("\n",$marketPrice);//调整市场价格
  807. $rows['ladderPrice'] = !empty($ladderPrice) ? $ladderPrice : "否";//阶梯价
  808. $rows['salePrice'] = implode("\n",$salePrice);//销售价
  809. //$rows['customerName'] = isset($v['customerName']) ? $v['customerName'] : '';//客户类型
  810. // $rows['goodsCode'] = isset($v['goodsCode']) ? $v['goodsCode'] : '';//商品编码
  811. $rows['createUserName'] = isset($v['createUserName']) ? $v['createUserName'] : '';//调整人
  812. $rows['shopName'] = isset($v['shopName']) ? $v['shopName'] : '';//相关店铺
  813. $rows['effectiveStatus'] = $v['effectiveStatus'] === 2 ? '生效' : '未生效';//状态
  814. foreach ($rows as $kk => $vv) {
  815. $rs[$kk] = mb_convert_encoding($vv, 'GBK', 'utf-8'); //转译编码
  816. }
  817. fputcsv($fp, $rs);
  818. $rows = [];
  819. }
  820. exit;
  821. }
  822. }