S.K. 1 месяц назад
Родитель
Сommit
ebd00abfae
44 измененных файлов: 15532 добавлений и 182 удалений
  1. 107
    0
      app/Filament/Pages/EsgMainPage.php
  2. 710
    0
      app/Filament/Resources/EsgResource.php
  3. 43
    0
      app/Filament/Resources/EsgResource/Pages/CreateEsg.php
  4. 53
    0
      app/Filament/Resources/EsgResource/Pages/EditEsg.php
  5. 19
    0
      app/Filament/Resources/EsgResource/Pages/ListEsg.php
  6. 1
    0
      app/Filament/Resources/NewsCategoryResource.php
  7. 202
    73
      app/Filament/Resources/NewsResource.php
  8. 1
    0
      app/Filament/Resources/NewsResource/Pages/CreateNews.php
  9. 2
    1
      app/Filament/Resources/UserResource.php
  10. 152
    0
      app/Http/Controllers/Api/EsgController.php
  11. 149
    79
      app/Http/Controllers/Api/NewsController.php
  12. 44
    0
      app/Models/Esg.php
  13. 90
    0
      app/Models/EsgMain.php
  14. 52
    0
      app/Models/EsgParagraph.php
  15. 0
    4
      app/Models/News.php
  16. 37
    9
      app/Models/NewsParagraph.php
  17. 2
    2
      app/Models/NewsPhoto.php
  18. 418
    0
      app/Traits/HandlesEsgParagraphs.php
  19. 1
    0
      composer.json
  20. 76
    1
      composer.lock
  21. 1
    1
      config/app.php
  22. 3
    3
      config/filament-shield.php
  23. 160
    0
      config/livewire.php
  24. 1
    1
      database/migrations/2025_05_20_043733_create_news_table.php
  25. 2
    3
      database/migrations/2025_05_20_043735_create_news_paragraphs_table.php
  26. 2
    2
      database/migrations/2025_05_20_043736_create_news_photos_table.php
  27. 34
    0
      database/migrations/2025_06_18_072530_create_esgs_table.php
  28. 32
    0
      database/migrations/2025_06_18_075604_create_esg_paragraphs_table.php
  29. 35
    0
      database/migrations/2025_07_02_041600_create_esg_mains_table.php
  30. 30
    0
      database/migrations/2026_01_13_082523_add_scheduled_date_to_news.php
  31. 25
    0
      database/migrations/2026_04_01_145408_alter_esg_paragraphs_column.php
  32. 6279
    0
      public/css/malzariey/filament-lexical-editor/filament-lexical-editor-styles.css
  33. Двоичные данные
      public/images/tool-bar.png
  34. 44
    0
      public/js/malzariey/filament-lexical-editor/components/lexical-component.js
  35. 26
    0
      resources/css/app.css
  36. 6600
    0
      resources/css/lexical-editor-extend.css
  37. 44
    0
      resources/js/lexical-editor-extend.js
  38. 11
    0
      resources/lang/zh_TW/filament-lexical-editor.php
  39. 19
    0
      resources/lang/zh_TW/filament-panels.php
  40. 17
    0
      resources/views/filament/pages/esg-main.blade.php
  41. 1
    1
      resources/views/welcome.blade.php
  42. 5
    0
      routes/api.php
  43. 1
    1
      routes/web.php
  44. 1
    1
      vite.config.js

+ 107
- 0
app/Filament/Pages/EsgMainPage.php Просмотреть файл

@@ -0,0 +1,107 @@
1
+<?php
2
+
3
+namespace App\Filament\Pages;
4
+
5
+use App\Models\EsgMain;
6
+use Filament\Forms\Components\Actions\Action;
7
+use Filament\Forms\Components\FileUpload;
8
+use Filament\Forms\Components\Tabs;
9
+use Filament\Forms\Components\Tabs\Tab;
10
+use Filament\Forms\Components\Textarea;
11
+use Filament\Forms\Components\TextInput;
12
+use Filament\Forms\Concerns\InteractsWithForms;
13
+use Filament\Forms\Form;
14
+use Filament\Notifications\Notification;
15
+use Filament\Pages\Page;
16
+use SolutionForest\FilamentTranslateField\Forms\Component\Translate;
17
+
18
+class EsgMainPage extends Page
19
+{
20
+    use InteractsWithForms;
21
+
22
+    protected static ?string $navigationIcon = 'heroicon-o-cog-6-tooth';
23
+    protected static ?string $navigationLabel = 'ESG 主要設定';
24
+    protected static ?string $title = 'ESG 主要設定';
25
+    protected static string $view = 'filament.pages.esg-main';
26
+    protected static ?string $navigationGroup = 'ESG 上稿內容管理';
27
+    protected static ?int $navigationSort = 99;
28
+
29
+    public ?array $data = [];
30
+    protected ?EsgMain $esgMain = null;
31
+
32
+    public function mount(): void
33
+    {
34
+        $this->esgMain = EsgMain::getMain();
35
+        $esgMainArray = $this->esgMain->safeToArray();
36
+        \Log::info("輸出", $esgMainArray);
37
+        $this->form->fill($esgMainArray);
38
+    }
39
+
40
+    public function form(Form $form): Form
41
+    {
42
+        return $form
43
+            ->schema([
44
+                Tabs::make('設定')->tabs([
45
+                    Tab::make('基本資訊')->schema([
46
+                        Translate::make()->schema(fn (string $locale) => [
47
+                            TextInput::make('title')
48
+                            ->label("標題"),
49
+                            Textarea::make('description')
50
+                        ])->locales(["zh_TW", "en"])
51
+                        ->columnSpanFull(),
52
+                        FileUpload::make('img_pc')->label("Banner (PC)")
53
+                        ->disk("public")
54
+                        ->directory("esg"),
55
+                        FileUpload::make('img_mobile')->label("Banner (Mobile)")
56
+                        ->disk("public")
57
+                        ->directory("esg"),
58
+                    ]),
59
+                    Tab::make('SEO 設定')->schema([
60
+                        Translate::make()->schema(fn (string $locale) => [
61
+                            TextInput::make('meta_title'),
62
+                            TextInput::make('meta_keyword'),
63
+                            Textarea::make('meta_description'),
64
+                        ])->locales(["zh_TW", "en"])
65
+                        ->columnSpanFull(),
66
+                        FileUpload::make('og_img')
67
+                        ->disk("public")
68
+                        ->directory("esg"),
69
+                    ]),
70
+                ])
71
+            ])
72
+            ->statePath('data');
73
+    }
74
+
75
+    public function save(): void
76
+    {
77
+        try {
78
+            $data = $this->form->getState();
79
+
80
+            $settings = EsgMain::getMain();
81
+            $settings->update($data);
82
+
83
+            Notification::make()
84
+                ->title('設定已儲存')
85
+                ->success()
86
+                ->send();
87
+
88
+        } catch (\Exception $e) {
89
+            Notification::make()
90
+                ->title('儲存失敗')
91
+                ->body($e->getMessage())
92
+                ->danger()
93
+                ->send();
94
+        }
95
+    }
96
+
97
+    protected function getFormActions(): array
98
+    {
99
+        return [
100
+            Action::make('save')
101
+                ->label('儲存設定')
102
+                ->action('save')
103
+                ->color('primary'),
104
+        ];
105
+    }
106
+
107
+}

+ 710
- 0
app/Filament/Resources/EsgResource.php Просмотреть файл

