-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.go
More file actions
382 lines (330 loc) · 9.19 KB
/
app.go
File metadata and controls
382 lines (330 loc) · 9.19 KB
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
package main
// raven built this
// https://github.com/ravvdevv
import (
"context"
"database/sql"
"fmt"
"os"
"path/filepath"
_ "modernc.org/sqlite"
"github.com/wailsapp/wails/v2/pkg/runtime"
)
// App struct
type App struct {
ctx context.Context
db *sql.DB
}
// NewApp creates a new App application struct
func NewApp() *App {
return &App{}
}
// startup is called when the app starts. The context is saved
// so we can call the runtime methods
func (a *App) startup(ctx context.Context) {
a.ctx = ctx
// Use a persistent path for the database
home, _ := os.UserHomeDir()
dbPath := filepath.Join(home, ".stockly", "stockly.db")
os.MkdirAll(filepath.Dir(dbPath), 0755)
db, err := sql.Open("sqlite", dbPath)
if err != nil {
fmt.Printf("Error opening database: %v\n", err)
return
}
a.db = db
a.initDB()
}
func (a *App) initDB() {
queries := []string{
`CREATE TABLE IF NOT EXISTS categories (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
description TEXT,
createdAt TEXT
)`,
`CREATE TABLE IF NOT EXISTS products (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
sku TEXT UNIQUE NOT NULL,
category TEXT,
price REAL,
stock INTEGER,
createdAt TEXT
)`,
`CREATE TABLE IF NOT EXISTS sales (
id TEXT PRIMARY KEY,
subtotal REAL,
tax REAL,
taxRate REAL,
total REAL,
paymentMethod TEXT,
amountTendered REAL,
changeDue REAL,
createdAt TEXT
)`,
`CREATE TABLE IF NOT EXISTS sale_items (
id INTEGER PRIMARY KEY AUTOINCREMENT,
saleId TEXT,
productId TEXT,
productName TEXT,
quantity INTEGER,
price REAL,
FOREIGN KEY(saleId) REFERENCES sales(id)
)`,
`CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
)`,
}
for _, q := range queries {
_, err := a.db.Exec(q)
if err != nil {
fmt.Printf("Error creating table: %v\n", err)
}
}
}
// Product models
type Product struct {
ID string `json:"id"`
Name string `json:"name"`
SKU string `json:"sku"`
Category string `json:"category"`
Price float64 `json:"price"`
Stock int `json:"stock"`
CreatedAt string `json:"createdAt"`
}
type SaleItem struct {
ProductID string `json:"productId"`
ProductName string `json:"productName"`
Quantity int `json:"quantity"`
Price float64 `json:"price"`
}
type Sale struct {
ID string `json:"id"`
Items []SaleItem `json:"items"`
Subtotal float64 `json:"subtotal"`
Tax float64 `json:"tax"`
TaxRate float64 `json:"taxRate"`
Total float64 `json:"total"`
PaymentMethod string `json:"paymentMethod"`
AmountTendered float64 `json:"amountTendered"`
ChangeDue float64 `json:"change"`
CreatedAt string `json:"createdAt"`
}
type Category struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
CreatedAt string `json:"createdAt"`
}
// Product Methods
func (a *App) GetProducts() []Product {
rows, err := a.db.Query("SELECT id, name, sku, category, price, stock, createdAt FROM products")
if err != nil {
return []Product{}
}
defer rows.Close()
var products []Product
for rows.Next() {
var p Product
rows.Scan(&p.ID, &p.Name, &p.SKU, &p.Category, &p.Price, &p.Stock, &p.CreatedAt)
products = append(products, p)
}
return products
}
func (a *App) AddProduct(p Product) error {
_, err := a.db.Exec("INSERT INTO products (id, name, sku, category, price, stock, createdAt) VALUES (?, ?, ?, ?, ?, ?, ?)",
p.ID, p.Name, p.SKU, p.Category, p.Price, p.Stock, p.CreatedAt)
return err
}
func (a *App) UpdateProduct(p Product) error {
_, err := a.db.Exec("UPDATE products SET name=?, sku=?, category=?, price=?, stock=? WHERE id=?",
p.Name, p.SKU, p.Category, p.Price, p.Stock, p.ID)
return err
}
func (a *App) DeleteProduct(id string) error {
_, err := a.db.Exec("DELETE FROM products WHERE id=?", id)
return err
}
// Sale Methods
func (a *App) GetSales() []Sale {
rows, err := a.db.Query("SELECT id, subtotal, tax, taxRate, total, paymentMethod, amountTendered, changeDue, createdAt FROM sales")
if err != nil {
return []Sale{}
}
defer rows.Close()
var sales []Sale
for rows.Next() {
var s Sale
rows.Scan(&s.ID, &s.Subtotal, &s.Tax, &s.TaxRate, &s.Total, &s.PaymentMethod, &s.AmountTendered, &s.ChangeDue, &s.CreatedAt)
// Get items for this sale
itemRows, err := a.db.Query("SELECT productId, productName, quantity, price FROM sale_items WHERE saleId = ?", s.ID)
if err == nil {
for itemRows.Next() {
var item SaleItem
itemRows.Scan(&item.ProductID, &item.ProductName, &item.Quantity, &item.Price)
s.Items = append(s.Items, item)
}
itemRows.Close()
}
sales = append(sales, s)
}
return sales
}
func (a *App) CompleteSale(s Sale) error {
tx, err := a.db.Begin()
if err != nil {
return err
}
_, err = tx.Exec("INSERT INTO sales (id, subtotal, tax, taxRate, total, paymentMethod, amountTendered, changeDue, createdAt) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
s.ID, s.Subtotal, s.Tax, s.TaxRate, s.Total, s.PaymentMethod, s.AmountTendered, s.ChangeDue, s.CreatedAt)
if err != nil {
tx.Rollback()
return err
}
for _, item := range s.Items {
_, err = tx.Exec("INSERT INTO sale_items (saleId, productId, productName, quantity, price) VALUES (?, ?, ?, ?, ?)",
s.ID, item.ProductID, item.ProductName, item.Quantity, item.Price)
if err != nil {
tx.Rollback()
return err
}
// Update stock
_, err = tx.Exec("UPDATE products SET stock = stock - ? WHERE id = ?", item.Quantity, item.ProductID)
if err != nil {
tx.Rollback()
return err
}
}
return tx.Commit()
}
// Category Methods
func (a *App) GetCategories() []Category {
rows, err := a.db.Query("SELECT id, name, description, createdAt FROM categories")
if err != nil {
return []Category{}
}
defer rows.Close()
var categories []Category
for rows.Next() {
var c Category
rows.Scan(&c.ID, &c.Name, &c.Description, &c.CreatedAt)
categories = append(categories, c)
}
return categories
}
func (a *App) SaveCategory(c Category) error {
_, err := a.db.Exec("INSERT OR REPLACE INTO categories (id, name, description, createdAt) VALUES (?, ?, ?, ?)",
c.ID, c.Name, c.Description, c.CreatedAt)
return err
}
func (a *App) RenameCategory(oldName string, newName string) error {
tx, err := a.db.Begin()
if err != nil {
return err
}
// Update category name
_, err = tx.Exec("UPDATE categories SET name=? WHERE name=?", newName, oldName)
if err != nil {
tx.Rollback()
return err
}
// Update all products with this category
_, err = tx.Exec("UPDATE products SET category=? WHERE category=?", newName, oldName)
if err != nil {
tx.Rollback()
return err
}
return tx.Commit()
}
func (a *App) DeleteCategory(id string) error {
_, err := a.db.Exec("DELETE FROM categories WHERE id=?", id)
return err
}
// GetTaxRate retrieves the current tax rate from settings
func (a *App) GetTaxRate() (float64, error) {
var rateStr string
err := a.db.QueryRow("SELECT value FROM settings WHERE key = 'tax_rate'").Scan(&rateStr)
if err == sql.ErrNoRows {
// Initialize with default 12% if not set
a.SaveTaxRate(12.0)
return 12.0, nil
}
if err != nil {
return 0, err
}
var rate float64
fmt.Sscanf(rateStr, "%f", &rate)
return rate, nil
}
// SaveTaxRate updates the global tax rate in settings
func (a *App) SaveTaxRate(rate float64) error {
_, err := a.db.Exec("INSERT OR REPLACE INTO settings (key, value) VALUES ('tax_rate', ?)", fmt.Sprintf("%.2f", rate))
return err
}
// ExportDatabase allows the user to save a backup of the current database
func (a *App) ExportDatabase() error {
home, _ := os.UserHomeDir()
dbPath := filepath.Join(home, ".stockly", "stockly.db")
targetPath, err := runtime.SaveFileDialog(a.ctx, runtime.SaveDialogOptions{
Title: "Export Database Backup",
DefaultFilename: "stockly_backup.db",
Filters: []runtime.FileFilter{
{DisplayName: "SQLite Database (*.db)", Pattern: "*.db"},
},
})
if err != nil || targetPath == "" {
return err
}
data, err := os.ReadFile(dbPath)
if err != nil {
return err
}
return os.WriteFile(targetPath, data, 0644)
}
// ImportDatabase allows the user to restore a backup
func (a *App) ImportDatabase() error {
sourcePath, err := runtime.OpenFileDialog(a.ctx, runtime.OpenDialogOptions{
Title: "Import Database Backup",
Filters: []runtime.FileFilter{
{DisplayName: "SQLite Database (*.db)", Pattern: "*.db"},
},
})
if err != nil || sourcePath == "" {
return err
}
data, err := os.ReadFile(sourcePath)
if err != nil {
return err
}
// Close current DB to replace the file
a.db.Close()
home, _ := os.UserHomeDir()
dbPath := filepath.Join(home, ".stockly", "stockly.db")
err = os.WriteFile(dbPath, data, 0644)
if err != nil {
// Attempt to re-open even if write failed
db, _ := sql.Open("sqlite", dbPath)
a.db = db
return err
}
// Re-open
db, err := sql.Open("sqlite", dbPath)
if err != nil {
return err
}
a.db = db
return nil
}
// ResetDatabase clears all business data from the app
func (a *App) ResetDatabase() error {
tables := []string{"sale_items", "sales", "products", "categories"}
for _, table := range tables {
_, err := a.db.Exec(fmt.Sprintf("DELETE FROM %s", table))
if err != nil {
return err
}
}
return nil
}