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