NewsResource.php 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. <?php
  2. namespace App\Filament\Resources;
  3. use AbdulmajeedJamaan\FilamentTranslatableTabs\TranslatableTabs;
  4. use App\Filament\Resources\NewsResource\Pages;
  5. use App\Filament\Resources\NewsResource\RelationManagers;
  6. use App\Models\News;
  7. use App\Models\NewsCategory;
  8. use Filament\Forms;
  9. use Filament\Forms\Components\DatePicker;
  10. use Filament\Forms\Components\FileUpload;
  11. use Filament\Forms\Components\Group;
  12. use Filament\Forms\Components\Radio;
  13. use Filament\Forms\Components\Repeater;
  14. use Filament\Forms\Components\Section;
  15. use Filament\Forms\Components\Select;
  16. use Filament\Forms\Components\Tabs;
  17. use Filament\Forms\Components\Tabs\Tab;
  18. use Filament\Forms\Components\Textarea;
  19. use Filament\Forms\Components\TextInput;
  20. use Filament\Forms\Form;
  21. use Filament\Forms\Get;
  22. use Filament\Resources\Resource;
  23. use Filament\Tables;
  24. use Filament\Tables\Columns\IconColumn;
  25. use Filament\Tables\Columns\ImageColumn;
  26. use Filament\Tables\Columns\TextColumn;
  27. use Filament\Tables\Filters\SelectFilter;
  28. use Filament\Tables\Table;
  29. use Illuminate\Database\Eloquent\Builder;
  30. use Illuminate\Database\Eloquent\SoftDeletingScope;
  31. use Illuminate\Support\Str;
  32. use Malzariey\FilamentLexicalEditor\Enums\ToolbarItem;
  33. use Malzariey\FilamentLexicalEditor\FilamentLexicalEditor;
  34. class NewsResource extends Resource
  35. {
  36. protected static ?string $model = News::class;
  37. protected static ?string $navigationIcon = 'heroicon-o-newspaper';
  38. protected static ?string $navigationLabel = "最新消息管理";
  39. protected static ?string $navigationGroup = '最新消息';
  40. protected static ?string $modelLabel = "最新消息管理";
  41. protected static ?int $navigationSort = 3;
  42. public static function form(Form $form): Form
  43. {
  44. $editor_toolbar= [
  45. ToolbarItem::UNDO, ToolbarItem::REDO, ToolbarItem::NORMAL,
  46. ToolbarItem::H2, ToolbarItem::H3, ToolbarItem::H4, ToolbarItem::H5,
  47. ToolbarItem::BULLET, ToolbarItem::NUMBERED, ToolbarItem::FONT_SIZE,
  48. ToolbarItem::BOLD, ToolbarItem::ITALIC, ToolbarItem::UNDERLINE,
  49. ToolbarItem::LINK, ToolbarItem::TEXT_COLOR, ToolbarItem::BACKGROUND_COLOR,
  50. ToolbarItem::SUBSCRIPT, ToolbarItem::LOWERCASE, ToolbarItem::DIVIDER,
  51. ToolbarItem::UPPERCASE, ToolbarItem::CLEAR, ToolbarItem::HR
  52. ];
  53. return $form
  54. ->schema([
  55. //
  56. Tabs::make()->schema([
  57. Tab::make("基本資訊")->schema([
  58. Select::make("news_category_id")->label("分類")->options(function (){
  59. return NewsCategory::pluck("name", "id");
  60. })->required()
  61. ->columnSpan(1),
  62. DatePicker::make("post_date")->label("發佈日")
  63. ->native(false)
  64. ->closeOnDateSelection()
  65. ->columnSpan(1),
  66. FileUpload::make("news_img")->label("圖片")
  67. ->directory("news")->maxSize(122880)
  68. ->columnSpan(2),
  69. TranslatableTabs::make('')
  70. ->schema([
  71. TextInput::make("title")
  72. ->label("標題")
  73. ->columnSpan(1),
  74. TextInput::make("written_by")
  75. ->label("撰文者")
  76. ->columnSpan(1),
  77. Textarea::make("description")
  78. ->label("簡述")
  79. ->columnSpan(2)
  80. ])->columns(2)->columnSpan(2),
  81. ])->columns(2),
  82. Tab::make("SEO")->schema([
  83. TranslatableTabs::make('')
  84. ->schema([
  85. TextInput::make("meta_title")->label("SEO 標題"),
  86. TextInput::make("meta_keyword")->label("SEO 關鍵字"),
  87. Textarea::make("meta_description")->label("SEO 簡述")
  88. ])->columnSpanFull(),
  89. FileUpload::make('meta_img')->label("放大預覽圖")
  90. ->directory("news/seo")
  91. ->columnSpan(1),
  92. ]),
  93. Tab::make("內文編輯")->schema([
  94. Repeater::make("paragraphs")->schema([
  95. TextInput::make('item_key')
  96. ->default(fn () => Str::random())
  97. ->hidden()
  98. ->afterStateHydrated(function (TextInput $component, $state) {
  99. if (empty($state)) {
  100. $component->state(Str::random());
  101. }
  102. }),
  103. Radio::make("paragraph_type")->options([
  104. 1 => "圖片",
  105. 2 => "文字",
  106. // 3 => "影音"
  107. ])->label("")->inline()->default(1)->Live(),
  108. Group::make()->schema([
  109. Section::make('')->schema([
  110. Repeater::make("multiple_images")->schema([
  111. TextInput::make('para_img_item_key')
  112. ->default(fn () => Str::random())
  113. ->hidden()
  114. ->afterStateHydrated(function (TextInput $component, $state) {
  115. if (empty($state)) {
  116. $component->state(Str::random());
  117. }
  118. }),
  119. TextInput::make("img_alt")->label("圖片註釋")->translatableTabs()->columnSpan(1),
  120. FileUpload::make('img_url')->label("")
  121. ->directory("news/paragraphs")
  122. ->maxFiles(10),
  123. ])
  124. ->relationship("photos")
  125. ->label("")
  126. ->orderColumn('order')
  127. ])
  128. ])->visible(fn (Get $get):bool => $get("paragraph_type") == 1),
  129. Group::make()->schema([
  130. FilamentLexicalEditor::make('text_content_tw')
  131. ->label('繁體中文內容')
  132. ->id(fn ($get) => "text_content_tw_" . $get('item_key') . "_" . uniqid())
  133. ->enabledToolbars($editor_toolbar)
  134. ->columnSpanFull(),
  135. FilamentLexicalEditor::make('text_content_en')
  136. ->label('English Content')
  137. ->id(fn ($get) => "text_content_en_" . $get('item_key') . "_" . uniqid())
  138. ->enabledToolbars($editor_toolbar)
  139. ->columnSpanFull(),
  140. ])->visible(fn (Get $get):bool => $get("paragraph_type") == 2),
  141. ])
  142. ->mutateRelationshipDataBeforeFillUsing(function (array $data): array {
  143. if ($data['paragraph_type'] == 2 && !empty($data['text_content'])) {
  144. $content = is_string($data['text_content'])
  145. ? json_decode($data['text_content'], true)
  146. : $data['text_content'];
  147. if (is_array($content)) {
  148. $data['text_content_tw'] = $content['zh_TW'] ?? '';
  149. $data['text_content_en'] = $content['en'] ?? '';
  150. }
  151. }
  152. return $data;
  153. })
  154. ->mutateRelationshipDataBeforeSaveUsing(function (array $data): array{
  155. if ($data['paragraph_type'] == 2) {
  156. $data["text_content"] = ["zh_TW" => $data["text_content_tw"], "en" => $data["text_content_en"]];
  157. // 移除臨時的分離欄位,只保留合併的 JSON 欄位
  158. unset($data['text_content_tw']);
  159. unset($data['text_content_en']);
  160. }
  161. return $data;
  162. })
  163. ->relationship("paragraphs")
  164. ->label("段落")
  165. ->collapsible()
  166. ->reorderableWithButtons()
  167. ->orderColumn('order')
  168. ->cloneable()
  169. ])
  170. ])->columnSpanFull(),
  171. ]);
  172. }
  173. public static function table(Table $table): Table
  174. {
  175. return $table
  176. ->columns([
  177. //
  178. TextColumn::make("newsCategory.name")->label("分類")->alignCenter(),
  179. TextColumn::make("title")->label("標題")->alignCenter(),
  180. TextColumn::make("written_by")->label("發佈者")->alignCenter(),
  181. TextColumn::make("post_date")->label("發佈時間")->dateTime('Y/m/d')->alignCenter(),
  182. ImageColumn::make("news_img_url")->label("列表圖")->alignCenter(),
  183. TextColumn::make("list_audit_state")->label("狀態")->badge()
  184. ->color(fn (string $state): string => match ($state) {
  185. '暫存' => 'warning',
  186. '已發佈' => 'success',
  187. }),
  188. IconColumn::make("on_top")->label("置頂")
  189. ->color(fn (string $state): string => match ($state) {
  190. 1 => 'success',
  191. default => ''
  192. })
  193. ->icon(fn (string $state): string => match ($state) {
  194. 1 => 'heroicon-o-check-circle',
  195. default => ''
  196. })
  197. ->action(function ($record): void {
  198. $record->on_top = !$record->on_top;
  199. $record->save();
  200. }),
  201. TextColumn::make("created_at")->label("建立時間")->dateTime('Y/m/d H:i:s')->alignCenter(),
  202. TextColumn::make("updated_at")->label("更新時間")->dateTime()->alignCenter(),
  203. ])
  204. ->filters([
  205. SelectFilter::make('news_category_id')->label("分類")
  206. ->options(NewsCategory::orderBy("order")->pluck("name", "id"))
  207. ->attribute('news_category_id'),
  208. SelectFilter::make('post_date')->label("年份")
  209. ->options(News::select(\DB::raw("DATE_FORMAT(post_date, '%Y') as year"))->whereNotNull("post_date")->distinct()->pluck("year","year")->toArray())
  210. ->query(
  211. fn (array $data, Builder $query): Builder =>
  212. $query->when(
  213. $data['value'],
  214. fn (Builder $query, $value): Builder => $query->where('post_date', 'like', $data['value']. "%")
  215. )
  216. ),
  217. SelectFilter::make('visible')->label("狀態")
  218. ->options([
  219. 0 => "暫存",
  220. 1 => "已發佈",
  221. ])
  222. ->query(
  223. fn (array $data, Builder $query): Builder =>
  224. $query->when(
  225. $data['value'],
  226. fn (Builder $query, $value): Builder => $query->where('visible', $data['value'])
  227. )
  228. ),
  229. ])
  230. ->actions([
  231. Tables\Actions\EditAction::make(),
  232. Tables\Actions\DeleteAction::make(),
  233. \Filament\Tables\Actions\Action::make("audit")
  234. ->label(fn ($record) => match ($record->visible) {
  235. 0 => '發佈',
  236. 1 => '下架',
  237. })
  238. ->color(fn ($record) => match ($record->visible) {
  239. 0 => 'warning',
  240. 1 => 'gray',
  241. })
  242. ->icon(fn ($record) => match ($record->visible) {
  243. 0 => 'heroicon-m-chevron-double-up',
  244. 1 => 'heroicon-m-chevron-double-down',
  245. })
  246. ->action(function ($record): void {
  247. $record->visible = !$record->visible;
  248. $record->save();
  249. })
  250. ->outlined()
  251. ->requiresConfirmation(),
  252. ])
  253. ->bulkActions([
  254. Tables\Actions\BulkActionGroup::make([
  255. Tables\Actions\DeleteBulkAction::make(),
  256. ]),
  257. ])
  258. ->defaultSort('order', 'desc')
  259. ->defaultSort('created_at', 'desc');
  260. }
  261. public static function getRelations(): array
  262. {
  263. return [
  264. //
  265. ];
  266. }
  267. public static function getPages(): array
  268. {
  269. return [
  270. 'index' => Pages\ListNews::route('/'),
  271. 'create' => Pages\CreateNews::route('/create'),
  272. 'edit' => Pages\EditNews::route('/{record}/edit'),
  273. ];
  274. }
  275. }