GoodsController.php 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * Author: 芸众商城 www.yunzshop.com
  5. * Date: 2017/2/22
  6. * Time: 下午1:51
  7. */
  8. namespace app\backend\modules\goods\controllers;
  9. use app\backend\modules\goods\models\Brand;
  10. use app\backend\modules\goods\models\Category;
  11. use app\backend\modules\goods\models\Goods;
  12. use app\backend\modules\goods\models\GoodsOption;
  13. use app\backend\modules\goods\models\GoodsSpecItem;
  14. use app\backend\modules\goods\models\Sale;
  15. use app\backend\modules\goods\services\CopyGoodsService;
  16. use app\backend\modules\goods\services\CreateGoodsService;
  17. use app\backend\modules\goods\services\EditGoodsService;
  18. use app\backend\modules\goods\services\GoodsOptionService;
  19. use app\backend\modules\goods\services\GoodsService;
  20. use app\backend\modules\uploadVerificate\UploadVerificationBaseController;
  21. use app\common\components\BaseController;
  22. use app\backend\modules\goods\services\CategoryService;
  23. use app\backend\modules\goods\models\GoodsParam;
  24. use app\backend\modules\goods\models\GoodsSpec;
  25. use app\common\components\Widget;
  26. use app\common\helpers\Cache;
  27. use app\common\helpers\PaginationHelper;
  28. use app\common\helpers\Url;
  29. use app\common\models\GoodsCategory;
  30. use app\common\models\GoodsSmallUrl;
  31. use app\common\services\SmallQrCode;
  32. use Illuminate\Database\Eloquent\Collection;
  33. use Illuminate\Support\Facades\DB;
  34. use Setting;
  35. use app\common\services\goods\VideoDemandCourseGoods;
  36. use app\common\models\Store as StoreCashier;
  37. use Yunshop\Designer\models\Store;
  38. use Yunshop\GoodsSource\common\models\GoodsSource;
  39. use Yunshop\Hotel\common\models\Hotel;
  40. use Yunshop\LeaseToy\models\LeaseOrderModel;
  41. use Yunshop\LeaseToy\models\LeaseToyGoodsModel;
  42. use Yunshop\MemberTags\Common\models\MemberTagsModel;
  43. use Yunshop\VideoDemand\models\CourseGoodsModel;
  44. use app\common\helpers\ImageHelper;
  45. use app\common\models\goods\GoodsService as ServiceProvide;
  46. class GoodsController extends UploadVerificationBaseController
  47. {
  48. protected $goods_id = null;
  49. protected $shopset;
  50. protected $shoppay;
  51. private $list;
  52. private $brand;
  53. protected $lang = null;
  54. protected $success_url = 'goods.goods.index';
  55. protected $widget_url = 'goods.goods.widget-column';
  56. public function preAction()
  57. {
  58. parent::preAction(); // TODO: Change the autogenerated stub
  59. $this->lang = array(
  60. "shopname" => "商品名称",
  61. "mainimg" => "商品图片",
  62. "limittime" => "限时卖时间",
  63. "shopnumber" => "商品编号",
  64. "shopprice" => "商品价格",
  65. "putaway" => "上架",
  66. "soldout" => "下架",
  67. "good" => "商品",
  68. "price" => "价格",
  69. 'yes_stock' => '出售中',
  70. 'no_stock' => '售罄',
  71. "repertory" => "库存",
  72. "copyshop" => "复制商品",
  73. "isputaway" => "是否上架",
  74. "shopdesc" => "商品描述",
  75. "shopinfo" => "商品详情",
  76. 'shopoption' => "商品规格",
  77. 'marketprice' => "销售价格",
  78. 'shopsubmit' => "发布商品"
  79. );
  80. $this->goods_id = (int)\YunShop::request()->id;
  81. $this->shopset = Setting::get('shop.category');
  82. }
  83. public function index()
  84. {
  85. $producerId = intval(request()->producer_id);
  86. return view('goods.index', [
  87. 'data' => json_encode($this->goodsListData()),
  88. 'producerId' => json_encode($producerId),
  89. ]);
  90. }
  91. public function goodsSearch()
  92. {
  93. $producerId = intval(request()->producer_id);
  94. //课程商品id集合
  95. $courseGoods_ids = (new VideoDemandCourseGoods())->courseGoodsIds();
  96. $requestSearch = request()->search;
  97. $page = request()->page;
  98. if ($requestSearch) {
  99. $requestSearch = array_filter($requestSearch, function ($item) {
  100. return $item !== '';// && $item !== 0;
  101. });
  102. $categorySearch = array_filter(request()->category, function ($item) {
  103. if (is_array($item)) {
  104. return !empty($item[0]);
  105. }
  106. return !empty($item);
  107. });
  108. if ($categorySearch) {
  109. $requestSearch['category'] = $categorySearch;
  110. }
  111. }
  112. $per_size = request()->input('per_size')?request()->input('per_size'):20;
  113. $tab_state = request()->input('tab_state');
  114. //todo blank 这个插件的代码怎么加到这里???
  115. if ($producerId && app('plugins')->isEnabled('producer')) {
  116. $goodsBuild = Goodsselect(['id', 'display_order', 'thumb', 'title', 'has_option', 'price', 'stock', 'real_sales', 'status', 'is_hot', 'is_new', 'is_recommand', 'is_discount','cost_price'])->Search($requestSearch)->pluginIdShow()->with(['hasOneSmallCodeUrl'])
  117. ->whereHas('hasOneProducerGoods', function ($hasOneProducerGoods) use ($producerId) {
  118. $hasOneProducerGoods->where('producer_id', $producerId);
  119. });
  120. } else {
  121. $goodsBuild = Goods::select(['yz_goods.id', 'display_order', 'thumb', 'title', 'has_option', 'price', 'stock', 'real_sales', 'status', 'is_hot', 'is_new', 'is_recommand', 'is_discount','cost_price'])->Search($requestSearch)->pluginIdShow()->with(['hasOneSmallCodeUrl']);
  122. }
  123. //排序
  124. $order_by = request()->input('order_by');
  125. if ($order_by) {
  126. foreach ($order_by as $by_key => $by_value) {
  127. if ($by_value) {
  128. $goodsBuild->orderBy('yz_goods.'.$by_key, $by_value);
  129. }
  130. }
  131. } else {
  132. $goodsBuild->orderBy('yz_goods.display_order', 'desc');
  133. }
  134. $list = $goodsBuild->orderBy('yz_goods.id', 'desc')->state($tab_state)->paginate($per_size);
  135. foreach ($list as $key => $item) {
  136. $list[$key]['thumb'] = yz_tomedia($item->thumb);
  137. if (in_array($item['id'], $courseGoods_ids)) {
  138. $list[$key]['link'] = yzAppFullUrl('member/coursedetail/' . $item['id']);
  139. } else {
  140. $list[$key]['link'] = yzAppFullUrl('goods/' . $item['id']);
  141. }
  142. if ($item->hasOneSmallCodeUrl->collect_small_url) {
  143. $list[$key]['small_link'] = $item->hasOneSmallCodeUrl->collect_small_url;
  144. } else {
  145. $list[$key]['small_link'] = "";
  146. }
  147. $cost_ratio = 0;
  148. if($item['cost_price']){
  149. $basic = bcsub($item['price'],$item['cost_price'],2);
  150. $cost_ratio = bcdiv($basic,$item['cost_price'],4)*100;
  151. }
  152. $list[$key]['cost_ratio'] = $cost_ratio."%";
  153. }
  154. $list = $list->toArray();
  155. $list['lower_shelf'] = Goods::Search($requestSearch)->pluginIdShow()->state(0)->count();
  156. $list['put_shelf'] = Goods::Search($requestSearch)->pluginIdShow()->state(1)->count();
  157. $list['all_goods'] = Goods::Search($requestSearch)->pluginIdShow()->state()->count();
  158. if ($list) {
  159. return $this->successJson('成功', $list);
  160. } else {
  161. return $this->errorJson('找不到数据');
  162. }
  163. }
  164. protected function goodsListData()
  165. {
  166. $producerId = intval(request()->producer_id);
  167. //课程商品id集合
  168. $courseGoods_ids = (new VideoDemandCourseGoods())->courseGoodsIds();
  169. //增加商品属性搜索
  170. $product_attr_list = [
  171. 'is_new' => '新品',
  172. 'is_hot' => '热卖',
  173. 'is_recommand' => '推荐',
  174. 'is_discount' => '促销',
  175. ];
  176. //这里一次查出来太慢改成接口查询
  177. // $brands = Brand::getBrands()->getQuery()->select(['id','name'])->get()->toArray();
  178. $requestSearch = \YunShop::request()->search;
  179. if ($requestSearch) {
  180. $requestSearch = array_filter($requestSearch, function ($item) {
  181. return $item !== '';// && $item !== 0;
  182. });
  183. $categorySearch = array_filter(\YunShop::request()->category, function ($item) {
  184. if (is_array($item)) {
  185. return !empty($item[0]);
  186. }
  187. return !empty($item);
  188. });
  189. if ($categorySearch) {
  190. $requestSearch['category'] = $categorySearch;
  191. }
  192. }
  193. $category = Category::parentGetCategorys()->get();
  194. if ($producerId && app('plugins')->isEnabled('producer')) {
  195. $list = Goods::select(['id', 'display_order', 'thumb', 'title', 'has_option', 'price', 'stock', 'real_sales', 'status', 'is_hot', 'is_new', 'is_recommand', 'is_discount','cost_price'])->Search($requestSearch)->with(['hasOneSmallCodeUrl'])->pluginIdShow()
  196. ->whereHas('hasOneProducerGoods', function ($hasOneProducerGoods) use ($producerId) {
  197. $hasOneProducerGoods->where('producer_id', $producerId);
  198. })
  199. ->orderBy('display_order', 'desc')
  200. ->orderBy('yz_goods.id', 'desc')
  201. ->state(1)
  202. ->paginate(20);
  203. } else {
  204. $list = Goods::select(['id', 'display_order', 'thumb', 'title', 'has_option', 'price', 'stock', 'real_sales', 'status', 'is_hot', 'is_new', 'is_recommand', 'is_discount','cost_price'])
  205. ->Search($requestSearch)
  206. ->with(['hasOneSmallCodeUrl'])
  207. ->pluginIdShow()
  208. ->state(1)
  209. ->orderBy('display_order', 'desc')
  210. ->orderBy('yz_goods.id', 'desc')->paginate(20);
  211. }
  212. foreach ($list as $key => $item) {
  213. $list[$key]['thumb'] = yz_tomedia($item->thumb);
  214. if (in_array($item['id'], $courseGoods_ids)) {
  215. $list[$key]['link'] = yzAppFullUrl('member/coursedetail/' . $item['id']);
  216. } else {
  217. $list[$key]['link'] = yzAppFullUrl('goods/' . $item['id']);
  218. }
  219. if ($item->hasOneSmallCodeUrl->collect_small_url) {
  220. $list[$key]['small_link'] = $item->hasOneSmallCodeUrl->collect_small_url;
  221. } else {
  222. $list[$key]['small_link'] = "";
  223. }
  224. $cost_ratio = 0;
  225. if($item['cost_price']){
  226. $basic = bcsub($item['price'],$item['cost_price'],2);
  227. $cost_ratio = bcdiv($basic,$item['cost_price'],4)*100;
  228. }
  229. $list[$key]['cost_ratio'] = $cost_ratio."%";
  230. }
  231. $source_status = false;
  232. $source_is_open = \Setting::get('plugin.goods_source.is_open');
  233. if (app('plugins')->isEnabled('goods-source')&&(is_null($source_is_open) || $source_is_open)) {
  234. $source_status = true;
  235. }
  236. if ($source_status) {
  237. $source_list = GoodsSource::uniacid()->select(['id','source_name'])->get();
  238. } else {
  239. $source_list = New Collection();
  240. }
  241. $data = [
  242. 'list' => $list,
  243. 'courseGoods_ids' => $courseGoods_ids,
  244. 'requestSearch' => $requestSearch,
  245. 'category' => $category,
  246. 'cat_level' => $this->shopset['cat_level'],
  247. 'lang' => $this->lang,
  248. 'product_attr_list' => $product_attr_list,
  249. 'yz_url' => 'yzWebUrl',
  250. 'product_attr' => $requestSearch['product_attr'],
  251. 'edit_url' => yzWebFullUrl('goods.goods.edit'),
  252. 'delete_url' => yzWebFullUrl('goods.goods.destroy'),
  253. 'sort_url' => yzWebFullUrl('goods.goods.displayorder'),
  254. 'copy_url' => yzWebFullUrl('goods.goods.copy'),
  255. 'is_source_open' => $source_status ? 1 : 0,
  256. 'source_list' => $source_list,
  257. ];
  258. $data['lower_shelf'] = Goods::Search($requestSearch)->pluginIdShow()->state(0)->count();
  259. $data['put_shelf'] = Goods::Search($requestSearch)->pluginIdShow()->state(1)->count();
  260. $data['all_goods'] = Goods::Search($requestSearch)->pluginIdShow()->state()->count();
  261. return $data;
  262. }
  263. /**
  264. * 商品列表页数据
  265. */
  266. public function goodsList()
  267. {
  268. return $this->successJson('成功', $this->goodsListData());
  269. }
  270. public function copy()
  271. {
  272. $id = intval(\YunShop::request()->id);
  273. if (!$id) {
  274. $this->error('请传入正确参数.');
  275. }
  276. $result = CopyGoodsService::copyGoods($id);
  277. if (!$result) {
  278. $this->error('商品不存在.');
  279. }
  280. return $this->message('商品复制成功', Url::absoluteWeb($this->success_url));
  281. }
  282. public function create()
  283. {
  284. if (request()->ajax()) {
  285. $request = Request();
  286. $goods_service = new CreateGoodsService($request);
  287. $result = $goods_service->create();
  288. if ($result['status'] == 1) {
  289. return $this->successJson('商品创建成功');
  290. } else {
  291. return $this->errorJson($result['msg']);
  292. // !session()->has('flash_notification.message') && $this->error('商品修改失败');
  293. }
  294. }
  295. return view('goods.vue-goods', [
  296. 'store_url' => yzWebFullUrl(request()->input('route')),
  297. 'widget_url' => yzWebFullUrl($this->widget_url),
  298. 'success_url' => yzWebFullUrl($this->success_url),
  299. 'ckt_url' => Url::absoluteWeb('plugin.decorate.admin.page.get-list').'&i='.\YunShop::app()->uniacid.'#/picture_design_scene',
  300. 'is_decorate' => app('plugins')->isEnabled('decorate'),
  301. ])->render();
  302. }
  303. public function edit()
  304. {
  305. if (request()->ajax()) {
  306. $goods_service = new EditGoodsService(request()->input('id'), \YunShop::request());
  307. $result = $goods_service->edit();
  308. if ($result['status'] == 1) {
  309. return $this->successJson('商品修改成功');
  310. }
  311. return $this->errorJson($result['msg']);
  312. }
  313. return view('goods.vue-goods', [
  314. 'store_url' => yzWebFullUrl(request()->input('route'),['id'=>request()->input('id')]),
  315. 'success_url' => yzWebFullUrl($this->success_url),
  316. 'goods_id' => request()->input('id'),
  317. 'widget_url' => yzWebFullUrl($this->widget_url,['id'=> request()->input('id')]),
  318. 'ckt_url' => Url::absoluteWeb('plugin.decorate.admin.page.get-list').'&i='.\YunShop::app()->uniacid.'#/picture_design_scene',
  319. 'is_decorate' => app('plugins')->isEnabled('decorate'),
  320. ])->render();
  321. }
  322. //商品编辑挂件获取
  323. public function widgetColumn()
  324. {
  325. $data = app('GoodsWidgetContainer')->make('Manager')->handle();
  326. return $this->successJson('widgetColumn', $data);
  327. }
  328. public function oldPage()
  329. {
  330. //todo 所有操作去service里进行,供应商共用此方法。
  331. $request = Request();
  332. $goods_service = new EditGoodsService($request->id, \YunShop::request());
  333. $result = $goods_service->oldedit();
  334. if ($goods_service->goods_model->content) {
  335. $goods_service->goods_model->content = changeUmImgPath($goods_service->goods_model->content);
  336. }
  337. if ($result['status'] == 1) {
  338. Cache::flush();
  339. return $this->message('商品修改成功', Url::absoluteWeb($this->success_url));
  340. } else if ($result['status'] == -1) {
  341. if (isset($result['msg'])) {
  342. $this->error($result['msg']);
  343. }
  344. !session()->has('flash_notification.message') && $this->error('商品修改失败');
  345. }
  346. $list = collect($goods_service->goods_model)->toArray();
  347. if (!$list['id']) {
  348. return $this->message('商品不存在或已删除', '', 'error');
  349. }
  350. return view('goods.goods', [
  351. 'goods' => $goods_service->goods_model,
  352. 'lang' => $this->lang,
  353. 'goods_video' => collect($goods_service->goods_model->hasOneGoodsVideo)->toArray(),
  354. 'params' => collect($goods_service->goods_model->hasManyParams)->toArray(),
  355. 'allspecs' => collect($goods_service->goods_model->hasManySpecs)->toArray(),
  356. 'html' => $goods_service->optionsHtml,
  357. 'var' => \YunShop::app()->get(),
  358. 'brands' => $goods_service->brands,
  359. 'catetory_menus' => implode('', $goods_service->catetory_menus),
  360. 'virtual_types' => [],
  361. 'shopset' => $this->shopset,
  362. 'type' => 'edit',
  363. ])->render();
  364. }
  365. public function generateSmallCode()
  366. {
  367. $goods_id = intval(request()->id);
  368. if (!$goods_id) {
  369. return $this->message("商品ID不存在", '', 'error');
  370. }
  371. //检查商品小程序二维码是否存在
  372. $goods = GoodsSmallUrl::uniacid()->where("goods_id", $goods_id)->first();
  373. if (!empty($goods['collect_small_url'])) {
  374. return $this->message("小程序二维码已存在", '', 'error');
  375. }
  376. $small_qr = new SmallQrCode();
  377. $small_name = "goods_small_code_url_" . $goods_id;
  378. $data['scene'] = 'id=' . $goods_id;
  379. $data['page'] = "packageA/detail_v2/detail_v2";
  380. $pay_code = $small_qr->getSmallQrCode($small_name, $data);
  381. if ($pay_code['code'] == 0) {
  382. $goodsModel = new GoodsSmallUrl();
  383. $data = [
  384. 'uniacid' => \YunShop::app()->uniacid,
  385. 'goods_id' => $goods_id,
  386. 'collect_small_url' => $pay_code['file_path'],
  387. 'created_at' => time(),
  388. 'updated_at' => time()
  389. ];
  390. $goodsModel->fill($data);
  391. if ($goodsModel->save()) {
  392. return $this->message("小程序二维码已生成");
  393. } else {
  394. return $this->message("小程序二维码生成失败", '', 'error');
  395. }
  396. } else {
  397. return $this->message($pay_code['message'], '', 'error');
  398. }
  399. }
  400. public function displayorder()
  401. {
  402. $id = request()->id;
  403. $value = request()->value;
  404. if (empty($id)) {
  405. return $this->errorJson('排序失败,商品ID不能为空');
  406. }
  407. $goods = \app\common\models\Goods::find($id);
  408. $goods->display_order = $value;
  409. if ($goods->save()) {
  410. return $this->successJson('排序成功');
  411. } else {
  412. return $this->errorJson('排序失败');
  413. }
  414. // return $this->message('商品排序成功', Url::absoluteWeb($this->success_url));
  415. //$this->error($goods);
  416. }
  417. public function change()
  418. {
  419. //dd(\YunShop::request());
  420. $id = request()->id;
  421. $field = request()->type;
  422. $goods = \app\common\models\Goods::find($id);
  423. $goods->$field = request()->value;
  424. if ($goods->save()) {
  425. \Artisan::call('config:cache');
  426. \Cache::flush();
  427. return $this->successJson('修改成功');
  428. } else {
  429. return $this->errorJson('修改失败');
  430. }
  431. //$this->error($goods);
  432. }
  433. /**
  434. * 商品上下架权限需要独立控制 Yi_190517
  435. */
  436. public function setPutaway()
  437. {
  438. return $this->setProperty();
  439. }
  440. public function setProperty()
  441. {
  442. $id = request()->id;
  443. $field = request()->type;
  444. $data = request()->data; //(request()->data == 1 ? '0' : '1');
  445. $goods = \app\common\models\Goods::find($id);
  446. $goods->$field = $data;
  447. //dd($goods);
  448. $goods->save();
  449. Cache::flush();
  450. echo json_encode(["data" => $data, "result" => 1]);
  451. }
  452. //批量上下架
  453. public function batchSetProperty()
  454. {
  455. $ids = request()->ids;
  456. $data = request()->data;
  457. foreach ($ids as $id) {
  458. $goods = \app\common\models\Goods::find($id);
  459. $goods->status = $data;
  460. $goods->save();
  461. }
  462. echo json_encode(["data" => $data, "result" => 1]);
  463. }
  464. public function destroy()
  465. {
  466. $id = request()->id;
  467. $goods = Goods::destroy($id);
  468. return $this->successJson('商品删除成功');
  469. }
  470. public function batchDestroy()
  471. {
  472. $ids = request()->ids;
  473. foreach ($ids as $id) {
  474. $goods = Goods::destroy($id);
  475. }
  476. echo json_encode([
  477. "result" => $goods,
  478. ]);
  479. }
  480. public function batchService()
  481. {
  482. $ids = request()->ids;
  483. $service_form = request()->service_form;
  484. if (empty($ids)) {
  485. return $this->errorJson('请选择商品');
  486. }
  487. DB::transaction(function () use ($service_form, $ids) {
  488. foreach ($ids as $gid) {
  489. $goods_service = ServiceProvide::uniacid()->where('goods_id', $gid)->first();
  490. if (!$goods_service) {
  491. $goods_service = new ServiceProvide();
  492. $goods_service->uniacid = \YunShop::app()->uniacid;
  493. $goods_service->goods_id = $gid;
  494. }
  495. $goods_service->is_automatic = $service_form['is_automatic'];
  496. $goods_service->time_type = $service_form['time_type'];
  497. $goods_service->on_shelf_time = $service_form['on_shelf_time'];
  498. $goods_service->lower_shelf_time = $service_form['lower_shelf_time'];
  499. $goods_service->loop_date_start = $service_form['loop_date_start'];
  500. $goods_service->loop_date_end = $service_form['loop_date_end'];
  501. $goods_service->loop_time_up = $service_form['loop_time_up'];
  502. $goods_service->loop_time_down = $service_form['loop_time_down'];
  503. $goods_service->auth_refresh_stock = $service_form['auth_refresh_stock'];
  504. $goods_service->original_stock = $service_form['original_stock'];
  505. $goods_service->save();
  506. }
  507. });
  508. return $this->successJson('编辑成功');
  509. }
  510. /**
  511. * 获取参数模板
  512. */
  513. public function getParamTpl()
  514. {
  515. $tag = random(32);
  516. return view('goods.tpl.param', [
  517. 'tag' => $tag,
  518. ])->render();
  519. }
  520. /**
  521. * 获取规格模板
  522. */
  523. public function getSpecTpl()
  524. {
  525. $spec = [
  526. "id" => random(32),
  527. "title" => '',
  528. 'items' => [],
  529. ];
  530. return view('goods/tpl/spec', ['spec' => $spec]);
  531. }
  532. /**
  533. * 获取规格项模板
  534. */
  535. public function getSpecItemTpl()
  536. {
  537. $goodsModel = Goods::find($this->goods_id);
  538. $spec = array(
  539. "id" => \YunShop::request()->specid,
  540. );
  541. $specitem = array(
  542. "id" => random(32),
  543. "title" => \YunShop::request()->title,
  544. "show" => 1,
  545. 'virtual' => '',
  546. 'title2' => '',
  547. 'thumb' => '',
  548. );
  549. return view('goods/tpl/spec_item', [
  550. 'spec' => $spec,
  551. 'goods' => $goodsModel,
  552. 'specitem' => $specitem,
  553. ])->render();
  554. }
  555. /**
  556. * 获取搜索商品
  557. * @return html
  558. */
  559. public function getSearchGoods()
  560. {
  561. $keyword = \YunShop::request()->keyword;
  562. $goods = \app\common\models\Goods::select('id', 'title', 'thumb')
  563. ->where('title', 'like', '%' . $keyword . '%')
  564. ->where('status', 1)
  565. ->whereInPluginIds()
  566. ->get();
  567. if (!$goods->isEmpty()) {
  568. $goods = set_medias($goods->toArray(), array('thumb', 'share_icon'));
  569. }
  570. return view('goods.query', [
  571. 'goods' => $goods,
  572. 'exchange' => \YunShop::request()->exchange,
  573. ])->render();
  574. }
  575. public function getSearchGoodsJson()
  576. {
  577. $except_supplier = request()->except_supplier;
  578. $keyword = request()->keyword;
  579. $query = \app\common\models\Goods::select('id', 'title', 'thumb')
  580. ->where('title', 'like', '%' . $keyword . '%')
  581. ->where('status', 1);
  582. if ($except_supplier) {
  583. $except_plugin_id = [92,101];
  584. $query->whereNotIn('plugin_id', $except_plugin_id);
  585. } else {
  586. $query->whereInPluginIds();
  587. }
  588. $goods = $query->paginate(20);
  589. $goods->map(function ($q) {
  590. return $q->thumb_url = yz_tomedia($q->thumb);
  591. });
  592. return $this->successJson('ok', [
  593. 'goods' => $goods,
  594. ]);
  595. }
  596. public function getSearchGoodsLevel()
  597. {
  598. $keyword = \YunShop::request()->keyword;
  599. $model = \app\common\models\Goods::select('id', 'title', 'thumb')
  600. ->where('title', 'like', '%' . $keyword . '%')
  601. ->where('status', 1);
  602. $goods = $model->get();
  603. if (!$goods->isEmpty()) {
  604. $goods = set_medias($goods->toArray(), array('thumb', 'share_icon'));
  605. }
  606. return view('goods.query', [
  607. 'goods' => $goods,
  608. 'exchange' => \YunShop::request()->exchange,
  609. ])->render();
  610. }
  611. /**
  612. * 获取搜索门店
  613. * @return html
  614. */
  615. public function getSearchStore()
  616. {
  617. $keyword = \YunShop::request()->keyword;
  618. $store = StoreCashier::getStoreByName($keyword);
  619. return view('goods.store', [
  620. 'store' => $store
  621. ])->render();
  622. }
  623. /**
  624. * 获取搜索门店返回数组
  625. * @return string
  626. * @throws \Throwable
  627. */
  628. public function getSearchStoreJson()
  629. {
  630. $keyword = request()->keyword;
  631. $store = StoreCashier::getStoreByName($keyword);
  632. return $this->successJson('ok', $store);
  633. }
  634. /**
  635. * 获取搜索酒店
  636. * @return html
  637. */
  638. public function getSearchHotel()
  639. {
  640. if (app('plugins')->isEnabled('hotel')) {
  641. $keyword = \YunShop::request()->keyword;
  642. $hotel = Hotel::getHotelByName($keyword);
  643. return view('goods.hotel', [
  644. 'hotel' => $hotel
  645. ])->render();
  646. }
  647. return;
  648. }
  649. /**
  650. * 获取搜索酒店返回数组
  651. * @return string
  652. * @throws \Throwable
  653. */
  654. public function getSearchHotelJson()
  655. {
  656. if (app('plugins')->isEnabled('hotel')) {
  657. $keyword = request()->keyword;
  658. $hotel = Hotel::getHotelByName($keyword);
  659. return $this->successJson('ok', $hotel);
  660. }
  661. return;
  662. }
  663. /**
  664. * 获取搜索会员标签返回数组
  665. * @return string
  666. * @throws \Throwable
  667. */
  668. public function getSearchMemberTagsJson()
  669. {
  670. if (app('plugins')->isEnabled('member-tags')) {
  671. $keyword = request()->keyword;
  672. $tags = MemberTagsModel::GetTagsByTitle($keyword)->get(['id','title'])->toArray();
  673. return $this->successJson('ok', $tags);
  674. }
  675. return;
  676. }
  677. /**
  678. * 获取搜索商品by经销商
  679. * @return html
  680. */
  681. public function getSearchGoodsByDividend()
  682. {
  683. $keyword = \YunShop::request()->keyword;
  684. $goods = Goods::getGoodsByName($keyword);
  685. if (!$goods->isEmpty()) {
  686. $goods = set_medias($goods->toArray(), array('thumb', 'share_icon'));
  687. }
  688. return view('goods.dividend_goods_query', [
  689. 'goods' => $goods
  690. ])->render();
  691. }
  692. public function getSearchGoodsByDividendLevel()
  693. {
  694. $keyword = \YunShop::request()->keyword;
  695. $goods = \app\common\models\Goods::getGoodsLevelByName($keyword);
  696. if (!$goods->isEmpty()) {
  697. $goods = set_medias($goods->toArray(), array('thumb', 'share_icon'));
  698. }
  699. return view('goods.dividend_goods_query', [
  700. 'goods' => $goods
  701. ])->render();
  702. }
  703. public function getMyLinkGoods()
  704. {
  705. if (!\YunShop::request()->kw) {
  706. $postData = file_get_contents('php://input', true);
  707. $obj = json_decode($postData);
  708. \YunShop::request()->kw = $obj->kw;
  709. //dd($obj->kw);
  710. }
  711. if (\YunShop::request()->kw) {
  712. $goods = \app\common\models\Goods::getGoodsByName(\YunShop::request()->kw);
  713. if (!$goods->isEmpty()) {
  714. $goods = set_medias($goods->toArray(), array('thumb', 'share_icon'));
  715. }
  716. $goods = collect($goods)->map(function ($item) {
  717. $url = yzAppFullUrl('goods/' . $item['id']);
  718. // if (app('plugins')->isEnabled('store-cashier')) {
  719. // $store_goods = new \Yunshop\StoreCashier\common\models\StoreGoods();
  720. // $store_id = $store_goods->where('goods_id', $item['id'])->value('store_id');
  721. // if ($store_id) {
  722. // $url = yzAppFullUrl("goods/{$item['id']}/o2o/{$store_id}");
  723. // }
  724. // }
  725. // $is_course = (new VideoDemandCourseGoods())->isCourse($item['id']);
  726. // if ($is_course) {
  727. // $url = yzAppFullUrl("member/coursedetail/{$item['id']}");
  728. // }
  729. return array_add($item, 'url', $url);
  730. });
  731. echo json_encode($goods);
  732. exit;
  733. }
  734. }
  735. public function getSmallMyLinkGoods()
  736. {
  737. if (!\YunShop::request()->kw) {
  738. $postData = file_get_contents('php://input', true);
  739. $obj = json_decode($postData);
  740. \YunShop::request()->kw = $obj->kw;
  741. //dd($obj->kw);
  742. }
  743. if (\YunShop::request()->kw) {
  744. $goods = \app\common\models\Goods::getGoodsByName(\YunShop::request()->kw);
  745. if (!$goods->isEmpty()) {
  746. $goods = set_medias($goods->toArray(), array('thumb', 'share_icon'));
  747. }
  748. $goods = collect($goods)->map(function ($item) {
  749. $url = '/packageA/detail_v2/detail_v2?id=' . $item['id'];
  750. return array_add($item, 'url', $url);
  751. });
  752. echo json_encode($goods);
  753. exit;
  754. }
  755. }
  756. public function SearchOrder()
  757. {//获取商品名称
  758. $keyword = request()->keyword;
  759. $pluginId = request()->plugin_id;
  760. if (empty($pluginId)) {
  761. $pluginId = 0;
  762. }
  763. $goods = Goods::getSearchOrder($keyword, $pluginId);
  764. return view('goods.query', [
  765. 'goods' => $goods->toArray(),
  766. ])->render();
  767. }
  768. /**
  769. * 商品批量导入
  770. */
  771. public function import()
  772. {
  773. return view('goods.import')->render();
  774. }
  775. /**
  776. * 解压zip文件
  777. * @string $file 需要解压的文件的绝对路径
  778. * @string $destination 解压文件的绝对路径
  779. * @return bool
  780. *
  781. */
  782. private function unZipFile($file, $destination)
  783. {
  784. $zip = new \ZipArchive(); // 实例化对象
  785. if ($zip->open($file) !== true) { //打开zip文档
  786. return false; //无法打开zip文件
  787. }
  788. $zip->extractTo($destination);//将压缩文件解压到指定的目录下
  789. $zip->close(); //关闭zip文档
  790. return true;
  791. }
  792. //ajax 异步上传文件
  793. public function updateZip()
  794. {
  795. $file = request()->file('file');
  796. if (!$file) {
  797. return $this->errorJson('请传入正确参数.');
  798. }
  799. if ($file->isValid()) {
  800. // 获取文件相关信息
  801. $originalName = $file->getClientOriginalName(); // 文件原名
  802. $realPath = $file->getRealPath(); //临时文件的绝对路径
  803. $ext = $file->getClientOriginalExtension();
  804. $newOriginalName = md5($originalName . str_random(6)) . '.' . $ext;
  805. \Storage::disk('image')->put($newOriginalName, file_get_contents($realPath));
  806. if (config('app.framework') == 'platform') {
  807. $attachment = base_path() . '/static/upload/';
  808. } else {
  809. $attachment = $_SERVER['DOCUMENT_ROOT'] . '/attachment/image/';
  810. }
  811. if (is_dir($attachment)) {
  812. mkdir($attachment);
  813. }
  814. if ($this->unZipFile($attachment . $newOriginalName, $attachment) == true) {
  815. return $this->successJson('上传成功');
  816. } else {
  817. return $this->errorJson('解压失败');
  818. }
  819. }
  820. }
  821. /**
  822. * excel 商品导入
  823. * @return \Illuminate\Http\JsonResponse
  824. */
  825. public function a()
  826. {
  827. if (config('app.framework') == 'platform') {
  828. $attachment = 'static/upload/';
  829. } else {
  830. $attachment = 'attachment/';
  831. }
  832. $scheme = empty($_SERVER['HTTPS']) ? 'http://' : 'https://';
  833. $url = $scheme . $_SERVER['HTTP_HOST'];
  834. $url = $url . '/' . $attachment . 'image/';
  835. $data = request()->input('data');
  836. $i = 0;
  837. $goodsName = array_column($data, '商品名称');
  838. foreach ($data as $key => $value) {
  839. $goodsData[$i] = [
  840. 'uniacid' => $value['公众号'] ?: 0,
  841. 'display_order' => $value['排序'],
  842. 'title' => $value['商品名称'],
  843. 'brand_id' => $this->getBrandId(['uniacid' => $value['公众号'], 'brand' => $value['品牌']]),
  844. 'type' => $value['商品类型'],
  845. 'sku' => $value['商品单位'],
  846. 'is_recommand' => $value['推荐'],
  847. 'is_new' => $value['新上'],
  848. 'is_hot' => $value['热卖'],
  849. 'is_discount' => $value['促销'],
  850. 'thumb' => $url . $value['商品图片'],
  851. 'goods_sn' => $value['商品编号'],
  852. 'product_sn' => $value['商品条码'],
  853. 'price' => $value['商品现价'],
  854. 'market_price' => $value['商品原价'],
  855. 'cost_price' => $value['成本价'],
  856. 'weight' => $value['重量'],
  857. 'stock' => $value['库存'],
  858. 'virtual_sales' => $value['虚拟销量'],
  859. 'reduce_stock_method' => $value['拍下减库存'],
  860. 'no_refund' => $value['不可退货退款'],
  861. 'status' => $value['是否上架'],
  862. 'content' => $value['商品描述']
  863. ];
  864. $goodsCategorys[$value['商品名称']] = [
  865. 'title' => $value['商品名称'],
  866. 'category1' => $value['商品分类一'],
  867. 'category2' => $value['商品分类二'],
  868. ];
  869. $i++;
  870. }
  871. unset($data);
  872. unset($i);
  873. $result = Goods::insert($goodsData);
  874. unset($goodsData);
  875. $goodsId = Goods::select('id', 'uniacid', 'title')->whereIn('title', $goodsName)->get()->toArray();
  876. unset($goodsName);
  877. foreach ($goodsId as $k => $v) {
  878. if (isset($goodsCategorys[$v['title']])) {
  879. $goodsId[$k] = array_merge($v, $goodsCategorys[$v['title']]);
  880. }
  881. unset($k);
  882. }
  883. unset($v);
  884. $goodsCategory = array();
  885. foreach ($goodsId as $a => $b) {
  886. $temp = $this->getCategoryId([
  887. 'uniacid' => $b['uniacid'],
  888. 'category_name_1' => $b['category1'],
  889. 'category_name_2' => $b['category2'],
  890. ]);
  891. $goodsCategory[$a] = [
  892. 'goods_id' => $b['id'],
  893. 'category_id' => $temp['category_id'],
  894. 'category_ids' => $temp['category_ids'],
  895. 'created_at' => $_SERVER['REQUEST_TIME'],
  896. 'updated_at' => $_SERVER['REQUEST_TIME'],
  897. ];
  898. unset($temp);
  899. unset($a);
  900. }
  901. unset($b);
  902. $result = GoodsCategory::insert($goodsCategory);
  903. if ($result) {
  904. return $this->successJson('导入成功');
  905. }
  906. }
  907. /**
  908. * //todo 通过数组下标查找,没有就添加,如果上传的excel里分类较多,需优化
  909. * @param $level
  910. * @param $uniacid
  911. * @param $name
  912. * @return mixed
  913. */
  914. private function getCategoryId($array)
  915. {
  916. if ($array['category_name_1'] == null and $array['category_name_2'] == null) {
  917. return [
  918. 'category_id' => 0,
  919. 'category_ids' => '',
  920. ];
  921. }
  922. if (is_null($this->list)) {
  923. $this->list = array_column(Category::select('id', 'name', 'uniacid', 'level')->where('plugin_id', 0)->get()->toArray(), null, 'name');
  924. }
  925. $result = array();
  926. if ($this->list[$array['category_name_1']]) {
  927. if ($this->list[$array['category_name_1']]['uniacid'] == $array['uniacid']) {
  928. $result['category_id_1'] = $this->list[$array['category_name_1']]['id'];
  929. } else {
  930. $result['category_id_1'] = $this->addCategory([
  931. 'uniacid' => $array['uniacid'],
  932. 'name' => $array['category_name_1'],
  933. 'level' => 1,
  934. 'plugin_id' => 0,
  935. 'is_home' => 1,
  936. 'parent_id' => 0
  937. ]);
  938. }
  939. } else {
  940. $result['category_id_1'] = $this->addCategory([
  941. 'uniacid' => $array['uniacid'],
  942. 'name' => $array['category_name_1'],
  943. 'level' => 1,
  944. 'plugin_id' => 0,
  945. 'is_home' => 1,
  946. 'parent_id' => 0
  947. ]);
  948. }
  949. //商品二级分类
  950. if ($this->list[$array['category_name_2']]) {
  951. if ($this->list[$array['category_name_2']]['uniacid'] == $array['uniacid']) {
  952. $result['category_id'] = $this->list[$array['category_name_2']]['id'];
  953. $result['category_ids'] = $result['category_id_1'] . ',' . $result['category_id'];
  954. } else {
  955. $result['category_id'] = $this->addCategory([
  956. 'uniacid' => $array['uniacid'],
  957. 'name' => $array['category_name_2'],
  958. 'level' => 2,
  959. 'plugin_id' => 0,
  960. 'is_home' => 1,
  961. 'parent_id' => $result['category_id_1']
  962. ]);
  963. $result['category_ids'] = $result['category_id_1'] . ',' . $result['category_id'];
  964. }
  965. } else {
  966. $result['category_id'] = $this->addCategory([
  967. 'uniacid' => $array['uniacid'],
  968. 'name' => $array['category_name_2'],
  969. 'level' => 2,
  970. 'plugin_id' => 0,
  971. 'is_home' => 1,
  972. 'parent_id' => $result['category_id_1']
  973. ]);
  974. $result['category_ids'] = $result['category_id_1'] . ',' . $result['category_id'];
  975. }
  976. if (!$result['category_ids']) {
  977. $result['category_ids'] = $result['category_id'];
  978. }
  979. unset($result['category_id_1']);
  980. return $result;
  981. }
  982. /**
  983. * 添加分类表
  984. * @param $array
  985. * @return int
  986. */
  987. private function addCategory($array)
  988. {
  989. $id = Category::insertGetId($array);
  990. $this->list = array_column(Category::select('id', 'name', 'uniacid', 'level')->where('plugin_id', 0)->get()->toArray(), null, 'name');
  991. return $id;
  992. }
  993. /**
  994. * 通过数组下标获取brand_id
  995. * @param $array
  996. * @return mixed
  997. */
  998. private function getBrandId($array)
  999. {
  1000. if (is_null($this->brand)) {
  1001. $this->brand = array_column(Brand::get()->toArray(), null, 'name');
  1002. }
  1003. if ($this->brand[$array['brand']]) {
  1004. if ($this->brand[$array['brand']]['uniacid'] == $array['uniacid']) {
  1005. return $this->brand[$array['brand']]['id'];
  1006. } else {
  1007. //todo 添加品牌
  1008. return $this->addBrand([
  1009. 'uniacid' => $array['uniacid'],
  1010. 'name' => $array['brand'],
  1011. 'alias' => '批量添加',
  1012. 'logo' => '',
  1013. 'desc' => '',
  1014. 'created_at' => $_SERVER['REQUEST_TIME'],
  1015. 'updated_at' => $_SERVER['REQUEST_TIME'],
  1016. ]);
  1017. }
  1018. } else {
  1019. return $this->addBrand([
  1020. 'uniacid' => $array['uniacid'],
  1021. 'name' => $array['brand'],
  1022. 'alias' => '',
  1023. 'logo' => '',
  1024. 'desc' => '',
  1025. 'created_at' => $_SERVER['REQUEST_TIME'],
  1026. 'updated_at' => $_SERVER['REQUEST_TIME'],
  1027. ]);
  1028. }
  1029. }
  1030. /**
  1031. * 添加品牌
  1032. * @param $array
  1033. * @return int
  1034. */
  1035. private function addBrand($array)
  1036. {
  1037. $id = Brand::insertGetId($array);
  1038. $this->brand = array_column(Brand::get()->toArray(), null, 'name');
  1039. return $id;
  1040. }
  1041. /**
  1042. * demo 下载
  1043. */
  1044. public function excelImport()
  1045. {
  1046. $exportData['0'] = ["公众号", "排序", '商品名称', '商品分类一', '商品分类二', '商品品牌', '商品类型', '商品单位',
  1047. '商品属性', '商品图片', '商品编号', '商品条码', '商品现价', '商品原价', '成本价', '虚拟销量', '减库存方式', '不可退换货',
  1048. '是否上架', '商品描述', '推荐', '新上', '热卖', '促销', '商品图片'
  1049. ];
  1050. \Excel::create('商品批量导入模板', function ($excel) use ($exportData) {
  1051. $excel->setTitle('Office 2005 XLSX Document');
  1052. $excel->setCreator('芸众商城');
  1053. $excel->setLastModifiedBy("芸众商城");
  1054. $excel->setSubject("Office 2005 XLSX Test Document");
  1055. $excel->setDescription("Test document for Office 2005 XLSX, generated using PHP classes.");
  1056. $excel->setKeywords("office 2005 openxml php");
  1057. $excel->setCategory("report file");
  1058. $excel->sheet('info', function ($sheet) use ($exportData) {
  1059. $sheet->rows($exportData);
  1060. });
  1061. })->export('xls');
  1062. }
  1063. }