Upload markdown files and organize them in a tree structure
โ ๏ธ Warning: This action cannot be undone!
controllers/sellbillController.php (14,505 lines - largest controller) - Updated Version
sellbill
initiateStaticSessionCommingWithCurl.php (Line 7)
regenerateSession.php for improved security
include_once("initiateStaticSessionCommingWithCurl.php");
">if (isset($_POST['curlpost039;]) && $_POST[039;curlpost039;] == 1) {
include("../public/impOpreation.php");
include("../library/regenerateSession.php");
} ">else if (!in_array(">$do, $ajaxDoArr)) {
include("../public/impOpreation.php");
include("../library/regenerateSession.php");
}
$ajaxDoArr = array("addObgyVisit", "delObgyVisit", "updateObgyVisit", "showallajax", "billToExcel", "billToPDF");
sellbill
CREATE TABLE sellbill (
sellbillid INT PRIMARY KEY AUTO_INCREMENT,
sellbilldate DATETIME,
sellbillserial VARCHAR(255), -- invoice number
sellbillclientid INT NOT NULL DEFAULT 0,
sellbilltotaldeptbefor DECIMAL(10,2) NOT NULL, -- client debt before
sellbilltotaldeptafter DECIMAL(10,2) NOT NULL, -- client debt after
sellbilldiscount VARCHAR(255) NOT NULL DEFAULT '039;, -- discount amount or %
sellbilldiscounttype INT NOT NULL DEFAULT 0, -- 0=amount, 1=percentage
sellbilltotalbill DECIMAL(10,2) NOT NULL, -- total before discount
sellbillaftertotalbill DECIMAL(10,2) NOT NULL, -- total after discount
sellbilltotalpayed DECIMAL(10,2) NOT NULL, -- amount paid
sellbillfinalbill DECIMAL(10,2) NOT NULL, -- final amount due
sellbillstoreid INT NOT NULL, -- store location
sellbillsysdate DATETIME NOT NULL, -- system timestamp
comment TEXT NOT NULL,
userid INT NOT NULL, -- cashier/salesperson
conditions INT NOT NULL DEFAULT 0, -- 0=active, 1=deleted
sellbillclientname TEXT NOT NULL, -- client name snapshot
sellbillsaveid INT NOT NULL, -- cash register/safe
sellbildirectpayment INT NOT NULL, -- direct payment flag
billnameid INT NOT NULL, -- bill type/template
sellerid INT NOT NULL, -- sales representative
tempclientName VARCHAR(255) NOT NULL, -- temporary client name
sellQuantity DECIMAL(10,2) NOT NULL, -- total quantity sold
deletedsellid INT NOT NULL, -- deletion tracking
controlname VARCHAR(255) NOT NULL, -- control system name
tax DECIMAL(10,2) NOT NULL DEFAULT 0, -- tax amount
carnumber VARCHAR(255) NOT NULL, -- vehicle registration
cartype VARCHAR(255) NOT NULL, -- vehicle type
carchase VARCHAR(255) NOT NULL, -- chassis number
carmotor VARCHAR(255) NOT NULL, -- engine number
costcenterid INT, -- cost center allocation
localdonw INT DEFAULT 0, -- local download flag
dailyentryid VARCHAR(100) NOT NULL DEFAULT '039;, -- accounting entry
obygyVisitId INT DEFAULT 0, -- medical visit ID
onlineOrderId INT DEFAULT 0, -- e-commerce order link
delbyuserid INT NOT NULL DEFAULT 0, -- user who deleted
lastReviewType TINYINT NOT NULL DEFAULT 0, -- review status
lastReviewUser INT, -- reviewer ID
lastReviewDateTime DATETIME, -- review timestamp
delivery DECIMAL(10,2) NOT NULL DEFAULT 0, -- delivery charges
totalafterdelivery DECIMAL(10,2) NOT NULL DEFAULT 0, -- total with delivery
billReservation TINYINT NOT NULL DEFAULT 0, -- reservation flag
billReservationDate DATE NOT NULL, -- reservation date
webApiId INT NOT NULL DEFAULT 0, -- API integration
visaAccountId INT NOT NULL DEFAULT 0, -- payment account
cashPayed DECIMAL(10,2) NOT NULL, -- cash payment amount
visaPayed DECIMAL(10,2) NOT NULL, -- card payment amount
isBankAccountTransfer TINYINT NOT NULL DEFAULT 0, -- bank transfer flag
extraDiscountPer FLOAT NOT NULL DEFAULT 0, -- additional discount %
extraDiscountVal FLOAT NOT NULL DEFAULT 0, -- additional discount amount
taxOfDiscountPer FLOAT NOT NULL DEFAULT 0, -- tax on discount %
taxOfDiscountVal FLOAT NOT NULL DEFAULT 0, -- tax on discount amount
shippingDate DATE NOT NULL, -- shipping date
taxBillNumber INT NOT NULL DEFAULT 0, -- tax invoice number
collectionType TINYINT NOT NULL DEFAULT 0, -- collection method
collectionDate DATE NOT NULL, -- collection due date
qrerpid VARCHAR(255) NOT NULL, -- QR code for e-receipt
qrerpids TEXT NOT NULL, -- multiple QR codes
autoSaveFlag TINYINT NOT NULL DEFAULT 0, -- auto-save status
ereason TEXT NOT NULL, -- electronic invoice reason
estatus VARCHAR(255) NOT NULL, -- electronic invoice status
epdf VARCHAR(255) NOT NULL, -- electronic PDF path
obgyBillType TINYINT NOT NULL DEFAULT 0, -- medical bill type
billoperationid INT NOT NULL DEFAULT 0, -- operation reference
datestarting DATE NOT NULL, -- service start date
pricetype TINYINT NOT NULL DEFAULT 0, -- price tier used
currencyId INT NOT NULL DEFAULT 1, -- currency reference
knownwayId INT NULL DEFAULT NULL, -- marketing channel
travelDriverId INT NULL DEFAULT NULL, -- travel: driver
travelBusId INT NULL DEFAULT NULL, -- travel: vehicle
travelPathId INT NULL DEFAULT NULL, -- travel: route
travelTripId INT NULL DEFAULT NULL, -- travel: trip
travelTripTypeId INT NULL DEFAULT NULL, -- travel: trip type
travelTripDateId INT NULL DEFAULT NULL, -- travel: date
totalprodiscount VARCHAR(255) NOT NULL DEFAULT '039;, -- product discounts
manage_ex VARCHAR(255) NOT NULL DEFAULT '039;, -- management exception
med_hallmark VARCHAR(255) NOT NULL DEFAULT '039;, -- medical hallmark
pay_rec_no VARCHAR(255) NOT NULL DEFAULT '039;, -- payment receipt number
pay_rec_val VARCHAR(255) NOT NULL DEFAULT '039;, -- payment receipt value
-- Additional specialized fields...
decisionNo VARCHAR(255) NOT NULL DEFAULT '039;,
decisionValue VARCHAR(255) NOT NULL DEFAULT '039;,
sellToSupplier TINYINT NOT NULL DEFAULT 0,
supplierbuybillid INT NOT NULL DEFAULT 0,
shipfrom VARCHAR(255) NOT NULL DEFAULT '039;,
shipto VARCHAR(255) NOT NULL DEFAULT '039;,
paymethodshipping VARCHAR(255) NOT NULL DEFAULT '039;,
whatShippingCost DECIMAL(10,2) NOT NULL DEFAULT 0
);
sellbilldetail - Invoice Line Items
CREATE TABLE sellbilldetail (
sellbilldetailid INT PRIMARY KEY AUTO_INCREMENT,
sellbillid INT NOT NULL, -- parent invoice
sellbilldetailcatid INT NOT NULL, -- product category
sellbilldetailproductid INT NOT NULL, -- product ID
sellbilldetailquantity DECIMAL(10,2) NOT NULL, -- quantity sold
sellbilldetailprice DECIMAL(10,2) NOT NULL, -- unit price
sellbilldetailtotalprice DECIMAL(10,2) NOT NULL, -- line total
discountvalue DECIMAL(10,2) NOT NULL, -- line discount amount
discounttype DECIMAL(10,2) NOT NULL DEFAULT 0, -- discount percentage
note VARCHAR(256), -- line item notes
pricetype TINYINT NOT NULL DEFAULT 0, -- price tier used
sellbilldetaildate DATE NOT NULL, -- line item date
productunitid INT NOT NULL, -- unit of measure
buydiscount DECIMAL(10,2) NOT NULL, -- purchase discount
buydiscounttype INT NOT NULL, -- purchase discount type
storeid INT NOT NULL DEFAULT 0, -- inventory store
buyprice DECIMAL(10,2) NOT NULL, -- cost price
parcode VARCHAR(256) NOT NULL DEFAULT '039;, -- product barcode
lastbuyprice DECIMAL(10,2), -- last purchase price
meanbuyprice DECIMAL(10,2), -- average purchase price
lastbuyprice_withDiscount DECIMAL(10,2), -- last price with discount
meanbuyprice_withDiscount DECIMAL(10,2), -- average price with discount
lastbuyprice_withTax DECIMAL(10,2), -- last price with tax
meanbuyprice_withTax DECIMAL(10,2), -- average price with tax
lastbuyprice_withDiscountAndTax DECIMAL(10,2), -- last price fully loaded
scunitqty INT NOT NULL DEFAULT 0, -- size/color unit quantity
otherdetailquantity INT NOT NULL DEFAULT 0, -- additional quantity
sizeid INT NOT NULL DEFAULT 0, -- size variant
colorid INT NOT NULL DEFAULT 0, -- color variant
onlineOrderId INT NOT NULL DEFAULT 0, -- e-commerce reference
pricetypepro TINYINT NOT NULL DEFAULT 0, -- product price type
playstationPlayId INT NOT NULL DEFAULT 0, -- restaurant/gaming reference
soldSerialsInDetails TEXT NOT NULL DEFAULT '039;, -- serial numbers sold
buyPricesHistoryBookIdQuantity TEXT NOT NULL DEFAULT '039;, -- cost tracking
proHeight FLOAT NOT NULL DEFAULT 0, -- product height
proWidth FLOAT NOT NULL DEFAULT 0, -- product width
sellbilldetailpriceC DECIMAL(10,2) NOT NULL, -- price in secondary currency
sellbilldetailtotalpriceC DECIMAL(10,2) NOT NULL, -- total in secondary currency
discountvalueC DECIMAL(10,2) NOT NULL, -- discount in secondary currency
proSellTrackingSerial VARCHAR(50) NOT NULL DEFAULT '039;, -- tracking serial
travelBrokerId INT NOT NULL DEFAULT 0, -- travel broker
categorydiscount DECIMAL(10,2) NOT NULL DEFAULT 0, -- category discount
prosellDiscountPer FLOAT NOT NULL DEFAULT 0, -- product discount %
prosellDiscountPerType TINYINT NOT NULL DEFAULT 0, -- discount type
prosellDiscountVal FLOAT NOT NULL DEFAULT 0 -- product discount value
);
returnsellbill - Return Transactions
CREATE TABLE returnsellbill (
returnsellbillid INT PRIMARY KEY AUTO_INCREMENT,
returnsellbilldate DATETIME,
returnsellbillserial VARCHAR(255),
returnsellbillclientid INT NOT NULL,
returnsellbilltotaldeptbefor DECIMAL(10,2) NOT NULL,
returnsellbilltotaldeptafter DECIMAL(10,2) NOT NULL,
returnsellbilltotalbill DECIMAL(10,2) NOT NULL,
returnsellbillstoreid INT NOT NULL,
returnsellbillsysdate DATETIME NOT NULL,
comment TEXT NOT NULL,
userid INT NOT NULL,
conditions INT NOT NULL DEFAULT 0,
-- Additional return-specific fields...
originalSellBillId INT NOT NULL, -- reference to original sale
returnReason VARCHAR(255) NOT NULL, -- reason for return
returnType TINYINT NOT NULL DEFAULT 0 -- return type (full/partial)
);
returnsellbilldetail - Return Line Items
CREATE TABLE returnsellbilldetail (
returnsellbilldetailid INT PRIMARY KEY AUTO_INCREMENT,
returnsellbillid INT NOT NULL,
returnsellbilldetailproductid INT NOT NULL,
returnsellbilldetailquantity DECIMAL(10,2) NOT NULL,
returnsellbilldetailprice DECIMAL(10,2) NOT NULL,
returnsellbilldetailtotalprice DECIMAL(10,2) NOT NULL,
originalSellBillDetailId INT NOT NULL, -- reference to original line
returnCondition VARCHAR(255) NOT NULL, -- condition of returned item
restockFlag TINYINT NOT NULL DEFAULT 1 -- whether to restock
);
dailyentry - Journal Entry Header
CREATE TABLE dailyentry (
id INT PRIMARY KEY AUTO_INCREMENT,
totalcreditor DECIMAL(10,2) NOT NULL, -- total credit amount
totaldebtor DECIMAL(10,2) NOT NULL, -- total debit amount
thedate DATE NOT NULL, -- journal entry date
userid INT NOT NULL, -- user who created entry
condition TINYINT NOT NULL DEFAULT 0, -- 0=active, 1=deleted
reverseofid INT NOT NULL DEFAULT 0, -- ID of reversed entry
dDateTime DATETIME NOT NULL, -- creation timestamp
entryComment TEXT, -- journal entry description
fromFlag INT NOT NULL, -- 0=manual, 1=auto from program, 2=plugin
related INT NOT NULL, -- groups related entries
branchid INT DEFAULT 0, -- branch reference
isopeningentry TINYINT NOT NULL DEFAULT 0, -- opening balance flag
operationId INT NOT NULL, -- source transaction ID
operationDetailLink TEXT NOT NULL -- link to source transaction
);
dailyentrycreditor - Journal Entry Credit Lines
CREATE TABLE dailyentrycreditor (
id INT PRIMARY KEY AUTO_INCREMENT,
dailyentryid INT NOT NULL, -- parent journal entry
accountstreeid INT NOT NULL, -- credit account from chart of accounts
value DECIMAL(10,2) NOT NULL, -- credit amount
dComment VARCHAR(300) NOT NULL, -- line description
costcenterid INT NOT NULL -- cost center allocation
);
dailyentrydebtor - Journal Entry Debit Lines
CREATE TABLE dailyentrydebtor (
id INT PRIMARY KEY AUTO_INCREMENT,
dailyentryid INT NOT NULL, -- parent journal entry
accountstreeid INT NOT NULL, -- debit account from chart of accounts
value DECIMAL(10,2) NOT NULL, -- debit amount
dComment VARCHAR(300) NOT NULL, -- line description
costcenterid INT NOT NULL -- cost center allocation
);
add() function)
BEGIN TRANSACTION;
-- Insert main sales bill
INSERT INTO sellbill (
sellbilldate, sellbillserial, sellbillclientid, sellbilltotaldeptbefor,
sellbilltotaldeptafter, sellbilldiscount, sellbilldiscounttype,
sellbilltotalbill, sellbillaftertotalbill, sellbilltotalpayed,
sellbillfinalbill, sellbillstoreid, sellbillsysdate, comment,
userid, conditions, sellbillclientname, sellbillsaveid,
sellbildirectpayment, billnameid, sellerid, tempclientName,
sellQuantity, deletedsellid, controlname, tax, carnumber,
cartype, carchase, carmotor, costcenterid, webApiId,
visaAccountId, cashPayed, visaPayed, isBankAccountTransfer,
obygyVisitId, extraDiscountPer, extraDiscountVal, taxOfDiscountPer,
taxOfDiscountVal, taxBillNumber, collectionType, collectionDate,
obgyBillType, billoperationid, datestarting, pricetype,
currencyId, knownwayId, travelDriverId, travelBusId,
travelPathId, travelTripId, travelTripTypeId, travelTripDateId,
totalprodiscount, manage_ex, med_hallmark, pay_rec_no,
pay_rec_val, decisionNo, decisionValue, sellToSupplier,
supplierbuybillid, shipfrom, shipto, paymethodshipping,
whatShippingCost
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
-- Insert sales bill details (for each product)
INSERT INTO sellbilldetail (
sellbillid, sellbilldetailcatid, sellbilldetailproductid,
sellbilldetailquantity, sellbilldetailprice, sellbilldetailtotalprice,
discountvalue, discounttype, note, pricetype, sellbilldetaildate,
productunitid, buydiscount, buydiscounttype, storeid, buyprice,
parcode, lastbuyprice, meanbuyprice, lastbuyprice_withDiscount,
meanbuyprice_withDiscount, lastbuyprice_withTax, meanbuyprice_withTax,
lastbuyprice_withDiscountAndTax, scunitqty, otherdetailquantity,
sizeid, colorid, onlineOrderId, pricetypepro, playstationPlayId,
soldSerialsInDetails, buyPricesHistoryBookIdQuantity, proHeight,
proWidth, sellbilldetailpriceC, sellbilldetailtotalpriceC,
discountvalueC, proSellTrackingSerial, travelBrokerId,
categorydiscount, prosellDiscountPer, prosellDiscountPerType,
prosellDiscountVal
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
-- Update inventory (for each product/store combination)
UPDATE storedetail
SET productquantity = productquantity - ?
WHERE productid = ? AND storeid = ?
-- Update client debt
UPDATE client
SET clientdebt = clientdebt + ?
WHERE clientid = ?
-- Insert client debt change record
INSERT INTO clientdebtchange (
clientid, clientdebtchangebefore, clientdebtchangeamount,
clientdebtchangeafter, clientdebtchangetype, clientdebtchangedate,
clientdebtchangemodelid, processname, tablename, userid,
totalOperationCost, discount, dailyentryid, billid, paytype
) VALUES (?, ?, ?, ?, 0, ?, ?, 'ูุงุชูุฑุฉ ู
ุจูุนุงุช039;, 039;sellbill039;, ?, ?, ?, 0, ?, 039;credit039;)
-- Insert store report entry
INSERT INTO storereport (
productid, storeid, storemovtype, storemovcomment,
storemovquantity, storemovdate, userid, dailyentryid,
storemovprice, storemovtotalprice, conditions, unitid,
buyprice, parcode
) VALUES (?, ?, 1, 'ูุงุชูุฑุฉ ู
ุจูุนุงุช039;, ?, ?, ?, 0, ?, ?, 0, ?, ?, ?)
-- Update serial numbers (if tracking serials)
UPDATE productserial
SET conditions = 1
WHERE productserailid IN (?)
-- Insert payment records (if cash register used)
INSERT INTO savedaily (
savedailyamount, savedailydesc, savedailydate, savedailytype,
userid, saveid, billid, conditions, tablename, processtype,
savedailyamountreal
) VALUES (?, 'ูุงุชูุฑุฉ ู
ุจูุนุงุช039;, ?, 0, ?, ?, ?, 0, 039;sellbill039;, 0, ?)
-- CRITICAL: Create Daily Entry (Journal Entry) - insertEntery() function
INSERT INTO dailyentry (
totalcreditor, totaldebtor, thedate, userid, condition, reverseofid,
dDateTime, entryComment, fromFlag, related, branchid, isopeningentry,
operationId, operationDetailLink
) VALUES (?, ?, ?, ?, 0, 0, ?, 'ููุฏ ููู
ูุฉ ููุงุชูุฑุฉ ู
ุจูุนุงุช039;, 1, 0, ?, 0, ?, ?)
SET @dailyentry_id = LAST_INSERT_ID();
-- Insert debit entries (ู
ู - Assets/Receivables increase)
INSERT INTO dailyentrydebtor (
dailyentryid, accountstreeid, value, dComment, costcenterid
) VALUES
(@dailyentry_id, ?, ?, 'ุงูุนู
ูุงุก - ูุงุชูุฑุฉ ู
ุจูุนุงุช039;, ?), -- Accounts Receivable (if credit sale)
(@dailyentry_id, ?, ?, 'ุงูุฎุฒููุฉ - ูุงุชูุฑุฉ ู
ุจูุนุงุช039;, ?), -- Cash Account (if cash sale)
(@dailyentry_id, ?, ?, 'ุชูููุฉ ุงูุจุถุงุนุฉ ุงูู
ุจุงุนุฉ039;, ?); -- Cost of Goods Sold
-- Insert credit entries (ุงูู - Revenue/Liabilities increase)
INSERT INTO dailyentrycreditor (
dailyentryid, accountstreeid, value, dComment, costcenterid
) VALUES
(@dailyentry_id, ?, ?, 'ู
ุจูุนุงุช - ูุงุชูุฑุฉ ู
ุจูุนุงุช039;, ?), -- Sales Revenue Account
(@dailyentry_id, ?, ?, 'ุงูู
ุฎุฒูู - ูุงุชูุฑุฉ ู
ุจูุนุงุช039;, ?), -- Inventory Account (reduction)
(@dailyentry_id, ?, ?, 'ุถุฑูุจุฉ ุงูู
ุจูุนุงุช039;, ?); -- Sales Tax Payable
-- Update sales bill with daily entry ID
UPDATE sellbill SET dailyentryid = @dailyentry_id WHERE sellbillid = ?;
COMMIT;
show() functions)
-- Get sales bills with client and user information
SELECT sellbill.*, user.username, client.clientname, sellbilldetail.pricetype
FROM sellbill
LEFT JOIN user ON sellbill.userid = user.userid
LEFT JOIN client ON sellbill.sellbillclientid = client.clientid
LEFT JOIN sellbilldetail ON sellbill.sellbillid = sellbilldetail.sellbillid
WHERE sellbill.deletedsellid = 0
AND sellbill.conditions = 0
ORDER BY sellbill.sellbillid DESC
LIMIT ? OFFSET ?
-- Get sales bills by date range
SELECT DISTINCT sellbill.*, user.username, client.clientname, sellbilldetail.pricetype
FROM sellbill
LEFT JOIN user ON sellbill.userid = user.userid
LEFT JOIN client ON sellbill.sellbillclientid = client.clientid
LEFT JOIN sellbilldetail ON sellbill.sellbillid = sellbilldetail.sellbillid
WHERE sellbill.deletedsellid = 0
AND sellbill.conditions = 0
AND DATE(sellbill.sellbilldate) BETWEEN ? AND ?
ORDER BY sellbill.sellbilldate DESC
-- Get sales bills by client
SELECT * FROM sellbill
WHERE sellbillclientid = ?
AND deletedsellid = 0
AND conditions = 0
ORDER BY sellbillid DESC
-- Get sales bills by store
SELECT * FROM sellbill
WHERE sellbillstoreid = ?
AND deletedsellid = 0
AND conditions = 0
ORDER BY sellbilldate DESC
-- Get sales bills by salesperson
SELECT * FROM sellbill
WHERE sellerid = ?
AND deletedsellid = 0
AND conditions = 0
ORDER BY sellbilldate DESC
-- Get complete bill with details
SELECT sb., sbd., p.productName, p.parcode, pc.productCatName,
u.unitName, c.clientname, usr.username
FROM sellbill sb
LEFT JOIN sellbilldetail sbd ON sb.sellbillid = sbd.sellbillid
LEFT JOIN product p ON sbd.sellbilldetailproductid = p.productId
LEFT JOIN productcat pc ON sbd.sellbilldetailcatid = pc.productCatId
LEFT JOIN unit u ON sbd.productunitid = u.unitid
LEFT JOIN client c ON sb.sellbillclientid = c.clientid
LEFT JOIN user usr ON sb.userid = usr.userid
WHERE sb.sellbillid = ?
AND sb.deletedsellid = 0
AND sb.conditions = 0
ORDER BY sbd.sellbilldetailid
-- Get bill totals and statistics
SELECT
COUNT(sbd.sellbilldetailid) as total_items,
SUM(sbd.sellbilldetailquantity) as total_quantity,
SUM(sbd.sellbilldetailtotalprice) as subtotal,
sb.sellbilldiscount,
sb.tax,
sb.delivery,
sb.sellbillfinalbill as final_total
FROM sellbill sb
LEFT JOIN sellbilldetail sbd ON sb.sellbillid = sbd.sellbillid
WHERE sb.sellbillid = ?
GROUP BY sb.sellbillid
-- Insert return bill
INSERT INTO returnsellbill (
returnsellbilldate, returnsellbillserial, returnsellbillclientid,
returnsellbilltotaldeptbefor, returnsellbilltotaldeptafter,
returnsellbilltotalbill, returnsellbillstoreid, returnsellbillsysdate,
comment, userid, conditions, originalSellBillId, returnReason, returnType
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?, ?)
-- Insert return details
INSERT INTO returnsellbilldetail (
returnsellbillid, returnsellbilldetailproductid, returnsellbilldetailquantity,
returnsellbilldetailprice, returnsellbilldetailtotalprice,
originalSellBillDetailId, returnCondition, restockFlag
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
-- Restore inventory (if restocking)
UPDATE storedetail
SET productquantity = productquantity + ?
WHERE productid = ? AND storeid = ?
-- Update client debt (credit for return)
UPDATE client
SET clientdebt = clientdebt - ?
WHERE clientid = ?
-- Insert client debt change for return
INSERT INTO clientdebtchange (
clientid, clientdebtchangebefore, clientdebtchangeamount,
clientdebtchangeafter, clientdebtchangetype, clientdebtchangedate,
processname, tablename, userid
) VALUES (?, ?, ?, ?, 1, ?, 'ู
ุฑุชุฌุน ู
ุจูุนุงุช039;, 039;returnsellbill039;, ?)
-- Record cash payment
INSERT INTO savedaily (
savedailyamount, savedailydesc, savedailydate, savedailytype,
userid, saveid, billid, conditions, tablename
) VALUES (?, 'ุฏูุน ููุฏู - ูุงุชูุฑุฉ039;, ?, 0, ?, ?, ?, 0, 039;sellbill039;)
-- Record card payment
INSERT INTO savedaily (
savedailyamount, savedailydesc, savedailydate, savedailytype,
userid, saveid, billid, conditions, tablename, visaAccountId
) VALUES (?, 'ุฏูุน ุจุงูููุฒุง - ูุงุชูุฑุฉ039;, ?, 1, ?, ?, ?, 0, 039;sellbill039;, ?)
-- Record bank transfer
UPDATE client SET clientdebt = clientdebt - ? WHERE clientid = ?;
INSERT INTO clientdebtchange (
clientid, clientdebtchangeamount, processname, tablename, userid
) VALUES (?, ?, 'ุชุญููู ุจููู039;, 039;sellbill039;, ?)
-- Daily sales summary
SELECT
DATE(sellbilldate) as sale_date,
COUNT(sellbillid) as total_bills,
SUM(sellbillfinalbill) as total_sales,
SUM(cashPayed) as cash_received,
SUM(visaPayed) as card_received,
SUM(tax) as total_tax
FROM sellbill
WHERE deletedsellid = 0
AND conditions = 0
AND DATE(sellbilldate) BETWEEN ? AND ?
GROUP BY DATE(sellbilldate)
ORDER BY sale_date DESC
-- Product sales analysis
SELECT
p.productName,
pc.productCatName,
SUM(sbd.sellbilldetailquantity) as total_sold,
SUM(sbd.sellbilldetailtotalprice) as total_revenue,
AVG(sbd.sellbilldetailprice) as avg_price,
COUNT(DISTINCT sbd.sellbillid) as bills_count
FROM sellbilldetail sbd
JOIN product p ON sbd.sellbilldetailproductid = p.productId
JOIN productcat pc ON p.productCatId = pc.productCatId
JOIN sellbill sb ON sbd.sellbillid = sb.sellbillid
WHERE sb.deletedsellid = 0
AND sb.conditions = 0
AND DATE(sb.sellbilldate) BETWEEN ? AND ?
GROUP BY p.productId, p.productName, pc.productCatName
ORDER BY total_revenue DESC
-- Client sales analysis
SELECT
c.clientname,
COUNT(sb.sellbillid) as total_bills,
SUM(sb.sellbillfinalbill) as total_purchased,
AVG(sb.sellbillfinalbill) as avg_bill_amount,
MAX(sb.sellbilldate) as last_purchase_date
FROM sellbill sb
JOIN client c ON sb.sellbillclientid = c.clientid
WHERE sb.deletedsellid = 0
AND sb.conditions = 0
AND DATE(sb.sellbilldate) BETWEEN ? AND ?
GROUP BY c.clientid, c.clientname
ORDER BY total_purchased DESC
BEGIN TRANSACTION;
-- Validate inventory availability
SELECT SUM(productquantity) FROM storedetail
WHERE productid = ? AND storeid = ?;
-- Check client credit limit
SELECT clientdebt, debtLimit FROM client WHERE clientid = ?;
-- Create sales bill
INSERT INTO sellbill (...) VALUES (...);
SET @sellbill_id = LAST_INSERT_ID();
-- Create line items
INSERT INTO sellbilldetail (...) VALUES (...);
-- Update inventory
UPDATE storedetail SET productquantity = productquantity - ?
WHERE productid = ? AND storeid = ?;
-- Update client debt
UPDATE client SET clientdebt = clientdebt + ? WHERE clientid = ?;
-- Create debt change record
INSERT INTO clientdebtchange (...) VALUES (...);
-- Create store movement record
INSERT INTO storereport (...) VALUES (...);
-- Process payments
INSERT INTO savedaily (...) VALUES (...);
COMMIT;
SELECT sb.*, u.username, c.clientname, s.storeName,
COUNT(sbd.sellbilldetailid) as item_count,
SUM(sbd.sellbilldetailquantity) as total_quantity
FROM sellbill sb
LEFT JOIN user u ON sb.userid = u.userid
LEFT JOIN client c ON sb.sellbillclientid = c.clientid
LEFT JOIN store s ON sb.sellbillstoreid = s.storeId
LEFT JOIN sellbilldetail sbd ON sb.sellbillid = sbd.sellbillid
WHERE sb.deletedsellid = 0 AND sb.conditions = 0
GROUP BY sb.sellbillid
ORDER BY sb.sellbilldate DESC
LIMIT ? OFFSET ?
/api/v1/sales
GET /api/v1/sales
Query Parameters:
page: Page number (default: 1)
limit: Items per page (default: 20, max: 100)
date_from: Start date (YYYY-MM-DD)
date_to: End date (YYYY-MM-DD)
client_id: Filter by client
store_id: Filter by store
user_id: Filter by cashier
seller_id: Filter by salesperson
status: Filter by status (active, deleted, returned)
payment_method: Filter by payment method (cash, card, credit)
min_amount: Minimum bill amount
max_amount: Maximum bill amount
serial: Search by invoice number
{
"success": true,
"data": [
{
"sellbillid": 1001,
"sellbillserial": "INV-001001",
"sellbilldate": "2024-01-20T14:30:00Z",
"client": {
"sellbillclientid": 25,
"clientname": "Ahmed Mohamed",
"sellbillclientname": "Ahmed Mohamed"
},
"store": {
"sellbillstoreid": 1,
"storeName": "Main Store"
},
"cashier": {
"userid": 5,
"username": "cashier1"
},
"seller": {
"sellerid": 8,
"sellerName": "Sales Rep 1"
},
"amounts": {
"sellbilltotalbill": 1500.00,
"sellbilldiscount": "50.00",
"sellbilldiscounttype": 0,
"sellbillaftertotalbill": 1450.00,
"tax": 145.00,
"delivery": 25.00,
"totalafterdelivery": 1620.00,
"sellbillfinalbill": 1620.00
},
"payment": {
"sellbilltotalpayed": 1620.00,
"cashPayed": 1000.00,
"visaPayed": 620.00,
"sellbilltotaldeptbefor": 500.00,
"sellbilltotaldeptafter": 500.00
},
"items": {
"total_items": 5,
"sellQuantity": 12.0
},
"dates": {
"sellbillsysdate": "2024-01-20T14:30:00Z",
"shippingDate": "2024-01-21",
"collectionDate": "2024-01-27"
},
"flags": {
"conditions": 0,
"deletedsellid": 0,
"billReservation": 0,
"isBankAccountTransfer": 0
},
"references": {
"billnameid": 1,
"costcenterid": 2,
"currencyId": 1,
"onlineOrderId": 0,
"taxBillNumber": 2024001
}
}
],
"pagination": {
"current_page": 1,
"total_pages": 125,
"total_items": 2487,
"per_page": 20
},
"summary": {
"total_sales": 125000.50,
"total_tax": 12500.05,
"cash_received": 85000.30,
"card_received": 39999.20,
"pending_collection": 1.00
}
}
GET /api/v1/sales/{id}
Response:
{
"success": true,
"data": {
"sellbillid": 1001,
"sellbillserial": "INV-001001",
"sellbilldate": "2024-01-20T14:30:00Z",
"client": {
"sellbillclientid": 25,
"clientname": "Ahmed Mohamed",
"clientphone": "01234567890",
"clientaddress": "Cairo, Egypt"
},
"store": {
"sellbillstoreid": 1,
"storeName": "Main Store",
"storeAddress": "Downtown Cairo"
},
"amounts": {
"sellbilltotalbill": 1500.00,
"discount": {
"sellbilldiscount": "50.00",
"sellbilldiscounttype": 0,
"extraDiscountPer": 2.0,
"extraDiscountVal": 29.00
},
"sellbillaftertotalbill": 1421.00,
"tax": 142.10,
"delivery": 25.00,
"sellbillfinalbill": 1588.10
},
"payment": {
"sellbilltotalpayed": 1588.10,
"cashPayed": 1000.00,
"visaPayed": 588.10,
"payment_methods": [
{
"type": "cash",
"amount": 1000.00,
"received_at": "2024-01-20T14:30:00Z"
},
{
"type": "visa",
"amount": 588.10,
"account_id": 5,
"received_at": "2024-01-20T14:31:00Z"
}
]
},
"items": [
{
"sellbilldetailid": 2001,
"product": {
"sellbilldetailproductid": 150,
"productName": "iPhone 14 Pro",
"parcode": "1234567890123",
"category": {
"sellbilldetailcatid": 5,
"productCatName": "Mobile Phones"
}
},
"pricing": {
"sellbilldetailprice": 1200.00,
"sellbilldetailquantity": 1.0,
"sellbilldetailtotalprice": 1200.00,
"discountvalue": 50.00,
"discounttype": 0,
"buyprice": 800.00
},
"unit": {
"productunitid": 1,
"unitName": "Piece"
},
"variants": {
"sizeid": 1,
"sizeName": "128GB",
"colorid": 2,
"colorName": "Space Black"
},
"tracking": {
"soldSerialsInDetails": "SN123456789",
"proSellTrackingSerial": "TRK001"
}
}
],
"vehicle_info": {
"carnumber": "ABC-1234",
"cartype": "Sedan",
"carchase": "CH123456",
"carmotor": "MT789012"
},
"shipping": {
"shippingDate": "2024-01-21",
"shipfrom": "Main Warehouse",
"shipto": "Client Address",
"delivery": 25.00,
"paymethodshipping": "COD"
},
"audit": {
"sellbillsysdate": "2024-01-20T14:30:00Z",
"userid": 5,
"username": "cashier1",
"lastReviewType": 1,
"lastReviewUser": 10,
"lastReviewDateTime": "2024-01-20T15:00:00Z"
},
"references": {
"dailyentryid": "DE2024001",
"taxBillNumber": 2024001,
"qrerpid": "QR123456",
"webApiId": 1001
}
}
}
POST /api/v1/sales
Content-Type: application/json
Request Body:
{
"client": {
"sellbillclientid": 25,
"tempclientName": "Ahmed Mohamed"
},
"store": {
"sellbillstoreid": 1
},
"payment": {
"sellbildirectpayment": 1,
"cashPayed": 1000.00,
"visaPayed": 588.10,
"visaAccountId": 5,
"isBankAccountTransfer": 0
},
"settings": {
"billnameid": 1,
"sellerid": 8,
"pricetype": 0,
"currencyId": 1,
"costcenterid": 2
},
"discounts": {
"sellbilldiscount": "50.00",
"sellbilldiscounttype": 0,
"extraDiscountPer": 2.0,
"extraDiscountVal": 29.00
},
"shipping": {
"delivery": 25.00,
"shippingDate": "2024-01-21",
"shipfrom": "Main Warehouse",
"shipto": "Client Address"
},
"items": [
{
"product": {
"sellbilldetailproductid": 150,
"sellbilldetailcatid": 5,
"parcode": "1234567890123"
},
"quantity": 1.0,
"pricing": {
"sellbilldetailprice": 1200.00,
"discountvalue": 50.00,
"discounttype": 0,
"pricetype": 0
},
"unit": {
"productunitid": 1
},
"variants": {
"sizeid": 1,
"colorid": 2
},
"store": {
"storeid": 1
},
"serials": ["SN123456789"],
"note": "Customer requested specific color"
}
],
"vehicle": {
"carnumber": "ABC-1234",
"cartype": "Sedan",
"carchase": "CH123456",
"carmotor": "MT789012"
},
"comment": "Sale completed successfully",
"references": {
"onlineOrderId": 0,
"obygyVisitId": 0,
"knownwayId": 1
}
}
Response:
{
"success": true,
"message": "Sale created successfully",
"data": {
"sellbillid": 1002,
"sellbillserial": "INV-001002",
"sellbilldate": "2024-01-20T15:45:00Z",
"sellbillfinalbill": 1588.10,
"taxBillNumber": 2024002,
"qrerpid": "QR123457",
"dailyentryid": "DE2024002",
"webApiId": 1002,
"inventory_updated": true,
"client_debt_updated": true,
"payment_processed": true,
"accounting": {
"daily_entry_created": true,
"daily_entry_id": 5001,
"total_debits": 1588.10,
"total_credits": 1588.10,
"journal_entries": [
{
"type": "debit",
"account": "Accounts Receivable",
"amount": 1588.10,
"description": "ุงูุนู
ูุงุก - ูุงุชูุฑุฉ ู
ุจูุนุงุช"
},
{
"type": "credit",
"account": "Sales Revenue",
"amount": 1421.00,
"description": "ู
ุจูุนุงุช - ูุงุชูุฑุฉ ู
ุจูุนุงุช"
},
{
"type": "credit",
"account": "Sales Tax Payable",
"amount": 142.10,
"description": "ุถุฑูุจุฉ ุงูู
ุจูุนุงุช"
},
{
"type": "debit",
"account": "Cost of Goods Sold",
"amount": 800.00,
"description": "ุชูููุฉ ุงูุจุถุงุนุฉ ุงูู
ุจุงุนุฉ"
},
{
"type": "credit",
"account": "Inventory",
"amount": 800.00,
"description": "ุงูู
ุฎุฒูู - ูุงุชูุฑุฉ ู
ุจูุนุงุช"
}
]
}
}
}
PUT /api/v1/sales/{id}
Content-Type: application/json
Request Body: (Same as create, allows partial updates)
Response:
{
"success": true,
"message": "Sale updated successfully",
"data": {
"sellbillid": 1002,
"updated_at": "2024-01-20T16:00:00Z",
"changes": {
"amounts_recalculated": true,
"inventory_adjusted": true,
"client_debt_adjusted": true
}
}
}
DELETE /api/v1/sales/{id}
Response:
{
"success": true,
"message": "Sale voided successfully",
"data": {
"sellbillid": 1002,
"voided_at": "2024-01-20T16:30:00Z",
"inventory_restored": true,
"client_debt_reversed": true,
"payments_reversed": true
}
}
POST /api/v1/sales/{id}/return
Content-Type: application/json
Request Body:
{
"return_type": "partial", // full, partial
"return_reason": "Defective product",
"items": [
{
"sellbilldetailid": 2001,
"return_quantity": 1.0,
"return_condition": "defective",
"restock": false,
"refund_amount": 1200.00
}
],
"refund_method": "cash", // cash, card, credit
"comment": "Product had manufacturing defect"
}
Response:
{
"success": true,
"message": "Return processed successfully",
"data": {
"returnsellbillid": 501,
"returnsellbillserial": "RET-000501",
"return_amount": 1200.00,
"refund_processed": true,
"inventory_adjusted": false,
"client_debt_adjusted": true
}
}
GET /api/v1/sales/{id}/accounting
Response:
{
"success": true,
"data": {
"sellbillid": 1001,
"dailyentry": {
"id": 5001,
"thedate": "2024-01-20",
"totalcreditor": 1588.10,
"totaldebtor": 1588.10,
"entryComment": "ููุฏ ููู
ูุฉ ููุงุชูุฑุฉ ู
ุจูุนุงุช",
"operationId": 1001,
"operationDetailLink": "sellbillController.php?do=showDetail&id=1001"
},
"debit_entries": [
{
"accountstreeid": 1001,
"account_name": "ุงูุนู
ูุงุก",
"account_name_en": "Accounts Receivable",
"value": 1588.10,
"dComment": "ุงูุนู
ูุงุก - ูุงุชูุฑุฉ ู
ุจูุนุงุช",
"costcenterid": 1
},
{
"accountstreeid": 5001,
"account_name": "ุชูููุฉ ุงูุจุถุงุนุฉ ุงูู
ุจุงุนุฉ",
"account_name_en": "Cost of Goods Sold",
"value": 800.00,
"dComment": "ุชูููุฉ ุงูุจุถุงุนุฉ ุงูู
ุจุงุนุฉ",
"costcenterid": 1
}
],
"credit_entries": [
{
"accountstreeid": 4001,
"account_name": "ู
ุจูุนุงุช",
"account_name_en": "Sales Revenue",
"value": 1421.00,
"dComment": "ู
ุจูุนุงุช - ูุงุชูุฑุฉ ู
ุจูุนุงุช",
"costcenterid": 1
},
{
"accountstreeid": 2001,
"account_name": "ุงูู
ุฎุฒูู",
"account_name_en": "Inventory",
"value": 800.00,
"dComment": "ุงูู
ุฎุฒูู - ูุงุชูุฑุฉ ู
ุจูุนุงุช",
"costcenterid": 1
},
{
"accountstreeid": 2010,
"account_name": "ุถุฑูุจุฉ ุงูู
ุจูุนุงุช ุงูู
ุณุชุญูุฉ",
"account_name_en": "Sales Tax Payable",
"value": 142.10,
"dComment": "ุถุฑูุจุฉ ุงูู
ุจูุนุงุช",
"costcenterid": 1
}
]
}
}
GET /api/v1/sales/analytics
Query Parameters:
date_from: Start date
date_to: End date
group_by: Grouping (daily, weekly, monthly)
store_id: Filter by store
client_id: Filter by client
{
"success": true,
"data": {
"summary": {
"total_sales": 125000.50,
"total_bills": 1250,
"average_bill": 100.00,
"total_tax": 12500.05,
"total_discounts": 2500.10
},
"by_period": [
{
"period": "2024-01-20",
"total_sales": 5500.00,
"total_bills": 45,
"average_bill": 122.22
}
],
"by_payment_method": {
"cash": 75000.30,
"card": 45000.20,
"credit": 4999.00
},
"top_products": [
{
"productId": 150,
"productName": "iPhone 14 Pro",
"quantity_sold": 25,
"total_revenue": 30000.00
}
],
"top_clients": [
{
"clientid": 25,
"clientname": "Ahmed Mohamed",
"total_purchased": 15000.00,
"bills_count": 12
}
]
}
}
// Inventory validation
$availableQty = StoreDetail::where('productid039;, $productId)
->where('storeid039;, $storeId)
->sum('productquantity039;);
">if ($requestedQty > $availableQty) {
throw new InsufficientInventoryException();
}
// Client credit limit validation
">$client = Client::find($clientId);
">$newDebt = ">$client->clientdebt + $billAmount;
">if (">$newDebt > $client->debtLimit) {
throw new CreditLimitExceededException();
}
// Price authorization validation
">if ($sellingPrice < $product->productBuyPrice) {
throw new BelowCostPriceException();
}
DB::beginTransaction();
try {
// Create sales bill
$sellBill = SellBill::create($billData);
// Create line items and update inventory
foreach (">$items as $item) {
$sellBill->details()->create($item);
StoreDetail::decrementInventory($item['productid039;], $item[039;quantity039;]);
}
// Update client debt
Client::updateDebt(">$clientId, $billAmount);
// Process payments
$this->processPayments($payments);
DB::commit();
} ">catch (Exception $e) {
DB::rollback();
throw $e;
}
curl -X POST http://localhost/api/v1/sales \
-H "Content-Type: application/json" \
-H "Authorization: Bearer your-jwt-token" \
-d '{
"client": {"sellbillclientid": 25},
"store": {"sellbillstoreid": 1},
"payment": {"cashPayed": 1500.00},
"items": [{
"product": {"sellbilldetailproductid": 150},
"quantity": 1.0,
"pricing": {"sellbilldetailprice": 1500.00}
}]
}'
curl -X GET "http://localhost/api/v1/sales/analytics?date_from=2024-01-20&date_to=2024-01-20&group_by=daily" \
-H "Authorization: Bearer your-jwt-token"
class SalesAPI {
constructor(baseURL, token) {
this.baseURL = baseURL;
this.token = token;
}
async createSale(saleData) {
const response = ">await fetch(${this.baseURL}/api/v1/sales, {
method: 'POST039;,
headers: {
'Content-Type039;: 039;application/json039;,
'Authorization039;: Bearer ${this.token}
},
body: JSON.stringify(saleData)
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.error.message);
}
return await response.json();
}
async processReturn(saleId, returnData) {
const response = ">await fetch(${">this.baseURL}/api/v1/sales/${saleId}/return, {
method: 'POST039;,
headers: {
'Content-Type039;: 039;application/json039;,
'Authorization039;: Bearer ${this.token}
},
body: JSON.stringify(returnData)
});
return await response.json();
}
async getDailySales(date) {
const response = await fetch(
${this.baseURL}/api/v1/sales/analytics?date_from=${date}&date_to=${date}&group_by=daily,
{ headers: { 'Authorization039;: Bearer ${this.token} } }
);
return await response.json();
}
}
// POS Usage
">const salesAPI = new SalesAPI('http://localhost039;, 039;pos-token039;);
// Create a sale
try {
const result = await salesAPI.createSale({
client: { sellbillclientid: 1 },
store: { sellbillstoreid: 1 },
payment: { cashPayed: 100.00 },
items: [{
product: { sellbilldetailproductid: 1 },
quantity: 2,
pricing: { sellbilldetailprice: 50.00 }
}]
});
console.log('Sale created:039;, result.data.sellbillserial);
} catch (error) {
console.error('Sale failed:039;, error.message);
}
// Line 1332-1340 in sellbillController.php
">elseif ($do == "updateReservation") {
">if (isset($_GET["reservation"]) && (int) $_GET["reservation"] == 3 && isset(">$_GET["sellbillid"]) && (int) $_GET["sellbillid"] > 0) {
">$sellbillid = (int) $_GET["sellbillid"];
">$bill = $mySellbillRecord->load($sellbillid);
$bill->billReservation = 3;
$mySellbillRecord->update($bill);
}
header('Location:039; . $hosturl . 039;/controllers/salesreportbills.php?do=billReservation039;);
}
SQL Operations:
-- Update bill reservation status
UPDATE sellbill SET billReservation = 3 WHERE sellbillid = ?
API Endpoint: POST /controllers/sellbillController.php?do=updateReservation&reservation=3&sellbillid={id}
Business Logic:
// Line 1342+ in sellbillController.php
">elseif ($do == "addsellBillManyParcodes") {
$manyParcodes = $_POST['manyParcodes039;];
">if ($Programsettingdata->usedParcode == 1) { //use 'i039; to indicate product ID
$manyParcodes = str_replace(['ู039;, 039;รท039;, 039;/039;, 039;I039;], 039;i039;, $manyParcodes);
}
// Process barcode string: "00001,00002.5,i123.10"
// Where .5 = quantity 5, i123.10 = product ID 123 with quantity 10
$manyParcodes = str_replace("\n", ",", $manyParcodes);
$manyParcodes = preg_replace('/[^0-9,i.]+/039;, 039;039;, $manyParcodes);
// Build distinct product array with quantities
foreach (explode(',039;, $manyParcodes) as $value) {
">$t = explode('.039;, $value, 2);
$productCode = $t[0];
">$quantity = (float) $t[1] ?: 1;
$parcodeSKVArr[$productCode] += $quantity;
}
}
SQL Operations:
-- Get product by barcode
SELECT * FROM product WHERE productparcode = ? AND conditions = 0
-- Get product by ID (when starts with 'i039;)
SELECT * FROM product WHERE productid = ? AND conditions = 0
-- Create sale bill with multiple products
INSERT INTO sellbill (sellbillclientid, sellbilldate, sellbilltotal, userid, storeid, ...)
VALUES (?, ?, ?, ?, ?, ...)
-- Insert each product line
INSERT INTO sellbillunit (sellbillunitproductid, sellbillunitquantity, sellbillunitprice, sellbillunitsellbillid)
VALUES (?, ?, ?, ?)
API Endpoint: POST /controllers/sellbillController.php?do=addsellBillManyParcodes
Request Body:
{
"manyParcodes": "00001.2,00002.5,i123.10",
"manyParcodesSupplier": 1,
"manyParcodesStoreid": 1,
"manyParcodesSellerid": 2
}
Business Logic:
// Line 1773-1914 in sellbillController.php
">elseif ($do == "addresBill") {
$restaurantorderlast20 = R::getAll("SELECT * FROM restaurantorder order by id desc limit 20");
$OrdereditId = (int) filter_input(INPUT_GET, "id");
$tableId = (int) filter_input(INPUT_GET, "tableId");
">if ($OrdereditId) {
$restaurantOrder = $restaurantOrderDAO->load($OrdereditId);
">$sellBilldata = $mySellbillRecord->load($restaurantOrder->sellBillId);
$restaurantOrder->finished = 0;
$restaurantOrderDAO->update($restaurantOrder);
R::exec("UPDATE restaurantorder SET finished= 1 WHERE id != '$OrdereditId039; and tableId = 039;$tableId039;");
}
// Complex table permission logic for hall/takeaway/delivery
">if ($Usergroupdata->seeAllHalls) {
$queryString = '039;;
} else {
// Build permission-based table query
$queryString = ' and ( 039;;
">if ($Usergroupdata->hall == 1) $queryString .= ' restauranttable.id > 0 039;;
">if ($Usergroupdata->takeAway == 1) $queryString .= ' or restauranttable.id = -1 039;;
">if ($Usergroupdata->delivery == 1) $queryString .= ' or restauranttable.id = -2 039;;
$queryString .= ' ) 039;;
}
}
SQL Operations:
-- Get recent restaurant orders
SELECT * FROM restaurantorder ORDER BY id DESC LIMIT 20
-- Load specific restaurant order
SELECT * FROM restaurantorder WHERE id = ?
-- Load associated sell bill
SELECT * FROM sellbill WHERE sellbillid = ?
-- Update restaurant order status
UPDATE restaurantorder SET finished = 0 WHERE id = ?
-- Mark other orders as finished for same table
UPDATE restaurantorder SET finished = 1 WHERE id != ? AND tableId = ?
-- Get restaurant tables based on permissions
SELECT restauranttable.*, hall.hallname FROM restauranttable
LEFT JOIN hall ON restauranttable.hallid = hall.hallid
WHERE restauranttable.conditions = 0 [AND permission_query]
-- Get daily cash totals
SELECT * FROM savedaily WHERE userid = ? AND savedailydate BETWEEN ? AND ?
-- Get product sales for the day
SELECT product., COUNT() as sales_count FROM sellbillunit
JOIN product ON product.productid = sellbillunit.sellbillunitproductid
WHERE sellbillunitdate BETWEEN ? AND ?
GROUP BY product.productid
API Endpoint: GET /controllers/sellbillController.php?do=addresBill&id={order_id}&tableId={table_id}
Business Logic:
// Line 1915+ in sellbillController.php
">elseif ($do == "endKitchenBill") {
">$tableId = (int) $_POST["tableId"];
$printBill = (int) $_POST["printBill"];
">$sellBillIdold = (int) $_POST["sellBillIdold"];
">if ($sellBillIdold > 0) {
delete(">$sellBillIdold); // Delete old bill if exists
}
// Process kitchen completion logic
// Mark order as ready, print if requested
}
SQL Operations:
-- Delete old bill if updating
DELETE FROM sellbill WHERE sellbillid = ?
DELETE FROM sellbillunit WHERE sellbillunitsellbillid = ?
-- Update kitchen order status
UPDATE restaurantorder SET kitchen_status = 'completed039; WHERE tableId = ?
-- Mark order as ready for serving
UPDATE restaurantorder SET ready_for_service = 1 WHERE id = ?
API Endpoint: POST /controllers/sellbillController.php?do=endKitchenBill
Request Body:
{
"tableId": 5,
"printBill": 1,
"sellBillIdold": 123
}
---
// Line 2808+ in sellbillController.php
">elseif ($do == "addapi") {
// API-specific bill creation logic
// Handles JSON input, validates, creates bill
// Returns JSON response for external systems
}
SQL Operations:
-- Same as standard add operation but with API response format
INSERT INTO sellbill (...) VALUES (...)
INSERT INTO sellbillunit (...) VALUES (...)
-- Create daily entry for accounting
INSERT INTO dailyentry (...) VALUES (...)
API Endpoint: POST /api/v1/bills (mapped to sellbillController.php?do=addapi)
Request/Response: JSON format for POS integration
---
// Line 3032+ in sellbillController.php
">elseif ($do == "addAndRetuen") {
// Create original sale
// Process return items
// Calculate net transaction
// Handle accounting entries for both sale and return
}
Business Logic: Used for exchanges where customer returns items and purchases different ones in single transaction
---
// Line 3137+ in sellbillController.php
">elseif ($do == "addAndSend") {
// Create sale bill
// Process delivery information
// Update shipping status
// Integrate with logistics
}
Business Logic: E-commerce/delivery service integration
---
// Line 3243+ in sellbillController.php
">elseif ($do == "addAndPrint") {
// Create sale bill
// Generate print job
// Send to printer
// Return print status
}
Business Logic: POS terminal integration with receipt printers
---