Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions product_multi_image/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,60 @@
##############################################################################

from . import models
from openerp import SUPERUSER_ID
import imghdr
import base64
import unicodedata
import re
try:
import slugify as slugify_lib
except ImportError:
slugify_lib = None

def get_slug(name):
if slugify_lib:
try:
return slugify_lib.slugify(name)
except TypeError:
pass
uni = unicodedata.normalize('NFKD', name).encode(
'ascii', 'ignore').decode('ascii')
slug = re.sub(r'[\W_]', ' ', uni).strip().lower()
slug = re.sub(r'[-\s]+', '-', slug)
return slug

def get_from_product_medium(cr):
# product_template_obj = registry['product.template']
# products_ids = product_template_obj.search(
# cr, SUPERUSER_ID, [('product_images', '=', False),
# ('image_medium', '!=', False)])
cr.execute("SELECT id, image_medium, name "
"FROM product_template "
"WHERE image_medium is not null and"
" ID not in (SELECT product_tmpl_id"
" FROM product_images)")
products = cr.fetchall()
for product in products:
extension = imghdr.what('', base64.b64decode(
product[1]))
extension = '.{}'.format(extension or 'jpe')
cr.execute("INSERT INTO product_images(file_db_store,name,extension,"
"product_tmpl_id,link)"
"VALUES('{}','{}','{}',{},False)".format(
product[1], get_slug(product[2]), extension,
product[0]))


def get_from_product_images(cr, registry):
old_images_obj = registry['product.images']
old_images_ids = old_images_obj.search(cr, SUPERUSER_ID, [])
products_list = []
for o in old_images_obj.browse(cr, SUPERUSER_ID, old_images_ids):
products_list.append(o.product_tmpl_id.id)
image_type = 'url' if o.link else 'db'
cr.execute("INSERT INTO product_image(file_db_store, "
"name,extension,url,comments,product_id,type)"
"VALUES('{}','{}','{}','{}','{}',{},'{}')".format(
o.file_db_store, get_slug(o.name), o.extension, o.url,
o.comments, o.product_tmpl_id.id, image_type))

2 changes: 2 additions & 0 deletions product_multi_image/__openerp__.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,6 @@
'views/res_company_view.xml'
],
'installable': True,
"pre_init_hook": "get_from_product_medium",
"post_init_hook": "get_from_product_images",
}
3 changes: 3 additions & 0 deletions product_multi_image/models/product_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,9 @@ def _check_filestore(self):
product_id = fields.Many2one(
comodel_name='product.template', string='Product', required=True,
ondelete='cascade')
products = fields.Many2many(comodel_name='product.product',
relation='image_product_product_rel',
store=True, string='Variants')

def _make_pretty(self, name):
return name.replace('_', ' ').capitalize()
Expand Down
25 changes: 23 additions & 2 deletions product_multi_image/models/product_product.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,28 @@
#
##############################################################################
import logging
import imghdr
import base64
from openerp import models, fields, api, _

_logger = logging.getLogger(__name__)


class Product(models.Model):
_inherit = "product.product"

@api.one
@api.depends("product_tmpl_id.image_ids.products")
def _get_images(self):
self.images = self.product_tmpl_id.image_ids.filtered(
lambda x: self in x.products)

images = fields.Many2many(comodel_name="product.image",
relation='product_product_image_rel',
compute='_get_images',
string="Images")


class ProductProduct(models.Model):
_inherit = "product.template"

Expand All @@ -40,13 +57,17 @@ def _get_main_image(self):
self.image_small = self.image_ids[0].image_small

def _set_image(self, image):
if self.image:
if image:
extension = imghdr.what('', base64.b64decode(image))
extension = '.{}'.format(extension or 'jpg')
if self.image_ids:
self.image_ids[0].write({'type': 'db',
'file_db_store': image})
'file_db_store': image,
'extension': extension})

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

La extensión hasta donde recuerdo era un campo que quería eliminar. El nombre refleja ya la extensión.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lo cambie porque en prestashop la extensión es obligatoria. Me pareció mas apropiado cambiarlo en este modulo ya que añadía información. La función se ejecuta en los inverse y el nombre esta hardcode 'Main image' no tiene extensión.

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK, me parece correcto entonces. Pero la nueva dependencia a imghr habrá que declararla. ¿No existe una forma de hacerlo sin necesitar una librería nueva? Tal vez sería conveniente hacerlo por nombre de archivo simplemente, aunque eso no sea exacto.

else:
self.image_ids = [(0, 0, {'type': 'db',
'file_db_store': image,
'extension': extension,
'name': _('Main image')})]
elif self.image_ids:
self.image_ids[0].unlink()
Expand Down
5 changes: 5 additions & 0 deletions product_multi_image/views/product_image_view.xml
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,11 @@
readonly="True"
nolabel="1" />
</group>
<group string="Products">

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Esto se debería hacer sobre la propia variante en su pestaña correspondiente, pero creando código para la función inverse en product.product que sólo modifique para el producto en concreto.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Esto no lo tengo muy claro. El campo images tienen un many2one a template, pero al añadir la imagen en una variante esta se copiaba a todos las variantes. El campo no se "copia" en product.product. Por esto me decidí a hacerlo de esta manera

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pero lo dicho, eso lo debes hacer en el inverse de la función tanto para product.template como para product.product. Si se hace en el template, escribir a cada variante el mismo. Si se hace en el product, sólo para el producto en concreto. Odoo hace algo parecido con el campo imagen normal. Echa un vistazo a su código.

<field name="product_id" invisible="1"/>
<field name="products" nolabel="1" widget="many2many_tags"
domain='[("product_tmpl_id","=",product_id)]'/>
</group>
</group>
</page>
<page string="Comments" name="page_comments">
Expand Down
11 changes: 11 additions & 0 deletions product_multi_image/views/product_product_view.xml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,17 @@
</xpath>
</field>
</record>

<record id="view_product_product_form_img_inh" model="ir.ui.view">
<field name="name">product.product.images.m2m</field>
<field name="model">product.product</field>
<field name="inherit_id" ref="product.product_normal_form_view"/>
<field name="arch" type="xml">
<field name="default_code" position="after">
<field name="images" widget="many2many_tags" readonly="1"/>

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Por qué ponerlo como un many2many?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mi idea es que las imagenes solo se editen en el template. En la pestaña imagenes hay un campo produts donde se pueden añadir product.produt que serían las variantes a las que queremos asignar la imagen. El campo añadido en product.product es solo informativo donde podemos ver las imagenes con la que esta asociada el producto.

Es verdad que he hecho todo esto teniendo en mente el conector y seguramente haya roto la idea que tenias para este modulo. Si es así dime como hacerlo y lo cambio

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ya, pero así se pierde la visualización cuando desde cualquier sitio del ERP se accede a la variante (pedido, factura, etc). Creo que es mejor lo otro que te digo. Prueba y me cuentas.

</field>
</field>
</record>

</data>
</openerp>