'Case onaccept routine:
- auto-create active appointments
- count household size for new cases
@param form: the FORM
@param create: perform additional actions for new cases'

@staticmethod
def case_onaccept(form, create=False):

    db = current.db
    s3db = current.s3db
    form_vars = form.vars
    if ('id' in form_vars):
        record_id = form_vars.id
    elif hasattr(form, 'record_id'):
        record_id = form.record_id
    else:
        return
    ctable = s3db.dvr_case
    stable = s3db.dvr_case_status
    left = stable.on((stable.id == ctable.status_id))
    query = (ctable.id == record_id)
    row = db(query).select(ctable.id, ctable.person_id, ctable.closed_on, stable.is_closed, left=left, limitby=(0, 1)).first()
    if (not row):
        return
    case = row.dvr_case
    if row.dvr_case_status.is_closed:
        if (not case.closed_on):
            case.update_record(closed_on=current.request.utcnow.date())
    elif case.closed_on:
        case.update_record(closed_on=None)
    person_id = case.person_id
    atable = s3db.dvr_case_appointment
    ttable = s3db.dvr_case_appointment_type
    left = atable.on((((atable.type_id == ttable.id) & (atable.person_id == person_id)) & (atable.deleted != True)))
    query = (((atable.id == None) & (ttable.active == True)) & (ttable.deleted != True))
    rows = db(query).select(ttable.id, left=left)
    for row in rows:
        atable.insert(case_id=record_id, person_id=person_id, type_id=row.id)
    if (create and (current.deployment_settings.get_dvr_household_size() == 'auto')):
        gtable = s3db.pr_group
        mtable = s3db.pr_group_membership
        query = ((((mtable.person_id == person_id) & (mtable.deleted != True)) & (gtable.id == mtable.group_id)) & (gtable.group_type == 7))
        rows = db(query).select(gtable.id)
        for row in rows:
            dvr_case_household_size(row.id)
