You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

663 regels
20 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 __eq__(self, other):
  92. return self.fields == other.fields
  93. def __getstate__(self):
  94. return self.fields
  95. def __setstate__(self, d):
  96. self.fields = d
  97. def encode(self, encoding='utf-8'):
  98. """convert all unicode values to utf-8"""
  99. for key in self.fields:
  100. if isinstance(self.fields[key], unicode):
  101. self.fields[key] = self.fields[key].encode(encoding)
  102. def _loadfromdb(self, doctype = None, name = None):
  103. if name: self.name = name
  104. if doctype: self.doctype = doctype
  105. is_single = False
  106. try:
  107. is_single = webnotes.model.meta.is_single(self.doctype)
  108. except Exception, e:
  109. pass
  110. if is_single:
  111. self._loadsingle()
  112. else:
  113. dataset = webnotes.conn.sql('select * from `%s%s` where name="%s"' % (self._prefix, self.doctype, self.name.replace('"', '\"')))
  114. if not dataset:
  115. raise Exception, '[WNF] %s %s does not exist' % (self.doctype, self.name)
  116. self._load_values(dataset[0], webnotes.conn.get_description())
  117. def _load_values(self, data, description):
  118. if '__islocal' in self.fields:
  119. del self.fields['__islocal']
  120. for i in range(len(description)):
  121. v = data[i]
  122. self.fields[description[i][0]] = webnotes.conn.convert_to_simple_type(v)
  123. def _merge_values(self, data, description):
  124. for i in range(len(description)):
  125. v = data[i]
  126. if v: # only if value, over-write
  127. self.fields[description[i][0]] = webnotes.conn.convert_to_simple_type(v)
  128. def _loadsingle(self):
  129. self.name = self.doctype
  130. self.fields.update(getsingle(self.doctype))
  131. def __setattr__(self, name, value):
  132. # normal attribute
  133. if not self.__dict__.has_key('_Document__initialized'):
  134. self.__dict__[name] = value
  135. elif self.__dict__.has_key(name):
  136. self.__dict__[name] = value
  137. else:
  138. # field attribute
  139. f = self.__dict__['fields']
  140. f[name] = value
  141. def __getattr__(self, name):
  142. if self.__dict__.has_key(name):
  143. return self.__dict__[name]
  144. elif self.fields.has_key(name):
  145. return self.fields[name]
  146. else:
  147. return ''
  148. def _get_amended_name(self):
  149. am_id = 1
  150. am_prefix = self.amended_from
  151. if webnotes.conn.sql('select amended_from from `tab%s` where name = "%s"' % (self.doctype, self.amended_from))[0][0] or '':
  152. am_id = cint(self.amended_from.split('-')[-1]) + 1
  153. am_prefix = '-'.join(self.amended_from.split('-')[:-1]) # except the last hyphen
  154. self.name = am_prefix + '-' + str(am_id)
  155. def _set_name(self, autoname, istable):
  156. self.localname = self.name
  157. # get my object
  158. import webnotes.model.code
  159. so = webnotes.model.code.get_server_obj(self, [])
  160. # amendments
  161. if self.amended_from:
  162. self._get_amended_name()
  163. # by method
  164. elif so and hasattr(so, 'autoname'):
  165. r = webnotes.model.code.run_server_obj(so, 'autoname')
  166. if r: return r
  167. # based on a field
  168. elif autoname and autoname.startswith('field:'):
  169. n = self.fields[autoname[6:]]
  170. if not n:
  171. raise Exception, 'Name is required'
  172. self.name = n.strip()
  173. elif autoname and autoname.startswith("naming_series:"):
  174. if not self.naming_series:
  175. # pick default naming series
  176. from webnotes.model.doctype import get_property
  177. self.naming_series = get_property(self.doctype, "options", "naming_series").split("\n")
  178. self.naming_series = self.naming_series[0] or self.naming_series[1]
  179. self.name = make_autoname(self.naming_series+'.#####')
  180. # based on expression
  181. elif autoname and autoname.startswith('eval:'):
  182. doc = self # for setting
  183. self.name = eval(autoname[5:])
  184. # call the method!
  185. elif autoname and autoname!='Prompt':
  186. self.name = make_autoname(autoname, self.doctype)
  187. # given
  188. elif self.fields.get('__newname',''):
  189. self.name = self.fields['__newname']
  190. # default name for table
  191. elif istable:
  192. self.name = make_autoname('#########', self.doctype)
  193. # unable to determine a name, use a serial number!
  194. if not self.name:
  195. self.name = make_autoname('#########', self.doctype)
  196. def _validate_name(self, case):
  197. if webnotes.conn.sql('select name from `tab%s` where name=%s' % (self.doctype,'%s'), self.name):
  198. raise NameError, 'Name %s already exists' % self.name
  199. # no name
  200. if not self.name: return 'No Name Specified for %s' % self.doctype
  201. # new..
  202. if self.name.startswith('New '+self.doctype):
  203. raise NameError, 'There were some errors setting the name, please contact the administrator'
  204. if case=='Title Case': self.name = self.name.title()
  205. if case=='UPPER CASE': self.name = self.name.upper()
  206. self.name = self.name.strip() # no leading and trailing blanks
  207. forbidden = ['%', "'", '"', '#', '*', '?', '`']
  208. for f in forbidden:
  209. if f in self.name:
  210. webnotes.msgprint('%s not allowed in ID (name)' % f, raise_exception =1)
  211. def _insert(self, autoname, istable, case='', make_autoname=1, keep_timestamps=False):
  212. # set name
  213. if make_autoname:
  214. self._set_name(autoname, istable)
  215. # validate name
  216. self._validate_name(case)
  217. # insert!
  218. if not keep_timestamps:
  219. if not self.owner:
  220. self.owner = webnotes.session['user']
  221. self.modified_by = webnotes.session['user']
  222. self.creation = self.modified = now()
  223. webnotes.conn.sql("insert into `tab%(doctype)s`" % self.fields \
  224. + """ (name, owner, creation, modified, modified_by)
  225. values (%(name)s, %(owner)s, %(creation)s, %(modified)s,
  226. %(modified_by)s)""", self.fields)
  227. def _update_single(self, link_list):
  228. update_str = ["(%s, 'modified', %s)",]
  229. values = [self.doctype, now()]
  230. webnotes.conn.sql("delete from tabSingles where doctype='%s'" % self.doctype)
  231. for f in self.fields.keys():
  232. if not (f in ('modified', 'doctype', 'name', 'perm', 'localname', 'creation'))\
  233. and (not f.startswith('__')): # fields not saved
  234. # validate links
  235. if link_list and link_list.get(f):
  236. self.fields[f] = self._validate_link(link_list[f][0], self.fields[f])
  237. if self.fields[f]==None:
  238. update_str.append("(%s,%s,NULL)")
  239. values.append(self.doctype)
  240. values.append(f)
  241. else:
  242. update_str.append("(%s,%s,%s)")
  243. values.append(self.doctype)
  244. values.append(f)
  245. values.append(self.fields[f])
  246. webnotes.conn.sql("insert into tabSingles(doctype, field, value) values %s" % (', '.join(update_str)), values)
  247. def validate_links(self, link_list):
  248. err_list = []
  249. for f in self.fields.keys():
  250. # validate links
  251. old_val = self.fields[f]
  252. if link_list and link_list.get(f):
  253. self.fields[f] = self._validate_link(link_list[f][0], self.fields[f])
  254. if old_val and not self.fields[f]:
  255. s = link_list[f][1] + ': ' + old_val
  256. err_list.append(s)
  257. return err_list
  258. def make_link_list(self):
  259. res = webnotes.model.meta.get_link_fields(self.doctype)
  260. link_list = {}
  261. for i in res: link_list[i[0]] = (i[1], i[2]) # options, label
  262. return link_list
  263. def _validate_link(self, dt, dn):
  264. if not dt: return dn
  265. if not dn: return None
  266. if dt=="[Select]": return dn
  267. if dt.lower().startswith('link:'):
  268. dt = dt[5:]
  269. if '\n' in dt:
  270. dt = dt.split('\n')[0]
  271. tmp = webnotes.conn.sql("""SELECT name FROM `tab%s`
  272. WHERE name = %s""" % (dt, '%s'), dn)
  273. return tmp and tmp[0][0] or ''# match case
  274. def _update_values(self, issingle, link_list, ignore_fields=0, keep_timestamps=False):
  275. if issingle:
  276. self._update_single(link_list)
  277. else:
  278. update_str, values = [], []
  279. # set modified timestamp
  280. if self.modified and not keep_timestamps:
  281. self.modified = now()
  282. self.modified_by = webnotes.session['user']
  283. fields_list = ignore_fields and self.get_valid_fields() or self.fields.keys()
  284. for f in fields_list:
  285. if (not (f in ('doctype', 'name', 'perm', 'localname',
  286. 'creation','_user_tags'))) and (not f.startswith('__')):
  287. # fields not saved
  288. # validate links
  289. if link_list and link_list.get(f):
  290. self.fields[f] = self._validate_link(link_list[f][0],
  291. self.fields.get(f))
  292. if self.fields.get(f) is None or self.fields.get(f)=='':
  293. update_str.append("`%s`=NULL" % f)
  294. else:
  295. values.append(self.fields.get(f))
  296. update_str.append("`%s`=%s" % (f, '%s'))
  297. if values:
  298. values.append(self.name)
  299. r = webnotes.conn.sql("update `tab%s` set %s where name=%s" % \
  300. (self.doctype, ', '.join(update_str), "%s"), values)
  301. def get_valid_fields(self):
  302. global valid_fields_map
  303. if not valid_fields_map.get(self.doctype):
  304. import webnotes.model.doctype
  305. if cint(webnotes.conn.get_value("DocType", self.doctype, "issingle")):
  306. doctypelist = webnotes.model.doctype.get(self.doctype)
  307. valid_fields_map[self.doctype] = doctypelist.get_fieldnames({
  308. "fieldtype": ["not in", webnotes.model.no_value_fields]})
  309. else:
  310. valid_fields_map[self.doctype] = \
  311. webnotes.conn.get_table_columns(self.doctype)
  312. return valid_fields_map.get(self.doctype)
  313. def save(self, new=0, check_links=1, ignore_fields=0, make_autoname=1,
  314. keep_timestamps=False):
  315. res = webnotes.model.meta.get_dt_values(self.doctype,
  316. 'autoname, issingle, istable, name_case', as_dict=1)
  317. res = res and res[0] or {}
  318. if new:
  319. self.fields["__islocal"] = 1
  320. # add missing parentinfo (if reqd)
  321. if self.parent and not (self.parenttype and self.parentfield):
  322. self.update_parentinfo()
  323. if self.parent and not self.idx:
  324. self.set_idx()
  325. # if required, make new
  326. if self.fields.get('__islocal') and (not res.get('issingle')):
  327. r = self._insert(res.get('autoname'), res.get('istable'), res.get('name_case'),
  328. make_autoname, keep_timestamps = keep_timestamps)
  329. if r:
  330. return r
  331. else:
  332. if not res.get('issingle') and not webnotes.conn.exists(self.doctype, self.name):
  333. webnotes.msgprint("""This document was updated before your change. Please refresh before saving.""", raise_exception=1)
  334. # save the values
  335. self._update_values(res.get('issingle'),
  336. check_links and self.make_link_list() or {}, ignore_fields=ignore_fields,
  337. keep_timestamps=keep_timestamps)
  338. self._clear_temp_fields()
  339. def insert(self):
  340. self.fields['__islocal'] = 1
  341. self.save()
  342. return self
  343. def update_parentinfo(self):
  344. """update parent type and parent field, if not explicitly specified"""
  345. tmp = webnotes.conn.sql("""select parent, fieldname from tabDocField
  346. where fieldtype='Table' and options=%s""", self.doctype)
  347. if len(tmp)==0:
  348. raise Exception, 'Incomplete parent info in child table (%s, %s)' \
  349. % (self.doctype, self.fields.get('name', '[new]'))
  350. elif len(tmp)>1:
  351. raise Exception, 'Ambiguous parent info (%s, %s)' \
  352. % (self.doctype, self.fields.get('name', '[new]'))
  353. else:
  354. self.parenttype = tmp[0][0]
  355. self.parentfield = tmp[0][1]
  356. def set_idx(self):
  357. """set idx"""
  358. self.idx = (webnotes.conn.sql("""select max(idx) from `tab%s`
  359. where parent=%s and parentfield=%s""" % (self.doctype, '%s', '%s'),
  360. (self.parent, self.parentfield))[0][0] or 0) + 1
  361. def _clear_temp_fields(self):
  362. # clear temp stuff
  363. keys = self.fields.keys()
  364. for f in keys:
  365. if f.startswith('__'):
  366. del self.fields[f]
  367. def clear_table(self, doclist, tablefield, save=0):
  368. """
  369. Clears the child records from the given `doclist` for a particular `tablefield`
  370. """
  371. from webnotes.model.utils import getlist
  372. table_list = getlist(doclist, tablefield)
  373. delete_list = [d.name for d in table_list]
  374. if delete_list:
  375. #filter doclist
  376. doclist = filter(lambda d: d.name not in delete_list, doclist)
  377. # delete from db
  378. webnotes.conn.sql("""\
  379. delete from `tab%s`
  380. where parent=%s and parenttype=%s"""
  381. % (table_list[0].doctype, '%s', '%s'),
  382. (self.name, self.doctype))
  383. self.fields['__unsaved'] = 1
  384. return webnotes.doclist(doclist)
  385. def addchild(self, fieldname, childtype = '', doclist=None):
  386. """
  387. Returns a child record of the give `childtype`.
  388. * if local is set, it does not save the record
  389. * if doclist is passed, it append the record to the doclist
  390. """
  391. from webnotes.model.doc import Document
  392. d = Document()
  393. d.parent = self.name
  394. d.parenttype = self.doctype
  395. d.parentfield = fieldname
  396. d.doctype = childtype
  397. d.docstatus = 0;
  398. d.name = ''
  399. d.owner = webnotes.session['user']
  400. d.fields['__islocal'] = 1 # for Client to identify unsaved doc
  401. if doclist != None:
  402. doclist.append(d)
  403. return d
  404. def get_values(self):
  405. """get non-null fields dict withouth standard fields"""
  406. from webnotes.model import default_fields
  407. ret = {}
  408. for key in self.fields:
  409. if key not in default_fields and self.fields[key]:
  410. ret[key] = self.fields[key]
  411. return ret
  412. def addchild(parent, fieldname, childtype = '', doclist=None):
  413. """
  414. Create a child record to the parent doc.
  415. Example::
  416. c = Document('Contact','ABC')
  417. d = addchild(c, 'contact_updates', 'Contact Update')
  418. d.last_updated = 'Phone call'
  419. d.save(1)
  420. """
  421. return parent.addchild(fieldname, childtype, doclist)
  422. def make_autoname(key, doctype=''):
  423. """
  424. Creates an autoname from the given key:
  425. **Autoname rules:**
  426. * The key is separated by '.'
  427. * '####' represents a series. The string before this part becomes the prefix:
  428. Example: ABC.#### creates a series ABC0001, ABC0002 etc
  429. * 'MM' represents the current month
  430. * 'YY' and 'YYYY' represent the current year
  431. *Example:*
  432. * DE/./.YY./.MM./.##### will create a series like
  433. DE/09/01/0001 where 09 is the year, 01 is the month and 0001 is the series
  434. """
  435. n = ''
  436. l = key.split('.')
  437. for e in l:
  438. en = ''
  439. if e.startswith('#'):
  440. digits = len(e)
  441. en = getseries(n, digits, doctype)
  442. elif e=='YY':
  443. import time
  444. en = time.strftime('%y')
  445. elif e=='MM':
  446. import time
  447. en = time.strftime('%m')
  448. elif e=='YYYY':
  449. import time
  450. en = time.strftime('%Y')
  451. else: en = e
  452. n+=en
  453. return n
  454. def getseries(key, digits, doctype=''):
  455. # series created ?
  456. if webnotes.conn.sql("select name from tabSeries where name='%s'" % key):
  457. # yes, update it
  458. webnotes.conn.sql("update tabSeries set current = current+1 where name='%s'" % key)
  459. # find the series counter
  460. r = webnotes.conn.sql("select current from tabSeries where name='%s'" % key)
  461. n = r[0][0]
  462. else:
  463. # no, create it
  464. webnotes.conn.sql("insert into tabSeries (name, current) values ('%s', 1)" % key)
  465. n = 1
  466. return ('%0'+str(digits)+'d') % n
  467. def getchildren(name, childtype, field='', parenttype='', from_doctype=0, prefix='tab'):
  468. import webnotes
  469. from webnotes.model.doclist import DocList
  470. tmp = ''
  471. if field:
  472. tmp = ' and parentfield="%s" ' % field
  473. if parenttype:
  474. tmp = ' and parenttype="%s" ' % parenttype
  475. dataset = webnotes.conn.sql("select * from `%s%s` where parent='%s' %s order by idx" \
  476. % (prefix, childtype, name, tmp))
  477. desc = webnotes.conn.get_description()
  478. l = DocList()
  479. for i in dataset:
  480. d = Document()
  481. d.doctype = childtype
  482. d._load_values(i, desc)
  483. l.append(d)
  484. return l
  485. def check_page_perm(doc):
  486. if doc.name=='Login Page':
  487. return
  488. if doc.publish:
  489. return
  490. if not webnotes.conn.sql("select name from `tabPage Role` where parent=%s and role='Guest'", doc.name):
  491. webnotes.response['403'] = 1
  492. raise webnotes.PermissionError, '[WNF] No read permission for %s %s' % ('Page', doc.name)
  493. def get_report_builder_code(doc):
  494. if doc.doctype=='Search Criteria':
  495. from webnotes.model.code import get_code
  496. if doc.standard != 'No':
  497. doc.report_script = get_code(doc.module, 'Search Criteria', doc.name, 'js')
  498. doc.custom_query = get_code(doc.module, 'Search Criteria', doc.name, 'sql')
  499. def get(dt, dn='', with_children = 1, from_controller = 0, prefix = 'tab'):
  500. """
  501. Returns a doclist containing the main record and all child records
  502. """
  503. import webnotes
  504. import webnotes.model
  505. from webnotes.model.doclist import DocList
  506. dn = dn or dt
  507. # load the main doc
  508. doc = Document(dt, dn, prefix=prefix)
  509. if dt=='Page' and webnotes.session['user'] == 'Guest':
  510. check_page_perm(doc)
  511. if not with_children:
  512. # done
  513. return DocList([doc,])
  514. # get all children types
  515. tablefields = webnotes.model.meta.get_table_fields(dt)
  516. # load chilren
  517. doclist = DocList([doc,])
  518. for t in tablefields:
  519. doclist += getchildren(doc.name, t[0], t[1], dt, prefix=prefix)
  520. # import report_builder code
  521. if not from_controller:
  522. get_report_builder_code(doc)
  523. return doclist
  524. def getsingle(doctype):
  525. """get single doc as dict"""
  526. dataset = webnotes.conn.sql("select field, value from tabSingles where doctype=%s", doctype)
  527. return dict(dataset)