xref: /webtrees/app/Module/CensusAssistantModule.php (revision 2644e3b0ee745578b62f82c449a64f7ceb61bbc2)
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\Census\CensusInterface;
23use Fisharebest\Webtrees\I18N;
24use Fisharebest\Webtrees\Individual;
25use Fisharebest\Webtrees\Registry;
26use Fisharebest\Webtrees\Tree;
27use Psr\Http\Message\ResponseInterface;
28use Psr\Http\Message\ServerRequestInterface;
29
30use function array_keys;
31use function assert;
32use function count;
33use function e;
34use function response;
35use function str_repeat;
36use function str_replace;
37use function view;
38
39/**
40 * Class CensusAssistantModule
41 */
42class CensusAssistantModule extends AbstractModule
43{
44    /**
45     * How should this module be identified in the control panel, etc.?
46     *
47     * @return string
48     */
49    public function title(): string
50    {
51        /* I18N: Name of a module */
52        return I18N::translate('Census assistant');
53    }
54
55    /**
56     * A sentence describing what this module does.
57     *
58     * @return string
59     */
60    public function description(): string
61    {
62        /* I18N: Description of the “Census assistant” module */
63        return I18N::translate('An alternative way to enter census transcripts and link them to individuals.');
64    }
65
66    /**
67     * @param ServerRequestInterface $request
68     *
69     * @return ResponseInterface
70     */
71    public function postCensusHeaderAction(ServerRequestInterface $request): ResponseInterface
72    {
73        $params = (array) $request->getParsedBody();
74
75        $census = $params['census'];
76
77        $html = $this->censusTableHeader(new $census());
78
79        return response($html);
80    }
81
82    /**
83     * @param ServerRequestInterface $request
84     *
85     * @return ResponseInterface
86     */
87    public function postCensusIndividualAction(ServerRequestInterface $request): ResponseInterface
88    {
89        $tree = $request->getAttribute('tree');
90        assert($tree instanceof Tree);
91
92        $params       = (array) $request->getParsedBody();
93        $individual   = Registry::individualFactory()->make($params['xref'], $tree);
94        $head         = Registry::individualFactory()->make($params['head'], $tree);
95        $census_class = $params['census'];
96        $census       = new $census_class();
97
98        // No head of household?  Create a fake one.
99        $head = $head ?? Registry::individualFactory()->new('X', '0 @X@ INDI', null, $tree);
100
101        // Generate columns (e.g. relationship name) using the correct language.
102        I18N::init($census->censusLanguage());
103
104        if ($individual instanceof Individual && $head instanceof Individual) {
105            $html = $this->censusTableRow($census, $individual, $head);
106        } else {
107            $html = $this->censusTableEmptyRow($census);
108        }
109
110        return response($html);
111    }
112
113    /**
114     * @param Individual $individual
115     *
116     * @return string
117     */
118    public function createCensusAssistant(Individual $individual): string
119    {
120        return view('modules/census-assistant', [
121            'individual' => $individual,
122        ]);
123    }
124
125    /**
126     * @param ServerRequestInterface $request
127     * @param Individual             $individual
128     * @param string                 $fact_id
129     * @param string                 $newged
130     * @param bool                   $keep_chan
131     *
132     * @return string
133     */
134    public function updateCensusAssistant(ServerRequestInterface $request, Individual $individual, string $fact_id, string $newged, bool $keep_chan): string
135    {
136        $params = (array) $request->getParsedBody();
137
138        $ca_title       = $params['ca_title'] ?? '';
139        $ca_place       = $params['ca_place'] ?? '';
140        $ca_citation    = $params['ca_citation'] ?? '';
141        $ca_individuals = $params['ca_individuals'] ?? [];
142        $ca_notes       = $params['ca_notes'] ?? '';
143        $ca_census      = $params['ca_census'] ?? '';
144
145        if ($ca_census !== '' && $ca_individuals !== []) {
146            $census = new $ca_census();
147
148            $note_text   = $this->createNoteText($census, $ca_title, $ca_place, $ca_citation, $ca_individuals, $ca_notes);
149            $note_gedcom = '0 @@ NOTE ' . str_replace("\n", "\n1 CONT ", $note_text);
150            $note        = $individual->tree()->createRecord($note_gedcom);
151
152            $newged .= "\n2 NOTE @" . $note->xref() . '@';
153
154            // Add the census fact to the rest of the household
155            foreach ($ca_individuals['xref'] ?? [] as $xref) {
156                if ($xref !== '' && $xref !== $individual->xref()) {
157                    Registry::individualFactory()->make($xref, $individual->tree())
158                        ->updateFact($fact_id, $newged, !$keep_chan);
159                }
160            }
161        }
162
163        return $newged;
164    }
165
166    /**
167     * @param CensusInterface      $census
168     * @param string               $ca_title
169     * @param string               $ca_place
170     * @param string               $ca_citation
171     * @param array<array<string>> $ca_individuals
172     * @param string               $ca_notes
173     *
174     * @return string
175     */
176    private function createNoteText(CensusInterface $census, string $ca_title, string $ca_place, string $ca_citation, array $ca_individuals, string $ca_notes): string
177    {
178        $text = $ca_title;
179
180        if ($ca_citation !== '') {
181            // Two trailing spaces create a line-break in markdown
182            $text .= "  \n" . $ca_citation;
183        }
184
185        if ($ca_place !== '') {
186            // Two trailing spaces create a line-break in markdown
187            $text .= "  \n" . $ca_place;
188        }
189
190        $text .= "\n\n|";
191
192        foreach ($census->columns() as $column) {
193            $text .= ' ' . $column->abbreviation() . ' |';
194        }
195
196        $text .= "\n|" . str_repeat(' ----- |', count($census->columns()));
197
198        foreach (array_keys($ca_individuals['xref'] ?? []) as $key) {
199            $text .= "\n|";
200
201            foreach ($census->columns() as $n => $column) {
202                $text .= ' ' . $ca_individuals[$n][$key] . ' |';
203            }
204        }
205
206        if ($ca_notes !== '') {
207            $text .= "\n\n" . strtr($ca_notes, ["\r" => '']);
208        }
209
210        return $text;
211    }
212
213    /**
214     * Generate an HTML row of data for the census header
215     * Add prefix cell (store XREF and drag/drop)
216     * Add suffix cell (delete button)
217     *
218     * @param CensusInterface $census
219     *
220     * @return string
221     */
222    protected function censusTableHeader(CensusInterface $census): string
223    {
224        $html = '';
225        foreach ($census->columns() as $column) {
226            $html .= '<th class="wt-census-assistant-field" title="' . $column->title() . '">' . $column->abbreviation() . '</th>';
227        }
228
229        return '<tr class="wt-census-assistant-row"><th hidden></th>' . $html . '<th></th></tr>';
230    }
231
232    /**
233     * Generate an HTML row of data for the census
234     * Add prefix cell (store XREF and drag/drop)
235     * Add suffix cell (delete button)
236     *
237     * @param CensusInterface $census
238     *
239     * @return string
240     */
241    public function censusTableEmptyRow(CensusInterface $census): string
242    {
243        $html = '<td class="wt-census-assistant-field" hidden><input type="hidden" name="ca_individuals[xref][]"></td>';
244
245        foreach ($census->columns() as $n => $column) {
246            $html .= '<td class="wt-census-assistant-field p-0"><input class="form-control wt-census-assistant-form-control p-0" type="text" name="ca_individuals[' . $n . '][]"></td>';
247        }
248
249        $html .= '<td class="wt-census-assistant-field"><a href="#" title="' . I18N::translate('Remove') . '">' . view('icons/delete') . '</a></td>';
250
251        return '<tr class="wt-census-assistant-row">' . $html . '</tr>';
252    }
253
254    /**
255     * Generate an HTML row of data for the census
256     * Add prefix cell (store XREF and drag/drop)
257     * Add suffix cell (delete button)
258     *
259     * @param CensusInterface $census
260     * @param Individual      $individual
261     * @param Individual      $head
262     *
263     * @return string
264     */
265    public function censusTableRow(CensusInterface $census, Individual $individual, Individual $head): string
266    {
267        $html = '<td class="wt-census-assistant-field" hidden><input type="hidden" name="ca_individuals[xref][]" value="' . e($individual->xref()) . '"></td>';
268
269        foreach ($census->columns() as $n => $column) {
270            $html .= '<td class="wt-census-assistant-field p-0"><input class="form-control wt-census-assistant-form-control p-0" type="text" value="' . $column->generate($individual, $head) . '" name="ca_individuals[' . $n . '][]"></td>';
271        }
272
273        $html .= '<td class="wt-census-assistant-field"><a href="#" title="' . I18N::translate('Remove') . '">' . view('icons/delete') . '</a></td>';
274
275        return '<tr class="wt-census-assistant-row">' . $html . '</tr>';
276    }
277}
278