'Onaccept-callback for case activites:
- automatically set end date when marked as completed'

@staticmethod
def case_activity_onaccept(form):

    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
    atable = s3db.dvr_case_activity
    query = (atable.id == record_id)
    activity = None
    is_closed = False
    if current.deployment_settings.get_dvr_case_activity_use_status():
        stable = s3db.dvr_case_activity_status
        left = stable.on((atable.status_id == stable.id))
        row = db(query).select(atable.id, atable.end_date, stable.is_closed, left=left, limitby=(0, 1)).first()
        if row:
            activity = row.dvr_case_activity
            is_closed = row.dvr_case_activity_status.is_closed
    else:
        row = db(query).select(atable.id, atable.end_date, atable.completed, limitby=(0, 1)).first()
        if row:
            activity = row
            is_closed = row.completed
    if (not activity):
        return
    if is_closed:
        data = {'followup': False, 'followup_date': None}
        if (not activity.end_date):
            data['end_date'] = current.request.utcnow.date()
        activity.update_record(**data)
    elif activity.end_date:
        activity.update_record(end_date=None)
