Files

179 lines
11 KiB
Python

"""Real people, household memberships and shared genealogies; accounts are optional."""
import datetime as dt
import json
import secrets
import family_permissions
class Members:
def __init__(self, app):
self.a = app
def initialize(self):
a = self.a
with a.LOCK, a.DB:
a.DB.execute('CREATE TABLE IF NOT EXISTS family_members (id TEXT PRIMARY KEY, body TEXT NOT NULL)')
# Only a confirmed person binding establishes membership. Login accounts and
# ancestors are not automatically treated as living household members.
if not a.setting('membersMigrationV1', False):
for user in a.objects('users'):
person = a.get_object('people', user.get('personId'))
if person and a.HOUSEHOLDS.family_of(person) == a.HOUSEHOLDS.family_of(user):
item = dict(id=secrets.token_hex(8), familyId=a.HOUSEHOLDS.family_of(user),
personId=person['id'], label='', status='active', revision=1)
a.DB.execute('INSERT INTO family_members VALUES (?,?)', (item['id'], json.dumps(item)))
a.DB.execute('INSERT OR REPLACE INTO settings VALUES (?,?)', ('membersMigrationV1', 'true'))
def rows(self, family):
return [x for x in self.a.objects('family_members') if x['familyId'] == family]
def directory(self, user):
"""A projection of real membership and confirmed links, never an ACL hierarchy."""
a = self.a
account = a.get_object('users', user['id']) or user
homes = a.HOUSEHOLDS.list(user)
home_map = {h['id']: h for h in homes}
readable = {}
for home in homes:
actor = a.HOUSEHOLDS.context(account, home['id'])
if home.get('kind', 'home') == 'home' and (a.HOUSEHOLDS.manager(actor) or actor.get('familyAccess') in ('read', 'edit')):
readable.setdefault(a.HOUSEHOLDS.genealogy_of(home['id']), []).append(home['id'])
trees, placed = {}, set()
for home in homes:
tree = a.HOUSEHOLDS.genealogy_of(home['id'])
if tree in trees or tree not in readable:
continue
context_id = a.HOUSEHOLDS.scope(user)
context_id = context_id if context_id in readable[tree] else readable[tree][0]
actor = a.HOUSEHOLDS.context(account, context_id)
people = a.HOUSEHOLDS.objects(actor, 'people')
links = a.HOUSEHOLDS.objects(actor, 'family_links')
connected = {}
remaining = {p['id'] for p in people}
while remaining:
levels, conflict = family_permissions.generations(people, links, min(remaining))
if not levels:
break
remaining -= set(levels)
# Independent branches have independent starting points, never guessed
# absolute ancestral generation numbers based on age or surname.
base, branch = min(levels.values()), min(levels)
confirmed = not conflict and max(levels.values()) > base
for pid, level in levels.items():
connected[pid] = (branch, level-base+1 if confirmed else None)
branches = {}
for person in people:
branch, level = connected[person['id']]
branches.setdefault(branch, {})[person['id']] = dict(
id=person['id'], name=person['name'], generation=level,
self=person['id'] == account.get('personId'),
lifeStatus=person.get('lifeStatus', 'alive'), homes=[], journalHomes=[])
for member in a.objects('family_members'):
if member['familyId'] not in home_map or member['personId'] not in connected:
continue
pid = member['personId']
branch, _ = connected[pid]
branches[branch][pid]['journalHomes'].append(dict(
id=member['familyId'], name=home_map[member['familyId']]['name']))
if member['status'] == 'historical':
continue
branches[branch][pid]['homes'].append(dict(
id=member['familyId'], name=home_map[member['familyId']]['name'], status=member['status']))
placed.add(member['familyId'])
trees[tree] = dict(
id=tree, familyId=context_id, homes=[dict(id=h['id'], name=h['name']) for h in homes
if a.HOUSEHOLDS.genealogy_of(h['id']) == tree],
branches=[dict(id=k, people=sorted(v.values(), key=lambda p: (p['generation'] or 100000, p['name'])))
for k, v in branches.items()])
return dict(trees=list(trees.values()), unplaced=[dict(id=h['id'], name=h['name']) for h in homes if h['id'] not in placed])
def member(self, family, key, active=False):
a = self.a
row = a.get_object('family_members', key)
person = a.get_object('people', row.get('personId')) if row else None
if not row or row['familyId'] != family or not person:
raise a.Problem('家庭成员不存在', 404)
if active and (row['status'] == 'historical' or person.get('lifeStatus') == 'deceased' or person.get('archived')):
raise a.Problem('该成员当前不适合开启位置共享', 409)
return row, person
def snapshot(self, user):
a = self.a; family = a.HOUSEHOLDS.scope(user)
items = []
for row in self.rows(family):
person = a.get_object('people', row['personId'])
if not person: continue
accounts = [u for u in a.objects('users') if u.get('personId') == person['id']]
items.append(dict(row, name=person['name'], lifeStatus=person.get('lifeStatus', 'alive'),
hasAccount=bool(accounts), self=person['id'] == user.get('personId')))
return dict(items=items, canManage=a.HOUSEHOLDS.manager(user),
canViewGenealogy=a.HOUSEHOLDS.manager(user) or user.get('familyAccess') in ('read', 'edit'),
genealogyId=a.HOUSEHOLDS.genealogy_of(family),
genealogyHomes=[dict(id=h['id'], name=h['name']) for h in a.HOUSEHOLDS.list(user)
if a.HOUSEHOLDS.genealogy_of(h['id']) == a.HOUSEHOLDS.genealogy_of(family)],
candidates=[dict(id=p['id'], name=p['name'], lifeStatus=p.get('lifeStatus', 'alive'))
for p in a.HOUSEHOLDS.objects(user, 'people')] if a.HOUSEHOLDS.manager(user) else [])
def save(self, user, data):
a = self.a
if not a.HOUSEHOLDS.manager(user): raise a.Problem('需要家庭管理员权限', 403)
family = a.HOUSEHOLDS.scope(user)
with a.LOCK, a.DB:
old = a.get_object('family_members', data.get('id'))
if data.get('id') and (not old or old['familyId'] != family): raise a.Problem('成员不存在', 404)
if data.get('revision', 0) != (old or {}).get('revision', 0): raise a.Problem('成员资料已变更,请重新载入', 409)
person_id = (old or {}).get('personId') or data.get('personId')
if old and data.get('personId', person_id) != person_id: raise a.Problem('成员身份不能换成另一个人')
person = a.get_object('people', person_id) if person_id else None
if person_id:
a.HOUSEHOLDS.owns_person(user, person)
else:
# New unconnected person: no existing genealogical record is modified,
# and this does not establish a self binding or change generations.
person = dict(a.FAMILY.person({'name': data.get('name', '')}, None), familyId=family)
person_id = person['id']
if any(m['personId'] == person_id and m['id'] != (old or {}).get('id') for m in self.rows(family)):
raise a.Problem('这个人物已经是本家庭成员,请编辑原成员记录', 409)
status = data.get('status', 'active')
if status not in ('active', 'away', 'historical'): raise a.Problem('成员状态不正确')
item = dict(id=(old or {}).get('id') or secrets.token_hex(8), familyId=family, personId=person_id,
label=a.clean_text(data.get('label', ''), 60), status=status,
revision=(old or {}).get('revision', 0)+1)
item['history'] = list((old or {}).get('history', []))
if not old or old.get('status') != status:
item['history'].append(dict(at=dt.datetime.now(dt.timezone.utc).isoformat(),
previous=(old or {}).get('status'),status=status,actorId=user['id']))
if not a.get_object('people', person_id):
now = dt.datetime.now(dt.timezone.utc).isoformat()
person.update(updatedAt=now, updatedBy=user['username'])
a.DB.execute('INSERT INTO people VALUES (?,?)', (person_id, json.dumps(person)))
rev = a.DB.execute('SELECT COALESCE(MAX(revision),0)+1 FROM family_changes').fetchone()[0]
a.DB.execute('INSERT INTO family_changes VALUES (?,?,?,?,?,?,?,?)',
(rev, 'person', person_id, None, json.dumps(person), user['username'], now, None))
key = a.HOUSEHOLDS.revision_key(user)
a.DB.execute('INSERT OR REPLACE INTO settings VALUES (?,?)', (key, json.dumps(a.setting(key, 0)+1)))
a.DB.execute('INSERT OR REPLACE INTO family_members VALUES (?,?)', (item['id'], json.dumps(item)))
a.audit('保存家庭成员', user['username'])
return item
def share_genealogy(self, user, data):
a = self.a
if user['role'] != 'admin': raise a.Problem('共用族谱需要平台管理员确认两个家庭的关联', 403)
source = a.HOUSEHOLDS.scope(user); target = data.get('targetFamilyId')
if data.get('confirm') is not True or not isinstance(target, str) or not a.get_object('households', target):
raise a.Problem('请选择关联家庭,并确认族谱资料将共用')
with a.LOCK, a.DB:
source_tree = a.HOUSEHOLDS.genealogy_of(source); target_tree = a.HOUSEHOLDS.genealogy_of(target)
if source_tree == target_tree: return {'ok': True}
# Joining two graph components never renumbers or silently merges people.
# Generation levels remain governed by the existing five-generation guard.
homes = [h for h in a.objects('households') if a.HOUSEHOLDS.genealogy_of(h['id']) in (source_tree, target_tree)]
revision = max([a.setting(a.HOUSEHOLDS.revision_key(dict(user, _familyId=h['id'])), 0) for h in homes]+[0])+1
for home in homes:
home['genealogyId'] = target_tree
a.DB.execute('UPDATE households SET body=? WHERE id=?', (json.dumps(home), home['id']))
key = a.HOUSEHOLDS.revision_key(dict(user, _familyId=target))
a.DB.execute('INSERT OR REPLACE INTO settings VALUES (?,?)', (key, json.dumps(revision)))
a.audit('共用族谱', user['username']+' / '+source+' / '+target)
return {'ok': True}