Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 
 
 

181 rinda
6.5 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. # Search
  23. from __future__ import unicode_literals
  24. import webnotes
  25. import webnotes.widgets.query_builder
  26. from webnotes.utils import cstr
  27. from startup.query_handlers import standard_queries
  28. # this is called when a new doctype is setup for search - to set the filters
  29. @webnotes.whitelist()
  30. def getsearchfields():
  31. sf = webnotes.conn.sql("""\
  32. SELECT value FROM `tabProperty Setter`
  33. WHERE doc_type=%s AND property='search_fields'""", \
  34. (webnotes.form_dict.get("doctype")))
  35. if not (sf and len(sf)>0 and sf[0][0]):
  36. sf = webnotes.conn.sql("select search_fields from tabDocType where name=%s", webnotes.form_dict.get("doctype"))
  37. sf = sf and sf[0][0] or ''
  38. sf = [s.strip() for s in sf.split(',')]
  39. if sf and sf[0]:
  40. res = webnotes.conn.sql("select fieldname, label, fieldtype, options from tabDocField where parent='%s' and fieldname in (%s)" % (webnotes.form_dict.get("doctype","_NA"), '"'+'","'.join(sf)+'"'))
  41. else:
  42. res = []
  43. res = [[c or '' for c in r] for r in res]
  44. for r in res:
  45. if r[2]=='Select' and r[3] and r[3].startswith('link:'):
  46. dt = r[3][5:]
  47. ol = webnotes.conn.sql("select name from `tab%s` where docstatus!=2 order by name asc" % dt)
  48. r[3] = '\n'.join([''] + [o[0] for o in ol])
  49. webnotes.response['searchfields'] = [['name', 'ID', 'Data', '']] + res
  50. # this is called by the Link Field
  51. @webnotes.whitelist()
  52. def search_link(dt, txt, query=None, filters=None):
  53. search_widget(dt, txt, query, page_len=10, filters=filters)
  54. webnotes.response['results'] = build_for_autosuggest(webnotes.response["values"])
  55. # this is called by the search box
  56. @webnotes.whitelist()
  57. def search_widget(doctype, txt, query=None, searchfield="name", start=0, page_len=50, filters=None):
  58. if isinstance(filters, basestring):
  59. import json
  60. filters = json.loads(filters)
  61. if query and query.split()[0].lower()!="select":
  62. webnotes.response["values"] = webnotes.get_method(query)(doctype, txt,
  63. searchfield, start, page_len, filters)
  64. elif not query and doctype in standard_queries:
  65. search_widget(doctype, txt, standard_queries[doctype],
  66. searchfield, start, page_len, filters)
  67. else:
  68. if query:
  69. webnotes.response["values"] = webnotes.conn.sql(scrub_custom_query(query,
  70. searchfield, txt))
  71. else:
  72. if filters:
  73. webnotes.response["values"] = get_query_result(
  74. ', '.join(get_std_fields_list(doctype, searchfield)), doctype, txt,
  75. searchfield, start, page_len, filters)
  76. else:
  77. query = make_query(', '.join(get_std_fields_list(doctype, searchfield)), doctype,
  78. searchfield, txt, start, page_len)
  79. webnotes.widgets.query_builder.runquery(query)
  80. def make_query(fields, dt, key, txt, start, length):
  81. doctype = webnotes.get_doctype(dt)
  82. enabled_condition = ""
  83. if doctype.get({"parent":dt, "fieldname":"enabled", "fieldtype":"Check"}):
  84. enabled_condition = " AND ifnull(`tab%s`.`enabled`,0)=1" % dt
  85. if doctype.get({"parent":dt, "fieldname":"disabled", "fieldtype":"Check"}):
  86. enabled_condition = " AND ifnull(`tab%s`.`disabled`,0)!=1" % dt
  87. query = """select %(fields)s
  88. FROM `tab%(dt)s`
  89. WHERE `tab%(dt)s`.`%(key)s` LIKE '%(txt)s'
  90. AND `tab%(dt)s`.docstatus != 2 %(enabled_condition)s
  91. ORDER BY `tab%(dt)s`.`%(key)s`
  92. ASC LIMIT %(start)s, %(len)s """ % {
  93. 'fields': fields,
  94. 'dt': dt,
  95. 'key': key,
  96. 'txt': txt + '%',
  97. 'start': start,
  98. 'len': length,
  99. 'enabled_condition': enabled_condition,
  100. }
  101. return query
  102. def get_query_result(fields, dt, txt, searchfield, start, page_len, filters):
  103. doctype = webnotes.get_doctype(dt)
  104. enabled_condition = ""
  105. if doctype.get({"parent":dt, "fieldname":"enabled", "fieldtype":"Check"}):
  106. enabled_condition = " AND ifnull(`enabled`,0)=1 "
  107. if doctype.get({"parent":dt, "fieldname":"disabled", "fieldtype":"Check"}):
  108. enabled_condition = " AND ifnull(`disabled`,0)!=1"
  109. filter_condition, filter_values = build_filter_conditions(filters)
  110. args = {
  111. 'fields': fields,
  112. 'dt': dt,
  113. 'key': searchfield,
  114. 'txt': '%s',
  115. 'start': start,
  116. 'len': page_len,
  117. 'enabled_condition': enabled_condition,
  118. 'filter_condition': filter_condition
  119. }
  120. return webnotes.conn.sql("""select %(fields)s FROM `tab%(dt)s`
  121. WHERE `%(key)s` LIKE %(txt)s
  122. AND docstatus != 2 %(enabled_condition)s %(filter_condition)s
  123. ORDER BY `%(key)s`
  124. ASC LIMIT %(start)s, %(len)s""" % args,
  125. tuple(["%%%s%%" % txt] + filter_values))
  126. def build_filter_conditions(filters):
  127. conditions, filter_values = [], []
  128. for key in filters:
  129. conditions.append('`' + key + '` = %s')
  130. filter_values.append(filters[key])
  131. conditions = conditions and " and " + " and ".join(conditions) or ""
  132. return conditions, filter_values
  133. def get_std_fields_list(dt, key):
  134. # get additional search fields
  135. sflist = webnotes.conn.sql("select search_fields from tabDocType where name = '%s'" % dt)
  136. sflist = sflist and sflist[0][0] and sflist[0][0].split(',') or []
  137. sflist = ['name'] + sflist
  138. if not key in sflist:
  139. sflist = sflist + [key]
  140. return ['`tab%s`.`%s`' % (dt, f.strip()) for f in sflist]
  141. def build_for_autosuggest(res):
  142. results = []
  143. for r in res:
  144. info = ''
  145. if len(r) > 1:
  146. info = ', '.join([cstr(t) for t in r[1:]])
  147. if len(info) > 50:
  148. info = "<span title=\"%s\">%s...</span>" % (info, info[:50])
  149. results.append({'label':r[0], 'value':r[0], 'info':info})
  150. return results
  151. def scrub_custom_query(query, key, txt):
  152. if '%(key)s' in query:
  153. query = query.replace('%(key)s', key)
  154. if '%s' in query:
  155. query = query.replace('%s', ((txt or '') + '%'))
  156. return query