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