Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 
 
 

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