Completed
Pull Request — master (#3735)
by
unknown
07:12
created

CensusAssistantModule::updateCensusAssistant()   A

Complexity

Conditions 6
Paths 2

Size

Total Lines 30
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 18
nc 2
nop 5
dl 0
loc 30
rs 9.0444
c 0
b 0
f 0
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
18
declare(strict_types=1);
19
20
namespace Fisharebest\Webtrees\Module;
21
22
use Fisharebest\Webtrees\Census\CensusInterface;
23
use Fisharebest\Webtrees\Functions\Functions;
24
use Fisharebest\Webtrees\Registry;
25
use Fisharebest\Webtrees\I18N;
26
use Fisharebest\Webtrees\Individual;
27
use Fisharebest\Webtrees\Tree;
28
use Illuminate\Support\Collection;
29
use Psr\Http\Message\ResponseInterface;
30
use Psr\Http\Message\ServerRequestInterface;
31
32
use function array_keys;
33
use function assert;
34
use function count;
35
use function e;
36
use function response;
37
use function str_repeat;
38
use function str_replace;
39
use function strip_tags;
40
use function ucfirst;
41
use function view;
42
43
/**
44
 * Class CensusAssistantModule
45
 */
46
class CensusAssistantModule extends AbstractModule
47
{
48
    /**
49
     * How should this module be identified in the control panel, etc.?
50
     *
51
     * @return string
52
     */
53
    public function title(): string
54
    {
55
        /* I18N: Name of a module */
56
        return I18N::translate('Census assistant');
57
    }
58
59
    /**
60
     * A sentence describing what this module does.
61
     *
62
     * @return string
63
     */
64
    public function description(): string
65
    {
66
        /* I18N: Description of the “Census assistant” module */
67
        return I18N::translate('An alternative way to enter census transcripts and link them to individuals.');
68
    }
69
70
    /**
71
     * @param ServerRequestInterface $request
72
     *
73
     * @return ResponseInterface
74
     */
75
    public function postCensusHeaderAction(ServerRequestInterface $request): ResponseInterface
76
    {
77
        $params = (array) $request->getParsedBody();
78
79
        $census = $params['census'];
80
81
        $html = $this->censusTableHeader(new $census());
82
83
        return response($html);
84
    }
85
86
    /**
87
     * @param ServerRequestInterface $request
88
     *
89
     * @return ResponseInterface
90
     */
91
    public function postCensusIndividualAction(ServerRequestInterface $request): ResponseInterface
92
    {
93
        $tree = $request->getAttribute('tree');
94
        assert($tree instanceof Tree);
95
96
        $params       = (array) $request->getParsedBody();
97
        $individual   = Registry::individualFactory()->make($params['xref'], $tree);
98
        $head         = Registry::individualFactory()->make($params['head'], $tree);
99
        $census_class = $params['census'];
100
        $census       = new $census_class();
101
102
        // No head of household?  Create a fake one.
103
        $head = $head ?? Registry::individualFactory()->new('X', '0 @X@ INDI', null, $tree);
104
105
        // Generate columns (e.g. relationship name) using the correct language.
106
        I18N::init($census->censusLanguage());
107
108
        if ($individual instanceof Individual && $head instanceof Individual) {
109
            $html = $this->censusTableRow($census, $individual, $head);
110
        } else {
111
            $html = $this->censusTableEmptyRow($census);
112
        }
113
114
        return response($html);
115
    }
116
117
    /**
118
     * @param Individual $individual
119
     *
120
     * @return string
121
     */
122
    public function createCensusAssistant(Individual $individual): string
123
    {
124
        return view('modules/census-assistant', [
125
            'individual' => $individual,
126
            'options'    => $this->familyMembers($individual),
127
        ]);
128
    }
129
130
    /**
131
     * @param ServerRequestInterface $request
132
     * @param Individual             $individual
133
     * @param string                 $fact_id
134
     * @param string                 $newged
135
     * @param bool                   $keep_chan
136
     *
137
     * @return string
138
     */
139
    public function updateCensusAssistant(ServerRequestInterface $request, Individual $individual, string $fact_id, string $newged, bool $keep_chan): string
140
    {
141
        $params = (array) $request->getParsedBody();
142
143
        $ca_title       = $params['ca_title'] ?? '';
144
        $ca_place       = $params['ca_place'] ?? '';
145
        $ca_citation    = $params['ca_citation'] ?? '';
146
        $ca_individuals = $params['ca_individuals'] ?? [];
147
        $ca_notes       = $params['ca_notes'] ?? '';
148
        $ca_census      = $params['ca_census'] ?? '';
149
150
        if ($ca_census !== '' && $ca_individuals !== []) {
151
            $census = new $ca_census();
152
153
            $note_text   = $this->createNoteText($census, $ca_title, $ca_place, $ca_citation, $ca_individuals, $ca_notes);
154
            $note_gedcom = '0 @@ NOTE ' . str_replace("\n", "\n1 CONT ", $note_text);
155
            $note        = $individual->tree()->createRecord($note_gedcom);
156
157
            $newged .= "\n2 NOTE @" . $note->xref() . '@';
158
159
            // Add the census fact to the rest of the household
160
            foreach ($ca_individuals['xref'] ?? [] as $xref) {
161
                if ($xref !== '' && $xref !== $individual->xref()) {
162
                    Registry::individualFactory()->make($xref, $individual->tree())
163
                        ->updateFact($fact_id, $newged, !$keep_chan);
164
                }
165
            }
166
        }
167
168
        return $newged;
169
    }
170
171
    /**
172
     * @param CensusInterface $census
173
     * @param string          $ca_title
174
     * @param string          $ca_place
175
     * @param string          $ca_citation
176
     * @param string[][]      $ca_individuals
177
     * @param string          $ca_notes
178
     *
179
     * @return string
180
     */
181
    private function createNoteText(CensusInterface $census, string $ca_title, string $ca_place, string $ca_citation, array $ca_individuals, string $ca_notes): string
182
    {
183
        $text = $ca_title . "\n" . $ca_citation . "\n" . $ca_place . "\n\n|";
184
185
        foreach ($census->columns() as $column) {
186
            $text .= ' ' . $column->abbreviation() . ' |';
187
        }
188
189
        $text .= "\n|" . str_repeat(' ----- |', count($census->columns()));
190
191
        foreach (array_keys($ca_individuals['xref'] ?? []) as $key) {
192
            $text .= "\n|";
193
194
            foreach ($census->columns() as $n => $column) {
195
                $text .= ' ' . $ca_individuals[$n][$key] . ' |';
196
            }
197
        }
198
199
        return $text . "\n\n" . strtr($ca_notes, ["\r" => '']);
200
    }
201
202
    /**
203
     * Generate an HTML row of data for the census header
204
     * Add prefix cell (store XREF and drag/drop)
205
     * Add suffix cell (delete button)
206
     *
207
     * @param CensusInterface $census
208
     *
209
     * @return string
210
     */
211
    protected function censusTableHeader(CensusInterface $census): string
212
    {
213
        $html = '';
214
        foreach ($census->columns() as $column) {
215
            $html .= '<th class="wt-census-assistant-field" title="' . $column->title() . '">' . $column->abbreviation() . '</th>';
216
        }
217
218
        return '<tr class="wt-census-assistant-row"><th hidden></th>' . $html . '<th></th></tr>';
219
    }
220
221
    /**
222
     * Generate an HTML row of data for the census
223
     * Add prefix cell (store XREF and drag/drop)
224
     * Add suffix cell (delete button)
225
     *
226
     * @param CensusInterface $census
227
     *
228
     * @return string
229
     */
230
    public function censusTableEmptyRow(CensusInterface $census): string
231
    {
232
        $html = '<td class="wt-census-assistant-field" hidden><input type="hidden" name="ca_individuals[xref][]"></td>';
233
234
        foreach ($census->columns() as $n => $column) {
235
            $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>';
236
        }
237
238
        $html .= '<td class="wt-census-assistant-field"><a href="#" title="' . I18N::translate('Remove') . '">' . view('icons/delete') . '</a></td>';
239
240
        return '<tr class="wt-census-assistant-row">' . $html . '</tr>';
241
    }
242
243
    /**
244
     * Generate an HTML row of data for the census
245
     * Add prefix cell (store XREF and drag/drop)
246
     * Add suffix cell (delete button)
247
     *
248
     * @param CensusInterface $census
249
     * @param Individual      $individual
250
     * @param Individual      $head
251
     *
252
     * @return string
253
     */
254
    public function censusTableRow(CensusInterface $census, Individual $individual, Individual $head): string
255
    {
256
        $html = '<td class="wt-census-assistant-field" hidden><input type="hidden" name="ca_individuals[xref][]" value="' . e($individual->xref()) . '"></td>';
257
258
        foreach ($census->columns() as $n => $column) {
259
            $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>';
260
        }
261
262
        $html .= '<td class="wt-census-assistant-field"><a href="#" title="' . I18N::translate('Remove') . '">' . view('icons/delete') . '</a></td>';
263
264
        return '<tr class="wt-census-assistant-row">' . $html . '</tr>';
265
    }
266
267
    /**
268
     * Produce a list of close family members
269
     * for quick selection
270
     *
271
     * @param Individual $individual
272
     *
273
     * @return string[]
274
     */
275
    private function familyMembers(Individual $individual): array
276
    {
277
        $options  = [];
278
        $tree     = $individual->tree();
279
        $xrefs    = new Collection();
280
        $families = $individual->childFamilies()
281
            ->merge($individual->childStepFamilies())
282
            ->merge($individual->spouseFamilies())
283
            ->merge($individual->spouseStepFamilies());
284
285
        foreach ($families as $family) {
286
            foreach ($family->spouses() as $spouse) {
287
                $xrefs->push($spouse->xref());
288
                foreach ($spouse->childFamilies() as $spouse_child_family) {
289
                    foreach ($spouse_child_family->spouses() as $parent) {
290
                        $xrefs->push($parent->xref());
291
                    }
292
                }
293
            }
294
295
            foreach ($family->children() as $child) {
296
                $xrefs->push($child->xref());
297
                foreach ($child->spouseFamilies() as $in_laws) {
298
                    foreach ($in_laws->spouses() as $sibling_in_law) {
299
                        $xrefs->push($sibling_in_law->xref());
300
                    }
301
                    foreach ($in_laws->children() as $child_in_law) {
302
                        $xrefs->push($child_in_law->xref());
303
                    }
304
                }
305
            }
306
        }
307
308
        foreach ($xrefs->unique() as $xref) {
309
            $indi = Registry::individualFactory()->make($xref, $tree);
310
            if ($indi instanceof Individual && $indi->canShow()) {
311
                $options[$xref] = [
312
                    'name'         => strip_tags($indi->fullName()),
313
                    'lifespan'     => strip_tags($indi->lifespan()),
314
                    'relationship' => ucfirst(Functions::getCloseRelationshipName($individual, $indi)),
315
                    'birthyr'     => $indi->getBirthYear(),
316
                ];
317
            }
318
        }
319
320
        return $options;
321
    }
322
}
323