File size: 14,592 Bytes
edcf070
 
 
 
 
 
6c773a6
edcf070
 
 
 
 
 
d3525b4
44f1ca9
edcf070
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3525b4
edcf070
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8afed15
edcf070
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8afed15
edcf070
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8afed15
 
 
 
edcf070
 
 
8afed15
 
 
edcf070
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c773a6
 
 
edcf070
d3525b4
 
 
 
 
edcf070
 
 
 
 
 
 
 
 
 
 
6c773a6
 
edcf070
 
6c773a6
edcf070
6c773a6
 
edcf070
6c773a6
 
 
 
edcf070
6c773a6
 
 
 
edcf070
6c773a6
 
11c1b6f
6c773a6
 
edcf070
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9fc6937
 
 
 
 
 
edcf070
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44f1ca9
 
 
59cc420
 
edcf070
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ffd896
 
 
edcf070
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59cc420
 
 
 
edcf070
 
 
 
 
 
 
59cc420
 
 
 
 
 
 
 
 
edcf070
59cc420
 
edcf070
 
 
 
 
 
 
9fc6937
edcf070
 
 
 
 
 
4ffd896
 
 
edcf070
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8afed15
 
 
 
 
edcf070
 
8afed15
 
edcf070
 
 
 
 
 
 
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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
package controllers

import (
	"fmt"
	"net/http"
	"strconv"
	"strings"

	"service-warungpos-go/config"
	"service-warungpos-go/models"
	"service-warungpos-go/services"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"math/rand"
)

// DTOs untuk Kategori & Produk
type CategoryCreateRequest struct {
	Name        string `json:"name" binding:"required"`
	Description string `json:"description"`
}

type CategoryResponse struct {
	ID          uint      `json:"id"`
	CompanyID   uint      `json:"company_id"`
	Name        string    `json:"name"`
	Description string    `json:"description"`
	CreatedAt   string    `json:"created_at"`
}

type ProductCreateRequest struct {
	Name             string  `json:"name" binding:"required"`
	SKU              *string `json:"sku"`
	Price            int     `json:"price" binding:"required"`
	Stock            int     `json:"stock"`
	IsUnlimitedStock bool    `json:"is_unlimited_stock"`
	CategoryID       *uint   `json:"category_id"`
	ImageURL         string  `json:"image_url"`
}

// ==================== IMAGE UPLOAD ====================

func UploadProductImage(c *gin.Context) {
	file, err := c.FormFile("file")
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"detail": "File tidak ditemukan dalam request"})
		return
	}

	// Validasi jenis file
	allowedTypes := map[string]bool{
		"image/jpeg": true,
		"image/png":  true,
		"image/webp": true,
		"image/gif":  true,
	}

	contentType := file.Header.Get("Content-Type")
	if !allowedTypes[contentType] {
		c.JSON(http.StatusBadRequest, gin.H{"detail": "Hanya file gambar (JPG, PNG, WebP, GIF) yang diizinkan"})
		return
	}

	// Validasi ukuran (maksimal 5MB)
	if file.Size > 5*1024*1024 {
		c.JSON(http.StatusBadRequest, gin.H{"detail": "Ukuran gambar maksimal 5MB"})
		return
	}

	// Upload langsung ke Cloudinary
	secureURL, err := services.UploadToCloudinary(file)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"detail": fmt.Sprintf("Gagal upload gambar: %v", err)})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"image_url": secureURL,
	})
}

// ==================== CATEGORY CONTROLLER ====================

