初始版本

parents
Showing with 4801 additions and 0 deletions

Too many changes to show.

To preserve performance only 1000 of 1000+ files are displayed.

APP_ENV=local
APP_DEBUG=true
APP_KEY=SomeRandomString
APP_URL=http://localhost
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
* text=auto
*.css linguist-vendored
*.scss linguist-vendored
/node_modules
/public/storage
Homestead.yaml
Homestead.json
.idea
.env
websit.php
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class ClearDate extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'command:name';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$Arr=['purchase','purchase_delivery','purchase_delivery_items','purchase_items','putaway','putaway_items','upload_log'];
$DB=DB::connection('web');
foreach ($Arr as $k=>$v){
$result=$DB->table($v)->delete();
if($result){
echo $v.'清理成功';
}
}
}
}
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Foundation\Inspiring;
class Inspire extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'inspire';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Display an inspiring quote';
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$this->comment(PHP_EOL.Inspiring::quote().PHP_EOL);
}
}
<?php
namespace App\Console\Commands;
use App\Model\PurchaseDeliveryItemsModel;
use App\Model\PurchaseItemsModel;
use Illuminate\Console\Command;
class ReData extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'ReData';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$PurchaseItemsModel=new PurchaseDeliveryItemsModel();
$Puc=new PurchaseItemsModel();
$i=0;
$list=$PurchaseItemsModel->where('picking_id','=',31)->select('picking_items_id','picking_id','sku_id','delivery_items_id')->orderBy('picking_items_id','asc')->get()->toArray();
echo '总数-》'.count($list);
foreach ($list as $k=>$v){
$Find=$Puc->where('sku_id','=',$v['sku_id'])->where('picking_id','=',31)->select('picking_items_id')->first();
if(!$Find){
echo 'not Find=>'.$v['sku_id'];
continue;
}else{
$i++;
$result=$PurchaseItemsModel->where('delivery_items_id','=',$v['delivery_items_id'])->update(['picking_items_id'=>$Find['picking_items_id']]);
if(!$result){
echo 'fail->'.$v['sku_id'];
}
}
}
echo '成功->'.$i;
}
}
<?php
namespace App\Console\Commands;
use App\Model\PutawayItemsModel;
use App\Model\PutawayModel;
use Illuminate\Console\Command;
class Warehousing extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'Wh';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$Model=new PutawayItemsModel();
$Auth=$Model->where('putaway_id','=',58)->select('putaway_number','picking_sn','picking_price','sku_id')->get()->toArray();
foreach ($Auth as $k=>$v){
$data['data'][]=['picking_sn'=>$v['picking_sn'],'putaway_sn'=>'IN18063000001','goods_id'=>$v['sku_id'],'num'=>$v['putaway_number'],'cost'=>$v['picking_price']];
}
dump( $data['data']);
$data['data']=urlencode(json_encode($Auth));
$data['timestamp']=time();
$data['type']='sku.instock';
$token=WMSencryption($data);
$url=Config('website.serviceUrl').'/wmsapi/WebApiStockAuthPush?token='.$token;
$result=curl($url,$data,true);
$result=json_decode($result,true);
if(!$result || $result['errcode']!=0) return [30114,'基石推送入库失败'];
}
}
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
// Commands\Inspire::class,
Commands\ClearDate::class,
Commands\ReData::class,
Commands\Warehousing::class//手动入库
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
// $schedule->command('inspire')
// ->hourly();
}
}
<?php
namespace App\Events;
abstract class Event
{
//
}
<?php
namespace App\Exceptions;
use Exception;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
AuthorizationException::class,
HttpException::class,
ModelNotFoundException::class,
ValidationException::class,
];
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Exception $e
* @return void
*/
public function report(Exception $e)
{
\LogReport::write(\LogReport::anlyError($e->getMessage() , $e->getFile(), $e->getLine()));
parent::report($e);
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $e
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $e)
{
return parent::render($request, $e);
}
}
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller
{
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
/**
* Where to redirect users after login / registration.
*
* @var string
*/
protected $redirectTo = '/';
/**
* Create a new authentication controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
/**
* Get a validator for an incoming registration request.
*
* @param array $data
* @return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* @param array $data
* @return User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
}
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;
class PasswordController extends Controller
{
/*
|--------------------------------------------------------------------------
| Password Reset Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling password reset requests
| and uses a simple trait to include this behavior. You're free to
| explore this trait and override any methods you wish to tweak.
|
*/
use ResetsPasswords;
/**
* Create a new password controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest');
}
}
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesResources;
class Controller extends BaseController
{
use AuthorizesRequests, AuthorizesResources, DispatchesJobs, ValidatesRequests;
}
<?php
namespace App\Http\Controllers;
use App\Model\ConsignSaleModel;
use App\Model\PurchaseModel;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Model\ActivityModel;
use App\Model\ActivityModuleModel;
class WebApiController extends Controller
{
public function Entrance(Request $request, $id ){
$sign=Validate($request->input());
if($sign!==true){
$this->Export(10001,'签名错误',$sign);
}
$this->$id($request, $id);
}
private function Export($errcode=0,$errmsg='成功',$data=''){
ErrorLog($errcode,$errcode,$errmsg);
if(is_array($errcode)){
echo json_encode(['errcode'=>$errcode[0],'errmsg'=>$errcode[1],'data'=>!empty($errcode[2])?$errcode[2]:'']);
exit();
}else{
echo json_encode(['errcode'=>$errcode,'errmsg'=>$errmsg,'data'=>$data]);
exit();
}
}
private function ActivityInfo($request, $id){
$Model=new ActivityModel();
$data=$Model->WebApiActivityInfo();
$this->Export($data);
}
}
<?php
namespace App\Http\Controllers;
use App\Model\ConsignSaleModel;
use App\Model\PreSaleOrderModel;
use App\Model\PurchaseItemsModel;
use App\Model\PurchaseModel;
use App\Model\PutawayItemsModel;
use App\Model\PutawayModel;
use App\Model\Server\WmsToPurModel;
use App\Model\SupplierReceiptModel;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class WmsApiController extends Controller
{
public function Entrance(Request $request, $id ){
$this->$id($request, $id);
}
private function Export($errcode=0,$errmsg='成功',$data='',$total=''){
//ErrorLog($errcode,$errcode,$errmsg);
if(is_array($errcode)){
if(!empty($errcode['errcode'])){
echo json_encode(['errcode'=>$errcode['errcode'],'errmsg'=>$errcode['errmsg'],'data'=>!empty($errcode['data'])?$errcode['data']:'','total'=>!empty($errcode['total'])?$errcode['total']:''],JSON_UNESCAPED_UNICODE);
}else{
echo json_encode(['errcode'=>$errcode[0],'errmsg'=>$errcode[1],'data'=>!empty($errcode[2])?$errcode[2]:'','total'=>!empty($errcode[3])?$errcode[3]:''],JSON_UNESCAPED_UNICODE);
}
}else{
echo json_encode(['errcode'=>$errcode,'errmsg'=>$errmsg,'data'=>$data,'total'=>$total],JSON_UNESCAPED_UNICODE);
}
exit();
}
private function ExportLayui($errcode=0,$errmsg=0,$data=[],$count=0,$other=''){
if(is_array($errcode)){
echo json_encode(['code'=>$errcode[0],'msg'=>$errcode[1],'data'=>$errcode[2],'count'=>$errcode[3],'other'=>!empty($errcode[4]) ? $errcode[4] : '']);
}else{
echo json_encode(['code'=>$errcode,'msg'=>$errmsg,'data'=>$data,'count'=>$count,'other'=>$other]);
}
exit();
}
private function WebApiPutaway($request){
$PutawayModel=new PutawayModel();
$this->Export($PutawayModel->WebApiPutaway($request->Wmsdata));
}
private function WebApiRevokePay($request){
$PurModel=new PurchaseModel();
$this->Export($PurModel->WebApiRevokePay($request->Wmsdata));
}
/*
* 寄售接口
*/
private function WebApiConsignSale($request){
$this->Export((new ConsignSaleModel())->main($request->Wmsdata));
}
/*
* 超售批量插入订单数据
*/
private function WebApiPreSaleOrderAdd($request){
$this->Export((new PreSaleOrderModel())->bultInsert($request->Wmsdata));
}
/*
* 超售批量update订单数据
*/
private function WebApiPreSaleOrderUpdate($request){
$this->Export((new PreSaleOrderModel())->updateStatus($request->Wmsdata));
}
/*
* 获取单个供应商银行信息
* @param int limit 每页多少条
* @param int p 第几页
* @param int currency 币种
* @param int supplier_id 供应商ID
*/
private function WebApiSupplierReceiptList($request){
$this->ExportLayui((new SupplierReceiptModel())->getList(0,$request->Wmsdata));
}
/*
* 账期回写请款状态(部分请款,完全请款)
*/
private function WebApiPeriodPayStatus($request){
$PurModel=new PurchaseModel();
$this->Export($PurModel->PeriodPayStatus($request->Wmsdata));
}
/*
* wms出库(库内异常退货)推送信息到采购
*/
private function WebApiAbnormalStockReturn($request){
$res = (new WmsToPurModel())->WebApiAbnormalStockReturn($request->Wmsdata);
$this->Export($res);
}
/*
* 批量获取单个sku送货在途
* @param $sku_arr =[10197,10198,10199] 需要查询的sku_id数组
* @return [10197:50,10198:30,10199:50] 返回查询后的送货在途数据
*/
private function WebApiRunningNumber($request){
$res = (new PurchaseItemsModel())->RunningNumber($request->Wmsdata);
$this->Export($res);
}
}
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
];
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\CheckLogin::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
],
'api' => [
],
'webapi'=>[
],
'WmsApi'=>[
\App\Http\Middleware\WmsVerification::class,
]
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];
}
<?php
//日志目录位置
defined('REPORT_LOG_PATH') or define('REPORT_LOG_PATH', dirname($_SERVER['DOCUMENT_ROOT']).'/storage/logs/LogReport/');
//项目名
defined('REPORT_APP_NAME') or define('REPORT_APP_NAME', 'pur');
//单日志文件大小限制
defined('LOG_FILE_SIZE') or define('LOG_FILE_SIZE', 2097152); //2MB
// 设定错误和异常处理
error_reporting(0);
LogReport::auto();
class LogReport
{
static $handler = [
'finally_except' => ['Think\Think', 'appException'],
'finally_error' => ['Think\Think', 'appError'],
];
static $data = [
'msg' => '',// 错误信息
'msgCode' => '',// 自定义错误码 六位数字字符串 etc "100000"
'ts' => '',// 10位整形 时间戳
'dateStr' => '',// 日期 2018-06-28 21:24:09
'app' => '',// 应用名称
'serverIp' => '',// 服务器ip
'fileName' => '',// 文件名
'lineNo' => '',// 行数
'method' => '',// 函数名
];
/**
* 自动注册
* @return [type] [description]
*/
static function auto()
{
if (defined('APP_PATH')) {
self::register();
self::set();
} else {
self::$handler = array_map(function($v){
return [];
}, self::$handler);
}
}
/**
* 注册致命错误
* @return [type] [description]
*/
static function register()
{
register_shutdown_function('LogReport::fatalError');
}
/**
* 设置处理方法
*/
static function set()
{
set_error_handler('LogReport::appError');
set_exception_handler('LogReport::exception');
}
/**
* 错误数据格式
* @param string|array $e 错误内容|'message','file','line','code','method'
* @param string $file 错误文件
* @param string $line 错误行数
* @param string $code 错误码
* @param string $method 错误函数
* @return [type] [description]
*/
static function anlyError($e, $file = null, $line = null, $code = null, $method = null)
{
if (!is_array($e)) {
$e = [
'message' => $e,
'file' => !is_null($file) ? $file : '',
'line' => !is_null($line) ? $line : '',
'code' => !is_null($code) ? $code : '',
'method' => !is_null($method) ? $method : '',
];
}
$data = self::$data;
$data['msg'] = !empty($e['message']) ? $e['message'] : '';
$data['msgCode'] = str_pad($e['code'], 6, '0', STR_PAD_LEFT);
$data['ts'] = time();
$data['dateStr'] = date('Y-m-d H:i:s');
$data['app'] = REPORT_APP_NAME;
$data['serverIp'] = !empty($_SERVER['REMOTE_ADDR'])?$_SERVER['REMOTE_ADDR']:'0.0.0.0';
$data['fileName'] = !empty($e['file']) ? $e['file'] : '';
$data['lineNo'] = !empty($e['line']) ? $e['line'] : '';
$data['method'] = !empty($e['method']) ? $e['method'] : '';
return $data;
}
/**
* 致命错误处理
* @return [type] [description]
*/
static function fatalError()
{
if ($e = error_get_last()) {
switch ($e['type']) {
case E_ERROR:
case E_PARSE:
case E_CORE_ERROR:
case E_COMPILE_ERROR:
case E_USER_ERROR:
ob_end_clean();
self::write(self::anlyError($e));
break;
}
}
// exit();
}
/**
* 一般错误处理
* @param [type] $errno [description]
* @param [type] $errstr [description]
* @param [type] $errfile [description]
* @param [type] $errline [description]
* @return [type] [description]
*/
static function appError($errno, $errstr, $errfile, $errline)
{
switch ($errno) {
case E_ERROR:
case E_PARSE:
case E_CORE_ERROR:
case E_COMPILE_ERROR:
case E_USER_ERROR:
self::write(self::anlyError($errstr , $errfile, $errline));
break;
}
if (!empty(self::$handler['finally_error'])) {
call_user_func(self::$handler['finally_error'], $errno, $errstr, $errfile, $errline);
}
}
/**
* 异常处理
* @return [type] [description]
*/
static function exception($e)
{
self::write(self::anlyError($e->getMessage() , $e->getFile(), $e->getLine()));
if (!empty(self::$handler['finally_except'])) {
call_user_func(self::$handler['finally_except'], $e);
}
}
/**
* 日志记录
* @param string $log 日志内容
* @return [type] [description]
*/
static function write($log)
{
if (is_array($log)) {
$log = json_encode($log);
}
if (empty($log)) {
return false;
}
// 自动创建日志目录
if (!is_dir(REPORT_LOG_PATH)) {
mkdir(REPORT_LOG_PATH, 0755, true);
}
$name = date('Ymd');
$filename = REPORT_LOG_PATH.$name.'.log';
//检测日志文件大小,超过配置大小则备份日志文件重新生成
if (is_file($filename) && floor(LOG_FILE_SIZE) <= filesize($filename)) {
rename($filename, dirname($filename) . '/' . $name. '-' . time() . '.log');
}
$log .= PHP_EOL;
return file_put_contents($filename, $log, FILE_APPEND);
}
}
\ No newline at end of file
<?php
namespace App\Http\Middleware;
use Closure;
use App\Http\Output;
use App\Http\Error;
use Config;
use DB;
class CheckLogin
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$userId = $request->cookie('oa_user_id');
$skey = $request->cookie('oa_skey');
$isApi = false;
$pos = strpos($request->path(), 'api/');
if ($pos === 0)
$isApi = true;
$login = Config::get('website.login');
if (!$userId || !$skey || (string)((int)$userId) != $userId || !preg_match('/^[a-zA-Z0-9]+$/', $skey)) {
if ($isApi)
return ["errcode" => 401, "errmsg" => "没有登录"];
return redirect($login['login'] . '?redirect=' . urlencode($request->url()));
}
$cookie = 'oa_user_id=' . $userId . '; oa_skey=' . $skey;
// $client = new \GuzzleHttp\Client();
// $rsp = $client->request('GET', $login['check'], [
// 'headers' => ['Cookie' => $cookie],
// 'connect_timeout' => 10,
// 'timeout' => 30
// ]);
$rsp=curl($login['check'],'',false,false,$cookie);
// if ($rsp->getStatusCode() != 200) {
// Log::error("query {$login['check']} failed: code " . $rsp->getStatusCode());
// if ($isApi)
// return ['errcode' => -$rsp->getStatusCode(), 'errmsg' => '鉴权失败'];
// abort(500);
// }
if (!$rsp) {
// Log::error("query {$login['check']} failed: code ");
if ($isApi)
return ['errcode' =>10001, 'errmsg' => '鉴权失败'];
abort(500);
}
// $ret = json_decode($rsp->getBody());
$ret = json_decode(trim($rsp, "\xEF\xBB\xBF")); //去掉bom头
if ($ret->retcode != 0) {
if ($isApi)
return ["errcode" => $ret->retcode, "errmsg" => $ret->errMsg];
return redirect($login['login'] . '?redirect=' . urlencode($request->url()));
}
$user = $ret->data;
$user->code=DB::connection()->table('lie_intracode')->where('admin_id',$user->userId)->select('code_id')->first();
$user->header = $request->cookie('oa_header');
$request->user = $user;
return $next($request);
}
}
<?php
namespace App\Http\Middleware;
use Closure;
use App\Http\Output;
use App\Http\Controllers\LoginController;
use App\Http\Error;
use Config;
class JsonpCallback
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$callback = $request->input('callback', null);
$result = $next($request);
if (!$callback)
return $result;
if (strpos($request->path(), 'api/') !== 0)
return $result;
if (!preg_match('/^[_A-Za-z0-9]+$/', $callback))
return $result;
if (is_array($result)) {
$result = $callback . '(' . json_encode($result) . ')';
} else {
$result->setContent($callback . '(' . $result->content() . ')');
}
return $result;
}
}
<?php
namespace App\Http\Middleware;
use Closure;
use App\Http\Output;
use App\Http\Error;
use Config;
use DB;
use Request;
use RedisDB;
class WmsVerification
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$data=Request::only('data','timestamp');
$token=Request::only('token');
if(empty($data['data']) || empty($data['timestamp']) || empty($token)) return $this->Export(30001,'参数缺失');
$token=$token['token'];
if(WMSVerification($data,$token)!==true) return $this->Export(30002,'签名验证失败');
$request->Wmsdata=json_decode(urldecode($data['data']),true);
return $next($request);
}
private function Export($errcode=0,$errmsg='成功',$data='',$total=''){
if(is_array($errcode)){
return json_encode(['errcode'=>$errcode[0],'errmsg'=>$errcode[1],'data'=>!empty($errcode[2])?$errcode[2]:'','total'=>!empty($errcode[3])?$errcode[3]:''], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
}else{
return json_encode(['errcode'=>$errcode,'errmsg'=>$errmsg,'data'=>$data,'total'=>$total], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
}
}
}
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
abstract class Request extends FormRequest
{
//
}
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
Route::group(['middleware' => 'web'], function () {
Route::get('/', 'WebController@info');
Route::match(['get', 'post'],'/web/{key}', 'WebController@info');
Route::match(['get', 'post'],'/api/{key}', 'ApiController@Entrance');
Route::match(['get', 'post'],'/hd/{key}', 'HandleController@Entrance');
Route::get('/pushAmq', 'QueuedController@pushAmq');
Route::get('/pullAmq', 'QueuedController@pullAmq');
});
Route::group(['middleware' => 'webapi'], function () {
Route::match(['get', 'post'],'/WebApi/{key}', 'WebApiController@Entrance');
});
Route::group(['middleware' => 'WmsApi'], function () {
Route::match(['get', 'post'],'/wmsapi/{key}','WmsApiController@Entrance');
});
\ No newline at end of file
<?php
namespace App\Jobs;
use App\Model\OperationLogModel;
use DB;
use App\Jobs\Job;
use App\Model\AbnormalItemsModel;
use App\Model\AbnormalModel;
use App\Model\PurchaseDeliveryItemsModel;
use App\Model\PurchaseModel;
use App\Model\PurDeliveryModel;
use App\Model\SnModel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
/*
* 计算来料异常,存入异常表
*/
class AddAbnormal extends Job implements ShouldQueue
{
use InteractsWithQueue, SerializesModels;
private $delivery_sn; //来料通知单
private $putaway_sn; //入库单号
private $putaway_id; //入库id
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($delivery_sn,$putaway_sn,$putaway_id)
{
$this->delivery_sn = $delivery_sn;
$this->putaway_sn = $putaway_sn;
$this->putaway_id = $putaway_id;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$purchaseModel= new PurchaseModel();
$abModel = new AbnormalModel();
$abItemModel = new AbnormalItemsModel();
$deliveryModel = new PurDeliveryModel();
$deliveryItem = new PurchaseDeliveryItemsModel();
$strError = "来料通知单:".$this->delivery_sn." 入库单:".$this->putaway_sn ." 入库ID:".$this->putaway_id;//错误提示
try{
$con = DB::connection('web');
$con->beginTransaction();
#判断此来料是否已经是异常
$deliveryArr = $abModel->where('delivery_sn',$this->delivery_sn)->first();
if ($deliveryArr){
$strError .= '已经存在此来料异常';
$con->rollBack();
OperationLogModel::log(0,1,'add_abnormal_error',$this->putaway_id,$this->delivery_sn,$strError);
return $strError;
}
$deliveryArr = $deliveryModel->where('delivery_sn',$this->delivery_sn)->first();
if ($deliveryArr['status'] != 5){ //部分发货情况下是来料异常
$strError .= '此来料不是部分收货状态';
$con->rollBack();
OperationLogModel::log(0,1,'add_abnormal_error',$this->putaway_id,$this->delivery_sn,$strError);
return $strError;
}
$deliveryItemObj = $deliveryItem->where('delivery_id',$deliveryArr['delivery_id'])->get(); //来料明细
if (!$deliveryItemObj){
$strError .= '没有异常数据';
$con->rollBack();
OperationLogModel::log(0,1,'add_abnormal_error',$this->putaway_id,$this->delivery_sn,$strError);
return $strError;
}else{
$deliveryItemArr = $deliveryItemObj->toArray();
$purchaseObj = $purchaseModel->where('picking_sn',current($deliveryItemArr)['picking_sn'])->first(); //来料明细
if (!$purchaseObj){
$strError .= '不存在此采购单:'.current($deliveryItemArr)['picking_sn'];
$con->rollBack();
OperationLogModel::log(0,1,'add_abnormal_error',$this->putaway_id,$this->delivery_sn,$strError);
return $strError;
}
$purchaseArr = $purchaseObj->toArray();
}
$abArr=[
'abnormal_sn'=>(new SnModel())->Sn('abnormal_sn'),
'picking_id'=>$purchaseArr['picking_id'],
'picking_sn'=>$purchaseArr['picking_sn'],
'delivery_id'=>$deliveryArr['delivery_id'],
'delivery_sn'=>$this->delivery_sn,
'putaway_id'=>$this->putaway_id,
'putaway_sn'=>$this->putaway_sn,
'supplier_id'=>$purchaseArr['supplier_id'],
'supplier_code'=>$purchaseArr['supplier_code'],
'supplier_name'=>$purchaseArr['supplier_name'],
'abnormal_type'=>1,
'create_time' =>time()
];
//插入异常主表
$abnormalID = $abModel->insertGetId($abArr); //差异ID
foreach ($deliveryItemArr as $k=>$v){
if ($v['shipping_number'] > $v['putaway_number']){ //大于差异数量才插入
$cha_number = $v['shipping_number']-$v['putaway_number'];
$abItemArr[$k]=[
'abnormal_id'=>$abnormalID,
'picking_items_id'=>$v['picking_items_id'],
'abnormal_number' => $cha_number, //原差异数量
'real_number'=>$cha_number,
'withdraw_amount'=>sprintf('%.6f',$v['picking_price']*$cha_number),
'abnormal_items_type'=>2,
'deal_type1'=>2,
'deal_type2'=>2,
'create_time' =>time()
];
}
}
//插入异常明细表
$abItemModel->BatchADD($abItemArr);
$con->commit();
OperationLogModel::log(0,1,'add_abnormal_success',$this->putaway_id,$this->delivery_sn,$strError);
}catch (\Exception $e) {
$con->rollBack();
OperationLogModel::log(0,1,'add_abnormal_error',0,$this->delivery_sn,json_encode($e->getMessage()).$strError);
}
}
}
<?php
namespace App\Jobs;
use App\Jobs\Job;
use App\Model\PackingModel;
use App\Model\PurchaseDeliveryItemsModel;
use App\Model\PurchaseDeliveryModel;
use App\Model\PurchaseItemsModel;
use App\Model\PurchaseModel;
use App\Model\PurDeliveryItemsModel;
use App\Model\PurDeliveryModel;
use App\Model\SnModel;
use App\Model\UploadLogModel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use DB;
use Illuminate\Support\Facades\Storage;
use League\Flysystem\Exception;
/*
* 快速生成来料通知单
*/
class FastDelivery extends Job implements ShouldQueue
{
use InteractsWithQueue, SerializesModels;
private $picking_id; //采购单号
private $create_id; //创建用户id
private $shipping_sn; //发货单号
/**
* Create a new job instance.
* @return void
*/
public function __construct($picking_id,$create_id,$shipping_sn)
{
$this->picking_id=$picking_id;
$this->create_id=$create_id;
$this->shipping_sn=$shipping_sn;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$PurchaseModel = new PurchaseModel();
$PurchaseItemsModel = new PurchaseItemsModel();
$PurchaseDeliveryModel=new PurchaseDeliveryModel();
$UploadLogModel=new UploadLogModel();
$PurchaseDeliveryItemsModel = new PurchaseDeliveryItemsModel();
//判断是否符合条件
if ($PurchaseDeliveryModel->checkHas($this->picking_id)){
return "已存在有效的来料通知单,不能在此生成送货单!";
}
#生成任务日志
$logId=$UploadLogModel->insertAndGetId($this->create_id,5,$this->picking_id,[date('Y-m-d H:i',time()). '建立任务']);
if(!$logId){
return "生成任务失败";
}
try{
$con = DB::connection('web');
$con->beginTransaction();
$purchaseInfo = $PurchaseModel->where("picking_id",$this->picking_id)->first();
$purchaseItemsInfo = $PurchaseItemsModel->where("picking_id",$this->picking_id)->where("status",1)->get()->toArray();
$incomingSn = (new SnModel())->Sn('incoming_sn');
#插入来料通知主表
$deliveryId=$PurchaseDeliveryModel->GrDelivery($this->create_id,$incomingSn);
#插入来料通知明细表
$all_picking_number = 0;
foreach ($purchaseItemsInfo as $k=>$v){
$dataArr[]=[
'delivery_id'=>$deliveryId,
'picking_items_id'=>$v['picking_items_id'],
'picking_id'=>$this->picking_id,
'picking_sn'=>$purchaseInfo['picking_sn'],
'packing_id'=>$v['packing_id'],
'delivery_type'=>1,
'sku_id'=>$v['sku_id'],
'goods_name'=>$v['goods_name'],
'brand_id'=>$v['brand_id'],
'brand_name'=>$v['brand_name'],
'picking_price'=>$v['picking_price'],
'initial_price'=>$v['initial_price'], //原始价格
'shipping_number'=>$v['picking_number'],
];
$all_picking_number += $v['picking_number'];
}
$insert1 = $PurchaseDeliveryItemsModel->insert($dataArr);
if(!$insert1){
throw new Exception("插入来料通知明细失败");
}
#更新来料通知
$SpNumber['picking_type']=$purchaseInfo['picking_type'];
$SpNumber['purchase_type']=$purchaseInfo['purchase_type']; //采购类型
$SpNumber['supplier_id']=$purchaseInfo['supplier_id'];
$SpNumber['supplier_code']=$purchaseInfo['supplier_code'];
$SpNumber['supplier_name']=$purchaseInfo['supplier_name'];
$SpNumber['currency']=$purchaseInfo['currency'];
$SpNumber['shipping_sn']=$this->shipping_sn; //客户号,发货单号
$SpNumber['shipping_number']=$all_picking_number;
$update1 = $PurchaseDeliveryModel->SaveDelivery($deliveryId,$SpNumber);
if(!$update1){
throw new Exception("更新来料通知失败");
}
#更新采购单详情的发货总数
foreach ($dataArr as $k=>$v){
$update2 = $PurchaseItemsModel->where('picking_items_id','=',$v['picking_items_id'])->increment('shipping_number',$v['shipping_number']);
if(!$update2){
throw new Exception("更新采购发货总数失败");
}
}
$insert2 = $PurchaseDeliveryModel->PushAmq($incomingSn);
if(!$insert2){
throw new Exception("推送到WMS失败");
}
$UploadLogModel->UpdateLogArr($logId,'执行成功',2,[date('Y-m-d H:i',time()). '执行成功'],['remark'=>$incomingSn]);
$con->commit();
return "success";
}catch (\Exception $e) {
$con->rollBack();
$this->delete();
$UploadLogModel->UpdateLogArr($logId,$e->getMessage(),3,[date('Y-m-d H:i',time()). '执行失败']);
return $e->getMessage();
}
}
}
<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
abstract class Job
{
/*
|--------------------------------------------------------------------------
| Queueable Jobs
|--------------------------------------------------------------------------
|
| This job base class provides a central location to place any logic that
| is shared across all of your jobs. The trait included with the class
| provides access to the "onQueue" and "delay" queue helper methods.
|
*/
use Queueable;
}
<?php
namespace App\Jobs;
use App\Model\OperationLogModel;
use App\Model\PreSaleOrderModel;
use App\Model\PurchaseItemsModel;
use App\Model\PurchaseNeedItemsModel;
use App\Model\PurchaseNeedModel;
use App\Model\SnModel;
use App\Model\SupplierChannelModel;
use League\Flysystem\Exception;
use RedisDB;
use App\Jobs\Job;
use App\Model\SafeStockModel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use DB;
class PreSaleOrder extends Job implements ShouldQueue
{
use InteractsWithQueue, SerializesModels;
private $id;
private $delays;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($id,$delay=true)//默认为延时队列
{
$this->id=$id;
$this->delays=$delay;
}
/**
* Execute the job.
* @return void
*/
public function handle()
{
$Redis=RedisDB::connection();
$QueueID=$Redis->get('Pur_PreSaleOrderQueueID');
if($QueueID!=$this->id && $this->delays===true){
OperationLogModel::log(0,1,'pre_sale_order_queue_error',0,0,"'任务ID对比失败,当前任务终止,当前任务ID:'.$this->id.',记录任务ID:'.$QueueID");
return $this->delete();
}
$time=strtotime(date('Y-m-d',strtotime('+1 day')))+60*60*5+1800;//获取第二天凌晨5点半的时间戳
$delay=$time-time();
if($QueueID==$this->id && $this->delays===true){//重新推送明天的任务
$time=time();
dispatch((new PreSaleOrder($time))->delay($delay));
$Redis->set('Pur_PreSaleOrderQueueID',$time);
}
$this->run();
}
public function run(){
$preSaleOrderModel = new PreSaleOrderModel();
$PurchaseNeedModel = new PurchaseNeedModel();
$PurchaseNeedItemsModel = new PurchaseNeedItemsModel();
#整理数据
if ($this->delays===false){
$saleData = $preSaleOrderModel->whereRaw("is_collect=0 and status=1 ")->get();
}else{
$saleData = $preSaleOrderModel->whereRaw("is_collect=0 and status=1 and create_time < ".dateToTime(date("Y-m-d 00:00:00")))->get();
}
if (!$saleData->count()){
OperationLogModel::log(0,1,'pre_sale_order_queue_error',0,0,"没有超售数据");
return '没有超售数据';
}
$saleDataGroup = arrayGroup($saleData->toArray(),'sku_id');
$SupplierChannelModel = new SupplierChannelModel();
try{
$con = DB::connection('web');
$con->beginTransaction();
$temp = "";
foreach ($saleDataGroup as $sku_id=>$v){
$need_number = array_sum(array_column($v,'need_number'));
#查询旧需求,合并需求
$oldObj = $PurchaseNeedModel->where("status","1")->where("sku_id",$sku_id)->get();
if(!$oldObj->isEmpty()){
$oldArr = $oldObj->toArray();
$need_number = $need_number+array_sum(array_column($oldArr,'need_number')); //汇总
$PurchaseNeedModel->where("status","1")->where("sku_id",$sku_id)->delete(); //删除需求主表
}
#查询最新供应商和采购员
$supplier_id = $supplier_code = $supplier_name = "";
$purchaseInfo = $SupplierChannelModel
->from("purchase as t")
->select(DB::Raw("lie_t.supplier_id,lie_t.supplier_code,lie_t.supplier_name,lie_t.create_uid"))
->join('purchase_items as i', 't.picking_id', '=', 'i.picking_id')
->where("i.sku_id",$sku_id)
->orderBy("i.picking_id","desc")
->first();
$salesname_id = 0;
if ($purchaseInfo) {
$salesname_id = $purchaseInfo['create_uid'] ;
}
if(current($v)['picking_type'] == 1){ //自采
if ($purchaseInfo){
$supplier_id = $purchaseInfo['supplier_id']; //最新供应商
$supplier_code = $purchaseInfo['supplier_code'];
$supplier_name = $purchaseInfo['supplier_name'];
$salesname_id = $purchaseInfo['create_uid'] ;
}
}else{
$supplierObj = $SupplierChannelModel->where("supplier_id",current($v)['supplier_id'])->first();
$supplier_code = $supplierObj['supplier_code'];
$supplier_name = $supplierObj['supplier_name'];
}
#插入purchase_need
$insert1 = [ //需求ID
'picking_type'=>current($v)['picking_type'],
'supplier_id'=>$supplier_id == "" ? current($v)['supplier_id'] : $supplier_id,
'supplier_code'=>$supplier_code,
'supplier_name'=>$supplier_name,
'salesman_id'=>$salesname_id,
'need_sn'=>(new SnModel())->Sn('need_sn'),
'sku_id'=>$sku_id,
'encap'=>current($v)['encap'],
'goods_name'=>current($v)['goods_name'],
'brand_id'=>current($v)['brand_id'],
'brand_name'=>current($v)['brand_name'],
'mpq'=>current($v)['mpq'],
'packing_id'=>current($v)['packing_id'],
'need_number'=>$need_number,
'need_time'=>date("Ymd",current($v)['create_time']),
'create_time'=>time(),
];
// print_r($insert1);
// die();
$needId = $PurchaseNeedModel->insertGetId($insert1);
if (!$needId){
throw new Exception("插入采购需求失败");
}
if(!$oldObj->isEmpty()){
$PurchaseNeedItemsModel->whereIn("need_id",array_column($oldArr,'need_id'))->update(["need_id"=>$needId]); //修改管理需求明细
}
#插入purchase_need_items
$insert2 =[];
foreach ($v as $a=>$b){
array_push($insert2,[
'need_id'=>$needId,
'rec_id'=>@$b['rec_id']
]);
}
$insertStatus = $PurchaseNeedItemsModel->insert($insert2);
if (!$insertStatus){
throw new Exception("插入采购需求明细失败");
}
$temp = $temp.$needId.',';
}
//更新日志状态
if ($this->delays===false){
$update1 = $preSaleOrderModel->whereRaw("is_collect=0 and status=1 ")->update(['is_collect'=>1]);
}else{
$update1 = $preSaleOrderModel->whereRaw("is_collect=0 and status=1 and create_time < ".dateToTime(date("Y-m-d 00:00:00")))->update(['is_collect'=>1]);
}
OperationLogModel::log(0,1,'pre_sale_order_queue_success',0,0,"超售统计任务成功,插入purchase_need 的id为:$temp"); //日志
$con->commit();
return "success,插入purchase_need 的id为:$temp";
}catch (\Exception $e) {
$con->rollBack();
OperationLogModel::log(0,1,'pre_sale_order_queue_error',0,0,"超售统计任务统计失败:".$e->getMessage()); //日志
return "error:".$e->getMessage();
}
}
}
<?php
namespace App\Jobs;
use App\Jobs\Job;
use App\Model\PackingModel;
use App\Model\PurchaseModel;
use App\Model\PutawayItemsModel;
use App\Model\PutawayModel;
use App\Model\SupplierChannelModel;
use App\Model\SupplierReceiptModel;
use App\Model\UploadLogModel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use DB;
class PushFinancePeriod extends Job implements ShouldQueue
{
use InteractsWithQueue, SerializesModels;
private $id;
private $admin;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($ID,$admin)
{
$this->id=$ID;
$this->admin=$admin;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$LogModel=new UploadLogModel();
$data['remark']=$this->id;
$Log=[date('Y-m-d H:i',time()). '建立任务'];
$data['log']=json_encode($Log);
$data['create_time']=time();
$data['update_time']=time();
$data['type']=3;
$data['admin_id']=$this->admin;
$result=$LogModel->insertGetId($data);
if(!$result) return $this->delete();
$LogID=$result;
$PutawayModel=new PutawayModel();
$PutawayInfo=$PutawayModel->where('putaway_id','=',$this->id)->select('delivery_sn','putaway_sn','picking_type','purchase_type','supplier_id','pay_status')->first();//查入库主表
if(!$PutawayInfo) return $LogModel->UpdateLogArr($LogID,'没有找到这个入库单',3,$Log);
$PutawayInfo=$PutawayInfo->toArray();
//样品\赠品采购不需要推送账期
if ($PutawayInfo['purchase_type'] != 1){
return $LogModel->UpdateLogArr($LogID,'样品\赠品采购不需要推送账期',3,$Log);
}
//$this->closeOrder($PutawayInfo['delivery_sn']); //关闭来料通知,hcy9.12
if($PutawayInfo['pay_status']!=1 && $PutawayInfo['pay_status']!=4) return $LogModel->UpdateLogArr($LogID,'该入库单已经处理',3,$Log);
if($PutawayInfo['picking_type']!=1){//不是自营
$result=$PutawayModel->where('putaway_id','=',$this->id)->update(['pay_status'=>3]);
if(!$result) return $LogModel->UpdateLogArr($LogID,'非自营采购单处理失败',3,$Log);
return $LogModel->UpdateLogArr($LogID,'非自营采购单处理成功',2,$Log);
}
$PurchaseModel=new PurchaseModel();
$PutawayItemsModel=new PutawayItemsModel();
$PuItemArr=['picking_id','putaway_items_id','picking_sn','picking_items_id','sku_id','goods_name','brand_id','brand_name','encap','mpq','packing_id',
'picking_price','putaway_number'];
$PutawayList=$PutawayItemsModel->where('putaway_id','=',$this->id)->select($PuItemArr)->get()->toArray();//查出所有的采购商品
$PurArr=['picking_sn','picking_id','purchaser_id','supplier_id','supplier_code','supplier_name','pay_type','day_num','currency',
'picking_amount','create_time','picking_info','status'];
$PurchaseInfo=$PurchaseModel->where('picking_id','=',$PutawayList[0]['picking_id'])->select($PurArr)->first();//查采购单信息
if(!$PurchaseInfo) return $LogModel->UpdateLogArr($LogID,'没有找到这个采购单',3,$Log);
$PurchaseInfo=$PurchaseInfo->toArray();
if($PurchaseInfo['pay_type']!=1 && $PurchaseInfo['pay_type']!=2){//不是账期订单
$result=$PutawayModel->where('putaway_id','=',$this->id)->update(['pay_status'=>3]);
if(!$result){
return $LogModel->UpdateLogArr($LogID,'处理非账期入库单失败',3,$Log);
}else{
return $LogModel->UpdateLogArr($LogID,'处理非账期入库单成功',2,$Log);
}
}
$PurchaseInfo['picking_info']=json_decode($PurchaseInfo['picking_info'],true);
$PurchaseInfo['settle_party']=$PurchaseInfo['picking_info']['agent_type'];
$PurchaseInfo['putaway_id']=$this->id;
$PurchaseInfo['putaway_sn']=$PutawayInfo['putaway_sn'];
$SuArr=['supplier_consignee','supplier_telephone','supplier_mobile'];
$SuModel=new SupplierChannelModel();
$supplier_address = $SuModel->where('supplier_id', $PurchaseInfo['supplier_id'])->select($SuArr)->first();//查供应商信息
$PurchaseInfo['supplier_consignee'] = $supplier_address['supplier_consignee'];//联系人
$PurchaseInfo['supplier_telephone'] = empty($supplier_address['supplier_telephone'])?$supplier_address['supplier_mobile']:$supplier_address['supplier_telephone'];//联系电话
$PackingModel=new PackingModel();
$PackingList=$PackingModel->PackingList();
$PurchaseInfo['putaway_amount']=0;
foreach ($PutawayList as $k=>$v){
$v['putaway_price']=$v['picking_price'];
$v['packing_name']=empty($PackingList[$v['packing_id']])?'':$PackingList[$v['packing_id']];
$PurchaseInfo['putaway_amount'] +=$v['picking_price']*$v['putaway_number'];
unset($v['picking_price']);
unset($v['packing_id']);
$PurchaseInfo['sb_items'][$k]=$v;
}
$PurchaseInfo['putaway_amount']=round($PurchaseInfo['putaway_amount'],2);
unset($PurchaseInfo['picking_info']);
unset($PurchaseInfo['purchaser_id']);
$SupplierReModel=new SupplierReceiptModel();
$SuArr=['bank_name','bank_adderss','account_no','bank_code','branch_no','swift_code','account_name','account_adderss'];
$supplier_data = $SupplierReModel->where('supplier_id', $PurchaseInfo['supplier_id'])->select($SuArr)->first();
if(!$supplier_data) return false;
$supplier_data=$supplier_data->toArray();
DB::connection('web')->beginTransaction();
$result=$PutawayModel->where('putaway_id','=',$this->id)->update(['pay_status'=>2]);
if(!$result){
DB::connection('web')->rollback();
return $LogModel->UpdateLogArr($LogID,'更新支付状态失败',3,$Log);
}
//todo 不需要同步采购状态,hcy 2018.12.07
// if($PurchaseInfo['status']==6 || $PurchaseInfo['status']==10){
// $pay_status=$PurchaseInfo['status']==10?1:4;
// $PurchaseModel->where('picking_id','=',$PurchaseInfo['picking_id'])->update(['pay_status'=>$pay_status]);
// }
$PurchaseInfo['supplier']=$supplier_data;
$CurlData['data']=$PurchaseInfo;
$CurlData['data']=urlencode(json_encode($CurlData['data']));
$CurlData['timestamp']=time();
$token=WMSencryption($CurlData);
$url=Config('website.FinanceUrl').'/webapi/pushAccountPeriodOrders?token='.$token;
$result=curl($url,$CurlData,true);
$result=json_decode($result,true);
if(isset($result['err_code']) && $result['err_code']==0){
DB::connection('web')->commit();
return $LogModel->UpdateLogArr($LogID,'推送付款单成功',2,$Log);
}else{
DB::connection('web')->rollback();
$ErrInfo='财务系统返回失败';
$ErrInfo .=empty($result['err_msg'])?'无':$result['err_msg'];
$result=$PutawayModel->where('putaway_id','=',$this->id)->update(['pay_status'=>4]);
if(!$result){
return $LogModel->UpdateLogArr($LogID,$ErrInfo.',状态未记录',3,$Log);
}else{
return $LogModel->UpdateLogArr($LogID,$ErrInfo,3,$Log);
}
}
}
/*
* 关闭来料通知
*/
private function closeOrder($delivery_sn){
#完成wms采购单
$dataWms['type'] = 'cancelinstockorder';
$dataWms['from'] = 'purchase';
$dataWms['to'] = 'wms';
$dataWms['Timestamp'] = time();
$dataWms['jsonParas'] = json_encode(array('entity' => array(array('delivery_sn' =>$delivery_sn,'userid'=>0,'status'=>1))));
$colose = curl(Config('website.WmsServiceUrl'), http_build_query($dataWms), true,false,'');
$coloseRes = json_decode($colose,true);
if(empty($coloseRes['entity'][0]['Status'])){
return [30115,'来料通知单关闭失败,请与仓库人员确认来料通知单的处理情况后再作处理'];
}
return true;
}
}
<?php
namespace App\Jobs;
use App\Model\PurchaseModel;
use RedisDB;
use App\Jobs\Job;
use App\Model\SafeStockModel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class SafeStock extends Job implements ShouldQueue
{
use InteractsWithQueue, SerializesModels;
private $id;
private $delays;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($id,$delay=true)//默认为延时队列
{
$this->id=$id;
$this->delays=$delay;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$Redis=RedisDB::connection();
$QueueID=$Redis->get('Pur_SafeStockQueueID');
if($QueueID!=$this->id && $this->delays===true){
$Ding['su']=0;
$Ding['fail']=0;
$Ding['count']=0;
$Ding['info']=urlencode('任务ID对比失败,当前任务终止,当前任务ID:'.$this->id.',记录任务ID:'.$QueueID);
$Ding['yes_day']=date('Y-m-d H:i:s');
SendAlarmMsg($Ding,'PurSafeStock',['ymx@ichunt.com','hcy@ichunt.com']);
return $this->delete();
}
$time=strtotime(date('Y-m-d',strtotime('+1 day')))+60*60*5;//获取第二天凌晨5点的时间戳
$delay=$time-time();
if($QueueID==$this->id && $this->delays===true){//重新推送明天的任务
$time=time();
dispatch((new SafeStock($time))->delay($delay));
$Redis->set('Pur_SafeStockQueueID',$time);
}
$count=100;
$SafeModel=new SafeStockModel();
$PurModel=new PurchaseModel();
$fail=0;
$su=0;
$i=0;
for ($p=1;$p<$count;$p++){
$data['data']=['p'=>$p];
$data['data']=urlencode(json_encode($data['data']));
$data['timestamp']=time();
$token=WMSencryption($data);
$list=json_decode(curl(GenerateApiUrl('http://','footstone').'/wmsapi/WebApiSafeStock?token='.$token,$data,true),true);
if(!$list){
$Ding['su']=$su;
$Ding['fail']=$fail;
$Ding['count']=$i;
$Ding['yes_day']=date('Y-m-d H:i:s');
SendAlarmMsg($Ding,'PurSafeStock',['ymx@ichunt.com','hcy@ichunt.com']);
return $this->delete();
}
$Arr=['goods_id'=>'sku_id','status'=>'goods_status','packing'=>'packing_id'];
$count=$list['total']+1;
foreach ($list['data'] as $k=>$v){
$i++;
foreach ($v as $k1=>$v1){
if(!empty($Arr[$k1])){
$list['data'][$k][$Arr[$k1]]=$v[$k1];
unset($list['data'][$k][$k1]);
}
}
$list['data'][$k]['update_time']=time();
$find=$SafeModel->where('sku_id','=',$list['data'][$k]['sku_id'])->select()->first();
if($find){
$info=$PurModel->whereIn('purchase.status',[4,6])->join('purchase_items',function($join) use ($v){
$join->on('purchase.picking_id','=','purchase_items.picking_id')->where('purchase_items.sku_id','=',$v['goods_id']);
})->select('purchase_items.picking_number','purchase_items.shipping_number','purchase_items.putaway_number')->get()->toArray();
if(!$info){
$list['data'][$k]['purchase_num']=0;
$list['data'][$k]['in_num']=0;
}else{
$CountPur=0;
$CountIn=0;
$CountPt=0;
foreach ($info as $k1=>$v1){
$CountPur +=$v1['picking_number'];
$CountIn +=$v1['shipping_number'];
$CountPt +=$v1['putaway_number'];
}
$list['data'][$k]['purchase_num']=$CountPur-$CountPt;
$list['data'][$k]['in_num']=$CountIn-$CountPt;
}
$result=$SafeModel->where('sku_id','=',$list['data'][$k]['sku_id'])->update($list['data'][$k]);
}else{
$list['data'][$k]['create_time']=time();
$result=$SafeModel->insert($list['data'][$k]);
}
if(!$result){
$fail++;
}else{
$su++;
}
}
}
$Ding['su']=$su;
$Ding['fail']=$fail;
$Ding['count']=$i;
$Ding['info']=urlencode('下一个任务ID为:'.$Redis->get('Pur_SafeStockQueueID'));
$Ding['yes_day']=date('Y-m-d H:i:s');
SendAlarmMsg($Ding,'PurSafeStock',['ymx@ichunt.com','hcy@ichunt.com']);
}
}
<?php
namespace App\Jobs;
use App\Jobs\Job;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class SysLog extends Job implements ShouldQueue
{
use InteractsWithQueue, SerializesModels;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($adminID,$table,$id,$log)
{
$this->AdminID=$adminID;
$this->table=$table;
$this->id=$id;
$this->log=$log;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
}
}
<?php
namespace App\Model;
use App\Model\Server\FoostoneModel;
use App\Model\Server\PurToWmsModel;
use Illuminate\Database\Eloquent\Model;
use Request;
use DB;
class AbnormalModel extends Model
{
protected $connection='web';
protected $table='abnormal';
protected $primaryKey='abnormal_id';
public $timestamps = false;
//异常库存列表
public function getAbnormalList($export=array())
{
$arr = ['p', 'limit','self','create_time1','create_time2','deal_time1','deal_time2'
,'abnormal_sn','picking_sn','delivery_sn','putaway_sn','supplier_name','create_uid','abnormal_type','status'];
$input = Request::only($arr);
$input=TrimX($input,true,$arr);
// //查询数据
$list = $this->where(function ($query) use ($input) {
foreach ($input as $k => $v){
$v = trim($v);
switch ($k){
case "p":
case "limit":
continue;
break;
case "create_time1":
$query->where('create_time', '>=', strtotime($v));
break;
case "create_time2":
$query->where('create_time', '<=',strtotime($v));
break;
case "deal_time1":
$query->where('deal_time', '>=',strtotime($v));
break;
case "deal_time2":
$query->where('deal_time', '<=', strtotime($v));
break;
case "self":
$query->where('create_uid', '=', $v);
break;
default:
$query->whereIn($k, explode(',',trim($v,',')));
break;
}
}
});
$list = $list->orderBy('create_time','desc')->paginate($input['limit'], ['*'], 'p', $input['p'])->toArray();
//getSql();
if (!$list) return [20001, '没有数据'];
$UserModel = new UserModel();
$putAwayModel = new PutawayModel();
$PurDeliveryModel = new PurDeliveryModel();
$PurchaseModel = new PurchaseModel();
$abItemModel = new AbnormalItemsModel();
$fixed = Config('fixed');
$HLCurrency=Config('fixed.HLCurrency');
foreach ($list['data'] as $k=>&$v){
$userName = $UserModel->FinduserInfoName($v['create_uid']);
$v['create_uid_name'] = $userName ? $userName : "";
$v['abnormal_type'] =array_key_exists($v['abnormal_type'],$fixed['AbnormalType']) ? $fixed['AbnormalType'][$v['abnormal_type']] : "";
$v['abnormal_status'] =array_key_exists($v['status'],$fixed['AbnormalStatus']) ? $fixed['AbnormalStatus'][$v['status']] :"";
$v['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
$v['putaway_id'] = !empty($v['putaway_sn']) ? $putAwayModel->getPutawayId($v['putaway_sn']) : "";
$v['delivery_id'] = !empty($v['delivery_sn']) ? $PurDeliveryModel->getDeliveryId($v['delivery_sn']) :"";
$v['picking_id'] = !empty($v['picking_sn']) ? $PurchaseModel->getPickingId($v['picking_sn']) :"";
//统计差异数量
$v['abnormal_number']= $abItemModel->countAbnormalNumber($v['abnormal_id']);
$v['currency'] = $HLCurrency[$v['currency']];
}
return [0, '成功', $list['data'], $list['total']];
}
// 编辑
public function safeStockEdit()
{
$safe_id = Request::input('safe_id');
$safe_stock = Request::input('safe_stock');
return $this->where('safe_id', $safe_id)->update(['safe_stock'=>$safe_stock]);
}
//生成异常通知单号
public function getAbnormalSn($AdminID=0,$abnormal_sn=''){
if(!$abnormal_sn) return false;
$data['abnormal_sn']=$abnormal_sn;
$data['create_uid']=$AdminID;
$data['create_time']=time();
$data['status']=-1;
$result=$this->insertGetId($data);
if(!$result) return false;
return $result;
}
//反写异常库存订单
public function SaveAbnormal($abnormalID,$data){
$Arr=['picking_id','picking_sn','delivery_sn','putaway_sn','supplier_id','currency','exchange_rate','supplier_code','supplier_name','abnormal_type','status','create_uid'];
if(!$abnormalID || !is_array($data)) return false;
foreach ($data as $k=>$v){
if(!in_array($k,$Arr)) unset($data[$k]);
}
return $this->where('abnormal_id','=',$abnormalID)->update($data);
}
/*
* 异常订单详情
*/
public function abnormalDetail(){
$input = TrimX(Request::only(['abnormalId']),true,['abnormalId']);
$abnormalObj = $this->where('abnormal_id','=',$input['abnormalId'])->orWhere('abnormal_sn',$input['abnormalId'])->first(); //异常主表
if (!$abnormalObj) return false;
$abnormalArr = $abnormalObj->toArray();
$abnormalId = $abnormalArr['abnormal_id'];
$userModel = new UserModel();
$createName = $userModel->FinduserInfoName($abnormalArr['create_uid']);
$dealName = $userModel->FinduserInfoName($abnormalArr['deal_uid']);
$abnormalArr['create_uid'] = $createName ? $createName :""; //创建人用户名
$abnormalArr['deal_uid'] = $dealName ? $dealName :""; //处理人用户名
$abnormalArr['deal_time'] = timeToDate($abnormalArr['deal_time']);
$abnormalArr['create_time'] = timeToDate($abnormalArr['create_time']);
$itemsArr = DB::connection($this->connection)
->select("SELECT
p.goods_name,
p.brand_name,
p.packing_id,
p.mpq,
p.encap,
p.picking_price,
t.abnormal_items_id,
t.abnormal_number,
t.abnormal_items_type,
t.real_number,
t.withdraw_amount,
t.picking_items_id,
t.deal_type1,
t.deal_type2,
a.currency
FROM
lie_abnormal_items t,
lie_purchase_items p,
lie_purchase a
WHERE
t.picking_items_id = p.picking_items_id
and a.picking_id = p.picking_id
and t.abnormal_id = $abnormalId
order by t.picking_items_id ASC "); //异常明细
//取出包装方式
$PackingModel = new PackingModel();
$PackList = $PackingModel->PackingList();
$Currency = Config('fixed.Currency');
$i = 0;
$itemGroupArr = arrayGroup($itemsArr,'picking_items_id');
foreach ($itemsArr as $k=>&$v){
$v['packing_id'] = $PackList[$v['packing_id']]; //转换包装
$v['currency'] = $Currency[$v['currency']]; //转换币种
$v['k'] = $v['abnormal_number'] > 0 ? $i+1: "";
$v['abnormal_numbers'] = current($itemGroupArr[$v['picking_items_id']])['abnormal_number'];
}
return ['itemsArr'=>$itemsArr,'abnormalArr'=>$abnormalArr];
}
/*
* 取消异常
*/
public function cancelAbnormal($abnormal_id){
$abInfo = $this->where("abnormal_id",$abnormal_id)->first();
$abItems = $this
->select("i.sku_id","a.real_number")
->from("abnormal_items as a")
->join("purchase_items as i","a.picking_items_id","=","i.picking_items_id")
->where("a.abnormal_id",$abnormal_id)
->get()->toArray();
if ($abInfo['abnormal_type'] == 2){ //库内异常要回滚订单
#通知仓库订单撤销
//状态:-10已取消 -1草稿,1待审核,2审核通过,3审核驳回 4已完成
if ($abInfo['status'] == 2){ //审核通过,需要撤销订单
$cancel = (new PurToWmsModel())->CancelOrder($abnormal_id,2);
if(empty($cancel['entity'][0]['Status']) ){
jsonError("订单撤销失败".isset($cancel['entity'][0]['Message'])?$cancel['entity'][0]['Message']:'');
}
}
$unlockSku = array_column($abItems,'real_number','sku_id');
#基石回滚库存
$unlockRes = (new FoostoneModel())->unlockSku($abnormal_id,$unlockSku,1);
if ($unlockRes['errcode'] != 0) {
jsonError("基石回滚库存失败,order_id: $abnormal_id sku_json: ".json_encode($unlockSku)." return: ".$unlockRes['errmsg']);
}
}
$pan = $this->where("abnormal_id",$abnormal_id)->update(['status'=>-10]);
if (!$pan){
jsonError("更新状态失败");
}
jsonSucces("取消成功!");
}
}
\ No newline at end of file
<?php
namespace App\Model;
use DB;
use Illuminate\Database\Eloquent\Model;
//公共模型,存放一些公共配置
class CommonModel extends Model
{
//获取省市县
public function getRegionAll()
{
$provinces = array(); $citys = array(); $towns = array();
$list = DB::connection('order')->table('lie_region')->orderBy('region_id', 'asc')->get();
foreach (@$list as $val) {
if (!$val['parent_id']) continue;
switch ($val['region_type']) {
case 1:
$provinces[$val['parent_id']]['parent_id'] = $val['parent_id'];
$provinces[$val['parent_id']]['children'][] = $val;
break;
case 2:
$citys[$val['parent_id']]['parent_id'] = $val['parent_id'];
$citys[$val['parent_id']]['children'][] = $val;
break;
case 3:
$towns[$val['parent_id']]['parent_id'] = $val['parent_id'];
$towns[$val['parent_id']]['children'][] = $val;
break;
}
}
echo json_encode(array(
'errcode'=>0,
'errmsg'=>'success',
'provinces'=> $provinces,
'citys'=> $citys,
'towns'=> $towns
),true);
}
//获取省市县名称
public function getRegionName($region_id){
if (empty($region_id)){
return "";
}
$list = DB::connection('order')->table('lie_region')->select("region_name")->where("region_id",$region_id)->get();
return !$list ? "" : current($list)['region_name'];
}
}
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
use Excel;
class ContractModel extends Model
{
protected $connection=false;
protected $table=false;
public $timestamps = false;
function CnContract($array,$Items){
$FileName='采购合同(编码'.$array['picking_sn'].')';
Excel::create($FileName, function ($excel) use ($array, $Items) {
$excel->sheet('采购合同', function ($sheet) use ($array, $Items) {
//设置宽度
$sheet->setWidth(array(
'A' => '8.11',
'B' => '9.56',
'C' => '8.11',
'D' => '8.11',
'E' => '8.11',
'F' => '8.11',
'G' => '7.11',
'H' => '9.11',
'I' => '16'
));
//设置页边距
$sheet->setPageMargin(array(
0.7, 0.7, 0.7, 0.7
));
$count=count($Items);
$Arr=Config('fixed.ExcelSet');
//处理位置
$ConfArr=$Arr['conf'];
foreach ($ConfArr as $k=>$v){
foreach ($v as $k1=>$v1){
foreach ($v1 as $k2=>$v2){
if(strpos($v2,'+')){
preg_match_all('/\d+/',$v2,$row);//截取行
$ConfArr[$k][$k1][$k2]=(int)$row[0][0]+(int)$count;//重新结算位置
}
}
}
}
foreach ($ConfArr as $k=>$v) {
foreach ($v as $k1=>$v1){
$sheet->mergeCells($k.$v1[0].':'.$v1[1].$v1[2]);
}
}
//填充数据
$ValuesArr=$Arr['values'];
foreach ($ValuesArr as $k=>$v){
foreach ($v as $k1=>$v1){
$value=$array[$v1[1]];
empty($v1[2]) || $value=$value[$v1[2]];
if(strpos($v1[0],'+')) {
preg_match_all('/\d+/', $v1[0], $row);//截取行
$rownum=(int)$row[0][0]+(int)$count;
$sheet->setCellValue($k.$rownum, $value);
}else{
$sheet->setCellValue($k.$v1[0], $value);
}
}
}
//处理详细得位置
for($i=15;$i<$count+16;$i++){
$sheet->mergeCells('B'.$i.':C'.$i);
}
//填充详细数据
$rownum=15;
$i=1;
foreach ($Items as $k=>$v){
$sheet->setCellValue('A'.$rownum, $i);
$sheet->setCellValue('B'.$rownum, $v['goods_name']);
$sheet->setCellValue('D'.$rownum, $v['brand_name']);
$sheet->setCellValue('E'.$rownum, $v['picking_number']);
$sheet->setCellValue('F'.$rownum, $v['batch_number']);
$sheet->setCellValue('G'.$rownum, $v['delivery_time']);
$sheet->setCellValue('H'.$rownum, $v['picking_price']);
$sheet->setCellValue('I'.$rownum, $v['picking_price']*$v['picking_number']);
$rownum++;
$i++;
}
//设置值
$ValueArr=$Arr['value'];
foreach ($ValueArr as $k=>$v){
if(strpos($k,'+')){
preg_match_all('/\d+/',$k,$row);//截取行
$column=substr($k,0,1);
$sheet->setCellValue($column.((int)$row[0][0]+(int)$count), $v);
}else{
$sheet->setCellValue($k, $v);
}
}
//设置居中
$sheet->getStyle('A4')->getAlignment()>setHorizontal(\PHPExcel_Style_Alignment::VERTICAL_CENTER)->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
$sheet->getStyle('C1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::VERTICAL_CENTER)->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
$sheet->getStyle('C2')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::VERTICAL_CENTER)->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
$sheet->getStyle('A5')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_RIGHT)->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
//写入logo
$objDrawing = new \PHPExcel_Worksheet_Drawing;
$objDrawing->setPath(public_path('img/logo.png'));
$objDrawing->setCoordinates('A1');
$objDrawing->setHeight(75);
$objDrawing->setWidth(100);
$objDrawing->setOffsetX(10);
$objDrawing->setRotation(10);
$objDrawing->setWorksheet($sheet);
//设置边框
$sheet->getStyle('A2:I2')->getBorders()->getBottom()->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
$border=$Arr['border'];
foreach ($border as $k=>$v){
for ($i=$v[0];$i<$v[2]+1;$i++){
$sheet->getStyle($k.$i.':'.$v[1].$i)->getBorders()->getBottom()->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
}
}
$sheet->getStyle('A14:I'.(18+(int)$count))->getBorders()->getAllBorders()->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
//设置加粗
$bold=$Arr['bold'];
foreach ($bold as $k=>$v){
if(strpos($k,'+')) {
preg_match_all('/\d+/', $k, $row);//截取行
$column = substr($k, 0, 1);
$k=$column . ((int)$row[0][0] + (int)$count);
}
$sheet->getStyle($k)->getFont()->setBold(true);
}
//设置字号
$size=$Arr['size'];
foreach ($size as $k=>$v){
if(strpos($k,'+')) {
preg_match_all('/\d+/', $k, $row);//截取行
$column = substr($k, 0, 1);
$k=$column . ((int)$row[0][0] + (int)$count);
}
$sheet->getStyle($k)->getFont()->setSize($v);
}
//设置宽度
$sheet->setHeight(array(
1 => '33.9',
4 => '40.6',
21+(int)$count => '34.5',
23+(int)$count => '34.5',
28+(int)$count => '34.5',
29+(int)$count => '34.5',
30+(int)$count => '34.5',
));
//设置自动折行
$sheet->getStyle('A1:I'.(38+(int)$count))->getAlignment()->setWrapText(true);
});
})->download('xls');
}
}
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class DepartmentModel extends Model
{
protected $table='department';
public $timestamps = false;
public function ObtainDepartmentIDArr($DepartmentID=''){
if(empty($DepartmentID)) return false;
$Arr[]=$DepartmentID;
$result=$this->where('parent','=',$DepartmentID)->select('departmentId')->get();
if(!$result) return $Arr;
$result=$result->toArray();
foreach ($result as $k=>$v){
$Arr[]=$v['departmentId'];
}
return $Arr;
}
//获取部门信息
public function DepartmentInfo($DepartmentID=''){
if(empty($DepartmentID)) return false;
$result=$this->where('departmentId','=',$DepartmentID)->select('title','departmentId')->first();
if(!$result) return false;
return $result->toArray();
}
}
<?php
namespace App\Model;
use App\map\OperationLogMap;
use Illuminate\Database\Eloquent\Model;
use Request;
use DB;
class OperationLogModel extends Model
{
protected $connection='web';
protected $table='operation_log';
protected $primaryKey='operation_id';
public $timestamps = false;
//列表
public function getList($export=array())
{
$input = Request::all();
$list = $this->where(function ($query) use ($input) {
foreach ($input as $k => $v){
$v = trim($v);
if (empty($v)){
continue;
}
switch ($k){
case "p":
case "limit":
case "_url":
continue;
break;
default:
$query->whereRaw("FIND_IN_SET($k,'".trim($v,',')."') > 0");
break;
}
}
})->orderBy('operation_id','desc')->paginate($input['limit'], ['*'], 'p', $input['p'])->toArray();
if (!$list) return [20001, '没有数据'];
$UserModel = new UserModel();
foreach ($list['data'] as $k=>&$v){
$userName = $UserModel->FinduserInfoName($v['user_id']);
$v['user_id_name'] = $userName ? $userName : "";
$v['relevance_type_name'] = OperationLogMap::$relevance_type[$v['relevance_type']];
$v['operation_type_name'] = OperationLogMap::$operation_type[$v['operation_type']];
$v['create_time'] = date("Y-m-d H:i:s",$v['create_time']);
}
return [0, '成功', $list['data'], $list['total']];
}
/*
* 插入操作日志
*@param `operation_type` '操作类型:1添加,2删除,3修改,4审核通过,5审核驳回,6导出',
*@param `relevance_type` '关联单据的类型或者模块: 参考 OperationLogMap
*@param `relevance_id` '关联ID',
*@param `relevance_sn` '关联单号',
*@param `content` '内容',
*@param `user_id` '操作人',
* @param `extend1` '扩展字段1',
*/
static function log($user_id,$operation_type=0,$relevance_type="",$relevance_id=0,$relevance_sn="",$content="",$extend1 = ""){
$data['operation_type'] = $operation_type ;
$data['relevance_type'] = $relevance_type;
$data['relevance_id'] =$relevance_id ;
$data['relevance_sn'] = $relevance_sn;
$data['content'] = is_array($content) ? json_encode($content,JSON_UNESCAPED_UNICODE) : $content;
$data['user_id'] = $user_id;
$data['extend1'] = is_array($extend1) ? json_encode($extend1,JSON_UNESCAPED_UNICODE) : $extend1;
$data['create_time'] = time();
return self::insert($data);
}
}
\ No newline at end of file
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class OrganizationModel extends Model
{
protected $table='organization';
public $timestamps = false;
//获取部门所有成员ID
public function ObtainDepartment($DepartmentID=''){
if(empty($DepartmentID)) return false;
$OrganizationModel=new DepartmentModel();
$DepartmentIDArr=$OrganizationModel->ObtainDepartmentIDArr($DepartmentID);
$result=$this->whereIn('departmentId',$DepartmentIDArr)->select('userId')->get();
if(!$result) return false;
$result=$result->toarray();
$Arr=[];
foreach ($result as $k=>$v){
$Arr[]=$v['userId'];
}
return $Arr;
}
public function FindUserdepartment($UserID=''){
if(empty($UserID)) return false;
$result=$this->where('userId','=',$UserID)->select('departmentId')->first();
if(!$result) return false;
$result=$result->toArray();
$DepartmentModel=new DepartmentModel();
return $DepartmentModel->DepartmentInfo($result['departmentId']);
}
}
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class PackingModel extends Model
{
protected $connection='web';
protected $table='packing';
protected $primaryKey = 'packing_id';
public $timestamps = false;
public function PackingList($status=1){
$map['status']=$status;
return $this->where($map)->lists('packing_name','packing_id')->toArray();
}
}
<?php
namespace App\Model;
use App\Jobs\AddAbnormal;
use App\Jobs\PushFinancePeriod;
use App\map\PreSaleOrderMap;
use ClassPreloader\Config;
use Illuminate\Database\Eloquent\Model;
use League\Flysystem\Exception;
use Request;
use DB;
class PreSaleOrderModel extends Model
{
protected $connection='web';
protected $table='pre_sale_order';
protected $primaryKey = 'id';
public $timestamps = false;
//列表
public function getList()
{
$arr = ['p', 'limit', 'start_time','end_time','sku_id','order_sn'];
$input = Request::only($arr);
$input=TrimX($input,true,$arr);
//查询数据
$list = $this->where(function ($query) use ($input) {
foreach ($input as $k => $v){
$v = trim($v);
switch ($k){
case "p":
case "limit":
continue;
break;
case "start_time":
$query->where('create_time', '>=', strtotime($v));
break;
case "end_time":
$query->where('create_time', '>=', strtotime($v));
break;
default:
$query->whereRaw("FIND_IN_SET($k,'".trim($v,',')."') > 0");
break;
}
}
});
$result = $list->orderBy('create_time','desc')->paginate($input['limit'], ['*'], 'p', $input['p'])->toArray();
if(!$result) return [20001,'没有数据'];
//查询包装单位
$packing = (new PackingModel())->get()->toArray();
$packingArr = array_column($packing ,null ,'packing_id');
if ($result['data']) {
foreach ($result['data'] as $k => &$v) {
$v['type'] = '订单';
$v['status'] = PreSaleOrderMap::$status[$v['status']];
$v['create_time'] = timeToDate($v['create_time']);
$v['deal_time'] = timeToDate($v['deal_time']);
$v['update_time'] = timeToDate($v['update_time']);
$v['goods_info'] = $v['goods_name'].'€€'.@$packingArr[$v['packing_id']]['packing_name'].'€€'.$v['encap'].'€€'.$v['mpq'];
$v['buy_price'] = sprintf('%.3f',$v['buy_price']/1.16);
$v['picking_type'] = $v['picking_type'] == 1 ? "自采": "寄售";
}
}
return [0, '成功', $result['data'], $result['total']];
}
/*
* 批量插入
* @param array $data =[
[
"order_sn"=>'1323336', // 订单号
"rec_id"=>"56489", //订单商品明细id
"sku_id"=>"10258", //商品id
"goods_name" =>"Rc04", //型号
"encap"=>"1", //封装.规格
"packing_name"=>"盒", //包装方式
"mpq"=>"1", //mpq
"need_number"=>456, //需求数量
"buy_price"=>"10.54", //购买价格
"brand_name"=>"YAGEO",//制造商
"brand_id"=>"5148",//制造商ID
"supplier_id"=>"10010" //供应商id
]
];
*/
public function bultInsert($data){
OperationLogModel::log(0,1,'pre_sale_order_add_get',0,0,$data,"获取到请求数据"); //日志
//接收数据
$param = ['order_sn','rec_id','sku_id','goods_name','encap','packing_name','mpq','need_number','buy_price','supplier_id'];
$nowTime = time();
//查询包装单位
$packing = (new PackingModel())->get()->toArray();
$packingArr = array_column($packing ,null ,'packing_name');
$temp = [];
$SupplierChannelModel = new SupplierChannelModel();
foreach ($data as $k=>&$v){
if (!checkRequire($v,$param)){
OperationLogModel::log(0,1,'pre_sale_order_add_error',0,0,$data,"超售error:缺少参数".checkRequire($v,$param,2)); //日志
return [10004,'缺少参数'.checkRequire($v,$param,2)];
}
if ($v['packing_name'] !== ""){ //如果存在包装
$packing_id = $packingArr[$v['packing_name']]['packing_id'];
}else{
$packing_id = 0;
}
$supplier_id = $supplier_code = $supplier_name = "";
$salesname_id = 0;
if($v['supplier_id'] == 10000){ //自采
$purchaseInfo = $this
->from("purchase as t")
->select(DB::Raw("lie_t.supplier_id,lie_t.supplier_code,lie_t.supplier_name,lie_t.create_uid"))
->join('purchase_items as i', 't.picking_id', '=', 'i.picking_id')
->where("i.sku_id",$v['sku_id'])
->orderBy("i.picking_id","desc")
->first();
if ($purchaseInfo){
$supplier_id = $purchaseInfo['supplier_id']; //最新供应商
$supplier_code = $purchaseInfo['supplier_code'];
$supplier_name = $purchaseInfo['supplier_name'];
$salesname_id = $purchaseInfo['create_uid'] ;
}
}else{
$supplierObj = $SupplierChannelModel->where("supplier_id",$v['supplier_id'])->first();
$v['supplier_type'] = "寄售";
$v['supplier_code'] = $supplierObj['supplier_code'];
$v['supplier_name'] = $supplierObj['supplier_name'];
$purchaseInfo = $this
->select(DB::Raw("lie_t.supplier_code,lie_t.supplier_name,lie_t.create_uid"))
->from("purchase as t")
->join('purchase_items as i', 't.picking_id', '=', 'i.picking_id')
->where("t.supplier_id",$v['supplier_id'])
->orderBy("i.picking_id","desc")
->first();
if ($purchaseInfo){
$supplier_code = $purchaseInfo['supplier_code'];
$supplier_name = $purchaseInfo['supplier_name'];
$salesname_id = $purchaseInfo['create_uid'] ;
}
}
array_push($temp,[
'picking_type'=>$v['supplier_id'] == 10000 ? 1:2,
'supplier_id'=>$supplier_id == "" ? $v['supplier_id'] : $supplier_id,
'supplier_code'=>$supplier_code,
'supplier_name'=>$supplier_name,
'salesman_id'=>$salesname_id,
'order_sn'=>$v['order_sn'],
'rec_id'=>$v['rec_id'],
'sku_id'=>$v['sku_id'],
'goods_name'=>$v['goods_name'],
'encap'=>$v['encap'],
'packing_id'=>$packing_id,
'mpq'=>$v['mpq'],
'need_number'=>$v['need_number'],
'buy_price'=>$v['buy_price'],
'create_time'=>$nowTime,
'deal_time'=>$nowTime,
'update_time'=>$nowTime,
'brand_id'=>$v['brand_id'],
'brand_name'=>$v['brand_name'],
]);
}
// print_r($temp);
// die();
//检测数据
$recIdArr = arrayToCommaStr($temp,'rec_id',1);
$find = $this->whereIn('rec_id',$recIdArr)->count();
if ($find > 0){
return [10001, '系统已经存在商品明细ID'];
}
try{
$con = DB::connection('web');
$con->beginTransaction();
$this->insert($temp);; //批量插入
OperationLogModel::log(0,1,'pre_sale_order_add_success',0,0,$temp,"批量插入超售订单明细数据成功"); //日志
$con->commit();
return [0, '成功'];
}catch (\Exception $e) {
$con->rollBack();
OperationLogModel::log(0,1,'pre_sale_order_add_error',0,0,$e->getMessage(),"批量插入超售订单明细数据失败"); //日志
return [10002, '失败'.$e->getMessage()];
}
}
/*
* 批量更新超售订单数据状态
* @param array $data = [
[
"rec_id"=>"1231", //订单商品明细id
"status" =>"1", //状态:-1已取消 1 处理中 2已处理 3已发货 4部分发货
"deal_time"=>"1526633313", //更新时间
]
];
*/
public function updateStatus($data){
//接收数据
$param = ['rec_id','status','deal_time'];
foreach ($data as $k=>$v){
if (!checkRequire($v,$param)){
OperationLogModel::log(0,1,'pre_sale_order_update_error',0,0,$data,"批量更新超售订单明细数据:缺少参数".checkRequire($v,$param,2)); //日志
return [10004,'缺少参数'.checkRequire($v,$param,2)];
}
}
try{
$con = DB::connection('web');
$con->beginTransaction();
foreach ($data as $a=>$b){
if (in_array($b['status'],PreSaleOrderMap::$statusAll)){
$this->where('rec_id',$b['rec_id'])->update(['status'=>$b['status'],'deal_time'=>$b['deal_time'],'update_time'=>time()]);
}else{
throw new Exception("更新状态不正确");
}
}
OperationLogModel::log(0,1,'pre_sale_order_update_success',0,0,"批量更新超售订单明细数据成功",$data); //日志
$con->commit();
return [0, '成功'];
}catch (\Exception $e) {
$con->rollBack();
OperationLogModel::log(0,1,'pre_sale_order_update_error',0,0,"批量更新超售订单明细数据失败",$data); //日志
return [10002, '失败:'.$e->getMessage()];
}
}
}
\ No newline at end of file
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class PurDeliveryItemsModel extends Model
{
protected $connection='web';
protected $table='purchase_delivery_items';
public $timestamps = false;
public function BatchADD($data){
return $this->insert($data);
}
public function FindSkuNum($PickingItemsID){
if(!$PickingItemsID) return false;
$list=$this->where('purchase_delivery_items.picking_items_id',$PickingItemsID)->join('purchase_delivery',function($join){
$join->on('purchase_delivery_items.delivery_id','=','purchase_delivery.delivery_id')->where('status','<>',-1);
})->sum('purchase_delivery_items.shipping_number');
return $list;
}
}
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
use Sn;
class PurDeliveryModel extends Model
{
protected $connection='web';
protected $table='purchase_delivery';
public $timestamps = false;
//查询来料通知ID
public function getDeliveryId($deliverySn){
$Find=$this->where('delivery_sn','=',$deliverySn)->select('delivery_sn')->first();
if(!$Find) return '';
return $Find['delivery_id'];
}
}
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
use DB;
class PurchaseAgentModel extends Model
{
protected $connection='web';
protected $table='purchasing_agent';
public $timestamps = false;
}
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
use Request;
use DB;
class PurchaseDeliveryItemsModel extends Model
{
protected $connection='web';
protected $table='purchase_delivery_items';
public $timestamps = false;
public function ApiPurchaseDeliveryItemsList(){
$collert=Request::only('delivery_id','p','limit');
$limit=!empty($collert['limit'])?$collert['limit']:10;
$p=!empty($collert['p'])?$collert['p']:1;
$collert=TrimX($collert,true,['delivery_id']);
if(empty($collert['delivery_id'])) return [10001,'请添加','',''];
//查数据
$list=$this->where('delivery_id','=',$collert['delivery_id'])->paginate($limit,['*'],'p',$p)->toArray();
if(!$list && !empty($list['data']) && count($list['data'])>0) return [30001,'请添加','',''];
//取出包装方式
$PackingModel = new PackingModel();
$PackList = $PackingModel->PackingList();
//取出来料通知单信息
$PurchaseDeliveryModel = new PurchaseDeliveryModel();
$PurchaseDeliveryInfo = $PurchaseDeliveryModel->GetPurchaseDeliveryByID($collert['delivery_id']);
$Currency = Config('fixed.Currency');
//整理数据
foreach ($list['data'] as $k => $v){
$list['data'][$k]['currency'] = $Currency[$PurchaseDeliveryInfo['currency']];
$list['data'][$k]['delivery_sn'] = $PurchaseDeliveryInfo['delivery_sn'];
$list['data'][$k]['shipping_sn'] = $PurchaseDeliveryInfo['shipping_sn'];
$list['data'][$k]['number_diff'] = intval($list['data'][$k]['shipping_number']) - intval($list['data'][$k]['putaway_number']);
$list['data'][$k]['packing_name'] = @$PackList[$list['data'][$k]['packing_id']];
$list['data'][$k]['price_amount'] = round($list['data'][$k]['shipping_number'] * $list['data'][$k]['picking_price'],4);
}
return [0,'成功',$list['data'],$list['total']];
}
// 导出
public function export()
{
$picking_id = Request::input('picking_id');
$result = $this->where('picking_id','=',$picking_id)->get()->toArray();
if (!$result) return ['errcode' => 20001, 'errmsg' => '没有数据'];
//取出包装方式
$PackingModel = new PackingModel();
$PackList = $PackingModel->PackingList();
//整理数据
$PurchaseDeliveryModel = new PurchaseDeliveryModel();
$Currency = Config('fixed.Currency');
$temp = array();
// CSV写入数据
foreach ($result as $k => $v) {
$PurchaseDeliveryInfo = $PurchaseDeliveryModel->GetPurchaseDeliveryByID($v['delivery_id']);
$temp[$k]['count'] = $k + 1;
$temp[$k]['delivery_sn'] = $PurchaseDeliveryInfo['delivery_sn']."\t"; // 来料通知单号(防止科学计数法展示)
$temp[$k]['shipping_sn'] = $PurchaseDeliveryInfo['shipping_sn'];
$temp[$k]['picking_sn'] = $v['picking_sn'];
$temp[$k]['goods_name'] = $v['goods_name'];
$temp[$k]['packing_name'] = $PackList[$v['packing_id']];
$temp[$k]['brand_name'] = $v['brand_name'];
$temp[$k]['picking_price'] = $v['picking_price'];
$temp[$k]['currency'] = $Currency[$PurchaseDeliveryInfo['currency']];
$temp[$k]['price_amount'] = intval($v['putaway_number']) * $v['picking_price'];
$temp[$k]['shipping_number'] = $v['shipping_number'];
$temp[$k]['putaway_number'] = $v['putaway_number'];
$temp[$k]['number_diff'] = intval($v['shipping_number']) - intval($v['putaway_number']);
}
$column = array('序号', '来料通知单号', '客户单号', '采购单号', '产品型号', '包装方式', '制造商', '单价', '币种', '金额', '计划数量', '收货数量', '差异数量'); // 表头
$fileName = '发货物流导出'.date('YmdHis', time()).'.csv';
export_csv($temp, $column, $fileName);
}
public function GetPurchaseDeliveryItemsListByPickingID(){
$collert=Request::only('picking_id','p','limit');
$limit=!empty($collert['limit'])?$collert['limit']:10;
$p=!empty($collert['p'])?$collert['p']:1;
$collert=TrimX($collert,true,['picking_id']);
if(empty($collert['picking_id'])) return [10001,'请添加picking_id','',''];
//查数据
$list=$this->where('picking_id','=',$collert['picking_id'])->paginate($limit,['*'],'p',$p)->toArray();
if(!$list && !empty($list['data']) && count($list['data'])>0) return [30001,'暂无数据','',''];
//取出包装方式
$PackingModel = new PackingModel();
$PackList = $PackingModel->PackingList();
//取出来料通知单信息
$PurchaseDeliveryModel = new PurchaseDeliveryModel();
$Currency = Config('fixed.Currency');
//整理数据
foreach ($list['data'] as $k => $v){
$PurchaseDeliveryInfo = $PurchaseDeliveryModel->GetPurchaseDeliveryByID($list['data'][$k]['delivery_id']);
$list['data'][$k]['currency'] = $Currency[$PurchaseDeliveryInfo['currency']];
$list['data'][$k]['delivery_sn'] = $PurchaseDeliveryInfo['delivery_sn'];
$list['data'][$k]['shipping_sn'] = $PurchaseDeliveryInfo['shipping_sn'];
$list['data'][$k]['number_diff'] = intval($list['data'][$k]['shipping_number']) - intval($list['data'][$k]['putaway_number']);
$list['data'][$k]['packing_name'] = $PackList[$list['data'][$k]['packing_id']];
$list['data'][$k]['price_amount'] = intval($list['data'][$k]['putaway_number']) * $list['data'][$k]['picking_price'];
}
return [0,'成功',$list['data'],$list['total']];
}
public function ItemsList($delivery_id='',$delivery_sn=''){
if(!$delivery_id || !$delivery_sn) return false;
$list=$this->where('delivery_id','=',$delivery_id)->select('delivery_items_id','sku_id','picking_price','shipping_number','picking_sn')->get();
if(!$list) return false;
$list=$list->toArray();
foreach ($list as $k=>$v){
unset($list[$k]);
$list[$k]['delivery_sn']=$delivery_sn;
$list[$k]['delivery_items_id']=$v['delivery_items_id'];
$list[$k]['goods_id']=$v['sku_id'];
$list[$k]['picking_price']=$v['picking_price'];
$list[$k]['shipping_number']=$v['shipping_number'];
$list[$k]['purchase_sn']=$v['picking_sn'];
}
return $list;
}
public function OBItemsList($ArrID){
$Arr=['delivery_items_id','delivery_id','picking_id','picking_items_id','picking_sn','sku_id','goods_name','brand_id','brand_name','packing_id','picking_price','initial_price','shipping_number'];
$result=$this->whereIn('delivery_items_id',$ArrID)->select($Arr)->get();
if(!$result) return false;
return $result->toArray();
}
public function SavePutawayNumber($delivery_items_id,$num){
if(!$delivery_items_id && !$num>0) return false;
$result=$this->where('delivery_items_id','=',$delivery_items_id)->increment('putaway_number',$num);
if(!$result) return false;
return $result;
}
}
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
use DB;
//发票明细模型
class PurchaseInvoiceItemsModel extends Model
{
protected $connection='web';
protected $table='purchase_invoice_items';
public $timestamps = false;
/*
* 获取详情
*/
public function getDetail($input){
return $this->where("invoice_id",$input['invoice_id'])->paginate($input['limit'], ['*'], 'p', $input['p'])->toArray();
}
}
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
use DB;
//发票明细模型
class PurchaseInvoicePutawayModel extends Model
{
protected $connection='web';
protected $table='purchase_invoice_putaway';
public $timestamps = false;
/*
* 获取添加发票明细详情
* @param str $putaway_ids 入库单,多个逗号分割
* @param int $type 1为完全开票 2 部分开票
* @return array
*/
public function getAddList($putaway_ids,$type){
if ($type == 'all'){ //完全开票
$putawayInfo = $this
->from("putaway as t")
->select(DB::Raw("lie_t.putaway_id,lie_t.putaway_sn,lie_i.picking_sn,lie_t.putaway_number as total_number,
SUM(lie_i.picking_price*lie_i.putaway_number*lie_i.exchange_rate) total_price"))
->join('putaway_items as i', 't.putaway_id', '=', 'i.putaway_id')
->whereIn("t.putaway_id",explode(',',$putaway_ids))
->groupBy('t.putaway_id')
->get();
if (!$putawayInfo){
return false;
}else{
return $putawayInfo->toArray();
}
}else{ //部分开票
$putawayInfo = $this
->from("putaway as t")
->join('putaway_items as i', 't.putaway_id', '=', 'i.putaway_id')
->join('purchase as p', 'p.picking_id', '=', 'i.picking_id')
->whereIn("t.putaway_id",explode(',',$putaway_ids))
->get();
if (!$putawayInfo){
return false;
}else{
$res = $putawayInfo->toArray();
//取出包装方式
$PackingModel = new PackingModel();
$PackList = $PackingModel->PackingList();
$PurchaseInvoiceModel = new PurchaseInvoiceModel();
foreach ($res as $k=>&$v){
$v['picking_price'] = $v['picking_price']*$v['exchange_rate'];
$v['packing_name']= @$PackList[$v['packing_id']];
$v['use_number'] = $v['putaway_number']-$PurchaseInvoiceModel->getTotalInvoiceNumber($v['putaway_id'],$v['putaway_items_id'],2);
$v['total_number'] = $v['putaway_number'] ;
$v['total_price'] = $v['picking_price']*$v['putaway_number'];
}
return $res;
}
}
}
/*
* 获取入库单详情
* 序 入库单号 采购单号 入库单数量 入库单金额 本次开票数量 本次开票金额
*/
public function getDetail($input){
$invoiceId = $input['invoice_id'];
$invoiceRes = (new PurchaseInvoiceModel())->where("invoice_id",$invoiceId)->first();
if($invoiceRes['invoice_type'] == 1){ //如果是完全开票
$putawayInfo = $this
->from("purchase_invoice_putaway as t")
->select(DB::Raw("
lie_t.picking_sn,
lie_t.putaway_sn,
lie_a.putaway_number,
sum(
lie_i.picking_price * lie_i.putaway_number * lie_i.exchange_rate
) as total_price,
lie_a.putaway_number as applying_number
"))
->join('putaway_items as i', 't.putaway_id', '=', 'i.putaway_id')
->join('putaway as a', 'a.putaway_id', '=', 't.putaway_id')
->where("t.invoice_id",$input['invoice_id'])
->groupBy('a.putaway_id')
->paginate($input['limit'], ['*'], 'p', $input['p'])
->toArray();
}else{ //部分开票
$putawayInfo = $this
->from("purchase_invoice_putaway as t")
->select(DB::Raw("
lie_t.picking_sn,
lie_t.putaway_sn,
lie_a.putaway_number,
(
lie_i.picking_price * lie_a.putaway_number * lie_i.exchange_rate
) as total_price,
sum(lie_t.applying_number) as applying_number,
SUM(
lie_i.picking_price * lie_t.applying_number * lie_i.exchange_rate
) as applying_price
"))
->join('putaway_items as i', 't.putaway_items_id', '=', 'i.putaway_items_id')
->join('putaway as a', 'a.putaway_id', '=', 't.putaway_id')
->where("t.invoice_id",$input['invoice_id'])
->groupBy('t.putaway_id')
->paginate($input['limit'], ['*'], 'p', $input['p'])
->toArray();
}
foreach ($putawayInfo['data'] as $k=>&$v){
$v['k'] = $k+1;
$v['applying_price'] = $invoiceRes['invoice_type'] == 1 ? $v['total_price'] : $v['applying_price'];
}
return $putawayInfo;
}
}
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
use Request;
use DB;
class PurchaseNeedItemsModel extends Model
{
protected $connection='web';
protected $table='purchase_need_items';
protected $primaryKey='id';
public $timestamps = false;
}
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class PurchasingAgentModel extends Model
{
protected $connection='web';
protected $table='purchasing_agent';
public $timestamps = false;
public function PurchasingAgentList($status='',$map=[]){
empty($status) || $map['status']=$status;
$list=$this->where($map)->get();
return $list->toArray();
}
public function PurchasingAgentInfo($agent_id=''){
if(empty($agent_id)) return false;
$result=$this->where('agent_id','=',$agent_id)->first();
if(!$result) return false;
return $result->toArray();
}
}
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
use Request;
use DB;
class PutawayItemsModel extends Model
{
protected $connection='web';
protected $table='putaway_items';
public $timestamps = false;
//获取入库详情
public function getPutawayItemsDetail()
{
$collert=Request::only('picking_id','p','limit');
$limit=!empty($collert['limit'])?$collert['limit']:10;
$p=!empty($collert['p'])?$collert['p']:1;
$collert=TrimX($collert,true,['picking_id']);
if(empty($collert['picking_id'])) return [10001,'请添加picking_id','',''];
//查数据
$PutawayModel = new PutawayModel();
$list = $PutawayModel->getPutawayDetails($collert['picking_id']);
return [0,'成功',$list['2'],$list['3']];
}
public function HoldPutawayItems($data){
return $this->insert($data);
}
}
\ No newline at end of file
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
use Request;
use App\Jobs\Queue;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
class QueuedModel extends Model
{
public function __construct()
{
parent::__construct();
$this->connection=new AMQPStreamConnection(env('RABBITMQ_HOST'), env('RABBITMQ_PORT'), env('RABBITMQ_LOGIN'), env('RABBITMQ_PASSWORD'), env('RABBITMQ_VHOST')); // 创建连接;
$this->queue_name = env('RABBITMQ_QUEUE');
}
public function pushAmq($content='')
{
$connection = $this->connection;
$channel = $connection->channel();
$channel->queue_declare($this->queue_name, true, true, false, false);
$message = new AMQPMessage($content);
$result=$channel->basic_publish($message, '', $this->queue_name); // 推送消息
$channel->close();
$connection->close();
return true;
}
public function pullAmq($queue_name='')
{
// $queue_name = 'test';
$connection = $this->connection;
$channel = $connection->channel();
$message = $channel->basic_get($queue_name); // 取出消息
echo '<pre>';
print_r($message);
$channel->basic_ack($message->delivery_info['delivery_tag']); // 确认取出消息后会发送一个ack来确认取出来了,然后会从rabbitmq中将这个消息移除,如果删掉这段代码,会发现rabbitmq中的消息还是没有减少
$channel->close();
$connection->close();
}
}
\ No newline at end of file
<?php
namespace App\Model\Report;
use App\Model\PackingModel;
use App\Model\PurchaseModel;
use Request;
use DB;
class ReportPriceTrendModel
{
protected $connection='web';
/*
* 商品价格走势
*/
public function skuReport(){
$arr = ['create_time1','create_time2','supplier_name','supplier_code','sku_id'];
$input = Request::only($arr);
$input=TrimX($input,true,$arr);
if (empty($input['sku_id'])){
return [10001,'sku_id不得为空'];
}
$where = " And i.sku_id = ".$input['sku_id']." ";
if (!empty($input['create_time1']) && !empty($input['create_time2'])){
$where .= " AND p.create_time >= ".strtotime($input['create_time1'])." AND p.create_time <= ".strtotime($input['create_time2'])." ";
}
if (!empty($input['supplier_name'])){
$where .= " and p.supplier_name like '".$input['supplier_name']."%'";
}
if (!empty($input['supplier_code'])){
$where .= " and p.supplier_code in (".$input['supplier_code'].")";
}
$sql = "SELECT
i.sku_id,
i.picking_price,
p.exchange_rate,
i.picking_price*p.exchange_rate as picking_price,
p.create_time
FROM
lie_purchase p,
lie_purchase_items i
WHERE
p.picking_id = i.picking_id
AND p.status not in (-10,-1,-2)
AND i.status =1
$where
ORDER BY p.create_time;";
// echo $sql;
// die();
$list=DB::connection($this->connection)->select($sql);
if(!count($list)) return [10002,'没有数据'];
foreach ($list as $k=>$v){
$list[$k]['create_time']=date('y/m/d',$v['create_time']);
}
$data['list'] = $list;
//$data['list'] = remove_duplicate($list,'create_time'); //去重
return [0,'成功',$data];
}
/*
* 供应商价格走势
*/
public function supplierReport(){
$arr = ['create_time1','create_time2','supplier_name','supplier_code'];
$input = Request::only($arr);
$input=TrimX($input,true,$arr);
if (empty($input['supplier_name']) && empty($input['supplier_code'])){
return [10001,'供应商名称或供应商编码不得为空'];
}
if (!empty($input['create_time1']) && !empty($input['create_time2'])){
$where = " AND p.create_time >= ".strtotime($input['create_time1'])." AND p.create_time <= ".strtotime($input['create_time2'])." ";
}
if (!empty($input['supplier_name'])){
$where .= " and p.supplier_name like '".$input['supplier_name']."%'";
}
if (!empty($input['supplier_code'])){
$where .= " and FIND_IN_SET(p.supplier_code,'".trim($input['supplier_code'],',')."') > 0 ";
}
//数据列表
$sql1 = "SELECT
sum(i.picking_price*p.exchange_rate*i.picking_number) as sum_picking_price,
sum(i.picking_number) as sum_picking_number,
FROM_UNIXTIME(p.create_time,'%Y-%m-%d') as create_time
FROM
lie_purchase p,
lie_purchase_items i
WHERE
p.picking_id = i.picking_id
AND p.status not in (-10,-1,-2)
AND i.status =1
$where
GROUP BY p.supplier_code,FROM_UNIXTIME(p.create_time,'%Y-%m-%d')
ORDER BY p.create_time;";
$list=DB::connection($this->connection)->select($sql1);
if(!count($list)) return [10002,'没有数据'];
foreach ($list as $k=>&$v){
$v['use_price']=round($v['sum_picking_price']/$v['sum_picking_number'],6);
}
$data['list'] = $list;
return [0,'成功',$data];
}
}
\ No newline at end of file
<?php
namespace App\Model\Report;
use App\Model\PackingModel;
use App\Model\PurchaseModel;
use Request;
use DB;
class ReportSkuModel
{
protected $connection='web';
/*统计数据,按skuid分组计算
*
skuid
分类
型号
品牌
包装/方式
封装
MPQ
采购次数
采购最低价
采购最高价
采购均价(加权平均价就是:sum(单次采购金额*数量)/总采购数量)
采购数量
采购总价
采购在途数量 * 采购在途(下单数量-入库数量-已审核异常的不补发数量)
采购在途金额
送货在途数量 * 送货在途(发货数量-入库数量-已审核异常的不补发数量-已审核异常的补发数量)
送货在途金额
入库数量
入库金额
*/
public function main($type = 1)
{
$arr = ['p','limit','sku_id','supplier_code','supplier_name'];
$input=TrimX(Request::all(),true,$arr);
$PurchaseModel = new PurchaseModel();
//查询数据
$list = $PurchaseModel
->select(DB::Raw("lie_i.sku_id,
lie_i.goods_name, -- 型号
lie_i.brand_id, -- 品牌id
lie_i.brand_name, -- 品牌名
lie_i.encap, -- 封装/规格
lie_i.mpq, -- mpq
lie_i.packing_id, -- 包装
count(1) as sum_pur_number , -- 采购次数
SUM(lie_i.picking_number) as sum_picking_number, -- 采购数量总数
MAX(lie_i.picking_price) as max_picking_price , -- 最高采购价格
MIN(lie_i.picking_price) as min_picking_price, -- 最低采购价格
SUM(lie_i.picking_price*lie_p.exchange_rate*lie_i.picking_number) as sum_pur_price, -- 采购总价
SUM(lie_i.shipping_number) as sum_shipping_number, -- 发货总数量
SUM(lie_i.putaway_number) as sum_putaway_number, -- 入库总数量
SUM(lie_i.picking_price*lie_p.exchange_rate*lie_i.putaway_number) as sum_putaway_price, -- 入库金额
SUM(lie_i.picking_number) as sum_picking_number,
SUM(lie_i.putaway_number) as sum_putaway_number,
SUM(lie_i.noshipping_number) as sum_noshipping_number,
SUM(lie_i.reshipping_number) as sum_reshipping_number,
SUM(lie_i.picking_price*lie_p.exchange_rate*lie_i.picking_number) as price_picking_number,
SUM(lie_i.picking_price*lie_p.exchange_rate*lie_i.putaway_number) as price_putaway_number,
SUM(lie_i.picking_price*lie_p.exchange_rate*lie_i.noshipping_number) as price_noshipping_number,
SUM(lie_i.picking_price*lie_p.exchange_rate*lie_i.reshipping_number) as price_reshipping_number
"))
->from("purchase as p")
->join('purchase_items as i', 'p.picking_id', '=', 'i.picking_id')
->whereNotIn("p.status",[-10,-2,-1])
->where("i.status",1)
->where(function ($query) use ($input) {
foreach ($input as $k => $v){
$v = trim($v);
if (empty($v)){
continue;
}
switch ($k){
case "p":
case "limit":
continue;
break;
case 'supplier_name':
$query->where('p.supplier_name','like',$v);
break;
case "supplier_code":
$query->whereIn('p.supplier_code',explode(',',$v));
break;
case "sku_id":
$query->where('i.sku_id','like',$v);
break;
}
}
})
->groupBy("sku_id")
->orderBy('i.picking_items_id','asc');
if ($type == 1){
$list = $list->paginate($input['limit'], ['*'], 'p', $input['p'])->toArray();
if (!$list) return [20001, '没有数据'];
return [0, '成功', $this->clearData($list['data']), $list['total']];
}else{
$list = $list->get();
if (!$list) return false;
return $this->clearData($list->toArray());
}
}
//清理数据
private function clearData($data){
$packingInfo = (new PackingModel())->PackingList();
foreach ($data as $k=>&$v){
$v['packing_name'] = @$packingInfo[$v['packing_id']];
$running_number = $v['sum_picking_number']-$v['sum_putaway_number']-$v['sum_noshipping_number']; //采购在途数量
$sum_running_price = $v['price_picking_number']-$v['price_putaway_number']-$v['price_noshipping_number'];//采购在途金额
$send_number = $v['sum_picking_number']-$v['sum_putaway_number']-$v['sum_noshipping_number']-$v['sum_noshipping_number']; //送货在途数量
$sum_send_price = $v['price_picking_number']-$v['price_putaway_number']-$v['price_noshipping_number']-$v['price_noshipping_number'];//送货在途金额
$v['running_number'] = $running_number > 0 ? $running_number : 0;
$v['sum_running_price'] = $sum_running_price > 0 ? $sum_running_price : 0;
$v['send_number'] = $send_number > 0 ? $send_number : 0;
$v['sum_send_price'] = $sum_send_price > 0 ? $sum_send_price : 0;
}
return $data;
}
// 导出
public function export()
{
$result = $this->main(2);
if (!$result) return ['errcode' => 20001, 'errmsg' => '没有数据'];
$column = array('sku_id','型号','品牌id','品牌名','封装','mpq','包装','采购次数','采购数量总数','最高采购价格','最低采购价格','采购总价','发货总数量','入库总数量','入库总金额','采购在途数量','采购在途金额','送货在途数量','送货在途金额'); // 表头
$temp = [];
foreach ($result as $k=>$v){
array_push($temp,[
'sku_id'=>$v['sku_id'],
'goods_name'=>$v['goods_name'],
'brand_id'=>$v['brand_id'],
'brand_name'=>$v['brand_name'],
'encap'=>$v['encap'],
'mpq'=>$v['mpq'],
'packing_name'=>$v['packing_name'],
'sum_pur_number'=>$v['sum_pur_number'],
'sum_picking_number'=>$v['sum_picking_number'],
'max_picking_price'=>$v['max_picking_price'],
'min_picking_price'=>$v['min_picking_price'],
'sum_pur_price'=>$v['sum_pur_price'],
'sum_shipping_number'=>$v['sum_shipping_number'],
'sum_putaway_number'=>$v['sum_putaway_number'],
'sum_putaway_price'=>$v['sum_putaway_price'],
'running_number'=>$v['running_number'],
'sum_running_price'=>$v['sum_running_price'],
'send_number'=>$v['send_number'],
'sum_send_price'=>$v['sum_send_price'],
]) ;
}
$fileName = '采购汇总-按商品'.date('YmdHis', time()).'.csv';
export_csv($temp, $column, $fileName);
}
}
\ No newline at end of file
<?php
namespace App\Model\Report;
use App\Model\PackingModel;
use App\Model\PurchaseModel;
use Request;
use DB;
class ReportSupplierModel
{
protected $connection='web';
/*统计数据,按供应商分组计算
*
供应商名称
供应商编码
采购次数 -- 非草稿、作废的采购单数量
采购金额
采购占比 --当前供应商采购金额/总非草稿、作废的采购总额
采购在途数量 --汇总供应商对应采购单下采购在途数量 (下单数量-入库数量-已审核异常的不补发数量)
采购在途金额 --汇总供应商对应采购单下采购在途数量*单价
送货在途数量 --汇总供应商对应采购单下送货在途数量 (发货数量-入库数量-已审核异常的不补发数量-已审核异常的补发数量)
送货在途金额 --汇总供应商对应采购单下采购送货在途数量*单价
入库数量
入库金额
入库占比 -- 当前供应商采购入库金额/总入库总额
*/
public function main($type = 1)
{
$arr = ['p','limit','sku_id','supplier_code','supplier_name'];
$input=TrimX(Request::all(),true,$arr);
$PurchaseModel = new PurchaseModel();
//查询数据
$list = $PurchaseModel
->select(DB::Raw("lie_p.supplier_name, -- 供应商名称
lie_p.supplier_code, -- 供应商型号
count(1) as sum_pur_number , -- 采购次数
SUM(lie_i.picking_number) as sum_picking_number,
SUM(lie_i.putaway_number) as sum_putaway_number,
SUM(lie_i.noshipping_number) as sum_noshipping_number,
SUM(lie_i.reshipping_number) as sum_reshipping_number,
SUM(lie_i.picking_price*lie_p.exchange_rate*lie_i.picking_number) as price_picking_number,
SUM(lie_i.picking_price*lie_p.exchange_rate*lie_i.putaway_number) as price_putaway_number,
SUM(lie_i.picking_price*lie_p.exchange_rate*lie_i.noshipping_number) as price_noshipping_number,
SUM(lie_i.picking_price*lie_p.exchange_rate*lie_i.reshipping_number) as price_reshipping_number,
SUM(lie_i.picking_price*lie_p.exchange_rate*lie_i.picking_number) as sum_pur_price, -- 采购金额
SUM(lie_i.putaway_number) as sum_putaway_number, -- 入库总数量
SUM(lie_i.picking_price*lie_p.exchange_rate*lie_i.putaway_number) as sum_putaway_price -- 入库金额
"))
->from("purchase as p")
->join('purchase_items as i', 'p.picking_id', '=', 'i.picking_id')
->whereNotIn("p.status",[-10,-2,-1])
->where("i.status",1)
->where(function ($query) use ($input) {
foreach ($input as $k => $v){
$v = trim($v);
if (empty($v)){
continue;
}
switch ($k){
case "p":
case "limit":
continue;
break;
case 'supplier_name':
$query->where('p.supplier_name','like',$v);
break;
case "supplier_code":
$query->whereIn('p.supplier_code',explode(',',$v));
break;
}
}
})
->groupBy("supplier_code")
->orderBy('i.picking_items_id','asc');
$packingInfo = (new PackingModel())->PackingList();
if ($type == 1){
$list = $list->paginate($input['limit'], ['*'], 'p', $input['p'])->toArray();
if (!$list) return [20001, '没有数据'];
foreach ($list['data'] as $k=>&$v){
$v['packing_name'] = @$packingInfo[$v['packing_id']];
}
return [0, '成功', $this->clearData($list['data']), $list['total']];
}else{
$list = $list->get();
if (!$list) return false;
$data = $list->toArray();
foreach ($data as $k=>&$v){
$v['packing_name'] = @$packingInfo[$v['packing_id']];
}
return $this->clearData($data);
}
}
//清理数据
public function clearData($data){
$PurchaseModel = new PurchaseModel();
$all = $PurchaseModel
->select(DB::Raw("
SUM(lie_i.picking_price*lie_p.exchange_rate*lie_i.picking_number) as sum_pur_price, -- 采购总金额
SUM(lie_i.picking_price*lie_p.exchange_rate*lie_i.putaway_number) as sum_putaway_price -- 入库总金额
"))
->from("purchase as p")
->join('purchase_items as i', 'p.picking_id', '=', 'i.picking_id')
->whereNotIn("p.status",[-10,-2,-1])
->where("i.status",1)->first() ;
foreach ($data as $k=>&$v){
$running_number = $v['sum_picking_number']-$v['sum_putaway_number']-$v['sum_noshipping_number']; //采购在途数量
$sum_running_price = $v['price_picking_number']-$v['price_putaway_number']-$v['price_noshipping_number'];//采购在途金额
$send_number = $v['sum_picking_number']-$v['sum_putaway_number']-$v['sum_noshipping_number']-$v['sum_noshipping_number']; //送货在途数量
$sum_send_price = $v['price_picking_number']-$v['price_putaway_number']-$v['price_noshipping_number']-$v['price_noshipping_number'];//送货在途金额
$v['running_number'] = $running_number > 0 ? $running_number : 0;
$v['sum_running_price'] = $sum_running_price > 0 ? $sum_running_price : 0;
$v['send_number'] = $send_number > 0 ? $send_number : 0;
$v['sum_send_price'] = $sum_send_price > 0 ? $sum_send_price : 0;
$v['percent_pur_price'] = (round($v['sum_pur_price']/$all['sum_pur_price'],4)*100).'%'; //采购占比
$v['percent_putaway_price'] = (round($v['sum_putaway_price']/$all['sum_putaway_price'],4)*100).'%'; //入库占比
}
return $data;
}
// 导出
public function export()
{
$result = $this->main(2);
if (!$result) return ['errcode' => 20001, 'errmsg' => '没有数据'];
$column = array('供应商名称','供应商编号','采购次数','采购金额','采购在途数量','采购在途金额','送货在途数量','送货在途金额','入库总数量','入库金额','采购占比','入库占比'); // 表头
$temp = [];
foreach ($result as $k=>$v){
array_push($temp,[
'supplier_name'=>$v['supplier_name'],
'supplier_code'=>$v['supplier_code'],
'sum_pur_number'=>$v['sum_pur_number'],
'sum_pur_price'=>$v['sum_pur_price'],
'running_number'=>$v['running_number'],
'sum_running_price'=>$v['sum_running_price'],
'send_number'=>$v['send_number'],
'sum_send_price'=>$v['sum_send_price'],
'sum_putaway_number'=>$v['sum_putaway_number'],
'sum_putaway_price'=>$v['sum_putaway_price'],
'percent_pur_price'=>$v['percent_pur_price'],
'percent_putaway_price'=>$v['percent_putaway_price'],
]) ;
}
$fileName = '采购汇总-按供应商'.date('YmdHis', time()).'.csv';
export_csv($temp, $column, $fileName);
}
}
\ No newline at end of file
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
use Request;
use DB;
class SafeStockModel extends Model
{
protected $connection='web';
protected $table='safe_stock';
protected $primaryKey='safe_id';
public $timestamps = false;
// 安全库存警报
public function getSafeStockList($export=array())
{
$arr = ['p', 'limit','sku_id','goods_status','goods_type', 'stock', 'goods_name', 'brand_name', 'where','num','mpq'];
$input = Request::only($arr);
$input=TrimX($input,true,$arr);
//查询数据
$list = $this->where(function ($query) use ($input) {
foreach ($input as $k => $v){
if ($k == 'p' || $k == 'limit') {
continue;
} else if($k == 'goods_name' || $k=='brand_name') {
$query->where($k, 'like', $v.'%');
} else if($k == 'goods_type') {
$query->where($k, '=', $v);
}else if($k=='goods_status' || $k=='sku_id'){
$query->whereIn($k, explode(',',trim($v,',')));
}else if ($k == 'stock') {
if(empty($input['where']) || empty($input['mpq'])) continue;
if(empty($input['num'])) $input['num']=0;
$num = $input['mpq'] == '2' ? $input['num']."*mpq" : $input['num'];
if ($v == 1) {
$query-> whereRaw('(stock-lock_stock)'.$input['where'].$num);
} else if ($v == 2) {
$query-> whereRaw('(stock+wait_stock)'.$input['where'].$num);
}else if ($v == 3) {
$query-> whereRaw('(stock+wait_stock+in_num)'.$input['where'].$num);
}else if ($v == 4) {
$query-> whereRaw('(stock+wait_stock+purchase_num)'.$input['where'].$num);
}
}
}
});
if (array_key_exists('limit',$input) !== false){
$list = $list->paginate($input['limit'], ['*'], 'p', $input['p'])->toArray();
}else{
$list = $list->get()->toArray();
}
if (!$list) return [20001, '没有数据'];
$PackingModel=new PackingModel();
$PackingList=$PackingModel->PackingList();
$StatusList=Config('fixed.SELFSTATUS');
$TypeList=Config('fixed.TYPEID');
if (array_key_exists('limit',$input) === false){
$list['data'] = $list;
$list['total'] = count($list);
}
foreach ($list['data'] as $k=>$v){
$list['data'][$k]['packing_id']=!empty($PackingList[$v['packing_id']])?$PackingList[$v['packing_id']]:'--';
$list['data'][$k]['status_name']=!empty($StatusList[$v['goods_status']])?$StatusList[$v['goods_status']]:'--';
$list['data'][$k]['goods_type_name']=!empty($TypeList[$v['goods_type']])?$TypeList[$v['goods_type']]:'--';
$list['data'][$k]['use_stock']=$v['stock']-$v['lock_stock'];
$list['data'][$k]['stock'] +=$v['wait_stock'];
}
return [0, '成功', $list['data'], $list['total']];
}
// 导出
public function export()
{
$arr = ['p', 'limit', 'sku_status', 'safe_stock_status', 'goods_name', 'brand_name', 'sku_id'];
$input = Request::only($arr);
$data = $this->getSafeStockList($input);
if ($data[0] != 0) {
return $data[1]; die;
}
$exData = [];
foreach ($data[2] as $k=>$v){
$exData[$k]['sku_id']=$v['sku_id'];
$exData[$k]['goods_name']=$v['goods_name'];
$exData[$k]['class_name']=$v['class_name'];
$exData[$k]['brand_name']=$v['brand_name'];
$exData[$k]['packing_id']=$v['packing_id'];
$exData[$k]['encap']=$v['encap'];
$exData[$k]['mpq']=$v['mpq'];
$exData[$k]['status_name']=$v['status_name'];
$exData[$k]['goods_type_name']=$v['goods_type_name'];
$exData[$k]['purchase_num']=$v['purchase_num'];
$exData[$k]['in_num']=$v['in_num'];
$exData[$k]['lock_stock']=$v['lock_stock'];
$exData[$k]['wait_stock']=$v['wait_stock'];
$exData[$k]['use_stock']=$v['use_stock'];
$exData[$k]['stock']=$v['stock'];
}
$column = array('商品ID', '商品型号','类别', '制造商', '包装方式', '封装', 'MPQ', '状态', '类型','采购在途','送货在途','锁定库存','待入库','可用库存','实际库存'); // 表头
$fileName = '采购参数维护'.date('YmdHis', time()).'.csv';
export_csv($exData, $column, $fileName);
}
// 编辑
public function safeStockEdit()
{
$safe_id = Request::input('safe_id');
$safe_stock = Request::input('safe_stock');
return $this->where('safe_id', $safe_id)->update(['safe_stock'=>$safe_stock]);
}
}
\ No newline at end of file
<?php
namespace App\Model\Server;
use App\map\PreSaleOrderMap;
use App\Model\OperationLogModel;
use ClassPreloader\Config;
use League\Flysystem\Exception;
use Request;
use DB;
/*
* 采购与基石交流公共接口
*/
class FoostoneModel
{
const IS_DEBUG = false;
/*
* 请求
* @param $map post的数据
* @param string $url post的网址
* @return $array
*/
static function push($data,$url){
$url = Config("website.serviceUrl").$url.'?token='. md5($data['data'].$data['timestamp'].Config("fixed.WMSKEY"));
// $url = "http://szfootstone.ichunt.net/".$url.'?token='. md5($data['data'].$data['timestamp'].Config("fixed.WMSKEY"));
$res = post_curl($url, $data, array('timeout' => 10));
if (self::IS_DEBUG){
print_r($url);
print_r("<br/>");
print_r($res);
}else{
return json_decode($res,true);
}
}
/**
* 锁定基石库存
* @return [type] [description]
*/
public function lockSku($order_id, $skus = array(),$lock_type, $is_pre_sale = false)
{
$datas = array(
'lock_type'=>$lock_type, //库内异常传1
'order_id' => $order_id,
'Items' => $skus,
'is_pre_sale' => $is_pre_sale,
);
$data['type'] = 'sku.lock';
$data['data'] = urlencode(json_encode($datas));
$data['timestamp'] = time();
return self::push($data,'/wmsapi/WebApiLockStock');
}
/**
* 解锁基石库存
* @param [type] $order_id 订单ID
* @param array $skus sku明细 sku-》数量
* @param int $lock_type 锁定类型,库内异常传1
* @param boolean $reduce 是否扣减库存
* @param boolean $reduce_wms 是否请求WMS取消订单
* @return [type] [description]
*/
public function unlockSku($order_id, $skus = array(),$lock_type, $reduce = false, $reduce_wms = false)
{
$datas = array(
'order_id' => $order_id,
'Items' => $skus,
'reduce' => $reduce,
'reduce_wms' => $reduce_wms,
'lock_type'=>$lock_type, //库内异常传1
);
$data['type'] = 'sku.unlock';
$data['data'] = urlencode(json_encode($datas));
$data['timestamp'] = time();
return self::push($data,'/wmsapi/WebApiUnlockStock');
}
/**
* 查询sku最低价格
* @param array $data 查询
*/
public function GetLowestPrice($data = [])
{
// $data = ['10197'=>'GZ1608U102CTF']; //debug
OperationLogModel::log(0,1,'skulower_price_get',0,0,$data,'请求');
$datas['type'] = 'sku.GetLowestPrice';
$datas['data'] = urlencode(json_encode($data));
$datas['timestamp'] = time();
$res = self::push($datas,'/wmsapi/WebApiGetLowestPrice');
if ($res == null || $res == ""){
$res = "";
}
OperationLogModel::log(0,1,'skulower_price_success',0,0,$res,'返回');
return $res;
}
/*
* 查询sku
*/
public function WebApiObGoodsID($data){
$Url=Config('website.FS_API_Url').'WebApiObGoodsID';
$map['data']['arr']=$data;
$key=Config('website.MD5KEY');
$map['AuthSign']=MD5(MD5(http_build_query($map)).$key);
$map['time']=time();
$updata['data']=$map;
$res = curl($Url,http_build_query($updata),1);
$result=json_decode($res,true);
return $result;
}
}
\ No newline at end of file
<?php
namespace App\Model\Server;
use App\map\PreSaleOrderMap;
use App\Model\OperationLogModel;
use League\Flysystem\Exception;
use Request;
use DB;
/* 采购 推送到 wms 公共模型(通过yyc的python接口跳转)
if(empty($res['entity'][0]['Status']) ){
return [20001,'来料通知单撤消失败,请与仓库人员确认来料通知单的处理情况后再作处理',isset($res['entity'][0]['Message'])?$res['entity'][0]['Message']:''];
}
*/
class PurToWmsModel
{
private $SERVICE_URL;
public function __construct()
{
$this->SERVICE_URL = Config('website.WmsServiceUrl');
}
/*
* 关闭来料通知单
*@param string $delivery_sn 来料通知单
*@param int $user_id 用户ID
*@parma int $status 1 关闭 2删除
*/
public function cancelinstockorder($data){
OperationLogModel::log(0,1,'ptw_cancelinstockorder_get',0,0,$data,'通知仓库关闭来料通知单-原始数据');
$dataWms['type'] = 'cancelinstockorder';
$dataWms['from'] = 'purchase';
$dataWms['to'] = 'wms';
$dataWms['Timestamp'] = time();
$dataWms['jsonParas'] = json_encode(['entity' =>$data]);
$result=curl( $this->SERVICE_URL, http_build_query($dataWms), true,false,'');
OperationLogModel::log(0,1,'ptw_cancelinstockorder_get',0,0,$result,'通知仓库关闭来料通知单-返回结果');
return json_decode($result,true);
}
/*
* 采购退料通知wms
*/
public function SupplierReturn($data){
OperationLogModel::log(0,1,'ptw_supplierreturn_get',0,0,$data,'采购退料通知仓库-原始数据');
$dataWms['type'] = 'supplierreturn';
$dataWms['from'] = 'purchase';
$dataWms['to'] = 'wms';
$dataWms['Timestamp'] = time();
$dataWms['jsonParas'] = json_encode(['entity' =>[$data]]);
$result=curl( $this->SERVICE_URL, http_build_query($dataWms), true,false,'');
OperationLogModel::log(0,1,'ptw_supplierreturn_return',0,0,$result,'采购退料通知仓库-返回结果');
return json_decode($result,true);
}
/*
* 取消订单
*/
public function CancelOrder($order_id,$order_type){
OperationLogModel::log(0,1,'ptw_cancelorder_get',0,0,"订单ID:$order_id 订单类型:$order_type ",'采购取消订单通知仓库-原始数据'); //日志
$data = [
'order_id'=>$order_id,
'order_type'=>$order_type, //订单类型 1销售出库 2 采购退料
];
$dataWms['type'] = 'cancelorder';
$dataWms['from'] = 'purchase';
$dataWms['to'] = 'wms';
$dataWms['Timestamp'] = time();
$dataWms['jsonParas'] = json_encode(['entity' =>[$data]]);
$result=curl($this->SERVICE_URL, http_build_query($dataWms), true,false,'');
OperationLogModel::log(0,1,'ptw_cancelorder_return',0,0,"订单ID:$order_id 订单类型:$order_type 返回结果:$result" ,'采购取消订单通知仓库-返回结果'); //日志
return json_decode($result,true);
}
}
<?php
namespace App\Model\Server;
use Request;
use DB;
//跟财务接口通讯模型
class ServerFinanceModel
{
private $financeUrl ; //财务网址
const IS_DEBUG = false; //是否调试
public function __construct()
{
$this->financeUrl = Config('website.FinanceUrl');
// $this->financeUrl = 'http://szfinance.ichunt.net';
}
//发送请求
public function push($url,$map){
$financeResult = json_decode(AuthCurl($url, $map, true), true);
if (self::IS_DEBUG){
print_r($url);
print_r("<br/>");
print_r($map);
print_r("<br/>");
print_r($financeResult);
die();
}
return $financeResult;
}
//获取可抵扣的收款单列表
public function getFinanceReceive($data,$userId){
$url = $this->financeUrl . '/webapi/apiReceive';
$map['choice'] = 1;
$map['limit'] = $data['limit'];
$map['p'] = $data['p'];
$map['receive_status'] = '1,2';
$map['supplier_id'] = $data['supplier_id'];
return $this->push($url,$map);
}
/*
* 获取某采购单付款情况
* @param int $picking_id 采购ID
* @param int $picking_sn 采购单号
*/
public function getFinancePurchaseInfo($picking_id,$picking_sn){
$url = $this->financeUrl . '/webapi/apiPaymentInfo';
$map['picking_id'] = $picking_id;
$map['picking_sn'] = $picking_sn;
return $this->push($url,$map);
}
/*
* 对接财务系统,生成收款單
* abnormal_sn:45646 //差异单号
* receive_type:1 //1来料异常,2库内异常 3作废订单 4采购收款
* settle_party:1 //1猎芯 2富开
* supplier_id:342 //供应商ID
* supplier_code:43 //供应商编码
* supplier_name:432 //供应商名称
* currency:1 //币种:1人民币,2美金,3港币,4欧元,5英镑
* settle_amount:432 //结算金额
* create_uid:100 //申请人
* create_name:432432 //申请人名称
* putaway_sn:1 //入库单号
* picking_sn:1 //采购单号
* delivery_sn:1 //来料通知单号
* remark:1 //备注
*/
public function pushReceive($data){
$url = $this->financeUrl . '/webapi/pushReceive';
$map['abnormal_sn'] = $data['abnormal_sn'];
$map['receive_type'] = $data['receive_type'];
$map['settle_party'] = $data['settle_party'];
$map['supplier_id'] = $data['supplier_id'];
$map['supplier_code'] = $data['supplier_code'];
$map['supplier_name'] = $data['supplier_name'];
$map['pay_type'] = $data ? $data['pay_type'] : "";
$map['day_num'] = $data ? $data['day_num'] : "";
$map['currency'] = $data['currency'];
$map['settle_amount'] = $data['settle_amount'];
$map['create_uid'] = $data['create_uid'];
$map['create_name'] = $data['create_name'];
$map['putaway_sn'] = $data['putaway_sn'];
$map['picking_sn'] = $data['picking_sn'];
$map['delivery_sn'] =$data['delivery_sn'];
$map['remark'] = $data['remark'];
return $this->push($url,$map);
}
/*
*查询此采购单(申请付款中+已付款)总金额
*@param string|array $picking_sn 采购单号
*@return array
*/
public function GetPurPay($picking,$type = 1){
$s = "";
if (is_array($picking)){
foreach ($picking as $k=>$v){
$s .= " '$v',";
}
$s = "in (".rtrim($s,',').")";
}else{
$s = " = '$picking'";
}
$sql = "SELECT
i.picking_sn,
i.picking_id,
SUM(i.pay_amount)AS pay_amount
FROM
lie_payment p,
lie_payment_items i
WHERE
p.payment_id = i.payment_id
AND p.`status` IN(- 1, 1, 2, 3, 7, 10)
AND ".($type == 1 ? 'picking_sn':"picking_id")." $s
GROUP BY picking_sn";
$res = SelectDb('finance',$sql);
return count($res) ? array_column($res,'pay_amount',($type == 1 ? 'picking_sn':"picking_id")) : [];
}
}
\ No newline at end of file
<?php
namespace App\Model\Server;
use App\map\PreSaleOrderMap;
use App\Model\AbnormalItemsModel;
use App\Model\AbnormalModel;
use App\Model\OperationLogModel;
use App\Model\PurchaseModel;
use App\Model\Server\ServerFinanceModel;
use App\Model\UserModel;
use League\Flysystem\Exception;
use Request;
use DB;
/*
* wms 推送到采购公共模型
*/
class WmsToPurModel
{
/*
* wms出库(库内异常退货推送到采购)
* @param array $data = "{\"outstock_sn\": \"LX1811010001\",
\"order_id\": \"237894\", //对应异常单id
\"shipping_id\": \"10\",
\"box_weight\": \"115.0000\",
\"express_amount\": \"0.0000\",
\"express_sn\": \"SUR400002492502\",
\"send_time\": \"1541041860\",
\"send_userid\": \"1460\",
\"is_print\": \"False\",
\"warehouse_code\": \"01\",
\"total_rows\": \"1\",
\"detail\": [
{
\"outstock_sn\": \"LX1811010001\",
\"order_id\": \"237894\",
\"rec_id\": \"250194\",
\"goods_id\": \"32937\",
\"goods_price\": \"1.15560\",
\"goods_number\": \"210.0000\"
}
]}";
*/
public function WebApiAbnormalStockReturn($data){
OperationLogModel::log(0,3,'change_abnormal_putaway_get',0,0,$data,'接收','采购退料单回传'); //日志
//接收数据
$param = ['order_id','send_time','detail'];
if (!checkRequire($data,$param)){
return [20001,'缺少参数'.checkRequire($data,$param,2)];
}
$abnormalId = $data['order_id'];
$PurchaseModel = new PurchaseModel();
$UserModel = new UserModel();
$AbnormalModel = new AbnormalModel();
$AbnormalItemsModel = new AbnormalItemsModel();
$ServerFinanceModel = new ServerFinanceModel();
//去重
$detail = [];
foreach ($data['detail'] as $k=>$v){
if (array_key_exists($v['goods_id'],$detail)){
$detail[$v['goods_id']]['goods_number'] += $v['goods_number'];
}else{
$detail[$v['goods_id']] = $v;
}
}
try{
$con = DB::connection('web');
$con->beginTransaction();
#对比出库数量跟申请数量是否一致
$abItems = $AbnormalItemsModel->select("i.sku_id","a.*")->from("abnormal_items as a") ->join("purchase_items as i","a.picking_items_id","=","i.picking_items_id")->where("a.abnormal_id",$abnormalId)->get();
if (!$abItems->count()){
throw new Exception("不存在此订单号");
}
$abItemsArr = $abItems->toArray();
$abItemsGroup = array_column($abItemsArr,null,'sku_id');
foreach ($detail as $a=>$b){
if (array_key_exists($b['goods_id'],$abItemsGroup) === false){
throw new Exception("不存在此sku_id".$b['goods_id']);
}else{
if ($abItemsGroup[$b['goods_id']]['real_number'] != $b['goods_number']){
throw new Exception("此商品:".$b['goods_id']."退货数量跟申请数量不一致");
}
}
}
#扣减基石库存
$unlockSku = array_column($abItemsArr,'real_number','sku_id');
$unlockRes = (new FoostoneModel())->unlockSku($abnormalId,$unlockSku,1,true); //扣减库存
if ($unlockRes['errcode'] != 0) {
throw new Exception("基石扣减库存失败:order_id:$abnormalId sku_id:$unlockSku msg:".$unlockRes['errmsg']);
}
#如果存在收款,通知财务,调用财务收款接口
$allWithdrawAmount = $AbnormalItemsModel->where("abnormal_id",$abnormalId)->sum("withdraw_amount");
$abInfo = $AbnormalModel->where("abnormal_id",$abnormalId)->first();
if ($allWithdrawAmount > 0) {
#查询供应商
$su = $PurchaseModel->where("picking_sn", $abInfo['picking_sn'])->select("supplier_id","supplier_code","supplier_name","currency","pay_type","day_num")->first();
//查用户名
$userName = $UserModel->FinduserInfoName($abInfo['create_uid']);
#对接财务系统,通知收款
$map['abnormal_sn'] = $abInfo->abnormal_sn;
$map['receive_type'] = $abInfo->abnormal_type;
$map['settle_party'] = 1;
$map['supplier_id'] = $su ? $su['supplier_id'] : "";
$map['supplier_code'] = $su ? $su['supplier_code'] : "";
$map['supplier_name'] = $su ? $su['supplier_name'] : "";
$map['pay_type'] = $su ? $su['pay_type'] : "";
$map['day_num'] = $su ? $su['day_num'] : "";
$map['currency'] = $su ? $su['currency'] : "";
$map['settle_amount'] = $allWithdrawAmount;
$map['create_uid'] = $abInfo['create_uid'];
$map['create_name'] = $userName ? $userName : "";
$map['putaway_sn'] = $abInfo->putaway_sn;
$map['picking_sn'] = $abInfo->picking_sn;
$map['delivery_sn'] = $abInfo->delivery_sn;
$map['remark'] = $abInfo->remark;
$finaneResult =$ServerFinanceModel->pushReceive($map);
if ($finaneResult['err_code'] > 0) {
throw new Exception("推送财务收款接口失败:".$finaneResult);
}
}
#获取出库最新汇率
$abnormalInfo = $AbnormalModel->where("abnormal_id",$abnormalId)->first();
$HLCurrency=Config('fixed.HLCurrency');
if($abnormalInfo['currency']==1){
$exchange_rate = 1;
}else{
$exchange_rate = webserver($HLCurrency[$abnormalInfo['currency']]);
if(!$exchange_rate || !$exchange_rate>0){
throw new Exception("汇率获取失败");
}
}
#最后更改状态为已完成+更新汇率
$pan = $AbnormalModel->where("abnormal_id",$abnormalId)->update(['status'=>4,'exchange_rate'=>$exchange_rate,'outstock_time'=>time()]);
OperationLogModel::log(0,3,'change_abnormal_putaway_success',0,0,$data,'成功','采购退料单回传'); //日志
$con->commit();
return [0, '成功'];
}catch (\Exception $e) {
$con->rollBack();
OperationLogModel::log(0,3,'change_abnormal_putaway_error',0,0,$data,$e->getMessage(),'采购退料单回传-失败'); //日志
return [20003, '失败:'.$e->getMessage()];
}
}
}
\ No newline at end of file
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
use DB;
class SnModel extends Model
{
protected $connection='web';
protected $table='numbering_rules';
public $timestamps = false;
/**
* 查询单号
*/
public function Sn($rule_code){
DB::connection($this->connection)->beginTransaction();
//$data = $this->where('rule_code', $rule_code)->lockForUpdate()->first();
$data = $this->where('rule_code', $rule_code)->first();
if (!empty($data)) {
$data = $data->toArray();
}
$str = $data['rule_prefix'];
$str_middle = '';
$number = $data['rule_suffix_number'] + 1;
if (!empty($data['rule_mask'])) {
$str_middle = date($data['rule_mask']);
}
$str .= $str_middle;
if ($str_middle != $data['rule_mask_str']) {//重置
$number = 1;
$save['rule_mask_str'] = $str_middle;
}
if ($data['rule_suffix_len'] > 0) {
$str .= $this->fillNum($data['rule_suffix_len'], $number);
if ($number != $data['rule_suffix_number']) {
$save['rule_suffix_number'] = $number;
}
if (isset($save)) {
$this->where('rule_id', $data['rule_id'])->update($save);
}
}
$str .= $data['rule_suffix'];
DB::connection($this->connection)->commit();
return $str;
}
/**
* 补充0
* @param [type] $len [description]
* @param [type] $num [description]
* @return [type] [description]
*/
private function fillNum($len, $num)
{
$str = '';
if ($len > 0) {
$str = str_pad($num, $len, '0', 0);
}
return $str;
}
}
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
use SoapWrapper;
class SoapWrapperModel extends Model
{
public function webserver($currency,$time=''){
if(empty($currency)) return false;
if(empty($time)){
$time=date('Y-m-d',time());
}else{
$time=date('Y-m-d',$time);
}
$Arr=['CURRENCY'=>$currency,'BIZDATE'=>$time];
SoapWrapper::add(function($login){
$login->name('login')->wsdl(Config('website.HL_LOGIN_URL'));
});
SoapWrapper::service('login', function ($login) use ($Arr) {
$result=$login->call('login',Config('website.HL_CONFIG'));
if(empty($result->sessionId)) return false;
});
SoapWrapper::add(function($hl){
$hl->name('hl')->wsdl(Config('website.HL_URL'));
});
SoapWrapper::service('hl', function ($hl) use ($Arr,&$currency) {
$currency=$hl->call('getExchangeRate',[json_encode($Arr)]);
});
return $currency;
}
}
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
use Request;
class SupplierAddressModel extends Model
{
protected $connection='web';
protected $table='supplier_address';
public $timestamps = false;
public function AddInfo($SupplierID='',$data='',$code=''){
if(empty($SupplierID) || empty($data) || !is_array($data)) return false;
$Add=$data[1];
$Add['supplier_id']=$SupplierID;
$Add['supplier_code']=$code;
$Add['address_type']=1;
$this->insert($Add);
$Add=$data[2];
$Add['supplier_id']=$SupplierID;
$Add['supplier_code']=$code;
$Add['address_type']=2;
$this->insert($Add);
}
public function SaveInfo($data=''){
if(!is_array($data) || empty($data[1]['info_id']) || empty($data[2]['info_id'])) return false;
$Save=$data[1];
$this->where('info_id','=',$data[1]['info_id'])->update($Save);
$Save=$data[2];
return $this->where('info_id','=',$data[2]['info_id'])->update($Save);
}
public function AddressInfo($SupplierID=''){
$collert=Request::only('supplier_id');
$collert=TrimX($collert,true,['supplier_id']);
empty($collert) && $collert['supplier_id']=$SupplierID;
if(empty($collert['supplier_id'])) return false;
$info=$this->where('supplier_id','=',$collert['supplier_id'])->get();
if(!$info) return false;
$info=$info->toArray();
$Arr=[];
foreach ($info as $k=>$v){
$Arr[$v['address_type']]=$v;
}
return $Arr;
}
}
<?php
namespace App\Model;
use App\map\SupplierReceiptMap;
use Illuminate\Database\Eloquent\Model;
use Request;
class SupplierReceiptModel extends Model
{
protected $connection='web';
protected $table='supplier_receipt';
public $timestamps = false;
//列表
public function getList($uid = "",$wmsData = "")
{
$input = $wmsData ? $wmsData : Request::all() ;
$list = $this->where(function ($query) use ($input) {
foreach ($input as $k => $v){
$v = trim($v);
if (empty($v)){
continue;
}
switch ($k){
case "p":
case "limit":
case "_url":
case "supplier_id":
case "create_uid":
continue;
break;
default:
$query->whereRaw("FIND_IN_SET($k,'".trim($v,',')."') > 0");
break;
}
}
})->orderBy('status','asc');
if ($input['supplier_id'] >0){
$list = $list->where("supplier_id",$input['supplier_id']);
}else{
$list = $list->where("create_uid",$uid)->where("supplier_id",0);
}
$list = $list->paginate($input['limit'], ['*'], 'p', $input['p'])->toArray();
if (!$list) return [20001, '没有数据'];
$UserModel = new UserModel();
foreach ($list['data'] as $k=>&$v){
$v['k'] = $k+1;
$v['create_uid_username'] = $UserModel->FinduserInfoName($v['create_uid']); //创建用户名
$v['create_time'] = date("Y-m-d H:i:s",$v['create_time']); //格式时间
$v['receipt_type'] = SupplierReceiptMap::$receipt_type[$v['receipt_type']]; //格式时间
$v['status_name'] = SupplierReceiptMap::$status[$v['status']]; //格式时间
}
return [0, '成功', $list['data'], $list['total']];
}
//插入1
public function AddInfo($SupplierID='',$data=''){
if(empty($data) || !is_array($data)) return false;
$data['supplier_id']=$SupplierID;
$result=$this->insert($data);
return $result;
}
//插入2
public function AddInfo2($uid = ""){
$indata = Request::all();
if ($indata['receipt']['receipt_type'] == 1){
$checkPerm = ['currency','bank_name','bank_adderss','account_no','account_name','certificate'];
}else{
$checkPerm = ['currency','bank_name','bank_adderss','account_no','account_name','certificate','swift_code'];
}
if(!checkRequire2($indata["receipt"],$checkPerm)){
return [20001, '请填写:'.checkRequire2($indata["receipt"],$checkPerm,2)];
}
if ($indata['receipt_id'] > 0){ //修改
$indata['receipt']['update_time'] =time();
unset($indata['receipt']['supplier_id']);
$indata['receipt']['status'] = 2; //重置状态为待审核
$result = $this->where("receipt_id",$indata['receipt_id'])->update($indata['receipt']);
}else{ //新增
$indata['receipt']['supplier_id'] = $indata['supplier_id'];
$indata['receipt']['create_uid'] =$uid;
$indata['receipt']['status'] =2;
$indata['receipt']['create_time'] =time();
$indata['receipt']['update_time'] =time();
$result=$this->insert($indata['receipt']);
}
return $result ? [0, '成功'] : [20002,'失败'];
}
public function SaveInfo($data=''){
if(!is_array($data) || empty($data['receipt_id'])) return false;
return $this->where('receipt_id','=',$data['receipt_id'])->update($data);
}
public function ReceiptInfo($SupplierID=''){
$collert=Request::only('supplier_id');
$collert=TrimX($collert,true,['supplier_id']);
empty($collert) && $collert['supplier_id']=$SupplierID;
if(empty($collert['supplier_id'])) return false;
$info=$this->where('supplier_id','=',$collert['supplier_id'])->first();
if(!$info) return false;
return $info->toArray();
}
public function ReceiptInfo2($receiptID=''){
$info=$this->where('receipt_id','=',$receiptID)->first();
if(!$info) return false;
return $info->toArray();
}
//更新状态
public function updateStatus($receipt_id,$status){
$res = $this->where('receipt_id',$receipt_id)->update(['status'=>$status,'update_time'=>time()]);
if (!$res){
return [10001,'更新失败,请重试'];
}else{
return [0,'更新成功'];
}
}
}
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class UploadLog extends Model
{
protected $connection='web';
protected $table='upload_log';
public $timestamps = false;
//生成的文件上传到OSS
public function SaveDownFile($FileName=''){
if(empty($FileName)) return false;
$result=json_decode(UploadToOss(storage_path().DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR.'uploads'.DIRECTORY_SEPARATOR.$FileName),true);
if(empty($result['code']) || $result['code'] != 200 || empty($result['data'][0])) return false;
return $result['data'][0];
}
public function SaveLog($map,$data){
return $this->where('up_id','=',$map)->update($data);
}
public function ApiUploadItemFile($admin=''){
$file = Request::file('file');
$Arr=['picking_id'];
$collert=Request::only($Arr);
if ($file->isValid()) {
$ext = $file->getClientOriginalExtension();
$realPath = $file->getRealPath();
if($ext!='csv'){
$this->Export(10001,'上传格式错误');
}
// 上传文件
$filename = date('Y-m-d-H-i-s') . '-' . uniqid() . '.' . $ext;
$bool = Storage::disk('uploads')->put($filename, file_get_contents($realPath));
if(!$bool) return [10002,'文件处理失败'];
$filePath = storage_path().DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR.'uploads'.DIRECTORY_SEPARATOR.$filename;
$result=json_decode(UploadToOss($filePath),true);
Storage::disk('uploads')->delete($filename);
if(!empty($result['code']) && $result['code']==200 && !empty($result['data'][0])){
$data['id']=$collert['picking_id'];
$data['file_name']=json_encode([
'upload'=>$result['data'][0]
]);
$data['log']=json_encode([
date('Y-m-d H:i',time()). '建立任务'
]);
$data['create_time']=time();
$data['update_time']=time();
$data['type']=1;
$data['admin_id']=$admin;
DB::connection($this->connection)->beginTransaction();
$insert=$this->insertGetId($data);
if($insert){
$return=dispatch(new UploadItems($insert));
if($return){
DB::connection($this->connection)->commit();
return [0,'上传成功,请等待系统自动处理'];
}else{
return [10004,'上传失败'];
}
}else{
return [10003,'上传失败'];
}
}else{
return [10002,'上传失败'];
}
}else{
return [10005,'上传失败'];
}
}
}
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
use App\Model\OrganizationModel;
class UserModel extends Model
{
protected $table='user_info';
public $timestamps = false;
public function DepartmentUserInfo($Department=''){
if(!$Department) return false;
$OrganizationModel=new OrganizationModel();
$UserID=$OrganizationModel->ObtainDepartment($Department);
$result=$this->whereIn('userId',$UserID)->select('userId','name','email')->orderBy('status','asc')->get();
if(!$result) return false;
return $result->toArray();
}
public function FinduserInfoName($UserID=''){
if(empty($UserID)) return "";
$result=$this->where('userId','=',$UserID)->select('userId','name','email')->first();
if(!$result) return "";
$result=$result->toArray();
empty($result['name']) && $result['name']=$result['email'];
return $result['name'];
}
public function FindUserInfoNE($UserID=''){
if(empty($UserID)) return false;
$result=$this->where('userId','=',$UserID)->select('userId','name','email')->first();
if(!$result) return false;
$result=$result->toArray();
empty($result['name']) && $result['name']=$result['email'];
return $result;
}
public function UserList(){
$data=$this->select('userId','name','email')->get()->toArray();
if($data && is_array($data)){
foreach ($data as $k=>$v){
if(empty($v['name'])){
$data[$k]['name']=$v['email'];
}
$arr[$v['userId']]=$v;
}
}
return $arr;
}
}
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}
<?php
namespace App\Providers;
use Illuminate\Contracts\Auth\Access\Gate as GateContract;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* @var array
*/
protected $policies = [
'App\Model' => 'App\Policies\ModelPolicy',
];
/**
* Register any application authentication / authorization services.
*
* @param \Illuminate\Contracts\Auth\Access\Gate $gate
* @return void
*/
public function boot(GateContract $gate)
{
$this->registerPolicies($gate);
//
}
}
<?php
namespace App\Providers;
use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* @var array
*/
protected $listen = [
'App\Events\SomeEvent' => [
'App\Listeners\EventListener',
],
];
/**
* Register any other events for your application.
*
* @param \Illuminate\Contracts\Events\Dispatcher $events
* @return void
*/
public function boot(DispatcherContract $events)
{
parent::boot($events);
//
}
}
<?php
namespace App\Providers;
use Illuminate\Routing\Router;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
class RouteServiceProvider extends ServiceProvider
{
/**
* This namespace is applied to your controller routes.
*
* In addition, it is set as the URL generator's root namespace.
*
* @var string
*/
protected $namespace = 'App\Http\Controllers';
/**
* Define your route model bindings, pattern filters, etc.
*
* @param \Illuminate\Routing\Router $router
* @return void
*/
public function boot(Router $router)
{
//
parent::boot($router);
}
/**
* Define the routes for the application.
*
* @param \Illuminate\Routing\Router $router
* @return void
*/
public function map(Router $router)
{
$this->mapWebRoutes($router);
//
}
/**
* Define the "web" routes for the application.
*
* These routes all receive session state, CSRF protection, etc.
*
* @param \Illuminate\Routing\Router $router
* @return void
*/
protected function mapWebRoutes(Router $router)
{
$router->group([
'namespace' => $this->namespace
], function ($router) {
require app_path('Http/routes.php');
});
}
}
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
<?php
namespace App\map;
class OperationLogMap{
// 操作类型:1添加,2删除,3修改,4审核通过,5审核驳回,6导出 operation_type
const OPERATION_TYPE_ADD = 1;
const OPERATION_TYPE_DELETE = 2;
const OPERATION_TYPE_UPDATE = 3;
const OPERATION_TYPE_PASS = 4;
const OPERATION_TYPE_NOPASS = 5;
const OPERATION_TYPE_EXPORT = 6;
static $operation_type =[
self::OPERATION_TYPE_ADD => "添加",
self::OPERATION_TYPE_DELETE => "删除",
self::OPERATION_TYPE_UPDATE => "修改",
self::OPERATION_TYPE_PASS => "审核通过",
self::OPERATION_TYPE_NOPASS => "审核驳回",
self::OPERATION_TYPE_EXPORT => "导出",
];
//关联模块
static $relevance_type = [
'abnormal' =>'采购异常审核',
'add_abnormal_error'=>'添加异常错误',
'add_abnormal_success'=>'添加异常成功',
'change_abnormal_putaway_get'=>'采购退料单回传-接收',
'change_abnormal_putaway_error'=>'采购退料单回传-错误',
'change_abnormal_putaway_success'=>'采购退料单回传-成功',
'checkOrAddNoshipping'=>'无需补发',
'consign_sale_error'=>'寄售写入错误',
'consign_sale_get'=>'寄售获取数据',
'consign_sale_success'=>'寄售写入成功',
'purchase_receive'=>'采购申请收款',
'pre_sale_order_add_get'=>'接收预售数据(基石传来)',
'pre_sale_order_add_error'=>'接收预售数据验证错误(基石传来)',
'pre_sale_order_add_success'=>'插入预售订单数据成功(基石传来)',
'pre_sale_order_update_success'=>'更新预售订单数据成功',
'pre_sale_order_update_error'=>'更新预售订单数据失败',
'pre_sale_order_add_error'=>'插入预售订单数据错误(基石传来)',
'pre_sale_order_queue_success'=>'预售任务统计成功',
'pre_sale_order_queue_error'=>'预售任务统计失败',
'purchase_need_refuse'=>'预售驳回',
'purchase_invoice_add'=>'添加进项票',
'purchase_invoice_exmain'=>'审核进项票',
'checkOrAddNoshipping'=>'删除未送商品数量需求',
'purchase_receive'=>'采购申请收款',
'WebApiPutaway'=>'WMS推送入库',
'ptw_cancelinstockorder_get'=>'通知仓库关闭来料通知单-发送',
'ptw_cancelinstockorder_return'=>'通知仓库关闭来料通知单-返回',
'ptw_supplierreturn_get'=>'采购退料通知仓库-原始数据',
'ptw_supplierreturn_return'=>'采购退料通知仓库-返回结果',
'ptw_cancelorder_get'=>'采购取消订单通知仓库-原始数据',
'ptw_cancelorder_return'=>'采购取消订单通知仓库-返回结果',
'skulower_price_get'=>'获取sku最低价-请求数据',
'skulower_price_success'=>'获取sku最低价-返回结果',
];
}
<?php
namespace App\map;
//预售订单数据
class PreSaleOrderMap{
//status 状态:-1已取消 1 处理中 2已处理 3已发货 4部分发货
const STATUS_CANCEL = -1;
const STATUS_DEALING = 1;
const STATUS_DEALT = 2;
const STATUS_ALL_DELIVERED = 3;
const STATUS_HALF_DELIVERED = 4;
static $status =[
self::STATUS_CANCEL => "已取消",
self::STATUS_DEALING => "处理中",
self::STATUS_DEALT => "已处理",
self::STATUS_ALL_DELIVERED => "已发货",
self::STATUS_HALF_DELIVERED => "部分发货",
];
//所有状态
static $statusAll = [self::STATUS_CANCEL,self::STATUS_DEALING,self::STATUS_DEALT,self::STATUS_ALL_DELIVERED,self::STATUS_HALF_DELIVERED];
}
This diff is collapsed. Click to expand it.
This diff could not be displayed because it is too large.
This diff is collapsed. Click to expand it.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
No preview for this file type
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
No preview for this file type
This diff could not be displayed because it is too large.
No preview for this file type
No preview for this file type
This diff could not be displayed because it is too large.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
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 sign in to comment