Initial commit

main
liutk 2024-06-06 10:08:04 +08:00
commit 21a291f1a6
608 changed files with 35309 additions and 0 deletions

18
.editorconfig 100644
View File

@ -0,0 +1,18 @@
root = true
[*]
charset = utf-8
end_of_line = lf
indent_size = 4
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true
[*.md]
trim_trailing_whitespace = false
[*.{yml,yaml}]
indent_size = 2
[docker-compose.yml]
indent_size = 4

59
.env.example 100644
View File

@ -0,0 +1,59 @@
APP_NAME=Laravel
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_URL=http://localhost
LOG_CHANNEL=stack
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
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
FILESYSTEM_DISK=public
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120
MEMCACHED_HOST=127.0.0.1
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_MAILER=smtp
MAIL_HOST=mailpit
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS="hello@example.com"
MAIL_FROM_NAME="${APP_NAME}"
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_HOST=
PUSHER_PORT=443
PUSHER_SCHEME=https
PUSHER_APP_CLUSTER=mt1
VITE_APP_NAME="${APP_NAME}"
VITE_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
VITE_PUSHER_HOST="${PUSHER_HOST}"
VITE_PUSHER_PORT="${PUSHER_PORT}"
VITE_PUSHER_SCHEME="${PUSHER_SCHEME}"
VITE_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

11
.gitattributes vendored 100644
View File

@ -0,0 +1,11 @@
* text=auto eol=lf
*.blade.php diff=html
*.css diff=css
*.html diff=html
*.md diff=markdown
*.php diff=php
/.github export-ignore
CHANGELOG.md export-ignore
.styleci.yml export-ignore

19
.gitignore vendored 100644
View File

@ -0,0 +1,19 @@
/.phpunit.cache
/node_modules
/public/build
/public/hot
/public/storage
/storage/*.key
/vendor
.env
.env.backup
.env.production
.phpunit.result.cache
Homestead.json
Homestead.yaml
auth.json
npm-debug.log
yarn-error.log
/.fleet
/.idea
/.vscode

5
README.md 100644
View File

@ -0,0 +1,5 @@
composer install
php artisan g:k
php artisan storage:link
php artisan admin:install
php artisan db:seed

View File

@ -0,0 +1,281 @@
<?php
namespace App\Admin;
use App\Models\Keyword;
use Slowlyo\OwlAdmin\Renderers\BaseRenderer;
use Slowlyo\OwlAdmin\Renderers\WangEditor;
class Components extends BaseRenderer {
/**
* 父级选择器
*/
public function parentControl($apiUrl = null, $name ='parent_id', $label = null, $labelField = 'name', $valueField = 'id')
{
return amisMake()->TreeSelectControl()->source($apiUrl)
->name($name)->label($label ?? __('admin.components.parent_select'))
->showIcon(false)
->labelField($labelField)
->valueField($valueField);
}
/**
* 排序字段
*/
public function sortControl($name ='sort', $label = null){
return amisMake()->NumberControl()
->name($name)->label($label ?? __('admin.components.order'))
->displayMode('enhance')
->value(0)
->min(0);
}
/**
* 2位小数输入框
*/
public function decimalControl($name ='decimal', $label = null){
return amisMake()->NumberControl()
->name($name)->label($label ?? __('admin.components.decimal'))
->kilobitSeparator(true)
->percision(2)
->step(0.01)
->value(0.00)
->min(0);
}
/**
* 富文本编辑器
*/
public function fuEditorControl($name ='content', $label = null, $height = 530)
{
return WangEditor::make()
->name($name)->label($label ?? __('admin.components.content'))
->height($height)
->excludeKeys(['group-video']);
}
/**
* 开关
*/
public function enableControl($name = 'is_enable', $label= null, $mode = 'horizontal'){
return amisMake()->SwitchControl()
->name($name)->label($label ?? __('admin.components.status'))
->mode($mode)
->onText(__('admin.components.status_map.enabled'))->offText(__('admin.components.status_map.disabled'));
}
/**
* 图片上传
*/
public function imageControl($name, $label){
return amis()->ImageControl($name, $label)
->joinValues(false)
->autoUpload(true)->maxSize('5*1024*1024');//不能大于5M
}
/**
* 图片上传,带裁剪
*/
public function cropImageControl($name, $label, $aspectRatio = null){
$cropImage = amis()->ImageControl($name, $label)->joinValues(false);
// if($aspectRatio){
$cropImage->crop([
'aspectRatio' => $aspectRatio ?? 1
]);
// }
$cropImage->autoUpload(true);
return $cropImage;
}
/**
* 普通文件上传
*/
public function fileControl($name, $label, $accept = '.txt', $multiple = false){
return amis()->FileControl($name, $label ?? __('admin.components.files'))
->multiple($multiple)
->joinValues(false)
->useChunk(false)
->maxSize(20*1024*1024)
->accept($accept);
}
public function chunkFileControl($name, $label, $accept = '*', $multiple = false){
return amis()->FileControl($name, $label ?? __('admin.components.files'))
->multiple($multiple)
->joinValues(false)
->useChunk(true)
->accept($accept)
->startChunkApi(admin_url('start_chunk_upload_file'))
->chunkApi(admin_url('save_chunk_upload_file'))
->finishChunkApi(admin_url('finish_chunk_upload_file'));
}
/**
* 标签选择
*/
public function keywordsTagControl($name = 'tags', $label= null, $pKey = null){
return amisMake()->TagControl()
->name($name)->label($label ?? __('admin.components.tag'))
->maxTagLength(0)
->options(Keyword::where('parent_key', $pKey)->pluck('name', 'id')->toArray());
}
public function keywordsTag($label = null, $color = null){
if($color){
$tag = amisMake()->Tag()->label($label ?? __('admin.components.tag'))
->displayMode('rounded')->style([
'color' => '#fff',
'backgroundColor' =>$color,
'borderColor' => $color
]);
}else{
$tag = amisMake()->Tag()->label($label ?? __('admin.components.tag'))
->displayMode('rounded')->color('inactive');
}
return $tag;
}
/**
* 生成统计图config
* 折线图或者柱状图
*/
public function chartLineBarConfig($title = null, array $x , array $y){
$yAxisData = [];
$seriesData = [];
$color = [];
if(!isset($y[0])){
$_y = $y;
$y = [0=>$_y];
}
$i = 0;
$tips = '{b0}';
foreach($y as $item) {
//调色盘
$color[] = $item['color'];
//tips
$tips.= '<br/> {a'.$i.'}: {c'.$i.'}'.($item['unit'] ?? '');
//纵坐标
$yAxisData[] = [
'name'=>($item['unit'] ?? ''),
'type' =>'value',
'axisTick' => true,
'alignTicks' => true,
'axisLine' => [
'show' => true,
'lineStyle' => [
'color' => $item['color'] ?? ''
]
],
'axisLabel'=> [
'formatter'=>'{value} '
]
];
//数据
$_series = [
'name' => $item['name'] ?? '',
'data' => $item['data'] ?? [],
'type' => $item['type'] ?? 'line',
'yAxisIndex' => $i,
];
switch($item['type']){
case 'line':
$_series = array_merge($_series, [
'smooth'=> true,
'symbol'=> 'none',
'lineStyle' => [
'color' => $item['color'] ?? ''
],
'areaStyle' => [
'color' => $item['color'] ?? ''
],
]);
break;
case 'bar':
$_series = array_merge($_series, [
]);
break;
}
$seriesData[] = $_series;
$i++;
}
return [
'color' => $color,
'title' => [
'text' => $title,
],
"tooltip" => [//提示
'trigger'=>'axis',//坐标轴触发
'axisPointer' => [
'type' => 'cross'
],
// 'formatter' => $tips
],
'grid' => [
'left' => '8%',
'right' => '8%',
],
'xAxis' => [
'type' => 'category',
'data' => $x,
],
'yAxis' => $yAxisData,
'series' => $seriesData
];
}
/**
* 散点图
*/
public function chartScatterConfig($title = null, array $x , array $y, array $yData = null){
$yAxisData = [];
$seriesData = [];
$color = [];
if($yData){
$yAxisData = [
'type' =>'category',
// 'splitLine'=>[
// 'show'=>true,
// 'lineStyle'=>[
// 'type'=>'dashed'
// ]
// ],
'axisTick' => [
'alignWithLabel'=>true
],
'data'=> $yData
];
}
$seriesData = $y;
return [
'color' => $color,
'title' => [
'text' => $title,
],
"tooltip" => [//提示
'trigger'=>'axis',//坐标轴触发
'axisPointer' => [
'type' => 'cross'
],
],
'xAxis' => [
'type' => 'category',
'data' => $x,
],
'yAxis' => $yAxisData,
'series' => $seriesData
];
}
/**
* 生成饼状图config
* -todo
*/
public function chartPieConfig(){
return ;
}
}