func ListCategories(c *gin.Context) {
	userVal, _ := c.Get("user")
	user := userVal.(*models.User)

	var branchID *uint
	// Periksa query param branch_id
	if qBranchID := c.Query("branch_id"); qBranchID != "" {
		if val, err := strconv.ParseUint(qBranchID, 10, 32); err == nil {
			uVal := uint(val)
			branchID = &uVal
		}
	}

	// Jika kasir, paksa filter berdasarkan branch_id kasir
	if user.Role == "kasir" && user.BranchID != nil {
		branchID = user.BranchID
	}

	var allCategories []models.Category
	if err := config.DB.Select("id, company_id, name, description, created_at").Where("company_id = ?", *user.CompanyID).Find(&allCategories).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"detail": "Gagal mengambil data kategori"})
		return
	}

	// Jika tidak ada filter branch_id, kembalikan semua kategori langsung
	if branchID == nil {
		c.JSON(http.StatusOK, allCategories)
		return
	}

	// Ambil daftar product_id yang tidak tersedia di cabang ini
	var unavailableProductIDs []uint
	config.DB.Model(&models.BranchProduct{}).
		Where("branch_id = ? AND is_available = ?", *branchID, false).
		Pluck("product_id", &unavailableProductIDs)

	// Cari kategori dari produk aktif yang tersedia di cabang ini
	var availableCategoryIDs []uint
	query := config.DB.Model(&models.Product{}).
		Where("company_id = ? AND is_active = ?", *user.CompanyID, true)

	if len(unavailableProductIDs) > 0 {
		query = query.Where("id NOT IN ?", unavailableProductIDs)
	}

	query.Pluck("distinct category_id", &availableCategoryIDs)

	// Filter allCategories agar hanya mengembalikan kategori yang memiliki produk tersedia di cabang
	catMap := make(map[uint]bool)
	for _, catID := range availableCategoryIDs {
		catMap[catID] = true
	}

	var resp []models.Category
	for _, cat := range allCategories {
		if catMap[cat.ID] {
			resp = append(resp, cat)
		}
	}

	c.JSON(http.StatusOK, resp)
}

func GetCategory(c *gin.Context) {
	userVal, _ := c.Get("user")
	user := userVal.(*models.User)

	catIDStr := c.Param("category_id")
	catID, err := strconv.Atoi(catIDStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"detail": "ID kategori tidak valid"})
		return
	}

	var category models.Category
	if err := config.DB.Select("id, company_id, name, description, created_at").Where("id = ? AND company_id = ?", catID, *user.CompanyID).First(&category).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"detail": "Kategori tidak ditemukan"})
		return
	}

	c.JSON(http.StatusOK, category)
}

func CreateCategory(c *gin.Context) {
	userVal, _ := c.Get("user")
	user := userVal.(*models.User)

	var req CategoryCreateRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"detail": err.Error()})
		return
	}

	// Cek duplikasi nama kategori di perusahaan yang sama
	var count int64
	config.DB.Model(&models.Category{}).Where("name = ? AND company_id = ?", req.Name, *user.CompanyID).Count(&count)
	if count > 0 {
		c.JSON(http.StatusBadRequest, gin.H{"detail": fmt.Sprintf("Kategori '%s' sudah ada", req.Name)})
		return
	}

	newCat := models.Category{
		CompanyID:   *user.CompanyID,
		Name:        req.Name,
		Description: req.Description,
	}

	if err := config.DB.Create(&newCat).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"detail": "Gagal menyimpan kategori baru"})
		return
	}

	c.JSON(http.StatusCreated, newCat)
}

func UpdateCategory(c *gin.Context) {
	userVal, _ := c.Get("user")
	user := userVal.(*models.User)

	catIDStr := c.Param("category_id")
	catID, err := strconv.Atoi(catIDStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"detail": "ID kategori tidak valid"})
		return
	}

	var req CategoryCreateRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"detail": err.Error()})
		return
	}

	var category models.Category
	if err := config.DB.Select("id, company_id, name, description").Where("id = ? AND company_id = ?", catID, *user.CompanyID).First(&category).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"detail": "Kategori tidak ditemukan"})
		return
	}

	if req.Name != "" {
		var count int64
		config.DB.Model(&models.Category{}).Where("name = ? AND company_id = ? AND id != ?", req.Name, *user.CompanyID, catID).Count(&count)
		if count > 0 {
			c.JSON(http.StatusBadRequest, gin.H{"detail": fmt.Sprintf("Kategori '%s' sudah ada", req.Name)})
			return
		}
		category.Name = req.Name
	}
	category.Description = req.Description

	if err := config.DB.Save(&category).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"detail": "Gagal meng-update kategori"})
		return
	}

	c.JSON(http.StatusOK, category)
}

