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

CensusAssistantModule::familyMembers()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 31
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

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