forked from OCA/l10n-brazil
-
Notifications
You must be signed in to change notification settings - Fork 0
/
account_invoice.py
1541 lines (1393 loc) · 72.1 KB
/
account_invoice.py
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
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- encoding: utf-8 -*-
###############################################################################
# #
# Copyright (C) 2009 Renato Lima - Akretion #
# #
#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/>. #
###############################################################################
from lxml import etree
import time
from openerp import netsvc
from openerp.osv import orm, fields
from openerp.tools.translate import _
from openerp.addons import decimal_precision as dp
from sped.nfe.validator import txt
OPERATION_TYPE = {
'out_invoice': 'output',
'in_invoice': 'input',
'out_refund': 'input',
'in_refund': 'output'
}
JOURNAL_TYPE = {
'out_invoice': 'sale',
'in_invoice': 'purchase',
'out_refund': 'sale_refund',
'in_refund': 'purchase_refund'
}
class account_invoice(orm.Model):
_inherit = 'account.invoice'
def _amount_all(self, cr, uid, ids, name, args, context=None):
res = {}
for invoice in self.browse(cr, uid, ids, context=context):
res[invoice.id] = {
'amount_untaxed': 0.0,
'amount_tax': 0.0,
'amount_tax_discount': 0.0,
'amount_total': 0.0,
'icms_base': 0.0,
'icms_value': 0.0,
'icms_st_base': 0.0,
'icms_st_value': 0.0,
'ipi_base': 0.0,
'ipi_value': 0.0,
'pis_base': 0.0,
'pis_value': 0.0,
'cofins_base': 0.0,
'cofins_value': 0.0,
'ii_value': 0.0,
'amount_insurance': 0.0,
'amount_freight': 0.0,
'amount_costs': 0.0,
'amount_gross': 0.0,
'amount_discount': 0.0,
}
for line in invoice.invoice_line:
res[invoice.id]['amount_untaxed'] += line.price_total
res[invoice.id]['icms_base'] += line.icms_base
res[invoice.id]['icms_value'] += line.icms_value
res[invoice.id]['icms_st_base'] += line.icms_st_base
res[invoice.id]['icms_st_value'] += line.icms_st_value
res[invoice.id]['ipi_base'] += line.ipi_base
res[invoice.id]['ipi_value'] += line.ipi_value
res[invoice.id]['pis_base'] += line.pis_base
res[invoice.id]['pis_value'] += line.pis_value
res[invoice.id]['cofins_base'] += line.cofins_base
res[invoice.id]['cofins_value'] += line.cofins_value
res[invoice.id]['ii_value'] += line.ii_value
res[invoice.id]['amount_insurance'] += line.insurance_value
res[invoice.id]['amount_freight'] += line.freight_value
res[invoice.id]['amount_costs'] += line.other_costs_value
res[invoice.id]['amount_gross'] += line.price_gross
res[invoice.id]['amount_discount'] += line.discount_value
for invoice_tax in invoice.tax_line:
if not invoice_tax.tax_code_id.tax_discount:
res[invoice.id]['amount_tax'] += invoice_tax.amount
res[invoice.id]['amount_total'] = res[invoice.id]['amount_tax'] + res[invoice.id]['amount_untaxed']
return res
def _get_fiscal_type(self, cr, uid, context=None):
if context is None:
context = {}
return context.get('fiscal_type', 'product')
# TODO - Melhorar esse método!
def fields_view_get(self, cr, uid, view_id=None, view_type=False,
context=None, toolbar=False, submenu=False):
result = super(account_invoice, self).fields_view_get(
cr, uid, view_id=view_id, view_type=view_type, context=context,
toolbar=toolbar, submenu=submenu)
if context is None:
context = {}
if not view_type:
view_id = self.pool.get('ir.ui.view').search(
cr, uid, [('name', '=', 'account.invoice.tree')])
view_type = 'tree'
if view_type == 'form':
eview = etree.fromstring(result['arch'])
if 'type' in context.keys():
fiscal_types = eview.xpath("//field[@name='invoice_line']")
for fiscal_type in fiscal_types:
fiscal_type.set(
'context', "{'type': '%s', 'fiscal_type': '%s'}" % (
context['type'],
context.get('fiscal_type', 'product')))
fiscal_categories = eview.xpath("//field[@name='fiscal_category_id']")
for fiscal_category_id in fiscal_categories:
fiscal_category_id.set('domain',
"[('fiscal_type', '=', '%s'), \
('type', '=', '%s'), \
('journal_type', '=', '%s')]" \
% (context.get('fiscal_type', 'product'),
OPERATION_TYPE[context['type']],
JOURNAL_TYPE[context['type']]))
fiscal_category_id.set('required', '1')
document_series = eview.xpath("//field[@name='document_serie_id']")
for document_serie_id in document_series:
document_serie_id.set('domain', "[('fiscal_type', '=', '%s')]" % (context.get('fiscal_type', 'product')))
if context.get('fiscal_type', False):
delivery_infos = eview.xpath("//group[@name='delivery_info']")
for delivery_info in delivery_infos:
delivery_info.set('invisible', '1')
result['arch'] = etree.tostring(eview)
if view_type == 'tree':
doc = etree.XML(result['arch'])
nodes = doc.xpath("//field[@name='partner_id']")
partner_string = _('Customer')
if context.get('type', 'out_invoice') in ('in_invoice', 'in_refund'):
partner_string = _('Supplier')
for node in nodes:
node.set('string', partner_string)
result['arch'] = etree.tostring(doc)
return result
def _get_invoice_line(self, cr, uid, ids, context=None):
result = {}
for line in self.pool.get('account.invoice.line').browse(
cr, uid, ids, context=context):
result[line.invoice_id.id] = True
return result.keys()
def _get_invoice_tax(self, cr, uid, ids, context=None):
result = {}
for tax in self.pool.get('account.invoice.tax').browse(
cr, uid, ids, context=context):
result[tax.invoice_id.id] = True
return result.keys()
def _get_cfops(self, cr, uid, ids, name, arg, context=None):
result = {}
for invoice in self.browse(cr, uid, ids, context=context):
result[invoice.id] = []
new_ids = []
for line in invoice.invoice_line:
if line.cfop_id and not line.cfop_id.id in new_ids:
new_ids.append(line.cfop_id.id)
new_ids.sort()
result[invoice.id] = new_ids
return result
def _get_receivable_lines(self, cr, uid, ids, name, arg, context=None):
res = {}
for invoice in self.browse(cr, uid, ids, context=context):
res[invoice.id] = []
if not invoice.move_id:
continue
data_lines = [x for x in invoice.move_id.line_id if x.account_id.id == invoice.account_id.id and x.account_id.type in ('receivable', 'payable') and invoice.journal_id.revenue_expense]
New_ids = []
for line in data_lines:
New_ids.append(line.id)
New_ids.sort()
res[invoice.id] = New_ids
return res
_columns = {
'partner_shipping_id': fields.many2one(
'res.partner', 'Delivery Address',
readonly=True, required=True,
states={'draft': [('readonly', False)]},
help="Delivery address for current sales order."),
'state': fields.selection([
('draft', 'Draft'),
('proforma', 'Pro-forma'),
('proforma2', 'Pro-forma'),
('sefaz_export', 'Enviar para Receita'),
('sefaz_exception', 'Erro de autorização da Receita'),
('open', 'Open'),
('paid', 'Paid'),
('cancel', 'Cancelled')
], 'State', select=True, readonly=True,
help=' * The \'Draft\' state is used when a user is encoding a new and unconfirmed Invoice. \
\n* The \'Pro-forma\' when invoice is in Pro-forma state,invoice does not have an invoice number. \
\n* The \'Open\' state is used when user create invoice,a invoice number is generated.Its in open state till user does not pay invoice. \
\n* The \'Paid\' state is set automatically when invoice is paid.\
\n* The \'sefaz_out\' Gerado aquivo de exportação para sistema daReceita.\
\n* The \'sefaz_aut\' Recebido arquivo de autolização da Receita.\
\n* The \'Cancelled\' state is used when user cancel invoice.'),
'partner_shipping_id': fields.many2one('res.partner', 'Endereço de Entrega', readonly=True, states={'draft': [('readonly', False)]}, help="Shipping address for current sales order."),
'issuer': fields.selection(
[('0', 'Emissão própria'),
('1', 'Terceiros')], 'Emitente', readonly=True,
states={'draft': [('readonly', False)]}),
'nfe_purpose': fields.selection(
[('1', 'Normal'),
('2', 'Complementar'),
('3', 'Ajuste')], 'Finalidade da Emissão', readonly=True,
states={'draft': [('readonly', False)]}),
'internal_number': fields.char('Invoice Number', size=32,
readonly=True,
states={'draft': [('readonly', False)]},
help="Unique number of the invoice, \
computed automatically when the \
invoice is created."),
'vendor_serie': fields.char('Série NF Entrada', size=12, readonly=True,
states={'draft': [('readonly', False)]},
help="Série do número da Nota Fiscal do \
Fornecedor"),
'nfe_access_key': fields.char(
'Chave de Acesso NFE', size=44,
readonly=True, states={'draft': [('readonly', False)]}),
'nfe_status': fields.char('Status na Sefaz', size=44, readonly=True),
'nfe_date': fields.datetime('Data do Status NFE', readonly=True),
'nfe_export_date': fields.datetime('Exportação NFE', readonly=True),
'fiscal_document_id': fields.many2one(
'l10n_br_account.fiscal.document', 'Documento', readonly=True,
states={'draft': [('readonly', False)]}),
'fiscal_document_electronic': fields.related(
'fiscal_document_id', 'electronic', type='boolean', readonly=True,
relation='l10n_br_account.fiscal.document', store=True,
string='Electronic'),
'fiscal_type': fields.selection([('product', 'Produto'),
('service', 'Serviço')],
'Tipo Fiscal', requeried=True),
'move_line_receivable_id': fields.function(
_get_receivable_lines, method=True, type='many2many',
relation='account.move.line', string='Entry Lines'),
'document_serie_id': fields.many2one(
'l10n_br_account.document.serie', 'Série',
domain="[('fiscal_document_id','=',fiscal_document_id),\
('company_id','=',company_id)]", readonly=True,
states={'draft': [('readonly', False)]}),
'fiscal_category_id': fields.many2one(
'l10n_br_account.fiscal.category', 'Categoria', readonly=True,
states={'draft': [('readonly', False)]}),
'fiscal_position': fields.many2one(
'account.fiscal.position', 'Fiscal Position', readonly=True,
states={'draft': [('readonly', False)]},
domain="[('fiscal_category_id','=',fiscal_category_id)]"),
'cfop_ids': fields.function(
_get_cfops, method=True, type='many2many',
relation='l10n_br_account.cfop', string='CFOP'),
'fiscal_document_related_ids': fields.one2many(
'l10n_br_account.document.related', 'invoice_id',
'Fiscal Document Related', readonly=True,
states={'draft': [('readonly', False)]}),
'carrier_name': fields.char('Nome Transportadora', size=32),
'vehicle_plate': fields.char('Placa do Veiculo', size=7),
'vehicle_state_id': fields.many2one(
'res.country.state', 'UF da Placa'),
'vehicle_l10n_br_city_id': fields.many2one('l10n_br_base.city',
'Municipio', domain="[('state_id', '=', vehicle_state_id)]"),
'amount_gross': fields.function(
_amount_all, method=True,
digits_compute=dp.get_precision('Account'), string='Vlr. Bruto',
store={
'account.invoice': (lambda self, cr, uid, ids, c={}: ids,
['invoice_line'], 20),
'account.invoice.tax': (_get_invoice_tax, None, 20),
'account.invoice.line': (
_get_invoice_line, ['price_unit',
'invoice_line_tax_id',
'quantity', 'discount'], 20),
}, multi='all'),
'amount_discount': fields.function(
_amount_all, method=True,
digits_compute=dp.get_precision('Account'), string='Desconto',
store={
'account.invoice': (lambda self, cr, uid, ids, c={}: ids,
['invoice_line'], 20),
'account.invoice.tax': (_get_invoice_tax, None, 20),
'account.invoice.line': (
_get_invoice_line, ['price_unit',
'invoice_line_tax_id',
'quantity', 'discount'], 20),
}, multi='all'),
'amount_untaxed': fields.function(
_amount_all, method=True,
digits_compute=dp.get_precision('Account'), string='Untaxed',
store={
'account.invoice': (lambda self, cr, uid, ids, c={}: ids,
['invoice_line'], 20),
'account.invoice.tax': (_get_invoice_tax, None, 20),
'account.invoice.line': (
_get_invoice_line, ['price_unit',
'invoice_line_tax_id',
'quantity', 'discount'], 20),
}, multi='all'),
'amount_tax': fields.function(
_amount_all, method=True,
digits_compute=dp.get_precision('Account'), string='Tax',
store={
'account.invoice': (lambda self, cr, uid, ids, c={}: ids,
['invoice_line'], 20),
'account.invoice.tax': (_get_invoice_tax, None, 20),
'account.invoice.line': (_get_invoice_line,
['price_unit',
'invoice_line_tax_id',
'quantity', 'discount'], 20),
}, multi='all'),
'amount_total': fields.function(
_amount_all, method=True,
digits_compute=dp.get_precision('Account'), string='Total',
store={
'account.invoice': (lambda self, cr, uid, ids, c={}: ids,
['invoice_line'], 20),
'account.invoice.tax': (_get_invoice_tax, None, 20),
'account.invoice.line': (_get_invoice_line,
['price_unit',
'invoice_line_tax_id',
'quantity', 'discount'], 20),
}, multi='all'),
'icms_base': fields.function(
_amount_all, method=True,
digits_compute=dp.get_precision('Account'), string='Base ICMS',
store={
'account.invoice': (lambda self, cr, uid, ids, c={}: ids,
['invoice_line'], 20),
'account.invoice.tax': (_get_invoice_tax, None, 20),
'account.invoice.line': (_get_invoice_line,
['price_unit',
'invoice_line_tax_id',
'quantity', 'discount'], 20),
}, multi='all'),
'icms_value': fields.function(
_amount_all, method=True,
digits_compute=dp.get_precision('Account'), string='Valor ICMS',
store={
'account.invoice': (lambda self, cr, uid, ids, c={}: ids,
['invoice_line'], 20),
'account.invoice.tax': (_get_invoice_tax, None, 20),
'account.invoice.line': (_get_invoice_line,
['price_unit',
'invoice_line_tax_id',
'quantity', 'discount'], 20),
}, multi='all'),
'icms_st_base': fields.function(
_amount_all, method=True,
digits_compute=dp.get_precision('Account'), string='Base ICMS ST',
store={
'account.invoice': (lambda self, cr, uid, ids, c={}: ids,
['invoice_line'], 20),
'account.invoice.tax': (_get_invoice_tax, None, 20),
'account.invoice.line': (_get_invoice_line,
['price_unit',
'invoice_line_tax_id',
'quantity', 'discount'], 20),
},
multi='all'),
'icms_st_value': fields.function(
_amount_all, method=True,
digits_compute=dp.get_precision('Account'), string='Valor ICMS ST',
store={
'account.invoice': (lambda self, cr, uid, ids, c={}: ids,
['invoice_line'], 20),
'account.invoice.tax': (_get_invoice_tax, None, 20),
'account.invoice.line': (_get_invoice_line,
['price_unit',
'invoice_line_tax_id',
'quantity', 'discount'], 20),
}, multi='all'),
'ipi_base': fields.function(
_amount_all, method=True,
digits_compute=dp.get_precision('Account'), string='Base IPI',
store={
'account.invoice': (lambda self, cr, uid, ids, c={}: ids,
['invoice_line'], 20),
'account.invoice.tax': (_get_invoice_tax, None, 20),
'account.invoice.line': (_get_invoice_line,
['price_unit',
'invoice_line_tax_id',
'quantity', 'discount'], 20),
}, multi='all'),
'ipi_value': fields.function(
_amount_all, method=True,
digits_compute=dp.get_precision('Account'), string='Valor IPI',
store={
'account.invoice': (lambda self, cr, uid, ids, c={}: ids,
['invoice_line'], 20),
'account.invoice.tax': (_get_invoice_tax, None, 20),
'account.invoice.line': (_get_invoice_line,
['price_unit',
'invoice_line_tax_id',
'quantity', 'discount'], 20),
}, multi='all'),
'pis_base': fields.function(
_amount_all, method=True,
digits_compute=dp.get_precision('Account'), string='Base PIS',
store={
'account.invoice': (lambda self, cr, uid, ids, c={}: ids,
['invoice_line'], 20),
'account.invoice.tax': (_get_invoice_tax, None, 20),
'account.invoice.line': (_get_invoice_line,
['price_unit',
'invoice_line_tax_id',
'quantity', 'discount'], 20),
}, multi='all'),
'pis_value': fields.function(
_amount_all, method=True,
digits_compute=dp.get_precision('Account'), string='Valor PIS',
store={
'account.invoice': (lambda self, cr, uid, ids, c={}: ids,
['invoice_line'], 20),
'account.invoice.tax': (_get_invoice_tax, None, 20),
'account.invoice.line': (_get_invoice_line,
['price_unit',
'invoice_line_tax_id',
'quantity', 'discount'], 20),
}, multi='all'),
'cofins_base': fields.function(
_amount_all, method=True,
digits_compute=dp.get_precision('Account'), string='Base COFINS',
store={
'account.invoice': (lambda self, cr, uid, ids, c={}: ids,
['invoice_line'], 20),
'account.invoice.tax': (_get_invoice_tax, None, 20),
'account.invoice.line': (_get_invoice_line,
['price_unit',
'invoice_line_tax_id',
'quantity', 'discount'], 20),
}, multi='all'),
'cofins_value': fields.function(
_amount_all, method=True,
digits_compute=dp.get_precision('Account'), string='Valor COFINS',
store={
'account.invoice': (lambda self, cr, uid, ids, c={}: ids,
['invoice_line'], 20),
'account.invoice.tax': (_get_invoice_tax, None, 20),
'account.invoice.line': (_get_invoice_line,
['price_unit',
'invoice_line_tax_id',
'quantity', 'discount'], 20),
}, multi='all'),
'ii_value': fields.function(
_amount_all, method=True,
digits_compute=dp.get_precision('Account'), string='Valor II',
store={
'account.invoice': (lambda self, cr, uid, ids, c={}: ids,
['invoice_line'], 20),
'account.invoice.tax': (_get_invoice_tax, None, 20),
'account.invoice.line': (_get_invoice_line,
['price_unit',
'invoice_line_tax_id',
'quantity', 'discount'], 20),
}, multi='all'),
'weight': fields.float('Gross weight', readonly=True,
states={'draft': [('readonly', False)]},
help="The gross weight in Kg.",),
'weight_net': fields.float('Net weight', help="The net weight in Kg.",
readonly=True,
states={'draft': [('readonly', False)]}),
'number_of_packages': fields.integer(
'Volume', readonly=True, states={'draft': [('readonly', False)]}),
'amount_insurance': fields.function(
_amount_all, method=True,
digits_compute=dp.get_precision('Account'),
string='Valor do Seguro',
store={
'account.invoice': (lambda self, cr, uid, ids, c={}: ids,
['invoice_line'], 20),
'account.invoice.line': (_get_invoice_line,
['insurance_value'], 20),
}, multi='all'),
'amount_freight': fields.function(
_amount_all, method=True,
digits_compute=dp.get_precision('Account'),
string='Valor do Seguro',
store={
'account.invoice': (lambda self, cr, uid, ids, c={}: ids,
['invoice_line'], 20),
'account.invoice.line': (_get_invoice_line,
['freight_value'], 20),
}, multi='all'),
'amount_costs': fields.function(
_amount_all, method=True,
digits_compute=dp.get_precision('Account'), string='Outros Custos',
store={
'account.invoice': (lambda self, cr, uid, ids, c={}: ids,
['invoice_line'], 20),
'account.invoice.line': (_get_invoice_line,
['other_costs_value'], 20)}, multi='all')
}
def _default_fiscal_category(self, cr, uid, context=None):
DEFAULT_FCATEGORY_PRODUCT = {
'in_invoice': 'in_invoice_fiscal_category_id',
'out_invoice': 'out_invoice_fiscal_category_id',
'in_refund': 'in_refund_fiscal_category_id',
'out_refund': 'out_refund_fiscal_category_id'
}
DEFAULT_FCATEGORY_SERVICE = {
'in_invoice': 'in_invoice_service_fiscal_category_id',
'out_invoice': 'out_invoice_service_fiscal_category_id'
}
default_fo_category = {
'product': DEFAULT_FCATEGORY_PRODUCT,
'service': DEFAULT_FCATEGORY_SERVICE
}
invoice_type = context.get('type', 'out_invoice')
invoice_fiscal_type = context.get('fiscal_type', 'product')
user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
fcategory = self.pool.get('res.company').read(
cr, uid, user.company_id.id,
[default_fo_category[invoice_fiscal_type][invoice_type]],
context=context)[default_fo_category[invoice_fiscal_type][
invoice_type]]
return fcategory and fcategory[0] or False
def _default_fiscal_document(self, cr, uid, context):
invoice_fiscal_type = context.get('fiscal_type', 'product')
fiscal_invoice_id = invoice_fiscal_type + '_invoice_id'
user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
fiscal_document = self.pool.get('res.company').read(
cr, uid, user.company_id.id, [fiscal_invoice_id],
context=context)[fiscal_invoice_id]
return fiscal_document and fiscal_document[0] or False
def _default_fiscal_document_serie(self, cr, uid, context):
invoice_fiscal_type = context.get('fiscal_type', 'product')
fiscal_document_serie = False
user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
company = self.pool.get('res.company').browse(
cr, uid, user.company_id.id, context=context)
if invoice_fiscal_type == 'product':
fiscal_document_series = [doc_serie for doc_serie in
company.document_serie_product_ids if
doc_serie.fiscal_document_id.id ==
company.product_invoice_id.id and
doc_serie.active]
if fiscal_document_series:
fiscal_document_serie = fiscal_document_series[0].id
else:
fiscal_document_serie = company.document_serie_service_id and \
company.document_serie_service_id.id or False
return fiscal_document_serie
_defaults = {
'issuer': '0',
'nfe_purpose': '1',
'fiscal_type': _get_fiscal_type,
'fiscal_category_id': _default_fiscal_category,
'fiscal_document_id': _default_fiscal_document,
'document_serie_id': _default_fiscal_document_serie
}
def _check_invoice_number(self, cr, uid, ids, context=None):
if context is None:
context = {}
invoices = self.browse(cr, uid, ids, context=context)
domain = []
for invoice in invoices:
if not invoice.number:
continue
fiscal_document = invoice.fiscal_document_id and \
invoice.fiscal_document_id.id or False
domain.extend([('internal_number', '=', invoice.number),
('fiscal_type', '=', invoice.fiscal_type),
('fiscal_document_id', '=', fiscal_document)
])
if invoice.issuer == '0':
domain.extend(
[('company_id', '=', invoice.company_id.id),
('internal_number', '=', invoice.number),
('fiscal_document_id', '=', invoice.fiscal_document_id.id),
('issuer', '=', '0')])
else:
domain.extend(
[('partner_id', '=', invoice.partner_id.id),
('vendor_serie', '=', invoice.vendor_serie),
('issuer', '=', '1')])
invoice_id = self.pool.get('account.invoice').search(
cr, uid, domain)
if len(invoice_id) > 1:
return False
return True
_constraints = [
(_check_invoice_number,
u"Error!\nNão é possível registrar \
documentos fiscais com números repetidos.",
['number']),
]
def init(self, cr):
# Remove a constraint na coluna número do documento fiscal,
# no caso dos documentos de entradas dos fornecedores pode existir
# documentos fiscais de fornecedores diferentes com a mesma numeração
cr.execute("ALTER TABLE %s DROP CONSTRAINT IF EXISTS %s" % (
'account_invoice', 'account_invoice_number_uniq'))
# go from canceled state to draft state
def action_cancel_draft(self, cr, uid, ids, *args):
self.write(cr, uid, ids, {
'state': 'draft',
'internal_number': False,
'nfe_access_key': False,
'nfe_status': False,
'nfe_date': False,
'nfe_export_date': False})
wf_service = netsvc.LocalService("workflow")
for inv_id in ids:
wf_service.trg_delete(uid, 'account.invoice', inv_id, cr)
wf_service.trg_create(uid, 'account.invoice', inv_id, cr)
return True
def copy(self, cr, uid, id, default={}, context=None):
default.update({
'internal_number': False,
'nfe_access_key': False,
'nfe_status': False,
'nfe_date': False,
'nfe_export_date': False,
})
return super(account_invoice, self).copy(cr, uid, id, default, context)
def action_internal_number(self, cr, uid, ids, context=None):
if context is None:
context = {}
for inv in self.browse(cr, uid, ids):
if inv.issuer == '0':
sequence = self.pool.get('ir.sequence')
sequence_read = sequence.read(
cr, uid, inv.document_serie_id.internal_sequence_id.id,
['number_next'])
invalid_number = self.pool.get('l10n_br_account.invoice.invalid.number').search(
cr, uid, [('number_start', '<=', sequence_read['number_next']),
('number_end', '>=', sequence_read['number_next']),
('state', '=', 'done')])
if invalid_number:
raise orm.except_orm(
_(u'Número Inválido !'),
_("O número: %s da série: %s, esta inutilizado") % (
sequence_read['number_next'],
inv.document_serie_id.name))
seq_no = sequence.get_id(cr, uid, inv.document_serie_id.internal_sequence_id.id, context=context)
self.write(cr, uid, inv.id, {'internal_number': seq_no})
return True
def action_number(self, cr, uid, ids, context=None):
if context is None:
context = {}
#TODO: not correct fix but required a frech values before reading it.
self.write(cr, uid, ids, {})
for obj_inv in self.browse(cr, uid, ids, context=context):
inv_id = obj_inv.id
move_id = obj_inv.move_id and obj_inv.move_id.id or False
ref = obj_inv.internal_number or obj_inv.reference or ''
cr.execute('UPDATE account_move SET ref=%s '
'WHERE id=%s AND (ref is null OR ref = \'\')',
(ref, move_id))
cr.execute('UPDATE account_move_line SET ref=%s '
'WHERE move_id=%s AND (ref is null OR ref = \'\')',
(ref, move_id))
cr.execute('UPDATE account_analytic_line SET ref=%s '
'FROM account_move_line '
'WHERE account_move_line.move_id = %s '
'AND account_analytic_line.move_id = account_move_line.id',
(ref, move_id))
for inv_id, name in self.name_get(cr, uid, [inv_id]):
ctx = context.copy()
if obj_inv.type in ('out_invoice', 'out_refund'):
ctx = self.get_log_context(cr, uid, context=ctx)
message = _('Invoice ') + " '" + name + "' " + _("is validated.")
self.log(cr, uid, inv_id, message, context=ctx)
return True
def action_move_create(self, cr, uid, ids, *args):
result = super(account_invoice, self).action_move_create(cr, uid, ids, *args)
for inv in self.browse(cr, uid, ids):
if inv.move_id:
self.pool.get('account.move').write(cr, uid, [inv.move_id.id], {'ref': inv.internal_number})
for move_line in inv.move_id.line_id:
self.pool.get('account.move.line').write(cr, uid, [move_line.id], {'ref': inv.internal_number})
move_lines = [x for x in inv.move_id.line_id if x.account_id.id == inv.account_id.id and x.account_id.type in ('receivable', 'payable')]
i = len(move_lines)
for move_line in move_lines:
move_line_name = '%s/%s' % (inv.internal_number, i)
self.pool.get('account.move.line').write(cr, uid, [move_line.id], {'name': move_line_name})
i -= 1
return result
def nfe_check(self, cr, uid, ids, context=None):
result = txt.validate(cr, uid, ids, context)
return result
def _fiscal_position_map(self, cr, uid, result, context=None, **kwargs):
if not context:
context = {}
context.update({'use_domain': ('use_invoice', '=', True)})
kwargs.update({'context': context})
if not kwargs.get('fiscal_category_id', False):
return result
obj_company = self.pool.get('res.company').browse(
cr, uid, kwargs.get('company_id', False))
obj_fcategory = self.pool.get('l10n_br_account.fiscal.category')
fcategory = obj_fcategory.browse(
cr, uid, kwargs.get('fiscal_category_id'))
result['value']['journal_id'] = fcategory.property_journal and \
fcategory.property_journal.id or False
if not result['value'].get('journal_id', False):
raise orm.except_orm(
_('Nenhum Diário !'),
_("Categoria fiscal: '%s', não tem um diário contábil para a \
empresa %s") % (fcategory.name, obj_company.name))
obj_fp_rule = self.pool.get('account.fiscal.position.rule')
return obj_fp_rule.apply_fiscal_mapping(cr, uid, result, **kwargs)
def onchange_partner_id(self, cr, uid, ids, type, partner_id,
date_invoice=False, payment_term=False,
partner_bank_id=False, company_id=False,
fiscal_category_id=False):
result = super(account_invoice, self).onchange_partner_id(
cr, uid, ids, type, partner_id, date_invoice, payment_term,
partner_bank_id, company_id)
return self._fiscal_position_map(
cr, uid, result, False, partner_id=partner_id,
partner_invoice_id=partner_id, company_id=company_id,
fiscal_category_id=fiscal_category_id)
def onchange_company_id(self, cr, uid, ids, company_id, partner_id, type,
invoice_line, currency_id,
fiscal_category_id=False):
result = super(account_invoice, self).onchange_company_id(
cr, uid, ids, company_id, partner_id, type, invoice_line,
currency_id)
return self._fiscal_position_map(
cr, uid, result, False, partner_id=partner_id,
partner_invoice_id=partner_id, company_id=company_id,
fiscal_category_id=fiscal_category_id)
def onchange_fiscal_category_id(self, cr, uid, ids,
partner_address_id=False,
partner_id=False, company_id=False,
fiscal_category_id=False):
result = {'value': {}}
return self._fiscal_position_map(
cr, uid, result, False, partner_id=partner_id,
partner_invoice_id=partner_id, company_id=company_id,
fiscal_category_id=fiscal_category_id)
def onchange_fiscal_document_id(self, cr, uid, ids, fiscal_document_id,
company_id, issuer, fiscal_type,
context=None):
result = {'value': {'document_serie_id': False}}
if not context:
context = {}
company = self.pool.get('res.company').browse(cr, uid, company_id,
context=context)
if issuer == '0':
serie = False
if fiscal_type == 'product':
series = [doc_serie.id for doc_serie in
company.document_serie_product_ids if
doc_serie.fiscal_document_id.id == fiscal_document_id and
doc_serie.active]
if series:
serie = series[0]
else:
serie = company.document_serie_service_id and \
company.document_serie_service_id.id or False
result['value']['document_serie_id'] = serie
return result
class account_invoice_line(orm.Model):
_inherit = 'account.invoice.line'
def fields_view_get(self, cr, uid, view_id=None, view_type=False,
context=None, toolbar=False, submenu=False):
result = super(account_invoice_line, self).fields_view_get(
cr, uid, view_id=view_id, view_type=view_type, context=context,
toolbar=toolbar, submenu=submenu)
if context is None:
context = {}
if view_type == 'form':
eview = etree.fromstring(result['arch'])
if 'type' in context.keys():
fiscal_categories = eview.xpath("//field[@name='fiscal_category_id']")
for fiscal_category_id in fiscal_categories:
fiscal_category_id.set('domain',
"[('type', '=', '%s'), \
('journal_type', '=', '%s')]" \
% (OPERATION_TYPE[context['type']],
JOURNAL_TYPE[context['type']]))
fiscal_category_id.set('required', '1')
cfops = eview.xpath("//field[@name='cfop_id']")
for cfop_id in cfops:
cfop_id.set('domain', "[('type','=','%s')]" % (
OPERATION_TYPE[context['type']],))
cfop_id.set('required', '1')
if context.get('fiscal_type', False) == 'service':
cfops = eview.xpath("//field[@name='cfop_id']")
for cfop_id in cfops:
cfop_id.set('invisible', '1')
cfop_id.set('required', '0')
product_ids = eview.xpath("//field[@name='product_id']")
for product_id in product_ids:
product_id.set('domain', "[('fiscal_type', '=', '%s')]" % (
context.get('fiscal_type', 'product')))
result['arch'] = etree.tostring(eview)
return result
def _amount_line(self, cr, uid, ids, prop, unknow_none, unknow_dict):
res = {}
tax_obj = self.pool.get('account.tax')
cur_obj = self.pool.get('res.currency')
for line in self.browse(cr, uid, ids):
res[line.id] = {
'discount_value': 0.0,
'price_gross': 0.0,
'price_subtotal': 0.0,
'price_total': 0.0,
}
price = line.price_unit * (1 - (line.discount or 0.0) / 100.0)
taxes = tax_obj.compute_all(
cr, uid, line.invoice_line_tax_id, price, line.quantity,
line.product_id, line.invoice_id.partner_id,
fiscal_position=line.fiscal_position,
insurance_value=line.insurance_value,
freight_value=line.freight_value,
other_costs_value=line.other_costs_value)
if line.invoice_id:
currency = line.invoice_id.currency_id
price_gross = cur_obj.round(cr, uid, currency,
line.price_unit * line.quantity)
res[line.id].update({
'price_subtotal': cur_obj.round(
cr, uid, currency,
taxes['total'] - taxes['total_tax_discount']),
'price_total': cur_obj.round(
cr, uid, currency, taxes['total']),
'price_gross': price_gross,
'discount_value': (price_gross - taxes['total']),
})
return res
_columns = {
'fiscal_category_id': fields.many2one(
'l10n_br_account.fiscal.category', 'Categoria'),
'fiscal_position': fields.many2one(
'account.fiscal.position', u'Posição Fiscal',
domain="[('fiscal_category_id','=',fiscal_category_id)]"),
'cfop_id': fields.many2one('l10n_br_account.cfop', 'CFOP'),
'fiscal_classification_id': fields.many2one(
'account.product.fiscal.classification', 'Classficação Fiscal'),
'product_type': fields.selection(
[('product', 'Produto'), ('service', u'Serviço')],
'Tipo do Produto', required=True),
'discount_value': fields.function(
_amount_line, method=True, string='Vlr. desconto', type="float",
digits_compute=dp.get_precision('Account'),
store=True, multi='all'),
'price_total': fields.function(
_amount_line, method=True, string='Total', type="float",
digits_compute=dp.get_precision('Account'),
store=True, multi='all'),
'price_gross': fields.function(
_amount_line, method=True, string='Vlr. Bruto', type="float",
digits_compute=dp.get_precision('Account'),
store=True, multi='all'),
'price_subtotal': fields.function(
_amount_line, method=True, string='Subtotal', type="float",
digits_compute=dp.get_precision('Account'),
store=True, multi='all'),
'price_total': fields.function(
_amount_line, method=True, string='Total', type="float",
digits_compute=dp.get_precision('Account'),
store=True, multi='all'),
'icms_manual': fields.boolean('ICMS Manual?'),
'icms_origin': fields.selection(
[('0', '0 - Nacional, exceto as indicadas nos códigos 3 a 5'),
('1', '1 - Estrangeira - Importação direta, exceto a indicada no código 6'),
('2', '2 - Estrangeira - Adquirida no mercado interno, exceto a indicada no código 7'),
('3', '3 - Nacional, mercadoria ou bem com Conteúdo de Importação superior a 40% (quarenta por cento)'),
('4', '4 - Nacional, cuja produção tenha sido feita em conformidade com os processos produtivos básicos de que tratam o Decreto-Lei nº 288/67, e as Leis nºs 8.248/91, 8.387/91, 10.176/01 e 11.484/07'),
('5', '5 - Nacional, mercadoria ou bem com Conteúdo de Importação inferior ou igual a 40% (quarenta por cento)'),
('6', '6 - Estrangeira - Importação direta, sem similar nacional, constante em lista de Resolução CAMEX'),
('7', '7 - Estrangeira - Adquirida no mercado interno, sem similar nacional, constante em lista de Resolução CAMEX')],
'Origem'),
'icms_base_type': fields.selection(
[('0', 'Margem Valor Agregado (%)'), ('1', 'Pauta (valor)'),
('2', 'Preço Tabelado Máximo (valor)'),
('3', 'Valor da Operação')],
'Tipo Base ICMS', required=True),
'icms_base': fields.float('Base ICMS', required=True,
digits_compute=dp.get_precision('Account')),
'icms_base_other': fields.float('Base ICMS Outras', required=True,
digits_compute=dp.get_precision('Account')),
'icms_value': fields.float('Valor ICMS', required=True,
digits_compute=dp.get_precision('Account')),
'icms_percent': fields.float('Perc ICMS',
digits_compute=dp.get_precision('Discount')),
'icms_percent_reduction': fields.float('Perc Redução de Base ICMS',
digits_compute=dp.get_precision('Discount')),
'icms_st_base_type': fields.selection(
[('0', 'Preço tabelado ou máximo sugerido'),
('1', 'Lista Negativa (valor)'),
('2', 'Lista Positiva (valor)'), ('3', 'Lista Neutra (valor)'),
('4', 'Margem Valor Agregado (%)'), ('5', 'Pauta (valor)')],
'Tipo Base ICMS ST', required=True),
'icms_st_value': fields.float('Valor ICMS ST', required=True,
digits_compute=dp.get_precision('Account')),
'icms_st_base': fields.float('Base ICMS ST', required=True,
digits_compute=dp.get_precision('Account')),
'icms_st_percent': fields.float('Percentual ICMS ST',
digits_compute=dp.get_precision('Discount')),
'icms_st_percent_reduction': fields.float(
'Perc Redução de Base ICMS ST',
digits_compute=dp.get_precision('Discount')),
'icms_st_mva': fields.float('MVA ICMS ST',
digits_compute=dp.get_precision('Discount')),
'icms_st_base_other': fields.float('Base ICMS ST Outras',
required=True, digits_compute=dp.get_precision('Account')),
'icms_cst_id': fields.many2one('account.tax.code', 'CST ICMS',
domain=[('domain', '=', 'icms')]),
'issqn_manual': fields.boolean('ISSQN Manual?'),
'issqn_type': fields.selection(
[('N', 'Normal'), ('R', 'Retida'),
('S', 'Substituta'), ('I', 'Isenta')], 'Tipo do ISSQN',
required=True),
'service_type_id': fields.many2one(
'l10n_br_account.service.type', 'Tipo de Serviço'),
'issqn_base': fields.float('Base ISSQN', required=True,