InvoiceTransactionRule.py 10.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
##############################################################################
#
# Copyright (c) 2002 Nexedi SARL and Contributors. All Rights Reserved.
#                    Jean-Paul Smets-Solanes <jp@nexedi.com>
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# garantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
##############################################################################

from AccessControl import ClassSecurityInfo
from Products.ERP5Type import Permissions, PropertySheet, Constraint, Interface
from Products.ERP5.Document.Rule import Rule
from Products.ERP5Type.XMLMatrix import XMLMatrix
from Products.CMFCore.utils import getToolByName
from UserDict import UserDict

from zLOG import LOG

class InvoiceTransactionRule(Rule, XMLMatrix):
    """
Jean-Paul Smets's avatar
Jean-Paul Smets committed
40 41 42 43
      Invoice Transaction Rule object generates accounting movements
      for each invoice movement based on category membership and
      other predicated. Template accounting movements are stored
      in cells inside an instance of the InvoiceTransactionRule.
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65

      WARNING: what to do with movement split ?
    """

    # CMF Type Definition
    meta_type = 'ERP5 Invoice Transaction Rule'
    portal_type = 'Invoice Transaction Rule'
    add_permission = Permissions.AddPortalContent
    isPortalContent = 1
    isRADContent = 1

    # Declarative security
    security = ClassSecurityInfo()
    security.declareObjectProtected(Permissions.View)

    # Default Properties
    property_sheets = ( PropertySheet.Base
                      , PropertySheet.XMLObject
                      , PropertySheet.CategoryCore
                      , PropertySheet.DublinCore
                      )

Jean-Paul Smets's avatar
Jean-Paul Smets committed
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
    def _getMatchingCell(self, movement):
      """
        Browse all cells and test them until match found
      """
      for cell in self.getCellValueList(base_id = 'vat_per_region'):
        if cell.test(movement):
          LOG('Found Cell' ,0, cell.getRelativeUrl())
          return cell
      return None          
    
    def _getMatchingCell1(self, movement):
      """
        Browse all predicates and make sur all dimensions match
        An alternate implementation left as example
      """
      dimension_dict = {}   # Possible dimensions
      tdimension_dict = {}  # Dimensions which responded 1 on test
      for predicate in self.contentValues():        
        if predicate.is_predicate:
          if predicate.getStringIndex() not in tdimension_dict.keys() \
              and predicate.test(movement):
            tdimension_dict[predicate.getStringIndex()] = predicate.getRelativeUrl()
          dimension_dict[predicate.getStringIndex()] = 1
      if len(dimension_dict) == len(tdimension_dict):
        # If all dimesions are satisfied, then return 1
        cell_key = []
        for matrix_range_item in self.getCellRange(base_id = 'vat_per_region'):
          for range_item in matrix_range_item:
            if range_item in tdimension_dict.values():
              cell_key.append(range_item)
              break # Just in case, make sure only one range_item per matrix_range_item
        kwd = {'base_id': 'vat_per_region'}                      
        return self.getCell(*cell_key, **kwd)
      return None          
                    
101 102 103 104 105
    def test(self, movement):
      """
        Tests if the rule (still) applies
      """
      # An invoice transaction rule applies when the movement's parent is an invoice rule
Jean-Paul Smets's avatar
Jean-Paul Smets committed
106 107 108 109 110 111 112
      parent = movement.getParentValue()
      parent_rule_value = parent.getSpecialiseValue()
      if parent_rule_value is None:
        return 0        
      if parent_rule_value.getPortalType() in ('Invoicing Rule', 'Invoice Rule'):
        if self._getMatchingCell(movement) is not None:
          return 1
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
      return 0

    # Simulation workflow
    security.declareProtected(Permissions.ModifyPortalContent, 'expand')
    def expand(self, applied_rule, force=0, **kw):
      """
        Expands the current movement downward.

        -> new status -> expanded

        An applied rule can be expanded only if its parent movement
        is expanded.
      """

      invoice_transaction_line_type = 'Simulation Movement'

Jean-Paul Smets's avatar
Jean-Paul Smets committed
129 130
      # First, get the simulation movement we were expanded from
      my_invoice_line_simulation = applied_rule.getParentValue()
131

132
      # Next, we can try to expand the rule
133
      if force or \
134 135
         (applied_rule.getLastExpandSimulationState() not in self.getPortalReservedInventoryStateList() and \
         applied_rule.getLastExpandSimulationState() not in self.getPortalCurrentInventoryStateList()):
136

Jean-Paul Smets's avatar
Jean-Paul Smets committed
137 138
        # Find a matching cell
        my_cell = self._getMatchingCell(my_invoice_line_simulation)
139 140

        if my_cell is not None :
Jean-Paul Smets's avatar
Jean-Paul Smets committed
141
          my_cell_transaction_id_list = my_cell.contentIds()
142 143 144
        else :
          my_cell_transaction_id_list = []

145 146 147 148 149
        if my_cell is not None : # else, we do nothing
          # check each contained movement and delete
          # those that we don't need
          for movement in applied_rule.objectValues():
            if movement.getId() not in my_cell_transaction_id_list :
