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