bztang-admin/app/backend/modules/goods/controllers/GoodsController.php

1352 lines
46 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
/**
* Created by PhpStorm.
* Author:
* 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\Dispatch;
use app\backend\modules\goods\models\Goods;
use app\backend\modules\goods\models\GoodsDispatch;
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\events\goods\GoodsChangeEvent;
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();
}
//运费数据
$dispatchData = $this->getDispatchData();
$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,
'dispatchTypesSetting' => $dispatchData['dispatchTypesSetting'],
'dispatchTemplates' => $dispatchData['dispatchTemplates'],
];
$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 batchCopy()
{
$ids = request()->ids;
foreach ($ids as $id) {
$result = CopyGoodsService::copyGoods($id);
if (!$result) {
$this->error('商品ID【' . $id . '】不存在.');
}
}
echo json_encode(["result" => 1]);
}
/**
* 批量修改运费
*/
public function batchEditDispatch()
{
if (!$ids = request()->goods_id_arr) {
return $this->errorJson('请选择商品');
}
$dispatchObserverConfig = \app\common\modules\shop\ShopConfig::current()->get('observer.goods.dispatch');
$class = $dispatchObserverConfig['class'];
$function = $dispatchObserverConfig['function_save'];
$data = request()->data;
if (class_exists($class) && method_exists($class, $function) && is_callable([$class, $function]) && $data) {
foreach ($ids as $id) {
$result = $class::$function($id, $data, 'update');
if (!$result) {
$this->error('商品ID【' . $id . '】更新运费失败.');
}
}
}
return $this->successJson('修改成功');
}
public function create()
{
if (request()->ajax()) {
$request = Request();
$goods_service = new CreateGoodsService($request);
$result = $goods_service->create();
if ($result['status'] == 1) {
return $this->successJson('商品创建成功', ['good_id' => $result['good_id']]);
} 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()
{
$goods = \app\common\models\Goods::find(request()->input('id'));
$field = request()->type;
$goods->$field = request()->input('value');
$goodsModel = clone $goods;
if ($goods->save()) {
event(new GoodsChangeEvent($goodsModel));
\Artisan::call('config:cache');
\Cache::flush();
return $this->successJson('修改成功');
}
return $this->errorJson('修改失败');
}
/**
* 商品上下架权限需要独立控制 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');
}
/**
* 运费数据
* @return array
*/
private function getDispatchData()
{
$dispatchTemplates = Dispatch::select('id','dispatch_name')
->uniacid()
->where(['enabled' => 1 , 'plugin_id' => 0])
->where('is_plugin', 0)
->get()
->toArray();
return [
'dispatchTypesSetting' => (new Goodsdispatch())->dispatchTypesSettingV2(),
'dispatchTemplates' => $dispatchTemplates,
];
}
}