This file is indexed.

/usr/lib/python2.7/dist-packages/trytond/modules/project_invoice/work.py is in tryton-modules-project-invoice 3.4.0-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
#This file is part of Tryton.  The COPYRIGHT file at the top level of
#this repository contains the full copyright notices and license terms.
from itertools import groupby
from decimal import Decimal
from sql.aggregate import Sum

from trytond.model import ModelView, fields
from trytond.pool import PoolMeta
from trytond.pyson import Eval, Bool, PYSONEncoder
from trytond.pool import Pool
from trytond.transaction import Transaction
from trytond.wizard import Wizard, StateAction
from trytond.tools import reduce_ids, grouped_slice


__all__ = ['Work', 'OpenInvoice']
__metaclass__ = PoolMeta

INVOICE_METHODS = [
    ('manual', 'Manual'),
    ('effort', 'On Effort'),
    ('timesheet', 'On Timesheet'),
    ]


class Work:
    __name__ = 'project.work'
    project_invoice_method = fields.Selection(INVOICE_METHODS,
        'Invoice Method',
        states={
            'readonly': Bool(Eval('invoiced_hours')),
            'required': Eval('type') == 'project',
            'invisible': Eval('type') != 'project',
            },
        depends=['invoiced_hours', 'type'])
    invoice_method = fields.Function(fields.Selection(INVOICE_METHODS,
            'Invoice Method'), 'get_invoice_method')
    invoiced_hours = fields.Function(fields.Float('Invoiced Hours',
            digits=(16, 2),
            states={
                'invisible': Eval('invoice_method') == 'manual',
                },
            depends=['invoice_method']), 'get_invoice_values')
    hours_to_invoice = fields.Function(fields.Float('Hours to Invoice',
            digits=(16, 2),
            states={
                'invisible': Eval('invoice_method') == 'manual',
                },
            depends=['invoice_method']), 'get_invoice_values')
    invoiced_amount = fields.Function(fields.Numeric('Invoiced Amount',
            digits=(16, Eval('currency_digits', 2)),
            states={
                'invisible': Eval('invoice_method') == 'manual',
                },
            depends=['currency_digits', 'invoice_method']),
        'get_invoice_values')
    invoice_line = fields.Many2One('account.invoice.line', 'Invoice Line',
        readonly=True)

    @classmethod
    def __setup__(cls):
        super(Work, cls).__setup__()
        cls._buttons.update({
                'invoice': {
                    'invisible': ((Eval('type') != 'project')
                        | (Eval('project_invoice_method', 'manual')
                            == 'manual')),
                    'readonly': ~Eval('hours_to_invoice'),
                    },
                })
        cls._error_messages.update({
                'missing_product': 'There is no product on work "%s".',
                'missing_list_price': 'There is no list price on work "%s".',
                'missing_party': 'There is no party on work "%s".',
                })

    @staticmethod
    def default_project_invoice_method():
        return 'manual'

    @classmethod
    def copy(cls, records, default=None):
        if default is None:
            default = {}
        default = default.copy()
        default.setdefault('invoice_line', None)
        return super(Work, cls).copy(records, default=default)

    def get_invoice_method(self, name):
        if self.type == 'project':
            return self.project_invoice_method
        elif self.parent:
            return self.parent.invoice_method
        else:
            return 'manual'

    @staticmethod
    def default_invoiced_hours():
        return 0.

    @staticmethod
    def _get_invoiced_hours_manual(works):
        return {}

    @staticmethod
    def _get_invoiced_hours_effort(works):
        return dict((w.id, w.effort) for w in works
            if w.invoice_line)

    @classmethod
    def _get_invoiced_hours_timesheet(cls, works):
        return cls._get_hours_timesheet(works, True)

    @staticmethod
    def default_hours_to_invoice():
        return 0.

    @staticmethod
    def _get_hours_to_invoice_manual(works):
        return {}

    @staticmethod
    def _get_hours_to_invoice_effort(works):
        return dict((w.id, w.effort) for w in works
            if w.state == 'done' and not w.invoice_line)

    @classmethod
    def _get_hours_to_invoice_timesheet(cls, works):
        return cls._get_hours_timesheet(works, False)

    @staticmethod
    def default_invoiced_amount():
        return Decimal(0)

    @staticmethod
    def _get_invoiced_amount_manual(works):
        return {}

    @staticmethod
    def _get_invoiced_amount_effort(works):
        pool = Pool()
        InvoiceLine = pool.get('account.invoice.line')

        invoice_lines = InvoiceLine.browse([
                w.invoice_line.id for w in works
                if w.invoice_line])

        id2invoice_lines = dict((l.id, l) for l in invoice_lines)
        amounts = {}
        for work in works:
            if work.invoice_line:
                invoice_line = id2invoice_lines[work.invoice_line.id]
                amounts[work.id] = invoice_line.amount
            else:
                amounts[work.id] = Decimal(0)
        return amounts

    @staticmethod
    def _get_invoiced_amount_timesheet(works):
        pool = Pool()
        InvoiceLine = pool.get('account.invoice.line')

        invoice_lines = InvoiceLine.browse([
                t.invoice_line.id for w in works
                for t in w.work.timesheet_lines
                if t.invoice_line])

        id2invoice_lines = dict((l.id, l) for l in invoice_lines)
        amounts = {}
        for work in works:
            amounts[work.id] = Decimal(0)
            for timesheet_line in work.work.timesheet_lines:
                if not timesheet_line.invoice_line:
                    continue
                invoice_line = id2invoice_lines[timesheet_line.invoice_line.id]
                amounts[work.id] += (invoice_line.unit_price
                    * Decimal(str(timesheet_line.hours)))
        return amounts

    @staticmethod
    def _get_hours_timesheet(works, invoiced):
        pool = Pool()
        TimesheetLine = pool.get('timesheet.line')
        cursor = Transaction().cursor
        line = TimesheetLine.__table__()

        hours = {}
        twork2work = dict((w.work.id, w.id) for w in works)
        ids = twork2work.keys()
        for sub_ids in grouped_slice(ids):
            red_sql = reduce_ids(line.work, sub_ids)
            if invoiced:
                where = line.invoice_line != None
            else:
                where = line.invoice_line == None
            cursor.execute(*line.select(line.work, Sum(line.hours),
                    where=red_sql & where,
                    group_by=line.work))
            hours.update(dict((twork2work[w], h)
                    for w, h in cursor.fetchall()))
        return hours

    @classmethod
    def get_invoice_values(cls, works, name):
        works += cls.search([
                ('parent', 'child_of', [w.id for w in works]),
                ])

        values = {}
        method2works = {}
        for work in works:
            method2works.setdefault(work.invoice_method, []).append(work)
        for method, m_works in method2works.iteritems():
            method = getattr(cls, '_get_%s_%s' % (name, method))
            values.update(method(m_works))

        default = getattr(cls, 'default_%s' % name)()
        return cls.sum_tree(works, lambda w: values.get(w.id, default))

    @classmethod
    @ModelView.button
    def invoice(cls, works):
        pool = Pool()
        Invoice = pool.get('account.invoice')

        invoices = []
        for work in works:
            invoice_lines = work._get_lines_to_invoice()
            if not invoice_lines:
                continue
            invoice = work._get_invoice()
            invoice.save()
            invoices.append(invoice)
            for key, lines in groupby(invoice_lines,
                    key=work._group_lines_to_invoice_key):
                lines = list(lines)
                key = dict(key)
                invoice_line = work._get_invoice_line(key, invoice, lines)
                invoice_line.invoice = invoice.id
                invoice_line.save()
                origins = {}
                for line in lines:
                    origin = line['origin']
                    origins.setdefault(origin.__class__, []).append(origin)
                for klass, records in origins.iteritems():
                    klass.write(records, {
                            'invoice_line': invoice_line.id,
                            })
        Invoice.update_taxes(invoices)

    def _get_invoice(self):
        "Return invoice for the work"
        pool = Pool()
        Invoice = pool.get('account.invoice')
        Journal = pool.get('account.journal')

        journals = Journal.search([
                ('type', '=', 'revenue'),
                ], limit=1)
        if journals:
            journal, = journals
        else:
            journal = None

        if not self.party:
            self.raise_user_error('missing_party', (self.rec_name,))

        return Invoice(
            company=self.company,
            type='out_invoice',
            journal=journal,
            party=self.party,
            invoice_address=self.party.address_get(type='invoice'),
            currency=self.company.currency,
            account=self.party.account_receivable,
            payment_term=self.party.customer_payment_term,
            description=self.work.name,
            )

    def _group_lines_to_invoice_key(self, line):
        "The key to group lines"
        return (('product', line['product']),
            ('unit_price', line['unit_price']),
            ('description', line['description']))

    def _get_invoice_line(self, key, invoice, lines):
        "Return a invoice line for the lines"
        pool = Pool()
        InvoiceLine = pool.get('account.invoice.line')
        ModelData = pool.get('ir.model.data')
        Uom = pool.get('product.uom')

        hour = Uom(ModelData.get_id('product', 'uom_hour'))
        quantity = sum(l['quantity'] for l in lines)
        product = key['product']

        invoice_line = InvoiceLine()
        invoice_line.type = 'line'
        invoice_line.quantity = Uom.compute_qty(hour, quantity,
            product.default_uom)
        invoice_line.unit = product.default_uom
        invoice_line.product = product
        invoice_line.description = key['description']
        invoice_line.account = product.account_revenue_used
        invoice_line.unit_price = Uom.compute_price(hour, key['unit_price'],
            product.default_uom)

        taxes = []
        pattern = invoice_line._get_tax_rule_pattern()
        party = invoice.party
        for tax in product.customer_taxes_used:
            if party.customer_tax_rule:
                tax_ids = party.customer_tax_rule.apply(tax, pattern)
                if tax_ids:
                    taxes.extend(tax_ids)
                continue
            taxes.append(tax.id)
        if party.customer_tax_rule:
            tax_ids = party.customer_tax_rule.apply(None, pattern)
            if tax_ids:
                taxes.extend(tax_ids)
        invoice_line.taxes = taxes
        return invoice_line

    def _get_lines_to_invoice_manual(self):
        return []

    def _get_lines_to_invoice_effort(self):
        if not self.invoice_line and self.effort and self.state == 'done':
            if not self.product:
                self.raise_user_error('missing_product', (self.rec_name,))
            elif self.list_price is None:
                self.raise_user_error('missing_list_price', (self.rec_name,))
            return [{
                    'product': self.product,
                    'quantity': self.effort,
                    'unit_price': self.list_price,
                    'origin': self,
                    'description': self.work.name,
                    }]
        return []

    def _get_lines_to_invoice_timesheet(self):
        if self.work.timesheet_lines:
            if not self.product:
                self.raise_user_error('missing_product', (self.rec_name,))
            elif self.list_price is None:
                self.raise_user_error('missing_list_price', (self.rec_name,))
            return [{
                    'product': self.product,
                    'quantity': l.hours,
                    'unit_price': self.list_price,
                    'origin': l,
                    'description': self.work.name,
                    } for l in self.work.timesheet_lines
                if not l.invoice_line]
        return []

    def _test_group_invoice(self):
        return (self.company, self.party)

    def _get_lines_to_invoice(self, test=None):
        "Return lines for work and children"
        lines = []
        if test is None:
            test = self._test_group_invoice()
        lines += getattr(self, '_get_lines_to_invoice_%s' %
            self.invoice_method)()
        for children in self.children:
            if children.type == 'project':
                if test != children._test_group_invoice():
                    continue
            lines += children._get_lines_to_invoice(test=test)
        return lines


class OpenInvoice(Wizard):
    'Open Invoice'
    __name__ = 'project.open_invoice'
    start_state = 'open_'
    open_ = StateAction('account_invoice.act_invoice_form')

    def do_open_(self, action):
        pool = Pool()
        Work = pool.get('project.work')
        works = Work.search([
                ('parent', 'child_of', Transaction().context['active_ids']),
                ])
        invoice_ids = set()
        for work in works:
            if work.invoice_line and work.invoice_line.invoice:
                invoice_ids.add(work.invoice_line.invoice.id)
            for timesheet_line in work.work.timesheet_lines:
                if (timesheet_line.invoice_line
                        and timesheet_line.invoice_line.invoice):
                    invoice_ids.add(timesheet_line.invoice_line.invoice.id)
        encoder = PYSONEncoder()
        action['pyson_domain'] = encoder.encode(
            [('id', 'in', list(invoice_ids))])
        action['pyson_search_value'] = encoder.encode([])
        return action, {}