Esempio n. 1
0
    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 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")
Esempio n. 3
0
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})
Esempio n. 4
0
 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()
Esempio n. 5
0
    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)
Esempio n. 6
0
    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)
Esempio n. 7
0
    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)
Esempio n. 10
0
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()