func DeleteCategory(c *gin.Context) {
	userVal, _ := c.Get("user")
	user := userVal.(*models.User)

	catIDStr := c.Param("category_id")
	catID, err := strconv.Atoi(catIDStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"detail": "ID kategori tidak valid"})
		return
	}

	var productCount int64
	config.DB.Model(&models.Product{}).Where("category_id = ?", catID).Count(&productCount)
	if productCount > 0 {
		c.JSON(http.StatusBadRequest, gin.H{"detail": fmt.Sprintf("Kategori masih memiliki %d produk. Pindahkan produk dulu.", productCount)})
		return
	}

	var category models.Category
	if err := config.DB.Select("id, name").Where("id = ? AND company_id = ?", catID, *user.CompanyID).First(&category).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"detail": "Kategori tidak ditemukan"})
		return
	}

	if err := config.DB.Delete(&category).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"detail": "Gagal menghapus kategori"})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"message": fmt.Sprintf("Kategori '%s' berhasil dihapus", category.Name),
	})
}

// ==================== PRODUCT CONTROLLER ====================

func ListProducts(c *gin.Context) {
	userVal, _ := c.Get("user")
	user := userVal.(*models.User)

	var branchID *uint
	// Cek filter branch_id query param (owner di POS)
	if qBranchID := c.Query("branch_id"); qBranchID != "" {
		if val, err := strconv.ParseUint(qBranchID, 10, 32); err == nil {
			uVal := uint(val)
			branchID = &uVal
		}
	}

	// Kasir terikat branch
	if user.Role == "kasir" && user.BranchID != nil {
		branchID = user.BranchID
	}

	categoryFilter := c.Query("category_id")
	activeOnlyStr := c.DefaultQuery("active_only", "true")
	activeOnly := activeOnlyStr == "true"
	searchQuery := c.Query("search")
	limitStr := c.Query("limit")
	skipStr := c.Query("skip")

	query := config.DB.Select("id, company_id, category_id, name, sku, price, stock, is_unlimited_stock, image_url, is_active, created_at, updated_at").
		Preload("Category", func(db *gorm.DB) *gorm.DB {
			return db.Select("id, name")
		}).
		Where("company_id = ?", *user.CompanyID)

	if activeOnly {
		query = query.Where("is_active = ?", true)
	}

	if categoryFilter != "" {
		if catID, err := strconv.Atoi(categoryFilter); err == nil {
			query = query.Where("category_id = ?", catID)
		}
	}

	if searchQuery != "" {
		query = query.Where("LOWER(name) LIKE ? OR LOWER(sku) LIKE ?", "%"+strings.ToLower(searchQuery)+"%", "%"+strings.ToLower(searchQuery)+"%")
	}

	// Filter ketersediaan cabang (BranchProduct) di level database
	if branchID != nil {
		query = query.Where("id NOT IN (SELECT product_id FROM branch_products WHERE branch_id = ? AND is_available = ?)", *branchID, false)
	}

	// Terapkan pagination jika limit diisi
	if limitStr != "" {
		if limit, err := strconv.Atoi(limitStr); err == nil {
			query = query.Limit(limit)
		}
	}
	if skipStr != "" {
		if skip, err := strconv.Atoi(skipStr); err == nil {
			query = query.Offset(skip)
		}
	}

	products := []models.Product{}
	if err := query.Find(&products).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"detail": "Gagal mengambil data produk"})
		return
	}

	c.JSON(http.StatusOK, products)
}

func GetProduct(c *gin.Context) {
	userVal, _ := c.Get("user")
	user := userVal.(*models.User)

	productIDStr := c.Param("product_id")
	productID, err := strconv.Atoi(productIDStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"detail": "ID produk tidak valid"})
		return
	}

	var product models.Product
	if err := config.DB.Select("id, company_id, category_id, name, sku, price, stock, is_unlimited_stock, image_url, is_active, created_at, updated_at").
		Preload("Category", func(db *gorm.DB) *gorm.DB {
			return db.Select("id, name")
		}).
		Where("id = ? AND company_id = ?", productID, *user.CompanyID).
		First(&product).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"detail": "Produk tidak ditemukan"})
		return
	}

	c.JSON(http.StatusOK, product)
}