@@ -0,0 +1,710 @@
1
+<?php
2
+
3
+namespace App\Filament\Resources;
4
+
5
+use App\Filament\Resources\EsgResource\Pages;
6
+use App\Models\Esg;
7
+use Filament\Forms\Components\Fieldset;
8
+use Filament\Forms\Components\FileUpload;
9
+use Filament\Forms\Components\Grid;
10
+use Filament\Forms\Components\Group;
11
+use Filament\Forms\Components\Placeholder;
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\Components\Toggle;
22
+use Filament\Forms\Form;
23
+use Filament\Forms\Get;
24
+use Filament\Resources\Resource;
25
+use Filament\Tables;
26
+use Filament\Tables\Columns\TextColumn;
27
+use Filament\Tables\Table;
28
+use Illuminate\Database\Eloquent\Builder;
29
+use Illuminate\Database\Eloquent\SoftDeletingScope;
30
+use Malzariey\FilamentLexicalEditor\Enums\ToolbarItem;
31
+use Malzariey\FilamentLexicalEditor\FilamentLexicalEditor;
32
+use SolutionForest\FilamentTranslateField\Forms\Component\Translate;
33
+use Filament\Forms\Components\Hidden;
34
+use Str;
35
+
36
+class EsgResource extends Resource
37
+{
38
+    protected static ?string $model = Esg::class;
39
+
40
+    protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';
41
+    protected static ?string $modelLabel = "ESG 管理";
42
+    protected static ?string $navigationGroup = 'ESG 上稿內容管理';
43
+    protected static ?string $navigationLabel = "ESG 管理";
44
+
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, ToolbarItem::FONT_FAMILY
55
+        ];
56
+        return $form
57
+            ->schema([
58
+                //
59
+                Tabs::make("")->tabs([
60
+                    Tab::make('基本資訊')->schema([
61
+                        TextInput::make('keyword')->label("關聯字詞")->required()
62
+                        ->validationMessages([
63
+                            'required' => '請填寫關聯字詞',
64
+                        ]),
65
+                        Translate::make()->schema(fn (string $locale) => [
66
+                            TextInput::make('title')
67
+                            ->label("標題")
68
+                            ->columnSpan(1)
69
+                            ->required($locale == "zh_TW")
70
+                            ->validationMessages([
71
+                                'required' => '請填寫標題',
72
+                            ])
73
+                        ])->locales(["zh_TW", "en"])
74
+                        ->columnSpanFull()->columns(3),
75
+                    ]),
76
+                    Tab::make('Banner 設定')->schema([
77
+                        FileUpload::make('banner_pc')->label("Banner (PC)")
78
+                        ->disk("public")
79
+                        ->helperText('桌機版建議上傳圖片比例 4 : 1,寬1920px 高480px,檔案大小限制為1MB以下')
80
+                        // ->helperText('建議寬高限制為:1280*720px,檔案大小限制為1M以下')->maxSize('1024')
81
+                        ->directory("esg")->required()
82
+                        ->validationMessages([
83
+                            'required' => '請上傳圖片',
84
+                        ]),
85
+                        FileUpload::make('banner_mobile')->label("Banner (Mobile)")
86
+                        ->disk("public")
87
+                        ->helperText('手機版建議上傳圖片比例 4 : 1,寬1920px 高480px,檔案大小限制為1MB以下')
88
+                        // ->helperText('建議寬高限制為:600*896px,檔案大小限制為1M以下')->maxSize('1024')
89
+                        ->directory("esg")->required()
90
+                        ->validationMessages([
91
+                            'required' => '請上傳圖片',
92
+                        ]),
93
+                        Translate::make()->schema(fn (string $locale) => [
94
+                            TextInput::make('banner_alt')
95
+                            ->label("Banner 圖片註釋")
96
+                            ->required($locale == "zh_TW")
97
+                            ->validationMessages([
98
+                                'required' => '請填寫圖片註釋',
99
+                            ]),
100
+                            Textarea::make("description")->rows(5)->columnSpanFull()->label("短文"),
101
+                        ])->locales(["zh_TW", "en"])
102
+                        ->columnSpanFull(),
103
+                    ]),
104
+                    Tab::make("段落設計")->schema([
105
+                        //1: 純文字 2:區塊文字 3:表格 4:影片 or 圖片 5:左右圖文
106
+                        Repeater::make("paragraphs")->label("")->schema([
107
+                            TextInput::make('item_key')
108
+                                ->default(fn () => Str::random())
109
+                                ->hidden()
110
+                                ->afterStateHydrated(function (TextInput $component, $state) {
111
+                                    if (empty($state)) {
112
+                                        $component->state(Str::random());
113
+                                    }
114
+                                }),
115
+                            Radio::make("type")->options([
116
+                                1 => "純文字",
117
+                                2 => "區塊文字",
118
+                                3 => "表格",
119
+                                4 => "圖片",
120
+                                5 => "影片",
121
+                            ])->label("")->default(1)->Live(),
122
+                            Group::make()->schema([
123
+                                Section::make('純文字設定')->schema([
124
+                                    FilamentLexicalEditor::make('content.text_content_tw')
125
+                                        ->label('中文')
126
+                                        
127
+                                            ->label(new \Illuminate\Support\HtmlString('中文  <a href="' . asset('images/tool-bar.png') . '", target="_blank">工具列說明</a>'))
128
+                                        ->id(fn ($get) => "text_content_tw_" . $get('item_key') . "_" . uniqid())
129
+                                        ->enabledToolbars($editor_toolbar)
130
+                                        ->required()
131
+                                        ->columnSpanFull(),
132
+                                    FilamentLexicalEditor::make('content.text_content_en')
133
+                                        ->label('English')
134
+                                        ->id(fn ($get) => "text_content_en_" . $get('item_key') . "_" . uniqid())
135
+                                        ->enabledToolbars($editor_toolbar)
136
+                                        ->columnSpanFull(),
137
+                                ]),
138
+                            ])->visible(fn (Get $get):bool => $get("type") == 1),
139
+                            Group::make()->schema([
140
+                                Section::make('區塊文字設定')->schema([
141
+                                    // 文字區塊重複器
142
+                                    Repeater::make("content.text_blocks")->schema([
143
+                                        TextInput::make('block_item_key')
144
+                                            ->default(fn () => Str::random())
145
+                                            ->hidden()
146
+                                            ->afterStateHydrated(function (TextInput $component, $state) {
147
+                                                if (empty($state)) {
148
+                                                    $component->state(Str::random());
149
+                                                }
150
+                                            }),
151
+                                        FilamentLexicalEditor::make('block_content_tw')
152
+                                            // ->label('繁體中文內容')
153
+                                            ->label(new \Illuminate\Support\HtmlString('繁體中文內容  <a href="' . asset('images/tool-bar.png') . '", target="_blank">工具列說明</a>'))
154
+                                            ->id(fn ($get) => "block_content_tw_" . $get('block_item_key') . "_" . uniqid())
155
+                                            ->enabledToolbars($editor_toolbar)
156
+                                            ->required()
157
+                                            ->live(onBlur: true)
158
+                                            ->columnSpanFull(),
159
+                                        FilamentLexicalEditor::make('block_content_en')
160
+                                            ->label('English Content')
161
+                                            ->id(fn ($get) => "block_content_en_" . $get('block_item_key') . "_" . uniqid())
162
+                                            ->enabledToolbars($editor_toolbar)
163
+                                            ->columnSpanFull(),
164
+                                    ])
165
+                                    ->label("")
166
+                                    ->addActionLabel('增加區塊')
167
+                                    ->orderColumn('order')
168
+                                    ->reorderableWithButtons()
169
+                                    ->cloneable()
170
+                                    ->minItems(1)
171
+                                    ->maxItems(20)
172
+                                    ->defaultItems(1),
173
+                                ]),
174
+                            ])->visible(fn (Get $get):bool => $get('type') == 2),
175
+                            Group::make()->schema([
176
+                                Section::make('表格設定')->schema([
177
+                                    Hidden::make('content.is_card')
178
+                                    ->default('0'),
179
+                                    /*
180
+                                    Radio::make('content.is_card')
181
+                                            ->label('手機板卡片顯示')
182
+                                            ->options([
183
+                                                '1' => '是',  // 改為數字鍵值
184
+                                                '0' => '否'
185
+                                            ])
186
+                                            ->default('1')
187
+                                            ->inline(),
188
+                                    */
189
+                                    // 表格資料
190
+                                    Placeholder::make('table_builder_info')->label("")->content('請先設定表格欄數,然後填入表格資料'),
191
+                                    Grid::make(3)->schema([
192
+                                        Radio::make('content.column_count')
193
+                                            ->label('欄數')
194
+                                            ->options([
195
+                                                2 => '2欄',  // 改為數字鍵值
196
+                                                3 => '3欄',
197
+                                                4 => '4欄'
198
+                                            ])
199
+                                            ->default(2)
200
+                                            ->inline()
201
+                                            ->live()
202
+                                            ->reactive(), // ✅ 添加 reactive()
203
+                                    ]),
204
+                                    Translate::make()->schema(fn (string $locale) => [
205
+                                        Grid::make(2)  // 改用 Grid 來支援動態 columns
206
+                                            ->schema([
207
+                                                TextInput::make('content.head1')->label('標題第1欄')->required()
208
+                                                ->validationMessages([
209
+                                                    'required' => '請填寫',
210
+                                                ]),
211
+                                                Radio::make('content.head_align1')
212
+                                                    ->label('對齊')
213
+                                                    ->options([
214
+                                                        1 => '置左',  // 改為數字鍵值
215
+                                                        2 => '置中',
216
+                                                        3 => '置右'
217
+                                                    ])
218
+                                                    ->default(1),
219
+                                                TextInput::make('content.head2')->label('標題第2欄')->required()
220
+                                                ->validationMessages([
221
+                                                    'required' => '請填寫',
222
+                                                ]),
223
+                                                Radio::make('content.head_align2')
224
+                                                    ->label('對齊')
225
+                                                    ->options([
226
+                                                        1 => '置左',  // 改為數字鍵值
227
+                                                        2 => '置中',
228
+                                                        3 => '置右'
229
+                                                    ])
230
+                                                    ->default(1),
231
+                                                TextInput::make('content.head3')->label('標題第3欄')
232
+                                                    ->visible(fn (Get $get) => intval($get('content.column_count')) >= 3)->columnSpan(1),
233
+                                                    Radio::make('content.head_align3')
234
+                                                        ->label('對齊')
235
+                                                        ->options([
236
+                                                            1 => '置左',  // 改為數字鍵值
237
+                                                            2 => '置中',
238
+                                                            3 => '置右'
239
+                                                        ])
240
+                                                        ->default(1)
241
+                                                        ->visible(fn (Get $get) => intval($get('content.column_count')) >= 3)->columnSpan(1),
242
+                                                TextInput::make('content.head4')->label('標題第4欄')
243
+                                                    ->visible(fn (Get $get) => intval($get('content.column_count')) >= 4)->columnSpan(1),
244
+                                                    Radio::make('content.head_align4')
245
+                                                        ->label('對齊')
246
+                                                        ->options([
247
+                                                            1 => '置左',  // 改為數字鍵值
248
+                                                            2 => '置中',
249
+                                                            3 => '置右'
250
+                                                        ])
251
+                                                        ->default(1)
252
+                                                        ->visible(fn (Get $get) => intval($get('content.column_count')) >= 4)->columnSpan(1),
253
+                                            ])
254
+                                            ->reactive()  // 加入響應式
255
+                                    ])->locales(["zh_TW", "en"]),
256
+                                    Repeater::make('content.simple_table_rows')
257
+                                        ->label('表格資料')
258
+                                        ->schema([
259
+                                            TextInput::make('simple_table_rows_key')
260
+                                                ->default(fn () => Str::random())
261
+                                                ->hidden()
262
+                                                ->afterStateHydrated(function (TextInput $component, $state) {
263
+                                                    if (empty($state)) {
264
+                                                        $component->state(Str::random());
265
+                                                    }
266
+                                                }),
267
+                                            Grid::make(1)  // 改用 Grid 來支援動態 columns
268
+                                                ->schema([
269
+                                                    Section::make("第一欄")->schema([
270
+                                                        Fieldset::make('中文')->schema([
271
+                                                            Radio::make('align1_tw')
272
+                                                                ->label('對齊')
273
+                                                                ->options([
274
+                                                                    1 => '置左',  // 改為數字鍵值
275
+                                                                    2 => '置中',
276
+                                                                    3 => '置右'
277
+                                                                ])
278
+                                                            ->default(1)->inline(),
279
+                                                            FilamentLexicalEditor::make('col1_tw')
280
+                                                                ->id(fn ($get) => "col1_tw_" . $get('simple_table_rows_key') . "_" . uniqid())
281
+                                                                ->label(new \Illuminate\Support\HtmlString('<a href="' . asset('images/tool-bar.png') . '", target="_blank">工具列說明</a>'))
282
+                                                                ->enabledToolbars($editor_toolbar)
283
+                                                                ->required()
284
+                                                                ->columnSpanFull(),
285
+                                                        ]),
286
+                                                        Fieldset::make('英文')->schema([
287
+                                                            Radio::make('align1_en')
288
+                                                            ->label('對齊')
289
+                                                            ->options([
290
+                                                                1 => '置左',  // 改為數字鍵值
291
+                                                                2 => '置中',
292
+                                                                3 => '置右'
293
+                                                            ])
294
+                                                            ->default(1)->inline(),
295
+                                                            FilamentLexicalEditor::make('col1_en')
296
+                                                                ->id(fn ($get) => "col1_en_" . $get('simple_table_rows_key') . "_" . uniqid())
297
+                                                                ->enabledToolbars($editor_toolbar)
298
+                                                                ->columnSpanFull(),
299
+                                                        ]),
300
+                                                    ]),
301
+                                                    Section::make("第二欄")->schema([
302
+                                                        Fieldset::make('中文')->schema([
303
+                                                            Radio::make('align2_tw')
304
+                                                                ->label('對齊')
305
+                                                                ->options([
306
+                                                                    1 => '置左',  // 改為數字鍵值
307
+                                                                    2 => '置中',
308
+                                                                    3 => '置右'
309
+                                                                ])
310
+                                                            ->default(1)->inline(),
311
+                                                            FilamentLexicalEditor::make('col2_tw')
312
+                                                                ->id(fn ($get) => "col2_tw_" . $get('simple_table_rows_key') . "_" . uniqid())
313
+                                                                ->label(new \Illuminate\Support\HtmlString('<a href="' . asset('images/tool-bar.png') . '", target="_blank">工具列說明</a>'))
314
+                                                                ->enabledToolbars($editor_toolbar)
315
+                                                                ->required()
316
+                                                                ->columnSpanFull(),
317
+                                                        ]),
318
+                                                        Fieldset::make('英文')->schema([
319
+                                                            Radio::make('align2_en')
320
+                                                                ->label('對齊')
321
+                                                                ->options([
322
+                                                                    1 => '置左',  // 改為數字鍵值
323
+                                                                    2 => '置中',
324
+                                                                    3 => '置右'
325
+                                                                ])
326
+                                                            ->default(1)->inline(),
327
+                                                            FilamentLexicalEditor::make('col2_en')
328
+                                                                ->id(fn ($get) => "col2_en_" . $get('simple_table_rows_key') . "_" . uniqid())
329
+                                                                ->enabledToolbars($editor_toolbar)
330
+                                                                ->columnSpanFull(),
331
+                                                        ]),
332
+                                                    ]),
333
+                                                    Section::make("第三欄")->schema([
334
+                                                        Fieldset::make('中文')->schema([
335
+                                                            Radio::make('align3_tw')
336
+                                                                ->label('對齊')
337
+                                                                ->options([
338
+                                                                    1 => '置左',  // 改為數字鍵值
339
+                                                                    2 => '置中',
340
+                                                                    3 => '置右'
341
+                                                                ])
342
+                                                            ->default(1),
343
+                                                            FilamentLexicalEditor::make('col3_tw')
344
+                                                                ->id(fn ($get) => "col3_tw_" . $get('simple_table_rows_key') . "_" . uniqid())
345
+                                                                ->label(new \Illuminate\Support\HtmlString('<a href="' . asset('images/tool-bar.png') . '", target="_blank">工具列說明</a>'))
346
+                                                                ->enabledToolbars($editor_toolbar)
347
+                                                                ->required()
348
+                                                                ->columnSpanFull(),
349
+                                                        ]),
350
+                                                        Fieldset::make('英文')->schema([
351
+                                                            Radio::make('align3_en')
352
+                                                                ->label('對齊')
353
+                                                                ->options([
354
+                                                                    1 => '置左',  // 改為數字鍵值
355
+                                                                    2 => '置中',
356
+                                                                    3 => '置右'
357
+                                                                ])
358
+                                                            ->default(1)->inline(),
359
+                                                            FilamentLexicalEditor::make('col3_en')
360
+                                                                ->id(fn ($get) => "col3_en_" . $get('simple_table_rows_key') . "_" . uniqid())
361
+                                                                ->enabledToolbars($editor_toolbar)
362
+                                                                ->columnSpanFull(),
363
+                                                            ]),
364
+                                                    ])->visible(fn (Get $get) => intval($get('../../../content.column_count')) >= 3),
365
+                                                    Section::make("第四欄")->schema([
366
+                                                        Fieldset::make('中文')->schema([
367
+                                                            Radio::make('align4_tw')
368
+                                                                ->label('對齊')
369
+                                                                ->options([
370
+                                                                    1 => '置左',  // 改為數字鍵值
371
+                                                                    2 => '置中',
372
+                                                                    3 => '置右'
373
+                                                                ])
374
+                                                            ->default(1)->inline(),
375
+                                                            FilamentLexicalEditor::make('col4_tw')
376
+                                                                ->id(fn ($get) => "col4_tw_" . $get('simple_table_rows_key') . "_" . uniqid())
377
+                                                                ->label(new \Illuminate\Support\HtmlString('<a href="' . asset('images/tool-bar.png') . '", target="_blank">工具列說明</a>'))
378
+                                                                ->enabledToolbars($editor_toolbar)
379
+                                                                ->required()
380
+                                                                ->columnSpanFull(),
381
+                                                        ]),
382
+                                                        Fieldset::make('英文')->schema([
383
+                                                            Radio::make('align4_en')
384
+                                                                ->label('對齊')
385
+                                                                ->options([
386
+                                                                    1 => '置左',  // 改為數字鍵值
387
+                                                                    2 => '置中',
388
+                                                                    3 => '置右'
389
+                                                                ])
390
+                                                            ->default(1)->inline(),
391
+                                                            FilamentLexicalEditor::make('col4_en')
392
+                                                                ->id(fn ($get) => "col4_en_" . $get('simple_table_rows_key') . "_" . uniqid())
393
+                                                                ->enabledToolbars($editor_toolbar)
394
+                                                                ->columnSpanFull(),
395
+                                                        ]),
396
+                                                    ])->visible(fn (Get $get) => intval($get('../../../content.column_count')) >= 4),
397
+                                                ])
398
+                                                ->reactive()  // 加入響應式
399
+                                        ])
400
+                                        ->id(fn ($get) => "simple_table_" . $get('simple_table_rows_key'))
401
+                                        ->addActionLabel('新增列')
402
+                                        ->reorderableWithButtons()
403
+                                        ->minItems(1)
404
+                                ]),
405
+                            ])->visible(fn (Get $get):bool => $get('type') == 3),
406
+                            Group::make()->schema([
407
+                                Section::make('')->schema([
408
+                                    Repeater::make("content.multiple_images")->schema([
409
+                                        TextInput::make('para_img_item_key')
410
+                                            ->default(fn () => Str::random())
411
+                                            ->hidden()
412
+                                            ->afterStateHydrated(function (TextInput $component, $state) {
413
+                                                if (empty($state)) {
414
+                                                    $component->state(Str::random());
415
+                                                }
416
+                                            }),
417
+                                        Translate::make()->schema(fn (string $locale) => [
418
+                                            TextInput::make('image_alt')->label("圖片註文")
419
+                                        ])->locales(["zh_TW", "en"])
420
+                                        ->id(fn ($get) => "para_img_mul_" . $get('para_img_item_key')),
421
+                                        FileUpload::make('image_url')->label("")->disk("public")
422
+                                        ->helperText('檔案大小限制為1MB以下')
423
+                                        // ->helperText('建議寬高限制為:1080*675px,檔案大小限制為1M以下')->maxSize('1024')
424
+                                        ->directory("esg/paragraphPhoto")
425
+                                        ->maxFiles(10)
426
+                                        ->required()
427
+                                        ->validationMessages([
428
+                                            'required' => '請上傳圖片',
429
+                                        ]),
430
+                                    ])
431
+                                    ->addActionLabel('新增')
432
+                                    ->label("")
433
+                                    ->orderColumn('order')
434
+                                ])
435
+                            ])->visible(fn (Get $get):bool => $get("type") == 4),
436
+                            Group::make()->schema([
437
+                                Section::make("")->schema([
438
+                                    FileUpload::make('content.video_img')->label("影片底圖")
439
+                                    ->disk("public")
440
+                                    ->helperText('檔案大小限制為1MB以下')
441
+                                    ->directory("esg/paragraphVideo"),
442
+                                    Translate::make()->schema(fn (string $locale) => [
443
+                                        TextInput::make('content.link')->label("網址")->required()
444
+                                        ->validationMessages([
445
+                                            'required' => '請附上連結',
446
+                                        ])
447
+                                    ])->locales(["zh_TW", "en"]),
448
+                                    Translate::make()->schema(fn (string $locale) => [
449
+                                        TextInput::make('content.video_alt')->label("影片註文"),
450
+                                    ])->locales(["zh_TW", "en"])
451
+                                ]),
452
+                            ])->visible(fn (Get $get):bool => $get("type") == 5),
453
+                        ])
454
+                        ->relationship("paragraphs")
455
+                        ->addActionLabel('新增段落')
456
+                        ->collapsible()
457
+                        ->reorderableWithButtons()
458
+                        ->orderColumn('order')
459
+                        ->cloneable()
460
+                        ->mutateRelationshipDataBeforeFillUsing(function (array $data): array {
461
+                            switch($data["type"]){
462
+                                case "1":
463
+                                    if (!empty($data["content"]['text_content'])) {
464
+                                        $content = is_string($data["content"]['text_content'])
465
+                                            ? json_decode($data["content"]['text_content'], true)
466
+                                            : $data["content"]['text_content'];
467
+
468
+                                        if (is_array($content)) {
469
+                                            $data["content"]['text_content_tw'] = $content['zh_TW'] ?? '';
470
+                                            $data["content"]['text_content_en'] = $content['en'] ?? '';
471
+                                        }
472
+                                    }
473
+                                    break;
474
+                                case "2":
475
+                                    if (!empty($data["content"]['text_blocks']) && count($data["content"]['text_blocks']) > 0) {
476
+                                        foreach ($data["content"]['text_blocks'] as $block_index => $block){
477
+                                            $content = is_string($block['block_content'])
478
+                                                ? json_decode($block['block_content'], true)
479
+                                                : $block['block_content'];
480
+
481
+                                            if (is_array($content)) {
482
+                                                $data["content"]['text_blocks'][$block_index]["block_content_tw"] = $content['zh_TW'] ?? '';
483
+                                                $data["content"]['text_blocks'][$block_index]["block_content_en"] = $content['en'] ?? '';
484
+                                            }
485
+                                        }
486
+                                    }
487
+                                    break;
488
+                                case "3":
489
+                                    if (!empty($data["content"]['simple_table_rows']) && count($data["content"]['simple_table_rows']) > 0) {
490
+                                        foreach ($data["content"]['simple_table_rows'] as $row_key => $row) {
491
+                                            $flatRow = [];
492
+
493
+                                            foreach ($row as $key => $value) {
494
+                                                if (is_array($value) && isset($value['zh_TW'], $value['en'])) {
495
+                                                    // 多语言字段,分离为两个字段
496
+                                                    $flatRow[$key . '_tw'] = $value['zh_TW'];
497
+                                                    $flatRow[$key . '_en'] = $value['en'];
498
+                                                } else {
499
+                                                    // 非多语言字段,保持原样
500
+                                                    $flatRow[$key] = $value;
501
+                                                }
502
+                                            }
503
+
504
+                                            $data["content"]['simple_table_rows'][$row_key] = $flatRow;
505
+                                        }
506
+                                    }
507
+                                    break;
508
+                            }
509
+                            return $data;
510
+                        })
511
+                        ->mutateRelationshipDataBeforeSaveUsing(function (array $data): array {
512
+                            switch($data["type"]){
513
+                                case "1":
514
+                                    $data["content"]["text_content"] = ["zh_TW" => $data["content"]["text_content_tw"] ?? "" , "en" => $data["content"]["text_content_en"] ?? ""];
515
+                                    // 移除臨時的分離欄位,只保留合併的 JSON 欄位
516
+                                    unset($data["content"]["text_content_tw"]);
517
+                                    unset($data["content"]["text_content_en"]);
518
+
519
+                                    // 清理 HTML 標籤(如果需要)
520
+                                    foreach ($data['content']['text_content'] as $locale => $content) {
521
+                                        $data['content']['text_content'][$locale] = stripslashes($content);
522
+                                    }
523
+                                    break;
524
+                                case "2":
525
+                                    // 確保有 text_blocks
526
+                                    if (!isset($data['content']['text_blocks'])) {
527
+                                        $data['content']['text_blocks'] = [];
528
+                                    }
529
+
530
+                                    // 處理每個文字區塊
531
+                                    foreach ($data['content']['text_blocks'] as $index => &$block) {
532
+                                        // 確保區塊有必要的欄位
533
+                                        $block['block_item_key'] = $block['block_item_key'] ?? Str::random();
534
+                                        $block['order'] = $block['order'] ?? ($index + 1);
535
+
536
+                                        $block["block_content"] = ["zh_TW" => $block["block_content_tw"] ?? "" , "en" => $block["block_content_en"] ?? ""];
537
+                                        // 移除臨時的分離欄位,只保留合併的 JSON 欄位
538
+                                        unset($block["block_content_tw"]);
539
+                                        unset($block["block_content_en"]);
540
+                                        // 清理區塊內容
541
+                                        if (isset($block['block_content'])) {
542
+                                            foreach ($block['block_content'] as $locale => $content) {
543
+                                                $block['block_content'][$locale] = stripslashes($content);
544
+                                            }
545
+                                        }
546
+                                    }
547
+                                    break;
548
+                                case "3":
549
+                                    // 確保欄數設定
550
+                                    $columnCount = $data['content']['column_count'] ?? 2;
551
+
552
+                                    // 確保表頭存在
553
+                                    if (!isset($data['content']['headers'])) {
554
+                                        $data['content']['headers'] = ['zh_TW' => [], 'en' => []];
555
+                                    }
556
+
557
+                                    // 確保表格資料存在
558
+                                    if (!isset($data['content']['simple_table_rows'])) {
559
+                                        $data['content']['simple_table_rows'] = [];
560
+                                    }
561
+
562
+                                    // 處理表格資料,確保欄數一致
563
+                                    foreach ($data['content']['simple_table_rows'] as $rowIndex => &$row) {
564
+                                        // 確保每行都有正確的欄數
565
+                                        for ($i = 1; $i <= $columnCount; $i++) {
566
+                                            $row["col{$i}"] = ["zh_TW" => $row["col{$i}_tw"] ?? "" , "en" => $row["col{$i}_en"] ?? ""];
567
+                                            foreach ($row["col{$i}"] as $locale => $content) {
568
+                                                $row["col{$i}"][$locale] = $content;
569
+                                            }
570
+                                            unset($row["col{$i}_tw"]);
571
+                                            unset($row["col{$i}_en"]);
572
+                                            $row["align{$i}"] = ["zh_TW" => $row["align{$i}_tw"] ?? "" , "en" => $row["align{$i}_en"] ?? ""];
573
+                                            foreach ($row["align{$i}"] as $locale => $content) {
574
+                                                $row["align{$i}"][$locale] = $content;
575
+                                            }
576
+                                            unset($row["align{$i}_tw"]);
577
+                                            unset($row["align{$i}_en"]);
578
+                                        }
579
+
580
+                                        // 移除多餘的欄位
581
+                                        for ($i = $columnCount + 1; $i <= 4; $i++) {
582
+                                            unset($row["col{$i}_tw"]);
583
+                                            unset($row["col{$i}_en"]);
584
+                                            unset($row["align{$i}_tw"]);
585
+                                            unset($row["align{$i}_en"]);
586
+                                        }
587
+                                    }
588
+                                    break;
589
+                            }
590
+                            return $data;
591
+                        })
592
+                        ->mutateRelationshipDataBeforeCreateUsing(function (array $data): array {
593
+                            switch($data["type"]){
594
+                                case "1":
595
+                                    $data["content"]["text_content"] = ["zh_TW" => $data["content"]["text_content_tw"] ?? "" , "en" => $data["content"]["text_content_en"] ?? ""];
596
+                                    // 移除臨時的分離欄位,只保留合併的 JSON 欄位
597
+                                    unset($data["content"]["text_content_tw"]);
598
+                                    unset($data["content"]["text_content_en"]);
599
+
600
+                                    // 清理 HTML 標籤(如果需要)
601
+                                    foreach ($data['content']['text_content'] as $locale => $content) {
602
+                                        $data['content']['text_content'][$locale] = stripslashes($content);
603
+                                    }
604
+                                    break;
605
+                                case "2":
606
+                                    // 確保有 text_blocks
607
+                                    if (!isset($data['content']['text_blocks'])) {
608
+                                        $data['content']['text_blocks'] = [];
609
+                                    }
610
+
611
+                                    // 處理每個文字區塊
612
+                                    foreach ($data['content']['text_blocks'] as $index => &$block) {
613
+                                        // 確保區塊有必要的欄位
614
+                                        $block['block_item_key'] = $block['block_item_key'] ?? Str::random();
615
+                                        $block['order'] = $block['order'] ?? ($index + 1);
616
+
617
+                                        $block["block_content"] = ["zh_TW" => $block["block_content_tw"] ?? "" , "en" => $block["block_content_en"] ?? ""];
618
+                                        // 移除臨時的分離欄位,只保留合併的 JSON 欄位
619
+                                        unset($block["block_content_tw"]);
620
+                                        unset($block["block_content_en"]);
621
+                                        // 清理區塊內容
622
+                                        if (isset($block['block_content'])) {
623
+                                            foreach ($block['block_content'] as $locale => $content) {
624
+                                                $block['block_content'][$locale] = stripslashes($content);
625
+                                            }
626
+                                        }
627
+                                    }
628
+                                    break;
629
+                                case "3":
630
+                                    // 確保欄數設定
631
+                                    $columnCount = $data['content']['column_count'] ?? 2;
632
+
633
+                                    // 確保表頭存在
634
+                                    if (!isset($data['content']['headers'])) {
635
+                                        $data['content']['headers'] = ['zh_TW' => [], 'en' => []];
636
+                                    }
637
+
638
+                                    // 確保表格資料存在
639
+                                    if (!isset($data['content']['simple_table_rows'])) {
640
+                                        $data['content']['simple_table_rows'] = [];
641
+                                    }
642
+
643
+                                    // 處理表格資料,確保欄數一致
644
+                                    foreach ($data['content']['simple_table_rows'] as $rowIndex => &$row) {
645
+                                        // 確保每行都有正確的欄數
646
+                                        for ($i = 1; $i <= $columnCount; $i++) {
647
+                                            $row["col{$i}"] = ["zh_TW" => $row["col{$i}_tw"] ?? "" , "en" => $row["col{$i}_en"] ?? ""];
648
+                                            foreach ($row["col{$i}"] as $locale => $content) {
649
+                                                $row["col{$i}"][$locale] = $content;
650
+                                            }
651
+                                            unset($row["col{$i}_tw"]);
652
+                                            unset($row["col{$i}_en"]);
653
+                                            $row["align{$i}"] = ["zh_TW" => $row["align{$i}_tw"] ?? "" , "en" => $row["align{$i}_en"] ?? ""];
654
+                                            foreach ($row["align{$i}"] as $locale => $content) {
655
+                                                $row["align{$i}"][$locale] = $content;
656
+                                            }
657
+                                            unset($row["align{$i}_tw"]);
658
+                                            unset($row["align{$i}_en"]);
659
+                                        }
660
+
661
+                                        // 移除多餘的欄位
662
+                                        for ($i = $columnCount + 1; $i <= 4; $i++) {
663
+                                            unset($row["col{$i}_tw"]);
664
+                                            unset($row["col{$i}_en"]);
665
+                                            unset($row["align{$i}_tw"]);
666
+                                            unset($row["align{$i}_en"]);
667
+                                        }
668
+                                    }
669
+                                    break;
670
+                            }
671
+                            \Log::info($data);
672
+                            return $data;
673
+                        })
674
+                    ])->columnSpanFull(),
675
+                ])
676
+                ->columnSpanFull()
677
+            ]);
678
+    }
679
+
680
+    public static function table(Table $table): Table
681
+    {
682
+        return $table
683
+            ->columns([
684
+                //
685
+                TextColumn::make("title")->label("標題"),
686
+            ])
687
+            ->filters([
688
+                //
689
+            ])
690
+            ->actions([
691
+                Tables\Actions\EditAction::make(),
692
+            ]);
693
+    }
694
+
695
+    public static function getRelations(): array
696
+    {
697
+        return [
698
+            //
699
+        ];
700
+    }
701
+
702
+    public static function getPages(): array
703
+    {
704
+        return [
705
+            'index' => Pages\ListEsg::route('/'),
706
+            'create' => Pages\CreateEsg::route('/create'),
707
+            'edit' => Pages\EditEsg::route('/{record}/edit'),
708
+        ];
709
+    }
710
+}

