'Link to a member Record'

def s3_link_to_member(self, user, person_id=None):

    db = current.db
    s3db = current.s3db
    user_id = user.id
    organisation_id = user.organisation_id
    mtablename = 'member_membership'
    mtable = s3db.table(mtablename)
    if ((not mtable) or (not organisation_id)):
        return None
    ptable = s3db.pr_person
    ltable = s3db.pr_person_user
    query = ((((mtable.deleted == False) & (mtable.person_id == ptable.id)) & (ptable.pe_id == ltable.pe_id)) & (ltable.user_id == user_id))
    rows = db(query).select(mtable.id, limitby=(0, 2))
    if (len(rows) == 1):
        member_id = rows.first().id
        db((mtable.id == member_id)).update(organisation_id=organisation_id)
        self.s3_set_record_owner(mtable, member_id, force_update=True)
    if isinstance(person_id, list):
        person_ids = person_id
    else:
        person_ids = [person_id]
    query = (mtable.person_id.belongs(person_ids) & (mtable.organisation_id == organisation_id))
    row = db(query).select(mtable.id, limitby=(0, 1)).first()
    if row:
        member_id = row.id
    else:
        record = Storage(person_id=person_ids[0], organisation_id=organisation_id, owned_by_user=user_id)
        member_id = mtable.insert(**record)
        if member_id:
            record['id'] = member_id
            customise = current.deployment_settings.customise_resource(mtablename)
            if customise:
                request = S3Request('member', 'membership', current.request, args=[str(member_id)])
                customise(request, mtablename)
            self.s3_set_record_owner(mtable, member_id)
            s3db.onaccept(mtablename, record, method='create')
    return member_id
