Beispiel #1
0
def org_tags(dbo, username):
    """
    Generates a list of tags from the organisation and user info
    """
    u = users.get_users(dbo, username)
    realname = ""
    email = ""
    if len(u) > 0:
        u = u[0]
        realname = u["REALNAME"]
        email = u["EMAILADDRESS"]
    tags = {
        "ORGANISATION"          : configuration.organisation(dbo),
        "ORGANISATIONADDRESS"   : configuration.organisation_address(dbo),
        "ORGANISATIONTELEPHONE" : configuration.organisation_telephone(dbo),
        "DATE"                  : python2display(dbo.locale, now(dbo.timezone)),
        "USERNAME"              : username,
        "USERREALNAME"          : realname,
        "USEREMAILADDRESS"      : email
    }
    return tags
Beispiel #2
0
 def substituteHFTag(self, searchin, page, user, title=""):
     """
     Substitutes special header and footer tokens in searchin. page
     contains the current page number.
     """
     output = searchin
     nav = self.navbar.replace(
         "<a href=\"%d.%s\">%d</a>" % (page, self.pc.extension, page),
         str(page))
     dateportion = i18n.python2display(self.locale,
                                       i18n.now(self.dbo.timezone))
     timeportion = i18n.format_date("%H:%M:%S", i18n.now(self.dbo.timezone))
     if page != -1:
         output = output.replace("$$NAV$$", nav)
     else:
         output = output.replace("$$NAV$$", "")
     output = output.replace("$$TITLE$$", title)
     output = output.replace("$$TOTAL$$", str(self.totalAnimals))
     output = output.replace("$$DATE$$", dateportion)
     output = output.replace("$$TIME$$", timeportion)
     output = output.replace("$$DATETIME$$",
                             "%s %s" % (dateportion, timeportion))
     output = output.replace("$$VERSION$$", i18n.get_version())
     output = output.replace("$$REGISTEREDTO$$",
                             configuration.organisation(self.dbo))
     output = output.replace(
         "$$USER$$",
         "%s (%s)" % (user, users.get_real_name(self.dbo, user)))
     output = output.replace("$$ORGNAME$$",
                             configuration.organisation(self.dbo))
     output = output.replace("$$ORGADDRESS$$",
                             configuration.organisation_address(self.dbo))
     output = output.replace("$$ORGTEL$$",
                             configuration.organisation_telephone(self.dbo))
     output = output.replace("$$ORGEMAIL$$", configuration.email(self.dbo))
     return output
