Launchpad automatic translations update.
[odoo/odoo.git] / addons / auction / auction.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
6 #
7 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU Affero General Public License as
9 #    published by the Free Software Foundation, either version 3 of the
10 #    License, or (at your option) any later version.
11 #
12 #    This program is distributed in the hope that it will be useful,
13 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #    GNU Affero General Public License for more details.
16 #
17 #    You should have received a copy of the GNU Affero General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 #
20 ##############################################################################
21 from osv import fields, osv, orm
22 from tools.translate import _
23 import netsvc
24 import time
25
26 #----------------------------------------------------------
27 # Auction Artists
28 #----------------------------------------------------------
29
30 class auction_artists(osv.osv):
31     _name = "auction.artists"
32     _columns = {
33         'name': fields.char('Artist/Author Name', size=64, required=True),
34         'pseudo': fields.char('Pseudo', size=64),
35         'birth_death_dates':fields.char('Lifespan', size=64),
36         'biography': fields.text('Biography'),
37     }
38 auction_artists()
39
40 #----------------------------------------------------------
41 # Auction Dates
42 #----------------------------------------------------------
43 class auction_dates(osv.osv):
44     """Auction Dates"""
45     _name = "auction.dates"
46     _description=__doc__
47
48     def _adjudication_get(self, cr, uid, ids, prop, unknow_none, unknow_dict):
49         res={}
50         total = 0.0
51         lots_obj = self.pool.get('auction.lots')
52         for auction in self.browse(cr, uid, ids):
53             lots_ids = lots_obj.search(cr, uid, [('auction_id', '=', auction.id)])
54             for lots in lots_obj.browse(cr, uid, lots_ids):
55                 total+=lots.obj_price or 0.0
56                 res[auction.id]=total
57         return res
58
59     def name_get(self, cr, uid, ids, context=None):
60         if not ids:
61             return []
62         reads = self.read(cr, uid, ids, ['name', 'auction1'], context=context)
63         name = [(r['id'], '['+r['auction1']+'] '+ r['name']) for r in reads]
64         return name
65
66     def _get_invoice(self, cr, uid, ids, name, arg, context=None):
67         lots_obj = self.pool.get('auction.lots')
68         result = {}
69         for data in self.browse(cr, uid, ids, context=context):
70             buyer_inv_ids = []
71             seller_inv_ids = []
72             result[data.id] = {
73                 'seller_invoice_history': buyer_inv_ids,
74                 'buyer_invoice_history': seller_inv_ids,
75             }
76             lots_ids = lots_obj.search(cr, uid, [('auction_id','=',data.id)])
77             for lot in lots_obj.browse(cr, uid, lots_ids, context=context):
78                 if lot.ach_inv_id:
79                     buyer_inv_ids.append(lot.ach_inv_id.id)
80                 if lot.sel_inv_id:
81                     seller_inv_ids.append(lot.sel_inv_id.id)
82             result[data.id]['seller_invoice_history'] = seller_inv_ids
83             result[data.id]['buyer_invoice_history'] = buyer_inv_ids
84         return result
85
86     _columns = {
87         'name': fields.char('Auction Name', size=64, required=True),
88         'expo1': fields.date('First Exposition Day', required=True, help="Beginning exposition date for auction"),
89         'expo2': fields.date('Last Exposition Day', required=True, help="Last exposition date for auction"),
90         'auction1': fields.date('First Auction Day', required=True, help="Start date of auction"),
91         'auction2': fields.date('Last Auction Day', required=True, help="End date of auction"),
92         'journal_id': fields.many2one('account.journal', 'Buyer Journal', required=True, help="Account journal for buyer"),
93         'journal_seller_id': fields.many2one('account.journal', 'Seller Journal', required=True, help="Account journal for seller"),
94         'buyer_costs': fields.many2many('account.tax', 'auction_buyer_taxes_rel', 'auction_id', 'tax_id', 'Buyer Costs', help="Account tax for buyer"),
95         'seller_costs': fields.many2many('account.tax', 'auction_seller_taxes_rel', 'auction_id', 'tax_id', 'Seller Costs', help="Account tax for seller"),
96         'acc_income': fields.many2one('account.account', 'Income Account', required=True),
97         'acc_expense': fields.many2one('account.account', 'Expense Account', required=True),
98         'adj_total': fields.function(_adjudication_get, method=True, string='Total Adjudication', store=True),
99         'state': fields.selection((('draft', 'Draft'), ('closed', 'Closed')), 'State', select=1, readonly=True,
100                                   help='When auction starts the state is \'Draft\'.\n At the end of auction, the state becomes \'Closed\'.'),
101         'account_analytic_id': fields.many2one('account.analytic.account', 'Analytic Account', required=False),
102         'buyer_invoice_history': fields.function(_get_invoice, relation='account.invoice', method=True, string="Buyer Invoice", type='many2many', multi=True),
103         'seller_invoice_history': fields.function(_get_invoice, relation='account.invoice', method=True, string="Seller Invoice", type='many2many', multi=True),
104     }
105
106     _defaults = {
107         'state': lambda *a: 'draft',
108     }
109
110     _order = "auction1 desc"
111
112     def close(self, cr, uid, ids, context=None):
113         """
114         Close an auction date.
115
116         Create invoices for all buyers and sellers.
117         STATE ='close'
118
119         RETURN: True
120         """
121         lots_obj = self.pool.get('auction.lots')
122         lots_ids = lots_obj.search(cr, uid, [('auction_id', 'in', ids), ('state', '=', 'draft'), ('obj_price', '>', 0)])
123         lots_obj.lots_invoice(cr, uid, lots_ids, {}, None)
124         lots_ids2 = lots_obj.search(cr, uid, [('auction_id', 'in', ids), ('obj_price', '>', 0)])
125         lots_obj.seller_trans_create(cr, uid, lots_ids2, {})
126         self.write(cr, uid, ids, {'state': 'closed'}) #close the auction
127         return True
128
129 auction_dates()
130
131 #----------------------------------------------------------
132 # Deposits
133 #----------------------------------------------------------
134 class auction_deposit(osv.osv):
135     """Auction Deposit Border"""
136
137     _name = "auction.deposit"
138     _description=__doc__
139     _order = "id desc"
140     _columns = {
141         'transfer' : fields.boolean('Transfer'),
142         'name': fields.char('Depositer Inventory', size=64, required=True),
143         'partner_id': fields.many2one('res.partner', 'Seller', required=True, change_default=True),
144         'date_dep': fields.date('Deposit date', required=True),
145         'method': fields.selection((('keep', 'Keep until sold'), ('decease', 'Decrease limit of 10%'), ('contact', 'Contact the Seller')), 'Withdrawned method', required=True),
146         'tax_id': fields.many2one('account.tax', 'Expenses'),
147         'create_uid': fields.many2one('res.users', 'Created by', readonly=True),
148         'info': fields.char('Description', size=64),
149         'lot_id': fields.one2many('auction.lots', 'bord_vnd_id', 'Objects'),
150         'specific_cost_ids': fields.one2many('auction.deposit.cost', 'deposit_id', 'Specific Costs'),
151         'total_neg': fields.boolean('Allow Negative Amount'),
152     }
153     _defaults = {
154         'method': lambda *a: 'keep',
155         'total_neg': lambda *a: False,
156         'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'auction.deposit'),
157     }
158
159 auction_deposit()
160
161 #----------------------------------------------------------
162 # (Specific) Deposit Costs
163 #----------------------------------------------------------
164 class auction_deposit_cost(osv.osv):
165
166     """Auction Deposit Cost"""
167
168     _name = 'auction.deposit.cost'
169     _description=__doc__
170     _columns = {
171         'name': fields.char('Cost Name', required=True, size=64),
172         'amount': fields.float('Amount'),
173         'account': fields.many2one('account.account', 'Destination Account', required=True),
174         'deposit_id': fields.many2one('auction.deposit', 'Deposit'),
175     }
176 auction_deposit_cost()
177
178 #----------------------------------------------------------
179 # Lots Categories
180 #----------------------------------------------------------
181 class aie_category(osv.osv):
182
183     _name="aie.category"
184     _order = "name"
185     _columns={
186        'name': fields.char('Name', size=64, required=True),
187        'code':fields.char('Code', size=64),
188        'parent_id': fields.many2one('aie.category', 'Parent aie Category', ondelete='cascade'),
189        'child_ids': fields.one2many('aie.category', 'parent_id', help="children aie category")
190     }
191
192     def name_get(self, cr, uid, ids, context=None):
193         res = []
194         if not ids:
195             return res
196         reads = self.read(cr, uid, ids, ['name', 'parent_id'], context=context)
197         for record in reads:
198             name = record['name']
199             if record['parent_id']:
200                 name = record['parent_id'][1] + ' / ' + name
201             res.append((record['id'], name))
202         return res
203
204 aie_category()
205
206 class auction_lot_category(osv.osv):
207     """Auction Lots Category"""
208
209     _name = 'auction.lot.category'
210     _description=__doc__
211     _columns = {
212         'name': fields.char('Category Name', required=True, size=64),
213         'priority': fields.float('Priority'),
214         'active' : fields.boolean('Active', help="If the active field is set to False, it will allow you to hide the auction lot category without removing it."),
215         'aie_categ': fields.many2one('aie.category', 'Category', ondelete='cascade'),
216     }
217     _defaults = {
218         'active' : lambda *a: 1,
219     }
220 auction_lot_category()
221
222 #----------------------------------------------------------
223 # Lots
224 #----------------------------------------------------------
225 def _type_get(self, cr, uid, context=None):
226     obj = self.pool.get('auction.lot.category')
227     ids = obj.search(cr, uid, [])
228     res = obj.read(cr, uid, ids, ['name'], context)
229     res = [(r['name'], r['name']) for r in res]
230     return res
231
232 class auction_lots(osv.osv):
233
234     """Auction Object"""
235     _name = "auction.lots"
236     _order = "obj_num,lot_num,id"
237     _description=__doc__
238
239     def button_not_bought(self, cr, uid, ids, context=None):
240         return self.write(cr, uid, ids, {'state':'unsold'})
241
242     def button_taken_away(self, cr, uid, ids, context=None):
243         return self.write(cr, uid, ids, {'state':'taken_away', 'ach_emp': True})
244
245     def button_unpaid(self, cr, uid, ids, context=None):
246         return self.write(cr, uid, ids, {'state':'draft'})
247
248     def button_bought(self, cr, uid, ids, context=None):
249         return self.write(cr, uid, ids, {'state':'sold'})
250
251     def _getprice(self, cr, uid, ids, fields, args, context=None):
252         """This Function compute amount total with tax for buyer and seller.
253         @param ids: List of  auction lots's id
254         @param name: List of function fields.
255         @param context: A standard dictionary for contextual values
256         @return: Dictionary of function fields value.
257         """
258
259         res = {}
260         account_analytic_line_obj = self.pool.get('account.analytic.line')
261         lots = self.browse(cr, uid, ids, context=context)
262         pt_tax = self.pool.get('account.tax')
263         for lot in lots:
264             taxes = []
265             for name in fields:
266                 res[lot.id] = {name: False}
267                 amount = lot.obj_price or 0.0
268                 result = 0.0
269                 if name == "buyer_price":
270                     if lot.author_right:
271                         taxes.append(lot.author_right)
272                     if lot.auction_id:
273                         taxes += lot.auction_id.buyer_costs
274                     tax = pt_tax.compute_all(cr, uid, taxes, amount, 1)['taxes']
275                     for t in tax:
276                         result += t.get('amount', 0.0)
277                     result += amount
278                 elif name == "seller_price":
279                     if lot.bord_vnd_id.tax_id:
280                         taxes.append(lot.bord_vnd_id.tax_id)
281                     elif lot.auction_id and lot.auction_id.seller_costs:
282                         taxes += lot.auction_id.seller_costs
283                     tax = pt_tax.compute_all(cr, uid, taxes, amount, 1)['taxes']
284                     for t in tax:
285                         result += t.get('amount', 0.0)
286                     result += amount
287                 elif name == "gross_revenue":
288                     if lot.auction_id:
289                         result = lot.buyer_price - lot.seller_price
290
291                 elif name == "net_revenue":
292                     if lot.auction_id:
293                         result = lot.buyer_price - lot.seller_price - lot.costs
294
295                 elif name == "gross_margin":
296                    if ((lot.obj_price==0) and (lot.state=='draft')):
297                      amount = lot.lot_est1
298                    else:
299                      amount = lot.obj_price
300                    if amount > 0:
301                      result = (lot.gross_revenue * 100) / amount
302                      result = round(result,2)
303
304                 elif name == "net_margin":
305                     if ((lot.obj_price==0) and (lot.state=='draft')):
306                         amount = lot.lot_est1
307                     else:
308                         amount = lot.obj_price
309                     if amount > 0:
310                         result = (lot.net_revenue * 100) / amount
311                         result = round(result,2)
312                 elif name == "costs":
313                     # costs: Total credit of analytic account
314                     # objects sold during this auction (excluding analytic lines that are in the analytic journal of the auction date)
315                     #TOCHECK: Calculation OF Indirect Cost
316                     som = 0.0
317                     if lot.auction_id:
318                         auct_id = lot.auction_id.id
319                         lot_count = self.search(cr, uid, [('auction_id', '=', auct_id)], count=True)
320                         line_ids = account_analytic_line_obj.search(cr, uid, [
321                                     ('account_id', '=', lot.auction_id.account_analytic_id.id),
322                                     ('journal_id', '<>', lot.auction_id.journal_id.id),
323                                     ('journal_id', '<>', lot.auction_id.journal_seller_id.id)])
324                         for r in lot.bord_vnd_id.specific_cost_ids:
325                             som += r.amount
326                         for line in account_analytic_line_obj.browse(cr, uid, line_ids, context=context):
327                             if line.amount:
328                                 som -= line.amount
329                         result = som/lot_count
330
331                 elif name=="paid_ach":
332                     result = False
333                     if lot.ach_inv_id and lot.ach_inv_id.state == 'paid':
334                         result = True
335
336                 elif name=="paid_vnd":
337                     result = False
338                     if lot.sel_inv_id and lot.sel_inv_id.state == 'paid':
339                         result = True
340
341                 res[lot.id][name] = result
342
343
344         return res
345
346     def onchange_obj_ret(self, cr, uid, ids, obj_ret, context=None):
347         if obj_ret:
348             return {'value': {'obj_price': 0}}
349         return {}
350
351     _columns = {
352         'bid_lines':fields.one2many('auction.bid_line', 'lot_id', 'Bids'),
353         'auction_id': fields.many2one('auction.dates', 'Auction', select=1, help="Auction for object"),
354         'bord_vnd_id': fields.many2one('auction.deposit', 'Depositer Inventory', required=True, help="Provide deposit information: seller, Withdrawned Method, Object, Deposit Costs"),
355         'name': fields.char('Title', size=64, required=True, help='Auction object name'),
356         'name2': fields.char('Short Description (2)', size=64),
357         'lot_type': fields.selection(_type_get, 'Object category', size=64),
358         'author_right': fields.many2one('account.tax', 'Author rights', help="Account tax for author commission"),
359         'lot_est1': fields.float('Minimum Estimation', help="Minimum Estimate Price"),
360         'lot_est2': fields.float('Maximum Estimation', help="Maximum Estimate Price"),
361         'lot_num': fields.integer('List Number', required=True, select=1, help="List number in depositer inventory"),
362         'create_uid': fields.many2one('res.users', 'Created by', readonly=True),
363         'history_ids':fields.one2many('auction.lot.history', 'lot_id', 'Auction history'),
364         'lot_local':fields.char('Location', size=64, help="Auction Location"),
365         'artist_id':fields.many2one('auction.artists', 'Artist/Author'),
366         'artist2_id':fields.many2one('auction.artists', 'Artist/Author2'),
367         'important':fields.boolean('To be Emphatized'),
368         'product_id':fields.many2one('product.product', 'Product', required=True),
369         'obj_desc': fields.text('Object Description'),
370         'obj_num': fields.integer('Catalog Number'),
371         'obj_ret': fields.float('Price retired', help="Object Ret"),
372         'obj_comm': fields.boolean('Commission'),
373         'obj_price': fields.float('Adjudication price', help="Object Price"),
374         'ach_avance': fields.float('Buyer Advance'),
375         'ach_login': fields.char('Buyer Username', size=64),
376         'ach_uid': fields.many2one('res.partner', 'Buyer'),
377         'seller_id': fields.related('bord_vnd_id','partner_id', type='many2one', relation='res.partner', string='Seller', readonly=True),
378         'ach_emp': fields.boolean('Taken Away', readonly=True, help="When state is Taken Away, this field is marked as True"),
379         'is_ok': fields.boolean('Buyer\'s payment', help="When buyer pay for bank statement', this field is marked"),
380         'ach_inv_id': fields.many2one('account.invoice', 'Buyer Invoice', readonly=True, states={'draft':[('readonly', False)]}),
381         'sel_inv_id': fields.many2one('account.invoice', 'Seller Invoice', readonly=True, states={'draft':[('readonly', False)]}),
382         'vnd_lim': fields.float('Seller limit'),
383         'vnd_lim_net': fields.boolean('Net limit ?', readonly=True),
384         'image': fields.binary('Image', help="Object Image"),
385         'paid_vnd':fields.function(_getprice, string='Seller Paid', method=True, type='boolean', store=True, multi="paid_vnd", help="When state of Seller Invoice is 'Paid', this field is selected as True."),
386         'paid_ach':fields.function(_getprice, string='Buyer Invoice Reconciled', method=True, type='boolean', store=True, multi="paid_ach", help="When state of Buyer Invoice is 'Paid', this field is selected as True."),
387         'state': fields.selection((
388             ('draft', 'Draft'),
389             ('unsold', 'Unsold'),
390             ('paid', 'Paid'),
391             ('sold', 'Sold'),
392             ('taken_away', 'Taken away')), 'State', required=True, readonly=True,
393             help=' * The \'Draft\' state is used when a object is encoding as a new object. \
394                 \n* The \'Unsold\' state is used when object does not sold for long time, user can also set it as draft state after unsold. \
395                 \n* The \'Paid\' state is used when user pay for the object \
396                 \n* The \'Sold\' state is used when user buy the object.'),
397         'buyer_price': fields.function(_getprice, method=True, string='Buyer price', store=True, multi="buyer_price", help="Buyer Price"),
398         'seller_price': fields.function(_getprice, method=True, string='Seller price', store=True, multi="seller_price", help="Seller Price"),
399         'gross_revenue':fields.function(_getprice, method=True, string='Gross revenue', store=True, multi="gross_revenue", help="Buyer Price - Seller Price"),
400         'gross_margin':fields.function(_getprice, method=True, string='Gross Margin (%)', store=True, multi="gross_margin", help="(Gross Revenue*100.0)/ Object Price"),
401         'costs':fields.function(_getprice, method=True, string='Indirect costs', store=True, multi="costs", help="Deposit cost"),
402         'statement_id': fields.many2many('account.bank.statement.line', 'auction_statement_line_rel', 'auction_id', 'statement', 'Payment', help="Bank statement line for given buyer"),
403         'net_revenue':fields.function(_getprice, method=True, string='Net revenue', store=True, multi="net_revenue", help="Buyer Price - Seller Price - Indirect Cost"),
404         'net_margin':fields.function(_getprice, method=True, string='Net Margin (%)', store=True, multi="net_margin", help="(Net Revenue * 100)/ Object Price"),
405     }
406     _defaults = {
407         'state':lambda *a: 'draft',
408         'lot_num':lambda *a:1,
409         'is_ok': lambda *a: False,
410     }
411
412     def name_get(self, cr, user, ids, context=None):
413         if not ids:
414             return []
415         result = [ (r['id'], str(r['obj_num'])+' - '+r['name']) for r in self.read(cr, user, ids, ['name', 'obj_num'])]
416         return result
417
418     def name_search(self, cr, user, name, args=None, operator='ilike', context=None):
419         if not args:
420             args = []
421         ids = []
422         if name:
423             ids = self.search(cr, user, [('obj_num', '=', int(name))] + args)
424         if not ids:
425             ids = self.search(cr, user, [('name', operator, name)] + args)
426         return self.name_get(cr, user, ids)
427
428     def _sum_taxes_by_type_and_id(self, taxes):
429         """
430         PARAMS: taxes: a list of dictionaries of the form {'id':id, 'amount':amount, ...}
431         RETURNS : a list of dictionaries of the form {'id':id, 'amount':amount, ...}; one dictionary per unique id.
432             The others fields in the dictionaries (other than id and amount) are those of the first tax with a particular id.
433         """
434         taxes_summed = {}
435         for tax in taxes:
436             key = (tax['type'], tax['id'])
437             if key in taxes_summed:
438                 taxes_summed[key]['amount'] += tax['amount']
439             else:
440                 taxes_summed[key] = tax
441         return taxes_summed.values()
442
443     def compute_buyer_costs(self, cr, uid, ids):
444         amount_total = {}
445         lots = self.browse(cr, uid, ids)
446         ##CHECKME: Is that AC would be worthwhile to make groups of lots that have the same costs to spend a lot of lists compute?
447         taxes = []
448         amount=0.0
449         pt_tax = self.pool.get('account.tax')
450         for lot in lots:
451             taxes = lot.product_id.taxes_id
452             if lot.author_right:
453                 taxes.append(lot.author_right)
454             elif lot.auction_id:
455                 taxes += lot.auction_id.buyer_costs
456             tax=pt_tax.compute_all(cr, uid, taxes, lot.obj_price, 1)['taxes']
457             for t in tax:
458                 amount+=t['amount']
459         amount_total['value']= amount
460         amount_total['amount']= amount
461
462         return amount_total
463
464
465     def _compute_lot_seller_costs(self, cr, uid, lot, manual_only=False):
466         costs = []
467         tax_cost_ids=[]
468
469         border_id = lot.bord_vnd_id
470         if border_id:
471             if border_id.tax_id:
472                 tax_cost_ids.append(border_id.tax_id)
473             elif lot.auction_id and lot.auction_id.seller_costs:
474                 tax_cost_ids += lot.auction_id.seller_costs
475
476         tax_costs = self.pool.get('account.tax').compute_all(cr, uid, tax_cost_ids, lot.obj_price, 1)['taxes']
477         # delete useless keys from the costs computed by the tax object... this is useless but cleaner...
478         for cost in tax_costs:
479             del cost['account_paid_id']
480             del cost['account_collected_id']
481
482         if not manual_only:
483             costs.extend(tax_costs)
484             for c in costs:
485                 c.update({'type': 0})
486 ######
487         if lot.vnd_lim_net<0 and lot.obj_price>0:
488             #FIXME:the string passes have lot 'should go through the system translations.
489             obj_price_wh_costs = reduce(lambda x, y: x + y['amount'], tax_costs, lot.obj_price)
490             if obj_price_wh_costs < lot.vnd_lim:
491                 costs.append({  'type': 1,
492                                 'id': lot.obj_num,
493                                 'name': 'Remise lot '+ str(lot.obj_num),
494                                 'amount': lot.vnd_lim - obj_price_wh_costs}
495                             )
496         return costs
497
498     def compute_seller_costs(self, cr, uid, ids, manual_only=False):
499         lots = self.browse(cr, uid, ids)
500         costs = []
501
502         # group objects (lots) by deposit id
503         # ie create a dictionary containing lists of objects
504         bord_lots = {}
505         for lot in lots:
506             key = lot.bord_vnd_id.id
507             if not key in bord_lots:
508                 bord_lots[key] = []
509             bord_lots[key].append(lot)
510
511         # use each list of object in turn
512         for lots in bord_lots.values():
513             total_adj = 0
514             total_cost = 0
515             for lot in lots:
516                 total_adj += lot.obj_price or 0.0
517                 lot_costs = self._compute_lot_seller_costs(cr, uid, lot, manual_only)
518                 for c in lot_costs:
519                     total_cost += c['amount']
520                 costs.extend(lot_costs)
521             bord = lots[0].bord_vnd_id
522             if bord:
523                 if bord.specific_cost_ids:
524                     bord_costs = [{'type':2, 'id':c.id, 'name':c.name, 'amount':c.amount, 'account_id':c.account} for c in bord.specific_cost_ids]
525                     for c in bord_costs:
526                         total_cost += c['amount']
527                     costs.extend(bord_costs)
528             if (total_adj+total_cost)<0:
529                 #FIXME: translate tax name
530                 new_id = bord and bord.id or 0
531                 c = {'type':3, 'id':new_id, 'amount':-total_cost-total_adj, 'name':'Ristourne'}
532                 costs.append(c)
533         return self._sum_taxes_by_type_and_id(costs)
534
535     # sum remise limite net and ristourne
536     def compute_seller_costs_summed(self, cr, uid, ids): #ach_pay_id
537
538         """This Fuction  sum Net remittance limit and refund"""
539
540         taxes = self.compute_seller_costs(cr, uid, ids)
541         taxes_summed = {}
542         for tax in taxes:
543             if tax['type'] == 1:
544                 tax['id'] = 0
545                 #FIXME: translate tax names
546                 tax['name'] = 'Discount sharp boundary'
547             elif tax['type'] == 2:
548                 tax['id'] = 0
549                 tax['name'] = 'Miscellaneous expenditure'
550             elif tax['type'] == 3:
551                 tax['id'] = 0
552                 tax['name'] = 'Cross.'
553             key = (tax['type'], tax['id'])
554             if key in taxes_summed:
555                 taxes_summed[key]['amount'] += tax['amount']
556             else:
557                 taxes_summed[key] = tax
558         return taxes_summed.values()
559
560     def buyer_proforma(self, cr, uid, ids, context=None):
561
562         invoices = {}
563         inv_ref = self.pool.get('account.invoice')
564         res_obj = self.pool.get('res.partner')
565         inv_line_obj = self.pool.get('account.invoice.line')
566         wf_service = netsvc.LocalService('workflow')
567         for lot in self.browse(cr, uid, ids, context=context):
568             if not lot.obj_price>0:
569                 continue
570             if not lot.ach_uid.id:
571                 raise orm.except_orm(_('Missed buyer !'), _('The object "%s" has no buyer assigned.') % (lot.name,))
572             else:
573                 partner_ref =lot.ach_uid.id
574                 res = res_obj.address_get(cr, uid, [partner_ref], ['contact', 'invoice'])
575                 contact_addr_id = res['contact']
576                 invoice_addr_id = res['invoice']
577                 if not invoice_addr_id:
578                     raise orm.except_orm(_('No Invoice Address'), _('The Buyer "%s" has no Invoice Address.') % (contact_addr_id,))
579                 inv = {
580                     'name': 'Auction proforma:' +lot.name,
581                     'journal_id': lot.auction_id.journal_id.id,
582                     'partner_id': partner_ref,
583                     'type': 'out_invoice',
584                 }
585                 inv.update(inv_ref.onchange_partner_id(cr, uid, [], 'out_invoice', partner_ref)['value'])
586                 inv['account_id'] = inv['account_id'] and inv['account_id'][0]
587                 inv_id = inv_ref.create(cr, uid, inv, context)
588                 invoices[partner_ref] = inv_id
589                 self.write(cr, uid, [lot.id], {'ach_inv_id':inv_id, 'state':'sold'})
590
591                 #calcul des taxes
592                 taxes = map(lambda x: x.id, lot.product_id.taxes_id)
593                 taxes+=map(lambda x:x.id, lot.auction_id.buyer_costs)
594                 if lot.author_right:
595                     taxes.append(lot.author_right.id)
596
597                 inv_line= {
598                     'invoice_id': inv_id,
599                     'quantity': 1,
600                     'product_id': lot.product_id.id,
601                     'name': 'proforma'+'['+str(lot.obj_num)+'] '+ lot.name,
602                     'invoice_line_tax_id': [(6, 0, taxes)],
603                     'account_analytic_id': lot.auction_id.account_analytic_id.id,
604                     'account_id': lot.auction_id.acc_income.id,
605                     'price_unit': lot.obj_price,
606                 }
607                 inv_line_obj.create(cr, uid, inv_line, context)
608             inv_ref.button_compute(cr, uid, invoices.values())
609             wf_service.trg_validate(uid, 'account.invoice', inv_id, 'invoice_proforma2', cr)
610         return invoices.values()
611
612     # creates the transactions between the auction company and the seller
613     # this is done by creating a new in_invoice for each
614     def seller_trans_create(self, cr, uid, ids, context=None):
615         """
616             Create a seller invoice for each bord_vnd_id, for selected ids.
617         """
618         # use each list of object in turn
619         invoices = {}
620         inv_ref=self.pool.get('account.invoice')
621         inv_line_obj = self.pool.get('account.invoice.line')
622         wf_service = netsvc.LocalService('workflow')
623         for lot in self.browse(cr, uid, ids, context=context):
624             if not lot.auction_id.id:
625                 continue
626             if lot.bord_vnd_id.id in invoices:
627                 inv_id = invoices[lot.bord_vnd_id.id]
628             else:
629                 inv = {
630                     'name': 'Auction:' +lot.name,
631                     'journal_id': lot.auction_id.journal_seller_id.id,
632                     'partner_id': lot.bord_vnd_id.partner_id.id,
633                     'type': 'in_invoice',
634                 }
635                 inv.update(inv_ref.onchange_partner_id(cr, uid, [], 'in_invoice', lot.bord_vnd_id.partner_id.id)['value'])
636                 inv_id = inv_ref.create(cr, uid, inv, context)
637                 invoices[lot.bord_vnd_id.id] = inv_id
638
639             self.write(cr, uid, [lot.id], {'sel_inv_id':inv_id, 'state':'sold'})
640
641             taxes = map(lambda x: x.id, lot.product_id.taxes_id)
642             if lot.bord_vnd_id.tax_id:
643                 taxes.append(lot.bord_vnd_id.tax_id.id)
644             else:
645                 taxes += map(lambda x: x.id, lot.auction_id.seller_costs)
646
647             inv_line= {
648                 'invoice_id': inv_id,
649                 'quantity': 1,
650                 'product_id': lot.product_id.id,
651                 'name': '['+str(lot.obj_num)+'] '+lot.auction_id.name,
652                 'invoice_line_tax_id': [(6, 0, taxes)],
653                 'account_analytic_id': lot.auction_id.account_analytic_id.id,
654                 'account_id': lot.auction_id.acc_expense.id,
655                 'price_unit': lot.obj_price,
656             }
657             inv_line_obj.create(cr, uid, inv_line, context)
658             inv_ref.button_compute(cr, uid, invoices.values())
659         for inv in inv_ref.browse(cr, uid, invoices.values(), context=context):
660             inv_ref.write(cr, uid, [inv.id], {
661                 'check_total': inv.amount_total
662             })
663             wf_service.trg_validate(uid, 'account.invoice', inv.id, 'invoice_open', cr)
664         return invoices.values()
665
666     def lots_invoice(self, cr, uid, ids, context, invoice_number=False):
667         """(buyer invoice
668             Create an invoice for selected lots (IDS) to BUYER_ID.
669             Set created invoice to the ACTION state.
670             PRE:
671                 ACTION:
672                     False: no action
673                     xxxxx: set the invoice state to ACTION
674
675             RETURN: id of generated invoice
676         """
677         inv_ref = self.pool.get('account.invoice')
678         res_obj = self.pool.get('res.partner')
679         inv_line_obj = self.pool.get('account.invoice.line')
680         wf_service = netsvc.LocalService('workflow')
681         invoices={}
682         for lot in self.browse(cr, uid, ids, context):
683             if not lot.auction_id.id:
684                 continue
685             if not lot.ach_uid.id:
686                 raise orm.except_orm(_('Missed buyer !'), _('The object "%s" has no buyer assigned.') % (lot.name,))
687             if (lot.auction_id.id, lot.ach_uid.id) in invoices:
688                 inv_id = invoices[(lot.auction_id.id, lot.ach_uid.id)]
689             else:
690                 add = res_obj.read(cr, uid, [lot.ach_uid.id], ['address'])[0]['address']
691                 if not len(add):
692                     raise orm.except_orm(_('Missed Address !'), _('The Buyer has no Invoice Address.'))
693                 inv = {
694                     'name':lot.auction_id.name or '',
695                     'reference': lot.ach_login,
696                     'journal_id': lot.auction_id.journal_id.id,
697                     'partner_id': lot.ach_uid.id,
698                     'type': 'out_invoice',
699                 }
700                 if invoice_number:
701                     inv['number'] = invoice_number
702                 inv.update(inv_ref.onchange_partner_id(cr, uid, [], 'out_invoice', lot.ach_uid.id)['value'])
703                 inv_id = inv_ref.create(cr, uid, inv, context)
704                 invoices[(lot.auction_id.id, lot.ach_uid.id)] = inv_id
705             self.write(cr, uid, [lot.id], {'ach_inv_id':inv_id, 'state':'sold'})
706             #calcul des taxes
707             taxes = map(lambda x: x.id, lot.product_id.taxes_id)
708             taxes+=map(lambda x:x.id, lot.auction_id.buyer_costs)
709             if lot.author_right:
710                 taxes.append(lot.author_right.id)
711
712             inv_line= {
713                 'invoice_id': inv_id,
714                 'quantity': 1,
715                 'product_id': lot.product_id.id,
716                 'name': '['+str(lot.obj_num)+'] '+ lot.name,
717                 'invoice_line_tax_id': [(6, 0, taxes)],
718                 'account_analytic_id': lot.auction_id.account_analytic_id.id,
719                 'account_id': lot.auction_id.acc_income.id,
720                 'price_unit': lot.obj_price,
721             }
722             inv_line_obj.create(cr, uid, inv_line, context)
723             inv_ref.button_compute(cr, uid, [inv_id])
724         for l in  inv_ref.browse(cr, uid, invoices.values(), context):
725             wf_service.trg_validate(uid, 'account.invoice', l.id, 'invoice_open', cr)
726         return invoices.values()
727
728 auction_lots()
729
730 #----------------------------------------------------------
731 # Auction Bids
732 #----------------------------------------------------------
733 class auction_bid(osv.osv):
734     """Bid Auctions"""
735
736     _name = "auction.bid"
737     _description=__doc__
738     _order = 'id desc'
739     _columns = {
740         'partner_id': fields.many2one('res.partner', 'Buyer Name', required=True),
741         'contact_tel':fields.char('Contact Number', size=64),
742         'name': fields.char('Bid ID', size=64, required=True),
743         'auction_id': fields.many2one('auction.dates', 'Auction Date', required=True),
744         'bid_lines': fields.one2many('auction.bid_line', 'bid_id', 'Bid'),
745     }
746     _defaults = {
747         'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'auction.bid'),
748     }
749
750     def onchange_contact(self, cr, uid, ids, partner_id):
751         if not partner_id:
752             return {'value': {'contact_tel':False}}
753         contact = self.pool.get('res.partner').browse(cr, uid, partner_id)
754         if len(contact.address):
755             v_contact=contact.address[0] and contact.address[0].phone
756         else:
757             v_contact = False
758         return {'value': {'contact_tel': v_contact}}
759
760 auction_bid()
761
762 class auction_lot_history(osv.osv):
763     """Lot History"""
764
765     _name = "auction.lot.history"
766     _description=__doc__
767     _columns = {
768         'name': fields.date('Date', size=64),
769         'lot_id': fields.many2one('auction.lots', 'Object', required=True, ondelete='cascade'),
770         'auction_id': fields.many2one('auction.dates', 'Auction date', required=True, ondelete='cascade'),
771         'price': fields.float('Withdrawn price', digits=(16, 2))
772     }
773     _defaults = {
774         'name': lambda *args: time.strftime('%Y-%m-%d')
775     }
776 auction_lot_history()
777
778 class auction_bid_lines(osv.osv):
779     _name = "auction.bid_line"
780     _description="Bid"
781
782     _columns = {
783         'name': fields.char('Bid date', size=64),
784         'bid_id': fields.many2one('auction.bid', 'Bid ID', required=True, ondelete='cascade'),
785         'lot_id': fields.many2one('auction.lots', 'Object', required=True, ondelete='cascade'),
786         'call': fields.boolean('To be Called'),
787         'price': fields.float('Maximum Price'),
788         'auction': fields.char(string='Auction Name', size=64)
789     }
790     _defaults = {
791         'name': lambda *args: time.strftime('%Y-%m-%d')
792     }
793
794     def onchange_name(self, cr, uid, ids, lot_id):
795         if not lot_id:
796             return {'value': {'auction':False}}
797         auctions = self.pool.get('auction.lots').browse(cr, uid, lot_id)
798         v_auction=auctions.auction_id.name or False
799         return {'value': {'auction': v_auction}}
800
801
802 auction_bid_lines()
803
804 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: