[MERGE] from trunk

bzr revid: chm@openerp.com-20121010185721-in3ab4mr8h72lect
This commit is contained in:
Christophe Matthieu 2012-10-10 20:57:21 +02:00
commit 76a257cd1b
41 changed files with 1045 additions and 304 deletions

View File

@ -155,6 +155,7 @@ class account_account_type(osv.osv):
return res
def _save_report_type(self, cr, uid, account_type_id, field_name, field_value, arg, context=None):
field_value = field_value or 'none'
obj_data = self.pool.get('ir.model.data')
obj_financial_report = self.pool.get('account.financial.report')
#unlink if it exists somewhere in the financial reports related to BS or PL
@ -596,10 +597,7 @@ class account_account(osv.osv):
return res
def copy(self, cr, uid, id, default=None, context=None, done_list=None, local=False):
if default is None:
default = {}
else:
default = default.copy()
default = {} if default is None else default.copy()
if done_list is None:
done_list = []
account = self.browse(cr, uid, id, context=context)
@ -781,10 +779,7 @@ class account_journal(osv.osv):
]
def copy(self, cr, uid, id, default=None, context=None, done_list=None, local=False):
if default is None:
default = {}
else:
default = default.copy()
default = {} if default is None else default.copy()
if done_list is None:
done_list = []
journal = self.browse(cr, uid, id, context=context)
@ -1185,6 +1180,7 @@ class account_fiscalyear(osv.osv):
}
def copy(self, cr, uid, id, default=None, context=None):
default = {} if default is None else default.copy()
default.update({
'period_ids': [],
'end_journal_period_id': False
@ -1444,14 +1440,8 @@ class account_move(osv.osv):
return result
def copy(self, cr, uid, id, default=None, context=None):
if context is None:
default = {}
else:
default = default.copy()
if context is None:
context = {}
else:
context = context.copy()
default = {} if default is None else default.copy()
context = {} if context is None else context.copy()
default.update({
'state':'draft',
'name':'/',

View File

@ -461,9 +461,10 @@ class account_bank_statement(osv.osv):
return {}
balance_start = self._compute_balance_end_real(cr, uid, journal_id, context=context)
journal_data = self.pool.get('account.journal').read(cr, uid, journal_id, ['company_id'], context=context)
journal_data = self.pool.get('account.journal').read(cr, uid, journal_id, ['company_id', 'currency'], context=context)
company_id = journal_data['company_id']
return {'value': {'balance_start': balance_start, 'company_id': company_id}}
currency_id = journal_data['currency'] or self.pool.get('res.company').browse(cr, uid, company_id[0], context=context).currency_id.id
return {'value': {'balance_start': balance_start, 'company_id': company_id, 'currency': currency_id}}
def unlink(self, cr, uid, ids, context=None):
stat = self.read(cr, uid, ids, ['state'], context=context)

View File

@ -211,17 +211,17 @@
</tree>
</field>
<group class="oe_subtotal_footer oe_right">
<field name="amount_untaxed"/>
<field name="amount_untaxed" widget="monetary" options="{'currency_field': 'currency_id'}"/>
<div>
<label for="amount_tax"/>
<button name="button_reset_taxes" states="draft,proforma2"
string="(update)" class="oe_link oe_edit_only"
type="object" help="Recompute taxes and total"/>
</div>
<field name="amount_tax" nolabel="1"/>
<field name="amount_total" class="oe_subtotal_footer_separator"/>
<field name="amount_tax" nolabel="1" widget="monetary" options="{'currency_field': 'currency_id'}"/>
<field name="amount_total" class="oe_subtotal_footer_separator" widget="monetary" options="{'currency_field': 'currency_id'}"/>
<field name="residual"/>
<field name="residual" widget="monetary" options="{'currency_field': 'currency_id'}"/>
<field name="reconciled" invisible="1"/>
</group>
<div style="width: 50%%">
@ -322,7 +322,7 @@
<field string="Customer" name="partner_id"
on_change="onchange_partner_id(type,partner_id,date_invoice,payment_term, partner_bank_id,company_id)"
groups="base.group_user" context="{'search_default_customer':1, 'show_address': 1}"
options='{"always_reload": true}'/>
options='{"always_reload": True}'/>
<field name="fiscal_position" widget="selection" />
</group>
<group>
@ -368,16 +368,16 @@
</tree>
</field>
<group class="oe_subtotal_footer oe_right">
<field name="amount_untaxed"/>
<field name="amount_untaxed" widget="monetary" options="{'currency_field': 'currency_id'}"/>
<div>
<label for="amount_tax"/>
<button name="button_reset_taxes" states="draft,proforma2"
string="(update)" class="oe_link oe_edit_only"
type="object" help="Recompute taxes and total"/>
</div>
<field name="amount_tax" nolabel="1"/>
<field name="amount_total" class="oe_subtotal_footer_separator"/>
<field name="residual" groups="account.group_account_user"/>
<field name="amount_tax" nolabel="1" widget="monetary" options="{'currency_field': 'currency_id'}"/>
<field name="amount_total" class="oe_subtotal_footer_separator" widget="monetary" options="{'currency_field': 'currency_id'}"/>
<field name="residual" groups="account.group_account_user" widget="monetary" options="{'currency_field': 'currency_id'}"/>
<field name="reconciled" invisible="1"/>
</group>
<group>

View File

@ -633,13 +633,10 @@
<field name="period_id" class="oe_inline"/>
</div>
<field name='company_id' widget="selection" groups="base.group_multi_company" />
<field name="currency" invisible="1"/>
</group><group>
<label for="balance_start"/>
<div>
<field name="balance_start" class="oe_inline"/>
<field name="currency" class="oe_inline"/>
</div>
<field name="balance_end_real"/>
<field name="balance_start" widget="monetary" options='{"currency_field" : "currency"}'/>
<field name="balance_end_real" widget="monetary" options='{"currency_field" : "currency"}'/>
</group>
</group>
@ -1130,8 +1127,8 @@
<field name="account_tax_id" domain="[('parent_id','=',False)]"/>
</group>
<group attrs="{'readonly':[('state','=','valid')]}" string="Currency" groups="base.group_multi_currency">
<field name="currency_id"/>
<field name="amount_currency"/>
<field name="currency_id" invisible="1"/>
<field name="amount_currency" widget="monetary" options="{'currency_field': 'currency_id'}"/>
</group>
<group string="Reconciliation">
<field name="reconcile_id"/>
@ -1177,8 +1174,8 @@
<field name="credit"/>
<separator colspan="4" string="Optional Information"/>
<field name="currency_id" groups="base.group_multi_currency"/>
<field name="amount_currency" groups="base.group_multi_currency"/>
<field name="currency_id" invisible="1"/>
<field name="amount_currency" groups="base.group_multi_currency" widget="monetary" options="{'currency_field': 'currency_id'}"/>
<field name="quantity"/>
<field name="move_id" required="False"/>
<newline/>
@ -2567,7 +2564,7 @@ action = pool.get('res.config').next(cr, uid, [], context)
<field name="date" attrs="{'readonly':[('state','!=','draft')]}" on_change="onchange_date(date, company_id)"/>
<field name="closing_date" readonly="1"/>
<field name="period_id" class="oe_inline"/>
<field name="currency" invisible="1" groups="base.group_multi_currency"/>
<field name="currency" invisible="1"/>
</group>
</group>
<notebook>
@ -2629,12 +2626,12 @@ action = pool.get('res.config').next(cr, uid, [], context)
<group col="6" colspan="4">
<group col="2" colspan="2">
<separator string="Opening Balance" colspan="4"/>
<field name="balance_start" readonly="1" string="Opening Cash Control"/>
<field name="last_closing_balance" readonly="1" string="Last Closing Balance" />
<field name="total_entry_encoding" />
<field name="balance_start" readonly="1" string="Opening Cash Control" widget="monetary" options="{'currency_field': 'currency_id'}"/>
<field name="last_closing_balance" readonly="1" string="Last Closing Balance" widget="monetary" options="{'currency_field': 'currency_id'}"/>
<field name="total_entry_encoding" widget="monetary" options="{'currency_field': 'currency_id'}"/>
</group>
<group string="Closing Balance">
<field name="balance_end"/>
<field name="balance_end" widget="monetary" options="{'currency_field': 'currency_id'}"/>
</group>
</group>
</sheet>

View File

@ -106,27 +106,27 @@
</group>
<notebook colspan="4">
<page string="General">
<group>
<group>
<field name="purchase_value"/>
<field name="salvage_value"/>
<field name="value_residual"/>
<group>
<group>
<field name="purchase_value" widget="monetary" options="{'currency_field': 'currency_id'}"/>
<field name="salvage_value" widget="monetary" options="{'currency_field': 'currency_id'}"/>
<field name="value_residual" widget="monetary" options="{'currency_field': 'currency_id'}"/>
<field name="partner_id"/>
</group>
<group>
<field name="method"/>
<field name="method_progress_factor" attrs="{'invisible':[('method','=','linear')], 'required':[('method','=','degressive')]}"/>
</group>
<group>
<field name="method"/>
<field name="method_progress_factor" attrs="{'invisible':[('method','=','linear')], 'required':[('method','=','degressive')]}"/>
<label for="method_time"/>
<div>
<field name="method_time" on_change="onchange_method_time(method_time)" class="oe_inline"/>
<button name="%(action_asset_modify)d" states="open" string="Change Duration" type="action" icon="terp-stock_effects-object-colorize" class="oe_inline" colspan="1"/>
<field name="method_time" on_change="onchange_method_time(method_time)" class="oe_inline"/>
<button name="%(action_asset_modify)d" states="open" string="Change Duration" type="action" icon="terp-stock_effects-object-colorize" class="oe_inline" colspan="1"/>
</div>
<field name="prorata" attrs="{'invisible': [('method_time','=','end')]}"/>
<field name="method_number" attrs="{'invisible':[('method_time','=','end')], 'required':[('method_time','=','number')]}"/>
<field name="method_period"/>
<field name="method_end" attrs="{'required': [('method_time','=','end')], 'invisible':[('method_time','=','number')]}"/>
</group>
</group>
<field name="prorata" attrs="{'invisible': [('method_time','=','end')]}"/>
<field name="method_number" attrs="{'invisible':[('method_time','=','end')], 'required':[('method_time','=','number')]}"/>
<field name="method_period"/>
<field name="method_end" attrs="{'required': [('method_time','=','end')], 'invisible':[('method_time','=','number')]}"/>
</group>
</group>
</page>
<page string="Depreciation Board">
<field name="depreciation_line_ids" mode="tree">

View File

@ -1070,7 +1070,8 @@ class account_voucher(osv.osv):
if line.amount == line.amount_unreconciled:
if not line.move_line_id.amount_residual:
raise osv.except_osv(_('Wrong bank statement line'),_("You have to delete the bank statement line which the payment was reconciled to manually. Please check the payment of the partner %s by the amount of %s.")%(line.voucher_id.partner_id.name, line.voucher_id.amount))
currency_rate_difference = line.move_line_id.amount_residual - amount
sign = voucher_brw.type in ('payment', 'purchase') and -1 or 1
currency_rate_difference = sign * (line.move_line_id.amount_residual - amount)
else:
currency_rate_difference = 0.0
move_line = {

View File

@ -136,11 +136,8 @@
<group>
<group>
<field name="partner_id" required="1" invisible="context.get('line_type', False)" on_change="onchange_partner_id(partner_id, journal_id, amount, currency_id, type, date, context)" context="{'invoice_currency':currency_id, 'default_customer': 0, 'search_default_supplier': 1, 'default_supplier': 1}" string="Supplier"/>
<label for="amount" string="Amount"/>
<div>
<field name="amount" invisible="context.get('line_type', False)" on_change="onchange_amount(amount, payment_rate, partner_id, journal_id, currency_id, type, date, payment_rate_currency_id, company_id, context)" class="oe_inline"/>
<field name="currency_id" class="oe_inline"/>
</div>
<field name="currency_id" invisible="1"/>
<field name="amount" invisible="context.get('line_type', False)" on_change="onchange_amount(amount, payment_rate, partner_id, journal_id, currency_id, type, date, payment_rate_currency_id, company_id, context)" class="oe_inline" widget='monetary' options='{"currency_field": "currency_id"}'/>
<field name="journal_id"
domain="[('type','in',['bank', 'cash'])]"
invisible="context.get('line_type', False)"
@ -203,7 +200,7 @@
</group>
<group col="2">
<separator string="Payment Options" colspan="2"/>
<field name="writeoff_amount"/>
<field name="writeoff_amount" widget='monetary' options='{"currency_field": "currency_id"}'/>
<field name="payment_option" required="1"/>
<field name="writeoff_acc_id"
attrs="{'invisible':[('payment_option','!=','with_writeoff')], 'required':[('payment_option','=','with_writeoff')]}"
@ -294,13 +291,12 @@
<group>
<field name="state" invisible="1"/>
<field name="partner_id" required="1" on_change="onchange_partner_id(partner_id, journal_id, amount, currency_id, type, date, context)" string="Customer" context="{'search_default_customer': 1}"/>
<label for="amount" string="Paid Amount"/>
<div>
<field name="amount" class="oe_inline"
invisible="context.get('line_type', False)"
on_change="onchange_amount(amount, payment_rate, partner_id, journal_id, currency_id, type, date, payment_rate_currency_id, company_id, context)"/>
<field name="currency_id" class="oe_inline"/>
</div>
<field name="currency_id" invisible="1"/>
<field name="amount" class="oe_inline"
string="Paid Amount"
widget='monetary' options='{"currency_field": "currency_id"}'
invisible="context.get('line_type', False)"
on_change="onchange_amount(amount, payment_rate, partner_id, journal_id, currency_id, type, date, payment_rate_currency_id, company_id, context)"/>
<field name="journal_id"
domain="[('type','in',['bank', 'cash'])]"
invisible="context.get('line_type', False)"
@ -323,7 +319,7 @@
</group>
<notebook invisible="1">
<page string="Payment Information" groups="base.group_user">
<label for="line_cr_ids"/>
<label for="line_cr_ids"/>
<field name="line_cr_ids" context="{'journal_id':journal_id, 'type':type, 'partner_id':partner_id}" on_change="onchange_line_ids(line_dr_ids, line_cr_ids, amount, currency_id, type, context)">
<tree string="Invoices and outstanding transactions" editable="bottom" colors="gray:amount==0">
<field name="move_line_id" context="{'journal_id':parent.journal_id, 'partner_id':parent.partner_id}"
@ -367,7 +363,7 @@
<field name="paid_amount_in_company_currency" colspan="4" invisible="1"/>
</group>
<group>
<field name="writeoff_amount"/>
<field name="writeoff_amount" widget="monetary" options="{'currency_field': 'currency_id'}"/>
<field name="payment_option" required="1"/>
<field name="writeoff_acc_id"
attrs="{'invisible':[('payment_option','!=','with_writeoff')], 'required':[('payment_option','=','with_writeoff')]}"
@ -406,14 +402,12 @@
<group>
<group>
<field name="partner_id" domain="[('customer','=',True)]" required="1" invisible="context.get('line_type', False)" on_change="onchange_partner_id(partner_id, journal_id, amount, currency_id, type, date, context)" string="Customer" context="{'search_default_customer': 1}"/>
<label for="amount" string="Paid Amount"/>
<div>
<field name="amount" class="oe_inline"
invisible="context.get('line_type', False)"
on_change="onchange_amount(amount, payment_rate, partner_id, journal_id, currency_id, type, date, payment_rate_currency_id, company_id, context)"/>
<field name="currency_id" class="oe_inline"/>
</div>
<field name="currency_id" invisible="1"/>
<field name="amount" class="oe_inline"
string="Paid Amount"
widget="monetary" options="{'currency_field': 'currency_id'}"
invisible="context.get('line_type', False)"
on_change="onchange_amount(amount, payment_rate, partner_id, journal_id, currency_id, type, date, payment_rate_currency_id, company_id, context)"/>
<field name="journal_id"
domain="[('type','in',['bank', 'cash'])]"
invisible="context.get('line_type', False)"
@ -436,7 +430,7 @@
</group>
<notebook>
<page string="Payment Information" groups="base.group_user">
<label for="line_cr_ids"/>
<label for="line_cr_ids"/>
<field name="line_cr_ids" context="{'journal_id':journal_id, 'type':type, 'partner_id':partner_id}" on_change="onchange_line_ids(line_dr_ids, line_cr_ids, amount, currency_id, type, context)">
<tree string="Invoices and outstanding transactions" editable="bottom" colors="gray:amount==0">
<field name="move_line_id" context="{'journal_id':parent.journal_id, 'partner_id':parent.partner_id}"
@ -480,7 +474,7 @@
<field name="paid_amount_in_company_currency" colspan="4" invisible="1"/>
</group>
<group>
<field name="writeoff_amount"/>
<field name="writeoff_amount" widget="monetary" options="{'currency_field': 'currency_id'}"/>
<field name="payment_option" required="1"/>
<field name="writeoff_acc_id"
attrs="{'invisible':[('payment_option','!=','with_writeoff')], 'required':[('payment_option','=','with_writeoff')]}"

View File

@ -73,7 +73,7 @@
<group>
<group>
<field name="type" invisible="True"/>
<field name="partner_id" domain="[('customer','=',True)]" on_change="onchange_partner_id(partner_id, journal_id, amount, currency_id, type, date, context)" string="Customer" context="{'search_default_customer':1, 'show_address': 1}" options='{"always_reload": true}'/>
<field name="partner_id" domain="[('customer','=',True)]" on_change="onchange_partner_id(partner_id, journal_id, amount, currency_id, type, date, context)" string="Customer" context="{'search_default_customer':1, 'show_address': 1}" options='{"always_reload": True}'/>
<field name="company_id" widget="selection" groups="base.group_multi_company"/>
</group>
<group>

View File

@ -43,7 +43,7 @@ class OAuthController(openerpweb.Controller):
url = "/#action=login&oauth_error=1"
except Exception,e:
# signup error
_logger.exception('oops')
_logger.exception("OAuth2: %s" % str(e))
url = "/#action=login&oauth_error=2"
return openerp.addons.web.controllers.main.set_cookie_and_redirect(req, url)

View File

@ -15,13 +15,17 @@ class res_users(osv.Model):
_inherit = 'res.users'
_columns = {
'oauth_provider_id': fields.many2one('auth.oauth.provider','OAuth Provider'),
'oauth_provider_id': fields.many2one('auth.oauth.provider', 'OAuth Provider'),
'oauth_uid': fields.char('OAuth User ID', help="Oauth Provider user_id"),
'oauth_access_token': fields.char('OAuth Token', readonly=True),
'oauth_access_token': fields.char('OAuth Access Token', readonly=True),
}
_sql_constraints = [
('uniq_users_oauth_provider_oauht_uid', 'unique(auth_provider_id, auth_uid)', 'OAuth UID must be unique per provider'),
]
def auth_oauth_rpc(self, cr, uid, endpoint, access_token, context=None):
params = urllib.urlencode({ 'access_token': access_token })
params = urllib.urlencode({'access_token': access_token})
if urlparse.urlparse(endpoint)[4]:
url = endpoint + '&' + params
else:
@ -41,22 +45,26 @@ class res_users(osv.Model):
validation = self.auth_oauth_rpc(cr, uid, p.validation_endpoint, access_token)
if validation.get("error"):
raise openerp.exceptions.AccessDenied
raise Exception(validation['error'])
if p.data_endpoint:
data = self.auth_oauth_rpc(cr, uid, p.data_endpoint, access_token)
validation.update(data)
# required
oauth_uid = validation['user_id']
if not oauth_uid:
raise openerp.exceptions.AccessDenied
raise openerp.exceptions.AccessDenied()
email = validation.get('email', 'provider_%d_user_%d' % (p.id, oauth_uid))
# optional
name = validation.get('name', email)
res = self.search(cr, uid, [("oauth_uid", "=", oauth_uid)])
res = self.search(cr, uid, [("oauth_uid", "=", oauth_uid), ('oauth_provider_id', '=', provider)])
if res:
self.write(cr, uid, res[0], { 'oauth_access_token': access_token })
assert len(res) == 1
self.write(cr, uid, res[0], {'oauth_access_token': access_token})
else:
# New user
# New user if signup module available
if not hasattr(self, '_signup_create_user'):
raise openerp.exceptions.AccessDenied()
new_user = {
'name': name,
'login': email,
@ -66,7 +74,9 @@ class res_users(osv.Model):
'oauth_access_token': access_token,
'active': True,
}
self.auth_signup_create(cr, uid, new_user)
# TODO pass signup token to allow attach new user to right partner
self._signup_create_user(cr, uid, new_user)
credentials = (cr.dbname, email, access_token)
return credentials
@ -74,7 +84,7 @@ class res_users(osv.Model):
try:
return super(res_users, self).check_credentials(cr, uid, password)
except openerp.exceptions.AccessDenied:
res = self.search(cr, SUPERUSER_ID, [('id','=',uid),('oauth_access_token','=',password)])
res = self.search(cr, SUPERUSER_ID, [('id', '=', uid), ('oauth_access_token', '=', password)])
if not res:
raise

View File

@ -26,13 +26,14 @@ Re-implement openerp's file import system:
'author': 'OpenERP SA',
'depends': ['base'],
'installable': True,
'auto_install': False, # set to true and allow uninstall?
'auto_install': True,
'css': [
'static/lib/select2/select2.css',
'static/src/css/import.css',
],
'js': [
'static/lib/select2/select2.js',
'static/lib/javascript-state-machine/state-machine.js',
'static/src/js/import.js',
],
'qweb': ['static/src/xml/import.xml'],

View File

@ -83,6 +83,10 @@ class ir_import(orm.TransientModel):
}]
fields_got = self.pool[model].fields_get(cr, uid, context=context)
for name, field in fields_got.iteritems():
# an empty string means the field is deprecated, @deprecated must
# be absent or False to mean not-deprecated
if field.get('deprecated', False) is not False:
continue
if field.get('readonly'):
states = field.get('states')
if not states:
@ -97,7 +101,7 @@ class ir_import(orm.TransientModel):
'id': name,
'name': name,
'string': field['string'],
# Y U NO ALWAYS HAVE REQUIRED
# Y U NO ALWAYS HAS REQUIRED
'required': bool(field.get('required')),
'fields': [],
}
@ -124,8 +128,8 @@ class ir_import(orm.TransientModel):
"""
csv_iterator = csv.reader(
StringIO(record.file),
quotechar=options['quoting'],
delimiter=options['separator'])
quotechar=str(options['quoting']),
delimiter=str(options['separator']))
csv_nonempty = itertools.ifilter(None, csv_iterator)
# TODO: guess encoding with chardet? Or https://github.com/aadsm/jschardet
encoding = options.get('encoding', 'utf-8')
@ -307,22 +311,14 @@ class ir_import(orm.TransientModel):
except ValueError, e:
return [{
'type': 'error',
'message': str(e),
'message': unicode(e),
'record': False,
}]
try:
_logger.info('importing %d rows...', len(data))
(code, record, message, _wat) = self.pool[record.res_model].import_data(
cr, uid, import_fields, data, context=context)
_logger.info('done')
except Exception, e:
_logger.exception("Import failed")
# TODO: remove when exceptions stop being an "expected"
# behavior of import_data on some (most) invalid
# input.
code, record, message = -1, None, str(e)
_logger.info('importing %d rows...', len(data))
import_result = self.pool[record.res_model].load(
cr, uid, import_fields, data, context=context)
_logger.info('done')
# If transaction aborted, RELEASE SAVEPOINT is going to raise
# an InternalError (ROLLBACK should work, maybe). Ignore that.
@ -339,14 +335,4 @@ class ir_import(orm.TransientModel):
except psycopg2.InternalError:
pass
if code != -1:
return []
# TODO: add key for error location?
# TODO: error not within normal preview, how to display? Re-preview
# with higher ``count``?
return [{
'type': 'error',
'message': message,
'record': record or False
}]
return import_result['messages']

View File

@ -0,0 +1,20 @@
Copyright (c) 2012 Jake Gordon and contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -0,0 +1,327 @@
Javascript Finite State Machine (v2.1.0)
========================================
This standalone javascript micro-framework provides a finite state machine for your pleasure.
* You can find the [code here](https://github.com/jakesgordon/javascript-state-machine)
* You can find a [description here](http://codeincomplete.com/posts/2011/8/19/javascript_state_machine_v2/)
* You can find a [working demo here](http://codeincomplete.com/posts/2011/8/19/javascript_state_machine_v2/example/)
Download
========
You can download [state-machine.js](https://github.com/jakesgordon/javascript-state-machine/raw/master/state-machine.js),
or the [minified version](https://github.com/jakesgordon/javascript-state-machine/raw/master/state-machine.min.js)
Alternatively:
git clone git@github.com:jakesgordon/javascript-state-machine
* All code is in state-machine.js
* Minified version provided in state-machine.min.js
* No 3rd party library is required
* Demo can be found in /index.html
* QUnit tests can be found in /test/index.html
Usage
=====
Include `state-machine.min.js` in your application.
In its simplest form, create a standalone state machine using:
var fsm = StateMachine.create({
initial: 'green',
events: [
{ name: 'warn', from: 'green', to: 'yellow' },
{ name: 'panic', from: 'yellow', to: 'red' },
{ name: 'calm', from: 'red', to: 'yellow' },
{ name: 'clear', from: 'yellow', to: 'green' }
]});
... will create an object with a method for each event:
* fsm.warn() - transition from 'green' to 'yellow'
* fsm.panic() - transition from 'yellow' to 'red'
* fsm.calm() - transition from 'red' to 'yellow'
* fsm.clear() - transition from 'yellow' to 'green'
along with the following members:
* fsm.current - contains the current state
* fsm.is(s) - return true if state `s` is the current state
* fsm.can(e) - return true if event `e` can be fired in the current state
* fsm.cannot(e) - return true if event `e` cannot be fired in the current state
Multiple 'from' and 'to' states for a single event
==================================================
If an event is allowed **from** multiple states, and always transitions to the same
state, then simply provide an array of states in the `from` attribute of an event. However,
if an event is allowed from multiple states, but should transition **to** a different
state depending on the current state, then provide multiple event entries with
the same name:
var fsm = StateMachine.create({
initial: 'hungry',
events: [
{ name: 'eat', from: 'hungry', to: 'satisfied' },
{ name: 'eat', from: 'satisfied', to: 'full' },
{ name: 'eat', from: 'full', to: 'sick' },
{ name: 'rest', from: ['hungry', 'satisfied', 'full', 'sick'], to: 'hungry' },
]});
This example will create an object with 2 event methods:
* fsm.eat()
* fsm.rest()
The `rest` event will always transition to the `hungry` state, while the `eat` event
will transition to a state that is dependent on the current state.
>> NOTE: The `rest` event could use a wildcard '*' for the 'from' state if it should be
allowed from any current state.
>> NOTE: The `rest` event in the above example can also be specified as multiple events with
the same name if you prefer the verbose approach.
Callbacks
=========
4 callbacks are available if your state machine has methods using the following naming conventions:
* onbefore**event** - fired before the event
* onleave**state** - fired when leaving the old state
* onenter**state** - fired when entering the new state
* onafter**event** - fired after the event
You can affect the event in 3 ways:
* return `false` from an `onbeforeevent` handler to cancel the event.
* return `false` from an `onleavestate` handler to cancel the event.
* return `ASYNC` from an `onleavestate` handler to perform an asynchronous state transition (see next section)
For convenience, the 2 most useful callbacks can be shortened:
* on**event** - convenience shorthand for onafter**event**
* on**state** - convenience shorthand for onenter**state**
In addition, a generic `onchangestate()` callback can be used to call a single function for _all_ state changes:
All callbacks will be passed the same arguments:
* **event** name
* **from** state
* **to** state
* _(followed by any arguments you passed into the original event method)_
Callbacks can be specified when the state machine is first created:
var fsm = StateMachine.create({
initial: 'green',
events: [
{ name: 'warn', from: 'green', to: 'yellow' },
{ name: 'panic', from: 'yellow', to: 'red' },
{ name: 'calm', from: 'red', to: 'yellow' },
{ name: 'clear', from: 'yellow', to: 'green' }
],
callbacks: {
onpanic: function(event, from, to, msg) { alert('panic! ' + msg); },
onclear: function(event, from, to, msg) { alert('thanks to ' + msg); },
ongreen: function(event, from, to) { document.body.className = 'green'; },
onyellow: function(event, from, to) { document.body.className = 'yellow'; },
onred: function(event, from, to) { document.body.className = 'red'; },
}
});
fsm.panic('killer bees');
fsm.clear('sedatives in the honey pots');
...
Additionally, they can be added and removed from the state machine at any time:
fsm.ongreen = null;
fsm.onyellow = null;
fsm.onred = null;
fsm.onchangestate = function(event, from, to) { document.body.className = to; };
Asynchronous State Transitions
==============================
Sometimes, you need to execute some asynchronous code during a state transition and ensure the
new state is not entered until your code has completed.
A good example of this is when you transition out of a `menu` state, perhaps you want to gradually
fade the menu away, or slide it off the screen and don't want to transition to your `game` state
until after that animation has been performed.
You can now return `StateMachine.ASYNC` from your `onleavestate` handler and the state machine
will be _'put on hold'_ until you are ready to trigger the transition using the new `transition()`
method.
For example, using jQuery effects:
var fsm = StateMachine.create({
initial: 'menu',
events: [
{ name: 'play', from: 'menu', to: 'game' },
{ name: 'quit', from: 'game', to: 'menu' }
],
callbacks: {
onentermenu: function() { $('#menu').show(); },
onentergame: function() { $('#game').show(); },
onleavemenu: function() {
$('#menu').fadeOut('fast', function() {
fsm.transition();
});
return StateMachine.ASYNC; // tell StateMachine to defer next state until we call transition (in fadeOut callback above)
},
onleavegame: function() {
$('#game').slideDown('slow', function() {
fsm.transition();
};
return StateMachine.ASYNC; // tell StateMachine to defer next state until we call transition (in slideDown callback above)
}
}
});
State Machine Classes
=====================
You can also turn all instances of a _class_ into an FSM by applying
the state machine functionality to the prototype, including your callbacks
in your prototype, and providing a `startup` event for use when constructing
instances:
MyFSM = function() { // my constructor function
this.startup();
};
MyFSM.prototype = {
onpanic: function(event, from, to) { alert('panic'); },
onclear: function(event, from, to) { alert('all is clear'); },
// my other prototype methods
};
StateMachine.create({
target: MyFSM.prototype,
events: [
{ name: 'startup', from: 'none', to: 'green' },
{ name: 'warn', from: 'green', to: 'yellow' },
{ name: 'panic', from: 'yellow', to: 'red' },
{ name: 'calm', from: 'red', to: 'yellow' },
{ name: 'clear', from: 'yellow', to: 'green' }
]});
This should be easy to adjust to fit your appropriate mechanism for object construction.
Initialization Options
======================
How the state machine should initialize can depend on your application requirements, so
the library provides a number of simple options.
By default, if you dont specify any initial state, the state machine will be in the `'none'`
state and you would need to provide an event to take it out of this state:
var fsm = StateMachine.create({
events: [
{ name: 'startup', from: 'none', to: 'green' },
{ name: 'panic', from: 'green', to: 'red' },
{ name: 'calm', from: 'red', to: 'green' },
]});
alert(fsm.current); // "none"
fsm.startup();
alert(fsm.current); // "green"
If you specify the name of your initial event (as in all the earlier examples), then an
implicit `startup` event will be created for you and fired when the state machine is constructed.
var fsm = StateMachine.create({
initial: 'green',
events: [
{ name: 'panic', from: 'green', to: 'red' },
{ name: 'calm', from: 'red', to: 'green' },
]});
alert(fsm.current); // "green"
If your object already has a `startup` method you can use a different name for the initial event
var fsm = StateMachine.create({
initial: { state: 'green', event: 'init' },
events: [
{ name: 'panic', from: 'green', to: 'red' },
{ name: 'calm', from: 'red', to: 'green' },
]});
alert(fsm.current); // "green"
Finally, if you want to wait to call the initial state transition event until a later date you
can `defer` it:
var fsm = StateMachine.create({
initial: { state: 'green', event: 'init', defer: true },
events: [
{ name: 'panic', from: 'green', to: 'red' },
{ name: 'calm', from: 'red', to: 'green' },
]});
alert(fsm.current); // "none"
fsm.init();
alert(fsm.current); // "green"
Of course, we have now come full circle, this last example is pretty much functionally the
same as the first example in this section where you simply define your own startup event.
So you have a number of choices available to you when initializing your state machine.
Handling Failures
======================
By default, if you try to call an event method that is not allowed in the current state, the
state machine will throw an exception. If you prefer to handle the problem yourself, you can
define a custom `error` handler:
var fsm = StateMachine.create({
initial: 'green',
error: function(eventName, from, to, args, errorCode, errorMessage) {
return 'event ' + eventName + ' was naughty :- ' + errorMessage;
},
events: [
{ name: 'panic', from: 'green', to: 'red' },
{ name: 'calm', from: 'red', to: 'green' },
]});
alert(fsm.calm()); // "event calm was naughty :- event not allowed in current state green"
Release Notes
=============
See [RELEASE NOTES](https://github.com/jakesgordon/javascript-state-machine/blob/master/RELEASE_NOTES.md) file.
License
=======
See [LICENSE](https://github.com/jakesgordon/javascript-state-machine/blob/master/LICENSE) file.
Contact
=======
If you have any ideas, feedback, requests or bug reports, you can reach me at
[jake@codeincomplete.com](mailto:jake@codeincomplete.com), or via
my website: [Code inComplete](http://codeincomplete.com/posts/2011/8/19/javascript_state_machine_v2/)

View File

@ -0,0 +1,32 @@
Version 2.1.0 (January 7th 2012)
--------------------------------
* Wrapped in self executing function to be more easily used with loaders like `require.js` or `curl.js` (issue #15)
* Allow event to be cancelled by returning `false` from `onleavestate` handler (issue #13) - WARNING: this breaks backward compatibility for async transitions (you now need to return `StateMachine.ASYNC` instead of `false`)
* Added explicit return values for event methods (issue #12)
* Added support for wildcard events that can be fired 'from' any state (issue #11)
* Added support for no-op events that transition 'to' the same state (issue #5)
* extended custom error callback to handle any exceptions caused by caller provided callbacks
* added custom error callback to override exception when an illegal state transition is attempted (thanks to cboone)
* fixed typos (thanks to cboone)
* fixed issue #4 - ensure before/after event hooks are called even if the event doesn't result in a state change
Version 2.0.0 (August 19th 2011)
--------------------------------
* adding support for asynchronous state transitions (see README) - with lots of qunit tests (see test/async.js).
* consistent arguments for ALL callbacks, first 3 args are ALWAYS event name, from state and to state, followed by whatever arguments the user passed to the original event method.
* added a generic `onchangestate(event,from,to)` callback to detect all state changes with a single function.
* allow callbacks to be declared at creation time (instead of having to attach them afterwards)
* renamed 'hooks' => 'callbacks'
* [read more...](http://codeincomplete.com/posts/2011/8/19/javascript_state_machine_v2/)
Version 1.2.0 (June 21st 2011)
------------------------------
* allows the same event to transition to different states, depending on the current state (see 'Multiple...' section in README.md)
* [read more...](http://codeincomplete.com/posts/2011/6/21/javascript_state_machine_v1_2_0/)
Version 1.0.0 (June 1st 2011)
-----------------------------
* initial version
* [read more...](http://codeincomplete.com/posts/2011/6/1/javascript_state_machine/)

View File

@ -0,0 +1,8 @@
desc "create minified version of state-machine.js"
task :minify do
require File.expand_path(File.join(File.dirname(__FILE__), 'minifier/minifier'))
Minifier.enabled = true
Minifier.minify('state-machine.js')
end

View File

@ -0,0 +1,39 @@
<!DOCTYPE html>
<html>
<head>
<title>Javascript Finite State Machine</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link href="demo/demo.css" media="screen, print" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="demo" class='green'>
<h1> Finite State Machine </h1>
<div id="controls">
<button id="clear" onclick="Demo.clear();">clear</button>
<button id="calm" onclick="Demo.calm();">calm</button>
<button id="warn" onclick="Demo.warn();">warn</button>
<button id="panic" onclick="Demo.panic();">panic!</button>
</div>
<div id="diagram">
</div>
<div id="notes">
<i>dashed lines are asynchronous state transitions (3 seconds)</i>
</div>
<textarea id="output">
</textarea>
</div>
<script src="state-machine.js"></script>
<script src="demo/demo.js"></script>
</body>
</html>

View File

@ -0,0 +1,155 @@
(function (window) {
StateMachine = {
//---------------------------------------------------------------------------
VERSION: "2.1.0",
//---------------------------------------------------------------------------
Result: {
SUCCEEDED: 1, // the event transitioned successfully from one state to another
NOTRANSITION: 2, // the event was successfull but no state transition was necessary
CANCELLED: 3, // the event was cancelled by the caller in a beforeEvent callback
ASYNC: 4, // the event is asynchronous and the caller is in control of when the transition occurs
},
Error: {
INVALID_TRANSITION: 100, // caller tried to fire an event that was innapropriate in the current state
PENDING_TRANSITION: 200, // caller tried to fire an event while an async transition was still pending
INVALID_CALLBACK: 300, // caller provided callback function threw an exception
},
WILDCARD: '*',
ASYNC: 'async',
//---------------------------------------------------------------------------
create: function(cfg, target) {
var initial = (typeof cfg.initial == 'string') ? { state: cfg.initial } : cfg.initial; // allow for a simple string, or an object with { state: 'foo', event: 'setup', defer: true|false }
var fsm = target || cfg.target || {};
var events = cfg.events || [];
var callbacks = cfg.callbacks || {};
var map = {};
var add = function(e) {
var from = (e.from instanceof Array) ? e.from : (e.from ? [e.from] : [StateMachine.WILDCARD]); // allow 'wildcard' transition if 'from' is not specified
map[e.name] = map[e.name] || {};
for (var n = 0 ; n < from.length ; n++)
map[e.name][from[n]] = e.to || from[n]; // allow no-op transition if 'to' is not specified
};
if (initial) {
initial.event = initial.event || 'startup';
add({ name: initial.event, from: 'none', to: initial.state });
}
for(var n = 0 ; n < events.length ; n++)
add(events[n]);
for(var name in map) {
if (map.hasOwnProperty(name))
fsm[name] = StateMachine.buildEvent(name, map[name]);
}
for(var name in callbacks) {
if (callbacks.hasOwnProperty(name))
fsm[name] = callbacks[name]
}
fsm.current = 'none';
fsm.is = function(state) { return this.current == state; };
fsm.can = function(event) { return !this.transition && (map[event].hasOwnProperty(this.current) || map[event].hasOwnProperty(StateMachine.WILDCARD)); }
fsm.cannot = function(event) { return !this.can(event); };
fsm.error = cfg.error || function(name, from, to, args, error, msg) { throw msg; }; // default behavior when something unexpected happens is to throw an exception, but caller can override this behavior if desired (see github issue #3)
if (initial && !initial.defer)
fsm[initial.event]();
return fsm;
},
//===========================================================================
doCallback: function(fsm, func, name, from, to, args) {
if (func) {
try {
return func.apply(fsm, [name, from, to].concat(args));
}
catch(e) {
return fsm.error(name, from, to, args, StateMachine.Error.INVALID_CALLBACK, "an exception occurred in a caller-provided callback function");
}
}
},
beforeEvent: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onbefore' + name], name, from, to, args); },
afterEvent: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onafter' + name] || fsm['on' + name], name, from, to, args); },
leaveState: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onleave' + from], name, from, to, args); },
enterState: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onenter' + to] || fsm['on' + to], name, from, to, args); },
changeState: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onchangestate'], name, from, to, args); },
buildEvent: function(name, map) {
return function() {
var from = this.current;
var to = map[from] || map[StateMachine.WILDCARD] || from;
var args = Array.prototype.slice.call(arguments); // turn arguments into pure array
if (this.transition)
return this.error(name, from, to, args, StateMachine.Error.PENDING_TRANSITION, "event " + name + " inappropriate because previous transition did not complete");
if (this.cannot(name))
return this.error(name, from, to, args, StateMachine.Error.INVALID_TRANSITION, "event " + name + " inappropriate in current state " + this.current);
if (false === StateMachine.beforeEvent(this, name, from, to, args))
return StateMachine.CANCELLED;
if (from === to) {
StateMachine.afterEvent(this, name, from, to, args);
return StateMachine.NOTRANSITION;
}
// prepare a transition method for use EITHER lower down, or by caller if they want an async transition (indicated by an ASYNC return value from leaveState)
var fsm = this;
this.transition = function() {
fsm.transition = null; // this method should only ever be called once
fsm.current = to;
StateMachine.enterState( fsm, name, from, to, args);
StateMachine.changeState(fsm, name, from, to, args);
StateMachine.afterEvent( fsm, name, from, to, args);
};
var leave = StateMachine.leaveState(this, name, from, to, args);
if (false === leave) {
this.transition = null;
return StateMachine.CANCELLED;
}
else if ("async" === leave) {
return StateMachine.ASYNC;
}
else {
if (this.transition)
this.transition(); // in case user manually called transition() but forgot to return ASYNC
return StateMachine.SUCCEEDED;
}
};
}
}; // StateMachine
//===========================================================================
if ("function" === typeof define) {
define("statemachine", [], function() { return StateMachine; });
}
else {
window.StateMachine = StateMachine;
}
}(this));

View File

@ -10,7 +10,8 @@
.oe_import .oe_import_grid,
.oe_import .oe_import_error_report,
.oe_import .oe_import_with_file,
.oe_import .oe_import_noheaders {
.oe_import .oe_import_noheaders,
.oe_import .oe_import_report_more {
display: none;
}
@ -19,7 +20,8 @@
}
.oe_import.oe_import_error .oe_import_error_report,
.oe_import.oe_import_with_file .oe_import_with_file,
.oe_import.oe_import_noheaders .oe_import_noheaders {
.oe_import.oe_import_noheaders .oe_import_noheaders,
.oe_import .oe_import_report_showmore .oe_import_report_more {
display: block;
}
@ -29,6 +31,9 @@
.oe_import .oe_import_error_report ul .oe_import_report_warning {
background-color: #FEFFD9;
}
.oe_import .oe_import_error_report ul .oe_import_report_info {
background-color: #d3ffd3;
}
.oe_import .oe_import_noheaders {
color: #888;
@ -47,7 +52,7 @@
}
.oe_import .oe_import_options label {
display: inline-block;
width: 10em;
width: 8em;
text-align: right;
}

View File

@ -47,31 +47,35 @@ openerp.base_import = function (instance) {
this._super.apply(this, arguments);
if(add_button) {
this.$buttons.on('click', '.oe_list_button_import', function() {
new instance.web.DataImport(self, self.dataset).open();
self.do_action({
type: 'ir.actions.client',
tag: 'import',
params: {
model: self.dataset.model
}
}, void 0, void 0, function () {
self.reload();
});
return false;
});
}
}
});
instance.web.DataImport = instance.web.Dialog.extend({
instance.web.client_actions.add(
'import', 'instance.web.DataImport');
instance.web.DataImport = instance.web.Widget.extend({
template: 'ImportView',
dialog_title: _lt("Import Data"),
opts: [
{name: 'encoding', label: _lt("Encoding:"), value: 'utf-8'},
{name: 'separator', label: _lt("Separator:"), value: ','},
{name: 'quoting', label: _lt("Quoting:"), value: '"'}
],
events: {
'change .oe_import_grid input': 'import_dryrun',
'change input.oe_import_file': 'file_update',
'change input.oe_import_has_header, .oe_import_options input': 'settings_updated',
'click a.oe_import_csv': function (e) {
e.preventDefault();
},
'click a.oe_import_export': function (e) {
e.preventDefault();
},
// 'change .oe_import_grid input': 'import_dryrun',
'change .oe_import_file': 'loaded_file',
'click .oe_import_file_reload': 'loaded_file',
'change input.oe_import_has_header, .oe_import_options input': 'settings_changed',
'click a.oe_import_toggle': function (e) {
e.preventDefault();
var $el = $(e.target);
@ -79,30 +83,84 @@ openerp.base_import = function (instance) {
? $el.next()
: $el.parent().next())
.toggle();
},
'click .oe_import_report a.oe_import_report_count': function (e) {
e.preventDefault();
$(e.target).parent().toggleClass('oe_import_report_showmore');
},
'click .oe_import_moreinfo_action a': function (e) {
e.preventDefault();
// #data will parse the attribute on its own, we don't like
// that sort of things
var action = JSON.parse($(e.target).attr('data-action'));
// FIXME: when JS-side clean_action
action.views = _(action.views).map(function (view) {
var id = view[0], type = view[1];
return [
id,
type !== 'tree' ? type
: action.view_type === 'form' ? 'list'
: 'tree'
];
});
this.do_action(_.extend(action, {
target: 'new',
flags: {
search_view: true,
display_title: true,
pager: true,
list: {selectable: false}
}
}));
},
// buttons
'click .oe_import_validate': 'validate',
'click .oe_import_import': 'import',
'click .oe_import_cancel': function (e) {
e.preventDefault();
this.exit();
}
},
init: function (parent, dataset) {
init: function (parent, params) {
var self = this;
this._super(parent, {
buttons: [
{text: _t("Import File"), click: function () {
self.do_import();
}, 'class': 'oe_import_dialog_button'}
]
});
this.res_model = parent.model;
this._super.apply(this, arguments);
this.res_model = params.model;
// import object id
this.id = null;
this.Import = new instance.web.Model('base_import.import');
},
start: function () {
var self = this;
return this.Import.call('create', [{
'res_model': this.res_model
}]).then(function (id) {
self.id = id;
self.$('input[name=import_id]').val(id);
});
this.setup_encoding_picker();
return $.when(
this._super(),
this.Import.call('create', [{
'res_model': this.res_model
}]).then(function (id) {
self.id = id;
self.$('input[name=import_id]').val(id);
})
)
},
setup_encoding_picker: function () {
this.$('input.oe_import_encoding').select2({
width: '160px',
query: function (q) {
var make = function (term) { return {id: term, text: term}; };
var suggestions = _.map(
('utf-8 utf-16 windows-1252 latin1 latin2 big5 ' +
'gb18030 shift_jis windows-1251 koir8_r').split(/\s+/),
make);
if (q.term) {
suggestions.unshift(make(q.term));
}
q.callback({results: suggestions});
},
initSelection: function (e, c) {
return c({id: 'utf-8', text: 'utf-8'});
}
}).select2('val', 'utf-8');
},
import_options: function () {
@ -118,34 +176,52 @@ openerp.base_import = function (instance) {
},
//- File & settings change section
file_update: function (e) {
onfile_loaded: function () {
this.$('.oe_import_button').prop('disabled', true);
if (!this.$('input.oe_import_file').val()) { return; }
this.$el.removeClass('oe_import_preview oe_import_error');
jsonp(this.$el, {
url: '/base_import/set_file'
}, this.proxy('settings_updated'));
}, this.proxy('settings_changed'));
},
settings_updated: function () {
onpreviewing: function () {
var self = this;
this.$('.oe_import_button').prop('disabled', true);
this.$el.addClass('oe_import_with_file');
// TODO: test that write // succeeded?
this.Import.call(
'parse_preview', [this.id, this.import_options()])
.then(this.proxy('preview'));
},
preview: function (result) {
this.$el.removeClass('oe_import_preview_error oe_import_error');
this.$el.toggleClass(
'oe_import_noheaders',
!this.$('input.oe_import_has_header').prop('checked'));
if (result.error) {
this.$el.addClass('oe_import_error');
this.$('.oe_import_error_report').html(
this.Import.call(
'parse_preview', [this.id, this.import_options()])
.then(function (result) {
var signal = result.error ? 'preview_failed' : 'preview_succeeded';
self[signal](result);
});
},
onpreview_error: function (event, from, to, result) {
this.$('.oe_import_options').show();
this.$el.addClass('oe_import_preview_error oe_import_error');
this.$('.oe_import_error_report').html(
QWeb.render('ImportView.preview.error', result));
return;
}
},
onpreview_success: function (event, from, to, result) {
this.$('.oe_import_import').removeClass('oe_highlight');
this.$('.oe_import_validate').addClass('oe_highlight');
this.$('.oe_import_button').prop('disabled', false);
this.$el.addClass('oe_import_preview');
this.$('table').html(QWeb.render('ImportView.preview', result));
if (result.headers.length === 1) {
this.$('.oe_import_options').show();
this.onresults(null, null, null, [{
type: 'warning',
message: _t("A single column was found in the file, this often means the file separator is incorrect")
}]);
}
var $fields = this.$('.oe_import_fields input');
this.render_fields_matches(result, $fields);
var data = this.generate_fields_completion(result);
@ -180,7 +256,6 @@ openerp.base_import = function (instance) {
width: 'resolve',
dropdownCssClass: 'oe_import_selector'
});
this.import_dryrun();
},
generate_fields_completion: function (root) {
var basic = [];
@ -252,40 +327,116 @@ openerp.base_import = function (instance) {
//- import itself
call_import: function (options) {
var self = this;
var fields = this.$('.oe_import_fields input.oe_import_match_field').map(function (index, el) {
return $(el).select2('val') || false;
}).get();
return this.Import.call(
'do', [this.id, fields, this.import_options()], options);
},
import_dryrun: function () {
// this.call_import({ dryrun: true })
// .then(this.proxy('render_import_errors'));
onvalidate: function () {
return this.call_import({ dryrun: true })
.then(this.proxy('validated'));
},
do_import: function () {
onimport: function () {
var self = this;
this.call_import({ dryrun: false }).then(function (errors) {
if (_.isEmpty(errors)) {
if (self.getParent().reload_content) {
self.getParent().reload_content();
}
self.close();
return this.call_import({ dryrun: false }).then(function (message) {
if (!_.any(message, function (message) {
return message.type === 'error' })) {
self['import_succeeded']();
return;
}
self.render_import_errors(errors);
self['import_failed'](message);
});
},
render_import_errors: function (errors) {
if (_.isEmpty(errors)) {
this.$el.removeClass('oe_import_error');
return;
onimported: function () {
this.exit();
},
exit: function () {
this.do_action({
type: 'ir.actions.client',
tag: 'history_back'
});
},
onresults: function (event, from, to, message) {
var no_messages = _.isEmpty(message);
this.$('.oe_import_import').toggleClass('oe_highlight', no_messages);
this.$('.oe_import_validate').toggleClass('oe_highlight', !no_messages);
if (no_messages) {
message.push({
type: 'info',
message: _t("Everything seems valid.")
});
}
// import failed (or maybe just warnings, if we ever get
// warnings?)
// row indexes come back 0-indexed, spreadsheets
// display 1-indexed.
var offset = 1;
// offset more if header
if (this.import_options().headers) { offset += 1; }
this.$el.addClass('oe_import_error');
this.$('.oe_import_error_report').html(
QWeb.render('ImportView.error', {errors: errors}));
QWeb.render('ImportView.error', {
errors: _(message).groupBy('message'),
at: function (rows) {
var from = rows.from + offset;
var to = rows.to + offset;
if (from === to) {
return _.str.sprintf(_t("at row %d"), from);
}
return _.str.sprintf(_t("between rows %d and %d"),
from, to);
},
more: function (n) {
return _.str.sprintf(_t("(%d more)"), n);
},
info: function (msg) {
if (typeof msg === 'string') {
return _.str.sprintf(
'<div class="oe_import_moreinfo oe_import_moreinfo_message">%s</div>',
_.str.escapeHTML(msg));
}
if (msg instanceof Array) {
return _.str.sprintf(
'<div class="oe_import_moreinfo oe_import_moreinfo_choices">%s <ul>%s</ul></div>',
_.str.escapeHTML(_t("Here are the possible values:")),
_(msg).map(function (msg) {
return '<li>'
+ _.str.escapeHTML(msg)
+ '</li>';
}).join(''));
}
// Final should be object, action descriptor
return [
'<div class="oe_import_moreinfo oe_import_moreinfo_action">',
_.str.sprintf('<a href="#" data-action="%s">',
_.str.escapeHTML(JSON.stringify(msg))),
_.str.escapeHTML(
_t("Get all possible values")),
'</a>',
'</div>'
].join('')
},
})).get(0).scrollIntoView();
},
});
// FSM-ize DataImport
StateMachine.create({
target: instance.web.DataImport.prototype,
events: [
{ name: 'loaded_file',
from: ['none', 'file_loaded', 'preview_error', 'preview_success', 'results'],
to: 'file_loaded' },
{ name: 'settings_changed',
from: ['file_loaded', 'preview_error', 'preview_success', 'results'],
to: 'previewing' },
{ name: 'preview_failed', from: 'previewing', to: 'preview_error' },
{ name: 'preview_succeeded', from: 'previewing', to: 'preview_success' },
{ name: 'validate', from: 'preview_success', to: 'validating' },
{ name: 'validate', from: 'results', to: 'validating' },
{ name: 'validated', from: 'validating', to: 'results' },
{ name: 'import', from: ['preview_success', 'results'], to: 'importing' },
{ name: 'import_succeeded', from: 'importing', to: 'imported'},
{ name: 'import_failed', from: 'importing', to: 'results' }
]
})
};

View File

@ -2,17 +2,45 @@
<t t-name="ImportView">
<t t-set="_id" t-value="_.uniqueId('export')"/>
<form action="" method="post" enctype="multipart/form-data" class="oe_import">
<header>
<button type="button" disabled="disabled"
class="oe_button oe_import_button oe_import_validate oe_highlight"
>Validate</button>
<button type="button" disabled="disabled"
class="oe_button oe_import_button oe_import_import"
>Import</button>
<span class="oe_fade">or</span>
<a class="oe_import_cancel" href="#">Cancel</a>
</header>
<input type="hidden" name="session_id"
t-att-value="widget.session.session_id"/>
<input type="hidden" name="import_id"/>
<h2>Upload your file</h2>
<p>Select the <a href="#" class="oe_import_csv">.CSV</a>
<p>Select the <a
href="http://en.wikipedia.org/wiki/Comma-separated_values"
class="oe_import_csv" target="_blank">.CSV</a>
file to import. If you need a sample importable file, you
can use <a href="#" class="oe_import_export">the export
tool</a> to generate one.</p>
can use the export tool to generate one.</p>
<label t-attf-for="file_#{_id}" autofocus="autofocus">CSV File:</label>
<input type="file" id-attf-id="file_#{_id}"
name="file" class="oe_import_file"/>
<button type="button" class="oe_import_file_reload">
<img src="/web/static/src/img/icons/gtk-refresh.png"/>
</button>
<div class="oe_import_with_file">
<a href="#" class="oe_import_toggle">
File Format Options…</a>
<div class="oe_import_toggled oe_import_options">
<p t-foreach="widget.opts" t-as="option">
<!-- no @name, avoid submission when file_update called -->
<label t-attf-for="#{option.name}_#{_id}">
<t t-esc="option.label"/></label>
<input t-attf-id="#{option.name}_#{_id}"
t-attf-class="oe_import_#{option.name}"
t-att-value="option.value"/>
</p>
</div>
</div>
<div class="oe_import_with_file">
<h2>Map your data to OpenERP</h2>
@ -27,18 +55,6 @@
<div class="oe_import_error_report"></div>
<table class="oe_import_grid" width="100%"/>
<a href="#" class="oe_import_toggle">
File Format Options…</a>
<div class="oe_import_toggled oe_import_options">
<p t-foreach="widget.opts" t-as="option">
<!-- no @name, avoid submission when file_update called -->
<label t-attf-for="#{option.name}_#{_id}">
<t t-esc="option.label"/></label>
<input t-attf-id="#{option.name}_#{_id}"
t-attf-class="oe_import_#{option.name}"
t-att-value="option.value"/>
</p>
</div>
<h2>Frequently Asked Questions</h2>
<dl>
@ -81,17 +97,37 @@
</tr>
</t>
<t t-name="ImportView.preview.error">
<p>Import preview failed due to: <t t-esc="error"/></p>
<p>Import preview failed due to: <t t-esc="error"/>. The issue is
usually an incorrect file encoding.</p>
<p>Here is the start of the file we could not import:</p>
<pre><t t-esc="preview"/></pre>
</t>
<ul t-name="ImportView.error">
<li t-foreach="errors" t-as="error" t-attf-class="oe_import_report_#{error.type}">
<!-- can also have error.record, but may be *huge* if
e.g. has image fields -->
<t t-esc="error.message"/>
<li t-foreach="errors" t-as="error"
t-attf-class="oe_import_report oe_import_report_#{error_value[0].type}">
<t t-call="ImportView.error.each">
<t t-set="error" t-value="error_value[0]"/>
</t>
<a href="#" class="oe_import_report_count" t-if="error_value.length gt 1">
<t t-esc="more(error_value.length - 1)"/>
</a>
<ul class="oe_import_report_more" t-if="error_value.length gt 1">
<li t-foreach="error_value.length - 1" t-as="index">
<t t-call="ImportView.error.each">
<t t-set="error" t-value="error_value[index + 1]"/>
</t>
</li>
</ul>
</li>
</ul>
<t t-name="ImportView.error.each">
<span class="oe_import_report_message">
<t t-esc="error.message"/>
</span>
<t t-if="error.rows" t-esc="at(error.rows)"/>
<t t-if="error.moreinfo" t-raw="info(error.moreinfo)"/>
</t>
<t t-extend="ListView.buttons">
<t t-jquery="span.oe_alternative">
this.attr('t-if', 'widget.options.import_enabled');

View File

@ -160,17 +160,17 @@
<field name="street2"/>
<div class="address_format">
<field name="city" placeholder="City" style="width: 40%%"/>
<field name="state_id" options='{"no_open": true}' placeholder="State" style="width: 24%%"/>
<field name="state_id" options='{"no_open": True}' placeholder="State" style="width: 24%%"/>
<field name="zip" placeholder="ZIP" style="width: 34%%"/>
</div>
<field name="country_id" placeholder="Country" options='{"no_open": true}'/>
<field name="country_id" placeholder="Country" options='{"no_open": True}'/>
</div>
</group>
<group>
<label for="contact_name" />
<div>
<field name="contact_name" class="oe_inline"/>,
<field name="title" placeholder="Title" domain="[('domain', '=', 'contact')]" class="oe_inline" options='{"no_open": true}'/>
<field name="title" placeholder="Title" domain="[('domain', '=', 'contact')]" class="oe_inline" options='{"no_open": True}'/>
</div>
<field name="email_from" widget="email"/>
<field name="function" />
@ -477,10 +477,10 @@
<field name="street2"/>
<div class="address_format">
<field name="city" placeholder="City" style="width: 40%%"/>
<field name="state_id" options='{"no_open": true}' placeholder="State" style="width: 24%%"/>
<field name="state_id" options='{"no_open": True}' placeholder="State" style="width: 24%%"/>
<field name="zip" placeholder="ZIP" style="width: 34%%"/>
</div>
<field name="country_id" placeholder="Country" options='{"no_open": true}'/>
<field name="country_id" placeholder="Country" options='{"no_open": True}'/>
</div>
</group>
@ -488,7 +488,7 @@
<label for="contact_name" />
<div>
<field name="contact_name" class="oe_inline"/>
<field name="title" placeholder="Title" domain="[('domain', '=', 'contact')]" options='{"no_open": true}' class="oe_inline"/>
<field name="title" placeholder="Title" domain="[('domain', '=', 'contact')]" options='{"no_open": True}' class="oe_inline"/>
</div>
<field name="function" />
<field name="mobile"/>

View File

@ -55,7 +55,7 @@
</div>
<field name="content" placeholder="e.g. Once upon a time..." class="oe_edit_only"/>
<div class="oe_document_page">
<field name="display_content" widget="html" class="oe_view_only" options='{"safe": true}'/>
<field name="display_content" widget="html" class="oe_view_only" options='{"safe": True}'/>
</div>
</form>
</field>

View File

@ -8,7 +8,7 @@
<field name="model">wizard.document.page.history.show_diff</field>
<field name="arch" type="xml">
<form string="Difference" version="7.0">
<field name="diff" widget="html" options='{"safe": true}'/>
<field name="diff" widget="html" options='{"safe": True}'/>
<footer>
<button string="Cancel" class="oe_link" special="cancel" />
</footer>

View File

@ -20,7 +20,7 @@
<field name="email_cc" readonly="1" attrs="{'invisible':[('email_cc','=',False)]}"/>
<field name="reply_to" readonly="1" attrs="{'invisible':[('reply_to','=',False)]}"/>
<field name="subject" readonly="1"/>
<field name="body_html" widget="html" readonly="1" options='{"safe": true}'/>
<field name="body_html" widget="html" readonly="1" options='{"safe": True}'/>
</group>
</form>
</field>

View File

@ -126,10 +126,10 @@
<field name="street2"/>
<div class="address_format">
<field name="city" placeholder="City" style="width: 40%%"/>
<field name="state_id" class="oe_no_button" placeholder="State" style="width: 37%%" options='{"no_open": true}'/>
<field name="state_id" class="oe_no_button" placeholder="State" style="width: 37%%" options='{"no_open": True}'/>
<field name="zip" placeholder="ZIP" style="width: 20%%"/>
</div>
<field name="country_id" placeholder="Country" class="oe_no_button" options='{"no_open": true}'/>
<field name="country_id" placeholder="Country" class="oe_no_button" options='{"no_open": True}'/>
</div>
</group>
<group>

View File

@ -42,14 +42,14 @@
</group>
<group string="Position">
<field name="department_id" on_change="onchange_department_id(department_id)"/>
<field name="job_id" options='{"no_open": true}' domain="[('state','!=','old')]" context="{'form_view_ref': 'hr.view_hr_job_employee_form'}"/>
<field name="job_id" options='{"no_open": True}' domain="[('state','!=','old')]" context="{'form_view_ref': 'hr.view_hr_job_employee_form'}"/>
<field name="parent_id"/>
<field name="coach_id"/>
</group>
<group>
<field name="company_id" groups="base.group_multi_company" on_change="onchange_company(company_id)"/>
<field name="user_id" on_change="onchange_user(user_id)" string="Related User"/>
<field name="address_id" on_change="onchange_address_id(address_id)" context="{'show_address': 1}" options='{"always_reload": true, "highlight_first_line": true}'/>
<field name="address_id" on_change="onchange_address_id(address_id)" context="{'show_address': 1}" options='{"always_reload": True, "highlight_first_line": True}'/>
</group>
</group>
<field name="notes" placeholder="Other Information ..." colspan="4"/>
@ -57,14 +57,14 @@
<page string="Personal Information" groups="base.group_hr_user">
<group>
<group string="Citizenship &amp; Other Info">
<field name="country_id" options='{"no_open": true}'/>
<field name="country_id" options='{"no_open": True}'/>
<field name="identification_id" groups="base.group_hr_user"/>
<field name="passport_id" groups="base.group_hr_user"/>
<field name="bank_account_id"/>
<field name="otherid" groups="base.group_hr_user"/>
</group>
<group string="Contact Information">
<field name="address_home_id" context="{'show_address': 1}" options='{"always_reload": true, "highlight_first_line": true}'/>
<field name="address_home_id" context="{'show_address': 1}" options='{"always_reload": True, "highlight_first_line": True}'/>
</group>
<group string="Status">
<field name="gender"/>

View File

@ -124,7 +124,7 @@
<field name="note" placeholder="Free Notes"/>
</div>
<group class="oe_subtotal_footer">
<field name="amount"/>
<field name="amount" widget="monetary" options="{'currency_field': 'currency_id'}"/>
</group>
</group>
</page>

View File

@ -10,4 +10,4 @@
"account_type_output_tax","Output Tax","Output Tax","liability","Unreconciled"
"account_type_input_tax","Input Tax","Input Tax","asset","Unreconciled"
"account_type_profit_and_loss","Profit and Loss","Profit and Loss","none","None"
"account_type_view","View","view",,"None"
"account_type_view","View","view","none","None"

1 id name code report_type close_method
10 account_type_output_tax Output Tax Output Tax liability Unreconciled
11 account_type_input_tax Input Tax Input Tax asset Unreconciled
12 account_type_profit_and_loss Profit and Loss Profit and Loss none None
13 account_type_view View view none None

View File

@ -35,8 +35,8 @@
<field name="street2"/>
<field name="zip"/>
<field name="city"/>
<field name="country_id" options='{"no_open": true}'/>
<field name="state_id" options='{"no_open": true}'/>
<field name="country_id" options='{"no_open": True}'/>
<field name="state_id" options='{"no_open": True}'/>
<templates>
<t t-name="kanban-box">
<h4><field name="name"/></h4>

View File

@ -1101,7 +1101,7 @@ class task(base_stage, osv.osv):
task_record = self.browse(cr, uid, task_id, context=context)
if task_record.project_id:
project_follower_ids = [follower.id for follower in task_record.project_id.message_follower_ids]
self.message_subscribe(cr, uid, [task_id], project_follower_ids,
self.message_subscribe(cr, uid, [task_id], project_follower_ids,
context=context)
self._store_history(cr, uid, [task_id], context=context)
self.create_send_note(cr, uid, [task_id], context=context)
@ -1354,16 +1354,15 @@ class project_project(osv.osv):
'use_tasks': True
}
#
# Tasks History, used for cumulative flow charts (Lean/Agile)
#
class project_task_history(osv.osv):
"""
Tasks History, used for cumulative flow charts (Lean/Agile)
"""
_name = 'project.task.history'
_description = 'History of Tasks'
_rec_name = 'task_id'
_log_access = False
def _get_date(self, cr, uid, ids, name, arg, context=None):
result = {}
for history in self.browse(cr, uid, ids, context=context):
@ -1415,35 +1414,38 @@ class project_task_history(osv.osv):
'date': fields.date.context_today,
}
class project_task_history_cumulative(osv.osv):
_name = 'project.task.history.cumulative'
_table = 'project_task_history_cumulative'
_inherit = 'project.task.history'
_auto = False
_columns = {
'end_date': fields.date('End Date'),
'project_id': fields.related('task_id', 'project_id', string='Project', type='many2one', relation='project.project')
'project_id': fields.many2one('project.project', 'Project'),
}
def init(self, cr):
cr.execute(""" CREATE OR REPLACE VIEW project_task_history_cumulative AS (
SELECT
history.date::varchar||'-'||history.history_id::varchar as id,
history.date as end_date,
history.date::varchar||'-'||history.history_id::varchar AS id,
history.date AS end_date,
*
FROM (
SELECT
id as history_id,
date+generate_series(0, CAST((coalesce(end_date,DATE 'tomorrow')::date - date)AS integer)-1) as date,
task_id, type_id, user_id, kanban_state, state,
greatest(remaining_hours,1) as remaining_hours, greatest(planned_hours,1) as planned_hours
h.id AS history_id,
h.date+generate_series(0, CAST((coalesce(h.end_date, DATE 'tomorrow')::date - h.date) AS integer)-1) AS date,
h.task_id, h.type_id, h.user_id, h.kanban_state, h.state,
greatest(h.remaining_hours, 1) AS remaining_hours, greatest(h.planned_hours, 1) AS planned_hours,
t.project_id
FROM
project_task_history
) as history
project_task_history AS h
JOIN project_task AS t ON (h.task_id = t.id)
) AS history
)
""")
class project_category(osv.osv):
""" Category of project's task (or issue) """
_name = "project.category"

View File

@ -311,7 +311,7 @@
<field colspan="4" name="name"/>
<field name="hours" widget="float_time"/>
<field name="date"/>
<field name="user_id" options='{"no_open": true}'/>
<field name="user_id" options='{"no_open": True}'/>
<field name="company_id" groups="base.group_multi_company" widget="selection"/>
</group>
</form>
@ -401,7 +401,7 @@
<group>
<group>
<field name="project_id" on_change="onchange_project(project_id)" context="{'default_use_tasks':1}"/>
<field name="user_id" attrs="{'readonly':[('state','in',['done', 'cancelled'])]}" options='{"no_open": true}'/>
<field name="user_id" attrs="{'readonly':[('state','in',['done', 'cancelled'])]}" options='{"no_open": True}'/>
<field name="company_id" groups="base.group_multi_company" widget="selection"/>
</group>
<group>

View File

@ -18,10 +18,12 @@
</tree>
</field>
</record>
<record id="view_task_history_graph" model="ir.ui.view">
<field name="name">project.task.history.cumulative.graph</field>
<field name="model">project.task.history.cumulative</field>
<field name="arch" type="xml">
<!-- <field name="project_id"/> -->
<graph string="Project Tasks" type="bar">
<field name="date"/>
<field name="planned_hours" operator="+"/>
@ -29,21 +31,6 @@
</graph>
</field>
</record>
<!-- Where is this object in py file ? -->
<!--<record id="view_task_history_burndown_graph" model="ir.ui.view">-->
<!-- <field name="name">project.task.history.burndown.graph</field>-->
<!-- <field name="model">project.task.history.burndown</field>-->
<!-- <field name="arch" type="xml">-->
<!-- <graph string="Burndown Chart of Tasks" type="bar">-->
<!-- <field name="date"/>-->
<!-- <field name="remaining_hours" operator="+"/>-->
<!-- <field name="type_id" group="True"/>-->
<!-- </graph>-->
<!-- </field>-->
<!--</record>-->
<record id="view_task_history_search" model="ir.ui.view">
<field name="name">project.task.history.cumulative.search</field>
@ -51,18 +38,18 @@
<field name="arch" type="xml">
<search string="Task's Analysis">
<field name="date"/>
<filter name="open" string="In Progress" domain="[('state','in',('open','draft'))]" help="In Progress Tasks" icon="terp-camera_test"/>
<filter string="Pending" domain="[('state','=','pending')]" context="{'show_delegated':False}" help="Pending Tasks" icon="terp-gtk-media-pause"/>
<separator/>
<filter name="kanban_blocked" string="Blocked" domain="[('kanban_state','=','blocked')]" icon="terp-gtk-media-pause"/>
<filter name="kanban_ready" string="Ready" domain="[('kanban_state','=','done')]" icon="terp-camera_test"/>
<separator/>
<filter string="My Tasks" domain="[('user_id','=',uid)]" help="My Tasks" icon="terp-personal" />
<filter string="Unassigned Tasks" domain="[('user_id','=',False)]" help="Unassigned Tasks" icon="terp-personal-" />
<separator/>
<filter string="My Projects" domain="[('project_id.user_id','=',uid)]" help="My Projects" icon="terp-personal"/>
<field name="project_id"/>
<field name="user_id"/>
<filter name="open" string="In Progress Tasks" domain="[('state','in',('open','draft'))]"/>
<filter string="Pending Tasks" domain="[('state','=','pending')]" context="{'show_delegated':False}"/>
<separator/>
<filter name="kanban_blocked" string="Blocked" domain="[('kanban_state','=','blocked')]"/>
<filter name="kanban_ready" string="Ready" domain="[('kanban_state','=','done')]"/>
<separator/>
<filter string="My Tasks" domain="[('user_id','=',uid)]"/>
<filter string="Unassigned Tasks" domain="[('user_id','=',False)]"/>
<separator/>
<filter string="My Projects" domain="[('project_id.user_id','=',uid)]"/>
</search>
</field>
</record>
@ -73,27 +60,12 @@
<field name="view_type">form</field>
<field name="view_mode">graph,tree</field>
<field name="view_id" ref="view_task_history_graph"/>
<field eval="False" name="filter"/>
<field name="filter" eval="False"/>
<field name="context">{"search_default_open":1, "search_default_this_month": 1}</field>
</record>
<menuitem action="action_view_task_history_cumulative"
id="menu_action_view_task_history_cumulative"
parent="base.menu_project_report" />
<!--<record id="action_view_task_history_burndown" model="ir.actions.act_window">-->
<!-- <field name="name">Burndown Chart</field>-->
<!-- <field name="res_model">project.task.history.cumulative</field>-->
<!-- <field name="view_type">form</field>-->
<!-- <field name="view_mode">graph,tree</field>-->
<!-- <field name="view_id" ref="view_task_history_burndown_graph"/>-->
<!-- <field eval="False" name="filter"/>-->
<!-- <field name="context">{"search_default_open":1, "search_default_this_month": 1, "search_default_project_id": project_id}</field>-->
<!--</record>-->
<!--<menuitem action="action_view_task_history_burndown"-->
<!-- id="menu_action_view_task_history_burndown"-->
<!-- parent="project_report_task" />-->
parent="base.menu_project_report"/>
</data>
</openerp>

View File

@ -92,8 +92,8 @@
<field name="inherit_id" ref="project.view_task_form2" />
<field name="arch" type="xml">
<field name="progress" position="after">
<field name="context_id" widget="selection" options='{"no_open": true}'/>
<field name="timebox_id" widget="selection" options='{"no_open": true}'/>
<field name="context_id" widget="selection" options='{"no_open": True}'/>
<field name="timebox_id" widget="selection" options='{"no_open": True}'/>
</field>
</field>
</record>

View File

@ -8,7 +8,7 @@
<field name="arch" type="xml">
<form string="Plannify Timebox" version="7.0">
<group col="4">
<field name="timebox_id" widget="selection" options='{"no_open": true}'/>
<field name="timebox_id" widget="selection" options='{"no_open": True}'/>
<field name="timebox_to_id" widget="selection"/>
</group>
<field name="task_ids" domain="[('timebox_id','=',timebox_id),('state','=','open')]" />

View File

@ -166,6 +166,7 @@ class purchase_order(osv.osv):
'warehouse_id': fields.many2one('stock.warehouse', 'Destination Warehouse', states={'confirmed':[('readonly',True)], 'approved':[('readonly',True)],'done':[('readonly',True)]}),
'location_id': fields.many2one('stock.location', 'Destination', required=True, domain=[('usage','<>','view')]),
'pricelist_id':fields.many2one('product.pricelist', 'Pricelist', required=True, states={'confirmed':[('readonly',True)], 'approved':[('readonly',True)],'done':[('readonly',True)]}, help="The pricelist sets the currency used for this purchase order. It also computes the supplier price for the selected products/quantities."),
'currency_id': fields.related('pricelist_id', 'currency_id', type="many2one", relation="res.currency", readonly=True, required=True),
'state': fields.selection(STATE_SELECTION, 'Status', readonly=True, help="The state of the purchase order or the quotation request. A quotation is a purchase order in a 'Draft' state. Then the order has to be confirmed by the user, the state switch to 'Confirmed'. Then the supplier must confirm the order to change the state to 'Approved'. When the purchase order is paid and received, the state becomes 'Done'. If a cancel action occurs in the invoice or in the reception of goods, the state becomes in exception.", select=True),
'order_line': fields.one2many('purchase.order.line', 'order_id', 'Order Lines', states={'approved':[('readonly',True)],'done':[('readonly',True)]}),
'validator' : fields.many2one('res.users', 'Validated by', readonly=True),
@ -246,6 +247,11 @@ class purchase_order(osv.osv):
def button_dummy(self, cr, uid, ids, context=None):
return True
def onchange_pricelist(self, cr, uid, ids, pricelist_id, context=None):
if not pricelist_id:
return {}
return {'value': {'currency_id': self.pool.get('product.pricelist').browse(cr, uid, pricelist_id, context=context).currency_id.id}}
def onchange_dest_address_id(self, cr, uid, ids, address_id):
if not address_id:
return {}

View File

@ -223,7 +223,8 @@
<group>
<field name="partner_id" on_change="onchange_partner_id(partner_id)" context="{'search_default_supplier':1,'default_supplier':1,'default_customer':0}" domain="[('supplier','=',True)]"/>
<field name="partner_ref"/>
<field domain="[('type','=','purchase')]" name="pricelist_id" groups="product.group_purchase_pricelist"/>
<field domain="[('type','=','purchase')]" name="pricelist_id" groups="product.group_purchase_pricelist" on_change="onchange_pricelist(pricelist_id, context)"/>
<field name="currency_id" invisible='1'/>
</group>
<group>
<field name="date_order"/>
@ -249,14 +250,14 @@
</tree>
</field>
<group class="oe_subtotal_footer oe_right">
<field name="amount_untaxed"/>
<field name="amount_tax"/>
<field name="amount_untaxed" widget="monetary" options="{'currency_field': 'currency_id'}"/>
<field name="amount_tax" widget="monetary" options="{'currency_field': 'currency_id'}"/>
<div class="oe_subtotal_footer_separator oe_inline">
<label for="amount_total"/>
<button name="button_dummy"
states="draft" string="(update)" type="object" class="oe_edit_only oe_link"/>
</div>
<field name="amount_total" nolabel="1" class="oe_subtotal_footer_separator"/>
<field name="amount_total" nolabel="1" class="oe_subtotal_footer_separator" widget="monetary" options="{'currency_field': 'currency_id'}"/>
</group>
<div class="oe_clear"/>
<label for="notes"/>

View File

@ -201,6 +201,7 @@ class sale_order(osv.osv):
help="""This field controls how invoice and delivery operations are synchronized.
- With 'Before Delivery', a draft invoice is created, and it must be paid before delivery."""),
'pricelist_id': fields.many2one('product.pricelist', 'Pricelist', required=True, readonly=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, help="Pricelist for current sales order."),
'currency_id': fields.related('pricelist_id', 'currency_id', type="many2one", relation="res.currency", readonly=True, required=True),
'project_id': fields.many2one('account.analytic.account', 'Contract/Analytic Account', readonly=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, help="The analytic account related to a sales order."),
'order_line': fields.one2many('sale.order.line', 'order_id', 'Order Lines', readonly=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}),
@ -264,13 +265,18 @@ class sale_order(osv.osv):
return osv.osv.unlink(self, cr, uid, unlink_ids, context=context)
def onchange_pricelist_id(self, cr, uid, ids, pricelist_id, order_lines, context=None):
if (not pricelist_id) or (not order_lines):
if not pricelist_id:
return {}
value = {
'currency_id': self.pool.get('product.pricelist').browse(cr, uid, pricelist_id, context=context).currency_id.id
}
if not order_lines:
return {'value': value}
warning = {
'title': _('Pricelist Warning!'),
'message' : _('If you change the pricelist of this order (and eventually the currency), prices of existing order lines will not be updated.')
}
return {'warning': warning}
return {'warning': warning, 'value': value}
def onchange_partner_id(self, cr, uid, ids, part):
if not part:

