Отчеты пишутся в формате HTML/QWeb, как и все обычные представления в Odoo. Вы можете использовать стандартный QWeb. Сам рендеринг PDF выполняется системной утилитой wkhtmltopdf.
Если вы хотите создать отчет для определенной модели, вам нужно будет определить Отчет и Шаблон отчета, которые он будет использовать. Если вы хотите, вы также можете указать конкретный Формат бумаги для этого отчета. Наконец, если вам нужен доступ к чему то большему чем ваша модель, вы можете определить класс Кастомные отчеты, который даст вам доступ к большему количеству моделей и записей в шаблоне.
Отчет
Каждый отчет должен быть объявлен с помощью действия.
Для простоты определения отчета доступен сокращенный элемент <report>, а не настраивать действие и его окружение вручную. Этот <report> может принимать следующие атрибуты:
idСгенерированный записью external id
name(обязательный параметр)полезен только в качестве запоминающегося описания, чтобы можно было найти в списке аналогичных объектов
model(обязательный параметр)модель к которой относится отчет
report_type(обязательный параметр)укажите
qweb-pdfдля создания PDF файлов печатных форм, илиqweb-htmlдля HTMLreport_nameимя отчета (которое будет присвоено выданному PDF файлу)
groupsMany2manyfield to the groups allowed to view/use the current reportattachment_useЕсли установлено значение True, отчет будет сохранен как прикрепление к записи с использованием имени, сгенерированного выражением
attachment; Вы можете это использовать , если вам нужно, чтобы ваш отчет генерировался только один раз (по юридическим причинам, например)attachmentВыражение python, которое определяет имя отчета; Запись доступна как переменная
object
Предупреждение
The paper format cannot currently be declared via the <report>
shortcut, it must be added afterwards using a <record> extension on the
report action itself:
<record id="<report_id>" model="ir.actions.report.xml">
<field name="paperformat_id" ref="<paperformat>"/>
</record>
Пример:
<report
id="account_invoices"
model="account.invoice"
string="Invoices"
report_type="qweb-pdf"
name="account.report_invoice"
file="account.report_invoice"
attachment_use="True"
attachment="(object.state in ('open','paid')) and
('INV'+(object.number or '').replace('/','')+'.pdf')"
/>
Шаблон отчета
Минимальный жизнеспособный шаблон
Минимальный шаблон будет выглядеть так:
<template id="report_invoice">
<t t-call="report.html_container">
<t t-foreach="docs" t-as="o">
<t t-call="report.external_layout">
<div class="page">
<h2>Report title</h2>
<p>This object's name is <span t-field="o.name"/></p>
</div>
</t>
</t>
</t>
</template>
Вызов external_layout добавит стандартные заголовок и нижний колонтитул в ваш отчет. Тело PDF будет содержимым внутри <div class="page"> . id шаблона должен быть именем, указанным при объявлении отчета; Например account.report_invoice для вышеупомянутого отчета. Поскольку это шаблон QWeb, вы можете получить доступ ко всем полям объекта docs принятого внутри шаблона.
В отчетах доступны переменные, в основном:
docsзаписи для текущего отчета
doc_idsсписок id для записей
docsdoc_modelмодель для записей
docstimeссылка на
timeиз стандартной библиотеки Pythontranslate_doca function to translate a part of a report. It must be used as follow:
<t t-foreach="doc_ids" t-as="doc_id"> <t t-raw="translate_doc(doc_id, doc_model, 'partner_id.lang', account.report_invoice_document')"/> </t>
userзапись
res.userдля пользователя, печатающего отчетres_companyзапись компании текущего
user
Если вы хотите получить доступ к другим записям/моделям в шаблоне, вам понадобится кастомный отчет..
Переводимые шаблоны
Если вы хотите перевести отчеты (например, на язык партнера), вам необходимо определить два шаблона:
Основной шаблон отчета
Переводимый документ
You can then call translate_doc from your main template to obtain the translated document. If you wish to see the details of the translation in the backend, you can go to .
Например, рассмотрим отчет Sale Order из модуля «Продажи»:
<!-- Main template -->
<template id="sale.report_saleorder">
<t t-call="report.html_container">
<t t-foreach="doc_ids" t-as="doc_id">
<t t-raw="translate_doc(doc_id, doc_model, 'partner_id.lang', 'sale.report_saleorder_document')"/>
</t>
</t>
</template>
<!-- Translatable template -->
<template id="report_saleorder_document">
<t t-call="report.external_layout">
<div class="page">
<div class="oe_structure"/>
<div class="row">
<div class="col-xs-6">
<strong t-if="o.partner_shipping_id == o.partner_invoice_id">Invoice and shipping address:</strong>
<strong t-if="o.partner_shipping_id != o.partner_invoice_id">Invoice address:</strong>
<div t-field="o.partner_invoice_id" t-field-options="{"no_marker": true}"/>
<...>
<div class="oe_structure"/>
</div>
</t>
</template>
The main template calls translate_doc with partner_id.lang as a parameter,
which means it uses a custom report model to access a res.partner record.
Штрих-коды
Barcodes are images returned by a controller and can easily be embedded in reports thanks to the QWeb syntax:
<img t-att-src="'/report/barcode/QR/%s' % 'My text in qr code'"/>
Дополнительные параметры могут быть переданы как строка запроса
<img t-att-src="'/report/barcode/?
type=%s&value=%s&width=%s&height=%s'%('QR', 'text', 200, 200)"/>
Полезные заметки
Классы Bootstrap и FontAwesome можно использовать в шаблоне отчета.
Локальный CSS можно поместить непосредственно в шаблон
Глобальный CSS можно вставить в основной макет отчета, унаследовав его шаблон и вставить свой CSS
<template id="report_saleorder_style" inherit_id="report.style"> <xpath expr="."> <t> .example-css-class { background-color: red; } </t> </xpath> </template>
Если кажется, что в вашем отчете PDF отсутствуют стили, проверьте эти инструкции.
Формат бумаги
Форматы бумаги - это записи модели report.paperformat и могут содержать следующие атрибуты:
name(обязательный параметр)полезен только в качестве запоминающегося описания, чтобы можно было найти в списке аналогичных объектов
descriptionнебольшое описание вашего формата
formatлибо предопределенный формат (от A0 до A9, от B0 до B10, Legal, Letter, Tabloid, ...) или
custom; A4 по умолчанию. Вы не можете использовать нестандартный формат, если вы определяете размеры страницы.dpiзначение DPI на выходе; 90 по умолчанию
margin_top,margin_bottom,margin_left,margin_rightразмеры полей в мм
page_height,page_widthразмер страницы в мм
orientationLandscape или Portrait
header_lineбулево значение для отображения строки заголовка
header_spacingОтступ от заголовка в мм
Пример:
<record id="paperformat_frenchcheck" model="report.paperformat">
<field name="name">French Bank Check</field>
<field name="default" eval="True"/>
<field name="format">custom</field>
<field name="page_height">80</field>
<field name="page_width">175</field>
<field name="orientation">Portrait</field>
<field name="margin_top">3</field>
<field name="margin_bottom">3</field>
<field name="margin_left">3</field>
<field name="margin_right">3</field>
<field name="header_line" eval="False"/>
<field name="header_spacing">3</field>
<field name="dpi">80</field>
</record>
Кастомные отчеты
The report model has a default get_html function that looks for a model
named report.module.report_name. If it exists, it will use it to
call the QWeb engine; otherwise a generic function will be used. If you wish
to customize your reports by including more things in the template (like
records of others models, for example), you can define this model, overwrite
the function render_html and pass objects in the docargs dictionnary:
from openerp import api, models
class ParticularReport(models.AbstractModel):
_name = 'report.module.report_name'
@api.multi
def render_html(self, data=None):
report_obj = self.env['report']
report = report_obj._get_report_from_name('module.report_name')
docargs = {
'doc_ids': self._ids,
'doc_model': report.model,
'docs': self,
}
return report_obj.render('module.report_name', docargs)
Отчеты - это веб-страницы
Отчеты динамически генерируются модулем отчета и могут быть доступны напрямую через URL:
Например, вы можете получить доступ к отчету Sale Order в режиме html, перейдя в http://<server-address>/report/html/sale.report_saleorder/38
Или вы можете получить доступ к PDF-версии по адресу http://<server-address>/report/pdf/sale.report_saleorder/38