builder.rb 12 KB

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