unpackJWT($JWT);
$this->uid = $payload['userId'];
$usver = DB::table('users')->where('id', $this->uid)->first();
$this->user = $usver;
// $this->avatar=$admin->avatar;
$this->fName = $usver->firstName;
$this->sName = $usver->secondName;
$this->lName = $usver->lastName;
$this->nickname = 'Администратор ' . $this->fName;
/*if(!empty($this->sName))$this->nickname.=' '.$this->sName;
if(!empty($this->lName))$this->nickname.=' '.$this->lName;*/
return true;
}
public function getResponse($form, $catName)
{
return "
$form
\n\t";
}
public function queryOnesS($request)
{
$ch = curl_init();
$url = env('ONESS_PATH', 'http://pestshop.morskoi.com') . $request;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
curl_setopt($ch, CURLOPT_COOKIESESSION, 1);
curl_setopt($ch, CURLINFO_HEADER_OUT, 1);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 33);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_ENCODING, '');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
$res = curl_exec($ch);
$info = curl_getinfo($ch);
// return $info;
if ($info['http_code'] != '200') return false;
$res = json_decode($res, true);
return $res;
}
public function queryAS($request)
{
$ch = curl_init();
$url = env('JWT_RPATH', 'http://pestshop.morskoi.com') . $request;
// return $url;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
curl_setopt($ch, CURLOPT_COOKIESESSION, 1);
curl_setopt($ch, CURLINFO_HEADER_OUT, 1);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 33);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_ENCODING, '');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
$res = curl_exec($ch);
$info = curl_getinfo($ch);
if ($info['http_code'] != '200') return false;
$res = json_decode($res, true);
return $res;
}
public function userEditForm(Request $request, $JWT, $uid)
{
// return response($request->url());
$this->setUserData($JWT);
$user = DB::table('users')->where('users.id', $uid)->first();
if ($user) {
$action = "/pestshop_admin/$JWT/agents";
$perms = $this->queryAS("/user/$JWT/getpermissions/$uid");
$shops = DB::table('shops')->get();
$current = [];
if ($perms['status'] == 'ok') {
$tmp = base64_decode($perms['perm']);
$tmp = explode(',', $tmp);
if (!empty($tmp))
foreach ($tmp as $key => $val) {
$current[$val] = 1;
}
}
$permForm = view('admin.permissions', ['action' => "$action", 'shops' => $shops, 'current' => $current, 'uid' => $uid,]);
$form = "
$permForm\n\t";
} else return response("Запись не найдена!
");
return $this->getResponse($form, 'Редактирование данных агента #' . $uid);
}
function changePermissions(Request $request, $JWT)
{
if (!empty($request->permissions)) {
$reqPerm = json_encode($request->permissions);
$change = base64_encode($reqPerm);
// echo $change;return response(21);
if (isset($request->uid)) {
$perm = $this->queryAS("/user/$JWT/change/permissions/change/$change/{$request->uid}");
if (isset($perm['status'])) {
if ($perm['status'] == 'ok') {
$out = 'Изменения разрешений доступа сохранены
';
DB::table('notifications')->where('uid', $request->uid)->whereNotIn('nShop', $request->permissions)->delete();
$options = '{"sendEmail":"1","sendSMS":"1","sendPush":"1"}';
// $options=stripslashes($options);
foreach ($request->permissions as $val) {
DB::insert(
"INSERT IGNORE INTO `notifications` (`uid`, `nShop`, `options`) VALUES (?, ?, ?)",
[$request->uid, $val, $options]
);
}
} else $out = 'Не удалось сохранить изменения, ошибка: ' . $perm['status'] . '
';
} else $out = 'Не удалось сохранить изменения, ошибка: unknown error
';
}
} else $out = 'Необходимо дать доступ хотя бы к одному магазину
';
return response($out);
}
public function shopEditForm(Request $request, $JWT, $shopid)
{
$currentBanner = '';
$shop = DB::table('shops')->where('shopID', $shopid)->first();
// return response("$JWT, $shopid");
if ($shop) {
$shopName = $shop->shopName;
if (!empty($shop->banner)) $currentBanner = "
";
}
$form = view('admin.shopform', [
'action' => "/pestshop_admin/$JWT/shops",
'catName' => 'Магазин ' . $shopName,
'shopName' => htmlentities($shopName),
'shopid' => $shop->id,
'currentBanner' => $currentBanner,
'JWT' => $JWT,
'countMsg' => $this->countMsg,
'warnMsg' => $this->warnMsg,
'nickname' => $this->nickname,
'avatar' => $this->avatar,
]);
return $this->getResponse($form, 'Редактирование данных магазина #' . $shop->id);
}
public function storeEditForm(Request $request, $JWT, $shopid = 1, $sid)
{
$this->setUserData($JWT);
$login = '';
$shopSelect = '';
// return response($request->url());
$store = DB::table('stores')->where('storeID', $sid)->where('shop', $shopid)->first();
if ($store) {
$shops = DB::table('shops')->get();
foreach ($shops as $shop) {
$selected = '';
if ($shop->id == $shopid) $selected = 'selected';
$shopSelect .= "\n\t";
}
if ($store->location && $store->location != '-') {
$tmp = explode(', ', $store->location);
$lat = $tmp[0];
$lng = $tmp[1];
} else {
$lat = '55.751849';
$lng = '37.626515';
}
$login = 'pestshop_srvc' . $store->storeID;
$ONES_URL = env('ONES_URL', 'example.com');
$form = "
\n\t";
} else return response("Запись не найдена!
");
return $this->getResponse($form, 'Редактирование данных торговой точки (склада) #' . $sid);
}
public function categoriesEditForm(Request $request, $JWT, $shopid = 1, $catid)
{
$this->setUserData($JWT);
// return response($request->url());
$category = DB::table('categories')->where('catID', $catid)->where('cShop', $shopid)->first();
if ($category)
$form = "
\n\t";
else return response("Запись не найдена!
");
return $this->getResponse($form, 'Редактирование товарной категории #' . $catid);
}
public function brandsEditForm(Request $request, $JWT, $brandid)
{
$this->setUserData($JWT);
// return response($request->url());
$brand = DB::table('brands')->where('brandID', $brandid)->first();
if ($brand)
$form = "
\n\t";
else return response("Запись не найдена!
");
return $this->getResponse($form, 'Редактирование товарной категории #' . $brandid);
}
public function goodsEditForm(Request $request, $JWT, $shopid = 1, $goodsid)
{
$this->setUserData($JWT);
$i = 1;
$j = 0;
$action = "/pestshop_admin/$JWT/goods/$shopid/$goodsid?page=" . $request->page;
// return response($request->url());
$goods = DB::table('goods')->join('categories as c', 'goods.category', '=', 'c.catID')->join('brands as b', 'goods.brand', '=', 'b.brandID')->where('gShop', $shopid)->where('goodsID', $goodsid)->first();
$currentPhoto = "\n\t
\n\t";
if (!empty($goods->photos)) {
$tmp = json_decode($goods->photos, true);
// print_r($tmp);
foreach ($tmp as $val) {
if ($j == 0) $currentPhoto .= "
";
$currentPhoto .= "\n\t
Удалить фотографию

";
if ($j == 2) $currentPhoto .= "
";
$i++;
$j++;
if ($j > 2) $j = 0;
}
} else $currentPhoto .= "\n\t
Для этого товара нет загруженных фотографий
\n\t";
$currentPhoto .= "\n\t
\n\t";
$cats = DB::table('categories')->orderBy('catName', 'asc')->get();
if ($cats) {
$categories = "\n\t';
} else $categories = "";
$brnds = DB::table('brands')->orderBy('brandName', 'asc')->get();
if ($brnds) {
$brands = "\n\t';
} else $brands = "";
$currs = DB::table('currency')->orderBy('curID', 'asc')->get();
if ($currs) {
$currencies = "\n\t';
} else $currencies = "";
if ($goods)
$form = "
\n\t";
else return response("Запись не найдена!
");
return $this->getResponse($form, 'Редактирование товара #' . $goodsid);
}
public function delGoodsPhoto(Request $request, $JWT, $goodsid, $photo)
{
$photo--;
$goods = DB::table('goods')->where('gShop', 1)->where('goodsID', $goodsid)->first();
$photos = json_decode($goods->photos, true);
Storage::delete('public/goodsphoto/' . $photos[$photo]);
unset($photos[$photo]);
$photos = array_values($photos);
$photos = json_encode($photos);
$res = DB::table('goods')->where('gShop', 1)->where('goodsID', $goodsid)->update(['photos' => $photos]);
return $this->goodsEditForm($request, $JWT, $goodsid);
}
public function searchGoods(Request $request, $JWT)
{
$outText = '';
$html = '';
$addAction = '?page=' . $request->page;
$goodsCount = DB::table('goods as g')->join('brands as b', 'g.brand', '=', 'b.brandID')->join('categories as ctgr', 'g.category', '=', 'ctgr.catID')->where('gShop', $request->gShop)->where('name', 'like', "%{$request->name}%")->count();
if ($goodsCount) {
$goods = DB::table('goods as g')->join('brands as b', 'g.brand', '=', 'b.brandID')->join('categories as ctgr', 'g.category', '=', 'ctgr.catID')->where('gShop', $request->gShop)->where('name', 'like', "%{$request->name}%")->select('ctgr.catID as catID', 'g.name as name', 'b.brandName as brandName', 'ctgr.catName as catName', 'g.goodsID as goodsID')->orderBy('catName')->orderBy('name')->limit(10)->get();
foreach ($goods as $good) {
$html .= "
| {$good->goodsID} |
{$good->name} |
{$good->catName} |
{$good->brandName} |
|
|
";
}
} else $html .= "\n\t
Ничего не найдено |
\n\t";
$outText = "\n\t" . '
| ID |
Название |
Категория |
Бренд |
Количество |
Действие |
' . $html . '
' . "\n\t";
return $outText;
}
public function promosEditForm(Request $request, $JWT, $shopid, $promosid)
{
$this->setUserData($JWT);
$action = "/pestshop_admin/$JWT/promos/$shopid/$promosid?page=" . $request->page;
// return response($request->url());
$promo = DB::table('promos')->where('pShop', $shopid)->where('promoID', $promosid)->first();
$currentBanner = "\n\t
\n\t";
if (!empty($promo->banner)) {
$currentBanner .= "\n\t
Удалить баннер

";
} else $currentBanner .= "\n\t
Для этой акции баннер не загружен
\n\t";
$currentBanner .= "\n\t
\n\t";
if ($promo)
$form = "
\n\t";
else return response("Запись не найдена!
");
return $this->getResponse($form, 'Редактирование промоакции #' . $promosid);
}
public function delPromosBanner(Request $request, $JWT, $shopid, $promosid, $banner)
{
$promos = DB::table('promos')->where('pShop', $shopid)->where('promoID', $promosid)->first();
Storage::delete('public/promosbanner/' . $promos->banner);
$res = DB::table('promos')->where('pShop', $shopid)->where('promoID', $promosid)->update(['banner' => ""]);
return $this->promosEditForm($request, $JWT, $shopid, $promosid);
}
public function getStoresCat(Request $request, $JWT, $shopid, $storesid, $msg = '')
{
$html = '';
$addAction = '';
$storesGoods = DB::table('catalogue as c')->join('goods as g', 'c.goodsID', '=', 'g.goodsID')->join('brands as b', 'g.brand', '=', 'b.brandID')->join('categories as ctgr', 'g.category', '=', 'ctgr.catID')->where('c.store', $storesid)->where('c.cShop', $shopid)->select('c.catID as catID', 'g.name as name', 'b.brandName as brandName', 'ctgr.catName as catName', 'c.num as num', 'g.unit as unit', 'c.id as cid')->orderBy('catName')->orderBy('name')->paginate(15);
// var_dump($storesGoods->items());return response(21);
if ($storesGoods && !empty($storesGoods->items())) {
$html .= '' . $storesGoods->links() . '';
$addAction = '?page=' . $storesGoods->currentPage();
foreach ($storesGoods as $storesGood) {
$html .= "
| {$storesGood->cid} |
{$storesGood->name} |
{$storesGood->catName} |
{$storesGood->brandName} |
{$storesGood->num} |
{$storesGood->unit} |
|
";
}
} else $html .= "\n\t
| Список товара пуст |
\n\t";
$outText = "\n\t" . $msg . "\n\t" . '
| ID |
Название |
Категория |
Бренд |
Количество |
Единицы |
Действие |
' . $html . '
' . "\n\t";
$outText .= view('admin.addstoregoodsform', ['JWT' => $JWT, 'storesid' => $storesid, 'shopid' => $shopid, 'page' => $request->page]);
return $this->getResponse($outText, 'Каталог товара торговой точки #' . $storesid);
}
public function addGoods(Request $request, $JWT, $shopid, $storesid, $catID, $goodsid, $num)
{
try {
$res = DB::table('catalogue')->insertGetId(['catID' => $catID, 'goodsID' => $goodsid, 'store' => $storesid, 'cShop' => $shopid, 'num' => $num]);
} catch (\Illuminate\Database\QueryException $e) {
//return response('query error: '.$e->errorInfo[2]]);
if (mb_stripos($e->errorInfo[2], 'duplicate entry') !== false) return response('Этот товар уже есть в каталоге торговой точки
');
else return response('Ошибка добавления
');
}
return response('Товар в каталог торговой точки добавлен
');
}
public function delGoodsItem(Request $request, $JWT, $shopid, $storesid, $catid)
{
$shopid = DB::table('catalogue')->where('cShop', $shopid)->where('store', $storesid)->where('catID', $catid)->value('cShop');
$res = DB::table('catalogue')->where('cShop', $shopid)->where('store', $storesid)->where('catID', $catid)->delete();
return $this->getStoresCat($request, $JWT, $shopid, $storesid);
}
public function loadCatalogue(Request $request, $JWT, $shopid, $storesid)
{
$this->setUserData($JWT);
$msg = "Каталог товаров обновлен!
";
$num = DB::table('stores')->where('storeID', $storesid)->where('shop', $shopid)->count();
if (!$num) return $this->getStoresCat($request, $JWT, $shopid, $storesid, "Не удалось обновить каталог товаров, торговая точка не найдена!
");
$response = $this->queryOnesS("/$JWT/getit/$shopid/$storesid");
// print_r($response);return (21);
if ($response && $response['status'] == 'ok') {
$data = $response['data'];
$shopData = $data['shop'];
if (!empty($shopData)) {
DB::table('shops')->where('id', $shopid)->update([
'shopID' => $shopData['shopID'],
'INN' => $shopData['INN'],
'shopName' => $shopData['shopName'],
]);
DB::table('stores')->where('storeID', $storesid)->update(['storeName' => $shopData['storeName']]);
}
$categories = $data['categories'];
if (!empty($categories))
// DB::table('categories')->where('cShop', $shopid)->delete();
foreach ($categories as $category) {
if ($category['shop'] != $shopid) return $this->getStoresCat($request, $JWT, $shopid, $storesid, "Не удалось обновить каталог товаров, сервис синхронизации предоставил некорректные данные!
");
DB::insert(
"INSERT INTO `categories` (`cShop`,`catOnesID`,`parent`,`catName`) VALUES (?,?,?,?) ON DUPLICATE KEY UPDATE `parent`=?, `catName`=?",
[$shopid, $category['catID'], $category['parent'], $category['catName'], $category['parent'], $category['catName']]
);
}
$brands = $data['brand'];
if (!empty($brands))
foreach ($brands as $brand => $val) {
DB::insert("INSERT IGNORE INTO `brands` (`brandName`) VALUES (?)", [$brand]);
}
$goods = $data['goods'];
if (!empty($goods)) {
// DB::table('goods')->where('gShop', $shopid)->delete();
foreach ($goods as $product) {
if (!isset($cats[$product['catOnesID']])) $cats[$product['catOnesID']] = DB::table('categories')->where('catOnesID', $product['catOnesID'])->value('catID');
$brandID = DB::table('brands')->where('brandName', $product['brand'])->value('brandID');
DB::insert(
"INSERT INTO `goods` (`gOnesID`,`gShop`,`name`,`category`,`brand`,`description`,`price`,`currency`,`unit`,`photos`) VALUES (?,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE `name`=?,`category`=?,`brand`=?,`description`=?,`price`=?,`currency`=?,`unit`=?",
[
$product['gOnesID'], $shopid, $product['name'], $cats[$product['catOnesID']], $brandID,
$product['description'], $product['price'], $product['currency'], $product['unit'], "",
$product['name'], $cats[$product['catOnesID']], $brandID, $product['description'], $product['price'],
$product['currency'], $product['unit']
]
);
}
}
$catalogue = $data['catalogue'];
// $i=1;
if (!empty($catalogue)) {
DB::table('catalogue')->where('cShop', $shopid)->where('store', $storesid)->delete();
foreach ($catalogue as $catRec) {
if (!isset($cats[$catRec['catOnesID']])) $cats[$catRec['catOnesID']] = DB::table('categories')->where('catOnesID', $catRec['catOnesID'])->value('catID');
if (!isset($gds[$catRec['gOnesID']])) $gds[$catRec['gOnesID']] = DB::table('goods')->where('gOnesID', $catRec['gOnesID'])->value('goodsID');
$insRes = DB::insert(
"INSERT INTO `catalogue` (`catID`,`cShop`,`goodsID`,`store`,`num`) VALUES (?,?,?,?,?) ON DUPLICATE KEY UPDATE `catID`=?, `num`=?",
[$cats[$catRec['catOnesID']], $shopid, $gds[$catRec['gOnesID']], $storesid, $catRec['num'], $cats[$catRec['catOnesID']], $catRec['num']]
);
// print_r($catalogue);return
// echo $i++.". INSERT INTO `catalogue` (`catID`,`cShop`,`goodsID`,`store`,`num`) VALUES ('".$cats[$catRec['catOnesID']]."', '".$shopid."', '".$gds[$catRec['gOnesID']]."', '".$storesid."', '".$catRec['num']."') ON DUPLICATE KEY UPDATE `catID`='".$cats[$catRec['catOnesID']]."', `num`='".$catRec['num']."'\n";
}
}
} else {
if ($response['status'] == 'not ready')
switch ($response['code']) {
case '-1':
$msg = ", данные для этой торговой точки или склада не выгружались";
break;
case '0':
$msg = ", нет новых данных";
break;
case '1':
$msg = ", данные обновляются, запросите данные позже";
break;
case '2':
$msg = ", вы вообще никогда не должны были увидеть это сообщение об ошибке, свяжитесь с разработчиками";
break;
default:
$msg = ", неизвестная ошибка, свяжитесь с разработчиками";
}
if ($response['status'] == 'not found') $msg = ", текущие данные уже были загружены";
$msg = "Не удалось обновить каталог товаров точки$msg
";
}
return $this->getStoresCat($request, $JWT, $shopid, $storesid, $msg);
}
function getAttachBlock($files)
{
$attach = '';
if (!empty($files)) {
$tmp = json_decode($files, true);
foreach ($tmp as $val)
$attach .= "\n\t$val";
} else $attach = "\n\tвложений нет\n\t";
$attach = "
\n\t";
return $attach;
}
public function getMsg($JWT, $where, $mid)
{
$this->setUserData($JWT);
$msg = DB::table('messages')->where('id', $mid)->first();
$from = DB::table('users')->where('id', $msg->from)->first();
$to = DB::table('users')->where('id', $msg->to)->first();
if (!$msg->parent) $msg->parent = $mid;
if (mb_stripos($msg->title, 'Re') !== false) $title = $msg->title;
else $title = 'Re: ' . $msg->title;
$where = $msg->status;
if ($where == 'wait') $where = 'unread';
// return response(344);
if ($msg) {
$attachments = $this->getAttachBlock($msg->files);
$form = "
Тема: {$msg->title}
От: {$from->firstName} {$from->secondName} {$from->lastName}
Отправлено: {$msg->sentDate}
Сообщение:
{$msg->message}
$attachments
\n\t";
} else return response("Запись не найдена!
");
return $this->getResponse($form, 'Сообщение #' . $mid);
}
public function getMsgThread($JWT, $where, $tid)
{
$this->setUserData($JWT);
$tread = '';
$root = '';
$msg = DB::table('messages')->where('id', $tid)->first();
$from = DB::table('users')->where('id', $msg->from)->first();
if ($this->uid != $msg->from) $parentFrom = $msg->from;
else $parentFrom = $msg->to;
$to = DB::table('users')->where('id', $msg->to)->first();
$userArray[$msg->from] = "{$from->firstName} {$from->secondName} {$from->lastName}";
$userArray[$msg->to] = "{$to->firstName} {$to->secondName} {$to->lastName}";
if (!$msg->parent) $msg->parent = $tid;
if (mb_stripos($msg->title, 'Re') !== false) $title = $msg->title;
else $title = 'Re: ' . $msg->title;
$where = $msg->status;
// return response($userArray);
if ($msg) {
$attachments = $this->getAttachBlock($msg->files);
$root = "
Тема: {$msg->title}
От: {$from->firstName} {$from->secondName} {$from->lastName}
Отправлено: {$msg->sentDate}
Сообщение:
{$msg->message}
$attachments
\n\t\t";
} else return response("Запись не найдена!
");
$msgs = DB::table('messages')->where('parent', $tid)->get();
foreach ($msgs as $msg) {
$attachments = $this->getAttachBlock($msg->files);
$tread .= "
Тема: {$msg->title}
От: {$userArray[$msg->from]}
Отправлено: {$msg->sentDate}
Сообщение:
{$msg->message}
$attachments
\n\t\t";
}
$form = "
$root
$tread
\n\t";
return $this->getResponse($form, 'Нитка сообщений #' . $tid);
}
}