~openerp-commiter/openobject-addons/trunk-extra-addons

« back to all changes in this revision

Viewing changes to auction/auction.py

  • Committer: Fabien Pinckaers
  • Date: 2008-11-12 06:43:12 UTC
  • Revision ID: fp@tinyerp.com-20081112064312-fp85io97i1e95tuz
moved

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
##############################################################################
2
 
#
3
 
# Copyright (c) 2004 TINY SPRL. (http://tiny.be) All Rights Reserved.
4
 
#                                       Fabien Pinckaers <fp@tiny.Be>
5
 
#
6
 
# WARNING: This program as such is intended to be used by professional
7
 
# programmers who take the whole responsability of assessing all potential
8
 
# consequences resulting from its eventual inadequacies and bugs
9
 
# End users who are looking for a ready-to-use solution with commercial
10
 
# garantees and support are strongly adviced to contract a Free Software
11
 
# Service Company
12
 
#
13
 
# This program is Free Software; you can redistribute it and/or
14
 
# modify it under the terms of the GNU General Public License
15
 
# as published by the Free Software Foundation; either version 2
16
 
# of the 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 General Public License for more details.
22
 
#
23
 
# You should have received a copy of the GNU General Public License
24
 
# along with this program; if not, write to the Free Software
25
 
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
26
 
#
27
 
##############################################################################
28
 
 
29
 
import time
30
 
import netsvc
31
 
from osv import fields, osv, orm
32
 
import ir
33
 
from mx import DateTime
34
 
 
35
 
#----------------------------------------------------------
36
 
# Auction Artists
37
 
#----------------------------------------------------------
38
 
class auction_artists(osv.osv):
39
 
        _name = "auction.artists"
40
 
        _columns = {
41
 
                'name': fields.char('Artist/Author Name', size=64, required=True),
42
 
                'pseudo': fields.char('Pseudo', size=64),
43
 
                'birth_death_dates':fields.char('Birth / Death dates',size=64),
44
 
                'biography': fields.text('Biography'),
45
 
        }
46
 
auction_artists()
47
 
 
48
 
#----------------------------------------------------------
49
 
# Auction Dates
50
 
#----------------------------------------------------------
51
 
class auction_dates(osv.osv):
52
 
        _name = "auction.dates"
53
 
 
54
 
        def _adjudication_get(self, cr, uid, ids, prop, unknow_none,unknow_dict):
55
 
                tmp={}
56
 
                for id in ids:
57
 
                        tmp[id]=0.0
58
 
                        cr.execute("select sum(obj_price) from auction_lots where auction_id=%d", (id,))
59
 
                        sum = cr.fetchone()
60
 
                        if sum:
61
 
                                tmp[id]=sum[0]
62
 
                return tmp
63
 
 
64
 
        def name_get(self, cr, uid, ids, context={}):
65
 
                if not len(ids):
66
 
                        return []
67
 
                reads = self.read(cr, uid, ids, ['name', 'auction1'], context)
68
 
                name = [(r['id'],'['+r['auction1']+'] '+ r['name']) for r in reads]
69
 
                return name
70
 
 
71
 
        _columns = {
72
 
                'name': fields.char('Auction date', size=64, required=True),
73
 
                'expo1': fields.date('First Exposition Day', required=True),
74
 
                'expo2': fields.date('Last Exposition Day', required=True),
75
 
                'auction1': fields.date('First Auction Day', required=True),
76
 
                'auction2': fields.date('Last Auction Day', required=True),
77
 
                'journal_id': fields.many2one('account.journal', 'Buyer Journal', required=True),
78
 
                'journal_seller_id': fields.many2one('account.journal', 'Seller Journal', required=True),
79
 
                'buyer_costs': fields.many2many('account.tax', 'auction_buyer_taxes_rel', 'auction_id', 'tax_id', 'Buyer Costs'),
80
 
                'seller_costs': fields.many2many('account.tax', 'auction_seller_taxes_rel', 'auction_id', 'tax_id', 'Seller Costs'),
81
 
                'acc_income': fields.many2one('account.account', 'Income Account', required=True),
82
 
                'acc_expense': fields.many2one('account.account', 'Expense Account', required=True),
83
 
                'adj_total': fields.function(_adjudication_get, method=True, string='Total Adjudication',store=True),
84
 
        #       'state': fields.selection((('draft','Draft'),('closed','Closed')),'State',select=1, readonly=True),
85
 
                'state': fields.selection((('draft','Draft'),('close','Closed')),'State',select=1, readonly=True),
86
 
                'account_analytic_id': fields.many2one('account.analytic.account', 'Analytic Account', required=True),
87
 
 
88
 
        }
89
 
        _defaults = {
90
 
                'state': lambda *a: 'draft',
91
 
        }
92
 
        _order = "auction1 desc"
93
 
 
94
 
        def close(self, cr, uid, ids, *args):
95
 
                print "GGGGGGGGGGGGGGGggg"
96
 
                """
97
 
                Close an auction date.
98
 
 
99
 
                Create invoices for all buyers and sellers.
100
 
                STATE ='close'
101
 
 
102
 
                RETURN: True
103
 
                """
104
 
                # objects vendus mais non factures
105
 
                cr.execute('select count(*) as c from auction_lots where auction_id in ('+','.join(map(str,ids))+') and state=%s and obj_price>0', ('draft',))
106
 
                nbr = cr.fetchone()[0]
107
 
                ach_uids = {}
108
 
                cr.execute('select id from auction_lots where auction_id in ('+','.join(map(str,ids))+') and state=%s and obj_price>0', ('draft',))
109
 
                r=self.pool.get('auction.lots').lots_invoice(cr, uid, [x[0] for x in cr.fetchall()],{},None)
110
 
                print "RRRRRRRRRRRRRRRRrrrr",r
111
 
                cr.execute('select id from auction_lots where auction_id in ('+','.join(map(str,ids))+') and obj_price>0')
112
 
                ids2 = [x[0] for x in cr.fetchall()]
113
 
        #       for auction in auction_ids:
114
 
                c=self.pool.get('auction.lots').seller_trans_create(cr, uid, ids2,{})
115
 
                self.write(cr, uid, ids, {'state':'closed'}) #close the auction
116
 
                print "jjjjjjjjjjjjjjjj"
117
 
                return True
118
 
auction_dates()
119
 
 
120
 
 
121
 
#----------------------------------------------------------
122
 
# Deposits
123
 
#----------------------------------------------------------
124
 
def _inv_uniq(cr, ids):
125
 
        cr.execute('select name from auction_deposit where id in ('+','.join(map(lambda x: str(x), ids))+')')
126
 
        for datas in cr.fetchall():
127
 
                cr.execute('select count(*) from auction_deposit where name=%s', (datas[0],))
128
 
                if cr.fetchone()[0]>1:
129
 
                        return False
130
 
        return True
131
 
 
132
 
class auction_deposit(osv.osv):
133
 
        _name = "auction.deposit"
134
 
        _description="Deposit Border"
135
 
        _order = "id desc"
136
 
        _columns = {
137
 
                'transfer' : fields.boolean('Transfer'),
138
 
                'name': fields.char('Depositer Inventory', size=64, required=True),
139
 
                'partner_id': fields.many2one('res.partner', 'Seller', required=True, change_default=True),
140
 
                'date_dep': fields.date('Deposit date', required=True),
141
 
                'method': fields.selection((('keep','Keep until sold'),('decease','Decrease limit of 10%'),('contact','Contact the Seller')), 'Withdrawned method', required=True),
142
 
                'tax_id': fields.many2one('account.tax', 'Expenses'),
143
 
                'create_uid': fields.many2one('res.users', 'Created by', readonly=True),
144
 
                'info': fields.char('Description', size=64),
145
 
                'lot_id': fields.one2many('auction.lots', 'bord_vnd_id', 'Objects'),
146
 
                'specific_cost_ids': fields.one2many('auction.deposit.cost', 'deposit_id', 'Specific Costs'),
147
 
                'total_neg': fields.boolean('Allow Negative Amount'),
148
 
        }
149
 
        _defaults = {
150
 
#               'date_dep': lambda *a: time.strftime('%Y-%m-%d'),
151
 
                'method': lambda *a: 'keep',
152
 
                'total_neg': lambda *a: False,
153
 
                'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'auction.deposit'),
154
 
        }
155
 
        _constraints = [
156
 
        ]
157
 
        def partner_id_change(self, cr, uid, ids, part):
158
 
                return {}
159
 
auction_deposit()
160
 
 
161
 
#----------------------------------------------------------
162
 
# (Specific) Deposit Costs
163
 
#----------------------------------------------------------
164
 
class auction_deposit_cost(osv.osv):
165
 
        _name = 'auction.deposit.cost'
166
 
        _columns = {
167
 
                'name': fields.char('Cost Name', required=True, size=64),
168
 
                'amount': fields.float('Amount'),
169
 
                'account': fields.many2one('account.account', 'Destination Account', required=True),
170
 
                'deposit_id': fields.many2one('auction.deposit', 'Deposit'),
171
 
        }
172
 
auction_deposit_cost()
173
 
 
174
 
#----------------------------------------------------------
175
 
# Lots Categories
176
 
#----------------------------------------------------------
177
 
class auction_lot_category(osv.osv):
178
 
        _name = 'auction.lot.category'