func CreateProduct(c *gin.Context) {
	userVal, _ := c.Get("user")
	user := userVal.(*models.User)

	var req ProductCreateRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"detail": err.Error()})
		return
	}

	if req.SKU == nil || *req.SKU == "" {
		generated := fmt.Sprintf("SKU-%04X%04X", rand.Intn(65536), rand.Intn(65536))
		req.SKU = &generated
	}

	// Verifikasi SKU jika diisi
	if req.SKU != nil && *req.SKU != "" {
		var count int64
		config.DB.Model(&models.Product{}).Where("sku = ?", *req.SKU).Count(&count)
		if count > 0 {
			c.JSON(http.StatusBadRequest, gin.H{"detail": fmt.Sprintf("Produk dengan SKU '%s' sudah ada", *req.SKU)})
			return
		}
	}

	newProduct := models.Product{
		CompanyID:        *user.CompanyID,
		Name:             req.Name,
		SKU:              req.SKU,
		Price:            req.Price,
		Stock:            req.Stock,
		IsUnlimitedStock: req.IsUnlimitedStock,
		CategoryID:       req.CategoryID,
		ImageURL:         req.ImageURL,
		IsActive:         true,
	}

	if err := config.DB.Create(&newProduct).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"detail": "Gagal menyimpan produk baru"})
		return
	}

	if newProduct.CategoryID != nil {
		config.DB.Select("id, name").First(&newProduct.Category, *newProduct.CategoryID)
	}

	c.JSON(http.StatusCreated, newProduct)
}

func UpdateProduct(c *gin.Context) {
	userVal, _ := c.Get("user")
	user := userVal.(*models.User)

	productIDStr := c.Param("product_id")
	productID, err := strconv.Atoi(productIDStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"detail": "ID produk tidak valid"})
		return
	}

	var req ProductCreateRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"detail": err.Error()})
		return
	}

	if req.SKU != nil && *req.SKU == "" {
		req.SKU = nil
	}

	var product models.Product
	if err := config.DB.Where("id = ? AND company_id = ?", productID, *user.CompanyID).First(&product).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"detail": "Produk tidak ditemukan"})
		return
	}

	// Verifikasi SKU jika berubah
	if req.SKU != nil && *req.SKU != "" {
		if product.SKU == nil || *product.SKU != *req.SKU {
			var count int64
			config.DB.Model(&models.Product{}).Where("sku = ? AND id != ?", *req.SKU, productID).Count(&count)
			if count > 0 {
				c.JSON(http.StatusBadRequest, gin.H{"detail": fmt.Sprintf("Produk dengan SKU '%s' sudah ada", *req.SKU)})
				return
			}
			product.SKU = req.SKU
		}
	} else {
		product.SKU = nil
	}

	product.Name = req.Name
	product.Price = req.Price
	product.Stock = req.Stock
	product.IsUnlimitedStock = req.IsUnlimitedStock
	product.CategoryID = req.CategoryID
	product.ImageURL = req.ImageURL

	if err := config.DB.Save(&product).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"detail": "Gagal meng-update produk"})
		return
	}

	if product.CategoryID != nil {
		config.DB.Select("id, name").First(&product.Category, *product.CategoryID)
	}

	c.JSON(http.StatusOK, product)
}

func DeleteProduct(c *gin.Context) {
	userVal, _ := c.Get("user")
	user := userVal.(*models.User)

	productIDStr := c.Param("product_id")
	productID, err := strconv.Atoi(productIDStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"detail": "ID produk tidak valid"})
		return
	}

	result := config.DB.Model(&models.Product{}).
		Where("id = ? AND company_id = ?", productID, *user.CompanyID).
		Update("is_active", false)
	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"detail": "Gagal menghapus produk"})
		return
	}
	if result.RowsAffected == 0 {
		c.JSON(http.StatusNotFound, gin.H{"detail": "Produk tidak ditemukan"})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"message": "Produk berhasil dinonaktifkan",
	})
}