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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
package main

import (
	"database/sql"
	"fmt"
	"strings"
	"time"
)

// Invoice represents an invoice with metadata
type Invoice struct {
	ID            int64
	ClientID      int64
	InvoiceNumber string
	CreatedAt     int64
	SentAt        sql.NullInt64
	PaidAt        sql.NullInt64
	TotalHours    float64
	HourlyRate    sql.NullFloat64
	TotalAmount   sql.NullFloat64
	Currency      string
	Notes         string
	Status        string
}

// InvoiceLineItem represents a single line item on an invoice (immutable snapshot)
type InvoiceLineItem struct {
	ID            int64
	InvoiceID     int64
	Date          string
	StartTime     int64
	EndTime       sql.NullInt64
	Hours         float64
	Description   string
	SourceEntryID sql.NullInt64
}

// InvoiceWithItems combines an invoice with its line items
type InvoiceWithItems struct {
	Invoice
	LineItems []InvoiceLineItem
}

// GenerateInvoiceNumber generates a unique invoice number in SHORTCODE-YYYY-NNN format
// where SHORTCODE is the client's invoice prefix, YYYY is the current year, and NNN is
// a sequential number starting from 001 for that client+year combination.
func GenerateInvoiceNumber(db *sql.DB, shortcode string) (string, error) {
	if shortcode == "" {
		return "", fmt.Errorf("client shortcode is required for invoice number generation")
	}

	currentYear := time.Now().Year()
	prefix := fmt.Sprintf("%s-%d", shortcode, currentYear)

	// Find the highest invoice number for this client+year combination
	var maxNumber sql.NullInt64
	query := `
		SELECT MAX(CAST(SUBSTR(invoice_number, LENGTH(?) + 2) AS INTEGER))
		FROM invoices
		WHERE invoice_number LIKE ? || '-%'
	`
	err := db.QueryRow(query, prefix, prefix).Scan(&maxNumber)
	if err != nil && err != sql.ErrNoRows {
		return "", fmt.Errorf("failed to query max invoice number: %w", err)
	}

	nextNumber := 1
	if maxNumber.Valid {
		nextNumber = int(maxNumber.Int64) + 1
	}

	return fmt.Sprintf("%s-%03d", prefix, nextNumber), nil
}

// GetUninvoicedEntries returns all time entries for a client that haven't been invoiced yet
func GetUninvoicedEntries(db *sql.DB, clientID int64) ([]TimeEntry, error) {
	rows, err := db.Query(`
		SELECT id, client_id, start_time, end_time, comment
		FROM time_entries
		WHERE client_id = ? AND invoice_id IS NULL AND end_time IS NOT NULL
		ORDER BY start_time
	`, clientID)
	if err != nil {
		return nil, fmt.Errorf("failed to query uninvoiced entries: %w", err)
	}
	defer rows.Close()

	var entries []TimeEntry
	for rows.Next() {
		var entry TimeEntry
		if err := rows.Scan(&entry.ID, &entry.ClientID, &entry.StartTime, &entry.EndTime, &entry.Comment); err != nil {
			return nil, fmt.Errorf("failed to scan entry: %w", err)
		}
		entries = append(entries, entry)
	}

	if err := rows.Err(); err != nil {
		return nil, fmt.Errorf("error iterating entries: %w", err)
	}

	return entries, nil
}

