'Update affiliations for an area
@param record: the area record'

@staticmethod
def area_update_affiliations(record_id):

    ROLE = 'Areas'
    db = current.db
    s3db = current.s3db
    table = s3db.po_area
    row = db((table.id == record_id)).select(table.pe_id, table.deleted, table.deleted_fk, table.organisation_id, limitby=(0, 1)).first()
    if (not row):
        return
    area_pe_id = row.pe_id
    if (not area_pe_id):
        return
    if row.deleted:
        try:
            fk = json.loads(row.deleted_fk)
        except ValueError:
            organisation_id = None
        else:
            organisation_id = fk.get('organisation_id')
    else:
        organisation_id = row.organisation_id
    organisation_pe_id = s3db.pr_get_pe_id('org_organisation', organisation_id)
    rtable = s3db.pr_role
    atable = s3db.pr_affiliation
    query = (((((atable.pe_id == row.pe_id) & (atable.deleted != True)) & (atable.role_id == rtable.id)) & (rtable.role == ROLE)) & (rtable.pe_id != organisation_pe_id))
    rows = db(query).select(rtable.pe_id)
    for row in rows:
        s3db.pr_remove_affiliation(row.pe_id, area_pe_id, role=ROLE)
    from pr import OU
    s3db.pr_add_affiliation(organisation_pe_id, area_pe_id, role=ROLE, role_type=OU)
