Esempio n. 1
0
def insert_waitinglist_from_form(dbo, data, username):
    """
    Creates a waiting list record from the screen
    data: The webpy data object containing form parameters
    """
    l = dbo.locale
    if utils.df_ks(data, "description") == "":
        raise utils.ASMValidationError(_("Description cannot be blank", l))
    if utils.df_ki(data, "owner") == "0":
        raise utils.ASMValidationError(_("Waiting list entries must have a contact", l))
    if utils.df_ks(data, "dateputon") == "":
        raise utils.ASMValidationError(_("Date put on cannot be blank", l))
    nwlid = db.get_id(dbo, "animalwaitinglist")
    db.execute(dbo, db.make_insert_user_sql(dbo, "animalwaitinglist", username, (
        ( "ID", db.di(nwlid)),
        ( "SpeciesID", utils.df_s(data, "species")),
        ( "DatePutOnList", utils.df_d(data, "dateputon", l)),
        ( "OwnerID", utils.df_s(data, "owner")),
        ( "AnimalDescription", utils.df_t(data, "description")),
        ( "ReasonForWantingToPart", utils.df_t(data, "reasonforwantingtopart")),
        ( "CanAffordDonation", utils.df_c(data, "canafforddonation")), 
        ( "Urgency", utils.df_s(data, "urgency")),
        ( "DateRemovedFromList", utils.df_d(data, "dateremoved", l)),
        ( "AutoRemovePolicy", utils.df_s(data, "autoremovepolicy")),
        ( "DateOfLastOwnerContact", db.dd(now(dbo.timezone))), 
        ( "ReasonForRemoval", utils.df_t(data, "reasonforremoval")),
        ( "Comments", utils.df_t(data, "comments")),
        ( "UrgencyLastUpdatedDate", db.dd(now(dbo.timezone))),
        ( "UrgencyUpdateDate", db.dd(add_days(now(dbo.timezone), configuration.waiting_list_urgency_update_period(dbo))))
        )))
    audit.create(dbo, username, "animalwaitinglist", str(nwlid))
    return nwlid
Esempio n. 2
0
def insert_retailer_from_form(dbo, username, data):
    """
    Inserts a retailer from the workflow move to retailer screen.
    Returns the new movement id
    """
    # Validate that we have a movement date before doing anthing
    l = dbo.locale
    if None == utils.df_kd(data, "retailerdate", l):
        raise utils.ASMValidationError(i18n._("Retailer movements must have a valid movement date.", l))

    # Is this animal already at a foster? If so, return that foster first
    fm = get_animal_movements(dbo, utils.df_ki(data, "animal"))
    for m in fm:
        if m["MOVEMENTTYPE"] == FOSTER and m["RETURNDATE"] is None:
            return_movement(dbo, m["ID"], utils.df_ki(data, "animal"), utils.df_kd(data, "retailerdate", l))
    # Create the retailer movement
    move_dict = {
        "person"                : utils.df_ks(data, "person"),
        "animal"                : utils.df_ks(data, "animal"),
        "movementdate"          : utils.df_ks(data, "retailerdate"),
        "adoptionno"            : utils.df_ks(data, "movementnumber"),
        "type"                  : str(RETAILER),
        "donation"              : utils.df_ks(data, "amount"),
        "returncategory"        : configuration.default_return_reason(dbo)
    }
    movementid = insert_movement_from_form(dbo, username, move_dict)
    return movementid
Esempio n. 3
0
def attach_link_from_form(dbo, username, linktype, linkid, data):
    """
    Attaches a link to a web resource from a form
    """
    existingvid = db.query_int(dbo, "SELECT COUNT(*) FROM media WHERE WebsiteVideo = 1 " \
        "AND LinkID = %d AND LinkTypeID = %d" % ( int(linkid), int(linktype) ))
    defvid = 0
    if existingvid == 0 and utils.df_ki(data,
                                        "linktype") == MEDIATYPE_VIDEO_LINK:
        defvid = 1
    mediaid = db.get_id(dbo, "media")
    url = utils.df_ks(data, "linktarget")
    if url.find("://") == -1:
        url = "http://" + url
    sql = db.make_insert_sql(
        "media",
        (("ID", db.di(mediaid)), ("MediaName", db.ds(url)),
         ("MediaType", utils.df_s(data, "linktype")),
         ("MediaNotes", utils.df_t(data, "comments")),
         ("WebsitePhoto", db.di(0)), ("WebsiteVideo", db.di(defvid)),
         ("DocPhoto", db.di(0)), ("ExcludeFromPublish", db.di(0)),
         ("NewSinceLastPublish", db.di(1)),
         ("UpdatedSinceLastPublish", db.di(0)), ("LinkID", db.di(linkid)),
         ("LinkTypeID", db.di(linktype)), ("Date", db.nowsql())))
    db.execute(dbo, sql)
    audit.create(
        dbo, username, "media",
        str(mediaid) + ": for " + str(linkid) + "/" + str(linktype) +
        ": link to " + utils.df_ks(data, "linktarget"))
Esempio n. 4
0
def insert_user_from_form(dbo, username, data):
    """
    Creates a user record from posted form data. Uses
    the roles key (which should be a comma separated list of
    role ids) to create userrole records.
    """
    nuserid = db.get_id(dbo, "users")
    sql = db.make_insert_sql("users", ( 
        ( "ID", db.di(nuserid)),
        ( "UserName", utils.df_t(data, "username")),
        ( "RealName", utils.df_t(data, "realname")),
        ( "EmailAddress", utils.df_t(data, "email")),
        ( "Password", db.ds(hash_password(utils.df_ks(data, "password"), True))),
        ( "SuperUser", utils.df_s(data, "superuser")),
        ( "RecordVersion", db.di(0)),
        ( "SecurityMap", db.ds("dummy")),
        ( "OwnerID", utils.df_s(data, "person")),
        ( "LocationFilter", utils.df_t(data, "locationfilter")),
        ( "IPRestriction", utils.df_t(data, "iprestriction"))
        ))
    db.execute(dbo, sql)
    audit.create(dbo, username, "users", str(nuserid))
    roles = utils.df_ks(data, "roles").strip()
    if roles != "":
        for rid in roles.split(","):
            if rid.strip() != "":
                db.execute(dbo, "INSERT INTO userrole VALUES (%d, %d)" % (nuserid, int(rid)))
    return nuserid
Esempio n. 5
0
def insert_retailer_from_form(dbo, username, data):
    """
    Inserts a retailer from the workflow move to retailer screen.
    Returns the new movement id
    """
    # Validate that we have a movement date before doing anthing
    l = dbo.locale
    if None == utils.df_kd(data, "retailerdate", l):
        raise utils.ASMValidationError(
            i18n._("Retailer movements must have a valid movement date.", l))

    # Is this animal already at a foster? If so, return that foster first
    fm = get_animal_movements(dbo, utils.df_ki(data, "animal"))
    for m in fm:
        if m["MOVEMENTTYPE"] == FOSTER and m["RETURNDATE"] is None:
            return_movement(dbo, m["ID"], utils.df_ki(data, "animal"),
                            utils.df_kd(data, "retailerdate", l))
    # Create the retailer movement
    move_dict = {
        "person": utils.df_ks(data, "person"),
        "animal": utils.df_ks(data, "animal"),
        "movementdate": utils.df_ks(data, "retailerdate"),
        "adoptionno": utils.df_ks(data, "movementnumber"),
        "type": str(RETAILER),
        "donation": utils.df_ks(data, "amount"),
        "returncategory": configuration.default_return_reason(dbo)
    }
    movementid = insert_movement_from_form(dbo, username, move_dict)
    return movementid
Esempio n. 6
0
def update_diary_from_form(dbo, username, data):
    """
    Updates a diary note from form data
    """
    l = dbo.locale
    diaryid = utils.df_ki(data, "diaryid")
    if utils.df_ks(data, "diarydate") == "":
        raise utils.ASMValidationError(i18n._("Diary date cannot be blank", l))
    if utils.df_kd(data, "diarydate", l) is None:
        raise utils.ASMValidationError(i18n._("Diary date is not valid", l))
    if utils.df_ks(data, "subject") == "":
        raise utils.ASMValidationError(i18n._("Diary subject cannot be blank", l))
    if utils.df_ks(data, "note") == "":
        raise utils.ASMValidationError(i18n._("Diary note cannot be blank", l))
    diarytime =  utils.df_ks(data, "diarytime").strip()
    if diarytime != "":
        if diarytime.find(":") == -1:
            raise utils.ASMValidationError(i18n._("Invalid time, times should be in HH:MM format", l))
        if not utils.is_numeric(diarytime.replace(":", "")):
            raise utils.ASMValidationError(i18n._("Invalid time, times should be in HH:MM format", l))

    sql = db.make_update_user_sql(dbo, "diary", username, "ID=%d" % diaryid, (
        ( "DiaryDateTime", utils.df_dt(data, "diarydate", "diarytime", l) ),
        ( "DiaryForName", utils.df_t(data, "diaryfor") ),
        ( "Subject", utils.df_t(data, "subject") ),
        ( "Note", utils.df_t(data, "note") ),
        ( "Comments", utils.df_t(data, "comments") ),
        ( "DateCompleted", utils.df_d(data, "completed", l) )
        ))
    preaudit = db.query(dbo, "SELECT * FROM diary WHERE ID=%d" % diaryid)
    db.execute(dbo, sql)
    postaudit = db.query(dbo, "SELECT * FROM diary WHERE ID=%d" % diaryid)
    audit.edit(dbo, username, "diary", audit.map_diff(preaudit, postaudit))
Esempio n. 7
0
def update_waitinglist_from_form(dbo, data, username):
    """
    Updates a waiting list record from the screen
    data: The webpy data object containing form parameters
    """
    l = dbo.locale
    wlid = utils.df_ki(data, "id")
    if utils.df_ks(data, "description") == "":
        raise utils.ASMValidationError(_("Description cannot be blank", l))
    if utils.df_ki(data, "owner") == "0":
        raise utils.ASMValidationError(_("Waiting list entries must have a contact", l))
    if utils.df_ks(data, "dateputon") == "":
        raise utils.ASMValidationError(_("Date put on cannot be blank", l))

    preaudit = db.query(dbo, "SELECT * FROM animalwaitinglist WHERE ID = %d" % wlid)
    db.execute(dbo, db.make_update_user_sql(dbo, "animalwaitinglist", username, "ID=%d" % wlid, (
        ( "SpeciesID", utils.df_s(data, "species")),
        ( "DatePutOnList", utils.df_d(data, "dateputon", l)),
        ( "OwnerID", utils.df_s(data, "owner")),
        ( "AnimalDescription", utils.df_t(data, "description")),
        ( "ReasonForWantingToPart", utils.df_t(data, "reasonforwantingtopart")),
        ( "CanAffordDonation", utils.df_c(data, "canafforddonation")), 
        ( "Urgency", utils.df_s(data, "urgency")),
        ( "DateRemovedFromList", utils.df_d(data, "dateremoved", l)),
        ( "AutoRemovePolicy", utils.df_s(data, "autoremovepolicy")),
        ( "DateOfLastOwnerContact", utils.df_d(data, "dateoflastownercontact", l)),
        ( "ReasonForRemoval", utils.df_t(data, "reasonforremoval")),
        ( "Comments", utils.df_t(data, "comments"))
        )))
    additional.save_values_for_link(dbo, data, wlid, "waitinglist")
    postaudit = db.query(dbo, "SELECT * FROM animalwaitinglist WHERE ID = %d" % wlid)
    audit.edit(dbo, username, "animalwaitinglist", audit.map_diff(preaudit, postaudit))
Esempio n. 8
0
def insert_user_from_form(dbo, username, data):
    """
    Creates a user record from posted form data. Uses
    the roles key (which should be a comma separated list of
    role ids) to create userrole records.
    """
    nuserid = db.get_id(dbo, "users")
    sql = db.make_insert_sql(
        "users",
        (("ID", db.di(nuserid)), ("UserName", utils.df_t(data, "username")),
         ("RealName", utils.df_t(data, "realname")),
         ("EmailAddress", utils.df_t(data, "email")),
         ("Password", db.ds(hash_password(utils.df_ks(data, "password"),
                                          True))),
         ("SuperUser", utils.df_s(data, "superuser")),
         ("RecordVersion", db.di(0)), ("SecurityMap", db.ds("dummy")),
         ("OwnerID", utils.df_s(data, "person")),
         ("LocationFilter", utils.df_t(data, "locationfilter")),
         ("IPRestriction", utils.df_t(data, "iprestriction"))))
    db.execute(dbo, sql)
    audit.create(dbo, username, "users", str(nuserid))
    roles = utils.df_ks(data, "roles").strip()
    if roles != "":
        for rid in roles.split(","):
            if rid.strip() != "":
                db.execute(
                    dbo, "INSERT INTO userrole VALUES (%d, %d)" %
                    (nuserid, int(rid)))
    return nuserid
Esempio n. 9
0
def insert_onlineformincoming_from_form(dbo, data, remoteip):
    """
    Create onlineformincoming records from posted data. We 
    create a row for every key/value pair in the posted data
    with a unique collation ID.
    """
    IGNORE_FIELDS = [
        "formname", "flags", "redirect", "account", "filechooser", "method"
    ]
    collationid = db.query_int(
        dbo, "SELECT MAX(CollationID) FROM onlineformincoming") + 1
    formname = utils.df_ks(data, "formname")
    posteddate = i18n.now(dbo.timezone)
    flags = utils.df_ks(data, "flags")
    for k, v in data.iteritems():
        if k not in IGNORE_FIELDS:
            label = ""
            displayindex = 0
            fieldname = k
            # Form fields should have a _ONLINEFORMFIELD.ID suffix we can use to get the
            # original label and display position
            if k.find("_") != -1:
                fid = utils.cint(k[k.rfind("_") + 1:])
                fieldname = k[0:k.rfind("_")]
                if fid != 0:
                    fld = db.query(
                        dbo,
                        "SELECT Label, DisplayIndex FROM onlineformfield WHERE ID = %d"
                        % fid)
                    if len(fld) > 0:
                        label = fld[0]["LABEL"]
                        displayindex = fld[0]["DISPLAYINDEX"]

            sql = db.make_insert_sql(
                "onlineformincoming",
                (("CollationID", db.di(collationid)),
                 ("FormName", db.ds(formname)),
                 ("PostedDate", db.ddt(posteddate)), ("Flags", db.ds(flags)),
                 ("FieldName", db.ds(fieldname)), ("Label", db.ds(label)),
                 ("DisplayIndex", db.di(displayindex)),
                 ("Host", db.ds(remoteip)), ("Value", db.ds(v))))
            db.execute(dbo, sql)
    # Sort out the preview of the first few fields
    fieldssofar = 0
    preview = []
    for fld in get_onlineformincoming_detail(dbo, collationid):
        if fieldssofar < 3:
            fieldssofar += 1
            preview.append(fld["LABEL"] + ": " + fld["VALUE"])
    db.execute(
        dbo,
        "UPDATE onlineformincoming SET Preview = %s WHERE CollationID = %s" %
        (db.ds(", ".join(preview)), db.di(collationid)))
    return collationid
Esempio n. 10
0
def insert_regimen_from_form(dbo, username, data):
    """
    Creates a regimen record from posted form data
    """
    l = dbo.locale
    if utils.df_kd(data, "startdate", l) is None:
        raise utils.ASMValidationError(_("Start date must be a valid date", l))
    if utils.df_ks(data, "treatmentname") == "":
        raise utils.ASMValidationError(_("Treatment name cannot be blank", l))

    l = dbo.locale
    nregid = db.get_id(dbo, "animalmedical")
    timingrule = utils.df_ki(data, "timingrule")
    timingrulenofrequencies = utils.df_ki(data, "timingrulenofrequencies")
    timingrulefrequency = utils.df_ki(data, "timingrulefrequency")
    totalnumberoftreatments = utils.df_ki(data, "totalnumberoftreatments")
    treatmentsremaining = int(totalnumberoftreatments) * int(timingrule)
    treatmentrule = utils.df_ki(data, "treatmentrule")
    singlemulti = utils.df_ki(data, "singlemulti")
    if singlemulti == 0:
        timingrule = 0
        timingrulenofrequencies = 0
        timingrulefrequency = 0
        treatmentsremaining = 1
    if treatmentrule != 0:
        totalnumberoftreatments = 0
        treatmentsremaining = 0

    sql = db.make_insert_user_sql(
        dbo, "animalmedical", username,
        (("ID", db.di(nregid)),
         ("AnimalID", db.di(utils.df_ki(data, "animal"))),
         ("MedicalProfileID", utils.df_s(data, "profileid")),
         ("TreatmentName", utils.df_t(data, "treatmentname")),
         ("Dosage", utils.df_t(data, "dosage")),
         ("StartDate", utils.df_d(data, "startdate", l)), ("Status", db.di(0)),
         ("Cost", utils.df_m(data, "cost", l)),
         ("TimingRule", db.di(timingrule)),
         ("TimingRuleFrequency", db.di(timingrulefrequency)),
         ("TimingRuleNoFrequencies", db.di(timingrulenofrequencies)),
         ("TreatmentRule", utils.df_s(data, "treatmentrule")),
         ("TotalNumberOfTreatments", db.di(totalnumberoftreatments)),
         ("TreatmentsGiven", db.di(0)),
         ("TreatmentsRemaining", db.di(treatmentsremaining)),
         ("Comments", utils.df_t(data, "comments"))))
    db.execute(dbo, sql)
    audit.create(
        dbo, username, "animalmedical",
        str(nregid) + ": " + utils.df_ks(data, "treatmentname") + " " +
        utils.df_ks(data, "dosage"))
    update_medical_treatments(dbo, username, nregid)
Esempio n. 11
0
def insert_onlineform_from_form(dbo, username, data):
    """
    Create an onlineform record from posted data
    """
    formid = db.get_id(dbo, "onlineform")
    sql = db.make_insert_sql(
        "onlineform",
        (("ID", db.di(formid)), ("Name", db.ds(utils.df_ks(data, "name"))),
         ("RedirectUrlAfterPOST", db.ds(utils.df_ks(data, "redirect"))),
         ("SetOwnerFlags", db.ds(utils.df_ks(data, "flags"))),
         ("Description", db.ds(utils.df_ks(data, "description")))))
    db.execute(dbo, sql)
    audit.create(dbo, username, "onlineform", str(formid))
    return formid
Esempio n. 12
0
def insert_regimen_from_form(dbo, username, data):
    """
    Creates a regimen record from posted form data
    """
    l = dbo.locale
    if utils.df_kd(data, "startdate", l) is None:
        raise utils.ASMValidationError(_("Start date must be a valid date", l))
    if utils.df_ks(data, "treatmentname") == "":
        raise utils.ASMValidationError(_("Treatment name cannot be blank", l))

    l = dbo.locale
    nregid = db.get_id(dbo, "animalmedical")
    timingrule = utils.df_ki(data, "timingrule")
    timingrulenofrequencies = utils.df_ki(data, "timingrulenofrequencies")
    timingrulefrequency = utils.df_ki(data, "timingrulefrequency")
    totalnumberoftreatments = utils.df_ki(data, "totalnumberoftreatments")
    treatmentsremaining = int(totalnumberoftreatments) * int(timingrule)
    treatmentrule = utils.df_ki(data, "treatmentrule")
    singlemulti = utils.df_ki(data, "singlemulti")
    if singlemulti == 0:
        timingrule = 0
        timingrulenofrequencies = 0
        timingrulefrequency = 0
        treatmentsremaining = 1
    if treatmentrule != 0:
        totalnumberoftreatments = 0
        treatmentsremaining = 0

    sql = db.make_insert_user_sql(dbo, "animalmedical", username, ( 
        ( "ID", db.di(nregid)),
        ( "AnimalID", db.di(utils.df_ki(data, "animal"))),
        ( "MedicalProfileID", utils.df_s(data, "profileid")),
        ( "TreatmentName", utils.df_t(data, "treatmentname")),
        ( "Dosage", utils.df_t(data, "dosage")),
        ( "StartDate", utils.df_d(data, "startdate", l)),
        ( "Status", db.di(0)),
        ( "Cost", utils.df_m(data, "cost", l)),
        ( "TimingRule", db.di(timingrule)),
        ( "TimingRuleFrequency", db.di(timingrulefrequency)),
        ( "TimingRuleNoFrequencies", db.di(timingrulenofrequencies)),
        ( "TreatmentRule", utils.df_s(data, "treatmentrule")),
        ( "TotalNumberOfTreatments", db.di(totalnumberoftreatments)),
        ( "TreatmentsGiven", db.di(0)),
        ( "TreatmentsRemaining", db.di(treatmentsremaining)),
        ( "Comments", utils.df_t(data, "comments"))
        ))
    db.execute(dbo, sql)
    audit.create(dbo, username, "animalmedical", str(nregid) + ": " + utils.df_ks(data, "treatmentname") + " " + utils.df_ks(data, "dosage"))
    update_medical_treatments(dbo, username, nregid)
Esempio n. 13
0
def update_onlineform_from_form(dbo, username, data):
    """
    Update an onlineform record from posted data
    """
    formid = utils.df_ki(data, "formid")
    sql = db.make_update_sql("onlineform", "ID=%d" % formid, ( 
        ( "Name", db.ds(utils.df_ks(data, "name"))),
        ( "RedirectUrlAfterPOST", db.ds(utils.df_ks(data, "redirect"))),
        ( "SetOwnerFlags", db.ds(utils.df_ks(data, "flags"))),
        ( "Description", db.ds(utils.df_ks(data, "description")))
        ))
    preaudit = db.query(dbo, "SELECT * FROM onlineform WHERE ID = %d" % formid)
    db.execute(dbo, sql)
    postaudit = db.query(dbo, "SELECT * FROM onlineform WHERE ID = %d" % formid)
    audit.edit(dbo, username, "onlineform", audit.map_diff(preaudit, postaudit))
Esempio n. 14
0
def insert_onlineform_from_form(dbo, username, data):
    """
    Create an onlineform record from posted data
    """
    formid = db.get_id(dbo, "onlineform")
    sql = db.make_insert_sql("onlineform", ( 
        ( "ID", db.di(formid)),
        ( "Name", db.ds(utils.df_ks(data, "name"))),
        ( "RedirectUrlAfterPOST", db.ds(utils.df_ks(data, "redirect"))),
        ( "SetOwnerFlags", db.ds(utils.df_ks(data, "flags"))),
        ( "Description", db.ds(utils.df_ks(data, "description")))
        ))
    db.execute(dbo, sql)
    audit.create(dbo, username, "onlineform", str(formid))
    return formid
Esempio n. 15
0
def insert_onlineformincoming_from_form(dbo, data, remoteip):
    """
    Create onlineformincoming records from posted data. We 
    create a row for every key/value pair in the posted data
    with a unique collation ID.
    """
    IGNORE_FIELDS = [ "formname", "flags", "redirect", "account", "filechooser", "method" ]
    collationid = db.query_int(dbo, "SELECT MAX(CollationID) FROM onlineformincoming") + 1
    formname = utils.df_ks(data, "formname")
    posteddate = i18n.now(dbo.timezone)
    flags = utils.df_ks(data, "flags")
    for k, v in data.iteritems():
        if k not in IGNORE_FIELDS:
            label = ""
            displayindex = 0
            fieldname = k
            # Form fields should have a _ONLINEFORMFIELD.ID suffix we can use to get the
            # original label and display position
            if k.find("_") != -1:
                fid = utils.cint(k[k.rfind("_")+1:])
                fieldname = k[0:k.rfind("_")]
                if fid != 0:
                    fld = db.query(dbo, "SELECT Label, DisplayIndex FROM onlineformfield WHERE ID = %d" % fid)
                    if len(fld) > 0:
                        label = fld[0]["LABEL"]
                        displayindex = fld[0]["DISPLAYINDEX"]

            sql = db.make_insert_sql("onlineformincoming", ( 
                ( "CollationID", db.di(collationid)),
                ( "FormName", db.ds(formname)),
                ( "PostedDate", db.ddt(posteddate)),
                ( "Flags", db.ds(flags)),
                ( "FieldName", db.ds(fieldname)),
                ( "Label", db.ds(label)),
                ( "DisplayIndex", db.di(displayindex)),
                ( "Host", db.ds(remoteip)),
                ( "Value", db.ds(v))
                ))
            db.execute(dbo, sql)
    # Sort out the preview of the first few fields
    fieldssofar = 0
    preview = []
    for fld in get_onlineformincoming_detail(dbo, collationid):
        if fieldssofar < 3:
            fieldssofar += 1
            preview.append( fld["LABEL"] + ": " + fld["VALUE"] )
    db.execute(dbo, "UPDATE onlineformincoming SET Preview = %s WHERE CollationID = %s" % ( db.ds(", ".join(preview)), db.di(collationid) ))
    return collationid
Esempio n. 16
0
def update_user_from_form(dbo, username, data):
    """
    Updates a user record from posted form data
    Uses the roles key (which should be a comma separated list of
    role ids) to create userrole records.
    """
    userid = utils.df_ki(data, "userid")
    sql = db.make_update_sql(
        "users", "ID=%d" % userid,
        (("RealName", utils.df_t(data, "realname")),
         ("EmailAddress", utils.df_t(data, "email")),
         ("SuperUser", utils.df_s(data, "superuser")),
         ("OwnerID", utils.df_s(data, "person")),
         ("LocationFilter", utils.df_t(data, "locationfilter")),
         ("IPRestriction", utils.df_t(data, "iprestriction"))))
    preaudit = db.query(dbo, "SELECT * FROM users WHERE ID = %d" % userid)
    db.execute(dbo, sql)
    postaudit = db.query(dbo, "SELECT * FROM users WHERE ID = %d" % userid)
    audit.edit(dbo, username, "users",
               audit.map_diff(preaudit, postaudit, [
                   "USERNAME",
               ]))
    db.execute(dbo, "DELETE FROM userrole WHERE UserID = %d" % userid)
    if utils.df_ki(data, "issuperuser") == 0:
        roles = utils.df_ks(data, "roles").strip()
        if roles != "":
            for rid in roles.split(","):
                if rid.strip() != "":
                    db.execute(
                        dbo, "INSERT INTO userrole VALUES (%d, %d)" %
                        (userid, int(rid)))
Esempio n. 17
0
def update_user_from_form(dbo, username, data):
    """
    Updates a user record from posted form data
    Uses the roles key (which should be a comma separated list of
    role ids) to create userrole records.
    """
    userid = utils.df_ki(data, "userid")
    sql = db.make_update_sql("users", "ID=%d" % userid, ( 
        ( "RealName", utils.df_t(data, "realname")),
        ( "EmailAddress", utils.df_t(data, "email")),
        ( "SuperUser", utils.df_s(data, "superuser")),
        ( "OwnerID", utils.df_s(data, "person")),
        ( "LocationFilter", utils.df_t(data, "locationfilter")),
        ( "IPRestriction", utils.df_t(data, "iprestriction"))
        ))
    preaudit = db.query(dbo, "SELECT * FROM users WHERE ID = %d" % userid)
    db.execute(dbo, sql)
    postaudit = db.query(dbo, "SELECT * FROM users WHERE ID = %d" % userid)
    audit.edit(dbo, username, "users", audit.map_diff(preaudit, postaudit, [ "USERNAME", ]))
    db.execute(dbo, "DELETE FROM userrole WHERE UserID = %d" % userid)
    if utils.df_ki(data, "issuperuser") == 0:
        roles = utils.df_ks(data, "roles").strip()
        if roles != "":
            for rid in roles.split(","):
                if rid.strip() != "":
                    db.execute(dbo, "INSERT INTO userrole VALUES (%d, %d)" % (userid, int(rid)))
Esempio n. 18
0
def attach_link_from_form(dbo, username, linktype, linkid, data):
    """
    Attaches a link to a web resource from a form
    """
    existingvid = db.query_int(dbo, "SELECT COUNT(*) FROM media WHERE WebsiteVideo = 1 " \
        "AND LinkID = %d AND LinkTypeID = %d" % ( int(linkid), int(linktype) ))
    defvid = 0
    if existingvid == 0 and utils.df_ki(data, "linktype") == MEDIATYPE_VIDEO_LINK:
        defvid = 1
    mediaid = db.get_id(dbo, "media")
    url = utils.df_ks(data, "linktarget")
    if url.find("://") == -1:
        url = "http://" + url
    sql = db.make_insert_sql("media", (
        ( "ID", db.di(mediaid) ),
        ( "MediaName", db.ds(url) ),
        ( "MediaType", utils.df_s(data, "linktype") ),
        ( "MediaNotes", utils.df_t(data, "comments") ),
        ( "WebsitePhoto", db.di(0) ),
        ( "WebsiteVideo", db.di(defvid) ),
        ( "DocPhoto", db.di(0) ),
        ( "ExcludeFromPublish", db.di(0) ),
        ( "NewSinceLastPublish", db.di(1) ),
        ( "UpdatedSinceLastPublish", db.di(0) ),
        ( "LinkID", db.di(linkid) ),
        ( "LinkTypeID", db.di(linktype) ),
        ( "Date", db.nowsql() )
        ))
    db.execute(dbo, sql)
    audit.create(dbo, username, "media", str(mediaid) + ": for " + str(linkid) + "/" + str(linktype) + ": link to " + utils.df_ks(data, "linktarget"))
Esempio n. 19
0
def update_regimen_from_form(dbo, username, data):
    """
    Updates a regimen record from posted form data
    """
    l = dbo.locale
    regimenid = utils.df_ki(data, "regimenid")
    if utils.df_ks(data, "treatmentname") == "":
        raise utils.ASMValidationError(_("Treatment name cannot be blank", l))

    sql = db.make_update_user_sql(
        dbo, "animalmedical", username, "ID=%d" % regimenid,
        (("TreatmentName", utils.df_t(data, "treatmentname")),
         ("Dosage", utils.df_t(data, "dosage")),
         ("Status", utils.df_s(data, "status")),
         ("Cost", utils.df_m(data, "cost", l)),
         ("Comments", utils.df_t(data, "comments"))))
    preaudit = db.query(dbo,
                        "SELECT * FROM animalmedical WHERE ID=%d" % regimenid)
    db.execute(dbo, sql)
    postaudit = db.query(dbo,
                         "SELECT * FROM animalmedical WHERE ID=%d" % regimenid)
    audit.edit(
        dbo, username, "animalmedical",
        audit.map_diff(preaudit, postaudit, ["TREATMENTNAME", "DOSAGE"]))
    update_medical_treatments(dbo, username, utils.df_ki(data, "regimenid"))
Esempio n. 20
0
def save_values_for_link(dbo, data, linkid, linktype="animal"):
    """
    Saves incoming additional field values from a form, clearing any
    existing values first.
    """
    delete_values_for_link(dbo, linkid, linktype)
    af = get_field_definitions(dbo, linktype)
    l = dbo.locale
    for f in af:
        key = "a." + str(f["MANDATORY"]) + "." + str(f["ID"])
        if data.has_key(key):
            val = utils.df_ks(data, key)
            if f["FIELDTYPE"] == YESNO:
                val = str(utils.df_kc(data, key))
            elif f["FIELDTYPE"] == MONEY:
                val = str(utils.df_km(data, key, l))
            elif f["FIELDTYPE"] == DATE:
                if len(val.strip()) > 0 and utils.df_kd(data, key, l) == None:
                    raise utils.ASMValidationError(
                        _(
                            "Additional date field '{0}' contains an invalid date.",
                            l).format(f["FIELDNAME"]))
                val = python2display(dbo.locale, utils.df_kd(data, key, l))
            sql = db.make_insert_sql("additional",
                                     (("LinkType", db.di(f["LINKTYPE"])),
                                      ("LinkID", db.di(int(linkid))),
                                      ("AdditionalFieldID", db.di(f["ID"])),
                                      ("Value", db.ds(val))))
            try:
                db.execute(dbo, sql)
            except Exception, err:
                al.error("Failed saving additional field: %s" % str(err),
                         "animal.update_animal_from_form", dbo, sys.exc_info())
Esempio n. 21
0
def send_email_from_form(dbo, username, data):
    """
    Sends an email to a person from a posted form. Attaches it as
    a log entry if specified.
    """
    emailfrom = utils.df_ks(data, "from")
    emailto = utils.df_ks(data, "to")
    emailcc = utils.df_ks(data, "cc")
    subject = utils.df_ks(data, "subject")
    ishtml = utils.df_kc(data, "html")
    addtolog = utils.df_kc(data, "addtolog")
    logtype = utils.df_ki(data, "logtype")
    body = utils.df_ks(data, "body")
    utils.send_email(dbo, emailfrom, emailto, emailcc, subject, body, ishtml == 1 and "html" or "plain")
    if addtolog == 1:
        log.add_log(dbo, username, log.PERSON, utils.df_ki(data, "personid"), logtype, body)
Esempio n. 22
0
def update_onlineformfield_from_form(dbo, username, data):
    """
    Update an onlineformfield record from posted data
    """
    formfieldid = utils.df_ki(data, "formfieldid")
    sql = db.make_update_sql("onlineformfield", "ID=%d" % formfieldid, ( 
        ( "FieldName", db.ds(utils.df_ks(data, "fieldname"))),
        ( "FieldType", db.di(utils.df_ki(data, "fieldtype"))),
        ( "Label", db.ds(utils.df_ks(data, "label"))),
        ( "DisplayIndex", db.di(utils.df_ki(data, "displayindex"))),
        ( "Lookups", db.ds(utils.df_ks(data, "lookups"))),
        ( "Tooltip", db.ds(utils.df_ks(data, "tooltip")))
        ))
    preaudit = db.query(dbo, "SELECT * FROM onlineformfield WHERE ID = %d" % formfieldid)
    db.execute(dbo, sql)
    postaudit = db.query(dbo, "SELECT * FROM onlineformfield WHERE ID = %d" % formfieldid)
    audit.edit(dbo, username, "onlineformfield", audit.map_diff(preaudit, postaudit))
Esempio n. 23
0
def update_onlineform_from_form(dbo, username, data):
    """
    Update an onlineform record from posted data
    """
    formid = utils.df_ki(data, "formid")
    sql = db.make_update_sql(
        "onlineform", "ID=%d" % formid,
        (("Name", db.ds(utils.df_ks(data, "name"))),
         ("RedirectUrlAfterPOST", db.ds(utils.df_ks(data, "redirect"))),
         ("SetOwnerFlags", db.ds(utils.df_ks(data, "flags"))),
         ("Description", db.ds(utils.df_ks(data, "description")))))
    preaudit = db.query(dbo, "SELECT * FROM onlineform WHERE ID = %d" % formid)
    db.execute(dbo, sql)
    postaudit = db.query(dbo,
                         "SELECT * FROM onlineform WHERE ID = %d" % formid)
    audit.edit(dbo, username, "onlineform",
               audit.map_diff(preaudit, postaudit))
Esempio n. 24
0
def insert_onlineformfield_from_form(dbo, username, data):
    """
    Create an onlineformfield record from posted data
    """
    formfieldid = db.get_id(dbo, "onlineformfield")
    sql = db.make_insert_sql("onlineformfield", ( 
        ( "ID", db.di(formfieldid)),
        ( "OnlineFormID", db.di(utils.df_ki(data, "formid"))),
        ( "FieldName", db.ds(utils.df_ks(data, "fieldname"))),
        ( "FieldType", db.di(utils.df_ki(data, "fieldtype"))),
        ( "Label", db.ds(utils.df_ks(data, "label"))),
        ( "DisplayIndex", db.di(utils.df_ki(data, "displayindex"))),
        ( "Lookups", db.ds(utils.df_ks(data, "lookups"))),
        ( "Tooltip", db.ds(utils.df_ks(data, "tooltip")))
        ))
    db.execute(dbo, sql)
    audit.create(dbo, username, "onlineformfield", str(formfieldid))
    return formfieldid
Esempio n. 25
0
def insert_onlineformfield_from_form(dbo, username, data):
    """
    Create an onlineformfield record from posted data
    """
    formfieldid = db.get_id(dbo, "onlineformfield")
    sql = db.make_insert_sql(
        "onlineformfield",
        (("ID", db.di(formfieldid)),
         ("OnlineFormID", db.di(utils.df_ki(data, "formid"))),
         ("FieldName", db.ds(utils.df_ks(data, "fieldname"))),
         ("FieldType", db.di(utils.df_ki(data, "fieldtype"))),
         ("Label", db.ds(utils.df_ks(data, "label"))),
         ("DisplayIndex", db.di(utils.df_ki(data, "displayindex"))),
         ("Lookups", db.ds(utils.df_ks(data, "lookups"))),
         ("Tooltip", db.ds(utils.df_ks(data, "tooltip")))))
    db.execute(dbo, sql)
    audit.create(dbo, username, "onlineformfield", str(formfieldid))
    return formfieldid
Esempio n. 26
0
def send_email_from_form(dbo, username, data):
    """
    Sends an email to a person from a posted form. Attaches it as
    a log entry if specified.
    """
    emailfrom = utils.df_ks(data, "from")
    emailto = utils.df_ks(data, "to")
    emailcc = utils.df_ks(data, "cc")
    subject = utils.df_ks(data, "subject")
    ishtml = utils.df_kc(data, "html")
    addtolog = utils.df_kc(data, "addtolog")
    logtype = utils.df_ki(data, "logtype")
    body = utils.df_ks(data, "body")
    utils.send_email(dbo, emailfrom, emailto, emailcc, subject, body,
                     ishtml == 1 and "html" or "plain")
    if addtolog == 1:
        log.add_log(dbo, username, log.PERSON, utils.df_ki(data, "personid"),
                    logtype, body)
Esempio n. 27
0
def update_profile_from_form(dbo, username, data):
    """
    Updates a profile record from posted form data
    """
    l = dbo.locale
    profileid = utils.df_ki(data, "profileid")
    if utils.df_ks(data, "treatmentname") == "":
        raise utils.ASMValidationError(_("Treatment name cannot be blank", l))
    if utils.df_ks(data, "profilename") == "":
        raise utils.ASMValidationError(_("Profile name cannot be blank", l))

    timingrule = utils.df_ki(data, "timingrule")
    timingrulenofrequencies = utils.df_ki(data, "timingrulenofrequencies")
    timingrulefrequency = utils.df_ki(data, "timingrulefrequency")
    totalnumberoftreatments = utils.df_ki(data, "totalnumberoftreatments")
    treatmentrule = utils.df_ki(data, "treatmentrule")
    singlemulti = utils.df_ki(data, "singlemulti")
    if singlemulti == 0:
        timingrule = 0
        timingrulenofrequencies = 0
        timingrulefrequency = 0
    if treatmentrule != 0:
        totalnumberoftreatments = 0
    sql = db.make_update_user_sql(
        dbo, "medicalprofile", username, "ID=%d" % profileid,
        (("ProfileName", utils.df_t(data, "profilename")),
         ("TreatmentName", utils.df_t(data, "treatmentname")),
         ("Dosage", utils.df_t(data, "dosage")),
         ("Cost", utils.df_m(data, "cost", l)),
         ("TimingRule", db.di(timingrule)),
         ("TimingRuleFrequency", db.di(timingrulefrequency)),
         ("TimingRuleNoFrequencies", db.di(timingrulenofrequencies)),
         ("TreatmentRule", utils.df_s(data, "treatmentrule")),
         ("TotalNumberOfTreatments", db.di(totalnumberoftreatments)),
         ("Comments", utils.df_t(data, "comments"))))
    preaudit = db.query(dbo,
                        "SELECT * FROM medicalprofile WHERE ID=%d" % profileid)
    db.execute(dbo, sql)
    postaudit = db.query(
        dbo, "SELECT * FROM medicalprofile WHERE ID=%d" % profileid)
    audit.edit(
        dbo, username, "medicalprofile",
        audit.map_diff(preaudit, postaudit, ["TREATMENTNAME", "DOSAGE"]))
Esempio n. 28
0
def update_onlineformfield_from_form(dbo, username, data):
    """
    Update an onlineformfield record from posted data
    """
    formfieldid = utils.df_ki(data, "formfieldid")
    sql = db.make_update_sql(
        "onlineformfield", "ID=%d" % formfieldid,
        (("FieldName", db.ds(utils.df_ks(data, "fieldname"))),
         ("FieldType", db.di(utils.df_ki(data, "fieldtype"))),
         ("Label", db.ds(utils.df_ks(data, "label"))),
         ("DisplayIndex", db.di(utils.df_ki(data, "displayindex"))),
         ("Lookups", db.ds(utils.df_ks(data, "lookups"))),
         ("Tooltip", db.ds(utils.df_ks(data, "tooltip")))))
    preaudit = db.query(
        dbo, "SELECT * FROM onlineformfield WHERE ID = %d" % formfieldid)
    db.execute(dbo, sql)
    postaudit = db.query(
        dbo, "SELECT * FROM onlineformfield WHERE ID = %d" % formfieldid)
    audit.edit(dbo, username, "onlineformfield",
               audit.map_diff(preaudit, postaudit))
Esempio n. 29
0
def insert_profile_from_form(dbo, username, data):
    """
    Creates a profile record from posted form data
    """
    l = dbo.locale
    if utils.df_ks(data, "treatmentname") == "":
        raise utils.ASMValidationError(_("Treatment name cannot be blank", l))
    if utils.df_ks(data, "profilename") == "":
        raise utils.ASMValidationError(_("Profile name cannot be blank", l))

    nprofid = db.get_id(dbo, "medicalprofile")
    timingrule = utils.df_ki(data, "timingrule")
    timingrulenofrequencies = utils.df_ki(data, "timingrulenofrequencies")
    timingrulefrequency = utils.df_ki(data, "timingrulefrequency")
    totalnumberoftreatments = utils.df_ki(data, "totalnumberoftreatments")
    treatmentrule = utils.df_ki(data, "treatmentrule")
    singlemulti = utils.df_ki(data, "singlemulti")
    if singlemulti == 0:
        timingrule = 0
        timingrulenofrequencies = 0
        timingrulefrequency = 0
    if treatmentrule != 0:
        totalnumberoftreatments = 0
    sql = db.make_insert_user_sql(
        dbo, "medicalprofile", username,
        (("ID", db.di(nprofid)),
         ("ProfileName", utils.df_t(data, "profilename")),
         ("TreatmentName", utils.df_t(data, "treatmentname")),
         ("Dosage", utils.df_t(data, "dosage")),
         ("Cost", utils.df_m(data, "cost", l)),
         ("TimingRule", db.di(timingrule)),
         ("TimingRuleFrequency", db.di(timingrulefrequency)),
         ("TimingRuleNoFrequencies", db.di(timingrulenofrequencies)),
         ("TreatmentRule", utils.df_s(data, "treatmentrule")),
         ("TotalNumberOfTreatments", db.di(totalnumberoftreatments)),
         ("Comments", utils.df_t(data, "comments"))))
    db.execute(dbo, sql)
    audit.create(
        dbo, username, "medicalprofile",
        str(nprofid) + ": " + utils.df_ks(data, "treatmentname") + " " +
        utils.df_ks(data, "dosage"))
Esempio n. 30
0
def insert_diary_from_form(dbo, username, linktypeid, linkid, data):
    """
    Creates a diary note from the form data
    username: User creating the diary
    linktypeid, linkid: The link
    data: The web.py form object
    """
    l = dbo.locale
    if utils.df_ks(data, "diarydate") == "":
        raise utils.ASMValidationError(i18n._("Diary date cannot be blank", l))
    if utils.df_kd(data, "diarydate", l) is None:
        raise utils.ASMValidationError(i18n._("Diary date is not valid", l))
    if utils.df_ks(data, "subject") == "":
        raise utils.ASMValidationError(
            i18n._("Diary subject cannot be blank", l))
    if utils.df_ks(data, "note") == "":
        raise utils.ASMValidationError(i18n._("Diary note cannot be blank", l))
    diarytime = utils.df_ks(data, "diarytime").strip()
    if diarytime != "":
        if diarytime.find(":") == -1:
            raise utils.ASMValidationError(
                i18n._("Invalid time, times should be in HH:MM format", l))
        if not utils.is_numeric(diarytime.replace(":", "")):
            raise utils.ASMValidationError(
                i18n._("Invalid time, times should be in HH:MM format", l))

    linkinfo = get_link_info(dbo, linktypeid, linkid)
    diaryid = db.get_id(dbo, "diary")
    sql = db.make_insert_user_sql(
        dbo, "diary", username,
        (("ID", db.di(diaryid)), ("LinkID", db.di(linkid)),
         ("LinkType", db.di(linktypeid)), ("LinkInfo", db.ds(linkinfo)),
         ("DiaryDateTime", utils.df_dt(data, "diarydate", "diarytime", l)),
         ("DiaryForName", utils.df_t(data, "diaryfor")),
         ("Subject", utils.df_t(data, "subject")),
         ("Note", utils.df_t(data, "note")),
         ("DateCompleted", utils.df_d(data, "completed", l))))
    db.execute(dbo, sql)
    audit.create(dbo, username, "diary", str(diaryid))
    return diaryid
Esempio n. 31
0
def insert_waitinglist_from_form(dbo, data, username):
    """
    Creates a waiting list record from the screen
    data: The webpy data object containing form parameters
    """
    l = dbo.locale
    if utils.df_ks(data, "description") == "":
        raise utils.ASMValidationError(_("Description cannot be blank", l))
    if utils.df_ki(data, "owner") == "0":
        raise utils.ASMValidationError(
            _("Waiting list entries must have a contact", l))
    if utils.df_ks(data, "dateputon") == "":
        raise utils.ASMValidationError(_("Date put on cannot be blank", l))
    nwlid = db.get_id(dbo, "animalwaitinglist")
    db.execute(
        dbo,
        db.make_insert_user_sql(
            dbo, "animalwaitinglist", username,
            (("ID", db.di(nwlid)), ("SpeciesID", utils.df_s(data, "species")),
             ("DatePutOnList", utils.df_d(data, "dateputon", l)),
             ("OwnerID", utils.df_s(data, "owner")),
             ("AnimalDescription", utils.df_t(data, "description")),
             ("ReasonForWantingToPart",
              utils.df_t(data, "reasonforwantingtopart")),
             ("CanAffordDonation", utils.df_c(data, "canafforddonation")),
             ("Urgency", utils.df_s(data, "urgency")),
             ("DateRemovedFromList", utils.df_d(data, "dateremoved", l)),
             ("AutoRemovePolicy", utils.df_s(data, "autoremovepolicy")),
             ("DateOfLastOwnerContact", db.dd(now(dbo.timezone))),
             ("ReasonForRemoval", utils.df_t(data, "reasonforremoval")),
             ("Comments", utils.df_t(data, "comments")),
             ("UrgencyLastUpdatedDate", db.dd(now(dbo.timezone))),
             ("UrgencyUpdateDate",
              db.dd(
                  add_days(
                      now(dbo.timezone),
                      configuration.waiting_list_urgency_update_period(dbo)))
              ))))
    audit.create(dbo, username, "animalwaitinglist", str(nwlid))
    return nwlid
Esempio n. 32
0
def update_waitinglist_from_form(dbo, data, username):
    """
    Updates a waiting list record from the screen
    data: The webpy data object containing form parameters
    """
    l = dbo.locale
    wlid = utils.df_ki(data, "id")
    if utils.df_ks(data, "description") == "":
        raise utils.ASMValidationError(_("Description cannot be blank", l))
    if utils.df_ki(data, "owner") == "0":
        raise utils.ASMValidationError(
            _("Waiting list entries must have a contact", l))
    if utils.df_ks(data, "dateputon") == "":
        raise utils.ASMValidationError(_("Date put on cannot be blank", l))

    preaudit = db.query(dbo,
                        "SELECT * FROM animalwaitinglist WHERE ID = %d" % wlid)
    db.execute(
        dbo,
        db.make_update_user_sql(
            dbo, "animalwaitinglist", username, "ID=%d" % wlid,
            (("SpeciesID", utils.df_s(data, "species")),
             ("DatePutOnList", utils.df_d(data, "dateputon", l)),
             ("OwnerID", utils.df_s(data, "owner")),
             ("AnimalDescription", utils.df_t(data, "description")),
             ("ReasonForWantingToPart",
              utils.df_t(data, "reasonforwantingtopart")),
             ("CanAffordDonation", utils.df_c(data, "canafforddonation")),
             ("Urgency", utils.df_s(data, "urgency")),
             ("DateRemovedFromList", utils.df_d(data, "dateremoved", l)),
             ("AutoRemovePolicy", utils.df_s(data, "autoremovepolicy")),
             ("DateOfLastOwnerContact",
              utils.df_d(data, "dateoflastownercontact", l)),
             ("ReasonForRemoval", utils.df_t(data, "reasonforremoval")),
             ("Comments", utils.df_t(data, "comments")))))
    additional.save_values_for_link(dbo, data, wlid, "waitinglist")
    postaudit = db.query(
        dbo, "SELECT * FROM animalwaitinglist WHERE ID = %d" % wlid)
    audit.edit(dbo, username, "animalwaitinglist",
               audit.map_diff(preaudit, postaudit))
Esempio n. 33
0
def csave(dbo, username, data):
    """
    Takes configuration data passed as a web post and saves it to the
    database.
    """
    l = dbo.locale

    def valid_code(s):
        """
        Returns True if s has a valid code portion in it
        """
        VALID_CODES = ("NN", "NNN", "UUUU", "UUUUUUUUUU")
        for v in VALID_CODES:
            if s.find(v) != -1:
                return True
        return False

    for k in data.iterkeys():
        v = utils.df_ks(data, k)
        if k == "mode":
            pass
        elif k == "CodingFormat":
            # If there's no valid N or U tokens in there, it's not valid so reset to
            # the default.
            if not valid_code(v):
                cset(dbo, k, "TYYYYNNN")
            else:
                cset(dbo, k, v)
        elif k == "ShortCodingFormat":
            # If there's no N or U in there, it's not valid so reset to
            # the default.
            if not valid_code(v):
                cset(dbo, k, "NNT")
            else:
                cset(dbo, k, v)
        elif k == "DefaultDailyBoardingCost":
            # Need to handle currency fields differently
            cset(dbo, k, utils.df_m(data, k, l))
        elif k.startswith("rc:"):
            # It's a NOT check
            if v == "checked": v = "No"
            if v == "off": v = "Yes"
            cset(dbo, k[3:], v)
        elif v == "checked" or v == "off":
            # It's a checkbox
            if v == "checked": v = "Yes"
            if v == "off": v = "No"
            cset(dbo, k, v)
        else:
            # Must be a string
            cset(dbo, k, v)
    audit.edit(dbo, username, "configuration", str(data))
Esempio n. 34
0
def insert_movement_from_form(dbo, username, data):
    """
    Creates a movement record from posted form data 
    """
    movementid = db.get_id(dbo, "adoption")
    adoptionno = utils.df_ks(data, "adoptionno")
    animalid = utils.df_ki(data, "animal")
    if adoptionno == "":
        # No adoption number was supplied, generate a
        # unique number from the movementid
        idx = movementid
        while True:
            adoptionno = utils.padleft(idx, 6)
            data["adoptionno"] = adoptionno
            if 0 == db.query_int(
                    dbo,
                    "SELECT COUNT(*) FROM adoption WHERE AdoptionNumber LIKE '%s'"
                    % adoptionno):
                break
            else:
                idx += 1

    validate_movement_form_data(dbo, data)
    l = dbo.locale
    sql = db.make_insert_user_sql(
        dbo, "adoption", username,
        (("ID", db.di(movementid)), ("AdoptionNumber", db.ds(adoptionno)),
         ("OwnerID", db.di(utils.df_ki(data, "person"))),
         ("RetailerID", db.di(utils.df_ki(data, "retailer"))),
         ("AnimalID", db.di(utils.df_ki(data, "animal"))),
         ("OriginalRetailerMovementID",
          db.di(utils.df_ki(data, "originalretailermovement"))),
         ("MovementDate", utils.df_d(data, "movementdate", l)),
         ("MovementType", utils.df_s(data, "type")),
         ("ReturnDate", utils.df_d(data, "returndate", l)),
         ("ReturnedReasonID", utils.df_s(data, "returncategory")),
         ("Donation", utils.df_m(data, "donation", l)),
         ("InsuranceNumber", utils.df_t(data, "insurance")),
         ("ReasonForReturn", utils.df_t(data, "reason")),
         ("ReservationDate", utils.df_d(data, "reservationdate", l)),
         ("ReservationCancelledDate",
          utils.df_d(data, "reservationcancelled",
                     l)), ("IsTrial", utils.df_c(data, "trial")),
         ("IsPermanentFoster", utils.df_c(data, "permanentfoster")),
         ("TrialEndDate", utils.df_d(data, "trialenddate", l)),
         ("Comments", utils.df_t(data, "comments"))))
    db.execute(dbo, sql)
    audit.create(dbo, username, "adoption", str(movementid))
    animal.update_animal_status(dbo, animalid)
    animal.update_variable_animal_data(dbo, animalid)
    update_movement_donation(dbo, movementid)
    return movementid
Esempio n. 35
0
def insert_diary_from_form(dbo, username, linktypeid, linkid, data):
    """
    Creates a diary note from the form data
    username: User creating the diary
    linktypeid, linkid: The link
    data: The web.py form object
    """
    l = dbo.locale
    if utils.df_ks(data, "diarydate") == "":
        raise utils.ASMValidationError(i18n._("Diary date cannot be blank", l))
    if utils.df_kd(data, "diarydate", l) is None:
        raise utils.ASMValidationError(i18n._("Diary date is not valid", l))
    if utils.df_ks(data, "subject") == "":
        raise utils.ASMValidationError(i18n._("Diary subject cannot be blank", l))
    if utils.df_ks(data, "note") == "":
        raise utils.ASMValidationError(i18n._("Diary note cannot be blank", l))
    diarytime =  utils.df_ks(data, "diarytime").strip()
    if diarytime != "":
        if diarytime.find(":") == -1:
            raise utils.ASMValidationError(i18n._("Invalid time, times should be in HH:MM format", l))
        if not utils.is_numeric(diarytime.replace(":", "")):
            raise utils.ASMValidationError(i18n._("Invalid time, times should be in HH:MM format", l))

    linkinfo = get_link_info(dbo, linktypeid, linkid)
    diaryid = db.get_id(dbo, "diary")
    sql = db.make_insert_user_sql(dbo, "diary", username, (
        ( "ID", db.di(diaryid)),
        ( "LinkID", db.di(linkid) ),
        ( "LinkType", db.di(linktypeid) ),
        ( "LinkInfo", db.ds(linkinfo) ),
        ( "DiaryDateTime", utils.df_dt(data, "diarydate", "diarytime", l) ),
        ( "DiaryForName", utils.df_t(data, "diaryfor") ),
        ( "Subject", utils.df_t(data, "subject") ),
        ( "Note", utils.df_t(data, "note") ),
        ( "DateCompleted", utils.df_d(data, "completed", l) )
        ))
    db.execute(dbo, sql)
    audit.create(dbo, username, "diary", str(diaryid))
    return diaryid
