Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 
 
 

721 wiersze
20 KiB

  1. # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
  2. # MIT License. See license.txt
  3. from __future__ import unicode_literals
  4. """
  5. Contains the Document class representing an object / record
  6. """
  7. _toc = ["webnotes.model.doc.Document"]
  8. import webnotes
  9. import webnotes.model.meta
  10. from webnotes.utils import *
  11. class Document:
  12. """
  13. The wn(meta-data)framework equivalent of a Database Record.
  14. Stores,Retrieves,Updates the record in the corresponding table.
  15. Runs the triggers required.
  16. The `Document` class represents the basic Object-Relational Mapper (ORM). The object type is defined by
  17. `DocType` and the object ID is represented by `name`::
  18. Please note the anamoly in the Web Notes Framework that `ID` is always called as `name`
  19. If both `doctype` and `name` are specified in the constructor, then the object is loaded from the database.
  20. If only `doctype` is given, then the object is not loaded
  21. If `fielddata` is specfied, then the object is created from the given dictionary.
  22. **Note 1:**
  23. The getter and setter of the object are overloaded to map to the fields of the object that
  24. are loaded when it is instantiated.
  25. For example: doc.name will be the `name` field and doc.owner will be the `owner` field
  26. **Note 2 - Standard Fields:**
  27. * `name`: ID / primary key
  28. * `owner`: creator of the record
  29. * `creation`: datetime of creation
  30. * `modified`: datetime of last modification
  31. * `modified_by` : last updating user
  32. * `docstatus` : Status 0 - Saved, 1 - Submitted, 2- Cancelled
  33. * `parent` : if child (table) record, this represents the parent record
  34. * `parenttype` : type of parent record (if any)
  35. * `parentfield` : table fieldname of parent record (if any)
  36. * `idx` : Index (sequence) of the child record
  37. """
  38. def __init__(self, doctype = None, name = None, fielddata = None):
  39. self._roles = []
  40. self._perms = []
  41. self._user_defaults = {}
  42. self._new_name_set = False
  43. self._meta = None
  44. if isinstance(doctype, dict):
  45. fielddata = doctype
  46. doctype = None
  47. if fielddata:
  48. self.fields = webnotes._dict(fielddata)
  49. else:
  50. self.fields = webnotes._dict()
  51. if not self.fields.has_key('name'):
  52. self.fields['name']='' # required on save
  53. if not self.fields.has_key('doctype'):
  54. self.fields['doctype']='' # required on save
  55. if not self.fields.has_key('owner'):
  56. self.fields['owner']='' # required on save
  57. if doctype:
  58. self.fields['doctype'] = doctype
  59. if name:
  60. self.fields['name'] = name
  61. self.__initialized = 1
  62. if (doctype and name):
  63. self._loadfromdb(doctype, name)
  64. else:
  65. if not fielddata:
  66. self.fields['__islocal'] = 1
  67. if not self.fields.docstatus:
  68. self.fields.docstatus = 0
  69. def __nonzero__(self):
  70. return True
  71. def __str__(self):
  72. return str(self.fields)
  73. def __repr__(self):
  74. return repr(self.fields)
  75. def __unicode__(self):
  76. return unicode(self.fields)
  77. def __eq__(self, other):
  78. if isinstance(other, Document):
  79. return self.fields == other.fields
  80. else:
  81. return False
  82. def __getstate__(self):
  83. return self.fields
  84. def __setstate__(self, d):
  85. self.fields = d
  86. def encode(self, encoding='utf-8'):
  87. """convert all unicode values to utf-8"""
  88. from webnotes.utils import encode_dict
  89. encode_dict(self.fields)
  90. def _loadfromdb(self, doctype = None, name = None):
  91. if name: self.name = name
  92. if doctype: self.doctype = doctype
  93. is_single = False
  94. try:
  95. is_single = webnotes.model.meta.is_single(self.doctype)
  96. except Exception, e:
  97. pass
  98. if is_single:
  99. self._loadsingle()
  100. else:
  101. try:
  102. dataset = webnotes.conn.sql('select * from `tab%s` where name="%s"' % (self.doctype, self.name.replace('"', '\"')))
  103. except webnotes.SQLError, e:
  104. if e.args[0]==1146:
  105. dataset = None
  106. else:
  107. raise
  108. if not dataset:
  109. raise webnotes.DoesNotExistError, '[WNF] %s %s does not exist' % (self.doctype, self.name)
  110. self._load_values(dataset[0], webnotes.conn.get_description())
  111. def is_new(self):
  112. return self.fields.get("__islocal")
  113. def _load_values(self, data, description):
  114. if '__islocal' in self.fields:
  115. del self.fields['__islocal']
  116. for i in range(len(description)):
  117. v = data[i]
  118. self.fields[description[i][0]] = webnotes.conn.convert_to_simple_type(v)
  119. def _merge_values(self, data, description):
  120. for i in range(len(description)):
  121. v = data[i]
  122. if v: # only if value, over-write
  123. self.fields[description[i][0]] = webnotes.conn.convert_to_simple_type(v)
  124. def _loadsingle(self):
  125. self.name = self.doctype
  126. self.fields.update(getsingle(self.doctype))
  127. def __setattr__(self, name, value):
  128. # normal attribute
  129. if not self.__dict__.has_key('_Document__initialized'):
  130. self.__dict__[name] = value
  131. elif self.__dict__.has_key(name):
  132. self.__dict__[name] = value
  133. else:
  134. # field attribute
  135. f = self.__dict__['fields']
  136. f[name] = value
  137. def __getattr__(self, name):
  138. if self.__dict__.has_key(name):
  139. return self.__dict__[name]
  140. elif self.fields.has_key(name):
  141. return self.fields[name]
  142. else:
  143. return ''
  144. def get(self, name, value=None):
  145. return self.fields.get(name, value)
  146. def update(self, d):
  147. self.fields.update(d)
  148. return self
  149. def insert(self):
  150. self.fields['__islocal'] = 1
  151. self.save()
  152. return self
  153. def save(self, new=0, check_links=1, ignore_fields=0, make_autoname=1,
  154. keep_timestamps=False):
  155. self.get_meta()
  156. if new:
  157. self.fields["__islocal"] = 1
  158. # add missing parentinfo (if reqd)
  159. if self.parent and not (self.parenttype and self.parentfield):
  160. self.update_parentinfo()
  161. if self.parent and not self.idx:
  162. self.set_idx()
  163. # if required, make new
  164. if not self._meta.issingle:
  165. if self.is_new():
  166. r = self._insert(make_autoname=make_autoname, keep_timestamps = keep_timestamps)
  167. if r:
  168. return r
  169. else:
  170. if not webnotes.conn.exists(self.doctype, self.name):
  171. webnotes.msgprint(webnotes._("Cannot update a non-exiting record, try inserting.") + ": " + self.doctype + " / " + self.name,
  172. raise_exception=1)
  173. # save the values
  174. self._update_values(self._meta.issingle,
  175. check_links and self.make_link_list() or {}, ignore_fields=ignore_fields,
  176. keep_timestamps=keep_timestamps)
  177. self._clear_temp_fields()
  178. def _get_amended_name(self):
  179. am_id = 1
  180. am_prefix = self.amended_from
  181. if webnotes.conn.sql('select amended_from from `tab%s` where name = "%s"' % (self.doctype, self.amended_from))[0][0] or '':
  182. am_id = cint(self.amended_from.split('-')[-1]) + 1
  183. am_prefix = '-'.join(self.amended_from.split('-')[:-1]) # except the last hyphen
  184. self.name = am_prefix + '-' + str(am_id)
  185. def set_new_name(self, controller=None):
  186. if self._new_name_set:
  187. # already set by bean
  188. return
  189. self._new_name_set = True
  190. self.get_meta()
  191. autoname = self._meta.autoname
  192. self.localname = self.name
  193. # amendments
  194. if self.amended_from:
  195. return self._get_amended_name()
  196. # by method
  197. else:
  198. # get my object
  199. if not controller:
  200. controller = webnotes.get_obj([self])
  201. if hasattr(controller, 'autoname'):
  202. return controller.autoname()
  203. # based on a field
  204. if autoname and autoname.startswith('field:'):
  205. n = self.fields[autoname[6:]]
  206. if not n:
  207. raise Exception, 'Name is required'
  208. self.name = n.strip()
  209. elif autoname and autoname.startswith("naming_series:"):
  210. self.set_naming_series()
  211. if not self.naming_series:
  212. webnotes.msgprint(webnotes._("Naming Series mandatory"), raise_exception=True)
  213. self.name = make_autoname(self.naming_series+'.#####')
  214. # call the method!
  215. elif autoname and autoname!='Prompt':
  216. self.name = make_autoname(autoname, self.doctype)
  217. # given
  218. elif self.fields.get('__newname',''):
  219. self.name = self.fields['__newname']
  220. # default name for table
  221. elif self._meta.istable:
  222. self.name = make_autoname('#########', self.doctype)
  223. # unable to determine a name, use global series
  224. if not self.name:
  225. self.name = make_autoname('#########', self.doctype)
  226. def set_naming_series(self):
  227. if not self.naming_series:
  228. # pick default naming series
  229. self.naming_series = get_default_naming_series(self.doctype)
  230. def _insert(self, make_autoname=True, keep_timestamps=False):
  231. # set name
  232. if make_autoname:
  233. self.set_new_name()
  234. # validate name
  235. self.name = validate_name(self.doctype, self.name, self._meta.name_case)
  236. # insert!
  237. if not keep_timestamps:
  238. if not self.owner:
  239. self.owner = webnotes.session['user']
  240. self.modified_by = webnotes.session['user']
  241. if not self.creation:
  242. self.creation = self.modified = now()
  243. else:
  244. self.modified = now()
  245. webnotes.conn.sql("insert into `tab%(doctype)s`" % self.fields \
  246. + """ (name, owner, creation, modified, modified_by)
  247. values (%(name)s, %(owner)s, %(creation)s, %(modified)s,
  248. %(modified_by)s)""", self.fields)
  249. def _update_single(self, link_list):
  250. self.modified = now()
  251. update_str, values = [], []
  252. webnotes.conn.sql("delete from tabSingles where doctype='%s'" % self.doctype)
  253. for f in self.fields.keys():
  254. if not (f in ('modified', 'doctype', 'name', 'perm', 'localname', 'creation'))\
  255. and (not f.startswith('__')): # fields not saved
  256. # validate links
  257. if link_list and link_list.get(f):
  258. self.fields[f] = self._validate_link(link_list, f)
  259. if self.fields[f]==None:
  260. update_str.append("(%s,%s,NULL)")
  261. values.append(self.doctype)
  262. values.append(f)
  263. else:
  264. update_str.append("(%s,%s,%s)")
  265. values.append(self.doctype)
  266. values.append(f)
  267. values.append(self.fields[f])
  268. webnotes.conn.sql("insert into tabSingles(doctype, field, value) values %s" % (', '.join(update_str)), values)
  269. def validate_links(self, link_list):
  270. err_list = []
  271. for f in self.fields.keys():
  272. # validate links
  273. old_val = self.fields[f]
  274. if link_list and link_list.get(f):
  275. self.fields[f] = self._validate_link(link_list, f)
  276. if old_val and not self.fields[f]:
  277. err_list.append("{}: {}".format(link_list[f][1], old_val))
  278. return err_list
  279. def make_link_list(self):
  280. res = webnotes.model.meta.get_link_fields(self.doctype)
  281. link_list = {}
  282. for i in res: link_list[i[0]] = (i[1], i[2]) # options, label
  283. return link_list
  284. def _validate_link(self, link_list, f):
  285. dt = link_list[f][0]
  286. dn = self.fields.get(f)
  287. if not dt:
  288. webnotes.throw("Options not set for link field: " + f)
  289. if not dt: return dn
  290. if not dn: return None
  291. if dt=="[Select]": return dn
  292. if dt.lower().startswith('link:'):
  293. dt = dt[5:]
  294. if '\n' in dt:
  295. dt = dt.split('\n')[0]
  296. tmp = webnotes.conn.sql("""SELECT name FROM `tab%s`
  297. WHERE name = %s""" % (dt, '%s'), (dn,))
  298. return tmp and tmp[0][0] or ''# match case
  299. def _update_values(self, issingle, link_list, ignore_fields=0, keep_timestamps=False):
  300. if issingle:
  301. self._update_single(link_list)
  302. else:
  303. update_str, values = [], []
  304. # set modified timestamp
  305. if self.modified and not keep_timestamps:
  306. self.modified = now()
  307. self.modified_by = webnotes.session['user']
  308. fields_list = ignore_fields and self.get_valid_fields() or self.fields.keys()
  309. for f in fields_list:
  310. if (not (f in ('doctype', 'name', 'perm', 'localname',
  311. 'creation','_user_tags', "file_list", "_comments"))) and (not f.startswith('__')):
  312. # fields not saved
  313. # validate links
  314. if link_list and link_list.get(f):
  315. self.fields[f] = self._validate_link(link_list, f)
  316. if self.fields.get(f) is None or self.fields.get(f)=='':
  317. update_str.append("`%s`=NULL" % f)
  318. else:
  319. values.append(self.fields.get(f))
  320. update_str.append("`%s`=%s" % (f, '%s'))
  321. if values:
  322. values.append(self.name)
  323. r = webnotes.conn.sql("update `tab%s` set %s where name=%s" % \
  324. (self.doctype, ', '.join(update_str), "%s"), values)
  325. def get_valid_fields(self):
  326. import webnotes.model.doctype
  327. if getattr(webnotes.local, "valid_fields_map", None) is None:
  328. webnotes.local.valid_fields_map = {}
  329. self.get_meta()
  330. valid_fields_map = webnotes.local.valid_fields_map
  331. if not valid_fields_map.get(self.doctype):
  332. if cint( self._meta.issingle):
  333. doctypelist = webnotes.model.doctype.get(self.doctype)
  334. valid_fields_map[self.doctype] = doctypelist.get_fieldnames({
  335. "fieldtype": ["not in", webnotes.model.no_value_fields]})
  336. else:
  337. valid_fields_map[self.doctype] = \
  338. webnotes.conn.get_table_columns(self.doctype)
  339. return valid_fields_map.get(self.doctype)
  340. def get_meta(self):
  341. if not self._meta:
  342. self._meta = webnotes.conn.get_value("DocType", self.doctype, ["autoname", "issingle",
  343. "istable", "name_case"], as_dict=True) or webnotes._dict()
  344. return self._meta
  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. return d
  406. def get_values(self):
  407. """get non-null fields dict withouth standard fields"""
  408. from webnotes.model import default_fields
  409. ret = {}
  410. for key in self.fields:
  411. if key not in default_fields and self.fields[key]:
  412. ret[key] = self.fields[key]
  413. return ret
  414. def addchild(parent, fieldname, childtype = '', doclist=None):
  415. """
  416. Create a child record to the parent doc.
  417. Example::
  418. c = Document('Contact','ABC')
  419. d = addchild(c, 'contact_updates', 'Contact Update')
  420. d.last_updated = 'Phone call'
  421. d.save(1)
  422. """
  423. return parent.addchild(fieldname, childtype, doclist)
  424. def make_autoname(key, doctype=''):
  425. """
  426. Creates an autoname from the given key:
  427. **Autoname rules:**
  428. * The key is separated by '.'
  429. * '####' represents a series. The string before this part becomes the prefix:
  430. Example: ABC.#### creates a series ABC0001, ABC0002 etc
  431. * 'MM' represents the current month
  432. * 'YY' and 'YYYY' represent the current year
  433. *Example:*
  434. * DE/./.YY./.MM./.##### will create a series like
  435. DE/09/01/0001 where 09 is the year, 01 is the month and 0001 is the series
  436. """
  437. if not "#" in key:
  438. key = key + ".#####"
  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. current = webnotes.conn.sql("select `current` from `tabSeries` where name=%s for update", (key,))
  464. if current and current[0][0] is not None:
  465. current = current[0][0]
  466. # yes, update it
  467. webnotes.conn.sql("update tabSeries set current = current+1 where name=%s", (key,))
  468. current = cint(current) + 1
  469. else:
  470. # no, create it
  471. webnotes.conn.sql("insert into tabSeries (name, current) values (%s, 1)", (key,))
  472. current = 1
  473. return ('%0'+str(digits)+'d') % current
  474. def getchildren(name, childtype, field='', parenttype='', from_doctype=0):
  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 `tab%s` where parent=%s %s order by idx""" \
  486. % (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):
  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)
  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)
  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
  554. def get_default_naming_series(doctype):
  555. """get default value for `naming_series` property"""
  556. from webnotes.model.doctype import get_property
  557. naming_series = get_property(doctype, "options", "naming_series")
  558. if naming_series:
  559. naming_series = naming_series.split("\n")
  560. return naming_series[0] or naming_series[1]
  561. else:
  562. return None