def create(self, title, bill_id, number, convocation, session, rubric, subject, bill_type, phase, phase_date, uri='', registration_date=None, agenda_uri='', agenda_number=None, agenda_last_date=None, agenda=None, chronology=[], documents=[], committees=[], authors=[], initiators=[], executives=[], main_executives=[], alternatives=[], bind_bills=[], **kwargs): """Save related models on create.""" from bills.models import Bill bill = Bill(title=title, bill_id=bill_id, number=number, convocation=convocation, session=session, rubric=rubric, subject=subject, bill_type=bill_type, phase=phase, phase_date=phase_date, uri=uri, registration_date=registration_date, agenda_number=agenda_number, agenda_uri=agenda_uri, agenda_last_date=agenda_last_date) bill.save() bill = self.add_agenda(bill, agenda) bill = self.add_authors(bill, authors) bill = self.add_initiators(bill, initiators) bill = self.add_executives(bill, executives) bill = self.add_main_executives(bill, main_executives) bill = self.add_chronology(bill, chronology) bill = self.add_documents(bill, documents) bill = self.add_committees(bill, committees) bill = self.add_bill_alternatives(bill, alternatives) bill = self.add_bind_bills(bill, bind_bills) return bill
def house_bill_add(request, pk): house = get_object_or_404(House, pk=pk) if request.user.id != house.user.id: raise Http404 if request.method == 'POST': formset = BillFormset(request.POST, request.FILES) if formset.is_valid(): for form in formset: if not check_format(form.cleaned_data['date']): return render(request, 'houses/house_bill_add.html', {'error': 'You have entered the date in an incorrect format! Use yyyy-mm-dd', 'house': house, 'formset': formset}) bill = Bill() bill.user = request.user bill.type = form.cleaned_data['type'] bill.amount = form.cleaned_data['amount'] bill.date = form.cleaned_data['date'] if isinstance(form.cleaned_data['date'], datetime.date): parsed_date = form.cleaned_data['date'] else: parsed_date = datetime.datetime.strptime(form.cleaned_data['date'], '%Y-%m-%d') month = parsed_date.month year = parsed_date.year existing_billset = BillSet.objects.filter(house=house).filter(year=year).filter(month=month) if existing_billset.count() == 0: new_billset = BillSet() new_billset.house = house new_billset.month = month new_billset.year = year new_billset.save() bill.set = new_billset else: bill.set = existing_billset.first() bill.save() if form.cleaned_data['file'] is not None: billfile = BillFile() billfile.user = request.user billfile.file = form.cleaned_data['file'] billfile.bill = bill billfile.save() send_bill_email(house, bill) return redirect('house_detail', house.pk) else: return render(request, 'houses/house_bill_add.html', {'error': 'You have entered invalid bill data', 'house': house, 'formset': formset}) else: formset = BillFormset() return render(request, 'houses/house_bill_add.html', {'house': house, 'formset': formset})
def test_last_period_in_feb_2018(self): """Test rule on February month""" _feb_18_date = datetime.datetime.strptime("2018-02-01T", "%Y-%m-%dT") _last_period = Bill().get_last_closed_period(_feb_18_date) self.assertEquals(_last_period, '012018')
def test_last_period_in_mar_2018(self): """Test rule on March month""" _mar_18_date = datetime.datetime.strptime("2018-03-01T", "%Y-%m-%dT") _last_period = Bill().get_last_closed_period(_mar_18_date) self.assertEquals(_last_period, '022018')
def sample_bill_2(sample_event): """Creates new Bill object""" bill = Bill(title="test bill 2", event=sample_event) if bill not in Bill.objects.all(): yield create(bill) if bill in Bill.objects.all(): delete(bill)
def test_last_period_in_dec_2018(self): """Test rule on December month""" _dec_18_date = datetime.datetime.strptime("2018-12-01T", "%Y-%m-%dT") _last_period = Bill().get_last_closed_period(_dec_18_date) self.assertEquals(_last_period, '112018')
def test_last_period_in_jan_2018(self): """Test a cross year last month (January to December)""" _jan_18_date = datetime.datetime.strptime("2018-01-01T", "%Y-%m-%dT") _last_period = Bill().get_last_closed_period(_jan_18_date) self.assertEquals(_last_period, '122017')
def test_Bill_creation(self): billset = BillSet() billset.month = 10 billset.year = 2019 billset.house = self.house billset.save() pre_count = Bill.objects.count() bill = Bill() bill.set = billset bill.user = self.user bill.type = 'ELEC' bill.date = '2019-11-04' bill.amount = 199.99 bill.save() post_count = Bill.objects.count() self.assertGreater(post_count, pre_count)
def test_48h_call_charge(self): """ Test a 48 hours call """ ts_begin = datetime.datetime.strptime("2018-08-26 14:58:08", "%Y-%m-%d %H:%M:%S") ts_end = datetime.datetime.strptime("2018-08-28 14:58:08", "%Y-%m-%d %H:%M:%S") _one_minute_call_price = Bill().calculate_charge(ts_begin, ts_end) self.assertEqual(_one_minute_call_price, 172.98)
def test_cross_from_reduced_to_charge(self): """ Test a call started on a reduced time and ended at normal time """ ts_begin = datetime.datetime.strptime("2018-08-25 23:25:10", "%Y-%m-%d %H:%M:%S") ts_end = datetime.datetime.strptime("2018-08-26 10:15:10", "%Y-%m-%d %H:%M:%S") _one_minute_call_price = Bill().calculate_charge(ts_begin, ts_end) self.assertEqual(_one_minute_call_price, 23.31)
def test_normal_time_call_charge(self): """ Test a 10 mins normal time call """ ts_begin = datetime.datetime.strptime("2018-08-26 15:07:10", "%Y-%m-%d %H:%M:%S") ts_end = datetime.datetime.strptime("2018-08-26 15:17:40", "%Y-%m-%d %H:%M:%S") _one_minute_call_price = Bill().calculate_charge(ts_begin, ts_end) self.assertEqual(_one_minute_call_price, 1.26)
def test_2_mins_to_reduced_charge(self): """ Test a 13 mins call started at 3 mins before a reduced time """ ts_begin = datetime.datetime.strptime("2018-08-26 21:57:13", "%Y-%m-%d %H:%M:%S") ts_end = datetime.datetime.strptime("2018-08-26 23:10:56", "%Y-%m-%d %H:%M:%S") _one_minute_call_price = Bill().calculate_charge(ts_begin, ts_end) self.assertEqual(_one_minute_call_price, 0.54)
def test_half_hour_to_reduced_charge(self): """ Test a 40mins call started at 30mins before a reduced time """ ts_begin = datetime.datetime.strptime("2018-08-26 21:30:10", "%Y-%m-%d %H:%M:%S") ts_end = datetime.datetime.strptime("2018-08-26 23:10:10", "%Y-%m-%d %H:%M:%S") _one_minute_call_price = Bill().calculate_charge(ts_begin, ts_end) self.assertEqual(_one_minute_call_price, 2.97)
def test_6h1s_plus_1min_charge(self): """ Test a 59secs call started at 1 second after a end reduced time """ ts_begin = datetime.datetime.strptime("2018-08-26 06:00:01", "%Y-%m-%d %H:%M:%S") ts_end = datetime.datetime.strptime("2018-08-26 06:01:00", "%Y-%m-%d %H:%M:%S") _one_minute_call_price = Bill().calculate_charge(ts_begin, ts_end) self.assertEqual(_one_minute_call_price, 0.36)
def test_o_clock_6h_plus_1min_charge(self): """ Test a 1 min call ended at the end of a reduced call plus 1 min """ ts_begin = datetime.datetime.strptime("2018-08-26 06:00:00", "%Y-%m-%d %H:%M:%S") ts_end = datetime.datetime.strptime("2018-08-26 06:01:00", "%Y-%m-%d %H:%M:%S") _one_minute_call_price = Bill().calculate_charge(ts_begin, ts_end) self.assertEqual(_one_minute_call_price, 0.45)
def test_max_normal_time_call_in_a_day_charge(self): """ Test a call that started and ended into a normal time """ ts_begin = datetime.datetime.strptime("2018-08-26 06:00:00", "%Y-%m-%d %H:%M:%S") ts_end = datetime.datetime.strptime("2018-08-26 22:00:00", "%Y-%m-%d %H:%M:%S") _one_minute_call_price = Bill().calculate_charge(ts_begin, ts_end) self.assertEqual(_one_minute_call_price, 86.67)
def test_reduced_time_call_charge(self): """ Test a call that started and ended into a reduced time """ ts_begin = datetime.datetime.strptime("2018-08-26 22:00:00", "%Y-%m-%d %H:%M:%S") ts_end = datetime.datetime.strptime("2018-08-27 06:00:00", "%Y-%m-%d %H:%M:%S") _one_minute_call_price = Bill().calculate_charge(ts_begin, ts_end) self.assertEqual(_one_minute_call_price, 0.36)
def test_o_clock_to_reduced_6h_charge(self): """ Test a 10 mins call ended at the end of a reduced time o'clock """ ts_begin = datetime.datetime.strptime("2018-08-26 05:50:00", "%Y-%m-%d %H:%M:%S") ts_end = datetime.datetime.strptime("2018-08-26 06:00:00", "%Y-%m-%d %H:%M:%S") _one_minute_call_price = Bill().calculate_charge(ts_begin, ts_end) self.assertEqual(_one_minute_call_price, 0.36)
def test_o_clock_to_reduced_22h_charge(self): """ Test a 1hour 00sec call ended at begin reduced time o'clock """ ts_begin = datetime.datetime.strptime("2018-08-26 21:00:00", "%Y-%m-%d %H:%M:%S") ts_end = datetime.datetime.strptime("2018-08-26 22:00:00", "%Y-%m-%d %H:%M:%S") _one_minute_call_price = Bill().calculate_charge(ts_begin, ts_end) self.assertEqual(_one_minute_call_price, 1.17)
def test_o_clock_to_reduced_22h_plus_1sec_charge(self): """ Test a 10 mins call ended at the begin of a reduced time plus 1sec """ ts_begin = datetime.datetime.strptime("2018-08-26 21:50:00", "%Y-%m-%d %H:%M:%S") ts_end = datetime.datetime.strptime("2018-08-26 22:00:01", "%Y-%m-%d %H:%M:%S") _one_minute_call_price = Bill().calculate_charge(ts_begin, ts_end) self.assertEqual(_one_minute_call_price, 1.17)
def test_normal_time_call_charge_minus_1sec(self): """ Test a 9mins 59sec call in normal time """ ts_begin = datetime.datetime.strptime("2018-08-26 15:07:10", "%Y-%m-%d %H:%M:%S") ts_end = datetime.datetime.strptime("2018-08-26 15:17:09", "%Y-%m-%d %H:%M:%S") _one_minute_call_price = Bill().calculate_charge(ts_begin, ts_end) self.assertEqual(_one_minute_call_price, 1.17)
def setUp(self): set_storage_test(True) with open('test_set\\catalog\\us1\\front.jpg', 'rb') as fp_front: with open('test_set\\catalog\\us1\\back.jpg', 'rb') as fp_back: bill = Bill() bill.name = bill.catalog = bill.image_id = "usd1" bill.front.save('image1.jpg', fp_front) bill.back.save('image2.jpg', fp_back) bill.save() with open('test_set\\catalog\\il50\\front.jpg', 'rb') as fp_front: with open('test_set\\catalog\\il50\\back.jpg', 'rb') as fp_back: bill = Bill() bill.name = bill.catalog = bill.image_id = "il50" bill.front.save('image1.jpg', fp_front) bill.back.save('image2.jpg', fp_back) bill.save()
def create_bill(request): try: json_data = json.load(request.POST.item("request")) bill = Bill() bill.to_object(json_data) bill.save() response = json.dump(bill.to_json(), sort_keys=True) return HttpResponse(response, mimetype='application/json') except KeyError as e: return HttpResponseBadRequest(e.value, content_type = "text/html")
def test_bill_update(self): """ Test a Bill update (new Bill record) """ _start_call = Record() _start_call.timestamp = datetime.datetime.strptime( "2018-08-26T15:07:10+0000", "%Y-%m-%dT%H:%M:%S%z") _start_call.source = '51992657100' _start_call.destination = '5133877079' _start_call.call_type = 'S' _start_call.call_id = '1' _start_call.save() _end_call = Record() _end_call.timestamp = datetime.datetime.strptime( "2018-08-26T15:17:10+0000", "%Y-%m-%dT%H:%M:%S%z") _end_call.call_type = 'E' _end_call.call_id = '1' _end_call.save() _start_period = _start_call.timestamp _end_period = _end_call.timestamp _bill = Bill() _bill.subscriber = '51992657100' _bill.period = '072018' _bill.save() _bill_record = BillRecord() _bill_record.bill_origin = _bill _bill_record.start_call = _start_call _bill_record.end_call = _end_call _bill_record.call_price = _bill.calculate_charge( _start_period, _end_period) _bill_record.save() self.assertEquals( BillRecord.objects.filter(bill_origin=_bill).count(), 1)
def get_object(self): queryset = self.get_queryset() filter = {} # Get the lookup_fields to add to the queryset filter for field in self.lookup_fields: if field in self.kwargs: filter[field] = self.kwargs[field] # Assign default period id not informed if 'period' not in filter: filter['period'] = Bill().get_last_closed_period() # Return formated not found Bill Exception try: obj = get_object_or_404(queryset, **filter) except Http404: raise NotFound("Bill not found for " "subscriber %s " "on period %s/%s " % (filter['subscriber'], filter['period'][0:2], filter['period'][2:6])) return obj
def setUp(self): self.client = APIClient() # Create a Bill of last month for tests _start_call = Record() _start_call.timestamp = datetime.datetime.strptime( "2018-08-26T15:07:10+0000", "%Y-%m-%dT%H:%M:%S%z") _start_call.source = '51992657100' _start_call.destination = '5133877079' _start_call.call_type = 'S' _start_call.call_id = '1' _start_call.save() _end_call = Record() _end_call.timestamp = datetime.datetime.strptime( "2018-08-26T15:17:10+0000", "%Y-%m-%dT%H:%M:%S%z") _end_call.call_type = 'E' _end_call.call_id = '1' _end_call.save() _start_period = _start_call.timestamp _end_period = _end_call.timestamp _bill = Bill() _bill.subscriber = '51992657100' _bill.period = last_month_string() _bill.save() _bill_record = BillRecord() _bill_record.bill_origin = _bill _bill_record.start_call = _start_call _bill_record.end_call = _end_call _bill_record.call_price = _bill.calculate_charge( _start_period, _end_period ) _bill_record.save()
def handle(self, *args, **options): today = datetime.now().date() today = today.replace(day=1) prev_month = today - timedelta(days=1) prev_month_first_day = (today - timedelta(days=1)).replace(day=1) def daterange(start_date, end_date): for n in range(int((end_date - start_date).days)): yield start_date + timedelta(n) generated = BillGenerationHistory.objects.order_by("-date") numBills = 0 totalAmount = 0 if not generated: self.stdout.write( self.style.WARNING("No previous generation history found.")) self.stdout.write("Generating bill for %d" % prev_month.month) else: last_gen = generated[0] if last_gen.date.month == prev_month.month: self.stdout.write( "The bill for %s has already been generated." % prev_month.strftime("%B")) return else: self.stdout.write("Generating bill for %d" % prev_month.month) for user in get_user_model().objects.filter(typeAccount='STUDENT'): modes = ModeHistory.objects.filter( user=user.id).order_by("-dateChanged") if not modes: mode = "MONTHLY" else: mode = modes[0].mode print(user.id, mode) if (mode == "COUPON"): continue leaves = Leave.objects.filter(user=user.id)\ .filter(is_approved=True) absent_duration = 0 for date in daterange(prev_month_first_day, today): for leave in leaves: if date >= leave.commencement_date and date <= leave.get_end_date( ): absent_duration += 1 break month_duration = (prev_month - prev_month_first_day).days + 1 duration = month_duration - absent_duration bill_amount = 120 * duration bill = Bill() bill.buyer = user bill.bill_amount = bill_amount bill.bill_from = prev_month_first_day bill.bill_days = duration bill.save() numBills += 1 totalAmount += bill_amount self.stdout.write( self.style.SUCCESS("Bill generated for user %d" % user.id)) gen = BillGenerationHistory(date=prev_month_first_day, numBills=numBills, totalAmount=totalAmount) gen.save()
def save(self, *args, **kwargs): """Business rule for save a new Start or End call record Override the Record Save Method for implement business rule Verify Call Record consistency: - Only valid Call Record types are allowed: (START_CALL_TYPE or END_CALL_TYPE) - Only unique call_id per call type is allowed - A E type Call record only may exist if a origin S type Call record (same call_id) already exists - The end call date/time MAY be higher than the start call date/time """ # Verify Call Type _valid_type = False for choise in self.TYPE_CALL_CHOICES: if self.call_type == choise[0]: _valid_type = True if not _valid_type: raise ValidationError({'detail': 'Invalid call record Type'}) # Verify a call with same type and call_id already created if Record.objects.filter(call_id=self.call_id, call_type=self.call_type).exists(): raise ValidationError( {'detail': 'This record call_id is already created'}) # If a End Call record, generate a charge if self.call_type == self.END_CALL_TYPE: # Get the origin Start Call _origin_start_call = Record.objects.filter( call_id=self.call_id, call_type=self.START_CALL_TYPE) if not _origin_start_call.exists(): raise NotFound('Origin start call record not Found') # Verify the Start and End date/time consistency if _origin_start_call.get().timestamp > self.timestamp: raise ValidationError({ 'detail': "Date/time from origin " "start call is higher then end call" }) # Get the period string # The end call date determine his bill period _end_call_period = self.timestamp.strftime("%m%Y") self.source = _origin_start_call.get().source self.destination = _origin_start_call.get().destination # Get a already created bill for the subscriber on period _already_created_bill = Bill.objects.filter( period=_end_call_period, subscriber=self.source) if _already_created_bill.exists(): self.bill = _already_created_bill.get() # If not found a already created Bill, create a new one else: _new_created_bill = Bill() _new_created_bill.subscriber = self.source _new_created_bill.period = _end_call_period _new_created_bill.save(self) self.bill = _new_created_bill # save the information of bill on the origin # start call record _origin_start_call.update(bill=self.bill) # save the current end call record super(Record, self).save(*args, **kwargs) # update the bill Bill().update_bill_record(_origin_start_call.get(), self) else: # Verify a start call with same source and destination number if (self.source == self.destination): raise ValidationError( {'detail': 'Same source and destination numbers'}) super(Record, self).save(*args, **kwargs)
def sync(): csv_file = download_spreadsheet_as_csv( "1-JD7zf6NyprMBsd1nOo34cCpYql24x0RndWDCgI6f6U") print("file is here", csv_file) shutil.copyfile(csv_file, "tmp.csv") with open("tmp.csv", "r") as csv_file: reader = csv.reader(csv_file) first_skip = True for row in reader: print(row) if first_skip: first_skip = False continue try: print(row) ( back_url, # A front_url, # B heritage, # C ebay, # D pmg, # E cat, # F name, # G num, # H billOrCoin, # I image_id, # J, ) = row[0:10] if len(back_url.split('/')) < 5 or len( front_url.split('/')) < 5: print("empty row", row) continue print("Search", cat) features = row[10:] try: bill = Bill.objects.get(catalog=cat) print("already exists") except Bill.DoesNotExist: print("creating new") bill = Bill(catalog=cat) bill.name = name bill.heritage_link = heritage bill.ebay_link = ebay bill.pmg_link = pmg back_id = back_url.split("/")[5] tmp_file = download_file_from_gdrive(back_id) bill.back.save(cat + "_back.jpg", File(open(tmp_file, "rb"))) front_id = front_url.split("/")[5] tmp_file = download_file_from_gdrive(front_id) bill.front.save(cat + "_front.jpg", File(open(tmp_file, "rb"))) bill.is_coin = billOrCoin == "Coin" bill.image_id = image_id feature_dict = {} for i in range(len(features)): feature = features[i] if feature: value = feature if value == "FALSE": value = False if value == "TRUE": value = True feature_dict[FEATURES[i]] = value print(feature_dict) bill.features = feature_dict bill.save() except Exception as e: print("Error parsing row", e) csv_file.close()