Commit 7166432c by 宁成龙

Initial commit

parents
Showing with 5118 additions and 0 deletions

Too many changes to show.

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

root = true
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
indent_style = space
indent_size = 4
trim_trailing_whitespace = true
[*.md]
trim_trailing_whitespace = false
[*.{yml,yaml}]
indent_size = 2
APP_NAME=Laravel
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_URL=http://localhost
LOG_CHANNEL=stack
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
BROADCAST_DRIVER=log
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS=null
MAIL_FROM_NAME="${APP_NAME}"
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1
MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
RESOURCE_CONFIG_DIR=
APP_STORAGE_PATH=
CLOCKWORK_ENABLE=false
/node_modules
/public/hot
/public/storage
/storage/*.key
/storage/logs/*
/storage/framework/*
/.env.backup
/.phpunit.result.cache
/Homestead.json
/Homestead.yaml
/npm-debug.log
/yarn-error.log
/.idea
/.env
/vendor/_laravel_idea
/storage/clockwork/.gitignore
/*.jsbeautifyrc
/.vscode/extensions.json
/.vscode/settings.json
/.vscode
php:
preset: laravel
disabled:
- unused_use
finder:
not-name:
- index.php
- server.php
js:
finder:
not-name:
- webpack.mix.js
css: true
<p align="center"><a href="https://laravel.com" target="_blank"><img src="https://raw.githubusercontent.com/laravel/art/master/logo-lockup/5%20SVG/2%20CMYK/1%20Full%20Color/laravel-logolockup-cmyk-red.svg" width="400"></a></p>
<p align="center">
<a href="https://travis-ci.org/laravel/framework"><img src="https://travis-ci.org/laravel/framework.svg" alt="Build Status"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://poser.pugx.org/laravel/framework/d/total.svg" alt="Total Downloads"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://poser.pugx.org/laravel/framework/v/stable.svg" alt="Latest Stable Version"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://poser.pugx.org/laravel/framework/license.svg" alt="License"></a>
</p>
## About Laravel
Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experience to be truly fulfilling. Laravel takes the pain out of development by easing common tasks used in many web projects, such as:
- [Simple, fast routing engine](https://laravel.com/docs/routing).
- [Powerful dependency injection container](https://laravel.com/docs/container).
- Multiple back-ends for [session](https://laravel.com/docs/session) and [cache](https://laravel.com/docs/cache) storage.
- Expressive, intuitive [database ORM](https://laravel.com/docs/eloquent).
- Database agnostic [schema migrations](https://laravel.com/docs/migrations).
- [Robust background job processing](https://laravel.com/docs/queues).
- [Real-time event broadcasting](https://laravel.com/docs/broadcasting).
Laravel is accessible, powerful, and provides tools required for large, robust applications.
## Learning Laravel
Laravel has the most extensive and thorough [documentation](https://laravel.com/docs) and video tutorial library of all modern web application frameworks, making it a breeze to get started with the framework.
If you don't feel like reading, [Laracasts](https://laracasts.com) can help. Laracasts contains over 1500 video tutorials on a range of topics including Laravel, modern PHP, unit testing, and JavaScript. Boost your skills by digging into our comprehensive video library.
## Laravel Sponsors
We would like to extend our thanks to the following sponsors for funding Laravel development. If you are interested in becoming a sponsor, please visit the Laravel [Patreon page](https://patreon.com/taylorotwell).
### Premium Partners
- **[Vehikl](https://vehikl.com/)**
- **[Tighten Co.](https://tighten.co)**
- **[Kirschbaum Development Group](https://kirschbaumdevelopment.com)**
- **[64 Robots](https://64robots.com)**
- **[Cubet Techno Labs](https://cubettech.com)**
- **[Cyber-Duck](https://cyber-duck.co.uk)**
- **[Many](https://www.many.co.uk)**
- **[Webdock, Fast VPS Hosting](https://www.webdock.io/en)**
- **[DevSquad](https://devsquad.com)**
- **[OP.GG](https://op.gg)**
## Contributing
Thank you for considering contributing to the Laravel framework! The contribution guide can be found in the [Laravel documentation](https://laravel.com/docs/contributions).
## Code of Conduct
In order to ensure that the Laravel community is welcoming to all, please review and abide by the [Code of Conduct](https://laravel.com/docs/contributions#code-of-conduct).
## Security Vulnerabilities
If you discover a security vulnerability within Laravel, please send an e-mail to Taylor Otwell via [taylor@laravel.com](mailto:taylor@laravel.com). All security vulnerabilities will be promptly addressed.
## License
The Laravel framework is open-sourced software licensed under the [MIT license](https://opensource.org/licenses/MIT).
<?php
namespace App\Console\Commands;
use App\Http\Models\PayableModel;
use App\Http\Models\PurchaseOrderModel;
use App\Http\Services\PayableService;
use App\Http\Services\PurchaseUserService;
use Carbon\Carbon;
use Carbon\CarbonPeriod;
use DateInterval;
use Illuminate\Console\Command;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
class IndexStatistic extends Command
{
/**
* 首页数据统计
*
* @var string
*/
protected $signature = 'statistic:index';
/**
* The console command description.
*
* @var string
*/
protected $description = '首页数据统计';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
*/
public function handle()
{
//获取上一次跑数据的时间,用来防止中间出现停止统计的情况
$timeInterval = self::getTimeInterval('all');
$purchaseUsers = PurchaseUserService::getPurchaseUsers();
self::statistics($purchaseUsers, $timeInterval, 'day');
self::statistics($purchaseUsers, $timeInterval, 'month');
echo "完成首页统计";
}
const DATE_TYPE_DAY = 1;
const DATE_TYPE_WEEK = 2;
const DATE_TYPE_MONTH = 3;
const CURRENCY_RMB = 1;
const CURRENCY_USD = 2;
const CURRENCY_USD_TO_RMB = 3;
/*
* 统计
* 需要记录每日,每月的记录
* 粒度是采购员
*/
public static function statistics($purchaseUsers, $totalTimeInterval, $type = 'day')
{
//参数这个$totalTimeInterval是一个大的时间区间,要根据类型去拆成小的时间区间,因为存到mongo里面是分天或者分月的
$perTimeInterval = self::getPerTimeInterval($totalTimeInterval, $type);
$mongo = DB::connection('mongodb');
foreach ($perTimeInterval as $timeInterval) {
//找出所有采购员
foreach ($purchaseUsers as $key => $user) {
$purchaseOrders = self::getPurchaseOrders($user['userId'], $timeInterval);//采购单列表,用于下面的计算
if (!$purchaseOrders) {
continue;
}
$purchaseAmount = self::calculatePurchaseAmount($purchaseOrders);//采购金额
$grossProfit = self::calculateGrossProfit($purchaseOrders);//毛利
$date = $timeInterval[0];
$dayRecord = [
'purchase_uid' => $user['userId'],
'purchase_name' => $purchaseOrders[0]['purchase_name'],
'purchase_amount_rmb' => (float)Arr::get($purchaseAmount, self::CURRENCY_RMB, 0),
'purchase_amount_usd' => (float)Arr::get($purchaseAmount, self::CURRENCY_USD, 0),
'purchase_amount_usd_to_rmb' => (float)Arr::get($purchaseAmount, self::CURRENCY_USD_TO_RMB, 0),
'gross_profit' => $grossProfit,
'date' => $timeInterval[0],
'date_string' => date('Y-m-d', $timeInterval[0]),
'create_time' => time(),
];
if ($type == 'day') {
//先去mongo判断是否有今天的记录,有的话跳过
$existDayRecord = $mongo->collection('pur_statistics_index_day')
->where('date', $date)->where('purchase_uid', (int)$user['userId'])->first();
if ($existDayRecord) {
unset($dayRecord['create_time']);
$mongo->collection('pur_statistics_index_day')
->where('date', $date)->where('purchase_uid', $user['userId'])
->update($dayRecord);
continue;
}
$mongo->collection('pur_statistics_index_day')->insert($dayRecord);
} else {
$month = $timeInterval[0];
$dayRecord['date'] = $month;
$dayRecord['date_string'] = date('Y-m', $month);
$monthRecord = $dayRecord;
$existRecord = $mongo->collection('pur_statistics_index_month')
->where('date', $month)->where('purchase_uid', $user['userId'])->first();
if (!$existRecord) {
//如果不存在这条记录,那就取目前这条当作这个月的初始化数据
$mongo->collection('pur_statistics_index_month')->insert($monthRecord);
} else {
$mongo->collection('pur_statistics_index_month')
->where('date', $month)->where('purchase_uid', $user['userId'])
->update($monthRecord);
}
}
}
}
}
//默认是获取所有时间,否则的话就是获取上一次跑的时间,去mongodb里面获取最后一条记录的天数
private static function getTimeInterval($type = 'all')
{
$mongo = DB::connection('mongodb');
$now = Carbon::now()->getTimestamp();
if ($type == 'all') {
//设定一个开始时间
$start = Carbon::createFromDate('2021-11-11')->getTimestamp();
} else {
//去mongo找出最后一条记录的日期
$lastRecord = $mongo->collection('pur_statistics_index_day')->orderBy('_id', 'desc')->first();
$start = $lastRecord ? $lastRecord['create_time'] : Carbon::createFromDate('2021-11-11')->getTimestamp();;
}
return [$start, $now];
}
//获取分解后的每天间隔日期或者每月间隔日期
public static function getPerTimeInterval($timeInterval, $type)
{
$perTimeInterval = [];
$carbonStart = Carbon::createFromTimestamp($timeInterval[0]);
$carbonEnd = Carbon::createFromTimestamp($timeInterval[1]);
//根据传过来的timeInterval分成时间段
if ($type == 'day') {
//如果类型是天,那就分成多个天的时间段去统计
$period = CarbonPeriod::create($carbonStart->toDateTime(), $carbonEnd->toDateTime());
foreach ($period as $date) {
$start = $date->startOfDay()->getTimestamp();
$end = $date->endOfDay()->getTimestamp();
$perTimeInterval[] = [$start, $end];
}
} else {
//如果类型是月,那就分成多个月的时间段去统计,注意还要把当月也算出来
$interval = DateInterval::createFromDateString('1 month');
$period = CarbonPeriod::create($carbonStart->toDateTime(), $interval, $carbonEnd->toDateTime());
foreach ($period as $month) {
$start = $month->startOfMonth()->getTimestamp();
$end = $month->endOfMonth()->getTimestamp();
$perTimeInterval[] = [$start, $end];
}
//注意还要把当月也算出来
if (count($perTimeInterval) > 0 && end($perTimeInterval)[1] < $carbonEnd->timestamp) {
$perTimeInterval[] = [
end($perTimeInterval)[1] + 1,
$carbonEnd->timestamp,
];
}
}
return $perTimeInterval;
}
//根据时间区间获取统采购单信息
//不让数据库去帮我们做统计,而是全部拿出来自己算
protected static function getPurchaseOrders($purchaseUid, $timeInterval)
{
return PurchaseOrderModel::select([
'purchase_amount',
'gross_profit',
'currency',
'exchange_rate',
'purchase_name',
])->whereBetween('create_time', $timeInterval)
->where('purchase_uid', $purchaseUid)->whereIn('status', [
PurchaseOrderModel::OngoingStatus,
PurchaseOrderModel::CompleteStatus
])->get()->toArray();
}
//计算采购金额
private static function calculatePurchaseAmount($purchaseOrders)
{
$amountRMB = $amountUSD = $amountUSDToRMB = 0;
foreach ($purchaseOrders as $order) {
//要区分USD和RMB
if ($order['currency'] == self::CURRENCY_RMB) {
$amountRMB += $order['purchase_amount'];
} else {
$amountUSD += $order['purchase_amount'];
$amountUSDToRMB += $order['purchase_amount'] * $order['exchange_rate'];
}
}
return [
self::CURRENCY_RMB => round($amountRMB, 2),
self::CURRENCY_USD => round($amountUSD, 2),
self::CURRENCY_USD_TO_RMB => round($amountUSDToRMB, 2),
];
}
//计算毛利
private static function calculateGrossProfit($purchaseOrders)
{
$grossProfit = 0;
foreach ($purchaseOrders as $order) {
//如果是美金的,还要x汇率
$grossProfit += $order['gross_profit'];
}
return round($grossProfit, 2);
}
}
<?php
namespace App\Console\Commands;
use App\Http\Models\FlowLineModel;
use App\Http\Models\FlowModel;
use App\Http\Models\FlowNodeModel;
use App\Http\Models\Order\GoodsModel;
use App\Http\Models\OrderApproveModel;
use App\Http\Models\PurchaseContractModel;
use App\Http\Services\UserService;
use Illuminate\Console\Command;
class InitContractFileIdCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'command:init_contract_file_id';
/**
* The console command description.
*
* @var string
*/
protected $description = '初始化合同url到oss_file_id';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
echo date("Y-m-d H:i:s") . " start to init_contract_file_id." . "\n";
$PurchaseContractModel = new PurchaseContractModel;
$where = [
['contract_file_url', '<>', ''],
['oss_file_id', '=', '']
];
$contract_list = $PurchaseContractModel->where($where)->get()->toArray();
$img_url = 'http://files.ichunt.com/purchase/test/images/202203/18/74371cc711425fafd09c159caf121ea2.png';
$img_data = file_get_contents($img_url);
$tmp_file = "/var/tmp/" . date("Y_m_d_H_i_s");
file_put_contents($tmp_file, $img_data);
$url = Config('domain.frqapi_domain') . "/api/ApiQuoteList";
$data = [
'headers' => self::getFrqApiCommonHeaders(),
];
$http = new \GuzzleHttp\Client;
$response = $http->post($url, $data);
$stringBody = (string)$response->getBody();
$res_data = json_decode($stringBody, true);
var_dump($contract_list);
echo 111;exit;
echo date("Y-m-d H:i:s") . " finish to init_contractxxx_file_id. " . "\n";
}
}
<?php
namespace App\Console\Commands;
use App\Http\Models\PurchaseItemsModel;
use App\Http\Models\PurchaseOrderModel;
use Illuminate\Console\Command;
class OnceTaskCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'command:once:task';
/**
* The console command description.
*
* @var string
*/
protected $description = '临时一次性任务处理';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
//采购单付款方式为供应商赠送,则映射成预付款;
$list = PurchaseOrderModel::where("pay_id",4)->select("purchase_id")->get()->toArray();
foreach($list as $k=>$v){
$bk = PurchaseOrderModel::where("purchase_id",$v["purchase_id"])->update(["pay_id"=>1]);
dump($bk);
}
//采购单价为0,则采购明细中赠品字段勾选;否则,不勾选
$list = PurchaseItemsModel::where("price_in_tax",0)->where("is_gift",0)->select("purchase_id","purchase_item_id")->get()->toArray();
foreach($list as $k=>$v){
$bk = PurchaseItemsModel::where("purchase_id",$v["purchase_id"])->where("purchase_item_id",$v["purchase_item_id"])->update(["is_gift"=>1]);
dump($bk);
}
}
}
{
"name": "vendor_name/Commands",
"description": "description",
"minimum-stability": "stable",
"license": "proprietary",
"authors": [
{
"name": "HUNT",
"email": "email@example.com"
}
],
"require": {
}
}
<?php
namespace App\Console;
use App\Console\Commands\IndexStatistic;
use App\Console\Commands\OnceTaskCommand;
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 = [
//
IndexStatistic::class,
OnceTaskCommand::class,
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
// $schedule->command('inspire')->hourly();
}
/**
* Register the commands for the application.
*
* @return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
}
}
<?php
namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that are not reported.
*
* @var array
*/
protected $dontReport = [
//
];
/**
* A list of the inputs that are never flashed for validation exceptions.
*
* @var array
*/
protected $dontFlash = [
'password',
'password_confirmation',
];
/**
* Report or log an exception.
*
* @param \Throwable $exception
* @return void
*
* @throws \Throwable
*/
public function report(Throwable $exception)
{
parent::report($exception);
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Throwable $exception
* @return \Symfony\Component\HttpFoundation\Response
*
* @throws \Throwable
*/
public function render($request, Throwable $exception)
{
return parent::render($request, $exception);
}
}
<?php
namespace App\Exceptions;
use App\Http\ApiHelper\Response;
use Illuminate\Http\Request;
/*
* 系统内部错误
* 数据库错误
*
*/
class InternalException extends \Exception
{
public function __construct($message = "", $code = 200)
{
parent::__construct($message, $code);
}
public function render(Request $request)
{
return response()->json(json_decode(Response::setError($this->message), true));
}
}
<?php
namespace App\Exceptions;
use App\Http\ApiHelper\Response;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
/*
*无效请求异常
*/
class InvalidRequestException extends \Exception
{
public function __construct($message = "", $code = 200)
{
parent::__construct($message, $code);
}
public function render(Request $request)
{
$request_uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
$path_info = parse_url($request_uri);
$err_info = [
'domain' => isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '',
'interface' => isset($path_info) ? $path_info['path'] : '',
'user_agent' => isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '',
'ip' => request()->getClientIp(),
'time' => time(),
'other' => '',
'request_params' => $_REQUEST,
'msg' => $this->getMessage(),
"code" => $this->getCode(),
];
Log::error(json_encode($err_info, JSON_UNESCAPED_UNICODE));
return response()->json(json_decode(Response::setError($this->message), true));
}
}
<?php
namespace App\Http\ApiHelper;
interface ApiCode
{
const API_CODE_SUCCESS = 0;//接口请求正常
const API_CODE_ERROR = 1;//接口请求异常 可预测失败
const API_CODE_NEED_LOGIN = 101; //需要登录
const API_CODE_LOGIN_ERROR = 102; // 登录信息错误
const API_CODE_MOBILE_NOTFOUND_ERROR = 103; // 手机号不存在
const API_CODE_PASSWD_NOTFOUND_ERROR = 104; // 密码错误
const API_CODE_USER_DISABLE_ERROR = 105; // 账号被封禁
}
<?php
/**
* Created by PhpStorm.
* User: duwenjun
* Date: 2021/8/11
* Time: 2:52 PM
*/
namespace App\Http\ApiHelper;
class Response
{
public static function setError($errMsg, $errCode = ApiCode::API_CODE_ERROR, $data = [])
{
return json_encode(['code' => $errCode, 'msg' => $errMsg, 'data' => $data],
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
public static function setSuccess($data, $code = ApiCode::API_CODE_SUCCESS, $msg = "")
{
return json_encode(['code' => $code, 'msg' => $msg, 'data' => $data],
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
}
\ No newline at end of file
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
class BaseApiController extends Controller
{
}
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Http\Models\UploadFileModel;
use App\Http\Models\Order\OrderModel;
use App\Http\Models\PurchaseOrderModel;
use App\Http\Services\ScmOrderService;
use App\Http\Services\ScmOrderTemporaryService;
use App\Http\Services\Sync\DGKSyncService;
use App\Http\Services\UploadFileService;
use Illuminate\Http\Request;
class UploadFileApiController extends Controller
{
/**
* 新增申请单附件
* addPaymentFile
* @param Request $request
* @param $remark
* @param $fileType int
* @param $items
* @author tioncico
* Time: 3:26 下午
*/
public function addFile(Request $request)
{
$params = [
'remark' => $request->input("remark",""),
'fileType' => $request->input("fileType"),
'items' => $request->input("items"),
];
if (empty($params['items']) || !is_array($params['items'])) {
return $this->setError("文件数据必填!");
}
if (empty($params['fileType'])) {
return $this->setError("文件类型必填!");
}
$resultData = [];
foreach ($params['items'] as $item) {
$insertData = [
'fileName' => $item['fileName'],
'remark' => $params['remark'],
'fileType' => $params['fileType'],
'ossFileId' => $item['ossFileId'],
];
$id = UploadFileService::addFile($insertData);
$insertData['id'] = $id;
$resultData[] = $insertData;
}
return $this->setSuccessData(['uploadFileList' => $resultData]);
}
/**
* 删除文件
* deleteFile
* @param Request $request
* @param $fileId 文件id
* @author tioncico
* Time: 5:28 下午
*/
public function deleteFile(Request $request)
{
$fileId = $request->input('fileId');
if (empty($fileId)) {
return $this->setError("文件id必填!");
}
UploadFileModel::deleteFile($fileId);
return $this->setSuccess("删除成功");
}
}
<?php
namespace App\Http\Controllers;
use Facade\FlareClient\Api;
use Illuminate\Http\Request;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
use App\Http\ApiHelper\ApiCode;
use Illuminate\Support\Facades\Log;
class Controller extends BaseController implements ApiCode
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
public function user()
{
return request()->user;
}
public function setSuccessData($data = [], $count = 0, $code = ApiCode::API_CODE_SUCCESS, $msg = 'ok')
{
$res_data = [
"code" => $code,
"data" => $data,
];
if ($msg) {
$res_data['msg'] = $msg;
}
if ($count) {
$res_data['count'] = $count;
}
return response()->json($res_data);
}
public function setSuccess($msg = '操作成功', $code = ApiCode::API_CODE_SUCCESS, $data = [])
{
$res_data = [
"code" => $code,
"msg" => $msg,
'data' => (object)$data,
];
return response()->json($res_data);
}
public function setError($msg, $code = ApiCode::API_CODE_ERROR, $data = [])
{
$res_data = [
"code" => $code,
"msg" => $msg,
];
if ($data) {
$res_data['data'] = $data;
}
$this->logErr($msg, $code = ApiCode::API_CODE_ERROR, $data = null);
return response()->json($res_data);
}
private function logErr($msg, $code = ApiCode::API_CODE_ERROR, $data = null)
{
$request_uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
$path_info = parse_url($request_uri);
$err_info = [
'domain' => isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '',
'interface' => isset($path_info) ? $path_info['path'] : '',
'user_agent' => isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '',
'ip' => request()->getClientIp(),
'time' => time(),
'other' => '',
'request_params' => $_REQUEST,
'msg' => $msg,
"code" => $code,
"data" => $data
];
Log::error(json_encode($err_info, JSON_UNESCAPED_UNICODE));
}
}
<?php
namespace App\Http\Controllers\Sync;
use App\Http\Controllers\Controller;
class BaseSyncController extends Controller
{
public function startTransaction(){
\DB::connection("mysql")->beginTransaction();
}
public function commitTransaction(){
\DB::connection("mysql")->commit();
}
public function rollBackTransaction(){
\DB::connection("mysql")->rollBack();
}
}
<?php
namespace App\Http\Controllers\Sync;
use App\Exports\DgkOrderExport;
use App\Http\Caches\RateCache;
use App\Http\Models\EndCustInfoModel;
use App\Http\Models\PayableItemsModel;
use App\Http\Models\PaymentItemsModel;
use App\Http\Models\PurchaseContractModel;
use App\Http\Models\PurchaseItemsModel;
use App\Http\Models\PurchaseOrderModel;
use App\Http\Models\StockInItemModel;
use App\Http\Services\ActionLogService;
use App\Http\Services\FrqService;
use App\Http\Services\PurOrderItemService;
use App\Http\Services\PurOrderService;
use App\Http\Services\SupplierDeliveryService;
use App\Http\Services\Sync\CrmService;
use App\Http\Services\Sync\DGKSyncService;
use App\Http\Services\Sync\PurchaseOrderSyncService;
use App\Http\Services\Sync\StockInSyncService;
use App\Http\Services\ThirdExportService;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;
class TestController extends BaseSyncController
{
public function index()
{
$NUM = decimal_number_format("1200000.4555",DIGITS_SIX);
dd($NUM);
}
}
<?php
namespace App\Http\IdSender;
use App\Exceptions\InvalidRequestException;
use App\Http\Models\CmsUserInfoModel;
use App\Http\Models\PurchaseContractModel;
use App\Http\Models\SnConfigModel;
class IdSender
{
const TYPE_ORDER = 'order_order'; // 销售系统-销售订单
const TYPE_ORDER_SERVICE = 'order_order_service'; // 销售系统-售后单
const TYPE_PURCHASE_PLAN = 'pur_purchase_plan'; // 采购系统-采购计划单
const TYPE_PURCHASE = 'pur_purchase'; // 采购系统-采购单
const TYPE_PAYMENT = 'pur_payment'; // 采购系统-付款申请单
const TYPE_STOCK_IN = 'pur_stock_in'; // 采购系统-入库单&发货通知单
const TYPE_PAYABLE = 'pur_payable'; // 采购系统-应付单
const TYPE_SCM_ORDER = 'pur_scm_order'; // 采购系统-委托单
const TYPE_RETURN = 'pur_return_material'; // 采购系统-退货单
const TYPE_CONTRACT = 'pur_contract'; // 采购系统-合同单号
const TYPE_ORG_ICHUNT = 1; // 采购组织-深圳市猎芯科技有限公司
const TYPE_ORG_SHENMAO = 2; // 采购组织-深贸电子有限公司
const TYPE_LANG_CN = 1; // 合同语言类型 中文
const TYPE_LANG_EN = 2; // 合同语言类型 英文
// 统一sn生成器,生成sn
public static function getSn($type = self::TYPE_PURCHASE, $org = self::TYPE_ORG_ICHUNT)
{
$sn = '';
switch ($type) {
case self::TYPE_PURCHASE:
case self::TYPE_ORDER:
$sn = self::getSnWithUserName($type, $org);
break;
case self::TYPE_PURCHASE_PLAN:
case self::TYPE_PAYMENT:
case self::TYPE_STOCK_IN:
case self::TYPE_PAYABLE:
case self::TYPE_SCM_ORDER:
case self::TYPE_RETURN:
$sn = self::getCommonSn($type, $org);
break;
default:
}
return $sn;
}
// 生成合同单号
public static function getContractSn($orderInfo, $langType = self::TYPE_LANG_CN)
{
return $orderInfo['purchase_sn'] . "_" . self::getLangTypeVal($langType) . self::countContractNum($orderInfo['purchase_id']);
}
// 获取公共sn
private static function getCommonSn($type, $org)
{
$sn_config = self::getSnConfig($type);
return $sn_config["prefix"] . "-" . self::getOrgCode($org) . self::getDate() . self::getFilledId($sn_config);
}
// 获取合同编号语言类型
private static function getLangTypeVal($lang_type)
{
return ($lang_type == self::TYPE_LANG_CN) ? "A" : "B";
}
// 获取带用户名sn
private static function getSnWithUserName($type, $org)
{
$sn_config = self::getSnConfig($type);
$user = request()->user;
if (empty($user)) {
throw new InvalidRequestException("用户未登录,创建采购sn需要用户名.");
}
$user_info = CmsUserInfoModel::getUserInfoById($user->userId);
return $sn_config["prefix"] . "-" . $user_info['code_sn'] . "-" . self::getOrgCode($org) . self::getDate() . self::getFilledId($sn_config);
}
// 采购组织
private static function getOrgCode($org_type = self::TYPE_ORG_ICHUNT)
{
$org_code = '';
if ($org_type == self::TYPE_ORG_ICHUNT) {
$org_code = "SZ";
}
if ($org_type == self::TYPE_ORG_SHENMAO) {
$org_code = "HK";
}
return $org_code;
}
// 当前日期
private static function getDate()
{
return date("Ymd");
}
// 当日流水号id
private static function getFilledId($sn_config)
{
$current_date = date("Y-m-d");
if ($sn_config['current_date'] != $current_date) {
$sn_config['number_next'] = 1;
}
if (strlen($sn_config['number_next']) > $sn_config['padding']) {
$filled_id = $sn_config['number_next'];
} else {
$filled_id = str_pad($sn_config['number_next'], $sn_config['padding'], "0", STR_PAD_LEFT);
}
// 更新next_id
$update_sn_config = [
"current_date" => $current_date,
"number_next" => (int)($sn_config['number_next'] + $sn_config['number_increment'])
];
SnConfigModel::updateById($update_sn_config, $sn_config['id']);
return $filled_id;
}
// 获取sn配置信息
private static function getSnConfig($type)
{
$sn_config = SnConfigModel::getSnConfigByCode($type);
if (empty($sn_config)) {
throw new InvalidRequestException("sn_config is not config.");
}
return $sn_config;
}
/**
* 统计合同数量
* countContractNum
* @param $purchaseId
* @author tioncico
* Time: 1:51 下午
*/
private static function countContractNum($purchaseId)
{
$num = PurchaseContractModel::countCNContractByPurchaseId($purchaseId);
$num += 1;
$snCode = $num;
if ($num < 10) {
$snCode = str_pad($num, 2, "0", STR_PAD_LEFT);
}
return $snCode;
}
}
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
use Illuminate\Foundation\Http\Middleware\TrimStrings;
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 = [
// \App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\XhProf::class, // 接口性能分析中间件
\App\Http\Middleware\TrustProxies::class,
\Fruitcake\Cors\HandleCors::class,
\App\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
// \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\App\Http\Middleware\Monitor::class
];
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\WebAuthenticate::class,
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\App\Http\Middleware\Permission::class,
],
'api' => [
// 'throttle:60,1',
\App\Http\Middleware\ApiAuthenticate::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\App\Http\Middleware\TrimStrings::class,
\App\Http\Middleware\Permission::class,
],
'sync' => [
],
];
/**
* 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,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
// 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'monitor' => \App\Http\Middleware\Monitor::class,
];
}
<?php
namespace App\Http\Middleware;
use App\Http\ApiHelper\Response;
use Illuminate\Support\Facades\Config;
use Closure;
use Illuminate\Support\Facades\Log;
class ApiAuthenticate
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$source = $request->header("source"); //来源端:内部后台:pc 云芯系统:yunxin App: app 小程序:h5_app
$userId = $skey = null;
if ($source == 'pc') {
$userId = $request->header('oa-user-id');
$skey = $request->header('oa-skey');
} else {
if ($request->cookie()) {
$userId = $request->cookie('oa_user_id');
$skey = $request->cookie('oa_skey');
}
}
if (empty($userId) || empty($skey)) {
return $this->redirectTo($request);
}
$login = config::get('website.login');
if (!$userId || !$skey || (string)((int)$userId) != $userId || !preg_match('/^[a-zA-Z0-9]+$/', $skey)) {
return $this->redirectTo($request);
}
$cookie = 'oa_user_id=' . $userId . '; oa_skey=' . $skey;
$client = new \GuzzleHttp\Client();
$rsp = $client->request('GET', $login['check'], [
'headers' => ['Cookie' => $cookie],
'connect_timeout' => 5,
'timeout' => 10,
'verify' => false,
]);
if ($rsp->getStatusCode() != 200) {
Log::error("login error");
abort(500);
}
$ret = json_decode($rsp->getBody());
if ($ret->retcode != 0) {
return $this->redirectTo($request);
}
$user = $ret->data;
$user->header = $request->cookie('oa_header');
$request->user = $user;
$request->attributes->add(['user' => $user]);
if (empty($user)) {
return $this->redirectTo($request);
}
return $next($request);
}
protected function redirectTo($request)
{
return Response::setError("need login..");
}
}
<?php
namespace App\Http\Middleware;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
class Authenticate extends Middleware
{
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* @param \Illuminate\Http\Request $request
* @return string|null
*/
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('login');
}
}
}
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode as Middleware;
class CheckForMaintenanceMode extends Middleware
{
/**
* The URIs that should be reachable while maintenance mode is enabled.
*
* @var array
*/
protected $except = [
//
];
}
<?php
namespace App\Http\Middleware;
use Illuminate\Cookie\Middleware\EncryptCookies as Middleware;
class EncryptCookies extends Middleware
{
/**
* The names of the cookies that should not be encrypted.
*
* @var array
*/
protected $except = [
//
];
}
<?php
namespace App\Http\Middleware;
use Error;
use Closure;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Contracts\Container\Container;
use Illuminate\Contracts\Debug\ExceptionHandler;
use Psy\Exception\ErrorException;
use Psy\Exception\FatalErrorException;
class Monitor
{
/**
* The App container
*
* @var Container
*/
protected $container;
/**
* The Monitor Client
*
* @var
*/
protected $monitor;
/**
* Create a new middleware instance.
*
* @param Container $container
*/
public function __construct(Container $container)
{
$this->container = $container;
}
/**
* Handle an incoming request.
*
* @param Request $request
* @param Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
// dump("monitorDing");
$enabled = config('monitorDing.enabled');
try {
$response = $next($request);
} catch (Exception $e) {
$response = $this->handleException($request, $e);
$enabled && $this->sendText(sprintf("文件:%s (%s 行) 内容:%s", $e->getFile(), $e->getLine(), $e->getMessage()));
} catch (Error $error) {
$e = new FatalErrorException($error);
$response = $this->handleException($request, $e);
$enabled && $this->sendText(sprintf("文件:%s (%s 行) 内容:%s", $e->getFile(), $e->getLine(), $e->getMessage()));
} catch (ErrorException $error) {
$e = new FatalErrorException($error);
$response = $this->handleException($request, $e);
$enabled && $this->sendText(sprintf("文件:%s (%s 行) 内容:%s", $e->getFile(), $e->getLine(), $e->getMessage()));
} finally {
if ($response->getStatusCode() == '500' && (isset($response->exception) && $response->exception && $response->exception !== null)) {
$sysName = config('monitorDing.web_name');
if (strpos($_SERVER['HTTP_HOST'], 'liexin') !== false) {
$sysName = '本地' . $sysName;
} else {
$sysName = '外网' . $sysName;
}
$this->sendText(substr($sysName . ":" . $response->exception, 0,
500) . ',请求数据:' . json_encode($request->input()) . "---[更多详情请看日志]");
}
}
return $response;
}
/**
* Handle the given exception.
*
* (Copy from Illuminate\Routing\Pipeline by Taylor Otwell)
*
* @param $passable
* @param Exception $e
* @return mixed
* @throws Exception
*/
protected function handleException($passable, Exception $e)
{
if (!$this->container->bound(ExceptionHandler::class) || !$passable instanceof Request) {
throw $e;
}
$handler = $this->container->make(ExceptionHandler::class);
$handler->report($e);
return $handler->render($passable, $e);
}
/**
* 发送文本类型的消息
*
* @param $content string 消息内容
* @param array $atMobiles 被@人的手机号
* @param bool $isAtAll 是否 @ 所有人
* @throws SendErrorException
*/
public function sendText($content, $atMobiles = [], $isAtAll = false)
{
$params = [
'msgtype' => 'text',
'text' => [
'content' => $content,
],
'at' => [
'atMobiles' => $atMobiles,
'isAtAll' => $isAtAll
]
];
$this->send($params);
}
/**
* 发送
* @param array $params 请求需要的参数
* @throws SendErrorException
*/
private function send($params = [])
{
if (!config('monitorDing.enabled')) {
\Log::info('~~ Monitor Ding ~~');
\Log::info($params);
} else {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, config("monitorDing.webhook"));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json;charset=utf-8'));
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if (config()) {
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
}
$data = json_decode(curl_exec($ch), true);
curl_close($ch);
if ($data['errcode']) {
// throw new SendErrorException($data['errmsg']);
}
}
}
}
<?php
namespace App\Http\Middleware;
use App\Http\ApiHelper\Response;
use App\Http\Services\PermService;
use Closure;
class Permission
{
public function handle($request, Closure $next)
{
// 如果是admin账号,那么跳过检验权限
$user = request()->user;
$userId = $user->userId;
$email = $user->email;
$roles = PermService::getUserRoles($userId, $email);
if (PermService::hasRole(PermService::ROLE_ADMIN, $roles)) {
return $next($request);
}
$url = $request->url();
$url_info = parse_url($url);
if (isset($url_info['path'])) {
$path_arr = explode("/", $url_info['path']);
$path_arr = array_filter($path_arr);
$path_arr = array_values($path_arr);
$perm_id = implode("_", $path_arr);
$res = PermService::hasPerm($perm_id);
if (!$res) {
if ($path_arr && isset($path_arr[0]) && ($path_arr[0] == 'api')) {
return Response::setError("没有访问权限");
} else {
return response("没有访问权限");
}
}
}
return $next($request);
}
}
<?php
namespace App\Http\Middleware;
use App\Providers\RouteServiceProvider;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect(RouteServiceProvider::HOME);
}
return $next($request);
}
}
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\TrimStrings as Middleware;
class TrimStrings extends Middleware
{
/**
* The names of the attributes that should not be trimmed.
*
* @var array
*/
protected $except = [
'password',
'password_confirmation',
];
}
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Middleware\TrustHosts as Middleware;
class TrustHosts extends Middleware
{
/**
* Get the host patterns that should be trusted.
*
* @return array
*/
public function hosts()
{
return [
$this->allSubdomainsOfApplicationUrl(),
];
}
}
<?php
namespace App\Http\Middleware;
use Fideloper\Proxy\TrustProxies as Middleware;
use Illuminate\Http\Request;
class TrustProxies extends Middleware
{
/**
* The trusted proxies for this application.
*
* @var array|string|null
*/
protected $proxies;
/**
* The headers that should be used to detect proxies.
*
* @var int
*/
protected $headers = Request::HEADER_X_FORWARDED_ALL;
}
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
class VerifyCsrfToken extends Middleware
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = [
//
];
}
<?php
namespace App\Http\Middleware;
use Illuminate\Support\Facades\Config;
use Closure;
use Illuminate\Support\Facades\Log;
class WebAuthenticate
{
/**
* 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');
$login = Config::get('website.login');
if (!$userId || !$skey || (string)((int)$userId) != $userId || !preg_match('/^[a-zA-Z0-9]+$/', $skey)) {
return $this->redirectTo($request);
}
$cookie = 'oa_user_id=' . $userId . '; oa_skey=' . $skey;
$client = new \GuzzleHttp\Client();
$rsp = $client->request('GET', $login['check'], [
'headers' => ['Cookie' => $cookie],
'connect_timeout' => 5,
'timeout' => 10,
'verify' => false,
]);
if ($rsp->getStatusCode() != 200) {
Log::error("login error");
abort(500);
}
$ret = json_decode($rsp->getBody());
if ($ret->retcode != 0) {
return $this->redirectTo($request);
}
$user = $ret->data;
$user->header = $request->cookie('oa_header');
$request->user = $user;
$request->attributes->add(['user' => $user]);
return $next($request);
}
protected function redirectTo($request)
{
$login = Config::get('website.login');
if (! $request->expectsJson()) {
return redirect($login['login'] . '?redirect=' . urlencode($request->url()));
}
}
}
<?php
namespace App\Http\Middleware;
use Closure;
class XhProf
{
public function handle($request, Closure $next)
{
$app_config = get_resource_config_section('app', 'pur');
$open_xhprof = isset($app_config['open_xhprof']) ? $app_config['open_xhprof'] : 0;
if ($open_xhprof && function_exists('xhprof_enable')) {
list($usec, $sec) = explode(" ", microtime());
$startTime = (float)$sec + (float)$usec; // 程序开始时间
xhprof_enable(XHPROF_FLAGS_NO_BUILTINS | XHPROF_FLAGS_CPU | XHPROF_FLAGS_MEMORY, []);
$response = $next($request);
if (function_exists('xhprof_disable')) {
list($usec, $sec) = explode(" ", microtime());
$endTime = (float)$sec + (float)$usec;
$data = xhprof_disable();
$excl_wall_time = isset($app_config['xhprof_excl_wall_time']) ? $app_config['xhprof_excl_wall_time'] : 0.5;
if (($endTime - $startTime) > $excl_wall_time) {
file_put_contents(sys_get_temp_dir() . DIRECTORY_SEPARATOR . uniqid() . ".pur" . str_replace('/',
"-", $request->path()) . '.xhprof', serialize($data));
}
}
return $response;
} else {
return $next($request);
}
}
}
<?php
namespace App\Http\Models;
use App\Http\Caches\TableFieldCache;
use App\Http\Services\PermService;
use Carbon\CarbonInterface;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Date;
use DateTimeInterface;
class BaseModel extends Model
{
/*
* 过滤字段
* insert插入多条数据的时候可以使用
*/
public function filterField($data){
if(isMultipleArray($data)){
//多维数组
foreach($data as $k1=>$v1){
if(!is_array($v1)) break;
foreach($data as $k2=>$v2){
if(!in_array($k2,$this->getTableFields())){
unset($data[$k1][$k2]);
}
}
}
}else{
foreach($data as $k1=>$v1){
if(!in_array($k1,$this->getTableFields())){
unset($data[$k1]);
}
}
}
return $data;
}
/*
* 获取数据库表的字段
* @return array
* @param string
*/
public function getTableFields($tableName=""){
$tableFieldCache = new TableFieldCache("frq");
$tableName = $tableName ? $tableName : $this->table;
$oldFields = $tableFieldCache->getTableFieldsCache($tableName);
if(!$oldFields){
$tableFields = \Illuminate\Support\Facades\Schema::getColumnListing($tableName);
//此处考虑缓存数据库字段
$tableFieldCache->setTableFieldsCache($tableName,json_encode($tableFields));
}else{
$tableFields = json_decode($oldFields,true);
}
return $tableFields;
}
/*
*过滤不要的字段
*/
public function scopeExceptField($query,$fields=[]){
$tableFields = $this->getTableFields();
$fields = array_diff($tableFields,$fields);
$query->select($fields);
return $query;
}
/*
* where("aaaa","=","123")
* 构建查询语句
* 等于 =
*/
public function scopeBuildEqualQuery($query,$array=[]){
$tableFields = $this->getTableFields();
foreach($array as $field=>$value){
if(!in_array($field,$tableFields) || empty($value) ){
continue;
}
$query->where($field,"=",$value);
}
return $query;
}
/*
* whereIn("status",[1,2,3])
* 构建查询语句
* in
*/
public function scopeBuildWhereInQuery($query,$array=[]){
$tableFields = $this->getTableFields();
foreach($array as $field=>$value){
if(!in_array($field,$tableFields) || empty($array) ){
continue;
}
$query->whereIn($field,$value);
}
return $query;
}
/*
* 左匹配
* where("a","like","a%")
*/
public function scopeBuildLeftLikeQuery($query,$array=[]){
$tableFields = $this->getTableFields();
foreach($array as $field=>$value){
if(!in_array($field,$tableFields) || empty($value)){
continue;
}
$query->where($field,"like",trim($value).'%');
}
return $query;
}
/*
* 打印sql语句
*/
public function echoSql($query){
$tmp = str_replace('?', '"'.'%s'.'"', $query->toSql());
$tmp = vsprintf($tmp, $query->getBindings());
dd($tmp);
}
/*
* 时间查询
* 构建单个时间查询
*/
public function scopeSearchByTime($query,$field="",$begin_time='',$end_time=''){
if (!$begin_time && !$end_time) return $query;
$begin_time = $begin_time ? strtotime($begin_time." 00:00:00") : 0;
$end_time = $end_time ? strtotime($end_time." 23:59:59") : 0;
if($begin_time){
if($end_time){
$query = $query->where($field,">=",$begin_time)->where($field,"<=",$end_time);
}else{
$query = $query->where($field,">=",$begin_time);
}
}elseif($end_time){
$query = $query->where($field,"<=",$end_time);
}
return $query;
}
/*
* 构建时间查询语句
* 构建都条记录查询
* $timeArray["create_time"] = ["begin_time"=>"2021-11-01","end_time"=>"2021-11-01"]
* $timeArray["pur_time"] = ["begin_time"=>"2021-11-01","end_time"=>"2021-11-01"]
*/
public function scopeBuildTimeQuery($query,$timeArray=[]){
$tableFields = $this->getTableFields();
foreach($timeArray as $field=>$timeList){
if(!in_array($field,$tableFields)) continue;
$begin_time = $timeList["begin_time"];
$end_time = $timeList["end_time"];
if (!$begin_time && !$end_time){
continue;
}
$begin_time = $begin_time ? strtotime($begin_time." 00:00:00") : 0;
$end_time = $end_time ? strtotime($end_time." 23:59:59") : 0;
if($begin_time){
if($end_time){
$query = $query->where($field,">=",$begin_time)->where($field,"<=",$end_time);
}else{
$query = $query->where($field,">=",$begin_time);
}
}elseif($end_time){
$query = $query->where($field,"<=",$end_time);
}
}
return $query;
}
/*
* 获取数据
*/
public function scopeGetList($query,$page,$limit){
return $query->paginate($limit,[],'page',$page);
}
/*
* 权限
*/
public function scopeRule($query,$viewList){
// //获取用户部门下的所有用户
// $userIds = PermService::getSubUserId(getAdminUserId());
//// dd($userIds);
//
//
// //获取用户角色
// $a = PermService::getUserRoles(1642);
//// dd($a);
//
//
// //获取登录用户的所有权限
// $c = PermService::getUserPerms(1642);
//// dd($c);
//
// //判断登录用户是否拥有某个固定权限
// $d = PermService::hasPerm("frq_viewsub_list");
// dd($d);
if(!request()->user){
return $query;
}
//查看所有
if(PermService::hasPerm($viewList[0])){
return $query;
}
//查看下级
if(PermService::hasPerm($viewList[1])){//查看下级的权限//获取用户部门下的所有用户
$userIds = PermService::getSubUserId(getAdminUserId());
if(!empty($userIds)){
return $query->whereIn("purchase_uid",$userIds);
}
}
$query = $query->where("purchase_uid",getAdminUserId());
return $query;
}
public static function checkRule($query,$viewList){
if(PermService::hasPerm($viewList[0])){
return $query;
}
//查看下级
if(PermService::hasPerm($viewList[1])){//查看下级的权限//获取用户部门下的所有用户
$userIds = PermService::getSubUserId(getAdminUserId());
if(!empty($userIds)){
// $query->where(function($q){
// $q->whereIn("purchase_uid",$userIds)->orWhere("cid",1);
// })
return $query->whereIn("purchase_uid",$userIds);
}
}
$query = $query->where("purchase_uid",getAdminUserId());
return $query;
}
/**
* Notes:修改数据
* User: sl
* Date: 2022/5/25 11:32
* @param $where
* @param $updateData
* @return mixed
* buildSimpleQueryByUpdate([["a",1],["b",2],["or",[["k","<>","y"],["p","<",2]]],["c",">",4],["d","in",[1,2,3,4]]],["goods_sn"=>'IC-0000056'])
*/
public static function buildSimpleQueryByUpdate($where,$updateData){
$query = self::query();
$query = buildQuery($query,$where);
// echoToSql($query);
return $query->update($updateData);
}
}
<?php
namespace App\Http\Queue;
use Monolog\Formatter\LineFormatter;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
class RabbitQueueModel
{
private $connection;
const DEFAULT_QUEUE = 'lie_queue_pur';
const QUEUE_DGK_SYNC_ORDER = 'lie_queue_dgk_sync_order';
const QUEUE_ORDER = 'lie_queue_order';
const QUEUE_ERP = 'lie_queue_erp';
const FORWARD_TYPE_HTTP = "http";
const FORWARD_TYPE_SOAP = "soap";
public function __construct(string $connect_name = '')
{
if ($connect_name) {
$config = Config('rabbitmq.connections.' . $connect_name);
} else {
$default_connect_name = Config('rabbitmq.default');
$config = Config('rabbitmq.connections.' . $default_connect_name);
}
try {
// 创建rabbitmq链接
$this->connection = new AMQPStreamConnection(
$config['host'], $config['port'], $config['login'], $config['password'], $config['vhost']
);
} catch (\Exception $e) {
$this->connection = null;
$err_json = json_encode([
'message' => $e->getMessage(),
'file' => $e->getFile(),
'line' => $e->getLine(),
'code' => $e->getCode()
]);
(new Logger('queue'))->pushHandler(new StreamHandler(storage_path('logs/queue.log')))->info($err_json);
}
}
// 队列推送
public function insertQueue(
$route_key,
$queue_data,
$queue_name = self::DEFAULT_QUEUE,
$forward_type = self::FORWARD_TYPE_HTTP
) {
try {
$queue_message = [];
$queue_message["__route_key"] = $route_key;
$queue_message['__insert_time'] = time();
$queue_message['__from'] = $this->getFromUrl() ? $this->getFromUrl() : gethostname();
$queue_message['__uk'] = (string)self::_calc_uniqid($queue_message);
$queue_message['__type'] = $forward_type;
$queue_message['__search_key'] = isset($queue_data['__search_key']) ? $queue_data['__search_key'] : $route_key;
$queue_message['__trace_id'] = '';
$queue_message['data'] = $queue_data;
if ($this->connection) {
$message = new AMQPMessage(json_encode($queue_message, JSON_UNESCAPED_UNICODE));
$channel = $this->connection->channel();
$channel->queue_declare($queue_name, false, true, false, false);
$channel->basic_publish($message, '', $queue_name); // 推送消息
$channel->close();
$this->log("queue_insert", $queue_message, $queue_name);
} else {
throw new \Exception("rabbit connection is faild");
}
} catch (\Exception $e) {
$this->log("queue_insert_error", $queue_message, $queue_name);
return false;
}
return true;
}
public function getConnection()
{
return $this->connection;
}
private function getFromUrl()
{
$domain = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '';
$request_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
$from_url = '';
if ($domain && $request_url) {
$from_url = $domain . $request_url;
}
return $from_url;
}
private function _calc_uniqid($params)
{
return crc32(json_encode($params) . time());
}
private function log($sign, $queue_message, $queue_name = '')
{
$user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
$log_message = $sign . "|##data:" . json_encode(['queue_name' => $queue_name, 'mq_data' => $queue_message]) . ",##" . $user_agent;
$dateFormat = "Y-m-d H:i:s";
// 最后创建一个格式化器
$formatter = new LineFormatter(null, $dateFormat);
$stream = new StreamHandler(storage_path('logs/queue.log'));
$stream->setFormatter($formatter);
(new Logger('queue'))->pushHandler($stream)->info($log_message);
}
public function __destruct()
{
if ($this->connection) {
$this->connection->close();
}
}
}
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;
class BaseRequest extends FormRequest
{
protected function failedValidation(Validator $validator)
{
$error = $validator->errors()->all();
\Log::channel("formRequest")->info(
sprintf(
"错误:请求参数 %s,错误原因:%s",
print_r(request()->all(),true),
json_encode($error,JSON_UNESCAPED_UNICODE)
)
);
throw new HttpResponseException(response()->json(['code' => 1, 'msg' => $error[0]]));
}
public function authorize()
{
return true;
}
public function validated()
{
return $this->validator->validated();
}
public function __get($key)
{
if ($key == 'user') {
return request()->get('user');
}
if ($key == 'perms') {
return request()->get('perms');
}
}
}
<?php
namespace App\Http\Requests;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Monolog\Logger;
use Illuminate\Validation\Rule;
/*
* 添加采购需求单
*/
class PurFrqSyncAddFrq extends BaseRequest
{
public function __construct()
{
parent::__construct();
\Log::channel("purFrqSyncLog")->info(json_encode(request()->all(),JSON_UNESCAPED_UNICODE));
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
$rules = [
"list.*.frq_type"=>["required",'integer',Rule::in(['1', '2'])],
];
//1:已销定购 新增
$addRulesByS = [
"list.*.goods_id"=>"required|integer",
"list.*.goods_sn"=>"required",
"list.*.goods_name"=>"required",
"list.*.brand_id"=>"required|integer",
"list.*.brand_name"=>"required",
// "list.*.supplier_id"=>"required|integer",
// "list.*.supplier_name"=>"required",
// "list.*.supp_brand_name"=>"sometimes|required",
// "list.*.supp_goods_sn"=>"sometimes|required",
"list.*.exchange_rate"=>"required",
"list.*.sales_price"=>"required",
"list.*.sales_without_tax_price"=>"required",
"list.*.tax_rate"=>"required",
"list.*.order_item_id"=>"required|integer",
"list.*.sales_currency"=>"required",
"list.*.goods_unit"=>"required",
"list.*.seller_uid"=>"required|integer",
"list.*.seller_name"=>"required",
"list.*.purchase_uid"=>"required|integer",
"list.*.purchase_name"=>"required",
"list.*.source_sn"=>"required",
"list.*.create_uid"=>"required",
"list.*.create_name"=>"required",
"list.*.erp_order_id"=>"required",
"list.*.erp_rec_id"=>"required",
];
//2:计划备货 新增
$addRulesByP = [
"list.*.goods_id"=>"required|integer",
"list.*.goods_sn"=>"required",
"list.*.goods_name"=>"required",
"list.*.brand_id"=>"required|integer",
"list.*.brand_name"=>"required",
// "list.*.supplier_id"=>"required|integer",
// "list.*.supplier_name"=>"required",
// "list.*.supp_brand_name"=>"sometimes|required",
// "list.*.supp_goods_sn"=>"sometimes|required",
"list.*.exchange_rate"=>"required",
"list.*.currency"=>"required",
"list.*.frq_price_unit"=>"required",
"list.*.tax_rate"=>"required",
"list.*.purchase_plan_id"=>"required|integer",
"list.*.goods_unit"=>"required",
"list.*.purchase_uid"=>"required|integer",
"list.*.purchase_name"=>"required",
"list.*.source_sn"=>"required",
"list.*.create_uid"=>"required",
"list.*.create_name"=>"required",
];
$frq_type = request()->input("list.0.frq_type",0);
switch (request()->path()){
case "sync/addFrq" ://添加 新增
switch($frq_type){
case "1"://1:已销定购
$rules = $addRulesByS;
break;
case "2" ://采购备货计划
$rules = $addRulesByP;
break;
}
break;
case "sync/updateFrq" ://修改
break;
default:
}
return $rules;
}
/**
* 获取已定义验证规则的错误消息
*
* @return array
*/
public function messages()
{
return [];
}
/**
* 获取验证错误的自定义属性
*
* @return array
*/
public function attributes()
{
return [
"list.*.goods_id"=>"商品ID",
"list.*.goods_sn"=>"商品编码",
"list.*.goods_name"=>"商品型号",
"list.*.brand_id"=>"品牌ID",
"list.*.brand_name"=>"品牌名称",
"list.*.supplier_id"=>"供应商ID",
"list.*.supplier_name"=>"供应商名称",
"list.*.supp_brand_name"=>"供应商物料品牌",
"list.*.supp_goods_sn"=>"供应商商品唯一编码",
"list.*.exchange_rate"=>"汇率(当前汇率)",
"list.*.sales_price"=>"销售单价(含税)",
"list.*.sales_without_tax_price"=>"销售单价(未税)",
"list.*.order_item_id"=>"销售单商品明细id",
"list.*.sales_currency"=>"销售币种,1:人民币,2:美金",
"list.*.goods_unit"=>"商品单位",
"list.*.frq_type"=>"需求类型 1:以销定购,2:计划备货",
"list.*.seller_uid"=>"销售员ID",
"list.*.seller_name"=>"销售员名字",
"list.*.purchase_uid"=>"采购员UID",
"list.*.purchase_name"=>"采购员名字",
"list.*.source_sn"=>"来源单号(销售单号或采购计划申请单号)",
"list.*.currency"=>"采购需求申请币别",
"list.*.frq_price_unit"=>"采购计划申请单价(未税)",
"list.*.tax_rate"=>"税率",
"list.*.purchase_plan_id"=>"采购计划ID",
"list.*.create_uid"=>"创建人id",
"list.*.create_name"=>"创建人名称",
"list.*.erp_order_id"=>"ERP订单绑定ID",
"list.*.erp_rec_id"=>"ERP订单明细ID",
];
}
/*
* 验证钩子
*/
public function withValidator($validator)
{
// $validator->after(function ($validator) {
//// $validator->errors()->add('xx00', 'Something is wrong with this field!');
// });
}
protected function prepareForValidation()
{
}
/*
* 添加额外数据到需要验证的数据中心validatorData中
*/
protected function passedValidation()
{
// $frq_type = request()->input("0.frq_type",0);
// switch($frq_type){
// case "1"://1:已销定购
// $create_uid = intval($this->input("0.seller_uid",0));
// $create_name = $this->input("0.seller_name","");
// break;
// case "2" ://采购备货计划
// $create_uid = intval($this->input("0.purchase_uid",0));
// $create_name = $this->input("0.purchase_name","");
// break;
// }
//
//
// $data = $this->getInputSource()->all();
// data_fill($data,"list.*create_uid",$create_uid);
// data_fill($data,"list.*create_name",$create_name);
$this->merge([]);
}
}
<?php
namespace App\Http\Requests;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Monolog\Logger;
use Illuminate\Validation\Rule;
/*
* 添加采购需求单
*/
class PurOrderAdd extends BaseRequest
{
public function __construct()
{
parent::__construct();
// \Log::channel("purFrqSyncLog")->info(\GuzzleHttp\json_encode(request()->all(),JSON_UNESCAPED_UNICODE));
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
$rules = [
"company_id"=>["required",'integer',Rule::in(['1', '2'])],
"supplier_id"=>["required",'integer'],
"pay_id"=>["required",'integer',Rule::in(['1', '2',"3","4"])],
];
return $rules;
}
/**
* 获取已定义验证规则的错误消息
*
* @return array
*/
public function messages()
{
return [];
}
/**
* 获取验证错误的自定义属性
*
* @return array
*/
public function attributes()
{
return [
"company_id"=>"采购组织",
"supplier_id"=>"供应商",
"pay_id"=>"付款方式",
"first_pay_type"=>"首款类型",
"first_pay_amount"=>"首款金额",
"supp_pay_days"=>"账期天数",
];
}
/*
* 验证钩子
*/
public function withValidator($validator)
{
$validator->after(function ($validator) {
$pay_id = request()->input("pay_id",0);//币别,1:人民币,2:美金
$first_pay_type = request()->input("first_pay_type",0);//首款类型 1比率 2金额
$first_pay_amount = request()->input("first_pay_amount",0);
$supp_pay_days = request()->input("supp_pay_days",0);
if($pay_id == "1"){//预付款
if(!in_array($first_pay_type,[1,2])){
$validator->errors()->add('first_pay_type', '预付款方式下必须选择首款类型');
}
if(!$first_pay_amount){
$validator->errors()->add('first_pay_amount', '预付款方式下必须填写首款金额或首款比率值');
}
}elseif($pay_id == "2"){
if(intval($supp_pay_days) <= 0){
$validator->errors()->add('supp_pay_days', '账期方式下必须填写账期天数');
}
}
});
}
protected function prepareForValidation()
{
}
/*
* 添加额外数据到需要验证的数据中心validatorData中
*/
protected function passedValidation()
{
$pay_id = request()->input("pay_id",0);
// switch($frq_type){
// case "1"://1:已销定购
// $create_uid = intval($this->input("0.seller_uid",0));
// $create_name = $this->input("0.seller_name","");
// break;
// case "2" ://采购备货计划
// $create_uid = intval($this->input("0.purchase_uid",0));
// $create_name = $this->input("0.purchase_name","");
// break;
// }
//
//
// $data = $this->getInputSource()->all();
// data_fill($data,"*.create_uid",$create_uid);
// data_fill($data,"*.create_name",$create_name);
$this->merge([]);
}
}
<?php
namespace App\Http\Requests;
use Illuminate\Support\Facades\Route;
class PurchasePlanItemSave extends BaseRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
$rules = [
'purchase_plan_id' => 'required',
'goods_id' => 'required',
'goods_sn' => 'required',
'brand_id' => 'required',
'brand_name' => 'required',
'goods_name' => 'required',
'plan_qty' => 'required',
'goods_unit' => 'required',
'price_without_tax' => 'required',
'price_in_tax' => 'required',
'purchase_uid' => 'required',
'purchase_name' => 'required',
'remark' => 'max:200',
];
if ($this->routeIs('updatePurchasePlanItem')) {
$rules['plan_item_id'] = 'required';
}
return $rules;
}
public function withValidator($validator)
{
$validator->after(function ($validator) {
// $validator->errors()->add('field', 'Something is wrong with this field!');
});
}
}
<?php
namespace App\Http\Requests;
use App\Http\Models\PurchasePlanModel;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
class PurchasePlanSave extends BaseRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
$purchasePlanRules = [
'company_id' => 'required',
'company_name' => 'required',
'currency' => 'required',
'delivery_warehouse_id' => 'required',
'delivery_warehouse_name' => 'required',
'remark' => 'max:255',
];
$purchasePlanItemRules = [
//校验详情数组
'purchase_plan_items.*.plan_item_id' => 'integer',
'purchase_plan_items.*.goods_id' => 'required',
'purchase_plan_items.*.goods_sn' => 'required',
'purchase_plan_items.*.brand_id' => 'required',
'purchase_plan_items.*.brand_name' => 'required',
'purchase_plan_items.*.standard_brand_id' => 'required',
'purchase_plan_items.*.standard_brand_name' => 'required',
'purchase_plan_items.*.goods_name' => 'required',
'purchase_plan_items.*.plan_qty' => 'required|integer|min:0',
'purchase_plan_items.*.goods_unit' => 'required',
'purchase_plan_items.*.price_without_tax' => 'required|numeric|min:0',
'purchase_plan_items.*.price_in_tax' => 'numeric|min:0',
'purchase_plan_items.*.purchase_uid' => 'required',
'purchase_plan_items.*.purchase_name' => 'required',
'purchase_plan_items.*.frq_time' => 'date',
'purchase_plan_items.*.remark' => 'max:255',
'purchase_plan_items.*.spu_id' => 'required',
'purchase_plan_items.*.supplier_name' => 'max:128',
'purchase_plan_items.*.supp_brand_name' => 'max:128',
'purchase_plan_items.*.supp_goods_sn' => 'max:128',
];
//更新采购计划不需要校验详情
if ($this->routeIs('updatePurchasePlan')) {
$purchasePlanRules = [
'purchase_plan_id' => 'required',
'company_id' => 'required',
'company_name' => 'required',
'currency' => 'required',
'delivery_warehouse_id' => 'required',
'delivery_warehouse_name' => 'required',
'remark' => 'max:255',
];
}
return array_merge($purchasePlanItemRules, $purchasePlanRules);
}
public function attributes()
{
return [
'purchase_plan_items.*.goods_id' => trans('validation.attributes.goods_id'),
'purchase_plan_items.*.goods_sn' => trans('validation.attributes.goods_sn'),
'purchase_plan_items.*.brand_id' => trans('validation.attributes.brand_id'),
'purchase_plan_items.*.standard_brand_id' => trans('validation.attributes.standard_brand_id'),
'purchase_plan_items.*.standard_name' => trans('validation.attributes.standard_brand_name'),
'purchase_plan_items.*.brand_name' => trans('validation.attributes.brand_name'),
'purchase_plan_items.*.goods_name' => trans('validation.attributes.goods_name'),
'purchase_plan_items.*.plan_qty' => trans('validation.attributes.plan_qty'),
'purchase_plan_items.*.goods_unit' => trans('validation.attributes.goods_unit'),
'purchase_plan_items.*.price_without_tax' => trans('validation.attributes.price_without_tax'),
'purchase_plan_items.*.price_in_tax' => trans('validation.attributes.price_in_tax'),
'purchase_plan_items.*.purchase_uid' => trans('validation.attributes.purchase_uid'),
'purchase_plan_items.*.purchase_name' => trans('validation.attributes.purchase_name'),
'purchase_plan_items.*.remark' => trans('validation.attributes.remark'),
'purchase_plan_items.*.spu_id' => trans('validation.attributes.spu_id'),
'purchase_plan_items.*.supplier_name' => '供应商名称',
'purchase_plan_items.*.supp_brand_name' => '供应商品牌名',
'purchase_plan_items.*.supp_goods_sn' => '供应商商品唯一编码',
];
}
public function withValidator($validator)
{
$validator->after(function ($validator) {
// $validator->errors()->add('field', 'Something is wrong with this field!');
});
}
protected function prepareForValidation()
{
$this->merge([
'purchase_plan_items' => json_decode($this->get('purchase_plan_items'), true),
'remark' => $this->get('remark') ?: '',
]);
}
protected function passedValidation()
{
}
}
<?php
namespace App\Http\Requests;
use App\Http\Models\PurchasePlanModel;
use App\Http\Models\ReturnMaterialExtendModel;
use App\Http\Models\ReturnMaterialModel;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
class ReturnMaterialSave extends BaseRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
if ($this->routeIs('addReturnMaterial')) {
return [
'stock_in_item_ids' => 'required',
'rma_reason' => 'required|numeric',
'remark' => 'max:255',
'consignee' => 'required',
'tel' => 'required',
'address' => 'required',
'return_material_items' => 'required',
'return_material_items.*.stock_in_item_id' => 'required',
'return_material_items.*.return_qty' => 'required',
];
} else {
$rule = [
'rma_reason' => 'required|numeric',
'remark' => 'max:255',
'consignee' => 'required',
'tel' => 'required',
'address' => 'required',
'rma_id' => 'required',
'return_material_items' => '',
];
if ($this->input('return_material_items')) {
$rule = array_merge($rule, [
'return_material_items.*.rma_item_id' => 'required',
'return_material_items.*.return_qty' => 'required',
'return_material_items.*.return_without_tax' => 'required',
'return_material_items.*.return_in_tax' => 'required'
]);
$returnMaterial = ReturnMaterialModel::where('rma_id', $this->input('rma_id'))->first()->toArray();
if ($returnMaterial['company_id'] == ReturnMaterialModel::COMPANY_SM) {
unset($rule['return_material_items.*.return_in_tax']);
}
}
return $rule;
}
}
public function attributes()
{
return [
'rma_reason' => '退货原因',
'consignee' => '退货收货人',
'tel' => '退货收货人电话',
'address' => '退货收货人地址',
'return_material_items' => '退货详情列表',
'return_material_items.*.stock_in_item_id' => '退货详情的入库单ID',
'return_material_items.*.return_qty' => '退货详情的退货数量',
'return_material_items.*.rma_item_id' => '退货详情的ID',
'return_material_items.*.return_without_tax' => '退货单价(未税)',
'return_material_items.*.return_in_tax' => '退货单价(含税)',
];
}
public function withValidator($validator)
{
$validator->after(function ($validator) {
// $validator->errors()->add('field', 'Something is wrong with this field!');
});
}
protected function prepareForValidation()
{
$this->merge([
'return_material_items' => json_decode($this->input('return_material_items'), true),
]);
}
protected function passedValidation()
{
}
}
<?php
namespace App\Http\Requests;
//退货单同步的表单校验,和采购新增的退货单的数据差挺远的,所以要单独提出来一份表单验证
class ReturnMaterialSyncSave extends BaseRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'after_sales_id' => 'required',
'after_sales_sn' => 'required',
'create_uid' => 'required',
'create_name' => 'required',
'items' => 'required',
'items.*.order_item_id' => 'required|integer|min:1',
'items.*.after_sales_item_id' => 'required|integer|min:1',
'items.*.return_qty' => 'required|integer',
'items.*.rma_reason' => 'required|max:300',
'items.*.remark' => 'required|max:300',
];
}
public function attributes()
{
return [
];
}
public function withValidator($validator)
{
$validator->after(function ($validator) {
});
}
protected function prepareForValidation()
{
if (!is_array($this->input('items'))) {
$this->merge([
'items' => json_decode($this->input('items'), true),
]);
}
}
protected function passedValidation()
{
}
}
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class ScmOrderTemporarySave extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
//
];
}
}
<?php
namespace App\Http\Services;
class BaseService
{
const _LIMIT_ = 15;
public function startTransaction(){
\DB::connection("mysql")->beginTransaction();
}
public function commitTransaction(){
\DB::connection("mysql")->commit();
}
public function rollBackTransaction(){
\DB::connection("mysql")->rollBack();
}
public static $purchase_items = [
"frq_id"=>"需求单ID",
"order_item_id"=>"销售订单明细ID",
"goods_name"=>"商品型号",
"goods_sn"=>"商品编码",
"brand_name"=>"品牌",
];
/*
* 记录日志 单条
* $detail 采购明细 数组
*/
public function getPurItemFormat($detail){
$logStr = [];
foreach($detail as $field=>$val){
if(in_array($field,array_keys(self::$purchase_items))){
$logStr[] = sprintf("%s:%s",self::$purchase_items[$field],$val);
}
}
return implode(",",$logStr);
}
}
<?php
namespace App\Http\Transformers;
use App\Http\Models\PurchasePlanModel;
use App\Http\Models\SupplierAddressModel;
use App\Http\Models\SupplierContactModel;
use App\Http\Utils\NameConvert;
use Illuminate\Support\Arr;
class CommonTransformer
{
//这个currency可以传currency或者company_id,因为这两个的值都是类型相等的,前者为1,后者肯定也是1
public static function priceTransform($price, $currency, $number = 0)
{
$price = $number > 0 ? number_format($price, $number) : $price;
$currencyUnit = Arr::get(config('field.currency_sign'), $currency);
return $price ? $currencyUnit . '' . $price : 0;
}
}
<?php
/**
* Created by PhpStorm.
* User: duwenjun
* Date: 2021/9/1
* Time: 9:40 AM
*/
namespace App\Http\Utils;
class ArrUtil
{
public static function notContainsOnlyNull($arr)
{
return !empty(array_filter($arr, function ($a) {
return $a !== null;
}));
}
// 判断数组值是否相同,如果都相同,那么最终array_unique只有一个值
public static function isSame($arr)
{
return count(array_unique($arr)) == 1;
}
}
\ No newline at end of file
<?php
namespace App\Http\Utils;
//币种调用类
use App\Http\Caches\RateCache;
class Currency
{
const CURRENCY_TYPE_RMB = 1; //币种-人民币
const CURRENCY_TYPE_USD = 2; //币种-美元
public static function getCode($id)
{
$currencyArrConfig = config("field.CurrencyEn");
return $currencyArrConfig[$id] ?? '';
}
public static function getName($id)
{
$currencyArrConfig = config("field.Currency");
return $currencyArrConfig[$id] ?? '';
}
public static function priceFormat($currency, $price, $num = 2, $sep = '')
{
$sign = self::getCurrencySign($currency);
$minus = $price < 0 ? '-' : '';
$price = number_format(abs($price), $num, '.', $sep);
$price = $sign . $price;
return $minus . $price;
}
public static function getCurrencySign($currency)
{
$currencySignArr = config("field.currency_sign");
return $currencySignArr[$currency] ?? '';
}
public static function calculatePrice($currency, $price)
{
//人民币税率1.13,非人民币0
$taxRate = $currency == self::CURRENCY_TYPE_RMB ? config("field.TaxRate") : 1;
$priceInTax = $price;
$priceWithoutTax = $price / $taxRate;
return [$priceInTax, $priceWithoutTax];
}
public static function getCurrencyExchangeRate($currency)
{
$exchangeRate = 1;
if ($currency != self::CURRENCY_TYPE_RMB) {
$exchangeRate = (new RateCache)->getRate(self::getName($currency));//汇率 6.55
}
return $exchangeRate;
}
public static function getCurrencyList()
{
$currencyList = [];
foreach (config("field.CurrencyEn") as $currencyId => $currencyName) {
$currencyList[$currencyId]["id"] = $currencyId;
$currencyList[$currencyId]["code"] = $currencyName;
$currencyList[$currencyId]["exchange_rate"] = self::getCurrencyExchangeRate($currencyId) ?? 0;
$currencyList[$currencyId]["symbol"] = self::getCurrencySign($currencyId)??"";
$currencyList[$currencyId]["currencyCn"] = self::getName($currencyId)??"";
}
return $currencyList;
}
}
<?php
namespace App\Http\Utils;
class ErrMsg
{
public static function getExceptionInfo(\Exception $exception)
{
$err_info = [
'message' => $exception->getMessage(),
'file' => $exception->getFile(),
'line' => $exception->getLine(),
'code' => $exception->getCode()
];
return $err_info;
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: duwenjun
* Date: 2022/3/9
* Time: 1:35 PM
*/
namespace App\Http\Utils;
class FileUrl
{
// private static
private static $baseDomain = null;
private static function initConfig()
{
if (is_null(self::$baseDomain)) {
self::$baseDomain = Config('website.file_domain');
}
return true;
}
private static function getBaseDomain()
{
return self::$baseDomain;
}
public static function getUrl($file_id)
{
self::initConfig();
$file_url = '';
if ($file_id) {
$file_url = self::getBaseDomain() . "/download/" . $file_id;
}
return $file_url;
}
}
\ No newline at end of file
<?php
namespace App\Http\Utils;
//日志数据构建类
use Illuminate\Support\Facades\Lang;
class LogDataGenerate
{
//获取新增日志,根据插入数据来的
//objId是主键ID
public static function getInsertLog($objId, $insertData = [])
{
$logData = '';
foreach ($insertData as $key => $item) {
if (!Lang::has('log-fields.' . $key)) {
continue;
}
$logData .= trans('log-fields.' . $key) . '为' . $item . '; ';
}
return $logData ? [
'obj_id' => $objId,
'log_data' => ['message' => '新增数据 : ' . $logData],
] : [];
}
//获取修改的日志,根据更新数据来的
public static function getUpdateLog($objId, $updateData = [], $originData = [])
{
$logData = '';
foreach ($updateData as $key => $item) {
if (!Lang::has('log-fields.' . $key)) {
continue;
}
$originItem = \Arr::get($originData, $key);
if ($originItem == $item) {
continue;
}
//单独处理币种
switch ($key) {
case 'currency':
$originItem = \Arr::get(config('field.Currency'), $originItem);
$item = \Arr::get(config('field.Currency'), $item);
}
$logData .= trans('log-fields.' . $key) . "由 ${originItem} 修改为 ${item} ;";
}
return $logData ? [
'obj_id' => $objId,
'log_data' => ['message' => '修改数据 : ' . $logData],
] : [];
}
//获取删除的日志
public static function getDeleteLog($objId, $deleteData = [])
{
$logData = '';
foreach ($deleteData as $key => $item) {
if (!Lang::has('log-fields.' . $key)) {
continue;
}
$logData .= trans('log-fields.' . $key) . '为' . $item . '; ';
}
return $logData ? [
'obj_id' => $objId,
'log_data' => ['message' => '删除数据 : ' . $logData]
] : [];
}
}
<?php
/**
* Created by PhpStorm.
* User: duwenjun
* Date: 2021/8/13
* Time: 4:44 PM
*/
namespace App\Http\Utils;
use App\Http\Models\CmsUserInfoModel;
use App\Http\Models\Order\OrderServiceItemsModel;
use App\Http\Models\PayableModel;
use App\Http\Models\PaymentItemsModel;
use App\Http\Models\PaymentModel;
use App\Http\Models\PurchaseApproveModel;
use App\Http\Models\PurchaseSeviceApproveModel;
use App\Http\Services\PriceService;
class NameConvert
{
// 获取性别
public static function getGenderName($gender)
{
$gender = "未设置";
if ($gender == CmsUserInfoModel::GENDER_TYPE_MAN) {
$gender = "男性";
}
if ($gender == CmsUserInfoModel::GENDER_TYPE_WOMAN) {
$gender = "女性";
}
return $gender;
}
// 获取间隔天数;用于计算有效期,因为有效期为有效天数+创建时间,数据库存储的有效期为时间戳,需要反向计算有效期
public static function getIntervalDay($expire_time, $create_time)
{
$interval_days = '';
if ($expire_time) {
$interval_days = ($expire_time - $create_time) / 86400;
$interval_days = ceil($interval_days);
}
return $interval_days;
}
// 获取创建时间
public static function getDateTime($create_time)
{
$date_time = '';
if ($create_time && is_numeric($create_time)) {
$date_time = date("Y-m-d H:i:s", $create_time);
}
return $date_time;
}
public static function getDate($create_time)
{
$time = '';
if ($create_time) {
$time = date("Y-m-d", $create_time);
}
return $time;
}
// 获取审核状态
public static function getApproveStatusName($a_status)
{
$status_name = '';
if ($a_status == PurchaseApproveModel::APPROVE_STATUS_PROCESS) {
$status_name = "审核中";
}
if ($a_status == PurchaseApproveModel::APPROVE_STATUS_PASS) {
$status_name = "已通过";
}
if ($a_status == PurchaseApproveModel::APPROVE_STATUS_FAIL) {
$status_name = "未通过";
}
if ($a_status == PurchaseSeviceApproveModel::APPROVE_STATUS_CANCEL) {
$status_name = "取消审核";
}
return $status_name;
}
// 获取付款申请单状态
public static function getPaymentStatusName($status)
{
$status_name = '';
$status_name_map = PaymentModel::$STATUS_NAME_MAP;
if (isset($status_name_map[$status])) {
$status_name = $status_name_map[$status];
}
return $status_name;
}
// 获取付款申请单来源类型
public static function getPaymentTypeName($payment_type)
{
$type_name = '';
if ($payment_type == PaymentModel::PAYMENT_TYPE_PUR) {
$type_name = "采购单";
}
if ($payment_type == PaymentModel::PAYMENT_TYPE_PAYABLE) {
$type_name = "应付单";
}
return $type_name;
}
// 获取付款申请单付款类型 1预付款2退预付款3采购付款4退采购付款
public static function getPaymentPayTypeName($pay_type)
{
$type_name = '';
if (isset(PaymentItemsModel::$PAY_TYPE_NAME_MAP[$pay_type])) {
$type_name = PaymentItemsModel::$PAY_TYPE_NAME_MAP[$pay_type];
}
return $type_name;
}
// 获取应付单状态
public static function getPayableStatusName($status)
{
$status_name = '';
$status_name_map = PayableModel::$STATUS_NAME_MAP;
if (isset($status_name_map[$status])) {
$status_name = $status_name_map[$status];
}
return $status_name;
}
// 获取应付单付款状态
public static function getPayablePayStatusName($status)
{
$pay_status_name = '';
$status_name_map = PayableModel::$PAY_STATUS_NAME_MAP;
if (isset($status_name_map[$status])) {
$pay_status_name = $status_name_map[$status];
}
return $pay_status_name;
}
// 获取应付单开票状态
public static function getPayableInvoiceStatusName($status)
{
$invoice_status_name = '';
$status_name_map = PayableModel::$INVOICE_STATUS_NAME_MAP;
if (isset($status_name_map[$status])) {
$invoice_status_name = $status_name_map[$status];
}
return $invoice_status_name;
}
// 获取应付单入库类型
public static function getPayableStockInTypeName($stock_in_type)
{
$stock_in_type_name = '';
$stock_in_type_name_map = PayableModel::$STOCK_IN_NAME_MAP;
if (isset($stock_in_type_name_map[$stock_in_type])) {
$stock_in_type_name = $stock_in_type_name_map[$stock_in_type];
}
return $stock_in_type_name;
}
// 获取报价货币名称,根据类型转换名称,如1=人民币
public static function getCurrencyName($currency_type)
{
$name = '';
if ($currency_type) {
$currency_map = config('field.Currency');
if ($currency_map && isset($currency_map[$currency_type])) {
$name = $currency_map[$currency_type];
}
}
return $name;
}
// 获取币种code,如 1=RMB
public static function getCurrencyCode($currency_type)
{
$name = '';
if ($currency_type) {
$currency_map = config('field.currency_code');
if ($currency_map && isset($currency_map[$currency_type])) {
$name = $currency_map[$currency_type];
}
}
return $name;
}
// 获取报价货币类型,根据名称获取类型,如 人民币=1
public static function getCurrencyType($currency_name)
{
$type = 0;
if ($currency_name) {
$currency_map = config('field.Currency');
$type = array_search($currency_name, $currency_map);
}
return $type;
}
// 售后单-申请原因
public static function getServiceApplyReasonVal($apply_reason_type)
{
$apply_reason_val = '';
if ($apply_reason_type) {
$apply_reason_map = OrderServiceItemsModel::$APPLY_REASON_MAP;
if (isset($apply_reason_map[$apply_reason_type])) {
$apply_reason_val = $apply_reason_map[$apply_reason_type];
}
}
return $apply_reason_val;
}
// 售后单-货物处理方案
public static function getServiceRefundPlanVal($refund_plan_type)
{
$refund_plan_val = '';
if ($refund_plan_type == OrderServiceItemsModel::FEFUND_PLAN_SUP) {
$refund_plan_val = "退供应商";
}
if ($refund_plan_type == OrderServiceItemsModel::FEFUND_PLAN_SELF) {
$refund_plan_val = "转自营";
}
return $refund_plan_val;
}
//这个currency可以传currency或者company_id,因为这两个的值都是类型相等的,前者为1,后者肯定也是1
public static function getFmtPrice($price, $currency, $thousands_sep = ',')
{
$price = (float)$price;
$prefix_sign = '';
if ($price < 0) {
$prefix_sign = "-";
$price = abs($price);
}
$currency_sign =Currency::getCurrencySign($currency);
return $prefix_sign . $currency_sign . (string)number_format($price, 2, '.', $thousands_sep);
}
// 获取格式化金额,不带币种符合
public static function getNoSignFmtPrice($price)
{
return (string)number_format($price, 2);
}
//这个currency可以传currency或者company_id,因为这两个的值都是类型相等的,前者为1,后者肯定也是1
public static function getSignPrice($price, $currency)
{
$price = (float)$price;
$prefix_sign = '';
if ($price < 0) {
$prefix_sign = "-";
$price = abs($price);
}
$currency_sign = ($currency == PriceService::CURRENCY_TYPE_RMB ? '¥' : '$');
return $prefix_sign . $currency_sign . (string)number_format($price, 2);
}
// 固定符号为人民币
public static function getRmbSignPrice($price)
{
$price = (float)$price;
$prefix_sign = '';
if ($price < 0) {
$prefix_sign = "-";
$price = abs($price);
}
$currency_sign = '¥';
return $prefix_sign . $currency_sign . (string)$price;
}
/**
* 将单个数字转换成中文大写
* 零、壹、贰、叁、肆、伍、陆、柒、捌、玖
* @param $num
* @author handa
* @date 2022/3/29
*/
public static function numToUpperChar($num)
{
switch ($num) {
case 0:
return '零';
case 1:
return '壹';
case 2:
return '贰';
case 3:
return '叄';
case 4:
return '肆';
case 5:
return '伍';
case 6:
return '陆';
case 7:
return '柒';
case 8:
return '捌';
case 9:
return '玖';
default:
return '';
}
}
}
<?php
namespace App\Http\Utils;
use App\Http\ApiHelper\ApiCode;
use SoapClient;
use App\Exceptions\InvalidRequestException;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
class SoapRequester
{
const SOAP_NAME_ERP = "soap_name_erp";
public static function request($soap_name, $soap_func, $request_data)
{
$request_result = [];
try {
ini_set('soap.wsdl_cache_enabled', '0');
ini_set('default_socket_timeout', 30);//设置socket超时时间
libxml_disable_entity_loader(false);
if ($soap_name == self::SOAP_NAME_ERP) {
$soapClient = new SoapClient(Config('config.erp_domain') . '/ormrpc/services/WSIchuntjKFacade?wsdl');
}
$res = $soapClient->$soap_func(json_encode($request_data));
if ($res) {
$soap_res_arr = json_decode($res, true);
if ($soap_res_arr) {
$request_result = $soap_res_arr['data'];
}
// 如果接口返回错误,记录日志
if ($soap_res_arr && ($soap_res_arr['code'] !== ApiCode::API_CODE_SUCCESS)) {
self::errLog($soap_name, $soap_func, $request_data, $res);
}
} else {
self::errLog($soap_name, $soap_func, $request_data, $res);
}
} catch (\Exception $e) {
$err_json = json_encode([
'message' => $e->getMessage(),
'file' => $e->getFile(),
'line' => $e->getLine(),
'code' => $e->getCode()
]);
(new Logger('soap'))->pushHandler(new StreamHandler(storage_path('logs/soap.log')))->error($err_json);
self::errLog($soap_name, $soap_func, $request_data, null);
throw new InvalidRequestException('soap接口请求异常,请联系技术查看日志,错误信息:' . $e->getMessage());
}
return $request_result;
}
// 请求错误日志
private static function errLog($soap_name, $soap_func, $request_data, $res)
{
$err_json = json_encode([
'soap_name' => $soap_name,
'soap_func' => $soap_func,
'request_data' => $request_data,
'res' => $res,
]);
(new Logger('soap'))->pushHandler(new StreamHandler(storage_path('logs/soap.log')))->error($err_json);
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: duwenjun
* Date: 2021/9/1
* Time: 9:40 AM
*/
namespace App\Http\Utils;
use Illuminate\Support\Facades\Validator;
class ValidatorMsg
{
// 只返回错误的第一条错误
public static function getMsg($error_list)
{
$err_msg = '';
foreach ($error_list as $err_key => $err_msgs) {
foreach ($err_msgs as $msg) {
$err_msg .= "{$err_key}|{$msg}";
break;
}
break;
}
return $err_msg;
}
public static function checkValidateParamThrowException($validateRule,$params)
{
$validator = Validator::make($params, $validateRule);
if ($validator->fails()) {
$errors = $validator->errors()->toJson(JSON_UNESCAPED_UNICODE);
throw new \InvalidArgumentException($errors);
}
return true;
}
}
<?php
namespace App\Listeners;
use Faker\Provider\DateTime;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Log;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
class QueryListener
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param QueryExecuted $event
* @return void
*/
public function handle(QueryExecuted $event)
{
try {
if (Config('app.debug') == true) {
$sql = str_replace("?", "'%s'", $event->sql);
foreach ($event->bindings as $i => $binding) {
if ($binding instanceof DateTime) {
$event->bindings[$i] = $binding->format('\'Y-m-d H:i:s\'');
} else {
if (is_string($binding)) {
$event->bindings[$i] = "'$binding'";
}
}
}
$log = vsprintf($sql, $event->bindings);
$log = $log . ' [ RunTime:' . $event->time . 'ms ] ';
$fileName = sprintf("logs/log/sql-%s.log",date("Y-m-d"));
\Log::channel("sql")->info(sprintf($log));
// (new Logger('sql'))->pushHandler(new StreamHandler(storage_path($fileName)))->info($log);
}
} catch (\Exception $exception) {
\Log::channel("sql")->info(
sprintf(
"错误:请求参数 %s,错误原因:%s",
print_r(request()->all(),true),
json_encode($exception->getMessage(),JSON_UNESCAPED_UNICODE)
)
);
// (new Logger('sql'))->pushHandler(new StreamHandler(storage_path($fileName)))->info($exception->getMessage());
}
}
}
<?php
namespace App\Presenters;
class BrandSelectorPresenter
{
public function render($name, $text, $value = null, $data = [0 => '禁用', 1 => '启用'], $option = [])
{
$isRequired = array_get($option, 'required', false);
$requiredHtml = $isRequired ? '<span style="color: red">*</span>' : "";
$html = <<<EOF
<label class="layui-form-label">
$requiredHtml
$text</label>
<div class="layui-input-inline">
<div id="$name" class="layui-input-inline" value="$value" style="width: 700px;">
</div>
<input type="hidden" name="$name" id="$name">
</div>
<script>
//渲染品牌多选
let brandUrl = '/api/common/getBrandList';
let brandSelector = xmSelect.render({
el: '#$name',
name: '$name',
searchTips: '请输入要查找的制造商',
paging: true,
empty: '没有查找到数据',
prop: {
name: 'brand_name',
value: 'brand_id'
},
height: "1300px",
remoteSearch: true,
autoRow: true,
pageRemote: true,
pageSize: 10,
filterable: true,
remoteMethod: function (val, cb, show, pageIndex) {
//val: 搜索框的内容, 不开启搜索默认为空, cb: 回调函数, show: 当前下拉框是否展开, pageIndex: 当前第几页
$.ajax({
url: brandUrl,
type: 'post',
data: {
brand_ids: $('#$name').val(),
brand_name: val,
page: pageIndex
},
dataType: 'json',
timeout: 10000,
success: function (res) {
if (!res) return layer.msg('网络错误,请重试', {icon: 5});
if (res.code === 0) {
cb(res.data, res.count/10);
}
},
error: function () {
return layer.msg('网络错误,请重试', {icon: 5});
}
});
},
on: function (data) {
let brandIds = '';
for (let x in data.arr) // x 为属性名
{
brandIds = brandIds + data.arr[x].brand_id + ',';
}
$("#brand_ids").val(brandIds);
}
});
let brandIds = $('#brand_selector').attr('value');
brandSelector.setValue(brandIds.split(','));
</script>
EOF;
return $html;
}
}
\ No newline at end of file
<?php
namespace App\Presenters;
class DateTimePresenter
{
public function render($name, $text, $value)
{
$time = $value;
return <<<EOF
<label class="layui-form-label">$text</label>
<div class="layui-input-inline">
<input type="text" id="$name" name="$name"
placeholder="请输入$text"
class="layui-input"
value="$time">
</div>
<script>
window.onload = function(){
layui.use('laydate', function(){
let laydate = layui.laydate;
laydate.render({
elem: 'input[name=$name]'
,type: 'datetime'
,format: 'yyyy-MM-dd H:i:s'
});
});
}
</script>
EOF;
}
}
\ No newline at end of file
<?php
namespace App\Presenters\Filter;
class DayTypePresenter
{
public function render($relateObjName = '')
{
$unique = "unique_" . mt_rand(1, 100000);
$html = <<<EOF
<div class="layui-row" style="width:268px;margin-bottom: 3px;margin-top: 5px">
<div class="layui-col-md2" style="margin-left: 34px">
<button type="button" class="layui-btn layui-btn-primary layui-btn-sm day_type_button" id="${unique}_today">今日</button>
</div>
<div class="layui-col-md2">
<button type="button" class="layui-btn layui-btn-primary layui-btn-sm day_type_button" id="${unique}_last_days">近三天</button>
</div>
<div class="layui-col-md2">
<button type="button" class="layui-btn layui-btn-primary layui-btn-sm day_type_button" style="margin-left: 11px" id="${unique}_this_week">本周</button>
</div>
<div class="layui-col-md2">
<button type="button" class="layui-btn layui-btn-primary layui-btn-sm day_type_button" style="margin-left: 10px" id="${unique}_this_month">本月</button>
</div>
<div class="layui-col-md3">
</div>
</div>
<script>
layui.use(['form', 'element'], function () {
$('.day_type_button').click(function() {
$('.day_type_button').attr('class','layui-btn layui-btn-primary layui-btn-sm day_type_button');
$(this).attr('class','layui-btn layui-btn-sm layui-btn-normal day_type_button');
});
});
</script>
EOF;
return $html;
}
public function optionsRender($data)
{
$optionsHtml = '';
foreach ($data as $key => $value) {
$optionsHtml = $optionsHtml . "<option value='$key'>$value</option>";
}
return $optionsHtml;
}
}
\ No newline at end of file
<?php
namespace App\Presenters\Filter;
//左边数据可以多种,右边数据也可以多种,而且右边数据跟着左边来变
class MultiTransformableSelectPresenter
{
public function render($map = [], $data = [])
{
$defaultKey = array_keys($map)[0];
$unique = "unique_" . mt_rand(1, 100000);
$selectUnique = "unique_" . mt_rand(1, 100000);
//默认的第一项数据
$firstDataItemKey = array_first(array_keys($data));
$html = <<<EOF
<div class="layui-row" style="width:268px;margin-bottom: 3px;">
<div class="layui-col-md5">
<div class="layui-input-inline" style="width: 100px;margin-left: 10px">
<select lay-filter="$unique">
{$this->optionsRender($map)}
</select>
</div>
</div>
<div class="layui-col-md7" style="margin-left: -3px">
<div class="layui-input-inline">
<select class="value_select" name="$defaultKey" id="$selectUnique" lay-filter="$selectUnique" lay-search="">
</select>
</div>
</div>
{$this->selectOptionsRender($data)}
</div>
<script>
$(function() {
layui.use(['form', 'element'], function () {
let form = layui.form;
//初始化渲染
let optionsHtml = $('#$firstDataItemKey').html();
$('#$selectUnique').html(optionsHtml);
form.render();
//变更渲染
form.on('select($unique)', function(data){
console.log(data.value)
optionsHtml = $('#'+data.value).html();
$('#$selectUnique').html(optionsHtml);
data.othis.parent().parent().parent().find('.value_select').attr('name',data.value);
form.render();
});
});
});
</script>
EOF;
return $html;
}
public function optionsRender($data)
{
$optionsHtml = '';
foreach ($data as $key => $value) {
$optionsHtml = $optionsHtml . "<option value='$key'>$value</option>";
}
return $optionsHtml;
}
public function selectOptionsRender($data)
{
$html = '';
foreach ($data as $key => $value) {
//第二层
$optionsHtml = ' <option value="">请选择</option>';
foreach ($value as $k => $v) {
$optionsHtml = $optionsHtml . "<option value='$k'>$v</option>";
}
$html .= <<<EOF
<div id="$key" style="display: none" >
$optionsHtml;
</div>
EOF;
}
return $html;
}
}
\ No newline at end of file
<?php
namespace App\Presenters\Filter;
class TransformableInputPresenter
{
public function render($map = [])
{
$unique = "unique_" . mt_rand(1, 100000);
$defaultKey = array_keys($map)[0];
$html = <<<EOF
<div class="layui-row" style="width:268px;margin-bottom: 3px;">
<div class="layui-col-md5">
<div class="layui-input-inline" style="width: 100px;margin-left: 10px">
<select lay-filter="$unique">
{$this->optionsRender($map)}
</select>
</div>
</div>
<div class="layui-col-md7" style="margin-left: -3px">
<div class="layui-input-inline">
<input type="text" name="$defaultKey" placeholder="请输入" class="layui-input"
style="width: 158px">
</div>
</div>
</div>
<script>
$(function() {
layui.use(['form', 'element'], function () {
let form = layui.form;
form.on('select($unique)', function(data){
data.othis.parent().parent().parent().find('input').attr('name',data.value);
form.render();
});
});
});
</script>
EOF;
return $html;
}
public function optionsRender($data)
{
$optionsHtml = '';
foreach ($data as $key => $value) {
$optionsHtml = $optionsHtml . "<option value='$key'>$value</option>";
}
return $optionsHtml;
}
}
\ No newline at end of file
<?php
namespace App\Presenters\Filter;
//左边可以下拉,右边也可以下拉
class TransformableSelectPresenter
{
public function render($map = [], $data = [])
{
$defaultKey = array_keys($map)[0];
$unique = "unique_" . mt_rand(1, 100000);
$selectUnique = "unique_" . mt_rand(1, 100000);
$html = <<<EOF
<div class="layui-row" style="width:268px;margin-bottom: 3px;">
<div class="layui-col-md5">
<div class="layui-input-inline" style="width: 100px;margin-left: 10px">
<select lay-filter="$unique">
{$this->optionsRender($map)}
</select>
</div>
</div>
<div class="layui-col-md7" style="margin-left: -3px">
<div class="layui-input-inline">
<select class="value_select" name="$defaultKey" lay-filter="$selectUnique" lay-search="">
{$this->selectOptionsRender($data)}
</select>
</div>
</div>
</div>
<script>
$(function() {
layui.use(['form', 'element'], function () {
let form = layui.form;
form.on('select($unique)', function(data){
data.othis.parent().parent().parent().find('.value_select').attr('name',data.value);
});
});
});
</script>
EOF;
return $html;
}
public function optionsRender($data)
{
$optionsHtml = '';
foreach ($data as $key => $value) {
$optionsHtml = $optionsHtml . "<option value='$key'>$value</option>";
}
return $optionsHtml;
}
public function selectOptionsRender($data)
{
$optionsHtml = ' <option value="">请选择</option>';
foreach ($data as $key => $value) {
$optionsHtml = $optionsHtml . "<option value='$key'>$value</option>";
}
return $optionsHtml;
}
}
\ No newline at end of file
<?php
namespace App\Presenters\Filter;
use Carbon\Carbon;
class TransformableTimeIntervalPresenter
{
public function render($map = [])
{
$unique = "unique_" . mt_rand(1, 100000);
$defaultKey = array_keys($map)[0];
$todayTimeInterval = Carbon::now()->startOfDay()->toDateString() . ' ~ ' . Carbon::now()->addDay(1)->toDateString();
$threeDayTimeInterval = Carbon::now()->subDay(2)->toDateString() . ' ~ ' . Carbon::now()->addDay(1)->toDateString();
$thisWeekTimeInterval = Carbon::now()->startOfWeek()->toDateString() . ' ~ ' . Carbon::now()->addDay(1)->toDateString();
$thisMonthTimeInterval = Carbon::now()->startOfMonth()->toDateString() . ' ~ ' . Carbon::now()->addDay(1)->toDateString();
$html = <<<EOF
<div class="layui-row" style="margin-bottom: 3px;">
<div class="layui-col-md6">
<div class="layui-col-md5">
<div class="layui-input-inline" style="width: 100px;margin-left: 10px">
<select lay-filter="$unique">
{$this->optionsRender($map)}
</select>
</div>
</div>
<div class="layui-col-md7" style="margin-left: -15px">
<div class="layui-input-inline" style="min-width: 150px;width: 158px">
<input type="text" name="$defaultKey" id="$unique" placeholder="请选择时间区间" autocomplete="off" class="layui-input">
</div>
</div>
</div>
<div class="layui-col-md6">
<div style="margin-top: 5px;">
<div class="layui-col-md2" style="margin-left: 17px">
<button type="button" class="layui-btn layui-btn-primary layui-btn-sm day_type_button"
dateInterval="$todayTimeInterval"
id="${unique}_today">今日</button>
</div>
<div class="layui-col-md2">
<button type="button" class="layui-btn layui-btn-primary layui-btn-sm day_type_button"
dateInterval="$threeDayTimeInterval"
id="${unique}_last_days">近三天</button>
</div>
<div class="layui-col-md2">
<button type="button" class="layui-btn layui-btn-primary layui-btn-sm day_type_button" style="margin-left: 11px"
dateInterval="$thisWeekTimeInterval"
id="${unique}_this_week">本周</button>
</div>
<div class="layui-col-md2">
<button type="button" class="layui-btn layui-btn-primary layui-btn-sm day_type_button" style="margin-left: 10px"
dateInterval="$thisMonthTimeInterval"
id="${unique}_this_month">本月</button>
</div>
<div class="layui-col-md3">
</div>
</div>
</div>
</div>
<script>
$(function() {
layui.use(['form', 'element','laydate'], function(){
let laydate = layui.laydate;
let form = layui.form;
form.on('select($unique)', function(data){
data.othis.parent().parent().parent().find('input').attr('name',data.value);
});
laydate.render({
elem: '#$unique'
,type: 'date'
,trigger:'click'
,range: '~' //或 range: '~' 来自定义分割字符
,change: function (value, date, endDate) {
alert(123)
}
});
$('.day_type_button').click(function() {
$('.day_type_button').attr('class','layui-btn layui-btn-primary layui-btn-sm day_type_button');
$(this).attr('class','layui-btn layui-btn-sm layui-btn-normal day_type_button');
laydate.render({
elem: '#$unique'
,type: 'date'
,value: $(this).attr('dateInterval')
,trigger:'click'
,range: '~' //或 range: '~' 来自定义分割字符
});
});
});
})
</script>
EOF;
return $html;
}
public function optionsRender($data)
{
$optionsHtml = '';
foreach ($data as $key => $value) {
$optionsHtml = $optionsHtml . "<option value='$key'>$value</option>";
}
return $optionsHtml;
}
}
\ No newline at end of file
<?php
namespace App\Presenters;
class ImageUploadPresenter
{
public function render($name, $text, $value = null, $option = [])
{
$isRequired = array_get($option, 'required', false);
$requiredHtml = $isRequired ? '<span style="color: red">*</span>' : "";
$uploadUrl = config('website.UploadUrl');
$value = !empty(trim($value)) ? $value : "[]";
$Autograph = Autograph();
return <<<EOF
<label class="layui-form-label">
$requiredHtml
$text
</label>
<div class="layui-input-inline" style="width: 700px">
<input type="hidden" id="$name" name="$name" value='$value'>
<input id="uploadContainer" type="file" multiple name="upload">
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link href="https://cdn.bootcdn.net/ajax/libs/bootstrap-fileinput/5.1.4/css/fileinput.min.css" rel="stylesheet">
<script src="https://cdn.bootcdn.net/ajax/libs/bootstrap-fileinput/5.1.4/js/fileinput.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/bootstrap-fileinput/5.1.4/js/locales/zh.min.js"></script>
<script>
$Autograph
let element = $("#uploadContainer");
let arr = $("#$name").val()?JSON.parse($("#$name").val()):[];
element.fileinput({
uploadUrl : "$uploadUrl",//上传图片的url
allowedFileExtensions : [ 'jpg', 'png','jepg','jpeg' ],
overwriteInitial : false,
uploadAsync:true,
showRemove:false,
showUpload:false,
initialPreviewShowPreview:false,
language:'zh',
maxFileSize : 5000,
maxFileCount: 5,
initialCaption: "请上传$text",
initialPreview: $value,
initialPreviewAsData: true,
uploadExtraData:function(){
let data = {
k1:k1,
k2:k2,
source:1
}
return data;
}
}).on("filebatchselected", function(event, files) {
element.fileinput('upload');
}).on('fileuploaded', function(event, data, previewId, index) {
let response = data.response
arr.push(response.data.shift())
$("#$name").val(JSON.stringify(arr))
});
</script>
EOF;
}
}
\ No newline at end of file
<?php
namespace App\Presenters;
class MultiSelectorByClassPresenter
{
public function render($name, $text, $value = null, $data = [], $option = [])
{
$data = $data ?: [['name' => '启用', 'value' => 1], ['name' => '禁用', 'value' => -1]];
$isRequired = array_get($option, 'required', false);
$requiredHtml = $isRequired ? '<span style="color: red">*</span>' : "";
$elemId = $name . "Selector";
$data = json_encode($data);
$html = <<<EOF
<label class="layui-form-label">
$requiredHtml
$text</label>
<div class="layui-input-inline">
<div id="$elemId" class="layui-input-inline" value="$value" style="width: 300px;">
</div>
<input type="hidden" name="$name" id="$name" value="$value">
</div>
<script>
window.onload = function(){
layui.config({
base: '/js/web/layui/exts/xmSelect/'
}).extend({
xmSelect: 'xm-select'
}).use(['xmSelect', 'element'], function () {
let xmSelect = layui.xmSelect;
//渲染多选
let selector = xmSelect.render({
el: '.$elemId',
name: '$name',
searchTips: '请输入要查找的$text',
paging: true,
empty: '没有数据',
prop: {
name: 'name',
value: 'value'
},
data : $data,
height: "1300px",
autoRow: true,
pageSize: 10,
filterable: true,
on: function (data) {
let values = [];
for (let x in data.arr) // x 为属性名
{
values.push(data.arr[x].value);
}
$("#$name").val(values.join(','));
}
});
let values = $('#$elemId').attr('value');
selector.setValue(values.split(','));
});
}
</script>
EOF;
return $html;
}
}
\ No newline at end of file
<?php
namespace App\Presenters;
class MultiSelectorPresenter
{
public function render($name, $text, $value = null, $data = [], $option = [])
{
$data = $data ?: [['name' => '启用', 'value' => 1], ['name' => '禁用', 'value' => -1]];
$isRequired = array_get($option, 'required', false);
$requiredHtml = $isRequired ? '<span style="color: red">*</span>' : "";
$elemId = $name . "Selector";
$data = json_encode($data);
$html = <<<EOF
<label class="layui-form-label">
$requiredHtml
$text</label>
<div class="layui-input-inline">
<div id="$elemId" class="layui-input-inline" value="$value" style="width: 300px;">
</div>
<input type="hidden" name="$name" id="$name" value="$value">
</div>
<script>
window.onload = function(){
layui.config({
base: '/js/web/layui/exts/xmSelect/'
}).extend({
xmSelect: 'xm-select'
}).use(['xmSelect', 'element'], function () {
let xmSelect = layui.xmSelect;
//渲染多选
let selector = xmSelect.render({
el: '#$elemId',
name: '$name',
searchTips: '请输入要查找的$text',
paging: true,
empty: '没有数据',
prop: {
name: 'name',
value: 'value'
},
direction: 'down',
data : $data,
height: "1300px",
autoRow: true,
pageSize: 10,
filterable: true,
on: function (data) {
let values = [];
for (let x in data.arr) // x 为属性名
{
values.push(data.arr[x].value);
}
console.log(values)
$("#$name").val(values.join(','));
}
});
let values = $('#$elemId').attr('value');
selector.setValue(values.split(','));
});
}
</script>
EOF;
return $html;
}
}
\ No newline at end of file
<?php
namespace App\Presenters;
class RegionSelectorPresenter
{
public function render($name, $text, $status = null, $data = [0 => '禁用', 1 => '启用'], $option = [])
{
$isRequired = array_get($option, 'required', false);
$requiredHtml = $isRequired ? '<span style="color: red">*</span>' : "";
return <<<EOF
<label class="layui-form-label">
$requiredHtml
$text
</label>
<div class="layui-input-inline" style="width: 400px">
<select name="city" lay-verify="">
<option value="">请选择一个城市</option>
<option value="010">北京</option>
<option value="021">上海</option>
<option value="0571">杭州</option>
</select>
<select name="city" lay-verify="">
<option value="">请选择一个城市</option>
<option value="010">北京</option>
<option value="021">上海</option>
<option value="0571">杭州</option>
</select>
</div>
<script>
layui.use(['form'], function () {
let $ = layui.$;
let form = layui.form;
});
</script>
EOF;
}
}
\ No newline at end of file
<?php
namespace App\Presenters;
class StatusPresenter
{
public function render($name, $text, $status = null, $data = [0 => '禁用', 1 => '启用'], $option = [])
{
$isRequired = array_get($option, 'required', false);
$isDisable = array_get($option, 'disable') === true ? 'disabled' : '';
$width = array_get($option, 'width', 'auto');
$noName = array_get($option, 'noName');
$name = $noName ? '' : $name;
$requiredHtml = $isRequired ? '<span class="require">*</span>' : "";
$html = <<<EOF
<label class="layui-form-label">
$requiredHtml
$text
</label>
<div class="layui-input-inline" style="width: $width">
<select name="$name" id="$name" lay-filter="$name" $isDisable lay-search="">
{$this->optionsRender($data, $status)}
</select>
</div>
EOF;
return $html;
}
public function optionsRender($data, $status)
{
$optionsHtml = ' <option value="">请选择</option>';
$checked = '';
foreach ($data as $key => $value) {
if ($status !== '' && $status != null) {
$checked = ($key == $status) ? "selected='selected'" : '';
}
$optionsHtml = $optionsHtml . "<option value='$key' $checked>$value</option>";
}
return $optionsHtml;
}
}
\ No newline at end of file
<?php
namespace App\Presenters;
class TimeIntervalPresenter
{
public function render($name, $text)
{
$time = request()->get($name);
$html = <<<EOF
<label class="layui-form-label">$text</label>
<div class="layui-input-inline" style="min-width: 300px">
<input type="text" name="{$name}" placeholder="请选择时间区间" autocomplete="off" class="layui-input">
</div>
<script>
window.onload = function(){
layui.use('laydate', function(){
let laydate = layui.laydate;
laydate.render({
elem: 'input[name=$name]'
,type: 'datetime'
,trigger:'click'
,range: '~' //或 range: '~' 来自定义分割字符
,value: '$time'
});
});
}
</script>
EOF;
return $html;
}
}
\ No newline at end of file
<?php
namespace App\Providers;
use App\Http\Models\PurchasePlanModel;
use App\Http\Models\ReturnMaterialModel;
use App\Observers\PurchasePlanObserver;
use App\Observers\ReturnMaterialObserver;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
// $this->_dbQueryBuilderMacro();
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
date_default_timezone_set("Asia/Shanghai");
PurchasePlanModel::observe(PurchasePlanObserver::class);
ReturnMaterialModel::observe(ReturnMaterialObserver::class);
}
}
<?php
namespace App\Providers;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* @var array
*/
protected $policies = [
// 'App\Model' => 'App\Policies\ModelPolicy',
];
/**
* Register any authentication / authorization services.
*
* @return void
*/
public function boot()
{
$this->registerPolicies();
//
}
}
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Broadcast;
use Illuminate\Support\ServiceProvider;
class BroadcastServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Broadcast::routes();
require base_path('routes/channels.php');
}
}
<?php
namespace App\Providers;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* @var array
*/
protected $listen = [
Registered::class => [
SendEmailVerificationNotification::class,
],
'Illuminate\Database\Events\QueryExecuted' => [
'App\Listeners\QueryListener',
]
];
/**
* Register any events for your application.
*
* @return void
*/
public function boot()
{
parent::boot();
//
}
}
<?php
namespace App\Providers;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Route;
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';
/**
* The path to the "home" route for your application.
*
* @var string
*/
public const HOME = '/home';
/**
* Define your route model bindings, pattern filters, etc.
*
* @return void
*/
public function boot()
{
//
parent::boot();
}
/**
* Define the routes for the application.
*
* @return void
*/
public function map()
{
$this->mapApiRoutes();
$this->mapWebRoutes();
$this->mapSyncRoutes();
$this->mapQueueRoutes();
}
/**
* Define the "web" routes for the application.
*
* These routes all receive session state, CSRF protection, etc.
*
* @return void
*/
protected function mapWebRoutes()
{
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
}
/**
* Define the "api" routes for the application.
*
* These routes are typically stateless .
*
* @return void
*/
protected function mapApiRoutes()
{
Route::prefix('api')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
}
/**
* Define the "api" routes for the application.
*
* These routes are typically stateless .
*
* @return void
*/
protected function mapSyncRoutes()
{
Route::prefix('sync')
->middleware('sync')
->namespace($this->namespace)
->group(base_path('routes/sync.php'));
}
// 采购系统队列接口调用
protected function mapQueueRoutes()
{
Route::prefix('queue')
->namespace($this->namespace)
->group(base_path('routes/queue.php'));
}
}
<?php
define("DIGITS_TWO",2);
define("DIGITS_FOUR",4);
define("DIGITS_SIX",6);
/**
* 是否为多维数组
* @param array $arr
* @return bool
*/
function isMultipleArray(array &$arr): bool
{
if (count($arr) <= 0) {
return false;
}
if (count($arr) == count($arr, COUNT_RECURSIVE)) {
foreach ($arr as $tempArr) {
if (is_array($tempArr)) {
return true;
}
}
return false;
}
return true;
}
//判断是否有对应的权限
//request()->perms是Permission中间件过来的
function checkPerm($perm): bool
{
$perms = request()->perms ?: [];
return in_array($perm, $perms);
}
/**
* 价格格式化
* @param [type] $price [description]
* @param integer $sign [description]
* @param integer $num [description]
* @return [type] [description]
*/
function price_format($price, $sign = 0, $num = 2, $sep = '')
{
$minus = $price < 0 ? '-' : '';
$price = floatval(strval($price));
$price = number_format(abs($price), $num, '.', $sep);
$sign = \Arr::get(config("field.currency_sign"),intval($sign),"");
if (!empty($sign)) {
$price = $sign . $price;
}
if($minus){
return $minus.$price;
}
return $price;
}
function arrayGet($arr, $key, $default = "", $func = "")
{
if (isset($arr[$key])) {
if ($func && is_callable($func)) {
try {
return $func($arr[$key]);
} catch (\Throwable $e) {
return $arr[$key];
}
} else {
return $arr[$key];
}
} else {
return $default;
}
}
/*
* 构建时间查询
*/
function buildQueryTimeRange($time = "")
{
$time = explode("~", $time);
$buildTimeQueryData["begin_time"] = isset($time[0]) ? $time[0] : "";
$buildTimeQueryData["end_time"] = isset($time[1]) ? $time[1] : "";
return $buildTimeQueryData;
}
/*
* 排序
*/
//function _arraySort($array,$keys,$sort='asc') {
// $newArr = $valArr = array();
// foreach ($array as $key=>$value) {
// $valArr[$key] = $value[$keys];
// }
// ($sort == 'asc') ? asort($valArr) : arsort($valArr);
// reset($valArr);
// foreach($valArr as $key=>$value) {
// $newArr[$key] = $array[$key];
// }
// return $newArr;
//}
function arraySort($list, $keys, $sort = "asc")
{
if ($sort == "asc") {
$sort = SORT_ASC;
} else {
$sort = SORT_DESC;
}
array_multisort(array_column($list, $keys), $sort, $list);
return $list;
}
/*
* 去重数组
* 过滤数组
*/
function array_filter_unique($arr)
{
return array_unique(array_filter($arr));
}
/*
* 截取字符串
*/
//如果字符串长度超过10,则截取并以省略号结尾
function truncStr($str, $len = 100, $endStr = "")
{
$str = (string)$str;
if (mb_strlen($str, 'utf-8') > $len) {
return mb_substr($str, 0, $len, 'utf-8') . $endStr;
} else {
return $str;
}
}
/*
* 获取登录者的信息
*/
function getAdminUser()
{
$admin = request()->get("user");
if (!$admin) {
throw new \App\Exceptions\InvalidRequestException("没找到登录相关信息,请先登录~_~");
}
$arr = [];
$arr["userId"] = $admin->userId;
$arr["name"] = $admin->name;
$arr["email"] = $admin->email;
$arr["engName"] = $admin->engName;
return $arr;
}
/*
* 获取登录者用户id
*/
function getAdminUserId()
{
$admin = request()->get("user");
if (!$admin) {
throw new \App\Exceptions\InvalidRequestException("没找到登录相关信息,请先登录~_~");
}
return $admin->userId;
}
/*
* 获取登录者的名字
*/
function getAdminUserName()
{
$admin = request()->get("user");
if (!$admin) {
throw new \App\Exceptions\InvalidRequestException("没找到登录相关信息,请先登录~_~");
}
return $admin->name;
}
/*
* 遍历数组中某个字段的值 作为 键 返回新数组
*/
function arrayChangeKeyByField($list, $searchKey)
{
$arr = [];
if (!$searchKey) {
return $list;
}
foreach ($list as $k => $v) {
if (isset($v[$searchKey])) {
$arr[$v[$searchKey]] = $v;
}
}
return $arr ? $arr : $list;
}
/*
* 把数组中null的字符串转为空
*/
function conversionArray($arr)
{
if (empty($arr)) {
return $arr;
}
foreach ($arr as $k => $v) {
if (is_array($v)) {
$arr[$k] = conversionArray($v);
} else {
if ($v === null) {
$arr[$k] = "";
}
}
}
return $arr;
}
function dateDefault($time)
{
$time = intval($time);
if ($time) {
return date("Y-m-d H:i:s", $time);
}
return "";
}
/*
* 格式化数字 保留两位小数
* 应领导要求封装成了一个函数,次函数已废弃 参考函数decimal_number_format
*/
if (!function_exists('sprintf2')) {
function sprintf2($amount){
$amount = floatval(strval($amount));
$tmp = number_format($amount,2,".","");
return $tmp;
}
}
/*
* 格式化数字 保留6位小数
* 应领导要求封装成了一个函数,次函数已废弃 参考函数decimal_number_format
*/
if (!function_exists('sprintf6')) {
function sprintf6($amount){
$amount = floatval(strval($amount));
$tmp = number_format($amount,6,".","");
return $tmp;
}
}
/*
* 格式化数字 保留4位小数
* 应领导要求封装成了一个函数,次函数已废弃 参考函数decimal_number_format
*/
if (!function_exists('sprintf4')) {
function sprintf4($amount){
$amount = floatval(strval($amount));
$tmp = number_format($amount,4,".","");
return $tmp;
}
}
/**
* 通用格式化字符串为数字金额
* @$amount 需要格式化的数字或者字符串 1.2345
* @$digits 保留小数位数 1.23
* @$currency 币别 ¥12003.4567
* @$thousandsSymbol 千分位字符串隔开 1,200,3.4567
*
* define("DIGITS_TWO",2);
define("DIGITS_FOUR",4);
define("DIGITS_SIX",6);
*/
if (!function_exists('decimal_number_format')) {
function decimal_number_format($amount,$digits=DIGITS_TWO,$currency="",$thousandsSymbol=""){
$amount = floatval(strval($amount));
//格式化币别
if($currency){
$minus = $amount < 0 ? '-' : '';
$numerical = number_format(abs($amount),$digits,".",$thousandsSymbol);
$sign = \Arr::get(config("field.currency_sign"),intval($currency),"");
if (!empty($sign)) {
$numerical = $sign . $numerical;
}
return $minus ? $minus.$numerical : $numerical;
}else{
$numerical = number_format($amount,$digits,".","");
return $numerical;
}
}
}
if (!function_exists('printJson')) {
function printJson($data)
{
print_r(is_array($data) ? json_encode($data) : $data);
die;
}
}
if (!function_exists('drawLetter')) {
/*
* 格式化型号, echo DrawLetter("LMGAGA 质量 &&*****") 输出:LMGAGA
* @param $g string 关键词
*/
function drawLetter($g){
$g = preg_replace('/[\x{4e00}-\x{9fff}]+/u', '', $g);
$g = preg_replace('/[^A-Za-z0-9]+/', '', $g);
return strtoupper($g);
}
}
if (!function_exists('buildQuery')) {
function buildQuery($query, $where)
{
foreach ($where as $subWhere) {
if (count($subWhere) == 2) {
$fiels = $exp = $subWhere[0] ?? "";
$value = $subWhere[1] ?? null;
if (empty($fiels) || $value === null) {
continue;
}
if ($exp == "or") {
$query->orWhere(function ($q) use ($value) {
buildQuery($q, $value);
});
} else {
$query->where($subWhere[0], $subWhere[1]);
}
} else if (count($subWhere) == 3) {
$fiels = $subWhere[0] ?? "";
$exp = $subWhere[1] ?? null;
$value = $subWhere[2] ?? null;
if (empty($fiels) || $exp === null || $value === null) {
continue;
}
if ($exp == "in" && is_array($value) && !empty($value)) {
$query->whereIn($fiels, $value);
} else {
$query->where($fiels, $exp, $value);
}
}
}
return $query;
}
}
if (!function_exists('echoToSql')) {
function echoToSql($query){
$tmp = str_replace('?', '"'.'%s'.'"', $query->toSql());
$tmp = vsprintf($tmp, $query->getBindings());
dd($tmp);
}
}
/**
* Notes:提取数组中某个字段$searchkey作为键值,然后从数组中检索给定的键的所有值
* User: sl
* Date: 2022/5/25 15:39
* @param $arr
* @param $key
* @param $val
* @return array
*/
function flipArrayPluck($arr,$newKey,$seachKey){
$newArr = [];
foreach($arr as $v){
$newArr[$v[$newKey]][] = $v[$seachKey];
}
return $newArr;
}
This diff is collapsed. Click to expand it.
This diff could not be displayed because it is too large.
No preview for this file type
No preview for this file type
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 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
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.
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
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 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
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
This diff is collapsed. Click to expand it.
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