Exemplo n.º 1
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
Exemplo n.º 2
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
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
Exemplo n.º 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
Exemplo n.º 5
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
Exemplo n.º 6
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
Exemplo n.º 7
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"])
Exemplo n.º 8
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
Exemplo n.º 9
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))
Exemplo n.º 10
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
Exemplo n.º 11
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))
    return logid
Exemplo n.º 12
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))
Exemplo n.º 13
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
def insert_animalcontrol_from_form(dbo, post, username):
    """
    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 = db.get_id(dbo, "animalcontrol")
    db.execute(
        dbo,
        db.make_insert_user_sql(
            dbo, "animalcontrol", username,
            (("ID", db.di(nid)),
             ("IncidentDateTime",
              post.db_datetime("incidentdate", "incidenttime")),
             ("IncidentTypeID", post.db_integer("incidenttype")),
             ("CallDateTime", post.db_datetime("calldate", "calltime")),
             ("CallNotes", post.db_string("callnotes")),
             ("CallTaker", post.db_string("calltaker")),
             ("CallerID", post.db_integer("caller")),
             ("VictimID", post.db_integer("victim")),
             ("DispatchAddress", post.db_string("dispatchaddress")),
             ("DispatchTown", post.db_string("dispatchtown")),
             ("DispatchCounty", post.db_string("dispatchcounty")),
             ("DispatchPostcode", post.db_string("dispatchpostcode")),
             ("DispatchLatLong", post.db_string("dispatchlatlong")),
             ("DispatchedACO", post.db_string("dispatchedaco")),
             ("DispatchDateTime",
              post.db_datetime("dispatchdate", "dispatchtime")),
             ("RespondedDateTime",
              post.db_datetime("respondeddate", "respondedtime")),
             ("FollowupDateTime",
              post.db_datetime("followupdate", "followuptime")),
             ("FollowupDateTime2",
              post.db_datetime("followupdate2", "followuptime2")),
             ("FollowupDateTime3",
              post.db_datetime("followupdate3", "followuptime3")),
             ("CompletedDate", post.db_date("completeddate")),
             ("IncidentCompletedID", post.db_integer("completedtype")),
             ("OwnerID", post.db_integer("owner")),
             ("Owner2ID", post.db_integer("owner2")),
             ("Owner3ID", post.db_integer("owner3")),
             ("AnimalID", post.db_integer("animal")),
             ("AnimalDescription", post.db_string("animaldescription")),
             ("SpeciesID", post.db_integer("species")),
             ("Sex", post.db_integer("sex")), ("AgeGroup",
                                               post.db_string("agegroup")))))
    audit.create(dbo, username, "animalcontrol", str(nid))
    return nid
Exemplo n.º 15
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)
Exemplo n.º 16
0
def insert_animalcontrol_from_form(dbo, post, username):
    """
    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 = db.get_id(dbo, "animalcontrol")
    db.execute(dbo, db.make_insert_user_sql(dbo, "animalcontrol", username, (
        ( "ID", db.di(nid)),
        ( "IncidentDateTime", post.db_datetime("incidentdate", "incidenttime")),
        ( "IncidentTypeID", post.db_integer("incidenttype")),
        ( "CallDateTime", post.db_datetime("calldate", "calltime")),
        ( "CallNotes", post.db_string("callnotes")),
        ( "CallTaker", post.db_string("calltaker")),
        ( "CallerID", post.db_integer("caller")),
        ( "VictimID", post.db_integer("victim")),
        ( "DispatchAddress", post.db_string("dispatchaddress")),
        ( "DispatchTown", post.db_string("dispatchtown")),
        ( "DispatchCounty", post.db_string("dispatchcounty")),
        ( "DispatchPostcode", post.db_string("dispatchpostcode")),
        ( "PickupLocationID", post.db_integer("pickuplocation")),
        ( "DispatchLatLong", post.db_string("dispatchlatlong")),
        ( "DispatchedACO", post.db_string("dispatchedaco")),
        ( "DispatchDateTime", post.db_datetime("dispatchdate", "dispatchtime")),
        ( "RespondedDateTime", post.db_datetime("respondeddate", "respondedtime")),
        ( "FollowupDateTime", post.db_datetime("followupdate", "followuptime")),
        ( "FollowupComplete", post.db_boolean("followupcomplete")),
        ( "FollowupDateTime2", post.db_datetime("followupdate2", "followuptime2")),
        ( "FollowupComplete2", post.db_boolean("followupcomplete2")),
        ( "FollowupDateTime3", post.db_datetime("followupdate3", "followuptime3")),
        ( "FollowupComplete3", post.db_boolean("followupcomplete3")),
        ( "CompletedDate", post.db_date("completeddate")),
        ( "IncidentCompletedID", post.db_integer("completedtype")),
        ( "OwnerID", post.db_integer("owner")),
        ( "Owner2ID", post.db_integer("owner2")),
        ( "Owner3ID", post.db_integer("owner3")),
        ( "AnimalDescription", post.db_string("animaldescription")),
        ( "SpeciesID", post.db_integer("species")),
        ( "Sex", post.db_integer("sex")),
        ( "AgeGroup", post.db_string("agegroup"))
        )))
    audit.create(dbo, username, "animalcontrol", nid, audit.dump_row(dbo, "animalcontrol", nid))

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

    return nid