View File

@ -0,0 +1,97 @@
<?php
namespace App\Admin\Controllers;
use Slowlyo\OwlAdmin\Admin;
use Slowlyo\OwlAdmin\Renderers\Page;
use Slowlyo\OwlAdmin\Renderers\Form;
use Slowlyo\OwlAdmin\Controllers\AdminController;
use Slowlyo\OwlAdmin\Renderers\Operation;
use App\Services\Admin\AdService;
use App\Admin\Components;
use App\Models\Keyword;
use App\Models\Ad;
/**
* 广告管理
*
* @property AdService $service
*/
class AdController extends AdminController
{
protected string $serviceName = AdService::class;
public function list(): Page
{
$crud = $this->baseCRUD()->tableLayout('fixed')
->headerToolbar([
$this->createButton(),
...$this->baseHeaderToolBar(),
])
->filter($this->baseFilter()->labelWidth('80px')->body([
amis()->GroupControl()->mode('horizontal')->body([
amis()->TextControl('id', __('admin.ads.id'))
->placeholder(__('admin.id')),
amis()->TextControl('remark', __('admin.ads.remark'))
->placeholder(__('admin.ads.remark')),
Components::make()->parentControl(admin_url('api/keywords/tree-list?parent_name=banner_address&has_owner=0'), 'address', __('admin.ads.address'), 'name', 'key'),
amis()->SelectControl('enable', __('admin.ads.is_enable'))
->options([
1=>'开启',0=>'关闭'
]),
]),
amis()->GroupControl()->mode('horizontal')->body([
amis()->InputDatetimeRange()->label(__('admin.ads.published_at'))->name('published_at'),
amis()->InputDatetimeRange()->label(__('admin.created_at'))->name('created_at'),
]),
]))
->columns([
amis()->TableColumn('id', __('admin.ads.id'))->width('50px')->sortable(),
amis()->TableColumn('address', __('admin.ads.address'))->type('mapping')
->map(Keyword::allChildrenOfKey('banner_address')->pluck('name', 'key')->toArray())
->itemSchema(amis()->Tag()->label('${item}')->color(Admin::setting()->get('system_theme_setting')['theme_color'] ?? '#1677ff')),
amis()->TableColumn('sort', __('admin.ads.sort'))->quickEdit(
amis()->NumberControl()->min(0)->saveImmediately(true)
),
amis()->TableColumn('resource', __('admin.ads.resource'))->type('image')->height('50px')->width('150px')->enlargeAble(true),
amis()->TableColumn('remark', __('admin.ads.remark')),
amis()->TableColumn('published_at', __('admin.ads.published_at'))->remark(__('admin.ads.published_at_remark')),
amis()->TableColumn('is_enable', __('admin.ads.is_enable'))->type('switch'),
amis()->TableColumn('created_at', __('admin.created_at'))->type('datetime')->sortable(true),
Operation::make()->label(__('admin.actions'))->buttons([
$this->rowEditButton(),
$this->rowDeleteButton(),
])
]);
return $this->baseList($crud);
}
public function form($isEdit = false): Form
{
return $this->baseForm()->body([
Components::make()->parentControl(admin_url('api/keywords/tree-list?parent_name=banner_address&has_owner=0'), 'address', __('admin.ads.address'), 'name', 'key')->required(true),
Components::make()->imageControl('resource', __('admin.ads.resource'))->required(true),
amis()->TextControl('remark', __('admin.ads.remark')),
Components::make()->sortControl('sort', __('admin.ads.sort')),
amis()->DateTimeControl('published_at', __('admin.ads.published_at'))->format('YYYY-MM-DD HH:mm:ss')->description(__('admin.ads.published_at_remark')),
amis()->SwitchControl('is_enable', __('admin.ads.is_enable'))->value(false),
amis()->RadiosControl('jump_type', __('admin.ads.jump_type'))->selectFirst(true)->options(Ad::jumpTypeMap())->required(true),
amis()->TextControl('jump_config.web_link', __('admin.ads.jump_config_arr.web_link'))->visibleOn('this.jump_type == '.Ad::TYPE_WEB)->required(true),
amis()->TextControl('jump_config.app_link', __('admin.ads.jump_config_arr.app_link'))->visibleOn('this.jump_type == '.Ad::TYPE_APP)->required(true),
amis()->GroupControl()->body([
amis()->TextControl('jump_config.mini_id', __('admin.ads.jump_config_arr.mini_id'))->visibleOn('this.jump_type == '.Ad::TYPE_MINI)->required(true),
amis()->TextControl('jump_config.mini_link', __('admin.ads.jump_config_arr.mini_link'))->visibleOn('this.jump_type == '.Ad::TYPE_MINI)->required(true),
]),
]);
}
public function detail(): Form
{
return $this->baseDetail()->body([
amis()->TextControl('id', 'ID')->static(),
amis()->TextControl('created_at', __('admin.created_at'))->static(),
amis()->TextControl('updated_at', __('admin.updated_at'))->static()
]);
}
}

View File

@ -0,0 +1,50 @@
<?php
namespace App\Admin\Controllers;
use Slowlyo\OwlAdmin\Renderers\Page;
use Slowlyo\OwlAdmin\Controllers\AdminRoleController as AdminRoleBaseController;
class AdminRoleController extends AdminRoleBaseController
{
public function list(): Page
{
$crud = $this->baseCRUD()
->headerToolbar([
$this->createButton(true),
...$this->baseHeaderToolBar(),
])
->filterTogglable(false)
->itemCheckableOn('${id !== 1}')
->columns([
amis()->TableColumn()->label('ID')->name('id')->sortable(),
amis()->TableColumn()->label(__('admin.admin_role.name'))->name('name'),
amis()->TableColumn()->label(__('admin.admin_role.slug'))->name('slug')->type('tag'),
amis()->TableColumn()
->label(__('admin.created_at'))
->name('created_at')
->type('datetime')
->sortable(true),
amis()->TableColumn()
->label(__('admin.updated_at'))
->name('updated_at')
->type('datetime')
->sortable(true),
amis()->Operation()->label(__('admin.actions'))->buttons([
$this->setPermission()->visibleOn('${slug != "administrator"}'),
$this->rowEditButton(true)->visibleOn('${slug != "administrator"}'),
$this->rowDeleteButton()->visibleOn('${slug != "administrator"}'),
]),
]);
return $this->baseList($crud)->css([
'.tree-full' => [
'overflow' => 'hidden !important',
],
'.cxd-TreeControl > .cxd-Tree' => [
'height' => '100% !important',
'max-height' => '100% !important',
],
]);
}
}

View File

