xref: /webtrees/app/Module/ResearchTaskModule.php (revision 6172e7f6cb6d9b42e9feef9b728f7561b0d70dc9)
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\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    /**
56     * Early initialisation.  Called before most of the middleware.
57     */
58    public function boot(): void
59    {
60        Registry::elementFactory()->registerTags([
61            'FAM:_TODO'           => new ResearchTask(I18N::translate('Research task')),
62            'FAM:_TODO:DATE'      => new TransmissionDate(I18N::translate('Date')),
63            'FAM:_TODO:_WT_USER'  => new WebtreesUser(I18N::translate('User')),
64            'INDI:_TODO'          => new ResearchTask(I18N::translate('Research task')),
65            'INDI:_TODO:DATE'     => new TransmissionDate(I18N::translate('Date')),
66            'INDI:_TODO:_WT_USER' => new WebtreesUser(I18N::translate('User')),
67        ]);
68
69        Registry::elementFactory()->make('FAM')->subtag('_TODO', '0:M');
70        Registry::elementFactory()->make('INDI')->subtag('_TODO', '0:M');
71    }
72
73    /**
74     * A sentence describing what this module does.
75     *
76     * @return string
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 ? PHP_INT_MAX : 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']) 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            ->select(['individuals.*'])
168            ->distinct()
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            ->select(['families.*'])
192            ->distinct()
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        $params = (array) $request->getParsedBody();
252
253        $this->setBlockSetting($block_id, 'show_other', $params['show_other']);
254        $this->setBlockSetting($block_id, 'show_unassigned', $params['show_unassigned']);
255        $this->setBlockSetting($block_id, 'show_future', $params['show_future']);
256    }
257
258    /**
259     * An HTML form to edit block settings
260     *
261     * @param Tree $tree
262     * @param int  $block_id
263     *
264     * @return string
265     */
266    public function editBlockConfiguration(Tree $tree, int $block_id): string
267    {
268        $show_other      = $this->getBlockSetting($block_id, 'show_other', self::DEFAULT_SHOW_OTHER);
269        $show_unassigned = $this->getBlockSetting($block_id, 'show_unassigned', self::DEFAULT_SHOW_UNASSIGNED);
270        $show_future     = $this->getBlockSetting($block_id, 'show_future', self::DEFAULT_SHOW_FUTURE);
271
272        return view('modules/todo/config', [
273            'show_future'     => $show_future,
274            'show_other'      => $show_other,
275            'show_unassigned' => $show_unassigned,
276        ]);
277    }
278}
279