Exemplo n.º 17
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))
Exemplo n.º 18
0
Arquivo: stock.py Projeto: magul/asm3
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))
Exemplo n.º 19
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)
Exemplo n.º 20
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
Exemplo n.º 21
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
Exemplo n.º 22
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)
Exemplo n.º 23
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
Exemplo n.º 24
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))
Exemplo n.º 25
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)
Exemplo n.º 26
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
Exemplo n.º 27
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
def insert_traploan_from_form(dbo, username, post):
    """
    Creates a traploan record from posted form data 
    """
    traploanid = db.get_id(dbo, "ownertraploan")
    sql = db.make_insert_user_sql(
        dbo, "ownertraploan", username,
        (("ID", db.di(traploanid)), ("OwnerID", post.db_integer("person")),
         ("TrapTypeID", post.db_integer("type")),
         ("LoanDate", post.db_date("loandate")),
         ("DepositAmount", post.db_integer("depositamount")),
         ("DepositReturnDate", post.db_date("depositreturndate")),
         ("TrapNumber", post.db_string("trapnumber")),
         ("ReturnDueDate", post.db_date("returnduedate")),
         ("ReturnDate", post.db_date("returndate")),
         ("Comments", post.db_string("comments"))))
    db.execute(dbo, sql)
    audit.create(dbo, username, "ownertraploan", str(traploanid))
    return traploanid
Exemplo n.º 29
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
Exemplo n.º 30
0
def insert_traploan_from_form(dbo, username, post):
    """
    Creates a traploan record from posted form data 
    """
    traploanid = db.get_id(dbo, "ownertraploan")
    sql = db.make_insert_user_sql(dbo, "ownertraploan", username, ( 
        ( "ID", db.di(traploanid)),
        ( "OwnerID", post.db_integer("person")),
        ( "TrapTypeID", post.db_integer("type")),
        ( "LoanDate", post.db_date("loandate")),
        ( "DepositAmount", post.db_integer("depositamount")),
        ( "DepositReturnDate", post.db_date("depositreturndate")),
        ( "TrapNumber", post.db_string("trapnumber")),
        ( "ReturnDueDate", post.db_date("returnduedate")),
        ( "ReturnDate", post.db_date("returndate")),
        ( "Comments", post.db_string("comments"))
        ))
    db.execute(dbo, sql)
    audit.create(dbo, username, "ownertraploan", traploanid, audit.dump_row(dbo, "ownertraploan", traploanid))
    return traploanid
Exemplo n.º 31
0
def insert_profile_from_form(dbo, username, data):
    """
    Creates a profile record from posted form data
    """
    l = dbo.locale
    if utils.df_ks(data, "treatmentname") == "":
        raise utils.ASMValidationError(_("Treatment name cannot be blank", l))
    if utils.df_ks(data, "profilename") == "":
        raise utils.ASMValidationError(_("Profile name cannot be blank", l))

    nprofid = db.get_id(dbo, "medicalprofile")
    timingrule = utils.df_ki(data, "timingrule")
    timingrulenofrequencies = utils.df_ki(data, "timingrulenofrequencies")
    timingrulefrequency = utils.df_ki(data, "timingrulefrequency")
    totalnumberoftreatments = utils.df_ki(data, "totalnumberoftreatments")
    treatmentrule = utils.df_ki(data, "treatmentrule")
    singlemulti = utils.df_ki(data, "singlemulti")
    if singlemulti == 0:
        timingrule = 0
        timingrulenofrequencies = 0
        timingrulefrequency = 0
    if treatmentrule != 0:
        totalnumberoftreatments = 0
    sql = db.make_insert_user_sql(
        dbo, "medicalprofile", username,
        (("ID", db.di(nprofid)),
         ("ProfileName", utils.df_t(data, "profilename")),
         ("TreatmentName", utils.df_t(data, "treatmentname")),
         ("Dosage", utils.df_t(data, "dosage")),
         ("Cost", utils.df_m(data, "cost", l)),
         ("TimingRule", db.di(timingrule)),
         ("TimingRuleFrequency", db.di(timingrulefrequency)),
         ("TimingRuleNoFrequencies", db.di(timingrulenofrequencies)),
         ("TreatmentRule", utils.df_s(data, "treatmentrule")),
         ("TotalNumberOfTreatments", db.di(totalnumberoftreatments)),
         ("Comments", utils.df_t(data, "comments"))))
    db.execute(dbo, sql)
    audit.create(
        dbo, username, "medicalprofile",
        str(nprofid) + ": " + utils.df_ks(data, "treatmentname") + " " +
        utils.df_ks(data, "dosage"))
Exemplo n.º 32
0
def insert_vaccination_from_form(dbo, username, data):
    """
    Creates a vaccination record from posted form data
    """
    l = dbo.locale
    if utils.df_kd(data, "required", l) is None:
        raise utils.ASMValidationError(_("Required date must be a valid date", l))

    nvaccid = db.get_id(dbo, "animalvaccination")
    sql = db.make_insert_user_sql(dbo, "animalvaccination", username, ( 
        ( "ID", db.di(nvaccid)),
        ( "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"))
        ))
    db.execute(dbo, sql)
    audit.create(dbo, username, "animalvaccination", str(nvaccid))
    return nvaccid
