builder.rb 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. class CustomWizard::Builder
  2. attr_accessor :wizard, :updater, :submissions
  3. def initialize(user, wizard_id)
  4. data = PluginStore.get('custom_wizard', wizard_id)
  5. return if data.blank?
  6. @steps = data['steps']
  7. @wizard = CustomWizard::Wizard.new(user, data)
  8. @submissions = Array.wrap(PluginStore.get("#{wizard_id}_submissions", user.id))
  9. end
  10. def self.sorted_handlers
  11. @sorted_handlers ||= []
  12. end
  13. def self.step_handlers
  14. sorted_handlers.map { |h| { wizard_id: h[:wizard_id], block: h[:block] } }
  15. end
  16. def self.add_step_handler(priority = 0, wizard_id, &block)
  17. sorted_handlers << { priority: priority, wizard_id: wizard_id, block: block }
  18. @sorted_handlers.sort_by! { |h| -h[:priority] }
  19. end
  20. USER_FIELDS = ['name', 'username', 'email', 'date_of_birth', 'title', 'locale']
  21. PROFILE_FIELDS = ['location', 'website', 'bio_raw', 'profile_background', 'card_background']
  22. def self.fill_placeholders(string, user, data)
  23. result = string.gsub(/u\{(.*?)\}/) do |match|
  24. result = ''
  25. result = user.send($1) if USER_FIELDS.include?($1)
  26. result = user.user_profile.send($1) if PROFILE_FIELDS.include?($1)
  27. result
  28. end
  29. result.gsub!(/w\{(.*?)\}/) { |match| data[$1.to_sym] }
  30. end
  31. def build
  32. unless (@wizard.completed? && !@wizard.multiple_submissions && !@wizard.user.admin) || !@steps || !@wizard.permitted?
  33. @steps.each do |step_template|
  34. @wizard.append_step(step_template['id']) do |step|
  35. step.title = step_template['title'] if step_template['title']
  36. step.description = step_template['description'] if step_template['description']
  37. step.banner = step_template['banner'] if step_template['banner']
  38. step.key = step_template['key'] if step_template['key']
  39. if step_template['fields'] && step_template['fields'].length
  40. step_template['fields'].each do |field_template|
  41. append_field(step, step_template, field_template)
  42. end
  43. end
  44. step.on_update do |updater|
  45. @updater = updater
  46. user = @wizard.user
  47. if step_template['fields'] && step_template['fields'].length
  48. step_template['fields'].each do |field|
  49. validate_field(field, updater) if field['type'] != 'text-only'
  50. end
  51. end
  52. next if updater.errors.any?
  53. CustomWizard::Builder.step_handlers.each do |handler|
  54. if handler[:wizard_id] == @wizard.id
  55. handler[:block].call(self)
  56. end
  57. end
  58. next if updater.errors.any?
  59. data = updater.fields.to_h
  60. ## if the wizard has data from the previous steps make that accessible to the actions.
  61. if @submissions && @submissions.last && !@submissions.last.key?("submitted_at")
  62. submission = @submissions.last
  63. data = submission.merge(data)
  64. end
  65. if step_template['actions'] && step_template['actions'].length && data
  66. step_template['actions'].each do |action|
  67. self.send(action['type'].to_sym, user, action, data)
  68. end
  69. end
  70. final_step = updater.step.next.nil?
  71. if @wizard.save_submissions && updater.errors.empty?
  72. save_submissions(data, final_step)
  73. elsif final_step
  74. PluginStore.remove("#{@wizard.id}_submissions", @wizard.user.id)
  75. end
  76. if final_step && @wizard.id === @wizard.user.custom_fields['redirect_to_wizard']
  77. @wizard.user.custom_fields.delete('redirect_to_wizard');
  78. @wizard.user.save_custom_fields(true)
  79. end
  80. if updater.errors.empty?
  81. redirect_to = data['redirect_to']
  82. updater.result = { redirect_to: redirect_to } if redirect_to
  83. end
  84. end
  85. end
  86. end
  87. end
  88. @wizard
  89. end
  90. def append_field(step, step_template, field_template)
  91. params = {
  92. id: field_template['id'],
  93. type: field_template['type'],
  94. required: field_template['required']
  95. }
  96. params[:label] = field_template['label'] if field_template['label']
  97. params[:description] = field_template['description'] if field_template['description']
  98. params[:image] = field_template['image'] if field_template['image']
  99. params[:key] = field_template['key'] if field_template['key']
  100. ## Load previously submitted values
  101. if @submissions.last && !@submissions.last.key?("submitted_at")
  102. submission = @submissions.last
  103. params[:value] = submission[field_template['id']] if submission[field_template['id']]
  104. end
  105. ## If a field updates a profile field, load the current value
  106. if step_template['actions'] && step_template['actions'].any?
  107. profile_actions = step_template['actions'].select { |a| a['type'] === 'update_profile' }
  108. if profile_actions.any?
  109. profile_actions.each do |action|
  110. if update = action['profile_updates'].select { |u| u['key'] === field_template['id'] }.first
  111. params[:value] = prefill_profile_field(update)
  112. end
  113. end
  114. end
  115. end
  116. if field_template['type'] === 'checkbox'
  117. params[:value] = standardise_boolean(params[:value])
  118. end
  119. field = step.add_field(params)
  120. if field_template['type'] === 'dropdown'
  121. build_dropdown_list(field, field_template)
  122. end
  123. end
  124. def prefill_profile_field(update)
  125. attribute = update['value']
  126. custom_field = update['value_custom']
  127. user_field = update['user_field']
  128. if user_field || custom_field
  129. UserCustomField.where(user_id: @wizard.user.id, name: user_field || custom_field).pluck(:value)
  130. elsif UserProfile.column_names.include? attribute
  131. UserProfile.find_by(user_id: @wizard.user.id).send(attribute)
  132. elsif User.column_names.include? attribute
  133. User.find(@wizard.user.id).send(attribute)
  134. end
  135. end
  136. def build_dropdown_list(field, field_template)
  137. field.dropdown_none = field_template['dropdown_none'] if field_template['dropdown_none']
  138. if field_template['choices'] && field_template['choices'].length > 0
  139. field_template['choices'].each do |c|
  140. field.add_choice(c['key'], label: c['value'])
  141. end
  142. elsif field_template['choices_key'] && field_template['choices_key'].length > 0
  143. choices = I18n.t(field_template['choices_key'])
  144. if choices.is_a?(Hash)
  145. choices.each { |k, v| field.add_choice(k, label: v) }
  146. end
  147. elsif field_template['choices_preset'] && field_template['choices_preset'].length > 0
  148. objects = []
  149. if field_template['choices_preset'] === 'categories'
  150. objects = Site.new(Guardian.new(@wizard.user)).categories
  151. end
  152. if field_template['choices_filters'] && field_template['choices_filters'].length > 0
  153. field_template['choices_filters'].each do |f|
  154. objects.reject! do |o|
  155. if f['key'].include? 'custom_fields'
  156. o.custom_fields[f['key'].split('.')[1]].to_s != f['value'].to_s
  157. else
  158. o[prop].to_s != f['value'].to_s
  159. end
  160. end
  161. end
  162. end
  163. if objects.length > 0
  164. objects.each do |o|
  165. field.add_choice(o.id, label: o.name)
  166. end
  167. end
  168. end
  169. end
  170. def validate_field(field, updater)
  171. value = updater.fields[field['id']]
  172. min_length = field['min_length']
  173. if min_length && value.is_a?(String) && value.length < min_length.to_i
  174. label = field['label'] || I18n.t("#{field['key']}.label")
  175. updater.errors.add(field['id'].to_s, I18n.t('wizard.field.too_short', label: label, min: min_length.to_i))
  176. end
  177. ## ensure all checkboxes are booleans
  178. if field['type'] === 'checkbox'
  179. updater.fields[field['id']] = standardise_boolean(value)
  180. end
  181. end
  182. def standardise_boolean(value)
  183. !!HasCustomFields::Helpers::CUSTOM_FIELD_TRUE.include?(value)
  184. end
  185. def create_topic(user, action, data)
  186. if action['custom_title']
  187. title = action['custom_title']
  188. else
  189. title = data[action['title']]
  190. end
  191. if action['post_builder']
  192. post = CustomWizard::Builder.fill_placeholders(action['post_template'], user, data)
  193. else
  194. post = data[action['post']]
  195. end
  196. if title
  197. params = {
  198. title: title,
  199. raw: post,
  200. skip_validations: true
  201. }
  202. if action['custom_category_enabled'] &&
  203. !action['custom_category_wizard_field'] &&
  204. action['custom_category_user_field_key']
  205. if action['custom_category_user_field_key'].include?('custom_fields')
  206. field = action['custom_category_user_field_key'].split('.').last
  207. category_id = user.custom_fields[field]
  208. else
  209. category_id = user.send(action['custom_category_user_field_key'])
  210. end
  211. else
  212. category_id = action['category_id']
  213. end
  214. params[:category] = category_id
  215. topic_custom_fields = {}
  216. if action['add_fields']
  217. action['add_fields'].each do |field|
  218. value = field['value_custom'] ? field['value_custom'] : data[field['value']]
  219. key = field['key']
  220. if key && (value.present? || value === false)
  221. if key.include?('custom_fields')
  222. keyArr = key.split('.')
  223. if keyArr.length === 3
  224. custom_key = keyArr.last
  225. type = keyArr.first
  226. if type === 'topic'
  227. topic_custom_fields[custom_key] = value
  228. elsif type === 'post'
  229. params[:custom_fields] ||= {}
  230. params[:custom_fields][custom_key.to_sym] = value
  231. end
  232. end
  233. else
  234. params[key.to_sym] = value
  235. end
  236. end
  237. end
  238. end
  239. creator = PostCreator.new(user, params)
  240. post = creator.create
  241. if creator.errors.present?
  242. updater.errors.add(:create_topic, creator.errors.full_messages.join(" "))
  243. else
  244. if topic_custom_fields.present?
  245. topic_custom_fields.each do |k, v|
  246. post.topic.custom_fields[k] = v
  247. end
  248. post.topic.save_custom_fields(true)
  249. end
  250. data['redirect_to'] = post.topic.url
  251. end
  252. end
  253. end
  254. def send_message(user, action, data)
  255. title = data[action['title']]
  256. if action['post_builder']
  257. post = CustomWizard::Builder.fill_placeholders(action['post_template'], user, data)
  258. else
  259. post = data[action['post']]
  260. end
  261. if title && post
  262. creator = PostCreator.new(user,
  263. title: title,
  264. raw: post,
  265. archetype: Archetype.private_message,
  266. target_usernames: action['username']
  267. )
  268. post = creator.create
  269. if creator.errors.present?
  270. updater.errors.add(:send_message, creator.errors.full_messages.join(" "))
  271. else
  272. data['redirect_to'] = post.topic.url
  273. end
  274. end
  275. end
  276. def update_profile(user, action, data)
  277. return unless action['profile_updates'].length
  278. attributes = {}
  279. custom_fields = {}
  280. action['profile_updates'].each do |pu|
  281. value = pu['value']
  282. custom_field = pu['value_custom']
  283. user_field = pu['user_field']
  284. key = pu['key']
  285. if user_field || custom_field
  286. custom_fields[user_field || custom_field] = data[key]
  287. else
  288. attributes[value.to_sym] = data[key]
  289. end
  290. end
  291. if custom_fields.present?
  292. attributes[:custom_fields] = custom_fields
  293. end
  294. if attributes.present?
  295. user_updater = UserUpdater.new(user, user)
  296. user_updater.update(attributes)
  297. end
  298. end
  299. def save_submissions(data, final_step)
  300. if final_step
  301. data['submitted_at'] = Time.now.iso8601
  302. end
  303. if data.present?
  304. @submissions.pop(1) if @wizard.unfinished?
  305. @submissions.push(data)
  306. PluginStore.set("#{@wizard.id}_submissions", @wizard.user.id, @submissions)
  307. end
  308. end
  309. end