def insert_foundanimal_from_form(dbo, post, username):
    """
    Inserts a new found animal record from the screen
    data: The webpy data object containing form parameters
    """
    l = dbo.locale
    if post.date("datefound") is None:
        raise utils.ASMValidationError(_("Date found cannot be blank", l))
    if post.date("datereported") is None:
        raise utils.ASMValidationError(_("Date reported cannot be blank", l))
    if post.integer("owner") == 0:
        raise utils.ASMValidationError(
            _("Found animals must have a contact", l))

    nid = db.get_id(dbo, "animalfound")
    db.execute(
        dbo,
        db.make_insert_user_sql(
            dbo, "animalfound", username,
            (("ID", db.di(nid)), ("AnimalTypeID", post.db_integer("species")),
             ("DateReported", post.db_date("datereported")),
             ("ReturnToOwnerDate", post.db_date("returntoownerdate")),
             ("DateFound", post.db_date("datefound")),
             ("Sex", post.db_integer("sex")),
             ("BreedID", post.db_integer("breed")),
             ("AgeGroup", post.db_string("agegroup")),
             ("BaseColourID", post.db_integer("colour")),
             ("DistFeat", post.db_string("markings")),
             ("AreaFound", post.db_string("areafound")),
             ("AreaPostcode", post.db_string("areapostcode")),
             ("OwnerID", post.db_integer("owner")),
             ("Comments", post.db_string("comments")))))
    audit.create(dbo, username, "animalfound", str(nid))
    return nid
Пример #2
0
def insert_foundanimal_from_form(dbo, post, username):
    """
    Inserts a new found animal record from the screen
    data: The webpy data object containing form parameters
    """
    l = dbo.locale
    if post.date("datefound") is None:
        raise utils.ASMValidationError(_("Date found cannot be blank", l))
    if post.date("datereported") is None:
        raise utils.ASMValidationError(_("Date reported cannot be blank", l))
    if post.integer("owner") == 0:
        raise utils.ASMValidationError(_("Found animals must have a contact", l))

    nid = dbo.insert("animalfound", {
        "AnimalTypeID":     post.integer("species"),
        "DateReported":     post.date("datereported"),
        "ReturnToOwnerDate": post.date("returntoownerdate"),
        "DateFound":        post.date("datefound"),
        "Sex":              post.integer("sex"),
        "BreedID":          post.integer("breed"),
        "AgeGroup":         post["agegroup"],
        "BaseColourID":     post.integer("colour"),
        "DistFeat":         post["markings"],
        "AreaFound":        post["areafound"],
        "AreaPostcode":     post["areapostcode"],
        "OwnerID":          post.integer("owner"),
        "Comments":         post["comments"]
    }, username)

    # Save any additional field values given
    additional.save_values_for_link(dbo, post, nid, "foundanimal", True)

    return nid
Пример #3
0
def insert_foster_from_form(dbo, username, post):
    """
    Inserts a movement from the workflow foster an animal screen.
    Returns the new movement id
    """
    # Validate that we have a movement date before doing anthing
    l = dbo.locale
    if None is post.date("fosterdate"):
        raise utils.ASMValidationError(i18n._("Foster movements must have a valid foster date.", l))
    # Is this animal already on foster? If so, return that foster first
    fm = get_animal_movements(dbo, post.integer("animal"))
    for m in fm:
        if m.MOVEMENTTYPE == FOSTER and m.RETURNDATE is None:
            # if the existing foster is to this person, bail
            if m.OWNERID == post.integer("person"):
                raise utils.ASMValidationError(i18n._("Already fostered to this person.", l))
            else:
                return_movement(dbo, m.ID, post.integer("animal"), post.date("fosterdate"))
    # Create the foster movement
    move_dict = {
        "person"                : post["person"],
        "animal"                : post["animal"],
        "movementdate"          : post["fosterdate"],
        "permanentfoster"       : post["permanentfoster"],
        "adoptionno"            : post["movementnumber"],
        "returndate"            : post["returndate"],
        "type"                  : str(FOSTER),
        "donation"              : post["amount"],
        "returncategory"        : configuration.default_return_reason(dbo)
    }
    movementid = insert_movement_from_form(dbo, username, utils.PostedData(move_dict, l))
    return movementid