Exemplo n.º 33
0
def insert_vaccination_from_form(dbo, username, data):
    """
    Creates a vaccination record from posted form data
    """
    l = dbo.locale
    if utils.df_kd(data, "required", l) is None:
        raise utils.ASMValidationError(
            _("Required date must be a valid date", l))

    nvaccid = db.get_id(dbo, "animalvaccination")
    sql = db.make_insert_user_sql(
        dbo, "animalvaccination", username,
        (("ID", db.di(nvaccid)), ("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"))))
    db.execute(dbo, sql)
    audit.create(dbo, username, "animalvaccination", str(nvaccid))
    return nvaccid
Exemplo n.º 34
0
def insert_log_from_form(dbo, username, linktypeid, linkid, post):
    """
    Creates a log from the form data
    username: User creating the diary
    linktypeid, linkid: The link
    data: The web.py form object
    """
    l = dbo.locale
    if post.date("logdate") is None:
        raise utils.ASMValidationError(
            i18n._("Log date must be a valid date", l))
    logid = db.get_id(dbo, "log")
    sql = db.make_insert_user_sql(
        dbo, "log", username,
        (("ID", db.di(logid)), ("LogTypeID", post.db_integer("type")),
         ("LinkID", db.di(linkid)), ("LinkType", db.di(linktypeid)),
         ("Date", post.db_date("logdate")),
         ("Comments", post.db_string("entry"))))
    db.execute(dbo, sql)
    audit.create(dbo, username, "log", str(logid))
    return logid
Exemplo n.º 35
0
def insert_diary_from_form(dbo, username, linktypeid, linkid, post):
    """
    Creates a diary note from the form data
    username: User creating the diary
    linktypeid, linkid: The link
    post: A PostedData object
    """
    l = dbo.locale
    if post["diarydate"] == "":
        raise utils.ASMValidationError(i18n._("Diary date cannot be blank", l))
    if post.date("diarydate") is None:
        raise utils.ASMValidationError(i18n._("Diary date is not valid", l))
    if post["subject"] == "":
        raise utils.ASMValidationError(
            i18n._("Diary subject cannot be blank", l))
    if post["note"] == "":
        raise utils.ASMValidationError(i18n._("Diary note cannot be blank", l))
    diarytime = post["diarytime"].strip()
    if diarytime != "":
        if diarytime.find(":") == -1:
            raise utils.ASMValidationError(
                i18n._("Invalid time, times should be in HH:MM format", l))
        if not utils.is_numeric(diarytime.replace(":", "")):
            raise utils.ASMValidationError(
                i18n._("Invalid time, times should be in HH:MM format", l))

    linkinfo = get_link_info(dbo, linktypeid, linkid)
    diaryid = db.get_id(dbo, "diary")
    sql = db.make_insert_user_sql(
        dbo, "diary", username,
        (("ID", db.di(diaryid)), ("LinkID", db.di(linkid)),
         ("LinkType", db.di(linktypeid)), ("LinkInfo", db.ds(linkinfo)),
         ("DiaryDateTime", post.db_datetime("diarydate", "diarytime")),
         ("DiaryForName", post.db_string("diaryfor")),
         ("Subject", post.db_string("subject")),
         ("Note", post.db_string("note")),
         ("DateCompleted", post.db_date("completed"))))
    db.execute(dbo, sql)
    audit.create(dbo, username, "diary", str(diaryid))
    return diaryid
Exemplo n.º 36
0
Arquivo: diary.py Projeto: magul/asm3
def insert_diary_from_form(dbo, username, linktypeid, linkid, post):
    """
    Creates a diary note from the form data
    username: User creating the diary
    linktypeid, linkid: The link
    post: A PostedData object
    """
    l = dbo.locale
    if post["diarydate"] == "":
        raise utils.ASMValidationError(i18n._("Diary date cannot be blank", l))
    if post.date("diarydate") is None:
        raise utils.ASMValidationError(i18n._("Diary date is not valid", l))
    if post["subject"] == "":
        raise utils.ASMValidationError(i18n._("Diary subject cannot be blank", l))
    if post["note"] == "":
        raise utils.ASMValidationError(i18n._("Diary note cannot be blank", l))
    diarytime =  post["diarytime"].strip()
    if diarytime != "":
        if diarytime.find(":") == -1:
            raise utils.ASMValidationError(i18n._("Invalid time, times should be in HH:MM format", l))
        if not utils.is_numeric(diarytime.replace(":", "")):
            raise utils.ASMValidationError(i18n._("Invalid time, times should be in HH:MM format", l))

    linkinfo = get_link_info(dbo, linktypeid, linkid)
    diaryid = db.get_id(dbo, "diary")
    sql = db.make_insert_user_sql(dbo, "diary", username, (
        ( "ID", db.di(diaryid)),
        ( "LinkID", db.di(linkid) ),
        ( "LinkType", db.di(linktypeid) ),
        ( "LinkInfo", db.ds(linkinfo) ),
        ( "DiaryDateTime", post.db_datetime("diarydate", "diarytime")), 
        ( "DiaryForName", post.db_string("diaryfor")),
        ( "Subject", post.db_string("subject")),
        ( "Note", post.db_string("note")),
        ( "Comments", post.db_string("comments")),
        ( "DateCompleted", post.db_date("completed"))
        ))
    db.execute(dbo, sql)
    audit.create(dbo, username, "diary", diaryid, audit.dump_row(dbo, "diary", diaryid))
    return diaryid
Exemplo n.º 37
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
Exemplo n.º 38
0
def insert_treatments(dbo, username, amid, requireddate, isstart = True):
    """
    Creates new treatment records for the given medical record
    with the required date given. isstart says that the date passed
    is the real start date, so don't look at the timing rule to 
    calculate the next date.
    """
    am = db.query(dbo, "SELECT * FROM animalmedical WHERE ID = %d" % amid)[0]
    nofreq = int(am["TIMINGRULENOFREQUENCIES"])
    if not isstart:
        if am["TIMINGRULEFREQUENCY"] == DAILY:
            requireddate += datetime.timedelta(days=nofreq)
        if am["TIMINGRULEFREQUENCY"] == WEEKLY:
            requireddate += datetime.timedelta(days=nofreq*7)
        if am["TIMINGRULEFREQUENCY"] == MONTHLY:
            requireddate += datetime.timedelta(days=nofreq*31)
        if am["TIMINGRULEFREQUENCY"] == YEARLY:
            requireddate += datetime.timedelta(days=nofreq*365)

    # Create correct number of records
    norecs = am["TIMINGRULE"]
    if norecs == 0: norecs = 1

    for x in range(1, norecs+1):
        sql = db.make_insert_user_sql(dbo, "animalmedicaltreatment", username, (
            ( "ID", db.di(db.get_id(dbo, "animalmedicaltreatment"))),
            ( "AnimalID", db.di(am["ANIMALID"]) ),
            ( "AnimalMedicalID", db.di(amid)),
            ( "DateRequired", db.dd(requireddate)),
            ( "DateGiven", db.dd(None)),
            ( "GivenBy", db.ds("")),
            ( "TreatmentNumber", db.di(x)),
            ( "TotalTreatments", db.di(norecs)),
            ( "Comments", db.ds(""))
        ))
        db.execute(dbo, sql)

    # Update the number of treatments given and remaining
    calculate_given_remaining(dbo, amid)
Exemplo n.º 39
0
def insert_log_from_form(dbo, username, linktypeid, linkid, data):
    """
    Creates a log from the form data
    username: User creating the diary
    linktypeid, linkid: The link
    data: The web.py form object
    """
    l = dbo.locale
    if utils.df_kd(data, "logdate", l) is None:
        raise utils.ASMValidationError(i18n._("Log date must be a valid date", l))
    logid = db.get_id(dbo, "log")
    sql = db.make_insert_user_sql(dbo, "log", username, (
        ( "ID", db.di(logid)),
        ( "LogTypeID", utils.df_s(data, "type")),
        ( "LinkID", db.di(linkid) ),
        ( "LinkType", db.di(linktypeid) ),
        ( "Date", utils.df_d(data, "logdate", l) ),
        ( "Comments", utils.df_t(data, "entry") )
        ))
    db.execute(dbo, sql)
    audit.create(dbo, username, "log", str(logid))
    return logid
Exemplo n.º 40
0
def insert_diary_from_form(dbo, username, linktypeid, linkid, data):
    """
    Creates a diary note from the form data
    username: User creating the diary
    linktypeid, linkid: The link
    data: The web.py form object
    """
    l = dbo.locale
    if utils.df_ks(data, "diarydate") == "":
        raise utils.ASMValidationError(i18n._("Diary date cannot be blank", l))
    if utils.df_kd(data, "diarydate", l) is None:
        raise utils.ASMValidationError(i18n._("Diary date is not valid", l))
    if utils.df_ks(data, "subject") == "":
        raise utils.ASMValidationError(i18n._("Diary subject cannot be blank", l))
    if utils.df_ks(data, "note") == "":
        raise utils.ASMValidationError(i18n._("Diary note cannot be blank", l))
    diarytime =  utils.df_ks(data, "diarytime").strip()
    if diarytime != "":
        if diarytime.find(":") == -1:
            raise utils.ASMValidationError(i18n._("Invalid time, times should be in HH:MM format", l))
        if not utils.is_numeric(diarytime.replace(":", "")):
            raise utils.ASMValidationError(i18n._("Invalid time, times should be in HH:MM format", l))

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

    nprofid = db.get_id(dbo, "medicalprofile")
    timingrule = utils.df_ki(data, "timingrule")
    timingrulenofrequencies = utils.df_ki(data, "timingrulenofrequencies")
    timingrulefrequency = utils.df_ki(data, "timingrulefrequency")
    totalnumberoftreatments = utils.df_ki(data, "totalnumberoftreatments")
    treatmentrule = utils.df_ki(data, "treatmentrule")
    singlemulti = utils.df_ki(data, "singlemulti")
    if singlemulti == 0:
        timingrule = 0
        timingrulenofrequencies = 0
        timingrulefrequency = 0
    if treatmentrule != 0:
        totalnumberoftreatments = 0
    sql = db.make_insert_user_sql(dbo, "medicalprofile", username, ( 
        ( "ID", db.di(nprofid)),
        ( "ProfileName", utils.df_t(data, "profilename")),
        ( "TreatmentName", utils.df_t(data, "treatmentname")),
        ( "Dosage", utils.df_t(data, "dosage")),
        ( "Cost", utils.df_m(data, "cost", l)),
        ( "TimingRule", db.di(timingrule)),
        ( "TimingRuleFrequency", db.di(timingrulefrequency)),
        ( "TimingRuleNoFrequencies", db.di(timingrulenofrequencies)),
        ( "TreatmentRule", utils.df_s(data, "treatmentrule")),
        ( "TotalNumberOfTreatments", db.di(totalnumberoftreatments)),
        ( "Comments", utils.df_t(data, "comments"))
        ))
    db.execute(dbo, sql)
    audit.create(dbo, username, "medicalprofile", str(nprofid) + ": " + utils.df_ks(data, "treatmentname") + " " + utils.df_ks(data, "dosage"))
