'Actions after creating/updating appointments
- Update last_seen_on in the corresponding case(s)
- Update the case status if configured to do so
@param form: the FORM'

@staticmethod
def case_appointment_onaccept(form):

    formvars = form.vars
    if ('id' in formvars):
        record_id = formvars.id
    elif hasattr(form, 'record_id'):
        record_id = form.record_id
    else:
        record_id = None
    if (not record_id):
        return
    db = current.db
    s3db = current.s3db
    settings = current.deployment_settings
    table = s3db.dvr_case_appointment
    person_id = formvars.get('person_id')
    case_id = formvars.get('case_id')
    if ((not person_id) or (not case_id)):
        row = db((table.id == record_id)).select(table.case_id, table.person_id, limitby=(0, 1)).first()
        if row:
            person_id = row.person_id
            case_id = row.case_id
    if (settings.get_dvr_appointments_update_last_seen_on() and person_id):
        dvr_update_last_seen(person_id)
    if (settings.get_dvr_appointments_update_case_status() and (s3_str(formvars.get('status')) == '4')):
        ttable = s3db.dvr_case_appointment_type
        query = ((((table.id == record_id) & (table.deleted != True)) & (ttable.id == table.type_id)) & (ttable.status_id != None))
        row = db(query).select(table.date, ttable.status_id, limitby=(0, 1)).first()
        if row:
            date = row.dvr_case_appointment.date
            if (not date):
                date = current.request.utcnow.date()
            status_id = row.dvr_case_appointment_type.status_id
            query = (table.person_id == person_id)
            if case_id:
                query &= (table.case_id == case_id)
            query &= (((((((table.date != None) & (table.status == 4)) & (table.date > date)) & (table.deleted != True)) & (ttable.id == table.type_id)) & (ttable.status_id != None)) & (ttable.status_id != status_id))
            later = db(query).select(table.id, limitby=(0, 1)).first()
            if later:
                status_id = None
        else:
            status_id = None
        if status_id:
            ctable = s3db.dvr_case
            stable = s3db.dvr_case_status
            query = (((((ctable.person_id == person_id) & (ctable.archived != True)) & (ctable.deleted != True)) & (stable.id == ctable.status_id)) & (stable.is_closed != True))
            if case_id:
                query &= (ctable.id == case_id)
            cases = db(query).select(ctable.id, ctable.person_id, ctable.archived)
            has_permission = current.auth.s3_has_permission
            for case in cases:
                if has_permission('update', ctable, record_id=case.id):
                    r = S3Request('dvr', 'case', current.request, args=[], get_vars={})
                    r.customise_resource('dvr_case')
                    case.update_record(status_id=status_id)
                    s3db.onaccept(ctable, case, method='update')
