Class: JindaController

Inherits:
ApplicationController show all
Defined in:
lib/generators/jinda/templates/app/controllers/jinda_controller.rb

Instance Method Summary collapse

Methods inherited from ApplicationController

#prepare_meta_tags

Instance Method Details

#ajax_noticeObject



27
28
29
30
31
32
33
34
35
# File 'lib/generators/jinda/templates/app/controllers/jinda_controller.rb', line 27

def ajax_notice
  if notice=Jinda::Notice.recent(current_ma_user, request.env["REMOTE_ADDR"])
    notice.update_attribute :unread, false
    js = "notice('#{notice.message}');"
  else
    js = ""
  end
  render plain: "<script>#{js}</script>"
end

#cancelObject



15
16
17
18
19
20
21
22
# File 'lib/generators/jinda/templates/app/controllers/jinda_controller.rb', line 15

def cancel
  Jinda::Xmain.find(params[:id]).update_attributes :status=>'X'
  if params[:return]
    redirect_to params[:return]
  else
    redirect_to action:"pending"
  end
end

#clear_xmainsObject



23
24
25
26
# File 'lib/generators/jinda/templates/app/controllers/jinda_controller.rb', line 23

def clear_xmains
  Jinda::Xmain.where(:status =>{'$in'=>['R','I']}).update_all(:status=>'X')
  redirect_to action:"pending"
end

#docObject

generate documentation for application



352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
# File 'lib/generators/jinda/templates/app/controllers/jinda_controller.rb', line 352

def doc
  require 'rdoc'
  @app= get_app
  @intro = File.read('README.md')
  @print= "<div align='right'><img src='/assets/printer.png'/> <a href='/jinda/doc_print' target='_blank'/>Print</a></div>"
  doc= render_to_string 'doc.md', :layout => false
  html= Maruku.new(doc).to_html
  File.open('public/doc.html','w') {|f| f.puts html }
  respond_to do |format|
    format.html {
      render :plain=> @print+html, :layout => 'layouts/jqm/_page'
      # render :text=> Maruku.new(doc).to_html, :layout => false
      # format.html {
      #   h = RDoc::Markup::ToHtml.new
      #   render :text=> h.convert(doc), :layout => 'layouts/_page'
    }
    format.pdf  {
      latex= Maruku.new(doc).to_latex
      File.open('tmp/doc.md','w') {|f| f.puts doc}
      File.open('tmp/doc.tex','w') {|f| f.puts latex}
      # system('pdflatex tmp/doc.tex ')
      # send_file( 'tmp/doc.pdf', :type => ‘application/pdf’,
      # :disposition => ‘inline’, :filename => 'doc.pdf')
      render :plain=>'done'
    }
  end
end

#doc_printObject



348
349
350
# File 'lib/generators/jinda/templates/app/controllers/jinda_controller.rb', line 348

def doc_print
  render :file=>'public/doc.html', :layout=>'layouts/print'
end

#documentObject

handle uploaded image



380
381
382
383
384
385
386
387
388
389
390
391
392
# File 'lib/generators/jinda/templates/app/controllers/jinda_controller.rb', line 380

def document
  doc = Jinda::Doc.find params[:id]
  if doc.cloudinary
    require 'net/http'
    require "uri"
    uri = URI.parse(doc.url)
    data = Net::HTTP.get_response(uri)
    send_data(data.body, :filename=>doc.filename, :type=>doc.content_type, :disposition=>"inline")
  else
    data= read_binary(doc.url)
    send_data(data, :filename=>doc.filename, :type=>doc.content_type, :disposition=>"inline")
  end
end

#end_action(next_runseq = nil) ⇒ Object



275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
# File 'lib/generators/jinda/templates/app/controllers/jinda_controller.rb', line 275