Exemplo n.º 42
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))
Exemplo n.º 43
0
def insert_treatments(dbo, username, amid, requireddate, isstart=True):
    """
    Creates new treatment records for the given medical record
    with the required date given. isstart says that the date passed
    is the real start date, so don't look at the timing rule to 
    calculate the next date.
    """
    am = db.query(dbo, "SELECT * FROM animalmedical WHERE ID = %d" % amid)[0]
    nofreq = int(am["TIMINGRULENOFREQUENCIES"])
    if not isstart:
        if am["TIMINGRULEFREQUENCY"] == DAILY:
            requireddate += datetime.timedelta(days=nofreq)
        if am["TIMINGRULEFREQUENCY"] == WEEKLY:
            requireddate += datetime.timedelta(days=nofreq * 7)
        if am["TIMINGRULEFREQUENCY"] == MONTHLY:
            requireddate += datetime.timedelta(days=nofreq * 31)
        if am["TIMINGRULEFREQUENCY"] == YEARLY:
            requireddate += datetime.timedelta(days=nofreq * 365)

    # Create correct number of records
    norecs = am["TIMINGRULE"]
    if norecs == 0: norecs = 1

    for x in range(1, norecs + 1):
        sql = db.make_insert_user_sql(
            dbo, "animalmedicaltreatment", username,
            (("ID", db.di(db.get_id(dbo, "animalmedicaltreatment"))),
             ("AnimalID", db.di(am["ANIMALID"])),
             ("AnimalMedicalID", db.di(amid)),
             ("DateRequired", db.dd(requireddate)), ("DateGiven", db.dd(None)),
             ("GivenBy", db.ds("")), ("TreatmentNumber", db.di(x)),
             ("TotalTreatments", db.di(norecs)), ("Comments", db.ds(""))))
        db.execute(dbo, sql)

    # Update the number of treatments given and remaining
    calculate_given_remaining(dbo, amid)
Exemplo n.º 44
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
Exemplo n.º 45
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"])
Exemplo n.º 46
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 = 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", nid, audit.dump_row(dbo, "animalfound", nid))

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

    return nid
Exemplo n.º 47
0
def insert_test_from_form(dbo, username, data):
    """
    Creates a test record from posted form data
    """
    l = dbo.locale
    if utils.df_kd(data, "required", l) is None:
        raise utils.ASMValidationError(_("Required date must be a valid date", l))

    ntestid = db.get_id(dbo, "animaltest")
    sql = db.make_insert_user_sql(dbo, "animaltest", username, ( 
        ( "ID", db.di(ntestid)),
        ( "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"))
        ))
    db.execute(dbo, sql)
    audit.create(dbo, username, "animaltest", str(ntestid))
    # ASM2_COMPATIBILITY
    update_asm2_tests(dbo, ntestid)
    return ntestid
Exemplo n.º 48
0
def insert_test_from_form(dbo, username, data):
    """
    Creates a test record from posted form data
    """
    l = dbo.locale
    if utils.df_kd(data, "required", l) is None:
        raise utils.ASMValidationError(
            _("Required date must be a valid date", l))

    ntestid = db.get_id(dbo, "animaltest")
    sql = db.make_insert_user_sql(
        dbo, "animaltest", username,
        (("ID", db.di(ntestid)), ("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"))))
    db.execute(dbo, sql)
    audit.create(dbo, username, "animaltest", str(ntestid))
    # ASM2_COMPATIBILITY
    update_asm2_tests(dbo, ntestid)
    return ntestid
