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

CensusAssistantModule::familyMembers()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 28
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

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