@ -0,0 +1,99 @@
<?php
namespace App\Admin\Controllers;
use Slowlyo\OwlAdmin\Renderers\Page;
use Slowlyo\OwlAdmin\Renderers\Form;
use Slowlyo\OwlAdmin\Renderers\Operation;
use Slowlyo\OwlAdmin\Renderers\SwitchControl;
use Slowlyo\OwlAdmin\Renderers\TableColumn;
use App\Services\Admin\AdminUserService;
use Slowlyo\OwlAdmin\Services\AdminRoleService;
use Slowlyo\OwlAdmin\Controllers\AdminController;
/**
* @property AdminUserService $service
*/
class AdminUserController extends AdminController
{
protected string $serviceName = AdminUserService::class;
public function list(): Page
{
$crud = $this->baseCRUD()
->headerToolbar([
$this->createButton(true),
...$this->baseHeaderToolBar(),
])
->filter($this->baseFilter()->body(
amisMake()->TextControl('keyword', __('admin.keyword'))
->size('md')
->placeholder(__('admin.admin_user.search_username'))
))
->quickSaveItemApi(admin_url('quick-edit/admin_users/$id'))
->itemCheckableOn('${id !== 1}')
->columns([
amisMake()->TableColumn('id', 'ID')->sortable(),
amisMake()->TableColumn('avatar', __('admin.admin_user.avatar'))->type('avatar')->src('${avatar}'),
amisMake()->TableColumn('username', __('admin.username')),
amisMake()->TableColumn('name', __('admin.admin_user.name')),
amisMake()->TableColumn('roles', __('admin.admin_user.roles'))->type('each')->items(
amisMake()->Tag()->label('${name}')->className('my-1')
),
amisMake()->TableColumn('lock', __('admin.admin_user.lock'))->quickEdit(SwitchControl::make()->saveImmediately(true)->mode('inline')->disabledOn('${id === 1}')),
amisMake()->TableColumn('created_at', __('admin.created_at'))->type('datetime')->sortable(true),
Operation::make()->label(__('admin.actions'))->buttons([
$this->rowEditButton(true)->visibleOn('${id != 1}'),
//单独修改密码
$this->editPassword()->visibleOn('${id != 1}'),
$this->rowDeleteButton()->visibleOn('${id != 1}'),
]),
]);
return $this->baseList($crud);
}
public function form(): Form
{
return $this->baseForm()->body([
amisMake()->ImageControl('avatar', __('admin.admin_user.avatar'))->receiver($this->uploadImagePath()),
amisMake()->TextControl('name', __('admin.admin_user.name'))->required(),
amisMake()->TextControl('username', __('admin.username'))->required(),
amisMake()->TextControl('password', __('admin.password'))->type('input-password')->required()->validations(['minLength' => 6])->hiddenOn('${id > 0}'),
amisMake()->TextControl('confirm_password', __('admin.confirm_password'))->type('input-password')->required()->validations(['minLength' => 6])->hiddenOn('${id > 0}'),
amisMake()->SelectControl('roles', __('admin.admin_user.roles'))
->searchable()
->multiple()
->labelField('name')
->valueField('id')
->joinValues(false)
->extractValue()
->options(AdminRoleService::make()->query()->get(['id', 'name'])),
SwitchControl::make()->name('lock')->label(__('admin.admin_user.lock'))->value(false),
]);
}
public function detail(): Form
{
return $this->baseDetail()->body([]);
}
public function editPassword()
{
return amisMake()->DialogAction()->icon('fa-regular fa-lightbulb')->label(__('admin.admin_user.edit_password'))->level('link')->dialog(
amisMake()->Dialog()->title(__('admin.admin_user.edit_password'))->body([
amisMake()->Form()->title('')
->api([
'method'=>'PUT',
'url'=> admin_url('system/admin_users/$id')
])
->body([
amisMake()->TextControl('id')->value('${id}')->hidden(true),
amisMake()->TextControl('username')->value('${username}')->hidden(true),
amisMake()->TextControl('password', __('admin.password'))->type('input-password')->required()->validations(['minLength' => 6]),
amisMake()->TextControl('confirm_password', __('admin.confirm_password'))->type('input-password')->required()->validations(['minLength' => 6]),
]),
])->size('md')
);
}
}

View File

@ -0,0 +1,109 @@
<?php
namespace App\Admin\Controllers;
use App\Casts\Storage;
use Slowlyo\OwlAdmin\Admin;
use Slowlyo\OwlAdmin\Renderers\Page;
use Slowlyo\OwlAdmin\Renderers\Form;
use Slowlyo\OwlAdmin\Controllers\AdminController;
use App\Services\Admin\ArticleService;
use App\Admin\Components;
use App\Models\Keyword;
use App\Traits\CustomActionTrait;
class ArticleController extends AdminController
{
use CustomActionTrait;
protected string $serviceName = ArticleService::class;
public function list():Page
{
$crud = $this->baseCRUD()->tableLayout('fixed')
->headerToolbar([
$this->createTypeButton('drawer', 'xl'),
...$this->baseHeaderToolBar(),
])
->filter($this->baseFilter()->body([
amis()->GroupControl()->mode('horizontal')->body([
amis()->TextControl('id', __('admin.articles.id'))
->placeholder(__('admin.id')),
amis()->TextControl('title', __('admin.articles.title'))
->placeholder(__('admin.articles.title')),
Components::make()->parentControl(admin_url('api/keywords/tree-list?parent_name=article_category&has_owner=0'), 'category', __('admin.articles.category'), 'name', 'key'),
Components::make()->keywordsTagControl('t_ids', __('admin.articles.tags'), 'article_tag'),
]),
amis()->GroupControl()->mode('horizontal')->body([
amis()->SelectControl('enable', __('admin.articles.is_enable'))
->columnRatio(3)
->options([
1=>'开启',0=>'关闭'
]),
amis()->SelectControl('recommend', __('admin.articles.is_recommend'))
->columnRatio(3)
->options([
1=>'开启',0=>'关闭'
]),
amis()->InputDatetimeRange()->label(__('admin.articles.published_at'))->name('published_at'),
]),
amis()->GroupControl()->mode('horizontal')->body([
amis()->InputDatetimeRange()->label(__('admin.created_at'))->name('created_at')->columnRatio(6),
]),
]))
->itemBadge([//行角标
'text' => __('admin.articles.is_recommend'),
'mode' => 'ribbon',
'position' => 'top-left',
'badgeLevel' => 'danger',
'visibleOn' => '${is_recommend > 0}',
'size' => 15
])
->columns([
amis()->TableColumn('id', __('admin.id'))->sortable(true),
amis()->TableColumn('title', __('admin.articles.title'))->width('300px'),
amis()->TableColumn('category', __('admin.articles.category'))->type('mapping')
->map(Keyword::allChildrenOfKey('article_category')->pluck('name', 'key')->toArray())
->itemSchema(amis()->Tag()->label('${item}')->color(Admin::setting()->get('system_theme_setting')['theme_color'] ?? '#1677ff')),
amis()->TableColumn('tags', __('admin.articles.tags'))->type('mapping')->map(Keyword::tagsMap('article_tag')),
amis()->TableColumn('cover', __('admin.articles.cover'))->type('image')->height('50px')->width('50px')->enlargeAble(true),
amis()->TableColumn('published_at', __('admin.articles.published_at'))->remark(__('admin.articles.published_at_remark')),
amis()->TableColumn('is_enable', __('admin.articles.is_enable'))->type('switch'),
amis()->TableColumn('is_recommend', __('admin.articles.is_recommend'))->type('switch'),
amis()->TableColumn('created_at', __('admin.created_at'))->type('datetime')->sortable(true),
amis()->Operation()->label(__('admin.actions'))->buttons([
$this->rowEditTypeButton('drawer', 'xl'),
$this->rowDeleteButton(),
])
]);
return $this->baseList($crud);
}
public function form(): Form
{
return $this->baseForm()->panelClassName('px-0')->body([
amis()->Grid()->columns([
amis()->Wrapper()->body([
amis()->TextControl('title', __('admin.articles.title'))->required(true),
Components::make()->parentControl(admin_url('api/keywords/tree-list?parent_name=article_category&has_owner=0'), 'category', __('admin.articles.category'), 'name', 'key'),
Components::make()->keywordsTagControl('t_ids', __('admin.articles.tags'), 'article_tag'),
Components::make()->cropImageControl('cover', __('admin.articles.cover')),
Components::make()->sortControl('sort', __('admin.articles.sort')),
amis()->DateTimeControl('published_at', __('admin.articles.published_at'))->format('YYYY-MM-DD HH:mm:ss')->description(__('admin.articles.published_at_remark')),
amis()->SwitchControl('is_enable', __('admin.articles.is_enable'))->value(false),
amis()->SwitchControl('is_recommend', __('admin.articles.is_recommend'))->value(false),
Components::make()->fileControl('appendixes', __('admin.articles.appendixes'), '.xsl,.xlsx,.txt,.doc,.docx,.pdf,.pptx'),
])->md(4),
amis()->Wrapper()->body([
Components::make()->fuEditorControl('content', __('admin.articles.content')),
])->md(8)
]),
]);
}
public function detail(): Form
{
return $this->baseDetail()->body([]);
}
}

