Files
FamilyBook/app/ContactImporter.php
T
laoyang b5725b449a v24 第 6 轮:名册导入 / 两种备注 / 多段工作经历 / 家谱卡片与首字母检索修正
用户 2026-10-03 第二批(8 条)。逐条落点:

1. **名册导入**(新):支持 **vCard 3.0/4.0(.vcf)** 与 **CSV/TSV**(中英文表头都认)。
   新增 `app/ContactImport.php`(纯解析)+ `app/ContactImporter.php`(判重+落库)。
   判重按 **手机号(哈希,精确)→ 姓名(大小写无关)**;命中已有的人**只补空字段,
   绝不覆盖**(批量覆盖没法回退)。
   解析上要处理的三件事都处理了:**折行接回**(长名字/地址会被按字节折断)、
   转义还原(`\,` `\;` `\n`)、多值收全(TEL/EMAIL/ADR 可能出现多次)。
   UTF-16/GBK 的 vcf 也认(手机导出的常见编码)。
2. 成员详情页:右上角「移除」→ **「返回」**(回名册);「删除」移到页面**最下方**
   (在「开通登录账号」下面),并改成 `<details>` 两步确认 + 写清会连带删掉什么。
3. 编辑资料里的「这个人的一句话」**去掉** —— 那句话只能**本人**改。
   ⚠️ 落法是「这一栏只在改自己时出现」:用户要的是"别人不能替他写",
   而不是"这句没人能填";服务端也只在 `$isSelf` 时读表单,否则管理员一编辑就把它清空。
4. **工作单位 / 职务 / 职称可以有多段**(新表 `person_jobs`):表单是一组"经历行"
   (单位/职务/职称/起止年月/备注,可 +/×),详情页按"现在 + 历史"列出。
   `persons.org/title` 保留,语义变成"当前那段的快照"(列表页等只要"现在在哪儿"),
   升级时把老的 org/title 回填成一段经历。
5/备注分两种:「自我介绍」(`persons.note`,他本人写的、别人看得到)与
   **「我对他的私人备注」**(新表 `person_notes`,每人每对象一条,**只有写的人自己看得到**)。
   详情页有独立的一块;表单里只在"编辑别人"时出现。
6. 成员表单:**头像放到最前**、去掉「选择文件」按钮(点那张默认头像即选文件);
   表单标签统一 15px/600(原来 13–14px,和 12px 的灰字提示分不出层级)。
7. 名册列表:⋯ 前面加**「编辑」**按钮(改资料是高频动作,藏进 ⋯ 要点两下)。
8. 家谱:
   · **首字母检索 bug**:输入 `yy` 会搜出「岳父/洪勇」。根因是前端把
     **姓名与称呼的首字母拼成一串**再判子序列 —— 洪勇的称呼是"岳父" → `hy`+`yf`=`hyyf`
     → `yy` 跨字段命中。改成**逐字段独立判**(服务端本来就是逐字段判的,两边现在同口径)。
   · **卡片仍比头像宽**:头像是 **1:1(正方形)** 槽位,卡片里却写成 96×72 的长方形 +
     `object-fit: contain` → 照片被缩到 72 宽、左右各留 12px 白 → 看着"框比头像宽"。
     改成**正方形头像区 + `object-fit: cover`**(90×128 卡片,88×88 头像区)。
   · 右上角加**「我的家谱」**按钮(只在看别人的家谱时出现 —— 看自己的时候点它没意义)。

**测试新增**(都能变红,且做过反向验证):
- `_fb_import_test.py` 21 条:新人新建 / 手机号命中不重复建人 / **已有字段一个都不被覆盖** /
  缺的字段被补上 / 反复导入幂等 / 只给姓名也能命中 / 认不出的文件被明确拒绝,
  外加 ⑱ **"有单位但没有经历行"的人**(最容易漏的覆盖路径)。
- `_fb_roster_filter_test.js`(jsdom,用真实渲染出的 HTML)8 条:直击
  「输 yy 不该命中 岳父/洪勇」;反向验证时把实现改回拼接写法 → ① 立刻红。
- 改动过程中被测试抓出**两个真 bug**并已修:
  ① 导入时给"已有单位的人"也插经历 → `PersonJob::syncCurrent()` 回写把这人的单位**覆盖**了;
  ② `syncCurrent()` 在经历表为空时会把 `persons.org/title` **清空** ——
     而它被"编辑资料"这类常规路径调用一次就触发,属于**随手一保存就丢数据**。
     现在空表直接 return("经历表不是唯一的一份")。

