def print_listing_min_max_prices_json(): qs = ListingPage.objects.live() rent_prices = qs.filter( rent_price__gt=0 ).aggregate(min=Min('rent_price'), max=Max('rent_price')) sell_prices = qs.filter( sell_price__gt=0 ).aggregate(min=Min('sell_price'), max=Max('sell_price'), avg=Avg('sell_price')) rent_min = max(rent_prices['min'] or 0, 500) rent_max = max(rent_prices['max'] or 0, rent_min) rent_choices = [] if rent_max > 0: rent_diff = rent_min rent_choices.append(rent_min) while rent_min < rent_max: rent_min += rent_diff rent_choices.append(min(rent_min, rent_max)) sell_min = sell_prices['min'] or 0 sell_max = sell_prices['max'] or 0 sell_avg = sell_prices['avg'] or 0 sell_choices_aux = [ Decimal('5000.00'), Decimal('10000.00'), Decimal('50000.00'), Decimal('100000.00'), Decimal('200000.00'), Decimal('300000.00'), Decimal('400000.00'), Decimal('500000.00'), Decimal('1000000.00'), Decimal('3000000.00'), Decimal('5000000.00'), Decimal('10000000.00'), Decimal('100000000.00'), ] last_choice = None sell_choices = [] for i, choice in enumerate(sell_choices_aux): if choice > sell_min and last_choice and not sell_choices: sell_choices.append(last_choice) elif sell_max > choice > sell_avg: sell_choices.append(choice) elif choice > sell_max: sell_choices.append(choice) break last_choice = choice dct = { 'rent': [(float(v), 'R$ ' + localize(v)) for v in rent_choices], 'sell': [(float(v), 'R$ ' + localize(v)) for v in sell_choices], } return json.dumps(dct)
def valeur(self): retour = {} tarif = TarifFioul.objects.get(zone=self.zone, type_fioul=self.type_fioul) decote = TarifDecote.objects.get(zone=self.zone, min__lte=self.qte, max__gte=self.qte) livraison = TarifLivraison.objects.get( zone=self.zone, type_livraison=self.type_livraison) config = Config.objects.filter(actif=True)[0] retour["total_ttc"] = ( (tarif.prix_ttc + decote.decote + livraison.extra) * Decimal(self.qte) / Decimal(1000)) retour["prix_litre"] = retour["total_ttc"] / Decimal(self.qte) # retour['total_ttc'] += livraison.extra retour["total_ht"] = retour["total_ttc"] / (Decimal("1") + config.taux_tva) retour["livraison_ttc"] = livraison.extra retour["livraison_nom"] = livraison.type_livraison.nom retour["livraison_date"] = template_date(livraison.date_livraison(), "l j F") retour["livraisons"] = {} liv_prix_base = livraison.extra * Decimal(self.qte) / Decimal(1000) for liv in TarifLivraison.objects.filter(zone=self.zone, actif=True): liv_label = "" if self.type_livraison != liv.type_livraison: liv_prix = (liv.extra * Decimal(self.qte) / Decimal(1000)) - liv_prix_base if liv_prix > 0: liv_label = "+ " + localize(floatformat(liv_prix, "-2")) + " euros" elif liv_prix < 0: liv_label = ("- " + localize(floatformat(-1 * liv_prix, "-2")) + " euros") retour["livraisons"][liv.id] = liv_label retour["fioul_nom"] = tarif.type_fioul.nom retour["qte"] = int(self.qte) retour["acompte"] = config.commission * self.qte / 1000 retour["acompte_ht"] = retour["acompte"] / (1 + config.taux_tva) retour["reste"] = retour["total_ttc"] - retour["acompte"] retour["acompte"] = round(retour["acompte"], 2) retour["acompte_ht"] = round(retour["acompte_ht"], 2) retour["reste"] = round(retour["reste"], 2) retour["total_ttc"] = round(retour["total_ttc"], 2) retour["total_ht"] = round(retour["total_ht"], 2) retour["prix_litre"] = round(retour["prix_litre"], 4) retour["livraison_ttc"] = round(retour["livraison_ttc"], 2) return retour
def localized_display_ending_time(self): days = self.days if self.ending_time > time.min else 0 days_fmt = ungettext_lazy(u'the next day', u'after {number_of_days} days', days) days_str = days_fmt.format(number_of_days=days) if days else u'' return u'{time} {days}'.format(time=localize(self.ending_time), days=days_str).strip()
def get_version(): """ Return formatted version string. Returns: string: string with project version or empty string. """ if all([ VERSION, UPDATED, any([ isinstance(UPDATED, date), isinstance(UPDATED, datetime), ]), ]): return FORMAT_STRING.format(**{ "version": VERSION, "updated": UPDATED, }) elif VERSION: return VERSION elif UPDATED: return localize(UPDATED) if any([ isinstance(UPDATED, date), isinstance(UPDATED, datetime), ]) else "" else: return ""
def _sanitize_value(value): if isinstance(value, unicode): return value.encode("utf-8") elif isinstance(value, datetime.datetime): return value.isoformat().encode("utf-8") else: return localize(value)
def get_refund_export_csv(refund_export: RefundExport): byte_data = io.BytesIO() StreamWriter = codecs.getwriter('utf-8') output = StreamWriter(byte_data) writer = csv.writer(output) writer.writerow( [_("Payer"), "IBAN", "BIC", _("Amount"), _("Currency"), _("Code")]) for row in refund_export.rows_data: bic = '' if row.get('bic'): try: BICValidator()(row['bic']) except ValidationError: pass else: bic = row['bic'] writer.writerow([ row['payer'], row['iban'], bic, localize(Decimal(row['amount'])), refund_export.currency, row['id'], ]) filename = _get_filename(refund_export) + ".csv" byte_data.seek(0) return filename, 'text/csv', byte_data
def format_response(spec_offer): item = dict() item['hotel'] = spec_offer.hotel.name if spec_offer.hotel.stars: item['stars'] = range(spec_offer.hotel.stars) item['stars_flag'] = True item['resort'] = spec_offer.hotel.resort.name item['country'] = spec_offer.hotel.resort.country.name item['image'] = set_version_img_url( spec_offer.hotel.image, context, 'spec_offer_min') item['is_limited_seats'] = spec_offer.is_limited_seats item['type'] = spec_offer.type.name if spec_offer.price_offer: item['price_offer_flag'] = True item['price_offer'] = spec_offer.get_price_offer_display() item['price_offer_icon'] = PriceOfferEnum.icons.get(spec_offer.price_offer) item['check_in_date'] = localize(spec_offer.check_in_date) item['cost'] = intcomma(format_price(spec_offer.cost)) item['amount_days'] = spec_offer.amount_days if spec_offer.supply: item['supply'] = spec_offer.get_supply_display() item['supply_flag'] = True item['order_spec_url'] = reverse('get_spec_offer', kwargs={'pk': spec_offer.id}) if spec_offer.departure_place: item['departure_place_flag'] = True item['place'] = spec_offer.get_departure_place_display() return item
def localized_display_ending_time(self): days = self.days if self.ending_time > time.min else 0 days_fmt = ungettext_lazy(u'the next day', u'after {number_of_days} days', days) days_str = days_fmt.format( number_of_days=days) if days else u'' return u'{time} {days}'.format(time=localize(self.ending_time), days=days_str).strip()
def get(self, request, *args, **kwargs): message = 'Reverted to previous version, saved on {datetime}'.format( datetime=localize(self.version.revision.date_created)) with transaction.atomic(), revisions.create_revision(): self.version.revision.revert() revisions.set_comment(message) self.messages.success( message) return super().get(request, *args, **kwargs)
def _sanitize_value(value): if isinstance(value, unicode): return value.encode("utf-8") elif isinstance(value, datetime.datetime): return value.isoformat().encode("utf-8") elif isinstance(value, datetime.date): return str(value.strftime('%d.%m.%Y')) elif isinstance(value, Decimal): return str(value) else: return localize(value)
def appointment_time(self, obj=None): try: start = localize(timezone.localtime(obj.appointment.start)) except AttributeError: start = "" try: end_time = time_format(timezone.localtime(obj.appointment.end), "H:i") except AttributeError: end_time = "" return f"{start} - {end_time}"
def test_detail(admin_client, live_server, admin_browser): author = AuthorFactory.create() url = reverse('testapp_author_detail', args=[ author.pk, ]) r = admin_client.get(url) assert r.status_code == 200 content = r.content.decode() birthdate_txt = localize(author.birthday) assert author.name in content assert birthdate_txt in content admin_browser.get(live_server.url + url)
def format_result(self, request, item): result = dict() result['pk'] = item.pk result['name'] = item.name result['creation_date'] = localize(item.creation_date) result['resting_place'] = item.resting_place if item.rating: result['rating'] = range(item.rating) if item.photo: result['photo'] = item.photo.url result['evaluation'] = striptags(truncatechars_html( item.general_evaluation, 100)) return result
def data(self): if self.livraison_ttc < 0: prix_livraison = "- %s" % localize( floatformat(-1 * self.livraison_ttc, "-2")) else: prix_livraison = "+ %s" % localize( floatformat(self.livraison_ttc, "-2")) d = { "client_nom": self.adresse_livraison.nom, "client_prenom": self.adresse_livraison.prenom, "commande_id": self.id, "distributeur_email": self.zone.email, "distributeur_tel": self.zone.telephone, "distributeur_raison_sociale": self.zone.raison_sociale, "distributeur_siret": self.zone.siret, "distributeur_adresse": self.zone.adresse, "distributeur_code_postal": self.zone.code_postal, "livraison_adresse": self.adresse_livraison.detail_1, "livraison_code_postal": self.adresse_livraison.code_postal, "livraison_ville": self.adresse_livraison.detail_4, "livraison_message": self.commentaire, "client_telephone": self.client.telephone, "qte": self.qte, "prix_litre": localize(floatformat(self.total_ttc / Decimal(self.qte), "-4")), "type_fioul": self.type_fioul.nom, "type_livraison": self.type_livraison.nom, "prix_livraison": prix_livraison, "total_ttc": localize(floatformat(self.total_ttc, "-2")), "acompte": localize(floatformat(self.commission_ttc, "-2")), "reste": localize(floatformat(self.get_reste_ttc(), "-2")), "date_livraison": template_date(self.date_livraison, "j F Y"), # '' : self.id, } return d
def get_version(): """ Return formatted version string. Returns: str: string with project version or empty string. """ if all([VERSION, UPDATED, any([isinstance(UPDATED, date), isinstance(UPDATED, datetime), ]), ]): return FORMAT_STRING.format(**{"version": VERSION, "updated": UPDATED, }) elif VERSION: return VERSION elif UPDATED: return localize(UPDATED) if any([isinstance(UPDATED, date), isinstance(UPDATED, datetime), ]) else "" else: return ""
def get_context_data(self, **kwargs): context = super(HelpDesk, self).get_context_data(**kwargs) open_shifts = get_open_shifts() shifts_by_facility = itertools.groupby(open_shifts, lambda s: s.facility) facility_list = [] used_places = set() for facility, shifts_at_facility in shifts_by_facility: address_line = facility.address_line if facility.address else None shifts_by_date = itertools.groupby(shifts_at_facility, lambda s: s.starting_time.date()) used_places.add(facility.place.area) facility_list.append({ 'name': facility.name, 'news': getNewsFacility(facility), 'address_line': address_line, 'google_maps_link': google_maps_directions( address_line) if address_line else None, 'description': mark_safe(facility.description), 'area_slug': facility.place.area.slug, 'shifts': [{ 'date_string': localize(shift_date), 'link': reverse('planner_by_facility', kwargs={ 'pk': facility.pk, 'year': shift_date.year, 'month': shift_date.month, 'day': shift_date.day, }) } for shift_date, shifts_of_day in shifts_by_date] }) context['areas_json'] = json.dumps( [{'slug': area.slug, 'name': area.name} for area in sorted(used_places, key=lambda p: p.name)]) context['facility_json'] = json.dumps(facility_list, cls=DjangoJSONEncoder) context['shifts'] = open_shifts return context
def rent_price_display(self): if not self.rent_price: return 'Sob consulta' return 'R$ {}'.format(localize(self.rent_price))
def onPage(canvas, doc, da=None, a=None): width, height = canvas._doctemplate.pagesize canvas.saveState() fattura = doc.fatture[doc.fattura_corrente] if da is None: da = fattura.emessa_da if a is None: a = fattura.emessa_a fatturazione = FATTURE_PER_TIPO[fattura.tipo] stondata_style = ParagraphStyle("IntestazioneStondata", fontName='Helvetica', fontSize=8, leading=10, borderRadius=5, borderWidth=1, borderColor=colors.silver, borderPadding=5) a_style = ParagraphStyle("Titolo della fattura", fontName='Helvetica', fontSize=8, leading=10) tipo = fattura.tipo # set PDF properties *************** canvas.setFont('Helvetica', 8) canvas.setAuthor(settings.LICENSE_OWNER) canvas.setCreator('TaM v.%s' % settings.TAM_VERSION) canvas._doc.info.producer = ('TaM invoices') canvas.setSubject(u"%s" % fattura.nome_fattura()) nome = fattura.custom_name descrittoreFattura = u"%s %s" % (nome, fattura.descrittore()) canvas.setTitle(descrittoreFattura) # Header *************** y = height - doc.topMargin x = doc.leftMargin if test: canvas.setLineWidth(1) p = canvas.beginPath() p.moveTo(0, y) p.lineTo(width, y) canvas.drawPath(p) if fatturazione.mittente == "consorzio": logo_height = 2.5 * cm y -= logo_height canvas.drawImage(logoImage_path, x=x, y=y, width=7 * cm, height=logo_height) descrittore = Paragraph( '<font size="14"><b>%s</b></font> del %s' % (descrittoreFattura, localize(fattura.data)), a_style) descrittore.wrapOn(canvas, width / 2, y) descrittore.drawOn(canvas, x=x, y=y - descrittore.height) y -= descrittore.height + 10 if fatturazione.mittente == "conducente": # nelle fatture conducente metto il mittente a sinistra fattura_da = Paragraph(da.strip().replace('\n', '<br/>'), a_style) fattura_da.wrapOn(canvas, 6.5 * cm, 10 * cm) fattura_da.drawOn(canvas, x, y - fattura_da.height) y -= fattura_da.height y -= 0.2 * cm # spacer tra mittente e destinatario if fattura.note: note = Preformatted(fattura.note, a_style) note.wrapOn(canvas, width / 2, 10 * cm) y = y - note.height - 8 note.drawOn(canvas, 1 * cm, y=y) note_fisse = fattura.note_fisse() if note_fisse: # le vecchie ricevute hanno l'indicazione di servizio emodializzato y = y - 10 testata_fissa = Paragraph("<font size='6'>%s</font>" % note_fisse, a_style) testata_fissa.wrapOn(canvas, width / 2, 2 * cm) y = y - testata_fissa.height testata_fissa.drawOn(canvas, x, y) left_y = y - 8 # spacer finale if test: p = canvas.beginPath() p.moveTo(0, y) p.lineTo(width / 2, y) canvas.drawPath(p) # faccio la seconda colonna (destra) dell'header y = height - doc.topMargin x = width - 8 * cm if not fatturazione.mittente == "conducente": # nelle fatture conducente ho messo già il conducente a sinistra fattura_da = Paragraph(da.strip().replace('\n', '<br/>'), a_style) fattura_da.wrapOn(canvas, 6.5 * cm, 10 * cm) fattura_da.drawOn(canvas, x, y - fattura_da.height) y -= fattura_da.height y -= 0.1 * cm # spacer tra mittente e destinatario fattura_a = Paragraph(a.replace('\n', '<br/>'), stondata_style) fattura_a.wrapOn(canvas, 6.5 * cm, 10 * cm) fattura_a.drawOn(canvas, x, y - fattura_a.height - fattura_a.style.borderPadding) y -= fattura_a.height + fattura_a.style.borderPadding * 2 # spazio finale right_y = y lower_y = min(left_y, right_y) y = lower_y if test: p = canvas.beginPath() p.moveTo(width / 2, y) p.lineTo(width, y) canvas.drawPath(p) note_finali_lines = [] for footer_row in fattura.footer(): note_finali_lines.append(footer_row) note_finali = Paragraph("<br/>".join(note_finali_lines), normalStyle) note_finali.wrap(width - doc.rightMargin - doc.leftMargin, 5 * cm) note_finali.drawOn(canvas, doc.leftMargin, doc.bottomMargin) # linea sotto l'intestazione canvas.setLineWidth(1) p = canvas.beginPath() p.moveTo(doc.leftMargin, y) p.lineTo(width - doc.rightMargin, y) canvas.drawPath(p) doc.pageTemplate.frames = [ Frame(doc.leftMargin, doc.bottomMargin + note_finali.height, width - (doc.leftMargin + doc.rightMargin), y - doc.bottomMargin - note_finali.height, showBoundary=test), # x,y, width, height ] canvas.setLineWidth(0.3) p = canvas.beginPath() p.moveTo(doc.leftMargin, doc.bottomMargin) p.lineTo(width - doc.rightMargin, doc.bottomMargin) canvas.drawPath(p) canvas.restoreState()
def gen_bill_ride_stuff(ob): buffer_ = BytesIO() try: tree = ET.fromstring(ob.xml_content.encode('utf8')) except ET.ParseError: tree = None pagesize = A4 margin = inch, inch, inch, inch canvas = Canvas(buffer_, pagesize=pagesize) c = RenderStack(0, 0, pagesize[0], pagesize[1], margin=margin) # p.roundRect(c.x(0), c.y(0), c.width(1), c.height(1), 3, stroke=1, fill=0) # Print warnings warnings = get_warning(ob) if warnings: canvas.saveState() grey = 0.3 canvas.setFillColorCMYK(0, 0, 0, grey) canvas.setStrokeColorCMYK(0, 0, 0, grey) canvas.setFont("Helvetica", 50) total_height = 60 * len(warnings) canvas.translate(c.x(0.5), c.y(0.7)) canvas.rotate(45) canvas.translate(0, total_height / 2) for item in warnings: canvas.drawCentredString(0, 0, item) canvas.translate(0, -60) canvas.restoreState() def add_items(items, showBoundary=False): f = Frame(c.x(0), c.y(0), c.width(1), c.height(1), showBoundary=showBoundary, leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=0) f.addFromList(items, canvas) if items: raise Exception("Does not fit - items left") # Parameters column_height = 0.3 column_width = 0.5 footer_height = 0.14 standard_separation = inch / 20 # styles styles = getSampleStyleSheet() small = styles['Normal'].clone("Smaller", fontSize=8) normal = styles['Normal'] bigheader = styles['h2'] mediumheader = styles['h3'] smallheader = styles['h4'] with c.section(0, 1 - column_height, 1, 1): # columna izquierda with c.section(0, 0, column_width, 1, margin=(0, 0, standard_separation, 0)): if ob.company.get_logo(): with c.section(0, 0.5, 1, 1, margin=standard_separation): # logo logo = ob.company.get_logo() if logo: add_items( [get_image(logo.file.file.name, width=c.width(1), height=c.height(1))] ) with c.section(0, 0, 1, column_width, margin=standard_separation): story = [] if ob.company.nombre_comercial: story.append(Paragraph(ob.company.nombre_comercial, bigheader)) story.append(Paragraph("Razon Social: {}".format(ob.company.razon_social), normal)) else: story.append(Paragraph("Razon Social: {}".format(ob.company.razon_social), bigheader)) if ob.company.direccion_matriz != ob.punto_emision.establecimiento.direccion: story.append(Paragraph(u"Dirección Matriz:", normal)) story.append(Paragraph(ob.company.direccion_matriz, small)) story.append(Paragraph(u"Dirección Sucursal:", normal)) story.append(Paragraph(ob.punto_emision.establecimiento.direccion, small)) else: story.append(Paragraph(u"Dirección:", normal)) story.append(Paragraph(ob.company.direccion_matriz, small)) if ob.company.contribuyente_especial: story.append(Paragraph("Contribuyente Especial: {}".format(ob.company.contribuyente_especial), normal)) story.append(Paragraph("{} Obligado a llevar Contabilidad".format( "SI" if ob.company.obligado_contabilidad else "NO"), normal)) add_items(story) # columna derecha with c.section(column_width, 0, 1, 1, margin=standard_separation): story.append(Paragraph("RUC {}".format(ob.company.ruc), normal)) subtipo = None if ob.status == SRIStatus.options.Accepted: tipo = "FACTURA" number = get_bill_number_from_tree(tree) elif ob.status == SRIStatus.options.Annulled: tipo = "FACTURA ANULADA" subtipo = "SIN VALIDEZ TRIBUTARIA" number = get_bill_number_from_tree(tree) elif ob.status == SRIStatus.options.Sent: tipo = "FACTURA ANULADA" subtipo = "PENDIENTE DE AUTORIZACIÓN" number = get_bill_number_from_tree(tree) else: tipo = "PROFORMA" subtipo = "SIN VALIDEZ TRIBUTARIA" number = ob.number story.append(Paragraph(tipo, smallheader)) if subtipo: story.append(Paragraph(subtipo, normal)) story.append(Paragraph(number, normal)) canvas.setTitle("{} {}".format(tipo, number)) if ob.clave_acceso: story.append(Paragraph("Clave de Acceso", mediumheader)) story.append(Paragraph(ob.clave_acceso, small)) story.append(Image(make_barcode(ob.clave_acceso), width=c.width(1), height=c.height(0.1))) if ob.numero_autorizacion: story.append(Paragraph(u"Autorización", mediumheader)) story.append(Paragraph(ob.numero_autorizacion, small)) story.append(Paragraph(l10n.localize(ob.fecha_autorizacion), small)) story.append(Paragraph("Ambiente: {}".format(ob.ambiente_sri.upper()), normal)) add_items(story) with c.section(0, 1 - column_height - 0.1, 1, 1 - column_height, margin=(standard_separation, 0, standard_separation, 0)): story = [] story.append(Paragraph("Cliente".format(ob.issued_to.razon_social), mediumheader)) story.append(Paragraph("Razon Social / Nombres y Apellidos: {}".format(ob.issued_to.razon_social), normal)) story.append(Paragraph("Identificacion: {} {}".format(ob.issued_to.tipo_identificacion, ob.issued_to.identificacion), normal)) story.append(Paragraph("Fecha de Emision: {}".format(l10n.localize(ob.date)), normal)) # FIXME: Guia de remision add_items(story) with c.section(0, footer_height, 1, 1 - column_height - 0.1, margin=(0, 0, 0, standard_separation)): headers = [(u'Cod.\nPrincipal', c.width(0.1)), (u'Cod.\nAuxiliar', c.width(0.1)), (u'Cant.', c.width(0.1)), (u'Descripción', c.width(0.4)), (u'Precio\nUnitario', c.width(0.1)), (u'Dcto.', c.width(0.1)), (u'Total', c.width(0.1))] data, widths = zip(*headers) data = [data] for item in ob.items: linea = [ item.code, '', str(decimals(item.qty, item.sku.batch.item.decimales_qty)), item.name, str(decimals(item.unit_price, 4)), str(decimals(item.discount, 2)), str(decimals(item.total_sin_impuestos, 2)) ] data.append(linea) detail_table = Table(data, style=[('GRID', (0, 0), (-1, -1), 0.5, colors.grey)], colWidths=widths) detail_table.hAlign = 'LEFT' add_items([detail_table]) with c.section(0, 0, 1, footer_height, margin=(0, 0, 0, standard_separation)): col_mid_point = 0.5 with c.section(0, 0, col_mid_point, 1, margin=(0, 0, standard_separation, 0)): data = [ ["DSSTI Facturas"], ] data.append(["Descarge su comprobante en:\n http://facturas.dssti.com"]) extrainfo_table = Table(data, style=[('GRID', (0, 0), (-1, -1), 0.5, colors.grey)], colWidths=[c.width(1)]) extrainfo_table.hAlign = 'LEFT' add_items([extrainfo_table]) with c.section(col_mid_point, 0, 1, 1, margin=(0, 0, 0, 0)): data = [ ["Subtotal IVA 12%", money_2d(ob.subtotal[12])], ["Subtotal IVA 0%", money_2d(ob.subtotal[0])], ["IVA 12%", money_2d(ob.iva[12])], ['ICE', money_2d(ob.total_ice)], ["Total a Pagar", money_2d(ob.total)], ] totals_table = Table(data, style=[('GRID', (0, 0), (-1, -1), 0.5, colors.grey), ('ALIGN', (1, 0), (1, -1), 'RIGHT'), ], colWidths=[c.width(0.5), c.width(0.5), ]) totals_table.hAlign = 'RIGHT' add_items([totals_table]) canvas.showPage() canvas.save() pdf = buffer_.getvalue() buffer_.close() return pdf
def apply_schedule_template(self, request, pk): """ Juicy function that lets one create a schedule template, and then apply the template on one date to create individual shifts. Has three phases: 1. GET: Allow selecting date and shifts 2. POST: Displays a preview of what will be done 3. POST: Actually apply the template. """ schedule_template = get_object_or_404(self.model, pk=pk) shift_templates = schedule_template.shift_templates.all() context = dict(self.admin_site.each_context(request)) context["opts"] = self.model._meta # Needed for admin template breadcrumbs # Phase 1 if request.method == 'GET': # Empty form, prepopulated with tomorrow's date form = ApplyTemplateForm( initial={'apply_for_date': timezone.now().date() + timedelta( days=1)}) context.update({ "schedule_template": schedule_template, "shift_templates": shift_templates, "apply_form": form, }) return TemplateResponse( request, "admin/scheduletemplates/apply_template.html", context) # Phase 2 and 3 elif request.method == 'POST': # Verify the form data. form = ApplyTemplateForm(request.POST) if not form.is_valid(): # Shouldn't happen, but let's make sure we don't proceed with # applying shifts. raise ValueError("Invalid date format {}".format(form.errors)) apply_date = form.cleaned_data['apply_for_date'] # Get selected shifts. # TODO: This should be done with a ModelMultipleChoiceField on the form. id_list = request.POST.getlist('selected_shift_templates', []) selected_shift_templates = shift_templates.filter(id__in=id_list) # Phase 2: display a preview of whole day if request.POST.get('preview'): existing_shifts = scheduler_models.Shift.objects.filter( facility=schedule_template.facility) existing_shifts = existing_shifts.on_shiftdate(apply_date) existing_shifts = existing_shifts.select_related('task', 'workplace') existing_shifts = list(existing_shifts.annotate( volunteer_count=Count('helpers'))) if len(existing_shifts): messages.warning(request, ungettext_lazy( u'A shift already exists at {date}', u'{num_shifts} shifts already exists at {date}', len(id_list)).format( num_shifts=len(existing_shifts), date=localize(apply_date))) combined_shifts = list( selected_shift_templates) + existing_shifts # returns (task, workplace, start_time and is_template) # to make combined list sortable def __shift_key(shift): is_template = isinstance(shift, models.ShiftTemplate) task = shift.task.id if shift.task else 0 workplace = shift.workplace.id if shift.workplace else 0 shift_start = shift.starting_time if not isinstance(shift_start, time): # can't compare starting_time of shift (datetime) # and shift templates (time) directly shift_start = shift_start.time() return task, workplace, shift_start, is_template combined_shifts = sorted(combined_shifts, key=__shift_key) else: combined_shifts = selected_shift_templates context.update({ "schedule_template": schedule_template, "selected_date": apply_date, "selected_shifts": selected_shift_templates, "existing_shifts": existing_shifts, "combined_shifts": combined_shifts, "apply_form": form, # Needed because we need to POST the data again }) return TemplateResponse( request, "admin/scheduletemplates/apply_template_confirm.html", context) # Phase 3: Create shifts elif request.POST.get('confirm'): for template in selected_shift_templates: starting_time = datetime.combine(apply_date, template.starting_time) scheduler_models.Shift.objects.create( facility=template.schedule_template.facility, starting_time=starting_time, ending_time=starting_time + template.duration, task=template.task, workplace=template.workplace, slots=template.slots) messages.success(request, ungettext_lazy( u'{num_shifts} shift was added to {date}', u'{num_shifts} shifts were added to {date}', len(id_list)).format( num_shifts=len(id_list), date=localize(apply_date))) return redirect( 'admin:scheduletemplates_scheduletemplate_change', pk) else: messages.error(request, _( u'Something didn\'t work. Sorry about that.').format( len(id_list), localize(apply_date))) return redirect( 'admin:scheduletemplates_scheduletemplate_change', pk)
def _sanitize_value(value): if isinstance(val, unicode): return value.encode("utf-8") else: return localize(value)
def apply_schedule_template(self, request, pk): """ Juicy function that lets one create a schedule template, and then apply the template on one date to create individual shifts. Has three phases: 1. GET: Allow selecting date and shifts 2. POST: Displays a preview of what will be done 3. POST: Actually apply the template. """ schedule_template = get_object_or_404(self.model, pk=pk) shift_templates = schedule_template.shift_templates.all() context = dict(self.admin_site.each_context(request)) context["opts"] = self.model._meta # Needed for admin template breadcrumbs # Phase 1 if request.method == 'GET': # Empty form, prepopulated with tomorrow's date form = ApplyTemplateForm( initial={ 'apply_for_date': timezone.now().date() + timedelta(days=1) }) context.update({ "schedule_template": schedule_template, "shift_templates": shift_templates, "apply_form": form, }) return TemplateResponse( request, "admin/scheduletemplates/apply_template.html", context) # Phase 2 and 3 elif request.method == 'POST': # Verify the form data. form = ApplyTemplateForm(request.POST) if not form.is_valid(): # Shouldn't happen, but let's make sure we don't proceed with # applying shifts. raise ValueError("Invalid date format {}".format(form.errors)) apply_date = form.cleaned_data['apply_for_date'] # Get selected shifts. # TODO: This should be done with a ModelMultipleChoiceField on the form. id_list = request.POST.getlist('selected_shift_templates', []) selected_shift_templates = shift_templates.filter(id__in=id_list) # Phase 2: display a preview of whole day if request.POST.get('preview'): existing_shifts = scheduler_models.Shift.objects.filter( facility=schedule_template.facility) existing_shifts = existing_shifts.on_shiftdate(apply_date) existing_shifts = existing_shifts.select_related( 'task', 'workplace') existing_shifts = list( existing_shifts.annotate(volunteer_count=Count('helpers'))) if len(existing_shifts): messages.warning( request, ungettext_lazy( u'A shift already exists at {date}', u'{num_shifts} shifts already exists at {date}', len(id_list)).format( num_shifts=len(existing_shifts), date=localize(apply_date))) combined_shifts = list( selected_shift_templates) + existing_shifts # returns (task, workplace, start_time and is_template) # to make combined list sortable def __shift_key(shift): is_template = isinstance(shift, models.ShiftTemplate) task = shift.task.id if shift.task else 0 workplace = shift.workplace.id if shift.workplace else 0 shift_start = shift.starting_time if not isinstance(shift_start, time): # can't compare starting_time of shift (datetime) # and shift templates (time) directly shift_start = shift_start.time() return task, workplace, shift_start, is_template combined_shifts = sorted(combined_shifts, key=__shift_key) else: combined_shifts = selected_shift_templates context.update({ "schedule_template": schedule_template, "selected_date": apply_date, "selected_shifts": selected_shift_templates, "existing_shifts": existing_shifts, "combined_shifts": combined_shifts, "apply_form": form, # Needed because we need to POST the data again }) return TemplateResponse( request, "admin/scheduletemplates/apply_template_confirm.html", context) # Phase 3: Create shifts elif request.POST.get('confirm') or request.POST.get( 'confirm_and_repeat'): for template in selected_shift_templates: starting_time = datetime.combine(apply_date, template.starting_time) scheduler_models.Shift.objects.create( facility=template.schedule_template.facility, starting_time=starting_time, ending_time=starting_time + template.duration, task=template.task, workplace=template.workplace, slots=template.slots, members_only=template.members_only) messages.success( request, ungettext_lazy( u'{num_shifts} shift was added to {date}', u'{num_shifts} shifts were added to {date}', len(id_list)).format(num_shifts=len(id_list), date=localize(apply_date))) if request.POST.get('confirm'): return redirect( 'admin:scheduletemplates_scheduletemplate_change', pk) else: return redirect('admin:apply_schedule_template', pk) else: messages.error( request, _(u'Something didn\'t work. Sorry about that.').format( len(id_list), localize(apply_date))) if request.POST.get('confirm'): return redirect( 'admin:scheduletemplates_scheduletemplate_change', pk) else: return redirect('admin:apply_schedule_template', pk)
def to_representation(self, value): return l10n.localize(value)
def send_payment_event_payment_email(payment, event): """ Sends an email to a user for an event such ass success/errors in payments, or updates to subscriptions. Mail type depends on the given event. @param payment: Always supply a payment for this function, the subscription will be taken from its `subscription` relation. If all you have is a subscription, supply the `subscription.last_payment`. @param event: one of the values of `PAYMENT_EVENTS`. @return: True if the mail was successfully relayed, False or raises otherwise. """ cur_language = translation.get_language() try: if not payment.user: logger.warning( 'Sending payment status message was ignored because no user was attached to the payment', extra={'payment': payment.id}) return if not event in PAYMENT_EVENTS: logger.error( 'Could not send out a payment event email because the event type was unknown.', extra={'payment': payment.id}) return user = payment.user email = user.email template = 'wechange_payments/mail/mail_base.html' subject_template = 'wechange_payments/mail/subject_base.txt' portal = CosinnusPortal.get_current() # switch language to user's preference language translation.activate( getattr(user.cosinnus_profile, 'language', settings.LANGUAGES[0][0])) link_html = '[' + str(pgettext_lazy( '(URL-LABEL)', 'Link')) + '](' + portal.get_domain() + '%s)' mail_html = '[%s](mailto:%s)' # prepare all possible variables sepa_mandate = None iban = None if payment.type == PAYMENT_TYPE_DIRECT_DEBIT: reference_payment = payment.subscription.reference_payment sepa_mandate = reference_payment.extra_data.get( 'sepa_mandate_token', None) iban = reference_payment.extra_data.get('iban', None) variables = { 'payment': payment, 'link_payment_info': link_html % reverse('wechange_payments:payment-infos'), 'link_invoices': link_html % reverse('wechange_payments:invoices'), 'link_new_payment': link_html % reverse('wechange_payments:payment'), 'link_payment_issues': link_html % reverse('wechange_payments:suspended-subscription'), 'portal_name': portal.name, 'username': full_name(payment.user), 'payment_amount': str(int(payment.amount)), 'vat_amount': str(int(settings.PAYMENTS_INVOICE_PROVIDER_TAX_RATE_PERCENT)), 'subscription_amount': str(int(payment.subscription.amount)), 'next_debit_date': localize(payment.subscription.get_next_payment_date()), 'payment_method': payment.get_type_string(), 'support_email': mail_html % (portal.support_email, portal.support_email), 'sepa_mandate': sepa_mandate, 'iban': iban, 'sepa_creditor': settings.PAYMENTS_SEPA_CREDITOR_ID, } # compose email parts data = { 'mail_pre': MAIL_PRE % variables, 'mail_links': MAIL_LINKS % variables, 'mail_post': MAIL_POST % variables, 'mail_body': MAIL_BODY.get(event) % variables, 'mail_subject': MAIL_SUBJECT.get(event) % variables, } # add SEPA mandate info to mail body for successful SEPA payment email if payment.type == PAYMENT_TYPE_DIRECT_DEBIT and event == PAYMENT_EVENT_SUCCESSFUL_PAYMENT: sepa_variables = { 'payment': payment.subscription.reference_payment, 'SETTINGS': settings, } data['mail_body'] += '\n\n-\n\n' + render_to_string( 'wechange_payments/mail/sepa_mandate_partial.html', sepa_variables) # send mail if settings.PAYMENTS_USE_HOOK_INSTEAD_OF_SEND_MAIL == True: signals.success_email_sender.send( sender=payment, to_user=user, template=template, subject_template=subject_template, data=data) else: subject = render_to_string(subject_template, data) message = render_to_string(template, data) mail_func = resolve_class(settings.PAYMENTS_SEND_MAIL_FUNCTION) mail_func(subject, message, settings.DEFAULT_FROM_EMAIL, [email]) return True except Exception as e: logger.warning( 'Payments: Sending a payment status email to the user failed!', extra={ 'internal_transaction_id': payment.internal_transaction_id, 'vendor_transaction_id': payment.vendor_transaction_id, 'exception': e }) if settings.DEBUG: raise return False # switch language back to previous translation.activate(cur_language)
def get_version() -> str: """ Format version string. :return: formatted version string. :rtype: str. """ if all( [ settings.DJVERSION_VERSION, settings.DJVERSION_UPDATED, any( [ isinstance(settings.DJVERSION_UPDATED, date), isinstance(settings.DJVERSION_UPDATED, datetime), ] ), settings.DJVERSION_FORMAT_STRING, ] ): return settings.DJVERSION_FORMAT_STRING.format( **{ "version": settings.DJVERSION_VERSION, "updated": localize(settings.DJVERSION_UPDATED), } ) elif settings.DJVERSION_VERSION: return settings.DJVERSION_VERSION elif settings.DJVERSION_UPDATED: return ( localize(settings.DJVERSION_UPDATED) if any( [ isinstance(settings.DJVERSION_UPDATED, date), isinstance(settings.DJVERSION_UPDATED, datetime), ] ) else "" ) elif all([Repo, settings.DJVERSION_GIT_REPO_PATH]): # type: ignore try: repo = Repo(settings.DJVERSION_GIT_REPO_PATH) # type: ignore if settings.DJVERSION_GIT_USE_TAG: # type: ignore tag = next( (tag for tag in repo.tags if tag.commit == repo.head.commit), None ) return tag.name if tag else "" elif settings.DJVERSION_GIT_USE_COMMIT: # type: ignore return repo.head.commit.hexsha if repo.head.commit else "" else: return "" except Exception: return "" else: return ""
def format_result(self, request, item): return { 'id': item.id, 'date': localize(item.date), 'title': item.title }
def gen_bill_ride_stuff(ob): buffer_ = BytesIO() try: tree = ET.fromstring(ob.xml_content.encode('utf8')) except ET.ParseError: tree = None pagesize = A4 margin = inch, inch, inch, inch canvas = Canvas(buffer_, pagesize=pagesize) c = RenderStack(0, 0, pagesize[0], pagesize[1], margin=margin) # p.roundRect(c.x(0), c.y(0), c.width(1), c.height(1), 3, stroke=1, fill=0) # Print warnings warnings = get_warning(ob) if warnings: canvas.saveState() grey = 0.3 canvas.setFillColorCMYK(0, 0, 0, grey) canvas.setStrokeColorCMYK(0, 0, 0, grey) canvas.setFont("Helvetica", 50) total_height = 60 * len(warnings) canvas.translate(c.x(0.5), c.y(0.7)) canvas.rotate(45) canvas.translate(0, total_height / 2) for item in warnings: canvas.drawCentredString(0, 0, item) canvas.translate(0, -60) canvas.restoreState() def add_items(items, showBoundary=False): f = Frame(c.x(0), c.y(0), c.width(1), c.height(1), showBoundary=showBoundary, leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=0) f.addFromList(items, canvas) if items: raise Exception("Does not fit - items left") # Parameters column_height = 0.3 column_width = 0.5 footer_height = 0.14 standard_separation = inch / 20 # styles styles = getSampleStyleSheet() small = styles['Normal'].clone("Smaller", fontSize=8) normal = styles['Normal'] bigheader = styles['h2'] mediumheader = styles['h3'] smallheader = styles['h4'] with c.section(0, 1 - column_height, 1, 1): # columna izquierda with c.section(0, 0, column_width, 1, margin=(0, 0, standard_separation, 0)): if ob.company.get_logo(): with c.section(0, 0.5, 1, 1, margin=standard_separation): # logo logo = ob.company.get_logo() if logo: add_items([ get_image(logo.file.file.name, width=c.width(1), height=c.height(1)) ]) with c.section(0, 0, 1, column_width, margin=standard_separation): story = [] if ob.company.nombre_comercial: story.append( Paragraph(ob.company.nombre_comercial, bigheader)) story.append( Paragraph( "Razon Social: {}".format(ob.company.razon_social), normal)) else: story.append( Paragraph( "Razon Social: {}".format(ob.company.razon_social), bigheader)) if ob.company.direccion_matriz != ob.punto_emision.establecimiento.direccion: story.append(Paragraph(u"Dirección Matriz:", normal)) story.append(Paragraph(ob.company.direccion_matriz, small)) story.append(Paragraph(u"Dirección Sucursal:", normal)) story.append( Paragraph(ob.punto_emision.establecimiento.direccion, small)) else: story.append(Paragraph(u"Dirección:", normal)) story.append(Paragraph(ob.company.direccion_matriz, small)) if ob.company.contribuyente_especial: story.append( Paragraph( "Contribuyente Especial: {}".format( ob.company.contribuyente_especial), normal)) story.append( Paragraph( "{} Obligado a llevar Contabilidad".format( "SI" if ob.company.obligado_contabilidad else "NO" ), normal)) add_items(story) # columna derecha with c.section(column_width, 0, 1, 1, margin=standard_separation): story.append(Paragraph("RUC {}".format(ob.company.ruc), normal)) subtipo = None if ob.status == SRIStatus.options.Accepted: tipo = "FACTURA" number = get_bill_number_from_tree(tree) elif ob.status == SRIStatus.options.Annulled: tipo = "FACTURA ANULADA" subtipo = "SIN VALIDEZ TRIBUTARIA" number = get_bill_number_from_tree(tree) elif ob.status == SRIStatus.options.Sent: tipo = "FACTURA ANULADA" subtipo = "PENDIENTE DE AUTORIZACIÓN" number = get_bill_number_from_tree(tree) else: tipo = "PROFORMA" subtipo = "SIN VALIDEZ TRIBUTARIA" number = ob.number story.append(Paragraph(tipo, smallheader)) if subtipo: story.append(Paragraph(subtipo, normal)) story.append(Paragraph(number, normal)) canvas.setTitle("{} {}".format(tipo, number)) if ob.clave_acceso: story.append(Paragraph("Clave de Acceso", mediumheader)) story.append(Paragraph(ob.clave_acceso, small)) story.append( Image(make_barcode(ob.clave_acceso), width=c.width(1), height=c.height(0.1))) if ob.numero_autorizacion: story.append(Paragraph(u"Autorización", mediumheader)) story.append(Paragraph(ob.numero_autorizacion, small)) story.append( Paragraph(l10n.localize(ob.fecha_autorizacion), small)) story.append( Paragraph("Ambiente: {}".format(ob.ambiente_sri.upper()), normal)) add_items(story) with c.section(0, 1 - column_height - 0.1, 1, 1 - column_height, margin=(standard_separation, 0, standard_separation, 0)): story = [] story.append( Paragraph("Cliente".format(ob.issued_to.razon_social), mediumheader)) story.append( Paragraph( "Razon Social / Nombres y Apellidos: {}".format( ob.issued_to.razon_social), normal)) story.append( Paragraph( "Identificacion: {} {}".format( ob.issued_to.tipo_identificacion, ob.issued_to.identificacion), normal)) story.append( Paragraph("Fecha de Emision: {}".format(l10n.localize(ob.date)), normal)) # FIXME: Guia de remision add_items(story) with c.section(0, footer_height, 1, 1 - column_height - 0.1, margin=(0, 0, 0, standard_separation)): headers = [(u'Cod.\nPrincipal', c.width(0.1)), (u'Cod.\nAuxiliar', c.width(0.1)), (u'Cant.', c.width(0.1)), (u'Descripción', c.width(0.4)), (u'Precio\nUnitario', c.width(0.1)), (u'Dcto.', c.width(0.1)), (u'Total', c.width(0.1))] data, widths = zip(*headers) data = [data] for item in ob.items: linea = [ item.code, '', str(decimals(item.qty, item.sku.batch.item.decimales_qty)), item.name, str(decimals(item.unit_price, 4)), str(decimals(item.discount, 2)), str(decimals(item.total_sin_impuestos, 2)) ] data.append(linea) detail_table = Table(data, style=[('GRID', (0, 0), (-1, -1), 0.5, colors.grey)], colWidths=widths) detail_table.hAlign = 'LEFT' add_items([detail_table]) with c.section(0, 0, 1, footer_height, margin=(0, 0, 0, standard_separation)): col_mid_point = 0.5 with c.section(0, 0, col_mid_point, 1, margin=(0, 0, standard_separation, 0)): data = [ ["DSSTI Facturas"], ] data.append( ["Descarge su comprobante en:\n http://facturas.dssti.com"]) extrainfo_table = Table(data, style=[('GRID', (0, 0), (-1, -1), 0.5, colors.grey)], colWidths=[c.width(1)]) extrainfo_table.hAlign = 'LEFT' add_items([extrainfo_table]) with c.section(col_mid_point, 0, 1, 1, margin=(0, 0, 0, 0)): data = [ ["Subtotal IVA 12%", money_2d(ob.subtotal[12])], ["Subtotal IVA 0%", money_2d(ob.subtotal[0])], ["IVA 12%", money_2d(ob.iva[12])], ['ICE', money_2d(ob.total_ice)], ["Total a Pagar", money_2d(ob.total)], ] totals_table = Table(data, style=[ ('GRID', (0, 0), (-1, -1), 0.5, colors.grey), ('ALIGN', (1, 0), (1, -1), 'RIGHT'), ], colWidths=[ c.width(0.5), c.width(0.5), ]) totals_table.hAlign = 'RIGHT' add_items([totals_table]) canvas.showPage() canvas.save() pdf = buffer_.getvalue() buffer_.close() return pdf
def _sanitize_value(value): value = value.replace(',', '') if isinstance(val, unicode): return value.encode("utf-8") else: return localize(value)
def localize_positive(val): """ Localize a number and force positive prefix. """ prefix = '+' if Decimal(val) > 0 else '' return prefix + localize(val)
def get_local_datetime(obj): return l10n.localize(obj.updated_datetime)
def get_local_datetime(obj): return l10n.localize(obj.changed_datetime)
def onPage(canvas, doc, da=None, a=None): width, height = canvas._doctemplate.pagesize canvas.saveState() fattura = doc.fatture[doc.fattura_corrente] if da is None: da = fattura.emessa_da if a is None: a = fattura.emessa_a fatturazione = FATTURE_PER_TIPO[fattura.tipo] stondata_style = ParagraphStyle("IntestazioneStondata", fontName='Helvetica', fontSize=8, leading=10, borderRadius=5, borderWidth=1, borderColor=colors.silver, borderPadding=5) a_style = ParagraphStyle("Titolo della fattura", fontName='Helvetica', fontSize=8, leading=10) tipo = fattura.tipo # set PDF properties *************** canvas.setFont('Helvetica', 8) canvas.setAuthor(settings.LICENSE_OWNER) canvas.setCreator('TaM v.%s' % settings.TAM_VERSION) canvas._doc.info.producer = ('TaM invoices') canvas.setSubject(u"%s" % fattura.nome_fattura()) if tipo == '3': nome = 'Ricevuta servizio TAXI' else: nome = 'Fattura' # Fatture consorzio e conducente si chiamano semplicemente FATTURA descrittoreFattura = u"%s %s" % (nome, fattura.descrittore()) canvas.setTitle(descrittoreFattura) # Header *************** y = height - doc.topMargin x = doc.leftMargin if test: canvas.setLineWidth(1) p = canvas.beginPath() p.moveTo(0, y) p.lineTo(width, y) canvas.drawPath(p) if fatturazione.mittente == "consorzio": logo_height = 2.5 * cm y -= logo_height canvas.drawImage(logoImage_path, x=x, y=y, width=7 * cm, height=logo_height) descrittore = Paragraph( '<font size="14"><b>%s</b></font> del %s' % (descrittoreFattura, localize(fattura.data)), a_style) descrittore.wrapOn(canvas, width / 2, y) descrittore.drawOn(canvas, x=x, y=y - descrittore.height) y -= descrittore.height + 10 if fatturazione.mittente == "conducente": # nelle fatture conducente metto il mittente a sinistra fattura_da = Paragraph(da.strip().replace('\n', '<br/>'), a_style) fattura_da.wrapOn(canvas, 6.5 * cm, 10 * cm) fattura_da.drawOn(canvas, x, y - fattura_da.height) y -= fattura_da.height y -= 0.2 * cm # spacer tra mittente e destinatario if fattura.note: note = Preformatted(fattura.note, a_style) note.wrapOn(canvas, width / 2, 10 * cm) y = y - note.height - 8 note.drawOn(canvas, 1 * cm, y=y) note_fisse = fattura.note_fisse() if note_fisse: # le vecchie ricevute hanno l'indicazione di servizio emodializzato y = y - 10 testata_fissa = Paragraph("<font size='6'>%s</font>" % note_fisse, a_style) testata_fissa.wrapOn(canvas, width / 2, 2 * cm) y = y - testata_fissa.height testata_fissa.drawOn(canvas, x, y) left_y = y - 8 # spacer finale if test: p = canvas.beginPath() p.moveTo(0, y) p.lineTo(width / 2, y) canvas.drawPath(p) # faccio la seconda colonna (destra) dell'header y = height - doc.topMargin x = width - 8 * cm if not fatturazione.mittente == "conducente": # nelle fatture conducente ho messo già il conducente a sinistra fattura_da = Paragraph(da.strip().replace('\n', '<br/>'), a_style) fattura_da.wrapOn(canvas, 6.5 * cm, 10 * cm) fattura_da.drawOn(canvas, x, y - fattura_da.height) y -= fattura_da.height y -= 0.1 * cm # spacer tra mittente e destinatario fattura_a = Paragraph(a.replace('\n', '<br/>'), stondata_style) fattura_a.wrapOn(canvas, 6.5 * cm, 10 * cm) fattura_a.drawOn(canvas, x, y - fattura_a.height - fattura_a.style.borderPadding) y -= fattura_a.height + fattura_a.style.borderPadding * 2 # spazio finale right_y = y lower_y = min(left_y, right_y) y = lower_y if test: p = canvas.beginPath() p.moveTo(width / 2, y) p.lineTo(width, y) canvas.drawPath(p) note_finali_lines = [] for footer_row in fattura.footer(): note_finali_lines.append(footer_row) note_finali = Paragraph("<br/>".join(note_finali_lines), normalStyle) note_finali.wrap(width - doc.rightMargin - doc.leftMargin, 5 * cm) note_finali.drawOn(canvas, doc.leftMargin, doc.bottomMargin) # linea sotto l'intestazione canvas.setLineWidth(1) p = canvas.beginPath() p.moveTo(doc.leftMargin, y) p.lineTo(width - doc.rightMargin, y) canvas.drawPath(p) doc.pageTemplate.frames = [ Frame(doc.leftMargin, doc.bottomMargin + note_finali.height, width - (doc.leftMargin + doc.rightMargin), y - doc.bottomMargin - note_finali.height, showBoundary=test), # x,y, width, height ] canvas.setLineWidth(0.3) p = canvas.beginPath() p.moveTo(doc.leftMargin, doc.bottomMargin) p.lineTo(width - doc.rightMargin, doc.bottomMargin) canvas.drawPath(p) canvas.restoreState()
def format_item_display(self, obj): """ Renvoyer le HTML de l'élément dans le deck """ return "<strong>{title}</strong><br><small>{when}</small><br>{author}".format( title=obj.title, author=humanize_join(obj.get_authors(), 2), when=localize(obj.created))
def text(self, strip_html=False): """Creates the text representation of the notification.""" value = "" try: if self.verb == JOIN: # actor is a user and target is a journey value = _( "%(user)s se ha <strong>unido</strong> al viaje <strong>%(journey)s</strong> del %(date)s" ) % { "user": six.text_type(self.actor), "journey": six.text_type(self.target).lower(), "date": localize(self.target.departure), } elif self.verb == LEAVE: value = _( "%(user)s ha <strong>abandonado</strong> el viaje <strong>%(journey)s</strong> del %(date)s" ) % { "user": six.text_type(self.actor), "journey": six.text_type(self.target).lower(), "date": localize(self.target.departure), } elif self.verb == THROW_OUT: value = _( "%(user)s te ha <strong>expulsado</strong> el viaje <strong>%(journey)s</strong> del %(date)s" ) % { "user": six.text_type(self.actor), "journey": six.text_type(self.target).lower(), "date": localize(self.target.departure), } elif self.verb == CONFIRM: value = _( "%(user)s te ha <strong>confirmado</strong> para el viaje <strong>%(journey)s</strong> del %(date)s" ) % { "user": six.text_type(self.actor), "journey": six.text_type(self.target).lower(), "date": localize(self.target.departure), } elif self.verb == REJECT: value = _( "%(user)s te ha <strong>rechazado</strong> para el viaje <strong>%(journey)s</strong> del %(date)s" ) % { "user": six.text_type(self.actor), "journey": six.text_type(self.target).lower(), "date": localize(self.target.departure), } elif self.verb == CANCEL: value = _( "El viaje <strong>%(journey)s</strong> del %(date)s ha sido <strong>cancelado</strong>" ) % { "journey": six.text_type(self.actor).lower(), "date": localize(self.actor.departure), } elif self.verb == MESSAGE: value = _( "%(user)s ha mandado un <strong>nuevo mensaje</strong> en <strong>%(journey)s</strong> del %(date)s" ) % { "user": six.text_type(self.actor), "journey": six.text_type(self.target).lower(), "date": localize(self.target.departure), } except AttributeError: pass if strip_html: value = strip_tags(value) return mark_safe(value)
def get_local_last_login(obj): return l10n.localize(obj.last_login)
def __unicode__(self): return u'Заголовок: "%s". Дата создания - %s' % (self.title, localize(self.date))