1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 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
120
121
122
123
124
125
126
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
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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
package main

import (
	"database/sql"
	"encoding/json"
	"fmt"
	"os"
)

// TimeEntryJSON represents a time entry in the import JSON format
type TimeEntryJSON struct {
	Date     string `json:"date"`               // YYYY-MM-DD format
	Start    string `json:"start"`              // HH:MM format
	End      string `json:"end"`                // HH:MM format
	Timezone string `json:"timezone,omitempty"` // Optional timezone (e.g., "UTC", "Europe/Berlin"), defaults to local
	Comment  string `json:"comment,omitempty"`  // Optional comment
}

// ImportStats tracks statistics for a client import operation
type ImportStats struct {
	TotalEntries      int
	Imported          int
	SkippedOverlap    int
	SkippedOpenExists int
	SkippedInvalid    int
	OverlapDetails    []string
	InvalidDetails    []string
}

// importClient imports time entries from a JSON file into an existing or new client.
// Supports open timestamps (missing end time) and overlap detection.
// If shortcode is provided and a new client is created, it will be assigned that shortcode.
func importClient(db *sql.DB, clientName string, jsonPath string, shortcode string) error {
	// Read JSON file
	data, err := os.ReadFile(jsonPath)
	if err != nil {
		return fmt.Errorf("failed to read JSON file: %w", err)
	}

	// Parse JSON
	var entries []TimeEntryJSON
	if err := json.Unmarshal(data, &entries); err != nil {
		return fmt.Errorf("failed to parse JSON: %w", err)
	}

	// Check if client exists using normalized name lookup
	existingClient, exactMatch, err := GetClientByNormalizedName(db, clientName)
	if err != nil {
		return fmt.Errorf("failed to look up client: %w", err)
	}

	// If client exists but name doesn't match exactly, show error with correct name
	if existingClient != nil && !exactMatch {
		return fmt.Errorf("client '%s' already exists, please use the exact name '%s' to import to that client", existingClient.Name, existingClient.Name)
	}

	// If client doesn't exist, shortcode is required
	if existingClient == nil && shortcode == "" {
		return fmt.Errorf("shortcode is required when creating a new client (e.g., 'NP' for NewPipe)")
	}

	// Begin transaction for atomic import
	tx, err := db.Begin()
	if err != nil {
		return fmt.Errorf("failed to begin transaction: %w", err)
	}
	// Ensure rollback on error
	defer func() {
		if err != nil {
			tx.Rollback()
		}
	}()

	var clientID int64
	if existingClient != nil {
		clientID = existingClient.ID
		fmt.Printf("Found existing client '%s' (ID: %d)\n", clientName, clientID)
	} else {
		// Create new client within transaction (shortcode is guaranteed non-empty here)
		result, err := tx.Exec("INSERT INTO clients (name, shortcode, target_hours) VALUES (?, ?, 40.0)", clientName, shortcode)
		if err != nil {
			return fmt.Errorf("failed to create client: %w", err)
		}
		clientID, err = result.LastInsertId()
		if err != nil {
			return fmt.Errorf("failed to get client ID: %w", err)
		}
		fmt.Printf("Created new client '%s' with shortcode '%s' (ID: %d)\n", clientName, shortcode, clientID)
	}

	// Track import statistics
	stats := ImportStats{TotalEntries: len(entries)}

	// Process each entry
	for i, entry := range entries {
		// Validate and parse start time
		if entry.Date == "" || entry.Start == "" {
			stats.SkippedInvalid++
			stats.InvalidDetails = append(stats.InvalidDetails,
				fmt.Sprintf("Entry %d: missing date or start time", i+1))
			continue
		}

		startTime, err := parseDateTime(entry.Date, entry.Start, entry.Timezone)
		if err != nil {
			stats.SkippedInvalid++
			stats.InvalidDetails = append(stats.InvalidDetails,
				fmt.Sprintf("Entry %d: %v", i+1, err))
			continue
		}

		// Handle missing end time (open timestamp)
		var endTime int64
		var endTimePtr *int64
		if entry.End == "" {
			// Check if there's already an open entry
			hasOpen, err := HasOpenEntry(db, clientID)
			if err != nil {
				return fmt.Errorf("failed to check for open entries: %w", err)
			}
			if hasOpen {
				stats.SkippedOpenExists++
				stats.InvalidDetails = append(stats.InvalidDetails,
					fmt.Sprintf("Entry %d (%s %s): skipped open entry, client already has an open timestamp",
						i+1, entry.Date, entry.Start))
				continue
			}
			endTime = 0
			endTimePtr = nil
		} else {
			// Parse end time
			parsedEndTime, err := parseDateTime(entry.Date, entry.End, entry.Timezone)
			if err != nil {
				stats.SkippedInvalid++
				stats.InvalidDetails = append(stats.InvalidDetails,
					fmt.Sprintf("Entry %d: %v", i+1, err))
				continue
			}

			// If end time is before start time on the same date, assume it crosses midnight
			if parsedEndTime <= startTime {
				parsedEndTime += 24 * 3600 // Add 24 hours
			}

			endTime = parsedEndTime
			endTimePtr = &endTime
		}

		// Check for overlap with existing entries
		hasOverlap, err := CheckTimeOverlap(db, clientID, startTime, endTime)
		if err != nil {
			return fmt.Errorf("failed to check time overlap: %w", err)
		}
		if hasOverlap {
			stats.SkippedOverlap++
			if endTimePtr == nil {
				stats.OverlapDetails = append(stats.OverlapDetails,
					fmt.Sprintf("%s %s (open)", entry.Date, entry.Start))
			} else {
				stats.OverlapDetails = append(stats.OverlapDetails,
					fmt.Sprintf("%s %s-%s", entry.Date, entry.Start, entry.End))
			}
			continue
		}

		// Insert entry using transaction
		if endTimePtr == nil {
			_, err = tx.Exec(
				"INSERT INTO time_entries (client_id, start_time, end_time, comment) VALUES (?, ?, NULL, ?)",
				clientID, startTime, entry.Comment,
			)
		} else {
			_, err = tx.Exec(
				"INSERT INTO time_entries (client_id, start_time, end_time, comment) VALUES (?, ?, ?, ?)",
				clientID, startTime, *endTimePtr, entry.Comment,
			)
		}
		if err != nil {
			return fmt.Errorf("failed to insert entry %d: %w", i+1, err)
		}

		stats.Imported++
	}

	// Commit the transaction
	if err := tx.Commit(); err != nil {
		return fmt.Errorf("failed to commit import transaction: %w", err)
	}

	// Print detailed summary
	fmt.Printf("\n═══ Import Summary for '%s' ═══\n", clientName)
	fmt.Printf("Total entries in file: %d\n", stats.TotalEntries)
	fmt.Printf("✓ Successfully imported: %d\n", stats.Imported)

	if stats.SkippedOverlap > 0 {
		fmt.Printf("⊘ Skipped (overlap): %d\n", stats.SkippedOverlap)
		for _, detail := range stats.OverlapDetails {
			fmt.Printf("  - %s\n", detail)
		}
	}

	if stats.SkippedOpenExists > 0 {
		fmt.Printf("⊘ Skipped (open entry exists): %d\n", stats.SkippedOpenExists)
	}

	if stats.SkippedInvalid > 0 {
		fmt.Printf("✗ Skipped (invalid): %d\n", stats.SkippedInvalid)
		for _, detail := range stats.InvalidDetails {
			fmt.Printf("  - %s\n", detail)
		}
	}

	fmt.Println("═══════════════════════════════")
	return nil
}

// printUsage prints the command-line usage information
func printUsage() {
	fmt.Fprintf(os.Stderr, `Usage:
  timetrack [database]                                              Start TUI with optional database path
  timetrack migrate <database>                                      Run database migrations
  timetrack import-client <database> <name> <json-file> [shortcode] Import client from JSON file

The JSON file should contain an array of time entries:
[
  {"date": "2025-10-18", "start": "10:00", "end": "18:00", "timezone": "UTC", "comment": "Optional description"},
  {"date": "2025-10-17", "start": "09:00", "end": "17:00"}
]

The timezone field is optional and defaults to local time if not specified.
Supported timezone names: "UTC", "Europe/Berlin", "America/New_York", etc.

The shortcode parameter is required when creating a new client (e.g., 'NP' for NewPipe).
It is used to generate unique invoice numbers (e.g., NP-2025-001). When appending to
an existing client, the shortcode parameter is ignored.
`)
}