Browse Source

Fixing generator

Andrea Fazzi 5 năm trước cách đây
mục cha
commit
49e56fcbae

+ 1 - 0
.gitignore

@@ -1,2 +1,3 @@
 **/*~
 core
+output

+ 16 - 19
handlers/handlers.go

@@ -92,9 +92,9 @@ func generateHandler(r *mux.Router, model interface{}) {
 
 		apiPatterns []PathPattern
 
-		executePatterns []PathPattern = []PathPattern{
-			PathPattern{"/%s/{id}/execute", "", []string{"GET"}},
-		}
+		// executePatterns []PathPattern = []PathPattern{
+		// 	PathPattern{"/%s/{id}/execute", "", []string{"GET"}},
+		// }
 
 		filePatterns []PathPattern = []PathPattern{
 			PathPattern{"/%s/{id}/files/{filename}", "", []string{"GET"}},
@@ -121,12 +121,12 @@ func generateHandler(r *mux.Router, model interface{}) {
 		r.Handle(pattern.Path(pluralizedModelName(model)), jwtHeader.Handler(recoverHandler(modelHandler(pluralizedModelName(model), pattern)))).Methods(pattern.Methods...)
 	}
 
-	if model == "documents" {
-		for _, pattern := range executePatterns {
-			log.Printf("Register handler %s", pattern.Path(pluralizedModelName(model)))
-			r.Handle(pattern.Path(pluralizedModelName(model)), jwtCookie.Handler(recoverHandler(modelHandler(pluralizedModelName(model), pattern)))).Methods(pattern.Methods...)
-		}
-	}
+	// if model == "documents" {
+	// 	for _, pattern := range executePatterns {
+	// 		log.Printf("Register handler %s", pattern.Path(pluralizedModelName(model)))
+	// 		r.Handle(pattern.Path(pluralizedModelName(model)), jwtCookie.Handler(recoverHandler(modelHandler(pluralizedModelName(model), pattern)))).Methods(pattern.Methods...)
+	// 	}
+	// }
 
 	if model == "jobs" {
 		for _, pattern := range filePatterns {
@@ -310,18 +310,15 @@ func modelHandler(model string, pattern PathPattern) http.Handler {
 
 func executeHandler() http.Handler {
 	fn := func(w http.ResponseWriter, r *http.Request) {
-		switch r.Method {
-		case "GET":
-			get(w, r, model, pattern)
-
-		case "POST":
-			post(w, r, model, pattern)
-
-		case "DELETE":
-			delete(w, r, model, pattern)
+		format := r.URL.Query().Get("format")
+		data, err := orm.GetDocumentExecute(mux.Vars(r), r)
+		if err != nil {
+			renderer.Render[format](w, r, err)
+		} else {
+			renderer.Render[format](w, r, data, r.URL.Query())
 		}
-	}
 
+	}
 	return http.HandlerFunc(fn)
 }
 

+ 1 - 0
main.go

@@ -42,6 +42,7 @@ var (
 		&orm.Administrative{},
 		&orm.Group{},
 		&orm.Document{},
+		&orm.Job{},
 	}
 )
 

+ 16 - 7
orm/document.go

@@ -1,6 +1,8 @@
 package orm
 
 import (
+	"errors"
+	"fmt"
 	"log"
 	"net/http"
 	"time"
@@ -17,6 +19,8 @@ type GeneratorType struct {
 	Name string
 }
 
+func (g *GeneratorType) String() string { return g.Name }
+
 type Document struct {
 	gorm.Model
 
@@ -25,7 +29,7 @@ type Document struct {
 	OutputPath string
 	CloudPath  string
 
-	GeneratorTypeID uint
+	GeneratorTypeID uint `schema:"generator_type_id"`
 	GeneratorType   *GeneratorType
 
 	KeepArtifacts bool
@@ -161,7 +165,7 @@ func CreateDocument(document *Document) (*Document, error) {
 	return document, nil
 }
 
-func GetDocumentExecute(args map[string]string) (interface{}, error) {
+func GetDocumentExecute(args map[string]string, r *http.Request) (interface{}, error) {
 	var document Document
 	if err := DB().Preload("GeneratorType").First(&document, args["id"]).Error; err != nil {
 		return nil, err
@@ -179,11 +183,16 @@ func GetDocumentExecute(args map[string]string) (interface{}, error) {
 
 	log.Printf("Start concurrent job %d for generator %s", job.ID, document.Name)
 
-	gen := generator.Generators[document.GeneratorType.Name]
-
-	gen.SetJobId(job.ID)
-
-	go gen.Run()
+	if document.GeneratorType != nil {
+		gen, ok := generator.Generators[document.GeneratorType.Name]
+		if !ok {
+			return nil, fmt.Errorf("Generator type %s not found!", document.GeneratorType.Name)
+		}
+		gen.SetJobId(job.ID)
+		go gen.Run()
+	} else {
+		return nil, errors.New("Generator type not defined!")
+	}
 
 	return &document, nil
 }

+ 5 - 17
orm/job.go

@@ -18,6 +18,8 @@ type File struct {
 	JobID uint
 }
 
+func (f *File) String() string { return f.Path }
+
 type Log struct {
 	gorm.Model
 
@@ -57,23 +59,9 @@ func GetFile(args map[string]string) (interface{}, error) {
 	}, nil
 }
 
-// func (j *Job) Create(args map[string]string, r *http.Request) (interface{}, error) {
-// 	if r.Method == "GET" {
-// 		return nil, nil
-// 	} else {
-// 		job := new(Job)
-// 		err := renderer.Decode(job, r)
-// 		if err != nil {
-// 			return nil, err
-// 		}
-// 		job, err = CreateJob(job)
-// 		if err != nil {
-// 			return nil, err
-// 		}
-
-// 		return job, nil
-// 	}
-// }
+func (j *Job) Create(args map[string]string, r *http.Request) (interface{}, error) {
+	return nil, fmt.Errorf("Not implemented")
+}
 
 func (j *Job) Read(args map[string]string, r *http.Request) (interface{}, error) {
 	var job Job

+ 1 - 0
orm/mappings.go

@@ -38,6 +38,7 @@ func MapHandlers(models []interface{}) error {
 				joinedPath += "/"
 			}
 			fns[joinedPath] = method.Interface().(func(map[string]string, *http.Request) (interface{}, error))
+			fns["/api"+joinedPath] = method.Interface().(func(map[string]string, *http.Request) (interface{}, error))
 		}
 
 	}

+ 41 - 78
templates/documents_add_update.html.tpl

@@ -2,89 +2,52 @@
 
 <div class="container">
 
-  <nav aria-label="breadcrumb">
-  {{if .Options.Get "update"}}
-  <ol class="breadcrumb">
-    <li class="breadcrumb-item"><a href="/documents?{{query "tpl_layout" "base" "tpl_content" "documents"}}">Documento</a></li>
-    <li class="breadcrumb-item active"><a href="#">Aggiorna documento</a></li>
-  </ol>
-  </nav>
-  
-  {{else}}
-  <nav aria-label="breadcrumb">
-    <ol class="breadcrumb">
-      <li class="breadcrumb-item"><a href="/documents?{{query "tpl_layout" "base" "tpl_content" "documents"}}">Documento</a></li>
-      <li class="breadcrumb-item active"><a href="#">Aggiungi</a></li>
-    </ol>
-  </nav>
-  {{end}}
-
- {{if .Options.Get "update"}}
-  <div class="karmen-info-header">
-    <div class="row">
-      <div class="col-md-8">
-	<h1>Aggiorna documento</h1>
-      </div>
-    </div>
-  </div>
-  
-  {{else}}
-  <h1 class="karmen-info-header">Crea nuovo documento</h1>
-  {{end}}
+  {{$update := .Options.Get "update"}}
 
-  {{if .Options.Get "update"}}
-  <form id="form_documents_add_update" action="/documents/{{.Data.ID}}/update" method="POST" role="form" data-toggle="validator">
+  {{if $update}}
+  {{template "breadcrumb" toSlice "Documenti" (all "Document") (.Data|string) (.Data.ID|show "Document") "Aggiorna" "current"}}
   {{else}}
-  <form id="form_documents_add_update" action="/documents/add/" method="POST" role="form" data-toggle="validator">
+  {{template "breadcrumb" toSlice "Documenti" (all "Document") "Aggiungi" "current"}}
   {{end}}
-
-    <div class="form-group has-feedback">
-      <label class="control-label" for="document_name">Nome</label>
-      <input type="text" name="Name" class="form-control" id="document_name" placeholder="Nome" {{if .Options.Get "update"}} value="{{.Data.Name}}" {{end}} required>
-    </div>
-
-    <div class="form-group has-feedback">
-      <label class="control-label" for="document_cloud_path">Cartella di lavoro remota (cloud)</label>
-      <input type="text" name="CloudPath" class="form-control" id="document_cloud_path" placeholder="Documents/" {{if .Options.Get "update"}} value="{{.Data.CloudPath}}" {{end}} required>
-    </div>
-
-    <div class="form-check">
-      <input type="checkbox" name="KeepArtifacts" class="form-check-input" id="keep_artifacts" {{if .Options.Get "update"}}{{if .Data.KeepArtifacts}}checked{{end}}{{end}}>
-      <label class="form-check-label" for="exampleCheck1">Mantieni gli artefatti</label>
-      <small id="activity_group_hours_help_box" class="form-text text-muted">
-        Se selezionato carica sulla cartella remota gli artefatti derivati dalla produzione del documento (es: file di Markdown).
-      </small>        
-    </div>
-
-        
-    <div class="form-group">
-      <label class="control-label" for="generator_type_id">Tipo di generatore</label>
-      <select name="GeneratorTypeID" class="form-control selectpicker" id="generator_type_id" placeholder="Tipo di generatore" data-live-search="true" form="form_documents_add_update" title="Seleziona il tipo di generatore" data-dropup-auto="false">
-	<option value="0"></option>
-  	{{range $generatorType := .Data.AllGeneratorTypes}}
-	{{if $.Options.Get "update"}}
-  	<option
-	   value="{{$generatorType.ID}}"
-	   {{index $.Data.SelectedGeneratorType $generatorType.ID}}>{{$generatorType.Name}}
-	</option>
-	{{else}}
-  	<option value="{{$generatorType.ID}}">{{$generatorType.Name}}</option>
-	{{end}}
-  	{{end}}
-      </select>
-    </div>
-
-    <div class="form-group">
-      <button type="submit" class="btn btn-primary">Salva</button>
-      {{if .Options.Get "update"}}
-      <a href="/documents/{{.Data.ID}}?{{query "tpl_layout" "base" "tpl_content" "documents_show"}}" class="btn btn-default">Annulla</a>
-      {{else}}
-      <a href="/documents?{{query "tpl_layout" "base" "tpl_content" "documents"}}" class="btn btn-default">Annulla</a>
-      {{end}}
-    </div>
+  
+  {{template "add_update_header" dict "update" $update "addTitle" "Crea nuovo documento" "updateTitle" (printf "Aggiorna documento %s" (.Data|string))}}
+
+  {{$form := "form_documents_add_update"}}
+  <form
+    class="needs-validation"
+    action="{{if $update}}{{.Data.ID|update "Document"}}{{else}}{{create "Document"}}{{end}}"
+    method="POST"
+    role="form"
+    id={{$form}}>
+
+    {{$options := ` { name: "Name",id: "document_name",label: "Nome",placeholder: "Nome",type: "text",required: "true"} `}}
+    {{template "input" dict "options" ($options|yaml) "value" (.Data|field "Name") "update" $update}}
+
+    {{$options := ` { name: "CloudPath",id: "document_cloud_path",label: "Cartella di lavoro remota",placeholder: "Documents/",type: "text",required: "true"} `}}
+    {{template "input" dict "options" ($options|yaml) "value" (.Data|field "CloudPath") "update" $update}}
+
+    {{$options := `
+    name: "KeepArtifacts"
+    id: "document_keep_artifacts"
+    label: "Mantieni gli artefatti"
+    formClass: "form-group form-check"
+    help: "Se selezionato carica sulla cartella remota gli artefatti derivati dalla produzione del documento (es: markdown, odt, etc.). "
+    `}}
+    {{template "checkbox" dict "options" ($options|yaml) "value" (.Data|field "KeepArtifacts") "update" $update}}
+
+    {{$options := `
+    name: "generator_type_id"
+    id: "generator_type_id"
+    label: "Tipo di generatore"
+    title: "Seleziona il tipo di generatore"
+    `}}
+    {{template "select" dict "options" ($options|yaml) "data" (.Data|field "AllGeneratorTypes") "selected" (.Data|field "SelectedGeneratorType") "update" $update "form" $form}}
     
+    {{ $options := ` { cancelTitle: "Annulla", saveTitle: "Salva", model: "Document"} ` }}
+    {{template "submit_cancel_buttons" dict "options" ($options|yaml) "id" (.Data|field "ID") "update" $update}}
+  
   </form>
-
+  
 </div>
 
 {{ end }}

+ 1 - 1
templates/documents_show.html.tpl

@@ -2,7 +2,7 @@
 
 <div class="container">
 
-  {{template "breadcrumb" toSlice "Dipartimenti" (all "Document") (.Data|string) "current"}}
+  {{template "breadcrumb" toSlice "Documenti" (all "Document") (.Data|string) "current"}}
   {{template "show_header" dict "title" (.Data|string) "updatePath" (.Data.ID|update "Document") "deletePath" (.Data.ID|delete "Document")}}
   
   <div class="row">

+ 18 - 47
templates/jobs_show.html.tpl

@@ -2,56 +2,27 @@
 
 <div class="container">
 
-  <nav aria-label="breadcrumb">
-    <ol class="breadcrumb">
-      <li class="breadcrumb-item"><a href="/documents?{{query "tpl_layout" "base" "tpl_content" "documents"}}">Documenti</a></li>
-      <li class="breadcrumb-item"><a href="/documents/{{.Data.DocumentID}}?{{query "tpl_layout" "base" "tpl_content" "documents_show"}}">{{.Data.Document.Name}}</a></li>
-      <li class="breadcrumb-item active"><a href="#">Lavoro ID {{.Data.ID}}</a></li>
-    </ol>
-  </nav>
-
-  <div class="karmen-info-header">
-    <div class="row">
-      <div class="col-md-8">
-	<h1>Lavoro ID {{.Data.ID}}</h1>
-      </div>
-      <div class="col-md-4">
-        
-	<div class="btn-group float-right" role="group">
-	  <button href="/jobs/{{.Data.ID}}/delete"
-		  data-url="/jobs/{{.Data.ID}}/delete"
-		  class="btn btn-danger karmen-ajax-delete">
-            <span class="fa fa-trash" aria-hidden="true"></span>
-	    Elimina
-	  </button>
-	</div>
-
-      </div>
-    </div>
-  </div>
+  {{template "breadcrumb" toSlice "Lavori" (all "Job") (.Data|string) "current"}}
+  {{template "show_header" dict "title" (.Data|string) "updatePath" (.Data.ID|update "Job") "deletePath" (.Data.ID|delete "Job")}}
   
   <div class="row">
     <div class="col-md-12">
+
+      {{$options := `
+      title: "File prodotti"
+      model: "File"
+      icon: "fa fa-file-alt"
+      `}}
       
-      <h2 class="karmen-relation-header">Documenti prodotti</h2>
-      {{if .Data.Files}}
-      <div class="list-group" id="files_list_group">
-    	{{range $file := .Data.Files}}
-    	<a href="/jobs/{{$file.JobID}}/files/{{$file.Path}}?format=pdf" class="list-group-item list-group-item-action">
-    	  <span class="fa fa-file-alt"></span>
-    	  {{$file.Path}}
-    	  {{end}}
-    	</a>
-      </div>
-      {{else}}
-      <p>Non è stato prodotto nessun file..</p>
-      {{end}}
-    </div>
+      {{$noElements := "Questo lavoro non ha ancora prodotto alcun file."}}
+      {{template "relation_list" dict "options" ($options|yaml) "data" .Data.Files "noElements" $noElements}}
     
+    </div>
   </div>
-  
-  <div class="row">
-    <div class="col-md-12">    
+
+    <div class="row">
+    <div class="col-md-12">
+
       <h2 class="karmen-relation-header">Messaggi dal generatore</h2>
       {{if .Data.Logs}}
       <pre class="terminal pre-scrollable">
@@ -62,13 +33,13 @@
         </code>
       </pre>
       {{else}}
-      <p>Non è stato prodotto nessun file..</p>
+      <p>Il generatore non ha prodotto alcun messaggio.</p>
       {{end}}
-    </div>
     
+    </div>
   </div>
 
-
+  
 </div>    
 
 {{ end }}