def insert_lookup(dbo, lookup, name, desc="", speciesid=0, pfbreed="", pfspecies="", defaultcost=0): t = LOOKUP_TABLES[lookup] sql = "" nid = 0 if lookup == "breed": nid = db.get_id(dbo, "breed") sql = "INSERT INTO breed (ID, BreedName, BreedDescription, PetFinderBreed, SpeciesID) VALUES (%s, %s, %s, %s, %s)" % ( db.di(nid), db.ds(name), db.ds(desc), db.ds(pfbreed), db.di(speciesid)) elif lookup == "species": nid = db.get_id(dbo, "species") sql = "INSERT INTO species (ID, SpeciesName, SpeciesDescription, PetFinderSpecies) VALUES (%s, %s, %s, %s)" % ( db.di(nid), db.ds(name), db.ds(desc), db.ds(pfspecies)) elif lookup == "donationtype" or lookup == "costtype" or lookup == "testtype" or lookup == "voucher" or lookup == "vaccinationtype": nid = db.get_id(dbo, lookup) sql = "INSERT INTO %s (ID, %s, %s, DefaultCost) VALUES (%s, %s, %s, %s)" % ( lookup, t[LOOKUP_NAMEFIELD], t[LOOKUP_DESCFIELD], db.di(nid), db.ds(name), db.ds(desc), db.ds(defaultcost)) # Create a matching account for the donation type financial.insert_account_from_donationtype(dbo, nid, name, desc) elif t[LOOKUP_DESCFIELD] == "": # No description nid = db.get_id(dbo, lookup) sql = "INSERT INTO %s (ID, %s) VALUES (%s, %s)" % ( lookup, t[LOOKUP_NAMEFIELD], db.di(nid), db.ds(name)) else: # Name/Description nid = db.get_id(dbo, lookup) sql = "INSERT INTO %s (ID, %s, %s) VALUES (%s, %s, %s)" % ( lookup, t[LOOKUP_NAMEFIELD], t[LOOKUP_DESCFIELD], db.di(nid), db.ds(name), db.ds(desc)) db.execute(dbo, sql) return nid
def view_room(): if (in_like_table()): room_name = get_all_room(session['username']) print(room_name) room_id = get_id(room_name['room_name']) room = get_room(room_id['_id']) room_members = get_room_members(room_id['_id']) books = get_all_books() print(room_id) print(room_members) messages = get_messages(room_id['_id']) #book_id=get_group(session['username'])[2] #book_name=book_id_to_name(book_id) songs = '' #os.listdir('./static/music/'+book_name[0]) return render_template('view_room.html', username=session['username'], room=room, room_members=room_members, songs=songs, messages=messages, books=books) else: books = get_all_books() return render_template('books.html', books=books)
def create_document_media(dbo, username, linktype, linkid, template, content): """ Creates a new media record for a document for the link given. linktype: ANIMAL, PERSON, etc linkid: ID for the link template: The name of the template used to create the document content: The document contents """ mediaid = db.get_id(dbo, "media") sql = db.make_insert_sql( "media", (("ID", db.di(mediaid)), ("MediaName", db.ds("%d.html" % mediaid)), ("MediaType", db.di(0)), ("MediaNotes", db.ds(template)), ("WebsitePhoto", db.di(0)), ("WebsiteVideo", db.di(0)), ("DocPhoto", db.di(0)), ("ExcludeFromPublish", db.di(0)), ("NewSinceLastPublish", db.di(1)), ("UpdatedSinceLastPublish", db.di(0)), ("LinkID", db.di(linkid)), ("LinkTypeID", db.di(linktype)), ("Date", db.nowsql()))) db.execute(dbo, sql) path = "" if linktype == ANIMAL: path = "/animal" elif linktype == PERSON: path = "/owner" elif linktype == LOSTANIMAL: path = "/lostanimal" elif linktype == FOUNDANIMAL: path = "/foundanimal" path += "/" + str(linkid) name = str(mediaid) + ".html" dbfs.put_string(dbo, name, path, content) audit.create(dbo, username, "media", str(mediaid) + ": for " + str(linkid) + "/" + str(linktype))
def attach_link_from_form(dbo, username, linktype, linkid, data): """ Attaches a link to a web resource from a form """ existingvid = db.query_int(dbo, "SELECT COUNT(*) FROM media WHERE WebsiteVideo = 1 " \ "AND LinkID = %d AND LinkTypeID = %d" % ( int(linkid), int(linktype) )) defvid = 0 if existingvid == 0 and utils.df_ki(data, "linktype") == MEDIATYPE_VIDEO_LINK: defvid = 1 mediaid = db.get_id(dbo, "media") url = utils.df_ks(data, "linktarget") if url.find("://") == -1: url = "http://" + url sql = db.make_insert_sql( "media", (("ID", db.di(mediaid)), ("MediaName", db.ds(url)), ("MediaType", utils.df_s(data, "linktype")), ("MediaNotes", utils.df_t(data, "comments")), ("WebsitePhoto", db.di(0)), ("WebsiteVideo", db.di(defvid)), ("DocPhoto", db.di(0)), ("ExcludeFromPublish", db.di(0)), ("NewSinceLastPublish", db.di(1)), ("UpdatedSinceLastPublish", db.di(0)), ("LinkID", db.di(linkid)), ("LinkTypeID", db.di(linktype)), ("Date", db.nowsql()))) db.execute(dbo, sql) audit.create( dbo, username, "media", str(mediaid) + ": for " + str(linkid) + "/" + str(linktype) + ": link to " + utils.df_ks(data, "linktarget"))
def insert_transport_from_form(dbo, username, post): """ Creates a transport record from posted form data """ l = dbo.locale if post.integer("animal") == 0: raise utils.ASMValidationError(i18n._("Transport requires an animal", l)) transportid = db.get_id(dbo, "animaltransport") sql = db.make_insert_user_sql(dbo, "animaltransport", username, ( ( "ID", db.di(transportid)), ( "AnimalID", post.db_integer("animal")), ( "DriverOwnerID", post.db_integer("driver")), ( "PickupOwnerID", post.db_integer("pickup")), ( "PickupAddress", post.db_string("pickupaddress")), ( "PickupTown", post.db_string("pickuptown")), ( "PickupCounty", post.db_string("pickupcounty")), ( "PickupDateTime", post.db_datetime("pickupdate", "pickuptime")), ( "PickupPostcode", post.db_string("pickuppostcode")), ( "DropoffOwnerID", post.db_integer("dropoff")), ( "DropoffAddress", post.db_string("dropoffaddress")), ( "DropoffTown", post.db_string("dropofftown")), ( "DropoffCounty", post.db_string("dropoffcounty")), ( "DropoffPostcode", post.db_string("dropoffpostcode")), ( "DropoffDateTime", post.db_datetime("dropoffdate", "dropofftime")), ( "Status", post.db_integer("status")), ( "Miles", post.db_integer("miles")), ( "Cost", post.db_integer("cost")), ( "CostPaidDate", post.db_date("costpaid")), ( "Comments", post.db_string("comments")) )) db.execute(dbo, sql) audit.create(dbo, username, "animaltransport", transportid, audit.dump_row(dbo, "animaltransport", transportid)) return transportid
def insert_user_from_form(dbo, username, data): """ Creates a user record from posted form data. Uses the roles key (which should be a comma separated list of role ids) to create userrole records. """ nuserid = db.get_id(dbo, "users") sql = db.make_insert_sql("users", ( ( "ID", db.di(nuserid)), ( "UserName", utils.df_t(data, "username")), ( "RealName", utils.df_t(data, "realname")), ( "EmailAddress", utils.df_t(data, "email")), ( "Password", db.ds(hash_password(utils.df_ks(data, "password"), True))), ( "SuperUser", utils.df_s(data, "superuser")), ( "RecordVersion", db.di(0)), ( "SecurityMap", db.ds("dummy")), ( "OwnerID", utils.df_s(data, "person")), ( "LocationFilter", utils.df_t(data, "locationfilter")), ( "IPRestriction", utils.df_t(data, "iprestriction")) )) db.execute(dbo, sql) audit.create(dbo, username, "users", str(nuserid)) roles = utils.df_ks(data, "roles").strip() if roles != "": for rid in roles.split(","): if rid.strip() != "": db.execute(dbo, "INSERT INTO userrole VALUES (%d, %d)" % (nuserid, int(rid))) return nuserid
def insert_user_from_form(dbo, username, post): """ Creates a user record from posted form data. Uses the roles key (which should be a comma separated list of role ids) to create userrole records. """ # Verify the username is unique l = dbo.locale if 0 != db.query_int(dbo, "SELECT COUNT(*) FROM users WHERE LOWER(UserName) LIKE LOWER(%s)" % post.db_string("username")): raise utils.ASMValidationError(i18n._("Username '{0}' already exists", l).format(post["username"])) nuserid = db.get_id(dbo, "users") sql = db.make_insert_sql("users", ( ( "ID", db.di(nuserid)), ( "UserName", post.db_string("username")), ( "RealName", post.db_string("realname")), ( "EmailAddress", post.db_string("email")), ( "Password", db.ds(hash_password(post["password"]))), ( "SuperUser", post.db_integer("superuser")), ( "RecordVersion", db.di(0)), ( "SecurityMap", db.ds("dummy")), ( "OwnerID", post.db_integer("person")), ( "SiteID", post.db_integer("site")), ( "LocationFilter", post.db_string("locationfilter")), ( "IPRestriction", post.db_string("iprestriction")) )) db.execute(dbo, sql) audit.create(dbo, username, "users", nuserid, audit.dump_row(dbo, "users", nuserid)) roles = post["roles"].strip() if roles != "": for rid in roles.split(","): if rid.strip() != "": db.execute(dbo, "INSERT INTO userrole VALUES (%d, %d)" % (nuserid, int(rid))) return nuserid
def attach_link_from_form(dbo, username, linktype, linkid, post): """ Attaches a link to a web resource from a form """ existingvid = db.query_int(dbo, "SELECT COUNT(*) FROM media WHERE WebsiteVideo = 1 " \ "AND LinkID = %d AND LinkTypeID = %d" % ( int(linkid), int(linktype) )) defvid = 0 if existingvid == 0 and post.integer("linktype") == MEDIATYPE_VIDEO_LINK: defvid = 1 mediaid = db.get_id(dbo, "media") url = post["linktarget"] if url.find("://") == -1: url = "http://" + url al.debug("attached link %s" % url, "media.attach_file_from_form") sql = db.make_insert_sql("media", ( ( "ID", db.di(mediaid) ), ( "MediaName", db.ds(url) ), ( "MediaType", post.db_integer("linktype") ), ( "MediaNotes", post.db_string("comments") ), ( "WebsitePhoto", db.di(0) ), ( "WebsiteVideo", db.di(defvid) ), ( "DocPhoto", db.di(0) ), ( "ExcludeFromPublish", db.di(0) ), # ASM2_COMPATIBILITY ( "NewSinceLastPublish", db.di(1) ), ( "UpdatedSinceLastPublish", db.di(0) ), # ASM2_COMPATIBILITY ( "LinkID", db.di(linkid) ), ( "LinkTypeID", db.di(linktype) ), ( "Date", db.nowsql() ) )) db.execute(dbo, sql) audit.create(dbo, username, "media", mediaid, str(mediaid) + ": for " + str(linkid) + "/" + str(linktype) + ": link to " + post["linktarget"])
def 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
def use_skill(self, what, quantity=1): ''' Uses the skill specified by 'what' with an optional quantity (default is 1) Must be logged in before and passed an integer ID. For a list of valid skill IDs, refer to http://kol.coldfront.net/thekolwiki/index.php/Skills_by_number ''' if not self.loggedin: raise MeatError('You must log in before calling use_skill()') if not isinstance(quantity, int): raise MeatError('Quantity must be an integer, type (quantity): %s' % type(quantity)) if quantity < 1: raise MeatError('Can\'t use this skill a negative quantity of times: too meta') skill = db.get_id(what) form_data = { 'pwd':self.pwd, 'action':'Skillz', 'whichskill':skill, 'quantity':quantity, } response = self.session.post(self.serverURL + '/skills.php', data=form_data) soup = BeautifulSoup(response.text) effect = soup.find('td', class_='effect') if effect is not None: return effect.text else: return None self.update()
def consume(self, kind, what, quantity=1): ''' Will look in player inventory for the target item 'which_item' and eat or drink it if it's available. ''' if not self.loggedin: raise MeatError('You must log in first') if not isinstance(quantity, int): raise MeatError('Quantity must be an integer, type(quantity): %s' % type(quantity)) if quantity < 1: raise MeatError('Can\'t use this skill a negative quantity of times') item_id = db.get_id(what) if item_id == None: raise MeatError('Invalid item name') form_data = { 'pwd': self.pwd, 'which': quantity, 'whichitem': item_id, } if kind is 'food': response = self.session.post(self.serverURL + '/inv_eat.php', params=form_data) elif kind is 'booze': response = self.session.post(self.serverURL + '/inv_booze.php', params=form_data) else: raise MeatError('kind must be either food or booze, kind: %s ' % kind) # self.output('consume', response.text) self.update() if "You don't have the item you're trying to use" in response.text or "You're too full to eat that" in response.text: return False else: return True
def specific_disaster_data(): id = request.args.get('id') data = get_id(id) if data == False: data = {"requests": []} #print(data["details"]["location"]) return jsonify(data)
def insert_account_from_form(dbo, username, post): """ Creates an account from posted form data """ l = dbo.locale if post["code"] == "": raise utils.ASMValidationError(i18n._("Account code cannot be blank.", l)) if 0 != db.query_int(dbo, "SELECT COUNT(*) FROM accounts WHERE Code Like '%s'" % post["code"]): raise utils.ASMValidationError(i18n._("Account code '{0}' has already been used.", l).format(post["code"])) aid = db.get_id(dbo, "accounts") sql = db.make_insert_user_sql(dbo, "accounts", username, ( ( "ID", db.di(aid)), ( "Code", post.db_string("code")), ( "AccountType", post.db_integer("type")), ( "DonationTypeID", post.db_integer("donationtype")), ( "Description", post.db_string("description")) )) db.execute(dbo, sql) audit.create(dbo, username, "accounts", str(aid)) accountid = post.integer("accountid") for rid in post.integer_list("viewroles"): db.execute(dbo, "INSERT INTO accountsrole (AccountID, RoleID, CanView, CanEdit) VALUES (%d, %d, 1, 0)" % (accountid, rid)) for rid in post.integer_list("editroles"): if rid in post.integer_list("viewroles"): db.execute(dbo, "UPDATE accountsrole SET CanEdit = 1 WHERE AccountID = %d AND RoleID = %d" % (accountid, rid)) else: db.execute(dbo, "INSERT INTO accountsrole (AccountID, RoleID, CanView, CanEdit) VALUES (%d, %d, 0, 1)" % (accountid, rid)) return aid
def insert_trx_from_form(dbo, username, post): """ Creates a transaction from posted form data """ l = dbo.locale amount = 0 source = 0 target = 0 deposit = post.money("deposit") withdrawal = post.money("withdrawal") account = post.integer("accountid") other = get_account_id(dbo, post["otheraccount"]) if other == 0: raise utils.ASMValidationError(i18n._("Account code '{0}' is not valid.", l).format(post["otheraccount"])) if deposit > 0: amount = deposit source = other target = account else: amount = withdrawal source = account target = other tid = db.get_id(dbo, "accountstrx") sql = db.make_insert_user_sql(dbo, "accountstrx", username, ( ( "ID", db.di(tid) ), ( "TrxDate", post.db_date("trxdate")), ( "Description", post.db_string("description")), ( "Reconciled", post.db_boolean("reconciled")), ( "Amount", db.di(amount)), ( "SourceAccountID", db.di(source)), ( "DestinationAccountID", db.di(target)), ( "OwnerDonationID", db.di(0)) )) db.execute(dbo, sql) audit.create(dbo, username, "accountstrx", str(tid) + ": " + post["description"])
def insert_stocklevel_from_form(dbo, post, username): """ Inserts a stocklevel item from a dialog. The post should include the ID of the stocklevel to adjust and a usage record will be written so usage data should be sent too. """ l = dbo.locale slid = post.integer("id") if post["name"] == "": raise utils.ASMValidationError(_("Stock level must have a name", l)) if post["unitname"] == "": raise utils.ASMValidationError(_("Stock level must have a unit", l)) nid = db.get_id(dbo, "stocklevel") db.execute(dbo, db.make_insert_sql("stocklevel", ( ( "ID", db.di(nid) ), ( "Name", post.db_string("name") ), ( "Description", post.db_string("description") ), ( "StockLocationID", post.db_integer("location") ), ( "UnitName", post.db_string("unitname") ), ( "Total", post.db_floating("total") ), ( "Balance", post.db_floating("balance") ), ( "Expiry", post.db_date("expiry") ), ( "BatchNumber", post.db_string("batchnumber") ), ( "Cost", post.db_integer("cost") ), ( "UnitPrice", post.db_integer("unitprice") ), ( "CreatedDate", db.todaysql() ) ))) insert_stockusage(dbo, username, slid, post.floating("balance"), post.date("usagedate"), post.integer("usagetype"), post["comments"]) audit.create(dbo, username, "stocklevel", nid, audit.dump_row(dbo, "stocklevel", nid)) return nid
def attach_link_from_form(dbo, username, linktype, linkid, data): """ Attaches a link to a web resource from a form """ existingvid = db.query_int(dbo, "SELECT COUNT(*) FROM media WHERE WebsiteVideo = 1 " \ "AND LinkID = %d AND LinkTypeID = %d" % ( int(linkid), int(linktype) )) defvid = 0 if existingvid == 0 and utils.df_ki(data, "linktype") == MEDIATYPE_VIDEO_LINK: defvid = 1 mediaid = db.get_id(dbo, "media") url = utils.df_ks(data, "linktarget") if url.find("://") == -1: url = "http://" + url sql = db.make_insert_sql("media", ( ( "ID", db.di(mediaid) ), ( "MediaName", db.ds(url) ), ( "MediaType", utils.df_s(data, "linktype") ), ( "MediaNotes", utils.df_t(data, "comments") ), ( "WebsitePhoto", db.di(0) ), ( "WebsiteVideo", db.di(defvid) ), ( "DocPhoto", db.di(0) ), ( "ExcludeFromPublish", db.di(0) ), ( "NewSinceLastPublish", db.di(1) ), ( "UpdatedSinceLastPublish", db.di(0) ), ( "LinkID", db.di(linkid) ), ( "LinkTypeID", db.di(linktype) ), ( "Date", db.nowsql() ) )) db.execute(dbo, sql) audit.create(dbo, username, "media", str(mediaid) + ": for " + str(linkid) + "/" + str(linktype) + ": link to " + utils.df_ks(data, "linktarget"))
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
def create_path(dbo, path, name): """ Creates a new DBFS folder """ db.execute( dbo, "INSERT INTO dbfs (ID, Name, Path) VALUES (%d, '%s', '%s')" % (db.get_id(dbo, "dbfs"), name, path))
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
def insert_user_from_form(dbo, username, data): """ Creates a user record from posted form data. Uses the roles key (which should be a comma separated list of role ids) to create userrole records. """ nuserid = db.get_id(dbo, "users") sql = db.make_insert_sql( "users", (("ID", db.di(nuserid)), ("UserName", utils.df_t(data, "username")), ("RealName", utils.df_t(data, "realname")), ("EmailAddress", utils.df_t(data, "email")), ("Password", db.ds(hash_password(utils.df_ks(data, "password"), True))), ("SuperUser", utils.df_s(data, "superuser")), ("RecordVersion", db.di(0)), ("SecurityMap", db.ds("dummy")), ("OwnerID", utils.df_s(data, "person")), ("LocationFilter", utils.df_t(data, "locationfilter")), ("IPRestriction", utils.df_t(data, "iprestriction")))) db.execute(dbo, sql) audit.create(dbo, username, "users", str(nuserid)) roles = utils.df_ks(data, "roles").strip() if roles != "": for rid in roles.split(","): if rid.strip() != "": db.execute( dbo, "INSERT INTO userrole VALUES (%d, %d)" % (nuserid, int(rid))) return nuserid
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
def insert_diary(dbo, username, linktypeid, linkid, diarydate, diaryfor, subject, note): """ Creates a diary note from the form data username: User creating the diary linktypeid, linkid: The link diarydate: The date to stamp on the note (python format) diaryfor: Who the diary note is for subject, note """ linkinfo = "" if linkid != 0: linkinfo = get_link_info(dbo, linktypeid, linkid) diaryid = db.get_id(dbo, "diary") sql = db.make_insert_user_sql(dbo, "diary", username, ( ( "ID", db.di(diaryid)), ( "LinkID", db.di(linkid) ), ( "LinkType", db.di(linktypeid) ), ( "LinkInfo", db.ds(linkinfo) ), ( "DiaryDateTime", db.dd(diarydate) ), ( "DiaryForName", db.ds(diaryfor) ), ( "Subject", db.ds(subject) ), ( "Note", db.ds(note) ), ( "DateCompleted", db.dd(None) ) )) db.execute(dbo, sql) audit.create(dbo, username, "diary", str(diaryid)) return diaryid
def insert_foundanimal_from_form(dbo, post, username): """ Inserts a new found animal record from the screen data: The webpy data object containing form parameters """ l = dbo.locale if post.date("datefound") is None: raise utils.ASMValidationError(_("Date found cannot be blank", l)) if post.date("datereported") is None: raise utils.ASMValidationError(_("Date reported cannot be blank", l)) if post.integer("owner") == 0: raise utils.ASMValidationError( _("Found animals must have a contact", l)) nid = db.get_id(dbo, "animalfound") db.execute( dbo, db.make_insert_user_sql( dbo, "animalfound", username, (("ID", db.di(nid)), ("AnimalTypeID", post.db_integer("species")), ("DateReported", post.db_date("datereported")), ("ReturnToOwnerDate", post.db_date("returntoownerdate")), ("DateFound", post.db_date("datefound")), ("Sex", post.db_integer("sex")), ("BreedID", post.db_integer("breed")), ("AgeGroup", post.db_string("agegroup")), ("BaseColourID", post.db_integer("colour")), ("DistFeat", post.db_string("markings")), ("AreaFound", post.db_string("areafound")), ("AreaPostcode", post.db_string("areapostcode")), ("OwnerID", post.db_integer("owner")), ("Comments", post.db_string("comments"))))) audit.create(dbo, username, "animalfound", str(nid)) return nid
def reschedule_vaccination(dbo, username, vaccinationid, newdays): """ Marks a vaccination completed today (if it's not already completed) and reschedules it for given + newdays onwards. """ av = db.query( dbo, "SELECT * FROM animalvaccination WHERE ID = %d" % int(vaccinationid))[0] given = av["DATEOFVACCINATION"] if given is None: given = now(dbo.timezone) db.execute( dbo, "UPDATE animalvaccination SET DateOfVaccination = %s WHERE ID = %d" % (db.dd(now(dbo.timezone)), int(vaccinationid))) audit.edit(dbo, username, "animalvaccination", str(vaccinationid) + " => given") nvaccid = db.get_id(dbo, "animalvaccination") db.execute( dbo, db.make_insert_user_sql( dbo, "animalvaccination", username, (("ID", db.di(nvaccid)), ("AnimalID", db.di(av["ANIMALID"])), ("VaccinationID", db.di(av["VACCINATIONID"])), ("DateOfVaccination", db.dd(None)), ("DateRequired", db.dd(add_days(given, int(newdays)))), ("Cost", db.di(av["COST"])), ("Comments", db.ds(av["COMMENTS"]))))) audit.create(dbo, username, "animalvaccination", str(nvaccid))
def test_database_operations(self): #initialization of engine db.create_engine('test.db') #create Table db.update('drop table if exists User') db.update('create table User(id int primary key, name varchar(20),password varchar(20),gender varchar(8))') #insert r1 = db.insert('User',id=db.get_id(),name='user1',password='******',gender='male') r2 = db.insert('User',id=db.get_id(),name='user2',password='******',gender='female') r3 = db.insert('User',id=db.get_id(),name='user3',password='******',gender='male') self.assertEquals(r1,1) self.assertEquals(r2,1) self.assertEquals(r3,1) #test select r4 = db.select_one('select name from User where gender=?','male') r5 = db.select_all('select name from User where gender=?','male') self.assertIsInstance(r4,dict) self.assertIsInstance(r5,list) r6 = db.select_one('select name from User where gender=?','asldfkj') r7 = db.select_all('select name from User where gender=?','asldfkj') self.assertIsNone(r6) self.assertEquals(r7,[]) #test update r8 = db.update('update User SET gender=? where name=?','male','user1') r9 = db.update('update User SET gender=? where name=?','male','asdfas') r10 = db.update('update User SET name =? where gender=?','haha','male') self.assertEquals(r8,1) self.assertEquals(r9,0) self.assertEquals(r10,2) #test transactions with db.transaction(): db.insert('User',id=db.get_id(),name='user5',password='******',gender='female') db.insert('User',id=db.get_id(),name='user5',password='******',gender='male') r12 = db.select_all('select * from User where name=?','user5') self.assertEquals(len(r12),2) db.engine = None
def patch_response(self, courier_id): if self.invalid: return {"patch_error": {"couriers": [{"id": courier_id}]}} courier_row = db.get_id("couriers", courier_id) response = { "courier_id": courier_row[0], "courier_type": courier_row[1], "regions": json.loads(courier_row[2]), "working_hours": json.loads(courier_row[3]) } return response
def insert_role_from_form(dbo, username, data): """ Creates a role record from posted form data. """ nroleid = db.get_id(dbo, "role") sql = db.make_insert_sql( "role", (("ID", db.di(nroleid)), ("Rolename", utils.df_t(data, "rolename")), ("SecurityMap", utils.df_t(data, "securitymap")))) db.execute(dbo, sql) audit.create(dbo, username, "role", str(nroleid))
def get_tasks(update, context): uuid = update.effective_chat.id user_id = get_id(uuid) user_passwd = get_passwd(uuid) login(user_id, user_passwd) message = get_upcoming_tasks_as_text() if message is None: message = "We might have some network issues, please try again later 😊" logger.error(f'Network issues for user {uuid}') update.message.reply_text(message, parse_mode='Markdown')
def add_log(dbo, username, linktype, linkid, logtypeid, logtext): logid = db.get_id(dbo, "log") sql = db.make_insert_user_sql( dbo, "log", username, (("ID", db.di(logid)), ("LogTypeID", db.di(logtypeid)), ("LinkID", db.di(linkid)), ("LinkType", db.di(linktype)), ("Date", db.dd(i18n.now(dbo.timezone))), ("Comments", db.ds(logtext)))) db.execute(dbo, sql) audit.create(dbo, username, "log", str(logid)) return logid
def get_courier(courier_id): courier_row = db.get_id("couriers", courier_id) if courier_row is None: return None data = { "courier_id": courier_row[0], "courier_type": courier_row[1], "regions": json.loads(courier_row[2]), "working_hours": json.loads(courier_row[3]) } return Courier(data)
def audio_book(): if request.method == 'POST': book_name = request.form.get('books', None) room_name = get_all_room(session['username']) print(room_name) room_id = get_id(room_name['room_name']) room = get_room(room_id['_id']) room_members = get_room_members(room_id['_id']) books = get_all_books() print(room_id) print(room_members) messages = get_messages(room_id['_id']) ready_audio(book_name) songs = os.listdir('./static/music/' + book_name) return render_template('view_room.html', username=session['username'], room=room, room_members=room_members, songs=songs, messages=messages, books=books) else: room_name = get_all_room(session['username']) print(room_name) room_id = get_id(room_name['room_name']) room = get_room(room_id['_id']) room_members = get_room_members(room_id['_id']) books = get_all_books() print(room_id) print(room_members) messages = get_messages(room_id['_id']) #book_id=get_group(session['username'])[2] #book_name=book_id_to_name(book_id) songs = '' #os.listdir('./static/music/'+book_name[0]) return render_template('view_room.html', username=session['username'], room=room, room_members=room_members, songs=songs, messages=messages, books=books)
def insert_role_from_form(dbo, username, data): """ Creates a role record from posted form data. """ nroleid = db.get_id(dbo, "role") sql = db.make_insert_sql("role", ( ( "ID", db.di(nroleid)), ( "Rolename", utils.df_t(data, "rolename")), ( "SecurityMap", utils.df_t(data, "securitymap")) )) db.execute(dbo, sql) audit.create(dbo, username, "role", str(nroleid))
def put_string(dbo, name, path, contents): """ Stores the file contents at the name and path. If the file exists, overwrites it. """ check_create_path(dbo, path) s = base64.b64encode(contents) name = name.replace("'", "") path = path.replace("'", "") dbfsid = db.get_id(dbo, "dbfs") db.execute(dbo, "DELETE FROM dbfs WHERE Path = '%s' AND Name = '%s'" % ( path, name )) db.execute(dbo, "INSERT INTO dbfs (ID, Name, Path, Content) VALUES (%d, '%s', '%s', '%s')" % ( dbfsid, name, path, s )) return dbfsid
def put_file(dbo, name, path, filepath): """ Reads the the file from filepath and stores it with name/path """ check_create_path(dbo, path) f = open(filepath, "rb") s = base64.b64encode(f.read()) f.close() db.execute( dbo, "INSERT INTO dbfs (ID, Name, Path, Content) VALUES (%d, '%s', '%s', '%s')" % (db.get_id(dbo, "dbfs"), name, path, s))
def start(message): if db.get_id(str(message.from_user.id)) is None: db.add(str(message.from_user.id), str(message.from_user.first_name)) bot.send_message( message.chat.id, "Вітаю, {0.first_name}!\nЯ - <b>{1.first_name}</b>, " "бот, у якому ви можете створювати власні галереї зображень ".format( message.from_user, bot.get_me()), parse_mode='html', reply_markup=markup1) print('has began to play' + str(message.from_user.id))
def add_log(dbo, username, linktype, linkid, logtypeid, logtext): logid = db.get_id(dbo, "log") sql = db.make_insert_user_sql(dbo, "log", username, ( ( "ID", db.di(logid) ), ( "LogTypeID", db.di(logtypeid) ), ( "LinkID", db.di(linkid) ), ( "LinkType", db.di(linktype) ), ( "Date", db.dd(i18n.now(dbo.timezone)) ), ( "Comments", db.ds(logtext) ) )) db.execute(dbo, sql) audit.create(dbo, username, "log", str(logid))
def insert_role_from_form(dbo, username, post): """ Creates a role record from posted form data. """ nroleid = db.get_id(dbo, "role") sql = db.make_insert_sql("role", ( ( "ID", db.di(nroleid)), ( "Rolename", post.db_string("rolename")), ( "SecurityMap", post.db_string("securitymap")) )) db.execute(dbo, sql) audit.create(dbo, username, "role", nroleid, audit.dump_row(dbo, "role", nroleid))
def insert_movement_from_form(dbo, username, data): """ Creates a movement record from posted form data """ movementid = db.get_id(dbo, "adoption") adoptionno = utils.df_ks(data, "adoptionno") animalid = utils.df_ki(data, "animal") if adoptionno == "": # No adoption number was supplied, generate a # unique number from the movementid idx = movementid while True: adoptionno = utils.padleft(idx, 6) data["adoptionno"] = adoptionno if 0 == db.query_int( dbo, "SELECT COUNT(*) FROM adoption WHERE AdoptionNumber LIKE '%s'" % adoptionno): break else: idx += 1 validate_movement_form_data(dbo, data) l = dbo.locale sql = db.make_insert_user_sql( dbo, "adoption", username, (("ID", db.di(movementid)), ("AdoptionNumber", db.ds(adoptionno)), ("OwnerID", db.di(utils.df_ki(data, "person"))), ("RetailerID", db.di(utils.df_ki(data, "retailer"))), ("AnimalID", db.di(utils.df_ki(data, "animal"))), ("OriginalRetailerMovementID", db.di(utils.df_ki(data, "originalretailermovement"))), ("MovementDate", utils.df_d(data, "movementdate", l)), ("MovementType", utils.df_s(data, "type")), ("ReturnDate", utils.df_d(data, "returndate", l)), ("ReturnedReasonID", utils.df_s(data, "returncategory")), ("Donation", utils.df_m(data, "donation", l)), ("InsuranceNumber", utils.df_t(data, "insurance")), ("ReasonForReturn", utils.df_t(data, "reason")), ("ReservationDate", utils.df_d(data, "reservationdate", l)), ("ReservationCancelledDate", utils.df_d(data, "reservationcancelled", l)), ("IsTrial", utils.df_c(data, "trial")), ("IsPermanentFoster", utils.df_c(data, "permanentfoster")), ("TrialEndDate", utils.df_d(data, "trialenddate", l)), ("Comments", utils.df_t(data, "comments")))) db.execute(dbo, sql) audit.create(dbo, username, "adoption", str(movementid)) animal.update_animal_status(dbo, animalid) animal.update_variable_animal_data(dbo, animalid) update_movement_donation(dbo, movementid) return movementid
def insert_diarytaskhead_from_form(dbo, username, data): """ Creates a diary task header from form data """ nid = db.get_id(dbo, "diarytaskhead") sql = db.make_insert_sql("diarytaskhead", (("ID", db.di(nid)), ("Name", utils.df_t(data, "name")), ("RecordType", utils.df_s(data, "type")), ("RecordVersion", db.di(0)))) db.execute(dbo, sql) audit.create(dbo, username, "diarytaskhead", str(nid)) return nid
def insert_diarytaskhead_from_form(dbo, username, post): """ Creates a diary task header from form data """ nid = db.get_id(dbo, "diarytaskhead") sql = db.make_insert_sql("diarytaskhead", (("ID", db.di(nid)), ("Name", post.db_string("name")), ("RecordType", post.db_integer("type")), ("RecordVersion", db.di(0)))) db.execute(dbo, sql) audit.create(dbo, username, "diarytaskhead", str(nid)) return nid
def get_order(order_id): order_row = db.get_id("orders", order_id) if order_row: data = { "id": order_row[0], "weight": order_row[1], "region": order_row[2], "delivery_hours": json.loads(order_row[3]), "assigned": order_row[4], "completed": order_row[5] } return Order(data) return None
def add_message(dbo, createdby, email, message, forname = "*", priority = 0, expires = add_days(now(), 7), added = now()): l = dbo.locale db.execute(dbo, db.make_insert_sql("messages", ( ( "ID", db.di(db.get_id(dbo, "messages"))), ( "Added", db.dd(added)), ( "Expires", db.dd(expires)), ( "CreatedBy", db.ds(createdby)), ( "Priority", db.di(priority)), ( "ForName", db.ds(forname)), ( "Message", db.ds(message))))) # If email is set, we email the message to everyone that it would match if email == 1: utils.send_user_email(dbo, createdby, forname, _("Message from {0}", l).format(createdby), message)
def insert_animalcontrol_from_form(dbo, post, username): """ Inserts a new animal control incident record from the screen data: The webpy data object containing form parameters """ l = dbo.locale if post.date("incidentdate") is None: raise utils.ASMValidationError(_("Incident date cannot be blank", l)) nid = db.get_id(dbo, "animalcontrol") db.execute( dbo, db.make_insert_user_sql( dbo, "animalcontrol", username, (("ID", db.di(nid)), ("IncidentDateTime", post.db_datetime("incidentdate", "incidenttime")), ("IncidentTypeID", post.db_integer("incidenttype")), ("CallDateTime", post.db_datetime("calldate", "calltime")), ("CallNotes", post.db_string("callnotes")), ("CallTaker", post.db_string("calltaker")), ("CallerID", post.db_integer("caller")), ("VictimID", post.db_integer("victim")), ("DispatchAddress", post.db_string("dispatchaddress")), ("DispatchTown", post.db_string("dispatchtown")), ("DispatchCounty", post.db_string("dispatchcounty")), ("DispatchPostcode", post.db_string("dispatchpostcode")), ("DispatchLatLong", post.db_string("dispatchlatlong")), ("DispatchedACO", post.db_string("dispatchedaco")), ("DispatchDateTime", post.db_datetime("dispatchdate", "dispatchtime")), ("RespondedDateTime", post.db_datetime("respondeddate", "respondedtime")), ("FollowupDateTime", post.db_datetime("followupdate", "followuptime")), ("FollowupDateTime2", post.db_datetime("followupdate2", "followuptime2")), ("FollowupDateTime3", post.db_datetime("followupdate3", "followuptime3")), ("CompletedDate", post.db_date("completeddate")), ("IncidentCompletedID", post.db_integer("completedtype")), ("OwnerID", post.db_integer("owner")), ("Owner2ID", post.db_integer("owner2")), ("Owner3ID", post.db_integer("owner3")), ("AnimalID", post.db_integer("animal")), ("AnimalDescription", post.db_string("animaldescription")), ("SpeciesID", post.db_integer("species")), ("Sex", post.db_integer("sex")), ("AgeGroup", post.db_string("agegroup"))))) audit.create(dbo, username, "animalcontrol", str(nid)) return nid
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)
def inv_qty(self, item_name): ''' Takes an item name or item id and returns the quantity in your inventory ''' if isinstance(item_name, str): key = unicode(db.get_id(item_name)) elif isinstance(item_name, int): key = unicode(item_name) elif isinstance(item_name, unicode): key = item_name if key in self.inventory: return int(self.inventory[key]) else: return 0
def insert_stockusage(dbo, username, slid, diff, usagedate, usagetype, comments): """ Inserts a new stock usage record """ nid = db.get_id(dbo, "stockusage") db.execute(dbo, db.make_insert_user_sql(dbo, "stockusage", username, ( ( "ID", db.di(nid)), ( "StockUsageTypeID", db.di(usagetype) ), ( "StockLevelID", db.di(slid) ), ( "UsageDate", db.dd(usagedate) ), ( "Quantity", db.df(diff) ), ( "Comments", db.ds(comments) ) ))) audit.create(dbo, username, "stockusage", nid, audit.dump_row(dbo, "stockusage", nid))
def insert_account_from_donationtype(dbo, dtid, name, desc): """ Creates an account from a donation type record """ l = dbo.locale aid = db.get_id(dbo, "accounts") acode = i18n._("Income::", l) + name.replace(" ", "") sql = db.make_insert_user_sql(dbo, "accounts", "system", (("ID", db.di(aid)), ("Code", db.ds(acode)), ("AccountType", db.di(INCOME)), ("DonationTypeID", db.di(dtid)), ("Description", db.ds(desc)))) db.execute(dbo, sql) audit.create(dbo, "system", "accounts", str(aid))
def insert_diarytaskhead_from_form(dbo, username, post): """ Creates a diary task header from form data """ nid = db.get_id(dbo, "diarytaskhead") sql = db.make_insert_sql("diarytaskhead", ( ( "ID", db.di(nid)), ( "Name", post.db_string("name")), ( "RecordType", post.db_integer("type")), ( "RecordVersion", db.di(0)) )) db.execute(dbo, sql) audit.create(dbo, username, "diarytaskhead", nid, audit.dump_row(dbo, "diarytaskhead", nid)) return nid
def remove_contact(contact): """Removes a contact""" entry = [] try: entry.append(contact.split()[0]) except: entry.append('') try: entry.append(contact.split()[1]) except: entry.append('') db.delete_entry(db.get_id(entry))
def insert_animalcontrol_from_form(dbo, post, username): """ Inserts a new animal control incident record from the screen data: The webpy data object containing form parameters """ l = dbo.locale if post.date("incidentdate") is None: raise utils.ASMValidationError(_("Incident date cannot be blank", l)) nid = db.get_id(dbo, "animalcontrol") db.execute(dbo, db.make_insert_user_sql(dbo, "animalcontrol", username, ( ( "ID", db.di(nid)), ( "IncidentDateTime", post.db_datetime("incidentdate", "incidenttime")), ( "IncidentTypeID", post.db_integer("incidenttype")), ( "CallDateTime", post.db_datetime("calldate", "calltime")), ( "CallNotes", post.db_string("callnotes")), ( "CallTaker", post.db_string("calltaker")), ( "CallerID", post.db_integer("caller")), ( "VictimID", post.db_integer("victim")), ( "DispatchAddress", post.db_string("dispatchaddress")), ( "DispatchTown", post.db_string("dispatchtown")), ( "DispatchCounty", post.db_string("dispatchcounty")), ( "DispatchPostcode", post.db_string("dispatchpostcode")), ( "PickupLocationID", post.db_integer("pickuplocation")), ( "DispatchLatLong", post.db_string("dispatchlatlong")), ( "DispatchedACO", post.db_string("dispatchedaco")), ( "DispatchDateTime", post.db_datetime("dispatchdate", "dispatchtime")), ( "RespondedDateTime", post.db_datetime("respondeddate", "respondedtime")), ( "FollowupDateTime", post.db_datetime("followupdate", "followuptime")), ( "FollowupComplete", post.db_boolean("followupcomplete")), ( "FollowupDateTime2", post.db_datetime("followupdate2", "followuptime2")), ( "FollowupComplete2", post.db_boolean("followupcomplete2")), ( "FollowupDateTime3", post.db_datetime("followupdate3", "followuptime3")), ( "FollowupComplete3", post.db_boolean("followupcomplete3")), ( "CompletedDate", post.db_date("completeddate")), ( "IncidentCompletedID", post.db_integer("completedtype")), ( "OwnerID", post.db_integer("owner")), ( "Owner2ID", post.db_integer("owner2")), ( "Owner3ID", post.db_integer("owner3")), ( "AnimalDescription", post.db_string("animaldescription")), ( "SpeciesID", post.db_integer("species")), ( "Sex", post.db_integer("sex")), ( "AgeGroup", post.db_string("agegroup")) ))) audit.create(dbo, username, "animalcontrol", nid, audit.dump_row(dbo, "animalcontrol", nid)) # Save any additional field values given additional.save_values_for_link(dbo, post, nid, "incident") return nid
def insert_onlineform_from_form(dbo, username, data): """ Create an onlineform record from posted data """ formid = db.get_id(dbo, "onlineform") sql = db.make_insert_sql( "onlineform", (("ID", db.di(formid)), ("Name", db.ds(utils.df_ks(data, "name"))), ("RedirectUrlAfterPOST", db.ds(utils.df_ks(data, "redirect"))), ("SetOwnerFlags", db.ds(utils.df_ks(data, "flags"))), ("Description", db.ds(utils.df_ks(data, "description"))))) db.execute(dbo, sql) audit.create(dbo, username, "onlineform", str(formid)) return formid
def remove_contact(contact): """Removes a contact""" entry = [] try: entry.append(contact.split()[0]) except: entry.append('') try: entry.append(contact.split()[1]) except: entry.append(''); db.delete_entry(db.get_id(entry))
def insert_diarytaskhead_from_form(dbo, username, data): """ Creates a diary task header from form data """ nid = db.get_id(dbo, "diarytaskhead") sql = db.make_insert_sql("diarytaskhead", ( ( "ID", db.di(nid)), ( "Name", utils.df_t(data, "name")), ( "RecordType", utils.df_s(data, "type")), ( "RecordVersion", db.di(0)) )) db.execute(dbo, sql) audit.create(dbo, username, "diarytaskhead", str(nid)) return nid
def insert_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)
def insert_onlineform_from_form(dbo, username, data): """ Create an onlineform record from posted data """ formid = db.get_id(dbo, "onlineform") sql = db.make_insert_sql("onlineform", ( ( "ID", db.di(formid)), ( "Name", db.ds(utils.df_ks(data, "name"))), ( "RedirectUrlAfterPOST", db.ds(utils.df_ks(data, "redirect"))), ( "SetOwnerFlags", db.ds(utils.df_ks(data, "flags"))), ( "Description", db.ds(utils.df_ks(data, "description"))) )) db.execute(dbo, sql) audit.create(dbo, username, "onlineform", str(formid)) return formid
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
def insert_lookup(dbo, lookup, name, desc="", speciesid=0, pfbreed="", pfspecies="", apcolour="", units="", site=1, defaultcost=0, retired=0): t = LOOKUP_TABLES[lookup] sql = "" nid = 0 if lookup == "basecolour": nid = db.get_id(dbo, "basecolour") sql = "INSERT INTO basecolour (ID, BaseColour, BaseColourDescription, AdoptAPetColour, IsRetired) VALUES (%s, %s, %s, %s, %s)" % ( db.di(nid), db.ds(name), db.ds(desc), db.ds(apcolour), db.di(retired)) elif lookup == "breed": nid = db.get_id(dbo, "breed") sql = "INSERT INTO breed (ID, BreedName, BreedDescription, PetFinderBreed, SpeciesID, IsRetired) VALUES (%s, %s, %s, %s, %s, %s)" % ( db.di(nid), db.ds(name), db.ds(desc), db.ds(pfbreed), db.di(speciesid), db.di(retired)) elif lookup == "internallocation": nid = db.get_id(dbo, "internallocation") sql = "INSERT INTO internallocation (ID, LocationName, LocationDescription, Units, SiteID, IsRetired) VALUES (%s, %s, %s, %s, %s, %s)" % ( db.di(nid), db.ds(name), db.ds(desc), db.ds(units), db.di(site), db.di(retired)) elif lookup == "species": nid = db.get_id(dbo, "species") sql = "INSERT INTO species (ID, SpeciesName, SpeciesDescription, PetFinderSpecies, IsRetired) VALUES (%s, %s, %s, %s, %s)" % ( db.di(nid), db.ds(name), db.ds(desc), db.ds(pfspecies), db.di(retired)) elif lookup == "donationtype" or lookup == "costtype" or lookup == "testtype" or lookup == "voucher" or lookup == "vaccinationtype" \ or lookup == "traptype" or lookup == "licencetype" or lookup == "citationtype": nid = db.get_id(dbo, lookup) sql = "INSERT INTO %s (ID, %s, %s, DefaultCost, IsRetired) VALUES (%s, %s, %s, %s, %s)" % ( lookup, t[LOOKUP_NAMEFIELD], t[LOOKUP_DESCFIELD], db.di(nid), db.ds(name), db.ds(desc), db.ds(defaultcost), db.di(retired)) # Create a matching account if we have a donation type if lookup == "donationtype" and configuration.create_donation_trx(dbo): financial.insert_account_from_donationtype(dbo, nid, name, desc) # Same goes for cost type if lookup == "costtype" and configuration.create_cost_trx(dbo): financial.insert_account_from_costtype(dbo, nid, name, desc) elif t[LOOKUP_DESCFIELD] == "": # No description nid = db.get_id(dbo, lookup) if t[LOOKUP_CANRETIRE] == 1: sql = "INSERT INTO %s (ID, %s, IsRetired) VALUES (%s, %s, %s)" % ( lookup, t[LOOKUP_NAMEFIELD], db.di(nid), db.ds(name), db.di(retired)) else: sql = "INSERT INTO %s (ID, %s) VALUES (%s, %s)" % ( lookup, t[LOOKUP_NAMEFIELD], db.di(nid), db.ds(name)) else: # Name/Description nid = db.get_id(dbo, lookup) if t[LOOKUP_CANRETIRE] == 1: sql = "INSERT INTO %s (ID, %s, %s, IsRetired) VALUES (%s, %s, %s, %s)" % ( lookup, t[LOOKUP_NAMEFIELD], t[LOOKUP_DESCFIELD], db.di(nid), db.ds(name), db.ds(desc), db.di(retired)) else: sql = "INSERT INTO %s (ID, %s, %s) VALUES (%s, %s, %s)" % ( lookup, t[LOOKUP_NAMEFIELD], t[LOOKUP_DESCFIELD], db.di(nid), db.ds(name), db.ds(desc)) db.execute(dbo, sql) return nid
def get_contact(contact): """ """ entry = [] try: if contact.split()[1]: entry.append(contact.split()[0]) entry.append(contact.split()[1]) except: entry.append('') entry.append(contact.split()[0]) for row in db.get_entry(db.get_id(entry)): return row