Esempio n. 36
0
def update_profile_from_form(dbo, username, data):
    """
    Updates a profile record from posted form data
    """
    l = dbo.locale
    profileid = utils.df_ki(data, "profileid")
    if utils.df_ks(data, "treatmentname") == "":
        raise utils.ASMValidationError(_("Treatment name cannot be blank", l))
    if utils.df_ks(data, "profilename") == "":
        raise utils.ASMValidationError(_("Profile name cannot be blank", l))

    timingrule = utils.df_ki(data, "timingrule")
    timingrulenofrequencies = utils.df_ki(data, "timingrulenofrequencies")
    timingrulefrequency = utils.df_ki(data, "timingrulefrequency")
    totalnumberoftreatments = utils.df_ki(data, "totalnumberoftreatments")
    treatmentrule = utils.df_ki(data, "treatmentrule")
    singlemulti = utils.df_ki(data, "singlemulti")
    if singlemulti == 0:
        timingrule = 0
        timingrulenofrequencies = 0
        timingrulefrequency = 0
    if treatmentrule != 0:
        totalnumberoftreatments = 0
    sql = db.make_update_user_sql(dbo, "medicalprofile", username, "ID=%d" % profileid, ( 
        ( "ProfileName", utils.df_t(data, "profilename")),
        ( "TreatmentName", utils.df_t(data, "treatmentname")),
        ( "Dosage", utils.df_t(data, "dosage")),
        ( "Cost", utils.df_m(data, "cost", l)),
        ( "TimingRule", db.di(timingrule)),
        ( "TimingRuleFrequency", db.di(timingrulefrequency)),
        ( "TimingRuleNoFrequencies", db.di(timingrulenofrequencies)),
        ( "TreatmentRule", utils.df_s(data, "treatmentrule")),
        ( "TotalNumberOfTreatments", db.di(totalnumberoftreatments)),
        ( "Comments", utils.df_t(data, "comments"))
        ))
    preaudit = db.query(dbo, "SELECT * FROM medicalprofile WHERE ID=%d" % profileid)
    db.execute(dbo, sql)
    postaudit = db.query(dbo, "SELECT * FROM medicalprofile WHERE ID=%d" % profileid)
    audit.edit(dbo, username, "medicalprofile", audit.map_diff(preaudit, postaudit, [ "TREATMENTNAME", "DOSAGE" ]))
Esempio n. 37
0
def csave(dbo, username, data):
    """
    Takes configuration data passed as a web post and saves it to the
    database.
    """
    l = dbo.locale
    def valid_code(s):
        """
        Returns True if s has a valid code portion in it
        """
        VALID_CODES = ("NN", "NNN", "UUUU", "UUUUUUUUUU")
        for v in VALID_CODES:
            if s.find(v) != -1:
                return True
        return False

    for k in data.iterkeys():
        v = utils.df_ks(data, k)
        if k == "mode":
            pass
        elif k == "CodingFormat":
            # If there's no valid N or U tokens in there, it's not valid so reset to
            # the default.
            if not valid_code(v):
                cset(dbo, k, "TYYYYNNN")
            else:
                cset(dbo, k, v)
        elif k == "ShortCodingFormat":
            # If there's no N or U in there, it's not valid so reset to
            # the default.
            if not valid_code(v):
                cset(dbo, k, "NNT")
            else:
                cset(dbo, k, v)
        elif k == "DefaultDailyBoardingCost":
            # Need to handle currency fields differently
            cset(dbo, k, utils.df_m(data, k, l))
        elif k.startswith("rc:"):
            # It's a NOT check
            if v == "checked": v = "No"
            if v == "off": v = "Yes"
            cset(dbo, k[3:], v)
        elif v == "checked" or v == "off":
            # It's a checkbox
            if v == "checked": v = "Yes"
            if v == "off": v = "No"
            cset(dbo, k, v)
        else:
            # Must be a string
            cset(dbo, k, v)
    audit.edit(dbo, username, "configuration", str(data))
Esempio n. 38
0
def insert_profile_from_form(dbo, username, data):
    """
    Creates a profile record from posted form data
    """
    l = dbo.locale
    if utils.df_ks(data, "treatmentname") == "":
        raise utils.ASMValidationError(_("Treatment name cannot be blank", l))
    if utils.df_ks(data, "profilename") == "":
        raise utils.ASMValidationError(_("Profile name cannot be blank", l))

    nprofid = db.get_id(dbo, "medicalprofile")
    timingrule = utils.df_ki(data, "timingrule")
    timingrulenofrequencies = utils.df_ki(data, "timingrulenofrequencies")
    timingrulefrequency = utils.df_ki(data, "timingrulefrequency")
    totalnumberoftreatments = utils.df_ki(data, "totalnumberoftreatments")
    treatmentrule = utils.df_ki(data, "treatmentrule")
    singlemulti = utils.df_ki(data, "singlemulti")
    if singlemulti == 0:
        timingrule = 0
        timingrulenofrequencies = 0
        timingrulefrequency = 0
    if treatmentrule != 0:
        totalnumberoftreatments = 0
    sql = db.make_insert_user_sql(dbo, "medicalprofile", username, ( 
        ( "ID", db.di(nprofid)),
        ( "ProfileName", utils.df_t(data, "profilename")),
        ( "TreatmentName", utils.df_t(data, "treatmentname")),
        ( "Dosage", utils.df_t(data, "dosage")),
        ( "Cost", utils.df_m(data, "cost", l)),
        ( "TimingRule", db.di(timingrule)),
        ( "TimingRuleFrequency", db.di(timingrulefrequency)),
        ( "TimingRuleNoFrequencies", db.di(timingrulenofrequencies)),
        ( "TreatmentRule", utils.df_s(data, "treatmentrule")),
        ( "TotalNumberOfTreatments", db.di(totalnumberoftreatments)),
        ( "Comments", utils.df_t(data, "comments"))
        ))
    db.execute(dbo, sql)
    audit.create(dbo, username, "medicalprofile", str(nprofid) + ": " + utils.df_ks(data, "treatmentname") + " " + utils.df_ks(data, "dosage"))
Esempio n. 39
0
def update_diary_from_form(dbo, username, data):
    """
    Updates a diary note from form data
    """
    l = dbo.locale
    diaryid = utils.df_ki(data, "diaryid")
    if utils.df_ks(data, "diarydate") == "":
        raise utils.ASMValidationError(i18n._("Diary date cannot be blank", l))
    if utils.df_kd(data, "diarydate", l) is None:
        raise utils.ASMValidationError(i18n._("Diary date is not valid", l))
    if utils.df_ks(data, "subject") == "":
        raise utils.ASMValidationError(
            i18n._("Diary subject cannot be blank", l))
    if utils.df_ks(data, "note") == "":
        raise utils.ASMValidationError(i18n._("Diary note cannot be blank", l))
    diarytime = utils.df_ks(data, "diarytime").strip()
    if diarytime != "":
        if diarytime.find(":") == -1:
            raise utils.ASMValidationError(
                i18n._("Invalid time, times should be in HH:MM format", l))
        if not utils.is_numeric(diarytime.replace(":", "")):
            raise utils.ASMValidationError(
                i18n._("Invalid time, times should be in HH:MM format", l))

    sql = db.make_update_user_sql(
        dbo, "diary", username, "ID=%d" % diaryid,
        (("DiaryDateTime", utils.df_dt(data, "diarydate", "diarytime", l)),
         ("DiaryForName", utils.df_t(data, "diaryfor")),
         ("Subject", utils.df_t(data, "subject")),
         ("Note", utils.df_t(data, "note")),
         ("Comments", utils.df_t(data, "comments")),
         ("DateCompleted", utils.df_d(data, "completed", l))))
    preaudit = db.query(dbo, "SELECT * FROM diary WHERE ID=%d" % diaryid)
    db.execute(dbo, sql)
    postaudit = db.query(dbo, "SELECT * FROM diary WHERE ID=%d" % diaryid)
    audit.edit(dbo, username, "diary", audit.map_diff(preaudit, postaudit))
Esempio n. 40
0
def insert_movement_from_form(dbo, username, data):
    """
    Creates a movement record from posted form data 
    """
    movementid = db.get_id(dbo, "adoption")
    adoptionno = utils.df_ks(data, "adoptionno")
    animalid = utils.df_ki(data, "animal")
    if adoptionno == "": 
        # No adoption number was supplied, generate a
        # unique number from the movementid
        idx = movementid
        while True:
            adoptionno = utils.padleft(idx, 6)
            data["adoptionno"] = adoptionno
            if 0 == db.query_int(dbo, "SELECT COUNT(*) FROM adoption WHERE AdoptionNumber LIKE '%s'" % adoptionno):
                break
            else:
                idx += 1

    validate_movement_form_data(dbo, data)
    l = dbo.locale
    sql = db.make_insert_user_sql(dbo, "adoption", username, ( 
        ( "ID", db.di(movementid)),
        ( "AdoptionNumber", db.ds(adoptionno)),
        ( "OwnerID", db.di(utils.df_ki(data, "person"))),
        ( "RetailerID", db.di(utils.df_ki(data, "retailer"))),
        ( "AnimalID", db.di(utils.df_ki(data, "animal"))),
        ( "OriginalRetailerMovementID", db.di(utils.df_ki(data, "originalretailermovement"))),
        ( "MovementDate", utils.df_d(data, "movementdate", l)),
        ( "MovementType", utils.df_s(data, "type")),
        ( "ReturnDate", utils.df_d(data, "returndate", l)),
        ( "ReturnedReasonID", utils.df_s(data, "returncategory")),
        ( "Donation", utils.df_m(data, "donation", l)),
        ( "InsuranceNumber", utils.df_t(data, "insurance")),
        ( "ReasonForReturn", utils.df_t(data, "reason")),
        ( "ReservationDate", utils.df_d(data, "reservationdate", l)),
        ( "ReservationCancelledDate", utils.df_d(data, "reservationcancelled", l)),
        ( "IsTrial", utils.df_c(data, "trial")),
        ( "IsPermanentFoster", utils.df_c(data, "permanentfoster")),
        ( "TrialEndDate", utils.df_d(data, "trialenddate", l)),
        ( "Comments", utils.df_t(data, "comments"))
        ))
    db.execute(dbo, sql)
    audit.create(dbo, username, "adoption", str(movementid))
    animal.update_animal_status(dbo, animalid)
    animal.update_variable_animal_data(dbo, animalid)
    update_movement_donation(dbo, movementid)
    return movementid
Esempio n. 41
0
def update_regimen_from_form(dbo, username, data):
    """
    Updates a regimen record from posted form data
    """
    l = dbo.locale
    regimenid = utils.df_ki(data, "regimenid")
    if utils.df_ks(data, "treatmentname") == "":
        raise utils.ASMValidationError(_("Treatment name cannot be blank", l))

    sql = db.make_update_user_sql(dbo, "animalmedical", username, "ID=%d" % regimenid, ( 
        ( "TreatmentName", utils.df_t(data, "treatmentname")),
        ( "Dosage", utils.df_t(data, "dosage")),
        ( "Status", utils.df_s(data, "status")),
        ( "Cost", utils.df_m(data, "cost", l)),
        ( "Comments", utils.df_t(data, "comments"))
        ))
    preaudit = db.query(dbo, "SELECT * FROM animalmedical WHERE ID=%d" % regimenid)
    db.execute(dbo, sql)
    postaudit = db.query(dbo, "SELECT * FROM animalmedical WHERE ID=%d" % regimenid)
    audit.edit(dbo, username, "animalmedical", audit.map_diff(preaudit, postaudit, [ "TREATMENTNAME", "DOSAGE" ]))
    update_medical_treatments(dbo, username, utils.df_ki(data, "regimenid"))
Esempio n. 42
0
def save_values_for_link(dbo, data, linkid, linktype="animal"):
    """
    Saves incoming additional field values from a form, clearing any
    existing values first.
    """
    delete_values_for_link(dbo, linkid, linktype)
    af = get_field_definitions(dbo, linktype)
    l = dbo.locale
    for f in af:
        key = "a." + str(f["MANDATORY"]) + "." + str(f["ID"])
        if data.has_key(key):
            val = utils.df_ks(data, key)
            if f["FIELDTYPE"] == YESNO:
                val = str(utils.df_kc(data, key))
            elif f["FIELDTYPE"] == MONEY:
                val = str(utils.df_km(data, key, l))
            elif f["FIELDTYPE"] == DATE:
                if len(val.strip()) > 0 and utils.df_kd(data, key, l) == None:
                    raise utils.ASMValidationError(
                        _("Additional date field '{0}' contains an invalid date.", l).format(f["FIELDNAME"])
                    )
                val = python2display(dbo.locale, utils.df_kd(data, key, l))
            sql = db.make_insert_sql(
                "additional",
                (
                    ("LinkType", db.di(f["LINKTYPE"])),
                    ("LinkID", db.di(int(linkid))),
                    ("AdditionalFieldID", db.di(f["ID"])),
                    ("Value", db.ds(val)),
                ),
            )
            try:
                db.execute(dbo, sql)
            except Exception, err:
                al.error(
                    "Failed saving additional field: %s" % str(err),
                    "animal.update_animal_from_form",
                    dbo,
                    sys.exc_info(),
                )
Esempio n. 43
0
 def d(key, default = None): 
     if data.has_key(key):
         return utils.df_ks(data, key)
     else:
         return default
Esempio n. 44
0
def attach_file_from_form(dbo, username, linktype, linkid, data):
    """
    Attaches a media file from the posted form
    data is the web.py data object and should contain
    comments, the filechooser object, with filename and value 
    props - OR a parameter called base64image containing a base64
    encoded jpg image.
    """
    ext = ""
    base64data = ""
    base64image = utils.df_ks(data, "base64image")
    if base64image != "":
        ext = ".jpg"
        # If an HTML5 data url was used, strip the prefix so we just have base64 data
        if base64image.find("data:") != -1:
            base64data = base64image[base64image.find(",")+1:]
            # Browser escaping turns base64 pluses back into spaces, so switch back
            base64data = base64data.replace(" ", "+")
        else:
            base64data = base64image
    else:
        ext = data.filechooser.filename
        ext = ext[ext.rfind("."):].lower()
    mediaid = db.get_id(dbo, "media")
    medianame = "%d%s" % ( mediaid, ext )
    ispicture = ext == ".jpg" or ext == ".jpeg"
    ispdf = ext == ".pdf"

    # Does this link have anything with web/doc set? If not, set the
    # web/doc flags
    web = 0
    doc = 0
    existing_web = db.query_int(dbo, "SELECT COUNT(*) FROM media WHERE WebsitePhoto = 1 " \
        "AND LinkID = %d AND LinkTypeID = %d" % ( int(linkid), int(linktype) ))
    existing_doc = db.query_int(dbo, "SELECT COUNT(*) FROM media WHERE DocPhoto = 1 " \
        "AND LinkID = %d AND LinkTypeID = %d" % ( int(linkid), int(linktype) ))
    if existing_web == 0 and ispicture:
        web = 1
    if existing_doc == 0 and ispicture:
        doc = 1

    if base64image != "":
        filedata = base64.b64decode(base64data)
    else:
        filedata = data.filechooser.value

    # Is it a picture?
    if ispicture:
        # Autorotate it to match the EXIF orientation
        filedata = auto_rotate_image(filedata)
        # Scale it down to the system set size
        scalespec = configuration.incoming_media_scaling(dbo)
        if scalespec != "None":
            filedata = scale_image(filedata, scalespec)

    # Is it a PDF? If so, compress it if we can and the option is on
    if ispdf and gs_installed() and SCALE_PDF:
        filedata = scale_pdf(filedata)
        medianame = "%d_scaled.pdf" % mediaid

    # Attach the file in the dbfs
    path = get_dbfs_path(linkid, linktype)
    dbfs.put_string(dbo, medianame, path, filedata)

    # Are the notes for an image blank and we're defaulting them from animal comments?
    comments = utils.df_ks(data, "comments")
    if comments == "" and ispicture and linktype == ANIMAL and configuration.auto_media_notes(dbo):
        comments = animal.get_comments(dbo, int(linkid))
        # Are the notes blank and we're defaulting them from the filename?
    elif comments == "" and configuration.default_media_notes_from_file(dbo) and base64image == "":
        comments = utils.filename_only(data.filechooser.filename)
    
    # Create the media record
    sql = db.make_insert_sql("media", (
        ( "ID", db.di(mediaid) ),
        ( "MediaName", db.ds(medianame) ),
        ( "MediaType", db.di(0) ),
        ( "MediaNotes", db.ds(comments) ),
        ( "WebsitePhoto", db.di(web) ),
        ( "WebsiteVideo", db.di(0) ),
        ( "DocPhoto", db.di(doc) ),
        ( "ExcludeFromPublish", db.di(0) ),
        ( "NewSinceLastPublish", db.di(1) ),
        ( "UpdatedSinceLastPublish", db.di(0) ),
        ( "LinkID", db.di(linkid) ),
        ( "LinkTypeID", db.di(linktype) ),
        ( "Date", db.nowsql() )
        ))
    db.execute(dbo, sql)
    audit.create(dbo, username, "media", str(mediaid) + ": for " + str(linkid) + "/" + str(linktype))
Esempio n. 45
0
def insert_person_from_form(dbo, data, username):
    """
    Creates a new person record from incoming form data
    data: The webpy data object containing form parameters
    Returns the ID of the new record
    """
    def d(key, default = None): 
        if data.has_key(key):
            return utils.df_ks(data, key)
        else:
            return default

    flags = utils.df_ks(data, "flags").split(",")
    def bi(b): return b and 1 or 0
    homechecked = bi("homechecked" in flags)
    banned = bi("banned" in flags)
    volunteer = bi("volunteer" in flags)
    member = bi("member" in flags)
    homechecker = bi("homechecker" in flags)
    donor = bi("donor" in flags)
    shelter = bi("shelter" in flags)
    aco = bi("aco" in flags)
    staff = bi("staff" in flags)
    fosterer = bi("fosterer" in flags)
    retailer = bi("retailer" in flags)
    vet = bi("vet" in flags)
    giftaid = bi("giftaid" in flags)
    flagstr = "|".join(flags) + "|"

    pid = db.get_id(dbo, "owner")
    sql = db.make_insert_user_sql(dbo, "owner", username, (
        ( "ID", db.di(pid) ),
        ( "OwnerName", db.ds("%s %s %s" % ( d("title", ""), d("forenames", ""), d("surname", "") ))),
        ( "OwnerTitle", db.ds(d("title", "") )),
        ( "OwnerInitials", db.ds(d("initials", "") )),
        ( "OwnerForenames", db.ds(d("forenames", "") )),
        ( "OwnerSurname", db.ds(d("surname", "") )),
        ( "OwnerAddress", db.ds(d("address", "") )),
        ( "OwnerTown", db.ds(d("town", "") )),
        ( "OwnerCounty", db.ds(d("county", "") )),
        ( "OwnerPostcode", db.ds(d("postcode", "") )),
        ( "LatLong", db.ds(d("latlong", "") )),
        ( "HomeTelephone", db.ds(d("hometelephone", "") )),
        ( "WorkTelephone", db.ds(d("worktelephone", "") )),
        ( "MobileTelephone", db.ds(d("mobiletelephone", "") )),
        ( "EmailAddress", db.ds(d("emailaddress", "") )),
        ( "IDCheck", db.di(homechecked) ),
        ( "Comments", db.ds(d("comments") )),
        ( "IsBanned", db.di(banned)),
        ( "IsVolunteer", db.di(volunteer)),
        ( "IsMember", db.di(member)),
        ( "MembershipExpiryDate", db.dd(d("membershipexpirydate") )),
        ( "MembershipNumber", db.ds(d("membershipnumber"))),
        ( "IsHomeChecker", db.di(homechecker)),
        ( "IsDonor", db.di(donor)),
        ( "IsShelter", db.di(shelter)),
        ( "IsACO", db.di(aco)),
        ( "IsStaff", db.di(staff)),
        ( "IsFosterer", db.di(fosterer)),
        ( "IsRetailer", db.di(retailer)),
        ( "IsVet", db.di(vet)),
        ( "IsGiftAid", db.di(giftaid)),
        ( "AdditionalFlags", db.ds(flagstr)),
        ( "HomeCheckAreas", db.ds(d("homecheckareas", "") )),
        ( "DateLastHomeChecked", db.dd(d("datelasthomechecked") )),
        ( "HomeCheckedBy", db.di(d("homecheckedby", 0) )),
        ( "MatchAdded", db.dd(d("matchadded") )),
        ( "MatchExpires", db.dd(d("matchexpires") )),
        ( "MatchActive", db.di(d("matchactive", 0) )),
        ( "MatchSex", db.di(d("matchsex", -1) )),
        ( "MatchSize", db.di(d("matchsize", -1) )),
        ( "MatchColour", db.di(d("matchcolour", -1) )),
        ( "MatchAgeFrom", db.di(d("matchagefrom", 0) )),
        ( "MatchAgeTo", db.di(d("matchageto", 0) )),
        ( "MatchAnimalType", db.di(d("matchanimaltype", -1) )),
        ( "MatchSpecies", db.di(d("matchspecies", -1) )),
        ( "MatchBreed", db.di(d("matchbreed", -1) )),
        ( "MatchBreed2", db.di(d("matchbreed2", -1) )),
        ( "MatchGoodWithCats", db.di(d("matchgoodwithcats", -1) )),
        ( "MatchGoodWithDogs", db.di(d("matchgoodwithdogs", -1) )),
        ( "MatchGoodWithChildren", db.di(d("matchgoodwithchildren", -1) )),
        ( "MatchHouseTrained", db.di(d("matchhousetrained", -1) )),
        ( "MatchCommentsContain", db.ds(d("matchcommentscontain") )
    )))
    db.execute(dbo, sql)
    audit.create(dbo, username, "owner", str(pid) + " %s %s %s" % (d("title"), d("forenames"), d("surname")))
    return pid
