Passed
Pull Request — master (#3735)
by
unknown
08:22
created

CensusAssistantModule::familyMembers()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 28
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 20
nc 6
nop 2
dl 0
loc 28
rs 8.9777
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\Services\TreeService;
28
use Fisharebest\Webtrees\Tree;
29
use Illuminate\Support\Collection;
30
use Psr\Http\Message\ResponseInterface;
31
use Psr\Http\Message\ServerRequestInterface;
32
33
use function array_keys;
34
use function assert;
35
use function count;
36
use function e;
37
use function response;
38
use function str_repeat;
39
use function str_replace;
40
use function strip_tags;
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
        $treeService = new TreeService();
79
80
        $censusClass = $params['census'];
81
        $census      = new $censusClass();
82
        $xref        = $params['xref'];
83
        $tree        = (int) $params['tree'];
84
        $individual  = Registry::individualFactory()->make($xref, $treeService->find($tree));
85
86
        $html = json_encode([
87
            'header' => $this->censusTableHeader($census),
88
            'family' => $this->familyMembers($individual, $census),
89
        ]);
90
91
        return response($html);
92
    }
93
94
    /**
95
     * @param ServerRequestInterface $request
96
     *
97
     * @return ResponseInterface
98
     */
99
    public function postCensusIndividualAction(ServerRequestInterface $request): ResponseInterface
100
    {
101
        $tree = $request->getAttribute('tree');
102
        assert($tree instanceof Tree);
103
104
        $params       = (array) $request->getParsedBody();
105
        $individual   = Registry::individualFactory()->make($params['xref'], $tree);
106
        $head         = Registry::individualFactory()->make($params['head'], $tree);
107
        $census_class = $params['census'];
108
        $census       = new $census_class();
109
110
        // No head of household?  Create a fake one.
111
        $head = $head ?? Registry::individualFactory()->new('X', '0 @X@ INDI', null, $tree);
112
113
        // Generate columns (e.g. relationship name) using the correct language.
114
        I18N::init($census->censusLanguage());
115
116
        if ($individual instanceof Individual && $head instanceof Individual) {
117
            $html = $this->censusTableRow($census, $individual, $head);
118
        } else {
119
            $html = $this->censusTableEmptyRow($census);
120
        }
121
122
        return response($html);
123
    }
124
125
    /**
126
     * @param Individual $individual
127
     *
128
     * @return string
129
     */
130
    public function createCensusAssistant(Individual $individual): string
131
    {
132
        return view('modules/census-assistant', [
133
            'individual' => $individual,
134
        ]);
135
    }
136
137
    /**
138
     * @param ServerRequestInterface $request
139
     * @param Individual             $individual
140
     * @param string                 $fact_id
141
     * @param string                 $newged
142
     * @param bool                   $keep_chan
143
     *
144
     * @return string
145
     */
146
    public function updateCensusAssistant(ServerRequestInterface $request, Individual $individual, string $fact_id, string $newged, bool $keep_chan): string
147
    {
148
        $params = (array) $request->getParsedBody();
149
150
        $ca_title       = $params['ca_title'] ?? '';
151
        $ca_place       = $params['ca_place'] ?? '';
152
        $ca_citation    = $params['ca_citation'] ?? '';
153
        $ca_individuals = $params['ca_individuals'] ?? [];
154
        $ca_notes       = $params['ca_notes'] ?? '';
155
        $ca_census      = $params['ca_census'] ?? '';
156
157
        if ($ca_census !== '' && $ca_individuals !== []) {
158
            $census = new $ca_census();
159
160
            $note_text   = $this->createNoteText($census, $ca_title, $ca_place, $ca_citation, $ca_individuals, $ca_notes);
161
            $note_gedcom = '0 @@ NOTE ' . str_replace("\n", "\n1 CONT ", $note_text);
162
            $note        = $individual->tree()->createRecord($note_gedcom);
163
164
            $newged .= "\n2 NOTE @" . $note->xref() . '@';
165
166
            // Add the census fact to the rest of the household
167
            foreach ($ca_individuals['xref'] ?? [] as $xref) {
168
                if ($xref !== '' && $xref !== $individual->xref()) {
169
                    Registry::individualFactory()->make($xref, $individual->tree())
170
                        ->updateFact($fact_id, $newged, !$keep_chan);
171
                }
172
            }
173
        }
174
175
        return $newged;
176
    }