View File

@ -0,0 +1,57 @@
<?php
namespace App\Admin\Controllers;
use Slowlyo\OwlAdmin\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Symfony\Component\HttpFoundation\Response;
use Slowlyo\OwlAdmin\Models\AdminUser;
use Slowlyo\OwlAdmin\Controllers\AuthController as AdminAuthController;
use Illuminate\Support\Facades\Hash;
class AuthController extends AdminAuthController
{
public function login(Request $request)
{
if (Admin::config('admin.auth.login_captcha')) {
if (!$request->has('captcha')) {
return $this->response()->fail(__('admin.required', ['attribute' => __('admin.captcha')]));
}
if (strtolower(cache()->pull($request->sys_captcha)) != strtolower($request->captcha)) {
return $this->response()->fail(__('admin.captcha_error'));
}
}
try {
$validator = Validator::make($request->all(), [
'username' => 'required',
'password' => 'required',
], [
'username' . '.required' => __('admin.required', ['attribute' => __('admin.username')]),
'password.required' => __('admin.required', ['attribute' => __('admin.password')]),
]);
if ($validator->fails()) {
abort(Response::HTTP_BAD_REQUEST, $validator->errors()->first());
}
$adminModel = Admin::config("admin.auth.model", AdminUser::class);
$user = $adminModel::query()->where('username', $request->username)->first();
if($user && $user->lock){
abort(Response::HTTP_BAD_REQUEST, '您的账号已被锁定,需要联系超级管理员解锁。');
}else{
if ($user && Hash::check($request->password, $user->password)) {
$module = Admin::currentModule(true);
$prefix = $module ? $module . '.' : '';
$token = $user->createToken($prefix . 'admin')->plainTextToken;
return $this->response()->success(compact('token'), __('admin.login_successful'));
}
abort(Response::HTTP_BAD_REQUEST, __('admin.login_failed'));
}
} catch (\Exception $e) {
return $this->response()->fail($e->getMessage());
}
}
}

View File

@ -0,0 +1,282 @@
<?php
namespace App\Admin\Controllers;
use Illuminate\Http\JsonResponse;
use Slowlyo\OwlAdmin\Renderers\Card;
use Slowlyo\OwlAdmin\Renderers\Flex;
use Slowlyo\OwlAdmin\Renderers\Html;
use Slowlyo\OwlAdmin\Renderers\Grid;
use Slowlyo\OwlAdmin\Renderers\Chart;
use Slowlyo\OwlAdmin\Renderers\Image;
use Slowlyo\OwlAdmin\Renderers\Action;
use Slowlyo\OwlAdmin\Renderers\Custom;
use Slowlyo\OwlAdmin\Renderers\Wrapper;
use Illuminate\Http\Resources\Json\JsonResource;
use Slowlyo\OwlAdmin\Controllers\AdminController;
class HomeController extends AdminController
{
public function index(): JsonResponse|JsonResource
{
$page = $this->basePage()->css($this->css())->body([
Grid::make()->columns([
$this->frameworkInfo()->md(5),
Flex::make()->items([
$this->pieChart(),
$this->cube(),
]),
]),
Grid::make()->columns([
$this->lineChart()->md(8),
Flex::make()->className('h-full')->items([
$this->clock(),
$this->hitokoto(),
])->direction('column'),
]),
]);
return $this->response()->success($page);
}
/**
* 一言
*/
public function hitokoto()
{
return Card::make()
->className('h-full clear-card-mb')
->body(
Custom::make()->html(<<<HTML
<div class="h-full flex flex-col mt-5 py-5 px-7">
<div>『</div>
<div class="flex flex-1 items-center w-full justify-center" id="hitokoto">
<a class="text-dark" href="#" id="hitokoto_text" target="_blank"></a>
</div>
<div class="flex justify-end">』</div>
</div>
<div class="flex justify-end mt-3">
——&nbsp;
<span id="hitokoto_from_who"></span>
<span>「</span>
<span id="hitokoto_from"></span>
<span>」</span>
</div>
HTML
)->onMount(<<<JS
fetch('https://v1.hitokoto.cn?c=i')
.then(response => response.json())
.then(data => {
const hitokoto = document.querySelector('#hitokoto_text')
hitokoto.href = `https://hitokoto.cn/?uuid=\${data.uuid}`
hitokoto.innerText = data.hitokoto
document.querySelector('#hitokoto_from_who').innerText = data.from_who
document.querySelector('#hitokoto_from').innerText = data.from
})
.catch(console.error)
JS
)
);
}
public function clock(): Card
{
return Card::make()->className('h-full bg-blingbling')->header([
'title' => '时钟',
])->body([
Custom::make()
->name('clock')
->html('<div id="clock" class="text-4xl"></div><div id="clock-date" class="mt-5"></div>')
->onMount(<<<JS
const clock = document.getElementById('clock');
const tick = () => {
clock.innerHTML = (new Date()).toLocaleTimeString();
requestAnimationFrame(tick);
};
tick();
const clockDate = document.getElementById('clock-date');
clockDate.innerHTML = (new Date()).toLocaleDateString();
JS
),
]);
}
public function frameworkInfo(): Card
{
return Card::make()->className('h-96')->body(
Wrapper::make()->className('h-full')->body([
Flex::make()->className('h-full')->direction('column')->justify('center')->alignItems('center')->items([
Image::make()->src(url(config('admin.logo'))),
Wrapper::make()->className('text-3xl mt-9')->body(config('admin.name')),
Flex::make()->className('w-64 mt-5')->justify('space-around')->items([
Action::make()
->level('link')
->label('GitHub')
->blank(true)
->actionType('url')
->blank(true)
->link('https://github.com/slowlyo/owl-admin'),
Action::make()
->level('link')
->label('OwlAdmin 文档')
->blank(true)
->actionType('url')
->link('http://doc.owladmin.com'),
Action::make()
->level('link')
->label('Amis 文档')
->blank(true)
->actionType('url')
->link('https://aisuda.bce.baidu.com/amis/zh-CN/docs/index'),
]),
]),
])
);
}
public function pieChart(): Card
{
return Card::make()->className('h-96')->body(
Chart::make()->height(350)->config("{
backgroundColor:'',
tooltip: { trigger: 'item' },
legend: { bottom: 0, left: 'center' },
series: [
{
name: 'Access From',
type: 'pie',
radius: ['40%', '70%'],
avoidLabelOverlap: false,
itemStyle: { borderRadius: 10, borderColor: '#fff', borderWidth: 2 },
label: { show: false, position: 'center' },
emphasis: {
label: { show: true, fontSize: '40', fontWeight: 'bold' }
},
labelLine: { show: false },
data: [
{ value: 1048, name: 'Search Engine' },
{ value: 735, name: 'Direct' },
{ value: 580, name: 'Email' },
{ value: 484, name: 'Union Ads' },
{ value: 300, name: 'Video Ads' }
]
}
]
}")
);
}
public function lineChart(): Card
{
$randArr = function () {
$_arr = [];
for ($i = 0; $i < 7; $i++) {
$_arr[] = random_int(10, 200);
}
return '[' . implode(',', $_arr) . ']';
};
$random1 = $randArr();
$random2 = $randArr();
$chart = Chart::make()->height(380)->className('h-96')->config("{
backgroundColor:'',
title:{ text: '会员增长情况', },
tooltip: { trigger: 'axis' },
xAxis: { type: 'category', boundaryGap: false, data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] },
yAxis: { type: 'value' },
grid:{ left: '7%', right:'3%', top: 60, bottom: 30, },
legend: { data: ['访问量','注册量'] },
series: [
{ name: '访问量', data: {$random1}, type: 'line', areaStyle: {}, smooth: true, symbol: 'none', },
{ name:'注册量', data: {$random2}, type: 'line', areaStyle: {}, smooth: true, symbol: 'none', },
]}");
return Card::make()->className('clear-card-mb')->body($chart);
}
public function cube(): Card
{
return Card::make()->className('h-96 ml-4 w-8/12')->body(
Html::make()->html(<<<HTML
<style>
.cube-box{ height: 300px; display: flex; align-items: center; justify-content: center; }
.cube { width: 100px; height: 100px; position: relative; transform-style: preserve-3d; animation: rotate 10s linear infinite; }
.cube:after {
content: '';
width: 100%;
height: 100%;
box-shadow: 0 0 50px rgba(0, 0, 0, 0.2);
position: absolute;
transform-origin: bottom;
transform-style: preserve-3d;
transform: rotateX(90deg) translateY(50px) translateZ(-50px);
background-color: rgba(0, 0, 0, 0.1);
}
.cube div {
background-color: rgba(64, 158, 255, 0.7);
position: absolute;
width: 100%;
height: 100%;
border: 1px solid rgb(27, 99, 170);
box-shadow: 0 0 60px rgba(64, 158, 255, 0.7);
}
.cube div:nth-child(1) { transform: translateZ(-50px); animation: shade 10s -5s linear infinite; }
.cube div:nth-child(2) { transform: translateZ(50px) rotateY(180deg); animation: shade 10s linear infinite; }
.cube div:nth-child(3) { transform-origin: right; transform: translateZ(50px) rotateY(270deg); animation: shade 10s -2.5s linear infinite; }
.cube div:nth-child(4) { transform-origin: left; transform: translateZ(50px) rotateY(90deg); animation: shade 10s -7.5s linear infinite; }
.cube div:nth-child(5) { transform-origin: bottom; transform: translateZ(50px) rotateX(90deg); background-color: rgba(0, 0, 0, 0.7); }
.cube div:nth-child(6) { transform-origin: top; transform: translateZ(50px) rotateX(270deg); }
@keyframes rotate {
0% { transform: rotateX(-15deg) rotateY(0deg); }
100% { transform: rotateX(-15deg) rotateY(360deg); }
}
@keyframes shade { 50% { background-color: rgba(0, 0, 0, 0.7); } }
</style>
<div class="cube-box">
<div class="cube">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
</div>
HTML
)
);
}
private function css(): array
{
return [
'.clear-card-mb' => [
'margin-bottom' => '0 !important',
],
'.cxd-Image' => [
'border' => '0',
],
'.bg-blingbling' => [
'color' => '#fff',
'background' => 'linear-gradient(to bottom right, #2C3E50, #FD746C, #FF8235, #ffff1c, #92FE9D, #00C9FF, #a044ff, #e73827)',
'background-repeat' => 'no-repeat',
'background-size' => '1000% 1000%',
'animation' => 'gradient 60s ease infinite',
],
'@keyframes gradient' => [
'0%{background-position:0% 0%}
50%{background-position:100% 100%}
100%{background-position:0% 0%}',
],
'.bg-blingbling .cxd-Card-title' => [
'color' => '#fff',
],
];
}
}