179
 
        _columns = {
180
 
                'name': fields.char('Category Name', required=True, size=64),
181
 
                'priority': fields.float('Priority'),
182
 
                'active' : fields.boolean('Active'),
183
 
                'aie_categ' : fields.selection([('41',"Unclassifieds"),
184
 
                        ('2',"Antiques"),
185
 
                        ('42',"Antique/African Arts"),
186
 
                        ('59',"Antique/Argenterie"),
187
 
                        ('45',"Antique/Art from the Ivory Coast"),
188
 
                        ('46',"Antique/Art from the Ivory Coast/African Arts"),
189
 
                        ('12',"Antique/Books, manuscripts, eso."),
190
 
                        ('11',"Antique/Carpet and textilles"),
191
 
                        ('14',"Antique/Cartoons"),
192
 
                        ('26',"Antique/Clocks and watches"),
193
 
                        ('31',"Antique/Collectible & art objects"),
194
 
                        ('33',"Antique/Engravings"),
195
 
                        ('10',"Antique/Furnitures"),
196
 
                        ('50',"Antique/Graphic Arts"),
197
 
                        ('37',"Antique/Jewelry"),
198
 
                        ('9',"Antique/Lightings"),
199
 
                        ('52',"Antique/Metal Ware"),
200
 
                        ('51',"Antique/Miniatures / Collections"),
201
 
                        ('53',"Antique/Musical Instruments"),
202
 
                        ('19',"Antique/Old weapons and militaria"),
203
 
                        ('43',"Antique/Oriental Arts"),
204
 
                        ('47',"Antique/Oriental Arts/Chineese furnitures"),
205
 
                        ('24',"Antique/Others"),
206
 
                        ('8',"Antique/Painting"),
207
 
                        ('25',"Antique/Porcelain, Ceramics, Glassmaking, ..."),
208
 
                        ('13',"Antique/Posters"),
209
 
                        ('56',"Antique/Religiosa"),
210
 
                        ('54',"Antique/Scientific Instruments"),
211
 
                        ('18',"Antique/Sculpture, bronze, eso."),
212
 
                        ('55',"Antique/Tin / Copper wares"),
213
 
                        ('16',"Antique/Toys"),
214
 
                        ('57',"Antique/Verreries"),
215
 
                        ('17',"Antique/Wine"),
216
 
                        ('1',"Contemporary Art"),
217
 
                        ('58',"Cont. Art/Arts"),
218
 
                        ('27',"Cont. Art/Curiosa"),
219
 
                        ('15',"Cont. Art/Jewelry"),
220
 
                        ('30',"Cont. Art/Other Media"),
221
 
                        ('3',"Cont. Art/Photo"),
222
 
                        ('4',"Cont. Art/Painting"),
223
 
                        ('5',"Cont. Art/Sculpture"),
224
 
                        ('48',"Cont. Art/Shows")],
225
 
                        'Aie Category'),
226
 
        }
227
 
        _defaults = {
228
 
                'active' : lambda *a: 1,
229
 
                'aie_categ' : lambda *a:1,
230
 
        }
231
 
auction_lot_category()
232
 
 
233
 
def _type_get(self, cr, uid,ids):
234
 
        cr.execute('select name, name from auction_lot_category order by name')
235
 
        return cr.fetchall()
236
 
 
237
 
#----------------------------------------------------------
238
 
# Lots
239
 
#----------------------------------------------------------
240
 
def _inv_constraint(cr, ids):
241
 
        cr.execute('select id, bord_vnd_id, lot_num from auction_lots where id in ('+','.join(map(lambda x: str(x), ids))+')')
242
 
        for datas in cr.fetchall():
243
 
                cr.execute('select count(*) from auction_lots where bord_vnd_id=%s and lot_num=%s', (datas[1],datas[2]))
244
 
                if cr.fetchone()[0]>1:
245
 
                        return False
246
 
        return True
247
 
 
248
 
class auction_lots(osv.osv):
249
 
        _name = "auction.lots"
250
 
        _order = "obj_num,lot_num,id"
251
 
        _description="Object"
252
 
 
253
 
        def button_not_bought(self,cr,uid,ids,*a):
254
 
                return self.write(cr,uid,ids, {'state':'unsold'})
255
 
        def button_taken_away(self,cr,uid,ids,*a):
256
 
                return self.write(cr,uid,ids, {'state':'taken_away'})
257
 
 
258
 
        def button_draft(self,cr,uid,ids,*a):
259
 
                return self.write(cr,uid,ids, {'state':'draft'})
260
 
 
261
 
        def button_bought(self,cr,uid,ids,*a):
262
 
                return self.write(cr,uid,ids, {'state':'sold'})
263
 
 
264
 
        def _buyerprice(self, cr, uid, ids, name, args, context):
265
 
                res={}
266
 
                lots=self.pool.get('auction.lots').browse(cr,uid,ids)
267
 
                pt_tax=self.pool.get('account.tax')
268
 
                for lot in lots:
269
 
                        amount_total=0.0
270
 
        #               if ((lot.obj_price==0) and (lot.state=='draft')):
271
 
        #                       montant=lot.lot_est1
272
 
        #               else:
273
 
                        montant=lot.obj_price or 0.0
274
 
                        taxes = []
275
 
                        if lot.author_right:
276
 
                                taxes.append(lot.author_right)
277
 
                        if lot.auction_id:
278
 
                                taxes += lot.auction_id.buyer_costs
279
 
                        tax=pt_tax.compute(cr,uid,taxes,montant,1)
280
 
                        for t in tax:
281
 
                                amount_total+=t['amount']
282
 
                        amount_total += montant
283
 
                        res[lot.id] = amount_total
284
 
                return res
285
 
 
286
 
 
287
 
        def _sellerprice(self, cr, uid, ids,*a):
288
 
                res={}
289
 
                lots=self.pool.get('auction.lots').browse(cr,uid,ids)
290
 
                pt_tax=self.pool.get('account.tax')
291
 
                for lot in lots:
292
 
                        amount_total=0.0
293
 
                #       if ((lot.obj_price==0) and (lot.state=='draft')):
294
 
                #               montant=lot.lot_est1
295
 
                #       else:
296
 
                        montant=lot.obj_price
297
 
                        taxes = []
298
 
                        if lot.bord_vnd_id.tax_id:
299
 
                                taxes.append(lot.bord_vnd_id.tax_id)
300
 
                        elif lot.auction_id and lot.auction_id.seller_costs:
301
 
                                taxes += lot.auction_id.seller_costs
302
 
                        tax=pt_tax.compute(cr,uid,taxes,montant,1)
303
 
                        for t in tax:
304
 
                                amount_total+=t['amount']
305
 
                        res[lot.id] =  montant+amount_total
306
 
                return res
307
 
 
308
 
        def _grossprice(self, cr, uid, ids, name, args, context):
309
 
                """gross revenue"""
310
 
                res={}
311
 
                auction_lots_obj = self.read(cr,uid,ids,['seller_price','buyer_price','auction_id'])
312
 
                for auction_data in auction_lots_obj:
313
 
                        total_tax = 0.0
314
 
                        if auction_data['auction_id']:
315
 
                                total_tax += auction_data['buyer_price']-auction_data['seller_price']
316
 
                        res[auction_data['id']] = total_tax
317
 
                return res
318
 
 
319
 
 
320
 
        def _grossmargin(self, cr, uid, ids, name, args, context):
321
 
                """
322
 
                gross Margin : Gross revenue * 100 / Adjudication
323
 
                (state==unsold or obj_ret_price>0): adj_price = 0 (=> gross margin = 0, net margin is negative)
324
 
                """
325
 
                res={}
326
 
                for lot in self.browse(cr, uid, ids, context):
327
 
                        if ((lot.obj_price==0) and (lot.state=='draft')):
328
 
                                montant=lot.lot_est1
329
 
                        else:
330
 
                                montant=lot.obj_price
331
 
                        if lot.obj_price>0:
332
 
                                total=(lot.gross_revenue*100.0) /lot.obj_price
333
 
                        else:
334
 
                                total = 0.0
335
 
                        res[lot.id]=round(total,2)
336
 
                return res
337
 
 
338
 
        def onchange_obj_ret(self, cr, uid, ids, obj_ret, *args):
339
 
                if obj_ret:
340
 
                        return {'value': {'obj_price': 0}}
341
 
                return {}
342
 
 
343
 
        def _costs(self,cr,uid,ids,context,*a):
344
 
                """
345
 
                costs: Total credit of analytic account
346
 
                / # objects sold during this auction
347
 
                (excluding analytic lines that are in the analytic journal of the auction date).
348
 
                """
349
 
                res={}
350
 
                for lot in self.browse(cr,uid,ids):
351
 
                        som=0.0
352
 
                        if not lot.auction_id:
353
 
                                res[lot.id] = 0.0
354
 
                                continue
355
 
                        auct_id=lot.auction_id.id
356
 
                        cr.execute('select count(*) from auction_lots where auction_id=%d', (auct_id,))
357
 
                        nb = cr.fetchone()[0]
358
 
                        account_analytic_line_obj = self.pool.get('account.analytic.line')
359
 
                        line_ids = account_analytic_line_obj.search(cr, uid, [('account_id', '=', lot.auction_id.account_analytic_id.id),('journal_id', '<>', lot.auction_id.journal_id.id),('journal_id', '<>', lot.auction_id.journal_seller_id.id)])
360
 
                        #indir_cost=lot.bord_vnd_id.specific_cost_ids
361
 
                        #for r in lot.bord_vnd_id.specific_cost_ids:
362
 
                        #       som+=r.amount
363
 
 
364
 
                        for line in account_analytic_line_obj.browse(cr,uid,line_ids):
365
 
                                if line.amount:
366
 
                                        som-=line.amount
367
 
                        res[lot.id]=som/nb
368
 
                return res
369
 
 
370
 
        def _netprice(self, cr, uid, ids, name, args, context):
371
 
                """This is the net revenue"""
372
 
                res={}
373
 
                auction_lots_obj = self.read(cr,uid,ids,['seller_price','buyer_price','auction_id','costs'])
374
 
                for auction_data in auction_lots_obj:
375
 
                        total_tax = 0.0
376
 
                        if auction_data['auction_id']:
377
 
                                total_tax += auction_data['buyer_price']-auction_data['seller_price']-auction_data['costs']
378
 
                        res[auction_data['id']] = total_tax
379
 
                return res
380
 
 
381
 
        def _netmargin(self, cr, uid, ids, name, args, context):
382
 
                res={}
383
 
                total_tax = 0.0
384
 
                total=0.0
385
 
                montant=0.0
386
 
                auction_lots_obj = self.read(cr,uid,ids,['net_revenue','auction_id','lot_est1','obj_price','state'])
387
 
                for auction_data in auction_lots_obj:
388
 
                        if ((auction_data ['obj_price']==0) and (auction_data['state']=='draft')):
389
 
                                montant=auction_data['lot_est1']
390
 
                        else: montant=auction_data ['obj_price']
391
 
                        if montant>0:
392
 
                                total_tax += (auction_data['net_revenue']*100)/montant
393
 
                        else:
394
 
                                total_tax=0
395
 
                        res[auction_data['id']] =  total_tax
396
 
                return res
397
 
 
398
 
        def _is_paid_vnd(self,cr,uid,ids,*a):
399
 
                res = {}
400
 
                lots=self.browse(cr,uid,ids)
401
 
                for lot in lots:
402
 
                        res[lot.id] = False
403
 
                        if lot.sel_inv_id:
404
 
                                if lot.sel_inv_id.state == 'paid':
405
 
                                        res[lot.id] = True
406
 
                return res
407
 
        def _is_paid_ach(self,cr,uid,ids,*a):
408
 
                res = {}
409
 
                lots=self.browse(cr,uid,ids)
410
 
                for lot in lots:
411
 
                        res[lot.id] = False
412
 
                        if lot.ach_inv_id:
413
 
                                if lot.ach_inv_id.state == 'paid':
414
 
                                        res[lot.id] = True
415
 
                return res
416
 
        _columns = {
417
 
                'bid_lines':fields.one2many('auction.bid_line','lot_id', 'Bids'),
418
 
                'auction_id': fields.many2one('auction.dates', 'Auction Date'),
419
 
                'bord_vnd_id': fields.many2one('auction.deposit', 'Depositer Inventory', required=True),
420
 
                'name': fields.char('Short Description',size=64, required=True),
421
 
                'name2': fields.char('Short Description (2)',size=64),
422
 
                'lot_type': fields.selection(_type_get, 'Object category', size=64),
423
 
                'author_right': fields.many2one('account.tax', 'Author rights'),
424
 
                'lot_est1': fields.float('Minimum Estimation'),
425
 
                'lot_est2': fields.float('Maximum Estimation'),
426
 
                'lot_num': fields.integer('List Number', required=True, select=1 ),
427
 
                'create_uid': fields.many2one('res.users', 'Created by', readonly=True),
428
 
                'history_ids':fields.one2many('auction.lot.history', 'lot_id', 'Auction history'),
429
 
                'lot_local':fields.char('Location',size=64),
430
 
                'artist_id':fields.many2one('auction.artists', 'Artist/Author'),
431
 
                'artist2_id':fields.many2one('auction.artists', 'Artist/Author 2'),
432
 
                'important':fields.boolean('To be Emphatized'),
433
 
                'product_id':fields.many2one('product.product', 'Product', required=True),
434
 
                'obj_desc': fields.text('Object Description'),
435
 
                'obj_num': fields.integer('Catalog Number'),
436
 
                'obj_ret': fields.float('Price retired'),
437
 
                'obj_comm': fields.boolean('Commission'),
438
 
                'obj_price': fields.float('Adjudication price'),
439
 
                'ach_avance': fields.float('Buyer Advance'),
440
 
                'ach_login': fields.char('Buyer Username',size=64),
441
 
                'ach_uid': fields.many2one('res.partner', 'Buyer'),
442
 
                'ach_emp': fields.boolean('Taken Away'),
443
 
                'is_ok': fields.boolean('Buyer s payment'),
444
 
                'ach_inv_id': fields.many2one('account.invoice','Buyer Invoice', readonly=True, states={'draft':[('readonly',False)]}),
445
 
                'sel_inv_id': fields.many2one('account.invoice','Seller Invoice', readonly=True, states={'draft':[('readonly',False)]}),
446
 
                'vnd_lim': fields.float('Seller limit'),
447
 
                'vnd_lim_net': fields.boolean('Net limit ?',readonly=True),
448
 
                'image': fields.binary('Image'),
449
 
#               'paid_vnd':fields.function(_is_paid_vnd,string='Seller Paid',method=True,type='boolean',store=True),
450
 
                'paid_vnd':fields.boolean('Seller Paid'),
451
 
                'paid_ach':fields.function(_is_paid_ach,string='Buyer invoice reconciled',method=True, type='boolean',store=True),
452
 
                'state': fields.selection((('draft','Draft'),('unsold','Unsold'),('paid','Paid'),('sold','Sold'),('taken_away','Taken away')),'State', required=True, readonly=True),
453
 
                'buyer_price': fields.function(_buyerprice, method=True, string='Buyer price',store=True),
454
 
                'seller_price': fields.function(_sellerprice, method=True, string='Seller price',store=True),
455
 
                'gross_revenue':fields.function(_grossprice, method=True, string='Gross revenue',store=True),
456
 
                'gross_margin':fields.function(_grossmargin, method=True, string='Gross Margin (%)',store=True),
457
 
                'costs':fields.function(_costs,method=True,string='Indirect costs',store=True),
458
 
                'statement_id': fields.many2many('account.bank.statement.line', 'auction_statement_line_rel','auction_id', 'statement','Payment'),
459
 
                'net_revenue':fields.function(_netprice, method=True, string='Net revenue',store=True),
460
 
                'net_margin':fields.function(_netmargin, method=True, string='Net Margin (%)',store=True),
461
 
        }
462
 
        _defaults = {
463
 
                'state':lambda *a: 'draft',
464
 
                'lot_num':lambda *a:1,
465
 
                'is_ok': lambda *a: False
466
 
        }
467
 
        _constraints = [
468
 
#               (_inv_constraint, 'Twice the same inventory number !', ['lot_num','bord_vnd_id'])
469
 
        ]
470
 
 
471
 
 
472
 
        def name_get(self, cr, user, ids, context={}):
473
 
                if not len(ids):
474
 
                        return []
475
 
                result = [ (r['id'], str(r['obj_num'])+' - '+r['name']) for r in self.read(cr, user, ids, ['name','obj_num'])]
476
 
                return result
477
 
 
478
 
        def name_search(self, cr, user, name, args=[], operator='ilike', context={}):
479
 
                try:
480
 
                        ids = self.search(cr, user, [('obj_num','=',int(name))]+ args)
481
 
                except:
482
 
                        ids = []
483
 
                if not ids:
484
 
                        ids = self.search(cr, user, [('name',operator,name)]+ args)
485
 
                return self.name_get(cr, user, ids)
486
 
 
487
 
        def _sum_taxes_by_type_and_id(self, taxes):
488
 
                """
489
 
                PARAMS: taxes: a list of dictionaries of the form {'id':id, 'amount':amount, ...}
490
 
                RETURNS : a list of dictionaries of the form {'id':id, 'amount':amount, ...}; one dictionary per unique id.
491
 
                        The others fields in the dictionaries (other than id and amount) are those of the first tax with a particular id.
492
 
                """
493
 
                taxes_summed = {}
494
 
                for tax in taxes:
495
 
                        key = (tax['type'], tax['id'])
496
 
                        if key in taxes_summed:
497
 
                                taxes_summed[key]['amount'] += tax['amount']
498
 
                        else:
499
 
                                taxes_summed[key] = tax
500
 
                return taxes_summed.values()
501
 
 
502
 
        def compute_buyer_costs(self, cr, uid, ids):
503
 
                amount_total = {}
504
 
                lots = self.browse(cr, uid, ids)
505
 
##CHECKME: est-ce que ca vaudrait la peine de faire des groupes de lots qui ont les memes couts pour passer des listes de lots a compute?
506
 
                taxes = []
507
 
                amount=0.0
508
 
        #       pt_tax=pool.get('account.tax')
509
 
                for lot in lots:
510
 
                        taxes = lot.product_id.taxes_id
511
 
                        if lot.author_right:
512
 
                                taxes.append(lot.author_right)
513
 
                        elif lot.auction_id:
514
 
                                taxes += lot.auction_id.buyer_costs
515
 
                        tax=self.pool.get('account.tax').compute(cr,uid,taxes,lot.obj_price,1)
516
 
                        for t in tax:
517
 
                                amount+=t['amount']
518
 
                        #amount+=lot.obj_price*0.2
519
 
                        #amount+=lot.obj_price
520
 
                amount_total['value']= amount
521
 
                amount_total['amount']= amount
522
 
                return amount_total
523
 
 
524
 
 
525
 
 
526
 
#               for t in taxes_res:
527
 
#                       t.update({'type': 0})
528
 
#               return self._sum_taxes_by_type_and_id(taxes_res)
529
 
 
530
 
#       lots=self.browse(cr,uid,ids)
531
 
#       amount=0.0
532
 
#       for lot in lots:
533
 
#               taxes=lot.product_id.taxe_id
534
 
 
535
 
 
536
 
        def _compute_lot_seller_costs(self, cr, uid, lot, manual_only=False):
537
 
                costs = []
538
 
                tax_cost_ids=[]
539
 
#               tax_cost_ids = [i.id for i in lot.auction_id.seller_costs]
540
 
                # if there is a specific deposit cost for this depositer, add it
541
 
                border_id = lot.bord_vnd_id
542
 
                if border_id:
543
 
                        if border_id.tax_id:
544
 
                                tax_cost_ids.append(border_id.tax_id)
545
 
                        elif lot.auction_id and lot.auction_id.seller_costs:
546
 
                                tax_cost_ids += lot.auction_id.seller_costs
547
 
                tax_costs = self.pool.get('account.tax').compute(cr, uid, tax_cost_ids, lot.obj_price, 1)
548
 
                # delete useless keys from the costs computed by the tax object... this is useless but cleaner...
549
 
                for cost in tax_costs:
550
 
                        del cost['account_paid_id']
551
 
                        del cost['account_collected_id']
552
 
 
553
 
                if not manual_only:
554
 
                        costs.extend(tax_costs)
555
 
                        for c in costs:
556
 
                                c.update({'type': 0})
557
 
######
558
 
                if lot.vnd_lim_net<0 and lot.obj_price>0:
559
 
#FIXME: la string 'remise lot' devrait passer par le systeme de traductions
560
 
                        obj_price_wh_costs = reduce(lambda x, y: x + y['amount'], tax_costs, lot.obj_price)
561
 
                        if obj_price_wh_costs < lot.vnd_lim:
562
 
                                costs.append({  'type': 1,
563
 
                                                                'id': lot.obj_num,
564
 
                                                                'name': 'Remise lot '+ str(lot.obj_num),
565
 
                                                                'amount': lot.vnd_lim - obj_price_wh_costs}
566
 
                                                                #'account_id': lot.auction_id.acc_refund.id
567
 
                                                        )
568
 
                return costs
569
 
        def compute_seller_costs(self, cr, uid, ids, manual_only=False):
570
 
                lots = self.browse(cr, uid, ids)
571
 
                costs = []
572
 
 
573
 
                # group objects (lots) by deposit id
574
 
                # ie create a dictionary containing lists of objects
575
 
                bord_lots = {}
576
 
                for lot in lots:
577
 
                        key = lot.bord_vnd_id.id
578
 
                        if not key in bord_lots:
579
 
                                bord_lots[key] = []
580
 
                        bord_lots[key].append(lot)
581
 
 
582
 
                # use each list of object in turn
583
 
                for lots in bord_lots.values():
584
 
                        total_adj = 0
585
 
                        total_cost = 0
586
 
                        for lot in lots:
587
 
                                total_adj += lot.obj_price or 0.0
588
 
                                lot_costs = self._compute_lot_seller_costs(cr, uid, lot, manual_only)
589
 
                                for c in lot_costs:
590
 
                                        total_cost += c['amount']
591
 
                                costs.extend(lot_costs)
592
 
                        bord = lots[0].bord_vnd_id
593
 
                        if bord:
594
 
                                if bord.specific_cost_ids:
595
 
                                        bord_costs = [{'type':2, 'id':c.id, 'name':c.name, 'amount':c.amount, 'account_id':c.account} for c in bord.specific_cost_ids]
596
 
                                        for c in bord_costs:
597
 
                                                total_cost += c['amount']
598
 
                                        costs.extend(bord_costs)
599
 
                        if (total_adj+total_cost)<0:
600
 
#FIXME: translate tax name
601
 
                                new_id = bord and bord.id or 0
602
 
                                c = {'type':3, 'id':new_id, 'amount':-total_cost-total_adj, 'name':'Ristourne'}#, 'account_id':lots[0].auction_id.acc_refund.id}
603
 
                                costs.append(c)
604
 
                return self._sum_taxes_by_type_and_id(costs)
605
 
 
606
 
        # sum remise limite net and ristourne
607
 
        def compute_seller_costs_summed(self, cr, uid, ids): #ach_pay_id
608
 
                taxes = self.compute_seller_costs(cr, uid, ids)
609
 
                taxes_summed = {}
610
 
                for tax in taxes:
611
 
                        if tax['type'] == 1:
612
 
                                tax['id'] = 0
613
 
        #FIXME: translate tax names
614
 
                                tax['name'] = 'Remise limite nette'
615
 
                        elif tax['type'] == 2:
616
 
                                tax['id'] = 0
617
 
                                tax['name'] = 'Frais divers'
618
 
                        elif tax['type'] == 3:
619
 
                                tax['id'] = 0
620
 
                                tax['name'] = 'Rist.'
621
 
                        key = (tax['type'], tax['id'])
622
 
                        if key in taxes_summed:
623
 
                                taxes_summed[key]['amount'] += tax['amount']
624
 
                        else:
625
 
                                taxes_summed[key] = tax
626
 
                return taxes_summed.values()
627
 
 
628
 
        def buyer_proforma(self,cr,uid,ids,context):
629
 
                invoices = {}
630
 
                inv_ref=self.pool.get('account.invoice')
631
 
#               acc_receiv=self.pool.get('account.account').search([cr,uid,[('code','=','4010')]])
632
 
                for lot in self.browse(cr,uid,ids,context):
633
 
                        if not lot.obj_price>0:
634
 
                                continue
635
 
                        partner_r=self.pool.get('res.partner')
636
 
                        if not lot.ach_uid.id:
637
 
                                raise orm.except_orm('Missed buyer !', 'The object "%s" has no buyer assigned.' % (lot.name,))
638
 
                        else:
639
 
                                partner_ref =lot.ach_uid.id
640
 
                                lot_name = lot.obj_num
641
 
                                res = self.pool.get('res.partner').address_get(cr, uid, [partner_ref], ['contact', 'invoice'])
642
 
                                contact_addr_id = res['contact']
643
 
                                invoice_addr_id = res['invoice']
644
 
                                inv = {
645
 
                                        'name': 'Auction proforma:' +lot.name,
646
 
                                        'journal_id': lot.auction_id.journal_id.id,
647
 
                                        'partner_id': partner_ref,
648
 
                                        'type': 'out_invoice',
649
 
                                #       'state':'proforma',
650
 
                                }
651
 
                                inv.update(inv_ref.onchange_partner_id(cr,uid, [], 'out_invoice', partner_ref)['value'])
652
 
                                inv['account_id'] = inv['account_id'] and inv['account_id'][0]
653
 
                                inv_id = inv_ref.create(cr, uid, inv, context)
654
 
                                invoices[partner_ref] = inv_id
655
 
                                self.write(cr,uid,[lot.id],{'ach_inv_id':inv_id,'state':'sold'})
656
 
 
657
 
                                #calcul des taxes
658
 
                                taxes = map(lambda x: x.id, lot.product_id.taxes_id)
659
 
                                taxes+=map(lambda x:x.id, lot.auction_id.buyer_costs)
660
 
                                if lot.author_right:
661
 
                                        taxes.append(lot.author_right.id)
662
 
 
663
 
                                inv_line= {
664
 
                                        'invoice_id': inv_id,
665
 
                                        'quantity': 1,
666
 
                                        'product_id': lot.product_id.id,
667
 
                                        'name': 'proforma'+'['+str(lot.obj_num)+'] '+ lot.name,
668
 
                                        'invoice_line_tax_id': [(6,0,taxes)],
669
 
                                        'account_analytic_id': lot.auction_id.account_analytic_id.id,
670
 
                                        'account_id': lot.auction_id.acc_income.id,
671
 
                                        'price_unit': lot.obj_price,
672
 
                                }
673
 
                                self.pool.get('account.invoice.line').create(cr, uid, inv_line,context)
674
 
                        #       inv_ref.button_compute(cr, uid, [inv_id])
675
 
                        #       wf_service = netsvc.LocalService('workflow')
676
 
                        #       wf_service.trg_validate(uid, 'account.invoice', inv_id, 'invoice_open', cr)
677
 
                        inv_ref.button_compute(cr, uid, invoice.values())
678
 
                        wf_service = netsvc.LocalService('workflow')
679
 
                        wf_service.trg_validate(uid, 'account.invoice', inv_id, 'invoice_proforma', cr)
680
 
                return invoices.values()
681
 
 
682
 
 
683
 
        # creates the transactions between the auction company and the seller
684
 
        # this is done by creating a new in_invoice for each
685
 
        def seller_trans_create(self,cr, uid,ids,context):
686
 
                """
687
 
                        Create a seller invoice for each bord_vnd_id, for selected ids.
688
 
                """
689
 
                # use each list of object in turn
690
 
                invoices = {}
691
 
                inv_ref=self.pool.get('account.invoice')
692
 
                for lot in self.browse(cr,uid,ids,context):
693
 
                        partner_id = lot.bord_vnd_id.partner_id.id
694
 
                        if not lot.auction_id.id:
695
 
                                continue
696
 
                        lot_name = lot.obj_num
697
 
                        if lot.bord_vnd_id.id in invoices:
698
 
                                inv_id = invoices[lot.bord_vnd_id.id]
699
 
                        else:
700
 
                                res = self.pool.get('res.partner').address_get(cr, uid, [lot.bord_vnd_id.partner_id.id], ['contact', 'invoice'])
701
 
                                contact_addr_id = res['contact']
702
 
                                invoice_addr_id = res['invoice']
703
 
                                inv = {
704
 
                                        'name': 'Auction:' +lot.name,
705
 
                                        'journal_id': lot.auction_id.journal_seller_id.id,
706
 
                                        'partner_id': lot.bord_vnd_id.partner_id.id,
707
 
                                        'type': 'in_invoice',
708
 
                                }
709
 
                                inv.update(inv_ref.onchange_partner_id(cr,uid, [], 'in_invoice', lot.bord_vnd_id.partner_id.id)['value'])
710
 
                        #       inv['account_id'] = inv['account_id'] and inv['account_id'][0]
711
 
                                inv_id = inv_ref.create(cr, uid, inv, context)
712
 
                                invoices[lot.bord_vnd_id.id] = inv_id
713
 
 
714
 
                        self.write(cr,uid,[lot.id],{'sel_inv_id':inv_id,'state':'sold'})
715
 
 
716
 
                        taxes = map(lambda x: x.id, lot.product_id.taxes_id)
717
 
                        if lot.bord_vnd_id.tax_id:
718
 
                                taxes.append(lot.bord_vnd_id.tax_id.id)
719
 
                        else:
720
 
                                taxes += map(lambda x: x.id, lot.auction_id.seller_costs)
721
 
 
722
 
                        inv_line= {
723
 
                                'invoice_id': inv_id,
724
 
                                'quantity': 1,
725
 
                                'product_id': lot.product_id.id,
726
 
                                'name': '['+str(lot.obj_num)+'] '+lot.auction_id.name,
727
 
                                'invoice_line_tax_id': [(6,0,taxes)],
728
 
                                'account_analytic_id': lot.auction_id.account_analytic_id.id,
729
 
                                'account_id': lot.auction_id.acc_expense.id,
730
 
                                'price_unit': lot.obj_price,
731
 
                        }
732
 
                        self.pool.get('account.invoice.line').create(cr, uid, inv_line,context)
733
 
                        inv_ref.button_compute(cr, uid, invoices.values())
734
 
                for inv in inv_ref.browse(cr, uid, invoices.values(), context):
735
 
                        inv_ref.write(cr, uid, [inv.id], {
736
 
                                'check_total': inv.amount_total
737
 
                        })
738
 
                        wf_service = netsvc.LocalService('workflow')
739
 
                        wf_service.trg_validate(uid, 'account.invoice', inv.id, 'invoice_open', cr)
740
 
                return invoices.values()
741
 
 
742
 
        def lots_invoice(self, cr, uid, ids, context,invoice_number=False):
743
 
                """(buyer invoice
744
 
                        Create an invoice for selected lots (IDS) to BUYER_ID.
745
 
                        Set created invoice to the ACTION state.
746
 
                        PRE:
747
 
                                ACTION:
748
 
                                        False: no action
749
 
                                        xxxxx: set the invoice state to ACTION
750
 
 
751
 
                        RETURN: id of generated invoice
752
 
                """
753
 
                dt = time.strftime('%Y-%m-%d')
754
 
                inv_ref=self.pool.get('account.invoice')
755
 
                invoices={}
756
 
                print "KKKKKKKKKKKKKKKKK"
757
 
                for lot in self.browse(cr, uid, ids,context):
758
 
                        print "LLLLLLLLLLLLLLLL"
759
 
                #       partner_ref = lot.ach_uid.id
760
 
                        if not lot.auction_id.id:
761
 
                                continue
762
 
                        partner_r=self.pool.get('res.partner')
763
 
                        if not lot.ach_uid.id:
764
 
                                raise orm.except_orm('Missed buyer !', 'The object "%s" has no buyer assigned.' % (lot.name,))
765
 
                        if (lot.auction_id.id,lot.ach_uid.id) in invoices:
766
 
                                inv_id = invoices[(lot.auction_id.id,lot.ach_uid.id)]
767
 
                        else:
768
 
                                price = lot.obj_price or 0.0
769
 
                                lot_name =lot.obj_num
770
 
                                inv={
771
 
                                        'name':lot.auction_id.name or '',
772
 
                                        'reference': lot.ach_login,
773
 
                                        'journal_id': lot.auction_id.journal_id.id,
774
 
                                        'partner_id': lot.ach_uid.id,
775
 
                                        'type': 'out_invoice',
776
 
                                }
777
 
                                if invoice_number:
778
 
                                        inv['number'] = invoice_number
779
 
                                inv.update(inv_ref.onchange_partner_id(cr,uid, [], 'out_invoice', lot.ach_uid.id)['value'])
780
 
                                #inv['account_id'] = inv['account_id'] and inv['account_id'][0]
781
 
                                inv_id = inv_ref.create(cr, uid, inv, context)
782
 
                                print "IN>>>>>>>>>>>>ID",inv_id
783
 
                                invoices[(lot.auction_id.id,lot.ach_uid.id)] = inv_id
784
 
                        self.write(cr,uid,[lot.id],{'ach_inv_id':inv_id,'state':'sold'})
785
 
                        #calcul des taxes
786
 
                        taxes = map(lambda x: x.id, lot.product_id.taxes_id)
787
 
                        taxes+=map(lambda x:x.id, lot.auction_id.buyer_costs)
788
 
                        if lot.author_right:
789
 
                                taxes.append(lot.author_right.id)
790
 
 
791
 
                        inv_line= {
792
 
                                'invoice_id': inv_id,
793
 
                                'quantity': 1,
794
 
                                'product_id': lot.product_id.id,
795
 
                                'name': '['+str(lot.obj_num)+'] '+ lot.name,
796
 
                                'invoice_line_tax_id': [(6,0,taxes)],
797
 
                                'account_analytic_id': lot.auction_id.account_analytic_id.id,
798
 
                                'account_id': lot.auction_id.acc_income.id,
799
 
                                'price_unit': lot.obj_price,
800
 
                        }
801
 
                        self.pool.get('account.invoice.line').create(cr, uid, inv_line,context)
802
 
        #       inv_ref.button_compute(cr, uid, [inpq tu dis cav_id])
803
 
        #               inv_ref.button_compute(cr, uid, [inv_id])
804
 
                        inv_ref.button_compute(cr, uid, [inv_id])
805
 
                for l in  inv_ref.browse(cr, uid, invoices.values(), context):
806
 
                        wf_service = netsvc.LocalService('workflow')
807
 
                #       wf_service.trg_validate(uid, 'account.invoice',l.id, 'invoice_proforma', cr)
808
 
                        wf_service.trg_validate(uid, 'account.invoice',l.id, 'invoice_open', cr)
809
 
                return invoices.values()
810
 
 
811
 
 
812
 
        def numerotate(self, cr, uid, ids):
813
 
                cr.execute('select auction_id from auction_lots where id=%d', (ids[0],))
814
 
                auc_id = cr.fetchone()[0]
815
 
                cr.execute('select max(obj_num) from auction_lots where auction_id=%d', (auc_id,))
816
 
                try:
817
 
                        max = cr.fetchone()[0]
818
 
                except:
819
 
                        max = 0
820
 
                for id in ids:
821
 
                        max+=1
822
 
                        cr.execute('update auction_lots set obj_num=%d where id=%d', (max, id))
823
 
                return []
824
 
 
825
 
auction_lots()
826
 
 
827
 
#----------------------------------------------------------
828
 
# Auction Bids
829
 
#----------------------------------------------------------
830
 
class auction_bid(osv.osv):
831
 
        _name = "auction.bid"
832
 
        _description="Bid auctions"
833
 
        _columns = {
834
 
                'partner_id': fields.many2one('res.partner', 'Buyer Name', required=True),
835
 
                'contact_tel':fields.char('Contact',size=64),
836
 
                'name': fields.char('Bid ID', size=64,required=True),
837
 
                'auction_id': fields.many2one('auction.dates', 'Auction Date', required=True),
838
 
                'bid_lines': fields.one2many('auction.bid_line', 'bid_id', 'Bid'),
839
 
        }
840
 
        _defaults = {
841
 
                'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'auction.bid'),
842
 
        }
843
 
        def onchange_contact(self, cr, uid, ids, partner_id):
844
 
                if not partner_id:
845
 
                        return {'value': {'contact_tel':False}}
846
 
                contact = self.pool.get('res.partner').browse(cr, uid, partner_id)
847
 
                v_contact=contact.address[0] and contact.address[0].phone or False
848
 
                return {'value': {'contact_tel': v_contact}}
849
 
 
850
 
auction_bid()
851
 
 
852
 
class auction_lot_history(osv.osv):
853
 
        _name = "auction.lot.history"
854
 
        _description="Lot history"
855
 
        _columns = {
856
 
                'name': fields.date('Date',size=64),
857
 
                'lot_id': fields.many2one('auction.lots','Object', required=True, ondelete='cascade'),
858
 
                'auction_id': fields.many2one('auction.dates', 'Auction date', required=True, ondelete='cascade'),
859
 
                'price': fields.float('Withdrawn price', digits=(16,2))
860
 
        }
861
 
        _defaults = {
862
 
                'name': lambda *args: time.strftime('%Y-%m-%d')
863
 
        }
864
 
auction_lot_history()
865
 
 
866
 
class auction_bid_lines(osv.osv):
867
 
        _name = "auction.bid_line"
868
 
        _description="Bid"
869
 
 
870
 
#       def get_nom(self,cr,uid,ids,*a):
871
 
#               res = {}
872
 
#               lots=self.browse(cr,uid,ids)
873
 
#               for lot in lots:
874
 
#                       res[lot.id] = lot.lot_id.auction_id.name
875
 
#                       print lot.lot_id.auction_id.name
876
 
#               return res
877
 
        _columns = {
878
 
                'name': fields.char('Bid date',size=64),
879
 
                'bid_id': fields.many2one('auction.bid','Bid ID', required=True, ondelete='cascade'),
880
 
                'lot_id': fields.many2one('auction.lots','Object', required=True, ondelete='cascade'),
881
 
                'call': fields.boolean('To be Called'),
882
 
                'price': fields.float('Maximum Price'),
883
 
                'auction': fields.char(string='Auction Name', size=64)
884
 
        }
885
 
        _defaults = {
886
 
                'name': lambda *args: time.strftime('%Y-%m-%d')
887
 
        }
888
 
 
889
 
        def onchange_name(self, cr, uid, ids, lot_id):
890
 
                if not lot_id:
891
 
                        return {'value': {'auction':False}}
892
 
                auctions = self.pool.get('auction.lots').browse(cr, uid, lot_id)
893
 
                v_auction=auctions.auction_id.name or False
894
 
                return {'value': {'auction': v_auction}}
895
 
 
896
 
 
897
 
auction_bid_lines()
898
 
 
899
 
class report_buyer_auction(osv.osv):
900
 
        _name = "report.buyer.auction"
901
 
        _description = "Auction Reporting on buyer view"
902
 
        _auto = False
903
 
        _columns = {
904
 
                'buyer_login': fields.char('Buyer Login',size=64, readonly=True, select=1),
905
 
                'buyer':fields.many2one('res.partner', 'Buyer', readonly=True, select=2),
906
 
                'object':fields.integer('No of objects',readonly=True, select=1),
907
 
                'total_price':fields.float('Total Adj.', digits=(16,2), readonly=True, select=2),
908
 
                'avg_price':fields.float('Avg Adj.', digits=(16,2), readonly=True, select=2),
909
 
                'date': fields.date('Create Date',  select=1),
910
 
                'auction': fields.many2one('auction.dates', 'Auction date',readonly=True, select=1),
911
 
 
912
 
        }
913
 
 
914
 
        def init(self, cr):
915
 
                cr.execute('''
916
 
                create or replace view report_buyer_auction  as (
917
 
                        select
918
 
                                min(al.id) as id,
919
 
                                al.ach_login as "buyer_login",
920
 
                                substring(al.create_date for 7) || '-01' as date,
921
 
                                al.ach_uid as "buyer",
922
 
                                ad.id as auction,
923
 
                                count(al.id) as "object",
924
 
                                sum(al.obj_price) as "total_price",
925
 
                                (sum(al.obj_price)/count(al.id)) as "avg_price"
926
 
                        from
927
 
                                auction_lots al,
928
 
                                auction_dates ad
929
 
                        where
930
 
                                ad.id=al.auction_id
931
 
                        group by
932
 
                                substring(al.create_date for 7),
933
 
                                al.ach_uid,
934
 
                                ad.id,
935
 
                                al.ach_login
936
 
                )''')
937
 
report_buyer_auction()
938
 
 
939
 
class report_buyer_auction2(osv.osv):
940
 
        _name = "report.buyer.auction2"
941
 
        _description = "Auction Reporting on buyer view"
942
 
        _auto = False
943
 
        _columns = {
944
 
                'auction': fields.many2one('auction.dates', 'Auction date',readonly=True, select=1),
945
 
                'buyer_login': fields.char('Buyer Login',size=64, readonly=True, select=True),
946
 
                'buyer':fields.many2one('res.partner', 'Buyer', readonly=True, select=2),
947
 
                'sumadj':fields.float('Sum of adjustication',readonly=True),
948
 
                'gross_revenue':fields.float('Gross Revenue', readonly=True),
949
 
                'net_revenue':fields.float('Net Revenue', readonly=True),
950
 
                'net_margin':fields.float('Net Margin', readonly=True),
951
 
                'date': fields.date('Create Date',  required=True)
952
 
        }
953
 
        def init(self, cr):
954
 
                cr.execute('''
955
 
                        create or replace view report_buyer_auction2  as (
956
 
                                select
957
 
                                        min(al.id) as id,
958
 
                                        substring(al.create_date for 7) || '-01' as date,
959
 
                                        al.ach_login as "buyer_login",
960
 
                                        al.ach_uid as "buyer",
961
 
                                        sum(al.obj_price) as sumadj,
962
 
                                        ad.id as auction,
963
 
                                        sum(al.gross_revenue) as gross_revenue,
964
 
                                        sum(al.net_revenue) as net_revenue,
965
 
                                        avg(al.net_margin) as net_margin
966
 
                                from
967
 
                                        auction_lots al,
968
 
                                        auction_dates ad
969
 
                                where
970
 
                                        al.auction_id=ad.id
971
 
                                group by
972
 
                                        al.ach_uid,
973
 
                                        al.ach_login,
974
 
                                        ad.id,
975
 
                                        substring(al.create_date for 7)
976
 
                        )''')
977
 
report_buyer_auction2()
978
 
 
979
 
 
980
 
class report_seller_auction(osv.osv):
981
 
        _name = "report.seller.auction"
982
 
        _description = "Auction Reporting on seller view"
983
 
        _auto = False
984
 
        _rec_name = 'date'
985
 
        _columns = {
986
 
                'auction': fields.many2one('auction.dates', 'Auction date',readonly=True, select=1),
987
 
                'seller': fields.many2one('res.partner','Seller',readonly=True, select=1),
988
 
                'object_number':fields.integer('No of Objects',readonly=True),
989
 
                'total_price':fields.float('Total adjudication',readonly=True),
990
 
                'avg_price':fields.float('Avg adjudication',readonly=True),
991
 
                'avg_estimation':fields.float('Avg estimation',readonly=True),
992
 
                'date': fields.date('Create Date',  required=True, select=1),
993
 
                'state': fields.selection((('draft','Draft'),('unsold','Unsold'),('sold','Sold')),'State',readonly=True, select=1)
994
 
        }
995
 
 
996
 
        def init(self, cr):
997
 
                cr.execute('''
998
 
                        create or replace view report_seller_auction  as (
999
 
                                select
1000
 
                                        adl.id as auction,
1001
 
                                        min(al.id) as id,
1002
 
                                        adl.auction1 as date,
1003
 
                                        ad.partner_id as seller,
1004
 
                                        count(al.id) as "object_number",
1005
 
                                        SUM(al.obj_price) as "total_price",
1006
 
                                        (SUM(al.obj_price)/count(al.id)) as avg_price,
1007
 
                                        sum(al.lot_est1+al.lot_est2)/2 as avg_estimation,
1008
 
                                        al.state
1009
 
                                from
1010
 
                                        auction_dates adl,
1011
 
                                        auction_lots al,
1012
 
                                        auction_deposit ad
1013
 
                                where
1014
 
                                        al.auction_id=adl.id and ad.id=al.bord_vnd_id
1015
 
                                group by
1016
 
                                        ad.partner_id,
1017
 
                                        al.state,adl.auction1,adl.id
1018
 
                                )''')
1019
 
report_seller_auction()
1020
 
 
1021
 
class report_seller_auction2(osv.osv):
1022
 
        _name = "report.seller.auction2"
1023
 
        _description = "Auction Reporting on seller view2"
1024
 
        _auto = False
1025
 
        _columns = {
1026
 
                'seller': fields.many2one('res.partner','Seller',readonly=True, select=1),
1027
 
                'auction': fields.many2one('auction.dates', 'Auction date',readonly=True, select=1),
1028
 
                'sum_adj':fields.float('Sum Adjustication',readonly=True, select=2),
1029
 
                'gross_revenue':fields.float('Gross revenue',readonly=True, select=2),
1030
 
                'net_revenue':fields.float('Net revenue',readonly=True, select=2),
1031
 
                'net_margin':fields.float('Net margin', readonly=True, select=2),
1032
 
                'date': fields.date('Auction date',  required=1),
1033
 
        }
1034
 
 
1035
 
        def init(self, cr):
1036
 
                cr.execute('''create or replace view report_seller_auction2  as
1037
 
                        (select
1038
 
                                min(al.id) as id,
1039
 
                                adl.auction1 as date,
1040
 
                                adl.id as auction,
1041
 
                                ad.partner_id as seller,
1042
 
                                sum(al.obj_price) as "sum_adj",
1043
 
                                sum(al.gross_revenue) as "gross_revenue",
1044
 
                                sum(al.net_revenue) as "net_revenue",
1045
 
                                avg(al.net_margin) as "net_margin"
1046
 
                        from
1047
 
                                auction_lots al,auction_dates adl,auction_deposit ad
1048
 
                        where
1049
 
                                adl.id=al.auction_id and ad.id=al.bord_vnd_id
1050
 
                        group by
1051
 
                                al.ach_uid,adl.auction1,adl.id,ad.partner_id)
1052
 
                         ''')
1053
 
 
1054
 
report_seller_auction2()
1055
 
 
1056
 
class report_auction_view2(osv.osv):
1057
 
        _name = "report.auction.view2"
1058
 
        _description = "Auction Reporting on  view2"
1059
 
        _auto = False
1060
 
        _rec_name = 'date'
1061
 
        _columns = {
1062
 
                'auction': fields.many2one('auction.dates', 'Auction date',readonly=True, select=1),
1063
 
                'sum_adj':fields.float('Sum of adjudication',readonly=True),
1064
 
                'obj_number':fields.integer('# of Objects',readonly=True),
1065
 
                'gross_revenue':fields.float('Gross revenue',readonly=True),
1066
 
                'net_revenue':fields.float('Net revenue',readonly=True),
1067
 
                'obj_margin':fields.float('Avg margin', readonly=True),
1068
 
                'obj_margin_procent':fields.float('Net margin (%)', readonly=True),
1069
 
                'date': fields.date('Auction date',  required=True, select=1)
1070
 
        }
1071
 
        def init(self, cr):
1072
 
                cr.execute('''create or replace view report_auction_view2 as (
1073
 
                        select
1074
 
                                ad.id as id,
1075
 
                                ad.auction1 as date,
1076
 
                                ad.id as "auction",
1077
 
                                count(al.id) as "obj_number",
1078
 
                                SUM(al.obj_price) as "sum_adj",
1079
 
                                SUM(al.gross_revenue) as "gross_revenue",
1080
 
                                SUM(al.net_revenue) as "net_revenue",
1081
 
                                avg(al.net_revenue) as "obj_margin",
1082
 
                                SUM(al.net_revenue)*100/sum(al.obj_price) as "obj_margin_procent"
1083
 
                        from
1084
 
                                auction_dates ad
1085
 
                        left join
1086
 
                                auction_lots al on (al.auction_id = ad.id)
1087
 
                        group by
1088
 
                                ad.id, ad.auction1
1089
 
                        having
1090
 
                                sum(al.obj_price) <> 0
1091
 
                        )''')
1092
 
report_auction_view2()
1093
 
 
1094
 
class report_auction_view(osv.osv):
1095
 
        _name = "report.auction.view"
1096
 
        _description = "Auction Reporting on view1"
1097
 
        _auto = False
1098
 
        _rec_name = 'auction_id'
1099
 
        _columns = {
1100
 
                'auction_id': fields.many2one('auction.dates', 'Auction date',readonly=True, select=1),
1101
 
                'nobjects':fields.float('No of objects',readonly=True),
1102
 
                'nbuyer':fields.float('No of buyers',readonly=True),
1103
 
                'nseller':fields.float('No of sellers',readonly=True),
1104
 
                'min_est':fields.float('Minimum Estimation', readonly=True, select=2),
1105
 
                'max_est':fields.float('Maximum Estimation', readonly=True, select=2),
1106
 
                'adj_price':fields.float('Adjudication price', readonly=True, select=2),
1107
 
                'obj_ret':fields.integer('# obj ret', readonly=True, select=2)
1108
 
        }
1109
 
 
1110
 
        def init(self, cr):
1111
 
                cr.execute('''create or replace view report_auction_view  as
1112
 
                        (select
1113
 
                                min(al.id) as id,
1114
 
                                al.auction_id as "auction_id",
1115
 
                                count(al.id) as "nobjects",
1116
 
                                count(al.ach_login) as "nbuyer",
1117
 
                                count(al.bord_vnd_id) as "nseller",
1118
 
                                sum(al.lot_est1) as "min_est",
1119
 
                                sum(al.lot_est2) as "max_est",
1120
 
                                (SELECT count(1) FROM auction_lots WHERE obj_ret>0) as obj_ret,
1121
 
                                sum(al.obj_price) as "adj_price"
1122
 
                        from
1123
 
                                auction_lots al
1124
 
                        group by
1125
 
                                al.auction_id
1126
 
                )''')
1127
 
 
1128
 
report_auction_view()
1129
 
 
1130
 
class report_auction_object_date(osv.osv):
1131
 
        _name = "report.auction.object.date"
1132
 
        _description = "Objects per day"
1133
 
        _auto = False
1134
 
        _columns = {
1135
 
                'obj_num': fields.integer('# of Objects'),
1136
 
                'name': fields.date('Created date', select=2),
1137
 
                'month': fields.date('Month', select=1),
1138
 
                'user_id':fields.many2one('res.users', 'User',select=1),
1139
 
        }
1140
 
 #l.create_uid as user,
1141
 
 
1142
 
        def init(self, cr):
1143
 
                cr.execute("""create or replace view report_auction_object_date as
1144
 
                        (select
1145
 
                           min(l.id) as id,
1146
 
                           substring(l.create_date for 10) as name,
1147
 
                           substring(l.create_date for 7)|| '-01' as month,
1148
 
                           count(l.obj_num) as obj_num,
1149
 
                           l.create_uid as user_id
1150
 
                        from
1151
 
                                auction_lots l
1152
 
                        group by
1153
 
                                substring(l.create_date for 10),
1154
 
                                substring(l.create_date for 7),
1155
 
                                l.create_uid
1156
 
                        )
1157
 
                """)
1158
 
report_auction_object_date()
1159
 
 
1160
 
class report_auction_estimation_adj_category(osv.osv):
1161
 
        _name = "report.auction.estimation.adj.category"
1162
 
        _description = "comparaison estimate/adjudication "
1163
 
        _auto = False
1164
 
        _rec_name='date'
1165
 
        _columns = {
1166
 
                        'lot_est1': fields.float('Minimum Estimation',select=2),
1167
 
                        'lot_est2': fields.float('Maximum Estimation',select=2),
1168
 
                        'obj_price': fields.float('Adjudication price'),
1169
 
                        'date': fields.date('Date', readonly=True,select=1),
1170
 
                        'lot_type': fields.selection(_type_get, 'Object Type', size=64),
1171
 
                        'adj_total': fields.float('Total Adjudication',select=2),
1172
 
                        'user_id':fields.many2one('res.users', 'User', select=1)
1173
 
        }
1174
 
 
1175
 
        def init(self, cr):
1176
 
                cr.execute("""
1177
 
                        create or replace view report_auction_estimation_adj_category as (
1178
 
                                select
1179
 
                                   min(l.id) as id,
1180
 
                                   substring(l.create_date for 7)||'-'||'01' as date,
1181
 
                                   l.lot_type as lot_type,
1182
 
                                   sum(l.lot_est1) as lot_est1,
1183
 
                                   sum(l.lot_est2) as lot_est2,
1184
 
                                   sum(l.obj_price) as adj_total,
1185
 
                                   l.create_uid as user_id
1186
 
                                from
1187
 
                                        auction_lots l,auction_dates m
1188
 
                                where
1189
 
                                        l.auction_id=m.id and l.obj_price >0
1190
 
                                group by
1191
 
                                         substring(l.create_date for 7),lot_type,l.create_uid
1192
 
                        )
1193
 
                """)
1194
 
report_auction_estimation_adj_category()
1195
 
 
1196
 
class report_auction_adjudication(osv.osv):
1197
 
        _name = "report.auction.adjudication"
1198
 
        _description = "report_auction_adjudication"
1199
 
        _auto = False
1200
 
        _columns = {
1201
 
                        'name': fields.many2one('auction.dates','Auction date',readonly=True,select=1),
1202
 
                        'state': fields.selection((('draft','Draft'),('close','Closed')),'State', select=1),
1203
 
                        'adj_total': fields.float('Total Adjudication'),
1204
 
                        'date': fields.date('Date', readonly=True,select=1),
1205
 
                        'user_id':fields.many2one('res.users', 'User',select=1)
1206
 
 
1207
 
        }
1208
 
 
1209
 
 
1210
 
        def init(self, cr):
1211
 
                cr.execute("""
1212
 
                        create or replace view report_auction_adjudication as (
1213
 
                                select
1214
 
                                        l.id as id,
1215
 
                                        l.id as name,
1216
 
                                        sum(m.obj_price) as adj_total,
1217
 
                                        substring(l.create_date for 7)||'-'||'01' as date,
1218
 
                                        l.create_uid as user_id,
1219
 
                                        l.state
1220
 
                                from
1221
 
                                        auction_dates l ,auction_lots m
1222
 
                                        where
1223
 
                                                m.auction_id=l.id
1224
 
                                        group by
1225
 
                                                l.id,l.state,l.name,l.create_uid,substring(l.create_date for 7)
1226
 
 
1227
 
                        )
1228
 
                """)
1229
 
report_auction_adjudication()
1230
 
 
1231
 
class report_attendance(osv.osv):
1232
 
        _name="report.attendance"
1233
 
        _description = "Report Sign In/Out"
1234
 
        _auto = False
1235
 
        #_rec_name='date'
1236
 
        _columns = {
1237
 
                'name': fields.date('Date', readonly=True,select=1),
1238
 
                'employee_id' : fields.many2one('hr.employee', 'Employee', select=1, readonly=True),
1239
 
                'total_attendance': fields.float('Total', readonly=True),
1240
 
}
1241
 
        def init(self, cr):