Beispiel #3
0
    def run(self):
        
        self.log("PetRescuePublisher starting...")

        if self.isPublisherExecuting(): return
        self.updatePublisherProgress(0)
        self.setLastError("")
        self.setStartPublishing()

        token = configuration.petrescue_token(self.dbo)
        all_desexed = configuration.petrescue_all_desexed(self.dbo)
        interstate = configuration.petrescue_interstate(self.dbo)
        postcode = configuration.organisation_postcode(self.dbo)
        suburb = configuration.organisation_town(self.dbo)
        state = configuration.organisation_county(self.dbo)
        contact_name = configuration.organisation(self.dbo)
        contact_email = configuration.petrescue_email(self.dbo)
        if contact_email == "": contact_email = configuration.email(self.dbo)
        contact_number = configuration.organisation_telephone(self.dbo)

        if token == "":
            self.setLastError("No PetRescue auth token has been set.")
            return

        if postcode == "" or contact_email == "":
            self.setLastError("You need to set your organisation postcode and contact email under Settings->Options->Shelter Details->Email")
            return

        animals = self.getMatchingAnimals(includeAdditionalFields=True)
        processed = []

        if len(animals) == 0:
            self.setLastError("No animals found to publish.")
            self.cleanup()
            return

        headers = { "Authorization": "Token token=%s" % token, "Accept": "*/*" }

        anCount = 0
        for an in animals:
            try:
                anCount += 1
                self.log("Processing: %s: %s (%d of %d)" % ( an["SHELTERCODE"], an["ANIMALNAME"], anCount, len(animals)))
                self.updatePublisherProgress(self.getProgress(anCount, len(animals)))

                # If the user cancelled, stop now
                if self.shouldStopPublishing(): 
                    self.log("User cancelled publish. Stopping.")
                    self.resetPublisherProgress()
                    self.cleanup()
                    return
       
                isdog = an.SPECIESID == 1
                iscat = an.SPECIESID == 2

                ageinyears = i18n.date_diff_days(an.DATEOFBIRTH, i18n.now())
               
                size = ""
                if an.SIZE == 2: size = "medium"
                elif an.SIZE < 2: size = "large"
                else: size = "small"

                coat = ""
                if an.COATTYPE == 0: coat = "short"
                elif an.COATTYPE == 1: coat = "long"
                else: coat = "medium_coat"

                origin = ""
                if an.ISTRANSFER == 1 and str(an.BROUGHTINBYOWNERNAME).lower().find("pound") == -1: origin = "shelter_transfer"
                elif an.ISTRANSFER == 1 and str(an.BROUGHTINBYOWNERNAME).lower().find("pound") != -1: origin = "pound_transfer"
                elif an.ORIGINALOWNERID > 0: origin = "owner_surrender"
                else: origin = "community_cat"

                best_feature = "Looking for love"
                if "BESTFEATURE" in an and an.BESTFEATURE != "":
                    best_feature = an.BESTFEATURE

                breeder_id = ""
                if "BREEDERID" in an and an.BREEDERID != "":
                    breeder_id = an.BREEDERID

                needs_constant_care = False
                if "NEEDSCONSTANTCARE" in an and an.NEEDSCONSTANTCARE != "" and an.NEEDSCONSTANTCARE != "0":
                    needs_constant_care = True

                # Check whether we've been vaccinated, wormed and hw treated
                vaccinated = medical.get_vaccinated(self.dbo, an.ID)
                sixmonths = self.dbo.today(offset=-182)
                hwtreated = isdog and self.dbo.query_int("SELECT COUNT(*) FROM animalmedical WHERE LOWER(TreatmentName) LIKE ? " \
                    "AND LOWER(TreatmentName) LIKE ? AND StartDate>? AND AnimalID=?", ("%heart%", "%worm%", sixmonths, an.ID)) > 0
                wormed = (isdog or iscat) and self.dbo.query_int("SELECT COUNT(*) FROM animalmedical WHERE LOWER(TreatmentName) LIKE ? " \
                    "AND LOWER(TreatmentName) NOT LIKE ? AND StartDate>? AND AnimalID=?", ("%worm%", "%heart%", sixmonths, an.ID)) > 0
                # PR want a null value to hide never-treated animals, so we
                # turn False into a null.
                if not hwtreated: hwtreated = None
                if not wormed: wormed = None

                # Use the fosterer's postcode, state and suburb if available
                location_postcode = postcode
                location_state_abbr = state
                location_suburb = suburb
                if an.ACTIVEMOVEMENTID and an.ACTIVEMOVEMENTTYPE == 2:
                    fr = self.dbo.first_row(self.dbo.query("SELECT OwnerTown, OwnerCounty, OwnerPostcode FROM adoption m " \
                        "INNER JOIN owner o ON m.OwnerID = o.ID WHERE m.ID=?", [ an.ACTIVEMOVEMENTID ]))
                    if fr is not None and fr.OWNERPOSTCODE: location_postcode = fr.OWNERPOSTCODE
                    if fr is not None and fr.OWNERCOUNTY: location_state_abbr = fr.OWNERCOUNTY
                    if fr is not None and fr.OWNERTOWN: location_suburb = fr.OWNERTOWN

                # Build a list of immutable photo URLs
                photo_urls = []
                photos = self.dbo.query("SELECT MediaName FROM media " \
                    "WHERE LinkTypeID = 0 AND LinkID = ? AND MediaMimeType = 'image/jpeg' " \
                    "AND (ExcludeFromPublish = 0 OR ExcludeFromPublish Is Null) " \
                    "ORDER BY WebsitePhoto DESC, ID", [an.ID])
                for m in photos:
                    photo_urls.append("%s?account=%s&method=dbfs_image&title=%s" % (SERVICE_URL, self.dbo.database, m.MEDIANAME))

                # Only send microchip_number for locations with a Victoria postcode 3xxx
                microchip_number = ""
                if location_postcode.startswith("3"):
                    microchip_number = utils.iif(an.IDENTICHIPPED == 1, an.IDENTICHIPNUMBER, "")

                # Construct a dictionary of info for this animal
                data = {
                    "remote_id":                str(an.ID), # animal identifier in ASM
                    "remote_source":            "SM%s" % self.dbo.database, # system/database identifier
                    "name":                     an.ANIMALNAME.title(), # animal name (title case, they validate against caps)
                    "shelter_code":             an.SHELTERCODE,
                    "adoption_fee":             i18n.format_currency_no_symbol(self.locale, an.FEE),
                    "species_name":             an.SPECIESNAME,
                    "breed_names":              self.get_breed_names(an), # [breed1,breed2] or [breed1]
                    "breeder_id":               breeder_id, # mandatory for QLD dogs born after 2017-05-26
                    "mix":                      an.CROSSBREED == 1, # true | false
                    "date_of_birth":            i18n.format_date("%Y-%m-%d", an.DATEOFBIRTH), # iso
                    "gender":                   an.SEXNAME.lower(), # male | female
                    "personality":              self.replace_html_entities(self.getDescription(an)), # 20-4000 chars of free type
                    "best_feature":             best_feature, # 25 chars free type, defaults to "Looking for love" requires BESTFEATURE additional field
                    "location_postcode":        location_postcode, # shelter/fosterer postcode
                    "location_state_abbr":      location_state_abbr, # shelter/fosterer state
                    "location_suburb":          location_suburb, # shelter/fosterer suburb
                    "microchip_number":         microchip_number, 
                    "desexed":                  an.NEUTERED == 1 or all_desexed, # true | false, validates to always true according to docs
                    "contact_method":           "email", # email | phone
                    "size":                     utils.iif(isdog, size, ""), # dogs only - small | medium | high
                    "senior":                   isdog and ageinyears > (7 * 365), # dogs only, true | false
                    "vaccinated":               vaccinated, # cats, dogs, rabbits, true | false
                    "wormed":                   wormed, # cats & dogs, true | false
                    "heart_worm_treated":       hwtreated, # dogs only, true | false
                    "coat":                     coat, # Only applies to cats and guinea pigs, but we send for everything: short | medium_coat | long
                    "intake_origin":            utils.iif(iscat, origin, ""), # cats only, community_cat | owner_surrender | pound_transfer | shelter_transfer
                    "incompatible_with_cats":   an.ISGOODWITHCATS == 1,
                    "incompatible_with_dogs":   an.ISGOODWITHDOGS == 1,
                    "incompatible_with_kids_under_5": an.ISGOODWITHCHILDREN == 1,
                    "incompatible_with_kids_6_to_12": an.ISGOODWITHCHILDREN == 1,
                    "needs_constant_care":      needs_constant_care,
                    "adoption_process":         "", # 4,000 chars how to adopt
                    "contact_details_source":   "self", # self | user | group
                    "contact_preferred_method": "email", # email | phone
                    "contact_name":             contact_name, # name of contact details owner
                    "contact_number":           contact_number, # number to enquire about adoption
                    "contact_email":            contact_email, # email to enquire about adoption
                    "foster_needed":            False, # true | false
                    "interstate":               interstate, # true | false - can the animal be flown to another state for adoption
                    "medical_notes":            "", # DISABLED an.HEALTHPROBLEMS, # 4,000 characters medical notes
                    "multiple_animals":         an.BONDEDANIMALID > 0 or an.BONDEDANIMAL2ID > 0, # More than one animal included in listing true | false
                    "photo_urls":               photo_urls, # List of photo URL strings
                    "status":                   "active" # active | removed | on_hold | rehomed | suspended | group_suspended
                }

                # PetRescue will insert/update accordingly based on whether remote_id/remote_source exists
                url = PETRESCUE_URL + "listings"
                jsondata = utils.json(data)
                self.log("Sending POST to %s to create/update listing: %s" % (url, jsondata))
                r = utils.post_json(url, jsondata, headers=headers)

                if r["status"] != 200:
                    self.logError("HTTP %d, headers: %s, response: %s" % (r["status"], r["headers"], self.utf8_to_ascii(r["response"])))
                else:
                    self.log("HTTP %d, headers: %s, response: %s" % (r["status"], r["headers"], self.utf8_to_ascii(r["response"])))
                    self.logSuccess("Processed: %s: %s (%d of %d)" % ( an["SHELTERCODE"], an["ANIMALNAME"], anCount, len(animals)))
                    processed.append(an)

            except Exception as err:
                self.logError("Failed processing animal: %s, %s" % (str(an["SHELTERCODE"]), err), sys.exc_info())

        try:
            # Get a list of all animals that we sent to PR recently (14 days)
            prevsent = self.dbo.query("SELECT AnimalID FROM animalpublished WHERE SentDate>=? AND PublishedTo='petrescue'", [self.dbo.today(offset=-14)])
            
            # Build a list of IDs we just sent, along with a list of ids for animals
            # that we previously sent and are not in the current sent list.
            # This identifies the listings we need to cancel
            animalids_just_sent = set([ x.ID for x in animals ])
            animalids_to_cancel = set([ str(x.ANIMALID) for x in prevsent if x.ANIMALID not in animalids_just_sent])

            # Get the animal records for the ones we need to cancel
            if len(animalids_to_cancel) == 0:
                animals = []
            else:
                animals = self.dbo.query("SELECT ID, ShelterCode, AnimalName, ActiveMovementDate, ActiveMovementType, DeceasedDate " \
                    "FROM animal a WHERE ID IN (%s)" % ",".join(animalids_to_cancel))

        except Exception as err:
            self.logError("Failed finding listings to cancel: %s" % err, sys.exc_info())

        # Cancel the inactive listings
        for an in animals:
            try:
                status = "on_hold"
                if an.ACTIVEMOVEMENTDATE is not None and an.ACTIVEMOVEMENTTYPE == 1: status = "rehomed"
                if an.DECEASEDDATE is not None: status = "removed"
                data = { "status": status }
                jsondata = utils.json(data)
                url = PETRESCUE_URL + "listings/%s/SM%s" % (an.ID, self.dbo.database)

                self.log("Sending PATCH to %s to update existing listing: %s" % (url, jsondata))
                r = utils.patch_json(url, jsondata, headers=headers)

                if r["status"] == 200:
                    self.log("HTTP %d, headers: %s, response: %s" % (r["status"], r["headers"], self.utf8_to_ascii(r["response"])))
                    self.logSuccess("%s - %s: Marked with new status %s" % (an.SHELTERCODE, an.ANIMALNAME, status))
                    # It used to be that we updated animalpublished for this animal to get sentdate to today
                    # we don't do this now so that we'll update dead listings every day for however many days we
                    # look back, but that's it
                else:
                    self.logError("HTTP %d, headers: %s, response: %s" % (r["status"], r["headers"], self.utf8_to_ascii(r["response"])))

            except Exception as err:
                self.logError("Failed closing listing for %s - %s: %s" % (an.SHELTERCODE, an.ANIMALNAME, err), sys.exc_info())

        # Mark sent animals published
        self.markAnimalsPublished(processed, first=True)

        self.cleanup()