Esempio n. 46
0
 def d(key, default=None):
     if data.has_key(key):
         return utils.df_ks(data, key)
     else:
         return default
Esempio n. 47
0
def insert_person_from_form(dbo, data, username):
    """
    Creates a new person record from incoming form data
    data: The webpy data object containing form parameters
    Returns the ID of the new record
    """
    def d(key, default=None):
        if data.has_key(key):
            return utils.df_ks(data, key)
        else:
            return default

    flags = utils.df_ks(data, "flags").split(",")

    def bi(b):
        return b and 1 or 0

    homechecked = bi("homechecked" in flags)
    banned = bi("banned" in flags)
    volunteer = bi("volunteer" in flags)
    member = bi("member" in flags)
    homechecker = bi("homechecker" in flags)
    donor = bi("donor" in flags)
    shelter = bi("shelter" in flags)
    aco = bi("aco" in flags)
    staff = bi("staff" in flags)
    fosterer = bi("fosterer" in flags)
    retailer = bi("retailer" in flags)
    vet = bi("vet" in flags)
    giftaid = bi("giftaid" in flags)
    flagstr = "|".join(flags) + "|"

    pid = db.get_id(dbo, "owner")
    sql = db.make_insert_user_sql(
        dbo, "owner", username,
        (("ID", db.di(pid)),
         ("OwnerName",
          db.ds("%s %s %s" %
                (d("title", ""), d("forenames", ""), d("surname", "")))),
         ("OwnerTitle", db.ds(d("title", ""))),
         ("OwnerInitials", db.ds(d("initials", ""))),
         ("OwnerForenames", db.ds(d("forenames", ""))),
         ("OwnerSurname", db.ds(d("surname", ""))),
         ("OwnerAddress", db.ds(d("address", ""))),
         ("OwnerTown", db.ds(d("town", ""))),
         ("OwnerCounty", db.ds(d("county", ""))),
         ("OwnerPostcode", db.ds(d("postcode", ""))),
         ("LatLong", db.ds(d("latlong", ""))),
         ("HomeTelephone", db.ds(d("hometelephone", ""))),
         ("WorkTelephone", db.ds(d("worktelephone", ""))),
         ("MobileTelephone", db.ds(d("mobiletelephone", ""))),
         ("EmailAddress", db.ds(d("emailaddress", ""))),
         ("IDCheck", db.di(homechecked)), ("Comments", db.ds(
             d("comments"))), ("IsBanned", db.di(banned)),
         ("IsVolunteer", db.di(volunteer)), ("IsMember", db.di(member)),
         ("MembershipExpiryDate", db.dd(d("membershipexpirydate"))),
         ("MembershipNumber", db.ds(d("membershipnumber"))),
         ("IsHomeChecker", db.di(homechecker)), ("IsDonor", db.di(donor)),
         ("IsShelter", db.di(shelter)), ("IsACO", db.di(aco)),
         ("IsStaff", db.di(staff)), ("IsFosterer", db.di(fosterer)),
         ("IsRetailer", db.di(retailer)), ("IsVet", db.di(vet)),
         ("IsGiftAid", db.di(giftaid)), ("AdditionalFlags", db.ds(flagstr)),
         ("HomeCheckAreas", db.ds(d("homecheckareas", ""))),
         ("DateLastHomeChecked", db.dd(d("datelasthomechecked"))),
         ("HomeCheckedBy", db.di(d(
             "homecheckedby", 0))), ("MatchAdded", db.dd(
                 d("matchadded"))), ("MatchExpires", db.dd(d("matchexpires"))),
         ("MatchActive", db.di(d(
             "matchactive", 0))), ("MatchSex", db.di(d(
                 "matchsex", -1))), ("MatchSize", db.di(d("matchsize", -1))),
         ("MatchColour", db.di(d(
             "matchcolour", -1))), ("MatchAgeFrom", db.di(d(
                 "matchagefrom", 0))), ("MatchAgeTo", db.di(d(
                     "matchageto", 0))), ("MatchAnimalType",
                                          db.di(d("matchanimaltype", -1))),
         ("MatchSpecies", db.di(d(
             "matchspecies", -1))), ("MatchBreed", db.di(d("matchbreed", -1))),
         ("MatchBreed2", db.di(d("matchbreed2", -1))),
         ("MatchGoodWithCats", db.di(
             d("matchgoodwithcats",
               -1))), ("MatchGoodWithDogs", db.di(d("matchgoodwithdogs", -1))),
         ("MatchGoodWithChildren", db.di(
             d("matchgoodwithchildren",
               -1))), ("MatchHouseTrained", db.di(d("matchhousetrained", -1))),
         ("MatchCommentsContain", db.ds(d("matchcommentscontain")))))
    db.execute(dbo, sql)
    audit.create(
        dbo, username, "owner",
        str(pid) + " %s %s %s" % (d("title"), d("forenames"), d("surname")))
    return pid
Esempio n. 48
0
def update_person_from_form(dbo, data, username):
    """
    Updates an existing person record from incoming form data
    data: The webpy data object containing form parameters
    """
    l = dbo.locale
    pid = utils.df_ki(data, "id")
    flags = utils.df_ks(data, "flags").split(",")

    def bi(b):
        return b and 1 or 0

    homechecked = bi("homechecked" in flags)
    banned = bi("banned" in flags)
    volunteer = bi("volunteer" in flags)
    member = bi("member" in flags)
    homechecker = bi("homechecker" in flags)
    donor = bi("donor" in flags)
    shelter = bi("shelter" in flags)
    aco = bi("aco" in flags)
    staff = bi("staff" in flags)
    fosterer = bi("fosterer" in flags)
    retailer = bi("retailer" in flags)
    vet = bi("vet" in flags)
    giftaid = bi("giftaid" in flags)
    flagstr = "|".join(flags) + "|"
    sql = db.make_update_user_sql(
        dbo, "owner", username, "ID=%d" % pid,
        (("OwnerName",
          db.ds("%s %s %s" %
                (utils.df_ks(data, "title"), utils.df_ks(
                    data, "forenames"), utils.df_ks(data, "surname")))),
         ("OwnerTitle", utils.df_t(data, "title")),
         ("OwnerInitials", utils.df_t(data, "initials")),
         ("OwnerForenames", utils.df_t(data, "forenames")),
         ("OwnerSurname", utils.df_t(data, "surname")),
         ("OwnerAddress", utils.df_t(data, "address")),
         ("OwnerTown", utils.df_t(data, "town")),
         ("OwnerCounty", utils.df_t(data, "county")),
         ("OwnerPostcode", utils.df_t(data, "postcode")),
         ("LatLong", utils.df_t(data, "latlong")),
         ("HomeTelephone", utils.df_t(data, "hometelephone")),
         ("WorkTelephone", utils.df_t(data, "worktelephone")),
         ("MobileTelephone", utils.df_t(data, "mobiletelephone")),
         ("EmailAddress", utils.df_t(
             data, "email")), ("IDCheck", db.di(homechecked)),
         ("Comments", utils.df_t(data,
                                 "comments")), ("IsBanned", db.di(banned)),
         ("IsVolunteer", db.di(volunteer)), ("IsMember", db.di(member)),
         ("MembershipExpiryDate", utils.df_d(data, "membershipexpires", l)),
         ("MembershipNumber", utils.df_t(data, "membershipnumber")),
         ("IsHomeChecker", db.di(homechecker)), ("IsDonor", db.di(donor)),
         ("IsShelter", db.di(shelter)), ("IsACO", db.di(aco)),
         ("IsStaff", db.di(staff)), ("IsFosterer", db.di(fosterer)),
         ("IsRetailer", db.di(retailer)), ("IsVet", db.di(vet)),
         ("IsGiftAid", db.di(giftaid)), ("AdditionalFlags", db.ds(flagstr)),
         ("HomeCheckAreas", utils.df_t(data, "areas")),
         ("DateLastHomeChecked", utils.df_d(data, "homechecked", l)),
         ("HomeCheckedBy", utils.df_s(data, "homecheckedby")),
         ("MatchActive", utils.df_s(data, "matchactive")),
         ("MatchAdded", utils.df_d(data, "matchadded", l)),
         ("MatchExpires", utils.df_d(data, "matchexpires", l)),
         ("MatchSex", utils.df_s(
             data, "matchsex")), ("MatchSize", utils.df_s(data, "matchsize")),
         ("MatchColour", utils.df_s(data, "matchcolour")),
         ("MatchAgeFrom", utils.df_s(data, "agedfrom")),
         ("MatchAgeTo", utils.df_s(
             data, "agedto")), ("MatchAnimalType", utils.df_s(
                 data, "matchtype")), ("MatchSpecies",
                                       utils.df_s(data, "matchspecies")),
         ("MatchBreed", utils.df_s(
             data,
             "matchbreed1")), ("MatchBreed2", utils.df_s(data, "matchbreed2")),
         ("MatchGoodWithCats", utils.df_s(data, "matchgoodwithcats")),
         ("MatchGoodWithDogs", utils.df_s(data, "matchgoodwithdogs")),
         ("MatchGoodWithChildren", utils.df_s(data, "matchgoodwithchildren")),
         ("MatchHouseTrained", utils.df_s(data, "matchhousetrained")),
         ("MatchCommentsContain", utils.df_t(data, "commentscontain"))))
    preaudit = db.query(dbo, "SELECT * FROM owner WHERE ID=%d" % pid)
    db.execute(dbo, sql)
    postaudit = db.query(dbo, "SELECT * FROM owner WHERE ID=%d" % pid)
    audit.edit(dbo, username, "owner",
               audit.map_diff(preaudit, postaudit, [
                   "OWNERNAME",
               ]))

    # Save any additional field values given
    additional.save_values_for_link(dbo, data, pid, "person")
Esempio n. 49
0
def update_person_from_form(dbo, data, username):
    """
    Updates an existing person record from incoming form data
    data: The webpy data object containing form parameters
    """
    l = dbo.locale
    pid = utils.df_ki(data, "id")
    flags = utils.df_ks(data, "flags").split(",")
    def bi(b): return b and 1 or 0
    homechecked = bi("homechecked" in flags)
    banned = bi("banned" in flags)
    volunteer = bi("volunteer" in flags)
    member = bi("member" in flags)
    homechecker = bi("homechecker" in flags)
    donor = bi("donor" in flags)
    shelter = bi("shelter" in flags)
    aco = bi("aco" in flags)
    staff = bi("staff" in flags)
    fosterer = bi("fosterer" in flags)
    retailer = bi("retailer" in flags)
    vet = bi("vet" in flags)
    giftaid = bi("giftaid" in flags)
    flagstr = "|".join(flags) + "|"
    sql = db.make_update_user_sql(dbo, "owner", username, "ID=%d" % pid, (
        ( "OwnerName", db.ds("%s %s %s" % ( utils.df_ks(data, "title"), utils.df_ks(data, "forenames"), utils.df_ks(data, "surname") ))),
        ( "OwnerTitle", utils.df_t(data, "title")),
        ( "OwnerInitials", utils.df_t(data, "initials")),
        ( "OwnerForenames", utils.df_t(data, "forenames")), 
        ( "OwnerSurname", utils.df_t(data, "surname")),
        ( "OwnerAddress", utils.df_t(data, "address")),
        ( "OwnerTown", utils.df_t(data, "town")),
        ( "OwnerCounty", utils.df_t(data, "county")),
        ( "OwnerPostcode", utils.df_t(data, "postcode")),
        ( "LatLong", utils.df_t(data, "latlong")),
        ( "HomeTelephone", utils.df_t(data, "hometelephone")),
        ( "WorkTelephone", utils.df_t(data, "worktelephone")),
        ( "MobileTelephone", utils.df_t(data, "mobiletelephone")),
        ( "EmailAddress", utils.df_t(data, "email")),
        ( "IDCheck", db.di(homechecked) ),
        ( "Comments", utils.df_t(data, "comments")),
        ( "IsBanned", db.di(banned)),
        ( "IsVolunteer", db.di(volunteer)),
        ( "IsMember", db.di(member)),
        ( "MembershipExpiryDate", utils.df_d(data, "membershipexpires", l)),
        ( "MembershipNumber", utils.df_t(data, "membershipnumber")),
        ( "IsHomeChecker", db.di(homechecker)),
        ( "IsDonor", db.di(donor)),
        ( "IsShelter", db.di(shelter)),
        ( "IsACO", db.di(aco)),
        ( "IsStaff", db.di(staff)),
        ( "IsFosterer", db.di(fosterer)),
        ( "IsRetailer", db.di(retailer)),
        ( "IsVet", db.di(vet)),
        ( "IsGiftAid", db.di(giftaid)),
        ( "AdditionalFlags", db.ds(flagstr)),
        ( "HomeCheckAreas", utils.df_t(data, "areas")),
        ( "DateLastHomeChecked", utils.df_d(data, "homechecked", l)),
        ( "HomeCheckedBy", utils.df_s(data, "homecheckedby")),
        ( "MatchActive", utils.df_s(data, "matchactive")),
        ( "MatchAdded", utils.df_d(data, "matchadded", l)),
        ( "MatchExpires", utils.df_d(data, "matchexpires", l)),
        ( "MatchSex", utils.df_s(data, "matchsex")),
        ( "MatchSize", utils.df_s(data, "matchsize")),
        ( "MatchColour", utils.df_s(data, "matchcolour")),
        ( "MatchAgeFrom", utils.df_s(data, "agedfrom")),
        ( "MatchAgeTo", utils.df_s(data, "agedto")),
        ( "MatchAnimalType", utils.df_s(data, "matchtype")),
        ( "MatchSpecies", utils.df_s(data, "matchspecies")),
        ( "MatchBreed", utils.df_s(data, "matchbreed1")),
        ( "MatchBreed2", utils.df_s(data, "matchbreed2")),
        ( "MatchGoodWithCats", utils.df_s(data, "matchgoodwithcats")),
        ( "MatchGoodWithDogs", utils.df_s(data, "matchgoodwithdogs")),
        ( "MatchGoodWithChildren", utils.df_s(data, "matchgoodwithchildren")),
        ( "MatchHouseTrained", utils.df_s(data, "matchhousetrained")),
        ( "MatchCommentsContain", utils.df_t(data, "commentscontain"))
    ))
    preaudit = db.query(dbo, "SELECT * FROM owner WHERE ID=%d" % pid)
    db.execute(dbo, sql)
    postaudit = db.query(dbo, "SELECT * FROM owner WHERE ID=%d" % pid)
    audit.edit(dbo, username, "owner", audit.map_diff(preaudit, postaudit, [ "OWNERNAME", ]))

    # Save any additional field values given
    additional.save_values_for_link(dbo, data, pid, "person")
Esempio n. 50
0
def insert_reserve_from_form(dbo, username, data):
    """
    Inserts a movement from the workflow reserve an animal screen.
    Returns the new movement id
    """
    # Validate that we have a date before doing anthing
    l = dbo.locale
    if None == utils.df_kd(data, "reservationdate", l):
        raise utils.ASMValidationError(
            i18n._("Reservations must have a valid reservation date.", l))

    # Do the movement itself first
    move_dict = {
        "person": utils.df_ks(data, "person"),
        "animal": utils.df_ks(data, "animal"),
        "reservationdate": utils.df_ks(data, "reservationdate"),
        "adoptionno": utils.df_ks(data, "movementnumber"),
        "movementdate": "",
        "type": str(NO_MOVEMENT),
        "donation": utils.df_ks(data, "amount"),
        "returncategory": configuration.default_return_reason(dbo)
    }
    movementid = insert_movement_from_form(dbo, username, move_dict)
    # Then the donation if we have one
    donation_amount = int(utils.df_m(data, "amount", l))
    if donation_amount > 0:
        due = ""
        received = utils.df_ks(data, "reservationdate")
        if configuration.movement_donations_default_due(dbo):
            due = utils.df_ks(data, "reservationdate")
            received = ""
        don_dict = {
            "person": utils.df_ks(data, "person"),
            "animal": utils.df_ks(data, "animal"),
            "movement": str(movementid),
            "type": utils.df_ks(data, "donationtype"),
            "payment": utils.df_ks(data, "payment"),
            "frequency": "0",
            "amount": utils.df_ks(data, "amount"),
            "due": due,
            "received": received,
            "giftaid": utils.df_ks(data, "giftaid")
        }
        financial.insert_donation_from_form(dbo, username, don_dict)
    # And a second donation if there is one
    donation_amount = int(utils.df_m(data, "amount2", l))
    if donation_amount > 0:
        due = ""
        received = utils.df_ks(data, "movementdate")
        if configuration.movement_donations_default_due(dbo):
            due = utils.df_ks(data, "movementdate")
            received = ""
        don_dict = {
            "person": utils.df_ks(data, "person"),
            "animal": utils.df_ks(data, "animal"),
            "movement": str(movementid),
            "type": utils.df_ks(data, "donationtype2"),
            "payment": utils.df_ks(data, "payment2"),
            "frequency": "0",
            "amount": utils.df_ks(data, "amount2"),
            "due": due,
            "received": received,
            "giftaid": utils.df_ks(data, "giftaid")
        }
        financial.insert_donation_from_form(dbo, username, don_dict)
    return movementid
