'Link a user account to an organisation
@param user: the user account record'

def s3_link_to_organisation(self, user):

    db = current.db
    s3db = current.s3db
    user_id = user.id
    (approver, organisation_id) = self.s3_approver(user)
    if organisation_id:
        user.organisation_id = organisation_id
    else:
        organisation_id = user.organisation_id
    if (not organisation_id):
        name = user.get('organisation_name', None)
        if name:
            acronym = user.get('organisation_acronym', None)
            otable = s3db.org_organisation
            record = Storage(name=name, acronym=acronym)
            organisation_id = otable.insert(**record)
            if organisation_id:
                record['id'] = organisation_id
                s3db.update_super(otable, record)
                s3db.onaccept(otable, record, method='create')
                self.s3_set_record_owner(otable, organisation_id)
            user.organisation_id = organisation_id
            utable = self.settings.table_user
            db((utable.id == user_id)).update(organisation_id=organisation_id)
    if (not organisation_id):
        return None
    ltable = s3db.org_organisation_user
    query = (ltable.user_id == user_id)
    rows = db(query).select(ltable.organisation_id, limitby=(0, 2))
    if (len(rows) == 1):
        if (rows.first().organisation_id != organisation_id):
            db(query).update(organisation_id=organisation_id)
        return organisation_id
    else:
        query = ((ltable.user_id == user_id) & (ltable.organisation_id == organisation_id))
        row = db(query).select(ltable.id, limitby=(0, 1)).first()
        if (not row):
            ltable.insert(user_id=user_id, organisation_id=organisation_id)
    return organisation_id
