Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 
 
 

691 lignes
21 KiB

  1. # Copyright (c) 2012 Web Notes Technologies Pvt Ltd (http://erpnext.com)
  2. #
  3. # MIT License (MIT)
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a
  6. # copy of this software and associated documentation files (the "Software"),
  7. # to deal in the Software without restriction, including without limitation
  8. # the rights to use, copy, modify, merge, publish, distribute, sublicense,
  9. # and/or sell copies of the Software, and to permit persons to whom the
  10. # Software is furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in
  13. # all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  16. # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
  17. # PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  18. # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  19. # CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
  20. # OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  21. #
  22. from __future__ import unicode_literals
  23. """
  24. Contains the Document class representing an object / record
  25. """
  26. import webnotes
  27. import webnotes.model.meta
  28. from webnotes.utils import *
  29. valid_fields_map = {}
  30. class Document:
  31. """
  32. The wn(meta-data)framework equivalent of a Database Record.
  33. Stores,Retrieves,Updates the record in the corresponding table.
  34. Runs the triggers required.
  35. The `Document` class represents the basic Object-Relational Mapper (ORM). The object type is defined by
  36. `DocType` and the object ID is represented by `name`::
  37. Please note the anamoly in the Web Notes Framework that `ID` is always called as `name`
  38. If both `doctype` and `name` are specified in the constructor, then the object is loaded from the database.
  39. If only `doctype` is given, then the object is not loaded
  40. If `fielddata` is specfied, then the object is created from the given dictionary.
  41. **Note 1:**
  42. The getter and setter of the object are overloaded to map to the fields of the object that
  43. are loaded when it is instantiated.
  44. For example: doc.name will be the `name` field and doc.owner will be the `owner` field
  45. **Note 2 - Standard Fields:**
  46. * `name`: ID / primary key
  47. * `owner`: creator of the record
  48. * `creation`: datetime of creation
  49. * `modified`: datetime of last modification
  50. * `modified_by` : last updating user
  51. * `docstatus` : Status 0 - Saved, 1 - Submitted, 2- Cancelled
  52. * `parent` : if child (table) record, this represents the parent record
  53. * `parenttype` : type of parent record (if any)
  54. * `parentfield` : table fieldname of parent record (if any)
  55. * `idx` : Index (sequence) of the child record
  56. """
  57. def __init__(self, doctype = None, name = None, fielddata = None, prefix='tab'):
  58. self._roles = []
  59. self._perms = []
  60. self._user_defaults = {}
  61. self._prefix = prefix
  62. if isinstance(doctype, dict):
  63. fielddata = doctype
  64. doctype = None
  65. if fielddata:
  66. self.fields = webnotes._dict(fielddata)
  67. else:
  68. self.fields = webnotes._dict()
  69. if not self.fields.has_key('name'):
  70. self.fields['name']='' # required on save
  71. if not self.fields.has_key('doctype'):
  72. self.fields['doctype']='' # required on save
  73. if not self.fields.has_key('owner'):
  74. self.fields['owner']='' # required on save
  75. if doctype:
  76. self.fields['doctype'] = doctype
  77. if name:
  78. self.fields['name'] = name
  79. self.__initialized = 1
  80. if (doctype and name):
  81. self._loadfromdb(doctype, name)
  82. else:
  83. if not fielddata:
  84. self.fields['__islocal'] = 1
  85. if not self.fields.docstatus:
  86. self.fields.docstatus = 0
  87. def __nonzero__(self):
  88. return True
  89. def __str__(self):
  90. return str(self.fields)
  91. def __repr__(self):
  92. return repr(self.fields)
  93. def __unicode__(self):
  94. return unicode(self.fields)
  95. def __eq__(self, other):
  96. if isinstance(other, Document):
  97. return self.fields == other.fields
  98. else:
  99. return False
  100. def __getstate__(self):
  101. return self.fields
  102. def __setstate__(self, d):
  103. self.fields = d
  104. def encode(self, encoding='utf-8'):
  105. """convert all unicode values to utf-8"""
  106. for key in self.fields:
  107. if isinstance(self.fields[key], unicode):
  108. self.fields[key] = self.fields[key].encode(encoding)
  109. def _loadfromdb(self, doctype = None, name = None):
  110. if name: self.name = name
  111. if doctype: self.doctype = doctype
  112. is_single = False
  113. try:
  114. is_single = webnotes.model.meta.is_single(self.doctype)
  115. except Exception, e:
  116. pass
  117. if is_single:
  118. self._loadsingle()
  119. else:
  120. dataset = webnotes.conn.sql('select * from `%s%s` where name="%s"' % (self._prefix, self.doctype, self.name.replace('"', '\"')))
  121. if not dataset:
  122. raise Exception, '[WNF] %s %s does not exist' % (self.doctype, self.name)
  123. self._load_values(dataset[0], webnotes.conn.get_description())
  124. def _load_values(self, data, description):
  125. if '__islocal' in self.fields:
  126. del self.fields['__islocal']
  127. for i in range(len(description)):
  128. v = data[i]
  129. self.fields[description[i][0]] = webnotes.conn.convert_to_simple_type(v)
  130. def _merge_values(self, data, description):
  131. for i in range(len(description)):
  132. v = data[i]
  133. if v: # only if value, over-write
  134. self.fields[description[i][0]] = webnotes.conn.convert_to_simple_type(v)
  135. def _loadsingle(self):
  136. self.name = self.doctype
  137. self.fields.update(getsingle(self.doctype))
  138. def __setattr__(self, name, value):
  139. # normal attribute
  140. if not self.__dict__.has_key('_Document__initialized'):
  141. self.__dict__[name] = value
  142. elif self.__dict__.has_key(name):
  143. self.__dict__[name] = value
  144. else:
  145. # field attribute
  146. f = self.__dict__['fields']
  147. f[name] = value
  148. def __getattr__(self, name):
  149. if self.__dict__.has_key(name):
  150. return self.__dict__[name]
  151. elif self.fields.has_key(name):
  152. return self.fields[name]
  153. else:
  154. return ''
  155. def _get_amended_name(self):
  156. am_id = 1
  157. am_prefix = self.amended_from
  158. if webnotes.conn.sql('select amended_from from `tab%s` where name = "%s"' % (self.doctype, self.amended_from))[0][0] or '':
  159. am_id = cint(self.amended_from.split('-')[-1]) + 1
  160. am_prefix = '-'.join(self.amended_from.split('-')[:-1]) # except the last hyphen
  161. self.name = am_prefix + '-' + str(am_id)
  162. def _set_name(self, autoname, istable):
  163. self.localname = self.name
  164. # get my object
  165. import webnotes.model.code
  166. so = webnotes.model.code.get_server_obj(self, [])
  167. # amendments
  168. if self.amended_from:
  169. self._get_amended_name()
  170. # by method
  171. elif so and hasattr(so, 'autoname'):
  172. r = webnotes.model.code.run_server_obj(so, 'autoname')
  173. if r: return r
  174. # based on a field
  175. elif autoname and autoname.startswith('field:'):
  176. n = self.fields[autoname[6:]]
  177. if not n:
  178. raise Exception, 'Name is required'
  179. self.name = n.strip()
  180. elif autoname and autoname.startswith("naming_series:"):
  181. if not self.naming_series:
  182. # pick default naming series
  183. from webnotes.model.doctype import get_property
  184. self.naming_series = get_property(self.doctype, "options", "naming_series")
  185. if not self.naming_series:
  186. webnotes.msgprint(webnotes._("Naming Series mandatory"), raise_exception=True)
  187. self.naming_series = self.naming_series.split("\n")
  188. self.naming_series = self.naming_series[0] or self.naming_series[1]
  189. self.name = make_autoname(self.naming_series+'.#####')
  190. # based on expression
  191. elif autoname and autoname.startswith('eval:'):
  192. doc = self # for setting
  193. self.name = eval(autoname[5:])
  194. # call the method!
  195. elif autoname and autoname!='Prompt':
  196. self.name = make_autoname(autoname, self.doctype)
  197. # given
  198. elif self.fields.get('__newname',''):
  199. self.name = self.fields['__newname']
  200. # default name for table
  201. elif istable:
  202. self.name = make_autoname('#########', self.doctype)
  203. # unable to determine a name, use a serial number!
  204. if not self.name:
  205. self.name = make_autoname('#########', self.doctype)
  206. def _insert(self, autoname, istable, case='', make_autoname=1, keep_timestamps=False):
  207. # set name
  208. if make_autoname:
  209. self._set_name(autoname, istable)
  210. # validate name
  211. validate_name(self.doctype, self.name, case)
  212. # insert!
  213. if not keep_timestamps:
  214. if not self.owner:
  215. self.owner = webnotes.session['user']
  216. self.modified_by = webnotes.session['user']
  217. self.creation = self.modified = now()
  218. webnotes.conn.sql("insert into `tab%(doctype)s`" % self.fields \
  219. + """ (name, owner, creation, modified, modified_by)
  220. values (%(name)s, %(owner)s, %(creation)s, %(modified)s,
  221. %(modified_by)s)""", self.fields)
  222. def _update_single(self, link_list):
  223. update_str = ["(%s, 'modified', %s)",]
  224. values = [self.doctype, now()]
  225. webnotes.conn.sql("delete from tabSingles where doctype='%s'" % self.doctype)
  226. for f in self.fields.keys():
  227. if not (f in ('modified', 'doctype', 'name', 'perm', 'localname', 'creation'))\
  228. and (not f.startswith('__')): # fields not saved
  229. # validate links
  230. if link_list and link_list.get(f):
  231. self.fields[f] = self._validate_link(link_list[f][0], self.fields[f])
  232. if self.fields[f]==None:
  233. update_str.append("(%s,%s,NULL)")
  234. values.append(self.doctype)
  235. values.append(f)
  236. else:
  237. update_str.append("(%s,%s,%s)")
  238. values.append(self.doctype)
  239. values.append(f)
  240. values.append(self.fields[f])
  241. webnotes.conn.sql("insert into tabSingles(doctype, field, value) values %s" % (', '.join(update_str)), values)
  242. def validate_links(self, link_list):
  243. err_list = []
  244. for f in self.fields.keys():
  245. # validate links
  246. old_val = self.fields[f]
  247. if link_list and link_list.get(f):
  248. self.fields[f] = self._validate_link(link_list[f][0], self.fields[f])
  249. if old_val and not self.fields[f]:
  250. s = link_list[f][1] + ': ' + old_val
  251. err_list.append(s)
  252. return err_list
  253. def make_link_list(self):
  254. res = webnotes.model.meta.get_link_fields(self.doctype)
  255. link_list = {}
  256. for i in res: link_list[i[0]] = (i[1], i[2]) # options, label
  257. return link_list
  258. def _validate_link(self, dt, dn):
  259. if not dt: return dn
  260. if not dn: return None
  261. if dt=="[Select]": return dn
  262. if dt.lower().startswith('link:'):
  263. dt = dt[5:]
  264. if '\n' in dt:
  265. dt = dt.split('\n')[0]
  266. tmp = webnotes.conn.sql("""SELECT name FROM `tab%s`
  267. WHERE name = %s""" % (dt, '%s'), dn)
  268. return tmp and tmp[0][0] or ''# match case
  269. def _update_values(self, issingle, link_list, ignore_fields=0, keep_timestamps=False):
  270. if issingle:
  271. self._update_single(link_list)
  272. else:
  273. update_str, values = [], []
  274. # set modified timestamp
  275. if self.modified and not keep_timestamps:
  276. self.modified = now()
  277. self.modified_by = webnotes.session['user']
  278. fields_list = ignore_fields and self.get_valid_fields() or self.fields.keys()
  279. for f in fields_list:
  280. if (not (f in ('doctype', 'name', 'perm', 'localname',
  281. 'creation','_user_tags'))) and (not f.startswith('__')):
  282. # fields not saved
  283. # validate links
  284. if link_list and link_list.get(f):
  285. self.fields[f] = self._validate_link(link_list[f][0],
  286. self.fields.get(f))
  287. if self.fields.get(f) is None or self.fields.get(f)=='':
  288. update_str.append("`%s`=NULL" % f)
  289. else:
  290. values.append(self.fields.get(f))
  291. update_str.append("`%s`=%s" % (f, '%s'))
  292. if values:
  293. values.append(self.name)
  294. r = webnotes.conn.sql("update `tab%s` set %s where name=%s" % \
  295. (self.doctype, ', '.join(update_str), "%s"), values)
  296. def get_valid_fields(self):
  297. global valid_fields_map
  298. if not valid_fields_map.get(self.doctype):
  299. import webnotes.model.doctype
  300. if cint(webnotes.conn.get_value("DocType", self.doctype, "issingle")):
  301. doctypelist = webnotes.model.doctype.get(self.doctype)
  302. valid_fields_map[self.doctype] = doctypelist.get_fieldnames({
  303. "fieldtype": ["not in", webnotes.model.no_value_fields]})
  304. else:
  305. valid_fields_map[self.doctype] = \
  306. webnotes.conn.get_table_columns(self.doctype)
  307. return valid_fields_map.get(self.doctype)
  308. def save(self, new=0, check_links=1, ignore_fields=0, make_autoname=1,
  309. keep_timestamps=False):
  310. res = webnotes.model.meta.get_dt_values(self.doctype,
  311. 'autoname, issingle, istable, name_case', as_dict=1)
  312. res = res and res[0] or {}
  313. if new:
  314. self.fields["__islocal"] = 1
  315. # add missing parentinfo (if reqd)
  316. if self.parent and not (self.parenttype and self.parentfield):
  317. self.update_parentinfo()
  318. if self.parent and not self.idx:
  319. self.set_idx()
  320. # if required, make new
  321. if self.fields.get('__islocal') and (not res.get('issingle')):
  322. r = self._insert(res.get('autoname'), res.get('istable'), res.get('name_case'),
  323. make_autoname, keep_timestamps = keep_timestamps)
  324. if r:
  325. return r
  326. else:
  327. if not res.get('issingle') and not webnotes.conn.exists(self.doctype, self.name):
  328. webnotes.msgprint("""This document was updated before your change. Please refresh before saving.""", raise_exception=1)
  329. # save the values
  330. self._update_values(res.get('issingle'),
  331. check_links and self.make_link_list() or {}, ignore_fields=ignore_fields,
  332. keep_timestamps=keep_timestamps)
  333. self._clear_temp_fields()
  334. def insert(self):
  335. self.fields['__islocal'] = 1
  336. self.save()
  337. return self
  338. def update_parentinfo(self):
  339. """update parent type and parent field, if not explicitly specified"""
  340. tmp = webnotes.conn.sql("""select parent, fieldname from tabDocField
  341. where fieldtype='Table' and options=%s""", self.doctype)
  342. if len(tmp)==0:
  343. raise Exception, 'Incomplete parent info in child table (%s, %s)' \
  344. % (self.doctype, self.fields.get('name', '[new]'))
  345. elif len(tmp)>1:
  346. raise Exception, 'Ambiguous parent info (%s, %s)' \
  347. % (self.doctype, self.fields.get('name', '[new]'))
  348. else:
  349. self.parenttype = tmp[0][0]
  350. self.parentfield = tmp[0][1]
  351. def set_idx(self):
  352. """set idx"""
  353. self.idx = (webnotes.conn.sql("""select max(idx) from `tab%s`
  354. where parent=%s and parentfield=%s""" % (self.doctype, '%s', '%s'),
  355. (self.parent, self.parentfield))[0][0] or 0) + 1
  356. def _clear_temp_fields(self):
  357. # clear temp stuff
  358. keys = self.fields.keys()
  359. for f in keys:
  360. if f.startswith('__'):
  361. del self.fields[f]
  362. def clear_table(self, doclist, tablefield, save=0):
  363. """
  364. Clears the child records from the given `doclist` for a particular `tablefield`
  365. """
  366. from webnotes.model.utils import getlist
  367. table_list = getlist(doclist, tablefield)
  368. delete_list = [d.name for d in table_list]
  369. if delete_list:
  370. #filter doclist
  371. doclist = filter(lambda d: d.name not in delete_list, doclist)
  372. # delete from db
  373. webnotes.conn.sql("""\
  374. delete from `tab%s`
  375. where parent=%s and parenttype=%s"""
  376. % (table_list[0].doctype, '%s', '%s'),
  377. (self.name, self.doctype))
  378. self.fields['__unsaved'] = 1
  379. return webnotes.doclist(doclist)
  380. def addchild(self, fieldname, childtype = '', doclist=None):
  381. """
  382. Returns a child record of the give `childtype`.
  383. * if local is set, it does not save the record
  384. * if doclist is passed, it append the record to the doclist
  385. """
  386. from webnotes.model.doc import Document
  387. d = Document()
  388. d.parent = self.name
  389. d.parenttype = self.doctype
  390. d.parentfield = fieldname
  391. d.doctype = childtype
  392. d.docstatus = 0;
  393. d.name = ''
  394. d.owner = webnotes.session['user']
  395. d.fields['__islocal'] = 1 # for Client to identify unsaved doc
  396. if doclist != None:
  397. doclist.append(d)
  398. return d
  399. def get_values(self):
  400. """get non-null fields dict withouth standard fields"""
  401. from webnotes.model import default_fields
  402. ret = {}
  403. for key in self.fields:
  404. if key not in default_fields and self.fields[key]:
  405. ret[key] = self.fields[key]
  406. return ret
  407. def addchild(parent, fieldname, childtype = '', doclist=None):
  408. """
  409. Create a child record to the parent doc.
  410. Example::
  411. c = Document('Contact','ABC')
  412. d = addchild(c, 'contact_updates', 'Contact Update')
  413. d.last_updated = 'Phone call'
  414. d.save(1)
  415. """
  416. return parent.addchild(fieldname, childtype, doclist)
  417. def make_autoname(key, doctype=''):
  418. """
  419. Creates an autoname from the given key:
  420. **Autoname rules:**
  421. * The key is separated by '.'
  422. * '####' represents a series. The string before this part becomes the prefix:
  423. Example: ABC.#### creates a series ABC0001, ABC0002 etc
  424. * 'MM' represents the current month
  425. * 'YY' and 'YYYY' represent the current year
  426. *Example:*
  427. * DE/./.YY./.MM./.##### will create a series like
  428. DE/09/01/0001 where 09 is the year, 01 is the month and 0001 is the series
  429. """
  430. n = ''
  431. l = key.split('.')
  432. for e in l:
  433. en = ''
  434. if e.startswith('#'):
  435. digits = len(e)
  436. en = getseries(n, digits, doctype)
  437. elif e=='YY':
  438. import time
  439. en = time.strftime('%y')
  440. elif e=='MM':
  441. import time
  442. en = time.strftime('%m')
  443. elif e=='YYYY':
  444. import time
  445. en = time.strftime('%Y')
  446. else: en = e
  447. n+=en
  448. return n
  449. def getseries(key, digits, doctype=''):
  450. # series created ?
  451. if webnotes.conn.sql("select name from tabSeries where name='%s'" % key):
  452. # yes, update it
  453. webnotes.conn.sql("update tabSeries set current = current+1 where name='%s'" % key)
  454. # find the series counter
  455. r = webnotes.conn.sql("select current from tabSeries where name='%s'" % key)
  456. n = r[0][0]
  457. else:
  458. # no, create it
  459. webnotes.conn.sql("insert into tabSeries (name, current) values ('%s', 1)" % key)
  460. n = 1
  461. return ('%0'+str(digits)+'d') % n
  462. def getchildren(name, childtype, field='', parenttype='', from_doctype=0, prefix='tab'):
  463. import webnotes
  464. from webnotes.model.doclist import DocList
  465. condition = ""
  466. values = []
  467. if field:
  468. condition += ' and parentfield=%s '
  469. values.append(field)
  470. if parenttype:
  471. condition += ' and parenttype=%s '
  472. values.append(parenttype)
  473. dataset = webnotes.conn.sql("""select * from `%s%s` where parent=%s %s order by idx""" \
  474. % (prefix, childtype, "%s", condition), tuple([name]+values))
  475. desc = webnotes.conn.get_description()
  476. l = DocList()
  477. for i in dataset:
  478. d = Document()
  479. d.doctype = childtype
  480. d._load_values(i, desc)
  481. l.append(d)
  482. return l
  483. def check_page_perm(doc):
  484. if doc.name=='Login Page':
  485. return
  486. if doc.publish:
  487. return
  488. if not webnotes.conn.sql("select name from `tabPage Role` where parent=%s and role='Guest'", doc.name):
  489. webnotes.response['403'] = 1
  490. raise webnotes.PermissionError, '[WNF] No read permission for %s %s' % ('Page', doc.name)
  491. def get_report_builder_code(doc):
  492. if doc.doctype=='Search Criteria':
  493. from webnotes.model.code import get_code
  494. if doc.standard != 'No':
  495. doc.report_script = get_code(doc.module, 'Search Criteria', doc.name, 'js')
  496. doc.custom_query = get_code(doc.module, 'Search Criteria', doc.name, 'sql')
  497. def get(dt, dn='', with_children = 1, from_controller = 0, prefix = 'tab'):
  498. """
  499. Returns a doclist containing the main record and all child records
  500. """
  501. import webnotes
  502. import webnotes.model
  503. from webnotes.model.doclist import DocList
  504. dn = dn or dt
  505. # load the main doc
  506. doc = Document(dt, dn, prefix=prefix)
  507. if dt=='Page' and webnotes.session['user'] == 'Guest':
  508. check_page_perm(doc)
  509. if not with_children:
  510. # done
  511. return DocList([doc,])
  512. # get all children types
  513. tablefields = webnotes.model.meta.get_table_fields(dt)
  514. # load chilren
  515. doclist = DocList([doc,])
  516. for t in tablefields:
  517. doclist += getchildren(doc.name, t[0], t[1], dt, prefix=prefix)
  518. # import report_builder code
  519. if not from_controller:
  520. get_report_builder_code(doc)
  521. return doclist
  522. def getsingle(doctype):
  523. """get single doc as dict"""
  524. dataset = webnotes.conn.sql("select field, value from tabSingles where doctype=%s", doctype)
  525. return dict(dataset)
  526. def copy_common_fields(from_doc, to_doc):
  527. from webnotes.model import default_fields
  528. doctype_list = webnotes.get_doctype(to_doc.doctype)
  529. for fieldname, value in from_doc.fields.items():
  530. if fieldname in default_fields:
  531. continue
  532. if doctype_list.get_field(fieldname) and to_doc.fields[fieldname] != value:
  533. to_doc.fields[fieldname] = value
  534. def validate_name(doctype, name, case=None):
  535. if webnotes.conn.sql('select name from `tab%s` where name=%s' % (doctype,'%s'), name):
  536. raise NameError, 'Name %s already exists' % name
  537. # no name
  538. if not name: return 'No Name Specified for %s' % doctype
  539. # new..
  540. if name.startswith('New '+doctype):
  541. raise NameError, 'There were some errors setting the name, please contact the administrator'
  542. if case=='Title Case': name = name.title()
  543. if case=='UPPER CASE': name = name.upper()
  544. name = name.strip() # no leading and trailing blanks
  545. forbidden = ['%', "'", '"', '#', '*', '?', '`']
  546. for f in forbidden:
  547. if f in name:
  548. webnotes.msgprint('%s not allowed in ID (name)' % f, raise_exception =1)
  549. return name