View File

@ -0,0 +1,12 @@
<?php
namespace App\Admin\Controllers;
use Slowlyo\OwlAdmin\Controllers\AdminController;
use App\Traits\UploadTrait;
class IndexController extends AdminController
{
use UploadTrait;
}

View File

@ -0,0 +1,72 @@
<?php
namespace App\Admin\Controllers;
use Slowlyo\OwlAdmin\Renderers\Page;
use Slowlyo\OwlAdmin\Renderers\Form;
use Slowlyo\OwlAdmin\Renderers\TableColumn;
use Slowlyo\OwlAdmin\Renderers\TextControl;
use Slowlyo\OwlAdmin\Controllers\AdminController;
use App\Services\Admin\KeywordService;
use App\Admin\Components;
use Illuminate\Http\Request;
class KeywordController extends AdminController
{
protected string $serviceName = KeywordService::class;
public function list(): Page
{
$crud = $this->baseCRUD()
//去掉分页-start
->loadDataOnce(true)
->footerToolbar([])
//去掉分页-end
->headerToolbar([
$this->createButton(true),
$this->exportAction(),
amis('reload')->align('right'),
amis('filter-toggler')->align('right'),
])
->filter($this->baseFilter()->body([
amis()->TextControl('name', __('admin.keyword'))
->size('md')
->placeholder(__('admin.keywords.search_name')),
amis()->TextControl('parent_name', __('admin.keywords.parent_keyword'))
->size('md')
->placeholder(__('admin.keywords.search_name'))
]
))
->columns([
// TableColumn::make()->name('id')->label('ID')->sortable(true),
TableColumn::make()->name('name')->label('名称'),
TableColumn::make()->name('key')->label('KEY')->copyable(true),
TableColumn::make()->name('value')->label('值'),
TableColumn::make()->name('sort')->label('排序'),
TableColumn::make()->name('created_at')->label('创建时间')->type('datetime')->sortable(true),
amisMake()->Operation()->label(__('admin.actions'))->buttons([
//按钮权限示例;
// amis()->action()->label('判断权限')->permission('keywords.custom', amis()->TextControl()->hidden()),
$this->rowEditButton(true),
$this->rowDeleteButton(),
]),
]);
return $this->baseList($crud);
}
public function form(): Form
{
return $this->baseForm()->body([
Components::make()->parentControl(admin_url('api/keywords/tree-list')),
TextControl::make()->name('name')->label('名称')->required(true),
TextControl::make()->name('key')->label('KEY')->required(true),
TextControl::make()->name('value')->label('值'),
amisMake()->NumberControl()->name('sort')->value(0)->min()->label('排序'),
]);
}
public function getTreeList(Request $request){
return $this->service->getTree();
}
}

View File

