Example #1
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)
Example #2
0
def update_waitinglist_from_form(dbo, data, username):
    """
    Updates a waiting list record from the screen
    data: The webpy data object containing form parameters
    """
    l = dbo.locale
    wlid = utils.df_ki(data, "id")
    if utils.df_ks(data, "description") == "":
        raise utils.ASMValidationError(_("Description cannot be blank", l))
    if utils.df_ki(data, "owner") == "0":
        raise utils.ASMValidationError(_("Waiting list entries must have a contact", l))
    if utils.df_ks(data, "dateputon") == "":
        raise utils.ASMValidationError(_("Date put on cannot be blank", l))

    preaudit = db.query(dbo, "SELECT * FROM animalwaitinglist WHERE ID = %d" % wlid)
    db.execute(dbo, db.make_update_user_sql(dbo, "animalwaitinglist", username, "ID=%d" % wlid, (
        ( "SpeciesID", utils.df_s(data, "species")),
        ( "DatePutOnList", utils.df_d(data, "dateputon", l)),
        ( "OwnerID", utils.df_s(data, "owner")),
        ( "AnimalDescription", utils.df_t(data, "description")),
        ( "ReasonForWantingToPart", utils.df_t(data, "reasonforwantingtopart")),
        ( "CanAffordDonation", utils.df_c(data, "canafforddonation")), 
        ( "Urgency", utils.df_s(data, "urgency")),
        ( "DateRemovedFromList", utils.df_d(data, "dateremoved", l)),
        ( "AutoRemovePolicy", utils.df_s(data, "autoremovepolicy")),
        ( "DateOfLastOwnerContact", utils.df_d(data, "dateoflastownercontact", l)),
        ( "ReasonForRemoval", utils.df_t(data, "reasonforremoval")),
        ( "Comments", utils.df_t(data, "comments"))
        )))
    additional.save_values_for_link(dbo, data, wlid, "waitinglist")
    postaudit = db.query(dbo, "SELECT * FROM animalwaitinglist WHERE ID = %d" % wlid)
    audit.edit(dbo, username, "animalwaitinglist", audit.map_diff(preaudit, postaudit))
Example #3
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)
Example #4
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
Example #5
0
def update_foundanimal_from_form(dbo, data, username):
    """
    Updates a found animal record from the screen
    data: The webpy data object containing form parameters
    """
    l = dbo.locale
    lfid = utils.df_ki(data, "id")
    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))

    preaudit = db.query(dbo, "SELECT * FROM animalfound WHERE ID = %d" % lfid)
    db.execute(dbo, db.make_update_user_sql(dbo, "animalfound", username, "ID=%d" % lfid, (
        ( "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"))
        )))
    additional.save_values_for_link(dbo, data, lfid, "foundanimal")
    postaudit = db.query(dbo, "SELECT * FROM animalfound WHERE ID = %d" % lfid)
    audit.edit(dbo, username, "animalfound", audit.map_diff(preaudit, postaudit))
Example #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"))
Example #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
Example #8
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
Example #9
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"))
Example #10
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
Example #11
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))
Example #12
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
Example #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
Example #14
0
def update_diary_from_form(dbo, username, data):
    """
    Updates a diary note from form data
    """
    l = dbo.locale
    diaryid = utils.df_ki(data, "diaryid")
    if utils.df_ks(data, "diarydate") == "":
        raise utils.ASMValidationError(i18n._("Diary date cannot be blank", l))
    if utils.df_kd(data, "diarydate", l) is None:
        raise utils.ASMValidationError(i18n._("Diary date is not valid", l))
    if utils.df_ks(data, "subject") == "":
        raise utils.ASMValidationError(i18n._("Diary subject cannot be blank", l))
    if utils.df_ks(data, "note") == "":
        raise utils.ASMValidationError(i18n._("Diary note cannot be blank", l))
    diarytime =  utils.df_ks(data, "diarytime").strip()
    if diarytime != "":
        if diarytime.find(":") == -1:
            raise utils.ASMValidationError(i18n._("Invalid time, times should be in HH:MM format", l))
        if not utils.is_numeric(diarytime.replace(":", "")):
            raise utils.ASMValidationError(i18n._("Invalid time, times should be in HH:MM format", l))

    sql = db.make_update_user_sql(dbo, "diary", username, "ID=%d" % diaryid, (
        ( "DiaryDateTime", utils.df_dt(data, "diarydate", "diarytime", l) ),
        ( "DiaryForName", utils.df_t(data, "diaryfor") ),
        ( "Subject", utils.df_t(data, "subject") ),
        ( "Note", utils.df_t(data, "note") ),
        ( "Comments", utils.df_t(data, "comments") ),
        ( "DateCompleted", utils.df_d(data, "completed", l) )
        ))
    preaudit = db.query(dbo, "SELECT * FROM diary WHERE ID=%d" % diaryid)
    db.execute(dbo, sql)
    postaudit = db.query(dbo, "SELECT * FROM diary WHERE ID=%d" % diaryid)
    audit.edit(dbo, username, "diary", audit.map_diff(preaudit, postaudit))