Exemplo n.º 49
0
def insert_person_from_form(dbo, data, username):
    """
    Creates a new person record from incoming form data
    data: The webpy data object containing form parameters
    Returns the ID of the new record
    """
    def d(key, default = None): 
        if data.has_key(key):
            return utils.df_ks(data, key)
        else:
            return default

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

    pid = db.get_id(dbo, "owner")
    sql = db.make_insert_user_sql(dbo, "owner", username, (
        ( "ID", db.di(pid) ),
        ( "OwnerName", db.ds("%s %s %s" % ( d("title", ""), d("forenames", ""), d("surname", "") ))),
        ( "OwnerTitle", db.ds(d("title", "") )),
        ( "OwnerInitials", db.ds(d("initials", "") )),
        ( "OwnerForenames", db.ds(d("forenames", "") )),
        ( "OwnerSurname", db.ds(d("surname", "") )),
        ( "OwnerAddress", db.ds(d("address", "") )),
        ( "OwnerTown", db.ds(d("town", "") )),
        ( "OwnerCounty", db.ds(d("county", "") )),
        ( "OwnerPostcode", db.ds(d("postcode", "") )),
        ( "LatLong", db.ds(d("latlong", "") )),
        ( "HomeTelephone", db.ds(d("hometelephone", "") )),
        ( "WorkTelephone", db.ds(d("worktelephone", "") )),
        ( "MobileTelephone", db.ds(d("mobiletelephone", "") )),
        ( "EmailAddress", db.ds(d("emailaddress", "") )),
        ( "IDCheck", db.di(homechecked) ),
        ( "Comments", db.ds(d("comments") )),
        ( "IsBanned", db.di(banned)),
        ( "IsVolunteer", db.di(volunteer)),
        ( "IsMember", db.di(member)),
        ( "MembershipExpiryDate", db.dd(d("membershipexpirydate") )),
        ( "MembershipNumber", db.ds(d("membershipnumber"))),
        ( "IsHomeChecker", db.di(homechecker)),
        ( "IsDonor", db.di(donor)),
        ( "IsShelter", db.di(shelter)),
        ( "IsACO", db.di(aco)),
        ( "IsStaff", db.di(staff)),
        ( "IsFosterer", db.di(fosterer)),
        ( "IsRetailer", db.di(retailer)),
        ( "IsVet", db.di(vet)),
        ( "IsGiftAid", db.di(giftaid)),
        ( "AdditionalFlags", db.ds(flagstr)),
        ( "HomeCheckAreas", db.ds(d("homecheckareas", "") )),
        ( "DateLastHomeChecked", db.dd(d("datelasthomechecked") )),
        ( "HomeCheckedBy", db.di(d("homecheckedby", 0) )),
        ( "MatchAdded", db.dd(d("matchadded") )),
        ( "MatchExpires", db.dd(d("matchexpires") )),
        ( "MatchActive", db.di(d("matchactive", 0) )),
        ( "MatchSex", db.di(d("matchsex", -1) )),
        ( "MatchSize", db.di(d("matchsize", -1) )),
        ( "MatchColour", db.di(d("matchcolour", -1) )),
        ( "MatchAgeFrom", db.di(d("matchagefrom", 0) )),
        ( "MatchAgeTo", db.di(d("matchageto", 0) )),
        ( "MatchAnimalType", db.di(d("matchanimaltype", -1) )),
        ( "MatchSpecies", db.di(d("matchspecies", -1) )),
        ( "MatchBreed", db.di(d("matchbreed", -1) )),
        ( "MatchBreed2", db.di(d("matchbreed2", -1) )),
        ( "MatchGoodWithCats", db.di(d("matchgoodwithcats", -1) )),
        ( "MatchGoodWithDogs", db.di(d("matchgoodwithdogs", -1) )),
        ( "MatchGoodWithChildren", db.di(d("matchgoodwithchildren", -1) )),
        ( "MatchHouseTrained", db.di(d("matchhousetrained", -1) )),
        ( "MatchCommentsContain", db.ds(d("matchcommentscontain") )
    )))
    db.execute(dbo, sql)
    audit.create(dbo, username, "owner", str(pid) + " %s %s %s" % (d("title"), d("forenames"), d("surname")))
    return pid
Exemplo n.º 50
0
def update_matching_transaction(dbo, username, odid):
    """
    Creates a matching account transaction for a donation or updates
    an existing trx if it already exists
    """
    # Don't do anything if we aren't creating matching transactions
    if not configuration.create_donation_trx(dbo):
        al.debug("Create donation trx is off, not creating trx.",
                 "financial.update_matching_transaction", dbo)
        return

    dr = db.query(dbo, "SELECT * FROM ownerdonation WHERE ID = %d" % int(odid))
    if dr is None or len(dr) == 0:
        al.error(
            "No matching transaction for %d found in database, bailing" %
            int(odid), "financial.update_matching_transaction", dbo)
        return

    d = dr[0]

    # If the donation hasn't been received, don't do anything
    if d["DATE"] is None:
        al.debug("Donation not received, not creating trx.",
                 "financial.update_matching_transaction", dbo)
        return
    # Do we already have an existing transaction for this donation?
    # If we do, we only need to check the amounts as it's now the
    # users problem if they picked the wrong donationtype/account
    trxid = db.query_int(
        dbo,
        "SELECT ID FROM accountstrx WHERE OwnerDonationID = %d" % int(odid))
    if trxid != 0:
        al.debug(
            "Already have an existing transaction, updating amount to %d" %
            d["DONATION"], "financial.update_matching_transaction", dbo)
        db.execute(
            dbo, "UPDATE accountstrx SET Amount = %d WHERE ID = %d" %
            (d["DONATION"], trxid))
        return
    # ========== NOT USED - we used to force regeneration
    #                       instead of checking for the existing transaction
    # Delete any existing transaction for this donation if there is one
    # al.debug("Removing any existing trx for this donation.", "financial.update_matching_transaction", dbo)
    # db.execute(dbo, "DELETE FROM accountstrx WHERE OwnerDonationID = %d" % int(odid))
    # ========== NOT USED
    # Get the source account for this type of donation, use the first income account on file for that type
    source = db.query_int(
        dbo,
        "SELECT ID FROM accounts WHERE AccountType = %d AND DonationTypeID = %d ORDER BY ID"
        % (INCOME, int(d["DONATIONTYPEID"])))
    if source == 0:
        # This shouldn't happen, but we can't go ahead without an account
        raise utils.ASMValidationError(
            "No source account found for donation type, can't create trx")
    # Get the target account
    target = configuration.donation_target_account(dbo)
    al.debug("Target account in config is: %s" % target,
             "financial.update_matching_transaction", dbo)
    # If no target is configured, use the first bank account on file
    if target == 0:
        target = db.query_int(dbo,
                              "SELECT ID FROM accounts WHERE AccountType = 1")
        al.debug("Got blank target, getting first bank account: %s" % target,
                 "financial.update_matching_transaction", dbo)
        if target == 0:
            # Shouldn't happen, but we have no bank accounts on file
            al.error("No target available for trx. Bailing.",
                     "financial.update_matching_transaction", dbo)
            raise utils.ASMValidationError(
                "No bank accounts on file, can't set target for donation trx")
    # Has a mapping been created by the user for this donation type
    # to a destination other than the default?
    maps = configuration.donation_account_mappings(dbo)
    if maps.has_key(str(d["DONATIONTYPEID"])):
        target = maps[str(d["DONATIONTYPEID"])]
        al.debug(
            "Found override for donationtype %s, got new target account %s" %
            (str(d["DONATIONTYPEID"]), str(target)),
            "financial.update_matching_transaction", dbo)
    # Is the donation for a negative amount? If so, flip the accounts
    # round as this is a refund donation and make the amount positive.
    amount = d["DONATION"]
    if amount < 0:
        oldtarget = target
        target = source
        source = oldtarget
        amount = abs(amount)
    # Create the transaction
    tid = db.get_id(dbo, "accountstrx")
    sql = db.make_insert_user_sql(
        dbo, "accountstrx", username,
        (("ID", db.di(tid)), ("TrxDate", db.dd(d["DATE"])),
         ("Description", db.ds(d["COMMENTS"])), ("Reconciled", db.di(0)),
         ("Amount", db.di(amount)), ("SourceAccountID", db.di(source)),
         ("DestinationAccountID", db.di(target)),
         ("OwnerDonationID", db.di(int(odid)))))
    db.execute(dbo, sql)
    al.debug("Trx created with ID %d" % int(tid),
             "financial.update_matching_transaction", dbo)