+ 43
- 0
app/Filament/Resources/EsgResource/Pages/CreateEsg.php Просмотреть файл

@@ -0,0 +1,43 @@
1
+<?php
2
+
3
+namespace App\Filament\Resources\EsgResource\Pages;
4
+
5
+use App\Filament\Resources\EsgResource;
6
+use App\Traits\HandlesEsgParagraphs;
7
+use Filament\Actions;
8
+use Filament\Resources\Pages\CreateRecord;
9
+use Illuminate\Database\Eloquent\Model;
10
+
11
+class CreateEsg extends CreateRecord
12
+{
13
+    use HandlesEsgParagraphs;
14
+    protected static string $resource = EsgResource::class;
15
+
16
+    protected function getRedirectUrl(): string
17
+    {
18
+        return $this->getResource()::getUrl('index');
19
+    }
20
+    protected function handleRecordCreation(array $data): Model
21
+    {
22
+        \Log::info("=== 開始建立流程 ===");
23
+
24
+        // ✅ 使用 Trait 方法處理表單中的 paragraphs
25
+        $processedParagraphs = $this->processFormParagraphs();
26
+
27
+        if ($processedParagraphs) {
28
+            \Log::info("預處理後的 paragraphs:", $processedParagraphs);
29
+        }
30
+
31
+        // 建立主記錄
32
+        $record = static::getModel()::create($data);
33
+        \Log::info("主記錄已建立:", ['id' => $record->id]);
34
+
35
+        // ✅ 使用 Trait 方法建立 paragraphs 關聯
36
+        if ($processedParagraphs) {
37
+            $this->createParagraphs($record, $processedParagraphs);
38
+        }
39
+
40
+        return $record->refresh();
41
+    }
42
+
43
+}

+ 53
- 0
app/Filament/Resources/EsgResource/Pages/EditEsg.php Просмотреть файл

@@ -0,0 +1,53 @@
1
+<?php
2
+
3
+namespace App\Filament\Resources\EsgResource\Pages;
4
+
5
+use App\Filament\Resources\EsgResource;
6
+use Filament\Actions;
7
+use Filament\Resources\Pages\EditRecord;
8
+use Illuminate\Database\Eloquent\Model;
9
+use App\Traits\HandlesEsgParagraphs;
10
+
11
+class EditEsg extends EditRecord
12
+{
13
+    use HandlesEsgParagraphs;
14
+    protected static string $resource = EsgResource::class;
15
+
16
+    protected function getRedirectUrl(): string
17
+    {
18
+        return $this->getResource()::getUrl('index');
19
+    }
20
+
21
+    /**
22
+     * 在填充表單前處理資料 - 手動載入關聯資料
23
+     */
24
+    protected function mutateFormDataBeforeFill(array $data): array
25
+    {
26
+
27
+        // ✅ 使用 Trait 方法載入並格式化 paragraphs
28
+        $data['paragraphs'] = $this->loadAndFormatParagraphs($this->record);
29
+        return $data;
30
+    }
31
+
32
+    protected function mutateFormDataBeforeSave(array $data): array
33
+    {
34
+        return $data;
35
+    }
36
+
37
+    /**
38
+     * 儲存時的處理
39
+     */
40
+    protected function handleRecordUpdate(Model $record, array $data): Model
41
+    {
42
+
43
+        // ✅ 使用 Trait 方法處理表單中的 paragraphs
44
+        $processedParagraphs = $this->processFormParagraphs();
45
+        // 更新主記錄
46
+        $record->update($data);
47
+        // ✅ 使用 Trait 方法處理 paragraphs 關聯
48
+        if ($processedParagraphs) {
49
+            $this->updateParagraphs($record, $processedParagraphs);
50
+        }
51
+        return $record->refresh();
52
+    }
53
+}

+ 19
- 0
app/Filament/Resources/EsgResource/Pages/ListEsg.php Просмотреть файл

@@ -0,0 +1,19 @@
1
+<?php
2
+
3
+namespace App\Filament\Resources\EsgResource\Pages;
4
+
5
+use App\Filament\Resources\EsgResource;
6
+use Filament\Actions;
7
+use Filament\Resources\Pages\ListRecords;
8
+
9
+class ListEsg extends ListRecords
10
+{
11
+    protected static string $resource = EsgResource::class;
12
+
13
+    protected function getHeaderActions(): array
14
+    {
15
+        return [
16
+            Actions\CreateAction::make(),
17
+        ];
18
+    }
19
+}

+ 1
- 0
app/Filament/Resources/NewsCategoryResource.php Просмотреть файл

@@ -21,6 +21,7 @@ class NewsCategoryResource extends Resource
21 21
     protected static ?string $navigationIcon = 'heroicon-o-rectangle-group';
22 22
     protected static ?string $navigationGroup = '上稿內容管理';
23 23
     protected static ?string $navigationLabel = "文章分類管理";
24
+    protected static bool $shouldRegisterNavigation = false;
24 25
 
25 26
     use Translatable;
26 27
     public static function form(Form $form): Form

+ 202
- 73
app/Filament/Resources/NewsResource.php Просмотреть файл

@@ -7,8 +7,11 @@ use App\Models\News;
7 7
 use App\Models\NewsCategory;
8 8
 use Filament\Forms\Components\Actions\Action;
9 9
 use Filament\Forms\Components\Group;
10
+use Filament\Forms\Components\Hidden;
10 11
 use Filament\Forms\Components\Repeater;
11 12
 use Filament\Forms\Components\RichEditor;
13
+use Filament\Forms\Components\Tabs;
14
+use Filament\Forms\Components\Tabs\Tab;
12 15
 use Filament\Forms\Components\TextInput;
13 16
 use Filament\Forms\Components\Textarea;
14 17
 use Filament\Forms\Components\Select;
@@ -16,9 +19,11 @@ use Filament\Forms\Components\Radio;
16 19
 use Filament\Forms\Components\Section;
17 20
 use Filament\Forms\Components\Toggle;
18 21
 use Filament\Forms\Components\DatePicker;
22
+use Filament\Forms\Components\DateTimePicker;
19 23
 use Filament\Forms\Components\FileUpload;
20 24
 use Filament\Forms\Get;
21 25
 use Filament\Forms\Form;
26
+use Filament\Forms\Set;
22 27
 use Filament\Resources\Resource;
23 28
 use Filament\Tables;
24 29
 use Filament\Tables\Columns\IconColumn;
@@ -29,8 +34,11 @@ use Filament\Tables\Table;
29 34
 use Illuminate\Database\Eloquent\Builder;
30 35
 use Illuminate\Support\Facades\DB;
31 36
 use Illuminate\Support\Str;
37
+use Malzariey\FilamentLexicalEditor\Enums\ToolbarItem;
38
+use Malzariey\FilamentLexicalEditor\FilamentLexicalEditor;
32 39
 use SolutionForest\FilamentTranslateField\Forms\Component\Translate;
33 40
 use RalphJSmit\Filament\SEO\SEO;
41
+use Illuminate\Support\HtmlString;
34 42
 
35 43
 class NewsResource extends Resource
36 44
 {
@@ -52,31 +60,102 @@ class NewsResource extends Resource
52 60
                         ->label("文章分類")
53 61
                         ->columnSpan(1)
54 62
                         ->native(false)
55
-                        ->Live(),
63
+                        ->afterStateHydrated(function ($component, $state) {
64
+                            // ✅ 如果沒有值,設定為第一項
65
+                            if (empty($state)) {
66
+                                $firstCategoryId = NewsCategory::first()?->id;
67
+                                if ($firstCategoryId) {
68
+                                    $component->state($firstCategoryId);
69
+                                }
70
+                            }
71
+                        })
72
+                        ->required(),
56 73
                     ])->columnSpanFull()->columns(2),
57 74
                     Group::make()->schema([
58 75
                         DatePicker::make('post_date')
59
-                        ->label("發布日期")
76
+                        ->label("文章日期")
77
+                        ->closeOnDateSelection()->required(),
78
+                        DateTimePicker::make('start_date')
79
+                        ->label("預約發布時間")
60 80
                         ->closeOnDateSelection(),
61
-                    ])->columnSpanFull()->columns(2),
81
+                        DateTimePicker::make('end_date')
82
+                        ->label("預約下架時間")
83
+                        ->closeOnDateSelection(),
84
+                    ])->columnSpanFull()->columns(3),
62 85
                     FileUpload::make('news_img_pc')->label("列表圖(desktop)")
63 86
                     ->disk("public")
87
+                    ->helperText('檔案大小限制為1MB以下')
64 88
                     // ->helperText('建議寬高限制為:1280*720px,檔案大小限制為1M以下')->maxSize('1024')
65 89
                     ->directory("news"),
66 90
                     FileUpload::make('news_img_mobile')->label("列表圖(mobile)")
67 91
                     ->disk("public")
92
+                    ->helperText('檔案大小限制為1MB以下')
68 93
                     // ->helperText('建議寬高限制為:600*896px,檔案大小限制為1M以下')->maxSize('1024')
69 94
                     ->directory("news"),
70 95
                     Translate::make()->schema(fn (string $locale) => [
71 96
                         TextInput::make('title')
72 97
                         ->label("標題")
98
+                        ->reactive()
99
+                        ->helperText(function (callable $get) {
100
+
101
+                            $activeLocale = $locale ?? 'zh_TW';
102
+
103
+                            $value = $get('title');
104
+
105
+                            $text = is_array($value)
106
+                                ? (string) ($value[$activeLocale] ?? '')
107
+                                : (string) ($value ?? '');
108
+
109
+                            $length = mb_strlen($text);
110
+                            $max = 24;
111
+
112
+                            $divClass = 'text-limit-amount';
113
+
114
+                            return new HtmlString("
115
+                                <div class='{$divClass} text-sm'>
116
+                                    目前字數:{$length} / {$max}
117
+                                </div>
118
+                            ");
119
+                        })
73 120
                         ->columnSpan(1),
74 121
                         TextInput::make('written_by')
75 122
                         ->label("發佈者")->columnSpan(1),
76
-                        Textarea::make("description")->rows(5)->columnSpanFull()->label("短文"),
123
+                        
124
+
125
+                        Textarea::make("description")
126
+                        ->rows(5)
127
+                        ->columnSpanFull()
128
+                        ->label("短文")
129
+                        ->maxLength(84)
130
+                        ->extraInputAttributes([
131
+                            'oninput' => 'if (this.value.length > 84) { this.value = this.value.slice(0, 84); }',
132
+                        ])
133
+                        ->reactive()
134
+                        ->helperText(function (callable $get) {
135
+
136
+                            $activeLocale = $locale ?? 'zh_TW';
137
+
138
+                            $value = $get('description');
139
+
140
+                            $text = is_array($value)
141
+                                ? (string) ($value[$activeLocale] ?? '')
142
+                                : (string) ($value ?? '');
143
+
144
+                            $length = mb_strlen($text);
145
+                            $max = 84;
146
+
147
+                            $divClass = 'text-limit-amount';
148
+
149
+                            return new HtmlString("
150
+                                <div class='{$divClass} text-sm'>
151
+                                    目前字數:{$length} / {$max}
152
+                                </div>
153
+                            ");
154
+                        })
77 155
                     ])->locales(["zh_TW", "en"])
78 156
                     ->id("main")
79 157
                     ->columnSpanFull()->columns(3),
158
+                    
80 159
                     TextInput::make('order')->label("排序")->integer()->default(0),
81 160
                 ])->columns(3),
82 161
                 Section::make("SEO")->schema([
@@ -89,6 +168,7 @@ class NewsResource extends Resource
89 168
                     ->locales(["zh_TW", "en"])
90 169
                     ->id("seo"),
91 170
                     FileUpload::make('meta_img')->label("放大預覽圖")->disk("public")
171
+                    ->helperText('檔案大小限制為1MB以下')
92 172
                     // ->helperText('建議寬高限制為:1200*630px,檔案大小限制為1M以下')->maxSize('1024')
93 173
                     ->directory("seo/news"),
94 174
                 ])->columnSpanFull(),