Esempio n. 51
0
def insert_reserve_from_form(dbo, username, data):
    """
    Inserts a movement from the workflow reserve an animal screen.
    Returns the new movement id
    """
    # Validate that we have a date before doing anthing
    l = dbo.locale
    if None == utils.df_kd(data, "reservationdate", l):
        raise utils.ASMValidationError(i18n._("Reservations must have a valid reservation date.", l))

    # Do the movement itself first
    move_dict = {
        "person"                : utils.df_ks(data, "person"),
        "animal"                : utils.df_ks(data, "animal"),
        "reservationdate"       : utils.df_ks(data, "reservationdate"),
        "adoptionno"            : utils.df_ks(data, "movementnumber"),
        "movementdate"          : "",
        "type"                  : str(NO_MOVEMENT),
        "donation"              : utils.df_ks(data, "amount"),
        "returncategory"        : configuration.default_return_reason(dbo)
    }
    movementid = insert_movement_from_form(dbo, username, move_dict)
    # Then the donation if we have one
    donation_amount = int(utils.df_m(data, "amount", l))
    if donation_amount > 0:
        due = ""
        received = utils.df_ks(data, "reservationdate")
        if configuration.movement_donations_default_due(dbo):
            due = utils.df_ks(data, "reservationdate")
            received = ""
        don_dict = {
            "person"                : utils.df_ks(data, "person"),
            "animal"                : utils.df_ks(data, "animal"),
            "movement"              : str(movementid),
            "type"                  : utils.df_ks(data, "donationtype"),
            "payment"               : utils.df_ks(data, "payment"),
            "frequency"             : "0",
            "amount"                : utils.df_ks(data, "amount"),
            "due"                   : due,
            "received"              : received,
            "giftaid"               : utils.df_ks(data, "giftaid")
        }
        financial.insert_donation_from_form(dbo, username, don_dict)
    # And a second donation if there is one
    donation_amount = int(utils.df_m(data, "amount2", l))
    if donation_amount > 0:
        due = ""
        received = utils.df_ks(data, "movementdate")
        if configuration.movement_donations_default_due(dbo):
            due = utils.df_ks(data, "movementdate")
            received = ""
        don_dict = {
            "person"                : utils.df_ks(data, "person"),
            "animal"                : utils.df_ks(data, "animal"),
            "movement"              : str(movementid),
            "type"                  : utils.df_ks(data, "donationtype2"),
            "payment"               : utils.df_ks(data, "payment2"),
            "frequency"             : "0",
            "amount"                : utils.df_ks(data, "amount2"),
            "due"                   : due,
            "received"              : received,
            "giftaid"               : utils.df_ks(data, "giftaid")
        }
        financial.insert_donation_from_form(dbo, username, don_dict)
    return movementid
Esempio n. 52
0
def validate_movement_form_data(dbo, data):
    """
    Verifies that form data is valid for a movement
    """
    l = dbo.locale
    movementid = utils.df_ki(data, "movementid")
    movement = None
    if movementid != 0:
        movement = db.query(
            dbo, "SELECT * FROM adoption WHERE ID = %d" % movementid)[0]
    adoptionno = utils.df_ks(data, "adoptionno")
    movementtype = utils.df_ki(data, "type")
    movementdate = utils.df_kd(data, "movementdate", l)
    returndate = utils.df_kd(data, "returndate", l)
    reservationdate = utils.df_kd(data, "reservationdate", l)
    reservationcancelled = utils.df_kd(data, "reservationcancelled", l)
    personid = utils.df_ki(data, "person")
    animalid = utils.df_ki(data, "animal")
    retailerid = utils.df_ki(data, "retailer")
    al.debug(
        "validating saved movement %d for animal %d" % (movementid, animalid),
        "movement.validate_movement_form_data", dbo)
    # If we have a date but no type, get rid of it
    if movementdate is None and movementtype == 0:
        data["movementdate"] = ""
        al.debug("blank date and type", "movement.validate_movement_form_data",
                 dbo)
    # If we've got a type, but no date, default today
    if movementtype > 0 and movementdate is None:
        movementdate = i18n.now()
        data["movementdate"] = i18n.python2display(l, movementdate)
        al.debug("type set and no date, defaulting today",
                 "movement.validate_movement_form_data", dbo)
    # If we've got a reserve cancellation without a reserve, remove it
    if reservationdate is None and reservationcancelled is not None:
        data["reservationdate"] = ""
        al.debug("movement has no reserve or cancelled date",
                 "movement.validate_movement_form_data", dbo)
    # Animals are always required
    if animalid == 0:
        al.debug("movement has no animal",
                 "movement.validate_movement_form_data", dbo)
        raise utils.ASMValidationError(i18n._("Movements require an animal",
                                              l))
    # Owners are required unless type is escaped, stolen or released
    if personid == 0 and movementtype != ESCAPED and movementtype != STOLEN and movementtype != RELEASED:
        al.debug("movement has no person and is not ESCAPED|STOLEN|RELEASED",
                 "movement.validate_movement_form_data", dbo)
        raise utils.ASMValidationError(
            i18n._("A person is required for this movement type.", l))
    # Is the movement number unique?
    if 0 != db.query_int(
            dbo,
            "SELECT COUNT(*) FROM adoption WHERE AdoptionNumber LIKE '%s' AND ID <> %d"
            % (adoptionno, movementid)):
        raise utils.ASMValidationError(
            i18n._("Movement numbers must be unique.", l))
    # If we're updating an existing record, we only need to continue validation
    # if one of the important fields has changed (movement date/type, return date, reservation, animal)
    if movement is not None:
        if movementtype == movement[
                "MOVEMENTTYPE"] and movementdate == movement[
                    "MOVEMENTDATE"] and returndate == movement[
                        "RETURNDATE"] and reservationdate == movement[
                            "RESERVATIONDATE"] and animalid == movement[
                                "ANIMALID"]:
            al.debug(
                "movement type, dates and animalid have not changed. Abandoning further validation",
                "movement.validate_movement_form_data", dbo)
            return
    # If the animal is held in case of reclaim, it can't be adopted
    if movementtype == ADOPTION:
        if 1 == db.query_int(
                dbo, "SELECT IsHold FROM animal WHERE ID = %d" % animalid):
            al.debug("movement is adoption and the animal is on hold",
                     "movement.validate_movement_form_data", dbo)
            raise utils.ASMValidationError(
                i18n._("This animal is currently held and cannot be adopted.",
                       l))
    # If it's a foster movement, make sure the owner is a fosterer
    if movementtype == FOSTER:
        if 0 == db.query_int(
                dbo, "SELECT IsFosterer FROM owner WHERE ID = %d" % personid):
            al.debug("movement is a foster and the person is not a fosterer.",
                     "movement.validate_movement_form_data", dbo)
            raise utils.ASMValidationError(
                i18n._(
                    "This person is not flagged as a fosterer and cannot foster animals.",
                    l))
    # If it's a retailer movement, make sure the owner is a retailer
    if movementtype == RETAILER:
        if 0 == db.query_int(
                dbo, "SELECT IsRetailer FROM owner WHERE ID = %d" % personid):
            al.debug(
                "movement is a retailer and the person is not a retailer.",
                "movement.validate_movement_form_data", dbo)
            raise utils.ASMValidationError(
                i18n._(
                    "This person is not flagged as a retailer and cannot handle retailer movements.",
                    l))
    # If a retailer is selected, make sure it's an adoption
    if retailerid != 0 and movementtype != ADOPTION:
        al.debug("movement has a retailerid set and this is not an adoption.",
                 "movement.validate_movement_form_data", dbo)
        raise utils.ASMValidationError(
            i18n._("From retailer is only valid on adoption movements.", l))
    # If a retailer is selected, make sure there's been a retailer movement in this animal's history
    if retailerid != 0:
        if 0 == db.query_int(
                dbo,
                "SELECT COUNT(*) FROM adoption WHERE AnimalID = %d AND MovementType = %d"
                % (animalid, RETAILER)):
            al.debug(
                "movement has a retailerid set but has never been to a retailer.",
                "movement.validate_movement_form_data", dbo)
            raise utils.ASMValidationError(
                i18n._(
                    "This movement cannot be from a retailer when the animal has no prior retailer movements.",
                    l))
    # You can't have a return without a movement
    if movementdate is None and returndate is not None:
        al.debug("movement is returned without a movement date.",
                 "movement.validate_movement_form_data", dbo)
        raise utils.ASMValidationError(
            i18n._("You can't have a return without a movement.", l))
    # Return should be after or same day as movement
    if movementdate is not None and returndate != None and movementdate > returndate:
        al.debug("movement return date is before the movement date.",
                 "movement.validate_movement_form_data", dbo)
        raise utils.ASMValidationError(
            i18n._("Return date cannot be before the movement date.", l))
    # Can't have multiple open movements
    if movementdate is not None:
        existingopen = db.query_int(dbo, "SELECT COUNT(*) FROM adoption WHERE MovementDate Is Not Null AND " \
            "ReturnDate Is Null AND AnimalID = %d AND ID <> %d" % (animalid, movementid))
        if existingopen > 0:
            al.debug(
                "movement is open and animal already has another open movement.",
                "movement.validate_movement_form_data", dbo)
            raise utils.ASMValidationError(
                i18n._("An animal cannot have multiple open movements.", l))
    # If we have a movement and return, is there another movement with a
    # movementdate between the movement and return date on this one?
    if movementdate is not None and returndate != None:
        clash = db.query_int(dbo, "SELECT COUNT(*) FROM adoption WHERE " \
        "AnimalID = %d AND ID <> %d AND ((ReturnDate > %s AND ReturnDate < %s) " \
        "OR (MovementDate < %s AND MovementDate > %s))" % ( animalid, movementid,
        db.dd(movementdate), db.dd(returndate), db.dd(returndate), db.dd(movementdate) ))
        if clash > 0:
            al.debug("movement dates overlap an existing movement.",
                     "movement.validate_movement_form_data", dbo)
            raise utils.ASMValidationError(
                i18n._("Movement dates clash with an existing movement.", l))
    # Does this movement date fall within the date range of an already
    # returned movement for the same animal?
    if movementdate is not None and returndate is None:
        clash = db.query_int(dbo, "SELECT COUNT(*) FROM adoption WHERE AnimalID = %d AND ID <> %d AND " \
        "MovementDate Is Not Null AND ReturnDate Is Not Null AND " \
        "%s > MovementDate AND %s < ReturnDate" % ( animalid, movementid, db.dd(movementdate), db.dd(movementdate)))
        if clash > 0:
            al.debug("movement dates overlap an existing movement.",
                     "movement.validate_movement_form_data", dbo)
            raise utils.ASMValidationError(
                i18n._("Movement dates clash with an existing movement.", l))
    # If there's a cancelled reservation, make sure it's after the reserve date
    if reservationdate is not None and reservationcancelled != None and reservationcancelled < reservationdate:
        al.debug("reserve date is after cancelled date.",
                 "movement.validate_movement_form_data", dbo)
        raise utils.ASMValidationError(
            i18n._("Reservation date cannot be after cancellation date.", l))
    # If this is a new reservation, make sure there's no open movement (fosters do not count)
    if movementid == 0 and movementtype == 0 and movementdate is None and reservationdate is not None:
        om = db.query_int(dbo, "SELECT COUNT(*) FROM adoption WHERE AnimalID = %d AND " \
            "MovementDate Is Not Null AND ReturnDate Is Null AND MovementType <> 2" % animalid)
        if om > 0:
            al.debug(
                "movement is a reservation but animal has active movement.",
                "movement.validate_movement_form_data", dbo)
            raise utils.ASMValidationError(
                i18n._("Can't reserve an animal that has an active movement.",
                       l))
    # Make sure the adoption number is unique
    an = db.query_int(dbo, "SELECT COUNT(*) FROM adoption WHERE ID <> %d AND " \
        "AdoptionNumber LIKE %s" % ( movementid, utils.df_t(data, "adoptionno" )))
    if an > 0:
        al.debug("movement number is not unique.",
                 "movement.validate_movement_form_data", dbo)
        raise utils.ASMValidationError(
            i18n._("The movement number '{0}' is not unique.",
                   l).format(utils.df_ks(data, "adoptionno")))
    # If this is an adoption and the owner had some criteria, expire them
    if movementtype == ADOPTION and personid > 0:
        al.debug("movement is an adoption, expiring person criteria.",
                 "movement.validate_movement_form_data", dbo)
        sql = "UPDATE owner SET MatchActive = 0, MatchExpires = %s WHERE ID = %d" % (
            db.dd(i18n.now(dbo.timezone)), int(personid))
        db.execute(dbo, sql)
    # If the option to cancel reserves on adoption is set, cancel any outstanding reserves for the animal
    if movementtype == ADOPTION and configuration.cancel_reserves_on_adoption(
            dbo):
        al.debug("movement is an adoption, cancelling outstanding reserves.",
                 "movement.validate_movement_form_data", dbo)
        sql = "UPDATE adoption SET ReservationCancelledDate = %s " \
            "WHERE ReservationCancelledDate Is Null AND MovementDate Is Null " \
            "AND AnimalID = %d AND ID <> %d" % ( db.dd(i18n.now(dbo.timezone)), animalid, int(movementid) )
        db.execute(dbo, sql)
Esempio n. 53
0
def handler(data, remoteip, referer):
    """
    Handles the various service method types.
    data: The GET/POST parameters 
    return value is a tuple containing MIME type, max-age, content
    """
    # Database info
    dbo = db.DatabaseInfo()

    # Get service parameters
    account = utils.df_ks(data, "account")
    username = utils.df_ks(data, "username")
    password = utils.df_ks(data, "password")
    method = utils.df_ks(data, "method")
    animalid = utils.df_ki(data, "animalid")
    formid = utils.df_ki(data, "formid")
    title = utils.df_ks(data, "title")
    cache_key = "a" + account + "u" + username + "p" + password + "m" + method + "a" + str(animalid) + "f" + str(formid) + "t" + title
    
    # cache keys aren't allowed spaces
    cache_key = cache_key.replace(" ", "")

    # Do we have a cached response for these parameters?
    cached_response = get_cached_response(cache_key)
    if cached_response is not None:
        al.debug("cache hit for %s/%s/%s/%s" % (account, method, animalid, title), "service.handler")
        return cached_response

    # Are we dealing with multiple databases, but no account was specified?
    if account == "" and MULTIPLE_DATABASES:
        return ("text/plan", 0, "ERROR: No database/alias specified")

    # Are we dealing with multiple databases and an account was specified?
    if account != "":
        if MULTIPLE_DATABASES:
            if MULTIPLE_DATABASES_TYPE == "smcom":
                # Is this sheltermanager.com? If so, we need to get the 
                # database connection info (dbo) before we can login.
                dbo = smcom.get_database_info(account)
            else:
                # Look up the database info from our map
                dbo  = db.get_multiple_database_info(account)
            if dbo.database == "FAIL" or dbo.database == "DISABLED": 
                al.error("auth failed - invalid smaccount %s from %s" % (account, remoteip), "service.handler", dbo)
                return ("text/plain", 0, "ERROR: Invalid database")

    # Does the method require us to authenticate? If so, do it.
    user = None
    if method in AUTH_METHODS:
        user = users.authenticate(dbo, username, password)
        if user is None:
            al.error("auth failed - %s/%s is not a valid username/password from %s" % (username, password, remoteip), "service.handler", dbo)
            return ("text/plain", 0, "ERROR: Invalid username and password")

    # Get the preferred locale for the site
    dbo.locale = configuration.locale(dbo)
    al.info("call %s->%s [%s %s]" % (username, method, str(animalid), title), "service.handler", dbo)

    if method =="animal_image":
        # If we have a hotlinking restriction, enforce it
        if referer != "" and IMAGE_HOTLINKING_ONLY_FROM_DOMAIN != "" and referer.find(IMAGE_HOTLINKING_ONLY_FROM_DOMAIN) == -1:
            raise utils.ASMPermissionError("Image hotlinking is forbidden.")
        if animalid == "" or utils.cint(animalid) == 0:
            al.error("animal_image failed, %s is not an animalid" % str(animalid), "service.handler", dbo)
            return ("text/plain", 0, "ERROR: Invalid animalid")
        # If the option is on, forbid hotlinking
        else:
            seq = utils.df_ki(data, "seq")
            if seq == 0: seq = 1
            mm = media.get_media_by_seq(dbo, media.ANIMAL, utils.cint(animalid), seq)
            if len(mm) == 0:
                return ("image/jpeg", 86400, dbfs.get_string(dbo, "nopic.jpg", "/reports"))
            else:
                return ("image/jpeg", 86400, dbfs.get_string(dbo, mm[0]["MEDIANAME"]))

    elif method =="extra_image":
        return ("image/jpeg", 86400, dbfs.get_string(dbo, title, "/reports"))

    elif method == "json_adoptable_animals":
        pc = publish.PublishCriteria(configuration.publisher_presets(dbo))
        rs = publish.get_animal_data(dbo, pc, True)
        return set_cached_response(cache_key, "application/json", 3600, html.json(rs))

    elif method == "xml_adoptable_animals":
        pc = publish.PublishCriteria(configuration.publisher_presets(dbo))
        rs = publish.get_animal_data(dbo, pc, True)
        return set_cached_response(cache_key, "application/xml", 3600, html.xml(rs))

    elif method == "json_recent_adoptions":
        rs = movement.get_recent_adoptions(dbo)
        return set_cached_response(cache_key, "application/json", 3600, html.json(rs))

    elif method == "xml_recent_adoptions":
        rs = movement.get_recent_adoptions(dbo)
        return set_cached_response(cache_key, "application/xml", 3600, html.xml(rs))

    elif method == "html_report":
        crid = reports.get_id(dbo, title)
        p = reports.get_criteria_params(dbo, crid, data)
        rhtml = reports.execute(dbo, crid, username, p)
        return set_cached_response(cache_key, "text/html", 3600, rhtml)

    elif method == "jsonp_shelter_animals":
        sa = animal.get_animal_find_simple(dbo, "", "shelter")
        return set_cached_response(cache_key, "application/javascript", 3600, str(utils.df_ks(data, "callback")) + "(" + html.json(sa) + ")")

    elif method == "json_shelter_animals":
        sa = animal.get_animal_find_simple(dbo, "", "shelter")
        return set_cached_response(cache_key, "application/json", 3600, html.json(sa))

    elif method == "xml_shelter_animals":
        sa = animal.get_animal_find_simple(dbo, "", "shelter")
        return set_cached_response(cache_key, "application/xml", 3600, html.json(sa))

    elif method == "upload_animal_image":
        media.attach_file_from_form(dbo, username, media.ANIMAL, int(animalid), data)
        return ("text/plain", 0, "OK")

    elif method == "online_form_html":
        if formid == 0:
            raise utils.ASMError("method online_form_html requires a valid formid")
        return set_cached_response(cache_key, "text/html", 120, onlineform.get_onlineform_html(dbo, formid))

    elif method == "online_form_post":
        onlineform.insert_onlineformincoming_from_form(dbo, data, remoteip)
        redirect = utils.df_ks(data, "redirect")
        if redirect == "":
            redirect = BASE_URL + "/static/pages/form_submitted.html"
        return ("redirect", 0, redirect)

    else:
        al.error("invalid method '%s'" % method, "service.handler", dbo)
        raise utils.ASMError("Invalid method '%s'" % method)
