view pkg/controllers/report.go @ 5321:0919946f624b extented-report

Added a report controller.
author Sascha L. Teichmann <sascha.teichmann@intevation.de>
date Thu, 27 May 2021 01:22:10 +0200
parents
children 80d9fd782f00
line wrap: on
line source

// This is Free Software under GNU Affero General Public License v >= 3.0
// without warranty, see README.md and license for details.
//
// SPDX-License-Identifier: AGPL-3.0-or-later
// License-Filename: LICENSES/AGPL-3.0.txt
//
// Copyright (C) 2021 by via donau
//   – Österreichische Wasserstraßen-Gesellschaft mbH
// Software engineering by Intevation GmbH
//
// Author(s):
//  * Sascha L. Teichmann <sascha.teichmann@intevation.de>

package controllers

import (
	"fmt"
	"log"
	"net/http"
	"os"
	"path/filepath"

	"gemma.intevation.de/gemma/pkg/config"
	"gemma.intevation.de/gemma/pkg/middleware"
	"gemma.intevation.de/gemma/pkg/xlsx"

	"github.com/360EntSecGroup-Skylar/excelize/v2"
	"github.com/gorilla/mux"
)

func report(rw http.ResponseWriter, req *http.Request) {

	vars := mux.Vars(req)

	name := vars["name"]

	config.WaitReady()
	path := config.ReportPath()
	if path == "" {
		http.NotFound(rw, req)
		return
	}

	stat, err := os.Stat(path)
	if err != nil {
		http.Error(rw, "Error: "+err.Error(), http.StatusInternalServerError)
		return
	}

	if !stat.Mode().IsDir() {
		http.NotFound(rw, req)
		return
	}

	xlsxFilename := filepath.Join(path, name+".xlsx")
	yamlFilename := filepath.Join(path, name+".yaml")

	_, errX := os.Stat(xlsxFilename)
	_, errY := os.Stat(yamlFilename)
	if errX != nil || errX != nil {
		if (errX != nil && os.IsNotExist(errX)) || (errY != nil && os.IsNotExist(errY)) {
			http.NotFound(rw, req)
		} else {
			http.Error(rw, "Something is wrong", http.StatusInternalServerError)
		}
		return
	}

	template, err := excelize.OpenFile(xlsxFilename)
	if err != nil {
		http.Error(rw, "Error: "+err.Error(), http.StatusInternalServerError)
		log.Printf("error: %v\n", err)
		return
	}

	action, err := xlsx.ActionFromFile(yamlFilename)
	if err != nil {
		http.Error(rw, "Error: "+err.Error(), http.StatusInternalServerError)
		log.Printf("error: %v\n", err)
		return
	}

	ctx := req.Context()
	conn := middleware.GetDBConn(req)

	if err := action.Execute(ctx, conn, template); err != nil {
		http.Error(rw, "Error: "+err.Error(), http.StatusInternalServerError)
		log.Printf("error: %v\n", err)
		return
	}
	rw.Header().Set(
		"Content-Disposition",
		fmt.Sprintf("attachment; filename=%s.xlsx", name))
	rw.Header().Set(
		"Content-Type",
		"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")

	if _, err := template.WriteTo(rw); err != nil {
		log.Printf("error: %v\n", err)
	}
}