// CreateInvoice creates a new invoice with the specified time entries.
// This function creates the invoice, snapshots the time entries as line items,
// and marks the source entries as invoiced - all atomically.
func CreateInvoice(db *sql.DB, clientID int64, entryIDs []int64, hourlyRate *float64, notes string) (*Invoice, error) {
	if len(entryIDs) == 0 {
		return nil, fmt.Errorf("cannot create invoice with no entries")
	}

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

	// Get client shortcode for invoice number generation
	var shortcode string
	err = db.QueryRow("SELECT shortcode FROM clients WHERE id = ?", clientID).Scan(&shortcode)
	if err != nil {
		return nil, fmt.Errorf("failed to get client shortcode: %w", err)
	}
	if shortcode == "" {
		return nil, fmt.Errorf("client must have a shortcode before creating invoices")
	}

	// Generate invoice number with client shortcode
	invoiceNumber, err := GenerateInvoiceNumber(db, shortcode)
	if err != nil {
		return nil, fmt.Errorf("failed to generate invoice number: %w", err)
	}

	// Fetch the time entries to be invoiced
	var placeholders strings.Builder
	args := []any{clientID}
	for i, entryID := range entryIDs {
		if i > 0 {
			placeholders.WriteString(",")
		}
		placeholders.WriteString("?")
		args = append(args, entryID)
	}

	query := fmt.Sprintf(`
		SELECT id, client_id, start_time, end_time, comment
		FROM time_entries
		WHERE client_id = ? AND id IN (%s) AND invoice_id IS NULL AND end_time IS NOT NULL
	`, placeholders.String())

	rows, err := tx.Query(query, args...)
	if err != nil {
		return nil, fmt.Errorf("failed to query entries: %w", err)
	}

	var entries []TimeEntry
	for rows.Next() {
		var entry TimeEntry
		if err := rows.Scan(&entry.ID, &entry.ClientID, &entry.StartTime, &entry.EndTime, &entry.Comment); err != nil {
			rows.Close()
			return nil, fmt.Errorf("failed to scan entry: %w", err)
		}
		entries = append(entries, entry)
	}
	rows.Close()

	if len(entries) == 0 {
		return nil, fmt.Errorf("no valid uninvoiced entries found")
	}

	if len(entries) != len(entryIDs) {
		return nil, fmt.Errorf("some entries are already invoiced or don't exist")
	}

	// Calculate total hours
	var totalHours float64
	for _, entry := range entries {
		if entry.EndTime.Valid {
			durationSeconds := entry.EndTime.Int64 - entry.StartTime
			totalHours += float64(durationSeconds) / 3600.0
		}
	}

	// Calculate total amount if hourly rate provided
	var totalAmount sql.NullFloat64
	if hourlyRate != nil {
		totalAmount = sql.NullFloat64{Float64: totalHours * (*hourlyRate), Valid: true}
	}

	// Create invoice record
	result, err := tx.Exec(`
		INSERT INTO invoices (client_id, invoice_number, created_at, total_hours, hourly_rate, total_amount, notes, status)
		VALUES (?, ?, ?, ?, ?, ?, ?, 'draft')
	`, clientID, invoiceNumber, time.Now().Unix(), totalHours, hourlyRate, totalAmount, notes)
	if err != nil {
		return nil, fmt.Errorf("failed to create invoice: %w", err)
	}

	invoiceID, err := result.LastInsertId()
	if err != nil {
		return nil, fmt.Errorf("failed to get invoice ID: %w", err)
	}

	// Create invoice line items (immutable snapshots)
	for _, entry := range entries {
		hours := float64(0)
		if entry.EndTime.Valid {
			hours = float64(entry.EndTime.Int64-entry.StartTime) / 3600.0
		}

		_, err = tx.Exec(`
			INSERT INTO invoice_line_items (invoice_id, date, start_time, end_time, hours, description, source_entry_id)
			VALUES (?, ?, ?, ?, ?, ?, ?)
		`,
			invoiceID,
			timestampToDate(entry.StartTime),
			entry.StartTime,
			entry.EndTime,
			hours,
			entry.Comment,
			entry.ID,
		)
		if err != nil {
			return nil, fmt.Errorf("failed to create line item: %w", err)
		}

		// Mark source entry as invoiced
		_, err = tx.Exec(`
			UPDATE time_entries
			SET invoice_id = ?
			WHERE id = ?
		`, invoiceID, entry.ID)
		if err != nil {
			return nil, fmt.Errorf("failed to mark entry as invoiced: %w", err)
		}
	}

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

	// Return the created invoice
	invoice := &Invoice{
		ID:            invoiceID,
		ClientID:      clientID,
		InvoiceNumber: invoiceNumber,
		CreatedAt:     time.Now().Unix(),
		TotalHours:    totalHours,
		Status:        "draft",
		Notes:         notes,
	}

	if hourlyRate != nil {
		invoice.HourlyRate = sql.NullFloat64{Float64: *hourlyRate, Valid: true}
		invoice.TotalAmount = totalAmount
	}

	return invoice, nil
}

// GetInvoiceWithItems loads a complete invoice with all its line items
func GetInvoiceWithItems(db *sql.DB, invoiceID int64) (*InvoiceWithItems, error) {
	// Load invoice
	var invoice Invoice
	err := db.QueryRow(`
		SELECT id, client_id, invoice_number, created_at, sent_at, paid_at,
		       total_hours, hourly_rate, total_amount, currency, notes, status
		FROM invoices
		WHERE id = ?
	`, invoiceID).Scan(
		&invoice.ID, &invoice.ClientID, &invoice.InvoiceNumber, &invoice.CreatedAt,
		&invoice.SentAt, &invoice.PaidAt, &invoice.TotalHours, &invoice.HourlyRate,
		&invoice.TotalAmount, &invoice.Currency, &invoice.Notes, &invoice.Status,
	)
	if err == sql.ErrNoRows {
		return nil, fmt.Errorf("invoice not found")
	}
	if err != nil {
		return nil, fmt.Errorf("failed to load invoice: %w", err)
	}

	// Load line items
	rows, err := db.Query(`
		SELECT id, invoice_id, date, start_time, end_time, hours, description, source_entry_id
		FROM invoice_line_items
		WHERE invoice_id = ?
		ORDER BY start_time
	`, invoiceID)
	if err != nil {
		return nil, fmt.Errorf("failed to query line items: %w", err)
	}
	defer rows.Close()

	var lineItems []InvoiceLineItem
	for rows.Next() {
		var item InvoiceLineItem
		if err := rows.Scan(&item.ID, &item.InvoiceID, &item.Date, &item.StartTime, &item.EndTime, &item.Hours, &item.Description, &item.SourceEntryID); err != nil {
			return nil, fmt.Errorf("failed to scan line item: %w", err)
		}
		lineItems = append(lineItems, item)
	}

	if err := rows.Err(); err != nil {
		return nil, fmt.Errorf("error iterating line items: %w", err)
	}

	return &InvoiceWithItems{
		Invoice:   invoice,
		LineItems: lineItems,
	}, nil
}

