diff options
author | Vidhu Kant Sharma <vidhukant@vidhukant.xyz> | 2023-01-29 20:11:09 +0530 |
---|---|---|
committer | Vidhu Kant Sharma <vidhukant@vidhukant.xyz> | 2023-01-29 20:11:09 +0530 |
commit | ac7aa8c6e95023def1eba7615d8a42ad52271500 (patch) | |
tree | b3477a9d3ae39244a759b19fe42e7d3bccbda38d /invoice | |
parent | 0607478f1e4c86619a606af7876a6625e859ee1a (diff) |
checking password before editing/deleting user
Diffstat (limited to 'invoice')
-rw-r--r-- | invoice/controller.go | 95 | ||||
-rw-r--r-- | invoice/db_actions.go | 131 | ||||
-rw-r--r-- | invoice/invoice.go | 101 | ||||
-rw-r--r-- | invoice/router.go | 152 | ||||
-rw-r--r-- | invoice/service.go | 68 |
5 files changed, 206 insertions, 341 deletions
diff --git a/invoice/controller.go b/invoice/controller.go new file mode 100644 index 0000000..e328dc4 --- /dev/null +++ b/invoice/controller.go @@ -0,0 +1,95 @@ +/* OpenBills-server - Server for libre billing software OpenBills-web + * Copyright (C) 2022 Vidhu Kant Sharma <vidhukant@vidhukant.xyz> + + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + +package invoice + +import ( + "errors" + "github.com/gin-gonic/gin" + "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/mongo" + "log" + "net/http" +) + +func getAll(ctx *gin.Context) { + // TODO: add functionality to filter results + invoices, err := getInvoices(nil) + if err != nil { + ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + log.Printf("ERROR: Failed to read invoices from DB: %v\n", err.Error()) + return + } + + ctx.JSON(http.StatusOK, invoices) +} + +func get(ctx *gin.Context) { + id, err := primitive.ObjectIDFromHex(ctx.Param("invoiceId")) + if err != nil { + ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + log.Printf("ERROR: Failed to get invoice with ID, Error parsing ID: %v\n", err.Error()) + return + } + + invoice, err := getInvoiceById(id) + if err != nil { + if errors.Is(err, mongo.ErrNoDocuments) { + ctx.JSON(http.StatusNotFound, gin.H{"error": err.Error()}) + } else { + ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + } + log.Printf("ERROR: Failed to read invoice %v from DB: %v\n", id, err.Error()) + return + } + + ctx.JSON(http.StatusOK, invoice) +} + +func save(ctx *gin.Context) { + var i Invoice + ctx.BindJSON(&i) + _, err := saveInvoice(i) + if err != nil { + ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + log.Printf("ERROR: Failed to add new invoice %v to DB: %v\n", i, err.Error()) + return + } + + log.Printf("Successfully created new Invoice: %v", i) + ctx.JSON(http.StatusOK, nil) +} + +func remove(ctx *gin.Context) { + id := ctx.Param("invoiceId") + objectId, err := primitive.ObjectIDFromHex(id) + if err != nil { + ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + log.Printf("ERROR: Failed to delete invoice, Error parsing ID: %v\n", err.Error()) + return + } + + err = deleteInvoice(objectId) + if err != nil { + ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + log.Printf("ERROR: Failed to delete invoice %v: %v\n", objectId, err.Error()) + return + } + + log.Printf("Deleted invoice %v from database.\n", objectId) + ctx.JSON(http.StatusOK, nil) +} diff --git a/invoice/db_actions.go b/invoice/db_actions.go deleted file mode 100644 index 0cbeec1..0000000 --- a/invoice/db_actions.go +++ /dev/null @@ -1,131 +0,0 @@ -/* OpenBills-server - Server for libre billing software OpenBills-web - * Copyright (C) 2022 Vidhu Kant Sharma <vidhukant@vidhukant.xyz> - - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - - * You should have received a copy of the GNU General Public License - * along with this program. If not, see <https://www.gnu.org/licenses/>. - */ - -package invoice - -import ( - "context" - - "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/primitive" -) - -// add invoice to db -func saveInvoice(i Invoice) (primitive.ObjectID, error) { - res, err := db.Collection("Invoices").InsertOne(context.TODO(), i) - return res.InsertedID.(primitive.ObjectID), err -} - -// add transporter to db -func saveTransporter(t Transporter) (primitive.ObjectID, error) { - res, err := db.Collection("Transporters").InsertOne(context.TODO(), t) - return res.InsertedID.(primitive.ObjectID), err -} - -// add transport vehicle to db -func saveTransport(t *Transport) (primitive.ObjectID, error) { - res, err := db.Collection("Transports").InsertOne(context.TODO(), t) - return res.InsertedID.(primitive.ObjectID), err -} - -// Delete invoice from DB -func deleteInvoice(id primitive.ObjectID) error { - _, err := db.Collection("Invoices").DeleteOne(context.TODO(), bson.M{"_id": id}) - return err -} - -// Delete transporter from DB -func deleteTransporter(id primitive.ObjectID) error { - _, err := db.Collection("Transporters").DeleteOne(context.TODO(), bson.M{"_id": id}) - return err -} - -// Delete transport vehicle from DB -func deleteTransport(id primitive.ObjectID) error { - _, err := db.Collection("Transports").DeleteOne(context.TODO(), bson.M{"_id": id}) - return err -} - -// modify invoice in DB -func modifyInvoice(id primitive.ObjectID, ni Invoice) error { - _, err := db.Collection("Invoices").UpdateOne(context.TODO(), bson.D{{"_id", id}}, bson.D{{"$set", ni}}) - return err -} - -// modify transporter in DB -func modifyTransporter(id primitive.ObjectID, nt Transporter) error { - _, err := db.Collection("Transporters").UpdateOne(context.TODO(), bson.D{{"_id", id}}, bson.D{{"$set", nt}}) - return err -} - -// modify transport in DB -func modifyTransport(id primitive.ObjectID, nt Transport) error { - _, err := db.Collection("Transports").UpdateOne(context.TODO(), bson.D{{"_id", id}}, bson.D{{"$set", nt}}) - return err -} - -/* GetInvoices queries the database and - * returns invoices based on the given filter - * if filter is nil every invoice is returned - */ -func getInvoices(filter bson.M) ([]Invoice, error) { - var invoices []Invoice - - cursor, err := db.Collection("Invoices").Find(context.TODO(), filter) - if err != nil { - return invoices, err - } - - err = cursor.All(context.TODO(), &invoices) - return invoices, err -} - -func getTransporters(filter bson.M) ([]Transporter, error) { - var transporters []Transporter - - cursor, err := db.Collection("Transporters").Find(context.TODO(), filter) - if err != nil { - return transporters, err - } - - err = cursor.All(context.TODO(), &transporters) - return transporters, err -} - -func getTransports(filter bson.M) ([]Transport, error) { - var transports []Transport - - cursor, err := db.Collection("Transports").Find(context.TODO(), filter) - if err != nil { - return transports, err - } - - err = cursor.All(context.TODO(), &transports) - return transports, err -} - -func getInvoiceByNumber(invoiceNumber int) (Invoice, error) { - var invoice Invoice - err := db.Collection("Invoices").FindOne(context.TODO(), bson.M{"InvoiceNumber": invoiceNumber}).Decode(&invoice) - return invoice, err -} - -func getInvoiceById(invoiceId primitive.ObjectID) (Invoice, error) { - var invoice Invoice - err := db.Collection("Invoices").FindOne(context.TODO(), bson.M{"_id": invoiceId}).Decode(&invoice) - return invoice, err -} diff --git a/invoice/invoice.go b/invoice/invoice.go index 91b881c..f7b638a 100644 --- a/invoice/invoice.go +++ b/invoice/invoice.go @@ -18,45 +18,18 @@ package invoice import ( - "go.mongodb.org/mongo-driver/bson/primitive" - "go.mongodb.org/mongo-driver/mongo" "github.com/MikunoNaka/OpenBills-server/client" - "github.com/MikunoNaka/OpenBills-server/item" "github.com/MikunoNaka/OpenBills-server/database" + "github.com/MikunoNaka/OpenBills-server/item" + t "github.com/MikunoNaka/OpenBills-server/transport" + "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/mongo" "time" ) // initialise a database connection for this package // not sure if I should do this but I am... -var db *mongo.Database = database.DB - -/* you should be able to: - * - add, modify, delete an invoice - * - add client to invoice - * - add items to invoice - */ - -/* Transporter details can be stored in - * the DB. That is decided by the frontend. - * You can optionally store Transporter - * and Transport details which are often used - */ -type Transporter struct { - Id primitive.ObjectID `bson:"_id,omitempty" json:"Id"` - Name string `bson:"Name" json:"Name"` - GSTIN string `bson:"GSTIN" json:"GSTIN"` - // Issued ID for the transporter if any - TransporterId string `bson:"TransporterId,omitempty" json:"TransporterId"` -} - -// transport vehicle details -type Transport struct { - Id primitive.ObjectID `bson:"_id,omitempty" json:"Id"` - Transporter Transporter `bson:"Transporter,omitempty" json:"Transporter"` - VehicleNum string `bson:"VehicleNum" json:"VehicleNum"` - Note string `bson:"Note" json:"Note"` - TransportMethod string `bson:"TransportMethod" json:"TransportMethod"` -} +var db *mongo.Collection = database.DB.Collection("Invoice") /* The *legendary* Invoice struct * Each Recipient, Item in invoice, Address @@ -80,37 +53,37 @@ type Transport struct { */ // TODO: add place of supply type Invoice struct { - Id primitive.ObjectID `bson:"_id,omitempty" json:"Id"` // not the same as invoice number - InvoiceNumber int `bson:"InvoiceNumber" json:"InvoiceNumber"` - CreatedAt time.Time `bson:"CreatedAt" json:"CreatedAt"` - LastUpdated time.Time `bson:"LastUpdated,omitempty" json:"LastUpdated"` - Recipient client.Client `bson:"Recipient" json:"Recipient"` - Paid bool `bson:"Paid" json:"Paid"` - TransactionId string `bson:"TransactionId" json:"TransactionId"` - Transport Transport `bson:"Transport" json:"Transport"` - // user can apply a discount on the whole invoice - // TODO: float64 isn't the best for this - DiscountPercentage float64 `bson:"DiscountPercentage" json:"DiscountPercentage"` - // helps to filter amount by amount - TotalAmount float64 `bson:"TotalAmount" json:"TotalAmount"` - /* client may have multiple shipping - * addresses but invoice only has one. - * Empty ShippingAddress means shipping - * address same as billing address - */ - BillingAddress client.Address `bson:"BillingAddress" json:"BillingAddress"` - ShippingAddress client.Address `bson:"ShippingAddress,omitempty" json:"ShippingAddress"` - Items []item.InvoiceItem `bson:"Items" json:"Items"` - // user can attach notes to the invoice - // frontend decides if recipient sees this or not - Note string `bson:"Note" json:"Note"` + Id primitive.ObjectID `bson:"_id,omitempty" json:"Id"` // not the same as invoice number + InvoiceNumber int `bson:"InvoiceNumber" json:"InvoiceNumber"` + CreatedAt time.Time `bson:"CreatedAt" json:"CreatedAt"` + LastUpdated time.Time `bson:"LastUpdated,omitempty" json:"LastUpdated"` + Recipient client.Client `bson:"Recipient" json:"Recipient"` + Paid bool `bson:"Paid" json:"Paid"` + TransactionId string `bson:"TransactionId" json:"TransactionId"` + Transport t.Transport `bson:"Transport" json:"Transport"` + // user can apply a discount on the whole invoice + // TODO: float64 isn't the best for this + DiscountPercentage float64 `bson:"DiscountPercentage" json:"DiscountPercentage"` + // helps to filter amount by amount + TotalAmount float64 `bson:"TotalAmount" json:"TotalAmount"` + /* client may have multiple shipping + * addresses but invoice only has one. + * Empty ShippingAddress means shipping + * address same as billing address + */ + BillingAddress client.Address `bson:"BillingAddress" json:"BillingAddress"` + ShippingAddress client.Address `bson:"ShippingAddress,omitempty" json:"ShippingAddress"` + Items []item.InvoiceItem `bson:"Items" json:"Items"` + // user can attach notes to the invoice + // frontend decides if recipient sees this or not + Note string `bson:"Note" json:"Note"` - /* Invoices can be drafts - * I personally like this functionality - * because we can constantly save the - * invoice to the DB as a draft - * and if OpenBills crashes or is disconnected - * we still have the progress - */ - Draft bool `bson:"Draft" json:"Draft"` + /* Invoices can be drafts + * I personally like this functionality + * because we can constantly save the + * invoice to the DB as a draft + * and if OpenBills crashes or is disconnected + * we still have the progress + */ + Draft bool `bson:"Draft" json:"Draft"` } diff --git a/invoice/router.go b/invoice/router.go index c89d667..4a3a3b0 100644 --- a/invoice/router.go +++ b/invoice/router.go @@ -18,156 +18,16 @@ package invoice import ( - "github.com/MikunoNaka/OpenBills-server/util" + "github.com/MikunoNaka/OpenBills-server/util" "github.com/gin-gonic/gin" - "log" - "errors" - "net/http" - "go.mongodb.org/mongo-driver/bson/primitive" - "go.mongodb.org/mongo-driver/mongo" ) func Routes(route *gin.Engine) { - i := route.Group("/invoice") - i.Use(util.Authorize()) + i := route.Group("/invoice", util.Authorize()) { - i.GET("/all", func(ctx *gin.Context) { - // TODO: add functionality to filter results - invoices, err := getInvoices(nil) - if err != nil { - ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - log.Printf("ERROR: Failed to read invoices from DB: %v\n", err.Error()) - return - } - - ctx.JSON(http.StatusOK, invoices) - }) - - // send invoice as JSON, filtering by ID - i.GET("/:invoiceId", func(ctx *gin.Context) { - id, err := primitive.ObjectIDFromHex(ctx.Param("invoiceId")) - if err != nil { - ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) - log.Printf("ERROR: Failed to get invoice with ID, Error parsing ID: %v\n", err.Error()) - return - } - - invoice, err := getInvoiceById(id) - if err != nil { - if errors.Is(err, mongo.ErrNoDocuments) { - ctx.JSON(http.StatusNotFound, gin.H{"error": err.Error()}) - } else { - ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - } - log.Printf("ERROR: Failed to read invoice %v from DB: %v\n", id, err.Error()) - return - } - - ctx.JSON(http.StatusOK, invoice) - }) - - i.POST("/new", func(ctx *gin.Context) { - var i Invoice - ctx.BindJSON(&i) - _, err := saveInvoice(i) - if err != nil { - ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - log.Printf("ERROR: Failed to add new invoice %v to DB: %v\n", i, err.Error()) - return - } - - log.Printf("Successfully created new Invoice: %v", i) - ctx.JSON(http.StatusOK, nil) - }) - - i.DELETE("/:invoiceId", func(ctx *gin.Context) { - id := ctx.Param("invoiceId") - objectId, err := primitive.ObjectIDFromHex(id) - if err != nil { - ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) - log.Printf("ERROR: Failed to delete invoice, Error parsing ID: %v\n", err.Error()) - return - } - - err = deleteInvoice(objectId) - if err != nil { - ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - log.Printf("ERROR: Failed to delete invoice %v: %v\n", objectId, err.Error()) - return - } - - log.Printf("Deleted invoice %v from database.\n", objectId ) - ctx.JSON(http.StatusOK, nil) - }) - } - - transport := route.Group("/transport") - { - transport.GET("/all", func(ctx *gin.Context) { - // TODO: add functionality to filter results - transports, err := getTransports(nil) - if err != nil { - ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - log.Printf("ERROR: Failed to read transport vehicles from DB: %v\n", err.Error()) - return - } - - ctx.JSON(http.StatusOK, transports) - }) - - transport.DELETE("/:transportId", func(ctx *gin.Context) { - id := ctx.Param("transportId") - objectId, err := primitive.ObjectIDFromHex(id) - if err != nil { - ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) - log.Printf("ERROR: Failed to delete transport vehicle, Error parsing ID: %v\n", err.Error()) - return - } - - err = deleteTransport(objectId) - if err != nil { - ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - log.Printf("ERROR: Failed to delete transport vehicle %v: %v\n", objectId, err.Error()) - return - } - - log.Printf("Deleted transport vehicle %v from database.\n", objectId ) - ctx.JSON(http.StatusOK, nil) - }) - } - - transporter := route.Group("/transporter") - { - transporter.GET("/all", func(ctx *gin.Context) { - // TODO: add functionality to filter results - transporters, err := getTransporters(nil) - if err != nil { - ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - log.Printf("ERROR: Failed to read transporters from DB: %v\n", err.Error()) - return - } - - ctx.JSON(http.StatusOK, transporters) - }) - - transporter.DELETE("/:transporterId", func(ctx *gin.Context) { - id := ctx.Param("transporterId") - objectId, err := primitive.ObjectIDFromHex(id) - if err != nil { - ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) - log.Printf("ERROR: Failed to delete transporter, Error parsing ID: %v\n", err.Error()) - return - } - - err = deleteTransporter(objectId) - if err != nil { - ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - log.Printf("ERROR: Failed to delete transporter %v: %v\n", objectId, err.Error()) - return - } - - log.Printf("Deleted transporter %v from database.\n", objectId ) - ctx.JSON(http.StatusOK, nil) - }) + i.GET("/all", getAll) + i.GET("/:invoiceId", get) // send invoice as JSON, filtering by ID + i.POST("/new", save) + i.DELETE("/:invoiceId", remove) } } diff --git a/invoice/service.go b/invoice/service.go new file mode 100644 index 0000000..ab37d8a --- /dev/null +++ b/invoice/service.go @@ -0,0 +1,68 @@ +/* OpenBills-server - Server for libre billing software OpenBills-web + * Copyright (C) 2022 Vidhu Kant Sharma <vidhukant@vidhukant.xyz> + + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + +package invoice + +import ( + "context" + + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/primitive" +) + +func saveInvoice(i Invoice) (primitive.ObjectID, error) { + res, err := db.InsertOne(context.TODO(), i) + return res.InsertedID.(primitive.ObjectID), err +} + +func deleteInvoice(id primitive.ObjectID) error { + _, err := db.DeleteOne(context.TODO(), bson.M{"_id": id}) + return err +} + +func modifyInvoice(id primitive.ObjectID, ni Invoice) error { + _, err := db.UpdateOne(context.TODO(), bson.D{{"_id", id}}, bson.D{{"$set", ni}}) + return err +} + +/* GetInvoices queries the database and + * returns invoices based on the given filter + * if filter is nil every invoice is returned + */ +func getInvoices(filter bson.M) ([]Invoice, error) { + var invoices []Invoice + + cursor, err := db.Find(context.TODO(), filter) + if err != nil { + return invoices, err + } + + err = cursor.All(context.TODO(), &invoices) + return invoices, err +} + +func getInvoiceByNumber(invoiceNumber int) (Invoice, error) { + var invoice Invoice + err := db.FindOne(context.TODO(), bson.M{"InvoiceNumber": invoiceNumber}).Decode(&invoice) + return invoice, err +} + +func getInvoiceById(invoiceId primitive.ObjectID) (Invoice, error) { + var invoice Invoice + err := db.FindOne(context.TODO(), bson.M{"_id": invoiceId}).Decode(&invoice) + return invoice, err +} |