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



338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
# File 'lib/generators/jinda/templates/app/controllers/jinda_controller.rb', line 338

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/_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



334
335
336
# File 'lib/generators/jinda/templates/app/controllers/jinda_controller.rb', line 334

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

#documentObject

handle uploaded image



366
367
368
369
370
371
372
373
374
375
376
377
378
# File 'lib/generators/jinda/templates/app/controllers/jinda_controller.rb', line 366

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



261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
# File 'lib/generators/jinda/templates/app/controllers/jinda_controller.rb', line 261

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



240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
# File 'lib/generators/jinda/templates/app/controllers/jinda_controller.rb', line 240

def end_form
  init_vars(params[:xmain_id])
  eval "@xvars[@runseq.code] = {} unless @xvars[@runseq.code]"
  params.each { |k,v|
    if params[k].respond_to? :original_filename
      get_image(k, params[k])
    elsif params[k]['filename'].respond_to? :original_filename
      eval "@xvars[@runseq.code][k] = v"
      params[k].each { |k1,v1|
        next unless v1.respond_to?(:original_filename)
        get_image1(k, k1, params[k][k1])
      }

    else
      v = v.to_unsafe_h unless v.class == String
      eval "@xvars[@runseq.code][k] = v"
    end
  }
  end_action
end

#end_outputObject



208
209
210
211
# File 'lib/generators/jinda/templates/app/controllers/jinda_controller.rb', line 208

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

#err404Object



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

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



410
411
412
413
414
415
# File 'lib/generators/jinda/templates/app/controllers/jinda_controller.rb', line 410

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



291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
# File 'lib/generators/jinda/templates/app/controllers/jinda_controller.rb', line 291

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



314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
# File 'lib/generators/jinda/templates/app/controllers/jinda_controller.rb', line 314

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



390
391
# File 'lib/generators/jinda/templates/app/controllers/jinda_controller.rb', line 390

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 ]



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

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

] run if, form, mail, output etc depend on icon in freemind ]



63
64
65
66
67
68
69
70
71
# File 'lib/generators/jinda/templates/app/controllers/jinda_controller.rb', line 63

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



127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
# File 'lib/generators/jinda/templates/app/controllers/jinda_controller.rb', line 127

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



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/generators/jinda/templates/app/controllers/jinda_controller.rb', line 72

def run_form
  init_vars(params[:id])
  if authorize?
    if ['F', 'X'].include? @xmain.status
      redirect_to_root
    else
      service= @xmain.service
      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



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# File 'lib/generators/jinda/templates/app/controllers/jinda_controller.rb', line 95

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



188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
# File 'lib/generators/jinda/templates/app/controllers/jinda_controller.rb', line 188

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



154
155
156
157
158
159
160
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
# File 'lib/generators/jinda/templates/app/controllers/jinda_controller.rb', line 154

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



120
121
122
123
124
125
126
# File 'lib/generators/jinda/templates/app/controllers/jinda_controller.rb', line 120

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



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

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



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

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