xref: /webtrees/app/Module/CensusAssistantModule.php (revision 090a06287954f43677f06ea778b3f67c029de8fe)
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\Registry;
24use Fisharebest\Webtrees\I18N;
25use Fisharebest\Webtrees\Individual;
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 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 . "\n" . $ca_citation . "\n" . $ca_place . "\n\n|";
179
180        foreach ($census->columns() as $column) {
181            $text .= ' ' . $column->abbreviation() . ' |';
182        }
183
184        $text .= "\n|" . str_repeat(' ----- |', count($census->columns()));
185
186        foreach (array_keys($ca_individuals['xref'] ?? []) as $key) {
187            $text .= "\n|";
188
189            foreach ($census->columns() as $n => $column) {
190                $text .= ' ' . $ca_individuals[$n][$key] . ' |';
191            }
192        }
193
194        return $text . "\n\n" . strtr($ca_notes, ["\r" => '']);
195    }
196
197    /**
198     * Generate an HTML row of data for the census header
199     * Add prefix cell (store XREF and drag/drop)
200     * Add suffix cell (delete button)
201     *
202     * @param CensusInterface $census
203     *
204     * @return string
205     */
206    protected function censusTableHeader(CensusInterface $census): string
207    {
208        $html = '';
209        foreach ($census->columns() as $column) {
210            $html .= '<th class="wt-census-assistant-field" title="' . $column->title() . '">' . $column->abbreviation() . '</th>';
211        }
212
213        return '<tr class="wt-census-assistant-row"><th hidden></th>' . $html . '<th></th></tr>';
214    }
215
216    /**
217     * Generate an HTML row of data for the census
218     * Add prefix cell (store XREF and drag/drop)
219     * Add suffix cell (delete button)
220     *
221     * @param CensusInterface $census
222     *
223     * @return string
224     */
225    public function censusTableEmptyRow(CensusInterface $census): string
226    {
227        $html = '<td class="wt-census-assistant-field" hidden><input type="hidden" name="ca_individuals[xref][]"></td>';
228
229        foreach ($census->columns() as $n => $column) {
230            $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>';
231        }
232
233        $html .= '<td class="wt-census-assistant-field"><a href="#" title="' . I18N::translate('Remove') . '">' . view('icons/delete') . '</a></td>';
234
235        return '<tr class="wt-census-assistant-row">' . $html . '</tr>';
236    }
237
238    /**
239     * Generate an HTML row of data for the census
240     * Add prefix cell (store XREF and drag/drop)
241     * Add suffix cell (delete button)
242     *
243     * @param CensusInterface $census
244     * @param Individual      $individual
245     * @param Individual      $head
246     *
247     * @return string
248     */
249    public function censusTableRow(CensusInterface $census, Individual $individual, Individual $head): string
250    {
251        $html = '<td class="wt-census-assistant-field" hidden><input type="hidden" name="ca_individuals[xref][]" value="' . e($individual->xref()) . '"></td>';
252
253        foreach ($census->columns() as $n => $column) {
254            $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>';
255        }
256
257        $html .= '<td class="wt-census-assistant-field"><a href="#" title="' . I18N::translate('Remove') . '">' . view('icons/delete') . '</a></td>';
258
259        return '<tr class="wt-census-assistant-row">' . $html . '</tr>';
260    }
261}
262