Kaynağa Gözat

Fixing document generator

Andrea Fazzi 5 yıl önce
ebeveyn
işleme
d04ab976e0

+ 3 - 3
generator/generators/list/list.go

@@ -1,11 +1,11 @@
 package list
 
 import (
-	"fmt"
 	"io/ioutil"
 	"log"
 	"os"
 	"path/filepath"
+	"strconv"
 	"sync"
 	"text/template"
 	"time"
@@ -185,7 +185,7 @@ func (generator *ListGenerator) Run() {
 	)
 
 	if generator.JobID > 0 {
-		outputPath = filepath.Join(generator.Config.Documents.OutputPath, fmt.Sprintf("%d/%d", job.DocumentID, job.ID))
+		outputPath = filepath.Join(generator.Config.Documents.OutputPath, strconv.Itoa(int(job.ID)))
 		cloudPath = job.Document.CloudPath
 	} else {
 		outputPath = "output"
@@ -201,7 +201,7 @@ func (generator *ListGenerator) Run() {
 	if generator.JobID > 0 {
 		job.End = time.Now()
 
-		job.Files = append(job.Files, &orm.File{Path: "elenco_docenti.pdf"})
+		job.Files = append(job.Files, &orm.File{Path: filepath.Join(outputPath, "elenco_docenti.pdf")})
 
 		err = generator.kaClient.UpdateJob(job)
 		if err != nil {

+ 6 - 2
handlers/handlers.go

@@ -104,7 +104,7 @@ func generateHandler(r *mux.Router, model interface{}) {
 	// Generate API patterns prefixing "api" path
 
 	for _, p := range patterns {
-		apiPatterns = append(apiPatterns, PathPattern{path.Join("/", "api", p.PathPattern), "", []string{"GET"}})
+		apiPatterns = append(apiPatterns, PathPattern{path.Join("/", "api", p.PathPattern), "", p.Methods})
 	}
 
 	// Install standard paths
@@ -128,7 +128,7 @@ func generateHandler(r *mux.Router, model interface{}) {
 	// 	}
 	// }
 
-	if model == "jobs" {
+	if modelName(model) == "Job" {
 		for _, pattern := range filePatterns {
 			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...)
@@ -293,6 +293,10 @@ func respondWithError(w http.ResponseWriter, r *http.Request, err error) {
 
 func modelHandler(model string, pattern PathPattern) http.Handler {
 	fn := func(w http.ResponseWriter, r *http.Request) {
+
+		// Replace "api" prefix
+		pattern.PathPattern = strings.Replace(pattern.PathPattern, "/api", "", -1)
+
 		switch r.Method {
 		case "GET":
 			get(w, r, model, pattern)

+ 1 - 0
main.go

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

+ 43 - 0
orm/file.go

@@ -0,0 +1,43 @@
+package orm
+
+import (
+	"fmt"
+	"net/http"
+
+	"github.com/jinzhu/gorm"
+)
+
+type File struct {
+	gorm.Model
+
+	Path string
+
+	JobID uint
+}
+
+func (f *File) String() string { return f.Path }
+
+func (f *File) Create(args map[string]string, r *http.Request) (interface{}, error) {
+	return nil, fmt.Errorf("Not implemented")
+}
+
+func (f *File) Read(args map[string]string, r *http.Request) (interface{}, error) {
+	var file File
+	if err := DB().First(&file, args["id"]).Error; err != nil {
+		return nil, err
+	}
+
+	return map[string]string{"filename": file.Path}, nil
+}
+
+func (f *File) ReadAll(args map[string]string, r *http.Request) (interface{}, error) {
+	return nil, fmt.Errorf("Not implemented")
+}
+
+func (f *File) Update(args map[string]string, r *http.Request) (interface{}, error) {
+	return nil, fmt.Errorf("Not implemented")
+}
+
+func (f *File) Delete(args map[string]string, r *http.Request) (interface{}, error) {
+	return nil, fmt.Errorf("Not implemented")
+}

+ 0 - 23
orm/job.go

@@ -3,23 +3,12 @@ package orm
 import (
 	"fmt"
 	"net/http"
-	"strconv"
 	"time"
 
 	"github.com/jinzhu/gorm"
 	"gogs.carducci-dante.gov.it/karmen/core/renderer"
 )
 
-type File struct {
-	gorm.Model
-
-	Path string
-
-	JobID uint
-}
-
-func (f *File) String() string { return f.Path }
-
 type Log struct {
 	gorm.Model
 
@@ -47,18 +36,6 @@ type Job struct {
 func (s *Job) GetID() uint    { return s.ID }
 func (j *Job) String() string { return fmt.Sprintf("Lavoro ID %d", j.ID) }
 
-func GetFile(args map[string]string) (interface{}, error) {
-	var job Job
-	if err := DB().Preload("Document").Preload("Files").First(&job, args["id"]).Error; err != nil {
-		return nil, err
-	}
-	return map[string]string{
-		"filename":    args["filename"],
-		"document_id": strconv.Itoa(int(job.DocumentID)),
-		"id":          strconv.Itoa(int(job.ID)),
-	}, nil
-}
-
 func (j *Job) Create(args map[string]string, r *http.Request) (interface{}, error) {
 	return nil, fmt.Errorf("Not implemented")
 }

+ 0 - 3
orm/mappings.go

@@ -2,7 +2,6 @@ package orm
 
 import (
 	"fmt"
-	"log"
 	"net/http"
 	"path"
 	"reflect"
@@ -38,7 +37,6 @@ 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))
 		}
 
 	}
@@ -49,7 +47,6 @@ func MapHandlers(models []interface{}) error {
 func GetFunc(path string) (GetFn, error) {
 	fn, ok := fns[path]
 	if !ok {
-		log.Println(fns)
 		return nil, fmt.Errorf("Can't map path %s to any model methods.", path)
 	}
 	return fn, nil

+ 18 - 4
renderer/funcmap.go

@@ -119,14 +119,24 @@ func getType(myvar interface{}) (res string) {
 }
 
 func query(values ...string) template.URL {
-	var urlValues url.Values
+	var (
+		urlValues url.Values
+		format    bool
+	)
 
 	urlValues = make(url.Values)
-	urlValues.Set("format", "html")
 
 	for i := 0; i < len(values); i += 2 {
+		if values[i] == "format" {
+			format = true
+		}
 		urlValues.Add(values[i], values[i+1])
 	}
+
+	if !format {
+		urlValues.Set("format", "html")
+	}
+
 	return template.URL(urlValues.Encode())
 }
 
@@ -179,10 +189,14 @@ func create(model string) string {
 	return fmt.Sprintf("/%s/%s/?%s", plural, action, q)
 }
 
-func show(model string, id uint) string {
+func show(model string, id uint, format ...string) string {
 	action := "show"
 	plural := inflection.Plural(strings.ToLower(model))
-	q := query("tpl_layout", "base", "tpl_content", fmt.Sprintf("%s_%s", plural, action))
+
+	args := []string{"tpl_layout", "base", "tpl_content", fmt.Sprintf("%s_%s", plural, action)}
+	args = append(args, format...)
+	// q := query("tpl_layout", "base", "tpl_content", fmt.Sprintf("%s_%s", plural, action))
+	q := query(args...)
 
 	return fmt.Sprintf("/%s/%d?%s", plural, id, q)
 }

+ 5 - 2
renderer/renderer.go

@@ -6,6 +6,7 @@ import (
 	"fmt"
 	"html/template"
 	"io"
+
 	"mime"
 	"net/http"
 	"net/url"
@@ -163,11 +164,13 @@ func NewPDFRenderer() (*PDFRenderer, error) {
 
 func (rend *PDFRenderer) Render(w http.ResponseWriter, r *http.Request, data interface{}, options ...url.Values) error {
 	w.Header().Set("Content-Type", "application/pdf")
-	fileMap := data.(map[string]string)
-	f, err := os.Open(filepath.Join("output", fileMap["document_id"], fileMap["id"], fileMap["filename"]))
+	fileInfo := data.(map[string]string)
+
+	f, err := os.Open(fileInfo["filename"])
 	if err != nil {
 		panic(err)
 	}
+
 	reader := bufio.NewReader(f)
 	io.Copy(w, reader)
 

+ 1 - 1
templates/jobs_show.html.tpl

@@ -7,7 +7,7 @@
   
   <div class="row">
     <div class="col-md-12">
-
+            
       {{$options := `
       title: "File prodotti"
       model: "File"

+ 7 - 1
templates/layout/relation_list.html.tpl

@@ -1,11 +1,17 @@
 {{define "relation_list"}}
+
+{{$format := "html"}}
+{{if .format}}
+{{$format = .format}}
+{{end}}
+
 <h2 class="karmen-relation-header">{{$title := .options.title}}{{if .title}}{{$title = .title}}{{end}}{{$title}}</h2>
 {{if (.data|isSlice)}}
 
 {{if gt (len .data) 0}}
 <div class="list-group" id="{{$title|toLower}}_list_group">
   {{range $el := .data}}
-  <a href="{{$el.ID | show $.options.model}}" class="list-group-item list-group-item-action">
+  <a href="{{show $.options.model $el.ID $format}}" class="list-group-item list-group-item-action">
     <span class="{{$.options.icon}}"></span>
     {{$el | string}}
     {{if $.small}}