Example #15
0
def update_voucher_from_form(dbo, username, data):
    """
    Updates a voucher record from posted form data
    """
    l = dbo.locale
    voucherid = utils.df_ki(data, "voucherid")
    sql = db.make_update_user_sql(dbo, "ownervoucher", username, "ID=%d" % voucherid, ( 
        ( "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"))
    ))
    preaudit = db.query(dbo, "SELECT * FROM ownervoucher WHERE ID = %d" % voucherid)
    db.execute(dbo, sql)
    postaudit = db.query(dbo, "SELECT * FROM ownervoucher WHERE ID = %d" % voucherid)
    audit.edit(dbo, username, "ownervoucher", audit.map_diff(preaudit, postaudit))
Example #16
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
Example #17
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
Example #18
0
def update_voucher_from_form(dbo, username, data):
    """
    Updates a voucher record from posted form data
    """
    l = dbo.locale
    voucherid = utils.df_ki(data, "voucherid")
    sql = db.make_update_user_sql(
        dbo, "ownervoucher", username, "ID=%d" % voucherid,
        (("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"))))
    preaudit = db.query(dbo,
                        "SELECT * FROM ownervoucher WHERE ID = %d" % voucherid)
    db.execute(dbo, sql)
    postaudit = db.query(
        dbo, "SELECT * FROM ownervoucher WHERE ID = %d" % voucherid)
    audit.edit(dbo, username, "ownervoucher",
               audit.map_diff(preaudit, postaudit))
Example #19
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
Example #20
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))
Example #21
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
Example #22
0
def update_waitinglist_from_form(dbo, data, username):
    """
    Updates a waiting list record from the screen
    data: The webpy data object containing form parameters
    """
    l = dbo.locale
    wlid = utils.df_ki(data, "id")
    if utils.df_ks(data, "description") == "":
        raise utils.ASMValidationError(_("Description cannot be blank", l))
    if utils.df_ki(data, "owner") == "0":
        raise utils.ASMValidationError(
            _("Waiting list entries must have a contact", l))
    if utils.df_ks(data, "dateputon") == "":
        raise utils.ASMValidationError(_("Date put on cannot be blank", l))

    preaudit = db.query(dbo,
                        "SELECT * FROM animalwaitinglist WHERE ID = %d" % wlid)
    db.execute(
        dbo,
        db.make_update_user_sql(
            dbo, "animalwaitinglist", username, "ID=%d" % wlid,
            (("SpeciesID", utils.df_s(data, "species")),
             ("DatePutOnList", utils.df_d(data, "dateputon", l)),
             ("OwnerID", utils.df_s(data, "owner")),
             ("AnimalDescription", utils.df_t(data, "description")),
             ("ReasonForWantingToPart",
              utils.df_t(data, "reasonforwantingtopart")),
             ("CanAffordDonation", utils.df_c(data, "canafforddonation")),
             ("Urgency", utils.df_s(data, "urgency")),
             ("DateRemovedFromList", utils.df_d(data, "dateremoved", l)),
             ("AutoRemovePolicy", utils.df_s(data, "autoremovepolicy")),
             ("DateOfLastOwnerContact",
              utils.df_d(data, "dateoflastownercontact", l)),
             ("ReasonForRemoval", utils.df_t(data, "reasonforremoval")),
             ("Comments", utils.df_t(data, "comments")))))
    additional.save_values_for_link(dbo, data, wlid, "waitinglist")
    postaudit = db.query(
        dbo, "SELECT * FROM animalwaitinglist WHERE ID = %d" % wlid)
    audit.edit(dbo, username, "animalwaitinglist",
               audit.map_diff(preaudit, postaudit))
Example #23
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
Example #24
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)
Example #25
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)
Example #26
0
def update_investigation_from_form(dbo, username, data):
    """
    Updates an investigation record from posted form data
    """
    l = dbo.locale
    investigationid = utils.df_ki(data, "investigationid")
    sql = db.make_update_user_sql(dbo, "ownerinvestigation", username, "ID=%d" % investigationid, ( 
        ( "Date", utils.df_d(data, "date", l)),
        ( "Notes", utils.df_t(data, "notes"))
        ))
    preaudit = db.query(dbo, "SELECT * FROM ownerinvestigation WHERE ID = %d" % investigationid)
    db.execute(dbo, sql)
    postaudit = db.query(dbo, "SELECT * FROM ownerinvestigation WHERE ID = %d" % investigationid)
    audit.edit(dbo, username, "ownerinvestigation", audit.map_diff(preaudit, postaudit))
Example #27
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)
Example #28
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
Example #29
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
Example #30
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
Example #31
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)
Example #32
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
Example #33
0
def update_log_from_form(dbo, username, data):
    """
    Updates a log from form data
    """
    l = dbo.locale
    logid = utils.df_ki(data, "logid")
    if utils.df_kd(data, "logdate", l) is None:
        raise utils.ASMValidationError(i18n._("Log date must be a valid date", l))
    sql = db.make_update_user_sql(dbo, "log", username, "ID=%d" % logid, (
        ( "LogTypeID", utils.df_s(data, "type")),
        ( "Date", utils.df_d(data, "logdate", l) ),
        ( "Comments", utils.df_t(data, "entry") )
        ))
    preaudit = db.query(dbo, "SELECT * FROM log WHERE ID=%d" % logid)
    db.execute(dbo, sql)
    postaudit = db.query(dbo, "SELECT * FROM log WHERE ID=%d" % logid)
    audit.edit(dbo, username, "log", audit.map_diff(preaudit, postaudit))
Example #34
0
def update_investigation_from_form(dbo, username, data):
    """
    Updates an investigation record from posted form data
    """
    l = dbo.locale
    investigationid = utils.df_ki(data, "investigationid")
    sql = db.make_update_user_sql(dbo, "ownerinvestigation", username,
                                  "ID=%d" % investigationid,
                                  (("Date", utils.df_d(data, "date", l)),
                                   ("Notes", utils.df_t(data, "notes"))))
    preaudit = db.query(
        dbo,
        "SELECT * FROM ownerinvestigation WHERE ID = %d" % investigationid)
    db.execute(dbo, sql)
    postaudit = db.query(
        dbo,
        "SELECT * FROM ownerinvestigation WHERE ID = %d" % investigationid)
    audit.edit(dbo, username, "ownerinvestigation",
               audit.map_diff(preaudit, postaudit))
Example #35
0
def insert_diary_from_form(dbo, username, linktypeid, linkid, data):
    """
    Creates a diary note from the form data
    username: User creating the diary
    linktypeid, linkid: The link
    data: The web.py form object
    """
    l = dbo.locale
    if utils.df_ks(data, "diarydate") == "":
        raise utils.ASMValidationError(i18n._("Diary date cannot be blank", l))
    if utils.df_kd(data, "diarydate", l) is None:
        raise utils.ASMValidationError(i18n._("Diary date is not valid", l))
    if utils.df_ks(data, "subject") == "":
        raise utils.ASMValidationError(
            i18n._("Diary subject cannot be blank", l))
    if utils.df_ks(data, "note") == "":
        raise utils.ASMValidationError(i18n._("Diary note cannot be blank", l))
    diarytime = utils.df_ks(data, "diarytime").strip()
    if diarytime != "":
        if diarytime.find(":") == -1:
            raise utils.ASMValidationError(
                i18n._("Invalid time, times should be in HH:MM format", l))
        if not utils.is_numeric(diarytime.replace(":", "")):
            raise utils.ASMValidationError(
                i18n._("Invalid time, times should be in HH:MM format", l))

    linkinfo = get_link_info(dbo, linktypeid, linkid)
    diaryid = db.get_id(dbo, "diary")
    sql = db.make_insert_user_sql(
        dbo, "diary", username,
        (("ID", db.di(diaryid)), ("LinkID", db.di(linkid)),
         ("LinkType", db.di(linktypeid)), ("LinkInfo", db.ds(linkinfo)),
         ("DiaryDateTime", utils.df_dt(data, "diarydate", "diarytime", l)),
         ("DiaryForName", utils.df_t(data, "diaryfor")),
         ("Subject", utils.df_t(data, "subject")),
         ("Note", utils.df_t(data, "note")),
         ("DateCompleted", utils.df_d(data, "completed", l))))
    db.execute(dbo, sql)
    audit.create(dbo, username, "diary", str(diaryid))
    return diaryid
Example #36
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
Example #37
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
Example #38
0
def update_diary_from_form(dbo, username, data):
    """
    Updates a diary note from form data
    """
    l = dbo.locale
    diaryid = utils.df_ki(data, "diaryid")
    if utils.df_ks(data, "diarydate") == "":
        raise utils.ASMValidationError(i18n._("Diary date cannot be blank", l))
    if utils.df_kd(data, "diarydate", l) is None:
        raise utils.ASMValidationError(i18n._("Diary date is not valid", l))
    if utils.df_ks(data, "subject") == "":
        raise utils.ASMValidationError(
            i18n._("Diary subject cannot be blank", l))
    if utils.df_ks(data, "note") == "":
        raise utils.ASMValidationError(i18n._("Diary note cannot be blank", l))
    diarytime = utils.df_ks(data, "diarytime").strip()
    if diarytime != "":
        if diarytime.find(":") == -1:
            raise utils.ASMValidationError(
                i18n._("Invalid time, times should be in HH:MM format", l))
        if not utils.is_numeric(diarytime.replace(":", "")):
            raise utils.ASMValidationError(
                i18n._("Invalid time, times should be in HH:MM format", l))

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

    # Save any additional field values given
    additional.save_values_for_link(dbo, data, pid, "person")
Example #40
0
def update_person_from_form(dbo, data, username):
    """
    Updates an existing person record from incoming form data
    data: The webpy data object containing form parameters
    """
    l = dbo.locale
    pid = utils.df_ki(data, "id")
    flags = utils.df_ks(data, "flags").split(",")

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

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

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