@@ -105,66 +185,94 @@ class NewsResource extends Resource
105 185
                         Radio::make("paragraph_type")->options([
106 186
                             1 => "圖片",
107 187
                             2 => "文字",
108
-                            3 => "影音"
188
+                            3 => "影音",
109 189
                         ])->label("")->default(1)->Live(),
110 190
                         Group::make()->schema([
111
-                            Translate::make()->schema(fn (string $locale) => [
112
-                                TextInput::make('image_alt')->label("圖片註文")->columnSpan(1),
113
-                            ])->locales(["zh_TW", "en"])
114
-                            ->id(fn ($get) => "para_img_" . $get('item_key')),
115
-                            FileUpload::make('image_url')->label("")->disk("public")
116
-                            // ->helperText('建議寬高限制為:1080*675px,檔案大小限制為1M以下')->maxSize('1024')
117
-                            ->directory("news/paragraph"),
118
-                            TextInput::make('image_link')->label("外連網址")->columnSpanFull()->url(),
119
-                        ])->visible(fn (Get $get):bool => $get("paragraph_type") == 1),
191
+                            Section::make('')->schema([
192
+                                Repeater::make("multiple_images")->schema([
193
+                                    TextInput::make('para_img_item_key')
194
+                                        ->default(fn () => Str::random())
195
+                                        ->hidden()
196
+                                        ->afterStateHydrated(function (TextInput $component, $state) {
197
+                                            if (empty($state)) {
198
+                                                $component->state(Str::random());
199
+                                            }
200
+                                        }),
201
+                                    Translate::make()->schema(fn (string $locale) => [
202
+                                        TextInput::make('image_alt')->label("圖片註文"),
203
+                                    ])->locales(["zh_TW", "en"])
204
+                                    ->id(fn ($get) => "para_img_mul_" . $get('para_img_item_key')),
205
+                                    FileUpload::make('image_url')->label("")->disk("public")
206
+                                    ->helperText('檔案大小限制為1MB以下')
207
+                                    // ->helperText('建議寬高限制為:1080*675px,檔案大小限制為1M以下')->maxSize('1024')
208
+                                    ->directory("news/extraPhoto")
209
+                                    ->maxFiles(10),
210
+                                ])
211
+                                ->relationship("photos")
212
+                                ->label("")
213
+                                ->orderColumn('order')
214
+                            ])
215
+                        ])->visible(fn (Get $get):bool => $get("paragraph_type") == 1),//
120 216
                         Group::make()->schema([
121
-                            Translate::make()->schema(fn (string $locale) => [
122
-                                RichEditor::make('text_content')
123
-                                ->toolbarButtons([
124
-                                    'blockquote',
125
-                                    'bold',
126
-                                    'bulletList',
127
-                                    'h2',
128
-                                    'h3',
129
-                                    'italic',
130
-                                    'link',
131
-                                    'orderedList',
132
-                                    'redo',
133
-                                    'strike',
134
-                                    'underline',
135
-                                    'undo',
217
+                            FilamentLexicalEditor::make('text_content_tw')
218
+                                // ->label('繁體中文內容')
219
+                                ->label(new \Illuminate\Support\HtmlString('繁體中文內容 <p href="#" style="cursor:pointer;color:blue;" onclick="var img = this.closest(\'div\').querySelector(\'img\');img.style.display = (img.style.display === \'none\') ? \'block\' : \'none\';"> 工具列說明</p><img src="' . asset('images/tool-bar.png') . '" style="display:none;">'))
220
+                                ->id(fn ($get) => "text_content_tw_" . $get('item_key') . "_" . uniqid())
221
+                                ->enabledToolbars([
222
+                                    ToolbarItem::UNDO, ToolbarItem::REDO, ToolbarItem::NORMAL,
223
+                                    ToolbarItem::H2, ToolbarItem::H3, ToolbarItem::H4, ToolbarItem::H5,
224
+                                    ToolbarItem::BULLET, ToolbarItem::NUMBERED, ToolbarItem::FONT_SIZE,
225
+                                    ToolbarItem::BOLD, ToolbarItem::ITALIC, ToolbarItem::UNDERLINE,
226
+                                    ToolbarItem::LINK, ToolbarItem::TEXT_COLOR, ToolbarItem::BACKGROUND_COLOR,
227
+                                    ToolbarItem::SUBSCRIPT, ToolbarItem::LOWERCASE, ToolbarItem::DIVIDER,
228
+                                    ToolbarItem::UPPERCASE, ToolbarItem::CLEAR, ToolbarItem::HR, ToolbarItem::FONT_FAMILY
136 229
                                 ])
137
-                                ->disableToolbarButtons([
138
-                                    'blockquote',
139
-                                    'strike',
140
-                                    'attachFiles',
230
+                                ->live(onBlur: true)
231
+                                ->columnSpanFull(),
232
+                            FilamentLexicalEditor::make('text_content_en')
233
+                                ->label('English Content')
234
+                                ->id(fn ($get) => "text_content_en_" . $get('item_key') . "_" . uniqid())
235
+                                ->enabledToolbars([
236
+                                    ToolbarItem::UNDO, ToolbarItem::REDO, ToolbarItem::NORMAL,
237
+                                    ToolbarItem::H2, ToolbarItem::H3, ToolbarItem::H4, ToolbarItem::H5,
238
+                                    ToolbarItem::BULLET, ToolbarItem::NUMBERED, ToolbarItem::FONT_SIZE,
239
+                                    ToolbarItem::BOLD, ToolbarItem::ITALIC, ToolbarItem::UNDERLINE,
240
+                                    ToolbarItem::LINK, ToolbarItem::TEXT_COLOR, ToolbarItem::BACKGROUND_COLOR,
241
+                                    ToolbarItem::SUBSCRIPT, ToolbarItem::LOWERCASE, ToolbarItem::DIVIDER,
242
+                                    ToolbarItem::UPPERCASE, ToolbarItem::CLEAR, ToolbarItem::HR, ToolbarItem::FONT_FAMILY
141 243
                                 ])
142
-                                ->fileAttachmentsDirectory('attachments')
143
-                                ->fileAttachmentsVisibility('private'),
144
-                            ])->locales(["zh_TW", "en"])
145
-                                ->id(fn ($get) => "para_text_" . $get('item_key')),
244
+                                ->columnSpanFull(),
146 245
                         ])->visible(fn (Get $get):bool => $get("paragraph_type") == 2),
147
-                            Group::make()->schema([
148
-                                Section::make("")->schema([
149
-                                    FileUpload::make('video_img')->label("影片底圖")
150
-                                    ->disk("public")
151
-                                    ->directory("news/paragraph/video"),
152
-                                    // ->helperText('建議寬高限制為:2000*720px,出血寬度720px,主要圖像範圍為:1280*720px,檔案大小限制為1M以下')->maxSize('1024'),
153
-                                    Radio::make("video_type")->label("")->options([
154
-                                        1 => "網址",
155
-                                        2 => "檔案"
156
-                                    ])->columnSpanFull()->default(1)->Live(),
157
-                                    Group::make()->schema([
158
-                                        TextInput::make('link')->label("網址")->nullable(),
159
-                                    ])->visible(fn (Get $get):bool => $get("video_type") == 1)->columnSpanFull(),
160
-                                    Group::make()->schema([
161
-                                        FileUpload::make('video_url')->label("")->disk("public")->directory("news/paragraph/video")
162
-                                        // ->helperText('建議影片寬高限制為:1920*1080px,出血寬度720px,大小限制為:100M以下')
163
-                                        // ->maxSize(102400)
164
-                                        ->nullable(),
165
-                                    ])->visible(fn (Get $get):bool => $get("video_type") == 2)->columnSpanFull(),
166
-                                ]),
167
-                            ])->visible(fn (Get $get):bool => $get("paragraph_type") == 3),
246
+                        Group::make()->schema([
247
+                            Section::make("")->schema([
248
+                                FileUpload::make('video_img')->label("影片底圖")
249
+                                ->disk("public")
250
+                                ->helperText('檔案大小限制為1MB以下')
251
+                                ->directory("news/paragraph/video"),
252
+                                // ->helperText('建議寬高限制為:2000*720px,出血寬度720px,主要圖像範圍為:1280*720px,檔案大小限制為1M以下')->maxSize('1024'),
253
+                                Translate::make()->schema(fn (string $locale) => [
254
+                                    TextInput::make('video_img_alt')->label("圖片註文")->columnSpan(1),
255
+                                ])->locales(["zh_TW", "en"])
256
+                                ->id(fn ($get) => "para_video_img_alt_" . $get('item_key')),
257
+                                Radio::make("video_type")->label("")->options([
258
+                                    1 => "網址",
259
+                                    2 => "檔案"
260
+                                ])->columnSpanFull()->default(1)->Live(),
261
+                                Group::make()->schema([
262
+                                    Translate::make()->schema(fn (string $locale) => [
263
+                                        TextInput::make('link')->label("網址")->nullable()->columnSpan(1)
264
+                                    ])->locales(["zh_TW", "en"])
265
+                                    ->id(fn ($get) => "para_link_" . $get('item_key')),
266
+                                ])->visible(fn (Get $get):bool => $get("video_type") == 1)->columnSpanFull(),
267
+                                Group::make()->schema([
268
+                                    FileUpload::make('video_url')->label("")->disk("public")->directory("news/paragraph/video")
269
+                                    ->helperText('檔案大小限制為100MB以下')
270
+                                    // ->helperText('建議影片寬高限制為:1920*1080px,出血寬度720px,大小限制為:100M以下')
271
+                                    // ->maxSize(102400)
272
+                                    ->nullable(),
273
+                                ])->visible(fn (Get $get):bool => $get("video_type") == 2)->columnSpanFull(),
274
+                            ]),
275
+                        ])->visible(fn (Get $get):bool => $get("paragraph_type") == 3),
168 276
                     ])
169 277
                     ->relationship("paragraphs")
170 278
                     ->label("段落")
@@ -172,33 +280,45 @@ class NewsResource extends Resource
172 280
                     ->reorderableWithButtons()
173 281
                     ->orderColumn('order')
174 282
                     ->cloneable()
283
+                    ->mutateRelationshipDataBeforeFillUsing(function (array $data): array {
284
+
285
+                        if ($data['paragraph_type'] == 2 && !empty($data['text_content'])) {
286
+                            $content = is_string($data['text_content'])
287
+                                ? json_decode($data['text_content'], true)
288
+                                : $data['text_content'];
289
+
290
+                            if (is_array($content)) {
291
+                                $data['text_content_tw'] = $content['zh_TW'] ?? '';
292
+                                $data['text_content_en'] = $content['en'] ?? '';
293
+                            }
294
+                        }
295
+
296
+                        return $data;
297
+                    })
298
+                    ->mutateRelationshipDataBeforeSaveUsing(function (array $data): array{
299
+                        if ($data['paragraph_type'] == 2) {
300
+                            $data["text_content"] = ["zh_TW" => $data["text_content_tw"], "en" => $data["text_content_en"]];
301
+                            // 移除臨時的分離欄位,只保留合併的 JSON 欄位
302
+                            unset($data['text_content_tw']);
303
+                            unset($data['text_content_en']);
304
+                        }
305
+                        return $data;
306
+                    })
175 307
                 ]),
176
-                Section::make("額外圖片")->schema([
177
-                    Repeater::make("extra_images")->schema([
178
-                        FileUpload::make('image_url')->label("")->disk("public")
179
-                        ->directory("news/extraPhoto")
180
-                        ->maxFiles(10),
181
-                        TextInput::make('image_link')->label("外連網址")->columnSpanFull()->url(),
182
-                    ])
183
-                    ->helperText('至少需上傳4張圖片才會出現圖片輯')
184
-                    ->relationship("photos")
185
-                    ->label("")
186
-                    ->collapsible()
187
-                    ->orderColumn('order')
188
-                    ->defaultItems(0)
189
-                ])->columns(5)
190 308
             ]);
191 309
     }
192 310
 
193 311
     public static function table(Table $table): Table
194 312
     {
313
+        $url = env('APP_URL')=="https://webdev.yico.tw:8088/" ? "https://demo.blockstudio.tw/yichiu/zh/news/" : "https://www.yico.tw/" ;
314
+
195 315
         return $table
196 316
             ->columns([
197 317
                 //
198 318
                 TextColumn::make("newsCategory.name")->label("分類")->alignCenter(),
199 319
                 TextColumn::make("title")->label("標題")->alignCenter(),
200 320
                 TextColumn::make("written_by")->label("發佈者")->alignCenter(),
201
-                TextColumn::make("post_date")->label("發佈時間")->dateTime('Y/m/d')->alignCenter(),
321
+                TextColumn::make("post_date")->label("文章時間")->dateTime('Y/m/d')->alignCenter(),
202 322
                 ImageColumn::make("news_img_pc_url")->label("列表圖")->alignCenter(),
203 323
                 TextColumn::make("list_audit_state")->label("狀態")->badge()
204 324
                 ->color(fn (string $state): string => match ($state) {
@@ -218,6 +338,8 @@ class NewsResource extends Resource
218 338
                     $record->on_top = !$record->on_top;
219 339
                     $record->save();
220 340
                 }),
341
+                TextColumn::make("start_date")->label("預計發佈時間")->dateTime('Y/m/d H:i:s')->alignCenter(),
342
+                TextColumn::make("end_date")->label("預計下架時間")->dateTime('Y/m/d H:i:s')->alignCenter(),
221 343
                 TextColumn::make("created_at")->label("建立時間")->dateTime('Y/m/d H:i:s')->alignCenter(),
222 344
                 TextColumn::make("updated_at")->label("更新時間")->dateTime()->alignCenter(),
223 345
             ])
@@ -269,6 +391,13 @@ class NewsResource extends Resource
269 391
                 })
270 392
                 ->outlined()
271 393
                 ->requiresConfirmation(),
394
+                Tables\Actions\Action::make('preview')
395
+                ->label('前台預覽')
396
+                ->icon('heroicon-m-arrow-top-right-on-square')
397
+                ->color('info')
398
+                ->url(fn ($record) => $url.$record->id."?preview=true")
399
+                ->openUrlInNewTab()
400
+                ->outlined(),
272 401
             ])
273 402
             ->bulkActions([
274 403
                 Tables\Actions\BulkActionGroup::make([

+ 1
- 0
app/Filament/Resources/NewsResource/Pages/CreateNews.php Просмотреть файл

@@ -17,6 +17,7 @@ class CreateNews extends CreateRecord
17 17
     }
18 18
     protected function handleRecordCreation(array $data): Model
19 19
     {
20
+        $data["visible"] = 0;
20 21
         return static::getModel()::create($data);
21 22
     }
22 23
 }

+ 2
- 1
app/Filament/Resources/UserResource.php Просмотреть файл

@@ -37,7 +37,8 @@ class UserResource extends Resource
37 37
                 ->relationship(
38 38
                 name: 'roles',
39 39
                 titleAttribute: 'name',
40
-                modifyQueryUsing: fn (Builder $query) => $query->whereNotIn("id", [1,2]),)
40
+                //modifyQueryUsing: fn (Builder $query) => $query->whereNotIn("id", [1,2]),
41
+                )
41 42
                 ->multiple()
42 43
                 ->preload()
43 44
         ]);

+ 152
- 0
app/Http/Controllers/Api/EsgController.php Просмотреть файл

