'Take ownership of the HR records of the person record
@ToDo: Add user to the Org Access role.'

def s3_link_to_human_resource(self, user, person_id, hr_type):

    db = current.db
    s3db = current.s3db
    settings = current.deployment_settings
    user_id = user.id
    organisation_id = user.organisation_id
    htablename = 'hrm_human_resource'
    htable = s3db.table(htablename)
    if ((not htable) or ((not organisation_id) and settings.get_hrm_org_required())):
        return None
    def customise(hr_id):
        '    Customise    hrm_human_resource    '
        customise = settings.customise_resource(htablename)
        if customise:
            if hr_id:
                args = [str(hr_id)]
            else:
                args = None
            request = S3Request('hrm', 'human_resource', current.request, args=args)
            customise(request, htablename)
    site_id = (user.site_id if (hr_type == 1) else None)
    ptable = s3db.pr_person
    ltable = s3db.pr_person_user
    query = ((((((ltable.user_id == user_id) & (ptable.pe_id == ltable.pe_id)) & (htable.person_id == ptable.id)) & (htable.type == hr_type)) & (htable.status == 1)) & (htable.deleted == False))
    rows = db(query).select(htable.id, limitby=(0, 2))
    accepted = None
    if (len(rows) == 1):
        record = rows.first()
        hr_id = record.id
        customise(hr_id)
        db((htable.id == hr_id)).update(organisation_id=organisation_id, site_id=site_id)
        accepted = 'update'
        hstable = s3db.hrm_human_resource_site
        query = (hstable.human_resource_id == hr_id)
        hstable.update_or_insert(query, site_id=site_id, human_resource_id=hr_id, owned_by_user=user_id)
    else:
        if rows:
            if (type(person_id) is list):
                person_id = person_id[0]
            query = (((((htable.person_id == person_id) & (htable.organisation_id == organisation_id)) & (htable.type == hr_type)) & (htable.site_id == site_id)) & (htable.deleted == False))
            row = db(query).select(htable.id, limitby=(0, 1)).first()
        else:
            row = None
        if row:
            hr_id = row.id
        else:
            customise(hr_id=None)
            record = Storage(person_id=person_id, organisation_id=organisation_id, site_id=site_id, type=hr_type, owned_by_user=user_id)
            hr_id = htable.insert(**record)
            record['id'] = hr_id
            accepted = 'create'
    if (hr_id and accepted):
        s3db.update_super(htable, record)
        self.s3_set_record_owner(htable, hr_id, force_update=True)
        s3db.onaccept(htablename, record, method=accepted)
    return hr_id