def end_action(next_runseq = nil)
  #    @runseq.status='F' unless @runseq_not_f
  @xmain.xvars= @xvars
  @xmain.status= 'R' # running
  @xmain.save!
  @runseq.status='F'
  @runseq.user= current_ma_user
  @runseq.stop= Time.now
  @runseq.save
  next_runseq= @xmain.runseqs.where(:rstep=> @runseq.rstep+1).first unless next_runseq
  if @end_job || !next_runseq # job finish
    @xmain.xvars= @xvars
    @xmain.status= 'F' unless @xmain.status== 'E' # finish
    @xmain.stop= Time.now
    @xmain.save
    if @xvars['p']['return']
      redirect_to @xvars['p']['return'] and return
    else
      if @user
        redirect_to :action=>'index' and return
      else
        redirect_to_root and return
      end
    end
  else
    @xmain.update_attribute :current_runseq, next_runseq.id
    redirect_to :action=>'run', :id=>@xmain.id and return
  end
end

#end_formObject



247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
# File 'lib/generators/jinda/templates/app/controllers/jinda_controller.rb', line 247

def end_form
  init_vars(params[:xmain_id])
  eval "@xvars[@runseq.code] = {} unless @xvars[@runseq.code]"
# Search for uploaded file name if exist
  params.each { |k,v|
    if params[k].respond_to? :original_filename
      get_image(k, params[k])
  # check if params of array in form eg: edit_article  
    elsif params[k].is_a?(ActionController::Parameters)
      params[k].each { |k1,v1|
      # eval "@xvars[@runseq.code][k1] = params.require(k1).permit(k1)"
      eval "@xvars[@runseq.code][k1] = v1" 
      next unless v1.respond_to?(:original_filename)
        get_image1(k, k1, params[k][k1])
      }
    else
    # bug in to_unsalfe_h rails 5.1.6 https://github.com/getsentry/raven-ruby/issues/799
    # Solution:
    # https://stackoverflow.com/questions/34949505/rails-5-unable-to-retrieve-hash-values-from-parameter
    # v = v.to_unsafe_h unless v.class == String
    # v = params.require[k] unless v.class == String
      v = v.to_s unless v.class == String
      eval "@xvars[@runseq.code][k] = v"
    end
  }
  end_action
end

#end_outputObject



215
216
217
218
# File 'lib/generators/jinda/templates/app/controllers/jinda_controller.rb', line 215

def end_output
  init_vars(params[:xmain_id])
  end_action
end

#err404Object



418
419
420
421
422
423
# File 'lib/generators/jinda/templates/app/controllers/jinda_controller.rb', line 418

def err404
  # ma_log 'ERROR', 'main/err404'
  flash[:notice] = "We're sorry, but something went wrong. We've been notified about this issue and we'll take a look at it shortly."
  ma_log "We're sorry, but something went wrong. We've been notified about this issue and we'll take a look at it shortly."
  redirect_to '/'
end

#err500Object



424
425
426
427
428
429
# File 'lib/generators/jinda/templates/app/controllers/jinda_controller.rb', line 424

def err500
  # ma_log 'ERROR', 'main/err500'
  flash[:notice] = "We're sorry, but something went wrong. We've been notified about this issue and we'll take a look at it shortly."
  ma_log "We're sorry, but something went wrong. We've been notified about this issue and we'll take a look at it shortly."
  redirect_to '/'
end

#error_logsObject



8
9
10
# File 'lib/generators/jinda/templates/app/controllers/jinda_controller.rb', line 8

def error_logs
  @xmains = Jinda::Xmain.in(status:['E']).desc(:created_at).page(params[:page]).per(10)
end

#get_image(key, params) ⇒ Object

process images from first level



305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
# File 'lib/generators/jinda/templates/app/controllers/jinda_controller.rb', line 305

