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