Add files via upload

This commit is contained in:
Tomáš Dvořák
2025-05-22 10:27:28 +02:00
committed by GitHub
parent 6ee99a0679
commit 94600eaeec
7 changed files with 1106 additions and 304 deletions
+15 -3
View File
@@ -46,13 +46,25 @@
<div class="rounded-full w-14 h-14 flex items-center justify-center bg-blue-100 text-blue-600 mb-4"> <div class="rounded-full w-14 h-14 flex items-center justify-center bg-blue-100 text-blue-600 mb-4">
<i class="fas fa-car-side text-2xl"></i> <i class="fas fa-car-side text-2xl"></i>
</div> </div>
<h2 class="text-xl font-bold text-gray-800 mb-2">Záznam jízdy služebního vozu</h2> <h2 class="text-xl font-bold text-gray-800 mb-2">Záznam služebních jízd</h2>
<p class="text-gray-600 mb-4">Systém pro evidenci služebních jízd.</p> <p class="text-gray-600 mb-4">Jednoduchý systém pro evidenci a správu jízd služebními vozidly.</p>
<a href="/evidence-aut" class="block text-center bg-blue-600 hover:bg-blue-700 text-white font-medium py-2 px-4 rounded-lg transition-colors"> <a href="/evidence-aut" class="block text-center bg-blue-600 hover:bg-blue-700 text-white font-medium py-2 px-4 rounded-lg transition-colors">
Otevřít aplikaci Otevřít aplikaci
</a> </a>
</div> </div>
<!-- Contact card -->
<div class="card bg-white rounded-xl shadow p-6 border-t-4 border-green-600" data-name="kontakt">
<div class="rounded-full w-14 h-14 flex items-center justify-center bg-green-100 text-green-600 mb-4">
<i class="fas fa-envelope text-2xl"></i>
</div>
<h2 class="text-xl font-bold text-gray-800 mb-2">Kontaktní formulář</h2>
<p class="text-gray-600 mb-4">Formulář pro kontaktování vedení společnosti.</p>
<a href="/kontakt" class="block text-center bg-green-600 hover:bg-green-700 text-white font-medium py-2 px-4 rounded-lg transition-colors">
Otevřít
</a>
</div>
<!-- 2. Lunches --> <!-- 2. Lunches -->
<div class="card bg-white rounded-xl shadow p-6 border-t-4 border-green-600" data-name="obědy obedy jídlo lunch"> <div class="card bg-white rounded-xl shadow p-6 border-t-4 border-green-600" data-name="obědy obedy jídlo lunch">
<div class="rounded-full w-14 h-14 flex items-center justify-center bg-green-100 text-green-600 mb-4"> <div class="rounded-full w-14 h-14 flex items-center justify-center bg-green-100 text-green-600 mb-4">
@@ -93,7 +105,7 @@
<footer class="bg-gray-800 text-gray-400 py-6 mt-12"> <footer class="bg-gray-800 text-gray-400 py-6 mt-12">
<div class="container mx-auto px-4 text-center"> <div class="container mx-auto px-4 text-center">
<p>© 2025 Poppe + Potthoff</p> <p> 2025 Poppe + Potthoff</p>
<p class="mt-2 text-sm">Created by <a href="https://tdvorak.dev" class="text-blue-400 hover:text-blue-300">TDvorak</a></p> <p class="mt-2 text-sm">Created by <a href="https://tdvorak.dev" class="text-blue-400 hover:text-blue-300">TDvorak</a></p>
</div> </div>
</footer> </footer>
+141
View File
@@ -0,0 +1,141 @@
# Contact Scrape Makefile
.PHONY: build run clean install dev test help
# Variables
BINARY_NAME=contact-scrape
BUILD_DIR=build
PORT=8080
help: ## Show this help message
@echo "Available commands:"
@awk 'BEGIN {FS = ":.*##"; printf "\nUsage:\n make \033[36m<target>\033[0m\n"} /^[a-zA-Z_-]+:.*?##/ { printf " \033[36m%-15s\033[0m %s\n", $$1, $$2 } /^##@/ { printf "\n\033[1m%s\033[0m\n", substr($$0, 5) } ' $(MAKEFILE_LIST)
##@ Development
dev: ## Run the application in development mode
@echo "Starting development server..."
@go run .
run: build ## Build and run the application
@echo "Starting $(BINARY_NAME)..."
@./$(BUILD_DIR)/$(BINARY_NAME)
test: ## Run tests
@echo "Running tests..."
@go test -v ./...
##@ Build
build: ## Build the application
@echo "Building $(BINARY_NAME)..."
@mkdir -p $(BUILD_DIR)
@go build -o $(BUILD_DIR)/$(BINARY_NAME) .
@echo "Binary built: $(BUILD_DIR)/$(BINARY_NAME)"
build-linux: ## Build for Linux (useful for deployment)
@echo "Building $(BINARY_NAME) for Linux..."
@mkdir -p $(BUILD_DIR)
@GOOS=linux GOARCH=amd64 go build -o $(BUILD_DIR)/$(BINARY_NAME)-linux .
@echo "Linux binary built: $(BUILD_DIR)/$(BINARY_NAME)-linux"
##@ Dependencies
deps: ## Download dependencies
@echo "Downloading dependencies..."
@go mod download
@go mod tidy
##@ Deployment
install: build ## Install the service (requires sudo)
@echo "Installing contact-scrape service..."
@sudo mkdir -p /opt/contact-scrape
@sudo cp $(BUILD_DIR)/$(BINARY_NAME) /opt/contact-scrape/
@sudo cp index.html /opt/contact-scrape/
@sudo mkdir -p /opt/contact-scrape/data
@sudo chown -R www-data:www-data /opt/contact-scrape
@sudo cp contact-scrape.service /etc/systemd/system/
@sudo systemctl daemon-reload
@sudo systemctl enable contact-scrape
@echo "Service installed. Start with: sudo systemctl start contact-scrape"
uninstall: ## Uninstall the service (requires sudo)
@echo "Uninstalling contact-scrape service..."
@sudo systemctl stop contact-scrape 2>/dev/null || true
@sudo systemctl disable contact-scrape 2>/dev/null || true
@sudo rm -f /etc/systemd/system/contact-scrape.service
@sudo systemctl daemon-reload
@sudo rm -rf /opt/contact-scrape
@echo "Service uninstalled."
status: ## Check service status
@sudo systemctl status contact-scrape
start: ## Start the service
@sudo systemctl start contact-scrape
stop: ## Stop the service
@sudo systemctl stop contact-scrape
restart: ## Restart the service
@sudo systemctl restart contact-scrape
logs: ## View service logs
@sudo journalctl -u contact-scrape -f
##@ File Management
upload-xlsx: ## Upload contacts.xlsx to server (set SERVER variable)
@if [ -z "$(SERVER)" ]; then echo "Usage: make upload-xlsx SERVER=user@hostname"; exit 1; fi
@echo "Uploading contacts.xlsx to $(SERVER)..."
@scp contacts.xlsx $(SERVER):/opt/contact-scrape/
@ssh $(SERVER) "sudo chown www-data:www-data /opt/contact-scrape/contacts.xlsx"
@ssh $(SERVER) "sudo systemctl restart contact-scrape"
@echo "File uploaded and service restarted."
##@ Monitoring
monitor: ## Monitor the service with file watching
@echo "Monitoring contacts.xlsx for changes..."
@while true; do \
inotifywait -e modify contacts.xlsx 2>/dev/null && \
echo "File changed, reloading..." && \
curl -X POST http://localhost:$(PORT)/reload; \
sleep 1; \
done
##@ Utilities
clean: ## Clean build artifacts
@echo "Cleaning build artifacts..."
@rm -rf $(BUILD_DIR)
@rm -f data/contacts.json
setup-dirs: ## Create necessary directories
@mkdir -p data
@mkdir -p $(BUILD_DIR)
check-file: ## Check if contacts.xlsx exists and show info
@if [ -f "contacts.xlsx" ]; then \
echo "✓ contacts.xlsx found"; \
ls -lh contacts.xlsx; \
else \
echo "✗ contacts.xlsx not found"; \
echo "Please place your Excel file in the current directory"; \
fi
##@ Docker (Optional)
docker-build: ## Build Docker image
@echo "Building Docker image..."
@docker build -t contact-scrape .
docker-run: ## Run in Docker container
@echo "Running Docker container..."
@docker run -p $(PORT):$(PORT) -v $(PWD)/contacts.xlsx:/app/contacts.xlsx -v $(PWD)/data:/app/data contact-scrape
##@ Information
info: ## Show application information
@echo "Contact Scrape Application"
@echo "========================="
@echo "Port: $(PORT)"
@echo "Binary: $(BINARY_NAME)"
@echo "Build dir: $(BUILD_DIR)"
@echo ""
@echo "Endpoints:"
@echo " http://localhost:$(PORT)/ - Web interface"
@echo " http://localhost:$(PORT)/contacts - JSON API"
@echo " http://localhost:$(PORT)/reload - Reload data (POST)"
+403
View File
@@ -0,0 +1,403 @@
package main
import (
"crypto/md5"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"regexp"
"strings"
"time"
"github.com/xuri/excelize/v2"
)
type Contact struct {
Name string `json:"name"`
Position string `json:"position"`
Phone string `json:"phone,omitempty"`
ServicePhone string `json:"service_phone,omitempty"`
Table int `json:"table"` // 1 for first table, 2 for second table
}
type ContactData struct {
Contacts []Contact `json:"contacts"`
LastUpdated time.Time `json:"last_updated"`
FileHash string `json:"file_hash"`
}
var (
currentData *ContactData
dataFile = "data/contacts.json"
xlsxFile = "contacts.xlsx"
)
func main() {
// Create data directory if it doesn't exist
if err := os.MkdirAll("data", 0755); err != nil {
log.Printf("Warning: Could not create data directory: %v", err)
}
// Load existing data or parse from Excel
loadData()
// Set up HTTP handlers
http.HandleFunc("/", serveIndex)
http.HandleFunc("/contacts", serveContacts)
http.HandleFunc("/reload", reloadData)
// Start server
port := os.Getenv("PORT")
if port == "" {
port = "80"
}
log.Printf("Server starting on port %s", port)
log.Printf("Access the application at: http://localhost:%s", port)
log.Fatal(http.ListenAndServe(":"+port, nil))
}
func loadData() {
// Check if Excel file exists
if _, err := os.Stat(xlsxFile); os.IsNotExist(err) {
log.Printf("Excel file %s not found, using empty data", xlsxFile)
currentData = &ContactData{
Contacts: []Contact{},
LastUpdated: time.Now(),
FileHash: "",
}
return
}
// Calculate current file hash
currentHash, err := calculateFileHash(xlsxFile)
if err != nil {
log.Printf("Error calculating file hash: %v", err)
return
}
// Check if cached data exists and is up to date
if cachedData, err := loadCachedData(); err == nil {
if cachedData.FileHash == currentHash {
log.Println("Using cached data (file unchanged)")
currentData = cachedData
return
}
}
// Parse Excel file
log.Println("Parsing Excel file...")
contacts, err := parseExcelFile(xlsxFile)
if err != nil {
log.Printf("Error parsing Excel file: %v", err)
// Use empty data if parsing fails
currentData = &ContactData{
Contacts: []Contact{},
LastUpdated: time.Now(),
FileHash: currentHash,
}
return
}
currentData = &ContactData{
Contacts: contacts,
LastUpdated: time.Now(),
FileHash: currentHash,
}
// Save to cache
if err := saveCachedData(currentData); err != nil {
log.Printf("Warning: Could not save cached data: %v", err)
}
log.Printf("Loaded %d contacts from Excel file", len(contacts))
}
func calculateFileHash(filename string) (string, error) {
file, err := os.Open(filename)
if err != nil {
return "", err
}
defer file.Close()
hash := md5.New()
if _, err := io.Copy(hash, file); err != nil {
return "", err
}
return fmt.Sprintf("%x", hash.Sum(nil)), nil
}
func loadCachedData() (*ContactData, error) {
file, err := os.Open(dataFile)
if err != nil {
return nil, err
}
defer file.Close()
var data ContactData
decoder := json.NewDecoder(file)
if err := decoder.Decode(&data); err != nil {
return nil, err
}
return &data, nil
}
func saveCachedData(data *ContactData) error {
file, err := os.Create(dataFile)
if err != nil {
return err
}
defer file.Close()
encoder := json.NewEncoder(file)
encoder.SetIndent("", " ")
return encoder.Encode(data)
}
func parseExcelFile(filename string) ([]Contact, error) {
f, err := excelize.OpenFile(filename)
if err != nil {
return nil, fmt.Errorf("failed to open Excel file: %v", err)
}
defer f.Close()
// Get the first sheet name
sheets := f.GetSheetList()
if len(sheets) == 0 {
return nil, fmt.Errorf("no sheets found in Excel file")
}
sheetName := sheets[0]
var contacts []Contact
// Parse first table (A-D columns)
contacts = append(contacts, parseTable(f, sheetName, "A", "D", 1)...)
// Parse second table (F-H columns)
contacts = append(contacts, parseTable(f, sheetName, "F", "H", 2)...)
return contacts, nil
}
func parseTable(f *excelize.File, sheetName, startCol, endCol string, tableNum int) []Contact {
var contacts []Contact
var currentContact *Contact
// Get all rows in the sheet
rows, err := f.GetRows(sheetName)
if err != nil {
log.Printf("Error getting rows: %v", err)
return contacts
}
// Skip header rows (first 3 rows based on your description)
startRow := 3
if len(rows) <= startRow {
return contacts
}
// Column indices
var nameCol, positionCol, phoneCol, servicePhoneCol int
if tableNum == 1 {
nameCol, positionCol, phoneCol, servicePhoneCol = 0, 1, 2, 3 // A, B, C, D
} else {
nameCol, positionCol, phoneCol = 5, 6, 7 // F, G, H
}
for i := startRow; i < len(rows); i++ {
row := rows[i]
// Skip if row is too short
if len(row) <= nameCol {
continue
}
// Check for "Aktualizace" - end of data
if len(row) > nameCol && strings.Contains(strings.ToLower(row[nameCol]), "aktualizace") {
break
}
// Check for special formatting rows (like "*02(xx)")
if len(row) > positionCol && strings.Contains(row[positionCol], "*") {
continue
}
name := strings.TrimSpace(row[nameCol])
position := ""
phone := ""
servicePhone := ""
if len(row) > positionCol {
position = strings.TrimSpace(row[positionCol])
}
if len(row) > phoneCol {
phone = strings.TrimSpace(row[phoneCol])
}
if tableNum == 1 && len(row) > servicePhoneCol {
servicePhone = strings.TrimSpace(row[servicePhoneCol])
}
// Clean phone numbers
phone = cleanPhoneNumber(phone)
servicePhone = cleanPhoneNumber(servicePhone)
// If we have a name, start a new contact
if name != "" && !strings.Contains(name, "(") {
currentContact = &Contact{
Name: name,
Position: position,
Phone: phone,
ServicePhone: servicePhone,
Table: tableNum,
}
contacts = append(contacts, *currentContact)
} else if currentContact != nil {
// This is additional data for the current contact
newContact := *currentContact
if position != "" {
newContact.Position = position
}
if phone != "" {
newContact.Phone = phone
}
if servicePhone != "" {
newContact.ServicePhone = servicePhone
}
contacts = append(contacts, newContact)
}
}
return contacts
}
func cleanPhoneNumber(phone string) string {
if phone == "" {
return ""
}
// Remove extra whitespace
phone = strings.TrimSpace(phone)
// Remove common formatting characters
re := regexp.MustCompile(`[^\d+\-\s()]`)
phone = re.ReplaceAllString(phone, "")
// If it's just a short number (internal extension), keep as is
if len(phone) <= 3 {
return phone
}
// If it looks like a Czech number without country code, add it
if regexp.MustCompile(`^[67]\d{8}$`).MatchString(strings.ReplaceAll(phone, " ", "")) {
return "+420 " + phone
}
return phone
}
func serveIndex(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
// Check if index.html exists
if _, err := os.Stat("index.html"); os.IsNotExist(err) {
// Serve embedded HTML if file doesn't exist
w.Header().Set("Content-Type", "text/html; charset=utf-8")
fmt.Fprint(w, getEmbeddedHTML())
return
}
http.ServeFile(w, r, "index.html")
}
func serveContacts(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
if currentData == nil {
http.Error(w, `{"error": "No data available"}`, http.StatusInternalServerError)
return
}
encoder := json.NewEncoder(w)
encoder.SetIndent("", " ")
encoder.Encode(currentData)
}
func reloadData(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
log.Println("Manual reload requested")
loadData()
w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, `{"status": "reloaded", "contacts_count": %d}`, len(currentData.Contacts))
}
func getEmbeddedHTML() string {
return `<!DOCTYPE html>
<html lang="cs">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Kontakty</title>
<script src="https://cdn.tailwindcss.com"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
</head>
<body class="bg-gray-100 min-h-screen">
<header class="bg-gradient-to-r from-blue-600 to-indigo-700 text-white shadow-lg">
<div class="container mx-auto px-4 py-6">
<h1 class="text-3xl font-bold">📞 Firemní telefonní seznam</h1>
<p class="mt-2 text-blue-100">Poppe + Potthoff kontakty</p>
</div>
</header>
<div class="container mx-auto px-4 py-8 max-w-7xl">
<div class="bg-white rounded-xl shadow p-6 md:p-8">
<div class="flex justify-between items-center mb-6">
<button onclick="reloadContacts()" id="reloadBtn"
class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-3 rounded-lg transition-all duration-200 shadow-md hover:shadow-lg flex items-center gap-2">
<i class="fas fa-sync-alt"></i>
Obnovit
</button>
</div>
<div class="mb-6">
<div class="relative">
<input type="text" id="searchInput" placeholder="Hledat podle jména, pozice nebo telefonu..."
class="w-full px-4 py-3 pl-12 rounded-lg shadow-sm border-gray-200 focus:border-blue-500 focus:ring-2 focus:ring-blue-500 focus:outline-none text-lg"
onkeyup="filterContacts()">
<i class="fas fa-search absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
</div>
</div>
<div id="loading" class="text-center py-16">
<div class="inline-block animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mb-4"></div>
<p class="text-gray-600 text-lg">Načítání kontaktů...</p>
</div>
<div id="contactsList" class="hidden">
<div id="stats" class="mb-6 p-4 bg-gray-50 rounded-lg border text-sm text-gray-700"></div>
<div id="contacts" class="grid gap-6 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4"></div>
</div>
</div>
</div>
<footer class="bg-gray-800 text-gray-400 py-6 mt-12">
<div class="container mx-auto px-4 text-center">
<p> 2025 Poppe + Potthoff</p>
</div>
</footer>
</body>
</html>`
}
+29
View File
@@ -0,0 +1,29 @@
[Unit]
Description=Contact Scrape Service
After=network.target
[Service]
Type=simple
User=www-data
WorkingDirectory=/opt/contact-scrape
ExecStart=/opt/contact-scrape/contact-scrape
Restart=always
RestartSec=5
Environment=PORT=8080
# Security settings
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/opt/contact-scrape/data
CapabilityBoundingSet=CAP_NET_BIND_SERVICE
AmbientCapabilities=CAP_NET_BIND_SERVICE
# Logging
StandardOutput=journal
StandardError=journal
SyslogIdentifier=contact-scrape
[Install]
WantedBy=multi-user.target
Binary file not shown.
+376
View File
@@ -0,0 +1,376 @@
<!DOCTYPE html>
<html lang="cs">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Kontakty</title>
<script src="https://cdn.tailwindcss.com"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
<style>
.contact-card {
transition: all 0.2s ease-in-out;
border-top: 4px solid #2563eb;
}
.contact-card:hover {
transform: translateY(-5px);
box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
}
.search-highlight {
background-color: #fef3c7;
padding: 1px 2px;
border-radius: 2px;
}
</style>
</head>
<body class="bg-gray-100 min-h-screen">
<header class="bg-gradient-to-r from-blue-600 to-indigo-700 text-white shadow-lg" style="margin-bottom: 20px;">
<div class="container mx-auto px-4 py-6">
<h1 class="text-3xl font-bold">📞 Firemní telefonní seznam</h1>
<p class="mt-2 text-blue-100">Poppe + Potthoff kontakty</p>
</div>
</header>
<div class="container mx-auto px-4 py-8 max-w-7xl">
<div class="bg-white rounded-xl shadow p-6 md:p-8">
<!-- Header -->
<div class="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-8 gap-4">
<div>
<h1 class="text-4xl font-bold text-gray-800 mb-2">📞 Kontakty</h1>
<p class="text-gray-600">Firemní telefonní seznam</p>
</div>
<button onclick="reloadContacts()" id="reloadBtn"
class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-3 rounded-lg transition-all duration-200 shadow-md hover:shadow-lg flex items-center gap-2">
<i class="fas fa-sync-alt"></i>
Obnovit
</button>
</div>
<!-- Search Bar -->
<div class="mb-6">
<div class="relative">
<input type="text" id="searchInput" placeholder="Hledat podle jména, pozice nebo telefonu..."
class="w-full px-4 py-3 pl-12 rounded-lg shadow-sm border-gray-200 focus:border-blue-500 focus:ring-2 focus:ring-blue-500 focus:outline-none text-lg"
onkeyup="filterContacts()">
<i class="fas fa-search absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
</div>
</div>
<!-- Filter Buttons -->
<div class="mb-6 flex flex-wrap gap-2">
<button onclick="filterByTable('all')" class="filter-btn active" data-filter="all">
Všechny kontakty
</button>
<button onclick="filterByTable(1)" class="filter-btn" data-filter="1">
Tabulka 1
</button>
<button onclick="filterByTable(2)" class="filter-btn" data-filter="2">
Tabulka 2
</button>
</div>
<!-- Loading State -->
<div id="loading" class="text-center py-16">
<div class="inline-block animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mb-4"></div>
<p class="text-gray-600 text-lg">Načítání kontaktů...</p>
</div>
<!-- Main Content -->
<div id="contactsList" class="hidden">
<!-- Stats -->
<div id="stats" class="mb-6 p-4 bg-gray-50 rounded-lg border text-sm text-gray-700"></div>
<!-- Contacts Grid -->
<div id="contacts" class="grid gap-6 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4"></div>
<!-- No Results -->
<div id="noResults" class="hidden text-center py-16">
<div class="text-6xl mb-4">🔍</div>
<h3 class="text-xl font-semibold text-gray-700 mb-2">Žádné výsledky</h3>
<p class="text-gray-500">Zkuste změnit hledaný výraz</p>
</div>
</div>
<!-- Error State -->
<div id="error" class="hidden text-center py-16">
<div class="text-6xl mb-4">⚠️</div>
<h3 class="text-xl font-semibold text-red-600 mb-2">Chyba při načítání</h3>
<p class="text-gray-600 mb-4">Nepodařilo se načíst kontakty</p>
<button onclick="loadContacts()" class="bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-lg transition-colors">
Zkusit znovu
</button>
</div>
</div>
</div>
<footer class="bg-gray-800 text-gray-400 py-6 mt-12">
<div class="container mx-auto px-4 text-center">
<p>2025 Poppe + Potthoff</p>
</div>
</footer>
<script>
let allContacts = [];
let filteredContacts = [];
let currentTableFilter = 'all';
async function loadContacts() {
try {
showLoading();
const response = await fetch('/contacts');
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const data = await response.json();
allContacts = data.contacts || [];
hideLoading();
showContactsList();
updateStats(data);
filterContacts();
} catch (error) {
console.error('Error loading contacts:', error);
hideLoading();
showError('Chyba při načítání kontaktů: ' + error.message);
}
}
function showLoading() {
document.getElementById('loading').classList.remove('hidden');
document.getElementById('contactsList').classList.add('hidden');
document.getElementById('error').classList.add('hidden');
}
function hideLoading() {
document.getElementById('loading').classList.add('hidden');
}
function showContactsList() {
document.getElementById('contactsList').classList.remove('hidden');
document.getElementById('error').classList.add('hidden');
}
function showError(message) {
document.getElementById('error').classList.remove('hidden');
document.getElementById('error').querySelector('p').textContent = message;
document.getElementById('contactsList').classList.add('hidden');
}
function updateStats(data) {
const lastUpdated = new Date(data.last_updated).toLocaleString('cs-CZ');
const table1Count = allContacts.filter(c => c.table === 1).length;
const table2Count = allContacts.filter(c => c.table === 2).length;
document.getElementById('stats').innerHTML = `
<div class="flex flex-wrap items-center gap-4 text-sm">
<div class="flex items-center gap-2">
<span class="w-2 h-2 bg-green-500 rounded-full"></span>
<span><strong>Celkem:</strong> ${allContacts.length} kontaktů</span>
</div>
<div class="flex items-center gap-2">
<span class="w-2 h-2 bg-blue-500 rounded-full"></span>
<span><strong>Tabulka 1:</strong> ${table1Count}</span>
</div>
<div class="flex items-center gap-2">
<span class="w-2 h-2 bg-purple-500 rounded-full"></span>
<span><strong>Tabulka 2:</strong> ${table2Count}</span>
</div>
<div class="flex items-center gap-2">
<span class="w-2 h-2 bg-gray-400 rounded-full"></span>
<span><strong>Poslední aktualizace:</strong> ${lastUpdated}</span>
</div>
</div>
`;
}
function filterByTable(tableNum) {
currentTableFilter = tableNum;
// Update filter buttons
document.querySelectorAll('.filter-btn').forEach(btn => {
btn.classList.remove('active');
if (btn.dataset.filter == tableNum) {
btn.classList.add('active');
}
});
filterContacts();
}
function filterContacts() {
const query = document.getElementById('searchInput').value.toLowerCase().trim();
// Apply table filter
let contacts = allContacts;
if (currentTableFilter !== 'all') {
contacts = contacts.filter(contact => contact.table == currentTableFilter);
}
// Apply search filter
if (query) {
contacts = contacts.filter(contact =>
(contact.name && contact.name.toLowerCase().includes(query)) ||
(contact.position && contact.position.toLowerCase().includes(query)) ||
(contact.phone && contact.phone.replace(/\s/g, '').includes(query.replace(/\s/g, ''))) ||
(contact.service_phone && contact.service_phone.replace(/\s/g, '').includes(query.replace(/\s/g, '')))
);
}
filteredContacts = contacts;
displayContacts(filteredContacts, query);
}
function highlightText(text, query) {
if (!query || !text) return text;
const regex = new RegExp(`(${query})`, 'gi');
return text.replace(regex, '<span class="search-highlight">$1</span>');
}
function displayContacts(contacts, searchQuery = '') {
const container = document.getElementById('contacts');
const noResults = document.getElementById('noResults');
if (contacts.length === 0) {
container.innerHTML = '';
noResults.classList.remove('hidden');
return;
}
noResults.classList.add('hidden');
container.innerHTML = '';
contacts.forEach(contact => {
const contactCard = document.createElement('div');
contactCard.className = 'contact-card bg-white p-6 rounded-lg border border-gray-200 hover:shadow-lg transition-all duration-200';
const name = contact.name || 'Bez jména';
const position = contact.position || '';
const tableColor = contact.table === 1 ? 'bg-blue-100 text-blue-800' : 'bg-purple-100 text-purple-800';
contactCard.innerHTML = `
<div class="flex items-start justify-between mb-3">
<h3 class="font-bold text-gray-800 text-lg leading-tight">${highlightText(name, searchQuery)}</h3>
<span class="text-xs ${tableColor} px-2 py-1 rounded-full font-medium flex-shrink-0 ml-2">T${contact.table}</span>
</div>
${position ? `<p class="text-gray-600 mb-4 text-sm leading-relaxed">${highlightText(position, searchQuery)}</p>` : ''}
<div class="space-y-2">
${contact.phone ? `
<div class="flex items-center text-sm group">
<i class="fas fa-phone-alt text-gray-400 mr-3 flex-shrink-0"></i>
<span class="font-medium text-gray-700 mr-2">Tel:</span>
<a href="tel:${contact.phone}" class="text-blue-600 hover:text-blue-800 hover:underline transition-colors">
${highlightText(contact.phone, searchQuery)}
</a>
</div>
` : ''}
${contact.service_phone ? `
<div class="flex items-center text-sm group">
<i class="fas fa-phone-alt text-gray-400 mr-3 flex-shrink-0"></i>
<span class="font-medium text-gray-700 mr-2">Služební:</span>
<a href="tel:${contact.service_phone}" class="text-blue-600 hover:text-blue-800 hover:underline transition-colors">
${highlightText(contact.service_phone, searchQuery)}
</a>
</div>
` : ''}
${!contact.phone && !contact.service_phone ? '<p class="text-gray-400 text-sm italic">Bez telefonu</p>' : ''}
</div>
`;
container.appendChild(contactCard);
});
}
async function reloadContacts() {
const btn = document.getElementById('reloadBtn');
const originalText = btn.innerHTML;
btn.disabled = true;
btn.innerHTML = `
<i class="fas fa-sync-alt animate-spin"></i>
Načítání...
`;
try {
const response = await fetch('/reload', { method: 'POST' });
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
// Small delay to show the loading state
await new Promise(resolve => setTimeout(resolve, 500));
await loadContacts();
// Show success feedback
btn.innerHTML = `
<i class="fas fa-check text-green-500"></i>
Obnoveno
`;
setTimeout(() => {
btn.innerHTML = originalText;
}, 2000);
} catch (error) {
console.error('Error reloading:', error);
btn.innerHTML = `
<i class="fas fa-times text-red-500"></i>
Chyba
`;
setTimeout(() => {
btn.innerHTML = originalText;
}, 2000);
alert('Chyba při obnovování: ' + error.message);
} finally {
btn.disabled = false;
}
}
// Initialize filter button styles
document.addEventListener('DOMContentLoaded', function() {
const style = document.createElement('style');
style.textContent = `
.filter-btn {
@apply px-4 py-2 rounded-lg border border-gray-300 text-gray-700 hover:bg-gray-50 transition-all duration-200 text-sm font-medium;
}
.filter-btn.active {
@apply bg-blue-500 text-white border-blue-500 shadow-md;
}
.filter-btn:hover:not(.active) {
@apply bg-gray-100 border-gray-400;
}
`;
document.head.appendChild(style);
});
// Load contacts on page load
document.addEventListener('DOMContentLoaded', loadContacts);
// Add keyboard shortcuts
document.addEventListener('keydown', function(e) {
// Ctrl/Cmd + K to focus search
if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
e.preventDefault();
document.getElementById('searchInput').focus();
}
// Escape to clear search
if (e.key === 'Escape') {
document.getElementById('searchInput').value = '';
filterContacts();
}
});
// Add search input focus ring and animations
document.getElementById('searchInput').addEventListener('focus', function() {
this.parentElement.classList.add('ring-2', 'ring-blue-500');
});
document.getElementById('searchInput').addEventListener('blur', function() {
this.parentElement.classList.remove('ring-2', 'ring-blue-500');
});
</script>
</body>
</html>
+23 -182
View File
@@ -8,6 +8,7 @@ import (
"log" "log"
"net/http" "net/http"
"os" "os"
"os/exec"
"strings" "strings"
"time" "time"
@@ -33,171 +34,6 @@ type GeoCoords struct {
Lng string `json:"lng"` Lng string `json:"lng"`
} }
type Contact struct {
Name string `json:"name"`
Position string `json:"position"`
Phone string `json:"phone"`
ServicePhone string `json:"service_phone"`
Table int `json:"table"`
}
func getEmbeddedHTML() string {
return `<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Kontakty</title>
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background-color: #f0f2f5;
margin: 0;
padding: 0;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.container {
max-width: 600px;
margin: 20px auto;
background-color: #ffffff;
border-radius: 8px;
overflow: hidden;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
.header {
background-color: #004990;
color: white;
padding: 20px 25px;
text-align: center;
}
.header h1 {
margin: 0;
font-size: 24px;
font-weight: 600;
}
.content {
padding: 25px;
}
.section {
margin-bottom: 25px;
border-bottom: 1px solid #eaeaea;
padding-bottom: 15px;
}
.section:last-child {
border-bottom: none;
margin-bottom: 0;
padding-bottom: 0;
}
.section-title {
font-size: 18px;
color: #004990;
margin-bottom: 15px;
font-weight: 600;
}
.info-row {
display: flex;
flex-wrap: wrap;
margin-bottom: 10px;
}
.info-item {
width: 48%;
margin-bottom: 15px;
}
.label {
font-weight: 600;
color: #555;
font-size: 14px;
display: block;
margin-bottom: 5px;
}
.value {
color: #333;
font-size: 16px;
}
.highlight {
background-color: #f8f9fa;
border-left: 3px solid #0072b0;
padding: 10px 15px;
margin: 15px 0;
}
.map-link {
display: inline-block;
margin-top: 10px;
color: #0072b0;
text-decoration: none;
font-weight: 500;
}
.map-link:hover {
text-decoration: underline;
}
.footer {
text-align: center;
padding: 15px;
font-size: 12px;
color: #777;
background-color: #f8f9fa;
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>Kontakty</h1>
</div>
<div class="content">
<div class="section">
<div class="section-title">Seznam kontaktů</div>
<div class="info-row">
<div class="info-item">
<span class="label">Jméno</span>
<span class="value">Jan Novák</span>
</div>
<div class="info-item">
<span class="label">Pozice</span>
<span class="value">Ředitel</span>
</div>
</div>
<div class="info-row">
<div class="info-item">
<span class="label">Telefon</span>
<span class="value">+420 123 456 789</span>
</div>
<div class="info-item">
<span class="label">Služební telefon</span>
<span class="value">+420 987 654 321</span>
</div>
</div>
<div class="highlight">
<span class="label">Stůl</span>
<span class="value">1</span>
</div>
</div>
</div>
<div class="footer">
&copy; 2025 Poppe + Potthoff - Automaticky generovaný email
</div>
</div>
</body>
</html>
`
}
func main() { func main() {
log.SetFlags(log.LstdFlags | log.Lshortfile) log.SetFlags(log.LstdFlags | log.Lshortfile)
@@ -207,22 +43,26 @@ func main() {
w.Write([]byte(`{"status":"ok"}`)) w.Write([]byte(`{"status":"ok"}`))
})) }))
http.HandleFunc("/contacts", enableCORS(handleContacts))
http.HandleFunc("/reload", enableCORS(handleReload))
http.HandleFunc("/", enableCORS(func(w http.ResponseWriter, r *http.Request) { http.HandleFunc("/", enableCORS(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/kontakty" { http.ServeFile(w, r, "index.html")
w.Header().Set("Content-Type", "text/html")
w.Write([]byte(getEmbeddedHTML()))
return
}
http.ServeFile(w, r, r.URL.Path[1:])
})) }))
http.HandleFunc("/evidence-aut", enableCORS(func(w http.ResponseWriter, r *http.Request) { http.HandleFunc("/evidence-aut", enableCORS(func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "evidence-aut.html") http.ServeFile(w, r, "evidence-aut.html")
})) }))
http.HandleFunc("/kontakt", enableCORS(func(w http.ResponseWriter, r *http.Request) {
// Run make dev in the kontakt directory
cmd := exec.Command("make", "dev")
cmd.Dir = "kontakt"
err := cmd.Start()
if err != nil {
log.Printf("Error running make dev: %v", err)
}
http.ServeFile(w, r, "kontakt/index.html")
}))
port := os.Getenv("PORT") port := os.Getenv("PORT")
if port == "" { if port == "" {
port = "80" port = "80"
@@ -299,16 +139,19 @@ func handleSubmit(w http.ResponseWriter, r *http.Request) {
return return
} }
// Formátování dat do českého formátu
czechMonths := []string{ czechMonths := []string{
"ledna", "února", "března", "dubna", "května", "června", "ledna", "února", "března", "dubna", "května", "června",
"července", "srpna", "září", "října", "listopadu", "prosince", "července", "srpna", "září", "října", "listopadu", "prosince",
} }
// Zpracování začátku cesty
parsedDateStart, err := time.Parse("2006-01-02", entry.DateStart) parsedDateStart, err := time.Parse("2006-01-02", entry.DateStart)
if err != nil { if err != nil {
log.Printf("Chyba při parsování data začátku: %v", err) log.Printf("Chyba při parsování data začátku: %v", err)
} }
// Zpracování konce cesty
parsedDateEnd, err := time.Parse("2006-01-02", entry.DateEnd) parsedDateEnd, err := time.Parse("2006-01-02", entry.DateEnd)
if err != nil { if err != nil {
log.Printf("Chyba při parsování data konce: %v", err) log.Printf("Chyba při parsování data konce: %v", err)
@@ -483,6 +326,7 @@ func sendEmail(entry TripEntry, parsedDateStart, parsedDateEnd time.Time, czechM
<div class="content"> <div class="content">
`) `)
// Formátování dat a časů pro zobrazení
formattedDateStart := "" formattedDateStart := ""
if parsedDateStart.IsZero() == false { if parsedDateStart.IsZero() == false {
monthNameStart := czechMonths[parsedDateStart.Month()-1] monthNameStart := czechMonths[parsedDateStart.Month()-1]
@@ -499,6 +343,7 @@ func sendEmail(entry TripEntry, parsedDateStart, parsedDateEnd time.Time, czechM
formattedDateEnd = entry.DateEnd formattedDateEnd = entry.DateEnd
} }
// Výpočet celkové doby jízdy
startDateTime, startErr := time.Parse("2006-01-02T15:04", fmt.Sprintf("%sT%s", entry.DateStart, entry.TimeStart)) startDateTime, startErr := time.Parse("2006-01-02T15:04", fmt.Sprintf("%sT%s", entry.DateStart, entry.TimeStart))
endDateTime, endErr := time.Parse("2006-01-02T15:04", fmt.Sprintf("%sT%s", entry.DateEnd, entry.TimeEnd)) endDateTime, endErr := time.Parse("2006-01-02T15:04", fmt.Sprintf("%sT%s", entry.DateEnd, entry.TimeEnd))
@@ -524,6 +369,7 @@ func sendEmail(entry TripEntry, parsedDateStart, parsedDateEnd time.Time, czechM
} }
} }
// Vypsání informací o řidiči a vozidle
htmlContent.WriteString(`<div class="section"> htmlContent.WriteString(`<div class="section">
<div class="section-title">Informace o řidiči a vozidle</div> <div class="section-title">Informace o řidiči a vozidle</div>
<div class="info-row"> <div class="info-row">
@@ -538,6 +384,7 @@ func sendEmail(entry TripEntry, parsedDateStart, parsedDateEnd time.Time, czechM
</div> </div>
</div>`) </div>`)
// Vypsání informací o trase
htmlContent.WriteString(`<div class="section"> htmlContent.WriteString(`<div class="section">
<div class="section-title">Informace o trase</div> <div class="section-title">Informace o trase</div>
<div class="info-row"> <div class="info-row">
@@ -552,6 +399,7 @@ func sendEmail(entry TripEntry, parsedDateStart, parsedDateEnd time.Time, czechM
</div> </div>
</div>`) </div>`)
// Vypsání informací o času
htmlContent.WriteString(`<div class="section"> htmlContent.WriteString(`<div class="section">
<div class="section-title">Časové údaje</div> <div class="section-title">Časové údaje</div>
<div class="info-row"> <div class="info-row">
@@ -570,6 +418,7 @@ func sendEmail(entry TripEntry, parsedDateStart, parsedDateEnd time.Time, czechM
</div> </div>
</div>`) </div>`)
// Vypsání informací o kilometrech
htmlContent.WriteString(`<div class="section"> htmlContent.WriteString(`<div class="section">
<div class="section-title">Stav tachometru</div> <div class="section-title">Stav tachometru</div>
<div class="info-row"> <div class="info-row">
@@ -620,11 +469,3 @@ func sendEmail(entry TripEntry, parsedDateStart, parsedDateEnd time.Time, czechM
return d.DialAndSend(m) return d.DialAndSend(m)
} }
func handleContacts(w http.ResponseWriter, r *http.Request) {
// Implement contact listing logic
}
func handleReload(w http.ResponseWriter, r *http.Request) {
// Implement contact reload logic
}