Exemplo n.º 51
0
def insert_person_from_form(dbo, data, username):
    """
    Creates a new person record from incoming form data
    data: The webpy data object containing form parameters
    Returns the ID of the new record
    """
    def d(key, default=None):
        if data.has_key(key):
            return utils.df_ks(data, key)
        else:
            return default

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

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

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

    pid = db.get_id(dbo, "owner")
    sql = db.make_insert_user_sql(
        dbo, "owner", username,
        (("ID", db.di(pid)),
         ("OwnerName",
          db.ds("%s %s %s" %
                (d("title", ""), d("forenames", ""), d("surname", "")))),
         ("OwnerTitle", db.ds(d("title", ""))),
         ("OwnerInitials", db.ds(d("initials", ""))),
         ("OwnerForenames", db.ds(d("forenames", ""))),
         ("OwnerSurname", db.ds(d("surname", ""))),
         ("OwnerAddress", db.ds(d("address", ""))),
         ("OwnerTown", db.ds(d("town", ""))),
         ("OwnerCounty", db.ds(d("county", ""))),
         ("OwnerPostcode", db.ds(d("postcode", ""))),
         ("LatLong", db.ds(d("latlong", ""))),
         ("HomeTelephone", db.ds(d("hometelephone", ""))),
         ("WorkTelephone", db.ds(d("worktelephone", ""))),
         ("MobileTelephone", db.ds(d("mobiletelephone", ""))),
         ("EmailAddress", db.ds(d("emailaddress", ""))),
         ("IDCheck", db.di(homechecked)), ("Comments", db.ds(
             d("comments"))), ("IsBanned", db.di(banned)),
         ("IsVolunteer", db.di(volunteer)), ("IsMember", db.di(member)),
         ("MembershipExpiryDate", db.dd(d("membershipexpirydate"))),
         ("MembershipNumber", db.ds(d("membershipnumber"))),
         ("IsHomeChecker", db.di(homechecker)), ("IsDonor", db.di(donor)),
         ("IsShelter", db.di(shelter)), ("IsACO", db.di(aco)),
         ("IsStaff", db.di(staff)), ("IsFosterer", db.di(fosterer)),
         ("IsRetailer", db.di(retailer)), ("IsVet", db.di(vet)),
         ("IsGiftAid", db.di(giftaid)), ("AdditionalFlags", db.ds(flagstr)),
         ("HomeCheckAreas", db.ds(d("homecheckareas", ""))),
         ("DateLastHomeChecked", db.dd(d("datelasthomechecked"))),
         ("HomeCheckedBy", db.di(d(
             "homecheckedby", 0))), ("MatchAdded", db.dd(
                 d("matchadded"))), ("MatchExpires", db.dd(d("matchexpires"))),
         ("MatchActive", db.di(d(
             "matchactive", 0))), ("MatchSex", db.di(d(
                 "matchsex", -1))), ("MatchSize", db.di(d("matchsize", -1))),
         ("MatchColour", db.di(d(
             "matchcolour", -1))), ("MatchAgeFrom", db.di(d(
                 "matchagefrom", 0))), ("MatchAgeTo", db.di(d(
                     "matchageto", 0))), ("MatchAnimalType",
                                          db.di(d("matchanimaltype", -1))),
         ("MatchSpecies", db.di(d(
             "matchspecies", -1))), ("MatchBreed", db.di(d("matchbreed", -1))),
         ("MatchBreed2", db.di(d("matchbreed2", -1))),
         ("MatchGoodWithCats", db.di(
             d("matchgoodwithcats",
               -1))), ("MatchGoodWithDogs", db.di(d("matchgoodwithdogs", -1))),
         ("MatchGoodWithChildren", db.di(
             d("matchgoodwithchildren",
               -1))), ("MatchHouseTrained", db.di(d("matchhousetrained", -1))),
         ("MatchCommentsContain", db.ds(d("matchcommentscontain")))))
    db.execute(dbo, sql)
    audit.create(
        dbo, username, "owner",
        str(pid) + " %s %s %s" % (d("title"), d("forenames"), d("surname")))
    return pid