Пример #4
0
def update_foundanimal_from_form(dbo, post, username):
    """
    Updates a found animal record from the screen
    post: The webpy data object containing form parameters
    """
    l = dbo.locale
    lfid = post.integer("id")

    if not dbo.optimistic_check("animalfound", post.integer("id"), post.integer("recordversion")):
        raise utils.ASMValidationError(_("This record has been changed by another user, please reload.", l))

    if post.date("datefound") is None:
        raise utils.ASMValidationError(_("Date found cannot be blank", l))
    if post.date("datereported") is None:
        raise utils.ASMValidationError(_("Date reported cannot be blank", l))
    if post.integer("owner") == 0:
        raise utils.ASMValidationError(_("Found animals must have a contact", l))

    dbo.update("animalfound", lfid, {
        "AnimalTypeID":     post.integer("species"),
        "DateReported":     post.date("datereported"),
        "ReturnToOwnerDate": post.date("returntoownerdate"),
        "DateFound":        post.date("datefound"),
        "Sex":              post.integer("sex"),
        "BreedID":          post.integer("breed"),
        "AgeGroup":         post["agegroup"],
        "BaseColourID":     post.integer("colour"),
        "DistFeat":         post["markings"],
        "AreaFound":        post["areafound"],
        "AreaPostcode":     post["areapostcode"],
        "OwnerID":          post.integer("owner"),
        "Comments":         post["comments"]
    }, username)
    additional.save_values_for_link(dbo, post, lfid, "foundanimal")
Пример #5
0
def insert_stocklevel_from_form(dbo, post, username):
    """
    Inserts a stocklevel item from a dialog.
    A usage record will be written, so usage data should be sent too.
    """
    l = dbo.locale
    if post["name"] == "":
        raise utils.ASMValidationError(_("Stock level must have a name", l))
    if post["unitname"] == "":
        raise utils.ASMValidationError(_("Stock level must have a unit", l))

    nid = dbo.insert("stocklevel", {
        "Name": post["name"],
        "Description": post["description"],
        "StockLocationID": post.integer("location"),
        "UnitName": post["unitname"],
        "Total": post.floating("total"),
        "Balance": post.floating("balance"),
        "Expiry": post.date("expiry"),
        "BatchNumber": post["batchnumber"],
        "Cost": post.integer("cost"),
        "UnitPrice": post.integer("unitprice"),
        "CreatedDate": dbo.now()
    },
                     username,
                     setCreated=False,
                     setRecordVersion=False)

    insert_stockusage(dbo, username, nid, post.floating("balance"),
                      post.date("usagedate"), post.integer("usagetype"),
                      post["comments"])
    return nid
Пример #6
0
def sign_document(dbo, username, mid, sigurl, signdate):
    """
    Signs an HTML document.
    sigurl: An HTML5 data: URL containing an image of the signature
    """
    al.debug("signing document %s for %s" % (mid, username), "media.sign_document", dbo)
    SIG_PLACEHOLDER = "signature:placeholder"
    date, medianame, mimetype, content = get_media_file_data(dbo, mid)
    # Is this an HTML document?
    if content.find("<p") == -1 and content.find("<td") == -1:
        al.error("document %s is not HTML" % mid, "media.sign_document", dbo)
        raise utils.ASMValidationError("Cannot sign a non-HTML document")
    # Has this document already been signed? 
    if 0 != dbo.query_int("SELECT COUNT(*) FROM media WHERE ID = ? AND SignatureHash Is Not Null AND SignatureHash <> ''", [mid]):
        al.error("document %s has already been signed" % mid, "media.sign_document", dbo)
        raise utils.ASMValidationError("Document is already signed")
    # Does the document have a signing placeholder image? If so, replace it
    if content.find(SIG_PLACEHOLDER) != -1:
        al.debug("document %s: found signature placeholder" % mid, "media.sign_document", dbo)
        content = content.replace(SIG_PLACEHOLDER, sigurl)
    else:
        # Create the signature at the foot of the document
        al.debug("document %s: no placeholder, appending" % mid, "media.sign_document", dbo)
        sig = "<hr />\n"
        sig += '<p><img src="' + sigurl + '" /></p>\n'
        sig += "<p>%s</p>\n" % signdate
        content += sig
    # Create a hash of the contents and store it with the media record
    dbo.update("media", mid, { "SignatureHash": utils.md5_hash(content) })
    # Update the dbfs contents
    update_file_content(dbo, username, mid, content)
Пример #7
0
def update_transport_from_form(dbo, username, post):
    """
    Updates a movement record from posted form data
    """
    l = dbo.locale
    if post.integer("animal") == 0:
        raise utils.ASMValidationError(i18n._("Transport requires an animal", l))
    if None is post.date("pickupdate") or None is post.date("dropoffdate"):
        raise utils.ASMValidationError(i18n._("Transports must have valid pickup and dropoff dates and times.", l))
    transportid = post.integer("transportid")

    dbo.update("animaltransport", transportid, {
        "AnimalID":             post.integer("animal"),
        "TransportTypeID":      post.integer("type"),
        "DriverOwnerID":        post.integer("driver"),
        "PickupOwnerID":        post.integer("pickup"),
        "PickupAddress":        post["pickupaddress"],
        "PickupTown":           post["pickuptown"],
        "PickupCounty":         post["pickupcounty"],
        "PickupPostcode":       post["pickuppostcode"],
        "PickupDateTime":       post.datetime("pickupdate", "pickuptime"),
        "DropoffOwnerID":       post.integer("dropoff"),
        "DropoffAddress":       post["dropoffaddress"],
        "DropoffTown":          post["dropofftown"],
        "DropoffCounty":        post["dropoffcounty"],
        "DropoffPostcode":      post["dropoffpostcode"],
        "DropoffDateTime":      post.datetime("dropoffdate", "dropofftime"),
        "Status":               post.integer("status"),
        "Miles":                post.integer("miles"),
        "Cost":                 post.integer("cost"),
        "CostPaidDate":         post.date("costpaid"),
        "Comments":             post["comments"]
    }, username)
Пример #8
0
def insert_reserve_for_animal_name(dbo, username, personid, animalname):
    """
    Creates a reservation for the animal with animalname to personid.
    animalname can either be just the name of a shelter animal, or it
    can be in the form name::code. If a code is present, that will be
    used to locate the animal.
    If the person is banned from adopting animals, an exception is raised.
    """
    l = dbo.locale
    if animalname.find("::") != -1:
        animalcode = animalname.split("::")[1]
        aid = dbo.query_int("SELECT ID FROM animal WHERE ShelterCode = ? ORDER BY ID DESC", [animalcode])
    else:
        aid = dbo.query_int("SELECT ID FROM animal WHERE LOWER(AnimalName) LIKE ? ORDER BY ID DESC", [animalname.lower()])
    if 1 == dbo.query_int("SELECT IsBanned FROM owner WHERE ID=?", [personid]):
        raise utils.ASMValidationError("owner %s is banned from adopting animals - not creating reserve")
    if aid == 0: 
        raise utils.ASMValidationError("could not find an animal for '%s' - not creating reserve" % animalname)
    move_dict = {
        "person"                : str(personid),
        "animal"                : str(aid),
        "reservationdate"       : i18n.python2display(l, dbo.today()),
        "reservationstatus"     : configuration.default_reservation_status(dbo),
        "movementdate"          : "",
        "type"                  : str(NO_MOVEMENT),
        "returncategory"        : configuration.default_return_reason(dbo)
    }
    return insert_movement_from_form(dbo, username, utils.PostedData(move_dict, l))
Пример #9
0
def insert_waitinglist_from_form(dbo, post, username):
    """
    Creates a waiting list record from the screen
    data: The webpy data object containing form parameters
    """
    l = dbo.locale
    if post["description"] == "":
        raise utils.ASMValidationError(_("Description cannot be blank", l))
    if post.integer("owner") == 0:
        raise utils.ASMValidationError(
            _("Waiting list entries must have a contact", l))
    if post["dateputon"] == "":
        raise utils.ASMValidationError(_("Date put on cannot be blank", l))

    nwlid = dbo.insert(
        "animalwaitinglist", {
            "SpeciesID":
            post.integer("species"),
            "Size":
            post.integer("size"),
            "DatePutOnList":
            post.date("dateputon"),
            "OwnerID":
            post.integer("owner"),
            "AnimalDescription":
            post["description"],
            "ReasonForWantingToPart":
            post["reasonforwantingtopart"],
            "CanAffordDonation":
            post.boolean("canafforddonation"),
            "Urgency":
            post.integer("urgency"),
            "DateRemovedFromList":
            post.date("dateremoved"),
            "AutoRemovePolicy":
            post.integer("autoremovepolicy"),
            "DateOfLastOwnerContact":
            post.date("dateoflastownercontact"),
            "ReasonForRemoval":
            post["reasonforremoval"],
            "Comments":
            post["comments"],
            "UrgencyLastUpdatedDate":
            dbo.today(),
            "UrgencyUpdateDate":
            dbo.today(
                offset=configuration.waiting_list_urgency_update_period(dbo))
        }, username)

    # Save any additional field values given
    additional.save_values_for_link(dbo, post, nwlid, "waitinglist", True)

    return nwlid
Пример #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)
Пример #11
0
def update_appointment_from_form(dbo, username, post):
    """
    Updates an appointment from form data
    """
    l = dbo.locale
    if post.datetime("apptdate", "appttime") is None:
        raise utils.ASMValidationError(
            i18n._("Appointment date must be a valid date", l))

    dbo.update(
        "clinicappointment", post.integer("appointmentid"), {
            "AnimalID": post.integer("animal"),
            "OwnerID": post.integer("person"),
            "ApptFor": post["for"],
            "DateTime": post.datetime("apptdate", "appttime"),
            "Status": post.integer("status"),
            "ArrivedDateTime": post.datetime("arriveddate", "arrivedtime"),
            "WithVetDateTime": post.datetime("withvetdate", "withvettime"),
            "CompletedDateTime": post.datetime("completedate", "completetime"),
            "ReasonForAppointment": post["reason"],
            "Comments": post["comments"],
            "Amount": post.integer("amount"),
            "IsVAT": post.boolean("vat"),
            "VATRate": post.floating("vatrate"),
            "VATAmount": post.integer("vatamount")
        }, username)
Пример #12
0
def create_document_template(dbo,
                             username,
                             name,
                             ext=".html",
                             content="<p></p>"):
    """
    Creates a document template from the name given.
    If there's no extension, adds it
    If it's a relative path (doesn't start with /) adds /templates/ to the front
    If it's an absolute path that doesn't start with /templates/, add /templates
    Changes spaces and unwanted punctuation to underscores
    """
    filepath = name
    if not filepath.endswith(ext): filepath += ext
    if not filepath.startswith("/"): filepath = "/templates/" + filepath
    if not filepath.startswith("/templates"):
        filepath = "/templates" + filepath
    filepath = sanitise_path(filepath)
    name = filepath[filepath.rfind("/") + 1:]
    path = filepath[:filepath.rfind("/")]

    if 0 != dbo.query_int(
            "SELECT COUNT(*) FROM templatedocument WHERE Name = ? AND Path = ?",
        (name, path)):
        raise utils.ASMValidationError("%s already exists" % filepath)

    dtid = dbo.insert("templatedocument", {
        "Name": name,
        "Path": path,
        "Content": base64.b64encode(content)
    })
    audit.create(dbo, username, "templatedocument", dtid,
                 "id: %d, name: %s" % (dtid, name))
    return dtid
