def test_update_title(self): old_title = "first" new_title = "new" journal = Journal(title=old_title, body="hello") self.assertEqual(old_title, journal.title) journal.update_title(new_title) self.assertEqual(new_title, journal.title)
def test_update_body(self): old_body = "first" new_body = "second" journal = Journal(title="test", body=old_body) self.assertEqual(old_body, journal.body) journal.update_body(new_body) self.assertEqual(new_body, journal.body)
def create_journal(): form = JournalForm() form['csrf_token'].data = request.cookies['csrf_token'] if form.validate_on_submit(): new_journal = Journal(name=form.data['name'], color=form.data['color'], user=current_user) db.session.add(new_journal) db.session.commit() return new_journal.to_dict() return {'errors': validation_errors_to_error_messages(form.errors)}
def create_journal(): form = JournalForm() form['csrf_token'].data = request.cookies['csrf_token'] print('----------') if form.validate_on_submit(): data = Journal() print(data, '----------') form.populate_obj(data) data.userId = current_user.id db.session.add(data) db.session.commit() return data.to_dict() return 'invalid info'
def test_get_journal_json(self): id = 1 title = "test title" body = "journal body" date = datetime.utcnow json_expected = { "id": id, "title": title, "body": body, "date_created": date } journal = Journal(id=id, title=title, body=body, date_created=date) self.assertEqual(json_expected, journal.get_journal_json())
def seed_journals(): user = User.query.first() demo = Journal(name='My First Journal', color='#ff9800', user_id=user.id) db.session.add(demo) for num in range(2, 18): demo2 = Journal(name=f'Journal {num}', color='#{:02x}{:02x}{:02x}'.format(r(), r(), r()), user_id=user.id) db.session.add(demo2) db.session.commit()
def rent_car(car_id): car = Car.query.get(car_id) journal = Journal.query.all() if request.method == 'POST': car.availability = False if car.availability else True if car.availability == False: car.created = datetime.now() time_begin = datetime.now() time_end = None car.num_book += 1 db.session.add(Journal(car_id=car_id, time_begin=time_begin, time_end=time_end)) db.session.commit() db.session.commit() age_seconds = (datetime.now() - car.created).seconds car.total_time += age_seconds car.total_rent = car.total_time * car.rent_price / 60 db.session.commit() if car.availability == True: journal[-1].time_end = datetime.now() journal[-1].total_cost = (journal[-1].time_end - car.created).seconds * car.rent_price/60 db.session.commit() return render_template('auto_detail.html', car=car)
def test_journal_repr(self): user_id = 1 date = datetime.utcnow journal = Journal(user_id=user_id, date_created=date) journal_repr = "<Journal's user_id={0}, created on {1}>".format( user_id, date) self.assertEqual(journal_repr, repr(journal))
def add_journal(): patient_name = "JohnDoe" patient = Patient.query.filter_by(username=patient_name).first() req_data = request.get_json() date = req_data.get('date') entry = req_data.get('entry') client = language.LanguageServiceClient() document = types.Document(content=entry, type=enums.Document.Type.PLAIN_TEXT) annotations = client.analyze_sentiment(document=document) score = annotations.document_sentiment.score magnitude = annotations.document_sentiment.magnitude # return('Overall Sentiment: score of {} with magnitude of {}'.format( # score, magnitude)) temp_journal_entry = Journal(date=date, entry=entry, sentiment_scre=score, sentiment_mag=mag, patient_id=patient.id) db.session.add(temp_journal_entry) db.session.commit() return ("{}".format(score))
def journal_create(c_id): char = Character.query.filter_by(id=c_id).first_or_404() if current_user.id != char.user_id: flash_no_permission() return redirect(url_for(no_perm)) heading = "Create Journal Entry for " + char.name form = JournalForm() form.session.choices = gen_session_choices(char) form.submit.label.text = "Create Journal Entry" if form.validate_on_submit(): journal_entry = Journal(title=form.title.data, content=form.content.data, is_visible=form.is_visible.data, character_id=c_id) if (form.session.data != 0): journal_entry.session_id = form.session.data db.session.add(journal_entry) db.session.commit() flash("Journal entry was created.", "success") return redirect( url_for("character.journal_view", c_id=c_id, j_id=journal_entry.id)) else: # pre-select session if get-param was passed session_id = request.args.get("session") # will do nothing if session_id not an int or not in choices if session_id: try: form.session.data = int(session_id) except: pass return render_template("character/journal_form.html", heading=heading, form=form, title=page_title("Add Journal Entry for '%s'" % char.name))
def check_journal(self, checker_article): journal = Journal.check_journal_match(checker_article.journal) if journal: checker_article.journal = journal.journal checker_article.journal_abbrev = journal.abbrev if not journal.journal in self.atlas_journals: self.add_problem(checker_article.id, "missing_journal") else: self.add_problem(checker_article.id, "journal")
def save_journal(form, article): option = form.select.data if option == "alt": article.journal = form.alt_journal.data journal = Journal.query.filter_by(journal=article.journal).first() if not journal: abort(500) alt = AltJournal( altjournal=form.value.data.lower().replace(".", ""), journal=journal ) db_add_commit(alt) elif option == "new": article.journal = form.new_journal_full.data new = Journal( journal=form.new_journal_full.data, abbrev=form.new_journal_abbrev.data ) db_add_commit(new) else: abort(500)
def journal_land(): # constructing the tree user_id = session['user_id'] tree = user_tree(user_id) # number of journals journal_no = len(tree) - 1 # form for new inputs of journals form = NewJournal() if form.validate_on_submit(): journal = Journal(name=form.new_journal.data, user_id=user_id) db.session.add(journal) db.session.commit() section = Section(name="my section", journal_id=journal.id) db.session.add(section) db.session.commit() entry = Entry(name="my entry", section_id=section.id, content="this is some content") db.session.add(entry) db.session.commit() user_id = session['user_id'] tree = user_tree(user_id) journal_no = len(tree) - 1 form.new_journal.data = '' return render_template('journal-land.html', tree=tree, journal_no=journal_no, form=form, name=tree[0][1]) return render_template('journal-land.html', tree=tree, journal_no=journal_no, form=form, name=tree[0][1])
def signupValidation(SignupForm): form = SignupForm username = form.username.data firstname = form.firstName.data surname = form.surname.data email = form.email.data password1 = form.password1.data password2 = form.password2.data # Username Validation # username can only contain . _ and alphanumeric regexusername = re.compile( '^(?=.{5,20}$)(?![_.])(?!.*[_.]{2})[a-zA-Z0-9._]+(?<![_.])$') # follow an email format ie. have an @, only allows alphanumerical and certain other characters regexemail = re.compile( '(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)') # password minimum 8 character, at least 1 number 1 letter regexpassword = re.compile('^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$') if not regexusername.match(username): return "username must be between 5-20 characters, contain letters, numbers or ._", None elif (User.query.filter_by(username=username).scalar()) is not None: return "username is taken", None # First name Validation elif (len(firstname) < 2 or len(firstname) > 14): # !!!!!!!!!!!!!!!!!!!! fix lower case thingy, lower case usernames still match # func.lower(User.username) == func.lower("GaNyE") return "firstname must be 2 - 20 characters", None elif not firstname.isalpha(): return "firstname can only contain letters", None # Surname Validation elif (len(surname) < 2 or len(surname) > 14): return "surname must be 2 - 20 characters", None elif not surname.isalpha(): return "surname can only contain letters", None # Email Validation elif not regexemail.match(email): return "invalid email", None elif (User.query.filter_by(email=email).scalar()) is not None: return "email is taken", None # Password validation elif password1 != password2: return "passwords do not match", None elif not regexpassword.match(password1): return "passwords must be a minimum of 8 characters, with at least 1 number and letter", None else: password = password1.encode('utf-8') salt = uuid.uuid4().hex.encode('utf-8') password_hash = hashlib.sha512(password + salt).hexdigest() user = User(username=username, firstname=firstname, surname=surname, email=email, salt=salt, password_hash=password_hash) db.session.add(user) db.session.commit() journal = Journal(name="my journal", user_id=user.id) db.session.add(journal) db.session.commit() section = Section(name="my section", journal_id=journal.id) db.session.add(section) db.session.commit() entry = Entry(name="my entry", section_id=section.id, content="this is some content") db.session.add(entry) db.session.commit() # i.e. error = False, so no errors return False, user.id
def buy_with_bank(): course_id = request.args.get('course') if course_id == None: return redirect(url_for('course.index')) bank_form = EnrollBankForm() cc_form = EnrollCreditCardForm() course_id = int(course_id) user = User(current_user) courses = [] courses.append(course_id) with Transaction().set_context(courses=courses): user = User(current_user) if user.active_membership: return redirect(url_for('course.index')) courses = Course.search([('id', '=', course_id)], limit=1) if len(courses) == 1: course, = courses if bank_form.bank_membership.data == 'MONTHLY': service_id = course.service.id else: service_id = course.yearly_service.id service = Service(service_id) if course: web_course = course ip_address = request.remote_addr if not ip_address or ip_address == '127.0.0.1': ip_address = '186.189.195.217' if ipaddress.ip_address(ip_address).is_private: ip_address = '186.189.195.217' access_token = 'cda5ddffc1e6b7' handler = ipinfo.getHandler(access_token) details = handler.getDetails(ip_address) country_code = details.country country_code = str(country_code) lcase_country_code = country_code.lower() currency_id = 16 for currency in data: if str(currency['code']) == country_code: currency_id = currency['id'] break currency = Currency(currency_id) if bank_form.validate_on_submit(): party = user.party today = date.today() subscriptions = Subscription.search([ ('party', '=', party.id), ('state', '=', 'running'), ('lines.service', '=', service_id), ]) if len(subscriptions) >= 1: print("NO ACTIVE SUBSCRIPTIONS") return redirect(url_for('course.payment')) else: enrolment, = Product.search([('is_enrolment', '=', True)], limit=1) payment_term, = PaymentTerm.search([()], limit=1) address = user.party.addresses[0] new_subscription = Subscription.create([{ 'party': user.party.id, 'start_date': today, 'invoice_start_date': today, 'invoice_recurrence': service.consumption_recurrence, 'enrolment': enrolment.id, 'unit_price_enrolment': 0, 'invoice_address': address, 'is_online': True, 'payment_term': payment_term.id, }]) new_subscription_line, = SubscriptionLine.create([{ 'subscription': new_subscription[0].id, 'service': service.id, 'quantity': 1, 'start_date': today, 'consumption_recurrence': service.consumption_recurrence, 'unit': 1, 'unit_price': service.product.list_price, }]) Subscription.quote(new_subscription) Subscription.run(new_subscription) SaleSubscriptionLine.generate_consumption(date=today, party=user.party) Subscription.generate_invoice(date=today, party=user.party) invoices = Invoice.search([('party', '=', user.party)], order=[('number', 'DESC')]) if len(invoices) >= 1: for invoice in invoices: if invoice.state == 'draft': Invoice.post([invoice]) current_line = None current_invoice = None for invoice in invoices: if invoice.state not in ['cancel', 'paid']: move = invoice.move for line in move.lines: if line.debit > 0: current_line = MoveLine(line.id) current_invoice = invoice break if not current_line or not current_invoice: return redirect(url_for('main.welcome')) def _group_payment_key(payment): return (('journal', payment.journal.id), ('kind', payment.kind)) def _new_group(values): return PaymentGroup(**values) invoice = current_invoice amount = current_invoice.total_amount ticket = bank_form.ticket.data journal, = Journal.search([('name', '=', 'DCOMPENSA')], limit=1) new_payment = Payment.create([{ 'journal': journal.id, 'kind': 'receivable', 'party': party.id, 'line': current_line.id, 'description': ticket, 'amount': current_line.debit, }]) Payment.approve(new_payment) payment, = new_payment groups = [] new_payment = sorted(new_payment, key=_group_payment_key) for key, grouped_payments in groupby(new_payment, key=_group_payment_key): def group(): group = _new_group(dict(key)) group.save() groups.append(group) return group Payment.process(list(grouped_payments), group) body = "Hemos recibido la siguiente informacion: " + \ "Nombre: "+ party.name + \ " \n Ticket: " + ticket + \ " \n Usuario: " + user.email msg = Message('Usuario Web API: '+ party.name, \ sender = '*****@*****.**', \ recipients = ['*****@*****.**']) msg.body = "Usuario Web API " + body mail.send(msg) return redirect(url_for('main.welcome')) return render_template('course/enroll.html', cc_form=cc_form, bank_form=bank_form, user=user, web_course=course, currency=currency)
def auto_rental(id_auto): # Получаем из таблицы Auto запись по автомобилю (по конкретному ID) auto = Auto.query.get(id_auto) # Получаем неизменяемую часть имени файла данного автомобиля (например, auto2_) img_url = auto.img_url[:6] # Получаем изменяемую часть имени файла данного автомобиля в виде целого числа k = int(auto.img_url[6]) # В dt помещаем текущую дату и время dt = datetime.now() if request.method == 'POST': # Пришел запрос с методом POST (на странице auto_detail.html пользователь нажал на кнопку 'Арендовать / Освободить') # Получаем все записи из таблицы Journal по данному автомобилю (по конкретному ID) journal = Journal.query.filter_by(auto_info=id_auto).all() # Устанавливаем доступность автомобиля в соответствие с тем, на какую кнопку (Арендовать / Свободен) нажал пользователь if auto.dostup == 'Свободен': auto.dostup = 'Занят' button_name = 'Освободить' if not journal: # Если записей в журнале по данному автомобилю не было, то добавляем строку в таблицу Journal db.session.add( Journal(auto_info=id_auto, time_begin=dt, time_end=None, cost=0, quantity=1, time_total=0, cost_total=0)) else: # Добавляем строку в таблицу Journal с учётом данных последней записи по данному автомобилю db.session.add( Journal(auto_info=id_auto, time_begin=dt, time_end=None, cost=0, quantity=journal[-1].quantity + 1, time_total=journal[-1].time_total, cost_total=journal[-1].cost_total)) else: # Меняем доступность автомобиля на "Свободен" и название кнопки на "Арендовать" auto.dostup = 'Свободен' button_name = 'Арендовать' # В последнюю запись по данному автомобилю в таблице Journal вносим данные: время окончания аренды, общее время аренды, стоимость последней аренды и общая стоимость аренды journal[-1].time_end = dt journal[-1].time_total += (dt - journal[-1].time_begin).seconds // 60 journal[-1].cost = ( (dt - journal[-1].time_begin).seconds // 60) * auto.price if journal[-1].cost == 0: journal[-1].cost = auto.price journal[-1].cost_total += journal[-1].cost # сохраняем изменения в базе db.session.commit() # Получаем все записи из таблицы Journal по данному автомобилю (по конкретному ID) journal = Journal.query.filter_by(auto_info=id_auto).all() # Заполняем словарь контекста для отображения на странице auto_detail.html context = { 'id_auto': auto.id, 'name_auto': auto.name, 'price': auto.price, 'in_rent_or_free': auto.dostup, 'yes_or_not': auto.transmission, 'auto_description': auto.description, 'img_url_1': auto.img_url, 'img_url_2': img_url + str((k + 1) // 5 + (k + 1) % 5) + '.jpg', 'img_url_3': img_url + str((k + 2) // 5 + (k + 2) % 5) + '.jpg', 'img_url_4': img_url + str((k + 3) // 5 + (k + 3) % 5) + '.jpg', 'button_name': button_name, 'journal_list': journal } return render_template('auto_detail.html', **context)
def pay_with_bank(): user = User(current_user) party = user.party today = date.today() courses = [] subscriptions = Subscription.search([('is_online', '=', True), ('party', '=', party.id), ('state', '=', 'running')]) if len(subscriptions) < 1: return render_template( 'bienvenido.html', user=user, flash_message= "Something wrong. Sorry the inconvenient. We will call you later.") else: for subscription in subscriptions: for line in subscription.lines: courses.append(line.service.id) with Transaction().set_context(courses=courses): if user.active_membership: return redirect(url_for('course.index')) ip_address = request.remote_addr if not ip_address or ip_address == '127.0.0.1': ip_address = '186.189.195.217' if ipaddress.ip_address(ip_address).is_private: ip_address = '186.189.195.217' access_token = 'cda5ddffc1e6b7' handler = ipinfo.getHandler(access_token) details = handler.getDetails(ip_address) country_code = details.country country_code = str(country_code) lcase_country_code = country_code.lower() currency_id = 16 for currency in data: if str(currency['code']) == country_code: currency_id = currency['id'] break currency = Currency(currency_id) subscriptions = Subscription.search([('party', '=', party.id), ('is_online', '=', True), ('state', '=', 'running')]) invoices = Invoice.search([ ('party', '=', party.id), ('state', '=', 'posted'), ], limit=1) current_line = None for invoice in invoices: move = invoice.move lines = move.lines for line in lines: if line.debit > 0: current_line = MoveLine(line.id) break if current_line is not None: enroll_form = EnrollRegistrationForm(invoice=current_line.description, amount=current_line.debit) if len(subscriptions) >= 1 and len(invoices) >= 1: if enroll_form.validate_on_submit(): def _group_payment_key(payment): return (('journal', payment.journal.id), ('kind', payment.kind)) def _new_group(values): return PaymentGroup(**values) invoice = enroll_form.invoice.data amount = enroll_form.amount.data ticket = enroll_form.ticket.data if not current_line: return redirect(url_for('main.welcome')) journal, = Journal.search([('name', '=', 'DCOMPENSA')], limit=1) new_payment = Payment.create([{ 'journal': journal.id, 'kind': 'receivable', 'party': party.id, 'line': current_line.id, 'description': ticket, 'amount': current_line.debit, }]) Payment.approve(new_payment) payment, = new_payment groups = [] new_payment = sorted(new_payment, key=_group_payment_key) for key, grouped_payments in groupby(new_payment, key=_group_payment_key): def group(): group = _new_group(dict(key)) group.save() groups.append(group) return group Payment.process(list(grouped_payments), group) body = "Hemos recibido la siguiente informacion: " + \ "Nombre: "+ party.name + \ " \n Ticket: " + ticket + \ " \n Usuario: " + user.email msg = Message('Usuario Web API: '+ party.name, \ sender = '*****@*****.**', \ recipients = ['*****@*****.**']) msg.body = "Usuario Web API " + body mail.send(msg) return redirect(url_for('main.welcome')) return render_template('course/pay_enroll_with_bank.html', user=user, enroll_form=enroll_form, invoices=invoices, subscriptions=subscriptions, currency=currency) else: return redirect(url_for('course.index'))