@ -0,0 +1,91 @@
<?php
namespace App\Admin\Controllers;
use Illuminate\Support\Arr;
use Illuminate\Http\Request;
use Slowlyo\OwlAdmin\Renderers\Tab;
use Slowlyo\OwlAdmin\Renderers\Tabs;
use Slowlyo\OwlAdmin\Renderers\Alert;
use Slowlyo\OwlAdmin\Renderers\InputKV;
use Slowlyo\OwlAdmin\Renderers\TextControl;
use Slowlyo\OwlAdmin\Controllers\AdminController;
class SettingController extends AdminController
{
public function index()
{
$page = $this->basePage()->body([
$this->form(),
]);
return $this->response()->success($page);
}
public function form()
{
return $this->baseForm(false)
->redirect('')->labelWidth('200px')
->api($this->getStorePath())
->data(settings()->all())
->body(
Tabs::make()->tabs([
Tab::make()->title('上传设置')->body([
amis()->RadiosControl('upload_disk', '上传驱动')->options([
'public'=>'本地存储',
'oss' => '阿里云OSS',
])->value('public')->required(true),
amis()->TextControl('oss_config.access_key_id', '阿里云AccessKeyId')->required(true)->size('lg')->visibleOn('${upload_disk == "oss"}'),
amis()->TextControl('oss_config.access_key_secret', '阿里云AccessKeySecret')->required(true)->size('lg')->visibleOn('${upload_disk == "oss"}'),
amis()->TextControl('oss_config.bucket', '对象存储Bucket')->required(true)->size('lg')->visibleOn('${upload_disk == "oss"}')->remark('示例: my-bucket'),
amis()->TextControl('oss_config.endpoint', '对象存储endpoint')->required(true)->size('lg')->visibleOn('${upload_disk == "oss"}')->remark('示例: oss-cn-shanghai.aliyuncs.com'),
amis()->TextControl('oss_config.domain', '自有域名')->size('lg')->visibleOn('${upload_disk == "oss"}')->remark('填写即启用 示例: my-domain.com'),
amis()->SwitchControl('oss_config.use_ssl', '开启SSL')->value(false)->visibleOn('${upload_disk == "oss"}'),
]),
])
);
}
public function store(Request $request)
{
$data = $request->only([
'upload_disk',
'oss_config'
]);
//上传设置-修改env文件内配置;
if(!empty($data['upload_disk'])){
$envData['FILESYSTEM_DISK'] = $data['upload_disk'];
if($envData['FILESYSTEM_DISK'] == 'oss'){//如果设置为OSS驱动,则配置env变量
$envData['OSS_ACCESS_KEY_ID'] = Arr::get($data['oss_config'], 'access_key_id');
$envData['OSS_ACCESS_KEY_SECRET'] = Arr::get($data['oss_config'], 'access_key_secret');
$envData['OSS_BUCKET'] = Arr::get($data['oss_config'], 'bucket');
$envData['OSS_ENDPOINT'] = Arr::get($data['oss_config'], 'endpoint');
$envData['OSS_DOMAIN'] = Arr::get($data['oss_config'], 'domain');
if(!empty($envData['OSS_DOMAIN'])){
$envData['OSS_CNAME'] = 'true';
}else{
$envData['OSS_CNAME'] = 'false';
}
$envData['OSS_SSL'] = Arr::get($data['oss_config'], 'use_ssl') ? 'true':'false';
}
$envPath = base_path() . DIRECTORY_SEPARATOR . '.env';
$contentArray = collect(file($envPath, FILE_IGNORE_NEW_LINES));
$contentArray->transform(function ($item) use ($envData){
foreach ($envData as $key => $value){
if(str_contains($item, $key)){
return $key . '=' . $value;
}
}
return $item;
});
$content = implode("\n", $contentArray->toArray());
\File::put($envPath, $content);
}
return settings()->adminSetMany($data);
}
}

View File

@ -0,0 +1,9 @@
<?php
use Slowlyo\OwlAdmin\Admin;
// Admin::styles([
// '.cxd-Panel-heading { border-width: 0; background: #4080ffc7 !important; }',
// // '.cxd-Panel {box-shadow: none; }',
// '.cxd-Panel-title { color:white;font-size: 16px; }'
// ]);

View File

@ -0,0 +1,43 @@
<?php
use Illuminate\Routing\Router;
use Illuminate\Support\Facades\Route;
Route::group([
'domain' => config('admin.route.domain'),
'prefix' => config('admin.route.prefix'),
'middleware' => config('admin.route.middleware'),
], function (Router $router) {
$router->group([
'prefix' => 'api',
], function (Router $router) {
$router->get('keywords/tree-list', '\App\Admin\Controllers\KeywordController@getTreeList')->name('api.keywords.tree-list');
});
$router->resource('index', \App\Admin\Controllers\HomeController::class);
$router->post('login', [App\Admin\Controllers\AuthController::class, 'login']);
$router->resource('system/admin_users', App\Admin\Controllers\AdminUserController::class);
$router->post('quick-edit/admin_users/{admin_user}',[\App\Admin\Controllers\AdminUserController::class, 'update']);
$router->get('system/admin_roles', [App\Admin\Controllers\AdminRoleController::class, 'index']);
$router->resource('system/settings', \App\Admin\Controllers\SettingController::class);
$router->resource('system/keywords', \App\Admin\Controllers\KeywordController::class);
$router->resource('articles', \App\Admin\Controllers\ArticleController::class);
$router->resource('ads', \App\Admin\Controllers\AdController::class);
//修改上传
$router->post('upload_file', [\App\Admin\Controllers\IndexController::class, 'uploadFile']);
$router->post('upload_image', [\App\Admin\Controllers\IndexController::class, 'uploadImage']);
$router->post('upload_rich', [\App\Admin\Controllers\IndexController::class, 'uploadRich']);
$router->post('start_chunk_upload_file', [\App\Admin\Controllers\IndexController::class, 'startChunk']);
$router->post('save_chunk_upload_file', [\App\Admin\Controllers\IndexController::class, 'saveChunk']);
$router->post('finish_chunk_upload_file', [\App\Admin\Controllers\IndexController::class, 'finishChunk']);
});

View File

@ -0,0 +1,45 @@
<?php
namespace App\Casts;
use Slowlyo\OwlAdmin\Admin;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Storage as StorageFacades;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
/**
* 转换文件存储路径
*
* get: 返回全路径
* set: 原样保存
*/
class Storage implements CastsAttributes
{
/**
* Cast the given value.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @param string $key
* @param mixed $value
* @param array $attributes
* @return array
*/
public function get($model, $key, $value, $attributes)
{
return $value ? (Str::startsWith($value, ['http://', 'https://']) ? $value : StorageFacades::disk(Admin::config('admin.upload.disk'))->url($value)) : '';
}
/**
* Prepare the given value for storage.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @param string $key
* @param array $value
* @param array $attributes
* @return string
*/
public function set($model, $key, $value, $attributes)
{
return $value;
}
}

View File

@ -0,0 +1,27 @@
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* Define the application's command schedule.
*/
protected function schedule(Schedule $schedule): void
{
// $schedule->command('inspire')->hourly();
}
/**
* Register the commands for the application.
*/
protected function commands(): void
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}

View File

@ -0,0 +1,30 @@
<?php
namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
class Handler extends ExceptionHandler
{
/**
* The list of the inputs that are never flashed to the session on validation exceptions.
*
* @var array<int, string>
*/
protected $dontFlash = [
'current_password',
'password',
'password_confirmation',
];
/**
* Register the exception handling callbacks for the application.
*/
public function register(): void
{
$this->reportable(function (Throwable $e) {
//
});
}
}

View File

@ -0,0 +1,12 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
class Controller extends BaseController
{
use AuthorizesRequests, ValidatesRequests;
}

View File

@ -0,0 +1,68 @@
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array<int, class-string|string>
*/
protected $middleware = [
// \App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\TrustProxies::class,
\Illuminate\Http\Middleware\HandleCors::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
/**
* The application's route middleware groups.
*
* @var array<string, array<int, class-string|string>>
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
// \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
\Illuminate\Routing\Middleware\ThrottleRequests::class.':api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
/**
* The application's middleware aliases.
*
* Aliases may be used instead of class names to conveniently assign middleware to routes and groups.
*
* @var array<string, class-string|string>
*/
protected $middlewareAliases = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::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,
'precognitive' => \Illuminate\Foundation\Http\Middleware\HandlePrecognitiveRequests::class,
'signed' => \App\Http\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
}

View File

@ -0,0 +1,17 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Illuminate\Http\Request;
class Authenticate extends Middleware
{
/**
* Get the path the user should be redirected to when they are not authenticated.
*/
protected function redirectTo(Request $request): ?string
{
return $request->expectsJson() ? null : route('login');
}
}

View File

@ -0,0 +1,17 @@
<?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<int, string>
*/
protected $except = [
//
];
}

View File

@ -0,0 +1,17 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance as Middleware;
class PreventRequestsDuringMaintenance extends Middleware
{
/**
* The URIs that should be reachable while maintenance mode is enabled.
*
* @var array<int, string>
*/
protected $except = [
//
];
}

View File