177
178
    /**
179
     * @param CensusInterface $census
180
     * @param string          $ca_title
181
     * @param string          $ca_place
182
     * @param string          $ca_citation
183
     * @param string[][]      $ca_individuals
184
     * @param string          $ca_notes
185
     *
186
     * @return string
187
     */
188
    private function createNoteText(CensusInterface $census, string $ca_title, string $ca_place, string $ca_citation, array $ca_individuals, string $ca_notes): string
189
    {
190
        $text = $ca_title . "\n" . $ca_citation . "\n" . $ca_place . "\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
        return $text . "\n\n" . strtr($ca_notes, ["\r" => '']);
207
    }
208
209
    /**
210
     * Generate an HTML row of data for the census header
211
     * Add prefix cell (store XREF and drag/drop)
212
     * Add suffix cell (delete button)
213
     *
214
     * @param CensusInterface $census
215
     *
216
     * @return string
217
     */
218
    protected function censusTableHeader(CensusInterface $census): string
219
    {
220
        $html = '';
221
        foreach ($census->columns() as $column) {
222
            $html .= '<th class="wt-census-assistant-field" title="' . $column->title() . '">' . $column->abbreviation() . '</th>';
223
        }
224
225
        return '<tr class="wt-census-assistant-row"><th hidden></th>' . $html . '<th></th></tr>';
226
    }
227
228
    /**
229
     * Generate an HTML row of data for the census
230
     * Add prefix cell (store XREF and drag/drop)
231
     * Add suffix cell (delete button)
232
     *
233
     * @param CensusInterface $census
234
     *
235
     * @return string
236
     */
237
    public function censusTableEmptyRow(CensusInterface $census): string
238
    {
239
        $html = '<td class="wt-census-assistant-field" hidden><input type="hidden" name="ca_individuals[xref][]"></td>';
240
241
        foreach ($census->columns() as $n => $column) {
242
            $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>';
243
        }
244
245
        $html .= '<td class="wt-census-assistant-field"><a href="#" title="' . I18N::translate('Remove') . '">' . view('icons/delete') . '</a></td>';
246
247
        return '<tr class="wt-census-assistant-row">' . $html . '</tr>';
248
    }
249
250
    /**
251
     * Generate an HTML row of data for the census
252
     * Add prefix cell (store XREF and drag/drop)
253
     * Add suffix cell (delete button)
254
     *
255
     * @param CensusInterface $census
256
     * @param Individual      $individual
257
     * @param Individual      $head
258
     *
259
     * @return string
260
     */
261
    public function censusTableRow(CensusInterface $census, Individual $individual, Individual $head): string
262
    {
263
        $html = '<td class="wt-census-assistant-field" hidden><input type="hidden" name="ca_individuals[xref][]" value="' . e($individual->xref()) . '"></td>';
264
265
        foreach ($census->columns() as $n => $column) {
266
            $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>';
267
        }
268
269
        $html .= '<td class="wt-census-assistant-field"><a href="#" title="' . I18N::translate('Remove') . '">' . view('icons/delete') . '</a></td>';
270
271
        return '<tr class="wt-census-assistant-row">' . $html . '</tr>';
272
    }
273
274
    /**
275
     * Produce a list of close family members
276
     * for quick selection
277
     *
278
     * @param Individual      $individual
279
     * @param CensusInterface $census
280
     *
281
     * @return string[]
282
     */
283
    private function familyMembers(Individual $individual, CensusInterface $census): array
284
    {
285
        $censusYear  = (int) substr($census->censusDate(), -4);
286
        $options     = [];
287
        $individuals = new Collection();
288
        $families    = $individual->childFamilies()
289
            ->merge($individual->childStepFamilies())
290
            ->merge($individual->spouseFamilies())
291
            ->merge($individual->spouseStepFamilies());
292
293
        foreach ($families as $family) {
294
            $individuals = $individuals
295
                ->merge($family->spouses())
296
                ->merge($family->children());
297
        }
298
299
        foreach ($individuals->unique() as $indi) {
300
            $birthyr = (int) $indi->getBirthYear() ?: 0;
301
            $deathyr = (int) $indi->getDeathYear() ?: PHP_INT_MAX;
302
            $options[] = [
303
                'xref'         => $indi->xref(),
304
                'text'         => strip_tags($indi->fullName() . ' (' . $indi->lifespan() . ')'),
305
                'relationship' => Functions::getCloseRelationshipName($individual, $indi),
306
                'disabled'     => $censusYear < $birthyr || $censusYear > $deathyr,
307
            ];
308
        }
309
310
        return $options;
311
    }
312
}
313