def test_placeholder_pk_thousands_format(self): page = create_page("page", "nav_playground.html", "en", published=True) for placeholder in page.placeholders.all(): page.placeholders.remove(placeholder) placeholder.pk += 1000 placeholder.save() page.placeholders.add(placeholder) page.reload() for placeholder in page.placeholders.all(): add_plugin(placeholder, "TextPlugin", "en", body="body", id=placeholder.pk) with SettingsOverride(USE_THOUSAND_SEPARATOR=True, USE_L10N=True): # Superuser user = self.get_superuser() self.client.login(username=getattr(user, get_user_model().USERNAME_FIELD), password=getattr(user, get_user_model().USERNAME_FIELD)) response = self.client.get("/en/?%s" % get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON')) for placeholder in page.placeholders.all(): self.assertContains( response, "'placeholder_id': '%s'" % placeholder.pk) self.assertNotContains( response, "'placeholder_id': '%s'" % format( placeholder.pk, ".", grouping=3, thousand_sep=",")) self.assertNotContains( response, "'plugin_id': '%s'" % format( placeholder.pk, ".", grouping=3, thousand_sep=",")) self.assertNotContains( response, "'clipboard': '%s'" % format( response.context['request'].toolbar.clipboard.pk, ".", grouping=3, thousand_sep=","))
def test_placeholder_pk_thousands_format(self): page = create_page("page", "nav_playground.html", "en", published=True) for placeholder in page.placeholders.all(): page.placeholders.remove(placeholder) placeholder.pk += 1000 placeholder.save() page.placeholders.add(placeholder) page.reload() for placeholder in page.placeholders.all(): plugin = add_plugin(placeholder, "TextPlugin", "en", body="body", id=placeholder.pk) with SettingsOverride(USE_THOUSAND_SEPARATOR=True, USE_L10N=True): # Superuser user = self.get_superuser() self.client.login(username=user.username, password=user.username) response = self.client.get("/en/?edit") for placeholder in page.placeholders.all(): self.assertContains(response, "'placeholder_id': '%s'" % placeholder.pk) self.assertNotContains( response, "'placeholder_id': '%s'" % format(placeholder.pk, ".", grouping=3, thousand_sep=",")) self.assertNotContains( response, "'plugin_id': '%s'" % format(placeholder.pk, ".", grouping=3, thousand_sep=",")) self.assertNotContains( response, "'clipboard': '%s'" % format(response.context['request'].toolbar.clipboard.pk, ".", grouping=3, thousand_sep=","))
def createMissionRow(mission, start_date, end_date): """Inner function to create mission row""" missionRow = [] missionRow.append(start_date.year) missionRow.append(end_date.isoformat()) missionRow.append("timesheet") missionRow.append(mission.nature) missionRow.append(not mission.active) missionRow.append(mission.subsidiary) if mission.lead: missionRow.append(mission.lead.client.organisation.company.name) missionRow.append(mission.lead.client.organisation.company.code) missionRow.append(mission.lead.client.organisation.name) missionRow.append(mission.lead.name) missionRow.append(mission.lead.deal_id) missionRow.append(numberformat.format(mission.lead.sales, ",") if mission.lead.sales else 0) if mission.lead.responsible: missionRow.append(mission.lead.responsible.name) missionRow.append(mission.lead.responsible.trigramme) missionRow.append(mission.lead.responsible.manager.trigramme if mission.lead.responsible.manager else "") else: missionRow.extend(["", "", ""]) else: missionRow.extend(["", "", "", "", "", 0, "", "", ""]) missionRow.append(mission.description or "") missionRow.append(mission.mission_id()) missionRow.append(mission.billing_mode or "") missionRow.append(numberformat.format(mission.price, ",") if mission.price else 0) missionRow.extend(mission.done_work()) return missionRow
def test_placeholder_pk_thousands_format(self): page = create_page("page", "nav_playground.html", "en", published=True) for placeholder in page.placeholders.all(): page.placeholders.remove(placeholder) placeholder.pk += 1000 placeholder.save() page.placeholders.add(placeholder) page.reload() for placeholder in page.placeholders.all(): add_plugin(placeholder, "TextPlugin", "en", body="body") with self.settings(USE_THOUSAND_SEPARATOR=True, USE_L10N=True): # Superuser user = self.get_superuser() self.client.login(username=getattr(user, get_user_model().USERNAME_FIELD), password=getattr(user, get_user_model().USERNAME_FIELD)) endpoint = page.get_absolute_url() + '?' + get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON') response = self.client.get(endpoint) for placeholder in page.placeholders.all(): self.assertContains( response, '"placeholder_id": "%s"' % placeholder.pk) self.assertNotContains( response, '"placeholder_id": "%s"' % format( placeholder.pk, ".", grouping=3, thousand_sep=",")) self.assertNotContains( response, '"plugin_id": "%s"' % format( placeholder.pk, ".", grouping=3, thousand_sep=",")) self.assertNotContains( response, '"clipboard": "%s"' % format( response.context['request'].toolbar.clipboard.pk, ".", grouping=3, thousand_sep=","))
def format_price(price, currency, decimal_pos=None): if not currency: return price if decimal_pos is None: decimal_pos = currency.decimal_places d = Decimal(str(price)) if decimal_pos == 0: exp = Decimal(1) else: exp = Decimal('1.0') / (Decimal(10)**abs(decimal_pos)) formatted_price = numberformat.format( u'%s' % str(d.quantize(exp, ROUND_HALF_UP)), currency.decimal_separator, abs(decimal_pos), grouping=3, thousand_sep=currency.thousand_separator) if currency.symbol_preceeds: params = (currency.symbol, formatted_price) else: params = (formatted_price, currency.symbol) return u'%s %s' % params
def number_format(value, decimal_pos=None, use_l10n=None, force_grouping=False): """ Formats a numeric value using localization settings If use_l10n is provided and is not None, that will force the value to be localized (or not), overriding the value of settings.USE_L10N. """ if use_l10n or (use_l10n is None and settings.USE_L10N): lang = get_language() else: lang = None return numberformat.format(value, get_format('DECIMAL_SEPARATOR', lang, use_l10n=use_l10n), decimal_pos, get_format('NUMBER_GROUPING', lang, use_l10n=use_l10n), get_format('THOUSAND_SEPARATOR', lang, use_l10n=use_l10n), force_grouping=force_grouping)
def elements(self): """ Returns a dict of the various elements for localised display. eg en_AU: value "1,234.56" curr_sym "$" decimal_sym "." major "1,234" minor "56" Additional items may be present if available. """ # If babel is available, use its comprehensive locale skills if babel: value = self curr_sym = self.locale.currency_symbols.get( self.currency, self.currency) decimal_sym = self.locale.number_symbols.get('decimal', ".") value = babel.numbers.format_decimal(value, "#,##0.00", locale=self.locale) # If no babel, use Django's built-in locale data else: value = "%.02f" % self curr_sym = self.currency decimal_sym = get_format('DECIMAL_SEPARATOR', self.locale) group_sym = get_format('THOUSAND_SEPARATOR', self.locale) num_group = get_format('NUMBER_GROUPING', self.locale) value = numberformat.format(value, decimal_sym, None, num_group, group_sym) major, minor = value.rsplit(decimal_sym, 1) return locals().copy()
def format_money(value): return numberformat.format(value, decimal_pos=2, decimal_sep=',', force_grouping=True, grouping=3, thousand_sep='.')
def intcomma_indian(value, preserve_decimal=False): """ Convert an integer to a string containing commas as per Indian Number System This function accepts integer, float, and string value, but strips decimal part before computing indian number notation of integral part. For example: 100000 becomes 1,00,000 1259647552 becomes 1,25,96,47,552 126500.25 becomes 1,26,500 -126500 becomes -1,26,500 :param value: integer, float, string :param preserve_decimal: Keep decimal values :return: string """ try: if not isinstance(value, (int, float, Decimal)): value = float(value) except (TypeError, ValueError): return value decimal_pos = None if preserve_decimal else 0 return numberformat.format(value, decimal_sep='.', decimal_pos=decimal_pos, grouping=(3, 2), thousand_sep=',')
def format_score(score): return numberformat.format(score, decimal_sep='', decimal_pos=0, grouping=3, thousand_sep='.', force_grouping=True)
def floatcomma_indian(value, decimal_pos=None): """ Convert a floating point number to a string containing commas as per Indian Number System This function accepts integer, float, and string value. If the value passed does not have any decimal places, then 2 decimal places are added by default. Decimal places are preserved in all other cases. Example: 25 becomes 25 121250.6 becomes 1,125.6 25.675 becomes 25.675 126500.25 becomes 1,26,500.25 -126500.75 becomes -1,26,500.75 :param value: integer or float :param decimal_pos: Number of decimal positions to add/preserve :return: """ try: if not isinstance(value, (int, float, Decimal)): value = float(value) except (TypeError, ValueError): return value return numberformat.format(value, decimal_sep='.', decimal_pos=decimal_pos, grouping=(3, 2), thousand_sep=',')
def elements(self): """ Returns a dict of the various elements for localised display. eg en_AU: value "1,234.56" curr_sym "$" decimal_sym "." major "1,234" minor "56" Additional items may be present if available. """ # If babel is available, use its comprehensive locale skills if babel: value = self curr_sym = self.locale.currency_symbols.get(self.currency, self.currency) decimal_sym = self.locale.number_symbols.get('decimal', ".") value = babel.numbers.format_decimal(value, "#,##0.00", locale=self.locale) # If no babel, use Django's built-in locale data else: value = "%.02f" % self curr_sym = self.currency decimal_sym = get_format('DECIMAL_SEPARATOR', self.locale) group_sym = get_format('THOUSAND_SEPARATOR', self.locale) num_group = get_format('NUMBER_GROUPING', self.locale) value = numberformat.format(value, decimal_sym, None, num_group, group_sym) major, minor = value.rsplit(decimal_sym, 1) return locals().copy()
def number_format(value, decimal_pos=None, use_l10n=None, force_grouping=False): """ Format a numeric value using localization settings. If use_l10n is provided and is not None, it forces the value to be localized (or not), overriding the value of settings.USE_L10N. """ if use_l10n is None: try: use_l10n = settings._USE_L10N_INTERNAL except AttributeError: use_l10n = settings.USE_L10N lang = get_language() if use_l10n else None return numberformat.format( value, get_format("DECIMAL_SEPARATOR", lang, use_l10n=use_l10n), decimal_pos, get_format("NUMBER_GROUPING", lang, use_l10n=use_l10n), get_format("THOUSAND_SEPARATOR", lang, use_l10n=use_l10n), force_grouping=force_grouping, use_l10n=use_l10n, )
def moeda_real_display(valor): if valor: return numberformat.format(valor, ",", grouping=3, thousand_sep=".", force_grouping=True) return ""
def format_number(num): """ Add thousand separator to a number """ return numberformat.format(num, grouping=3, decimal_sep='.', thousand_sep=',', force_grouping=True)
def format_money(value): return numberformat.format( value, decimal_pos=2, decimal_sep=',', force_grouping=True, grouping=3, thousand_sep='.' )
def float_format_br(number, decimal_pos=2): if number is None: return '' return format(number, decimal_sep=',', decimal_pos=decimal_pos, grouping=3, thousand_sep='.', force_grouping=3)
def currency(value,decimal=0): return numberformat.format( value, settings.DECIMAL_SEPARATOR, decimal, settings.NUMBER_GROUPING, settings.THOUSAND_SEPARATOR, force_grouping=True )
def monetary_format_br(number): if number is None: return '' number = float(number) return format(number, decimal_sep=',', decimal_pos=2, grouping=3, thousand_sep='.', force_grouping=3)
def integer_format_br(number): if number is None: return '' number = int(number) return format(number, decimal_sep='', decimal_pos=0, grouping=3, thousand_sep='.', force_grouping=3)
def number_format(value, decimal_pos=None): """ Formats a numeric value using localization settings """ return numberformat.format( value, get_format('DECIMAL_SEPARATOR'), decimal_pos, get_format('NUMBER_GROUPING'), get_format('THOUSAND_SEPARATOR'), )
def format_number(number: Union[int, float], decimal_places: Optional[int] = None): if decimal_places is not None: number = round(number, decimal_places) return format( number, decimal_sep=",", thousand_sep=".", force_grouping=True, grouping=3, )
def display_amount(self, amount=111, precision=2, with_slug=None): amount = decimal_round(amount, precision) amount_str = format(amount, '.', grouping=3, thousand_sep=' ', force_grouping=True) slug = self.symbol if with_slug is None else with_slug if get_language() == 'ru': return u'%s %s' % (amount_str, slug) if amount < 0: return amount_str.replace('-', u'-%s' % slug) return u'%s %s' % (slug, amount_str)
def floatdot(value, decimal_pos=4): """ Passed a string representing a decimal number with a comma separator, it returns the same decimal number with a dot separator. This is useful when the project is using european languages in ``USE_I18N`` and ``USE_L10N`` and you need to handle decimal numbers in templates to process data, like for example happens when you need to process geographic coordinates via Javascript in a Dutch or French environment. """ try: return format(value, ".", decimal_pos) except IndexError: # Just fail silently if there is the string is empty. pass
def _value_display(self, attr): value = getattr(self, attr, 0) if value > 0: formatted_value = format(value, '.', decimal_pos=2, grouping=3, thousand_sep=',', force_grouping=True) currency = getattr(self, "{0}_currency".format(attr)).code display_str = "{0} {1}".format(currency, formatted_value) else: display_str = "None" return display_str
def number_format(value, decimal_pos=None): """ Formats a numeric value using localization settings """ if settings.USE_L10N: lang = get_language() else: lang = None return numberformat.format( value, get_format('DECIMAL_SEPARATOR', lang), decimal_pos, get_format('NUMBER_GROUPING', lang), get_format('THOUSAND_SEPARATOR', lang), )
def natural_number_with_currency(number, currency, show_decimal_place=True, use_nbsp=True): """ Return a given `number` formatter a price for humans. """ humanized = '{} {}'.format( numberformat.format( number=number, decimal_sep=',', decimal_pos=2 if show_decimal_place else 0, grouping=3, thousand_sep=' ', force_grouping=True ), force_text(currency) ) return mark_safe(humanized.replace(' ', '\u00a0')) if use_nbsp else humanized
def natural_number_with_currency(number, currency, show_decimal_place=True, use_nbsp=True): """ Return a given `number` formatter a price for humans. """ humanized = '{} {}'.format( numberformat.format(number=number, decimal_sep=',', decimal_pos=2 if show_decimal_place else 0, grouping=3, thousand_sep=' ', force_grouping=True), force_text(currency)) return mark_safe(humanized.replace(' ', '\u00a0')) if use_nbsp else humanized
def decimal(value, decimal_pos=None, thousand_separator=None): if not value: return '' if thousand_separator: grouping = 3 thousand_sep = thousand_separator force_grouping = True else: grouping = 0 thousand_sep = '' force_grouping = False lang = translation.get_language() decimal_sep = get_format('DECIMAL_SEPARATOR', lang, use_l10n=True) return numberformat.format(value, decimal_sep, decimal_pos, grouping, thousand_sep, force_grouping)
def number_format(value, decimal_pos=None, use_l10n=None): """ Formats a numeric value using localization settings If use_l10n is provided and is not None, that will force the value to be localized (or not), overriding the value of settings.USE_L10N. """ if use_l10n or (use_l10n is None and settings.USE_L10N): lang = get_language() else: lang = None return numberformat.format( value, get_format('DECIMAL_SEPARATOR', lang, use_l10n=use_l10n), decimal_pos, get_format('NUMBER_GROUPING', lang, use_l10n=use_l10n), get_format('THOUSAND_SEPARATOR', lang, use_l10n=use_l10n), )
def test_placeholder_pk_thousands_format(self): page = create_page("page", "nav_playground.html", "en", published=True) for placeholder in page.placeholders.all(): page.placeholders.remove(placeholder) placeholder.pk += 1000 placeholder.save() page.placeholders.add(placeholder) page.reload() for placeholder in page.placeholders.all(): plugin = add_plugin(placeholder, "TextPlugin", "en", body="body", id=placeholder.pk) with SettingsOverride(USE_THOUSAND_SEPARATOR=True, USE_L10N=True): # Superuser user = self.get_superuser() self.client.login(username=user.username, password=user.username) response = self.client.get("/en/?edit") for placeholder in page.placeholders.all(): self.assertContains(response, "'placeholder_id': '%s'" % placeholder.pk) self.assertNotContains(response, "'placeholder_id': '%s'" % format(placeholder.pk, ".", grouping=3, thousand_sep=","))
def test_locale_independent(self): """ Localization of dates and numbers """ settings.USE_L10N = True settings.USE_THOUSAND_SEPARATOR = False self.assertEqual(u'66666.66', format(self.n, decimal_sep='.', decimal_pos=2, grouping=3, thousand_sep=',')) self.assertEqual(u'66666A6', format(self.n, decimal_sep='A', decimal_pos=1, grouping=1, thousand_sep='B')) settings.USE_THOUSAND_SEPARATOR = True self.assertEqual(u'66,666.66', format(self.n, decimal_sep='.', decimal_pos=2, grouping=3, thousand_sep=',')) self.assertEqual(u'6B6B6B6B6A6', format(self.n, decimal_sep='A', decimal_pos=1, grouping=1, thousand_sep='B')) self.assertEqual(u'-66666.6', format(-66666.666, decimal_sep='.', decimal_pos=1)) self.assertEqual(u'-66666.0', format(int('-66666'), decimal_sep='.', decimal_pos=1))
def render(self, name, value, attrs=None): self.mask['mask'] = '%s%s%s' % ( '9' * self.decimal_places, self.decimal_sep, chunks('9' * (self.max_digits - self.decimal_places), 3, self.thousands_sep), ) try: Decimal(value) except: pass else: value = numberformat.format( value, self.decimal_sep, decimal_pos=self.decimal_places, thousand_sep=self.thousands_sep, ) return super(DecimalInputMask, self).render(name, value, attrs=attrs)
def render(self, name, value, attrs=None): self.mask['mask'] = '%s%s%s' % ( '9' * self.decimal_places, self.decimal_sep, chunks( '9' * (self.max_digits - self.decimal_places), 3, self.thousands_sep), ) try: Decimal(value) except: pass else: value = numberformat.format( value, self.decimal_sep, decimal_pos=self.decimal_places, thousand_sep=self.thousands_sep, ) return super(DecimalInputMask, self).render(name, value, attrs=attrs)
def number_format(value, decimal_pos=None, use_l10n=None, force_grouping=False): """ Format a numeric value using localization settings. If use_l10n is provided and is not None, it forces the value to be localized (or not), overriding the value of settings.USE_L10N. """ use_l10n = use_l10n or (use_l10n is None and ( settings._USE_L10N_INTERNAL if hasattr(settings, '_USE_L10N_INTERNAL') else settings.USE_L10N )) lang = get_language() if use_l10n else None return numberformat.format( value, get_format('DECIMAL_SEPARATOR', lang, use_l10n=use_l10n), decimal_pos, get_format('NUMBER_GROUPING', lang, use_l10n=use_l10n), get_format('THOUSAND_SEPARATOR', lang, use_l10n=use_l10n), force_grouping=force_grouping, use_l10n=use_l10n, )
def format_price(price, currency, decimal_pos=None): if not currency: return price if decimal_pos is None: decimal_pos = currency.decimal_places d = Decimal(str(price)) if decimal_pos == 0: exp = Decimal(1) else: exp = Decimal('1.0') / (Decimal(10) ** abs(decimal_pos)) formatted_price = numberformat.format( u'%s' % str(d.quantize(exp, ROUND_HALF_UP)), currency.decimal_separator, abs(decimal_pos), grouping=3, thousand_sep=currency.thousand_separator) if currency.symbol_preceeds: params = (currency.symbol, formatted_price) else: params = (formatted_price, currency.symbol) return u'%s %s' % params
def test_locale_independent(self): """ Localization of numbers """ settings.USE_L10N = True settings.USE_THOUSAND_SEPARATOR = False self.assertEqual(u'66666.66', format(self.n, decimal_sep='.', decimal_pos=2, grouping=3, thousand_sep=',')) self.assertEqual(u'66666A6', format(self.n, decimal_sep='A', decimal_pos=1, grouping=1, thousand_sep='B')) settings.USE_THOUSAND_SEPARATOR = True self.assertEqual(u'66,666.66', format(self.n, decimal_sep='.', decimal_pos=2, grouping=3, thousand_sep=',')) self.assertEqual(u'6B6B6B6B6A6', format(self.n, decimal_sep='A', decimal_pos=1, grouping=1, thousand_sep='B')) self.assertEqual(u'-66666.6', format(-66666.666, decimal_sep='.', decimal_pos=1)) self.assertEqual(u'-66666.0', format(int('-66666'), decimal_sep='.', decimal_pos=1)) # date filter self.assertEqual(u'31.12.2009 в 20:50', Template('{{ dt|date:"d.m.Y в H:i" }}').render(self.ctxt)) self.assertEqual(u'⌚ 10:15', Template('{{ t|time:"⌚ H:i" }}').render(self.ctxt))
def test_locale_independent(self): """ Localization of numbers """ settings.USE_L10N = True settings.USE_THOUSAND_SEPARATOR = False self.assertEqual(u"66666.66", format(self.n, decimal_sep=".", decimal_pos=2, grouping=3, thousand_sep=",")) self.assertEqual(u"66666A6", format(self.n, decimal_sep="A", decimal_pos=1, grouping=1, thousand_sep="B")) settings.USE_THOUSAND_SEPARATOR = True self.assertEqual(u"66,666.66", format(self.n, decimal_sep=".", decimal_pos=2, grouping=3, thousand_sep=",")) self.assertEqual(u"6B6B6B6B6A6", format(self.n, decimal_sep="A", decimal_pos=1, grouping=1, thousand_sep="B")) self.assertEqual(u"-66666.6", format(-66666.666, decimal_sep=".", decimal_pos=1)) self.assertEqual(u"-66666.0", format(int("-66666"), decimal_sep=".", decimal_pos=1)) # date filter self.assertEqual(u"31.12.2009 в 20:50", Template('{{ dt|date:"d.m.Y в H:i" }}').render(self.ctxt)) self.assertEqual(u"⌚ 10:15", Template('{{ t|time:"⌚ H:i" }}').render(self.ctxt))
def do_float_dot(value, decimal_pos=4): return format(value or 0, ".", decimal_pos)
def floatdot(value, decimal_pos=2): if not value: return 0 return numberformat.format(value, ".", decimal_pos)
def dotted_number(number): number = float(number) return format(number, '.', 6)
def floatdot(value, separator=".", decimal_pos=4): return format(value, separator, decimal_pos)
def floatdot(value, decimal_pos=2): if not value: return format(0, ",", decimal_pos) else: return format(value, ",", decimal_pos)
def dotted_number(number): if type(number) == float: number = format(number, '.', 6) return number
def decimalformat(value): value = str(value).rstrip('0') or '0' return format(value, '.', 2)
def float_format_br(number, decimal_pos=2): if number is None: return "" return format(number, decimal_sep=",", decimal_pos=decimal_pos, grouping=3, thousand_sep=".", force_grouping=3)
def floatdot(value, decimal_pos=2): return format(value, ".", decimal_pos)
def floatdot(value, decimal_pos=4): ''' Similar a floatformat, pero utiliza punto en vez de la coma ''' value = str(value).replace(',', '.') return format(value, ".", decimal_pos)
def integer_format_br(number): if number is None: return "" number = int(number) return format(number, decimal_sep="", decimal_pos=0, grouping=3, thousand_sep=".", force_grouping=3)
def monetary_format_br(number): if number is None: return "" number = float(number) return format(number, decimal_sep=",", decimal_pos=2, grouping=3, thousand_sep=".", force_grouping=3)
def ratingformat(value): return format(value, '.', 1)
def financialControl(request, start_date=None, end_date=None): """Financial control extraction. This view is intented to be processed by a spreadsheet or a financial package software""" if end_date is None: end_date = previousMonth(datetime.date.today()) else: end_date = datetime.date(int(end_date[0:4]), int(end_date[4:6]), 1) if start_date is None: start_date = previousMonth(previousMonth(datetime.date.today())) else: start_date = datetime.date(int(start_date[0:4]), int(start_date[4:6]), 1) response = HttpResponse(content_type="text/plain") response["Content-Disposition"] = "attachment; filename=financialControl.dat" writer = csv.writer(response, delimiter=';') financialConditions = {} for fc in FinancialCondition.objects.all(): financialConditions["%s-%s" % (fc.mission_id, fc.consultant_id)] = (fc.daily_rate, fc.bought_daily_rate) # Header header = ["FiscalYear", "Month", "Type", "Nature", "AccountingColumn", "MissionSubsidiary", "ClientCompany", "ClientCompanyCode", "ClientOrganization", "Lead", "DealId", "LeadPrice", "LeadResponsible", "LeadResponsibleTrigramme", "Mission", "MissionId", "BillingMode", "MissionPrice", "ConsultantSubsidiary", "ConsultantTeam", "Trigramme", "Consultant", "Subcontractor", "CrossBilling", "ObjectiveRate", "DailyRate", "BoughtDailyRate", "BudgetType", "QuantityInDays", "QuantityInEuros"] writer.writerow([unicode(i).encode("ISO-8859-15", "ignore") for i in header]) timesheets = Timesheet.objects.filter(working_date__gte=start_date, working_date__lt=nextMonth(end_date)) staffings = Staffing.objects.filter(staffing_date__gte=start_date, staffing_date__lt=nextMonth(end_date)) consultants = dict([(i.trigramme.lower(), i) for i in Consultant.objects.all().select_related()]) missionsIdsFromStaffing = Mission.objects.filter(probability__gt=0, staffing__staffing_date__gte=start_date, staffing__staffing_date__lt=nextMonth(end_date)).values_list("id", flat=True) missionsIdsFromTimesheet = Mission.objects.filter(probability__gt=0, timesheet__working_date__gte=start_date, timesheet__working_date__lt=nextMonth(end_date)).values_list("id", flat=True) missionsIds = set(list(missionsIdsFromStaffing) + list(missionsIdsFromTimesheet)) missions = Mission.objects.filter(id__in=missionsIds) missions = missions.distinct().select_related().prefetch_related("lead__client__organisation__company", "lead__responsible") for mission in missions: missionRow = [] missionRow.append(start_date.year) missionRow.append(end_date.isoformat()) missionRow.append("timesheet") missionRow.append(mission.nature) missionRow.append("mission accounting (tbd)") missionRow.append(mission.subsidiary) if mission.lead: missionRow.append(mission.lead.client.organisation.company.name) missionRow.append(mission.lead.client.organisation.company.code) missionRow.append(mission.lead.client.organisation.name) missionRow.append(mission.lead.name) missionRow.append(mission.lead.deal_id) missionRow.append(numberformat.format(mission.lead.sales, ",") if mission.lead.sales else 0) if mission.lead.responsible: missionRow.append(mission.lead.responsible.name) missionRow.append(mission.lead.responsible.trigramme) else: missionRow.extend(["", ""]) else: missionRow.extend(["", "", "", "", "", 0, "", ""]) missionRow.append(mission.description or "") missionRow.append(mission.mission_id()) missionRow.append(mission.billing_mode or "") missionRow.append(numberformat.format(mission.price, ",") if mission.price else 0) for consultant in mission.consultants().select_related().prefetch_related("manager"): consultantRow = missionRow[:] # copy daily_rate, bought_daily_rate = financialConditions.get("%s-%s" % (mission.id, consultant.id), [0, 0]) rateObjective = consultant.getRateObjective(end_date) if rateObjective: rateObjective = rateObjective.daily_rate else: rateObjective = 0 doneDays = timesheets.filter(mission_id=mission.id, consultant=consultant.id).aggregate(Sum("charge")).values()[0] or 0 forecastedDays = staffings.filter(mission_id=mission.id, consultant=consultant.id).aggregate(Sum("charge")).values()[0] or 0 consultantRow.append(consultant.company) consultantRow.append(consultant.manager.trigramme if consultant.manager else "") consultantRow.append(consultant.trigramme) consultantRow.append(consultant.name) consultantRow.append(consultant.subcontractor) consultantRow.append(mission.subsidiary != consultant.company) consultantRow.append(numberformat.format(rateObjective, ",")) consultantRow.append(numberformat.format(daily_rate, ",") if daily_rate else 0) consultantRow.append(numberformat.format(bought_daily_rate, ",") if bought_daily_rate else 0) # Timesheet row for budgetType, quantity in (("done", doneDays), ("forecast", forecastedDays)): row = consultantRow[:] # Copy row.append(budgetType) row.append(numberformat.format(quantity, ",") if quantity else 0) row.append(numberformat.format(quantity * daily_rate, ",") if (quantity > 0 and daily_rate > 0) else 0) writer.writerow([unicode(i).encode("ISO-8859-15", "ignore") for i in row]) # for expense in Expense.objects.filter(expense_date__gte=start_date, expense_date__lt=nextMonth(end_date), chargeable=False).select_related(): row = [] row.append(start_date.year) row.append(end_date.isoformat()) row.append("expense") row.append(expense.category) row.append("expense accounting (tbd)") if expense.lead: row.append(expense.lead.subsidiary) row.extend(["", "", "", ""]) row.append(expense.lead.deal_id) else: row.extend(["", "", "", "", "", ""]) row.extend(["", "", "", "", ""]) try: consultant = consultants[expense.user.username.lower()] row.append(consultant.company.name) row.append(consultant.manager.trigramme) row.append(consultant.trigramme) row.append(consultant.name) row.append(consultant.subcontractor) if expense.lead: row.append(expense.lead.subsidiary != consultant.company) else: row.append("unknown for now") except KeyError: # Exepense user is not a consultant row.extend(["", "", "", "", "", ""]) row.extend(["", "", "", "", ""]) row.append(expense.amount) # TODO: compute pseudo HT amount writer.writerow([unicode(i).encode("ISO-8859-15", "ignore") for i in row]) return response
import datetime
def money_format(amount): from django.utils.numberformat import format amount = "%.2f" % amount return format(amount, ",", 2, 3, ".")