@ -0,0 +1,30 @@
<?php
namespace App\Http\Middleware;
use App\Providers\RouteServiceProvider;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;
class RedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next, string ...$guards): Response
{
$guards = empty($guards) ? [null] : $guards;
foreach ($guards as $guard) {
if (Auth::guard($guard)->check()) {
return redirect(RouteServiceProvider::HOME);
}
}
return $next($request);
}
}

View File

@ -0,0 +1,19 @@
<?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<int, string>
*/
protected $except = [
'current_password',
'password',
'password_confirmation',
];
}

View File

@ -0,0 +1,20 @@
<?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<int, string|null>
*/
public function hosts(): array
{
return [
$this->allSubdomainsOfApplicationUrl(),
];
}
}

View File

@ -0,0 +1,28 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Middleware\TrustProxies as Middleware;
use Illuminate\Http\Request;
class TrustProxies extends Middleware
{
/**
* The trusted proxies for this application.
*
* @var array<int, string>|string|null
*/
protected $proxies;
/**
* The headers that should be used to detect proxies.
*
* @var int
*/
protected $headers =
Request::HEADER_X_FORWARDED_FOR |
Request::HEADER_X_FORWARDED_HOST |
Request::HEADER_X_FORWARDED_PORT |
Request::HEADER_X_FORWARDED_PROTO |
Request::HEADER_X_FORWARDED_AWS_ELB;
}

View File

@ -0,0 +1,22 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Routing\Middleware\ValidateSignature as Middleware;
class ValidateSignature extends Middleware
{
/**
* The names of the query string parameters that should be ignored.
*
* @var array<int, string>
*/
protected $except = [
// 'fbclid',
// 'utm_campaign',
// 'utm_content',
// 'utm_medium',
// 'utm_source',
// 'utm_term',
];
}

View File

@ -0,0 +1,17 @@
<?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<int, string>
*/
protected $except = [
//
];
}

85
app/Models/Ad.php 100644
View File

@ -0,0 +1,85 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use EloquentFilter\Filterable;
use App\Casts\Storage;
class Ad extends Model
{
use HasFactory;
use Filterable;
public const TYPE_OFF = 0; //无跳转
public const TYPE_WEB = 1; //网页跳转
public const TYPE_APP = 2; //应用跳转
public const TYPE_MINI = 3;//小程序跳转
protected function serializeDate(\DateTimeInterface $date)
{
return $date->format('Y-m-d H:i:s');
}
protected $casts = [
'created_at' => 'datetime',
'updated_at' => 'datetime',
'published_at' => 'datetime',
'is_enable' => 'boolean',
'jump_config' => 'array',
];
protected $fillable = [
'resource',
'address',
'remark',
'published_at',
'is_enable',
'sort',
'jump_type',
'jump_config',
];
public static function jumpTypeMap() :array
{
return [
self::TYPE_WEB => '网页跳转',
self::TYPE_APP => '应用跳转',
self::TYPE_MINI => '小程序跳转',
self::TYPE_OFF => '无跳转',
];
}
public static function jumpTypeMapLabel()
{
return [
self::TYPE_OFF => "<span class='label'>无跳转</span>",
self::TYPE_WEB => "<span class='label label-info'>网页跳转</span>",
self::TYPE_APP => "<span class='label label-warning'>应用跳转</span>",
self::TYPE_MINI => "<span class='label label-green'>小程序跳转</span>",
'*'=>'其他:${jump_type}'
];
}
public static function typeMapLabel()
{
return [
self::TYPE_IN => "<span class='label label-info'>入住缴费</span>",
self::TYPE_CONTINUE => "<span class='label label-warning'>续住缴费</span>",
self::TYPE_EXIT => "<span class='label label-danger'>离开结算</span>",
'*'=>'其他:${live_in}'
];
}
public function scopeShow(){
$q->where('is_enable', true)->where('published_at', '>=', now());
}
public function scopeSort($q)
{
$q->orderBy('sort', 'asc')
->orderBy('published_at', 'desc')
->orderBy('created_at', 'desc');
}
}

View File

@ -0,0 +1,63 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use EloquentFilter\Filterable;
use App\Casts\Storage;
class Article extends Model
{
use HasFactory;
use Filterable;
protected function serializeDate(\DateTimeInterface $date)
{
return $date->format('Y-m-d H:i:s');
}
protected $appends = ['tags'];
protected $casts = [
'created_at' => 'datetime:Y-m-d H:i:s',
'updated_at' => 'datetime:Y-m-d H:i:s',
'published_at' => 'datetime:Y-m-d H:i:s',
'is_enable' => 'boolean',
'is_recommend' => 'boolean',
'appendixes' => 'array',
];
protected $fillable = [
'title',
'content',
'cover',
'category',
't_ids',
'published_at',
'is_enable',
'is_recommend',
'sort',
'appendixes',
];
public function scopeShow(){
$q->where('is_enable', true)->where('published_at', '>=', now());
}
public function scopeSort($q)
{
$q->orderBy('is_recommend', 'desc')
->orderBy('sort', 'asc')
->orderBy('published_at', 'desc')
->orderBy('created_at', 'desc');
}
protected function tags():Attribute
{
return Attribute::make(
get: fn($value) => $this->t_ids ? explode(',', $this->t_ids) : [],
);
}
}

View File

@ -0,0 +1,63 @@
<?php
namespace App\Models\Filters;
use Illuminate\Support\Arr;
use EloquentFilter\ModelFilter;
class AdFilter extends ModelFilter
{
/**
* 主键
*/
public function id($id)
{
return $this->where('id', $id);
}
/**
* 备注
*/
public function remark($remark)
{
return $this->where('remark','like', '%'.$remark.'%');
}
/**
* 位置
*/
public function address($address)
{
return $this->where('address', $address);
}
public function publishedAt($publishedAt){
$publishedAt = explode(',',$publishedAt);
return $this->where(function($q) use ($publishedAt) {
$startAt = Arr::get($publishedAt, 0) ?? null;
$endAt = Arr::get($publishedAt, 1) ?? null;
if(!empty($startAt)){
$q->where('published_at', '>=', $startAt);
}
if(!empty($endAt)){
$q->where('published_at', '<=', $endAt);
}
});
}
public function createdAt($createdAt){
$createdAt = explode(',',$createdAt);
return $this->where(function($q) use ($createdAt) {
$startAt = Arr::get($createdAt, 0) ?? null;
$endAt = Arr::get($createdAt, 1) ?? null;
if(!empty($startAt)){
$q->where('created_at', '>=', $startAt);
}
if(!empty($endAt)){
$q->where('created_at', '<=', $endAt);
}
});
}
public function enable($enable){
return $this->where('is_enable', $enable);
}
}

View File

@ -0,0 +1,80 @@
<?php
namespace App\Models\Filters;
use EloquentFilter\ModelFilter;
use Illuminate\Support\Arr;
class ArticleFilter extends ModelFilter
{
/**
* 主键
*/
public function id($id)
{
return $this->where('id', $id);
}
/**
* 标题
*/
public function title($title)
{
return $this->where('title','like', '%'.$title.'%');
}
/**
* 获取分类下的文章
*/
public function category($category)
{
return $this->where('category', $category);
}
/**
* 查询带有标签的文章
*/
public function tIds($tIds){
$tIds = explode(',',$tIds);
return $this->where(function($q) use ($tIds) {
foreach ($tIds as $tId) {
$q->whereRaw("FIND_IN_SET('".$tId."',t_ids)");
}
});
}
public function publishedAt($publishedAt){
$publishedAt = explode(',',$publishedAt);
return $this->where(function($q) use ($publishedAt) {
$startAt = Arr::get($publishedAt, 0) ?? null;
$endAt = Arr::get($publishedAt, 1) ?? null;
if(!empty($startAt)){
$q->where('published_at', '>=', $startAt);
}
if(!empty($endAt)){
$q->where('published_at', '<=', $endAt);
}
});
}
public function createdAt($createdAt){
$createdAt = explode(',',$createdAt);
return $this->where(function($q) use ($createdAt) {
$startAt = Arr::get($createdAt, 0) ?? null;
$endAt = Arr::get($createdAt, 1) ?? null;
if(!empty($startAt)){
$q->where('created_at', '>=', $startAt);
}
if(!empty($endAt)){
$q->where('created_at', '<=', $endAt);
}
});
}
public function enable($enable){
return $this->where('is_enable', $enable);
}
public function recommend($recommend){
return $this->where('is_recommend', $recommend);
}
}

