Raimon Esteve (Zikzakmedia) avatar Raimon Esteve (Zikzakmedia) committed 744deaa

Active Record

Comments (0)

Files changed (8)

+Version 2.6.0 - 2012-10-16
+* Active Record
+* Simplify module information with python configuration
+
 Version 2.4.0 - 2012-07-24
 * Initial release
 ===================
 
 The sale_margin module of the Tryton application platform.
-See __tryton__.py
 
 Installing
 ----------
 #This file is part margin module for Tryton.
 #The COPYRIGHT file at the top level of this repository contains 
 #the full copyright notices and license terms.
+from trytond.pool import Pool
+from .sale import *
 
-from .sale import *
+
+def register():
+    Pool.register(
+        Sale,
+        SaleLine,
+        module='sale_margin', type_='model')

__tryton__.py

-#This file is part sale_margin module for Tryton.
-#The COPYRIGHT file at the top level of this repository contains 
-#the full copyright notices and license terms.
-{
-    'name': 'Sale Margin',
-    'name_ca_ES': 'Marges comanda de venda',
-    'name_es_ES': 'Margen pedido de venta',
-    'version': '2.4.0',
-    'author': 'Zikzakmedia',
-    'email': 'zikzak@zikzakmedia.com',
-    'website': 'http://www.zikzakmedia.com/',
-    'description': '''The sale_margin module adds the 'Margin' on sales, 
-which gives the profitability by calculating the difference between the Unit Price and Cost Price.
-''',
-    'description_ca_ES': '''Aquest mòdul afegeix el 'Marge' en la comanda de venda,
-que proporciona la rendibilitat calculant la diferència entre el preu unitari i el preu de cost
-''',
-    'description_es_ES': '''Este módulo añade el 'Margen' en el pedido de venta,
-que proporciona la rentabilidad calculando la diferencia entre el precio unidad y el precio de coste
-''',
-    'depends': [
-        'ir',
-        'res',
-        'sale',
-    ],
-    'xml': [
-        'sale.xml',
-    ],
-    'translation': [
-        'locale/ca_ES.po',
-        'locale/es_ES.po',
-    ]
-}
 #the full copyright notices and license terms.
 
 from decimal import Decimal
-from trytond.model import ModelView, ModelSQL, fields
-from trytond.tools import safe_eval, datetime_strftime
+from trytond.model import fields
 from trytond.pyson import Eval
 from trytond.transaction import Transaction
-from trytond.pool import Pool
+from trytond.pool import Pool, PoolMeta
 