1242
 
                cr.execute("""CREATE OR REPLACE VIEW report_attendance AS
1243
 
                        SELECT
1244
 
                                id,
1245
 
                                name,
1246
 
                                employee_id,
1247
 
                                CASE WHEN SUM(total_attendance) < 0
1248
 
                                        THEN (SUM(total_attendance) +
1249
 
                                                CASE WHEN current_date <> name
1250
 
                                                        THEN 1440
1251
 
                                                        ELSE (EXTRACT(hour FROM current_time) * 60) + EXTRACT(minute FROM current_time)
1252
 
                                                END
1253
 
                                                )
1254
 
                                        ELSE SUM(total_attendance)
1255
 
                                END /60  as total_attendance
1256
 
                        FROM (
1257
 
                                SELECT
1258
 
                                        max(a.id) as id,
1259
 
                                        a.name::date as name,
1260
 
                                        a.employee_id,
1261
 
                                        SUM(((EXTRACT(hour FROM a.name) * 60) + EXTRACT(minute FROM a.name)) * (CASE WHEN a.action = 'sign_in' THEN -1 ELSE 1 END)) as total_attendance
1262
 
                                FROM hr_attendance a
1263
 
                                where name > current_date + interval '-1 day'
1264
 
                                GROUP BY a.name::date, a.employee_id
1265
 
                        ) AS fs
1266
 
                        GROUP BY name,fs.id,employee_id
1267
 
                        """)
1268
 
 
1269
 
report_attendance()
1270
 
 
1271
 
 
1272
 
class report_deposit_border(osv.osv):
1273
 
        _name="report.deposit.border"
1274
 
        _description = "Report deposit border"
1275
 
        _auto = False
1276
 
        _rec_name='bord'
1277
 
        _columns = {
1278
 
                'bord': fields.char('Depositer Inventory', size=64, required=True),
1279
 
                'seller': fields.many2one('res.partner','Seller',select=1),
1280
 
                'moy_est' : fields.float('Avg. Est', select=1, readonly=True),
1281
 
                'total_marge': fields.float('Total margin', readonly=True),
1282
 
                'nb_obj':fields.float('# of objects', readonly=True),
1283
 
}
1284
 
        def init(self, cr):
1285
 
                cr.execute("""CREATE OR REPLACE VIEW report_deposit_border AS
1286
 
                        SELECT
1287
 
                                min(al.id) as id,
1288
 
                                ab.partner_id as seller,
1289
 
                                ab.name as bord,
1290
 
                                COUNT(al.id) as nb_obj,
1291
 
                                SUM((al.lot_est1 + al.lot_est2)/2) as moy_est,
1292
 
                                SUM(al.net_revenue)/(count(ad.id)) as total_marge
1293
 
 
1294
 
                        FROM
1295
 
                                auction_lots al,auction_deposit ab,auction_dates ad
1296
 
                        WHERE
1297
 
                                ad.id=al.auction_id
1298
 
                                and al.bord_vnd_id=ab.id
1299
 
                        GROUP BY
1300
 
                                ab.name,ab.partner_id""")
1301
 
report_deposit_border()
1302
 
 
1303
 
class report_object_encoded(osv.osv):
1304
 
        _name = "report.object.encoded"
1305
 
        _description = "Object encoded"
1306
 
        _auto = False
1307
 
        _columns = {
1308
 
                'state': fields.selection((('draft','Draft'),('unsold','Unsold'),('paid','Paid'),('invoiced','Invoiced')),'State', required=True,select=1),
1309
 
                'user_id':fields.many2one('res.users', 'User', select=1),
1310
 
                'estimation': fields.float('Estimation',select=2),
1311
 
                'date': fields.date('Create Date',  required=True),
1312
 
                'gross_revenue':fields.float('Gross revenue',readonly=True, select=2),
1313
 
                'net_revenue':fields.float('Net revenue',readonly=True, select=2),
1314
 
                'obj_margin':fields.float('Net margin', readonly=True, select=2),
1315
 
                'obj_ret':fields.integer('# obj ret', readonly=True, select=2),
1316
 
                'adj':fields.integer('Adj.', readonly=True, select=2),
1317
 
                'obj_num':fields.integer('# of Encoded obj.', readonly=True, select=2),
1318
 
        }
1319
 
        def init(self, cr):
1320
 
                cr.execute('''create or replace view report_object_encoded  as
1321
 
                        (select min(al.id) as id,
1322
 
                                substring(al.create_date for 10) as date,
1323
 
                                al.state as state,
1324
 
                                al.create_uid as user_id,
1325
 
                                (SELECT count(1) FROM auction_lots WHERE obj_ret>0) as obj_ret,
1326
 
                                sum((100* al.lot_est1)/al.obj_price) as estimation,
1327
 
                                COUNT(al.product_id) as obj_num
1328
 
                        from auction_lots al
1329
 
                        where al.obj_price>0 and state='draft'
1330
 
                        group by substring(al.create_date for 10), al.state, al.create_uid)
1331
 
                         ''')
1332
 
report_object_encoded()
1333
 
 
1334
 
 
1335
 
class report_object_encoded_manager(osv.osv):
1336
 
        _name = "report.object.encoded.manager"
1337
 
        _description = "Object encoded"
1338
 
        _auto = False
1339
 
        _columns = {
1340
 
                'user_id':fields.many2one('res.users', 'User', select=True),
1341
 
                'estimation': fields.float('Estimation',select=True),
1342
 
                'date': fields.date('Create Date',  required=True),
1343
 
                'gross_revenue':fields.float('Gross revenue',readonly=True, select=True),
1344
 
                'net_revenue':fields.float('Net revenue',readonly=True, select=True),
1345
 
                'obj_margin':fields.float('Net margin', readonly=True, select=True),
1346
 
                'obj_ret':fields.integer('# obj ret', readonly=True, select=True),
1347
 
                'adj':fields.integer('Adj.', readonly=True, select=True),
1348
 
                'obj_num':fields.integer('# of Encoded obj.', readonly=True, select=True),
1349
 
        }
1350
 
        def init(self, cr):
1351
 
                cr.execute('''create or replace view report_object_encoded_manager  as
1352
 
                        (select
1353
 
                                min(al.id) as id,
1354
 
                                substring(al.create_date for 10) as date,
1355
 
                                al.create_uid as user_id,
1356
 
                                sum((100*lot_est1)/obj_price) as estimation,
1357
 
                                (SELECT count(1) FROM auction_lots WHERE obj_ret>0) as obj_ret,
1358
 
                                SUM(al.gross_revenue) as "gross_revenue",
1359
 
                                SUM(al.net_revenue) as "net_revenue",
1360
 
                                SUM(al.net_revenue)/count(al.id) as "obj_margin",
1361
 
                                COUNT(al.product_id) as obj_num,
1362
 
                                SUM(al.obj_price) as "adj"
1363
 
                        from auction_lots al
1364
 
                        where al.obj_price>0
1365
 
                        group by substring(al.create_date for 10), al.create_uid)
1366
 
                         ''')
1367
 
report_object_encoded_manager()
1368
 
 
1369
 
class report_unclassified_objects(osv.osv):
1370
 
        _name = "report.unclassified.objects"
1371
 
        _description = "Unclassified objects "
1372
 
        _auto = False
1373
 
        _columns = {
1374
 
                'name': fields.char('Short Description',size=64, required=True),
1375
 
                'obj_num': fields.integer('Catalog Number'),
1376
 
                'obj_price': fields.float('Adjudication price'),
1377
 
                'lot_num': fields.integer('List Number', required=True, select=1 ),
1378
 
                'state': fields.selection((('draft','Draft'),('unsold','Unsold'),('paid','Paid'),('sold','Sold')),'State', required=True, readonly=True),
1379
 
                'obj_comm': fields.boolean('Commission'),
1380
 
                'bord_vnd_id': fields.many2one('auction.deposit', 'Depositer Inventory', required=True),
1381
 
                'ach_login': fields.char('Buyer Username',size=64),
1382
 
                'lot_est1': fields.float('Minimum Estimation'),
1383
 
                'lot_est2': fields.float('Maximum Estimation'),
1384
 
                'lot_type': fields.selection(_type_get, 'Object category', size=64),
1385
 
                'auction': fields.many2one('auction.dates', 'Auction date',readonly=True, select=1),
1386
 
        }
1387
 
        def init(self, cr):
1388
 
                cr.execute("""create or replace view report_unclassified_objects as
1389
 
                        (select
1390
 
                                min(al.id) as id,
1391
 
                                al.name as name,
1392
 
                                al.obj_price as obj_price,
1393
 
                                al.obj_num as obj_num,
1394
 
                                al.lot_num as lot_num,
1395
 
                                al.state as state,
1396
 
                                al.obj_comm as obj_comm,
1397
 
                                al.bord_vnd_id as bord_vnd_id,
1398
 
                                al.ach_login as ach_login,
1399
 
                                al.lot_est1 as lot_est1,
1400
 
                                al.lot_est2 as lot_est2,
1401
 
                                al.lot_type as lot_type,
1402
 
                                al.auction_id as auction
1403
 
                        from auction_lots al,auction_lot_category ac
1404
 
                        where (al.lot_type=ac.name) AND (ac.aie_categ='41') AND (al.auction_id is null)
1405
 
group by al.obj_price,al.obj_num, al.lot_num, al.state, al.obj_comm,al.bord_vnd_id,al.ach_login,al.lot_est1,al.lot_est2,al.lot_type,al.auction_id,al.name)
1406
 
                         """)
1407
 
report_unclassified_objects()
1408