def get_image(key, params)
  doc = Jinda::Doc.create(
      :name=> key.to_s,
      :xmain=> @xmain.id,
      :runseq=> @runseq.id,
      :filename=> params.original_filename,
      :content_type => params.content_type || 'application/zip',
      :data_text=> '',
      :ma_display=>true,
      :ma_secured => @xmain.service.ma_secured )
  if defined?(IMAGE_LOCATION)
    filename = "#{IMAGE_LOCATION}/f#{Param.gen(:asset_id)}"
    File.open(filename,"wb") { |f| f.write(params.read) }
    # File.open(filename,"wb") { |f| f.puts(params.read) }
    eval "@xvars[@runseq.code][key] = '#{url_for(:action=>'document', :id=>doc.id, :only_path => true )}' "
    doc.update_attributes :url => filename, :basename => File.basename(filename), :cloudinary => false
  else
    result = Cloudinary::Uploader.upload(params)
    eval %Q{ @xvars[@runseq.code][key] = '#{result["url"]}' }
    doc.update_attributes :url => result["url"], :basename => File.basename(result["url"]), :cloudinary => true
  end
end

#get_image1(key, key1, params) ⇒ Object

process images from second level, e.g,, fields_for



328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
# File 'lib/generators/jinda/templates/app/controllers/jinda_controller.rb', line 328

def get_image1(key, key1, params)
  doc = Jinda::Doc.create(
      :name=> "#{key}_#{key1}",
      :xmain=> @xmain.id,
      :runseq=> @runseq.id,
      :filename=> params.original_filename,
      :content_type => params.content_type || 'application/zip',
      :data_text=> '',
      :ma_display=>true, :ma_secured => @xmain.service.ma_secured )
  if defined?(IMAGE_LOCATION)
    filename = "#{IMAGE_LOCATION}/f#{Param.gen(:asset_id)}"
    File.open(filename,"wb") { |f| f.write(params.read) }
    eval "@xvars[@runseq.code][key][key1] = '#{url_for(:action=>'document', :id=>doc.id, :only_path => true)}' "
    doc.update_attributes :url => filename, :basename => File.basename(filename), :cloudinary => false
  else
    result = Cloudinary::Uploader.upload(params)
    eval %Q{ @xvars[@runseq.code][key][key1] = '#{result["url"]}' }
    doc.update_attributes :url => result["url"], :basename => File.basename(result["url"]), :cloudinary => true
  end
end

#helpObject



404
405
# File 'lib/generators/jinda/templates/app/controllers/jinda_controller.rb', line 404

def help
end

#indexObject



3
4
# File 'lib/generators/jinda/templates/app/controllers/jinda_controller.rb', line 3

def index
end

#initObject

] prepare xmain.runseq eg: how many form_step or total_step and step properties check if authorized ] view menu by user selected what service (module and code) to run (not all services like menu did Its only one service



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/generators/jinda/templates/app/controllers/jinda_controller.rb', line 41

def init
  module_code, code = params[:s].split(":")
  @service= Jinda::Service.where(:module_code=> module_code, :code=> code).first
  # @service= Jinda::Service.where(:module_code=> params[:module], :code=> params[:service]).first
if @service && authorize_init?
    xmain = create_xmain(@service)
    result = create_runseq(xmain)
    unless result
      message = "cannot find action for xmain #{xmain.id}"
      ma_log(message)
      flash[:notice]= message
      redirect_to "pending" and return
    end
    xmain.update_attribute(:xvars, @xvars)
    xmain.runseqs.last.update_attribute(:end,true)
    #Above line cause error update_attribute in heroku shown in logs and it was proposed to fixed in github:'kul1/g241502'
    redirect_to :action=>'run', :id=>xmain.id
  else
    refresh_to "/", :alert => "Error: cannot process"
  end
end

#logsObject



5
6
7
# File 'lib/generators/jinda/templates/app/controllers/jinda_controller.rb', line 5

def logs
  @xmains = Jinda::Xmain.all.desc(:created_at).page(params[:page]).per(10)
end

#pendingObject



11
12
13
14
# File 'lib/generators/jinda/templates/app/controllers/jinda_controller.rb', line 11

def pending
  @title= "Pending Tasks"
  @xmains = Jinda::Xmain.in(status:['R','I']).asc(:created_at)
end

#runObject

]



67
68
69
70
71
72
73
74
75
# File 'lib/generators/jinda/templates/app/controllers/jinda_controller.rb', line 67

def run
  init_vars(params[:id])
  if authorize?
    # session[:full_layout]= false
    redirect_to(:action=>"run_#{@runseq.action}", :id=>@xmain.id)
  else
    redirect_to_root
  end
end

#run_doObject



134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
# File 'lib/generators/jinda/templates/app/controllers/jinda_controller.rb', line 134

def run_do
  init_vars(params[:id])
  @runseq.start ||= Time.now
  @runseq.status= 'R' # running
  $runseq_id= @runseq.id
  $user_id= current_ma_user.try(:id)
  set_global
  controller = Kernel.const_get(@xvars['custom_controller']).new
  result = controller.send(@runseq.code)
  init_vars_by_runseq($runseq_id)
  @xvars = $xvars
  @xvars[@runseq.code.to_sym]= result.to_s
  @xvars['current_step']= @runseq.rstep
  @runseq.status= 'F' #finish
  @runseq.stop= Time.now
  @runseq.save
  end_action
rescue => e
  @xmain.status='E'
  @xvars['error']= e.to_s+e.backtrace.to_s
  @xmain.xvars= $xvars
  @xmain.save
  @runseq.status= 'F' #finish
  @runseq.stop= Time.now
  @runseq.save
  refresh_to "/", :alert => "Sorry opeation error at  #{@xmain.id} #{@xvars['error']}"
end

#run_formObject



76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/generators/jinda/templates/app/controllers/jinda_controller.rb', line 76

def run_form
  init_vars(params[:id])
  if authorize?
    if ['F', 'X'].include? @xmain.status
      redirect_to_root
    else
      service= @xmain.service
    ###############################################################################################
    # Run View Form f created template by jinda rake follow freemind mm file
    ###############################################################################################
      if service
        @title= "Transaction ID #{@xmain.xid}: #{@xmain.name} / #{@runseq.name}"
        fhelp= "app/views/#{service.module.code}/#{service.code}/#{@runseq.code}.md"
        @help = File.read(fhelp) if File.exists?(fhelp)
        f= "app/views/#{service.module.code}/#{service.code}/#{@runseq.code}.html.erb"
        @ui= File.read(f)
      else
        # flash[:notice]= "Error: Can not find the view file for this controller"
        ma_log "Error: Can not find the view file for this controller"
        redirect_to_root
      end
    end
  else
    redirect_to_root
  end
end

#run_ifObject



102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/generators/jinda/templates/app/controllers/jinda_controller.rb', line 102

def run_if
  init_vars(params[:id])
  condition= eval(@runseq.code).to_s
  match_found= false
  if condition
    xml= REXML::Document.new(@runseq.xml).root
    next_runseq= nil
    text = xml.elements['//node/node'].attributes['TEXT']
    match, name= text.split(':',2)
    label= name2code(name.strip)
    if condition==match
      if label=="end"
        @end_job= true
      else
        next_runseq= @xmain.runseqs.where(:code=> label, :action.ne=>'redirect').first
        match_found= true if next_runseq
        @runseq_not_f= false
      end
    end
  end
  unless match_found || @end_job
    next_runseq= @xmain.runseqs.where( rstep:(@xvars['current_step']+1) ).first
  end
  end_action(next_runseq)
end

#run_mailObject



195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
# File 'lib/generators/jinda/templates/app/controllers/jinda_controller.rb', line 195

def run_mail
  init_vars(params[:id])
  service= @xmain.service
  f= "app/views/#{service.module.code}/#{service.code}/#{@runseq.code}.html.erb"
  @ui= File.read(f).html_safe
  @doc= Jinda::Doc.create :name=> @runseq.name,
                            :content_type=>"mail", :data_text=> render_to_string(:inline=>@ui, :layout=>false),
                            :xmain=>@xmain, :runseq=>@runseq, :user=>current_ma_user,
                            :ip=> get_ip, :service=>service, :ma_display=>false,
                            :ma_secured => @xmain.service.ma_secured
  eval "@xvars[:#{@runseq.code}] = url_for(:controller=>'jinda', :action=>'document', :id=>@doc.id)"
  mail_from = get_option('from')
  # sender= render_to_string(:inline=>mail_from) if mail_from
  mail_to = get_option('to')
  recipients= render_to_string(:inline=>mail_to) if mail_to
  mail_subject = get_option('subject')
  subject= render_to_string(:inline=>mail_subject) || "#{@runseq.name}"
  JindaMailer.gmail(@doc.data_text, recipients, subject).deliver unless DONT_SEND_MAIL
  end_action
end

#run_outputObject



161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
# File 'lib/generators/jinda/templates/app/controllers/jinda_controller.rb', line 161

def run_output
  init_vars(params[:id])
  service= @xmain.service
  disp= get_option("ma_display")
  ma_display = (disp && !affirm(disp)) ? false : true
  if service
    f= "app/views/#{service.module.code}/#{service.code}/#{@runseq.code}.html.erb"
    @ui= File.read(f)
    if Jinda::Doc.where(:runseq_id=>@runseq.id).exists?
      @doc= Jinda::Doc.where(:runseq_id=>@runseq.id).first
      @doc.update_attributes :data_text=> render_to_string(:inline=>@ui, :layout=>"utf8"),
                             :xmain=>@xmain, :runseq=>@runseq, :user=>current_ma_user,
                             :ip=> get_ip, :service=>service, :ma_display=>ma_display,
                             :ma_secured => @xmain.service.ma_secured
    else
      @doc= Jinda::Doc.create :name=> @runseq.name,
                                :content_type=>"output", :data_text=> render_to_string(:inline=>@ui, :layout=>"utf8"),
                                :xmain=>@xmain, :runseq=>@runseq, :user=>current_ma_user,
                                :ip=> get_ip, :service=>service, :ma_display=>ma_display,
                                :ma_secured => @xmain.service.ma_secured
    end
    @message = defined?(MSG_NEXT) ? MSG_NEXT : "Next &gt;"
    @message = "Finish" if @runseq.end
    eval "@xvars[@runseq.code] = url_for(:controller=>'Jinda', :action=>'document', :id=>@doc.id)"
  else
    # flash[:notice]= "Error: Can not find the view file for this controller"
    ma_log "Error: Can not find the view file for this controller"
    redirect_to_root
  end
  #ma_display= get_option("ma_display")
  unless ma_display
    end_action
  end
end

#run_redirectObject



127
128
129
130
131
132
133
# File 'lib/generators/jinda/templates/app/controllers/jinda_controller.rb', line 127

def run_redirect
  init_vars(params[:id])
  # next_runseq= @xmain.runseqs.first :conditions=>["id != ? AND code = ?",@runseq.id, @runseq.code]
  next_runseq= @xmain.runseqs.where(:id.ne=>@runseq.id, :code=>@runseq.code).first
  @xmain.current_runseq= next_runseq.id
  end_action(next_runseq)
end

#searchObject



406
407
408
409
410
411
412
413
414
415
416
417
# File 'lib/generators/jinda/templates/app/controllers/jinda_controller.rb', line 406

def search
  @q = params[:q] || params[:ma_search][:q] || ""
  @title = "ผลการค้นหา #{@q}"
  @backbtn= true
  @cache= true
  if @q.blank?
    redirect_to "/"
  else
    s= GmaSearch.create :q=>@q, :ip=> request.env["REMOTE_ADDR"]
    do_search
  end
end

#statusObject



393
394
395
396
397
398
399
400
401
402
403
# File 'lib/generators/jinda/templates/app/controllers/jinda_controller.rb', line 393

def status
  @xmain= Jinda::Xmain.where(:xid=>params[:xid]).first
  @title= "Task number #{params[:xid]} #{@xmain.name}"
  @backbtn= true
  @xvars= @xmain.xvars
  # flash.now[:notice]= "รายการ #{@xmain.id} ได้ถูกยกเลิกแล้ว" if @xmain.status=='X'
  ma_log "Task #{@xmain.id} is cancelled" if @xmain.status=='X'
    # flash.now[:notice]= "transaction #{@xmain.id} was cancelled" if @xmain.status=='X'
rescue
  refresh_to "/", :alert => "Could not find task number <b> #{params[:xid]} </b>"
end