Esempio n. 54
0
def handler(data, remoteip, referer):
    """
    Handles the various service method types.
    data: The GET/POST parameters 
    return value is a tuple containing MIME type, max-age, content
    """
    # Database info
    dbo = db.DatabaseInfo()

    # Get service parameters
    account = utils.df_ks(data, "account")
    username = utils.df_ks(data, "username")
    password = utils.df_ks(data, "password")
    method = utils.df_ks(data, "method")
    animalid = utils.df_ki(data, "animalid")
    formid = utils.df_ki(data, "formid")
    title = utils.df_ks(data, "title")
    cache_key = "a" + account + "u" + username + "p" + password + "m" + method + "a" + str(
        animalid) + "f" + str(formid) + "t" + title

    # cache keys aren't allowed spaces
    cache_key = cache_key.replace(" ", "")

    # Do we have a cached response for these parameters?
    cached_response = get_cached_response(cache_key)
    if cached_response is not None:
        al.debug(
            "cache hit for %s/%s/%s/%s" % (account, method, animalid, title),
            "service.handler")
        return cached_response

    # Are we dealing with multiple databases, but no account was specified?
    if account == "" and MULTIPLE_DATABASES:
        return ("text/plan", 0, "ERROR: No database/alias specified")

    # Are we dealing with multiple databases and an account was specified?
    if account != "":
        if MULTIPLE_DATABASES:
            if MULTIPLE_DATABASES_TYPE == "smcom":
                # Is this sheltermanager.com? If so, we need to get the
                # database connection info (dbo) before we can login.
                dbo = smcom.get_database_info(account)
            else:
                # Look up the database info from our map
                dbo = db.get_multiple_database_info(account)
            if dbo.database == "FAIL" or dbo.database == "DISABLED":
                al.error(
                    "auth failed - invalid smaccount %s from %s" %
                    (account, remoteip), "service.handler", dbo)
                return ("text/plain", 0, "ERROR: Invalid database")

    # Does the method require us to authenticate? If so, do it.
    user = None
    if method in AUTH_METHODS:
        user = users.authenticate(dbo, username, password)
        if user is None:
            al.error(
                "auth failed - %s/%s is not a valid username/password from %s"
                % (username, password, remoteip), "service.handler", dbo)
            return ("text/plain", 0, "ERROR: Invalid username and password")

    # Get the preferred locale for the site
    dbo.locale = configuration.locale(dbo)
    al.info("call %s->%s [%s %s]" % (username, method, str(animalid), title),
            "service.handler", dbo)

    if method == "animal_image":
        # If we have a hotlinking restriction, enforce it
        if referer != "" and IMAGE_HOTLINKING_ONLY_FROM_DOMAIN != "" and referer.find(
                IMAGE_HOTLINKING_ONLY_FROM_DOMAIN) == -1:
            raise utils.ASMPermissionError("Image hotlinking is forbidden.")
        if animalid == "" or utils.cint(animalid) == 0:
            al.error(
                "animal_image failed, %s is not an animalid" % str(animalid),
                "service.handler", dbo)
            return ("text/plain", 0, "ERROR: Invalid animalid")
        # If the option is on, forbid hotlinking
        else:
            seq = utils.df_ki(data, "seq")
            if seq == 0: seq = 1
            mm = media.get_media_by_seq(dbo, media.ANIMAL,
                                        utils.cint(animalid), seq)
            if len(mm) == 0:
                return ("image/jpeg", 86400,
                        dbfs.get_string(dbo, "nopic.jpg", "/reports"))
            else:
                return ("image/jpeg", 86400,
                        dbfs.get_string(dbo, mm[0]["MEDIANAME"]))

    elif method == "extra_image":
        return ("image/jpeg", 86400, dbfs.get_string(dbo, title, "/reports"))

    elif method == "json_adoptable_animals":
        pc = publish.PublishCriteria(configuration.publisher_presets(dbo))
        rs = publish.get_animal_data(dbo, pc, True)
        return set_cached_response(cache_key, "application/json", 3600,
                                   html.json(rs))

    elif method == "xml_adoptable_animals":
        pc = publish.PublishCriteria(configuration.publisher_presets(dbo))
        rs = publish.get_animal_data(dbo, pc, True)
        return set_cached_response(cache_key, "application/xml", 3600,
                                   html.xml(rs))

    elif method == "json_recent_adoptions":
        rs = movement.get_recent_adoptions(dbo)
        return set_cached_response(cache_key, "application/json", 3600,
                                   html.json(rs))

    elif method == "xml_recent_adoptions":
        rs = movement.get_recent_adoptions(dbo)
        return set_cached_response(cache_key, "application/xml", 3600,
                                   html.xml(rs))

    elif method == "html_report":
        crid = reports.get_id(dbo, title)
        p = reports.get_criteria_params(dbo, crid, data)
        rhtml = reports.execute(dbo, crid, username, p)
        return set_cached_response(cache_key, "text/html", 3600, rhtml)

    elif method == "jsonp_shelter_animals":
        sa = animal.get_animal_find_simple(dbo, "", "shelter")
        return set_cached_response(
            cache_key, "application/javascript", 3600,
            str(utils.df_ks(data, "callback")) + "(" + html.json(sa) + ")")

    elif method == "json_shelter_animals":
        sa = animal.get_animal_find_simple(dbo, "", "shelter")
        return set_cached_response(cache_key, "application/json", 3600,
                                   html.json(sa))

    elif method == "xml_shelter_animals":
        sa = animal.get_animal_find_simple(dbo, "", "shelter")
        return set_cached_response(cache_key, "application/xml", 3600,
                                   html.json(sa))

    elif method == "upload_animal_image":
        media.attach_file_from_form(dbo, username, media.ANIMAL, int(animalid),
                                    data)
        return ("text/plain", 0, "OK")

    elif method == "online_form_html":
        if formid == 0:
            raise utils.ASMError(
                "method online_form_html requires a valid formid")
        return set_cached_response(cache_key, "text/html", 120,
                                   onlineform.get_onlineform_html(dbo, formid))

    elif method == "online_form_post":
        onlineform.insert_onlineformincoming_from_form(dbo, data, remoteip)
        redirect = utils.df_ks(data, "redirect")
        if redirect == "":
            redirect = BASE_URL + "/static/pages/form_submitted.html"
        return ("redirect", 0, redirect)

    else:
        al.error("invalid method '%s'" % method, "service.handler", dbo)
        raise utils.ASMError("Invalid method '%s'" % method)
Esempio n. 55
0
def insert_adoption_from_form(dbo, username, data, creating=[]):
    """
    Inserts a movement from the workflow adopt an animal screen.
    Returns the new movement id
    creating is an ongoing list of animals we're already going to
    create adoptions for. It prevents a never ending recursive loop
    of animal1 being bonded to animal2 that's bonded to animal1, etc.
    """
    l = dbo.locale
    # Validate that we have a movement date before doing anthing
    if None == utils.df_kd(data, "movementdate", l):
        raise utils.ASMValidationError(
            i18n._("Adoption movements must have a valid adoption date.", l))
    # Get the animal record for this adoption
    a = animal.get_animal(dbo, utils.df_ki(data, "animal"))
    if a is None:
        raise utils.ASMValidationError(
            "Adoption POST has an invalid animal ID: %d" %
            utils.df_ki(data, "animal"))
    al.debug(
        "Creating adoption for %d (%s - %s)" %
        (a["ID"], a["SHELTERCODE"], a["ANIMALNAME"]),
        "movement.insert_adoption_from_form", dbo)
    creating.append(a["ID"])
    # If the animal is bonded to other animals, we call this function
    # again with a copy of the data and the bonded animal substituted
    # so we can create their adoption records too.
    if a["BONDEDANIMALID"] is not None and a["BONDEDANIMALID"] != 0 and a[
            "BONDEDANIMALID"] not in creating:
        al.debug(
            "Found bond to animal %d, creating adoption..." %
            a["BONDEDANIMALID"], "movement.insert_adoption_from_form", dbo)
        newdata = dict(data)
        newdata["animal"] = str(a["BONDEDANIMALID"])
        insert_adoption_from_form(dbo, username, newdata, creating)
    if a["BONDEDANIMAL2ID"] is not None and a["BONDEDANIMAL2ID"] != 0 and a[
            "BONDEDANIMAL2ID"] not in creating:
        al.debug(
            "Found bond to animal %d, creating adoption..." %
            a["BONDEDANIMAL2ID"], "movement.insert_adoption_from_form", dbo)
        newdata = dict(data)
        newdata["animal"] = str(a["BONDEDANIMAL2ID"])
        insert_adoption_from_form(dbo, username, newdata, creating)
    cancel_reserves = configuration.cancel_reserves_on_adoption(dbo)
    # Prepare a dictionary of data for the movement table via insert_movement_from_form
    move_dict = {
        "person": utils.df_ks(data, "person"),
        "animal": utils.df_ks(data, "animal"),
        "adoptionno": utils.df_ks(data, "movementnumber"),
        "movementdate": utils.df_ks(data, "movementdate"),
        "type": str(ADOPTION),
        "donation": utils.df_ks(data, "amount"),
        "insurance": utils.df_ks(data, "insurance"),
        "returncategory": configuration.default_return_reason(dbo),
        "trial": utils.df_ks(data, "trial"),
        "trialenddate": utils.df_ks(data, "trialenddate")
    }
    # Is this animal currently on foster? If so, return the foster
    fm = get_animal_movements(dbo, utils.df_ki(data, "animal"))
    for m in fm:
        if m["MOVEMENTTYPE"] == FOSTER and m["RETURNDATE"] is None:
            return_movement(dbo, m["ID"], utils.df_ki(data, "animal"),
                            utils.df_kd(data, "movementdate", l))
    # Is this animal current at a retailer? If so, return it from the
    # retailer and set the originalretailermovement and retailerid fields
    # on our new adoption movement so it can be linked back
    for m in fm:
        if m["MOVEMENTTYPE"] == RETAILER and m["RETURNDATE"] is None:
            return_movement(dbo, m["ID"], utils.df_ki(data, "animal"),
                            utils.df_kd(data, "movementdate", l))
            move_dict["originalretailermovement"] = str(m["ID"])
            move_dict["retailer"] = str(m["OWNERID"])
    # Did we say we'd like to flag the owner as homechecked?
    if utils.df_kc(data, "homechecked") == 1:
        db.execute(dbo, "UPDATE owner SET IDCheck = 1, DateLastHomeChecked = %s WHERE ID = %d" % \
            ( db.dd(i18n.now(dbo.timezone)), utils.df_ki(data, "person")))
    # If the animal was flagged as not available for adoption, then it
    # shouldn't be since we've just adopted it.
    db.execute(
        dbo, "UPDATE animal SET IsNotAvailableForAdoption = 0 WHERE ID = %s" %
        utils.df_ks(data, "animal"))
    # Is the animal reserved to the person adopting?
    movementid = 0
    for m in fm:
        if m["MOVEMENTTYPE"] == NO_MOVEMENT and m["RESERVATIONDATE"] is not None \
            and m["RESERVATIONCANCELLEDDATE"] is None and m["ANIMALID"] == utils.df_ki(data, "animal") \
            and m["OWNERID"] == utils.df_ki(data, "person"):
            # yes - update the existing movement
            movementid = m["ID"]
            move_dict["movementid"] = str(movementid)
            move_dict["adoptionno"] = utils.padleft(movementid, 6)
            move_dict["reservationdate"] = str(
                i18n.python2display(l, m["RESERVATIONDATE"]))
            move_dict["comments"] = utils.nulltostr(m["COMMENTS"])
            break
        elif cancel_reserves and m["MOVEMENTTYPE"] == NO_MOVEMENT and m["RESERVATIONDATE"] is not None \
            and m["RESERVATIONCANCELLEDDATE"] is None:
            # no, but it's reserved to someone else and we're cancelling
            # reserves on adoption
            db.execute(dbo, "UPDATE adoption SET ReservationCancelledDate = %s WHERE ID = %d" % \
                ( utils.df_d(data, "movementdate", l), m["ID"] ))
    if movementid != 0:
        update_movement_from_form(dbo, username, move_dict)
    else:
        movementid = insert_movement_from_form(dbo, username, move_dict)
    # Create the donation if there is one
    donation_amount = int(utils.df_m(data, "amount", l))
    if donation_amount > 0:
        due = ""
        received = utils.df_ks(data, "movementdate")
        if configuration.movement_donations_default_due(dbo):
            due = utils.df_ks(data, "movementdate")
            received = ""
        don_dict = {
            "person": utils.df_ks(data, "person"),
            "animal": utils.df_ks(data, "animal"),
            "movement": str(movementid),
            "type": utils.df_ks(data, "donationtype"),
            "payment": utils.df_ks(data, "payment"),
            "frequency": "0",
            "amount": utils.df_ks(data, "amount"),
            "due": due,
            "received": received,
            "giftaid": utils.df_ks(data, "giftaid")
        }
        financial.insert_donation_from_form(dbo, username, don_dict)
    # And a second donation if there is one
    donation_amount = int(utils.df_m(data, "amount2", l))
    if donation_amount > 0:
        due = ""
        received = utils.df_ks(data, "movementdate")
        if configuration.movement_donations_default_due(dbo):
            due = utils.df_ks(data, "movementdate")
            received = ""
        don_dict = {
            "person": utils.df_ks(data, "person"),
            "animal": utils.df_ks(data, "animal"),
            "movement": str(movementid),
            "type": utils.df_ks(data, "donationtype2"),
            "payment": utils.df_ks(data, "payment2"),
            "frequency": "0",
            "amount": utils.df_ks(data, "amount2"),
            "due": due,
            "received": received,
            "giftaid": utils.df_ks(data, "giftaid")
        }
        financial.insert_donation_from_form(dbo, username, don_dict)
    # Then any boarding cost record
    cost_amount = int(utils.df_m(data, "costamount", l))
    cost_type = utils.df_ks(data, "costtype")
    cost_create = utils.df_ki(data, "costcreate")
    if cost_amount > 0 and cost_type != "" and cost_create == 1:
        boc_dict = {
            "animalid": utils.df_ks(data, "animal"),
            "type": cost_type,
            "costdate": utils.df_ks(data, "movementdate"),
            "cost": utils.df_ks(data, "costamount")
        }
        animal.insert_cost_from_form(dbo, username, boc_dict)
    return movementid
