~unifield-team/unifield-wm/us-826

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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
# -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2011 MSF, TeMPO Consulting.
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import datetime
from osv import fields, osv
from tools.translate import _

class financing_contract_funding_pool_line(osv.osv):
    _name = "financing.contract.funding.pool.line"
    _description = "Funding pool line"

    _columns = {
        'contract_id': fields.many2one('financing.contract.format', 'Contract', required=True),
        'funding_pool_id': fields.many2one('account.analytic.account', 'Funding pool name', required=True),
        'funded': fields.boolean('Earmarked'),
        'total_project': fields.boolean('Total project'),
    }

    _defaults = {
        'funded': False,
        'total_project': True,
    }

    def check_fp(self, cr, uid, ids, context=None):
        """
        See all other funding pool lines and check that the FP is not used yet.
        If used, raise an error.
        """
        if context is None:
            context = {}
        if isinstance(ids, (int, long)):
            ids = [ids]
        for line in self.browse(cr, uid, ids):
            fp_id = line.funding_pool_id.id
            # Search other lines
            other_same_fp_ids = self.search(cr, uid, [('contract_id', '=', line.contract_id.id), ('id', '!=', line.id), ('funding_pool_id', '=', fp_id)])
            if other_same_fp_ids:
                raise osv.except_osv(_('Error'), _('This FP is already in use: %s') % (line.funding_pool_id.name))
        return True

    def create(self, cr, uid, vals, context=None):
        result = super(financing_contract_funding_pool_line, self).create(cr, uid, vals, context=context)
        # when a new funding pool is added to contract, then add all of the cost centers to the cost center tab, unless
        # the cost center is already there. No action is taken when a cost center is deleted
        if 'contract_id' in vals and 'funding_pool_id' in vals:
            # get the cc ids from for this funding pool
            quad_obj = self.pool.get('financing.contract.account.quadruplet')
            quad_ids = quad_obj.search(cr, uid, [('funding_pool_id','=',vals['funding_pool_id'])],context=context)
            quad_rows = quad_obj.browse(cr, uid, quad_ids,context=context)
            quad_cc_ids = []
            for quad in quad_rows:
                cc_id_temp = quad.cost_center_id.id
                if cc_id_temp not in quad_cc_ids:
                    quad_cc_ids.append(cc_id_temp)

            # get the format instance
            format_obj = self.pool.get('financing.contract.format')
            cc_rows = format_obj.browse(cr, uid, vals['contract_id'], context=context).cost_center_ids
            cc_ids = []
            for cc in cc_rows:
                cc_ids.append(cc.id)

            # append the ccs from the fp only if not already there
            cc_ids = list(set(cc_ids).union(quad_cc_ids))
            # replace the associated cc list -NOT WORKING
            format_obj.write(cr, uid, vals['contract_id'],{'cost_center_ids':[(6,0,cc_ids)]}, context=context)
        # UFTP-121: Check that FP is not used yet.
        self.check_fp(cr, uid, result)
        return result

    def write(self, cr, uid, ids, vals, context=None):
        """
        Check that no previous funding pool account is used yet.
        """
        if context is None:
            context = {}
        res = super(financing_contract_funding_pool_line, self).write(cr, uid, ids, vals, context=context)
        self.check_fp(cr, uid, ids)
        return res

financing_contract_funding_pool_line()

class financing_contract_contract(osv.osv):

    _name = "financing.contract.contract"
    _inherits = {"financing.contract.format": "format_id"}
    _trace = True

    def contract_open(self, cr, uid, ids, *args):
        self.write(cr, uid, ids, {
            'state': 'open',
            'open_date': datetime.date.today().strftime('%Y-%m-%d'),
            'soft_closed_date': None
        })
        return True

    def search_draft_or_temp_posted(self, cr, uid, ids, context=None):
        """
        Search all draft/temp posted register lines that have an analytic distribution in which funding pool lines have an analytic account set to those given in contract.
        """
        res = []
        for c in self.browse(cr, uid, ids):
            # Search draft posted statement lines
            fp_ids = [x and x.funding_pool_id and x.funding_pool_id.id for x in c.funding_pool_ids]
            if fp_ids:
                sql = """SELECT absl.statement_id
                FROM account_bank_statement_line AS absl, funding_pool_distribution_line AS fp
                WHERE distribution_id = analytic_distribution_id
                AND fp.analytic_id in %s
                AND absl.id in (
                    SELECT st.id
                    FROM account_bank_statement_line st
                        LEFT JOIN account_bank_statement_line_move_rel rel ON rel.move_id = st.id
                        LEFT JOIN account_move am ON am.id = rel.statement_id
                    WHERE (rel.statement_id is null OR am.state != 'posted')
                    ORDER BY st.id
                ) GROUP BY absl.statement_id"""
                cr.execute(sql, (tuple(fp_ids),))
                sql_res = cr.fetchall()
                if sql_res:
                    res += [x and x[0] for x in sql_res]
        return res

    def contract_soft_closed(self, cr, uid, ids, *args):
        """
        If some draft/temp posted register lines that have an analytic distribution in which funding pool lines have an analytic account set to those given in contract, then raise an error.
        Otherwise set contract as soft closed.
        """
        # Search draft/temp posted register lines
        if isinstance(ids, (long, int)):
            ids = [ids]
        for cont in self.read(cr, uid, ids, ['funding_pool_ids']):
            if not cont['funding_pool_ids']:
                raise osv.except_osv(_('Error'), _("This contract can not be soft-closed because it is not linked to any funding pool."))
        register_ids = self.search_draft_or_temp_posted(cr, uid, ids)
        if register_ids:
            msg= ''
            for i, st in enumerate(self.pool.get('account.bank.statement').browse(cr, uid, register_ids)):
                if i > 0:
                    msg += ' - '
                msg += st.name or ''
            raise osv.except_osv(_('Error'), _("There are still expenses linked to contract's funding pools not hard-posted in registers: %s") % (msg,))
        # Normal behaviour (change contract ' state)
        self.write(cr, uid, ids, {
            'state': 'soft_closed',
            'soft_closed_date': datetime.date.today().strftime('%Y-%m-%d')
        })
        return True

    def contract_hard_closed(self, cr, uid, ids, *args):
        self.write(cr, uid, ids, {
            'state': 'hard_closed',
            'hard_closed_date': datetime.date.today().strftime('%Y-%m-%d')
        })
        return True

    def get_contract_domain(self, cr, uid, browse_contract, reporting_type=None, context=None):
        # we update the context with the contract reporting type and currency
        format_line_obj = self.pool.get('financing.contract.format.line')
        # Values to be set
        if reporting_type is None:
            reporting_type = browse_contract.reporting_type

        analytic_domain = False
        isFirst = True
        # parse parent lines (either value or sum of children's values)
        for line in browse_contract.actual_line_ids:
            if not line.parent_id:
                # Calculate the all the children lines account domain
                temp = format_line_obj._get_analytic_domain(cr, uid, line, reporting_type, isFirst, context=context)
                if analytic_domain:
                    # if there exist already previous view, just add an OR operator
                    analytic_domain = ['|'] + analytic_domain + temp
                else:
                    # first time
                    analytic_domain = temp

        return analytic_domain

    def _get_overhead_amount(self, cr, uid, ids, field_name=None, arg=None, context=None):
        """
            Method to compute the overhead amount
        """
        res = {}
        for budget in self.browse(cr, uid, ids, context=context):
            # default value
            res[budget.id] = 0.0
            if budget.overhead_type == 'cost_percentage':
                res[budget.id] = round(budget.grant_amount * budget.overhead_percentage / (100.0 + budget.overhead_percentage))
            elif budget.overhead_type == 'grant_percentage':
                res[budget.id] = round(budget.grant_amount * budget.overhead_percentage / 100.0)
        return res

    _columns = {
        'name': fields.char('Financing contract name', size=64, required=True),
        'code': fields.char('Financing contract code', size=16, required=True),
        'donor_id': fields.many2one('financing.contract.donor', 'Donor', required=True, domain="[('active', '=', True)]"),
        'donor_grant_reference': fields.char('Donor grant reference', size=64),
        'hq_grant_reference': fields.char('HQ grant reference', size=64),
        'grant_amount': fields.float('Grant amount', required=True),
        'overhead_amount': fields.function(_get_overhead_amount, method=True, store=False, string="Overhead amount", type="float", readonly=True),
        'reporting_currency': fields.many2one('res.currency', 'Reporting currency', required=True),
        'notes': fields.text('Notes'),
        'open_date': fields.date('Open date'),
        'soft_closed_date': fields.date('Soft-closed date'),
        'hard_closed_date': fields.date('Hard-closed date'),
        'state': fields.selection([('draft','Draft'),
                                    ('open','Open'),
                                    ('soft_closed', 'Soft-closed'),
                                    ('hard_closed', 'Hard-closed')], 'State'),
        'currency_table_id': fields.many2one('res.currency.table', 'Currency Table'),
        'instance_id': fields.many2one('msf.instance','Proprietary Instance', required=True),
        # Define for _inherits
        'format_id': fields.many2one('financing.contract.format', 'Format', ondelete="cascade"),
        'fp_added_flag': fields.boolean('Flag when new FP is added')
    }

    _defaults = {
        'state': 'draft',
        'fp_added_flag': False,
        'reporting_currency': lambda self,cr,uid,c: self.pool.get('res.users').browse(cr, uid, uid, c).company_id.currency_id.id,
    }

    def _check_unicity(self, cr, uid, ids, context=None):
        if not context:
            context = {}
        for contract in self.browse(cr, uid, ids, context=context):
            bad_ids = self.search(cr, uid, [('|'),('name', '=ilike', contract.name),('code', '=ilike', contract.code)])
            if len(bad_ids) and len(bad_ids) > 1:
                return False
        return True

    _constraints = [
        (_check_unicity, 'You cannot have the same code or name between contracts!', ['code', 'name']),
    ]

    def copy(self, cr, uid, id, default=None, context=None, done_list=[], local=False):
        contract = self.browse(cr, uid, id, context=context)
        if not default:
            default = {}
        default = default.copy()
        default['code'] = (contract['code'] or '') + '(copy)'
        default['name'] = (contract['name'] or '') + '(copy)'
        # Copy lines manually but remove CCs and FPs
        default['funding_pool_ids'] = []
        default['cost_center_ids'] = []
        default['actual_line_ids'] = []
        copy_id = super(financing_contract_contract, self).copy(cr, uid, id, default, context=context)
        copy = self.browse(cr, uid, copy_id, context=context)
        self.pool.get('financing.contract.format').copy_format_lines(cr, uid, contract.format_id.id, copy.format_id.id, context=context)
        return copy_id

    def onchange_donor_id(self, cr, uid, ids, donor_id, format_id, actual_line_ids, context=None):
        res = {}
        if donor_id:
            donor = self.pool.get('financing.contract.donor').browse(cr, uid, donor_id, context=context)
            if donor.format_id:
                source_format = donor.format_id
                format_vals = {
                    'format_name': source_format.format_name,
                    'reporting_type': source_format.reporting_type,
                    'overhead_type': source_format.overhead_type,
                    'overhead_percentage': source_format.overhead_percentage,
                }
                res = {'value': format_vals}
        return res

    def onchange_currency_table(self, cr, uid, ids, currency_table_id, reporting_currency_id, context=None):
        values = {'reporting_currency': False}
        if reporting_currency_id:
            # it can be a currency from another table
            reporting_currency = self.pool.get('res.currency').browse(cr, uid, reporting_currency_id, context=context)
            # Search if the currency is in the table, and active
            if reporting_currency.reference_currency_id:
                currency_results = self.pool.get('res.currency').search(cr, uid, [('reference_currency_id', '=', reporting_currency.reference_currency_id.id),
                                                                                  ('currency_table_id', '=', currency_table_id),
                                                                                  ('active', '=', True)], context=context)
            else:
                currency_results = self.pool.get('res.currency').search(cr, uid, [('reference_currency_id', '=', reporting_currency_id),
                                                                                  ('currency_table_id', '=', currency_table_id),
                                                                                  ('active', '=', True)], context=context)
            if len(currency_results) > 0:
                # it's here, we keep the currency
                values['reporting_currency'] = reporting_currency_id
        # Restrain domain to selected table (or None if none selected
        domains = {'reporting_currency': [('currency_table_id', '=', currency_table_id)]}
        return {'value': values, 'domain': domains}

    def onchange_date(self, cr, uid, ids, eligibility_from_date, eligibility_to_date):
        """ This function will be called on the change of dates of the financing contract"""
        if eligibility_from_date and eligibility_to_date:
            if eligibility_from_date >= eligibility_to_date:
                warning = {
                    'title': _('Error'),
                    'message': _("The 'Eligibility Date From' should be sooner than the 'Eligibility Date To'.")
                }
                return {'warning': warning}
        return {}

    def create_reporting_line(self, cr, uid, browse_contract, browse_format_line, parent_report_line_id=None, context=None):
        format_line_obj = self.pool.get('financing.contract.format.line')
        reporting_line_obj = self.pool.get('financing.contract.donor.reporting.line')
        analytic_domain = format_line_obj._get_analytic_domain(cr,
                                                               uid,
                                                               browse_format_line,
                                                               browse_contract.reporting_type,
                                                               True,
                                                               context=context)
        vals = {'name': browse_format_line.name,
                'code': browse_format_line.code,
                'line_type': browse_format_line.line_type,
                'allocated_budget': round(browse_format_line.allocated_budget),
                'project_budget': round(browse_format_line.project_budget),
                'allocated_real': round(browse_format_line.allocated_real),
                'project_real': round(browse_format_line.project_real),

                'project_balance': round(browse_format_line.project_budget) -  round(browse_format_line.project_real),
                'allocated_balance': round(browse_format_line.allocated_budget) - round(browse_format_line.allocated_real),

                'analytic_domain': analytic_domain,
                'parent_id': parent_report_line_id}
        reporting_line_id = reporting_line_obj.create(cr,
                                                      uid,
                                                      vals,
                                                      context=context)
        # create child lines
        for child_line in browse_format_line.child_ids:
            self.create_reporting_line(cr, uid, browse_contract, child_line, reporting_line_id, context=context)
        return reporting_line_id

    def menu_interactive_report(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        # we update the context with the contract reporting type
        contract = self.browse(cr, uid, ids[0], context=context)
        context.update({'reporting_currency': contract.reporting_currency.id,
                        'reporting_type': contract.reporting_type,
                        'currency_table_id': contract.currency_table_id.id,
                        'active_id': ids[0],
                        'active_ids': ids,
                        'display_fp': True})
        ## INFO: display_fp in context permits to display Funding Pool column and its attached cost center.
        reporting_line_obj = self.pool.get('financing.contract.donor.reporting.line')
        # Create reporting lines
        # Contract line first (we'll fill it later)
        contract_line_id = reporting_line_obj.create(cr,
                                                     uid,
                                                     vals = {'name': contract.name,
                                                             'code': contract.code,
                                                             'line_type': 'view'},
                                                     context=context)

        # Values to be set
        allocated_budget = 0
        project_budget = 0
        allocated_real = 0
        project_real = 0
        project_balance = 0
        allocated_balance = 0

        # create "real" lines
        for line in contract.actual_line_ids:
            if not line.parent_id:
                # UTP-853: self.create_reporting_line rounds each line
                # (int value) so we add a round for sums equivalence
                allocated_budget += round(line.allocated_budget)
                project_budget += round(line.project_budget)
                allocated_real += round(line.allocated_real)
                project_real += round(line.project_real)
                reporting_line_id = self.create_reporting_line(cr, uid, contract, line, contract_line_id, context=context)

        # Refresh contract line with general infos
        analytic_domain = self.get_contract_domain(cr, uid, contract, context=context)

        allocated_balance  = allocated_budget - allocated_real
        project_balance= project_budget - project_real

        contract_values = {'allocated_budget': allocated_budget,
                           'project_budget': project_budget,
                           'allocated_real': allocated_real,
                           'project_real': project_real,

                            'allocated_balance': allocated_balance,
                            'project_balance': project_balance,

                           'analytic_domain': analytic_domain}
        reporting_line_obj.write(cr, uid, [contract_line_id], vals=contract_values, context=context)

        # retrieve the corresponding_view
        model_data_obj = self.pool.get('ir.model.data')
        view_id = False
        view_ids = model_data_obj.search(cr, uid,
                                        [('module', '=', 'financing_contract'),
                                         ('name', '=', 'view_donor_reporting_line_tree_%s' % str(contract.reporting_type))],
                                        offset=0, limit=1)
        if len(view_ids) > 0:
            view_id = model_data_obj.browse(cr, uid, view_ids[0]).res_id
        return {
               'type': 'ir.actions.act_window',
               'res_model': 'financing.contract.donor.reporting.line',
               'view_type': 'tree',
               'view_id': [view_id],
               'target': 'current',
               'domain': [('id', '=', contract_line_id)],
               'context': context
        }

    def menu_allocated_expense_report(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        wiz_obj = self.pool.get('wizard.expense.report')
        wiz_id = wiz_obj.create(cr, uid, {'reporting_type': 'allocated',
                                          'filename': 'allocated_expenses.csv',
                                          'contract_id': ids[0]}, context=context)
        # we open a wizard
        return {
                'type': 'ir.actions.act_window',
                'res_model': 'wizard.expense.report',
                'view_type': 'form',
                'view_mode': 'form',
                'target': 'new',
                'res_id': [wiz_id],
                'context': context,
        }

    def menu_project_expense_report(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        wiz_obj = self.pool.get('wizard.expense.report')
        wiz_id = wiz_obj.create(cr, uid, {'reporting_type': 'project',
                                          'filename': 'project_expenses.csv',
                                          'contract_id': ids[0]}, context=context)
        # we open a wizard
        return {
                'type': 'ir.actions.act_window',
                'res_model': 'wizard.expense.report',
                'view_type': 'form',
                'view_mode': 'form',
                'target': 'new',
                'res_id': [wiz_id],
                'context': context,
        }

    def menu_csv_interactive_report(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        wiz_obj = self.pool.get('wizard.interactive.report')
        wiz_id = wiz_obj.create(cr, uid, {'filename': 'interactive_report.csv',
                                          'contract_id': ids[0]}, context=context)
        # we open a wizard
        return {
                'type': 'ir.actions.act_window',
                'res_model': 'wizard.interactive.report',
                'view_type': 'form',
                'view_mode': 'form',
                'target': 'new',
                'res_id': [wiz_id],
                'context': context,
        }

    def create(self, cr, uid, vals, context=None):
        # Do not copy lines from the Donor on create if coming from the sync server
        if context is None:
            context = {}
        result = super(financing_contract_contract, self).create(cr, uid, vals, context=context)
        if not context.get('sync_update_execution'):
            contract = self.browse(cr, uid, result, context=context)
            if contract.donor_id and contract.donor_id.format_id and contract.format_id:
                self.pool.get('financing.contract.format').copy_format_lines(cr, uid, contract.donor_id.format_id.id, contract.format_id.id, context=context)
        return result


    def write(self, cr, uid, ids, vals, context=None):
        if 'donor_id' in vals:
            donor = self.pool.get('financing.contract.donor').browse(cr, uid, vals['donor_id'], context=context)
            for contract in self.browse(cr, uid, ids, context=context):
                if contract.donor_id and contract.format_id and vals['donor_id'] != contract.donor_id.id:
                    self.pool.get('financing.contract.format').copy_format_lines(cr, uid, donor.format_id.id, contract.format_id.id, context=context)

        if 'funding_pool_ids' in vals: # When the FP is added into the contract, then set this flag into the database
            vals['fp_added_flag'] = True

        # check if the flag has been set TRUE in the previous save
        fp_added_flag = self.browse(cr, uid, ids[0], context=context).fp_added_flag
        if 'format_id' in vals and fp_added_flag: # if the flag is TRUE, and there is a format
            format_obj = self.pool.get('financing.contract.format')
            f_value = format_obj.browse(cr, uid, vals['format_id'], context=context)

            # if there is some FP in this contract format, then perform the "recovery" of cost center ids, if not just use the one from the form
            if f_value.funding_pool_ids:
                cc_rows = f_value.cost_center_ids # retrieve all the cc stored previously in the DB
                cc_ids = []
                for cc in cc_rows:
                    cc_ids.append(cc.id)
                vals['cost_center_ids'] = [(6,0,cc_ids)] # this will be used at final value of cc list to this contract

        res = super(financing_contract_contract, self).write(cr, uid, ids, vals, context=context)
        if fp_added_flag: # if the previous save has been recovered thanks to the flag set to True, then reset it back to False
            cr.execute('''update financing_contract_contract set fp_added_flag = 'f' where id = %s''' % (ids[0]))

        # uf-2342 delete any assigned quads that are no longer valid due to changes in the contract
        # get list of all valid ids for this contract
        format =  self.browse(cr,uid,ids,context=context)[0].format_id
        funding_pool_ids = [x.funding_pool_id.id for x in format.funding_pool_ids]
        cost_center_ids = [x.id for x in format.cost_center_ids]

        quad_obj = self.pool.get('financing.contract.account.quadruplet')
        valid_quad_ids = quad_obj.search(cr, uid, [('funding_pool_id','in',funding_pool_ids),('cost_center_id','in',cost_center_ids)], context=context)

        # filter current assignments and re-write entries if necessary
        format_obj = self.pool.get('financing.contract.format')
        format_line_obj = self.pool.get('financing.contract.format.line')
        format_browse = format_obj.browse(cr, uid, format.id, context=context)
        for format_line in format_browse.actual_line_ids:
            account_quadruplet_ids = [account_quadruplet.id for account_quadruplet in format_line.account_quadruplet_ids]
            filtered_quads = [x for x in account_quadruplet_ids if x in valid_quad_ids]
            list_diff = set(account_quadruplet_ids).symmetric_difference(set(filtered_quads))
            if list_diff:
                ret = format_line_obj.write(cr, uid, format_line.id, {'account_quadruplet_ids': [(6, 0, filtered_quads)]}, context=context)
        return res

financing_contract_contract()

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: