~vauxoo/addons-vauxoo/7.0-changes-in-openerp-alan

« back to all changes in this revision

Viewing changes to invoice_datetime/invoice.py


[ADD] invoice_datetime module added.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# -*- encoding: utf-8 -*-
 
2
###########################################################################
 
3
#    Module Writen to OpenERP, Open Source Management Solution
 
4
#
 
5
#    Copyright (c) 2010 Vauxoo - http://www.vauxoo.com/
 
6
#    All Rights Reserved.
 
7
#    info Vauxoo (info@vauxoo.com)
 
8
############################################################################
 
9
#    Coded by: moylop260 (moylop260@vauxoo.com)
 
10
#    Launchpad Project Manager for Publication: Nhomar Hernandez - nhomar@vauxoo.com
 
11
############################################################################
 
12
#
 
13
#    This program is free software: you can redistribute it and/or modify
 
14
#    it under the terms of the GNU Affero General Public License as
 
15
#    published by the Free Software Foundation, either version 3 of the
 
16
#    License, or (at your option) any later version.
 
17
#
 
18
#    This program is distributed in the hope that it will be useful,
 
19
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
 
20
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
21
#    GNU Affero General Public License for more details.
 
22
#
 
23
#    You should have received a copy of the GNU Affero General Public License
 
24
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
25
#
 
26
##############################################################################
 
27
 
 
28
from openerp.osv import fields, osv
 
29
from openerp.tools.translate import _
 
30
from openerp import pooler, tools
 
31
from openerp import netsvc
 
32
from openerp import release
 
33
import datetime
 
34
from pytz import timezone
 
35
import pytz
 
36
from dateutil.relativedelta import relativedelta
 
37
 
 
38
import time
 
39
import os
 
40
 
 
41
 
 
42
class account_payment_term(osv.Model):
 
43
    _inherit = "account.payment.term"
 
44
 
 
45
    def compute(self, cr, uid, id, value, date_ref=False, context=None):
 
46
        if context is None:
 
47
            context = {}
 
48
        if date_ref:
 
49
            try:
 
50
                date_ref = time.strftime('%Y-%m-%d', time.strptime(
 
51
                    date_ref, '%Y-%m-%d %H:%M:%S'))
 
52
            except:
 
53
                pass
 
54
        return super(account_payment_term, self).compute(cr, uid, id, value,
 
55
            date_ref, context=context)
 
56
 
 
57
 
 
58
class account_invoice(osv.Model):
 
59
    _inherit = 'account.invoice'
 
60
    #_order = 'invoice_datetime asc'
 
61
 
 
62
    def _get_date_invoice_tz(self, cr, uid, ids, field_names=None, arg=False, context=None):
 
63
        if context is None:
 
64
            context = {}
 
65
        res = {}
 
66
        if release.version >= '6':
 
67
            dt_format = tools.DEFAULT_SERVER_DATETIME_FORMAT
 
68
            tz = self.pool.get('res.users').browse(cr, uid, uid).tz
 
69
            for invoice in self.browse(cr, uid, ids, context=context):
 
70
                res[invoice.id] = invoice.invoice_datetime and tools.\
 
71
                    server_to_local_timestamp(invoice.invoice_datetime,
 
72
                    tools.DEFAULT_SERVER_DATETIME_FORMAT,
 
73
                    tools.DEFAULT_SERVER_DATETIME_FORMAT, tz) or False
 
74
        elif release.version < '6':
 
75
            # TODO: tz change for openerp5
 
76
            for invoice in self.browse(cr, uid, ids, context=context):
 
77
                res[invoice.id] = invoice.date_invoice
 
78
        return res
 
79
 
 
80
    def _get_field_params(self, cr, uid, ids, name, unknow_none, context=None):
 
81
        if context is None:
 
82
            context = {}
 
83
        ids = isinstance(ids, (int, long)) and [ids] or ids
 
84
        res = {}
 
85
        key_by_company_id = "acc_invoice.date_invoice_type_" + str(self.pool.get("account.config.settings")._default_company(cr, uid))
 
86
        res[ids[0]] = self.pool.get("ir.config_parameter").get_param(cr, uid, key_by_company_id, default='date', context=context)
 
87
        return res
 
88
 
 
89
    _columns = {
 
90
        # Extract date_invoice from original, but add datetime
 
91
        #'date_invoice': fields.datetime('Date Invoiced', states={'open':[
 
92
        #('readonly',True)],'close':[('readonly',True)]},
 
93
        #help="Keep empty to use the current date"),
 
94
        'invoice_datetime': fields.datetime('Date time of invoice',
 
95
            states={'open': [('readonly', True)], 'close': [('readonly', True)]},
 
96
            help="Keep empty to use the current date"),
 
97
        'date_invoice_tz':  fields.function(_get_date_invoice_tz, method=True,
 
98
            type='datetime', string='Date Invoiced with TZ', store=True,
 
99
            help='Date of Invoice with Time Zone'),
 
100
        'date_type': fields.function(_get_field_params, storage=False, type='char', string="Date type")
 
101
    }
 
102
 
 
103
    def _get_default_type(self, cr, uid, ids):
 
104
        key_by_company_id = "acc_invoice.date_invoice_type_" + str(self.pool.get("account.config.settings")._default_company(cr, uid))
 
105
        type_show_date = self.pool.get("ir.config_parameter").get_param(cr, uid, key_by_company_id, default='date')
 
106
        return type_show_date
 
107
 
 
108
    _defaults = {
 
109
        #'date_invoice': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
 
110
        "date_type": _get_default_type
 
111
    }
 
112
        
 
113
    def copy(self, cr, uid, id, default=None, context=None):
 