Exemplo n.º 52
0
def update_matching_transaction(dbo, username, odid):
    """
    Creates a matching account transaction for a donation or updates
    an existing trx if it already exists
    """
    # Don't do anything if we aren't creating matching transactions
    if not configuration.create_donation_trx(dbo): 
        al.debug("Create donation trx is off, not creating trx.", "financial.update_matching_transaction", dbo)
        return

    dr = db.query(dbo, "SELECT * FROM ownerdonation WHERE ID = %d" % int(odid))
    if dr is None or len(dr) == 0:
        al.error("No matching transaction for %d found in database, bailing" % int(odid), "financial.update_matching_transaction", dbo)
        return

    d = dr[0]

    # If the donation hasn't been received, don't do anything
    if d["DATE"] is None: 
        al.debug("Donation not received, not creating trx.", "financial.update_matching_transaction", dbo)
        return
    # Do we already have an existing transaction for this donation?
    # If we do, we only need to check the amounts as it's now the
    # users problem if they picked the wrong donationtype/account
    trxid = db.query_int(dbo, "SELECT ID FROM accountstrx WHERE OwnerDonationID = %d" % int(odid))
    if trxid != 0:
        al.debug("Already have an existing transaction, updating amount to %d" % d["DONATION"], "financial.update_matching_transaction", dbo)
        db.execute(dbo, "UPDATE accountstrx SET Amount = %d WHERE ID = %d" % (d["DONATION"], trxid))
        return
    # ========== NOT USED - we used to force regeneration
    #                       instead of checking for the existing transaction
    # Delete any existing transaction for this donation if there is one
    # al.debug("Removing any existing trx for this donation.", "financial.update_matching_transaction", dbo)
    # db.execute(dbo, "DELETE FROM accountstrx WHERE OwnerDonationID = %d" % int(odid))
    # ========== NOT USED
    # Get the source account for this type of donation, use the first income account on file for that type
    source = db.query_int(dbo, "SELECT ID FROM accounts WHERE AccountType = %d AND DonationTypeID = %d ORDER BY ID" % (INCOME, int(d["DONATIONTYPEID"])))
    if source == 0:
        # This shouldn't happen, but we can't go ahead without an account
        raise utils.ASMValidationError("No source account found for donation type, can't create trx")
    # Get the target account
    target = configuration.donation_target_account(dbo)
    al.debug("Target account in config is: %s" % target, "financial.update_matching_transaction", dbo)
    # If no target is configured, use the first bank account on file
    if target == 0:
        target = db.query_int(dbo, "SELECT ID FROM accounts WHERE AccountType = 1")
        al.debug("Got blank target, getting first bank account: %s" % target, "financial.update_matching_transaction", dbo)
        if target == 0:
            # Shouldn't happen, but we have no bank accounts on file
            al.error("No target available for trx. Bailing.", "financial.update_matching_transaction", dbo)
            raise utils.ASMValidationError("No bank accounts on file, can't set target for donation trx")
    # Has a mapping been created by the user for this donation type
    # to a destination other than the default?
    maps = configuration.donation_account_mappings(dbo)
    if maps.has_key(str(d["DONATIONTYPEID"])):
        target = maps[str(d["DONATIONTYPEID"])]
        al.debug("Found override for donationtype %s, got new target account %s" % (str(d["DONATIONTYPEID"]), str(target)), "financial.update_matching_transaction", dbo)
    # Is the donation for a negative amount? If so, flip the accounts
    # round as this is a refund donation and make the amount positive.
    amount = d["DONATION"]
    if amount < 0:
        oldtarget = target
        target = source
        source = oldtarget
        amount = abs(amount)
    # Create the transaction
    tid = db.get_id(dbo, "accountstrx")
    sql = db.make_insert_user_sql(dbo, "accountstrx", username, (
        ( "ID", db.di(tid) ),
        ( "TrxDate", db.dd(d["DATE"])),
        ( "Description", db.ds(d["COMMENTS"])),
        ( "Reconciled", db.di(0)),
        ( "Amount", db.di(amount)),
        ( "SourceAccountID", db.di(source)),
        ( "DestinationAccountID", db.di(target)),
        ( "OwnerDonationID", db.di(int(odid)))
        ))
    db.execute(dbo, sql)
    al.debug("Trx created with ID %d" % int(tid), "financial.update_matching_transaction", dbo)