View File

@ -184,6 +184,7 @@
<field name="shop_id" groups="base.group_no_one" on_change="onchange_shop_id(shop_id, context)" widget="selection"/>
<field name="client_order_ref"/>
<field domain="[('type','=','sale')]" name="pricelist_id" groups="product.group_sale_pricelist" on_change="onchange_pricelist_id(pricelist_id,order_line)"/>
<field name="currency_id" invisible="1"/>
</group>
</group>
<notebook>
@ -214,7 +215,7 @@
<label for="product_uos_qty" groups="product.group_uos"/>
<div groups="product.group_uos">
<field name="product_uos_qty" class="oe_inline"/>
<field name="product_uos" options='{"no_open": true}' class="oe_inline"/>
<field name="product_uos" options='{"no_open": True}' class="oe_inline"/>
</div>
<field name="price_unit"/>
<label for="discount" groups="sale.group_discount_per_so_line"/>
@ -251,7 +252,7 @@
on_change="product_id_change(parent.pricelist_id, product_id, product_uom_qty, product_uom, product_uos_qty, product_uos, name, parent.partner_id, False, False, parent.date_order, False, parent.fiscal_position, True, context)"/>
<field name="product_uom"
on_change="product_uom_change(parent.pricelist_id, product_id, product_uom_qty, product_uom, product_uos_qty, product_uos, name, parent.partner_id, False, False, parent.date_order, context)"
groups="product.group_uom" options='{"no_open": true}'/>
groups="product.group_uom" options='{"no_open": True}'/>
<field name="product_uos_qty" groups="product.group_uos" invisible="1"/>
<field name="product_uos" string="UoS" groups="product.group_uos" invisible="1"/>
<field name="tax_id" widget="many2many_tags" domain="[('parent_id','=',False),('type_tax_use','&lt;&gt;','purchase')]"/>
@ -261,14 +262,14 @@
</tree>
</field>
<group class="oe_subtotal_footer oe_right" colspan="2" name="sale_total">
<field name="amount_untaxed"/>
<field name="amount_tax"/>
<field name="amount_untaxed" widget='monetary' options="{'currency_field': 'currency_id'}"/>
<field name="amount_tax" widget='monetary' options="{'currency_field': 'currency_id'}"/>
<div class="oe_subtotal_footer_separator oe_inline">
<label for="amount_total" />
<button name="button_dummy"
states="draft" string="(update)" type="object" class="oe_edit_only oe_link"/>
</div>
<field name="amount_total" nolabel="1" class="oe_subtotal_footer_separator"/>
<field name="amount_total" nolabel="1" class="oe_subtotal_footer_separator" widget='monetary' options="{'currency_field': 'currency_id'}"/>
</group>
<group name="sale_margin_grp">
</group>

View File

@ -11,7 +11,7 @@
<group>
<label for="margin"/>
<div>
<field name="margin"/>
<field name="margin" widget='monetary' options="{'currency_field': 'currency_id'}"/>
</div>
</group>
</xpath>

View File

@ -272,7 +272,7 @@
</field>
</record>
<menuitem id="menu_traceability" name="Traceability" parent="menu_stock_root"
sequence="3" groups="stock.group_tracking_lot,stock.group_production_lot"/>
sequence="3"/>
<menuitem action="action_tracking_form" id="menu_action_tracking_form"
groups="product.group_stock_packaging"
sequence="6"