builder.rb 12 KB

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