-class Sale(ModelSQL, ModelView):
-    _name = 'sale.sale'
+__all__ = ['Sale', 'SaleLine']
+__metaclass__ = PoolMeta
+
+class Sale:
+    'Sale'
+    __name__ = 'sale.sale'
 
     margin = fields.Function(fields.Numeric('Margin',
             digits=(16, Eval('currency_digits', 2),),
         readonly=True,
         depends=['currency_digits'])
 
-    def get_margin(self, ids, name):
+    def get_margin(self, name):
         '''
         Return the margin of each sales
         '''
-        currency_obj = Pool().get('currency.currency')
-        margins = {}
-        for sale in self.browse(ids):
-            if (sale.state in self._states_cached
-                    and sale.margin_cache is not None):
-                margins[sale.id] = sale.margin_cache
-                continue
-            for l in sale.lines:
-                margin = sum((l.margin for l in sale.lines if l.type == 'line'),
-                    Decimal(0))
-                margins[sale.id] = currency_obj.round(sale.currency, margin)
-        return margins
+        Currency = Pool().get('currency.currency')
+        if (self.state in self._states_cached
+                and self.margin_cache is not None):
+            return self.margin_cache
+        margin = sum((l.margin for l in self.lines if l.type == 'line'),
+                Decimal(0))
+        return Currency.round(self.currency, margin)
 
-    def store_cache(self, ids):
-        for sale in self.browse(ids):
-            self.write(sale.id, {
+    @classmethod
+    def store_cache(cls, sales):
+        for sale in sales:
+            cls.write([sale], {
                     'untaxed_amount_cache': sale.untaxed_amount,
                     'tax_amount_cache': sale.tax_amount,
                     'total_amount_cache': sale.total_amount,
                     'margin_cache': sale.margin,
                     })
 
-Sale()
 
-class SaleLine(ModelSQL, ModelView):
-    _name = 'sale.line'
+class SaleLine:
+    'Sale Line'
+    __name__ = 'sale.line'
 
     cost_price = fields.Numeric('Cost Price', digits=(16, 4),
         states={
                 'unit_price', 'unit', '_parent_sale.currency'],
             depends=['type']), 'get_margin')
 
-    def on_change_product(self, vals):
-        pool = Pool()
-        product_obj = pool.get('product.product')
-
-        if not vals.get('product'):
+    def on_change_product(self):
+        if not self.product:
             return {}
-
-        res = super(SaleLine, self).on_change_product(vals)
-
-        product = product_obj.browse(vals['product'])
-        res['cost_price'] = product.cost_price
+        res = super(SaleLine, self).on_change_product()
+        res['cost_price'] = self.product.cost_price
         return res
 
-    def on_change_with_margin(self, vals):
-        cost = Decimal(str(vals.get('quantity') or '0.0')) * \
-                    (vals.get('cost_price') or Decimal('0.0'))
-        amount = Decimal(str(vals.get('quantity') or '0.0')) * \
-                    (vals.get('unit_price') or Decimal('0.0'))
+    def on_change_with_margin(self):
+        cost = Decimal(str(self.quantity or '0.0')) * \
+                    (self.cost_price or Decimal('0.0'))
+        amount = Decimal(str(self.quantity or '0.0')) * \
+                    (self.unit_price or Decimal('0.0'))
         res = Decimal(amount-cost)
         return res
 
-    def get_margin(self, ids, name):
+    def get_margin(self, name):
         '''
         Return the margin of each sale lines
         '''
-        currency_obj = Pool().get('currency.currency')
+        Currency = Pool().get('currency.currency')
         res = {}
-        for line in self.browse(ids):
-            if line.type == 'line':
-                cost = Decimal(str(line.quantity)) * (line.cost_price or Decimal('0.0')) 
-                amount = Decimal(str(line.quantity)) * (line.unit_price)
-                res[line.id] = currency_obj.round(line.sale.currency, amount - cost)
-            else:
-                res[line.id] = Decimal('0.0')
-        return res
-
-SaleLine()
+        if self.type == 'line':
+            cost = Decimal(str(self.quantity)) * (self.cost_price or Decimal('0.0')) 
+            amount = Decimal(str(self.quantity)) * (self.unit_price)
+            return Currency.round(self.sale.currency, amount - cost)
+        else:
+            return Decimal('0.0')
                     <xpath
                         expr="/form/notebook/page/label[@name=&quot;unit_price&quot;]"
                         position="before">
-                        <newline/>
                         <label name="cost_price"/>
                         <field name="cost_price"/>
                     </xpath>
                     <xpath
                         expr="/form/notebook/page/field[@name=&quot;amount&quot;]"
                         position="after">
-                        <newline/>
                         <label name="margin"/>
                         <field name="margin"/>
                     </xpath>
 
 from setuptools import setup
 import re
+import os
+import ConfigParser
 
-info = eval(open('__tryton__.py').read())
+config = ConfigParser.ConfigParser()
+config.readfp(open('tryton.cfg'))
+info = dict(config.items('tryton'))
+for key in ('depends', 'extras_depend', 'xml'):
+    if key in info:
+        info[key] = info[key].strip().splitlines()
 major_version, minor_version, _ = info.get('version', '0.0.1').split('.', 2)
 major_version = int(major_version)
 minor_version = int(minor_version)
 
 setup(name='trytond_sale_margin',
     version=info.get('version', '0.0.1'),
-    description=info.get('description', ''),
-    author=info.get('author', 'Zikzakmedia'),
-    author_email=info.get('email', 'zikzak@zikzakmedia.com'),
-    url=info.get('website', 'http://www.zikzakmedia.com'),
+    description='Tryton module to add margins (price sale-price cost) in sales',
+    author='Zikzakmedia SL',
+    author_email='zikzak@zikzakmedia.com',
+    url='http://www.zikzakmedia.com',
     download_url="https://bitbucket.org/zikzakmedia/trytond-sale_margin",
     package_dir={'trytond.modules.sale_margin': '.'},
     packages=[
     ],
     package_data={
         'trytond.modules.sale_margin': info.get('xml', []) \
-                + info.get('translation', []) \
-                + ['icons/*.svg'],
+            + ['tryton.cfg', 'locale/*.po'],
     },
     classifiers=[
         'Development Status :: 5 - Production/Stable',
+[tryton]
+version=2.6.0
+depends:
+    ir
+    res
+    sale
+xml:
+    sale.xml
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.