Jean-Paul Smets's avatar
Jean-Paul Smets committed
150
              # movement.flushActivity(invoke=0) XXX never use it
151
              applied_rule.deleteContent(movement.getId())
152

153
          # Add every movement from the Matrix to the Simulation
154 155 156 157 158 159 160 161 162
          for transaction_line in my_cell.objectValues() :
            if transaction_line.getId() in applied_rule.objectIds() :
              simulation_movement = applied_rule[transaction_line.getId()]
            else :
              simulation_movement = applied_rule.newContent(id=transaction_line.getId()
                  , portal_type=invoice_transaction_line_type)
            #LOG('InvoiceTransactionRule.expand :', 0, repr(( 'movement', simulation_movement, transaction_line.getSource(), transaction_line.getDestination(), (my_invoice_line_simulation.getQuantity() * my_invoice_line_simulation.getPrice()) * transaction_line.getQuantity() )))
            simulation_movement._edit(source = transaction_line.getSource()
                , destination = transaction_line.getDestination()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
163 164
                , source_section = my_invoice_line_simulation.getSourceSection()
                , destination_section = my_invoice_line_simulation.getDestinationSection()
165 166 167 168
                , quantity = (my_invoice_line_simulation.getQuantity() * my_invoice_line_simulation.getPrice())
                  * transaction_line.getQuantity()
                  # calculate (quantity * price) * cell_quantity
                , force_update = 1
169 170 171
              )

        # Now we can set the last expand simulation state to the current state
172 173
        #XXX Note : this is wrong, as there isn't always a sale invoice when we expand this rule.
        #applied_rule.setLastExpandSimulationState(my_invoice.getSimulationState())
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224

      # Pass to base class
      Rule.expand(self, applied_rule, force=force, **kw)

    security.declareProtected(Permissions.ModifyPortalContent, 'solve')
    def solve(self, applied_rule, solution_list):
      """
        Solve inconsitency according to a certain number of solutions
        templates. This updates the

        -> new status -> solved

        This applies a solution to an applied rule. Once
        the solution is applied, the parent movement is checked.
        If it does not diverge, the rule is reexpanded. If not,
        diverge is called on the parent movement.
      """

    security.declareProtected(Permissions.ModifyPortalContent, 'diverge')
    def diverge(self, applied_rule):
      """
        -> new status -> diverged

        This basically sets the rule to "diverged"
        and blocks expansion process
      """

    # Solvers
    security.declareProtected(Permissions.View, 'isDivergent')
    def isDivergent(self, applied_rule):
      """
        Returns 1 if divergent rule
      """

    security.declareProtected(Permissions.View, 'getDivergenceList')
    def getDivergenceList(self, applied_rule):
      """
        Returns a list Divergence descriptors
      """

    security.declareProtected(Permissions.View, 'getSolverList')
    def getSolverList(self, applied_rule):
      """
        Returns a list Divergence solvers
      """

    # Deliverability / orderability
    def isOrderable(self, m):
      return 1

    def isDeliverable(self, m):
225
      if m.getSimulationState() in self.getPortalDraftOrderStateList():
226 227 228 229 230
        return 0
      return 1

    # Matrix related
    security.declareProtected( Permissions.ModifyPortalContent, 'newCellContent' )
231
    def newCellContent(self, id,**kw):
232 233 234 235
      """
          This method can be overriden
      """
      self.invokeFactory(type_name='Accounting Rule Cell',id=id)
236 237
      new_cell = self.get(id)
      return new_cell
238 239 240 241 242 243 244 245 246

    security.declareProtected(Permissions.ModifyPortalContent, 'updateMatrix')
    def updateMatrix(self) :
      """
      Makes sure that the cells are consistent with the predicates.
      """
      base_id = 'vat_per_region'
      kwd = {'base_id': base_id}
      new_range = self.InvoiceTransactionRule_asCellRange() # This is a site dependent script
247
      #LOG('InvoiceTransactionRule.updateMatrix :', 0, repr(( new_range, self.contentIds(), [x for x in self.searchFolder()], )))
248 249 250 251 252 253 254 255 256 257

      self._setCellRange(*new_range, **kwd)
      cell_range_key_list = self.getCellRangeKeyList(base_id = base_id)
      if cell_range_key_list <> [[None, None]] :
        for k in cell_range_key_list :
          c = self.newCell(*k, **kwd)
          c.edit( mapped_value_property_list = ( 'title',),
                  predicate_category_list = filter(lambda k_item: k_item is not None, k),
                  title = 'Transaction %s' % repr(map(lambda k_item : self.restrictedTraverse(k_item).getTitle(), k)),
                  force_update = 1
258
                )
259
      else :
Jean-Paul Smets's avatar
Jean-Paul Smets committed
260
        # If empty matrix, delete all cells
261 262 263
        cell_range_id_list = self.getCellRangeIdList(base_id = base_id)
        for k in cell_range_id_list :
          if self.get(k) is not None :
Jean-Paul Smets's avatar
Jean-Paul Smets committed
264
            self.deleteContent(k)