| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203 |
- <?php
- /**
- * Created by PhpStorm.
- * Author: 芸众商城 www.yunzshop.com
- * Date: 2017/2/22
- * Time: 下午1:51
- */
- namespace app\backend\modules\goods\controllers;
- use app\backend\modules\goods\models\Brand;
- use app\backend\modules\goods\models\Category;
- use app\backend\modules\goods\models\Goods;
- use app\backend\modules\goods\models\GoodsOption;
- use app\backend\modules\goods\models\GoodsSpecItem;
- use app\backend\modules\goods\models\Sale;
- use app\backend\modules\goods\services\CopyGoodsService;
- use app\backend\modules\goods\services\CreateGoodsService;
- use app\backend\modules\goods\services\EditGoodsService;
- use app\backend\modules\goods\services\GoodsOptionService;
- use app\backend\modules\goods\services\GoodsService;
- use app\backend\modules\uploadVerificate\UploadVerificationBaseController;
- use app\common\components\BaseController;
- use app\backend\modules\goods\services\CategoryService;
- use app\backend\modules\goods\models\GoodsParam;
- use app\backend\modules\goods\models\GoodsSpec;
- use app\common\components\Widget;
- use app\common\helpers\Cache;
- use app\common\helpers\PaginationHelper;
- use app\common\helpers\Url;
- use app\common\models\GoodsCategory;
- use app\common\models\GoodsSmallUrl;
- use app\common\services\SmallQrCode;
- use Illuminate\Database\Eloquent\Collection;
- use Illuminate\Support\Facades\DB;
- use Setting;
- use app\common\services\goods\VideoDemandCourseGoods;
- use app\common\models\Store as StoreCashier;
- use Yunshop\Designer\models\Store;
- use Yunshop\GoodsSource\common\models\GoodsSource;
- use Yunshop\Hotel\common\models\Hotel;
- use Yunshop\LeaseToy\models\LeaseOrderModel;
- use Yunshop\LeaseToy\models\LeaseToyGoodsModel;
- use Yunshop\MemberTags\Common\models\MemberTagsModel;
- use Yunshop\VideoDemand\models\CourseGoodsModel;
- use app\common\helpers\ImageHelper;
- use app\common\models\goods\GoodsService as ServiceProvide;
- class GoodsController extends UploadVerificationBaseController
- {
- protected $goods_id = null;
- protected $shopset;
- protected $shoppay;
- private $list;
- private $brand;
- protected $lang = null;
- protected $success_url = 'goods.goods.index';
- protected $widget_url = 'goods.goods.widget-column';
- public function preAction()
- {
- parent::preAction(); // TODO: Change the autogenerated stub
- $this->lang = array(
- "shopname" => "商品名称",
- "mainimg" => "商品图片",
- "limittime" => "限时卖时间",
- "shopnumber" => "商品编号",
- "shopprice" => "商品价格",
- "putaway" => "上架",
- "soldout" => "下架",
- "good" => "商品",
- "price" => "价格",
- 'yes_stock' => '出售中',
- 'no_stock' => '售罄',
- "repertory" => "库存",
- "copyshop" => "复制商品",
- "isputaway" => "是否上架",
- "shopdesc" => "商品描述",
- "shopinfo" => "商品详情",
- 'shopoption' => "商品规格",
- 'marketprice' => "销售价格",
- 'shopsubmit' => "发布商品"
- );
- $this->goods_id = (int)\YunShop::request()->id;
- $this->shopset = Setting::get('shop.category');
- }
- public function index()
- {
- $producerId = intval(request()->producer_id);
- return view('goods.index', [
- 'data' => json_encode($this->goodsListData()),
- 'producerId' => json_encode($producerId),
- ]);
- }
- public function goodsSearch()
- {
- $producerId = intval(request()->producer_id);
- //课程商品id集合
- $courseGoods_ids = (new VideoDemandCourseGoods())->courseGoodsIds();
- $requestSearch = request()->search;
- $page = request()->page;
- if ($requestSearch) {
- $requestSearch = array_filter($requestSearch, function ($item) {
- return $item !== '';// && $item !== 0;
- });
- $categorySearch = array_filter(request()->category, function ($item) {
- if (is_array($item)) {
- return !empty($item[0]);
- }
- return !empty($item);
- });
- if ($categorySearch) {
- $requestSearch['category'] = $categorySearch;
- }
- }
- $per_size = request()->input('per_size')?request()->input('per_size'):20;
- $tab_state = request()->input('tab_state');
- //todo blank 这个插件的代码怎么加到这里???
- if ($producerId && app('plugins')->isEnabled('producer')) {
- $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'])
- ->whereHas('hasOneProducerGoods', function ($hasOneProducerGoods) use ($producerId) {
- $hasOneProducerGoods->where('producer_id', $producerId);
- });
- } else {
- $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']);
- }
- //排序
- $order_by = request()->input('order_by');
- if ($order_by) {
- foreach ($order_by as $by_key => $by_value) {
- if ($by_value) {
- $goodsBuild->orderBy('yz_goods.'.$by_key, $by_value);
- }
- }
- } else {
- $goodsBuild->orderBy('yz_goods.display_order', 'desc');
- }
- $list = $goodsBuild->orderBy('yz_goods.id', 'desc')->state($tab_state)->paginate($per_size);
- foreach ($list as $key => $item) {
- $list[$key]['thumb'] = yz_tomedia($item->thumb);
- if (in_array($item['id'], $courseGoods_ids)) {
- $list[$key]['link'] = yzAppFullUrl('member/coursedetail/' . $item['id']);
- } else {
- $list[$key]['link'] = yzAppFullUrl('goods/' . $item['id']);
- }
- if ($item->hasOneSmallCodeUrl->collect_small_url) {
- $list[$key]['small_link'] = $item->hasOneSmallCodeUrl->collect_small_url;
- } else {
- $list[$key]['small_link'] = "";
- }
- $cost_ratio = 0;
- if($item['cost_price']){
- $basic = bcsub($item['price'],$item['cost_price'],2);
- $cost_ratio = bcdiv($basic,$item['cost_price'],4)*100;
- }
- $list[$key]['cost_ratio'] = $cost_ratio."%";
- }
- $list = $list->toArray();
- $list['lower_shelf'] = Goods::Search($requestSearch)->pluginIdShow()->state(0)->count();
- $list['put_shelf'] = Goods::Search($requestSearch)->pluginIdShow()->state(1)->count();
- $list['all_goods'] = Goods::Search($requestSearch)->pluginIdShow()->state()->count();
- if ($list) {
- return $this->successJson('成功', $list);
- } else {
- return $this->errorJson('找不到数据');
- }
- }
- protected function goodsListData()
- {
- $producerId = intval(request()->producer_id);
- //课程商品id集合
- $courseGoods_ids = (new VideoDemandCourseGoods())->courseGoodsIds();
- //增加商品属性搜索
- $product_attr_list = [
- 'is_new' => '新品',
- 'is_hot' => '热卖',
- 'is_recommand' => '推荐',
- 'is_discount' => '促销',
- ];
- //这里一次查出来太慢改成接口查询
- // $brands = Brand::getBrands()->getQuery()->select(['id','name'])->get()->toArray();
- $requestSearch = \YunShop::request()->search;
- if ($requestSearch) {
- $requestSearch = array_filter($requestSearch, function ($item) {
- return $item !== '';// && $item !== 0;
- });
- $categorySearch = array_filter(\YunShop::request()->category, function ($item) {
- if (is_array($item)) {
- return !empty($item[0]);
- }
- return !empty($item);
- });
- if ($categorySearch) {
- $requestSearch['category'] = $categorySearch;
- }
- }
- $category = Category::parentGetCategorys()->get();
- if ($producerId && app('plugins')->isEnabled('producer')) {
- $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()
- ->whereHas('hasOneProducerGoods', function ($hasOneProducerGoods) use ($producerId) {
- $hasOneProducerGoods->where('producer_id', $producerId);
- })
- ->orderBy('display_order', 'desc')
- ->orderBy('yz_goods.id', 'desc')
- ->state(1)
- ->paginate(20);
- } else {
- $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()
- ->state(1)
- ->orderBy('display_order', 'desc')
- ->orderBy('yz_goods.id', 'desc')->paginate(20);
- }
- foreach ($list as $key => $item) {
- $list[$key]['thumb'] = yz_tomedia($item->thumb);
- if (in_array($item['id'], $courseGoods_ids)) {
- $list[$key]['link'] = yzAppFullUrl('member/coursedetail/' . $item['id']);
- } else {
- $list[$key]['link'] = yzAppFullUrl('goods/' . $item['id']);
- }
- if ($item->hasOneSmallCodeUrl->collect_small_url) {
- $list[$key]['small_link'] = $item->hasOneSmallCodeUrl->collect_small_url;
- } else {
- $list[$key]['small_link'] = "";
- }
- $cost_ratio = 0;
- if($item['cost_price']){
- $basic = bcsub($item['price'],$item['cost_price'],2);
- $cost_ratio = bcdiv($basic,$item['cost_price'],4)*100;
- }
- $list[$key]['cost_ratio'] = $cost_ratio."%";
- }
- $source_status = false;
- $source_is_open = \Setting::get('plugin.goods_source.is_open');
- if (app('plugins')->isEnabled('goods-source')&&(is_null($source_is_open) || $source_is_open)) {
- $source_status = true;
- }
- if ($source_status) {
- $source_list = GoodsSource::uniacid()->select(['id','source_name'])->get();
- } else {
- $source_list = New Collection();
- }
- $data = [
- 'list' => $list,
- 'courseGoods_ids' => $courseGoods_ids,
- 'requestSearch' => $requestSearch,
- 'category' => $category,
- 'cat_level' => $this->shopset['cat_level'],
- 'lang' => $this->lang,
- 'product_attr_list' => $product_attr_list,
- 'yz_url' => 'yzWebUrl',
- 'product_attr' => $requestSearch['product_attr'],
- 'edit_url' => yzWebFullUrl('goods.goods.edit'),
- 'delete_url' => yzWebFullUrl('goods.goods.destroy'),
- 'sort_url' => yzWebFullUrl('goods.goods.displayorder'),
- 'copy_url' => yzWebFullUrl('goods.goods.copy'),
- 'is_source_open' => $source_status ? 1 : 0,
- 'source_list' => $source_list,
- ];
- $data['lower_shelf'] = Goods::Search($requestSearch)->pluginIdShow()->state(0)->count();
- $data['put_shelf'] = Goods::Search($requestSearch)->pluginIdShow()->state(1)->count();
- $data['all_goods'] = Goods::Search($requestSearch)->pluginIdShow()->state()->count();
- return $data;
- }
- /**
- * 商品列表页数据
- */
- public function goodsList()
- {
- return $this->successJson('成功', $this->goodsListData());
- }
- public function copy()
- {
- $id = intval(\YunShop::request()->id);
- if (!$id) {
- $this->error('请传入正确参数.');
- }
- $result = CopyGoodsService::copyGoods($id);
- if (!$result) {
- $this->error('商品不存在.');
- }
- return $this->message('商品复制成功', Url::absoluteWeb($this->success_url));
- }
- public function create()
- {
- if (request()->ajax()) {
- $request = Request();
- $goods_service = new CreateGoodsService($request);
- $result = $goods_service->create();
- if ($result['status'] == 1) {
- return $this->successJson('商品创建成功');
- } else {
- return $this->errorJson($result['msg']);
- // !session()->has('flash_notification.message') && $this->error('商品修改失败');
- }
- }
- return view('goods.vue-goods', [
- 'store_url' => yzWebFullUrl(request()->input('route')),
- 'widget_url' => yzWebFullUrl($this->widget_url),
- 'success_url' => yzWebFullUrl($this->success_url),
- 'ckt_url' => Url::absoluteWeb('plugin.decorate.admin.page.get-list').'&i='.\YunShop::app()->uniacid.'#/picture_design_scene',
- 'is_decorate' => app('plugins')->isEnabled('decorate'),
- ])->render();
- }
- public function edit()
- {
- if (request()->ajax()) {
- $goods_service = new EditGoodsService(request()->input('id'), \YunShop::request());
- $result = $goods_service->edit();
- if ($result['status'] == 1) {
- return $this->successJson('商品修改成功');
- }
- return $this->errorJson($result['msg']);
- }
- return view('goods.vue-goods', [
- 'store_url' => yzWebFullUrl(request()->input('route'),['id'=>request()->input('id')]),
- 'success_url' => yzWebFullUrl($this->success_url),
- 'goods_id' => request()->input('id'),
- 'widget_url' => yzWebFullUrl($this->widget_url,['id'=> request()->input('id')]),
- 'ckt_url' => Url::absoluteWeb('plugin.decorate.admin.page.get-list').'&i='.\YunShop::app()->uniacid.'#/picture_design_scene',
- 'is_decorate' => app('plugins')->isEnabled('decorate'),
- ])->render();
- }
- //商品编辑挂件获取
- public function widgetColumn()
- {
- $data = app('GoodsWidgetContainer')->make('Manager')->handle();
- return $this->successJson('widgetColumn', $data);
- }
- public function oldPage()
- {
- //todo 所有操作去service里进行,供应商共用此方法。
- $request = Request();
- $goods_service = new EditGoodsService($request->id, \YunShop::request());
- $result = $goods_service->oldedit();
- if ($goods_service->goods_model->content) {
- $goods_service->goods_model->content = changeUmImgPath($goods_service->goods_model->content);
- }
- if ($result['status'] == 1) {
- Cache::flush();
- return $this->message('商品修改成功', Url::absoluteWeb($this->success_url));
- } else if ($result['status'] == -1) {
- if (isset($result['msg'])) {
- $this->error($result['msg']);
- }
- !session()->has('flash_notification.message') && $this->error('商品修改失败');
- }
- $list = collect($goods_service->goods_model)->toArray();
- if (!$list['id']) {
- return $this->message('商品不存在或已删除', '', 'error');
- }
- return view('goods.goods', [
- 'goods' => $goods_service->goods_model,
- 'lang' => $this->lang,
- 'goods_video' => collect($goods_service->goods_model->hasOneGoodsVideo)->toArray(),
- 'params' => collect($goods_service->goods_model->hasManyParams)->toArray(),
- 'allspecs' => collect($goods_service->goods_model->hasManySpecs)->toArray(),
- 'html' => $goods_service->optionsHtml,
- 'var' => \YunShop::app()->get(),
- 'brands' => $goods_service->brands,
- 'catetory_menus' => implode('', $goods_service->catetory_menus),
- 'virtual_types' => [],
- 'shopset' => $this->shopset,
- 'type' => 'edit',
- ])->render();
- }
- public function generateSmallCode()
- {
- $goods_id = intval(request()->id);
- if (!$goods_id) {
- return $this->message("商品ID不存在", '', 'error');
- }
- //检查商品小程序二维码是否存在
- $goods = GoodsSmallUrl::uniacid()->where("goods_id", $goods_id)->first();
- if (!empty($goods['collect_small_url'])) {
- return $this->message("小程序二维码已存在", '', 'error');
- }
- $small_qr = new SmallQrCode();
- $small_name = "goods_small_code_url_" . $goods_id;
- $data['scene'] = 'id=' . $goods_id;
- $data['page'] = "packageA/detail_v2/detail_v2";
- $pay_code = $small_qr->getSmallQrCode($small_name, $data);
- if ($pay_code['code'] == 0) {
- $goodsModel = new GoodsSmallUrl();
- $data = [
- 'uniacid' => \YunShop::app()->uniacid,
- 'goods_id' => $goods_id,
- 'collect_small_url' => $pay_code['file_path'],
- 'created_at' => time(),
- 'updated_at' => time()
- ];
- $goodsModel->fill($data);
- if ($goodsModel->save()) {
- return $this->message("小程序二维码已生成");
- } else {
- return $this->message("小程序二维码生成失败", '', 'error');
- }
- } else {
- return $this->message($pay_code['message'], '', 'error');
- }
- }
- public function displayorder()
- {
- $id = request()->id;
- $value = request()->value;
- if (empty($id)) {
- return $this->errorJson('排序失败,商品ID不能为空');
- }
- $goods = \app\common\models\Goods::find($id);
- $goods->display_order = $value;
- if ($goods->save()) {
- return $this->successJson('排序成功');
- } else {
- return $this->errorJson('排序失败');
- }
- // return $this->message('商品排序成功', Url::absoluteWeb($this->success_url));
- //$this->error($goods);
- }
- public function change()
- {
- //dd(\YunShop::request());
- $id = request()->id;
- $field = request()->type;
- $goods = \app\common\models\Goods::find($id);
- $goods->$field = request()->value;
- if ($goods->save()) {
- \Artisan::call('config:cache');
- \Cache::flush();
- return $this->successJson('修改成功');
- } else {
- return $this->errorJson('修改失败');
- }
- //$this->error($goods);
- }
- /**
- * 商品上下架权限需要独立控制 Yi_190517
- */
- public function setPutaway()
- {
- return $this->setProperty();
- }
- public function setProperty()
- {
- $id = request()->id;
- $field = request()->type;
- $data = request()->data; //(request()->data == 1 ? '0' : '1');
- $goods = \app\common\models\Goods::find($id);
- $goods->$field = $data;
- //dd($goods);
- $goods->save();
- Cache::flush();
- echo json_encode(["data" => $data, "result" => 1]);
- }
- //批量上下架
- public function batchSetProperty()
- {
- $ids = request()->ids;
- $data = request()->data;
- foreach ($ids as $id) {
- $goods = \app\common\models\Goods::find($id);
- $goods->status = $data;
- $goods->save();
- }
- echo json_encode(["data" => $data, "result" => 1]);
- }
- public function destroy()
- {
- $id = request()->id;
- $goods = Goods::destroy($id);
- return $this->successJson('商品删除成功');
- }
- public function batchDestroy()
- {
- $ids = request()->ids;
- foreach ($ids as $id) {
- $goods = Goods::destroy($id);
- }
- echo json_encode([
- "result" => $goods,
- ]);
- }
- public function batchService()
- {
- $ids = request()->ids;
- $service_form = request()->service_form;
- if (empty($ids)) {
- return $this->errorJson('请选择商品');
- }
- DB::transaction(function () use ($service_form, $ids) {
- foreach ($ids as $gid) {
- $goods_service = ServiceProvide::uniacid()->where('goods_id', $gid)->first();
- if (!$goods_service) {
- $goods_service = new ServiceProvide();
- $goods_service->uniacid = \YunShop::app()->uniacid;
- $goods_service->goods_id = $gid;
- }
- $goods_service->is_automatic = $service_form['is_automatic'];
- $goods_service->time_type = $service_form['time_type'];
- $goods_service->on_shelf_time = $service_form['on_shelf_time'];
- $goods_service->lower_shelf_time = $service_form['lower_shelf_time'];
- $goods_service->loop_date_start = $service_form['loop_date_start'];
- $goods_service->loop_date_end = $service_form['loop_date_end'];
- $goods_service->loop_time_up = $service_form['loop_time_up'];
- $goods_service->loop_time_down = $service_form['loop_time_down'];
- $goods_service->auth_refresh_stock = $service_form['auth_refresh_stock'];
- $goods_service->original_stock = $service_form['original_stock'];
- $goods_service->save();
- }
- });
- return $this->successJson('编辑成功');
- }
- /**
- * 获取参数模板
- */
- public function getParamTpl()
- {
- $tag = random(32);
- return view('goods.tpl.param', [
- 'tag' => $tag,
- ])->render();
- }
- /**
- * 获取规格模板
- */
- public function getSpecTpl()
- {
- $spec = [
- "id" => random(32),
- "title" => '',
- 'items' => [],
- ];
- return view('goods/tpl/spec', ['spec' => $spec]);
- }
- /**
- * 获取规格项模板
- */
- public function getSpecItemTpl()
- {
- $goodsModel = Goods::find($this->goods_id);
- $spec = array(
- "id" => \YunShop::request()->specid,
- );
- $specitem = array(
- "id" => random(32),
- "title" => \YunShop::request()->title,
- "show" => 1,
- 'virtual' => '',
- 'title2' => '',
- 'thumb' => '',
- );
- return view('goods/tpl/spec_item', [
- 'spec' => $spec,
- 'goods' => $goodsModel,
- 'specitem' => $specitem,
- ])->render();
- }
- /**
- * 获取搜索商品
- * @return html
- */
- public function getSearchGoods()
- {
- $keyword = \YunShop::request()->keyword;
- $goods = \app\common\models\Goods::select('id', 'title', 'thumb')
- ->where('title', 'like', '%' . $keyword . '%')
- ->where('status', 1)
- ->whereInPluginIds()
- ->get();
- if (!$goods->isEmpty()) {
- $goods = set_medias($goods->toArray(), array('thumb', 'share_icon'));
- }
- return view('goods.query', [
- 'goods' => $goods,
- 'exchange' => \YunShop::request()->exchange,
- ])->render();
- }
- public function getSearchGoodsJson()
- {
- $except_supplier = request()->except_supplier;
- $keyword = request()->keyword;
- $query = \app\common\models\Goods::select('id', 'title', 'thumb')
- ->where('title', 'like', '%' . $keyword . '%')
- ->where('status', 1);
- if ($except_supplier) {
- $except_plugin_id = [92,101];
- $query->whereNotIn('plugin_id', $except_plugin_id);
- } else {
- $query->whereInPluginIds();
- }
- $goods = $query->paginate(20);
- $goods->map(function ($q) {
- return $q->thumb_url = yz_tomedia($q->thumb);
- });
- return $this->successJson('ok', [
- 'goods' => $goods,
- ]);
- }
- public function getSearchGoodsLevel()
- {
- $keyword = \YunShop::request()->keyword;
- $model = \app\common\models\Goods::select('id', 'title', 'thumb')
- ->where('title', 'like', '%' . $keyword . '%')
- ->where('status', 1);
- $goods = $model->get();
- if (!$goods->isEmpty()) {
- $goods = set_medias($goods->toArray(), array('thumb', 'share_icon'));
- }
- return view('goods.query', [
- 'goods' => $goods,
- 'exchange' => \YunShop::request()->exchange,
- ])->render();
- }
- /**
- * 获取搜索门店
- * @return html
- */
- public function getSearchStore()
- {
- $keyword = \YunShop::request()->keyword;
- $store = StoreCashier::getStoreByName($keyword);
- return view('goods.store', [
- 'store' => $store
- ])->render();
- }
- /**
- * 获取搜索门店返回数组
- * @return string
- * @throws \Throwable
- */
- public function getSearchStoreJson()
- {
- $keyword = request()->keyword;
- $store = StoreCashier::getStoreByName($keyword);
- return $this->successJson('ok', $store);
- }
- /**
- * 获取搜索酒店
- * @return html
- */
- public function getSearchHotel()
- {
- if (app('plugins')->isEnabled('hotel')) {
- $keyword = \YunShop::request()->keyword;
- $hotel = Hotel::getHotelByName($keyword);
- return view('goods.hotel', [
- 'hotel' => $hotel
- ])->render();
- }
- return;
- }
- /**
- * 获取搜索酒店返回数组
- * @return string
- * @throws \Throwable
- */
- public function getSearchHotelJson()
- {
- if (app('plugins')->isEnabled('hotel')) {
- $keyword = request()->keyword;
- $hotel = Hotel::getHotelByName($keyword);
- return $this->successJson('ok', $hotel);
- }
- return;
- }
- /**
- * 获取搜索会员标签返回数组
- * @return string
- * @throws \Throwable
- */
- public function getSearchMemberTagsJson()
- {
- if (app('plugins')->isEnabled('member-tags')) {
- $keyword = request()->keyword;
- $tags = MemberTagsModel::GetTagsByTitle($keyword)->get(['id','title'])->toArray();
- return $this->successJson('ok', $tags);
- }
- return;
- }
- /**
- * 获取搜索商品by经销商
- * @return html
- */
- public function getSearchGoodsByDividend()
- {
- $keyword = \YunShop::request()->keyword;
- $goods = Goods::getGoodsByName($keyword);
- if (!$goods->isEmpty()) {
- $goods = set_medias($goods->toArray(), array('thumb', 'share_icon'));
- }
- return view('goods.dividend_goods_query', [
- 'goods' => $goods
- ])->render();
- }
- public function getSearchGoodsByDividendLevel()
- {
- $keyword = \YunShop::request()->keyword;
- $goods = \app\common\models\Goods::getGoodsLevelByName($keyword);
- if (!$goods->isEmpty()) {
- $goods = set_medias($goods->toArray(), array('thumb', 'share_icon'));
- }
- return view('goods.dividend_goods_query', [
- 'goods' => $goods
- ])->render();
- }
- public function getMyLinkGoods()
- {
- if (!\YunShop::request()->kw) {
- $postData = file_get_contents('php://input', true);
- $obj = json_decode($postData);
- \YunShop::request()->kw = $obj->kw;
- //dd($obj->kw);
- }
- if (\YunShop::request()->kw) {
- $goods = \app\common\models\Goods::getGoodsByName(\YunShop::request()->kw);
- if (!$goods->isEmpty()) {
- $goods = set_medias($goods->toArray(), array('thumb', 'share_icon'));
- }
- $goods = collect($goods)->map(function ($item) {
- $url = yzAppFullUrl('goods/' . $item['id']);
- // if (app('plugins')->isEnabled('store-cashier')) {
- // $store_goods = new \Yunshop\StoreCashier\common\models\StoreGoods();
- // $store_id = $store_goods->where('goods_id', $item['id'])->value('store_id');
- // if ($store_id) {
- // $url = yzAppFullUrl("goods/{$item['id']}/o2o/{$store_id}");
- // }
- // }
- // $is_course = (new VideoDemandCourseGoods())->isCourse($item['id']);
- // if ($is_course) {
- // $url = yzAppFullUrl("member/coursedetail/{$item['id']}");
- // }
- return array_add($item, 'url', $url);
- });
- echo json_encode($goods);
- exit;
- }
- }
- public function getSmallMyLinkGoods()
- {
- if (!\YunShop::request()->kw) {
- $postData = file_get_contents('php://input', true);
- $obj = json_decode($postData);
- \YunShop::request()->kw = $obj->kw;
- //dd($obj->kw);
- }
- if (\YunShop::request()->kw) {
- $goods = \app\common\models\Goods::getGoodsByName(\YunShop::request()->kw);
- if (!$goods->isEmpty()) {
- $goods = set_medias($goods->toArray(), array('thumb', 'share_icon'));
- }
- $goods = collect($goods)->map(function ($item) {
- $url = '/packageA/detail_v2/detail_v2?id=' . $item['id'];
- return array_add($item, 'url', $url);
- });
- echo json_encode($goods);
- exit;
- }
- }
- public function SearchOrder()
- {//获取商品名称
- $keyword = request()->keyword;
- $pluginId = request()->plugin_id;
- if (empty($pluginId)) {
- $pluginId = 0;
- }
- $goods = Goods::getSearchOrder($keyword, $pluginId);
- return view('goods.query', [
- 'goods' => $goods->toArray(),
- ])->render();
- }
- /**
- * 商品批量导入
- */
- public function import()
- {
- return view('goods.import')->render();
- }
- /**
- * 解压zip文件
- * @string $file 需要解压的文件的绝对路径
- * @string $destination 解压文件的绝对路径
- * @return bool
- *
- */
- private function unZipFile($file, $destination)
- {
- $zip = new \ZipArchive(); // 实例化对象
- if ($zip->open($file) !== true) { //打开zip文档
- return false; //无法打开zip文件
- }
- $zip->extractTo($destination);//将压缩文件解压到指定的目录下
- $zip->close(); //关闭zip文档
- return true;
- }
- //ajax 异步上传文件
- public function updateZip()
- {
- $file = request()->file('file');
- if (!$file) {
- return $this->errorJson('请传入正确参数.');
- }
- if ($file->isValid()) {
- // 获取文件相关信息
- $originalName = $file->getClientOriginalName(); // 文件原名
- $realPath = $file->getRealPath(); //临时文件的绝对路径
- $ext = $file->getClientOriginalExtension();
- $newOriginalName = md5($originalName . str_random(6)) . '.' . $ext;
- \Storage::disk('image')->put($newOriginalName, file_get_contents($realPath));
- if (config('app.framework') == 'platform') {
- $attachment = base_path() . '/static/upload/';
- } else {
- $attachment = $_SERVER['DOCUMENT_ROOT'] . '/attachment/image/';
- }
- if (is_dir($attachment)) {
- mkdir($attachment);
- }
- if ($this->unZipFile($attachment . $newOriginalName, $attachment) == true) {
- return $this->successJson('上传成功');
- } else {
- return $this->errorJson('解压失败');
- }
- }
- }
- /**
- * excel 商品导入
- * @return \Illuminate\Http\JsonResponse
- */
- public function a()
- {
- if (config('app.framework') == 'platform') {
- $attachment = 'static/upload/';
- } else {
- $attachment = 'attachment/';
- }
- $scheme = empty($_SERVER['HTTPS']) ? 'http://' : 'https://';
- $url = $scheme . $_SERVER['HTTP_HOST'];
- $url = $url . '/' . $attachment . 'image/';
- $data = request()->input('data');
- $i = 0;
- $goodsName = array_column($data, '商品名称');
- foreach ($data as $key => $value) {
- $goodsData[$i] = [
- 'uniacid' => $value['公众号'] ?: 0,
- 'display_order' => $value['排序'],
- 'title' => $value['商品名称'],
- 'brand_id' => $this->getBrandId(['uniacid' => $value['公众号'], 'brand' => $value['品牌']]),
- 'type' => $value['商品类型'],
- 'sku' => $value['商品单位'],
- 'is_recommand' => $value['推荐'],
- 'is_new' => $value['新上'],
- 'is_hot' => $value['热卖'],
- 'is_discount' => $value['促销'],
- 'thumb' => $url . $value['商品图片'],
- 'goods_sn' => $value['商品编号'],
- 'product_sn' => $value['商品条码'],
- 'price' => $value['商品现价'],
- 'market_price' => $value['商品原价'],
- 'cost_price' => $value['成本价'],
- 'weight' => $value['重量'],
- 'stock' => $value['库存'],
- 'virtual_sales' => $value['虚拟销量'],
- 'reduce_stock_method' => $value['拍下减库存'],
- 'no_refund' => $value['不可退货退款'],
- 'status' => $value['是否上架'],
- 'content' => $value['商品描述']
- ];
- $goodsCategorys[$value['商品名称']] = [
- 'title' => $value['商品名称'],
- 'category1' => $value['商品分类一'],
- 'category2' => $value['商品分类二'],
- ];
- $i++;
- }
- unset($data);
- unset($i);
- $result = Goods::insert($goodsData);
- unset($goodsData);
- $goodsId = Goods::select('id', 'uniacid', 'title')->whereIn('title', $goodsName)->get()->toArray();
- unset($goodsName);
- foreach ($goodsId as $k => $v) {
- if (isset($goodsCategorys[$v['title']])) {
- $goodsId[$k] = array_merge($v, $goodsCategorys[$v['title']]);
- }
- unset($k);
- }
- unset($v);
- $goodsCategory = array();
- foreach ($goodsId as $a => $b) {
- $temp = $this->getCategoryId([
- 'uniacid' => $b['uniacid'],
- 'category_name_1' => $b['category1'],
- 'category_name_2' => $b['category2'],
- ]);
- $goodsCategory[$a] = [
- 'goods_id' => $b['id'],
- 'category_id' => $temp['category_id'],
- 'category_ids' => $temp['category_ids'],
- 'created_at' => $_SERVER['REQUEST_TIME'],
- 'updated_at' => $_SERVER['REQUEST_TIME'],
- ];
- unset($temp);
- unset($a);
- }
- unset($b);
- $result = GoodsCategory::insert($goodsCategory);
- if ($result) {
- return $this->successJson('导入成功');
- }
- }
- /**
- * //todo 通过数组下标查找,没有就添加,如果上传的excel里分类较多,需优化
- * @param $level
- * @param $uniacid
- * @param $name
- * @return mixed
- */
- private function getCategoryId($array)
- {
- if ($array['category_name_1'] == null and $array['category_name_2'] == null) {
- return [
- 'category_id' => 0,
- 'category_ids' => '',
- ];
- }
- if (is_null($this->list)) {
- $this->list = array_column(Category::select('id', 'name', 'uniacid', 'level')->where('plugin_id', 0)->get()->toArray(), null, 'name');
- }
- $result = array();
- if ($this->list[$array['category_name_1']]) {
- if ($this->list[$array['category_name_1']]['uniacid'] == $array['uniacid']) {
- $result['category_id_1'] = $this->list[$array['category_name_1']]['id'];
- } else {
- $result['category_id_1'] = $this->addCategory([
- 'uniacid' => $array['uniacid'],
- 'name' => $array['category_name_1'],
- 'level' => 1,
- 'plugin_id' => 0,
- 'is_home' => 1,
- 'parent_id' => 0
- ]);
- }
- } else {
- $result['category_id_1'] = $this->addCategory([
- 'uniacid' => $array['uniacid'],
- 'name' => $array['category_name_1'],
- 'level' => 1,
- 'plugin_id' => 0,
- 'is_home' => 1,
- 'parent_id' => 0
- ]);
- }
- //商品二级分类
- if ($this->list[$array['category_name_2']]) {
- if ($this->list[$array['category_name_2']]['uniacid'] == $array['uniacid']) {
- $result['category_id'] = $this->list[$array['category_name_2']]['id'];
- $result['category_ids'] = $result['category_id_1'] . ',' . $result['category_id'];
- } else {
- $result['category_id'] = $this->addCategory([
- 'uniacid' => $array['uniacid'],
- 'name' => $array['category_name_2'],
- 'level' => 2,
- 'plugin_id' => 0,
- 'is_home' => 1,
- 'parent_id' => $result['category_id_1']
- ]);
- $result['category_ids'] = $result['category_id_1'] . ',' . $result['category_id'];
- }
- } else {
- $result['category_id'] = $this->addCategory([
- 'uniacid' => $array['uniacid'],
- 'name' => $array['category_name_2'],
- 'level' => 2,
- 'plugin_id' => 0,
- 'is_home' => 1,
- 'parent_id' => $result['category_id_1']
- ]);
- $result['category_ids'] = $result['category_id_1'] . ',' . $result['category_id'];
- }
- if (!$result['category_ids']) {
- $result['category_ids'] = $result['category_id'];
- }
- unset($result['category_id_1']);
- return $result;
- }
- /**
- * 添加分类表
- * @param $array
- * @return int
- */
- private function addCategory($array)
- {
- $id = Category::insertGetId($array);
- $this->list = array_column(Category::select('id', 'name', 'uniacid', 'level')->where('plugin_id', 0)->get()->toArray(), null, 'name');
- return $id;
- }
- /**
- * 通过数组下标获取brand_id
- * @param $array
- * @return mixed
- */
- private function getBrandId($array)
- {
- if (is_null($this->brand)) {
- $this->brand = array_column(Brand::get()->toArray(), null, 'name');
- }
- if ($this->brand[$array['brand']]) {
- if ($this->brand[$array['brand']]['uniacid'] == $array['uniacid']) {
- return $this->brand[$array['brand']]['id'];
- } else {
- //todo 添加品牌
- return $this->addBrand([
- 'uniacid' => $array['uniacid'],
- 'name' => $array['brand'],
- 'alias' => '批量添加',
- 'logo' => '',
- 'desc' => '',
- 'created_at' => $_SERVER['REQUEST_TIME'],
- 'updated_at' => $_SERVER['REQUEST_TIME'],
- ]);
- }
- } else {
- return $this->addBrand([
- 'uniacid' => $array['uniacid'],
- 'name' => $array['brand'],
- 'alias' => '',
- 'logo' => '',
- 'desc' => '',
- 'created_at' => $_SERVER['REQUEST_TIME'],
- 'updated_at' => $_SERVER['REQUEST_TIME'],
- ]);
- }
- }
- /**
- * 添加品牌
- * @param $array
- * @return int
- */
- private function addBrand($array)
- {
- $id = Brand::insertGetId($array);
- $this->brand = array_column(Brand::get()->toArray(), null, 'name');
- return $id;
- }
- /**
- * demo 下载
- */
- public function excelImport()
- {
- $exportData['0'] = ["公众号", "排序", '商品名称', '商品分类一', '商品分类二', '商品品牌', '商品类型', '商品单位',
- '商品属性', '商品图片', '商品编号', '商品条码', '商品现价', '商品原价', '成本价', '虚拟销量', '减库存方式', '不可退换货',
- '是否上架', '商品描述', '推荐', '新上', '热卖', '促销', '商品图片'
- ];
- \Excel::create('商品批量导入模板', function ($excel) use ($exportData) {
- $excel->setTitle('Office 2005 XLSX Document');
- $excel->setCreator('芸众商城');
- $excel->setLastModifiedBy("芸众商城");
- $excel->setSubject("Office 2005 XLSX Test Document");
- $excel->setDescription("Test document for Office 2005 XLSX, generated using PHP classes.");
- $excel->setKeywords("office 2005 openxml php");
- $excel->setCategory("report file");
- $excel->sheet('info', function ($sheet) use ($exportData) {
- $sheet->rows($exportData);
- });
- })->export('xls');
- }
- }
|