NewsResource.php 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. <?php
  2. namespace App\Filament\Resources;
  3. use App\Filament\Resources\NewsResource\Pages;
  4. use App\Models\News;
  5. use App\Models\NewsCategory;
  6. use Filament\Forms\Components\Actions\Action;
  7. use Filament\Forms\Components\Group;
  8. use Filament\Forms\Components\Hidden;
  9. use Filament\Forms\Components\Repeater;
  10. use Filament\Forms\Components\RichEditor;
  11. use Filament\Forms\Components\Tabs;
  12. use Filament\Forms\Components\Tabs\Tab;
  13. use Filament\Forms\Components\TextInput;
  14. use Filament\Forms\Components\Textarea;
  15. use Filament\Forms\Components\Select;
  16. use Filament\Forms\Components\Radio;
  17. use Filament\Forms\Components\Section;
  18. use Filament\Forms\Components\Toggle;
  19. use Filament\Forms\Components\DatePicker;
  20. use Filament\Forms\Components\DateTimePicker;
  21. use Filament\Forms\Components\FileUpload;
  22. use Filament\Forms\Get;
  23. use Filament\Forms\Form;
  24. use Filament\Forms\Set;
  25. use Filament\Resources\Resource;
  26. use Filament\Tables;
  27. use Filament\Tables\Columns\IconColumn;
  28. use Filament\Tables\Columns\ImageColumn;
  29. use Filament\Tables\Columns\TextColumn;
  30. use Filament\Tables\Filters\SelectFilter;
  31. use Filament\Tables\Table;
  32. use Illuminate\Database\Eloquent\Builder;
  33. use Illuminate\Support\Facades\DB;
  34. use Illuminate\Support\Str;
  35. use Malzariey\FilamentLexicalEditor\Enums\ToolbarItem;
  36. use Malzariey\FilamentLexicalEditor\FilamentLexicalEditor;
  37. use SolutionForest\FilamentTranslateField\Forms\Component\Translate;
  38. use RalphJSmit\Filament\SEO\SEO;
  39. class NewsResource extends Resource
  40. {
  41. protected static ?string $model = News::class;
  42. protected static ?string $modelLabel = "文章管理";
  43. protected static ?string $navigationIcon = 'heroicon-o-newspaper';
  44. protected static ?string $navigationGroup = '上稿內容管理';
  45. protected static ?string $navigationLabel = "文章管理";
  46. public static function form(Form $form): Form
  47. {
  48. return $form
  49. ->schema([
  50. //
  51. Section::make("新增 文章")->schema([
  52. Group::make()->schema([
  53. Select::make("news_category_id")
  54. ->options(NewsCategory::get()->pluck("name","id"))
  55. ->label("文章分類")
  56. ->columnSpan(1)
  57. ->native(false)
  58. ->afterStateHydrated(function ($component, $state) {
  59. // ✅ 如果沒有值,設定為第一項
  60. if (empty($state)) {
  61. $firstCategoryId = NewsCategory::first()?->id;
  62. if ($firstCategoryId) {
  63. $component->state($firstCategoryId);
  64. }
  65. }
  66. })
  67. ->required(),
  68. ])->columnSpanFull()->columns(2),
  69. Group::make()->schema([
  70. DatePicker::make('post_date')
  71. ->label("發布日期")
  72. ->closeOnDateSelection()->required(),
  73. DateTimePicker::make('start_date')
  74. ->label("預約發布時間")
  75. ->closeOnDateSelection(),
  76. DateTimePicker::make('end_date')
  77. ->label("預約下架時間")
  78. ->closeOnDateSelection(),
  79. ])->columnSpanFull()->columns(3),
  80. FileUpload::make('news_img_pc')->label("列表圖(desktop)")
  81. ->disk("public")
  82. // ->helperText('建議寬高限制為:1280*720px,檔案大小限制為1M以下')->maxSize('1024')
  83. ->directory("news"),
  84. FileUpload::make('news_img_mobile')->label("列表圖(mobile)")
  85. ->disk("public")
  86. // ->helperText('建議寬高限制為:600*896px,檔案大小限制為1M以下')->maxSize('1024')
  87. ->directory("news"),
  88. Translate::make()->schema(fn (string $locale) => [
  89. TextInput::make('title')
  90. ->label("標題")
  91. ->columnSpan(1),
  92. TextInput::make('written_by')
  93. ->label("發佈者")->columnSpan(1),
  94. Textarea::make("description")->rows(5)->columnSpanFull()->label("短文"),
  95. ])->locales(["zh_TW", "en"])
  96. ->id("main")
  97. ->columnSpanFull()->columns(3),
  98. TextInput::make('order')->label("排序")->integer()->default(0),
  99. ])->columns(3),
  100. Section::make("SEO")->schema([
  101. // SEO::make(),
  102. Translate::make()->schema(fn (string $locale) => [
  103. TextInput::make('meta_title')->label("SEO 標題")->columnSpan(1),
  104. Textarea::make("meta_keyword")->rows(5)->columnSpanFull()->label("SEO 關鍵字"),
  105. Textarea::make("meta_description")->rows(5)->columnSpanFull()->label("SEO 短文"),
  106. ])
  107. ->locales(["zh_TW", "en"])
  108. ->id("seo"),
  109. FileUpload::make('meta_img')->label("放大預覽圖")->disk("public")
  110. // ->helperText('建議寬高限制為:1200*630px,檔案大小限制為1M以下')->maxSize('1024')
  111. ->directory("seo/news"),
  112. ])->columnSpanFull(),
  113. Section::make("文章內容")->schema([
  114. Repeater::make("paragraphs")->schema([
  115. TextInput::make('item_key')
  116. ->default(fn () => Str::random())
  117. ->hidden()
  118. ->afterStateHydrated(function (TextInput $component, $state) {
  119. if (empty($state)) {
  120. $component->state(Str::random());
  121. }
  122. }),
  123. Radio::make("paragraph_type")->options([
  124. 1 => "圖片",
  125. 2 => "文字",
  126. 3 => "影音",
  127. ])->label("")->default(1)->Live(),
  128. Group::make()->schema([
  129. Section::make('')->schema([
  130. Repeater::make("multiple_images")->schema([
  131. TextInput::make('para_img_item_key')
  132. ->default(fn () => Str::random())
  133. ->hidden()
  134. ->afterStateHydrated(function (TextInput $component, $state) {
  135. if (empty($state)) {
  136. $component->state(Str::random());
  137. }
  138. }),
  139. Translate::make()->schema(fn (string $locale) => [
  140. TextInput::make('image_alt')->label("圖片註文"),
  141. ])->locales(["zh_TW", "en"])
  142. ->id(fn ($get) => "para_img_mul_" . $get('para_img_item_key')),
  143. FileUpload::make('image_url')->label("")->disk("public")
  144. // ->helperText('建議寬高限制為:1080*675px,檔案大小限制為1M以下')->maxSize('1024')
  145. ->directory("news/extraPhoto")
  146. ->maxFiles(10),
  147. ])
  148. ->relationship("photos")
  149. ->label("")
  150. ->orderColumn('order')
  151. ])
  152. ])->visible(fn (Get $get):bool => $get("paragraph_type") == 1),
  153. Group::make()->schema([
  154. FilamentLexicalEditor::make('text_content_tw')
  155. ->label('繁體中文內容')
  156. ->id(fn ($get) => "text_content_tw_" . $get('item_key') . "_" . uniqid())
  157. ->enabledToolbars([
  158. ToolbarItem::UNDO, ToolbarItem::REDO, ToolbarItem::NORMAL,
  159. ToolbarItem::H2, ToolbarItem::H3, ToolbarItem::H4, ToolbarItem::H5,
  160. ToolbarItem::BULLET, ToolbarItem::NUMBERED, ToolbarItem::FONT_SIZE,
  161. ToolbarItem::BOLD, ToolbarItem::ITALIC, ToolbarItem::UNDERLINE,
  162. ToolbarItem::LINK, ToolbarItem::TEXT_COLOR, ToolbarItem::BACKGROUND_COLOR,
  163. ToolbarItem::SUBSCRIPT, ToolbarItem::LOWERCASE, ToolbarItem::DIVIDER,
  164. ToolbarItem::UPPERCASE, ToolbarItem::CLEAR, ToolbarItem::HR
  165. ])
  166. ->live(onBlur: true)
  167. ->columnSpanFull(),
  168. FilamentLexicalEditor::make('text_content_en')
  169. ->label('English Content')
  170. ->id(fn ($get) => "text_content_en_" . $get('item_key') . "_" . uniqid())
  171. ->enabledToolbars([
  172. ToolbarItem::UNDO, ToolbarItem::REDO, ToolbarItem::NORMAL,
  173. ToolbarItem::H2, ToolbarItem::H3, ToolbarItem::H4, ToolbarItem::H5,
  174. ToolbarItem::BULLET, ToolbarItem::NUMBERED, ToolbarItem::FONT_SIZE,
  175. ToolbarItem::BOLD, ToolbarItem::ITALIC, ToolbarItem::UNDERLINE,
  176. ToolbarItem::LINK, ToolbarItem::TEXT_COLOR, ToolbarItem::BACKGROUND_COLOR,
  177. ToolbarItem::SUBSCRIPT, ToolbarItem::LOWERCASE, ToolbarItem::DIVIDER,
  178. ToolbarItem::UPPERCASE, ToolbarItem::CLEAR, ToolbarItem::HR
  179. ])
  180. ->columnSpanFull(),
  181. ])->visible(fn (Get $get):bool => $get("paragraph_type") == 2),
  182. Group::make()->schema([
  183. Section::make("")->schema([
  184. FileUpload::make('video_img')->label("影片底圖")
  185. ->disk("public")
  186. ->directory("news/paragraph/video"),
  187. // ->helperText('建議寬高限制為:2000*720px,出血寬度720px,主要圖像範圍為:1280*720px,檔案大小限制為1M以下')->maxSize('1024'),
  188. Translate::make()->schema(fn (string $locale) => [
  189. TextInput::make('video_img_alt')->label("圖片註文")->columnSpan(1),
  190. ])->locales(["zh_TW", "en"])
  191. ->id(fn ($get) => "para_video_img_alt_" . $get('item_key')),
  192. Radio::make("video_type")->label("")->options([
  193. 1 => "網址",
  194. 2 => "檔案"
  195. ])->columnSpanFull()->default(1)->Live(),
  196. Group::make()->schema([
  197. TextInput::make('link')->label("網址")->nullable(),
  198. ])->visible(fn (Get $get):bool => $get("video_type") == 1)->columnSpanFull(),
  199. Group::make()->schema([
  200. FileUpload::make('video_url')->label("")->disk("public")->directory("news/paragraph/video")
  201. // ->helperText('建議影片寬高限制為:1920*1080px,出血寬度720px,大小限制為:100M以下')
  202. // ->maxSize(102400)
  203. ->nullable(),
  204. ])->visible(fn (Get $get):bool => $get("video_type") == 2)->columnSpanFull(),
  205. ]),
  206. ])->visible(fn (Get $get):bool => $get("paragraph_type") == 3),
  207. ])
  208. ->relationship("paragraphs")
  209. ->label("段落")
  210. ->collapsible()
  211. ->reorderableWithButtons()
  212. ->orderColumn('order')
  213. ->cloneable()
  214. ->mutateRelationshipDataBeforeFillUsing(function (array $data): array {
  215. if ($data['paragraph_type'] == 2 && !empty($data['text_content'])) {
  216. $content = is_string($data['text_content'])
  217. ? json_decode($data['text_content'], true)
  218. : $data['text_content'];
  219. if (is_array($content)) {
  220. $data['text_content_tw'] = $content['zh_TW'] ?? '';
  221. $data['text_content_en'] = $content['en'] ?? '';
  222. }
  223. }
  224. return $data;
  225. })
  226. ->mutateRelationshipDataBeforeSaveUsing(function (array $data): array{
  227. if ($data['paragraph_type'] == 2) {
  228. $data["text_content"] = ["zh_TW" => $data["text_content_tw"], "en" => $data["text_content_en"]];
  229. // 移除臨時的分離欄位,只保留合併的 JSON 欄位
  230. unset($data['text_content_tw']);
  231. unset($data['text_content_en']);
  232. }
  233. return $data;
  234. })
  235. ]),
  236. ]);
  237. }
  238. public static function table(Table $table): Table
  239. {
  240. $url = env('APP_URL')=="https://webdev.yico.tw:8088/" ? "https://demo.blockstudio.tw/yichiu/zh/news/" : "https://www.yico.tw/" ;
  241. return $table
  242. ->columns([
  243. //
  244. TextColumn::make("newsCategory.name")->label("分類")->alignCenter(),
  245. TextColumn::make("title")->label("標題")->alignCenter(),
  246. TextColumn::make("written_by")->label("發佈者")->alignCenter(),
  247. TextColumn::make("post_date")->label("發佈時間")->dateTime('Y/m/d')->alignCenter(),
  248. ImageColumn::make("news_img_pc_url")->label("列表圖")->alignCenter(),
  249. TextColumn::make("list_audit_state")->label("狀態")->badge()
  250. ->color(fn (string $state): string => match ($state) {
  251. '暫存' => 'warning',
  252. '已發佈' => 'success',
  253. }),
  254. IconColumn::make("on_top")->label("置頂")
  255. ->color(fn (string $state): string => match ($state) {
  256. 1 => 'success',
  257. default => ''
  258. })
  259. ->icon(fn (string $state): string => match ($state) {
  260. 1 => 'heroicon-o-check-circle',
  261. default => ''
  262. })
  263. ->action(function ($record): void {
  264. $record->on_top = !$record->on_top;
  265. $record->save();
  266. }),
  267. TextColumn::make("start_date")->label("預計上架時間")->dateTime('Y/m/d H:i:s')->alignCenter(),
  268. TextColumn::make("end_date")->label("預計下架時間")->dateTime('Y/m/d H:i:s')->alignCenter(),
  269. TextColumn::make("created_at")->label("建立時間")->dateTime('Y/m/d H:i:s')->alignCenter(),
  270. TextColumn::make("updated_at")->label("更新時間")->dateTime()->alignCenter(),
  271. ])
  272. ->filters([
  273. SelectFilter::make('news_category_id')->label("分類")
  274. ->options(NewsCategory::orderBy("order")->pluck("name", "id"))
  275. ->attribute('news_category_id'),
  276. SelectFilter::make('post_date')->label("年份")
  277. ->options(News::select(DB::raw("DATE_FORMAT(post_date, '%Y') as year"))->whereNotNull("post_date")->distinct()->pluck("year","year")->toArray())
  278. ->query(
  279. fn (array $data, Builder $query): Builder =>
  280. $query->when(
  281. $data['value'],
  282. fn (Builder $query, $value): Builder => $query->where('post_date', 'like', $data['value']. "%")
  283. )
  284. ),
  285. SelectFilter::make('visible')->label("狀態")
  286. ->options([
  287. 0 => "暫存",
  288. 1 => "已發佈",
  289. ])
  290. ->query(
  291. fn (array $data, Builder $query): Builder =>
  292. $query->when(
  293. $data['value'],
  294. fn (Builder $query, $value): Builder => $query->where('visible', $data['value'])
  295. )
  296. ),
  297. ])
  298. ->actions([
  299. Tables\Actions\EditAction::make(),
  300. Tables\Actions\DeleteAction::make(),
  301. \Filament\Tables\Actions\Action::make("audit")
  302. ->label(fn ($record) => match ($record->visible) {
  303. 0 => '發佈',
  304. 1 => '下架',
  305. })
  306. ->color(fn ($record) => match ($record->visible) {
  307. 0 => 'warning',
  308. 1 => 'gray',
  309. })
  310. ->icon(fn ($record) => match ($record->visible) {
  311. 0 => 'heroicon-m-chevron-double-up',
  312. 1 => 'heroicon-m-chevron-double-down',
  313. })
  314. ->action(function ($record): void {
  315. $record->visible = !$record->visible;
  316. $record->save();
  317. })
  318. ->outlined()
  319. ->requiresConfirmation(),
  320. Tables\Actions\Action::make('preview')
  321. ->label('前台預覽')
  322. ->icon('heroicon-m-arrow-top-right-on-square')
  323. ->color('info')
  324. ->url(fn ($record) => $url.$record->id."?preview=true")
  325. ->openUrlInNewTab()
  326. ->outlined(),
  327. ])
  328. ->bulkActions([
  329. Tables\Actions\BulkActionGroup::make([
  330. Tables\Actions\DeleteBulkAction::make(),
  331. ]),
  332. ])
  333. ->defaultSort('order', 'desc')
  334. ->defaultSort('created_at', 'desc');
  335. }
  336. public static function getRelations(): array
  337. {
  338. return [
  339. //
  340. ];
  341. }
  342. public static function getPages(): array
  343. {
  344. return [
  345. 'index' => Pages\ListNews::route('/'),
  346. 'create' => Pages\CreateNews::route('/create'),
  347. 'edit' => Pages\EditNews::route('/{record}/edit'),
  348. 'view' => Pages\ViewNews::route('/{record}/view'),
  349. ];
  350. }
  351. }