xref: /webtrees/app/Module/ResearchTaskModule.php (revision 7413816e6dd2d50e569034fb804f3dce7471bb94)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2023 webtrees development team
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <https://www.gnu.org/licenses/>.
16 */
17
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees\Module;
21
22use Fisharebest\Webtrees\Auth;
23use Fisharebest\Webtrees\DB;
24use Fisharebest\Webtrees\Elements\DateValueToday;
25use Fisharebest\Webtrees\Elements\NoteStructure;
26use Fisharebest\Webtrees\Elements\ResearchTask;
27use Fisharebest\Webtrees\Elements\WebtreesUser;
28use Fisharebest\Webtrees\Family;
29use Fisharebest\Webtrees\GedcomRecord;
30use Fisharebest\Webtrees\I18N;
31use Fisharebest\Webtrees\Individual;
32use Fisharebest\Webtrees\Registry;
33use Fisharebest\Webtrees\Tree;
34use Fisharebest\Webtrees\Validator;
35use Illuminate\Database\Query\JoinClause;
36use Illuminate\Support\Collection;
37use Illuminate\Support\Str;
38use Psr\Http\Message\ServerRequestInterface;
39
40/**
41 * Class ResearchTaskModule
42 */
43class ResearchTaskModule extends AbstractModule implements ModuleBlockInterface
44{
45    use ModuleBlockTrait;
46
47    private const DEFAULT_SHOW_OTHER      = '1';
48    private const DEFAULT_SHOW_UNASSIGNED = '1';
49    private const DEFAULT_SHOW_FUTURE     = '1';
50
51    // 31 DEC 9999
52    private const MAXIMUM_JULIAN_DAY = 5373484;
53
54    // Pagination
55    private const LIMIT_LOW  = 10;
56    private const LIMIT_HIGH = 20;
57
58    /**
59     * Early initialisation.  Called before most of the middleware.
60     */
61    public function boot(): void
62    {
63        Registry::elementFactory()->registerTags([
64            'FAM:_TODO'           => new ResearchTask(I18N::translate('Research task')),
65            'FAM:_TODO:DATE'      => new DateValueToday(I18N::translate('Date')),
66            'FAM:_TODO:NOTE'      => new NoteStructure(I18N::translate('Note')),
67            'FAM:_TODO:_WT_USER'  => new WebtreesUser(I18N::translate('User')),
68            'INDI:_TODO'          => new ResearchTask(I18N::translate('Research task')),
69            'INDI:_TODO:DATE'     => new DateValueToday(I18N::translate('Date')),
70            'INDI:_TODO:NOTE'     => new NoteStructure(I18N::translate('Note')),
71            'INDI:_TODO:_WT_USER' => new WebtreesUser(I18N::translate('User')),
72        ]);
73
74        Registry::elementFactory()->make('FAM')->subtag('_TODO', '0:M');
75        Registry::elementFactory()->make('INDI')->subtag('_TODO', '0:M');
76    }
77
78    public function description(): string
79    {
80        /* I18N: Description of “Research tasks” module */
81        return I18N::translate('A list of tasks and activities that are linked to the family tree.');
82    }
83
84    /**
85     * Generate the HTML content of this block.
86     *
87     * @param Tree                 $tree
88     * @param int                  $block_id
89     * @param string               $context
90     * @param array<string,string> $config
91     *
92     * @return string
93     */
94    public function getBlock(Tree $tree, int $block_id, string $context, array $config = []): string
95    {
96        $show_other      = $this->getBlockSetting($block_id, 'show_other', self::DEFAULT_SHOW_OTHER);
97        $show_unassigned = $this->getBlockSetting($block_id, 'show_unassigned', self::DEFAULT_SHOW_UNASSIGNED);
98        $show_future     = $this->getBlockSetting($block_id, 'show_future', self::DEFAULT_SHOW_FUTURE);
99
100        extract($config, EXTR_OVERWRITE);
101
102        $end_jd      = $show_future ? self::MAXIMUM_JULIAN_DAY : Registry::timestampFactory()->now()->julianDay();
103        $individuals = $this->individualsWithTasks($tree, $end_jd);
104        $families    = $this->familiesWithTasks($tree, $end_jd);
105
106        $records = $individuals->merge($families);
107
108        $tasks = new Collection();
109
110        foreach ($records as $record) {
111            foreach ($record->facts(['_TODO'], false, null, true) as $task) {
112                $user_name = $task->attribute('_WT_USER');
113
114                if ($user_name === Auth::user()->userName()) {
115                    // Tasks belonging to us.
116                    $tasks->add($task);
117                } elseif ($user_name === '' && $show_unassigned) {
118                    // Tasks belonging to nobody.
119                    $tasks->add($task);
120                } elseif ($user_name !== '' && $show_other) {
121                    // Tasks belonging to others.
122                    $tasks->add($task);
123                }
124            }
125        }
126
127        if ($records->isEmpty()) {
128            $content = '<p>' . I18N::translate('There are no research tasks in this family tree.') . '</p>';
129        } else {
130            $content = view('modules/todo/research-tasks', [
131                'limit_low'  => self::LIMIT_LOW,
132                'limit_high' => self::LIMIT_HIGH,
133                'tasks'      => $tasks,
134            ]);
135        }
136
137        if ($context !== self::CONTEXT_EMBED) {
138            return view('modules/block-template', [
139                'block'      => Str::kebab($this->name()),
140                'id'         => $block_id,
141                'config_url' => $this->configUrl($tree, $context, $block_id),
142                'title'      => $this->title(),
143                'content'    => $content,
144            ]);
145        }
146
147        return $content;
148    }
149
150    /**
151     * @param Tree $tree
152     * @param int  $max_julian_day
153     *
154     * @return Collection<int,Individual>
155     */
156    private function individualsWithTasks(Tree $tree, int $max_julian_day): Collection
157    {
158        return DB::table('individuals')
159            ->join('dates', static function (JoinClause $join): void {
160                $join
161                    ->on('i_file', '=', 'd_file')
162                    ->on('i_id', '=', 'd_gid');
163            })
164            ->where('i_file', '=', $tree->id())
165            ->where('d_fact', '=', '_TODO')
166            ->where('d_julianday1', '<', $max_julian_day)
167            ->distinct()
168            ->select(['individuals.*'])
169            ->get()
170            ->map(Registry::individualFactory()->mapper($tree))
171            ->filter(GedcomRecord::accessFilter());
172    }
173
174    /**
175     * @param Tree $tree
176     * @param int  $max_julian_day
177     *
178     * @return Collection<int,Family>
179     */
180    private function familiesWithTasks(Tree $tree, int $max_julian_day): Collection
181    {
182        return DB::table('families')
183            ->join('dates', static function (JoinClause $join): void {
184                $join
185                    ->on('f_file', '=', 'd_file')
186                    ->on('f_id', '=', 'd_gid');
187            })
188            ->where('f_file', '=', $tree->id())
189            ->where('d_fact', '=', '_TODO')
190            ->where('d_julianday1', '<', $max_julian_day)
191            ->distinct()
192            ->select(['families.*'])
193            ->get()
194            ->map(Registry::familyFactory()->mapper($tree))
195            ->filter(GedcomRecord::accessFilter());
196    }
197
198    /**
199     * How should this module be identified in the control panel, etc.?
200     *
201     * @return string
202     */
203    public function title(): string
204    {
205        /* I18N: Name of a module. Tasks that need further research. */
206        return I18N::translate('Research tasks');
207    }
208
209    /**
210     * Should this block load asynchronously using AJAX?
211     *
212     * Simple blocks are faster in-line, more complex ones can be loaded later.
213     *
214     * @return bool
215     */
216    public function loadAjax(): bool
217    {
218        return false;
219    }
220
221    /**
222     * Can this block be shown on the user’s home page?
223     *
224     * @return bool
225     */
226    public function isUserBlock(): bool
227    {
228        return true;
229    }
230
231    /**
232     * Can this block be shown on the tree’s home page?
233     *
234     * @return bool
235     */
236    public function isTreeBlock(): bool
237    {
238        return true;
239    }
240
241    /**
242     * Update the configuration for a block.
243     *
244     * @param ServerRequestInterface $request
245     * @param int                    $block_id
246     *
247     * @return void
248     */
249    public function saveBlockConfiguration(ServerRequestInterface $request, int $block_id): void
250    {
251        $show_other      = Validator::parsedBody($request)->boolean('show_other', false);
252        $show_unassigned = Validator::parsedBody($request)->boolean('show_unassigned', false);
253        $show_future     = Validator::parsedBody($request)->boolean('show_future', false);
254
255        $this->setBlockSetting($block_id, 'show_other', (string) $show_other);
256        $this->setBlockSetting($block_id, 'show_unassigned', (string) $show_unassigned);
257        $this->setBlockSetting($block_id, 'show_future', (string) $show_future);
258    }
259
260    /**
261     * An HTML form to edit block settings
262     *
263     * @param Tree $tree
264     * @param int  $block_id
265     *
266     * @return string
267     */
268    public function editBlockConfiguration(Tree $tree, int $block_id): string
269    {
270        $show_other      = $this->getBlockSetting($block_id, 'show_other', self::DEFAULT_SHOW_OTHER);
271        $show_unassigned = $this->getBlockSetting($block_id, 'show_unassigned', self::DEFAULT_SHOW_UNASSIGNED);
272        $show_future     = $this->getBlockSetting($block_id, 'show_future', self::DEFAULT_SHOW_FUTURE);
273
274        return view('modules/todo/config', [
275            'show_future'     => $show_future,
276            'show_other'      => $show_other,
277            'show_unassigned' => $show_unassigned,
278        ]);
279    }
280}
281