@@ -0,0 +1,152 @@
1
+<?php
2
+
3
+namespace App\Http\Controllers\Api;
4
+
5
+use App\Http\Controllers\Controller;
6
+use App\Models\Esg;
7
+use App\Models\EsgMain;
8
+use App\Supports\Response;
9
+use Carbon\Carbon;
10
+use Illuminate\Http\Request;
11
+use Illuminate\Support\Facades\DB;
12
+use Illuminate\Support\Facades\Log;
13
+use App\Http\Helper\Helper;
14
+use Illuminate\Support\Facades\Storage;
15
+
16
+/**
17
+ * @group Lottery Prize
18
+ */
19
+class EsgController extends Controller
20
+{
21
+    public function __construct(
22
+    )
23
+    {
24
+    }
25
+
26
+    public function main($locate = 'tw')
27
+    {
28
+        $data = [];
29
+        $esgMain = EsgMain::first();
30
+        $locate = $locate == "tw" ? "zh_TW" : $locate;
31
+        $data = [
32
+            "meta" => [
33
+                "meta_title" => $esgMain->meta_title,
34
+                "meta_keyword" => $esgMain->meta_keyword,
35
+                "meta_description" => $esgMain->meta_description,
36
+                "og_img" => $esgMain->og_img_url
37
+            ],
38
+            "img_pc" => $esgMain->img_pc_url,
39
+            "img_mobile" => $esgMain->img_mobile_url,
40
+            "title" => $esgMain->getTranslation("title", $locate, false),
41
+            "description" => $esgMain->getTranslation("description", $locate, false),
42
+        ];
43
+        $esgs = Esg::select("title", "keyword")->get();
44
+        foreach($esgs as $esg){
45
+            $data["tab_list"][] = [
46
+                "text" => $esg->getTranslation("title", $locate, false),
47
+                "key" => $esg->keyword
48
+            ];
49
+        }
50
+        return response()->json(["data" => $data], 200);
51
+    }
52
+
53
+    public function esgContent($locate, $keyword){
54
+
55
+        $locate = $locate == "tw" ? "zh_TW" : $locate;
56
+        if (!$esg = Esg::getContentByKeyword($keyword)) {
57
+            return response()->json([
58
+                'status' => "fail",
59
+                'message' => '查無資料'
60
+            ]);
61
+        }
62
+
63
+        $data = [
64
+            "banner" => [
65
+                "img_pc" => $esg->banner_pc_url,
66
+                "img_mobile" => $esg->banner_mobile_url,
67
+                "img_alt" => $esg->getTranslation("banner_alt", $locate, false),
68
+                "text" => $esg->getTranslation("description", $locate, false),
69
+            ],
70
+            "paragraphs" => $this->prepareOutputContent($esg->paragraphs->toArray(), $locate)
71
+        ];
72
+
73
+        return response()->json(["data" => $data], 200);
74
+    }
75
+
76
+    private function prepareOutputContent($paragraphs, $locate): array
77
+    {
78
+        $output = [];
79
+        // 調試關聯資料
80
+        if($paragraphs){
81
+            foreach($paragraphs as $paragraph){
82
+                $content = $paragraph["content"];
83
+                switch ($paragraph["type"]){
84
+                    case "1":
85
+                        $output[] = [
86
+                            "type" => "text",
87
+                            "content" => $content["text_content"][$locate]
88
+                        ];
89
+                        break;
90
+                    case "2":
91
+                        $output[] = [
92
+                            "type" => "grid",
93
+                            "columns" => count($content["text_blocks"]),
94
+                            "content" => array_map(function($block) use ($locate) {
95
+                                return [
96
+                                    "type" => "text",
97
+                                    "content" => $block["block_content"][$locate]
98
+                                ];
99
+                            }, $content["text_blocks"])
100
+                        ];
101
+                        break;
102
+                    case "3":
103
+                        $column_count = $content["column_count"];
104
+                        $table_header = [];
105
+                        $table_content = [];
106
+                        for($i=1; $i<=$column_count; $i++){
107
+                            $table_header[] = [
108
+                                "align" => $content["head_align" . strval($i)][$locate],
109
+                                "text" => $content["head" . strval($i)][$locate]
110
+                            ];
111
+                            $table_row_content = [];
112
+                            foreach($content["simple_table_rows"] as $table_row){
113
+                                $table_row_content[] = [
114
+                                    "align" => $table_row["align" . strval($i)][$locate],
115
+                                    "text" => $table_row["col" . strval($i)][$locate]
116
+                                ];
117
+                            }
118
+                            $table_content[] = $table_row_content;
119
+                        }
120
+                        $output[] = [
121
+                            "type" => "table",
122
+                            "is_card" => boolval($content["is_card"]),
123
+                            "header" => $table_header,
124
+                            "body" => $table_content
125
+                        ];
126
+                        break;
127
+                    case "4":
128
+                        $output[] = [
129
+                            "type" => "image",
130
+                            "images" => array_map(function($image) use ($locate) {
131
+                                return [
132
+                                    "image_url" => Storage::disk("public")->url($image["image_url"]),
133
+                                    "alt" => $image["image_alt"][$locate]
134
+                                ];
135
+                            }, $content["multiple_images"])
136
+                        ];
137
+                        break;
138
+                    case "5":
139
+                        $output[] = [
140
+                            "type" => "video",
141
+                            "is_yt" => true,
142
+                            "video_img_url" => Storage::disk("public")->url($content["video_img"]),
143
+                            "video_url" => $content["link"][$locate],
144
+                            "content" => $content["video_alt"][$locate]
145
+                        ];
146
+                        break;
147
+                }
148
+            }
149
+        }
150
+        return $output;
151
+    }
152
+}

+ 149
- 79
app/Http/Controllers/Api/NewsController.php Просмотреть файл

@@ -24,21 +24,40 @@ class NewsController extends Controller
24 24
 
25 25
     public function list(Request $request, $locate = 'tw')
26 26
     {
27
-        $categoryId = $request->input("categoryId", "");
28 27
         $page = $request->input("page", 1);
29 28
         $per_page = $request->input("per_page", 15);
29
+        $year = $request->input("year", -1);
30
+        $month = $request->input("month", -1);
30 31
         $locate = $locate == "tw" ? "zh_TW" : $locate;
31 32
         $result = [];
32
-
33
-        //年份清單
34
-        $yearList = News::select(DB::raw("DATE_FORMAT(post_date, '%Y') as years"))->distinct()->orderBy("years", "desc")->pluck("years");
35
-        $result["yearList"] = $yearList;
33
+        
34
+        $dateFilter = Carbon::now();
35
+        $now = Carbon::now(); 
36 36
 
37 37
         //文章列表
38 38
         $news = News::where("visible", 1);
39
-        if($categoryId){
40
-            $news->where("news_category_id", $categoryId);
39
+        if($month > 0 || $year > 0){
40
+            
41
+            if($year > 0){
42
+                $dateFilter->setYear(intval($year));
43
+                if($month > 0){
44
+                    $dateFilter->setMonth(intval($month));
45
+                    $news = $news->whereBetween("post_date", [$dateFilter->copy()->startOfMonth(), $dateFilter->copy()->endOfMonth()]);
46
+                }else{
47
+                    $news = $news->whereBetween("post_date", [$dateFilter->copy()->startOfYear(), $dateFilter->copy()->endOfYear()]);
48
+                }
49
+                
50
+            }
41 51
         }
52
+
53
+        $news = $news->where(fn($q) =>
54
+            $q->whereNull('start_date')
55
+            ->orWhere('start_date', '<=', $now)
56
+        )->where(fn($q) =>
57
+            $q->whereNull('end_date')
58
+            ->orWhere('end_date', '>=', $now)
59
+        );
60
+
42 61
         $news = $news->orderByDesc("order")->orderByDesc("post_date");
43 62
         $result["pagination"] = [
44 63
             "page" => $page,
@@ -54,17 +73,18 @@ class NewsController extends Controller
54 73
             $result["pagination"]["total_page"] =$news->lastPage();
55 74
 
56 75
         }
76
+        $result["list"] = [];
57 77
         foreach($news as $item){
58 78
             $result["list"][] = [
59 79
                 "id" => $item->id,
60 80
                 "categoryId" => $item->newsCategory->id,
61
-                "category" => $item->newsCategory->getTranslation("name", $locate),
81
+                "category" => $item->newsCategory->getTranslation("name", $locate, false),
62 82
                 "postDate" => Carbon::parse($item->post_date)->format("Y.m.d"),
63
-                "title" => $item->getTranslation("title", $locate),
83
+                "title" => $item->getTranslation("title", $locate, false),
64 84
                 "imgPC" => $item->news_img_pc_url,
65 85
                 "imgMobile" => $item->news_img_mobile_url,
66
-                "written" => $item->getTranslation("written_by", $locate),
67
-                "description" => $item->getTranslation("description", $locate),
86
+                "written" => $item->getTranslation("written_by", $locate, false),
87
+                "description" => $item->getTranslation("description", $locate, false),
68 88
             ];
69 89
         }
70 90
         return response()->json(["data" => $result], 200);
@@ -77,139 +97,189 @@ class NewsController extends Controller
77 97
         $result = [];
78 98
 
79 99
         //年份清單
80
-        $yearList = News::select(DB::raw("DATE_FORMAT(post_date, '%Y') as years"))->distinct()->orderBy("years", "desc")->pluck("years");
100
+        $yearList = News::select(DB::raw("DATE_FORMAT(post_date, '%Y/%m') as years"))->distinct()->orderBy("years", "desc")->pluck("years");
81 101
 
82 102
         //文章列表
83
-        $news = News::where("visible", 1);
84
-        if($categoryId){
85
-            $news->where("news_category_id", $categoryId);
86
-        }
87
-        $news = $news->where('on_top', 1)->first();
103
+        $news = News::where("visible", 1)->where('on_top', 1)->first();
104
+        if($news)
88 105
         $result["data"] = [
89 106
             "meta" => [
90
-                "meta_title" => $news->getTranslation("meta_title", $locate),
91
-                "meta_keyword" => $news->getTranslation("meta_keyword", $locate),
92
-                "meta_description" => $news->getTranslation("meta_description", $locate),
107
+                "meta_title" => $news->getTranslation("meta_title", $locate, false),
108
+                "meta_keyword" => $news->getTranslation("meta_keyword", $locate, false),
109
+                "meta_description" => $news->getTranslation("meta_description", $locate, false),
93 110
                 "imgPC" => $news->news_meta_img,
94 111
             ],
95
-            "yearList" =>[
96
-                $yearList
97
-            ],
112
+            "yearList" => $yearList,
98 113
             "top" => [
99 114
                 "id" => $news->id,
100 115
                 "categoryId" => $news->newsCategory->id,
101
-                "category" => $news->newsCategory->getTranslation("name", $locate),
116
+                "category" => $news->newsCategory->getTranslation("name", $locate, false),
102 117
                 "postDate" => Carbon::parse($news->post_date)->format("Y/m/d"),
103
-                "title" => $news->getTranslation("title", $locate),
118
+                "title" => $news->getTranslation("title", $locate, false),
104 119
                 "imgPC" => $news->news_img_pc_url,
105 120
                 "imgMobile" => $news->news_img_mobile_url,
106
-                "written" => $news->getTranslation("written_by", $locate),
107
-                "description" => $news->getTranslation("description", $locate),
121
+                "written" => $news->getTranslation("written_by", $locate, false),
122
+                "description" => $news->getTranslation("description", $locate, false),
108 123
             ]
109 124
         ];
110 125
         return response()->json($result, 200);
111 126
     }
112 127
 
113
-    public function detail($locale = 'tw', $id){
128
+    public function detail(Request $request, $locale = 'tw', $id){
129
+
130
+        $isPreview = $request->input("preview","");
131
+        $now = Carbon::now(); 
132
+        
133
+        if($isPreview){
134
+            $news = News::where('id', $id)
135
+                ->first();
136
+        }else{
137
+            $news = News::where('id', $id)
138
+                ->where("visible", 1)
139
+                ->where(fn($q) =>
140
+                    $q->whereNull('start_date')
141
+                    ->orWhere('start_date', '<=', $now)
142
+                )->where(fn($q) =>
143
+                    $q->whereNull('end_date')
144
+                    ->orWhere('end_date', '>=', $now)
145
+                )
146
+                ->first();
147
+        }
148
+
149
+
114 150
         $locate = $locale == "tw" ? "zh_TW" : $locale;
115
-        $news = News::find($id);
151
+        
116 152
         $otherNewsList = [];
117
-
153
+        if(!$news){
154
+            return response()->json([
155
+                'message' => "news not found"], 404);
156
+        }
157
+// dd($news);
118 158
         //取得前一篇
119
-        $previous = News::where(function ($query) use ($news) {
159
+        $previous = News::where(function ($query) use ($news, $now) {
120 160
             $query->where('order', $news->order)
121 161
             ->where('post_date', $news->post_date)
122
-            ->where('id', '>', $news->id);
162
+            ->where('id', '>', $news->id)
163
+            ->where("visible", 1)
164
+            ->where(fn($q) => $q->whereNull('start_date')->orWhere('start_date', '<=', $now))
165
+            ->where(fn($q) => $q->whereNull('end_date')->orWhere('end_date', '>=', $now));
123 166
         })
124
-        ->orWhere(function ($query) use ($news) {
167
+        ->orWhere(function ($query) use ($news, $now) {
125 168
             $query->where('order', $news->order)
126
-            ->where('post_date', '>', $news->post_date);
169
+            ->where('post_date', '>', $news->post_date)
170
+            ->where("visible", 1)
171
+            ->where(fn($q) => $q->whereNull('start_date')->orWhere('start_date', '<=', $now))
172
+            ->where(fn($q) => $q->whereNull('end_date')->orWhere('end_date', '>=', $now));
127 173
         })
128
-        ->orWhere(function ($query) use ($news) {
129
-            $query->where('order', '>', $news->order);
174
+        ->orWhere(function ($query) use ($news, $now) {
175
+            $query->where('order', '>', $news->order)
176
+            ->where("visible", 1)
177
+            ->where(fn($q) => $q->whereNull('start_date')->orWhere('start_date', '<=', $now))
178
+            ->where(fn($q) => $q->whereNull('end_date')->orWhere('end_date', '>=', $now));
130 179
         })
131 180
         ->orderBy('order', 'asc')
132 181
         ->orderBy('post_date', 'asc')
133 182
         ->orderBy('id', 'asc')
134 183
         ->first();
184
+
135 185
         //取得下一篇
136
-        $next = News::where(function ($query) use ($news) {
186
+        $next = News::where(function ($query) use ($news, $now) {
137 187
             $query->where('order', $news->order)
138 188
             ->where('post_date', $news->post_date)
139
-            ->where('id', '<', $news->id);
189
+            ->where('id', '<', $news->id)
190
+            ->where("visible", 1)
191
+            ->where(fn($q) => $q->whereNull('start_date')->orWhere('start_date', '<=', $now))
192
+            ->where(fn($q) => $q->whereNull('end_date')->orWhere('end_date', '>=', $now));
140 193
         })
141
-        ->orWhere(function ($query) use ($news) {
194
+        ->orWhere(function ($query) use ($news, $now) {
142 195
             $query->where('order', $news->order)
143
-            ->where('post_date', '<', $news->post_date);
196
+            ->where('post_date', '<', $news->post_date)
197
+            ->where("visible", 1)
198
+            ->where(fn($q) => $q->whereNull('start_date')->orWhere('start_date', '<=', $now))
199
+            ->where(fn($q) => $q->whereNull('end_date')->orWhere('end_date', '>=', $now));
144 200
         })
145
-        ->orWhere(function ($query) use ($news) {
146
-            $query->where('order', '<', $news->order);
201
+        ->orWhere(function ($query) use ($news, $now) {
202
+            $query->where('order', '<', $news->order)
203
+            ->where("visible", 1)
204
+            ->where(fn($q) => $q->whereNull('start_date')->orWhere('start_date', '<=', $now))
205
+            ->where(fn($q) => $q->whereNull('end_date')->orWhere('end_date', '>=', $now));
147 206
         })
148 207
         ->orderBy('order', 'desc')
149 208
         ->orderBy('post_date', 'desc')
150 209
         ->orderBy('id', 'desc')
151 210
         ->first();
211
+
152 212
         if($previous)$otherNewsList["previous"] = [
153 213
             "id" => $previous->id,
154 214
             "categoryId" => $previous->newsCategory->id,
155
-            "category" => $previous->newsCategory->getTranslation("name", $locate),
215
+            "category" => $previous->newsCategory->getTranslation("name", $locate, false),
156 216
             "postDate" => Carbon::parse($previous->post_date)->format("Y/m/d"),
157
-            "title" => $previous->getTranslation("title", $locate),
217
+            "title" => $previous->getTranslation("title", $locate, false),
158 218
             "imgPC" => $previous->news_img_pc_url,
159 219
             "imgMobile" => $previous->news_img_mobile_url,
160
-            "written" => $previous->getTranslation("written_by", $locate),
161
-            "description" => $previous->getTranslation("description", $locate),
220
+            "written" => $previous->getTranslation("written_by", $locate, false),
221
+            "description" => $previous->getTranslation("description", $locate, false),
162 222
         ];
163 223
         if($next)$otherNewsList["next"] = [
164 224
             "id" => $next->id,
165 225
             "categoryId" => $next->newsCategory->id,
166
-            "category" => $next->newsCategory->getTranslation("name", $locate),
167
-            "postDate" => Carbon::parse($previous->post_date)->format("Y/m/d"),
168
-            "title" => $next->getTranslation("title", $locate),
226
+            "category" => $next->newsCategory->getTranslation("name", $locate, false),
227
+            "postDate" => Carbon::parse($next->post_date)->format("Y/m/d"),
228
+            "title" => $next->getTranslation("title", $locate, false),
169 229
             "imgPC" => $next->news_img_pc_url,
170 230
             "imgMobile" => $next->news_img_mobile_url,
171
-            "written" => $next->getTranslation("written_by", $locate),
172
-            "description" => $next->getTranslation("description", $locate),
231
+            "written" => $next->getTranslation("written_by", $locate, false),
232
+            "description" => $next->getTranslation("description", $locate, false),
173 233
         ];
174 234
 
175
-
176 235
         $paragraphs = [];
177 236
         foreach($news->paragraphs as $paragraph){
178
-            $paragraphs[] = [
179
-                "type" => $paragraph->contentType(),
180
-                "imgUrl" => $paragraph->paragraph_img,
181
-                "imgOutLink" => $paragraph->image_link,
182
-                "alt" => $paragraph->getTranslation("image_alt", $locate),
183
-                "content" => nl2br($paragraph->getTranslation("text_content", $locate)),
184
-                "videoImg" => $paragraph->paragraph_video_img,
185
-                "videoType" => $paragraph->paragraph_video_type,
186
-                "link" => $paragraph->paragraph_video_url,
187
-            ];
188
-        }
189
-        $extraPhotos = [];
190
-        foreach($news->photos as $photo){
191
-            $extraPhotos[] = [
192
-                "imgUrl" => $photo->news_photo_img,
193
-                "imgOutLink" => $photo->image_link,
194
-            ];
237
+            $content = [];
238
+            switch ($paragraph->contentType()){
239
+                case "text":
240
+                    $paragraphs[] = [
241
+                        "type" => $paragraph->contentType(),
242
+                        "content" => nl2br($paragraph->getTextContent($locate)),
243
+                    ];
244
+                    break;
245
+                case "image":
246
+                    $photos = $paragraph->photos;
247
+                    $images = [];
248
+                    foreach($photos as $photo){
249
+                        $images[] = ["img_url" => $photo->news_photo_img, "alt" => $photo->getTranslation("image_alt", $locate, false)];
250
+                    }
251
+                    $paragraphs[] = [
252
+                        "type" => $paragraph->contentType(),
253
+                        "images" => $images,
254
+                    ];
255
+                    break;
256
+                case "video":
257
+                    $paragraphs[] = [
258
+                        "type" => $paragraph->contentType(),
259
+                        "video_img_url" => $paragraph->paragraph_video_img,
260
+                        "is_yt" => $paragraph->video_type == 1 ? true : false,
261
+                        "content" => $paragraph->getTranslation("video_img_alt", $locate, false),
262
+                        "video_url" => $paragraph->getTranslation("link", $locate, false),
263
+                    ];
264
+                    break;
265
+            }
195 266
         }
196 267
         $result = [
197 268
             "categoryId" => $news->newsCategory->id,
198
-            "category" => $news->newsCategory->getTranslation("name", $locate),
269
+            "category" => $news->newsCategory->getTranslation("name", $locate, false),
199 270
             "postDate" => Carbon::parse($news->post_date)->format("Y/m/d"),
200
-            "title" => $news->getTranslation("title", $locate),
201
-            "description" => $news->getTranslation("description", $locate),
202
-            "written" => $news->getTranslation("written_by", $locate),
271
+            "title" => $news->getTranslation("title", $locate, false),
272
+            "description" => $news->getTranslation("description", $locate, false),
273
+            "written" => $news->getTranslation("written_by", $locate, false),
203 274
             "imgPC" => $news->news_img_pc_url,
204 275
             "imgMobile" => $news->news_img_mobile_url,
205
-            "metaTitle" => $news->getTranslation("meta_title", $locate),
206
-            "metaKeyword" => $news->getTranslation("meta_keyword", $locate),
207
-            "metaDesc" => $news->getTranslation("meta_description", $locate),
276
+            "metaTitle" => $news->getTranslation("meta_title", $locate, false),
277
+            "metaKeyword" => $news->getTranslation("meta_keyword", $locate, false),
278
+            "metaDesc" => $news->getTranslation("meta_description", $locate, false),
208 279
             "metaImg" => $news->meta_img,
209
-            "paragraphs" => $paragraphs,
210
-            "photos" => $extraPhotos,
211
-            "otherNews" => $otherNewsList
280
+            "paragraphs" => $paragraphs
212 281
         ];
282
+        if(!empty($otherNewsList)) $result["otherNews"] = $otherNewsList;
213 283
         return response()->json(["data" => $result], 200);
214 284
     }
215 285
 }

+ 44
- 0
app/Models/Esg.php Просмотреть файл

@@ -0,0 +1,44 @@
1
+<?php
2
+
3
+namespace App\Models;
4
+
5
+use Illuminate\Database\Eloquent\Casts\Attribute;
6
+use Illuminate\Database\Eloquent\Factories\HasFactory;
7
+use Illuminate\Database\Eloquent\Model;
8
+use Illuminate\Database\Eloquent\SoftDeletes;
9
+use Illuminate\Support\Facades\Storage;
10
+use Spatie\Translatable\HasTranslations;
11
+
12
+class Esg extends Model
13
+{
14
+    use HasFactory, SoftDeletes, HasTranslations;
15
+    //
16
+    protected $guarded = ["id"];
17
+    protected $casts = [
18
+        'on_top' => 'boolean'
19
+    ];
20
+    protected $appends = ["banner_pc_url", "banner_mobile_url"];
21
+
22
+    public $translatable = ['title', 'banner_alt', 'description'];
23
+
24
+    public function paragraphs(){
25
+        return $this->hasMany(EsgParagraph::class)->orderBy('order');
26
+    }
27
+    protected function bannerPcUrl(): Attribute
28
+    {
29
+        return Attribute::make(
30
+            get: fn ($value) => is_null($this->banner_pc) ? null :Storage::disk('public')->url($this->banner_pc),
31
+        );
32
+    }
33
+
34
+    protected function bannerMobileUrl(): Attribute
35
+    {
36
+        return Attribute::make(
37
+            get: fn ($value) => is_null($this->banner_mobile) ? null :Storage::disk('public')->url($this->banner_mobile),
38
+        );
39
+    }
40
+
41
+    protected function getContentByKeyword($keyword){
42
+        return $this->where("keyword", $keyword)->with('paragraphs')->first();
43
+    }
44
+}

+ 90
- 0
app/Models/EsgMain.php Просмотреть файл

@@ -0,0 +1,90 @@
1
+<?php
2
+
3
+namespace App\Models;
4
+
5
+use Illuminate\Database\Eloquent\Casts\Attribute;
6
+use Illuminate\Database\Eloquent\Model;
7
+use Illuminate\Support\Facades\Storage;
8
+use Spatie\Translatable\HasTranslations;
9
+
10
+class EsgMain extends Model
11
+{
12
+    use HasTranslations;
13
+    protected $guarded = ['id'];
14
+    protected $appends = ["img_pc_url", "og_img_url", "img_mobile_url"];
15
+    public $translatable = ['title', 'description', 'meta_title', 'meta_keyword', 'meta_description'];
16
+    protected function imgPcUrl(): Attribute
17
+    {
18
+        return Attribute::make(
19
+            get: fn ($value) => is_null($this->img_pc) ? null :Storage::disk('public')->url($this->img_pc),
20
+        );
21
+    }
22
+    protected function imgMobileUrl(): Attribute
23
+    {
24
+        return Attribute::make(
25
+            get: fn ($value) => is_null($this->img_mobile) ? null :Storage::disk('public')->url($this->img_mobile),
26
+        );
27
+    }
28
+    protected function ogImgUrl(): Attribute
29
+    {
30
+        return Attribute::make(
31
+            get: fn ($value) => is_null($this->og_img) ? null :Storage::disk('public')->url($this->og_img),
32
+        );
33
+    }
34
+    public static function getMain(): self
35
+    {
36
+        $main = self::first();
37
+        if(empty($main)){
38
+            $main = self::create(self::getDefaultData());
39
+        }
40
+        return $main;
41
+    }
42
+
43
+    /**
44
+     * ✅ 獲取預設設定值
45
+     */
46
+    public static function getDefaultData(): array
47
+    {
48
+        return [
49
+            'title' => [
50
+                'zh_TW' => '預設網站標題',
51
+                'en' => 'Default Site Title'
52
+            ],
53
+            'description' => [
54
+                'zh_TW' => '預設網站描述',
55
+                'en' => 'Default Site Description'
56
+            ],
57
+        ];
58
+    }
59
+
60
+    /**
61
+     * ✅ 安全的 toArray 方法,確保多語系欄位格式正確
62
+     */
63
+    public function safeToArray(): array
64
+    {
65
+        $array = $this->toArray();
66
+
67
+        // 確保多語系欄位是正確的格式
68
+        foreach ($this->translatable as $field) {
69
+            if (isset($array[$field])) {
70
+                // 如果是字串,轉換為多語系格式
71
+                if (is_string($array[$field])) {
72
+                    $array[$field] = [
73
+                        'zh_TW' => $array[$field],
74
+                        'en' => ''
75
+                    ];
76
+                }
77
+                // 確保有必要的語言鍵
78
+                if (is_array($array[$field])) {
79
+                    $array[$field]['zh_TW'] = $array[$field]['zh_TW'] ?? '';
80
+                    $array[$field]['en'] = $array[$field]['en'] ?? '';
81
+                }
82
+            } else {
83
+                // 如果欄位不存在,建立預設結構
84
+                $array[$field] = ['zh_TW' => '', 'en' => ''];
85
+            }
86
+        }
87
+
88
+        return $array;
89
+    }
90
+}

+ 52
- 0
app/Models/EsgParagraph.php Просмотреть файл

@@ -0,0 +1,52 @@
1
+<?php
2
+
3
+namespace App\Models;
4
+
5
+use Illuminate\Database\Eloquent\Casts\Attribute;
6
+use Illuminate\Database\Eloquent\Factories\HasFactory;
7
+use Illuminate\Database\Eloquent\Model;
8
+use Illuminate\Database\Eloquent\Relations\BelongsTo;
9
+use Illuminate\Database\Eloquent\SoftDeletes;
10
+use Illuminate\Support\Facades\Storage;
11
+use Spatie\Translatable\HasTranslations;
12
+
13
+class EsgParagraph extends Model
14
+{
15
+    use HasFactory, HasTranslations;
16
+    //
17
+    protected $fillable = [
18
+        'esg_id',
19
+        'type',
20
+        'order',
21
+        'content',
22
+    ];
23
+
24
+    protected $casts = [
25
+        'content' => 'array', // 自動轉換 JSON
26
+        'type' => 'integer',
27
+        'order' => 'integer'
28
+    ];
29
+
30
+    public function esg(): BelongsTo
31
+    {
32
+        return $this->belongsTo(Esg::class);
33
+    }
34
+
35
+    // ✅ 取得段落類型名稱
36
+    public function getTypeNameAttribute(): string
37
+    {
38
+        return match($this->type) {
39
+            1 => '純文字',
40
+            2 => '區塊文字',
41
+            3 => '表格',
42
+            4 => '圖片',
43
+            default => '未知',
44
+        };
45
+    }
46
+
47
+    // 如果你想要更細緻的控制,可以使用 accessor 和 mutator
48
+    public function getContentAttribute($value)
49
+    {
50
+        return $value ? json_decode($value, true) : [];
51
+    }
52
+}

+ 0
- 4
app/Models/News.php Просмотреть файл

@@ -32,10 +32,6 @@ class News extends Model
32 32
     public function paragraphs(){
33 33
         return $this->hasMany(NewsParagraph::class)->orderBy('order');
34 34
     }
35
-
36
-    public function photos(){
37
-        return $this->hasMany(NewsPhoto::class)->orderBy("order");
38
-    }
39 35
     protected function newsImgPcUrl(): Attribute
40 36
     {
41 37
         return Attribute::make(

+ 37
- 9
app/Models/NewsParagraph.php Просмотреть файл

@@ -19,8 +19,11 @@ class NewsParagraph extends Model
19 19
 
20 20
     protected $guarded = ['id'];
21 21
     public $timestamps = false;
22
-    protected $appends = ['paragraph_img', 'paragraph_video_img', 'paragraph_video_type', 'paragraph_video_url'];
23
-    public $translatable = ['text_content', 'image_alt'];
22
+    protected $appends = ['paragraph_video_img', 'paragraph_video_type', 'paragraph_video_url'];
23
+    public $translatable = ['video_img_alt', 'link'];
24
+    protected $casts = [
25
+        'text_content' => 'array',         // JSON 轉陣列
26
+    ];
24 27
 
25 28
     public function news(){
26 29
         return $this->belongsTo(News::class);
@@ -39,17 +42,17 @@ class NewsParagraph extends Model
39 42
                 return "";
40 43
         }
41 44
     }
42
-    protected function paragraphImg(): Attribute
43
-    {
44
-        return Attribute::make(
45
-            get: fn ($value) => is_null($this->image_url) ? null :Storage::disk('public')->url($this->image_url),
46
-        );
45
+
46
+    public function photos(){
47
+        return $this->hasMany(NewsPhoto::class)->orderBy("order");
47 48
     }
49
+
48 50
     protected function paragraphVideoType(): Attribute
49 51
     {
50 52
         return Attribute::make(
51
-            get: fn ($value) => ($this->paragraph_type == 3) ? ($this->attributes["video_type"] == 1 ? "url" : "upload") : null,
53
+            get: fn ($value) => ($this->paragraph_type == 3 && !is_null($this->video_type)) ? ($this->video_type == 1 ? "url" : "upload") : null,
52 54
         );
55
+
53 56
     }
54 57
     protected function paragraphVideoImg(): Attribute
55 58
     {
@@ -60,7 +63,32 @@ class NewsParagraph extends Model
60 63
     protected function paragraphVideoUrl(): Attribute
61 64
     {
62 65
         return Attribute::make(
63
-            get: fn ($value) => ($this->attributes["video_type"] == 2) ? Storage::disk('public')->url($this->attributes["video_url"]) : $this->attributes["link"],
66
+            get: fn ($value) => ($this->video_type == 2) ? Storage::disk('public')->url($this->video_url) : $this->link,
64 67
         );
65 68
     }
69
+    /**
70
+     * 取得特定語言的文字內容
71
+     */
72
+    public function getTextContent($locale = 'zh_TW'): string
73
+    {
74
+        if ($this->paragraph_type != 2) {
75
+            return '';
76
+        }
77
+
78
+        $content = $this->text_content;
79
+
80
+        if (is_array($content)) {
81
+            return $content[$locale] ?? '';
82
+        }
83
+
84
+        if (is_string($content)) {
85
+            $decoded = json_decode($content, true);
86
+            return $decoded[$locale] ?? '';
87
+        }
88
+
89
+        return '';
90
+    }
91
+
92
+
93
+
66 94
 }

+ 2
- 2
app/Models/NewsPhoto.php Просмотреть файл

@@ -19,8 +19,8 @@ class NewsPhoto extends Model
19 19
     protected $appends = ['news_photo_img'];
20 20
     public $translatable = ['image_alt'];
21 21
 
22
-    public function news(){
23
-        return $this->belongsTo(News::class);
22
+    public function paragraph(){
23
+        return $this->belongsTo(NewsParagraph::class);
24 24
     }
25 25
     protected function newsPhotoImg(): Attribute
26 26
     {

+ 418
- 0
app/Traits/HandlesEsgParagraphs.php Просмотреть файл

@@ -0,0 +1,418 @@
1
+<?php
2
+// app/Traits/HandlesParagraphs.php
3
+
4
+namespace App\Traits;
5
+
6
+use Illuminate\Database\Eloquent\Model;
7
+use Illuminate\Support\Str;
8
+
9
+trait HandlesEsgParagraphs
10
+{
11
+    /**
12
+     * 格式化 paragraphs 資料以符合表單結構(載入時使用)
13
+     */
14
+    protected function formatParagraphsForForm(array $paragraphs): array
15
+    {
16
+        $formattedParagraphs = [];
17
+
18
+        foreach ($paragraphs as $paragraph) {
19
+            $formatted = [
20
+                'id' => $paragraph['id'],
21
+                'type' => $paragraph['type'],
22
+                'order' => $paragraph['order'],
23
+                'content' => $paragraph['content'] ?? [],
24
+            ];
25
+
26
+            // 根據類型進行特殊格式化
27
+            switch ($paragraph['type']) {
28
+                case 1: // 純文字
29
+                    $formatted = $this->formatTextParagraphForForm($formatted);
30
+                    break;
31
+
32
+                case 2: // 區塊文字
33
+                    $formatted = $this->formatBlockParagraphForForm($formatted);
34
+                    break;
35
+
36
+                case 3: // 表格
37
+                    $formatted = $this->formatTableParagraphForForm($formatted);
38
+                    break;
39
+
40
+                case 4: // 圖片
41
+                    $formatted = $this->formatImageParagraphForForm($formatted);
42
+                    break;
43
+            }
44
+
45
+            // 確保有 item_key
46
+            if (!isset($formatted['item_key'])) {
47
+                $formatted['item_key'] = Str::random();
48
+            }
49
+
50
+            $formattedParagraphs[] = $formatted;
51
+        }
52
+
53
+        return $formattedParagraphs;
54
+    }
55
+
56
+    /**
57
+     * 格式化純文字段落(載入時)
58
+     */
59
+    protected function formatTextParagraphForForm(array $paragraph): array
60
+    {
61
+        // 確保 text_content 結構正確
62
+        if (!isset($paragraph['content']['text_content'])) {
63
+            $paragraph['content']['text_content'] = ['zh_TW' => '', 'en' => ''];
64
+        }
65
+
66
+        return $paragraph;
67
+    }
68
+
69
+    /**
70
+     * 格式化區塊文字段落(載入時)
71
+     */
72
+    protected function formatBlockParagraphForForm(array $paragraph): array
73
+    {
74
+        // 確保 text_blocks 結構正確
75
+        if (!isset($paragraph['content']['text_blocks'])) {
76
+            $paragraph['content']['text_blocks'] = [];
77
+        }
78
+
79
+        // 為每個 text_block 添加必要的欄位
80
+        foreach ($paragraph['content']['text_blocks'] as $index => &$block) {
81
+            if (!isset($block['block_item_key'])) {
82
+                $block['block_item_key'] = Str::random();
83
+            }
84
+            if (!isset($block['order'])) {
85
+                $block['order'] = $index + 1;
86
+            }
87
+        }
88
+
89
+        return $paragraph;
90
+    }
91
+
92
+    /**
93
+     * 格式化表格段落(載入時)
94
+     */
95
+    protected function formatTableParagraphForForm(array $paragraph): array
96
+    {
97
+        $content = $paragraph['content'];
98
+
99
+        if (!isset($content['column_count'])) {
100
+            $content['column_count'] = 2;
101
+        }
102
+
103
+        if (!isset($content['table_title'])) {
104
+            $content['table_title'] = ['zh_TW' => '', 'en' => ''];
105
+        }
106
+
107
+        if (!isset($content['table_description'])) {
108
+            $content['table_description'] = ['zh_TW' => '', 'en' => ''];
109
+        }
110
+
111
+        if (!isset($content['simple_table_rows'])) {
112
+            $content['simple_table_rows'] = [];
113
+        }
114
+
115
+        // 確保表頭資料結構
116
+        $columnCount = $content['column_count'];
117
+        for ($i = 1; $i <= $columnCount; $i++) {
118
+            if (!isset($content["head{$i}"])) {
119
+                $content["head{$i}"] = ['zh_TW' => '', 'en' => ''];
120
+            }
121
+        }
122
+
123
+        $paragraph['content'] = $content;
124
+
125
+        return $paragraph;
126
+    }
127
+
128
+    /**
129
+     * 格式化圖片段落(載入時)
130
+     */
131
+    protected function formatImageParagraphForForm(array $paragraph): array
132
+    {
133
+        // 確保 multiple_images 結構正確
134
+        if (!isset($paragraph['content']['multiple_images'])) {
135
+            $paragraph['content']['multiple_images'] = [];
136
+        }
137
+
138
+        // 為每個圖片添加必要的欄位
139
+        foreach ($paragraph['content']['multiple_images'] as $index => &$image) {
140
+            if (!isset($image['para_img_item_key'])) {
141
+                $image['para_img_item_key'] = Str::random();
142
+            }
143
+            if (!isset($image['order'])) {
144
+                $image['order'] = $index + 1;
145
+            }
146
+        }
147
+
148
+        return $paragraph;
149
+    }
150
+
151
+    /**
152
+     * 預處理 paragraphs 資料(儲存前使用)
153
+     */
154
+    protected function preprocessParagraphs(array $paragraphs): array
155
+    {
156
+        foreach ($paragraphs as $index => &$paragraph) {
157
+            \Log::info("處理段落 {$index}:", $paragraph);
158
+
159
+            // 確保基本欄位存在
160
+            $paragraph['content'] = $paragraph['content'] ?? [];
161
+            $paragraph['order'] = $paragraph['order'] ?? ($index + 1);
162
+
163
+            // 根據類型進行特殊處理
164
+            switch ($paragraph['type']) {
165
+                case 1: // 純文字
166
+                    $paragraph = $this->preprocessTextParagraph($paragraph);
167
+                    break;
168
+
169
+                case 2: // 區塊文字
170
+                    $paragraph = $this->preprocessBlockParagraph($paragraph);
171
+                    break;
172
+
173
+                case 3: // 表格
174
+                    $paragraph = $this->preprocessTableParagraph($paragraph);
175
+                    break;
176
+
177
+                case 4: // 圖片
178
+                    $paragraph = $this->preprocessImageParagraph($paragraph);
179
+                    break;
180
+            }
181
+
182
+            // 添加處理時間戳
183
+            $paragraph['content']['processed_at'] = now()->toISOString();
184
+
185
+            \Log::info("段落 {$index} 處理完成:", $paragraph);
186
+        }
187
+
188
+        return $paragraphs;
189
+    }
190
+
191
+    /**
192
+     * 處理純文字段落(儲存前)
193
+     */
194
+    protected function preprocessTextParagraph(array $paragraph): array
195
+    {
196
+        $paragraph["content"]["text_content"] = ["zh_TW" => $paragraph["content"]["text_content_tw"] ?? "" , "en" => $paragraph["content"]["text_content_en"] ?? ""];
197
+        // 移除臨時的分離欄位,只保留合併的 JSON 欄位
198
+        unset($paragraph["content"]["text_content_tw"]);
199
+        unset($paragraph["content"]["text_content_en"]);
200
+
201
+        // 清理 HTML 標籤(如果需要)
202
+        foreach ($paragraph['content']['text_content'] as $locale => $content) {
203
+            $paragraph['content']['text_content'][$locale] = $this->cleanHtml($content);
204
+        }
205
+
206
+        return $paragraph;
207
+    }
208
+
209
+    /**
210
+     * 處理區塊文字段落(儲存前)
211
+     */
212
+    protected function preprocessBlockParagraph(array $paragraph): array
213
+    {
214
+        // 確保有 text_blocks
215
+        if (!isset($paragraph['content']['text_blocks'])) {
216
+            $paragraph['content']['text_blocks'] = [];
217
+        }
218
+
219
+        // 處理每個文字區塊
220
+        foreach ($paragraph['content']['text_blocks'] as $index => &$block) {
221
+            // 確保區塊有必要的欄位
222
+            $block['block_item_key'] = $block['block_item_key'] ?? Str::random();
223
+            $block['order'] = $block['order'] ?? ($index + 1);
224
+
225
+            $block["block_content"] = ["zh_TW" => $block["block_content_tw"] ?? "" , "en" => $block["block_content_en"] ?? ""];
226
+            // 移除臨時的分離欄位,只保留合併的 JSON 欄位
227
+            unset($block["block_content_tw"]);
228
+            unset($block["block_content_en"]);
229
+            // 清理區塊內容
230
+            if (isset($block['block_content'])) {
231
+                foreach ($block['block_content'] as $locale => $content) {
232
+                    $block['block_content'][$locale] = $this->cleanHtml($content);
233
+                }
234
+            }
235
+        }
236
+
237
+        return $paragraph;
238
+    }
239
+
240
+    /**
241
+     * 處理表格段落(儲存前)
242
+     */
243
+    protected function preprocessTableParagraph(array $paragraph): array
244
+    {
245
+
246
+        // 確保欄數設定
247
+        $columnCount = $paragraph['content']['column_count'] ?? 2;
248
+
249
+        // 確保表頭存在
250
+        if (!isset($paragraph['content']['headers'])) {
251
+            $paragraph['content']['headers'] = ['zh_TW' => [], 'en' => []];
252
+        }
253
+
254
+        // 確保表格資料存在
255
+        if (!isset($paragraph['content']['simple_table_rows'])) {
256
+            $paragraph['content']['simple_table_rows'] = [];
257
+        }
258
+
259
+        // 處理表格資料,確保欄數一致
260
+        foreach ($paragraph['content']['simple_table_rows'] as $rowIndex => &$row) {
261
+            // 確保每行都有正確的欄數
262
+            for ($i = 1; $i <= $columnCount; $i++) {
263
+                $row["col{$i}"] = ["zh_TW" => $row["col{$i}_tw"] ?? "" , "en" => $row["col{$i}_en"] ?? ""];
264
+                unset($block["block_content_tw"]);
265
+                unset($block["block_content_en"]);
266
+                $row["align{$i}"] = ["zh_TW" => $row["align{$i}_tw"] ?? "" , "en" => $row["align{$i}_en"] ?? ""];
267
+                unset($row["align{$i}_tw"]);
268
+                unset($row["align{$i}_en"]);
269
+            }
270
+
271
+            // 移除多餘的欄位
272
+            for ($i = $columnCount + 1; $i <= 4; $i++) {
273
+                unset($row["col{$i}_tw"]);
274
+                unset($row["col{$i}_en"]);
275
+                unset($row["align{$i}_tw"]);
276
+                unset($row["align{$i}_en"]);
277
+            }
278
+        }
279
+
280
+        return $paragraph;
281
+    }
282
+
283
+    /**
284
+     * 處理圖片段落(儲存前)
285
+     */
286
+    protected function preprocessImageParagraph(array $paragraph): array
287
+    {
288
+        \Log::info("處理圖片段落");
289
+
290
+        // 確保圖片陣列存在
291
+        if (!isset($paragraph['content']['multiple_images'])) {
292
+            $paragraph['content']['multiple_images'] = [];
293
+        }
294
+
295
+        // 處理每個圖片
296
+        foreach ($paragraph['content']['multiple_images'] as $index => &$image) {
297
+            $image['para_img_item_key'] = $image['para_img_item_key'] ?? Str::random();
298
+            $image['order'] = $image['order'] ?? ($index + 1);
299
+
300
+            // 驗證圖片檔案是否存在
301
+            if (isset($image['image_url'])) {
302
+                // 這裡可以添加圖片驗證邏輯
303
+            }
304
+        }
305
+
306
+        return $paragraph;
307
+    }
308
+
309
+    /**
310
+     * 更新 paragraphs 關聯(編輯時使用)
311
+     */
312
+    protected function updateParagraphs(Model $record, array $paragraphs): void
313
+    {
314
+        // 獲取現有的段落 IDs
315
+        $existingIds = collect($paragraphs)
316
+            ->pluck('id')
317
+            ->filter()
318
+            ->values()
319
+            ->toArray();
320
+
321
+        // 刪除不在列表中的段落
322
+        $record->paragraphs()
323
+            ->whereNotIn('id', $existingIds)
324
+            ->delete();
325
+
326
+        // 更新或建立段落
327
+        foreach ($paragraphs as $paragraphData) {
328
+            if (isset($paragraphData['id'])) {
329
+                // 更新現有段落
330
+                $paragraph = $record->paragraphs()->find($paragraphData['id']);
331
+                if ($paragraph) {
332
+                    $paragraph->update([
333
+                        'type' => $paragraphData['type'],
334
+                        'order' => $paragraphData['order'],
335
+                        'content' => $paragraphData['content'],
336
+                    ]);
337
+                }
338
+            } else {
339
+                // 建立新段落
340
+                $newParagraph = $record->paragraphs()->create([
341
+                    'type' => $paragraphData['type'],
342
+                    'order' => $paragraphData['order'],
343
+                    'content' => $paragraphData['content'],
344
+                ]);
345
+            }
346
+        }
347
+    }
348
+
349
+    /**
350
+     * 建立 paragraphs 關聯(新增時使用)
351
+     */
352
+    protected function createParagraphs(Model $record, array $paragraphs): void
353
+    {
354
+        foreach ($paragraphs as $paragraphData) {
355
+            $newParagraph = $record->paragraphs()->create([
356
+                'type' => $paragraphData['type'],
357
+                'order' => $paragraphData['order'],
358
+                'content' => $paragraphData['content'],
359
+            ]);
360
+        }
361
+    }
362
+
363
+    /**
364
+     * 清理 HTML 內容
365
+     */
366
+    protected function cleanHtml(string $html): string
367
+    {
368
+        // 這裡可以根據需求自定義清理邏輯
369
+        // 例如:移除危險標籤、清理空白等
370
+        return trim($html);
371
+    }
372
+
373
+    /**
374
+     * 後處理 paragraphs(儲存後使用)
375
+     */
376
+    protected function postProcessParagraphs($paragraphs): void
377
+    {
378
+        foreach ($paragraphs as $paragraph) {
379
+            \Log::info("後處理段落:", [
380
+                'id' => $paragraph->id,
381
+                'type' => $paragraph->type,
382
+                'content_keys' => array_keys($paragraph->content ?? [])
383
+            ]);
384
+
385
+            // 這裡可以進行:
386
+            // - 快取更新
387
+            // - 搜尋索引更新
388
+            // - 通知發送
389
+            // 等後續處理
390
+        }
391
+    }
392
+
393
+    /**
394
+     * 獲取並格式化關聯資料(載入時的輔助方法)
395
+     */
396
+    protected function loadAndFormatParagraphs(Model $record): array
397
+    {
398
+        $paragraphs = $record->paragraphs()
399
+            ->orderBy('order')
400
+            ->get()
401
+            ->toArray();
402
+
403
+        return $this->formatParagraphsForForm($paragraphs);
404
+    }
405
+
406
+    /**
407
+     * 處理表單狀態中的 paragraphs(儲存時的輔助方法)
408
+     */
409
+    protected function processFormParagraphs(): ?array
410
+    {
411
+        $formState = $this->form->getState();
412
+        if (!isset($formState['paragraphs'])) {
413
+            return null;
414
+        }
415
+
416
+        return $this->preprocessParagraphs($formState['paragraphs']);
417
+    }
418
+}

+ 1
- 0
composer.json Просмотреть файл

@@ -13,6 +13,7 @@
13 13
         "filament/spatie-laravel-translatable-plugin": "^3.2",
14 14
         "laravel/framework": "^12.0",
15 15
         "laravel/tinker": "^2.10.1",
16
+        "malzariey/filament-lexical-editor": "^1.1",
16 17
         "pboivin/filament-peek": "^2.0",
17 18
         "solution-forest/filament-translate-field": "^1.4"
18 19
     },

+ 76
- 1
composer.lock Просмотреть файл

@@ -4,7 +4,7 @@
4 4
         "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
5 5
         "This file is @generated automatically"
6 6
     ],
7
-    "content-hash": "4dd77b45cb10dba97a9548c348c2a50d",
7
+    "content-hash": "e9061dad4ffa638a18cda5e044ab8b4f",
8 8
     "packages": [
9 9
         {
10 10
             "name": "anourvalar/eloquent-serialize",
@@ -3276,6 +3276,81 @@
3276 3276
             "time": "2025-04-12T22:26:52+00:00"
3277 3277
         },
3278 3278
         {
3279
+            "name": "malzariey/filament-lexical-editor",
3280
+            "version": "1.1",
3281
+            "source": {
3282
+                "type": "git",
3283
+                "url": "https://github.com/malzariey/filament-lexical-editor.git",
3284
+                "reference": "df8d9ffcfc078fdafaa85a4265fdf03d835d5b27"
3285
+            },
3286
+            "dist": {
3287
+                "type": "zip",
3288
+                "url": "https://api.github.com/repos/malzariey/filament-lexical-editor/zipball/df8d9ffcfc078fdafaa85a4265fdf03d835d5b27",
3289
+                "reference": "df8d9ffcfc078fdafaa85a4265fdf03d835d5b27",
3290
+                "shasum": ""
3291
+            },
3292
+            "require": {
3293
+                "filament/filament": "^3.0",
3294
+                "filament/forms": "^3.0",
3295
+                "php": "^8.1",
3296
+                "spatie/laravel-package-tools": "^1.15.0"
3297
+            },
3298
+            "require-dev": {
3299
+                "nunomaduro/collision": "^7.9",
3300
+                "orchestra/testbench": "^8.0",
3301
+                "pestphp/pest": "^2.1",
3302
+                "pestphp/pest-plugin-arch": "^2.0",
3303
+                "pestphp/pest-plugin-laravel": "^2.0"
3304
+            },
3305
+            "type": "library",
3306
+            "extra": {
3307
+                "laravel": {
3308
+                    "providers": [
3309
+                        "Malzariey\\FilamentLexicalEditor\\FilamentLexicalEditorServiceProvider"
3310
+                    ]
3311
+                }
3312
+            },
3313
+            "autoload": {
3314
+                "psr-4": {
3315
+                    "Malzariey\\FilamentLexicalEditor\\": "src/"
3316
+                }
3317
+            },
3318
+            "notification-url": "https://packagist.org/downloads/",
3319
+            "license": [
3320
+                "MIT"
3321
+            ],
3322
+            "authors": [
3323
+                {
3324
+                    "name": "Majid Al Zariey",
3325
+                    "email": "malzariey@hajarco.com",
3326
+                    "role": "Developer"
3327
+                }
3328
+            ],
3329
+            "description": "Implementation of meta's lexical editor in FilamentPHP, a modern, extensible text editor framework.",
3330
+            "homepage": "https://github.com/malzariey/filament-lexical-editor",
3331
+            "keywords": [
3332
+                "Malzariey",
3333
+                "editor",
3334
+                "filaemntPHP",
3335
+                "filament-lexical-editor",
3336
+                "laravel",
3337
+                "lexical",
3338
+                "rich-text",
3339
+                "text-editor"
3340
+            ],
3341
+            "support": {
3342
+                "issues": "https://github.com/malzariey/filament-lexical-editor/issues",
3343
+                "source": "https://github.com/malzariey/filament-lexical-editor"
3344
+            },
3345
+            "funding": [
3346
+                {
3347
+                    "url": "https://github.com/malzariey",
3348
+                    "type": "github"
3349
+                }
3350
+            ],
3351
+            "time": "2025-04-30T11:06:41+00:00"
3352
+        },
3353
+        {
3279 3354
             "name": "masterminds/html5",
3280 3355
             "version": "2.9.0",
3281 3356
             "source": {

+ 1
- 1
config/app.php Просмотреть файл

@@ -65,7 +65,7 @@ return [
65 65
     |
66 66
     */
67 67
 
68
-    'timezone' => 'UTC',
68
+    'timezone' => 'Asia/Taipei',
69 69
 
70 70
     /*
71 71
     |--------------------------------------------------------------------------

+ 3
- 3
config/filament-shield.php Просмотреть файл

@@ -80,9 +80,9 @@ return [
80 80
     ],
81 81
 
82 82
     'discovery' => [
83
-        'discover_all_resources' => false,
84
-        'discover_all_widgets' => false,
85
-        'discover_all_pages' => false,
83
+        'discover_all_resources' => true,
84
+        'discover_all_widgets' => true,
85
+        'discover_all_pages' => true,
86 86
     ],
87 87
 
88 88
     'register_role_policy' => [

+ 160
- 0
config/livewire.php Просмотреть файл

@@ -0,0 +1,160 @@
1
+<?php
2
+
3
+return [
4
+
5
+    /*
6
+    |---------------------------------------------------------------------------
7
+    | Class Namespace
8
+    |---------------------------------------------------------------------------
9
+    |
10
+    | This value sets the root class namespace for Livewire component classes in
11
+    | your application. This value will change where component auto-discovery
12
+    | finds components. It's also referenced by the file creation commands.
13
+    |
14
+    */
15
+
16
+    'class_namespace' => 'App\\Livewire',
17
+
18
+    /*
19
+    |---------------------------------------------------------------------------
20
+    | View Path
21
+    |---------------------------------------------------------------------------
22
+    |
23
+    | This value is used to specify where Livewire component Blade templates are
24
+    | stored when running file creation commands like `artisan make:livewire`.
25
+    | It is also used if you choose to omit a component's render() method.
26
+    |
27
+    */
28
+
29
+    'view_path' => resource_path('views/livewire'),
30
+
31
+    /*
32
+    |---------------------------------------------------------------------------
33
+    | Layout
34
+    |---------------------------------------------------------------------------
35
+    | The view that will be used as the layout when rendering a single component
36
+    | as an entire page via `Route::get('/post/create', CreatePost::class);`.
37
+    | In this case, the view returned by CreatePost will render into $slot.
38
+    |
39
+    */
40
+
41
+    'layout' => 'components.layouts.app',
42
+
43
+    /*
44
+    |---------------------------------------------------------------------------
45
+    | Lazy Loading Placeholder
46
+    |---------------------------------------------------------------------------
47
+    | Livewire allows you to lazy load components that would otherwise slow down
48
+    | the initial page load. Every component can have a custom placeholder or
49
+    | you can define the default placeholder view for all components below.
50
+    |
51
+    */
52
+
53
+    'lazy_placeholder' => null,
54
+
55
+    /*
56
+    |---------------------------------------------------------------------------
57
+    | Temporary File Uploads
58
+    |---------------------------------------------------------------------------
59
+    |
60
+    | Livewire handles file uploads by storing uploads in a temporary directory
61
+    | before the file is stored permanently. All file uploads are directed to
62
+    | a global endpoint for temporary storage. You may configure this below:
63
+    |
64
+    */
65
+
66
+    'temporary_file_upload' => [
67
+        'disk' => null,        // Example: 'local', 's3'              | Default: 'default'
68
+        'rules' => 'max:512000',       // Example: ['file', 'mimes:png,jpg']  | Default: ['required', 'file', 'max:12288'] (12MB)
69
+        'directory' => null,   // Example: 'tmp'                      | Default: 'livewire-tmp'
70
+        'middleware' => null,  // Example: 'throttle:5,1'             | Default: 'throttle:60,1'
71
+        'preview_mimes' => [   // Supported file types for temporary pre-signed file URLs...
72
+            'png', 'gif', 'bmp', 'svg', 'wav', 'mp4',
73
+            'mov', 'avi', 'wmv', 'mp3', 'm4a',
74
+            'jpg', 'jpeg', 'mpga', 'webp', 'wma',
75
+        ],
76
+        'max_upload_time' => 5, // Max duration (in minutes) before an upload is invalidated...
77
+        'cleanup' => true, // Should cleanup temporary uploads older than 24 hrs...
78
+    ],
79
+
80
+    /*
81
+    |---------------------------------------------------------------------------
82
+    | Render On Redirect
83
+    |---------------------------------------------------------------------------
84
+    |
85
+    | This value determines if Livewire will run a component's `render()` method
86
+    | after a redirect has been triggered using something like `redirect(...)`
87
+    | Setting this to true will render the view once more before redirecting
88
+    |
89
+    */
90
+
91
+    'render_on_redirect' => false,
92
+
93
+    /*
94
+    |---------------------------------------------------------------------------
95
+    | Eloquent Model Binding
96
+    |---------------------------------------------------------------------------
97
+    |
98
+    | Previous versions of Livewire supported binding directly to eloquent model
99
+    | properties using wire:model by default. However, this behavior has been
100
+    | deemed too "magical" and has therefore been put under a feature flag.
101
+    |
102
+    */
103
+
104
+    'legacy_model_binding' => false,
105
+
106
+    /*
107
+    |---------------------------------------------------------------------------
108
+    | Auto-inject Frontend Assets
109
+    |---------------------------------------------------------------------------
110
+    |
111
+    | By default, Livewire automatically injects its JavaScript and CSS into the
112
+    | <head> and <body> of pages containing Livewire components. By disabling
113
+    | this behavior, you need to use @livewireStyles and @livewireScripts.
114
+    |
115
+    */
116
+
117
+    'inject_assets' => true,
118
+
119
+    /*
120
+    |---------------------------------------------------------------------------
121
+    | Navigate (SPA mode)
122
+    |---------------------------------------------------------------------------
123
+    |
124
+    | By adding `wire:navigate` to links in your Livewire application, Livewire
125
+    | will prevent the default link handling and instead request those pages
126
+    | via AJAX, creating an SPA-like effect. Configure this behavior here.
127
+    |
128
+    */
129
+
130
+    'navigate' => [
131
+        'show_progress_bar' => true,
132
+        'progress_bar_color' => '#2299dd',
133
+    ],
134
+
135
+    /*
136
+    |---------------------------------------------------------------------------
137
+    | HTML Morph Markers
138
+    |---------------------------------------------------------------------------
139
+    |
140
+    | Livewire intelligently "morphs" existing HTML into the newly rendered HTML
141
+    | after each update. To make this process more reliable, Livewire injects
142
+    | "markers" into the rendered Blade surrounding @if, @class & @foreach.
143
+    |
144
+    */
145
+
146
+    'inject_morph_markers' => true,
147
+
148
+    /*
149
+    |---------------------------------------------------------------------------
150
+    | Pagination Theme
151
+    |---------------------------------------------------------------------------
152
+    |
153
+    | When enabling Livewire's pagination feature by using the `WithPagination`
154
+    | trait, Livewire will use Tailwind templates to render pagination views
155
+    | on the page. If you want Bootstrap CSS, you can specify: "bootstrap"
156
+    |
157
+    */
158
+
159
+    'pagination_theme' => 'tailwind',
160
+];

+ 1
- 1
database/migrations/2025_05_20_043733_create_news_table.php Просмотреть файл

@@ -22,7 +22,7 @@ return new class extends Migration
22 22
             $table->json('title')->comment("標題");
23 23
             $table->json('description')->comment("短文");
24 24
             $table->json('written_by')->comment("編輯人");
25
-            $table->dateTime('post_date')->comment("文章發布日");
25
+            $table->date('post_date')->comment("文章發布日");
26 26
             $table->string('meta_img')->nullable()->comment('seo image');
27 27
             $table->json("meta_title")->nullable()->comment("seo title");
28 28
             $table->json("meta_keyword")->nullable()->comment("seo keyword");

+ 2
- 3
database/migrations/2025_05_20_043735_create_news_paragraphs_table.php Просмотреть файл

@@ -17,12 +17,11 @@ return new class extends Migration
17 17
             $table->id();
18 18
             $table->unsignedBigInteger('news_id')->index();
19 19
             $table->foreign('news_id')->references('id')->on('news')->comment("關聯文章");
20
-            $table->unsignedTinyInteger('paragraph_type')->comment('段落類型 1.image 2.text');
21
-            $table->string('image_url')->nullable()->comment("圖片網址");
22
-            $table->json('image_alt')->nullable()->comment("圖片註釋");
20
+            $table->unsignedTinyInteger('paragraph_type')->comment('段落類型 1.images 2.text 3.video');
23 21
             $table->json('text_content')->nullable()->comment("文字段落");
24 22
             $table->integer("video_type")->nullable();
25 23
             $table->string("video_img")->nullable();
24
+            $table->json('video_img_alt')->nullable()->comment("圖片註釋");
26 25
             $table->string("link")->nullable();
27 26
             $table->string("video_url")->nullable();
28 27
             $table->unsignedInteger('order')->default(0)->comment("排序");

+ 2
- 2
database/migrations/2025_05_20_043736_create_news_photos_table.php Просмотреть файл

@@ -15,8 +15,8 @@ return new class extends Migration
15 15
 
16 16
         Schema::create('news_photos', function (Blueprint $table) {
17 17
             $table->id();
18
-            $table->unsignedBigInteger('news_id')->index();
19
-            $table->foreign('news_id')->references('id')->on('news')->comment("關聯文章");
18
+            $table->unsignedBigInteger('news_paragraph_id')->index();
19
+            $table->foreign('news_paragraph_id')->references('id')->on('news_paragraphs')->comment("關聯文章段落");
20 20
             $table->string('image_url')->nullable()->comment("圖片網址");
21 21
             $table->json('image_alt')->nullable()->comment("圖片註釋");
22 22
             $table->unsignedInteger('order')->default(0)->comment("排序");

+ 34
- 0
database/migrations/2025_06_18_072530_create_esgs_table.php Просмотреть файл

@@ -0,0 +1,34 @@
1
+<?php
2
+
3
+use Illuminate\Database\Migrations\Migration;
4
+use Illuminate\Database\Schema\Blueprint;
5
+use Illuminate\Support\Facades\Schema;
6
+
7
+return new class extends Migration
8
+{
9
+    /**
10
+     * Run the migrations.
11
+     */
12
+    public function up(): void
13
+    {
14
+        Schema::create('esgs', function (Blueprint $table) {
15
+            $table->id();
16
+            $table->string('keyword')->index();
17
+            $table->json('title')->comment('標題');
18
+            $table->json("description")->comment("短文");
19
+            $table->string("banner_pc")->comment("banner for pc");
20
+            $table->string("banner_mobile")->comment("banner for mobile");
21
+            $table->json("banner_alt")->comment("banner alt");
22
+            $table->timestamps();
23
+            $table->softDeletes();
24
+        });
25
+    }
26
+
27
+    /**
28
+     * Reverse the migrations.
29
+     */
30
+    public function down(): void
31
+    {
32
+        Schema::dropIfExists('esgs');
33
+    }
34
+};

+ 32
- 0
database/migrations/2025_06_18_075604_create_esg_paragraphs_table.php Просмотреть файл

@@ -0,0 +1,32 @@
1
+<?php
2
+
3
+use Illuminate\Database\Migrations\Migration;
4
+use Illuminate\Database\Schema\Blueprint;
5
+use Illuminate\Support\Facades\Schema;
6
+
7
+return new class extends Migration
8
+{
9
+    /**
10
+     * Run the migrations.
11
+     */
12
+    public function up(): void
13
+    {
14
+        Schema::create('esg_paragraphs', function (Blueprint $table) {
15
+            $table->id();
16
+            $table->foreignId('esg_id')->constrained()->onDelete('cascade');
17
+            $table->tinyInteger("type")->comment("1: 純editor 2:表格 3:影片 or 圖片 4:左右圖文");
18
+            $table->json("content");
19
+            $table->integer("order")->comment("排序");
20
+            $table->timestamps();
21
+            $table->index(['esg_id', 'order']);
22
+        });
23
+    }
24
+
25
+    /**
26
+     * Reverse the migrations.
27
+     */
28
+    public function down(): void
29
+    {
30
+        Schema::dropIfExists('esg_paragraphs');
31
+    }
32
+};

+ 35
- 0
database/migrations/2025_07_02_041600_create_esg_mains_table.php Просмотреть файл

@@ -0,0 +1,35 @@
1
+<?php
2
+
3
+use Illuminate\Database\Migrations\Migration;
4
+use Illuminate\Database\Schema\Blueprint;
5
+use Illuminate\Support\Facades\Schema;
6
+
7
+return new class extends Migration
8
+{
9
+    /**
10
+     * Run the migrations.
11
+     */
12
+    public function up(): void
13
+    {
14
+        Schema::create('esg_mains', function (Blueprint $table) {
15
+            $table->id();
16
+            $table->json('title')->comment("標題");
17
+            $table->json('description')->comment("短文");
18
+            $table->string('og_img')->nullable()->comment('seo image');
19
+            $table->json("meta_title")->nullable()->comment("seo title");
20
+            $table->json("meta_keyword")->nullable()->comment("seo keyword");
21
+            $table->json("meta_description")->nullable()->comment("seo description");
22
+            $table->string('img_pc')->nullable()->comment('Image PC');
23
+            $table->string('img_mobile')->nullable()->comment('Image MOBILE');
24
+            $table->timestamps();
25
+        });
26
+    }
27
+
28
+    /**
29
+     * Reverse the migrations.
30
+     */
31
+    public function down(): void
32
+    {
33
+        Schema::dropIfExists('esg_mains');
34
+    }
35
+};

+ 30
- 0
database/migrations/2026_01_13_082523_add_scheduled_date_to_news.php Просмотреть файл

@@ -0,0 +1,30 @@
1
+<?php
2
+
3
+use Illuminate\Database\Migrations\Migration;
4
+use Illuminate\Database\Schema\Blueprint;
5
+use Illuminate\Support\Facades\Schema;
6
+
7
+return new class extends Migration
8
+{
9
+    /**
10
+     * Run the migrations.
11
+     */
12
+    public function up(): void
13
+    {
14
+        Schema::table('news', function (Blueprint $table) {
15
+            $table->dateTime('start_date')->nullable()->comment("預約發布日期");
16
+            $table->dateTime('end_date')->nullable()->comment("預約下架日期");
17
+        });
18
+    }
19
+
20
+    /**
21
+     * Reverse the migrations.
22
+     */
23
+    public function down(): void
24
+    {
25
+        Schema::table('news', function (Blueprint $table) {
26
+            $table->dropColumn('start_date');
27
+            $table->dropColumn('end_date');
28
+        });
29
+    }
30
+};

+ 25
- 0
database/migrations/2026_04_01_145408_alter_esg_paragraphs_column.php Просмотреть файл

@@ -0,0 +1,25 @@
1
+<?php
2
+
3
+use Illuminate\Database\Migrations\Migration;
4
+use Illuminate\Database\Schema\Blueprint;
5
+use Illuminate\Support\Facades\Schema;
6
+
7
+return new class extends Migration
8
+{
9
+    /**
10
+     * Run the migrations.
11
+     */
12
+    public function up(): void
13
+    {
14
+        Schema::table('news_paragraphs', function (Blueprint $table) {
15
+            $table->text('link')->nullable()->change();
16
+        });
17
+    }
18
+
19
+    public function down(): void
20
+    {
21
+        Schema::table('news_paragraphs', function (Blueprint $table) {
22
+            $table->string('link', 255)->nullable()->change();
23
+        });
24
+    }
25
+};

+ 6279
- 0
public/css/malzariey/filament-lexical-editor/filament-lexical-editor-styles.css
Разница между файлами не показана из-за своего большого размера
Просмотреть файл


Двоичные данные
public/images/tool-bar.png Просмотреть файл


+ 44
- 0
public/js/malzariey/filament-lexical-editor/components/lexical-component.js
Разница между файлами не показана из-за своего большого размера
Просмотреть файл


+ 26
- 0
resources/css/app.css Просмотреть файл

@@ -9,3 +9,29 @@
9 9
     --font-sans: 'Instrument Sans', ui-sans-serif, system-ui, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji',
10 10
         'Segoe UI Symbol', 'Noto Color Emoji';
11 11
 }
12
+.lexical__h2 {
13
+    font-size: 32px;
14
+    font-weight: 700
15
+}
16
+
17
+.lexical__h3 {
18
+    font-size: 26px
19
+}
20
+
21
+.lexical__h4 {
22
+    font-size: 24px;
23
+    margin: 0;
24
+    line-height: 2.5
25
+}
26
+
27
+.lexical__h5 {
28
+    font-size: 20px;
29
+}
30
+
31
+.lexical__paragraph {
32
+    font-size: 16px;
33
+}
34
+
35
+ul {
36
+    font-size: 16px;
37
+}

+ 6600
- 0
resources/css/lexical-editor-extend.css
Разница между файлами не показана из-за своего большого размера
Просмотреть файл


+ 44
- 0
resources/js/lexical-editor-extend.js
Разница между файлами не показана из-за своего большого размера
Просмотреть файл


+ 11
- 0
resources/lang/zh_TW/filament-lexical-editor.php Просмотреть файл

@@ -0,0 +1,11 @@
1
+2️⃣ 檔案內容(照貼,不要多包一層)
2
+<?php
3
+
4
+return [
5
+    'lexical-editor' => [
6
+        'heading_2' => '標題二',
7
+        'heading_3' => '標題三',
8
+        'heading_4' => '標題四',
9
+        'heading_5' => '標題五',
10
+    ],
11
+];

+ 19
- 0
resources/lang/zh_TW/filament-panels.php Просмотреть файл

@@ -0,0 +1,19 @@
1
+<?php
2
+
3
+return [
4
+    'layout' => [
5
+        'actions' => [
6
+            'theme_switcher' => [
7
+                'system' => [
8
+                    'label' => '系統主題',
9
+                ],
10
+                'light' => [
11
+                    'label' => '亮色主題',
12
+                ],
13
+                'dark' => [
14
+                    'label' => '深色主題',
15
+                ],
16
+            ],
17
+        ],
18
+    ],
19
+];

+ 17
- 0
resources/views/filament/pages/esg-main.blade.php Просмотреть файл

@@ -0,0 +1,17 @@
1
+<x-filament-panels::page>
2
+    {{-- ✅ 確保不直接輸出陣列 --}}
3
+    <form wire:submit="save">
4
+        {{ $this->form }}
5
+
6
+        <div class="mt-6">
7
+            <x-filament::button
8
+                type="submit"
9
+                color="primary"
10
+                wire:loading.attr="disabled"
11
+            >
12
+                <span wire:loading.remove>儲存設定</span>
13
+                <span wire:loading>儲存中...</span>
14
+            </x-filament::button>
15
+        </div>
16
+    </form>
17
+</x-filament-panels::page>

+ 1
- 1
resources/views/welcome.blade.php
Разница между файлами не показана из-за своего большого размера
Просмотреть файл


+ 5
- 0
routes/api.php Просмотреть файл

@@ -1,5 +1,6 @@
1 1
 <?php
2 2
 
3
+use App\Http\Controllers\Api\EsgController;
3 4
 use App\Http\Controllers\Api\NewsController;
4 5
 use Illuminate\Http\Request;
5 6
 use Illuminate\Support\Facades\Route;
@@ -24,5 +25,9 @@ Route::prefix('{locale}')->group(function (){
24 25
         Route::get('/list', [NewsController::class, 'list']);
25 26
         Route::get('/detail/{id}', [NewsController::class, 'detail'])->whereIn('locale', ["tw", "en", "jp"])->where('id', '[0-9]+');
26 27
     });
28
+    Route::prefix('esg')->group(function () {
29
+        Route::get('/', [EsgController::class, "main"]);
30
+        Route::get('/{key}', [EsgController::class, "esgContent"]);
31
+    });
27 32
 })->whereIn('locale', ["tw", "en"]);
28 33
 

+ 1
- 1
routes/web.php Просмотреть файл

@@ -3,5 +3,5 @@
3 3
 use Illuminate\Support\Facades\Route;
4 4
 
5 5
 Route::get('/', function () {
6
-    return view('welcome');
6
+    return redirect("admin");
7 7
 });

+ 1
- 1
vite.config.js Просмотреть файл

@@ -5,7 +5,7 @@ import tailwindcss from '@tailwindcss/vite';
5 5
 export default defineConfig({
6 6
     plugins: [
7 7
         laravel({
8
-            input: ['resources/css/app.css', 'resources/js/app.js'],
8
+            input: ['resources/css/app.css', 'resources/js/app.js','resources/css/lexical-editor-extend.css','resources/js/lexical-editor-extend.js'],
9 9
             refresh: true,
10 10
         }),
11 11
         tailwindcss(),