**战绩**:e2e **775/0** · 导入 21/0 · 第 5 轮专项 91/0 · 家谱 34/0 · 几何 428/0 ·
移动端 688/0 · 交互 97/0 · 升级 126/0。
线上:schema **v15**、指纹一致、`person_jobs`/`person_notes` 已建、
6 条老的"工作单位"全部回填成经历、13 个文件 md5 与本地一致、错误日志无新增。
2026-10-03 19:27:14 +08:00

285 lines
14 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
/**
* 把解析出来的联系人**落到名册里**(v24 用户 2026-10-03 第 1 条)。
*
* 与 App\ContactImport 的分工:
* · ContactImport —— 只管"文件 → 记录数组"(纯解析,不碰库);
* · 本类 —— 只管"记录数组 → 库里"(判重、补缺、建号、挂名册)。
* 分开的好处:解析器可以单独测(给一段 vCard 看输出),不需要库。
*
* 用户要求的两条规则(原话):
* 「导入时,如果名字或手机号在已有的名册中存在,则导入其他信息,
* 如果这些信息在系统中已经存在,则只导入其他信息。」
* 落成三条:
* ① **判重** 按 手机号(哈希,精确)→ 姓名(大小写无关,精确)依次找;
* ② 命中已有的人 → **只补空字段**,绝不覆盖(批量覆盖没法回退,见 ContactImport 的说明);
* ③ 没命中 → 新建一条,并加进导入者的名册。
*
* ⚠️ 判重范围是**整个家庭**(不只是我的名册):同一个家里"洪勇"只能有一条记录 ——
* 否则导入一次会造出一个重复的人,之后生日、关系、观影记录全都分成两半。
*/
declare(strict_types=1);
namespace App;
final class ContactImporter
{
/**
* @return array{added:int,updated:int,skipped:int,people:array<int,array{name:string,action:string,added:array}>}
*/
public static function run(int $familyId, int $meId, array $records, int $groupId = 0): array
{
$added = 0;
$updated = 0;
$skipped = 0;
$log = [];
// 现有的人一次取出来做索引(几十~几百人,比逐条查库快得多,也不会漏判)
// 索引键:phone_hash(精确)+ 姓名(小写)
$byPhone = [];
$byName = [];
foreach (Person::all($familyId, '', 'member', $meId) as $p) {
if (!empty($p['phone_hash'])) {
$byPhone[(string)$p['phone_hash']] = $p;
}
$n = mb_strtolower(trim((string)$p['name']), 'UTF-8');
if ($n !== '' && !isset($byName[$n])) {
$byName[$n] = $p;
}
}
foreach ($records as $r) {
$name = trim((string)($r['name'] ?? ''));
$phone = trim((string)($r['phone'] ?? ''));
if ($name === '' && $phone === '') {
$skipped++;
continue;
}
// ---- ① 判重:手机号优先(最精确),其次姓名 ----
$hit = null;
if ($phone !== '') {
$h = Crypto::hash($phone);
if (isset($byPhone[$h])) {
$hit = $byPhone[$h];
}
}
if ($hit === null && $name !== '') {
$k = mb_strtolower($name, 'UTF-8');
if (isset($byName[$k])) {
$hit = $byName[$k];
}
}
if ($hit !== null) {
// ---- ② 命中:只补空字段 ----
$filled = self::fillMissing($hit, $r, $meId);
if ($filled) {
$updated++;
$log[] = ['name' => (string)$hit['name'], 'action' => 'updated', 'added' => $filled];
} else {
$skipped++;
$log[] = ['name' => (string)$hit['name'], 'action' => 'same', 'added' => []];
}
continue;
}
// ---- ③ 没命中:新建 ----
$d = [
'name' => $name !== '' ? $name : $phone,
'phone' => $phone,
'email' => (string)($r['email'] ?? ''),
'address' => (string)($r['address'] ?? ''),
'org' => (string)($r['org'] ?? ''),
// 职务 + 职称合成一列(与 PersonJob::joinTitle 同一口径:
// 两个都有时用 " · " 分开,只有一个就只用那个)
'title' => PersonJob::joinTitle(
(string)($r['title'] ?? ''),
(string)($r['jobrank'] ?? '')
) ?? '',
'note' => (string)($r['note'] ?? ''),
'kind' => 'member',
'avatar' => '',
'birth_rank' => '',
'is_placeholder' => 0,
// 生日:解析器只给"能确定"的日期,给了就当阳历
'birthday_source' => 'solar',
'birthday_solar' => (string)($r['birthday'] ?? ''),
'birthday_lunar' => '',
'birthday_lunar_leap' => 0,
'birthday_id_card' => '',
];
try {
$pid = Person::create($familyId, $d);
} catch (\Throwable $ex) {
$skipped++;
continue;
}
// 补充联系方式(除主手机号之外的那些)
$extra = [];
$extraPhones = array_values(array_filter((array)($r['phones'] ?? []),
static fn($v) => trim((string)$v) !== '' && (string)$v !== $phone));
foreach ($extraPhones as $i => $v) {
$extra['phone'][] = ['label' => $i === 0 ? '其他' : '', 'value' => (string)$v];
}
$extraEmails = array_values(array_filter((array)($r['emails'] ?? []),
static fn($v) => trim((string)$v) !== '' && (string)$v !== (string)($r['email'] ?? '')));
foreach ($extraEmails as $i => $v) {
$extra['email'][] = ['label' => $i === 0 ? '其他' : '', 'value' => (string)$v];
}
if (($r['url'] ?? '') !== '') {
$extra['url'][] = ['label' => '', 'value' => (string)$r['url']];
}
if ($extra) {
Person::replaceContacts($pid, $extra);
}
// 工作经历(第 4 条那张表):导入来的单位/职务就是一段经历。
// ⚠️ 必须**同时**建这一段,否则详情页的"工作经历"永远是空的,
// 而 persons.org 里却有值 —— 两处对不上,用户会以为数据坏了。
if (trim((string)($r['org'] ?? '')) !== '' || trim((string)($r['title'] ?? '')) !== ''
|| trim((string)($r['jobrank'] ?? '')) !== '') {
PersonJob::replace($pid, [[
'org' => (string)($r['org'] ?? ''), 'title' => (string)($r['title'] ?? ''),
'rank_name' => (string)($r['jobrank'] ?? ''),
'start_ym' => '', 'end_ym' => '', 'note' => '',
]]);
}
// 进导入者的名册(谁导入的,就先出现在谁的名册里)
PersonRoster::ensure($familyId, $meId, $pid, $groupId > 0 ? $groupId : null, 'self');
// 建完把索引补上,避免同一个文件里出现两条同名时建出两个人
$byName[mb_strtolower($d['name'], 'UTF-8')] = ['id' => $pid, 'name' => $d['name']];
if ($phone !== '') {
$byPhone[Crypto::hash($phone)] = ['id' => $pid, 'name' => $d['name']];
}
$added++;
$log[] = ['name' => (string)$d['name'], 'action' => 'added', 'added' => ['新建']];
}
return ['added' => $added, 'updated' => $updated, 'skipped' => $skipped, 'people' => $log];
}
/**
* 把记录里**他没有的值**补上去;已有非空值一律不动。
*
* ⚠️ 写库只分两处:
* ① `persons` 上的标量列(邮箱/住址/单位/职务/生日)→ 一条 UPDATE;
* ② 多值(电话/邮箱/网址)→ 走 person_contacts 的整组替换(要把现有的并进去)。
* 第一版把"SQL 片段"与"中文标签"交替塞进同一个数组,读起来极易出错;
* 这里改成两个独立容器,各司其职。
*
* @return string[] 这次补上了哪些(中文标签,用来告诉用户"改了什么")
*/
private static function fillMissing(array $person, array $r, int $meId): array
{
$pid = (int)$person['id'];
$cols = []; // "`email` = ?" => 值
$labels = []; // 给人看的"补了什么"
// ---- ① persons 上的标量列:他空着才补 ----
$scalar = [
'email' => ['邮箱', (string)($r['email'] ?? ''), 200],
'address' => ['住址', (string)($r['address'] ?? ''), 200],
'org' => ['工作单位', (string)($r['org'] ?? ''), 120],
'note' => ['备注', (string)($r['note'] ?? ''), 2000],
];
foreach ($scalar as $col => $def) {
$label = $def[0];
$new = trim($def[1]);
$max = (int)$def[2];
if (trim((string)($person[$col] ?? '')) === '' && $new !== '') {
$cols["`$col` = ?"] = mb_substr($new, 0, $max, 'UTF-8');
$labels[] = $label;
}
}
// 职务与职称在库里是同一列 title(他那一列空着才补)
$newTitle = trim((string)($r['title'] ?? '') . ' ' . (string)($r['jobrank'] ?? ''));
if (trim((string)($person['title'] ?? '')) === '' && $newTitle !== '') {
$cols['`title` = ?'] = mb_substr($newTitle, 0, 120, 'UTF-8');
$labels[] = '职务/职称';
}
// 生日:他一个生日都没有时才补。有生日就绝不动 —— 生日是强身份信息,错了很难发现。
$hasBd = trim((string)Birthday::solarOf($person)) !== ''
|| trim((string)($person['birthday_lunar'] ?? '')) !== '';
if (!$hasBd && trim((string)($r['birthday'] ?? '')) !== '') {
$cols['`birthday` = ?'] = (string)$r['birthday'] . ' 00:00:00';
$labels[] = '生日';
}
if ($cols) {
$sql = [];
$args = [];
foreach ($cols as $frag => $val) {
$sql[] = $frag;
$args[] = $val;
}
$args[] = $pid;
Database::get()->prepare('UPDATE persons SET ' . implode(', ', $sql) . ' WHERE id = ?')
->execute($args);
}
// ---- ② 多值(电话/邮箱/网址):只在"这一类他一个都没有"时补 ----
// ⚠️ 判据是"这一类为空",不是逐条去重:person_contacts 里的手机号是**密文**,
// 没法拿明文比;而"他这一类本来就空着"是能确定的(也符合"只补空"的要求)。
$cur = Person::contactsOf($pid);
$add = [];
$mainPhone = trim((string)($r['phone'] ?? ''));
$mainMail = trim((string)($r['email'] ?? ''));
$extraPhones = array_values(array_filter((array)($r['phones'] ?? []),
static fn($v) => trim((string)$v) !== '' && trim((string)$v) !== $mainPhone));
$extraEmails = array_values(array_filter((array)($r['emails'] ?? []),
static fn($v) => trim((string)$v) !== '' && trim((string)$v) !== $mainMail));
if (!$cur['phone'] && $extraPhones) {
foreach ($extraPhones as $v) {
$add['phone'][] = ['label' => '', 'value' => (string)$v];
}
$labels[] = '电话';
}
if (!$cur['email'] && $extraEmails) {
foreach ($extraEmails as $v) {
$add['email'][] = ['label' => '', 'value' => (string)$v];
}
$labels[] = '邮箱';
}
if (!$cur['url'] && trim((string)($r['url'] ?? '')) !== '') {
$add['url'][] = ['label' => '', 'value' => (string)$r['url']];
$labels[] = '网址';
}
if ($add) {
// replaceContacts 是**整组替换** → 必须把现有的并进去,否则会把已有联系方式清掉
$merged = $cur;
foreach ($add as $k => $rows) {
foreach ($rows as $row) {
$merged[$k][] = $row;
}
}
Person::replaceContacts($pid, $merged);
}
// ---- ③ "工作经历"里空着、而这次**刚补上**了单位/职务 → 补一段经历 ----
// ⚠️⚠️ 两个硬条件,缺一不可:
// ① 这次确实补了(`$cols` 里刚写过 org 或 title)—— 他已经有的值不能碰;
// ② 经历表里本来就没有 —— 有经历时以经历表为准,不重复插。
// 为什么条件①这么关键:`PersonJob::replace()` 末尾会调
// `syncCurrent()` 把"最新那段"回写到 persons.org/title。若在这里对
// "已有单位的人"也插一段导入来的单位,syncCurrent 就会把
// **他原来的单位覆盖掉** —— 正好违反"只补空、不覆盖"。
// (这个 bug 是被 _fb_import_test.py 的 ⑩ 抓出来的。)
$justFilledOrg = isset($cols['`org` = ?']);
$justFilledTitle = isset($cols['`title` = ?']);
if (($justFilledOrg || $justFilledTitle) && !PersonJob::list($pid)) {
PersonJob::replace($pid, [[
// 用**刚存进去的值**(不是导入文件里的原值)——
// 这样 syncCurrent 回写时与库里一致,不会造成二次变动。
'org' => (string)($cols['`org` = ?'] ?? ''),
'title' => (string)($r['title'] ?? ''),
'rank_name' => (string)($r['jobrank'] ?? ''),
'start_ym' => '', 'end_ym' => '', 'note' => '',
]]);
}
return array_values(array_unique($labels));
}
}