Commit 5b8f23d2 authored by hangjun83's avatar hangjun83

openapi

parent 3e4efe21
<?php
/**
* Created by PhpStorm.
* User: jun.hang
* Date: 2018/9/17
* Time: 下午11:44
*/
namespace App\Console\Commands;
use App\Jobs\InteglePlatformJob;
use App\Jobs\WuxiLabJob;
use Illuminate\Console\Command;
use Illuminate\Console\ConfirmableTrait;
class IntegleJobCommand extends Command
{
use ConfirmableTrait;
/**
* 命令行的名称及用法。
*
* @var string
*/
protected $signature = 'integle:job
{--action_type= : 任务操作类型}
{--params= : 任务参数}';
/**
* 命令行的概述。
*
* @var string
*/
protected $description = '';
/**
* 创建新的命令实例。
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* 运行命令。
* @throws \Exception
*/
public function handle()
{
if (! $this->confirmToProceed()) {
return 1;
}
if($this->hasArgument('help')){
$this->help();
}else{
$action_type = $this->option('action_type');
$params = $this->option('params');
if(empty($action_type)){
$this->error('缺少命令参数,请输入具体的参数命令.如需帮助请输入 --help');
exit;
}
$productUpdateJob = (new InteglePlatformJob($action_type,$params))->delay(100)->onQueue('slow');
app('Illuminate\Contracts\Bus\Dispatcher')->dispatch($productUpdateJob);
}
}
public function help()
{
$helpStr = "参数帮助说明";
$this->comment($this->setHelp($helpStr)->getProcessedHelp());
$this->line("action_type: 具体动作参数\n\nbatchUpdateProduct => 批量更新商品\n\nparams : 操作需要传入的参数.非必填项");
}
}
<?php
namespace App\Console\Commands;
use App\Services\Kafka\KafkaService;
use Illuminate\Console\Command;
use Illuminate\Console\ConfirmableTrait;
class KafkaConsumerCommand extends Command
{
use ConfirmableTrait;
/**
* 命令行的名称及用法。
*
* @var string
*/
protected $signature = 'kafka:consumer';
/**
* 命令行的概述。
*
* @var string
*/
protected $description = 'kafka 消费模式';
/**
* 创建新的命令实例。
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* 运行命令。
* @throws \Exception
*/
public function handle()
{
if (! $this->confirmToProceed()) {
return 1;
}
//开启消费者模式
app(KafkaService::class)->startConsumer();
}
}
<?php
namespace App\Console\Commands;
use App\Jobs\WuxiLabJob;
use Illuminate\Console\Command;
use Illuminate\Console\ConfirmableTrait;
class WuxiLabJobCommand extends Command
{
use ConfirmableTrait;
/**
* 命令行的名称及用法。
*
* @var string
*/
protected $signature = 'wuxilab:job
{--action_type= : 任务操作类型}
{--params= : 任务参数}';
/**
* 命令行的概述。
*
* @var string
*/
protected $description = '药名康德任务命令行';
/**
* 创建新的命令实例。
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* 运行命令。
* @throws \Exception
*/
public function handle()
{
if (! $this->confirmToProceed()) {
return 1;
}
if($this->hasArgument('help')){
$this->help();
}else{
$action_type = $this->option('action_type');
$params = $this->option('params');
if(empty($action_type)){
$this->error('缺少命令参数,请输入具体的参数命令.如需帮助请输入 --help');
exit;
}
$productUpdateJob = (new WuxiLabJob($action_type,$params))->delay(100)->onQueue('slow');
app('Illuminate\Contracts\Bus\Dispatcher')->dispatch($productUpdateJob);
}
}
public function help()
{
$helpStr = "参数帮助说明";
$this->comment($this->setHelp($helpStr)->getProcessedHelp());
$this->line("action_type: 具体动作参数\n\n initProductToExcel => 初始化批量商品 \n batchUpdateProduct => 批量更新商品\n\nparams : 操作需要传入的参数.非必填项");
}
}
......@@ -22,7 +22,7 @@ class Kernel extends ConsoleKernel
* @var array
*/
protected $commands = [
\Laravelista\LumenVendorPublish\VendorPublishCommand::class
\Laravelista\LumenVendorPublish\VendorPublishCommand::class,
];
/**
......
<?php
namespace App\Export;
use App\Services\SysLogService;
use Maatwebsite\Excel\Facades\Excel;
use Maatwebsite\Excel\Excel as BaseExcel;
/**
* 导出基础类
*/
class BaseExport
{
protected $expand = '';
public function __construct()
{
$this->setFileExpand(BaseExcel::XLSX);
}
public function setFileExpand($name)
{
$this->expand = $name;
}
public function storeExcel($excelContent, $filePath, $diskType = null){
if($diskType == null){
$diskType = config('filesystem.default');
}
$result = Excel::store($excelContent,$filePath,$diskType, $this->expand);
$logContent = [
'filePath' => $filePath,
'diskType' => $diskType,
'datetime' => time()
];
app(SysLogService::class)->addOperationLogs($logContent);
}
}
<?php
namespace App\Export\WuxiLab\Models;
use Maatwebsite\Excel\Concerns\FromArray;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithHeadings;
class WuxiLabPackagesExportModel implements FromArray,WithHeadings, ShouldAutoSize
{
private $exportContent = [];
public function __construct($exportContent)
{
$this->setExportContent($exportContent);
}
public function setExportContent($content)
{
$this->exportContent = $this->toMap($content);
}
public function array(): array
{
return $this->exportContent;
}
public function toMap($rows): array
{
$exportRows = [];
foreach($rows as $key => $row){
array_push($exportRows,[
$row['r_code'], '', $row['p_pack'].'/'.$row['p_pack_unit'], $row['p_stock'] == 0 ? '0' : $row['p_stock'], 'CN-SH', $row['p_price'], $row['p_avg_cost'],
'RMB', 'CN', '0.00'
]);
}
return $exportRows;
}
public function headings(): array
{
return $this->getHeaderTitle();
}
private function getHeaderTitle()
{
return [
'ProductId', 'PackageItemNumber', 'PackageUnitDescription', 'PackageStockQuantity', 'PackageStockLocation', 'ListPrice', 'discount', 'Currency', 'PriceCountry',
'LNCost'
];
}
}
<?php
namespace App\Export\WuxiLab\Models;
use Maatwebsite\Excel\Concerns\FromArray;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithHeadings;
class WuxiLabProductsExportModel implements FromArray,WithHeadings, ShouldAutoSize
{
private $exportContent = [];
public function __construct($exportContent)
{
$this->setExportContent($exportContent);
}
public function setExportContent($content)
{
$this->exportContent = $this->toMap($content);
}
public function array(): array
{
return $this->exportContent;
}
public function toMap($rows): array
{
$exportRows = [];
foreach($rows as $key => $row){
array_push($exportRows,[
$row['r_code'], $row['c_cas'], $row['c_mdl'], $row['c_fzs'], $row['c_fzl'], 'N/A', '',
$row['c_en_name'], $row['c_cn_name'], 'rhawn', '0', '0', '0', 1, 3, '', $row['r_level'], 'AMINO_ACIDS_PEPTIDES', ''
]);
}
return $exportRows;
}
public function headings(): array
{
return $this->getHeaderTitle();
}
private function getHeaderTitle()
{
return [
'ProductId', 'CAS', 'MDL', 'MolecularFormula', 'MolecularWeight', 'ComplianceType', 'UN', 'EnglishName', 'ChineseName', 'Brand', 'StorageCondition',
'TransportationCondition', 'IsImported', 'LeadTimeMinDays', 'LeadTimeMaxDays', 'LeadTimeBackOrderDays', 'Purity', 'ProductCategory',
'ShipsAdditionalDescription'
];
}
}
<?php
namespace App\Export\WuxiLab\Models;
use Maatwebsite\Excel\Concerns\FromArray;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithHeadings;
class WuxiLabStocksExportModel implements FromArray,WithHeadings, ShouldAutoSize
{
private $exportContent = [];
public function __construct($exportContent)
{
$this->setExportContent($exportContent);
}
public function setExportContent($content)
{
$this->exportContent = $this->toMap($content);
}
public function array(): array
{
return $this->exportContent;
}
public function toMap($rows): array
{
$exportRows = [];
foreach($rows as $key => $row){
array_push($exportRows,[
$row['r_code'], 'CN', $row['p_pack_unit'], $row['p_stock'] == 0 ? '0' : $row['p_stock']
]);
}
return $exportRows;
}
public function headings(): array
{
return $this->getHeaderTitle();
}
private function getHeaderTitle()
{
return [
'ProductId', 'StockCountry', 'StockUnits', 'StockQuantity'
];
}
}
<?php
namespace App\Export\WuxiLab;
use App\Export\BaseExport;
use App\Export\WuxiLab\Models\WuxiLabPackagesExportModel;
use App\Export\WuxiLab\Models\WuxiLabProductsExportModel;
use App\Export\WuxiLab\Models\WuxiLabStocksExportModel;
class WuxiLabExport extends BaseExport
{
protected $defaultExportModel = ['product','package','stock'];
protected $filePath = '';
public function __construct()
{
parent::__construct();
}
public function getSavePath($fileName)
{
if($this->filePath == ''){
$this->filePath = config('filesystem.default').'/public/Excel/';
}
return $this->filePath.date('Ymd',time()).'/'.$fileName;
}
public function getFileName($model)
{
return 'wuxiLab_'.$model.'_'.date('Y_m_d_His',time()).'.'.$this->expand;
}
/**
* 存储到excel文件
* @param $saveContent
* @param null $model
*/
public function saveExcel($saveContent,$model = null)
{
if($model == null){
$model = $this->defaultExportModel;
}
if(!is_array($model) && $model != null){
$model = explode(',',$model);
}
foreach($model as $m){
switch($m){
case 'product' :
$export = new WuxiLabProductsExportModel($saveContent['rawList']);
break;
case 'package' :
$export = new WuxiLabPackagesExportModel($saveContent['packageList']);
break;
case 'stock' :
$export = new WuxiLabStocksExportModel($saveContent['packageList']);
break;
}
$savePath = $this->getSavePath(
$this->getFileName($m)
);
$this->storeExcel($export,$savePath);
}
}
}
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Jobs;
use App\Repositories\Contracts\BhSorderRefundRepository;
use App\Services\BhOrdersService;
use Illuminate\Support\Facades\DB;
class BhSorderRefundJob extends Job
{
protected $refundInfo;
public function __construct($refundInfo)
{
$this->refundInfo = $refundInfo;
}
/**
* Execute the job.
*/
public function handle()
{
try{
app(BhSorderRefundRepository::class)->update(['status' => 'running'],$this->refundInfo['id']);
$note = null;
$refundInfo = json_decode($this->refundInfo['exec_content']);
$service = app(BhOrdersService::class);
$service->sOrderRefund($refundInfo,$note);
//对任务进行更新
$update = [];
$update['status'] = 'finish';
$update['exec_nums'] = $this->refundInfo['exec_nums'] + 1;
$update['error_message'] = '';
if($note && count($note) > 0){
$update['error_message'] = json_encode($note,JSON_UNESCAPED_UNICODE);
}
}catch(\Exception $e){
//对任务进行更新
$update = [];
$update['status'] = 'error';
$update['error_message'] = $e->getMessage();
$update['exec_nums'] = intval($this->refundInfo['exec_nums'] + 1);
}
try{
$db = DB::connection('mysql');
$db->beginTransaction();
$update['updated_at'] = date('Y-m-d H:i:s',time());
app(BhSorderRefundRepository::class)->update($update,$this->refundInfo['id']);
$logInsert = [];
$logInsert['task_id'] = $this->refundInfo['id'];
if(isset($update['error_message']) && !empty($update['error_message'])){
$logInsert['content'] = $update['error_message'];
}else{
$logInsert['content'] = '执行完成';
}
$logInsert['created_at'] = date('Y-m-d H:i:s',time());
$logInsert['updated_at'] = date('Y-m-d H:i:s',time());
$db->table('task_log')->insertGetId($logInsert);
$db->commit();
}catch(\Exception $e){
$db->rollback();
throw $e;
}
}
}
......@@ -11,19 +11,27 @@
namespace App\Jobs;
class ExampleJob extends Job
use App\Services\InteglePlatformService;
class InteglePlatformJob extends Job
{
/**
* Create a new job instance.
*/
public function __construct()
protected $actionType = null;
protected $params = null;
public function __construct($actionType,$params)
{
$this->actionType = $actionType;
$this->params = $params;
}
/**
* Execute the job.
*/
public function handle()
{
$service = app(InteglePlatformService::class);
switch($this->actionType){
case 'batchUpdateProduct' :
$service->batchUpdateProducts();
break;
default:
}
}
}
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Jobs;
use App\Repositories\Contracts\RhawnSorderRefundRepository;
use App\Services\RhawnOrdersService;
use Illuminate\Support\Facades\DB;
class RhawnSorderRefundJob extends Job
{
protected $refundInfo;
public function __construct($refundInfo)
{
$this->refundInfo = $refundInfo;
}
/**
* Execute the job.
*/
public function handle()
{
try{
app(RhawnSorderRefundRepository::class)->update(['status' => 'running'],$this->refundInfo['id']);
$note = null;
$refundInfo = json_decode($this->refundInfo['exec_content']);
$service = app(RhawnOrdersService::class);
$service->sOrderRefund($refundInfo,$note);
//对任务进行更新
$update = [];
$update['status'] = 'finish';
$update['exec_nums'] = $this->refundInfo['exec_nums'] + 1;
$update['error_message'] = '';
if($note && count($note) > 0){
$update['error_message'] = json_encode($note,JSON_UNESCAPED_UNICODE);
}
}catch(\Exception $e){
//对任务进行更新
$update = [];
$update['status'] = 'error';
$update['error_message'] = $e->getMessage();
$update['exec_nums'] = intval($this->refundInfo['exec_nums'] + 1);
}
try{
$db = DB::connection('mysql');
$db->beginTransaction();
$update['updated_at'] = date('Y-m-d H:i:s',time());
app(RhawnSorderRefundRepository::class)->update($update,$this->refundInfo['id']);
$logInsert = [];
$logInsert['task_id'] = $this->refundInfo['id'];
if(isset($update['error_message']) && !empty($update['error_message'])){
$logInsert['content'] = $update['error_message'];
}else{
$logInsert['content'] = '执行完成';
}
$logInsert['created_at'] = date('Y-m-d H:i:s',time());
$logInsert['updated_at'] = date('Y-m-d H:i:s',time());
$db->table('task_log')->insertGetId($logInsert);
$db->commit();
}catch(\Exception $e){
$db->rollback();
throw $e;
}
}
}
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Jobs;
use App\Services\WuxiLabService;
class WuxiLabJob extends Job
{
protected $actionType = null;
protected $params = null;
public function __construct($actionType,$params)
{
$this->actionType = $actionType;
$this->params = $params;
}
public function handle()
{
$service = app(WuxiLabService::class);
switch($this->actionType){
case 'initProductToExcel' :
if(!isset($params) || $params == 0){
$params['limit'] = 1000;
}
$service->initCreateProductsToExcel($params['limit']);
break;
case 'batchUpdateProduct' :
$service->batchUpdateProducts();
break;
default:
}
}
}
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Listeners;
use App\Events\ExampleEvent;
class ExampleListener
{
/**
* Create the event listener.
*/
public function __construct()
{
}
/**
* Handle the event.
*
* @param \App\Events\ExampleEvent $event
*/
public function handle(ExampleEvent $event)
{
}
}
......@@ -11,10 +11,10 @@
namespace App\Providers;
use App\Observers\UserObserver;
use App\Repositories\Models\AdminUsers;
use App\Services\Kafka\KafkaService;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;
use Laravel\Lumen\Application as LumenApplication;
class AppServiceProvider extends ServiceProvider
{
......@@ -33,11 +33,28 @@ class AppServiceProvider extends ServiceProvider
public function boot()
{
Schema::defaultStringLength(191);
$this->registerObservers(); // 注册观察者
if( $this->app instanceof LumenApplication ){
$this->app->configure('kafka');
$this->setupConfig();
}
//单例绑定,初始化kafka
$this->app->singleton(KafkaService::class,function($app){
return new KafkaService(config('kafka.kafka'));
});
$this->commands([
\App\Console\Commands\IntegleJobCommand::class,
\App\Console\Commands\WuxiLabJobCommand::class,
\App\Console\Commands\KafkaConsumerCommand::class
]);
}
protected function registerObservers(): void
protected function setupConfig()
{
AdminUsers::observe(UserObserver::class);
$path = dirname(__DIR__, 2).'/config/kafka.php';
$this->mergeConfigFrom($path, 'kafka');
}
}
......@@ -11,45 +11,30 @@
namespace App\Providers;
use App\Repositories\Eloquent\BaseRepository;
use Prettus\Repository\Contracts\RepositoryInterface;
use Illuminate\Filesystem\Filesystem;
use Prettus\Repository\Providers\LumenRepositoryServiceProvider;
class RepositoryServiceProvider extends LumenRepositoryServiceProvider
{
protected $bindsClass =
[
'App\Repositories\Contracts\UsersRepository' => 'App\Repositories\Eloquent\UsersRepositoryEloquent',
'App\Repositories\Contracts\MenusRepository' => 'App\Repositories\Eloquent\MenusRepositoryEloquent',
'App\Repositories\Contracts\RolesRepository' => 'App\Repositories\Eloquent\RolesRepositoryEloquent',
'App\Repositories\Contracts\BhPordersRepository' => 'App\Repositories\Eloquent\BhPordersRepositoryEloquent',
'App\Repositories\Contracts\BhSordersRepository' => 'App\Repositories\Eloquent\BhSordersRepositoryEloquent',
'App\Repositories\Contracts\BhSoitemsRepository' => 'App\Repositories\Eloquent\BhSoitemsRepositoryEloquent',
'App\Repositories\Contracts\BhSorderRefundRepository' => 'App\Repositories\Eloquent\BhSorderRefundRepositoryEloquent',
'App\Repositories\Contracts\ToolsTaskRepository' => 'App\Repositories\Eloquent\ToolsTaskRepositoryEloquent',
'App\Repositories\Contracts\RhawnSordersRepository' => 'App\Repositories\Eloquent\RhawnSordersRepositoryEloquent',
'App\Repositories\Contracts\RhawnSoitemsRepository' => 'App\Repositories\Eloquent\RhawnSoitemsRepositoryEloquent',
'App\Repositories\Contracts\RhawnSorderRefundRepository' => 'App\Repositories\Eloquent\RhawnSorderRefundRepositoryEloquent',
];
/**
* Bootstrap services.
*/
public function boot()
public function register()
{
parent::register(); // TODO: Change the autogenerated stub
$this->bindRepository();
}
protected function bindRepository()
{
if(empty($this->bindsClass)){
return ;
}
foreach($this->bindsClass as $class => $concrete){
$this->app->bind($class,$concrete);
$fileObj = (new Filesystem());
$files = $fileObj->files(base_path('app/Repositories/Contracts'));
if($files){
collect($files)->map(function ($file){
$fileName = $file->getRelativePathname();
list($name,$extend) = explode('.',$fileName);
$class = "App\Repositories\Contracts\\".$name;
$concrete = "App\Repositories\Eloquent\\".$name."Eloquent";
$this->app->bind($class,$concrete);
});
}
}
}
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Repositories\Contracts;
use Prettus\Repository\Contracts\RepositoryInterface;
/**
* Interface UserRepository.
*/
interface BhSorderRefundRepository extends RepositoryInterface
{
}
......@@ -16,6 +16,6 @@ use Prettus\Repository\Contracts\RepositoryInterface;
/**
* Interface UserRepository.
*/
interface BhPordersRepository extends RepositoryInterface
interface RhawnRawRepository extends RepositoryInterface
{
}
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Repositories\Contracts;
use Prettus\Repository\Contracts\RepositoryInterface;
/**
* Interface UserRepository.
*/
interface RhawnSoitemsRepository extends RepositoryInterface
{
}
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Repositories\Contracts;
use Prettus\Repository\Contracts\RepositoryInterface;
/**
* Interface UserRepository.
*/
interface RhawnSorderRefundRepository extends RepositoryInterface
{
}
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Repositories\Contracts;
use Prettus\Repository\Contracts\RepositoryInterface;
/**
* Interface UserRepository.
*/
interface RhawnSordersRepository extends RepositoryInterface
{
}
......@@ -16,6 +16,6 @@ use Prettus\Repository\Contracts\RepositoryInterface;
/**
* Interface UserRepository.
*/
interface BhSordersRepository extends RepositoryInterface
interface ThirdApiPlatformRepository extends RepositoryInterface
{
}
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Repositories\Criteria;
use Illuminate\Database\Eloquent\Builder;
use App\Repositories\Criteria\Criteria;
class BhPordersCriteria extends Criteria
{
protected function condition(Builder $query): void
{
if ($orderNo = $this->request->get('bhOrderNo')) {
$query->where('po_no', '=', $orderNo);
}
}
}
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Repositories\Criteria;
use Illuminate\Database\Eloquent\Builder;
use App\Repositories\Criteria\Criteria;
class BhSorderRefundCriteria extends Criteria
{
protected function condition(Builder $query): void
{
if($this->request->has('type')){
$query->where('type', '=', $this->request->get('type'));
}
}
protected function after($model)
{
$model->orderbyDesc('id');
return $model;
}
}
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Repositories\Criteria;
use Illuminate\Database\Eloquent\Builder;
use App\Repositories\Criteria\Criteria;
class BhSorderRefundTaskLogCriteria extends Criteria
{
protected function condition(Builder $query): void
{
if($this->request->has('type')){
$query->where('type', '=', $this->request->get('type'));
}
}
}
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Repositories\Criteria;
use Illuminate\Database\Eloquent\Builder;
use App\Repositories\Criteria\Criteria;
class RhawnSorderRefundCriteria extends Criteria
{
protected function condition(Builder $query): void
{
if($this->request->has('type')){
$query->where('type', '=', $this->request->get('type'));
}
}
protected function after($model)
{
$model->orderbyDesc('id');
return $model;
}
}
<?php
namespace App\Repositories\Eloquent;
use App\Repositories\Contracts\BhSoitemsRepository;
use App\Repositories\Contracts\BhSordersRepository;
use App\Repositories\Criteria\RequestCriteria;
use App\Repositories\Models\BhSoitems;
use App\Repositories\Eloquent\BaseRepository;
use Prettus\Validator\Contracts\ValidatorInterface;
/**
* Class UserRepositoryEloquent.
*/
class BhSoitemsRepositoryEloquent extends BaseRepository implements BhSoitemsRepository
{
protected $fieldSearchable = [
];
/**
* Specify Model class name.
*
* @return string
*/
public function model()
{
return BhSoitems::class;
}
/**
* Boot up the repository, pushing criteria.
*
* @throws \Prettus\Repository\Exceptions\RepositoryException
*/
public function boot()
{
$this->pushCriteria(app(RequestCriteria::class));
}
/**
* 获取订单详情
* @param $orderId
* @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
*/
public function getSorderItemsDetailFromOrderId($orderId)
{
$order = app(BhSordersRepository::class)->find($orderId);
if(!$order){
throw new \LogicException('该订单不存在!',500);
}
//查询订单的详情
$soItems = BhSoitems::query()
->join('products','soitems.p_id','products.p_id')
->join('chemicals','products.c_id','chemicals.c_id')
->join('brands','products.b_id','brands.b_id')
->where('soitems.so_id',$order->so_id)->get();
return $soItems;
}
public function getSorderItemsDetailFromItemId($itemId,$pid=null)
{
//查询订单的详情
$soItems = BhSoitems::query()
->join('sorders','sorders.so_id','soitems.so_id')
->join('products','soitems.p_id','products.p_id')
->join('chemicals','products.c_id','chemicals.c_id')
->join('brands','products.b_id','brands.b_id')
->where('soitems.si_id',$itemId);
if(!is_null($pid)){
$soItems = $soItems->where('soitems.p_id',$pid);
}
$soItems = $soItems->get();
return $soItems;
}
/**
* 根据si_id获取订单明细项
* @param $si_id
* @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
*/
public function getSorderItemFromItemId($si_id)
{
$item = $this->find($si_id);
if(!$item){
throw new \LogicException('该订单项不存在!',500);
}
//查询订单的详情
$soItems = BhSoitems::query()
->join('products','soitems.p_id','products.p_id')
->where('soitems.si_id',$si_id)->get();
return $soItems;
}
}
<?php
namespace App\Repositories\Eloquent;
use App\Repositories\Contracts\BhSordersRepository;
use App\Repositories\Criteria\RequestCriteria;
use App\Repositories\Models\BhSorders;
use App\Repositories\Eloquent\BaseRepository;
use Illuminate\Support\Facades\DB;
use Prettus\Validator\Contracts\ValidatorInterface;
/**
* Class UserRepositoryEloquent.
*/
class BhSordersRepositoryEloquent extends BaseRepository implements BhSordersRepository
{
protected $fieldSearchable = [
];
/**
* Specify Model class name.
*
* @return string
*/
public function model()
{
return BhSorders::class;
}
/**
* Boot up the repository, pushing criteria.
*
* @throws \Prettus\Repository\Exceptions\RepositoryException
*/
public function boot()
{
$this->pushCriteria(app(RequestCriteria::class));
}
/**
* 返回指定订单编号的订单信息
* @param $order_no
* @return mixed
*/
public function getSorderFromOrderNo($orderNo)
{
$where = [
'so_no' => $orderNo
];
return $this->findWhere($where)->first();
}
/**
* 获取订单详情
* @param $orderNo
* @return mixed
*/
public function getSorderItemsFromOrderNo($orderNo){
$soItems = $this
->join('soitems','soitems.so_id','sorders.so_id')
->where('sorders.so_no',$orderNo)->get();
return $soItems;
}
/**
* 获取订单相关信息(包括,产品,客户,品牌等)
* @param $so_id
* @return mixed
*/
public function getSorderDetailFromOrderId($so_id)
{
$sOrderInfo = $this
->join('customers','sorders.cus_id','customers.cus_id')
->where('sorders.so_id',$so_id)
->get();
if(!$sOrderInfo){
return ;
}
$sOrderInfo = current($sOrderInfo->toArray());
$items = DB::connection('bh_mysql')->table('soitems')
->join('products','soitems.p_id','products.p_id')
->join('chemicals','products.c_id','chemicals.c_id')
->join('brands','products.b_id','brands.b_id')
->where('soitems.so_id',$so_id)
->get();
if(!$items){
$sOrderInfo['items'] = [];
}
$sOrderInfo['items'] = $items->toArray();
return $sOrderInfo;
}
}
......@@ -2,18 +2,19 @@
namespace App\Repositories\Eloquent;
use App\Repositories\Contracts\BhSorderRefundRepository;
use App\Repositories\Contracts\RhawnRawRepository;
use App\Repositories\Criteria\RequestCriteria;
use App\Repositories\Models\BhSorderRefund;
use App\Repositories\Eloquent\BaseRepository;
use App\Repositories\Models\RhawnProducts;
use App\Repositories\Models\RhawnRaw;
use Illuminate\Support\Facades\DB;
use Prettus\Validator\Contracts\ValidatorInterface;
/**
* Class UserRepositoryEloquent.
*/
class BhSorderRefundRepositoryEloquent extends BaseRepository implements BhSorderRefundRepository
class RhawnRawRepositoryEloquent extends BaseRepository implements RhawnRawRepository
{
protected $fieldSearchable = [
];
......@@ -25,7 +26,7 @@ class BhSorderRefundRepositoryEloquent extends BaseRepository implements BhSorde
*/
public function model()
{
return BhSorderRefund::class;
return RhawnRaw::class;
}
/**
......@@ -38,49 +39,34 @@ class BhSorderRefundRepositoryEloquent extends BaseRepository implements BhSorde
$this->pushCriteria(app(RequestCriteria::class));
}
/**
* 添加退款任务
* @param $request
*/
public function addRefundTask($params)
{
if(empty($params)){
throw new \LogicException('参数为空!',500);
}
$task = [];
$task['name'] = $params['name'];
unset($params['name']);
public function total(){
return $this->count();
}
$task['exec_content'] = json_encode($params);
$task['create_by'] = auth()->user()->id;
$task['status'] = 'notexec';
$task['type'] = 'sorder_refund';
public function getRawProductList($pageSize = 1000, $offset = 0)
{
$rawList = RhawnRaw::query()
->join('chemicals', 'chemicals.c_id','raw.c_id')
->offset($offset)
->limit($pageSize)
->get();
if(isset($params['task_id']) && !empty($params['task_id'])){
$id = $params['task_id'];
return $this->update($task,$id);
}else{
return $this->create($task);
}
return $rawList->toArray();
}
public function delRefundTask($params)
public function getProductPackage($rawProductIds)
{
if(empty($params)){
throw new \LogicException('参数为空!',500);
}
$packagesList = RhawnProducts::query()
->join('raw','raw.r_id','products.r_id')
->join('chemicals', 'chemicals.c_id','raw.c_id');
DB::beginTransaction();
try{
$this->delete($params['task_id']);
DB::table('task_log')
->where('task_id',$params['task_id'])
->delete();
DB::commit();
}catch(\Exception $e){
DB::rollback();
if(is_array($rawProductIds)){
$packagesList = $packagesList->whereIn('raw.r_id',$rawProductIds);
}else{
$packagesList = $packagesList->where('raw.r_id',$rawProductIds);
}
$packagesList = $packagesList->get();
return $packagesList->toArray();
}
}
<?php
namespace App\Repositories\Eloquent;
use App\Repositories\Contracts\RhawnSoitemsRepository;
use App\Repositories\Contracts\RhawnSordersRepository;
use App\Repositories\Criteria\RequestCriteria;
use App\Repositories\Eloquent\BaseRepository;
use App\Repositories\Models\RhawnSoitems;
use Prettus\Validator\Contracts\ValidatorInterface;
/**
* Class UserRepositoryEloquent.
*/
class RhawnSoitemsRepositoryEloquent extends BaseRepository implements RhawnSoitemsRepository
{
protected $fieldSearchable = [
];
/**
* Specify Model class name.
*
* @return string
*/
public function model()
{
return RhawnSoitems::class;
}
/**
* Boot up the repository, pushing criteria.
*
* @throws \Prettus\Repository\Exceptions\RepositoryException
*/
public function boot()
{
$this->pushCriteria(app(RequestCriteria::class));
}
/**
* 获取订单详情
* @param $orderId
* @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
*/
public function getSorderItemsDetailFromOrderId($orderId)
{
$order = app(RhawnSordersRepository::class)->find($orderId);
if(!$order){
throw new \LogicException('该订单不存在!',500);
}
//查询订单的详情
$soItems = RhawnSoitems::query()
->join('products','soitems.p_id','products.p_id')
->join('chemicals','products.c_id','chemicals.c_id')
->join('brands','products.b_id','brands.b_id')
->where('soitems.so_id',$order->so_id)->get();
return $soItems;
}
public function getSorderItemsDetailFromItemId($itemId,$pid=null)
{
//查询订单的详情
$soItems = RhawnSoitems::query()
->join('sorders','sorders.so_id','soitems.so_id')
->join('products','soitems.p_id','products.p_id')
->join('chemicals','products.c_id','chemicals.c_id')
->join('brands','products.b_id','brands.b_id')
->where('soitems.si_id',$itemId);
if(!is_null($pid)){
$soItems = $soItems->where('soitems.p_id',$pid);
}
$soItems = $soItems->get();
return $soItems;
}
/**
* 根据si_id获取订单明细项
* @param $si_id
* @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
*/
public function getSorderItemFromItemId($si_id)
{
$item = $this->find($si_id);
if(!$item){
throw new \LogicException('该订单项不存在!',500);
}
//查询订单的详情
$soItems = RhawnSoitems::query()
->join('products','soitems.p_id','products.p_id')
->where('soitems.si_id',$si_id)->get();
return $soItems;
}
public function getOrderItemsStockFromItemIds($id)
{
if(!is_array($id)){
$item = $this->find($id);
$id = (array)$id;
}else{
$item = RhawnSoitems::query()->whereIn('si_id',$id)->get();
}
if(!$item){
throw new \LogicException('该订单项不存在!',500);
}
//查询订单的详情
$soItemStock = RhawnSoitems::query()
->join('dpdetail','dpdetail.si_id','soitems.si_id')
->join('pstock','pstock.pstk_id','dpdetail.pstk_id')
->join('products','soitems.p_id','products.p_id')
->whereIn('soitems.si_id',$id)
->where('si_if_cancel',0)
//->where('dpdetail.dpd_invoiced','=',0)
->get();
return $soItemStock;
}
}
<?php
namespace App\Repositories\Eloquent;
use App\Repositories\Contracts\RhawnSorderRefundRepository;
use App\Repositories\Criteria\RequestCriteria;
use App\Repositories\Models\RhawnSorderRefund;
use App\Repositories\Eloquent\BaseRepository;
use Illuminate\Support\Facades\DB;
use Prettus\Validator\Contracts\ValidatorInterface;
/**
* Class UserRepositoryEloquent.
*/
class RhawnSorderRefundRepositoryEloquent extends BaseRepository implements RhawnSorderRefundRepository
{
protected $fieldSearchable = [
];
/**
* Specify Model class name.
*
* @return string
*/
public function model()
{
return RhawnSorderRefund::class;
}
/**
* Boot up the repository, pushing criteria.
*
* @throws \Prettus\Repository\Exceptions\RepositoryException
*/
public function boot()
{
$this->pushCriteria(app(RequestCriteria::class));
}
/**
* 添加退款任务
* @param $request
*/
public function addRefundTask($params)
{
if(empty($params)){
throw new \LogicException('参数为空!',500);
}
$task = [];
$task['name'] = $params['name'];
unset($params['name']);
$task['exec_content'] = json_encode($params);
$task['create_by'] = auth()->user()->id;
$task['status'] = 'notexec';
$task['type'] = 'rhawn_sorder_refund';
if(isset($params['task_id']) && !empty($params['task_id'])){
$id = $params['task_id'];
return $this->update($task,$id);
}else{
return $this->create($task);
}
}
public function delRefundTask($params)
{
if(empty($params)){
throw new \LogicException('参数为空!',500);
}
DB::beginTransaction();
try{
$this->delete($params['task_id']);
DB::table('task_log')
->where('task_id',$params['task_id'])
->delete();
DB::commit();
}catch(\Exception $e){
DB::rollback();
}
}
}
<?php
namespace App\Repositories\Eloquent;
use App\Repositories\Contracts\RhawnSordersRepository;
use App\Repositories\Criteria\RequestCriteria;
use App\Repositories\Models\RhawnSorders;
use App\Repositories\Eloquent\BaseRepository;
use Illuminate\Support\Facades\DB;
use Prettus\Validator\Contracts\ValidatorInterface;
/**
* Class UserRepositoryEloquent.
*/
class RhawnSordersRepositoryEloquent extends BaseRepository implements RhawnSordersRepository
{
protected $fieldSearchable = [
];
/**
* Specify Model class name.
*
* @return string
*/
public function model()
{
return RhawnSorders::class;
}
/**
* Boot up the repository, pushing criteria.
*
* @throws \Prettus\Repository\Exceptions\RepositoryException
*/
public function boot()
{
$this->pushCriteria(app(RequestCriteria::class));
}
/**
* 返回指定订单编号的订单信息
* @param $order_no
* @return mixed
*/
public function getSorderFromOrderNo($orderNo)
{
$where = [
'so_no' => $orderNo
];
return $this->findWhere($where)->first();
}
/**
* 获取订单详情
* @param $orderNo
* @return mixed
*/
public function getSorderItemsFromOrderNo($orderNo){
$soItems = $this
->join('soitems','soitems.so_id','sorders.so_id')
->where('sorders.so_no',$orderNo)->get();
return $soItems;
}
/**
* 获取订单相关信息(包括,产品,客户,品牌等)
* @param $so_id
* @return mixed
*/
public function getSorderDetailFromOrderId($so_id)
{
$sOrderInfo = $this
->join('customers','sorders.cus_id','customers.cus_id')
->where('sorders.so_id',$so_id)
->get();
if(!$sOrderInfo){
return ;
}
$sOrderInfo = current($sOrderInfo->toArray());
$items = DB::connection('bh_mysql')->table('soitems')
->join('products','soitems.p_id','products.p_id')
->join('chemicals','products.c_id','chemicals.c_id')
->join('brands','products.b_id','brands.b_id')
->where('soitems.so_id',$so_id)
->get();
if(!$items){
$sOrderInfo['items'] = [];
}
$sOrderInfo['items'] = $items->toArray();
return $sOrderInfo;
}
}
......@@ -2,20 +2,21 @@
namespace App\Repositories\Eloquent;
use App\Repositories\Contracts\BhPordersRepository;
use App\Repositories\Contracts\ThirdApiPlatformRepository;
use App\Repositories\Criteria\RequestCriteria;
use App\Repositories\Models\BhPorders;
use App\Repositories\Eloquent\BaseRepository;
use Illuminate\Support\Facades\DB;
use App\Repositories\Models\ThirdApiPlatform;
use Illuminate\Container\Container as Application;
use Prettus\Validator\Contracts\ValidatorInterface;
/**
* Class UserRepositoryEloquent.
*/
class BhPordersRepositoryEloquent extends BaseRepository implements BhPordersRepository
class ThirdApiPlatformRepositoryEloquent extends BaseRepository implements ThirdApiPlatformRepository
{
protected $fieldSearchable = [
'platform_name', 'platform_title',
];
/**
......@@ -24,29 +25,26 @@ class BhPordersRepositoryEloquent extends BaseRepository implements BhPordersRep
*/
public $rules = [
ValidatorInterface::RULE_CREATE => [
'menu_name' => 'required',
'title' => 'required',
'menu_path' => 'required',
'parent_id' => 'required',
'menu_type' => 'required',
'status' => 'required',
'sort' => 'required',
'is_show' => 'required',
'sys_default' => 'required'
'platform_name' => 'required',
'platform_title' => 'required',
'platform_type' => 'required',
'platform_token' => 'required',
'platform_status' => 'required',
],
ValidatorInterface::RULE_UPDATE => [
'menu_name' => 'required',
'title' => 'required',
'menu_path' => 'required',
'parent_id' => 'required',
'menu_type' => 'required',
'status' => 'required',
'sort' => 'required',
'is_show' => 'required',
'sys_default' => 'required'
'platform_name' => 'required',
'platform_title' => 'required',
'platform_type' => 'required',
'platform_token' => 'required',
'platform_status' => 'required',
]
];
public function __construct(Application $app)
{
parent::__construct($app);
}
/**
* Specify Model class name.
*
......@@ -54,7 +52,7 @@ class BhPordersRepositoryEloquent extends BaseRepository implements BhPordersRep
*/
public function model()
{
return BhPorders::class;
return ThirdApiPlatform::class;
}
/**
......@@ -67,27 +65,13 @@ class BhPordersRepositoryEloquent extends BaseRepository implements BhPordersRep
$this->pushCriteria(app(RequestCriteria::class));
}
/**
* 获取采购订单详情
* @param $po_id
* @return array
*/
public function getPorderItemsFromPoId($po_id,$pi_id = null)
public function getPlatformInfoByPlatformName($platformName)
{
$pOrder = $this->findWhere(['po_id' => $po_id])->toArray();
$db = DB::connection('bh_mysql');
$rowQueryobj = $db->table('poitems')
->join('products','poitems.p_id','products.p_id')
->join('chemicals','products.c_id','chemicals.c_id')
->join('brands','products.b_id','brands.b_id');
$rowQueryobj->where('poitems.po_id',$po_id);
if(!is_null($pi_id)){
$rowQueryobj->where('poitems.pi_id',$pi_id);
$platformInfo = $this->findWhere(['platform_name' => $platformName]);
if($platformInfo){
$platformInfo = $platformInfo[0];
return $platformInfo->toArray();
}
$pOrder['poitems'] = $rowQueryobj->get()->toArray();
return $pOrder;
return null;
}
}
......@@ -15,4 +15,6 @@ use Jiannei\Enum\Laravel\Repositories\Enums\LogEnum as BaseLogEnum;
class LogEnum extends BaseLogEnum
{
const SYSTEM_OPERATION = 'system:operation';
const SYSTEM_API = 'system:api';
}
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Repositories\Models;
class BhPorders extends Model
{
protected $table = 'porders';
protected $connection = 'bh_mysql';
protected $primaryKey = 'po_id';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'po_sup_order','po_if_direct'
];
protected $guarded = ['updated_at'];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = [
];
/**
* update时不做自动更新时间操作
* @return null
*/
public function getUpdatedAtColumn()
{
return null;
}
}
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Repositories\Models;
class BhSoitems extends Model
{
// 销售订单
protected $table = 'soitems';
protected $connection = 'bh_mysql';
protected $primaryKey = 'si_id';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
];
protected $guarded = ['created_at', 'updated_at'];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = [
];
/**
* update时不做自动更新时间操作
* @return null
*/
public function getUpdatedAtColumn()
{
return null;
}
public function getCreatedAtColumn()
{
return null;
}
}
\ No newline at end of file
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Repositories\Models;
class BhSorderRefund extends Model
{
protected $table = 'tools_task';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'id','name','exec_content','status','error_message','type','exec_nums','create_by'
];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = [
];
}
\ No newline at end of file
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Repositories\Models;
class BhSorders extends Model
{
// 销售订单
protected $table = 'sorders';
protected $connection = 'bh_mysql';
protected $primaryKey = 'so_id';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
];
protected $guarded = ['created_at', 'updated_at'];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = [
];
/**
* update时不做自动更新时间操作
* @return null
*/
public function getUpdatedAtColumn()
{
return null;
}
public function getCreatedAtColumn()
{
return null;
}
}
\ No newline at end of file
......@@ -11,15 +11,15 @@
namespace App\Repositories\Models;
class RhawnSorders extends Model
class RhawnProducts extends Model
{
// 销售订单
protected $table = 'sorders';
// 产品
protected $table = 'products';
protected $connection = 'rhawn_mysql';
protected $primaryKey = 'so_id';
protected $primaryKey = 'p_id';
/**
* The attributes that are mass assignable.
......@@ -29,8 +29,6 @@ class RhawnSorders extends Model
protected $fillable = [
];
protected $guarded = ['created_at', 'updated_at'];
/**
* The attributes excluded from the model's JSON form.
*
......
......@@ -11,15 +11,15 @@
namespace App\Repositories\Models;
class RhawnSoitems extends Model
class RhawnRaw extends Model
{
// 销售订单
protected $table = 'soitems';
// 产品
protected $table = 'raw';
protected $connection = 'rhawn_mysql';
protected $primaryKey = 'si_id';
protected $primaryKey = 'r_id';
/**
* The attributes that are mass assignable.
......@@ -29,8 +29,6 @@ class RhawnSoitems extends Model
protected $fillable = [
];
protected $guarded = ['created_at', 'updated_at'];
/**
* The attributes excluded from the model's JSON form.
*
......
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Repositories\Models;
class RhawnSorderRefund extends Model
{
protected $table = 'tools_task';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'id','name','exec_content','status','error_message','type','exec_nums','create_by'
];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = [
];
}
\ No newline at end of file
......@@ -11,10 +11,11 @@
namespace App\Repositories\Models;
class ToolsTask extends Model
class ThirdApiPlatform extends Model
{
protected $table = 'tools_task';
protected $connection = 'mysql';
protected $table = 'third_api_platform';
/**
* The attributes that are mass assignable.
......@@ -22,15 +23,15 @@ class ToolsTask extends Model
* @var array
*/
protected $fillable = [
'platform_name','platform_title','platform_url','platform_desc','platform_icon','platform_params','platform_type','platform_token','platform_status','created_by','updated_by'
];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = [
];
];
}
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Services;
use App\Jobs\BhSorderRefundJob;
use App\Repositories\Contracts\BhPordersRepository;
use App\Repositories\Contracts\BhSoitemsRepository;
use App\Repositories\Contracts\BhSorderRefundRepository;
use App\Repositories\Contracts\BhSordersRepository;
use App\Repositories\Contracts\ToolsTaskRepository;
use App\Repositories\Criteria\BhPordersCriteria;
use App\Repositories\Criteria\BhSorderRefundCriteria;
use App\Repositories\Criteria\BhSorderRefundTaskLogCriteria;
use App\Repositories\Enums\ResponseCodeEnum;
use App\Repositories\Models\AdminUsers;
use App\Repositories\Models\BhPorders;
use App\Support\Traits\Helpers;
use Illuminate\Support\Facades\DB;
class BhOrdersService
{
use Helpers;
protected $bhPordersRepository = null;
public function __construct(BhPordersRepository $bhPordersRepository)
{
$this->bhPordersRepository = $bhPordersRepository;
}
public function searchPordersToPage($request)
{
$params = $this->formatKeysfromArray($request->all(),'toUnderScore');
$this->bhPordersRepository->pushCriteria(new BhPordersCriteria($request));
$pOrdersList = $this->bhPordersRepository->paginate($params['page_size']);
$returnRecord = [];
if($pOrdersList){
$record = $this->procOrderResponseData($pOrdersList->items());
}
// 获取当前角色的所有权限
$returnRecord['data'] = $this->formatKeysfromArray($record);
$returnRecord['current_page'] = $pOrdersList->currentPage();
$returnRecord['total'] = $pOrdersList->total();
return $returnRecord;
}
/**
* 编辑订单信息
* @param $request
* @return bool|int
*/
public function editBhPordersInfo($request)
{
$params = $this->formatKeysfromArray($request->all(),'toUnderScore');
$order = BhPorders::query()->where('po_no',$params['po_no'])->get();
if(!$order){
throw new \LogicException('订单号不存在!',500);
}
$updateOrderArr = [];
if(isset($params['po_sup_order']) && !empty($params['po_sup_order'])){
$updateOrderArr['po_sup_order'] = $params['po_sup_order'];
}
$updateOrderArr['po_if_direct'] = 0;
if(isset($params['po_if_direct']) && !empty($params['po_if_direct'])){
if($params['po_if_direct'] == true){
$updateOrderArr['po_if_direct'] = 1;
}
}
$res = $order->first()->update($updateOrderArr);
return $this->procOrderResponseData($order);
}
/**
* 获取订单详情
* @param $request
*/
public function getBhSorderDetail($request)
{
$params = $this->formatKeysfromArray($request->all(),'toUnderScore');
if(!isset($params['order_no']) || empty($params['order_no'])){
throw new BadQueryStringException('订单编号错误',500);
}
$sOrder = app(BhSordersRepository::class)->getSorderFromOrderNo($params['order_no']);
if(!$sOrder){
throw new \LogicException('该订单编号不存在!',500);
}
//查询订单的详情
$soItems = app(BhSoitemsRepository::class)->getSorderItemsDetailFromOrderId($sOrder->so_id);
$soItems = $soItems->toArray();
$returnItem = [];
if($soItems){
foreach($soItems as $item){
$temp = [];
$temp['b_cn_name'] = $item['b_cn_name'];
$temp['p_code'] = $item['p_code'];
$temp['c_cas'] = $item['c_cas'];
$temp['p_cn_name'] = $item['p_cn_name'];
$temp['si_price'] = $item['si_price'];
$temp['si_discount'] = $item['si_discount'];
$temp['si_p_tod'] = $item['si_p_tod'];
$temp['si_num'] = $item['si_num'];
$temp['si_amount'] = $item['si_amount'];
$temp['si_vamount'] = $item['si_vamount'];
$temp['si_note'] = $item['si_note'];
$temp['si_num'] = $item['si_num'];
$temp['p_id'] = $item['p_id'];
$temp['si_id'] = $item['si_id'];
$temp['so_no'] = $sOrder->so_no;
if($item['si_if_cancel'] == 0){
$returnItem[] = $temp;
}
}
}
return $returnItem;
}
public function addSordersRefundTask($request)
{
$params = $this->formatKeysfromArray($request->all(),'toUnderScore');
$sOrder = app(BhSordersRepository::class)->getSorderFromOrderNo($params['order_no']);
if(!$sOrder){
throw new \LogicException('该订单编号不存在!',500);
}
if(isset($params['task_id']) && !empty($params['task_id'])){
if(!app(BhSorderRefundRepository::class)->find($params['task_id'])){
throw new \LogicException('该任务不存在!',500);
}
}
if($params['transfer_pre'] == 'true'){
$params['transfer_pre'] = 1;
}else{
$params['transfer_pre'] = 0;
}
if($params['cancel_porder'] == 'true'){
$params['cancel_porder'] = 1;
}else{
$params['cancel_porder'] = 0;
}
if($params['refund_nums'] == 'null'){
throw new \LogicException('请填写正确的退货数量',500);
}
return app(BhSorderRefundRepository::class)->addRefundTask($params);
}
public function delSorderRefundTask($request)
{
$params = $this->formatKeysfromArray($request->all(),'toUnderScore');
if(isset($params['task_id']) && !empty($params['task_id'])){
if(!app(BhSorderRefundRepository::class)->find($params['task_id'])){
throw new \LogicException('该任务不存在!',500);
}
}
return app(BhSorderRefundRepository::class)->delRefundTask($params);
}
/**
* 获取订单退货任务
* @param $request
* @return array
*/
public function getSordersRefundTask($request)
{
$params = $this->formatKeysfromArray($request->all(),'toUnderScore');
if(!$params['page_size'] || $params['page_size'] == 0){
$params['page_size'] = 10;
}
$repostiroy = app(BhSorderRefundRepository::class);
$repostiroy->pushCriteria(new BhSorderRefundCriteria($request));
$tasks = $repostiroy->customPaginate($params['page_size']);
if($tasks){
$allItems = collect($tasks['data'])->map(function($item){
$contentArr= [];
$execArr = json_decode($item['exec_content'],true);
foreach($execArr as $key => $content){
switch($key){
case 'order_no' : $contentArr[] = '【订单号】:'.$content; break;
case 'refund_nums' : $contentArr[] = '【退货数量】:'.$content; break;
case 'handle_fee' : $contentArr[] = '【手续费费用】:'.$content; break;
case 'item_id' : $contentArr[] = '【订单购买项id】:'.$content; break;
case 'transfer_pre' :
$content = $content == '1' ? '是' : '否';
$contentArr[] = '【是否转预存】:'.$content; break;
case 'cancel_porder' :
$content = $content == '1' ? '是' : '否';
$contentArr[] = '【是否取消采购订单】:'.$content; break;
}
}
$user = AdminUsers::find($item['create_by']);
$item['create_by'] = $user->username;
$item['content_string'] = implode('<br / >',$contentArr);
$item = array_merge($item,$execArr);
return $item;
});
$tasks['data'] = $allItems->toArray();
$tasks = $this->formatKeysfromArray($tasks);
}
return $tasks;
}
public function getBhSorderDetailByTaskId($request)
{
$params = $this->formatKeysfromArray($request->all(),'toUnderScore');
$task = app(BhSorderRefundRepository::class)->find($params['task_id']);
if(!$task){
throw new \LogicException('任务不存在!',500);
}
$task = $task->toArray();
$content = json_decode($task['exec_content'],true);
//获取销售订单item数据
$dbConnect = DB::connection('bh_mysql');
$soItems = app(BhSoitemsRepository::class)->getSorderItemsDetailFromItemId($content['item_id'],$content['p_id']);
$soItems = $soItems->toArray();
$returnItem = [];
if($soItems){
foreach($soItems as $item){
if($item['si_if_cancel'] == 0){
$returnItem[] = $item;
}
}
}
return $returnItem;
}
/**
* 手动执行脚本
* @param $request
*/
public function execSordersRefundTask($request)
{
$params = $this->formatKeysfromArray($request->all(),'toUnderScore');
$orderRefund = app(BhSorderRefundRepository::class)->find($params['task_id']);
$refundJob = (new BhSorderRefundJob($orderRefund->toArray()))->delay(100)->onQueue('slow');
app('Illuminate\Contracts\Bus\Dispatcher')->dispatch($refundJob);
}
/**
* 处理退货逻辑
* @param $refundInfo
*/
public function sOrderRefund($refundInfo,&$note)
{
$sOrder = app(BhSordersRepository::class)->getSorderItemsFromOrderNo($refundInfo->order_no);
if(!$sOrder){
throw new \LogicException('该订单号不存在!',500);
}
try{
$dbConnect = DB::connection('bh_mysql');
$dbConnect->beginTransaction();
// 处理订单退货项
foreach($sOrder->toArray() as $orderitem){
if($refundInfo->item_id == $orderitem['si_id']){
// 先处理源数据
$currentPrice = floatval($orderitem['si_discount']);
$currentAmount = floatval($orderitem['si_amount']);
// 退货剩余数量
$num = $spotNums = intval($refundInfo->refund_nums);
$futuresNum = 0;
if($num < 0){
throw new \LogicException('退货数量大于购买数量',500);
}
// 统计有多少数量
$sum = $dbConnect->table('soitems')
->where('so_id',$orderitem['so_id'])
->where('si_id',$orderitem['si_id'])
->sum('si_num');
// 获取实际现货数量
$dpdSum = $dbConnect->table('dpdetail')
->where('si_id',$orderitem['si_id'])
->sum('dpd_num');
// 如果是全部退货并且没有手续费的情况
if($sum == $refundInfo->refund_nums && $refundInfo->handle_fee == 0 && $dpdSum > 0){
throw new \LogicException('本功能不支持全部退货,如果需要全部退货请移步百化系统后台进行操作!',500);
}
// 判断是否有期货,如果有用现货数量做退货
if($sum > $dpdSum){
//期货数量
if($dpdSum > 0){
$futuresNum = $sum - $dpdSum;
}else{
$futuresNum = $refundInfo->refund_nums;
}
if($futuresNum > 0 && $refundInfo->handle_fee > 0){
throw new \LogicException('包含期货数据,并且期货不支持手续费',500);
}
if($futuresNum == $refundInfo->refund_nums){
$spotNums = 0;
}elseif($refundInfo->refund_nums > $futuresNum){
if($dpdSum > 0){
$spotNums = $refundInfo->refund_nums - $futuresNum;
}else{
$spotNums = 0;
}
}else{
$futuresNum = $futuresNum - $refundInfo->refund_nums;
if($dpdSum == 0){
$spotNums = 0;
}
}
}
//查询是否已经开票,如果开票不能进行退货
if($refundInfo->refund_nums > $futuresNum){
$dpdetail = $dbConnect->table('dpdetail')
->where('si_id',$orderitem['si_id'])
->get();
$dpdetail = $dpdetail->toArray();
if(count($dpdetail) > 0){
foreach($dpdetail as $detail){
if(floatval($detail->dpd_invoiced) > 0) {
throw new \logicexception('以开票的数据不能退货!',500);
}
}
}
}
// 如果有期货先处理期货,然后在处理现货。期货不需要dpdetail拆单
while(true) {
$currentProcessNums = $spotNums;
// 如果有期货数量优先处理
if($futuresNum > 0){
$currentProcessNums = $futuresNum;
}
//修改item数据项
$service = app(BhSoitemsRepository::class);
$soItem = $service->findWhere(['si_id' => $orderitem['si_id'],'si_if_cancel' => 0]);
$soItem = current($soItem->toArray());
if(empty($soItem) || count($soItem) == 0) {
throw new \LogicException('购买项数据id:'.$orderitem['si_id'].'数据不存在或已取消!',500);
}
//更新原本数据
$updateArr = [];
$createArr = [];
$updatedItem = [];
//如果取消的是全部
if (($currentProcessNums - $orderitem['si_num']) == 0) {
// 如果需要手续费
if (isset($refundInfo->handle_fee) && $refundInfo->handle_fee > 0) {
$createArr = $soItem;
unset($createArr['si_id']);
$createArr['si_num'] = $orderitem['si_num'];
$createArr['si_assigned_num'] = $createArr['si_num'];
$createArr['si_amount'] = bcsub($orderitem['si_amount'], $refundInfo->handle_fee, 2);
$createArr['si_discount'] = bcdiv($createArr['si_amount'], $orderitem['si_num'], 2);
$updateArr['si_num'] = $refundInfo->refund_nums;
//$updateArr['si_assigned_num'] = $updateArr['si_num'];
$updateArr['si_amount'] = $refundInfo->handle_fee;
$updateArr['si_discount'] = bcdiv($updateArr['si_amount'], $currentProcessNums, 2);
} else {
$updatedItem['cancel_si_id'] = $orderitem['si_id'];
}
} // 部分退货
else {
if($futuresNum > 0){
$updateArr['si_num'] = $orderitem['si_num'] - $currentProcessNums;
//$updateArr['si_assigned_num'] = $orderitem['si_assigned_num'];
}else{
$updateArr['si_num'] = bcsub($orderitem['si_num'], $currentProcessNums); // 如果数量只有1,且退货数量相等
$updateArr['si_assigned_num'] = $updateArr['si_num'];
}
$updateArr['si_amount'] = bcmul(
$orderitem['si_discount'],
$updateArr['si_num'],
2
);
if (isset($refundInfo->handle_fee) && $refundInfo->handle_fee > 0) {
$updateArr['si_amount'] = bcadd($updateArr['si_amount'], $refundInfo->handle_fee, 2);
}
$updateArr['si_discount'] = bcdiv($updateArr['si_amount'], $updateArr['si_num'], 2);
// 新增
$createArr = $soItem;
unset($createArr['si_id']);
$createArr['si_num'] = $currentProcessNums;
if (isset($refundInfo->handle_fee) && floatval($refundInfo->handle_fee) > 0) {
$createArr['si_amount'] = abs(bcsub($currentAmount, $updateArr['si_amount'], 2));
$createArr['si_discount'] = bcdiv($createArr['si_amount'], $createArr['si_num'], 2);
} // 没有手续费的情况下
else {
$createArr['si_discount'] = $soItem['si_discount'];
$createArr['si_amount'] = bcmul($soItem['si_discount'], $currentProcessNums, 2);
}
//$createArr['si_num'] = $currentProcessNums;
if($futuresNum > 0){
$createArr['si_assigned_num'] = 0;
}else{
$createArr['si_assigned_num'] = $createArr['si_num'];
}
if ($createArr['si_amount'] < 0) {
throw new \LogicException('手续费异常,处理失败!', 500);
}
}
/*If(isset($refundInfo->handle_fee) && $refundInfo->handle_fee > 0){
$updateArr['si_amount'] = bcadd($updateArr['si_amount'] , $refundInfo->handle_fee,2);
}
if($num > 1){
$updateArr['si_discount'] = bcdiv($updateArr['si_amount'] , $num, 2);
}*/
if (!empty($updateArr)) {
$update = $service->update($updateArr, $soItem['si_id']);
$updatedItem['update'] = $update->toArray();
} else {
$updatedItem['update'] = $orderitem;
}
/*$update = $service->update($updateArr,$soItem['si_id']);
$updatedItem['update'] = $update->toArray();*/
//判断是否能除尽
if (!empty($updateArr)) {
$amount = bcmul($updateArr['si_discount'], $updateArr['si_num'], 2);
if ($updateArr['si_amount'] != $amount) {
$note[] = 'si_id = ' . $soItem['si_id'] . '的数据有除不尽的情况,请手工处理';
}
}
//生成新记录
/*unset($createArr['si_id']);
$createArr['si_num'] = $refundInfo->refund_nums;
if(isset($refundInfo->handle_fee) && floatval($refundInfo->handle_fee) > 0){
$createArr['si_amount'] = abs(bcsub($currentAmount, $updateArr['si_amount'], 2));
$createArr['si_discount'] = bcdiv($createArr['si_amount'], $createArr['si_num'], 2);
} // 没有手续费的情况下
else{
$createArr['si_discount'] = $soItem['si_discount'];
$createArr['si_amount'] = bcmul($soItem['si_discount'], $refundInfo->refund_nums, 2);
}
$createArr['si_num'] = $refundInfo->refund_nums;
$createArr['si_assigned_num'] = $createArr['si_num'];
if($createArr['si_amount'] < 0){
throw new \LogicException('手续费异常,处理失败!',500);
}*/
if (!empty($createArr)) {
$newItem = $service->create($createArr);
$updatedItem['create'] = $newItem->toArray();
// 如果是部分退货
if ($currentProcessNums > 0 || ($currentProcessNums == 0 && $refundInfo->handle_fee > 0)) {
$updatedItem['cancel_si_id'] = $updatedItem['create']['si_id'];
}
} else {
$updatedItem['create'] = $soItem;
$updatedItem['cancel_si_id'] = $updatedItem['create']['si_id'];
}
$updatedItem['total'] = $currentAmount;
// 如果没有期货数量,dpdetail只处理现货数量
if ($futuresNum == 0) {
//修改配货单记录
if ($dpdetail) {
$maxRecord = $minRecord = [];
$needUpdate = null;
$totalNums = $totalAmount = 0;
//针对多个dpdetail数据,进行数量判断
//默认都是没有开票过的
foreach ($dpdetail as $detail) {
$detailArr = [];
$totalNums += $detail->dpd_num;
$totalAmount += $detail->dpd_amount;
foreach ($detail as $key => $val) {
$detailArr[$key] = $val;
}
if ($detail->dpd_num == $currentProcessNums) {
$needUpdate = $detailArr;
break;
}
// 1 数量5, 2条记录 3/2 , 退货4瓶
// 2 数量5, 2条记录 4/1 , 退货3瓶
// 3 数量6 3条记录 4/1/1, 退货3瓶
// 4 数量8 3条记录 4/2/2, 退货4瓶
// 5 数量8 3条记录 4/3/1, 退货4瓶
// 6 数量11 3条记录 6/4/1, 退货5瓶
if ($detail->dpd_num > $currentProcessNums) {
$nums = $detail->dpd_num;
$maxRecord[$nums][$detail->dpd_id] = $detailArr;
} elseif ($currentProcessNums > $detail->dpd_num) {
$nums = $currentProcessNums - $detail->dpd_num;
$minRecord[$nums][$detail->dpd_id] = $detailArr;
}
}
$cancelRecord = [];
// 如果退货数量跟此明细数量相同,不需要拆分的情况下
if (!is_null($needUpdate)) {
$dpUpdateArr = [];
// 如果有手续费,对价格进行更新
if ($refundInfo->handle_fee > 0) {
// 如果是全部退货
if ($currentProcessNums == $needUpdate['dpd_num'] && count($dpdetail) == 1) {
// 如果有手续费,将价格进行修改
foreach ($dpdetail as $detail) {
$otherUpdate = [];
$otherUpdate['dpd_amount'] = bcmul($updatedItem['update']['si_discount'], $detail->dpd_num, 2);
$dbConnect->table('dpdetail')
->where('dpd_id', $detail->dpd_id)
->update($otherUpdate);
}
} else {
// 如果有手续费,将价格进行修改
foreach ($dpdetail as $detail) {
if ($detail->dpd_id != $needUpdate['dpd_id']) {
$otherUpdate = [];
$otherUpdate['dpd_amount'] = bcmul($updatedItem['update']['si_discount'], $detail->dpd_num, 2);
$dbConnect->table('dpdetail')
->where('dpd_id', $detail->dpd_id)
->update($otherUpdate);
}
}
$dpUpdateArr['si_id'] = $updatedItem['create']['si_id'];
//将取消的记录价格进行更新
$dpUpdateArr['dpd_amount'] = bcmul($updatedItem['create']['si_discount'], $needUpdate['dpd_num'], 2);
$dbConnect->table('dpdetail')
->where('dpd_id', $needUpdate['dpd_id'])
->update($dpUpdateArr);
}
} // 如果没有手续费,不对价格进行更新
else {
$dpUpdateArr['si_id'] = $updatedItem['create']['si_id'];
$dbConnect->table('dpdetail')
->where('dpd_id', $needUpdate['dpd_id'])
->update($dpUpdateArr);
}
} else {
asort($maxRecord);
arsort($minRecord); // 降序排序
$num = $currentProcessNums;
// minrecord有值,只有退货数量大于此条记录的数量时
$cancelRecord = array_merge($cancelRecord, $this->handleDpdetailInfo($dbConnect, $num, $minRecord, $updatedItem, $refundInfo, 'asort'));
$cancelRecord = array_merge($cancelRecord, $this->handleDpdetailInfo($dbConnect, $num, $maxRecord, $updatedItem, $refundInfo, 'arsort'));
// 判断是否这次是全部取消
$dpCount = $dbConnect->table('dpdetail')
->where('si_id', $orderitem['si_id'])
->whereIn('dpd_id', $cancelRecord)->sum('dpd_num');
if ($dpCount == 0 && $sum == $currentProcessNums) {
$infos = $dbConnect->table('dpdetail')
->whereIn('dpd_id', $cancelRecord)->get();
foreach ($infos->toArray() as $info) {
$update = [];
$update['dpd_amount'] = bcmul($updatedItem['update']['si_discount'], $info->dpd_num, 2);
$update['si_id'] = $orderitem['si_id'];
$dbConnect->table('dpdetail')
->where('dpd_id', $info->dpd_id)
->update($update);
}
}
}
// 更新除了取消的记录以外的记录的价格
if (count($cancelRecord) > 0) {
$dpdetailInfo = $dbConnect->table('dpdetail')
->where('si_id', $orderitem['si_id'])
->whereNotIn('dpd_id', $cancelRecord)->get();
$dpdetailInfo = $dpdetailInfo->toArray();
if (count($dpdetailInfo) > 0) {
foreach ($dpdetailInfo as $info) {
$otherUpdate = [];
$otherUpdate['dpd_amount'] = bcmul($updatedItem['update']['si_discount'], $info->dpd_num, 2);
$dbConnect->table('dpdetail')
->where('dpd_id', $info->dpd_id)
->update($otherUpdate);
}
}
}
}
}
//新增配货单数据
/*foreach($dpdetail as $key => $value){
$dpCreateArr[$key] = $value;
}
unset($dpCreateArr['dpd_id']);
$dpCreateArr['dpd_num'] = $refundInfo->refund_nums;
$dpCreateArr['dpd_amount'] = $createArr['si_amount'];
$dpId = $dbConnect->table('dpdetail')->insertGetId($dpCreateArr);*/
// 修改采购订单的详情数据
$soItemArr = $soItem;
$poItems = $dbConnect->table('poitems')
->where('p_id', $soItemArr['p_id'])
->where('pi_id', $soItemArr['pi_id'])
->where('pi_status', '<>', 3)
->get();
if ($poItems) {
foreach ($poItems as $item) {
// 如果不是取消状态的
if ($item->pi_status != 3) {
// 可能存在对应多个po的情况
if ($item->pi_num < $currentProcessNums) {
throw new \LogicException('采购订单数量不足,无法退货!', 500);
}
// 如果退货数量小于采购订单数量
if ($item->pi_num > $currentProcessNums) {
// 修改当前的数量和金额
$poItemUpdateArr = [];
$poNums = bcsub($item->pi_num, $currentProcessNums);
$poItemUpdateArr['pi_num'] = $poNums;
$poItemUpdateArr['pi_amount'] = bcmul($item->pi_price, $poNums, 2);
/*if($futuresNum > 0){
$poItemUpdateArr['pi_rnum'] = 0;
}else{
$poItemUpdateArr['pi_rnum'] = $poItemUpdateArr['pi_num'];
}*/
if($futuresNum == 0){
$poItemUpdateArr['pi_rnum'] = $poItemUpdateArr['pi_num'];
}
if ($poItemUpdateArr['pi_num'] == $item->pi_rnum && $item->pi_status == 1) {
$poItemUpdateArr['pi_status'] = 2;
}
$dbConnect->table('poitems')
->where('pi_id', $item->pi_id)
->update($poItemUpdateArr);
// 新增退货的采购订单信息
$poItemCreateArr = [];
foreach ($item as $key => $ite) {
$poItemCreateArr[$key] = $ite;
}
unset($poItemCreateArr['pi_id']);
$poItemCreateArr['pi_num'] = $currentProcessNums;
$poItemCreateArr['pi_amount'] = bcmul($item->pi_price, $poItemCreateArr['pi_num'], 2);
if($futuresNum > 0){
$poItemCreateArr['pi_rnum'] = 0;
}else{
$poItemCreateArr['pi_rnum'] = $currentProcessNums;
}
$poItemCreateArr['pi_status'] = $poItemCreateArr['pi_num'] == $poItemCreateArr['pi_rnum'] ? 2 : 1;
$poItemsId = $dbConnect->table('poitems')->insertGetId($poItemCreateArr);
//将soitems表中的新增记录中的pi_id修改为新值
$dbConnect->table('soitems')
->where('si_id', $updatedItem['create']['si_id'])
->update([
'pi_id' => $poItemsId
]);
if ($refundInfo->cancel_porder == 1) {
// 取消采购订单
$this->cancelPorderItems($dbConnect, $poItemCreateArr['po_id'], $poItemsId);
}
} elseif ($item->pi_num == $currentProcessNums) {
if ($refundInfo->cancel_porder == 1) {
// 取消采购订单
$this->cancelPorderItems($dbConnect, $item->po_id, $item->pi_id);
}
}
}
}
}
//将dpdetail表里的新记录的si_id改为新值
/*$newDpdetail = $dbConnect->table('dpdetail')->where('dpd_id',$dpId)->first();
if(!$newDpdetail){
throw new \LogicException('数据处理失败!',500);
}
$updateDpArr = [];
$updateDpArr['si_id'] = $newItem->si_id;
$dbConnect->table('dpdetail')
->where('dpd_id',$dpId)
->update($updateDpArr);
*/
//预存款和退款处理
$this->cancelAndTransPrePay($dbConnect, $updatedItem['cancel_si_id'], $refundInfo);
if($currentProcessNums > 0){
if($futuresNum > 0){
$futuresNum = 0;
}else{
$spotNums = 0;
}
$currentProcessNums = 0;
}else{
break;
}
if($spotNums == 0){
break;
}
}
}
}
$dbConnect->commit();
}catch(\Exception $e){
$dbConnect->rollBack();
throw $e;
}
}
/**
* 具体处理拆分dpdetail数据
* @param $dbConnect
* @param $recordsArr
* @param $si_id
* @param $createArr
* @param $updateArr
* @param $refundInfo
* @param string $sort
* @return array
*/
protected function handleDpdetailInfo($dbConnect, &$num, $recordsArr, $updatedItem, $refundInfo, $sort = 'arsort')
{
$cancelRecord = [];
if(!empty($recordsArr) && count($recordsArr) > 0){
foreach($recordsArr as $records){
if(is_array(current($records))){
$sort($records);
foreach($records as $re){
if($num > 0){
// 退货数量 > 当前记录的数量 或者 退货数量 = 当前记录的数量
if(($num > $re['dpd_num']) || ($num == $re['dpd_num'])){
$num = $num - $re['dpd_num'];
$dpUpdateArr = [];
//$dpUpdateArr['si_id'] = $updatedItem['update']['si_id'];
/*if($num > $re['dpd_num']){
$dpUpdateArr['dpd_amount'] = bcmul($updatedItem['create']['si_discount'], $re['dpd_num'], 2);
}else{
$dpUpdateArr['dpd_amount'] = bcmul($updatedItem['update']['si_discount'], $re['dpd_num'], 2);
}*/
$dpUpdateArr['si_id'] = $updatedItem['create']['si_id'];
$dpUpdateArr['dpd_amount'] = bcmul($updatedItem['create']['si_discount'], $re['dpd_num'], 2);
$dbConnect->table('dpdetail')
->where('dpd_id',$re['dpd_id'])
->update($dpUpdateArr);
$cancelRecord[] = $re['dpd_id'];
} // 如果退货数量 < 当前记录的数量
elseif($num < $re['dpd_num']){
// 更新当前记录
$dpUpdateArr = [];
$dpUpdateArr['dpd_num'] = $re['dpd_num'] - $num;
//$dpUpdateArr['dpd_amount'] = bcsub($updatedItem['total'], $updatedItem['update']['si_amount'], 2);
$dpUpdateArr['dpd_amount'] = bcmul($updatedItem['update']['si_discount'], $dpUpdateArr['dpd_num'], 2);
$dbConnect->table('dpdetail')
->where('dpd_id',$re['dpd_id'])
->update($dpUpdateArr);
$cancelRecord[] = $re['dpd_id'];
//添加新的取消记录
$dpCreateArr = $re;
unset($dpCreateArr['dpd_id']);
$dpCreateArr['dpd_num'] = $num;
$dpCreateArr['dpd_amount'] = bcmul($updatedItem['create']['si_discount'], $num, 2);
$dpCreateArr['si_id'] = $updatedItem['create']['si_id'];
$dpId = $dbConnect->table('dpdetail')->insertGetId($dpCreateArr);
$num = 0;
$cancelRecord[] = $dpId;
}
}
}
}
}
}
return $cancelRecord;
}
/**
* 取消采购订单项
* @param $db
* @param $po_id
* @param $pi_id
*/
protected function cancelPorderItems($db,$po_id,$pi_id)
{
$pOrderItems = app(BhPordersRepository::class)->getPorderItemsFromPoId($po_id,$pi_id);
$total = $db->table('poitems')
->where('po_id',$po_id)
->where('pi_status','<>',3)
->where('pi_id','<>',$pi_id)
->sum('pi_amount');
//$row = $db->select("SELECT SUM(`pi_amount`) AS `total` FROM `poitems` WHERE `po_id` = ".$po_id." AND `pi_id` <> ".$pi_id." AND `pi_status` <> 3");
//$row = current($row);
//判断是否是最后一条非运费明细
if($total > 0){
$total += current($pOrderItems)['po_express'];
$db->table('porders')->where('po_id', $po_id)->update(['po_total'=>$total]);
$db->table('poitems')->where('pi_id', $pi_id)->update(['pi_status'=>'3']);
}else{
$db->table('porders')
->where('po_id', $po_id)
->update(
[
'po_total' => '0',
'po_review_status' => '2'
]
);
$db->table('poitems')->where('pi_id', $pi_id)->update(['pi_status'=>'3']);
}
//更新采购订单的开票状态
$pOrderItems = current($pOrderItems);
if($pOrderItems['po_invoiced_amount'] >= $pOrderItems['po_total']){
$db->table('porders')->where('po_id',$po_id)->update(['po_invoice_status' => 2]);
}elseif($pOrderItems['po_invoiced_amount'] > 0){
$db->table('porders')->where('po_id',$po_id)->update(['po_invoice_status' => 1]);
}else{
$db->table('porders')->where('po_id',$po_id)->update(['po_invoice_status' => 0]);
}
return true;
}
/**
* 取消并转预存
* @param $db
* @param $si_id
*/
protected function cancelAndTransPrePay($db,$si_id,$refundInfo)
{
//获取订单明细项
$sOrderItem = app(BhSoitemsRepository::class)->getSorderItemFromItemId($si_id);
$sOrderItem = current($sOrderItem->toArray());
if($sOrderItem['si_if_cancel'] == 1){
throw new \LogicException('已经取消过了,请不要重复操作!',500);
}
$sOrderDetail = app(BhSordersRepository::class)->getSorderDetailFromOrderId($sOrderItem['so_id']);
if(!$sOrderDetail){
throw new \LogicException('数据不存在!',500);
}
$sOrderDetail['express'] = 0;
foreach($sOrderDetail['items'] as $k=>$v){
if($v->p_id == 0){
$sOrderDetail['express'] = $v->si_amount;
unset($sOrderDetail['items'][$k]);
}
}
/*if($sOrderDetail['so_pay_status'] == 0){
throw new \LogicException('未完成付款的订单不能取消转预存款!',500);
}*/
if($sOrderDetail['so_pay_status'] == 1){
throw new \LogicException('部分付款的订单不能取消明细,请联系管理员!',500);
}
if($sOrderItem['pi_id'] > 0){
//判断对应的采购订单明细是否已经取消
$pOrderItems = $db->table('poitems')
->join('porders','poitems.po_id','porders.po_id')
->where('poitems.pi_id',$sOrderItem['pi_id'])
->first();
if(!$pOrderItems){
throw new \LogicException('查询采购订单明细 ['.$sOrderItem['pi_id'].'] 数据不存在!',500);
}
if($pOrderItems->pi_status != 3 && $refundInfo->cancel_porder == 1){
throw new \LogicException('请先取消采购订单:'.$pOrderItems->po_no.'中的对应采购订单明细!');
}
}
if($sOrderItem['si_assigned_num'] > 0){
$dp_status = array();
$invoiced_amount = 0;
$dpdetailInfos = $db->table('dpdetail')
->join('dispatch','dpdetail.dp_id','dispatch.dp_id')
->where('dpdetail.si_id',$sOrderItem['si_id'])
->get();
if(!$dpdetailInfos){
throw new \LogicException('dpdetail ['.$sOrderItem['si_id'].'] 配货单数据不存在!',500);
}
foreach($dpdetailInfos as $k=>$v){
$dp_status[] = $v->dp_status;
$invoiced_amount += $v->dpd_invoiced;
}
if($invoiced_amount != 0){
throw new \LogicException('已经开过发票,不能取消!',500);
}
$dp_status = array_unique($dp_status);
if(in_array('0',$dp_status) || in_array('1',$dp_status)){
throw new \LogicException('请物流部配合处理至已发货状态,再做取消操作!',500);
}
}
// 具体处理退货并转预存
$si_cancel_time = 0;
$siAmountTotal = $db->table('soitems')
->where('so_id',$sOrderItem['so_id'])
->where('si_id','<>',$si_id)
->where('si_if_cancel',0)
->sum('si_amount');
$siAmountTotalPid = $db->table('soitems')
->where('so_id',$sOrderItem['so_id'])
->where('si_id','<>',$si_id)
->where('si_if_cancel',0)
->where('p_id','>',0)
->sum('si_amount');
$soItem = app(BhSoitemsRepository::class)->find($si_id);
if($soItem){
if($soItem['si_assigned_num']){
$dp = $db->table('dpdetail')->where('si_id',$si_id)->get();
$dp = $dp->toArray();
foreach($dp as $k=>$v){
if($v->dp_id == 0 && $v->stk_id > 0){
//清除已配货记录
$stock = $db->table('stock')->where('stk_id',$v['stk_id'])->get();
$stock = current($stock->toArray());
$stock_data = array();
$stock_data['stk_lock_num'] = $stock->stk_lock_num - $v->dpd_num;
if($stock_data['stk_lock_num'] < 0){
$stock_data['stk_lock_num'] = 0;
}
$db->table('stock')
->where('stk_id',$v->stk_id)
->update($stock_data);
$db->table('dpdetail')
->delete($v->dpd_id);
$si_assigned_num = $soItem['si_assigned_num'] - $v->dpd_num;
app(BhSoitemsRepository::class)->update(['si_patch_status'=>'0','si_assigned_num'=>$si_assigned_num],$si_id);
}
}
}
}
$customer = $db->table('customers')
->where('cus_id',$sOrderDetail['cus_id'])
->first();
//判断是否是最后一条非运费明细
$note = $sOrderDetail['so_no'].'取消明细:'.$soItem['p_code'];
if($siAmountTotalPid > 0){
$refund_amount = $soItem['si_amount'];
if($sOrderDetail['so_pay_status'] > 0){
// 退款
if($refundInfo->transfer_pre == 0){
$refund_data = [];
$refund_data['r_company'] = $customer->cus_company;
$refund_data['r_amount'] = $refund_amount;
$refund_data['r_ctime'] = time();
$refund_data['r_note'] = $note;
$refund_data['r_bank_account'] = '';
$refund_data['r_confirm_note'] = '';
$db->table('refund')->insertGetId($refund_data);
}else{
$prepaylog_data = [];
$prepaylog_data['cus_id'] = $sOrderDetail['cus_id'];
$prepaylog_data['prepaylog_amount'] = $refund_amount;
$prepaylog_data['prepaylog_note'] = $note;
$prepaylog_data['prepaylog_date'] = time();
$prepaylog_data['prepaylog_time'] = time();
$prepaylog_data['prepaylog_operator'] = auth()->user()->id;
$prepayId = $db->table('prepaylog')->insertGetId($prepaylog_data);
$sum = $db->table('prepaylog')
->where('cus_id',$sOrderDetail['cus_id'])
->sum('prepaylog_amount');
$db->table('customers')
->where('cus_id',$sOrderDetail['cus_id'])
->update(['cus_prepay' => $sum]);
$si_cancel_time = time();
}
}
app(BhSordersRepository::class)->update(['so_total'=>$siAmountTotal],$sOrderItem['so_id']);
app(BhSoitemsRepository::class)->update(['si_if_cancel'=>'1','si_cancel_time'=>$si_cancel_time],$si_id);
}else {
if($sOrderDetail['so_pay_status'] > 0){
//得到退款金额
$sOrder = app(BhSordersRepository::class)->find($sOrderItem['so_id']);
if (!$sOrder) {
throw new \LogicException('数据不存在!', 500);
}
$sOrder = $sOrder->toArray();
$refund_amount = $sOrder['so_total'];
if($refundInfo->transfer_pre == 0){
$refund_data = array();
$refund_data['r_company'] = $customer->cus_company;
$refund_data['r_amount'] = $refund_amount;
$refund_data['r_ctime'] = time();
$refund_data['r_note'] = $note;
$refund_data['r_bank_account'] = '';
$refund_data['r_confirm_note'] = '';
$db->table('refund')->insertGetId($refund_data);
}else{
$prepaylog_data = [];
$prepaylog_data['cus_id'] = $sOrderDetail['cus_id'];
$prepaylog_data['prepaylog_amount'] = $refund_amount;
$prepaylog_data['prepaylog_note'] = $note;
$prepaylog_data['prepaylog_date'] = time();
$prepaylog_data['prepaylog_time'] = time();
$prepaylog_data['prepaylog_operator'] = auth()->user()->id;
$prepayId = $db->table('prepaylog')->insertGetId($prepaylog_data);
$sum = $db->table('prepaylog')
->where('cus_id', $sOrderDetail['cus_id'])
->sum('prepaylog_amount');
$db->table('customers')
->where('cus_id', $sOrderDetail['cus_id'])
->update(['cus_prepay' => $sum]);
$si_cancel_time = time();
}
}
app(BhSordersRepository::class)->update(['so_review_status' => '3', 'so_total' => '0'], $sOrderItem['so_id']);
app(BhSoitemsRepository::class)->update(['si_if_cancel' => '1', 'si_cancel_time' => $si_cancel_time], $si_id);
}
$db->table('logs')->insertGetId(
['l_obj'=>$sOrderItem['so_id'],'l_type'=>'sorders_mng','l_op'=>'cancelsi','l_op_name'=>'取消明细','l_note'=>$note,'l_timestamp'=>time(),'u_id'=>auth()->user()->id]
);
return true;
}
/**
* 处理需要返回的数据
* @param $pOrdersList
* @return array|\Illuminate\Support\Collection
*/
protected function procOrderResponseData($items)
{
$items = collect($items)->map(function($item){
$item = $item->toArray();
//开票状态
switch($item['po_invoice_status']){
case 0 : $item['po_invoice_status'] = '未开票';break;
case 1 : $item['po_invoice_status'] = '部分开票';break;
case 2 : $item['po_invoice_status'] = '全额开票';break;
}
//是否直发
switch($item['po_if_direct']){
case 0 : $item['po_if_direct_label'] = '否'; break;
case 1 : $item['po_if_direct_label'] = '是'; break;
}
//订单类型
switch($item['po_type']){
case 0 : $item['po_type'] = '备货'; break;
case 1 : $item['po_type'] = '订单'; break;
}
//审核状态
switch($item['po_review_status']){
case 0 : $item['po_review_status'] = '未付款'; break;
case 1 : $item['po_review_status'] = '部分付款'; break;
case 2 : $item['po_review_status'] = '全额付款'; break;
}
//付款类型
switch($item['po_pay_type']){
case 0 : $item['po_pay_type'] = '公账'; break;
case 1 : $item['po_pay_type'] = '私账'; break;
case 2 : $item['po_pay_type'] = '预付款'; break;
}
return $item;
});
return $items;
}
public function getBhSorderTaskLog($request)
{
$params = $this->formatKeysfromArray($request->all(),'toUnderScore');
if(!isset($params['type']) || empty($params['type'])){
$params['type'] = 'sorder_refund';
}
$taskService = app(ToolsTaskRepository::class);
$taskLogsList = $taskService->getTaskLogsFromType($params['type'],$params['task_id']);
return $taskLogsList;
}
}
<?php
namespace App\Services;
use App\Repositories\Contracts\RhawnRawRepository;
use App\Repositories\Contracts\ThirdApiPlatformRepository;
use App\Services\Kafka\KafkaService;
use App\Services\ThirdPlatform\Api\IntegleApiService;
use App\Services\ThirdPlatform\PlatformAbstractService;
class InteglePlatformService extends PlatformAbstractService
{
public function __construct(ThirdApiPlatformRepository $thirdApiPlatformRepository)
{
$this->setPlatformName('integle');
parent::__construct($thirdApiPlatformRepository);
}
/**
* 批量更新产品到integle平台
*/
public function batchUpdateProducts()
{
$status = $this->checkApiPlatformStatus($this->platformName);
if($status){
$this->getPlatformInfo($this->platformName);
$rhawnChemicalsService = app(RhawnChemicalsService::class);
$limit = $this->platformInfo['platform_params']['batchNums'];
$page = 0;
while(true) {
$rawList = $rhawnChemicalsService->getChemicalRawList($page * $limit, $limit);
if (!$rawList) {
break;
}
$rawIdList = [];
foreach ($rawList as $raw) {
$rawIdList[] = $raw['r_id'];
}
$packages = $rhawnChemicalsService->getChemicalPackage($rawIdList);
$newPackages = [];
if($packages){
foreach($packages as $pack){
$newPackages[$pack['r_code']] = $pack;
}
}
if(!empty($rawList)){
app(KafkaService::class)->produerSend(
[
'params' => ['rawList' => $rawList,'packageList' => $newPackages],
'consumer' => 'App\Services\InteglePlatformService',
'method' => 'batchUpdateApi'
]
);
$page ++;
}
}
}
}
public function batchUpdateApi($updateData)
{
$result = app(IntegleApiService::class)->pushBatchUpdateProduct($updateData);
if($result){
if($result['status'] === false){
app(KafkaService::class)->produerSend(
[
'consumer' => 'App\Services\InteglePlatformService',
'method' => 'batchUpdateApi',
'params' => $updateData
]
);
}
}
unset($result['status']);
$logsContent = [
'apiParams' => $updateData,
'apiReturn' => $result
];
app(SysLogService::class)->addApiLogs($logsContent);
}
}
<?php
namespace App\Services\Kafka;
use App\Services\SysLogService;
use App\Support\Traits\KafkaConfigHelpers;
use longlang\phpkafka\Consumer\ConsumeMessage;
use longlang\phpkafka\Consumer\Consumer;
use longlang\phpkafka\Producer\Producer;
class KafkaService
{
use KafkaConfigHelpers;
protected $kafkaProducerConfig = null;
protected $kafkaConsumerConfig = null;
protected $config = null;
public function __construct($config)
{
$this->kafkaProducerConfig = $this->getProducerConfig($config);
$this->kafkaConsumerConfig = $this->getConsumerConfig($config);
$this->config = $config;
}
/**
* 推送记录
* @param $contentValue
* @param null $topic
*/
public function produerSend($contentValue, $topic = null)
{
try {
$kafkaTopic = $topic;
if ($kafkaTopic == null) {
$kafkaTopic = $this->config['topic'];
}
$key = uniqid($kafkaTopic, true);
$producer = new Producer($this->kafkaProducerConfig);
$producer->send($kafkaTopic, json_encode($contentValue), $key);
app(SysLogService::class)->addOperationLogs(
[
'content' => $contentValue
]
);
} catch (\Exception $exception) {
$this->errLog($exception);
throw $exception;
}
}
/**
* 开启消费者
*/
public function startConsumer()
{
$consumer = new Consumer($this->kafkaConsumerConfig, function (ConsumeMessage $message) {
$consumer = $message->getConsumer();
$kafkaMessage = json_decode($message->getValue(),true);
try{
app($kafkaMessage['consumer'])->{$kafkaMessage['method']}($kafkaMessage['params']);
$consumer->ack($message); // 手动提交
}catch(\Exception $exception){
$this->errLog($exception);
}
$consumer->stop();
});
$consumer->start();
$consumer->close();
}
public function errLog($exception)
{
app(SysLogService::class)->addOperationLogs(
[
'error' => $exception->getCode(),
'message' => $exception->getMessage()
]
);
}
}
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Services;
use App\Repositories\Contracts\RhawnRawRepository;
use App\Repositories\Enums\ResponseCodeEnum;
use Illuminate\Support\Facades\DB;
class RhawnChemicalsService
{
public $rhawnRawRepository = null;
public function __construct(RhawnRawRepository $rhawnRawRepository)
{
$this->rhawnRawRepository = $rhawnRawRepository;
}
/**
* @param int $offset
* @param int $limit
*/
public function getChemicalRawList($offset = 0, $limit = 100)
{
$rawList = $this->rhawnRawRepository->getRawProductList($limit, $offset);
return $rawList;
}
public function getChemicalPackage($rawIds)
{
$packageList = $this->rhawnRawRepository->getProductPackage($rawIds);
return $packageList;
}
}
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Services;
use App\Jobs\RhawnSorderRefundJob;
use App\Repositories\Contracts\RhawnSoitemsRepository;
use App\Repositories\Contracts\RhawnSorderRefundRepository;
use App\Repositories\Contracts\RhawnSordersRepository;
use App\Repositories\Contracts\ToolsTaskRepository;
use App\Repositories\Criteria\RhawnSorderRefundCriteria;
use App\Repositories\Enums\ResponseCodeEnum;
use App\Repositories\Models\AdminUsers;
use App\Support\Traits\Helpers;
use Illuminate\Support\Facades\DB;
class RhawnOrdersService
{
use Helpers;
/**
* 获取订单详情
* @param $request
*/
public function getSorderDetail($request)
{
$params = $this->formatKeysfromArray($request->all(),'toUnderScore');
if(!isset($params['order_no']) || empty($params['order_no'])){
throw new BadQueryStringException('订单编号错误',500);
}
$sOrder = app(RhawnSordersRepository::class)->getSorderFromOrderNo($params['order_no']);
if(!$sOrder){
throw new \LogicException('该订单编号不存在!',500);
}
//查询订单的详情
$soItems = app(RhawnSoitemsRepository::class)->getSorderItemsDetailFromOrderId($sOrder->so_id);
$soItems = $soItems->toArray();
$returnItem = [];
if($soItems){
foreach($soItems as $item){
$temp = [];
$temp['b_cn_name'] = $item['b_cn_name'];
$temp['p_code'] = $item['p_code'];
$temp['c_cas'] = $item['c_cas'];
$temp['p_cn_name'] = $item['p_cn_name'];
$temp['si_price'] = $item['si_price'];
$temp['si_discount'] = $item['si_discount'];
$temp['si_p_tod'] = $item['si_p_tod'];
$temp['si_num'] = $item['si_num'];
$temp['si_amount'] = $item['si_amount'];
$temp['si_vamount'] = $item['si_vamount'];
$temp['si_note'] = $item['si_notes'];
$temp['si_num'] = $item['si_num'];
$temp['p_id'] = $item['p_id'];
$temp['si_id'] = $item['si_id'];
$temp['so_no'] = $sOrder->so_no;
if($item['si_if_cancel'] == 0){
$returnItem[] = $temp;
}
}
}
return $returnItem;
}
/**
* 获取销售订单库存批次
* @param $request
*/
public function getSordersStock($request)
{
$params = $this->formatKeysfromArray($request->all(),'toUnderScore');
$repository = app(RhawnSoitemsRepository::class);
$result = $repository->getOrderItemsStockFromItemIds($params['order_item_id']);
$returnItemStock = [];
if($result && !empty($result)){
foreach($result as $res){
$temp = [];
$temp['dpd_num'] = $res['dpd_num'];
$temp['si_id'] = $res['si_id'];
$temp['pstk_id'] = $res['pstk_id'];
$temp['pstk_num'] = $res['pstk_num'];
$temp['pstk_no'] = $res['pstk_no'];
$temp['selected'] = true;
$temp['dpd_invoiced_status'] = '未开票';
if($res['dpd_invoiced'] > 0){
$temp['selected'] = false;
$temp['dpd_invoiced_status'] = '已开票';
}
$returnItemStock[] = $temp;
}
}
return $returnItemStock;
}
public function addSordersRefundTask($request)
{
$params = $this->formatKeysfromArray($request->all(),'toUnderScore');
$sOrder = app(RhawnSordersRepository::class)->getSorderFromOrderNo($params['order_no']);
if(!$sOrder){
throw new \LogicException('该订单编号不存在!',500);
}
if(isset($params['task_id']) && !empty($params['task_id'])){
if(!app(RhawnSorderRefundRepository::class)->find($params['task_id'])){
throw new \LogicException('该任务不存在!',500);
}
}
if($params['transfer_pre'] == 'true'){
$params['transfer_pre'] = 1;
}else{
$params['transfer_pre'] = 0;
}
//先查询库存信息
$repository = app(RhawnSoitemsRepository::class);
$stockResult = $repository->getOrderItemsStockFromItemIds(explode(',',$params['item_id']));
if(empty($stockResult) || !$stockResult){
throw new \LogicException('订单明细id不存在!',500);
}
// 验证库存和发货数量
if(!empty($params['refund_nums'])){
$pstk_ids = $refundNums = [];
foreach (explode(',',$params['refund_nums']) as $num) {
$pstkArr = explode('|', $num);
$refundNums[$pstkArr[0]] = $pstkArr[1];
$pstk_ids[] = $pstkArr[0];
}
//分组查询发货数量
$dbConnect = DB::connection('rhawn_mysql');
$dpdSum = $dbConnect->table('dpdetail')
->whereIn('pstk_id', $pstk_ids)
->where('dpd_invoiced', '=', 0)
->groupBy('pstk_id')
->select(DB::raw("sum(dpd_num) as num"),)
->get();
if (!$dpdSum || empty($dpdSum)) {
throw new \LogicException('【' . implode(',', $pstk_ids) . '】对应的配货单数据不存在', 500);
}
if (count($dpdSum) < count($refundNums)) {
throw new \LogicException('需要退货的配送单不存在或已开票', 500);
}
collect($dpdSum)->map(function ($dpd) use ($refundNums) {
foreach ($refundNums as $num) {
if ($num > $dpd) {
throw new \LogicException('退货数量大于购买数量', 500);
}
}
});
}
return app(RhawnSorderRefundRepository::class)->addRefundTask($params);
}
/**
* 删除销售订单退货任务
* @param $request
* @return mixed
*/
public function delSorderRefundTask($request)
{
$params = $this->formatKeysfromArray($request->all(),'toUnderScore');
if(isset($params['task_id']) && !empty($params['task_id'])){
if(!app(RhawnSorderRefundRepository::class)->find($params['task_id'])){
throw new \LogicException('该任务不存在!',500);
}
}
return app(RhawnSorderRefundRepository::class)->delRefundTask($params);
}
/**
* 获取订单退货任务
* @param $request
* @return array
*/
public function getSordersRefundTask($request)
{
$params = $this->formatKeysfromArray($request->all(),'toUnderScore');
if(!$params['page_size'] || $params['page_size'] == 0){
$params['page_size'] = 10;
}
$repostiroy = app(RhawnSorderRefundRepository::class);
$repostiroy->pushCriteria(new RhawnSorderRefundCriteria($request));
$tasks = $repostiroy->customPaginate($params['page_size']);
if($tasks){
$allItems = collect($tasks['data'])->map(function($item){
$contentArr= [];
$execArr = json_decode($item['exec_content'],true);
foreach($execArr as $key => $content){
switch($key){
case 'order_no' : $contentArr[] = '【销售订单号】:'.$content; break;
case 'refund_nums' :
if(!empty($content)){
$nums = explode(',',$content);
$subContentArr = [];
foreach($nums as $k => $num){
$temp = explode('|',$num);
$subContentArr[] = '<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;【批号id】:'.$temp[0];
$subContentArr[] = '<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;【退货数量】:'.$temp[1];
}
$contentArr[] = '【现货退货数量】:'.implode("", $subContentArr); break;
}else{
$contentArr[] = '【现货退货数量】:0'; break;
}
case 'handle_fee' : $contentArr[] = '【手续费费用】:'.$content; break;
case 'item_id' : $contentArr[] = '【销售订单明细项】:'.$content; break;
case 'transfer_pre' :
$content = $content == '1' ? '是' : '否';
$contentArr[] = '【是否转预存】:'.$content; break;
case 'futures_num' :
$contentArr[] = '【期货退货数量】:'.$content; break;
}
}
$user = AdminUsers::find($item['create_by']);
$item['create_by'] = $user->username;
$item['content_string'] = implode('<br />',$contentArr);
$item = array_merge($item,$execArr);
return $item;
});
$tasks['data'] = $allItems->toArray();
$tasks = $this->formatKeysfromArray($tasks);
}
return $tasks;
}
/**
* 通过任务id获取销售订单任务详情
* @param $request
* @return array
*/
public function getRhawnSorderDetailByTaskId($request)
{
$params = $this->formatKeysfromArray($request->all(),'toUnderScore');
$task = app(RhawnSorderRefundRepository::class)->find($params['task_id']);
if(!$task){
throw new \LogicException('任务不存在!',500);
}
$task = $task->toArray();
$content = json_decode($task['exec_content'],true);
$pstkNums = [];
if(!empty($content['refund_nums'])){
foreach(explode(',',$content['refund_nums']) as $num){
$numArr = explode('|',$num);
$pstkNums[$numArr[0]] = $numArr[1];
}
}
//获取销售订单item数据
$result = app(RhawnSoitemsRepository::class)->getOrderItemsStockFromItemIds(explode(',',$content['item_id']));
$returnItemStock = [];
if($result && !empty($result)){
foreach($result as $res){
$temp = [];
$temp['dpd_num'] = $res['dpd_num'];
$temp['si_id'] = $res['si_id'];
$temp['pstk_id'] = $res['pstk_id'];
$temp['pstk_num'] = $res['pstk_num'];
$temp['pstk_no'] = $res['pstk_no'];
$temp['p_cn_name'] = $res['p_cn_name'];
$temp['refund_nums'] = $pstkNums[$res['pstk_id']];
$temp['selected'] = true;
$temp['dpd_invoiced_status'] = '未开票';
if($res['dpd_invoiced'] > 0){
$temp['selected'] = false;
$temp['dpd_invoiced_status'] = '已开票';
}
$returnItemStock[] = $temp;
}
}
return $returnItemStock;
}
/**
* 手动执行脚本
* @param $request
*/
public function execSordersRefundTask($request)
{
$params = $this->formatKeysfromArray($request->all(),'toUnderScore');
$orderRefund = app(RhawnSorderRefundRepository::class)->find($params['task_id']);
$refundJob = (new RhawnSorderRefundJob($orderRefund->toArray()))->delay(100)->onQueue('slow');
app('Illuminate\Contracts\Bus\Dispatcher')->dispatch($refundJob);
}
/**
* 处理退货逻辑
* @param $refundInfo
*/
public function sOrderRefund($refundInfo,&$note)
{
$sOrder = app(RhawnSordersRepository::class)->getSorderItemsFromOrderNo($refundInfo->order_no);
if(!$sOrder){
throw new \LogicException('该订单号不存在!',500);
}
try{
$dbConnect = DB::connection('rhawn_mysql');
$dbConnect->beginTransaction();
// 处理订单退货项
foreach($sOrder->toArray() as $key => $orderitem){
if(in_array($orderitem['si_id'],explode(',',$refundInfo->item_id))) {
// 先处理源数据
$currentPrice = floatval($orderitem['si_discount']);
$currentAmount = floatval($orderitem['si_amount']);
// 退货剩余数量
$numArr = !empty($refundInfo->refund_nums) ? explode(',', $refundInfo->refund_nums) : '';
$futuresNum = $refundInfo->futures_num && $refundInfo->futures_num > 0 ? $refundInfo->futures_num : 0;
$refundNums = [];
// 预判断退货数量
if (!empty($numArr)) {
$pstk_ids = [];
foreach ($numArr as $num) {
$pstkArr = explode('|', $num);
$refundNumsArr[$pstkArr[0]] = $pstkArr[1];
$pstk_ids[] = $pstkArr[0];
}
$dpd = $dbConnect->table('dpdetail')
->whereIn('pstk_id', $pstk_ids)
->where('si_id',$orderitem['si_id'])
->where('dpd_invoiced', '=', 0)
->get();
foreach($dpd->toArray() as $d){
$refundNums[$d->pstk_id] = $refundNumsArr[$d->pstk_id];
}
//分组查询发货数量
/*$dpdSum = $dbConnect->table('dpdetail')
->whereIn('pstk_id', $pstk_ids)
->where('dpd_invoiced', '=', 0)
->groupBy('pstk_id')
->select(DB::raw("sum(dpd_num) as num"),)
->get();
if (!$dpdSum || empty($dpdSum)) {
throw new \LogicException('【' . implode(',', $pstk_ids) . '】对应的配货单数据不存在', 500);
}
if (count($dpdSum) < count($refundNums)) {
throw new \LogicException('需要退货的配送单不存在或已开票', 500);
}
collect($dpdSum)->map(function ($dpd) use ($refundNums) {
foreach ($refundNums as $num) {
if ($num > $dpd) {
throw new \LogicException('退货数量大于购买数量', 500);
}
}
});*/
}
// 如果是期货,强行初始一个数组执行一次
if ($futuresNum > 0 && empty($refundNums)) {
$refundNums[0] = $futuresNum;
}
if (!empty($refundNums)) {
foreach ($refundNums as $pstk_id => $num) {
//修改item数据项
$service = app(RhawnSoitemsRepository::class);
$soItem = $service->findWhere(['si_id' => $orderitem['si_id'], 'si_if_cancel' => 0]);
$soItem = current($soItem->toArray());
if (empty($soItem) || count($soItem) == 0) {
throw new \LogicException('购买项数据id:' . $orderitem['si_id'] . '数据不存在或已取消!', 500);
}
//如果有退货期货,检查退货期货数量是否大于当前期货数量
if ($futuresNum > 0) {
if ($pstk_id > 0) {
$dpdSum = $dbConnect->table('dpdetail')
->where('pstk_id', $pstk_id)
->where('si_id', $refundInfo->item_id)
->where('dpd_invoiced', '=', 0)
->groupBy('pstk_id')
->select(DB::raw("sum(dpd_num) as num"),)
->get()->first();
} else {
$dpdSum = $dbConnect->table('dpdetail')
->where('si_id', $refundInfo->item_id)
->where('dpd_invoiced', '=', 0)
->select(DB::raw("sum(dpd_num) as num"),)
->get()->first();
}
if (($soItem['si_num'] - $dpdSum->num) == 0) {
$futuresNum = 0;
if ($pstk_id == 0) {
throw new \LogicException('当前数据不存在期货,无法对期货进行退货', 500);
}
}
if ($futuresNum > 0) {
if ($futuresNum > ($soItem['si_num'] - $dpdSum->num)) {
throw new \LogicException('期货退货数量大于可退货数量', 500);
}
}
}
// 判断现货退货数量是否大于soitem的数量
if ($num > $soItem['si_num']) {
throw new \LogicException('现货退货数量大于可退货数量', 500);
}
// 如果有期货数量优先处理
if ($futuresNum > 0) {
$currentProcessNums = $futuresNum;
} else {
$currentProcessNums = $num;
}
//更新原本数据
$updateArr = [];
$createArr = [];
$updatedItem = [];
//如果取消的是全部
if (($currentProcessNums - $orderitem['si_num']) == 0) {
// 如果需要手续费
if (isset($refundInfo->handle_fee) && $refundInfo->handle_fee > 0) {
$createArr = $soItem;
unset($createArr['si_id']);
$createArr['si_num'] = $orderitem['si_num'];
$createArr['si_assigned_num'] = $createArr['si_num'];
$createArr['si_amount'] = bcsub($orderitem['si_amount'], $refundInfo->handle_fee, 2);
$createArr['si_discount'] = bcdiv($createArr['si_amount'], $orderitem['si_num'], 2);
$updateArr['si_num'] = $currentProcessNums;
//$updateArr['si_assigned_num'] = $updateArr['si_num'];
$updateArr['si_amount'] = $refundInfo->handle_fee;
$updateArr['si_discount'] = bcdiv($updateArr['si_amount'], $currentProcessNums, 2);
} else {
$updatedItem['cancel_si_id'] = $orderitem['si_id'];
}
} // 部分退货
else {
if ($futuresNum > 0) {
$updateArr['si_num'] = $orderitem['si_num'] - $futuresNum;
//$updateArr['si_assigned_num'] = $orderitem['si_assigned_num'] - $futuresNum;
} else {
$updateArr['si_num'] = bcsub($orderitem['si_num'], $currentProcessNums); // 如果数量只有1,且退货数量相等
//$updateArr['si_assigned_num'] = $updateArr['si_num'];
$updateArr['si_assigned_num'] = $orderitem['si_assigned_num'] - $currentProcessNums;
}
$updateArr['si_amount'] = bcmul(
$orderitem['si_discount'],
$updateArr['si_num'],
2
);
if (isset($refundInfo->handle_fee) && $refundInfo->handle_fee > 0) {
$updateArr['si_amount'] = bcadd($updateArr['si_amount'], $refundInfo->handle_fee, 2);
}
$updateArr['si_discount'] = bcdiv($updateArr['si_amount'], $updateArr['si_num'], 2);
// 新增
$createArr = $soItem;
unset($createArr['si_id']);
$createArr['si_num'] = $currentProcessNums;
if (isset($refundInfo->handle_fee) && floatval($refundInfo->handle_fee) > 0) {
$createArr['si_amount'] = abs(bcsub($currentAmount, $updateArr['si_amount'], 2));
$createArr['si_discount'] = bcdiv($createArr['si_amount'], $createArr['si_num'], 2);
} // 没有手续费的情况下
else {
$createArr['si_discount'] = $soItem['si_discount'];
$createArr['si_amount'] = bcmul($soItem['si_discount'], $currentProcessNums, 2);
}
$createArr['si_num'] = $currentProcessNums;
if ($futuresNum > 0) {
$createArr['si_assigned_num'] = 0;
} else {
$createArr['si_assigned_num'] = $createArr['si_num'];
}
if ($createArr['si_amount'] < 0) {
throw new \LogicException('手续费异常,处理失败!', 500);
}
}
if (!empty($updateArr)) {
$update = $service->update($updateArr, $soItem['si_id']);
$updatedItem['update'] = $update->toArray();
} else {
$updatedItem['update'] = $orderitem;
}
//判断是否能除尽
if (!empty($updateArr)) {
$amount = bcmul($updateArr['si_discount'], $updateArr['si_num'], 2);
//if ($updateArr['si_amount'] != $amount) {
if (bccomp($updateArr['si_amount'], $amount) != 0) {
$note[] = 'si_id = ' . $soItem['si_id'] . '的数据有除不尽的情况,请手工处理';
}
}
if (!empty($createArr)) {
$newItem = $service->create($createArr);
$updatedItem['create'] = $newItem->toArray();
// 如果是部分退货
if ($currentProcessNums > 0 || ($currentProcessNums == 0 && $refundInfo->handle_fee > 0)) {
$updatedItem['cancel_si_id'] = $updatedItem['create']['si_id'];
}
} else {
$updatedItem['create'] = $soItem;
$updatedItem['cancel_si_id'] = $updatedItem['create']['si_id'];
}
$updatedItem['total'] = $currentAmount;
echo $futuresNum;
// 如果没有期货数量,dpdetail只处理现货数量
if ($futuresNum == 0) {
// 获取实际现货数量
$dpdDetail = $dbConnect->table('dpdetail')
->where('si_id', $orderitem['si_id'])
->where('pstk_id', $pstk_id)
->get()->first();
if ($dpdDetail) {
// 更新当前记录
$dpUpdateArr = [];
$dpUpdateArr['dpd_num'] = $dpdDetail->dpd_num - $currentProcessNums;
$dpUpdateArr['dpd_amount'] = bcmul($updatedItem['update']['si_discount'], $dpUpdateArr['dpd_num'], 2);
// 出现全部退货
if ($dpUpdateArr['dpd_num'] == 0) {
if ($refundInfo->handle_fee > 0) {
$dpUpdateArr['dpd_num'] = $dpdDetail->dpd_num;
$dpUpdateArr['dpd_amount'] = bcmul($updatedItem['update']['si_discount'], $currentProcessNums, 2);
} // 如果没有手续费,只修改对应的si_id
else {
$dpUpdateArr['si_id'] = $updatedItem['create']['si_id'];
$dpUpdateArr['dpd_amount'] = $dpdDetail->dpd_amount;
$dpUpdateArr['dpd_num'] = $dpdDetail->dpd_num;
}
} // 如果不是全部退货
else {
if ($refundInfo->handle_fee > 0) {
$otherDpdDetail = $dbConnect->table('dpdetail')
->where('si_id', $orderitem['si_id'])
->whereNotIn('pstk_id', [$pstk_id])
->get()->first();
if ($otherDpdDetail) {
$otherUpdate = [];
$otherUpdate['dpd_amount'] = bcmul($updatedItem['update']['si_discount'], $otherDpdDetail->dpd_num, 2);
$dbConnect->table('dpdetail')
->where('dpd_id', $otherDpdDetail->dpd_id)
->update($otherUpdate);
}
}
}
$dbConnect->table('dpdetail')
->where('dpd_id', $dpdDetail->dpd_id)
->update($dpUpdateArr);
// 如果是部分退货
if (($currentProcessNums < $dpdDetail->dpd_num) || ($currentProcessNums == $dpdDetail->dpd_num && $refundInfo->handle_fee > 0)) {
//添加新的取消记录
$dpCreateArr = $dpdDetail;
unset($dpCreateArr->dpd_id);
$dpCreateArr->dpd_num = $currentProcessNums;
$dpCreateArr->dpd_amount = bcmul($updatedItem['create']['si_discount'], $currentProcessNums, 2);
$dpCreateArr->si_id = $updatedItem['create']['si_id'];
$dpId = $dbConnect->table('dpdetail')->insertGetId((array)$dpCreateArr);
}
}
}
//预存款和退款处理
$this->cancelAndTransPrePay($dbConnect, $updatedItem['cancel_si_id'], $refundInfo);
if ($futuresNum > 0) {
$futuresNum = 0;
$currentProcessNums = 0;
if (empty($numArr)) break;
} else {
break;
}
}
}
}
}
$dbConnect->commit();
}catch(\Exception $e){
$dbConnect->rollBack();
throw $e;
}
}
/**
* 取消并转预存
* @param $db
* @param $si_id
*/
protected function cancelAndTransPrePay($db,$si_id,$refundInfo)
{
//获取订单明细项
$sOrderItem = app(RhawnSoitemsRepository::class)->getSorderItemFromItemId($si_id);
$sOrderItem = current($sOrderItem->toArray());
if($sOrderItem['si_if_cancel'] == 1){
throw new \LogicException('已经取消过了,请不要重复操作!',500);
}
$sOrderDetail = app(RhawnSordersRepository::class)->getSorderDetailFromOrderId($sOrderItem['so_id']);
if(!$sOrderDetail){
throw new \LogicException('数据不存在!',500);
}
$sOrderDetail['express'] = 0;
foreach($sOrderDetail['items'] as $k=>$v){
if($v->p_id == 0){
$sOrderDetail['express'] = $v->si_amount;
unset($sOrderDetail['items'][$k]);
}
}
/*if($sOrderDetail['so_pay_status'] == 0){
throw new \LogicException('未完成付款的订单不能取消转预存款!',500);
}*/
if($sOrderDetail['so_pay_status'] == 1){
throw new \LogicException('部分付款的订单不能取消明细,请联系管理员!',500);
}
if($sOrderItem['pi_id'] > 0){
//判断对应的采购订单明细是否已经取消
$pOrderItems = $db->table('poitems')
->join('porders','poitems.po_id','porders.po_id')
->where('poitems.pi_id',$sOrderItem['pi_id'])
->first();
if(!$pOrderItems){
throw new \LogicException('查询采购订单明细 ['.$sOrderItem['pi_id'].'] 数据不存在!',500);
}
if($pOrderItems->pi_status != 3 && $refundInfo->cancel_porder == 1){
throw new \LogicException('请先取消采购订单:'.$pOrderItems->po_no.'中的对应采购订单明细!');
}
}
if($sOrderItem['si_assigned_num'] > 0){
$dp_status = array();
$invoiced_amount = 0;
$dpdetailInfos = $db->table('dpdetail')
->join('dispatch','dpdetail.dp_id','dispatch.dp_id')
->where('dpdetail.si_id',$sOrderItem['si_id'])
->get();
if(!$dpdetailInfos){
throw new \LogicException('dpdetail ['.$sOrderItem['si_id'].'] 配货单数据不存在!',500);
}
foreach($dpdetailInfos as $k=>$v){
$dp_status[] = $v->dp_status;
$invoiced_amount += $v->dpd_invoiced;
}
if($invoiced_amount != 0){
throw new \LogicException('已经开过发票,不能取消!',500);
}
$dp_status = array_unique($dp_status);
if(in_array('0',$dp_status) || in_array('1',$dp_status)){
throw new \LogicException('请物流部配合处理至已发货状态,再做取消操作!',500);
}
}
// 具体处理退货并转预存
$si_cancel_time = 0;
$siAmountTotal = $db->table('soitems')
->where('so_id',$sOrderItem['so_id'])
->where('si_id','<>',$si_id)
->where('si_if_cancel',0)
->sum('si_amount');
$siAmountTotalPid = $db->table('soitems')
->where('so_id',$sOrderItem['so_id'])
->where('si_id','<>',$si_id)
->where('si_if_cancel',0)
->where('p_id','>',0)
->sum('si_amount');
$soItem = app(RhawnSoitemsRepository::class)->find($si_id);
if($soItem){
if($soItem['si_assigned_num']){
$dp = $db->table('dpdetail')->where('si_id',$si_id)->get();
$dp = $dp->toArray();
foreach($dp as $k=>$v){
if($v->dp_id == 0 && $v->stk_id > 0){
//清除已配货记录
$stock = $db->table('stock')->where('stk_id',$v['stk_id'])->get();
$stock = current($stock->toArray());
$stock_data = array();
$stock_data['stk_lock_num'] = $stock->stk_lock_num - $v->dpd_num;
if($stock_data['stk_lock_num'] < 0){
$stock_data['stk_lock_num'] = 0;
}
$db->table('stock')
->where('stk_id',$v->stk_id)
->update($stock_data);
$db->table('dpdetail')
->delete($v->dpd_id);
$si_assigned_num = $soItem['si_assigned_num'] - $v->dpd_num;
app(RhawnSoitemsRepository::class)->update(['si_patch_status'=>'0','si_assigned_num'=>$si_assigned_num],$si_id);
}
}
}
}
$customer = $db->table('customers')
->where('cus_id',$sOrderDetail['cus_id'])
->first();
//判断是否是最后一条非运费明细
$note = $sOrderDetail['so_no'].'取消明细:'.$soItem['p_code'];
if($siAmountTotalPid > 0){
$refund_amount = $soItem['si_amount'];
if($sOrderDetail['so_pay_status'] > 0){
// 退款
if($refundInfo->transfer_pre == 0){
$refund_data = [];
$refund_data['r_company'] = $customer->cus_company;
$refund_data['r_amount'] = $refund_amount;
$refund_data['r_ctime'] = time();
$refund_data['r_note'] = $note;
$refund_data['r_bank_account'] = '';
$refund_data['r_confirm_note'] = '';
$db->table('refund')->insertGetId($refund_data);
}else{
$prepaylog_data = [];
$prepaylog_data['cus_id'] = $sOrderDetail['cus_id'];
$prepaylog_data['prepaylog_amount'] = $refund_amount;
$prepaylog_data['prepaylog_note'] = $note;
$prepaylog_data['prepaylog_date'] = time();
$prepaylog_data['prepaylog_time'] = time();
$prepaylog_data['prepaylog_operator'] = auth()->user()->id;
$prepaylog_data['prepaylog_unpay'] = 0;
$prepaylog_data['prepaylog_if_abnormal'] = 0;
$prepaylog_data['prepaylog_if_deposit'] = 0;
$prepaylog_data['prepaylog_if_deal'] = 0;
$prepayId = $db->table('prepaylog')->insertGetId($prepaylog_data);
$sum = $db->table('prepaylog')
->where('cus_id',$sOrderDetail['cus_id'])
->sum('prepaylog_amount');
$db->table('customers')
->where('cus_id',$sOrderDetail['cus_id'])
->update(['cus_prepay' => $sum]);
$si_cancel_time = time();
}
}
app(RhawnSordersRepository::class)->update(['so_total'=>$siAmountTotal],$sOrderItem['so_id']);
app(RhawnSoitemsRepository::class)->update(['si_if_cancel'=>'1','si_cancel_time'=>$si_cancel_time],$si_id);
}else {
if($sOrderDetail['so_pay_status'] > 0){
//得到退款金额
$sOrder = app(RhawnSordersRepository::class)->find($sOrderItem['so_id']);
if (!$sOrder) {
throw new \LogicException('数据不存在!', 500);
}
$sOrder = $sOrder->toArray();
$refund_amount = $sOrder['so_total'];
if($refundInfo->transfer_pre == 0){
$refund_data = array();
$refund_data['r_company'] = $customer->cus_company;
$refund_data['r_amount'] = $refund_amount;
$refund_data['r_ctime'] = time();
$refund_data['r_note'] = $note;
$refund_data['r_bank_account'] = '';
$refund_data['r_confirm_note'] = '';
$db->table('refund')->insertGetId($refund_data);
}else{
$prepaylog_data = [];
$prepaylog_data['cus_id'] = $sOrderDetail['cus_id'];
$prepaylog_data['prepaylog_amount'] = $refund_amount;
$prepaylog_data['prepaylog_note'] = $note;
$prepaylog_data['prepaylog_date'] = time();
$prepaylog_data['prepaylog_time'] = time();
$prepaylog_data['prepaylog_operator'] = auth()->user()->id;
$prepaylog_data['prepaylog_unpay'] = 0;
$prepaylog_data['prepaylog_if_abnormal'] = 0;
$prepaylog_data['prepaylog_if_deposit'] = 0;
$prepaylog_data['prepaylog_if_deal'] = 0;
$prepayId = $db->table('prepaylog')->insertGetId($prepaylog_data);
$sum = $db->table('prepaylog')
->where('cus_id', $sOrderDetail['cus_id'])
->sum('prepaylog_amount');
$db->table('customers')
->where('cus_id', $sOrderDetail['cus_id'])
->update(['cus_prepay' => $sum]);
$si_cancel_time = time();
}
}
app(RhawnSordersRepository::class)->update(['so_review_status' => '3', 'so_total' => '0'], $sOrderItem['so_id']);
app(RhawnSoitemsRepository::class)->update(['si_if_cancel' => '1', 'si_cancel_time' => $si_cancel_time], $si_id);
}
$db->table('logs')->insertGetId(
['l_obj'=>$sOrderItem['so_id'],'l_type'=>'sorders_mng','l_op'=>'cancelsi','l_op_name'=>'取消明细','l_note'=>$note,'l_timestamp'=>time(),'u_id'=>auth()->user()->id]
);
return true;
}
public function getRhawnSorderTaskLog($request)
{
$params = $this->formatKeysfromArray($request->all(),'toUnderScore');
if(!isset($params['type']) || empty($params['type'])){
$params['type'] = 'rhaw_nsorder_refund';
}
$taskService = app(ToolsTaskRepository::class);
$taskLogsList = $taskService->getTaskLogsFromType($params['type'],$params['task_id']);
return $taskLogsList;
}
}
......@@ -12,21 +12,10 @@
namespace App\Services;
use App\Repositories\Contracts\SysLogRepository;
use App\Repositories\Enums\ResponseCodeEnum;
use App\Support\Traits\Helpers;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Spatie\Permission\Models\Role;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use App\Repositories\Models\AdminUsers;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use App\Repositories\Enums\LogEnum;
class SysLogService
{
use Helpers;
protected $sysLogRepository = null;
public function __construct(SysLogRepository $sysLogRepository)
......@@ -34,13 +23,26 @@ class SysLogService
$this->sysLogRepository = $sysLogRepository;
}
public function addSysLog($request)
public function addOperationLogs($logsContent)
{
$requestContent = [];
$requestContent['content'] = $request->all();
//$requestContent['ip'] = $request->ip();
//$requestContent['path'] = $request->url();
$context = [
'content' => $logsContent,
'optime' => microtime(true),
];
logger_async(LogEnum::SYSTEM_OPERATION, $context)
->onConnection(\config('logging.request.connection'))
->onQueue(\config('logging.request.queue'));
}
public function addApiLogs($logsContent)
{
$context = [
'content' => $logsContent,
'optime' => microtime(true),
];
logger_async(LogEnum::SYSTEM_API, $context)
->onConnection(\config('logging.request.connection'))
->onQueue(\config('logging.request.queue'));
}
}
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Services\ThirdPlatform\Api;
use App\Repositories\Contracts\ThirdApiPlatformRepository;
use App\Services\ThirdPlatform\PlatformAbstractService;
use App\Support\Traits\HttpClientHelpers;
class IntegleApiService extends PlatformAbstractService
{
use HttpClientHelpers;
public function __construct(ThirdApiPlatformRepository $thirdApiPlatformRepository)
{
$this->setPlatformName('integle');
parent::__construct($thirdApiPlatformRepository);
}
/**
* 批量更新商品信息
* @param $product
*/
public function pushBatchUpdateProduct($product)
{
$this->getPlatformInfo($this->platformName);
if(!$this->platformInfo){
throw new \LogicException('第三方平台信息无法获取!',500);
}
try{
$params = [];
$params['ak'] = $this->platformInfo['platform_params']['ak'];
$params['product'] = $this->mergeApiMetaData($product);
$response = $this->getPostClient('http://suppliers.integle.com/openapi/chem/batch-save',$params);
return $this->apiResponse($response);
}catch(\Exception $e){
return $this->requestError($e);
}
}
/**
* 整理组装 api 数据
* @param $metaData
* @return array
*/
public function mergeApiMetaData($metaData)
{
if(empty($metaData)){
return [];
}
$mergeData = [];
foreach($metaData['rawList'] as $datas){
$tempData['in_product_id'] = $datas['r_code'];
$tempData['cas'] = $datas['c_cas'];
$tempData['cn_name'] = $datas['r_cn_name'];
$tempData['en_name'] = $datas['r_en_name'];
$tempData['brand'] = '罗恩';
$tempData['package'] = [];
if(isset($metaData['packageList'][$datas['r_code']])){
$package = $metaData['packageList'][$datas['r_code']];
$pack['in_product_id'] = $package['p_code'];
$pack['purity'] = $package['r_level'];
$pack['package_size'] = $package['p_pack'];
$pack['package_unit'] = $package['p_pack_unit'];
$pack['price'] = $package['p_price'];
$pack['ship_within_time'] = 0;
$pack['area_stock'] = ['location' => '上海', 'inventory' => $package['p_stock']];
$pack['promotion_tag'] = '';
$pack['status'] = $package['p_status'] == '1' ? 1 : 0;
array_push($tempData['package'],$pack);
}
array_push($mergeData,$tempData);
unset($tempData);
}
return $mergeData;
}
protected function apiResponse($response)
{
$returnResult = [];
$decodeResponse = json_decode($response,true);
$returnResult['resultContent'] = $decodeResponse;
$returnResult['status'] = false;
if($decodeResponse){
if($decodeResponse['status'] == 1){
$returnResult['status'] = true;
}
}
return $returnResult;
}
protected function requestError($response)
{
return [
'status' => false,
'resultContent' => [
'error_code' => $response->getCode(),
'error_message' => $response->getMessage()
],
];
}
}
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Services\ThirdPlatform\Api;
use App\Repositories\Contracts\ThirdApiPlatformRepository;
use App\Support\Traits\HttpClientHelpers;
class WuxiApiService
{
use HttpClientHelpers;
protected $platformInfo = null;
public function __construct()
{
$this->platformInfo = app(ThirdApiPlatformRepository::class)->getPlatformInfoByPlatformName('wuxi_appTec');
$this->platformInfo['platform_params'] = json_decode($this->platformInfo['platform_params'], true);
}
/**
* 批量更新商品信息
* @param $product
* @return bool
*/
public function pushBatchUpdateProduct($product){
if(!$this->platformInfo){
throw new \LogicException('第三方平台信息无法获取!',500);
}
try{
$params = [];
$params['chemicalProducts'] = $this->mergeApiMetaData($product);
$response = $this->getPostClient('https://api.uploadcatalog.com/api/v1/update',$params, [
$this->platformInfo['platform_params']['username'], $this->platformInfo['platform_params']['password']
]);
return $this->apiResponse($response);
}catch(\Exception $e){
return $this->requestError($e);
}
}
/**
* 整理组装 api 数据
* @param $metaData
* @return array
*/
public function mergeApiMetaData($metaData)
{
if(empty($metaData)){
return [];
}
$mergeData = [];
foreach($metaData['rawList'] as $datas){
$tempData['supplier_product_id'] = $datas['r_code'];
$tempData['mdl'] = '';
$tempData['cas'] = $datas['c_cas'];
$tempData['nu'] = '';
$tempData['chinese_name'] = $datas['r_cn_name'];
$tempData['english_name'] = $datas['r_en_name'];
$tempData['chemicalformula'] = '';
$tempData['purity'] = $datas['r_level'];
/*$tempData['usually_ships_days_min'] = '';
$tempData['usually_ships_within_days'] = '';
$tempData['backorder_lead_time'] = '';*/
$tempData['status'] = $datas['r_status'] == '1' ? 'ACTIVE' : 'INACTIVE';
$tempData['inventorys'][] = [
'type' => $datas['r_unit'],
'quantity' => floatval($datas['r_stock']),
'country' => 'CN',
'stock_status' => $datas['r_stock'] > 0 ? 'INSTOCK' : 'OUTSTOCK',
];
$tempData['package'] = [];
if(isset($metaData['packageList'][$datas['r_code']])){
$package = $metaData['packageList'][$datas['r_code']];
$pack['unit_description'] = $package['p_pack_unit'];
$pack['package_status'] = $package['p_status'] == '1' ? 'ACTIVE' : 'INACTIVE';
$pack['inventorys'] = [
'package_quantity' => $package['p_stock'],
'stock_status' => $package['p_stock'] > 0 ? 'INSTOCK' : 'OUTSTOK',
'country' => 'CN'
];
$pack['prices'] = [
'price' => $package['p_price'],
'currency' => 'RMB',
'status' => 'ACTIVE'
];
$pack['costs'] = [
'In_cost' => $package['p_avg_cost'],
'In_cost_currency' => 'RMB',
'status' => $package['p_stock'] > 0 ? 'ACTIVE' : 'INACTVIE',
];
$pack['wuxiPackagePricings'] = [
'discount'=> 0.00,
'currency' => 'RMB',
'status' => 'INACTIVE'
];
array_push($tempData['package'],$pack);
}
array_push($mergeData,$tempData);
unset($tempData);
}
return $mergeData;
}
protected function apiResponse($response)
{
$decodeResponse = json_decode($response,true);
if($decodeResponse){
if(!empty($decodeResponse['successProduct'])){
return true;
}
}
return false;
}
protected function requestError($response)
{
return false;
}
}
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Services\ThirdPlatform;
use App\Repositories\Contracts\ThirdApiPlatformRepository;
abstract class PlatformAbstractService
{
protected $thirdApiPlatformRepository = null;
protected $platformName = '';
protected $platformInfo = null;
public function __construct(ThirdApiPlatformRepository $thirdApiPlatformRepository)
{
$this->thirdApiPlatformRepository = $thirdApiPlatformRepository;
//app(ThirdApiPlatformRepository::class)->getPlatformInfoByPlatformName($this->platformName);
}
protected function setPlatformName($platformName){
$this->platformName = $platformName;
}
/**
* 根据平台名称查询平台的状态(关闭或开启)
* @param $platformName
*/
protected function checkApiPlatformStatus($platformName)
{
$status = false;
$platformStatus = $this->getPlatformInfo($platformName);
if($platformStatus){
$status = $platformStatus['platform_status'] == 1 ? true : false;
}
return $status;
}
protected function getPlatformInfo($platformName)
{
if($this->platformInfo == null){
$platform = $this->thirdApiPlatformRepository->getPlatformInfoByPlatformName($platformName);
if(!$platform){
return null;
}
$platform['platform_params'] = json_decode($platform['platform_params'], true);
$this->platformInfo = $platform;
}
return $this->platformInfo;
}
protected function batchUpdateProducts()
{
}
protected function batchUpdateApi($apiParams)
{
}
}
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Services;
use App\Export\BaseExport;
use App\Export\WuxiLab\WuxiLabExport;
use App\Repositories\Contracts\ThirdApiPlatformRepository;
use App\Services\Kafka\KafkaService;
use App\Services\ThirdPlatform\Api\WuxiApiService;
use App\Services\ThirdPlatform\PlatformAbstractService;
use longlang\phpkafka\Protocol\ApiVersions\ApiVersionsResponse;
class WuxiLabService extends PlatformAbstractService
{
public function __construct(ThirdApiPlatformRepository $thirdApiPlatformRepository)
{
$this->setPlatformName('wuxi_appTec');
parent::__construct($thirdApiPlatformRepository);
}
/**
* 批量更新商品
*/
public function batchUpdateProducts()
{
$status = $this->checkApiPlatformStatus($this->platformName);
if($status){
$this->getPlatformInfo($this->platformName);
$rhawnChemicalsService = app(RhawnChemicalsService::class);
$limit = $this->platformInfo['platform_params']['batchNums'];
$page = 0;
while(true) {
$rawList = $rhawnChemicalsService->getChemicalRawList($page * $limit, $limit);
if (!$rawList) {
break;
}
$rawIdList = [];
foreach ($rawList as $raw) {
$rawIdList[] = $raw['r_id'];
}
$packages = $rhawnChemicalsService->getChemicalPackage($rawIdList);
$newPackages = [];
if($packages){
foreach($packages as $pack){
$newPackages[$pack['r_code']] = $pack;
}
}
if(!empty($rawList)){
/*if(
$this->batchUpdateApi(
['rawList' => $rawList,'packageList' => $newPackages]
)
){
//$page = intval($count / $limit) * $limit;
$page ++;
usleep(3000);
}*/
app(KafkaService::class)->produerSend(
[
'params' => ['rawList' => $rawList,'packageList' => $newPackages],
'consumer' => 'App\Services\WuxiLabService',
'method' => 'batchUpdateApi'
]
);
}
break;
}
}
}
public function batchUpdateApi($updateData)
{
$result = app(WuxiApiService::class)->pushBatchUpdateProduct($updateData);
if($result){
if($result['status'] === false){
app(KafkaService::class)->produerSend(
[
'' =>'',
'params' => $updateData
]
);
}
}
unset($result['status']);
$logsContent = [
'apiParams' => $updateData,
'apiReturn' => $result
];
app(SysLogService::class)->addApiLogs($logsContent);
}
/**
* 初始化生成产品excel文档
*/
public function initCreateProductsToExcel($exportLimit)
{
$rhawnChemicalsService = app(RhawnChemicalsService::class);
$limit = $exportLimit;
$page = 0;
while(true) {
$rawList = $rhawnChemicalsService->getChemicalRawList($page * $limit, $limit);
if (!$rawList) {
break;
}
$rawIdList = [];
foreach ($rawList as $raw) {
$rawIdList[] = $raw['r_id'];
}
$packages = $rhawnChemicalsService->getChemicalPackage($rawIdList);
$newPackages = [];
if($packages){
foreach($packages as $pack){
$newPackages[$pack['r_code']] = $pack;
}
}
if(!empty($rawList)){
app(WuxiLabExport::class)->saveExcel(
['rawList' => $rawList,'packageList' => $newPackages]
);
}
break;
}
}
}
......@@ -58,7 +58,7 @@ trait Helpers
return $data;
}
public static function print($arr){
public static function printArr($arr){
echo "<pre>";
print_R($arr);
}
......
<?php
namespace App\Support\Traits;
use Illuminate\Support\Str;
trait HttpClientHelpers
{
protected function getPostClient($uri, $paramsBody, $auth = null, $json = true)
{
$client = app(\GuzzleHttp\Client::class);
$options = [];
if($json) {
$options['headers'] = [
'Content-type'=> 'application/json',
"Accept" => "application/json"
];
$options['json'] = $paramsBody;
}
else{
$options['form_params'] = $paramsBody;
}
if($auth && is_array($auth)){
$options['auth'] = $auth;
}
$options['debug'] = env('API_DEBUG');
$response = $client->request('post',$uri,$options);
return $response->getBody()->getContents();
}
}
<?php
namespace App\Support\Traits;
use longlang\phpkafka\Consumer\ConsumerConfig;
use longlang\phpkafka\Producer\ProducerConfig;
trait KafkaConfigHelpers
{
public function getProducerConfig($config)
{
$kafkaConfig = app(ProducerConfig::class);
$kafkaConfig->setBootstrapServer($config['host'].":".$config['port']);
$kafkaConfig->setUpdateBrokers(true);
$kafkaConfig->setAcks(-1);
return $kafkaConfig;
}
public function getConsumerConfig($config)
{
$kafkaConfig = new ConsumerConfig();
$kafkaConfig->setBroker([$config['host'].":".$config['port']]);
$kafkaConfig->setTopic($config['topic']); // 主题名称
$kafkaConfig->setGroupId($config['groupid']); // 分组ID
$kafkaConfig->setClientId($config['clientid']); // 客户端ID
$kafkaConfig->setGroupInstanceId($config['clientid']); // 分组实例ID
return $kafkaConfig;
}
}
......@@ -71,7 +71,6 @@ $app->singleton(
$app->configure('app');
$app->configure('auth');
$app->configure('broadcasting');
$app->configure('cache');
$app->configure('database');
$app->configure('filesystems');
......@@ -129,6 +128,7 @@ $app->routeMiddleware([
$app->register(App\Providers\AppServiceProvider::class);
$app->register(App\Providers\AuthServiceProvider::class);
$app->register(App\Providers\RepositoryServiceProvider::class);
//$app->register(App\Providers\KafkaServiceProvider::class);
//$app->register(App\Providers\ListenersEventServiceProvider::class);
//$app->register(App\Providers\EventServiceProvider::class);
......@@ -144,9 +144,13 @@ $app->register(\Jiannei\Enum\Laravel\Providers\LumenServiceProvider::class);
$app->register(\Jiannei\Response\Laravel\Providers\LumenServiceProvider::class);
$app->register(\Jiannei\Logger\Laravel\Providers\ServiceProvider::class);
$app->register(Maatwebsite\Excel\ExcelServiceProvider::class);
$app->register(Spatie\CronlessSchedule\CronlessScheduleServiceProvider::class);
//跨域问题
$app->register(Fruitcake\Cors\CorsServiceProvider::class);
/*ext
|--------------------------------------------------------------------------
| Load The Application Routes
......
......@@ -5,10 +5,10 @@
"license": "MIT",
"type": "project",
"require": {
"php": "^7.3|^8.0",
"php": "^7.4|^8.0",
"ext-json": "*",
"api-ecosystem-for-laravel/dingo-api": "^3.1",
"fruitcake/laravel-cors": "^3.0",
"fruitcake/laravel-cors": "^2.0",
"guzzlehttp/guzzle": "^7.3",
"illuminate/redis": "^8.34",
"jiannei/laravel-enum": "^3.0",
......@@ -17,12 +17,16 @@
"laravel/lumen-framework": "^8.0",
"laravelista/lumen-vendor-publish": "^8.0",
"league/fractal": "^0.19.2",
"longlang/phpkafka": "^1.2",
"maatwebsite/excel": "^3.1",
"prettus/l5-repository": "^2.7",
"spatie/laravel-cronless-schedule": "^1.1",
"spatie/laravel-permission": "^5.1",
"tymon/jwt-auth": "^1.0.2"
},
"require-dev": {
"fzaninotto/faker": "^1.9.1",
"laravel/sail": "1.7.0",
"mockery/mockery": "^1.3.1",
"phpunit/phpunit": "^9.3"
},
......
......@@ -9,13 +9,16 @@
* with this source code in the file LICENSE.
*/
namespace App\Repositories\Contracts;
return [
'command_job' => [
'integle' => [
'topic' => '',
'producer' => '',
'consumer' => '',
'datetime' => ''
],
'wuxi' => [
use Prettus\Repository\Contracts\RepositoryInterface;
/**
* Interface UserRepository.
*/
interface BhSoitemsRepository extends RepositoryInterface
{
}
]
],
];
<?php
use Maatwebsite\Excel\Excel;
return [
'exports' => [
/*
|--------------------------------------------------------------------------
| Chunk size
|--------------------------------------------------------------------------
|
| When using FromQuery, the query is automatically chunked.
| Here you can specify how big the chunk should be.
|
*/
'chunk_size' => 1000,
/*
|--------------------------------------------------------------------------
| Pre-calculate formulas during export
|--------------------------------------------------------------------------
*/
'pre_calculate_formulas' => false,
/*
|--------------------------------------------------------------------------
| Enable strict null comparison
|--------------------------------------------------------------------------
|
| When enabling strict null comparison empty cells ('') will
| be added to the sheet.
*/
'strict_null_comparison' => false,
/*
|--------------------------------------------------------------------------
| CSV Settings
|--------------------------------------------------------------------------
|
| Configure e.g. delimiter, enclosure and line ending for CSV exports.
|
*/
'csv' => [
'delimiter' => ',',
'enclosure' => '"',
'line_ending' => PHP_EOL,
'use_bom' => false,
'include_separator_line' => false,
'excel_compatibility' => false,
'output_encoding' => '',
],
/*
|--------------------------------------------------------------------------
| Worksheet properties
|--------------------------------------------------------------------------
|
| Configure e.g. default title, creator, subject,...
|
*/
'properties' => [
'creator' => '',
'lastModifiedBy' => '',
'title' => '',
'description' => '',
'subject' => '',
'keywords' => '',
'category' => '',
'manager' => '',
'company' => '',
],
],
'imports' => [
/*
|--------------------------------------------------------------------------
| Read Only
|--------------------------------------------------------------------------
|
| When dealing with imports, you might only be interested in the
| data that the sheet exists. By default we ignore all styles,
| however if you want to do some logic based on style data
| you can enable it by setting read_only to false.
|
*/
'read_only' => true,
/*
|--------------------------------------------------------------------------
| Ignore Empty
|--------------------------------------------------------------------------
|
| When dealing with imports, you might be interested in ignoring
| rows that have null values or empty strings. By default rows
| containing empty strings or empty values are not ignored but can be
| ignored by enabling the setting ignore_empty to true.
|
*/
'ignore_empty' => false,
/*
|--------------------------------------------------------------------------
| Heading Row Formatter
|--------------------------------------------------------------------------
|
| Configure the heading row formatter.
| Available options: none|slug|custom
|
*/
'heading_row' => [
'formatter' => 'slug',
],
/*
|--------------------------------------------------------------------------
| CSV Settings
|--------------------------------------------------------------------------
|
| Configure e.g. delimiter, enclosure and line ending for CSV imports.
|
*/
'csv' => [
'delimiter' => null,
'enclosure' => '"',
'escape_character' => '\\',
'contiguous' => false,
'input_encoding' => 'UTF-8',
],
/*
|--------------------------------------------------------------------------
| Worksheet properties
|--------------------------------------------------------------------------
|
| Configure e.g. default title, creator, subject,...
|
*/
'properties' => [
'creator' => '',
'lastModifiedBy' => '',
'title' => '',
'description' => '',
'subject' => '',
'keywords' => '',
'category' => '',
'manager' => '',
'company' => '',
],
],
/*
|--------------------------------------------------------------------------
| Extension detector
|--------------------------------------------------------------------------
|
| Configure here which writer/reader type should be used when the package
| needs to guess the correct type based on the extension alone.
|
*/
'extension_detector' => [
'xlsx' => Excel::XLSX,
'xlsm' => Excel::XLSX,
'xltx' => Excel::XLSX,
'xltm' => Excel::XLSX,
'xls' => Excel::XLS,
'xlt' => Excel::XLS,
'ods' => Excel::ODS,
'ots' => Excel::ODS,
'slk' => Excel::SLK,
'xml' => Excel::XML,
'gnumeric' => Excel::GNUMERIC,
'htm' => Excel::HTML,
'html' => Excel::HTML,
'csv' => Excel::CSV,
'tsv' => Excel::TSV,
/*
|--------------------------------------------------------------------------
| PDF Extension
|--------------------------------------------------------------------------
|
| Configure here which Pdf driver should be used by default.
| Available options: Excel::MPDF | Excel::TCPDF | Excel::DOMPDF
|
*/
'pdf' => Excel::DOMPDF,
],
/*
|--------------------------------------------------------------------------
| Value Binder
|--------------------------------------------------------------------------
|
| PhpSpreadsheet offers a way to hook into the process of a value being
| written to a cell. In there some assumptions are made on how the
| value should be formatted. If you want to change those defaults,
| you can implement your own default value binder.
|
| Possible value binders:
|
| [x] Maatwebsite\Excel\DefaultValueBinder::class
| [x] PhpOffice\PhpSpreadsheet\Cell\StringValueBinder::class
| [x] PhpOffice\PhpSpreadsheet\Cell\AdvancedValueBinder::class
|
*/
'value_binder' => [
'default' => Maatwebsite\Excel\DefaultValueBinder::class,
],
'cache' => [
/*
|--------------------------------------------------------------------------
| Default cell caching driver
|--------------------------------------------------------------------------
|
| By default PhpSpreadsheet keeps all cell values in memory, however when
| dealing with large files, this might result into memory issues. If you
| want to mitigate that, you can configure a cell caching driver here.
| When using the illuminate driver, it will store each value in a the
| cache store. This can slow down the process, because it needs to
| store each value. You can use the "batch" store if you want to
| only persist to the store when the memory limit is reached.
|
| Drivers: memory|illuminate|batch
|
*/
'driver' => 'memory',
/*
|--------------------------------------------------------------------------
| Batch memory caching
|--------------------------------------------------------------------------
|
| When dealing with the "batch" caching driver, it will only
| persist to the store when the memory limit is reached.
| Here you can tweak the memory limit to your liking.
|
*/
'batch' => [
'memory_limit' => 60000,
],
/*
|--------------------------------------------------------------------------
| Illuminate cache
|--------------------------------------------------------------------------
|
| When using the "illuminate" caching driver, it will automatically use
| your default cache store. However if you prefer to have the cell
| cache on a separate store, you can configure the store name here.
| You can use any store defined in your cache config. When leaving
| at "null" it will use the default store.
|
*/
'illuminate' => [
'store' => null,
],
],
/*
|--------------------------------------------------------------------------
| Transaction Handler
|--------------------------------------------------------------------------
|
| By default the import is wrapped in a transaction. This is useful
| for when an import may fail and you want to retry it. With the
| transactions, the previous import gets rolled-back.
|
| You can disable the transaction handler by setting this to null.
| Or you can choose a custom made transaction handler here.
|
| Supported handlers: null|db
|
*/
'transactions' => [
'handler' => 'db',
'db' => [
'connection' => null,
],
],
'temporary_files' => [
/*
|--------------------------------------------------------------------------
| Local Temporary Path
|--------------------------------------------------------------------------
|
| When exporting and importing files, we use a temporary file, before
| storing reading or downloading. Here you can customize that path.
|
*/
'local_path' => storage_path('framework/cache/laravel-excel'),
/*
|--------------------------------------------------------------------------
| Remote Temporary Disk
|--------------------------------------------------------------------------
|
| When dealing with a multi server setup with queues in which you
| cannot rely on having a shared local temporary path, you might
| want to store the temporary file on a shared disk. During the
| queue executing, we'll retrieve the temporary file from that
| location instead. When left to null, it will always use
| the local path. This setting only has effect when using
| in conjunction with queued imports and exports.
|
*/
'remote_disk' => null,
'remote_prefix' => null,
/*
|--------------------------------------------------------------------------
| Force Resync
|--------------------------------------------------------------------------
|
| When dealing with a multi server setup as above, it's possible
| for the clean up that occurs after entire queue has been run to only
| cleanup the server that the last AfterImportJob runs on. The rest of the server
| would still have the local temporary file stored on it. In this case your
| local storage limits can be exceeded and future imports won't be processed.
| To mitigate this you can set this config value to be true, so that after every
| queued chunk is processed the local temporary file is deleted on the server that
| processed it.
|
*/
'force_resync_remote' => null,
],
];
<?php
return [
'default' => env('KAFKA_CONNECTION', 'local'),
'kafka' => [
'host' => env('KAFKA_HOST', '127.0.0.1'),
'port' => env('KAFKA_PORT', '9092'),
'topic' => env('KAFKA_TOPIC', 'system_channel'),
'groupid' => env('KAFKA_GROUPID', 'apiGroup'),
'clientid' => env('KAFKA_CLIENTID', 'apiGroup'),
],
];
......@@ -71,6 +71,7 @@ return [
'retry_after' => 90,
'block_for' => null,
],
],
/*
......
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
/**
* Class CreatePostsTable.
*/
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->text('title');
$table->text('body');
$table->boolean('published');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('posts');
}
}
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
class CreateToolsTaskTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
$tableNames = 'tools_task';
Schema::create($tableNames, function (Blueprint $table) {
$table->id();
$table->string('name')->comment('任务名称');
$table->longText('exec_content')->comment('任务内容');
$table->enum('status',['notexec','running','error','finish'])->comment('任务状态');
$table->string('type')->comment('任务类型');
$table->longText('error_message')->nullable()->comment('错误信息');
$table->unsignedTinyInteger('create_by')->comment('创建人');
$table->unsignedTinyInteger('exec_nums')->default(0)->comment('执行次数');
$table->timestamps();
});
Schema::table($tableNames,function(Blueprint $table){
DB::statement('ALTER TABLE '.$table->getTable(). ' ROW_FORMAT=DYNAMIC;');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('tools_task');
}
}
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateSysLogTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('sys_log', function (Blueprint $table) {
$table->id();
$table->string('path')->comment('请求路径');
$table->string('ip')->comment('请求ip');
$table->longText('content')->comment('请求内容');
$table->string('type')->comment('请求类型');
$table->timestamp('date')->comment('请求时间');
$table->unsignedTinyInteger('create_by')->comment('创建人');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('sys_log');
}
}
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateTaskLogTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('task_log', function (Blueprint $table) {
$table->id();
$table->string('task_id')->comment('任务id');
$table->longText('content')->comment('执行内容');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('task_log');
}
}
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateThirdApiPlatform extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('third_api_platform', function (Blueprint $table) {
$table->id();
$table->string('platform_name')->nullable()->comment('平台名称');
$table->string('platform_title')->nullable()->comment('平台标题');
$table->string('platform_url')->comment('平台网址');
$table->string('platform_desc')->comment('平台描述');
$table->string('platform_icon')->comment('平台icon');
$table->string('platform_params')->comment('平台参数');
$table->enum('platform_type',['self','third'])->nullable()->comment('平台类型');
$table->string('platform_token')->nullable()->comment('平台token');
$table->unsignedTinyInteger('platform_status')->nullable()->comment('平台状态');
$table->timestamps();
});
$tableNames = 'third_api_platform';
$columnNames = 'platform_name';
Schema::table($tableNames,function(Blueprint $table) use ($tableNames,$columnNames){
DB::statement('ALTER TABLE '.$tableNames. ' ROW_FORMAT=DYNAMIC;');
$table->index([$columnNames]);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('third_api_platform');
}
}
......@@ -21,10 +21,7 @@ class DatabaseSeeder extends Seeder
//$this->call(PermissionsSeeder::class);
if (app()->environment() === 'local') {
$this->call(AdminUsersSeeder::class);
$this->call(MenusSeeder::class);
$this->call(RolesSeeder::class);
$this->call(PermissionsSeeder::class);
$this->call(ThridApiPlatformSeeder::class);
}
}
}
<?php
use Database\Factories\PostFactory;
use Illuminate\Database\Seeder;
use App\Support\Traits\Helpers;
use App\Repositories\Models\AdminUsers;
use Illuminate\Support\Facades\DB;
class AdminUsersSeeder extends Seeder
{
use Helpers;
protected $userList = [
[
'username' =>'admin',
'nickname' =>'admin',
'password' => 'admin123456',
'email' => 'admin@admin.com',
'token' => '',
'status' => 1,
'is_admin' => 1,
'lastlogin' => 0,
'created_at' => '',
'updated_at' => ''
]
];
public function run()
{
//$this->command->getOutput()->info('正在初始化管理员数据中.');
try{
DB::beginTransaction();
collect($this->userList)->map(function($user){
$admin = app(AdminUsers::class);
$user['password'] = $admin->encryptPassword($user['password']);
$user['token'] = $this->randomFromDevice(16);
$user['created_at'] = date('Y-m-d H:i:s',time());
$user['updated_at'] = date('Y-m-d H:i:s',time());
AdminUsers::insert([$user]);
});
DB::commit();
$this->command->getOutput()->info('初始化管理员数据成功.');
}catch(Exception $e){
$this->command->getOutput()->error('初始化管理员失败,原因:'.$e->getMessage());
DB::rollback();
}
}
}
<?php
use Illuminate\Database\Seeder;
use App\Repositories\Models\Menus;
use Illuminate\Support\Facades\DB;
class MenusSeeder extends Seeder
{
protected $menuList = [
[
'menu_name' => 'page_index',
'title' => '平台首页',
'menu_path' => '#',
'parent_id' => -1,
'menu_type' => 'top',
'menu_icon' => 'md-home',
'component' => '',
'status' => 1,
'is_show' => 1,
'sys_default' => 1,
'sort' => 1.0,
'created_by' => 0,
'created_at' => '',
'updated_at' => '',
'children' => [
[
'menu_name' => 'sys_manager',
'title' => '系统管理',
'menu_path' => '#',
'parent_id' => 0,
'menu_type' => 'page',
'menu_icon' => 'ios-settings',
'component' => 'Main',
'status' => 1,
'is_show' => 1,
'sys_default' => 1,
'sort' => 1.0,
'created_by' => 0,
'created_at' => '',
'updated_at' => ''
]
],
],
[
'menu_name' => 'page_doc',
'title' => '物料中心',
'menu_path' => '#',
'parent_id' => -1,
'menu_type' => 'top',
'menu_icon' => 'md-book',
'component' => '',
'status' => 1,
'is_show' => 1,
'sys_default' => 1,
'sort' => 1.0,
'created_by' => 0,
'created_at' => '',
'updated_at' => '',
'children' => [
[
'menu_name' => 'doc_manage',
'title' => '文档管理',
'menu_path' => '/doc-manage',
'parent_id' => 0,
'menu_type' => 'page',
'menu_icon' => 'md-albums',
'component' => 'Main',
'status' => 1,
'is_show' => 1,
'sys_default' => 1,
'sort' => 1.11,
'created_by' => 0,
'created_at' => '',
'updated_at' => ''
]
],
],
];
protected $subMenusList = [
'sys_manager' =>
[
[
'menu_name' => 'menu_permission',
'title' => '菜单权限管理',
'menu_path' => '/menus',
'parent_id' => 0,
'menu_type' => 'page',
'menu_icon' => 'md-menu',
'component' => 'sys/menu-manage/menuManage',
'status' => 1,
'is_show' => 1,
'sys_default' => 1,
'sort' => 1.10,
'created_by' => 0,
'created_at' => '',
'updated_at' => '',
'children' => [
[
'menu_name' => 'menu_permission_add',
'title' => '添加菜单',
'menu_path' => '#',
'parent_id' => 0,
'menu_type' => 'button',
'menu_icon' => '#',
'component' => '#',
'status' => 1,
'is_show' => 1,
'sys_default' => 1,
'sort' => 1.11,
'created_by' => 0,
'created_at' => '',
'updated_at' => '',
],
[
'menu_name' => 'menu_permission_edit',
'title' => '编辑菜单',
'menu_path' => '#',
'parent_id' => 0,
'menu_type' => 'button',
'menu_icon' => '#',
'component' => '#',
'status' => 1,
'is_show' => 1,
'sys_default' => 1,
'sort' => 1.11,
'created_by' => 0,
'created_at' => '',
'updated_at' => '',
],
[
'menu_name' => 'menu_permission_delete',
'title' => '删除菜单',
'menu_path' => '#',
'parent_id' => 0,
'menu_type' => 'button',
'menu_icon' => '#',
'component' => '#',
'status' => 1,
'is_show' => 1,
'sys_default' => 1,
'sort' => 1.11,
'created_by' => 0,
'created_at' => '',
'updated_at' => '',
]
]
],
[
'menu_name' => 'role_permission',
'title' => '角色权限管理',
'menu_path' => '/permission',
'parent_id' => 0,
'menu_type' => 'page',
'menu_icon' => 'md-contacts',
'component' => 'sys/role-manage/roleManage',
'status' => 1,
'is_show' => 1,
'sys_default' => 1,
'sort' => 1.11,
'created_by' => 0,
'created_at' => '',
'updated_at' => '',
'children' => [
[
'menu_name' => 'role_permission_add',
'title' => '添加角色',
'menu_path' => '#',
'parent_id' => 0,
'menu_type' => 'button',
'menu_icon' => '#',
'component' => '#',
'status' => 1,
'is_show' => 1,
'sys_default' => 1,
'sort' => 1.11,
'created_by' => 0,
'created_at' => '',
'updated_at' => '',
],
[
'menu_name' => 'role_permission_edit',
'title' => '编辑角色',
'menu_path' => '#',
'parent_id' => 0,
'menu_type' => 'button',
'menu_icon' => '#',
'component' => '#',
'status' => 1,
'is_show' => 1,
'sys_default' => 1,
'sort' => 1.11,
'created_by' => 0,
'created_at' => '',
'updated_at' => '',
],
[
'menu_name' => 'role_permission_delete',
'title' => '删除角色',
'menu_path' => '#',
'parent_id' => 0,
'menu_type' => 'button',
'menu_icon' => '#',
'component' => '#',
'status' => 1,
'is_show' => 1,
'sys_default' => 1,
'sort' => 1.11,
'created_by' => 0,
'created_at' => '',
'updated_at' => '',
],
[
'menu_name' => 'role_permission_editPermission',
'title' => '角色权限分配',
'menu_path' => '#',
'parent_id' => 0,
'menu_type' => 'button',
'menu_icon' => '#',
'component' => '#',
'status' => 1,
'is_show' => 1,
'sys_default' => 1,
'sort' => 1.11,
'created_by' => 0,
'created_at' => '',
'updated_at' => '',
],
[
'menu_name' => 'role_permission_setDefault',
'title' => '角色默认设置',
'menu_path' => '#',
'parent_id' => 0,
'menu_type' => 'button',
'menu_icon' => '#',
'component' => '#',
'status' => 1,
'is_show' => 1,
'sys_default' => 1,
'sort' => 1.11,
'created_by' => 0,
'created_at' => '',
'updated_at' => '',
]
]
],
[
'menu_name' => 'user_manage',
'title' => '用户管理',
'menu_path' => '/user-manage',
'parent_id' => 0,
'menu_type' => 'page',
'menu_icon' => 'md-person',
'component' => 'sys/user-manage/userManage',
'status' => 1,
'is_show' => 1,
'sys_default' => 1,
'sort' => 1.11,
'created_by' => 0,
'created_at' => '',
'updated_at' => '',
'children' => [
[
'menu_name' => 'user_permission_search',
'title' => '搜索用户',
'menu_path' => '#',
'parent_id' => 0,
'menu_type' => 'button',
'menu_icon' => '#',
'component' => '#',
'status' => 1,
'is_show' => 1,
'sys_default' => 1,
'sort' => 1.11,
'created_by' => 0,
'created_at' => '',
'updated_at' => '',
],
[
'menu_name' => 'user_permission_add',
'title' => '添加用户',
'menu_path' => '#',
'parent_id' => 0,
'menu_type' => 'button',
'menu_icon' => '#',
'component' => '#',
'status' => 1,
'is_show' => 1,
'sys_default' => 1,
'sort' => 1.11,
'created_by' => 0,
'created_at' => '',
'updated_at' => '',
],
[
'menu_name' => 'user_permission_edit',
'title' => '编辑用户',
'menu_path' => '#',
'parent_id' => 0,
'menu_type' => 'button',
'menu_icon' => '#',
'component' => '#',
'status' => 1,
'is_show' => 1,
'sys_default' => 1,
'sort' => 1.11,
'created_by' => 0,
'created_at' => '',
'updated_at' => '',
],
[
'menu_name' => 'user_permission_delete',
'title' => '删除用户',
'menu_path' => '#',
'parent_id' => 0,
'menu_type' => 'button',
'menu_icon' => '#',
'component' => '#',
'status' => 1,
'is_show' => 1,
'sys_default' => 1,
'sort' => 1.11,
'created_by' => 0,
'created_at' => '',
'updated_at' => '',
],
[
'menu_name' => 'user_permission_enable',
'title' => '启用用户',
'menu_path' => '#',
'parent_id' => 0,
'menu_type' => 'button',
'menu_icon' => '#',
'component' => '#',
'status' => 1,
'is_show' => 1,
'sys_default' => 1,
'sort' => 1.11,
'created_by' => 0,
'created_at' => '',
'updated_at' => '',
],
[
'menu_name' => 'user_permission_disable',
'title' => '禁用用户',
'menu_path' => '#',
'parent_id' => 0,
'menu_type' => 'button',
'menu_icon' => '#',
'component' => '#',
'status' => 1,
'is_show' => 1,
'sys_default' => 1,
'sort' => 1.11,
'created_by' => 0,
'created_at' => '',
'updated_at' => '',
]
]
],
],
'doc_manage' =>
[
[
'menu_name' => 'sys_doc',
'title' => '系统文档',
'menu_path' => '/doc-manage',
'parent_id' => 0,
'menu_type' => 'page',
'menu_icon' => 'ios-document',
'component' => 'doc-manage/framework',
'status' => 1,
'is_show' => 1,
'sys_default' => 1,
'sort' => 1.11,
'created_by' => 0,
'created_at' => '',
'updated_at' => ''
],
]
];
public function run()
{
//$this->command->getOutput()->info('正在初始化菜单数据中.');
try {
DB::beginTransaction();
foreach ($this->menuList as $menu) {
$menu['created_at'] = date('Y-m-d H:i:s', time());
$menu['updated_at'] = date('Y-m-d H:i:s', time());
$childrenItem = $menu['children'];
unset($menu['children']);
$id = Menus::query()->insertGetId($menu);
if (isset($childrenItem) && !empty($childrenItem)) {
foreach ($childrenItem as $children) {
$children['parent_id'] = $id;
$children['created_at'] = date('Y-m-d H:i:s', time());
$children['updated_at'] = date('Y-m-d H:i:s', time());
$childrenId = Menus::query()->insertGetId($children);
if (isset($this->subMenusList[$children['menu_name']]) && !empty($this->subMenusList[$children['menu_name']])) {
collect($this->subMenusList[$children['menu_name']])->map(function ($subMenus) use ($childrenId) {
$subMenus['parent_id'] = $childrenId;
$subMenus['created_at'] = date('Y-m-d H:i:s', time());
$subMenus['updated_at'] = date('Y-m-d H:i:s', time());
if(isset($subMenus['children']) && !empty($subMenus['children'])){
$subChildrenItem = $subMenus['children'];
unset($subMenus['children']);
$subMenuId = Menus::query()->insertGetId($subMenus);
if (isset($subChildrenItem) && !empty($subChildrenItem)) {
foreach ($subChildrenItem as $subChildren) {
$subChildren['parent_id'] = $subMenuId;
$subChildren['created_at'] = date('Y-m-d H:i:s', time());
$subChildren['updated_at'] = date('Y-m-d H:i:s', time());
Menus::query()->insertGetId($subChildren);
}
}
}else{
$subMenuId = Menus::query()->insertGetId($subMenus);
}
});
}
}
}
}
DB::commit();
$this->command->getOutput()->info('菜单数据初始化成功.');
}catch(Exception $e){
$this->command->getOutput()->error('初始化菜单失败,原因:'.$e->getMessage());
DB::rollback();
}
}
}
<?php
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
use App\Repositories\Models\Menus;
use App\Repositories\Models\AdminUsers;
class PermissionsSeeder extends Seeder
{
protected $defaultPermissionList = [
[
'name' => '查看操作',
'menu_id' => 0,
'action' => 'view',
'permission_type' => 'button',
'sys_default' => 1,
'remark' => '查看操作权限',
'guard_name' => '',
],
[
'name' => '添加操作',
'menu_id' => 0,
'action' => 'add',
'permission_type' => 'button',
'sys_default' => 1,
'remark' => '添加操作权限',
'guard_name' => '',
],
[
'name' => '编辑操作',
'menu_id' => 0,
'action' => 'edit',
'permission_type' => 'button',
'sys_default' => 1,
'remark' => '编辑操作权限',
'guard_name' => '',
],
[
'name' => '删除操作',
'menu_id' => 0,
'action' => 'delete',
'permission_type' => 'button',
'sys_default' => 1,
'remark' => '删除操作权限',
'guard_name' => '',
],
[
'name' => '清空操作',
'menu_id' => 0,
'action' => 'clear',
'permission_type' => 'button',
'sys_default' => 1,
'remark' => '清空操作权限',
'guard_name' => '',
],
[
'name' => '启用操作',
'menu_id' => 0,
'action' => 'enable',
'permission_type' => 'button',
'sys_default' => 1,
'remark' => '启用操作权限',
'guard_name' => '',
],
[
'name' => '禁用操作',
'menu_id' => 0,
'action' => 'disable',
'permission_type' => 'button',
'sys_default' => 1,
'remark' => '禁用操作权限',
'guard_name' => '',
],
[
'name' => '搜索操作',
'menu_id' => 0,
'action' => 'search',
'permission_type' => 'button',
'sys_default' => 1,
'remark' => '搜索操作权限',
'guard_name' => '',
],
[
'name' => '上传操作',
'menu_id' => 0,
'action' => 'upload',
'permission_type' => 'button',
'sys_default' => 1,
'remark' => '上传操作权限',
'guard_name' => '',
],
[
'name' => '导出操作',
'menu_id' => 0,
'action' => 'export',
'permission_type' => 'button',
'sys_default' => 1,
'remark' => '导出操作权限',
'guard_name' => '',
],
[
'name' => '导入操作',
'menu_id' => 0,
'action' => 'input',
'permission_type' => 'button',
'sys_default' => 1,
'remark' => '导入操作权限',
'guard_name' => '',
],
[
'name' => '分配权限操作',
'menu_id' => 0,
'action' => 'editPermission',
'permission_type' => 'button',
'sys_default' => 1,
'remark' => '分配权限操作权限',
'guard_name' => '',
],
[
'name' => '设为默认操作',
'menu_id' => 0,
'action' => 'setDefault',
'permission_type' => 'button',
'sys_default' => 1,
'remark' => '设为默认操作权限',
'guard_name' => '',
],
[
'name' => '其他操作',
'menu_id' => 0,
'action' => 'other',
'permission_type' => 'button',
'sys_default' => 1,
'remark' => '其他操作权限',
'guard_name' => '',
],
];
public function run()
{
//$this->command->getOutput()->info('正在初始化权限数据中.');
try{
DB::beginTransaction();
collect($this->defaultPermissionList)->map(function($permission){
$permission['guard_name'] = config('auth.defaults.guard');
$permission['created_at'] = date('Y-m-d H:i:s',time());
$permission['updated_at'] = date('Y-m-d H:i:s',time());
Permission::create($permission);
});
// 将初始化菜单进行权限绑定
$menu = app(Menus::class)->query();
$menuList = $menu->where('status',1)->get()->toArray();
collect($menuList)->map(function($menu){
$permission = [];
$permission['name'] = $menu['menu_name'];
$permission['menu_id'] = $menu['id'];
switch($menu['menu_type']){
case 'page' : $permission['action'] = $menu['menu_name'].'view'; break;
case 'button' : $permission['action'] = $menu['menu_name']; break;
default : $permission['action'] = '';
}
$permission['permission_type'] = 'menu';
$permission['sys_default'] = 0;
$permission['remark'] = $menu['menu_name'].'的相关权限';
$permission['guard_name'] = config('auth.defaults.guard');
Permission::create($permission);
});
//给用户组分配权限
$allPermission = Permission::where('guard_name', config('auth.defaults.guard'))->get();
$role = Role::all()->first();
$role->givePermissionTo($allPermission);
//给用户指定用户组
$admin = app(AdminUsers::class)->where('is_admin',1)->first();
$admin->assignRole($role);
$admin->syncPermissions($allPermission);
DB::commit();
$this->command->getOutput()->info('初始化权限数据成功.');
}catch(Exception $e){
$this->command->getOutput()->error('初始化权限失败,原因:'.$e->getMessage());
DB::rollback();
}
}
}
<?php
use App\Support\Traits\InitMenusAndPermission;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class RhSalesOrderRefundMenuSeeder extends Seeder
{
use InitMenusAndPermission;
public function run()
{
//$this->command->getOutput()->info('正在初始化菜单数据中.');
try {
DB::beginTransaction();
// 初始化菜单及权限
$menus = [
[
'menu_name' => 'rhawn_sorder_refund',
'title' => '罗恩销售订单退货',
'menu_path' => '/tools/rhawn-sorder-refund',
'parent_id' => 'tools',
'menu_type' => 'page',
'menu_icon' => 'ios-laptop',
'component' => 'tools/rhawn/sorders-refund',
'status' => 1,
'is_show' => 1,
'sys_default' => 1,
'sort' => 1.0,
'created_by' => 0,
'created_at' => '',
'updated_at' => '',
'action' => '',
],[
'menu_name' => 'rhawn_sorder_refund_add',
'title' => '添加任务',
'menu_path' => '#',
'parent_id' => 'rhawn_sorder_refund',
'menu_type' => 'button',
'menu_icon' => '#',
'component' => '#',
'status' => 1,
'is_show' => 1,
'sys_default' => 1,
'sort' => 1.0,
'created_by' => 0,
'created_at' => '',
'updated_at' => '',
'action' => 'add',
],[
'menu_name' => 'rhawn_sorder_refund_edit',
'title' => '编辑任务',
'menu_path' => '#',
'parent_id' => 'rhawn_sorder_refund',
'menu_type' => 'button',
'menu_icon' => '#',
'component' => '#',
'status' => 1,
'is_show' => 1,
'sys_default' => 1,
'sort' => 1.0,
'created_by' => 0,
'created_at' => '',
'updated_at' => '',
'action' => 'edit',
],[
'menu_name' => 'rhawn_sorder_refund_delete',
'title' => '删除任务',
'menu_path' => '#',
'parent_id' => 'rhawn_sorder_refund',
'menu_type' => 'button',
'menu_icon' => '#',
'component' => '#',
'status' => 1,
'is_show' => 1,
'sys_default' => 1,
'sort' => 1.0,
'created_by' => 0,
'created_at' => '',
'updated_at' => '',
'action' => 'delete',
],[
'menu_name' => 'rhawn_sorder_refund_execute',
'title' => '执行任务',
'menu_path' => '#',
'parent_id' => 'rhawn_sorder_refund',
'menu_type' => 'button',
'menu_icon' => '#',
'component' => '#',
'status' => 1,
'is_show' => 1,
'sys_default' => 1,
'sort' => 1.0,
'created_by' => 0,
'created_at' => '',
'updated_at' => '',
'action' => 'other',
],
];
$this->initMenu($menus);
DB::commit();
$this->command->getOutput()->info('菜单数据初始化成功.');
}catch(Exception $e){
$this->command->getOutput()->error('初始化菜单失败,原因:'.$e->getMessage());
DB::rollback();
}
}
}
<?php
use Illuminate\Database\Seeder;
use App\Repositories\Models\Menus;
use Illuminate\Support\Facades\DB;
use Spatie\Permission\Models\Role;
class RolesSeeder extends Seeder
{
protected $rolesList = [
[
'name' => 'admin',
'is_default' => 0,
'remark' => '超级管理员组,拥有最高权限',
'guard_name' => '',
'created_at' => '',
'updated_at' => ''
],
];
public function run()
{
//$this->command->getOutput()->info('正在初始化角色数据中.');
try{
DB::beginTransaction();
collect($this->rolesList)->map(function($role){
$role['guard_name'] = config('auth.defaults.guard');
$role['created_at'] = date('Y-m-d H:i:s',time());
$role['updated_at'] = date('Y-m-d H:i:s',time());
Role::create($role,$role['guard_name']);
});
DB::commit();
$this->command->getOutput()->info('初始化角色数据成功.');
}catch(Exception $e){
$this->command->getOutput()->error('初始化角色失败,原因:'.$e->getMessage());
DB::rollback();
}
}
}
<?php
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Spatie\Permission\Models\Role;
class ThridApiPlatformSeeder extends Seeder
{
use \App\Support\Traits\Helpers;
protected $thirdapiplatform = [
[
'platform_name' => 'integle',
'platform_title' => 'integle',
'platform_url' => 'http://suppliers.integle.com',
'platform_desc' => 'integle 接口平台',
'platform_icon' => '',
'platform_params' => '',
'platform_type' => 'third',
'platform_status' => '1',
'platform_token' => '',
],
[
'platform_name' => 'wuxi_appTec',
'platform_title' => '药明康德',
'platform_url' => 'https://api.uploadcatalog.com',
'platform_desc' => '药明康德接口平台',
'platform_icon' => '',
'platform_params' => '',
'platform_type' => 'third',
'platform_status' => '1',
'platform_token' => '',
],
];
public function run()
{
try{
DB::beginTransaction();
$thirdApiPlatformRepo = app(\App\Repositories\Eloquent\ThirdApiPlatformRepositoryEloquent::class);
foreach($this->thirdapiplatform as $platform){
switch($platform['platform_name']){
case "integle" :
$platform['platform_params'] = json_encode([
'ak' => '2irXmYG_TMa120jd_WhryIkBWsxCFeNG',
'batchNums' => '500'
]);
break;
case "wuxi_appTec" :
$platform['platform_params'] = json_encode([
'username' => '790087059@qq.com',
'password' => 'YXH1992xb',
'auth' => 'dGVzdDEyMzpwYXNzNDU2',
'batchNums' => '500'
]);
break;
}
$platform['platform_type'] = 'third';
$platform['platform_status'] = '1';
$platform['platform_token'] = $this->randomFromDevice(16);
$platform['created_at'] = date('Y-m-d H:i:s',time());
$platform['updated_at'] = date('Y-m-d H:i:s',time());
$thirdApiPlatformRepo->updateOrCreate($platform);
}
DB::commit();
$this->command->getOutput()->info('初始化数据成功.');
}catch(Exception $e){
$this->command->getOutput()->error('初始化数据失败,原因:'.$e->getMessage());
DB::rollback();
}
}
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment