def save_values_for_link(dbo, post, 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 post.has_key(key):
            val = post[key]
            if f["FIELDTYPE"] == YESNO:
                val = str(post.boolean(key))
            elif f["FIELDTYPE"] == MONEY:
                val = str(post.integer(key))
            elif f["FIELDTYPE"] == DATE:
                if len(val.strip()) > 0 and post.date(key) == None:
                    raise utils.ASMValidationError(
                        _(
                            "Additional date field '{0}' contains an invalid date.",
                            l).format(f["FIELDNAME"]))
                val = python2display(dbo.locale, post.date(key))
            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())
Beispiel #2
0
def update_trx_from_form(dbo, username, post):
    """
    Updates a transaction from posted form data
    """
    l = dbo.locale
    amount = 0
    source = 0
    target = 0
    deposit = post.money("deposit")
    withdrawal = post.money("withdrawal")
    account = post.integer("accountid")
    trxid = post.integer("trxid")
    other = get_account_id(dbo, post["otheraccount"])
    if other == 0:
        raise utils.ASMValidationError(i18n._("Account code '{0}' is not valid.", l).format(post["otheraccount"]))
    if deposit > 0:
        amount = deposit
        source = other
        target = account
    else:
        amount = withdrawal
        source = account
        target = other
    sql = db.make_update_user_sql(dbo, "accountstrx", username, "ID=%d" % trxid, (
        ( "TrxDate", post.db_date("trxdate")),
        ( "Description", post.db_string("description")),
        ( "Reconciled", post.db_integer("reconciled")),
        ( "Amount", db.di(amount)),
        ( "SourceAccountID", db.di(source)),
        ( "DestinationAccountID", db.di(target))
        ))
    preaudit = db.query(dbo, "SELECT * FROM accountstrx WHERE ID = %d" % trxid)
    db.execute(dbo, sql)
    postaudit = db.query(dbo, "SELECT * FROM accountstrx WHERE ID = %d" % trxid)
    audit.edit(dbo, username, "accountstrx", audit.map_diff(preaudit, postaudit))
Beispiel #3
0
def reschedule_vaccination(dbo, username, vaccinationid, newdays):
    """
    Marks a vaccination completed today (if it's not already completed) 
    and reschedules it for given + newdays onwards.
    """
    av = db.query(
        dbo, "SELECT * FROM animalvaccination WHERE ID = %d" %
        int(vaccinationid))[0]
    given = av["DATEOFVACCINATION"]
    if given is None:
        given = now(dbo.timezone)
        db.execute(
            dbo,
            "UPDATE animalvaccination SET DateOfVaccination = %s WHERE ID = %d"
            % (db.dd(now(dbo.timezone)), int(vaccinationid)))
        audit.edit(dbo, username, "animalvaccination",
                   str(vaccinationid) + " => given")

    nvaccid = db.get_id(dbo, "animalvaccination")
    db.execute(
        dbo,
        db.make_insert_user_sql(
            dbo, "animalvaccination", username,
            (("ID", db.di(nvaccid)), ("AnimalID", db.di(av["ANIMALID"])),
             ("VaccinationID", db.di(av["VACCINATIONID"])),
             ("DateOfVaccination", db.dd(None)),
             ("DateRequired", db.dd(add_days(given, int(newdays)))),
             ("Cost", db.di(av["COST"])),
             ("Comments", db.ds(av["COMMENTS"])))))

    audit.create(dbo, username, "animalvaccination", str(nvaccid))
Beispiel #4
0
def insert_donation_from_form(dbo, username, data):
    """
    Creates a donation record from posted form data 
    """
    l = dbo.locale
    donationid = db.get_id(dbo, "ownerdonation")
    sql = db.make_insert_user_sql(dbo, "ownerdonation", username, ( 
        ( "ID", db.di(donationid)),
        ( "OwnerID", db.di(utils.df_ki(data, "person"))),
        ( "AnimalID", db.di(utils.df_ki(data, "animal"))),
        ( "MovementID", db.di(utils.df_ki(data, "movement"))),
        ( "DonationTypeID", utils.df_s(data, "type")),
        ( "DonationPaymentID", utils.df_s(data, "payment")),
        ( "Frequency", utils.df_s(data, "frequency")),
        ( "Donation", utils.df_m(data, "amount", l)),
        ( "DateDue", utils.df_d(data, "due", l)),
        ( "Date", utils.df_d(data, "received", l)),
        ( "NextCreated", db.di(0)),
        ( "IsGiftAid", utils.df_s(data, "giftaid")),
        ( "Comments", utils.df_t(data, "comments"))
        ))
    db.execute(dbo, sql)
    audit.create(dbo, username, "ownerdonation", str(donationid))
    update_matching_transaction(dbo, username, donationid)
    check_create_next_donation(dbo, username, donationid)
    movement.update_movement_donation(dbo, utils.df_ki(data, "movement"))
    return donationid
Beispiel #5
0
def insert_trx_from_form(dbo, username, post):
    """
    Creates a transaction from posted form data
    """
    l = dbo.locale
    amount = 0
    source = 0
    target = 0
    deposit = post.money("deposit")
    withdrawal = post.money("withdrawal")
    account = post.integer("accountid")
    other = get_account_id(dbo, post["otheraccount"])
    if other == 0:
        raise utils.ASMValidationError(i18n._("Account code '{0}' is not valid.", l).format(post["otheraccount"]))
    if deposit > 0:
        amount = deposit
        source = other
        target = account
    else:
        amount = withdrawal
        source = account
        target = other
    tid = db.get_id(dbo, "accountstrx")
    sql = db.make_insert_user_sql(dbo, "accountstrx", username, (
        ( "ID", db.di(tid) ),
        ( "TrxDate", post.db_date("trxdate")),
        ( "Description", post.db_string("description")),
        ( "Reconciled", post.db_boolean("reconciled")),
        ( "Amount", db.di(amount)),
        ( "SourceAccountID", db.di(source)),
        ( "DestinationAccountID", db.di(target)),
        ( "OwnerDonationID", db.di(0))
        ))
    db.execute(dbo, sql)
    audit.create(dbo, username, "accountstrx", str(tid) + ": " + post["description"])
Beispiel #6
0
def update_donation_from_form(dbo, username, data):
    """
    Updates a donation record from posted form data
    """
    l = dbo.locale
    donationid = utils.df_ki(data, "donationid")
    sql = db.make_update_user_sql(dbo, "ownerdonation", username, "ID=%d" % donationid, ( 
        ( "OwnerID", db.di(utils.df_ki(data, "person"))),
        ( "AnimalID", db.di(utils.df_ki(data, "animal"))),
        ( "MovementID", db.di(utils.df_ki(data, "movement"))),
        ( "DonationTypeID", utils.df_s(data, "type")),
        ( "DonationPaymentID", utils.df_s(data, "payment")),
        ( "Frequency", utils.df_s(data, "frequency")),
        ( "Donation", utils.df_m(data, "amount", l)),
        ( "DateDue", utils.df_d(data, "due", l)),
        ( "Date", utils.df_d(data, "received", l)),
        ( "IsGiftAid", utils.df_s(data, "giftaid")),
        ( "Comments", utils.df_t(data, "comments"))
        ))
    preaudit = db.query(dbo, "SELECT * FROM ownerdonation WHERE ID = %d" % donationid)
    db.execute(dbo, sql)
    postaudit = db.query(dbo, "SELECT * FROM ownerdonation WHERE ID = %d" % donationid)
    audit.edit(dbo, username, "ownerdonation", audit.map_diff(preaudit, postaudit))
    update_matching_transaction(dbo, username, donationid)
    check_create_next_donation(dbo, username, donationid)
    movement.update_movement_donation(dbo, utils.df_ki(data, "movement"))
Beispiel #7
0
def insert_donation_from_form(dbo, username, data):
    """
    Creates a donation record from posted form data 
    """
    l = dbo.locale
    donationid = db.get_id(dbo, "ownerdonation")
    sql = db.make_insert_user_sql(
        dbo, "ownerdonation", username,
        (("ID", db.di(donationid)),
         ("OwnerID", db.di(utils.df_ki(data, "person"))),
         ("AnimalID", db.di(utils.df_ki(data, "animal"))),
         ("MovementID", db.di(utils.df_ki(data, "movement"))),
         ("DonationTypeID", utils.df_s(data, "type")),
         ("DonationPaymentID", utils.df_s(data, "payment")),
         ("Frequency", utils.df_s(data, "frequency")),
         ("Donation", utils.df_m(data, "amount", l)),
         ("DateDue", utils.df_d(data, "due", l)),
         ("Date", utils.df_d(data, "received", l)), ("NextCreated", db.di(0)),
         ("IsGiftAid", utils.df_s(data, "giftaid")),
         ("Comments", utils.df_t(data, "comments"))))
    db.execute(dbo, sql)
    audit.create(dbo, username, "ownerdonation", str(donationid))
    update_matching_transaction(dbo, username, donationid)
    check_create_next_donation(dbo, username, donationid)
    movement.update_movement_donation(dbo, utils.df_ki(data, "movement"))
    return donationid
Beispiel #8
0
def create_document_media(dbo, username, linktype, linkid, template, content):
    """
    Creates a new media record for a document for the link given.
    linktype: ANIMAL, PERSON, etc
    linkid: ID for the link
    template: The name of the template used to create the document
    content: The document contents
    """
    mediaid = db.get_id(dbo, "media")
    sql = db.make_insert_sql(
        "media",
        (("ID", db.di(mediaid)), ("MediaName", db.ds("%d.html" % mediaid)),
         ("MediaType", db.di(0)), ("MediaNotes", db.ds(template)),
         ("WebsitePhoto", db.di(0)), ("WebsiteVideo", db.di(0)),
         ("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)
    path = ""
    if linktype == ANIMAL:
        path = "/animal"
    elif linktype == PERSON:
        path = "/owner"
    elif linktype == LOSTANIMAL:
        path = "/lostanimal"
    elif linktype == FOUNDANIMAL:
        path = "/foundanimal"
    path += "/" + str(linkid)
    name = str(mediaid) + ".html"
    dbfs.put_string(dbo, name, path, content)
    audit.create(dbo, username, "media",
                 str(mediaid) + ": for " + str(linkid) + "/" + str(linktype))
Beispiel #9
0
def update_lookup(dbo, iid, lookup, name, desc="", speciesid=0, pfbreed="", pfspecies="", units="", defaultcost=0):
    t = LOOKUP_TABLES[lookup]
    sql = ""
    if lookup == "breed":
        sql = "UPDATE breed SET BreedName=%s, BreedDescription=%s, PetFinderBreed=%s, SpeciesID=%s WHERE ID=%s" % (
            db.ds(name), db.ds(desc), db.ds(pfbreed), db.di(speciesid), db.di(iid))
    elif lookup == "internallocation":
        sql = "UPDATE %s SET %s = %s, %s = %s, Units = %s WHERE ID=%s" % (
            lookup, t[LOOKUP_NAMEFIELD], db.ds(name), t[LOOKUP_DESCFIELD], db.ds(desc), db.ds(units), db.di(iid))
    elif lookup == "species":
        sql = "UPDATE species SET SpeciesName=%s, SpeciesDescription=%s, PetFinderSpecies=%s WHERE ID=%s" % (
            db.ds(name), db.ds(desc), db.ds(pfspecies), db.di(iid))
    elif lookup == "donationtype" or lookup == "costtype" or lookup == "testtype" or lookup == "voucher" or lookup == "vaccinationtype" \
        or lookup == "traptype" or lookup == "licencetype" or lookup == "citationtype":
        sql = "UPDATE %s SET %s = %s, %s = %s, DefaultCost = %s WHERE ID=%s" % (
            lookup, t[LOOKUP_NAMEFIELD], db.ds(name), t[LOOKUP_DESCFIELD], db.ds(desc), db.di(defaultcost), db.di(iid))
    elif t[LOOKUP_DESCFIELD] == "":
        # No description
        sql = "UPDATE %s SET %s=%s WHERE ID=%s" % (
            lookup, t[LOOKUP_NAMEFIELD], db.ds(name), db.di(iid))
    else:
        # Name/Description
        sql = "UPDATE %s SET %s=%s, %s=%s WHERE ID=%s" % (
            lookup, t[LOOKUP_NAMEFIELD], db.ds(name), t[LOOKUP_DESCFIELD], db.ds(desc), db.di(iid))
    db.execute(dbo, sql)
Beispiel #10
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 != db.query_int(dbo, "SELECT COUNT(*) FROM users WHERE LOWER(UserName) LIKE LOWER(%s)" % post.db_string("username")):
        raise utils.ASMValidationError(i18n._("Username '{0}' already exists", l).format(post["username"]))
    nuserid = db.get_id(dbo, "users")
    sql = db.make_insert_sql("users", ( 
        ( "ID", db.di(nuserid)),
        ( "UserName", post.db_string("username")),
        ( "RealName", post.db_string("realname")),
        ( "EmailAddress", post.db_string("email")),
        ( "Password", db.ds(hash_password(post["password"]))),
        ( "SuperUser", post.db_integer("superuser")),
        ( "RecordVersion", db.di(0)),
        ( "SecurityMap", db.ds("dummy")),
        ( "OwnerID", post.db_integer("person")),
        ( "SiteID", post.db_integer("site")),
        ( "LocationFilter", post.db_string("locationfilter")),
        ( "IPRestriction", post.db_string("iprestriction"))
        ))
    db.execute(dbo, sql)
    audit.create(dbo, username, "users", nuserid, audit.dump_row(dbo, "users", nuserid))
    roles = post["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
Beispiel #11
0
def insert_diary(dbo, username, linktypeid, linkid, diarydate, diaryfor, subject, note):
    """
    Creates a diary note from the form data
    username: User creating the diary
    linktypeid, linkid: The link
    diarydate: The date to stamp on the note (python format)
    diaryfor: Who the diary note is for
    subject, note
    """
    linkinfo = ""
    if linkid != 0:
        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", db.dd(diarydate) ),
        ( "DiaryForName", db.ds(diaryfor) ),
        ( "Subject", db.ds(subject) ),
        ( "Note", db.ds(note) ),
        ( "DateCompleted", db.dd(None) )
        ))
    db.execute(dbo, sql)
    audit.create(dbo, username, "diary", str(diaryid))
    return diaryid
Beispiel #12
0
def update_donation_from_form(dbo, username, data):
    """
    Updates a donation record from posted form data
    """
    l = dbo.locale
    donationid = utils.df_ki(data, "donationid")
    sql = db.make_update_user_sql(
        dbo, "ownerdonation", username, "ID=%d" % donationid,
        (("OwnerID", db.di(utils.df_ki(data, "person"))),
         ("AnimalID", db.di(utils.df_ki(data, "animal"))),
         ("MovementID", db.di(utils.df_ki(data, "movement"))),
         ("DonationTypeID", utils.df_s(data, "type")),
         ("DonationPaymentID", utils.df_s(data, "payment")),
         ("Frequency", utils.df_s(data, "frequency")),
         ("Donation", utils.df_m(data, "amount", l)),
         ("DateDue", utils.df_d(data, "due", l)),
         ("Date", utils.df_d(data, "received", l)),
         ("IsGiftAid", utils.df_s(data, "giftaid")),
         ("Comments", utils.df_t(data, "comments"))))
    preaudit = db.query(
        dbo, "SELECT * FROM ownerdonation WHERE ID = %d" % donationid)
    db.execute(dbo, sql)
    postaudit = db.query(
        dbo, "SELECT * FROM ownerdonation WHERE ID = %d" % donationid)
    audit.edit(dbo, username, "ownerdonation",
               audit.map_diff(preaudit, postaudit))
    update_matching_transaction(dbo, username, donationid)
    check_create_next_donation(dbo, username, donationid)
    movement.update_movement_donation(dbo, utils.df_ki(data, "movement"))
Beispiel #13
0
def update_movement_from_form(dbo, username, data):
    """
    Updates a movement record from posted form data
    """
    validate_movement_form_data(dbo, data)
    l = dbo.locale
    movementid = utils.df_ki(data, "movementid")
    sql = db.make_update_user_sql(dbo, "adoption", username, "ID=%d" % movementid, ( 
        ( "AdoptionNumber", utils.df_t(data, "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"))
        ))
    preaudit = db.query(dbo, "SELECT * FROM adoption WHERE ID = %d" % movementid)
    db.execute(dbo, sql)
    postaudit = db.query(dbo, "SELECT * FROM adoption WHERE ID = %d" % movementid)
    audit.edit(dbo, username, "adoption", audit.map_diff(preaudit, postaudit))
    animal.update_animal_status(dbo, utils.df_ki(data, "animal"))
    animal.update_variable_animal_data(dbo, utils.df_ki(data, "animal"))
    update_movement_donation(dbo, movementid)
Beispiel #14
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
Beispiel #15
0
def save_values_for_link(dbo, post, 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 post.has_key(key):
            val = post[key]
            if f["FIELDTYPE"] == YESNO:
                val = str(post.boolean(key))
            elif f["FIELDTYPE"] == MONEY:
                val = str(post.integer(key))
            elif f["FIELDTYPE"] == DATE:
                if len(val.strip()) > 0 and post.date(key) == None:
                    raise utils.ASMValidationError(_("Additional date field '{0}' contains an invalid date.", l).format(f["FIELDNAME"]))
                val = python2display(dbo.locale, post.date(key))
            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())
Beispiel #16
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
Beispiel #17
0
def df_c(data, field):
    """ Returns a checkbox field for the database """
    if not data.has_key(field): 
        return db.di(0)
    if data[field] == "checked" or data[field] == "on":
        return db.di(1)
    else:
        return db.di(0)
Beispiel #18
0
def df_c(data, field):
    """ Returns a checkbox field for the database """
    if not data.has_key(field):
        return db.di(0)
    if data[field] == "checked" or data[field] == "on":
        return db.di(1)
    else:
        return db.di(0)
Beispiel #19
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"))
Beispiel #20
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"))
Beispiel #21
0
def insert_onlineformincoming_from_form(dbo, post, 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 = post["formname"]
    posteddate = i18n.now(dbo.timezone)
    flags = post["flags"]
    for k, v in post.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", post.db_string(k))
                ))
            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) ))
    # Did the original form specify some email addresses to send 
    # incoming submissions to?
    email = db.query_string(dbo, "SELECT o.EmailAddress FROM onlineform o " \
        "INNER JOIN onlineformincoming oi ON oi.FormName = o.Name " \
        "WHERE oi.CollationID = %d" % int(collationid))
    if email is not None and email.strip() != "":
        utils.send_email(dbo, configuration.email(dbo), email, "", "%s - %s" % (formname, ", ".join(preview)), get_onlineformincoming_plain(dbo, collationid))
    return collationid
Beispiel #22
0
def attach_link_from_form(dbo, username, linktype, linkid, post):
    """
    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 post.integer("linktype") == MEDIATYPE_VIDEO_LINK:
        defvid = 1
    mediaid = db.get_id(dbo, "media")
    url = post["linktarget"]
    if url.find("://") == -1:
        url = "http://" + url
    al.debug("attached link %s" % url, "media.attach_file_from_form")
    sql = db.make_insert_sql("media", (
        ( "ID", db.di(mediaid) ),
        ( "MediaName", db.ds(url) ),
        ( "MediaType", post.db_integer("linktype") ),
        ( "MediaNotes", post.db_string("comments") ),
        ( "WebsitePhoto", db.di(0) ),
        ( "WebsiteVideo", db.di(defvid) ),
        ( "DocPhoto", db.di(0) ),
        ( "ExcludeFromPublish", db.di(0) ),
        # ASM2_COMPATIBILITY
        ( "NewSinceLastPublish", db.di(1) ),
        ( "UpdatedSinceLastPublish", db.di(0) ),
        # ASM2_COMPATIBILITY
        ( "LinkID", db.di(linkid) ),
        ( "LinkTypeID", db.di(linktype) ),
        ( "Date", db.nowsql() )
        ))
    db.execute(dbo, sql)
    audit.create(dbo, username, "media", mediaid, str(mediaid) + ": for " + str(linkid) + "/" + str(linktype) + ": link to " + post["linktarget"])
def add_log(dbo, username, linktype, linkid, logtypeid, logtext):
    logid = db.get_id(dbo, "log")
    sql = db.make_insert_user_sql(
        dbo, "log", username,
        (("ID", db.di(logid)), ("LogTypeID", db.di(logtypeid)),
         ("LinkID", db.di(linkid)), ("LinkType", db.di(linktype)),
         ("Date", db.dd(i18n.now(dbo.timezone))),
         ("Comments", db.ds(logtext))))
    db.execute(dbo, sql)
    audit.create(dbo, username, "log", str(logid))
    return logid
Beispiel #24
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
Beispiel #25
0
def add_log(dbo, username, linktype, linkid, logtypeid, logtext):
    logid = db.get_id(dbo, "log")
    sql = db.make_insert_user_sql(dbo, "log", username, (
        ( "ID", db.di(logid) ),
        ( "LogTypeID", db.di(logtypeid) ),
        ( "LinkID", db.di(linkid) ),
        ( "LinkType", db.di(linktype) ),
        ( "Date", db.dd(i18n.now(dbo.timezone)) ),
        ( "Comments", db.ds(logtext) )
        ))
    db.execute(dbo, sql)
    audit.create(dbo, username, "log", str(logid))
Beispiel #26
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
Beispiel #27
0
def insert_diarytaskhead_from_form(dbo, username, data):
    """
    Creates a diary task header from form data
    """
    nid = db.get_id(dbo, "diarytaskhead")
    sql = db.make_insert_sql("diarytaskhead",
                             (("ID", db.di(nid)),
                              ("Name", utils.df_t(data, "name")),
                              ("RecordType", utils.df_s(data, "type")),
                              ("RecordVersion", db.di(0))))
    db.execute(dbo, sql)
    audit.create(dbo, username, "diarytaskhead", str(nid))
    return nid
def insert_diarytaskhead_from_form(dbo, username, post):
    """
    Creates a diary task header from form data
    """
    nid = db.get_id(dbo, "diarytaskhead")
    sql = db.make_insert_sql("diarytaskhead",
                             (("ID", db.di(nid)),
                              ("Name", post.db_string("name")),
                              ("RecordType", post.db_integer("type")),
                              ("RecordVersion", db.di(0))))
    db.execute(dbo, sql)
    audit.create(dbo, username, "diarytaskhead", str(nid))
    return nid
Beispiel #29
0
def add_message(dbo, createdby, email, message, forname = "*", priority = 0, expires = add_days(now(), 7), added = now()):
    l = dbo.locale
    db.execute(dbo, db.make_insert_sql("messages", (
        ( "ID", db.di(db.get_id(dbo, "messages"))),
        ( "Added", db.dd(added)),
        ( "Expires", db.dd(expires)),
        ( "CreatedBy", db.ds(createdby)),
        ( "Priority", db.di(priority)),
        ( "ForName", db.ds(forname)),
        ( "Message", db.ds(message)))))
    # If email is set, we email the message to everyone that it would match
    if email == 1:
        utils.send_user_email(dbo, createdby, forname, _("Message from {0}", l).format(createdby), message)
Beispiel #30
0
def insert_diarytaskhead_from_form(dbo, username, post):
    """
    Creates a diary task header from form data
    """
    nid = db.get_id(dbo, "diarytaskhead")
    sql = db.make_insert_sql("diarytaskhead", (
        ( "ID", db.di(nid)),
        ( "Name", post.db_string("name")),
        ( "RecordType", post.db_integer("type")),
        ( "RecordVersion", db.di(0))
        ))
    db.execute(dbo, sql)
    audit.create(dbo, username, "diarytaskhead", nid, audit.dump_row(dbo, "diarytaskhead", nid))
    return nid
Beispiel #31
0
def insert_stockusage(dbo, username, slid, diff, usagedate, usagetype, comments):
    """
    Inserts a new stock usage record
    """
    nid = db.get_id(dbo, "stockusage")
    db.execute(dbo, db.make_insert_user_sql(dbo, "stockusage", username, (
        ( "ID", db.di(nid)),
        ( "StockUsageTypeID", db.di(usagetype) ),
        ( "StockLevelID", db.di(slid) ),
        ( "UsageDate", db.dd(usagedate) ),
        ( "Quantity", db.df(diff) ),
        ( "Comments", db.ds(comments) )
    )))
    audit.create(dbo, username, "stockusage", nid, audit.dump_row(dbo, "stockusage", nid))
Beispiel #32
0
def insert_diarytaskhead_from_form(dbo, username, data):
    """
    Creates a diary task header from form data
    """
    nid = db.get_id(dbo, "diarytaskhead")
    sql = db.make_insert_sql("diarytaskhead", (
        ( "ID", db.di(nid)),
        ( "Name", utils.df_t(data, "name")),
        ( "RecordType", utils.df_s(data, "type")),
        ( "RecordVersion", db.di(0))
        ))
    db.execute(dbo, sql)
    audit.create(dbo, username, "diarytaskhead", str(nid))
    return nid
Beispiel #33
0
def insert_account_from_donationtype(dbo, dtid, name, desc):
    """
    Creates an account from a donation type record
    """
    l = dbo.locale
    aid = db.get_id(dbo, "accounts")
    acode = i18n._("Income::", l) + name.replace(" ", "")
    sql = db.make_insert_user_sql(dbo, "accounts", "system",
                                  (("ID", db.di(aid)), ("Code", db.ds(acode)),
                                   ("AccountType", db.di(INCOME)),
                                   ("DonationTypeID", db.di(dtid)),
                                   ("Description", db.ds(desc))))
    db.execute(dbo, sql)
    audit.create(dbo, "system", "accounts", str(aid))
Beispiel #34
0
def insert_investigation_from_form(dbo, username, data):
    """
    Creates an investigation record from posted form data
    """
    l = dbo.locale
    ninv = db.get_id(dbo, "ownerinvestigation")
    sql = db.make_insert_user_sql(dbo, "ownerinvestigation", username, ( 
        ( "ID", db.di(ninv)),
        ( "OwnerID", db.di(utils.df_ki(data, "personid"))),
        ( "Date", utils.df_d(data, "date", l)),
        ( "Notes", utils.df_t(data, "notes"))
        ))
    db.execute(dbo, sql)
    audit.create(dbo, username, "ownerinvestigation", str(ninv))
    return ninv
Beispiel #35
0
def add_message(dbo, createdby, email, message, forname = "*", priority = 0, expires = add_days(now(), 7), added = now()):
    l = dbo.locale
    mid = db.get_id(dbo, "messages")
    db.execute(dbo, db.make_insert_sql("messages", (
        ( "ID", db.di(mid)),
        ( "Added", db.dd(added)),
        ( "Expires", db.dd(expires)),
        ( "CreatedBy", db.ds(createdby)),
        ( "Priority", db.di(priority)),
        ( "ForName", db.ds(forname)),
        ( "Message", db.ds(message)))))
    # If email is set, we email the message to everyone that it would match
    if email == 1:
        utils.send_user_email(dbo, createdby, forname, _("Message from {0}", l).format(createdby), message)
    return mid
def insert_diarytaskdetail_from_form(dbo, username, post):
    """
    Creates a diary task detail from form data
    """
    nid = db.get_id(dbo, "diarytaskdetail")
    sql = db.make_insert_sql(
        "diarytaskdetail",
        (("ID", db.di(nid)), ("DiaryTaskHeadID", post.db_integer("taskid")),
         ("DayPivot", post.db_integer("pivot")),
         ("WhoFor", post.db_string("for")),
         ("Subject", post.db_string("subject")),
         ("Note", post.db_string("note")), ("RecordVersion", db.di(0))))
    db.execute(dbo, sql)
    audit.create(dbo, username, "diarytaskdetail", str(nid))
    return nid
Beispiel #37
0
def insert_investigation_from_form(dbo, username, data):
    """
    Creates an investigation record from posted form data
    """
    l = dbo.locale
    ninv = db.get_id(dbo, "ownerinvestigation")
    sql = db.make_insert_user_sql(
        dbo, "ownerinvestigation", username,
        (("ID", db.di(ninv)),
         ("OwnerID", db.di(utils.df_ki(data, "personid"))),
         ("Date", utils.df_d(data, "date", l)),
         ("Notes", utils.df_t(data, "notes"))))
    db.execute(dbo, sql)
    audit.create(dbo, username, "ownerinvestigation", str(ninv))
    return ninv
Beispiel #38
0
def create_additional_fields(dbo, row, errors, rowno, csvkey = "ANIMALADDITIONAL", linktype = "animal", linkid = 0):
    # Identify any additional fields that may have been specified with
    # ANIMALADDITIONAL<fieldname>
    for a in additional.get_field_definitions(dbo, linktype):
        v = gks(row, csvkey + str(a["FIELDNAME"]).upper())
        if v != "":
            sql = db.make_insert_sql("additional", (
                ( "LinkType", db.di(a["LINKTYPE"]) ),
                ( "LinkID", db.di(int(linkid)) ),
                ( "AdditionalFieldID", db.di(a["ID"]) ),
                ( "Value", db.ds(v) ) ))
            try:
                db.execute(dbo, sql)
            except Exception,e:
                errors.append( (rowno, str(row), str(e)) )
Beispiel #39
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
Beispiel #40
0
def check_create_next_donation(dbo, username, odid):
    """
    Checks to see if a donation is now received and the next in 
    a sequence needs to be created for donations with a frequency 
    """
    al.debug("Create next donation %d" % int(odid),
             "financial.check_create_next_donation", dbo)
    d = db.query(dbo, "SELECT * FROM ownerdonation WHERE ID = %d" % int(odid))
    if d is None or len(d) == 0:
        al.error("No donation found for %d" % int(odid),
                 "financial.check_create_next_donation", dbo)
        return
    d = d[0]
    # If we have a frequency > 0, the nextcreated flag isn't set
    # and there's a datereceived and due then we need to create the
    # next donation in the sequence
    if d["DATEDUE"] != None and d["DATE"] != None and d["FREQUENCY"] > 0 and d[
            "NEXTCREATED"] == 0:
        nextdue = d["DATEDUE"]
        if d["FREQUENCY"] == 1:
            nextdue = i18n.add_days(nextdue, 7)
        if d["FREQUENCY"] == 2:
            nextdue = i18n.add_months(nextdue, 1)
        if d["FREQUENCY"] == 3:
            nextdue = i18n.add_months(nextdue, 3)
        if d["FREQUENCY"] == 4:
            nextdue = i18n.add_years(nextdue, 1)
        al.debug("Next donation due %s" % str(nextdue),
                 "financial.check_create_next_donation", dbo)
        # Update nextcreated flag for this donation
        db.execute(
            dbo, "UPDATE ownerdonation SET NextCreated = 1 WHERE ID = %d" %
            int(odid))
        # Create the new donation due record
        did = db.get_id(dbo, "ownerdonation")
        sql = db.make_insert_user_sql(
            dbo, "ownerdonation", username,
            (("ID", db.di(did)), ("AnimalID", db.di(d["ANIMALID"])),
             ("OwnerID", db.di(d["OWNERID"])),
             ("MovementID", db.di(d["MOVEMENTID"])),
             ("DonationTypeID", db.di(d["DONATIONTYPEID"])),
             ("DateDue", db.dd(nextdue)), ("Date", db.dd(None)),
             ("Donation", db.di(d["DONATION"])),
             ("IsGiftAid", db.di(d["ISGIFTAID"])),
             ("DonationPaymentID", db.di(d["DONATIONPAYMENTID"])),
             ("Frequency", db.di(d["FREQUENCY"])), ("NextCreated", db.di(0)),
             ("Comments", db.ds(d["COMMENTS"]))))
        db.execute(dbo, sql)
Beispiel #41
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
Beispiel #42
0
def insert_account_from_form(dbo, username, post):
    """
    Creates an account from posted form data 
    """
    l = dbo.locale
    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'" % post["code"]):
        raise utils.ASMValidationError(i18n._("Account code '{0}' has already been used.", l).format(post["code"]))

    aid = db.get_id(dbo, "accounts")
    sql = db.make_insert_user_sql(dbo, "accounts", username, ( 
        ( "ID", db.di(aid)),
        ( "Code", post.db_string("code")),
        ( "AccountType", post.db_integer("type")),
        ( "DonationTypeID", post.db_integer("donationtype")),
        ( "Description", post.db_string("description"))
        ))
    db.execute(dbo, sql)
    audit.create(dbo, username, "accounts", str(aid))
    accountid = post.integer("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))
    return aid
Beispiel #43
0
def insert_account_from_donationtype(dbo, dtid, name, desc):
    """
    Creates an account from a donation type record
    """
    l = dbo.locale
    aid = db.get_id(dbo, "accounts")
    acode = i18n._("Income::", l) + name.replace(" ", "")
    sql = db.make_insert_user_sql(dbo, "accounts", "system", ( 
        ( "ID", db.di(aid)),
        ( "Code", db.ds(acode)),
        ( "AccountType", db.di(INCOME)),
        ( "DonationTypeID", db.di(dtid)),
        ( "Description", db.ds(desc))
        ))
    db.execute(dbo, sql)
    audit.create(dbo, "system", "accounts", str(aid))
Beispiel #44
0
def insert_transport_from_form(dbo, username, post):
    """
    Creates a transport record from posted form data 
    """
    l = dbo.locale
    if post.integer("animal") == 0:
        raise utils.ASMValidationError(i18n._("Transport requires an animal", l))

    transportid = db.get_id(dbo, "animaltransport")
    sql = db.make_insert_user_sql(dbo, "animaltransport", username, ( 
        ( "ID", db.di(transportid)),
        ( "AnimalID", post.db_integer("animal")),
        ( "DriverOwnerID", post.db_integer("driver")),
        ( "PickupOwnerID", post.db_integer("pickup")),
        ( "PickupAddress", post.db_string("pickupaddress")),
        ( "PickupTown", post.db_string("pickuptown")),
        ( "PickupCounty", post.db_string("pickupcounty")),
        ( "PickupDateTime", post.db_datetime("pickupdate", "pickuptime")),
        ( "PickupPostcode", post.db_string("pickuppostcode")),
        ( "DropoffOwnerID", post.db_integer("dropoff")),
        ( "DropoffAddress", post.db_string("dropoffaddress")),
        ( "DropoffTown", post.db_string("dropofftown")),
        ( "DropoffCounty", post.db_string("dropoffcounty")),
        ( "DropoffPostcode", post.db_string("dropoffpostcode")),
        ( "DropoffDateTime", post.db_datetime("dropoffdate", "dropofftime")),
        ( "Status", post.db_integer("status")),
        ( "Miles", post.db_integer("miles")),
        ( "Cost", post.db_integer("cost")),
        ( "CostPaidDate", post.db_date("costpaid")),
        ( "Comments", post.db_string("comments"))
        ))
    db.execute(dbo, sql)
    audit.create(dbo, username, "animaltransport", transportid, audit.dump_row(dbo, "animaltransport", transportid))
    return transportid
Beispiel #45
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))
Beispiel #46
0
def insert_stocklevel_from_form(dbo, post, username):
    """
    Inserts a stocklevel item from a dialog. The post should include
    the ID of the stocklevel to adjust and a usage record will be
    written so usage data should be sent too.
    """
    l = dbo.locale
    slid = post.integer("id")
    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 = db.get_id(dbo, "stocklevel")
    db.execute(dbo, db.make_insert_sql("stocklevel", (
        ( "ID", db.di(nid) ),
        ( "Name", post.db_string("name") ),
        ( "Description", post.db_string("description") ),
        ( "StockLocationID", post.db_integer("location") ),
        ( "UnitName", post.db_string("unitname") ),
        ( "Total", post.db_floating("total") ),
        ( "Balance", post.db_floating("balance") ),
        ( "Expiry", post.db_date("expiry") ),
        ( "BatchNumber", post.db_string("batchnumber") ),
        ( "Cost", post.db_integer("cost") ),
        ( "UnitPrice", post.db_integer("unitprice") ),
        ( "CreatedDate", db.todaysql() )
    )))
    insert_stockusage(dbo, username, slid, post.floating("balance"), post.date("usagedate"), post.integer("usagetype"), post["comments"])
    audit.create(dbo, username, "stocklevel", nid, audit.dump_row(dbo, "stocklevel", nid))
    return nid
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
Beispiel #48
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)
Beispiel #49
0
def insert_foundanimal_from_form(dbo, data, username):
    """
    Inserts a new found animal record from the screen
    data: The webpy data object containing form parameters
    """
    l = dbo.locale
    if utils.df_kd(data, "datefound", l) is None:
        raise utils.ASMValidationError(_("Date found cannot be blank", l))
    if utils.df_kd(data, "datereported", l) is None:
        raise utils.ASMValidationError(_("Date reported cannot be blank", l))
    if utils.df_ki(data, "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", utils.df_s(data, "species")),
        ( "DateReported", utils.df_d(data, "datereported", l)),
        ( "ReturnToOwnerDate", utils.df_d(data, "returntoownerdate", l)),
        ( "DateFound", utils.df_d(data, "datefound", l)),
        ( "Sex", utils.df_s(data, "sex")),
        ( "BreedID", utils.df_s(data, "breed")),
        ( "AgeGroup", utils.df_t(data, "agegroup")),
        ( "BaseColourID", utils.df_s(data, "colour")),
        ( "DistFeat", utils.df_t(data, "markings")),
        ( "AreaFound", utils.df_t(data, "areafound")),
        ( "AreaPostcode", utils.df_t(data, "areapostcode")),
        ( "OwnerID", utils.df_s(data, "owner")),
        ( "Comments", utils.df_t(data, "comments"))
        )))
    audit.create(dbo, username, "animalfound", str(nid))
    return nid
Beispiel #50
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
Beispiel #51
0
def update_media_notes(dbo, username, mid, notes):
    sql = db.make_update_sql("media", "ID=%d" % int(mid), (
        ("MediaNotes", db.ds(notes)),
        ("MediaName", "MediaName"),
        ("UpdatedSinceLastPublish", db.di(1)),
    ))
    db.execute(dbo, sql)
    audit.edit(dbo, username, "media", str(mid) + "notes => " + notes)
Beispiel #52
0
def insert_diarytaskdetail_from_form(dbo, username, data):
    """
    Creates a diary task detail from form data
    """
    nid = db.get_id(dbo, "diarytaskdetail")
    sql = db.make_insert_sql("diarytaskdetail", (
        ( "ID", db.di(nid)),
        ( "DiaryTaskHeadID", utils.df_s(data, "taskid")),
        ( "DayPivot", utils.df_s(data, "pivot")),
        ( "WhoFor", utils.df_t(data, "for")),
        ( "Subject", utils.df_t(data, "subject")),
        ( "Note", utils.df_t(data, "note")),
        ( "RecordVersion", db.di(0))
        ))
    db.execute(dbo, sql)
    audit.create(dbo, username, "diarytaskdetail", str(nid))
    return nid
Beispiel #53
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)
Beispiel #54
0
def update_media_notes(dbo, username, mid, notes):
    sql = db.make_update_sql("media", "ID=%d" % int(mid), (
        ( "MediaNotes", db.ds(notes)),
        ( "MediaName", "MediaName" ),
        ( "UpdatedSinceLastPublish", db.di(1)),
        ))
    db.execute(dbo, sql)
    audit.edit(dbo, username, "media", str(mid) + "notes => " + notes)
Beispiel #55
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))
Beispiel #56
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
Beispiel #57
0
def insert_voucher_from_form(dbo, username, data):
    """
    Creates a voucher record from posted form data 
    """
    l = dbo.locale
    voucherid = db.get_id(dbo, "ownervoucher")
    sql = db.make_insert_user_sql(
        dbo, "ownervoucher", username,
        (("ID", db.di(voucherid)),
         ("OwnerID", db.di(utils.df_ki(data, "personid"))),
         ("VoucherID", utils.df_s(data, "type")),
         ("DateIssued", utils.df_d(data, "issued", l)),
         ("DateExpired", utils.df_d(data, "expires", l)),
         ("Value", utils.df_m(data, "amount", l)),
         ("Comments", utils.df_t(data, "comments"))))
    db.execute(dbo, sql)
    audit.create(dbo, username, "ownervoucher", str(voucherid))
    return voucherid
Beispiel #58
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"]))
Beispiel #59
0
def update_test_today(dbo, username, testid, resultid):
    """
    Marks a test record as performed today. 
    """
    db.execute(
        dbo,
        db.make_update_user_sql(dbo, "animaltest", username,
                                "ID = %d" % testid,
                                (("DateOfTest", db.dd(now(dbo.timezone))),
                                 ("TestResultID", db.di(resultid)))))
Beispiel #60
0
def create_blank_document_media(dbo, username, linktype, linkid):
    """
    Creates a new media record for a blank document for the link given.
    linktype: ANIMAL, PERSON, etc
    linkid: ID for the link
    returns the new media id
    """
    mediaid = db.get_id(dbo, "media")
    sql = db.make_insert_sql(
        "media",
        (
            ("ID", db.di(mediaid)),
            ("MediaName", db.ds("%d.html" % mediaid)),
            ("MediaType", db.di(0)),
            ("MediaNotes", db.ds("New document")),
            ("WebsitePhoto", db.di(0)),
            ("WebsiteVideo", db.di(0)),
            ("DocPhoto", db.di(0)),
            ("ExcludeFromPublish", db.di(0)),
            # ASM2_COMPATIBILITY
            ("NewSinceLastPublish", db.di(1)),
            ("UpdatedSinceLastPublish", db.di(0)),
            # ASM2_COMPATIBILITY
            ("LinkID", db.di(linkid)),
            ("LinkTypeID", db.di(linktype)),
            ("Date", db.nowsql())))
    db.execute(dbo, sql)
    path = ""
    if linktype == ANIMAL:
        path = "/animal"
    elif linktype == PERSON:
        path = "/owner"
    elif linktype == LOSTANIMAL:
        path = "/lostanimal"
    elif linktype == FOUNDANIMAL:
        path = "/foundanimal"
    path += "/" + str(linkid)
    name = str(mediaid) + ".html"
    dbfs.put_string(dbo, name, path, "")
    audit.create(dbo, username, "media",
                 str(mediaid) + ": for " + str(linkid) + "/" + str(linktype))
    return mediaid