NewsResource.php 14KB

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