def create(self, contract_date=None): self.contract_date = DateConverter.to_date(contract_date, "%d.%m.%Y") contract = DatabaseManager.get_contract(self.school.id, self.program.id) if contract: self.contract_no = contract.contract_no self.contract_year = contract.contract_year app.logger.warning( "[%s] Contract already exists [%s, %s]. Only update contract date and regenerate", __class__.__name__, self.school.nick, self.program.id) contract.update(self.contract_date) self.generate() else: self.contract_no = str( DatabaseManager.get_next_contract_no(self.program.id)) self.contract_year = DateConverter.get_year() app.logger.info( "[%s] Adding new contract: school_nick %s: city %s | current_date %s, | contract_no %s" "| contract_year %s", __class__.__name__, self.school.nick, self.school.city, self.contract_date, self.contract_no, self.contract_year) if self.create_new(): self.generate() else: app.logger.error( "[%s] Something went wrong when creating a contract", __class__.__name__)
def create(self): application = DatabaseManager.get_application(self.school.id, self.summary.id) if len(application) > 1: app.logger.error( "Application serious error: should never be returned more than one item in this list" ) return False if not application: self.summary.set_number_of_weeks( self.common_data.get_week_numbers()) if self.create_new(): app.logger.info( "Application for summary {0}/{1} for school {2} added". format(self.summary.no, self.summary.year, self.school.nick)) self.__increase_in_summary() return True else: if DatabaseManager.remove_application(application[0].id): app.logger.info( "Application {3} for summary {0}/{1} for school {2} removed" .format(self.summary.no, self.summary.year, self.school.nick, application[0].id)) return self.create()
def get_remaning_products(school_data, product_type): data = DatabaseManager.get_product_no(session.get('program_id'), product_type) schools = DatabaseManager.get_all_schools_with_contract(session.get('program_id')) products = DatabaseManager.get_products(session.get('program_id'), product_type) for school in schools: current_contract = DatabaseManager.get_current_contract(school.id, session.get('program_id')) if not current_contract: continue kids_no = current_contract.dairy_products if not kids_no or kids_no == 0: continue # Prepare empty statistics if not school_data.get(school.nick, None): school_data[school.nick] = list() for product in products: school_data[school.nick].append(ProductStats(product, kids_no)) for d in data: if school == d[0]: for product_stats in school_data[school.nick]: if product_stats.product_name == d[ 1].get_name_mapping(): # @TODO this comparizon should be moved to Product, check how to compare to objects product_stats.decrease_product(d[2]) product_remaining = dict() for key, value in school_data.items(): for v in value: if not product_remaining.get(v.product_name, None): product_remaining[v.product_name] = 0 product_remaining[v.product_name] += v[3] return product_remaining
def school_form(school_id=INVALID_ID): if not session.get('program_id'): return redirect(url_for('program')) if school_id == INVALID_ID: id_of_school_being_added = DatabaseManager.id_of_school_being_added(FILL_STR_SCHOOL) if not id_of_school_being_added: new_school = School(nick=FILL_STR_SCHOOL, name=FILL_STR_SCHOOL, address=FILL_STR_SCHOOL, city=FILL_STR_SCHOOL, regon=FILL_STR_SCHOOL, email=FILL_STR_SCHOOL, responsible_person=FILL_STR_SCHOOL + FILL_BY_SCHOOL, phone=FILL_STR_SCHOOL + FILL_BY_SCHOOL) if DatabaseManager.add_row(new_school): return redirect(url_for('school_form', school_id=new_school.id, School=new_school)) else: return redirect(url_for('school_form', school_id=INVALID_ID)) else: return redirect( url_for('school_form', school_id=id_of_school_being_added.id, School=id_of_school_being_added)) current_school = DatabaseManager.get_school(school_id) if request.method == 'POST': data_to_update = {"nick": empty_if_none(request.form["nick"]), "name": empty_if_none(request.form["name"]), "address": empty_if_none(request.form["address"]), "city": empty_if_none(request.form["city"]), "nip": empty_if_none(request.form["nip"]), "regon": empty_if_none(request.form["regon"]), "email": empty_if_none(request.form["email"]), "phone": empty_if_none(request.form["phone"]), "responsible_person": empty_if_none(request.form["responsible_person"]), "representative": empty_if_none(request.form["representative"]), "representative_nip": empty_if_none(request.form["representative_nip"]), "representative_regon": empty_if_none(request.form["representative_regon"])} school_id = DatabaseManager.update_school_data(current_school, **data_to_update) return redirect(url_for('school_form', school_id=current_school.id)) return render_template("school_form.html", School=current_school, Contracts=DatabaseManager.get_all_contracts(school_id, session.get('program_id')))
def _generate_5a(self): DocumentCreator.__init__(self, self.template_document_va, self.output_directory) self.document.merge_rows('date_vegFruit', self.records_to_merge_vegFruit) self.document.merge_rows('date_milk', self.records_to_merge_milk) data_to_merge = dict() data_to_merge.update(self.default_data.get()) data_to_merge['weeks'] = DatabaseManager.str_from_weeks( DatabaseManager.get_weeks(self.program_id), self.summary.weeks) data_to_merge['sum_vegFruit'] = str(self.sum_product_vegFruit) data_to_merge['sum_kids_vegFruit'] = str(self.sum_product_vegFruit) data_to_merge['sum_milk'] = str(self.sum_product_milk) data_to_merge['sum_kids_milk'] = str(self.sum_product_milk) self.document.merge(**data_to_merge) doc_5a_name = "Ewidencja_VA_Wniosek_{}_{}.docx".format( self.summary.no, self.summary.year) doc_5a_name_copy = path.join( self.main_app_dir, "{0}_EwidencjaVa_{1}_{2}.docx".format(self.school.nick, self.summary.no, self.summary.year)) DocumentCreator.generate(self, doc_5a_name, False) if path.exists(doc_5a_name_copy): remove(doc_5a_name_copy) copyfile(path.join(self.output_directory, doc_5a_name), doc_5a_name_copy)
def __get_active_week(program_id, school_id, given_weeks): weeks = dict() for week_no in given_weeks: if DatabaseManager.is_any_record(program_id, school_id, week_no): weeks[week_no] = Week(number=week_no, date=DatabaseManager.get_dates( program_id, week_no)) return weeks
def __update_summary(self): self.summary.fruitVeg_income = self.summary.get_fruit_veg_income() self.summary.milk_income = self.summary.get_dairy_income() app.logger.info( "Update summary {2} fruitVeg_income: {0}, milk_income: {1}".format( self.summary.fruitVeg_income, self.summary.milk_income, self.school.nick)) DatabaseManager.modify()
def create_new(self): number = SummaryCreator.get_next_number(self.program_id) summary = Summary(no=number, year=SummaryCreator._get_current_year(), program_id=self.program_id, weeks=self.weeks) if DatabaseManager.add_row(summary): self.summary = DatabaseManager.get_summary(self.program_id, number)
def prepare_dairy_data(program_id, school, weeks): milk = DatabaseManager.get_product_amount(program_id, school, ProductName.MILK, weeks) yoghurt = DatabaseManager.get_product_amount(program_id, school, ProductName.YOGHURT, weeks) kefir = DatabaseManager.get_product_amount(program_id, school, ProductName.KEFIR, weeks) cheese = DatabaseManager.get_product_amount(program_id, school, ProductName.CHEESE, weeks) dairy_all = milk + yoghurt + kefir + cheese max_kids_perWeeks_milk = DatabaseManager.get_maxKids_perWeek(program_id, school, ProductType.DAIRY, weeks) return (dairy_all, max_kids_perWeeks_milk, dict([(ProductName.MILK, milk), (ProductName.YOGHURT, yoghurt), (ProductName.KEFIR, kefir), (ProductName.CHEESE, cheese)]))
def create_new(self): record = Record(date=self.date, state=RecordState.NOT_DELIVERED, product_id=self.product.id, contract_id=self.contract.id, week_id=DatabaseManager.get_week_by_date(self.date).id, generation_date=self.generation_date) return DatabaseManager.add_row(record)
def create_records(): if not str(session.get('program_id')): return redirect(url_for('program')) all_weeks = DatabaseManager.get_weeks(session.get('program_id')) all_schools = DatabaseManager.get_all_schools_with_contract(session.get('program_id')) if request.method == 'POST': school_id = request.form.get('wz_school', None) if school_id: return redirect(url_for('school_records', school_id=school_id)) return render_template("create_records.html", Weeks=all_weeks, School=all_schools)
def __init__(self, program_id): self.date = datetime.today().strftime('%d-%m-%Y') self.program = DatabaseManager.get_program(program_id) self.contracts = DatabaseManager.get_contracts(program_id) self.program_semester = self.program.get_current_semester() self.year = self.program.school_year self.records_to_merge = [] output_directory = config_parser.get('Directories', 'current_program') DocumentCreator.__init__(self, config_parser.get('DocTemplates', 'register'), output_directory)
def __init__(self, program_id, weeks: Set[int], no=None): self.summary: Summary = None self.program_id = program_id self.weeks = weeks if no: self.summary = DatabaseManager.get_summary(self.program_id, no) self.summary.weeks = weeks DatabaseManager.modify() self.school_no = 0 output_directory = config_parser.get('Directories', 'current_program') DocumentCreator.__init__(self, config_parser.get('DocTemplates', 'summary'), output_directory) DatabaseManager.__init__(self)
def create_summary(): if not session.get('program_id'): return redirect(url_for('program')) if request.method == 'POST': application_date = request.form["application_date"] application_weeks = request.form["application_weeks"] schools_for_summary = request.form.getlist("application_schools", type=int) application_summary = request.form.get("application_summary") if not application_date or not application_weeks: flash('Podaj date ewidencji oraz zakres tygodni', 'error') return redirect(url_for('program_form', program_id=session.get('program_id'))) weeks = parse_special_string_format_to_set(application_weeks) summary_no = int(application_summary) if application_summary else None summary_creator = SummaryCreator(session.get('program_id'), weeks, no=summary_no) summary = summary_creator.create() if not summary: app.logger.error("create_summary: summary is None. Can not create Application.") return redirect(url_for('program_form', program_id=session.get('program_id'))) update_summary_list_based_on_config_file(summary.no) appCreators = list() schools = set([application.school for application in DatabaseManager.get_school_with_summary(summary.id)]) schools.update([DatabaseManager.get_school(i) for i in schools_for_summary]) any_problems_flash_list = list() for school in schools: try: application = ApplicationCreator(session.get('program_id'), school, summary, application_date) if application.inconsistent_records_error: any_problems_flash_list.append(application.inconsistent_records_error) if application.create(): appCreators.append(application) except ValueError as e: app.logger.error(f"Cannot create application for {school.nick}: {e}") any_problems_flash_list.append( (f"Szkoła {school.nick} zostanie pominięta, ponieważ ilość tygodni na oświadczeniu: {len(application.common_data.get_week_numbers())} {application.common_data.get_week_numbers()} " f"nie zgadza sie z ilością w generowanym wniosku: {summary.number_of_weeks}.", 'error')) for appCreator in appCreators: summary_creator.school_no += 1 # TODO change this to update in some smarter way appCreator.generate() summary_creator.generate() for problem in any_problems_flash_list: flash(problem[0], problem[1]) return redirect(url_for('program_form', program_id=session.get('program_id')))
def add_week(program_id): current_program = request.args.get('program') if not current_program: current_program = DatabaseManager.get_program(program_id) if request.method == 'POST': if not request.form['week_no'] or not request.form['start_date'] or not request.form['end_date']: flash('Uzupełnij wszystkie dane', 'error') else: new_week = Week(week_no=request.form['week_no'], start_date=DateConverter.to_date(request.form['start_date']), end_date=DateConverter.to_date(request.form['end_date']), program_id=current_program.id) if DatabaseManager.add_row(new_week): return redirect(url_for("program_form", program_id=current_program.id)) return render_template("add_week.html", program_id=program_id, program=current_program)
def prepare_weeks(program_id): data_to_merge = dict() data_to_merge['week_date_1'] = DatabaseManager.get_dates(program_id, 1) data_to_merge['week_date_2'] = DatabaseManager.get_dates(program_id, 2) data_to_merge['week_date_3'] = DatabaseManager.get_dates(program_id, 4) data_to_merge['week_date_4'] = DatabaseManager.get_dates(program_id, 13) data_to_merge['week_date_5'] = None data_to_merge['week_date_6'] = None data_to_merge['week_date_7'] = None data_to_merge['week_date_8'] = None data_to_merge['week_date_9'] = None data_to_merge['week_date_10'] = None data_to_merge['week_date_11'] = None data_to_merge['week_date_12'] = None return data_to_merge
def __are_records_inconsistent(self, inconsistency_treated_as_error=False): inconsistent_records = DatabaseManager.get_any_inconsistent_records_with_annex( self.program_id, self.school.id, self.common_data.get_week_numbers()) if inconsistent_records: raise InconsistentAnnexWzError(inconsistent_records, inconsistency_treated_as_error)
def __init__(self, common_app_info: CommonData): super().__init__(common_app_info) self.product_type = ProductType.DAIRY self.base_name = "milk" self.contract_kids_no = DatabaseManager.get_contract( self.common_app_info.school_id, self.common_app_info.program_id).dairy_products
def school_form_edit_annex(school_id, annex_id): if not session.get('program_id'): return redirect(url_for('program')) school = DatabaseManager.get_school(school_id) annex: Contract = DatabaseManager.get_existing_annex(annex_id) if request.method == 'POST': date = DateConverter.to_date(request.form['contract_date']) date_valid = DateConverter.to_date(request.form['validity_date']) fruitVeg_products = request.form['fruitVeg_products'] dairy_products = request.form['dairy_products'] if annex: annex.update(date, date_valid, fruitVeg_products, dairy_products) AnnexCreator(annex.school_id, annex.program_id, annex).generate() return redirect(url_for('school_form', school_id=school_id)) return render_template("add_annex_form.html", school=school, annex=annex)
def create_new(self): application_data = dict() application_data['summary_id'] = self.summary.id application_data['school_id'] = self.school.id application_data.update(self.product_data) application = Application(**application_data) return DatabaseManager.add_row(application)
def __init__(self, common_app_info: CommonData): super().__init__(common_app_info) self.product_type = ProductType.FRUIT_VEG self.base_name = "fruitVeg" self.contract_kids_no = DatabaseManager.get_contract( self.common_app_info.school_id, self.common_app_info.program_id).fruitVeg_products
def create(self, contract_date=None, validity_date=None, fruitVeg_products=None, dairy_products=None): if validity_date and DatabaseManager.is_annex( DateConverter.DateConverter.to_date(validity_date, pattern="%d.%m.%Y"), self.school.id, self.program_id): app.logger.error( "[%s] Annex already exists [%s, %s]. Only modifying is possible", __class__.__name__, self.school.nick, self.validity_date) return False #TODO Validate if any records for this period already exsits if yes update record (remove and add) # and notify that recodrd were update self.contract_date = datetime.strptime(contract_date, "%d.%m.%Y") self.validity_date = datetime.strptime(validity_date, "%d.%m.%Y") self.fruitVeg_products = fruitVeg_products # @TODO if None get_the_latest_value self.dairy_products = dairy_products app.logger.info( "[%s] Adding new annex: school_nick %s: city %s | current_date %s, | contract_no %s" "| contract_year %s | validity_date %s | fruitVeg_products %s | dairy_products %s ", __class__.__name__, self.school.nick, self.school.city, self.contract_date, self.contract_no, self.contract_year, self.validity_date, self.fruitVeg_products, self.dairy_products) if self.create_new(): self.generate() else: app.logger.error("[%s] Something went wrong when creating annex", __class__.__name__) return True
def record_created(current_date, week_id, duplicated_records=""): if not str(session.get('program_id')): return redirect(url_for('program')) daily_records = DatabaseManager.get_daily_records(session.get('program_id'), current_date) if request.method == 'GET': duplicated_records = request.args.get('duplicated_records') if request.method == 'POST': if request.form['action']: action_record_list = request.form['action'].split("_") action = action_record_list[0] record_id = action_record_list[1] if action == "update": DatabaseManager.get_record(record_id).set_to_delivered() app.logger.info("Update state to Delivered Record.id %s", record_id) if action == "modify": pass if action == "update_product": pass if action == "delete": generation_date = DatabaseManager.get_record(record_id).generation_date DatabaseManager.remove_record(record_id) if generation_date: daily_records = DatabaseManager.get_daily_records(session.get('program_id'), current_date, generation_date) RecordCreator.regenerate_documentation(daily_records) app.logger.info("Remove: Record.id %s", record_id) return redirect( url_for('record_created', daily_records=daily_records, current_date=current_date, week_id=week_id, duplicated_records=duplicated_records)) if duplicated_records: flash("Nie możesz dodać WZtek: {}".format(duplicated_records), 'error') return render_template("generated_record.html", daily_records=daily_records, current_date=current_date, week_id=week_id, duplicated_records=duplicated_records)
def __init__(self, school, program_id, ommit_representat=True): self.main_contract_dir = config_parser.get('Directories', 'contract_all') if not path.exists(self.main_contract_dir): makedirs(self.main_contract_dir) self.program = DatabaseManager.get_program(program_id) self.school = school self.contract_no = None self.contract_year = None self.contract_date = None self.ommit_representat = ommit_representat output_directory = self.school.generate_directory_name( config_parser.get('Directories', 'contract')) DocumentCreator.__init__(self, config_parser.get('DocTemplates', 'contract'), output_directory) DatabaseManager.__init__(self)
def generate_contracts(program_id): current_program = DatabaseManager.get_program(program_id) contract_date = request.form["contract_date"] if not is_current_program_set(current_program, config_parser): flash('Żeby wygenerować umowy ustaw program jako aktulany', 'error') elif not contract_date or contract_date == "dd.mm.rrrr": flash('Uzupełnij datę zawarcia umów', 'error') else: if session.get('program_id') == program_id: all_schols = DatabaseManager.get_all_schools() for school in all_schols: if school.nick != FILL_STR_SCHOOL: # Dont create contract for school with not full date filled new_contract = ContractCreator(school, session.get('program_id')) new_contract.create(DateConverter.to_date(contract_date)) flash("Umowy zostały wygenerowane pomyślnie", 'success') else: flash('Możesz wygnerować umowy tylko dla akutalnie wybranego programu', 'error') return render_template("program_form.html", Program=current_program)
def add_product(program_id, product_type): current_program = DatabaseManager.get_program(program_id) if request.method == 'POST': if not product_type: product_type = request.form['type'] return redirect(url_for("add_product", program_id=current_program.id, product_type=product_type, program=current_program)) if product_type: if not request.form['name'] or not request.form['min_amount']: flash('Uzupełnij nazwe i liczbe podań', 'error') else: new_product = Product(name=ProductName(int(request.form['name'])).name, type=ProductType(int(product_type)).name, min_amount=int(request.form['min_amount']), program_id=current_program.id) if DatabaseManager.add_row(new_product): return redirect(url_for("program_form", program_id=current_program.id)) return render_template("add_product.html", program_id=current_program.id, program=current_program, product_type=product_type)
def _prepare_school_data(self): no = 1 for contract in self.contracts: self.fill_data_in_table(contract, no, False) # Fill additional fields with annex information if needed any for annex in DatabaseManager.get_annex(contract.program_id, contract.contract_no): self.fill_data_in_table(annex, no, True) no += 1
def school_records(school_id): if not session.get('program_id'): return redirect(url_for('program')) records = DatabaseManager.get_school_records(session.get('program_id'), school_id) if request.method == 'POST': if request.form['action']: action_record_list = request.form['action'].split("_") action = action_record_list[0] record_id = action_record_list[1] if action == "update": DatabaseManager.get_record(record_id).set_to_delivered() app.logger.info("Update state to Delivered Record.id %s", record_id) if action == "modify": pass # @TODO modify records if action == "delete": DatabaseManager.remove_record(record_id) app.logger.info("Remove: Record.id %s", record_id) return redirect(url_for('school_records', school_id=school_id)) return render_template("generated_record_per_school.html", records=records)
def create_new(self): annex = Contract(contract_no=self.contract_no, contract_year=self.contract_year, contract_date=self.contract_date, validity_date=self.validity_date, fruitVeg_products=self.fruitVeg_products, dairy_products=self.dairy_products, is_annex=True, school_id=self.school.id, program_id=self.program_id) return DatabaseManager.add_row(annex)
def program(): all_programs = DatabaseManager.get_programs_all() if not str(session.get('program_id')): session['program_id'] = DatabaseManager.get_program().id current = request.args.get('current') current_session_program = DatabaseManager.get_program(current) if current else DatabaseManager.get_program( session.get('program_id')) if current_session_program: session['program_id'] = current_session_program.id update_program_id_summary_set_mapping(current_session_program.id) program = DatabaseManager.get_program(session['program_id']) school_year = program.school_year.replace("/", "_") config_parser.set('Program', 'year', f"{school_year}") config_parser.set('Program', 'semester', f"{program.semester_no}") update_summary_list_based_on_session(current_session_program.id) with open(config_file, 'w') as configfile: config_parser.write(configfile) return render_template("program.html", Programs=all_programs, current=current_session_program, invalid_program_id=INVALID_ID)