114
        if context is None:
 
115
            context = {}
 
116
        if default is None:
 
117
            default = {}
 
118
        default.update({'invoice_datetime': False, 'date_invoice' : False})
 
119
        return super(account_invoice, self).copy(cr, uid, id, default, context)
 
120
    
 
121
    def _get_time_zone(self, cr, uid, invoice_id, context=None):
 
122
        if context is None:
 
123
            context = {}
 
124
        res_users_obj = self.pool.get('res.users')
 
125
        userstz = res_users_obj.browse(cr, uid, [uid])[0].partner_id.tz
 
126
        a = 0
 
127
        if userstz:
 
128
            hours = timezone(userstz)
 
129
            fmt = '%Y-%m-%d %H:%M:%S %Z%z'
 
130
            now = datetime.datetime.now()
 
131
            loc_dt = hours.localize(datetime.datetime(now.year, now.month, now.day,
 
132
                                             now.hour, now.minute, now.second))
 
133
            timezone_loc = (loc_dt.strftime(fmt))
 
134
            diff_timezone_original = timezone_loc[-5:-2]
 
135
            timezone_original = int(diff_timezone_original)
 
136
            s = str(datetime.datetime.now(pytz.timezone(userstz)))
 
137
            s = s[-6:-3]
 
138
            timezone_present = int(s)*-1
 
139
            a = timezone_original + ((
 
140
                timezone_present + timezone_original)*-1)
 
141
        return a
 
142
    
 
143
    def assigned_datetime(self, cr, uid, values, context=None):
 
144
        if context is None:
 
145
            context = {}
 
146
        res = {}
 
147
        if values.get('date_invoice', False) and\
 
148
                                    not values.get('invoice_datetime', False):
 
149
            user_hour = self._get_time_zone(cr, uid, [], context=context)
 
150
            time_invoice = datetime.time(abs(user_hour), 0, 0)
 
151
 
 
152
            date_invoice = datetime.datetime.strptime(
 
153
                values['date_invoice'], '%Y-%m-%d').date()
 
154
                
 
155
            dt_invoice = datetime.datetime.combine(
 
156
                date_invoice, time_invoice).strftime('%Y-%m-%d %H:%M:%S')
 
157
 
 
158
            res['invoice_datetime'] = dt_invoice
 
159
            res['date_invoice'] = values['date_invoice']
 
160
            
 
161
        if values.get('invoice_datetime', False) and not\
 
162
            values.get('date_invoice', False):
 
163
            date_invoice = fields.datetime.context_timestamp(cr, uid,
 
164
                datetime.datetime.strptime(values['invoice_datetime'],
 
165
                tools.DEFAULT_SERVER_DATETIME_FORMAT), context=context)
 
166
            res['date_invoice'] = date_invoice
 
167
            res['invoice_datetime'] = values['invoice_datetime']
 
168
        
 
169
        if 'invoice_datetime' in values  and 'date_invoice' in values:
 
170
            if values['invoice_datetime'] and values['date_invoice']:
 
171
                date_invoice = datetime.datetime.strptime(
 
172
                    values['invoice_datetime'],
 
173
                    '%Y-%m-%d %H:%M:%S').date().strftime('%Y-%m-%d')
 
174
                if date_invoice != values['date_invoice']:
 
175
                    if self.browse(cr, uid, ids)[0].date_type == 'datetime':
 
176
                        date_invoice = fields.datetime.context_timestamp(cr, uid,
 
177
                            datetime.datetime.strptime(values['invoice_datetime'],
 
178
                            tools.DEFAULT_SERVER_DATETIME_FORMAT), context=context)
 
179
                        res['date_invoice'] = date_invoice
 
180
                        res['invoice_datetime'] = values['invoice_datetime']
 
181
                    elif self.browse(cr, uid, ids)[0].date_type == 'date':
 
182
                        user_hour = self._get_time_zone(cr, uid, [], context=context)
 
183
                        time_invoice = datetime.time(abs(user_hour), 0, 0)
 
184
 
 
185
                        date_invoice = datetime.datetime.strptime(
 
186
                            values['date_invoice'], '%Y-%m-%d').date()
 
187
                            
 
188
                        dt_invoice = datetime.datetime.combine(
 
189
                            date_invoice, time_invoice).strftime('%Y-%m-%d %H:%M:%S')
 
190
 
 
191
                        res['invoice_datetime'] = dt_invoice
 
192
                        res['date_invoice'] = values['date_invoice']
 
193
                    else:
 
194
                        raise osv.except_osv(_('Warning!'), _('Invoice dates should be equal'))
 
195
                    #~ else:
 
196
                        #~ raise osv.except_osv(_('Warning!'), _('Invoice dates should be equal'))
 
197
                            
 
198
        if  not values.get('invoice_datetime', False) and\
 
199
                                        not values.get('date_invoice', False):
 
200
            res['date_invoice'] = fields.date.context_today(self,cr,uid,context=context)
 
201
            res['invoice_datetime'] = fields.datetime.now()
 
202
            
 
203
        return res
 
204
 
 
205
    def action_move_create(self, cr, uid, ids, context=None):
 
206
        for inv in self.browse(cr, uid, ids, context=context):
 
207
            if inv.type in ('out_invoice', 'out_refund'):
 
208
                vals_date = self.assigned_datetime(cr, uid,
 
209
                    {'invoice_datetime': inv.invoice_datetime,
 
210
                        'date_invoice': inv.date_invoice},
 
211
                        context=context)
 
212
                self.write(cr, uid, ids, vals_date, context=context)
 
213
        return super(account_invoice,
 
214
                        self).action_move_create(cr, uid, ids, context=context)