View File

@ -0,0 +1,31 @@
<?php
namespace App\Models\Filters;
use EloquentFilter\ModelFilter;
use App\Models\Keyword;
class KeywordFilter extends ModelFilter
{
/**
* 关键字
*/
public function name($name)
{
return $this->where('name','like', '%'.$name.'%')
->orWhere('key','like', '%'.$name.'%');
}
public function parentName($parent_name)
{
if(request('has_owner', 1)){
$this->where(function($q) use ($parent_name){
$q->where('name','like', '%'.$parent_name.'%')
->orWhere('key','like', '%'.$parent_name.'%');
});
}
return $this->orWhere('path','like', '%-'.
Keyword::where('name','like', '%'.$parent_name.'%')->orWhere('key','like', '%'.$parent_name.'%')->value('id')
. '-%' ?? '');
}
}

View File

@ -0,0 +1,76 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use EloquentFilter\Filterable;
use App\Admin\Components;
use Illuminate\Support\Str;
class Keyword extends Model
{
use HasFactory;
use Filterable;
protected $fillable = ['name', 'key', 'value', 'parent_id', 'parent_key', 'path', 'sort', 'lv'];
protected function serializeDate(\DateTimeInterface $date)
{
return $date->format('Y-m-d H:i:s');
}
protected static function boot()
{
parent::boot();
// 监听 Keyword 的创建事件,用于初始化 path 和 lv 字段值
static::saving(function ($keyword) {
// 如果创建的是一个根类目
if (! $keyword->parent_id) {
// 将层级设为 1
$keyword->lv = 1;
// 将 path 设为 -
$keyword->path = '-';
if(empty($keyword->key)){
$keyword->key = Str::quickRandom($length = 16);
}
} else {
// 将层级设为父类目的层级 + 1
$keyword->lv = $keyword->parent->lv + 1;
$keyword->parent_key = $keyword->parent->key;
// 将 path 值设为父类目的 path 追加父类目 ID 以及最后跟上一个 - 分隔符
$keyword->path = $keyword->parent->path.$keyword->parent_id.'-';
//当前key是否为空
if(empty($keyword->key)){
$keyword->key = $keyword->parent_key . '_' . (self::where('parent_key', $keyword->parent_key)->count() + 1);
}
}
});
}
public function parent()
{
return $this->belongsTo(static::class, 'parent_id');
}
public function children()
{
return $this->hasMany(static::class, 'parent_id');
}
public function scopeAllChildrenOfKey($q, $parentKey)
{
$q->where('path','like', '%-'.
static::where('key', $parentKey)->value('id')
. '-%' ?? '');
}
public static function tagsMap(String $key)
{
$mapArr = [];
self::query()->where('parent_key', $key)->get()->map(function($item) use (&$mapArr){
$mapArr[$item->id] = Components::make()->keywordsTag($item->name, $item->value);
});
return $mapArr;
}
}

View File

@ -0,0 +1,45 @@
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}

View File

@ -0,0 +1,25 @@
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
//
}
/**
* Bootstrap any application services.
*/
public function boot()
{
\Schema::defaultStringLength(191);
}
}

View File

@ -0,0 +1,26 @@
<?php
namespace App\Providers;
// use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* The model to policy mappings for the application.
*
* @var array<class-string, class-string>
*/
protected $policies = [
//
];
/**
* Register any authentication / authorization services.
*/
public function boot(): void
{
//
}
}

View File

@ -0,0 +1,19 @@
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Broadcast;
use Illuminate\Support\ServiceProvider;
class BroadcastServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Broadcast::routes();
require base_path('routes/channels.php');
}
}

View File

@ -0,0 +1,38 @@
<?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 to listener mappings for the application.
*
* @var array<class-string, array<int, class-string>>
*/
protected $listen = [
Registered::class => [
SendEmailVerificationNotification::class,
],
];
/**
* Register any events for your application.
*/
public function boot(): void
{
//
}
/**
* Determine if events and listeners should be automatically discovered.
*/
public function shouldDiscoverEvents(): bool
{
return false;
}
}

View File

@ -0,0 +1,67 @@
<?php
namespace App\Providers;
use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Database\Events\TransactionBeginning;
use Illuminate\Database\Events\TransactionCommitted;
use Illuminate\Database\Events\TransactionRolledBack;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\ServiceProvider;
class QueryLoggerServiceProvider extends ServiceProvider
{
/**
* {@inheritdoc}
*/
public function boot()
{
if (! config('app.debug')) {
return;
}
$this->app['events']->listen([
QueryExecuted::class,
TransactionBeginning::class,
TransactionCommitted::class,
TransactionRolledBack::class,
], function ($event) {
Log::debug(match (true) {
$event instanceof TransactionBeginning => 'begin transaction',
$event instanceof TransactionCommitted => 'commit transaction',
$event instanceof TransactionRolledBack => 'rollback transaction',
default => $this->prepareSql($event),
});
});
}
/**
* @param \Illuminate\Database\Events\QueryExecuted $query
* @return string
*/
protected function prepareSql(QueryExecuted $query): string
{
$sql = str_replace(['%', '?'], ['%%', '%s'], $query->sql);
$bindings = $query->connection->prepareBindings($query->bindings);
if (count($bindings)) {
$sql = vsprintf($sql, array_map([$query->connection->getPdo(), 'quote'], $bindings));
}
return sprintf('[%s] %s', $this->formatDuration($query->time), $sql);
}
/**
* @param float $milliseconds
* @return string
*/
protected function formatDuration($milliseconds): string
{
return match (true) {
$milliseconds >= 1000 => round($milliseconds / 1000, 2).'s',
$milliseconds < 0.01 => round($milliseconds * 1000).'μs',
default => $milliseconds.'ms',
};
}
}

View File

@ -0,0 +1,40 @@
<?php
namespace App\Providers;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;
class RouteServiceProvider extends ServiceProvider
{
/**
* The path to your application's "home" route.
*
* Typically, users are redirected here after authentication.
*
* @var string
*/
public const HOME = '/home';
/**
* Define your route model bindings, pattern filters, and other route configuration.
*/
public function boot(): void
{
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
});
$this->routes(function () {
Route::middleware('api')
->prefix('api')
->group(base_path('routes/api.php'));
Route::middleware('web')
->group(base_path('routes/web.php'));
});
}
}

View File

@ -0,0 +1,114 @@
<?php
namespace App\Services\Admin;
use App\Models\Ad;
use App\Models\Filters\AdFilter;
use App\Traits\UploadTrait;
use Illuminate\Support\Arr;
/**
* @method Ad getModel()
* @method Ad|\Illuminate\Database\Query\Builder query()
*/
class AdService extends BaseService
{
use UploadTrait;
protected string $modelName = Ad::class;
protected string $modelFilterName = AdFilter::class;
protected bool $modelSortAble = true;
public function store($data): bool
{
$columns = $this->getTableColumns();
$model = $this->getModel();
$isEnable = Arr::get($data, 'is_enabled');
$publishedAt = Arr::get($data, 'published_at');
if ($isEnable && empty($publishedAt)) {
$data['published_at'] = now();
}
if(isset($data['resource'])){
$data['resource'] = $this->saveImage('resource', 'ads/resource')[0];
}
//处理跳转配置
$jumpType = Arr::get($data, 'jump_type');
if($jumpType !== null){
switch($jumpType){
case Ad::TYPE_OFF:
$data['jump_config'] = null;
break;
case Ad::TYPE_WEB:
$data['jump_config'