Пример #13
0
def create_animalcontrol(dbo, username, collationid):
    """
    Creates a animal control/incident record from the incoming form data with 
    collationid.
    Also, attaches the form to the incident as media.
    """
    l = dbo.locale
    fields = get_onlineformincoming_detail(dbo, collationid)
    d = {}
    d["incidentdate"] = i18n.python2display(l, i18n.now(dbo.timezone))
    d["incidenttime"] = i18n.format_time_now(dbo.timezone)
    d["calldate"] = d["incidentdate"]
    d["calltime"] = d["incidenttime"]
    d["incidenttype"] = 1
    for f in fields:
        if f["FIELDNAME"] == "callnotes": d["callnotes"] = f["VALUE"]
        if f["FIELDNAME"] == "dispatchaddress": d["dispatchaddress"] = f["VALUE"]
        if f["FIELDNAME"] == "dispatchcity": d["dispatchtown"] = f["VALUE"]
        if f["FIELDNAME"] == "dispatchstate": d["dispatchcounty"] = f["VALUE"]
        if f["FIELDNAME"] == "dispatchzipcode": d["dispatchpostcode"] = f["VALUE"]
    # Have we got enough info to create the animal control record? We need notes and dispatchaddress
    if not d.has_key("callnotes") or not d.has_key("dispatchaddress"):
        raise utils.ASMValidationError(i18n._("There is not enough information in the form to create an incident record (need call notes and dispatch address).", l))
    # We need the person/caller record before we create the incident
    collationid, personid, personname = create_person(dbo, username, collationid)
    d["caller"] = personid
    # Create the incident 
    incidentid = animalcontrol.insert_animalcontrol_from_form(dbo, utils.PostedData(d, dbo.locale), username)
    # Attach the form to the incident
    formname = get_onlineformincoming_name(dbo, collationid)
    formhtml = get_onlineformincoming_html(dbo, collationid)
    media.create_document_media(dbo, username, media.ANIMALCONTROL, incidentid, formname, formhtml )
    return (collationid, incidentid, utils.padleft(incidentid, 6) + " - " + personname)
Пример #14
0
def insert_user_from_form(dbo, username, post):
    """
    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.
    """
    # Verify the username is unique
    l = dbo.locale
    if 0 != dbo.query_int("SELECT COUNT(*) FROM users WHERE LOWER(UserName) LIKE LOWER(?)", [post["username"]]):
        raise utils.ASMValidationError(i18n._("Username '{0}' already exists", l).format(post["username"]))

    nuserid = dbo.insert("users", {
        "UserName":             post["username"],
        "RealName":             post["realname"],
        "EmailAddress":         post["email"],
        "Password":             hash_password(post["password"]),
        "SuperUser":            post.integer("superuser"),
        "DisableLogin":         post.integer("disablelogin"),
        "RecordVersion":        0,
        "SecurityMap":          "dummy",
        "OwnerID":              post.integer("person"),
        "SiteID":               post.integer("site"),
        "LocationFilter":       post["locationfilter"],
        "IPRestriction":        post["iprestriction"]
    }, username, setCreated=False)

    dbo.delete("userrole", "UserID=%d" % nuserid)
    roles = post["roles"].strip()
    if roles != "":
        for rid in roles.split(","):
            if rid.strip() != "":
                dbo.insert("userrole", { "UserID": nuserid, "RoleID": rid }, generateID=False)
    return nuserid
Пример #15
0
def update_test_from_form(dbo, username, data):
    """
    Updates a test record from posted form data
    """
    l = dbo.locale
    testid = utils.df_ki(data, "testid")
    if utils.df_kd(data, "required", l) is None:
        raise utils.ASMValidationError(
            _("Required date must be a valid date", l))

    sql = db.make_update_user_sql(
        dbo, "animaltest", username, "ID=%d" % testid,
        (("AnimalID", db.di(utils.df_ki(data, "animal"))),
         ("TestTypeID", utils.df_s(data, "type")),
         ("TestResultID", utils.df_s(data, "result")),
         ("DateOfTest", utils.df_d(data, "given", l)),
         ("DateRequired", utils.df_d(data, "required", l)),
         ("Cost", utils.df_m(data, "cost", l)),
         ("Comments", utils.df_t(data, "comments"))))
    preaudit = db.query(dbo, "SELECT * FROM animaltest WHERE ID = %d" % testid)
    db.execute(dbo, sql)
    postaudit = db.query(dbo,
                         "SELECT * FROM animaltest WHERE ID = %d" % testid)
    audit.edit(dbo, username, "animaltest",
               audit.map_diff(preaudit, postaudit))
    # ASM2_COMPATIBILITY
    update_asm2_tests(dbo, testid)
Пример #16
0
def insert_reserve_from_form(dbo, username, post):
    """
    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 is post.date("reservationdate"):
        raise utils.ASMValidationError(i18n._("Reservations must have a valid reservation date.", l))

    # Do the movement itself first
    move_dict = {
        "person"                : post["person"],
        "animal"                : post["animal"],
        "reservationdate"       : post["reservationdate"],
        "reservationstatus"     : post["reservationstatus"],
        "adoptionno"            : post["movementnumber"],
        "movementdate"          : "",
        "type"                  : str(NO_MOVEMENT),
        "donation"              : post["amount"],
        "returncategory"        : configuration.default_return_reason(dbo)
    }
    movementid = insert_movement_from_form(dbo, username, utils.PostedData(move_dict, l))
    # Create any payments
    financial.insert_donations_from_form(dbo, username, post, post["reservationdate"], False, post["person"], post["animal"], movementid) 
    return movementid
Пример #17
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"))
Пример #18
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
Пример #19
0
def update_vaccination_from_form(dbo, username, data):
    """
    Updates a vaccination record from posted form data
    """
    l = dbo.locale
    vaccid = utils.df_ki(data, "vaccid")
    if utils.df_kd(data, "required", l) is None:
        raise utils.ASMValidationError(
            _("Required date must be a valid date", l))

    sql = db.make_update_user_sql(
        dbo, "animalvaccination", username, "ID=%d" % vaccid,
        (("AnimalID", db.di(utils.df_ki(data, "animal"))),
         ("VaccinationID", utils.df_s(data, "type")),
         ("DateOfVaccination", utils.df_d(data, "given", l)),
         ("DateRequired", utils.df_d(data, "required", l)),
         ("Cost", utils.df_m(data, "cost", l)),
         ("Comments", utils.df_t(data, "comments"))))
    preaudit = db.query(
        dbo, "SELECT * FROM animalvaccination WHERE ID = %d" % vaccid)
    db.execute(dbo, sql)
    postaudit = db.query(
        dbo, "SELECT * FROM animalvaccination WHERE ID = %d" % vaccid)
    audit.edit(dbo, username, "animalvaccination",
               audit.map_diff(preaudit, postaudit))
Пример #20
0
def insert_transfer_from_form(dbo, username, post):
    """
    Inserts a movement from the workflow transfer an animal screen.
    Returns the new movement id
    """
    # Validate that we have a movement date before doing anthing
    l = dbo.locale
    if None == post.date("transferdate"):
        raise utils.ASMValidationError(
            i18n._("Transfers must have a valid transfer date.", l))

    # Is this animal already on foster? If so, return that foster first
    fm = get_animal_movements(dbo, post.integer("animal"))
    for m in fm:
        if m["MOVEMENTTYPE"] == FOSTER and m["RETURNDATE"] is None:
            return_movement(dbo, m["ID"], post.integer("animal"),
                            post.date("transferdate"))
    # Create the transfer movement
    move_dict = {
        "person": post["person"],
        "animal": post["animal"],
        "adoptionno": post["movementnumber"],
        "movementdate": post["transferdate"],
        "type": str(TRANSFER),
        "donation": post["amount"],
        "returncategory": configuration.default_return_reason(dbo)
    }
    movementid = insert_movement_from_form(dbo, username,
                                           utils.PostedData(move_dict, l))
    return movementid
Пример #21
0
def insert_animalcontrol_from_form(dbo, post, username, geocode=True):
    """
    Inserts a new animal control incident record from the screen
    data: The webpy data object containing form parameters
    """
    l = dbo.locale
    if post.date("incidentdate") is None:
        raise utils.ASMValidationError(_("Incident date cannot be blank", l))

    nid = dbo.insert(
        "animalcontrol", {
            "IncidentDateTime": post.datetime("incidentdate", "incidenttime"),
            "IncidentTypeID": post.integer("incidenttype"),
            "CallDateTime": post.datetime("calldate", "calltime"),
            "CallNotes": post["callnotes"],
            "CallTaker": post["calltaker"],
            "CallerID": post.integer("caller"),
            "VictimID": post.integer("victim"),
            "DispatchAddress": post["dispatchaddress"],
            "DispatchTown": post["dispatchtown"],
            "DispatchCounty": post["dispatchcounty"],
            "DispatchPostcode": post["dispatchpostcode"],
            "JurisdictionID": post.integer("jurisdiction"),
            "PickupLocationID": post.integer("pickuplocation"),
            "DispatchLatLong": post["dispatchlatlong"],
            "DispatchedACO": post["dispatchedaco"],
            "DispatchDateTime": post.datetime("dispatchdate", "dispatchtime"),
            "RespondedDateTime": post.datetime("respondeddate",
                                               "respondedtime"),
            "FollowupDateTime": post.datetime("followupdate", "followuptime"),
            "FollowupComplete": post.boolean("followupcomplete"),
            "FollowupDateTime2": post.datetime("followupdate2",
                                               "followuptime2"),
            "FollowupComplete2": post.boolean("followupcomplete2"),
            "FollowupDateTime3": post.datetime("followupdate3",
                                               "followuptime3"),
            "FollowupComplete3": post.boolean("followupcomplete3"),
            "CompletedDate": post.date("completeddate"),
            "IncidentCompletedID": post.integer("completedtype"),
            "SiteID": post.integer("site"),
            "OwnerID": post.integer("owner"),
            "Owner2ID": post.integer("owner2"),
            "Owner3ID": post.integer("owner3"),
            "AnimalDescription": post["animaldescription"],
            "SpeciesID": post.integer("species"),
            "Sex": post.integer("sex"),
            "AgeGroup": post["agegroup"]
        }, username)

    additional.save_values_for_link(dbo, post, nid, "incident", True)
    update_animalcontrol_roles(dbo, nid, post.integer_list("viewroles"),
                               post.integer_list("editroles"))

    # Look up a geocode for the dispatch address
    if geocode:
        update_dispatch_geocode(dbo, nid, "", post["dispatchaddress"],
                                post["dispatchtown"], post["dispatchcounty"],
                                post["dispatchpostcode"])

    return nid
Пример #22
0
def update_account_from_form(dbo, username, post):
    """
    Updates an account from posted form data
    """
    l = dbo.locale
    accountid = post.integer("accountid")
    if post["code"] == "":
        raise utils.ASMValidationError(
            i18n._("Account code cannot be blank.", l))
    if 0 != db.query_int(
            dbo,
            "SELECT COUNT(*) FROM accounts WHERE Code Like '%s' AND ID <> %d" %
        (post["code"], accountid)):
        raise utils.ASMValidationError(
            i18n._("Account code '{0}' has already been used.",
                   l).format(post["code"]))

    sql = db.make_update_user_sql(
        dbo, "accounts", username, "ID=%d" % accountid,
        (("Code", post.db_string("code")),
         ("AccountType", post.db_integer("type")),
         ("DonationTypeID", post.db_integer("donationtype")),
         ("Description", post.db_string("description"))))
    preaudit = db.query(dbo,
                        "SELECT * FROM accounts WHERE ID = %d" % accountid)
    db.execute(dbo, sql)
    postaudit = db.query(dbo,
                         "SELECT * FROM accounts WHERE ID = %d" % accountid)
    audit.edit(dbo, username, "accounts", audit.map_diff(preaudit, postaudit))
    db.execute(dbo,
               "DELETE FROM accountsrole WHERE AccountID = %d" % accountid)
    for rid in post.integer_list("viewroles"):
        db.execute(
            dbo,
            "INSERT INTO accountsrole (AccountID, RoleID, CanView, CanEdit) VALUES (%d, %d, 1, 0)"
            % (accountid, rid))
    for rid in post.integer_list("editroles"):
        if rid in post.integer_list("viewroles"):
            db.execute(
                dbo,
                "UPDATE accountsrole SET CanEdit = 1 WHERE AccountID = %d AND RoleID = %d"
                % (accountid, rid))
        else:
            db.execute(
                dbo,
                "INSERT INTO accountsrole (AccountID, RoleID, CanView, CanEdit) VALUES (%d, %d, 0, 1)"
                % (accountid, rid))
Пример #23
0
def delete_lookup(dbo, lookup, iid):
    l = dbo.locale
    t = LOOKUP_TABLES[lookup]
    for fv in t[LOOKUP_FOREIGNKEYS]:
        table, field = fv.split(".")
        if 0 < db.query_int(dbo, "SELECT COUNT(*) FROM %s WHERE %s = %s" % (table, field, str(iid))):
            raise utils.ASMValidationError(_("This item is referred to in the database ({0}) and cannot be deleted until it is no longer in use.", l).format(fv))
    db.execute(dbo, "DELETE FROM %s WHERE ID = %s" % (lookup, str(iid)))
Пример #24
0
def change_password(dbo, username, oldpassword, newpassword):
    """
    Changes the password for a user
    """
    l = dbo.locale
    if None is authenticate(dbo, username, oldpassword):
        raise utils.ASMValidationError(i18n._("Password is incorrect.", l))
    dbo.execute("UPDATE users SET Password = ? WHERE UserName LIKE ?", (hash_password(newpassword), username))
Пример #25
0
def merge_person(dbo, username, personid, mergepersonid):
    """
    Reparents all satellite records of mergepersonid onto
    personid and then deletes it.
    """
    l = dbo.locale
    if personid == mergepersonid:
        raise utils.ASMValidationError(
            _(
                "The person record to merge must be different from the original.",
                l))
    if personid == 0 or mergepersonid == 0:
        raise utils.ASMValidationError("Internal error: Cannot merge ID 0")

    def reparent(table, field, linktypefield="", linktype=-1):
        if linktype >= 0:
            db.execute(
                dbo, "UPDATE %s SET %s = %d WHERE %s = %d AND %s = %d" %
                (table, field, personid, field, mergepersonid, linktypefield,
                 linktype))
        else:
            db.execute(
                dbo, "UPDATE %s SET %s = %d WHERE %s = %d" %
                (table, field, personid, field, mergepersonid))

    reparent("adoption", "OwnerID")
    reparent("adoption", "RetailerID")
    reparent("animal", "OriginalOwnerID")
    reparent("animal", "BroughtInByOwnerID")
    reparent("animal", "OwnersVetID")
    reparent("animal", "CurrentVetID")
    reparent("animallost", "OwnerID")
    reparent("animalfound", "OwnerID")
    reparent("animalwaitinglist", "OwnerID")
    reparent("ownerdonation", "OwnerID")
    reparent("ownervoucher", "OwnerID")
    reparent("users", "OwnerID")
    reparent("media", "LinkID", "LinkTypeID", media.PERSON)
    reparent("diary", "LinkID", "LinkType", diary.PERSON)
    reparent("log", "LinkID", "LinkType", log.PERSON)
    audit.delete(
        dbo, username, "owner",
        str(db.query(dbo, "SELECT * FROM owner WHERE ID=%d" % mergepersonid)))
    db.execute(dbo, "DELETE FROM owner WHERE ID = %d" % mergepersonid)
Пример #26
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"]))