Esempio n. 56
0
def validate_movement_form_data(dbo, data):
    """
    Verifies that form data is valid for a movement
    """
    l = dbo.locale
    movementid = utils.df_ki(data, "movementid")
    movement = None
    if movementid != 0: movement = db.query(dbo, "SELECT * FROM adoption WHERE ID = %d" % movementid)[0]
    adoptionno = utils.df_ks(data, "adoptionno")
    movementtype = utils.df_ki(data, "type")
    movementdate = utils.df_kd(data, "movementdate", l)
    returndate = utils.df_kd(data, "returndate", l)
    reservationdate = utils.df_kd(data, "reservationdate", l)
    reservationcancelled = utils.df_kd(data, "reservationcancelled", l)
    personid = utils.df_ki(data, "person")
    animalid = utils.df_ki(data, "animal")
    retailerid = utils.df_ki(data, "retailer")
    al.debug("validating saved movement %d for animal %d" % (movementid, animalid), "movement.validate_movement_form_data", dbo)
    # If we have a date but no type, get rid of it
    if movementdate is None and movementtype == 0:
        data["movementdate"] = ""
        al.debug("blank date and type", "movement.validate_movement_form_data", dbo)
    # If we've got a type, but no date, default today
    if movementtype > 0 and movementdate is None:
        movementdate = i18n.now()
        data["movementdate"] = i18n.python2display(l, movementdate)
        al.debug("type set and no date, defaulting today", "movement.validate_movement_form_data", dbo)
    # If we've got a reserve cancellation without a reserve, remove it
    if reservationdate is None and reservationcancelled is not None:
        data["reservationdate"] = ""
        al.debug("movement has no reserve or cancelled date", "movement.validate_movement_form_data", dbo)
    # Animals are always required
    if animalid == 0:
        al.debug("movement has no animal", "movement.validate_movement_form_data", dbo)
        raise utils.ASMValidationError(i18n._("Movements require an animal", l))
    # Owners are required unless type is escaped, stolen or released
    if personid == 0 and movementtype != ESCAPED and movementtype != STOLEN and movementtype != RELEASED:
        al.debug("movement has no person and is not ESCAPED|STOLEN|RELEASED", "movement.validate_movement_form_data", dbo)
        raise utils.ASMValidationError(i18n._("A person is required for this movement type.", l))
    # Is the movement number unique?
    if 0 != db.query_int(dbo, "SELECT COUNT(*) FROM adoption WHERE AdoptionNumber LIKE '%s' AND ID <> %d" % (adoptionno, movementid)):
        raise utils.ASMValidationError(i18n._("Movement numbers must be unique.", l))
    # If we're updating an existing record, we only need to continue validation
    # if one of the important fields has changed (movement date/type, return date, reservation, animal)
    if movement is not None:
        if movementtype == movement["MOVEMENTTYPE"] and movementdate == movement["MOVEMENTDATE"] and returndate == movement["RETURNDATE"] and reservationdate == movement["RESERVATIONDATE"] and animalid == movement["ANIMALID"]:
            al.debug("movement type, dates and animalid have not changed. Abandoning further validation", "movement.validate_movement_form_data", dbo)
            return
    # If the animal is held in case of reclaim, it can't be adopted
    if movementtype == ADOPTION:
        if 1 == db.query_int(dbo, "SELECT IsHold FROM animal WHERE ID = %d" % animalid):
            al.debug("movement is adoption and the animal is on hold", "movement.validate_movement_form_data", dbo)
            raise utils.ASMValidationError(i18n._("This animal is currently held and cannot be adopted.", l))
    # If it's a foster movement, make sure the owner is a fosterer
    if movementtype == FOSTER:
        if 0 == db.query_int(dbo, "SELECT IsFosterer FROM owner WHERE ID = %d" % personid):
            al.debug("movement is a foster and the person is not a fosterer.", "movement.validate_movement_form_data", dbo)
            raise utils.ASMValidationError(i18n._("This person is not flagged as a fosterer and cannot foster animals.", l))
    # If it's a retailer movement, make sure the owner is a retailer
    if movementtype == RETAILER:
        if 0 == db.query_int(dbo, "SELECT IsRetailer FROM owner WHERE ID = %d" % personid):
            al.debug("movement is a retailer and the person is not a retailer.", "movement.validate_movement_form_data", dbo)
            raise utils.ASMValidationError(i18n._("This person is not flagged as a retailer and cannot handle retailer movements.", l))
    # If a retailer is selected, make sure it's an adoption
    if retailerid != 0 and movementtype != ADOPTION:
        al.debug("movement has a retailerid set and this is not an adoption.", "movement.validate_movement_form_data", dbo)
        raise utils.ASMValidationError(i18n._("From retailer is only valid on adoption movements.", l))
    # If a retailer is selected, make sure there's been a retailer movement in this animal's history
    if retailerid != 0:
        if 0 == db.query_int(dbo, "SELECT COUNT(*) FROM adoption WHERE AnimalID = %d AND MovementType = %d" % ( animalid, RETAILER )):
            al.debug("movement has a retailerid set but has never been to a retailer.", "movement.validate_movement_form_data", dbo)
            raise utils.ASMValidationError(i18n._("This movement cannot be from a retailer when the animal has no prior retailer movements.", l))
    # You can't have a return without a movement
    if movementdate is None and returndate is not None:
        al.debug("movement is returned without a movement date.", "movement.validate_movement_form_data", dbo)
        raise utils.ASMValidationError(i18n._("You can't have a return without a movement.", l))
    # Return should be after or same day as movement
    if movementdate is not None and returndate != None and movementdate > returndate:
        al.debug("movement return date is before the movement date.", "movement.validate_movement_form_data", dbo)
        raise utils.ASMValidationError(i18n._("Return date cannot be before the movement date.", l))
    # Can't have multiple open movements
    if movementdate is not None:
        existingopen = db.query_int(dbo, "SELECT COUNT(*) FROM adoption WHERE MovementDate Is Not Null AND " \
            "ReturnDate Is Null AND AnimalID = %d AND ID <> %d" % (animalid, movementid))
        if existingopen > 0:
            al.debug("movement is open and animal already has another open movement.", "movement.validate_movement_form_data", dbo)
            raise utils.ASMValidationError(i18n._("An animal cannot have multiple open movements.", l))
    # If we have a movement and return, is there another movement with a 
    # movementdate between the movement and return date on this one?
    if movementdate is not None and returndate != None:
        clash = db.query_int(dbo, "SELECT COUNT(*) FROM adoption WHERE " \
        "AnimalID = %d AND ID <> %d AND ((ReturnDate > %s AND ReturnDate < %s) " \
        "OR (MovementDate < %s AND MovementDate > %s))" % ( animalid, movementid, 
        db.dd(movementdate), db.dd(returndate), db.dd(returndate), db.dd(movementdate) ))
        if clash > 0:
            al.debug("movement dates overlap an existing movement.", "movement.validate_movement_form_data", dbo)
            raise utils.ASMValidationError(i18n._("Movement dates clash with an existing movement.", l))
    # Does this movement date fall within the date range of an already
    # returned movement for the same animal?
    if movementdate is not None and returndate is None:
        clash = db.query_int(dbo, "SELECT COUNT(*) FROM adoption WHERE AnimalID = %d AND ID <> %d AND " \
        "MovementDate Is Not Null AND ReturnDate Is Not Null AND " \
        "%s > MovementDate AND %s < ReturnDate" % ( animalid, movementid, db.dd(movementdate), db.dd(movementdate)))
        if clash > 0:
            al.debug("movement dates overlap an existing movement.", "movement.validate_movement_form_data", dbo)
            raise utils.ASMValidationError(i18n._("Movement dates clash with an existing movement.", l))
    # If there's a cancelled reservation, make sure it's after the reserve date
    if reservationdate is not None and reservationcancelled != None and reservationcancelled < reservationdate:
        al.debug("reserve date is after cancelled date.", "movement.validate_movement_form_data", dbo)
        raise utils.ASMValidationError(i18n._("Reservation date cannot be after cancellation date.", l))
    # If this is a new reservation, make sure there's no open movement (fosters do not count)
    if movementid == 0 and movementtype == 0 and movementdate is None and reservationdate is not None:
        om = db.query_int(dbo, "SELECT COUNT(*) FROM adoption WHERE AnimalID = %d AND " \
            "MovementDate Is Not Null AND ReturnDate Is Null AND MovementType <> 2" % animalid)
        if om > 0:
            al.debug("movement is a reservation but animal has active movement.", "movement.validate_movement_form_data", dbo)
            raise utils.ASMValidationError(i18n._("Can't reserve an animal that has an active movement.", l))
    # Make sure the adoption number is unique
    an = db.query_int(dbo, "SELECT COUNT(*) FROM adoption WHERE ID <> %d AND " \
        "AdoptionNumber LIKE %s" % ( movementid, utils.df_t(data, "adoptionno" )))
    if an > 0:
        al.debug("movement number is not unique.", "movement.validate_movement_form_data", dbo)
        raise utils.ASMValidationError(i18n._("The movement number '{0}' is not unique.", l).format(utils.df_ks(data, "adoptionno")))
    # If this is an adoption and the owner had some criteria, expire them
    if movementtype == ADOPTION and personid > 0:
        al.debug("movement is an adoption, expiring person criteria.", "movement.validate_movement_form_data", dbo)
        sql = "UPDATE owner SET MatchActive = 0, MatchExpires = %s WHERE ID = %d" % ( db.dd(i18n.now(dbo.timezone)), int(personid) )
        db.execute(dbo, sql)
    # If the option to cancel reserves on adoption is set, cancel any outstanding reserves for the animal
    if movementtype == ADOPTION and configuration.cancel_reserves_on_adoption(dbo):
        al.debug("movement is an adoption, cancelling outstanding reserves.", "movement.validate_movement_form_data", dbo)
        sql = "UPDATE adoption SET ReservationCancelledDate = %s " \
            "WHERE ReservationCancelledDate Is Null AND MovementDate Is Null " \
            "AND AnimalID = %d AND ID <> %d" % ( db.dd(i18n.now(dbo.timezone)), animalid, int(movementid) )
        db.execute(dbo, sql)
Esempio n. 57
0
def attach_file_from_form(dbo, username, linktype, linkid, data):
    """
    Attaches a media file from the posted form
    data is the web.py data object and should contain
    comments, the filechooser object, with filename and value 
    props - OR a parameter called base64image containing a base64
    encoded jpg image.
    """
    ext = ""
    base64data = ""
    base64image = utils.df_ks(data, "base64image")
    if base64image != "":
        ext = ".jpg"
        # If an HTML5 data url was used, strip the prefix so we just have base64 data
        if base64image.find("data:") != -1:
            base64data = base64image[base64image.find(",") + 1:]
            # Browser escaping turns base64 pluses back into spaces, so switch back
            base64data = base64data.replace(" ", "+")
        else:
            base64data = base64image
    else:
        ext = data.filechooser.filename
        ext = ext[ext.rfind("."):].lower()
    mediaid = db.get_id(dbo, "media")
    medianame = "%d%s" % (mediaid, ext)
    ispicture = ext == ".jpg" or ext == ".jpeg"
    ispdf = ext == ".pdf"

    # Does this link have anything with web/doc set? If not, set the
    # web/doc flags
    web = 0
    doc = 0
    existing_web = db.query_int(dbo, "SELECT COUNT(*) FROM media WHERE WebsitePhoto = 1 " \
        "AND LinkID = %d AND LinkTypeID = %d" % ( int(linkid), int(linktype) ))
    existing_doc = db.query_int(dbo, "SELECT COUNT(*) FROM media WHERE DocPhoto = 1 " \
        "AND LinkID = %d AND LinkTypeID = %d" % ( int(linkid), int(linktype) ))
    if existing_web == 0 and ispicture:
        web = 1
    if existing_doc == 0 and ispicture:
        doc = 1

    if base64image != "":
        filedata = base64.b64decode(base64data)
    else:
        filedata = data.filechooser.value

    # Is it a picture?
    if ispicture:
        # Autorotate it to match the EXIF orientation
        filedata = auto_rotate_image(filedata)
        # Scale it down to the system set size
        scalespec = configuration.incoming_media_scaling(dbo)
        if scalespec != "None":
            filedata = scale_image(filedata, scalespec)

    # Is it a PDF? If so, compress it if we can and the option is on
    if ispdf and gs_installed() and SCALE_PDF:
        filedata = scale_pdf(filedata)
        medianame = "%d_scaled.pdf" % mediaid

    # Attach the file in the dbfs
    path = get_dbfs_path(linkid, linktype)
    dbfs.put_string(dbo, medianame, path, filedata)

    # Are the notes for an image blank and we're defaulting them from animal comments?
    comments = utils.df_ks(data, "comments")
    if comments == "" and ispicture and linktype == ANIMAL and configuration.auto_media_notes(
            dbo):
        comments = animal.get_comments(dbo, int(linkid))
        # Are the notes blank and we're defaulting them from the filename?
    elif comments == "" and configuration.default_media_notes_from_file(
            dbo) and base64image == "":
        comments = utils.filename_only(data.filechooser.filename)

    # Create the media record
    sql = db.make_insert_sql(
        "media",
        (("ID", db.di(mediaid)), ("MediaName", db.ds(medianame)),
         ("MediaType", db.di(0)), ("MediaNotes", db.ds(comments)),
         ("WebsitePhoto", db.di(web)), ("WebsiteVideo", db.di(0)),
         ("DocPhoto", db.di(doc)), ("ExcludeFromPublish", db.di(0)),
         ("NewSinceLastPublish", db.di(1)),
         ("UpdatedSinceLastPublish", db.di(0)), ("LinkID", db.di(linkid)),
         ("LinkTypeID", db.di(linktype)), ("Date", db.nowsql())))
    db.execute(dbo, sql)
    audit.create(dbo, username, "media",
                 str(mediaid) + ": for " + str(linkid) + "/" + str(linktype))
Esempio n. 58
0
def insert_adoption_from_form(dbo, username, data, creating = []):
    """
    Inserts a movement from the workflow adopt an animal screen.
    Returns the new movement id
    creating is an ongoing list of animals we're already going to
    create adoptions for. It prevents a never ending recursive loop
    of animal1 being bonded to animal2 that's bonded to animal1, etc.
    """
    l = dbo.locale
    # Validate that we have a movement date before doing anthing
    if None == utils.df_kd(data, "movementdate", l):
        raise utils.ASMValidationError(i18n._("Adoption movements must have a valid adoption date.", l))
    # Get the animal record for this adoption
    a = animal.get_animal(dbo, utils.df_ki(data, "animal"))
    if a is None:
        raise utils.ASMValidationError("Adoption POST has an invalid animal ID: %d" % utils.df_ki(data, "animal"))
    al.debug("Creating adoption for %d (%s - %s)" % (a["ID"], a["SHELTERCODE"], a["ANIMALNAME"]), "movement.insert_adoption_from_form", dbo)
    creating.append(a["ID"])
    # If the animal is bonded to other animals, we call this function
    # again with a copy of the data and the bonded animal substituted
    # so we can create their adoption records too.
    if a["BONDEDANIMALID"] is not None and a["BONDEDANIMALID"] != 0 and a["BONDEDANIMALID"] not in creating:
        al.debug("Found bond to animal %d, creating adoption..." % a["BONDEDANIMALID"], "movement.insert_adoption_from_form", dbo)
        newdata = dict(data)
        newdata["animal"] = str(a["BONDEDANIMALID"])
        insert_adoption_from_form(dbo, username, newdata, creating)
    if a["BONDEDANIMAL2ID"] is not None and a["BONDEDANIMAL2ID"] != 0 and a["BONDEDANIMAL2ID"] not in creating:
        al.debug("Found bond to animal %d, creating adoption..." % a["BONDEDANIMAL2ID"], "movement.insert_adoption_from_form", dbo)
        newdata = dict(data)
        newdata["animal"] = str(a["BONDEDANIMAL2ID"])
        insert_adoption_from_form(dbo, username, newdata, creating)
    cancel_reserves = configuration.cancel_reserves_on_adoption(dbo)
    # Prepare a dictionary of data for the movement table via insert_movement_from_form
    move_dict = {
        "person"                : utils.df_ks(data, "person"),
        "animal"                : utils.df_ks(data, "animal"),
        "adoptionno"            : utils.df_ks(data, "movementnumber"),
        "movementdate"          : utils.df_ks(data, "movementdate"),
        "type"                  : str(ADOPTION),
        "donation"              : utils.df_ks(data, "amount"),
        "insurance"             : utils.df_ks(data, "insurance"),
        "returncategory"        : configuration.default_return_reason(dbo),
        "trial"                 : utils.df_ks(data, "trial"),
        "trialenddate"          : utils.df_ks(data, "trialenddate")
    }
    # Is this animal currently on foster? If so, return the foster
    fm = get_animal_movements(dbo, utils.df_ki(data, "animal"))
    for m in fm:
        if m["MOVEMENTTYPE"] == FOSTER and m["RETURNDATE"] is None:
            return_movement(dbo, m["ID"], utils.df_ki(data, "animal"), utils.df_kd(data, "movementdate", l))
    # Is this animal current at a retailer? If so, return it from the
    # retailer and set the originalretailermovement and retailerid fields
    # on our new adoption movement so it can be linked back
    for m in fm:
        if m["MOVEMENTTYPE"] == RETAILER and m["RETURNDATE"] is None:
            return_movement(dbo, m["ID"], utils.df_ki(data, "animal"), utils.df_kd(data, "movementdate", l))
            move_dict["originalretailermovement"] = str(m["ID"])
            move_dict["retailer"] = str(m["OWNERID"])
    # Did we say we'd like to flag the owner as homechecked?
    if utils.df_kc(data, "homechecked") == 1:
        db.execute(dbo, "UPDATE owner SET IDCheck = 1, DateLastHomeChecked = %s WHERE ID = %d" % \
            ( db.dd(i18n.now(dbo.timezone)), utils.df_ki(data, "person")))
    # If the animal was flagged as not available for adoption, then it
    # shouldn't be since we've just adopted it.
    db.execute(dbo, "UPDATE animal SET IsNotAvailableForAdoption = 0 WHERE ID = %s" % utils.df_ks(data, "animal"))
    # Is the animal reserved to the person adopting? 
    movementid = 0
    for m in fm:
        if m["MOVEMENTTYPE"] == NO_MOVEMENT and m["RESERVATIONDATE"] is not None \
            and m["RESERVATIONCANCELLEDDATE"] is None and m["ANIMALID"] == utils.df_ki(data, "animal") \
            and m["OWNERID"] == utils.df_ki(data, "person"):
            # yes - update the existing movement
            movementid = m["ID"]
            move_dict["movementid"] = str(movementid)
            move_dict["adoptionno"] = utils.padleft(movementid, 6)
            move_dict["reservationdate"] = str(i18n.python2display(l, m["RESERVATIONDATE"]))
            move_dict["comments"] = utils.nulltostr(m["COMMENTS"])
            break
        elif cancel_reserves and m["MOVEMENTTYPE"] == NO_MOVEMENT and m["RESERVATIONDATE"] is not None \
            and m["RESERVATIONCANCELLEDDATE"] is None:
            # no, but it's reserved to someone else and we're cancelling
            # reserves on adoption
            db.execute(dbo, "UPDATE adoption SET ReservationCancelledDate = %s WHERE ID = %d" % \
                ( utils.df_d(data, "movementdate", l), m["ID"] ))
    if movementid != 0:
        update_movement_from_form(dbo, username, move_dict)
    else:
        movementid = insert_movement_from_form(dbo, username, move_dict)
    # Create the donation if there is one
    donation_amount = int(utils.df_m(data, "amount", l))
    if donation_amount > 0:
        due = ""
        received = utils.df_ks(data, "movementdate")
        if configuration.movement_donations_default_due(dbo):
            due = utils.df_ks(data, "movementdate")
            received = ""
        don_dict = {
            "person"                : utils.df_ks(data, "person"),
            "animal"                : utils.df_ks(data, "animal"),
            "movement"              : str(movementid),
            "type"                  : utils.df_ks(data, "donationtype"),
            "payment"               : utils.df_ks(data, "payment"),
            "frequency"             : "0",
            "amount"                : utils.df_ks(data, "amount"),
            "due"                   : due,
            "received"              : received,
            "giftaid"               : utils.df_ks(data, "giftaid")
        }
        financial.insert_donation_from_form(dbo, username, don_dict)
    # And a second donation if there is one
    donation_amount = int(utils.df_m(data, "amount2", l))
    if donation_amount > 0:
        due = ""
        received = utils.df_ks(data, "movementdate")
        if configuration.movement_donations_default_due(dbo):
            due = utils.df_ks(data, "movementdate")
            received = ""
        don_dict = {
            "person"                : utils.df_ks(data, "person"),
            "animal"                : utils.df_ks(data, "animal"),
            "movement"              : str(movementid),
            "type"                  : utils.df_ks(data, "donationtype2"),
            "payment"               : utils.df_ks(data, "payment2"),
            "frequency"             : "0",
            "amount"                : utils.df_ks(data, "amount2"),
            "due"                   : due,
            "received"              : received,
            "giftaid"               : utils.df_ks(data, "giftaid")
        }
        financial.insert_donation_from_form(dbo, username, don_dict)
    # Then any boarding cost record
    cost_amount = int(utils.df_m(data, "costamount", l))
    cost_type = utils.df_ks(data, "costtype")
    cost_create = utils.df_ki(data, "costcreate")
    if cost_amount > 0 and cost_type != "" and cost_create == 1:
        boc_dict = {
            "animalid"          : utils.df_ks(data, "animal"),
            "type"              : cost_type,
            "costdate"          : utils.df_ks(data, "movementdate"),
            "cost"              : utils.df_ks(data, "costamount")
        }
        animal.insert_cost_from_form(dbo, username, boc_dict)
    return movementid