Django Status Transition Issue: Incorrect Status Update for 'New', 'Active', and 'Deleted'

I have a question. I recently noticed that the statuses aren't updating correctly from "new" to "active" and from "deleted" to "not visible anymore."

For example, the program should show the "new" status in January and switch to "active" in February, but instead, it's showing "new" for both January and February, and only switching to "active" in March.

The same issue is happening with the "deleted" status. It should show as "deleted" in January and change to "not visible anymore" in February. However, it's showing as "deleted" in January, February, and March, and then disappears entirely in April.

What could be causing this issue? I assume it is the wrong timestamps that were set up, but I am not sure how to redefine them.

The main issue is in production, not in development although the codes are the same.

class ReportView(View):
template_name = "reports/report.html"

def get(self, request):
    context = {
        'menu': get_service_menu_data(),
    }
    return render(request, self.template_name, context)

def post(self, request):
    logger.info(f"Request: {request.method} {request.path}?{str(request.body)[str(request.body).index('&') + 1:-1]}")
    form = csv_form(request.POST)
    if form.is_valid():
        company = form.cleaned_data.get('company')
        month = form.cleaned_data.get('month')
        year = form.cleaned_data.get('year')

        date_from = datetime.date(int(year), int(month), 1)
        date_to = datetime.date(int(year), int(month), calendar.monthrange(int(year), int(month))[1]) + datetime.timedelta(days=1)
        prev_month = date_from - relativedelta(months=1)
        next_month = date_to + relativedelta(months=1)

        current_numbers = PhoneNumberHolder.objects.filter(
            billing_group__billing_group=company,
            purchased__lte=date_to
        ).exclude(
            terminated__lt=date_from
        )

        prev_numbers = PhoneNumberHolder.objects.filter(
            billing_group__billing_group=company,
            purchased__lte=prev_month + relativedelta(months=1) - relativedelta(days=1)
        ).exclude(
            terminated__lt=prev_month
        )

        next_numbers = PhoneNumberHolder.objects.filter(
            billing_group__billing_group=company,
            purchased__lte=next_month,
            terminated__isnull=True
        ) | PhoneNumberHolder.objects.filter(
            billing_group__billing_group=company,
            purchased__lte=next_month,
            terminated__gte=next_month
        )

        status_data = {
            'new': [],
            'active': [],
            'deleted': [],
            'port_pending': [],
        }

        for number in current_numbers:
            was_present = prev_numbers.filter(phone_number=number.phone_number).exists()
            will_be_present = next_numbers.filter(phone_number=number.phone_number).exists()

            price_info = {
                'country_code': number.phone_number.country_code,
                'phone_number': number.phone_number.number,
                'telnyx_price': None,
                'our_price': number.individual_price or number.phone_number.price.price,
                'status': None,
                'terminated_date': number.terminated.strftime('%Y-%m-%d') if number.terminated else None
            }

            if number.status == number.STATUS_PORT_PENDING:
                price_info['status'] = 'port_pending'
                status_data['port_pending'].append(price_info)
            elif not will_be_present or (number.terminated and number.terminated < next_month):
                price_info['status'] = 'deleted'
                status_data['deleted'].append(price_info)
            else:
                price_info['status'] = 'active'
                status_data['active'].append(price_info)

        for number in prev_numbers:
            if not current_numbers.filter(phone_number=number.phone_number).exists():
                price_info = {
                    'country_code': number.phone_number.country_code,
                    'phone_number': number.phone_number.number,
                    'telnyx_price': None,
                    'our_price': number.individual_price or number.phone_number.price.price,
                    'status': 'deleted',
                    'terminated_date': number.terminated.strftime('%Y-%m-%d') if number.terminated else None
                }
                status_data['deleted'].append(price_info)

        new_numbers = next_numbers.exclude(phone_number__in=current_numbers.values_list('phone_number', flat=True))
        for number in new_numbers:
            price_info = {
                'country_code': number.phone_number.country_code,
                'phone_number': number.phone_number.number,
                'telnyx_price': None,
                'our_price': number.individual_price or number.phone_number.price.price,
                'status': 'new',
                'terminated_date': None
            }
            status_data['new'].append(price_info)

        data = Telnyx_raw_data.objects.filter(billing_group=company,
                                              call_start_date__range=[date_from, date_to]
                                              ).order_by('call_start_date', 'direction').values()
        prices = calculate_cost(data)
        all_data = zip(data, prices['final'], prices['minute'], prices['is_new'], prices['loss'])

        number_prices, numbers_total = format_number_bill(company, date_to)

        csv_data = {
            'billing_group': company,
            'date_from': str(date_from),
            'date_to': str(date_to),
        }
        report_date = [item for item in csv_form().months if item[0] == month][0]
        context = {
            'menu': get_service_menu_data(),
            'date': f"{year}, {report_date[1]}",
            'status_data': status_data,
            'data': all_data,
            'call_bill_total': round(prices['total'], 5),
            'csv': csv_data,
            'number_bill': {
                'prices': number_prices,
                'total': numbers_total
            },
            'telnyx_prices': get_telnyx_number_prices(),
        }
        logger.info(f"Response: Report data collected: {csv_data['billing_group']}, {report_date[2]}")
    return render(request, self.template_name, context)
Вернуться на верх