Beispiel #4
0
    def run(self):

        self.log("PetRescuePublisher starting...")

        if self.isPublisherExecuting(): return
        self.updatePublisherProgress(0)
        self.setLastError("")
        self.setStartPublishing()

        token = configuration.petrescue_token(self.dbo)
        postcode = configuration.organisation_postcode(self.dbo)
        contact_name = configuration.organisation(self.dbo)
        contact_email = configuration.email(self.dbo)
        contact_number = configuration.organisation_telephone(self.dbo)

        if token == "":
            self.setLastError("No PetRescue auth token has been set.")
            return

        if postcode == "" or contact_email == "":
            self.setLastError(
                "You need to set your organisation postcode and contact email under Settings->Options->Shelter Details->Email"
            )
            return

        animals = self.getMatchingAnimals()
        processed = []

        if len(animals) == 0:
            self.setLastError("No animals found to publish.")
            self.cleanup()
            return

        headers = {"Authorization": "Token token=%s" % token, "Accept": "*/*"}

        anCount = 0
        for an in animals:
            try:
                anCount += 1
                self.log("Processing: %s: %s (%d of %d)" %
                         (an["SHELTERCODE"], an["ANIMALNAME"], anCount,
                          len(animals)))
                self.updatePublisherProgress(
                    self.getProgress(anCount, len(animals)))

                # If the user cancelled, stop now
                if self.shouldStopPublishing():
                    self.log("User cancelled publish. Stopping.")
                    self.resetPublisherProgress()
                    self.cleanup()
                    return

                isdog = an.SPECIESID == 1
                iscat = an.SPECIESID == 2

                ageinyears = i18n.date_diff_days(an.DATEOFBIRTH, i18n.now())

                vaccinated = medical.get_vaccinated(self.dbo, an.ID)

                size = ""
                if an.SIZE == 2: size = "medium"
                elif an.SIZE < 2: size = "large"
                else: size = "small"

                coat = ""
                if an.COATTYPE == 0: coat = "short"
                elif an.COATTYPE == 1: coat = "long"
                else: coat = "medium_coat"

                origin = ""
                if an.ISTRANSFER == 1 and an.BROUGHTINBYOWNERNAME.lower().find(
                        "pound") == -1:
                    origin = "shelter_transfer"
                elif an.ISTRANSFER == 1 and an.BROUGHTINBYOWNERNAME.lower(
                ).find("pound") != -1:
                    origin = "pound_transfer"
                elif an.ORIGINALOWNERID > 0:
                    origin = "owner_surrender"
                else:
                    origin = "community_cat"

                photo_url = "%s?account=%s&method=animal_image&animalid=%d" % (
                    SERVICE_URL, self.dbo.database, an.ID)

                # Construct a dictionary of info for this animal
                data = {
                    "remote_id":
                    str(an.ID),  # animal identifier in ASM
                    "remote_source":
                    "SM%s" % self.dbo.database,  # system/database identifier
                    "name":
                    an.ANIMALNAME,  # animal name
                    "adoption_fee":
                    i18n.format_currency_no_symbol(self.locale, an.FEE),
                    "species_name":
                    an.SPECIESNAME,
                    "breed_names":
                    self.get_breed_names(an),  # breed1,breed2 or breed1
                    "mix":
                    an.CROSSBREED == 1,  # true | false
                    "date_of_birth":
                    i18n.format_date("%Y-%m-%d", an.DATEOFBIRTH),  # iso
                    "gender":
                    an.SEXNAME.lower(),  # male | female
                    "personality":
                    an.WEBSITEMEDIANOTES,  # 20-4000 chars of free type
                    "location_postcode":
                    postcode,  # shelter postcode
                    "postcode":
                    postcode,  # shelter postcode
                    "microchip_number":
                    utils.iif(an.IDENTICHIPPED == 1, an.IDENTICHIPNUMBER, ""),
                    "desexed":
                    an.NEUTERED ==
                    1,  # true | false, validates to always true according to docs
                    "contact_method":
                    "email",  # email | phone
                    "size":
                    utils.iif(isdog, size,
                              ""),  # dogs only - small | medium | high
                    "senior":
                    isdog and ageinyears > 7,  # dogs only, true | false
                    "vaccinated":
                    vaccinated,  # cats, dogs, rabbits, true | false
                    "wormed":
                    vaccinated,  # cats & dogs, true | false
                    "heart_worm_treated":
                    vaccinated,  # dogs only, true | false
                    "coat":
                    utils.iif(iscat, coat,
                              ""),  # cats only, short | medium_coat | long
                    "intake_origin":
                    utils.iif(
                        iscat, origin, ""
                    ),  # cats only, community_cat | owner_surrender | pound_transfer | shelter_transfer
                    "adoption_process":
                    "",  # 4,000 chars how to adopt
                    "contact_details_source":
                    "self",  # self | user | group
                    "contact_preferred_method":
                    "email",  # email | phone
                    "contact_name":
                    contact_name,  # name of contact details owner
                    "contact_number":
                    contact_number,  # number to enquire about adoption
                    "contact_email":
                    contact_email,  # email to enquire about adoption
                    "foster_needed":
                    False,  # true | false
                    "interstate":
                    True,  # true | false - can the animal be adopted to another state
                    "medical_notes":
                    an.HEALTHPROBLEMS,  # 4,000 characters medical notes
                    "multiple_animals":
                    False,  # More than one animal included in listing true | false
                    "photo_urls": [photo_url],  # List of photo URL strings
                    "status":
                    "active"  # active | removed | on_hold | rehomed | suspended | group_suspended
                }

                # PetRescue will insert/update accordingly based on whether remote_id/remote_source exists
                url = PETRESCUE_URL + "listings"
                jsondata = utils.json(data)
                self.log("Sending POST to %s to create/update listing: %s" %
                         (url, jsondata))
                r = utils.post_json(url, jsondata, headers=headers)

                if r["status"] != 200:
                    self.logError("HTTP %d, headers: %s, response: %s" %
                                  (r["status"], r["headers"], r["response"]))
                else:
                    self.log("HTTP %d, headers: %s, response: %s" %
                             (r["status"], r["headers"], r["response"]))
                    self.logSuccess("Processed: %s: %s (%d of %d)" %
                                    (an["SHELTERCODE"], an["ANIMALNAME"],
                                     anCount, len(animals)))
                    processed.append(an)

            except Exception as err:
                self.logError(
                    "Failed processing animal: %s, %s" %
                    (str(an["SHELTERCODE"]), err), sys.exc_info())

        # Next, identify animals we've previously sent who:
        # 1. Have an active exit movement in the last month or died in the last month
        # 2. Have an entry in animalpublished/petrescue where the sent date is older than the active movement
        # 3. Have an entry in animalpublished/petrescue where the sent date is older than the deceased date

        animals = self.dbo.query("SELECT a.ID, a.ShelterCode, a.AnimalName, p.SentDate, a.ActiveMovementDate, a.DeceasedDate FROM animal a " \
            "INNER JOIN animalpublished p ON p.AnimalID = a.ID AND p.PublishedTo='petrescue' " \
            "WHERE Archived = 1 AND ((DeceasedDate Is Not Null AND DeceasedDate >= ?) OR " \
            "(ActiveMovementDate Is Not Null AND ActiveMovementDate >= ? AND ActiveMovementType NOT IN (2,8))) " \
            "ORDER BY a.ID", [self.dbo.today(offset=-30), self.dbo.today(offset=-30)])

        for an in animals:
            if (an.ACTIVEMOVEMENTDATE and an.SENTDATE < an.ACTIVEMOVEMENTDATE
                ) or (an.DECEASEDDATE and an.SENTDATE < an.DECEASEDDATE):

                status = utils.iif(an.DECEASEDDATE is not None, "removed",
                                   "rehomed")
                data = {"status": status}
                jsondata = utils.json(data)
                url = PETRESCUE_URL + "listings/%s/SM%s" % (an.ID,
                                                            self.dbo.database)

                self.log("Sending PATCH to %s to update existing listing: %s" %
                         (url, jsondata))
                r = utils.patch_json(url, jsondata, headers=headers)

                if r["status"] != 200:
                    self.logError("HTTP %d, headers: %s, response: %s" %
                                  (r["status"], r["headers"], r["response"]))
                else:
                    self.log("HTTP %d, headers: %s, response: %s" %
                             (r["status"], r["headers"], r["response"]))
                    self.logSuccess("%s - %s: Marked with new status %s" %
                                    (an.SHELTERCODE, an.ANIMALNAME, status))
                    # By marking these animals in the processed list again, their SentDate
                    # will become today, which should exclude them from sending these status
                    # updates to close the listing again in future
                    processed.append(an)

        # Mark sent animals published
        self.markAnimalsPublished(processed, first=True)

        self.cleanup()