// ListInvoices returns all invoices for a client, ordered by creation date descending
func ListInvoices(db *sql.DB, clientID int64) ([]Invoice, error) {
	rows, err := db.Query(`
		SELECT id, client_id, invoice_number, created_at, sent_at, paid_at,
		       total_hours, hourly_rate, total_amount, currency, notes, status
		FROM invoices
		WHERE client_id = ?
		ORDER BY created_at DESC
	`, clientID)
	if err != nil {
		return nil, fmt.Errorf("failed to query invoices: %w", err)
	}
	defer rows.Close()

	var invoices []Invoice
	for rows.Next() {
		var invoice Invoice
		if err := rows.Scan(
			&invoice.ID, &invoice.ClientID, &invoice.InvoiceNumber, &invoice.CreatedAt,
			&invoice.SentAt, &invoice.PaidAt, &invoice.TotalHours, &invoice.HourlyRate,
			&invoice.TotalAmount, &invoice.Currency, &invoice.Notes, &invoice.Status,
		); err != nil {
			return nil, fmt.Errorf("failed to scan invoice: %w", err)
		}
		invoices = append(invoices, invoice)
	}

	if err := rows.Err(); err != nil {
		return nil, fmt.Errorf("error iterating invoices: %w", err)
	}

	return invoices, nil
}

// MarkInvoiceSent updates an invoice's sent_at timestamp and sets status to 'sent'
func MarkInvoiceSent(db *sql.DB, invoiceID int64) error {
	result, err := db.Exec(`
		UPDATE invoices
		SET sent_at = ?, status = 'sent'
		WHERE id = ? AND sent_at IS NULL
	`, time.Now().Unix(), invoiceID)
	if err != nil {
		return fmt.Errorf("failed to mark invoice as sent: %w", err)
	}

	rows, err := result.RowsAffected()
	if err != nil {
		return fmt.Errorf("failed to get rows affected: %w", err)
	}

	if rows == 0 {
		return fmt.Errorf("invoice not found or already sent")
	}

	return nil
}

// MarkInvoicePaid updates an invoice's paid_at timestamp and sets status to 'paid'
func MarkInvoicePaid(db *sql.DB, invoiceID int64) error {
	result, err := db.Exec(`
		UPDATE invoices
		SET paid_at = ?, status = 'paid'
		WHERE id = ? AND paid_at IS NULL
	`, time.Now().Unix(), invoiceID)
	if err != nil {
		return fmt.Errorf("failed to mark invoice as paid: %w", err)
	}

	rows, err := result.RowsAffected()
	if err != nil {
		return fmt.Errorf("failed to get rows affected: %w", err)
	}

	if rows == 0 {
		return fmt.Errorf("invoice not found or already paid")
	}

	return nil
}

// createInvoiceCLI handles the 'create-invoice' command-line operation.
// It loads the specified client, gets all uninvoiced entries, creates an invoice,
// and prints a summary.
func createInvoiceCLI(db *sql.DB, clientName string) error {
	// Get client
	client, err := GetClientByName(db, clientName)
	if err != nil {
		return fmt.Errorf("failed to get client: %w", err)
	}
	if client == nil {
		return fmt.Errorf("client '%s' not found", clientName)
	}

	// Get uninvoiced entries
	entries, err := GetUninvoicedEntries(db, client.ID)
	if err != nil {
		return fmt.Errorf("failed to get uninvoiced entries: %w", err)
	}

	if len(entries) == 0 {
		fmt.Printf("No uninvoiced entries for client '%s'\n", clientName)
		return nil
	}

	// Collect entry IDs
	var entryIDs []int64
	for _, entry := range entries {
		entryIDs = append(entryIDs, entry.ID)
	}

	fmt.Printf("Creating invoice for client '%s' with %d entries\n", clientName, len(entries))

	// Create invoice
	invoice, err := CreateInvoice(db, client.ID, entryIDs, nil, "")
	if err != nil {
		return fmt.Errorf("failed to create invoice: %w", err)
	}

	fmt.Printf("\n✓ Invoice created successfully\n")
	fmt.Printf("  Invoice Number: %s\n", invoice.InvoiceNumber)
	fmt.Printf("  Total Hours: %.2f\n", invoice.TotalHours)
	fmt.Printf("  Status: %s\n", invoice.Status)

	return nil
}