'Link location if area_tag has SAME code
Link alert_id for non-template area'

@staticmethod
def cap_area_tag_onaccept(form):

    form_vars = form.vars
    area_id = form_vars.get('area_id', None)
    if (not area_id):
        return
    db = current.db
    atable = db.cap_area
    arow = db((atable.id == area_id)).select(atable.alert_id, limitby=(0, 1)).first()
    alert_id = arow.alert_id
    if alert_id:
        db((db.cap_area_tag.id == form_vars.id)).update(alert_id=alert_id)
        s3db = current.s3db
        tag = form_vars.get('tag')
        same_code = current.deployment_settings.get_cap_same_code()
        import_location = False
        if (tag and same_code):
            if (tag == 'SAME'):
                if ('geocode' in current.deployment_settings.get_cap_area_default()):
                    import_location = True
                else:
                    table = s3db.cap_alert
                    row = db((table.id == alert_id)).select(table.external, limitby=(0, 1)).first()
                    if (not row.external):
                        import_location = True
        if import_location:
            ttable = s3db.gis_location_tag
            gtable = s3db.gis_location
            tquery = ((((((ttable.tag == same_code) & (ttable.value == form_vars.get('value'))) & (ttable.deleted != True)) & (ttable.location_id == gtable.id)) & (gtable.end_date == None)) & (gtable.deleted != True))
            trow = db(tquery).select(ttable.location_id, limitby=(0, 1)).first()
            if (trow and trow.location_id):
                ltable = db.cap_area_location
                ldata = {'area_id': area_id, 'alert_id': (alert_id or None), 'location_id': trow.location_id}
                lid = ltable.insert(**ldata)
                current.auth.s3_set_record_owner(ltable, lid)
