diff --git a/src/container/PaymentContainer/index.js b/src/container/PaymentContainer/index.js index 02a9f15..4d35470 100644 --- a/src/container/PaymentContainer/index.js +++ b/src/container/PaymentContainer/index.js @@ -12,1167 +12,1177 @@ import PaymentScreen from "@screens/Payment"; const moment = require("moment"); @inject( - "itemStore", - "customerStore", - "receiptStore", - "discountStore", - "categoryStore", - "paymentStore", - "printerStore", - "shiftStore", - "attendantStore", - "stateStore", + "itemStore", + "customerStore", + "receiptStore", + "discountStore", + "categoryStore", + "paymentStore", + "printerStore", + "shiftStore", + "attendantStore", + "stateStore", ) @observer export default class PaymentContainer extends React.Component { - constructor(props) { - super(props); - this.state = { - arrayObjects: [], - }; - } + constructor(props) { + super(props); + this.state = { + arrayObjects: [], + }; + } - componentWillMount() { - this.props.stateStore.changeValue("value", "0", "Payment"); + componentWillMount() { + this.props.stateStore.changeValue("value", "0", "Payment"); - if (this.props.customerStore.rows.length > 0) { - this.setState({ arrayObjects: this.props.customerStore.rows.slice() }); - } - const { params } = this.props.navigation.state; - // this.setState({ amountDue: params.value.toString() }); + if (this.props.customerStore.rows.length > 0) { + this.setState({ arrayObjects: this.props.customerStore.rows.slice() }); + } + const { params } = this.props.navigation.state; + // this.setState({ amountDue: params.value.toString() }); + this.props.stateStore.changeValue( + "amountDue", + params.value.toString(), + "Payment", + ); + + this.getBluetoothState(params.receipt); + if (!this.props.printerStore.defaultPrinter) { + // this.setState({ connectionStatus: "No Default Printer" }); + this.props.stateStore.changeValue( + "connectionStatus", + "No Default Printer", + "Payment", + ); + } + for (let i = 0; i < this.props.printerStore.rows.length; i += 1) { + if (this.props.printerStore.rows[i].defaultPrinter) { + // this.setState({ connectionStatus: "Connecting..." }); this.props.stateStore.changeValue( - "amountDue", - params.value.toString(), - "Payment", + "connectionStatus", + "Connecting...", + "Payment", ); - this.getBluetoothState(params.receipt); - if (!this.props.printerStore.defaultPrinter) { - // this.setState({ connectionStatus: "No Default Printer" }); + BluetoothSerial.connect(this.props.printerStore.rows[i].macAddress) + .then(() => { + // this.setState({ connection: true }); + this.props.stateStore.changeValue("connection", true, "Payment"); + + this.props.printerStore.setDefaultPrinter({ + _id: this.props.printerStore.rows[i]._id, + name: this.props.printerStore.rows[i].name, + macAddress: this.props.printerStore.rows[i].macAddress, + defaultPrinter: this.props.printerStore.rows[i].defaultPrinter, + }); + }) + .catch(() => { + // this.setState({ connectionStatus: "Connecting..." }); this.props.stateStore.changeValue( - "connectionStatus", - "No Default Printer", - "Payment", + "connectionStatus", + "Connecting...", + "Payment", ); - } - for (let i = 0; i < this.props.printerStore.rows.length; i += 1) { - if (this.props.printerStore.rows[i].defaultPrinter) { - // this.setState({ connectionStatus: "Connecting..." }); + + BluetoothSerial.connect(this.props.printerStore.rows[i].macAddress) + .then(() => { + // this.setState({ connection: true }); this.props.stateStore.changeValue( - "connectionStatus", - "Connecting...", - "Payment", + "connection", + true, + "Payment", ); - BluetoothSerial.connect(this.props.printerStore.rows[i].macAddress) - .then(() => { - // this.setState({ connection: true }); - this.props.stateStore.changeValue("connection", true, "Payment"); - - this.props.printerStore.setDefaultPrinter({ - _id: this.props.printerStore.rows[i]._id, - name: this.props.printerStore.rows[i].name, - macAddress: this.props.printerStore.rows[i].macAddress, - defaultPrinter: this.props.printerStore.rows[i].defaultPrinter, - }); - }) - .catch(() => { - // this.setState({ connectionStatus: "Connecting..." }); - this.props.stateStore.changeValue( - "connectionStatus", - "Connecting...", - "Payment", - ); - - BluetoothSerial.connect(this.props.printerStore.rows[i].macAddress) - .then(() => { - // this.setState({ connection: true }); - this.props.stateStore.changeValue( - "connection", - true, - "Payment", - ); - - this.props.printerStore.setDefaultPrinter({ - _id: this.props.printerStore.rows[i]._id, - name: this.props.printerStore.rows[i].name, - macAddress: this.props.printerStore.rows[i].macAddress, - defaultPrinter: this.props.printerStore.rows[i] - .defaultPrinter, - }); - }) - .catch(() => { - // this.setState({ connectionStatus: "Offline" }); - this.props.stateStore.changeValue( - "connectionStatus", - "Offline", - "Payment", - ); - }); - }); - } - } + this.props.printerStore.setDefaultPrinter({ + _id: this.props.printerStore.rows[i]._id, + name: this.props.printerStore.rows[i].name, + macAddress: this.props.printerStore.rows[i].macAddress, + defaultPrinter: this.props.printerStore.rows[i] + .defaultPrinter, + }); + }) + .catch(() => { + // this.setState({ connectionStatus: "Offline" }); + this.props.stateStore.changeValue( + "connectionStatus", + "Offline", + "Payment", + ); + }); + }); + } } - async getBluetoothState(value) { - if (value) { - BluetoothStatus.enable(true); - } else { - BluetoothStatus.disable(true); - } + } + async getBluetoothState(value) { + if (value) { + BluetoothStatus.enable(true); + } else { + BluetoothStatus.disable(true); } - onValueChange(text) { - if (text === "Del") { - const finalValue = this.props.stateStore.payment_state[0].value.slice( - 0, - -1, - ); - // this.setState({ value: finalValue }); - this.props.stateStore.changeValue("value", finalValue, "Payment"); + } + onValueChange(text) { + if (text === "Del") { + const finalValue = this.props.stateStore.payment_state[0].value.slice( + 0, + -1, + ); + // this.setState({ value: finalValue }); + this.props.stateStore.changeValue("value", finalValue, "Payment"); + } else { + if (text.length > 1) { + // this.setState({ value: text }); + this.props.stateStore.changeValue("value", text, "Payment"); + } else { + if (this.props.stateStore.payment_state[0].value === "0") { + // this.setState({ value: text }); + this.props.stateStore.changeValue("value", text, "Payment"); } else { - if (text.length > 1) { - // this.setState({ value: text }); - this.props.stateStore.changeValue("value", text, "Payment"); - } else { - if (this.props.stateStore.payment_state[0].value === "0") { - // this.setState({ value: text }); - this.props.stateStore.changeValue("value", text, "Payment"); - } else { - // this.setState({ value: this.state.value + text }); - this.props.stateStore.changeValue( - "value", - this.props.stateStore.payment_state[0].value + text, - "Payment", - ); - } - } + // this.setState({ value: this.state.value + text }); + this.props.stateStore.changeValue( + "value", + this.props.stateStore.payment_state[0].value + text, + "Payment", + ); } + } } - async onPay() { - if (this.props.stateStore.payment_state[0].value) { - if ( - parseFloat(this.props.stateStore.payment_state[0].value, 10) < - parseFloat(this.props.stateStore.payment_state[0].amountDue, 10) - ) { - Alert.alert( - "Alert", - "Amount Paid must be greater than or equal to Amount Due", - ); - } else if ( - parseInt(this.props.stateStore.payment_state[0].value, 10) >= - parseInt(this.props.stateStore.payment_state[0].amountDue, 10) - ) { - let receiptNumber = await this.props.receiptStore.numberOfReceipts(); - let receiptNumberLength = receiptNumber.toString().length; - let finalReceiptNumber = ""; - for ( - let lengthNumber = 0; - lengthNumber < 15 - receiptNumberLength; - lengthNumber += 1 - ) { - finalReceiptNumber = finalReceiptNumber + "0"; - } - finalReceiptNumber = finalReceiptNumber + receiptNumber.toString(); - let receiptCurrent = this.props.receiptStore.defaultReceipt; - - - - BluetoothSerial.isConnected().then(res => { - let totalPurchase = 0.0; - //Let me print first - Alert.alert( - "Receipt Confirmation", // title - "Do you want to print receipt?", - [ - { - text: "No", - style: "cancel", - onPress: () => { - this.props.shiftStore.defaultShift.addTotalDiscount( - receiptCurrent.discounts, - ); - this.props.shiftStore.defaultShift.addNumberOfTransaction(); - this.props.shiftStore.defaultShift.addTotalTaxes( - receiptCurrent.taxesValue, - ); - this.props.shiftStore.defaultShift.addTotalTaxes( - receiptCurrent.taxesValue, - ); - // Let me print first - let totalAmountDue = 0.0; - this.props.receiptStore.defaultReceipt.lines.map(val => { - const { defaultShift } = this.props.shiftStore; - defaultShift.addCommission(parseInt(val.commission_amount, 10)); + } + async onPay() { + if (this.props.stateStore.payment_state[0].value) { + if ( + parseFloat(this.props.stateStore.payment_state[0].value, 10) < + parseFloat(this.props.stateStore.payment_state[0].amountDue, 10) + ) { + Alert.alert( + "Alert", + "Amount Paid must be greater than or equal to Amount Due", + ); + } else if ( + parseInt(this.props.stateStore.payment_state[0].value, 10) >= + parseInt(this.props.stateStore.payment_state[0].amountDue, 10) + ) { + let receiptNumber = await this.props.receiptStore.numberOfReceipts(); + let receiptNumberLength = receiptNumber.toString().length; + let finalReceiptNumber = ""; + for ( + let lengthNumber = 0; + lengthNumber < 15 - receiptNumberLength; + lengthNumber += 1 + ) { + finalReceiptNumber = finalReceiptNumber + "0"; + } + finalReceiptNumber = finalReceiptNumber + receiptNumber.toString(); + let receiptCurrent = this.props.receiptStore.defaultReceipt; - totalAmountDue = - parseInt(totalAmountDue, 10) + - parseInt(val.price.toFixed(2), 10) * - parseInt(val.qty.toFixed(2), 10); - }); - this.props.shiftStore.defaultShift.addTotalSales(totalAmountDue); - this.props.receiptStore.defaultReceipt.lines.map(val => { - totalPurchase = - parseFloat(totalPurchase, 10) + - parseFloat(val.price, 10) * parseFloat(val.qty, 10); - }); + BluetoothSerial.isConnected().then(res => { + let totalPurchase = 0.0; + //Let me print first + Alert.alert( + "Receipt Confirmation", // title + "Do you want to print receipt?", + [ + { + text: "No", + style: "cancel", + onPress: () => { + this.props.shiftStore.defaultShift.addTotalDiscount( + receiptCurrent.discounts, + ); + this.props.shiftStore.defaultShift.addNumberOfTransaction(); + this.props.shiftStore.defaultShift.addTotalTaxes( + receiptCurrent.taxesValue, + ); + this.props.shiftStore.defaultShift.addTotalTaxes( + receiptCurrent.taxesValue, + ); + // Let me print first + let totalAmountDue = 0.0; + this.props.receiptStore.defaultReceipt.lines.map(val => { + const { defaultShift } = this.props.shiftStore; + defaultShift.addCommission( + parseInt(val.commission_amount, 10), + ); - receiptCurrent.completed( - this.props.attendantStore.defaultAttendant.user_name, - ); - const { defaultShift } = this.props.shiftStore; + totalAmountDue = + parseInt(totalAmountDue, 10) + + parseInt(val.price.toFixed(2), 10) * + parseInt(val.qty.toFixed(2), 10); + }); + this.props.shiftStore.defaultShift.addTotalSales( + totalAmountDue, + ); + this.props.receiptStore.defaultReceipt.lines.map(val => { + totalPurchase = + parseFloat(totalPurchase, 10) + + parseFloat(val.price, 10) * parseFloat(val.qty, 10); + }); - // If shift started and shift hasn't ended - if (defaultShift.shiftStarted && !defaultShift.shiftEnded) { - // Set the default receipt - const { defaultReceipt } = this.props.receiptStore; + receiptCurrent.completed( + this.props.attendantStore.defaultAttendant.user_name, + ); + const { defaultShift } = this.props.shiftStore; - // set shift - defaultReceipt.setShift(defaultShift._id); + // If shift started and shift hasn't ended + if (defaultShift.shiftStarted && !defaultShift.shiftEnded) { + // Set the default receipt + const { defaultReceipt } = this.props.receiptStore; - const { ending_cash } = defaultShift; + // set shift + defaultReceipt.setShift(defaultShift._id); - // Set the end cash - defaultShift.setEndCash( - ending_cash + defaultReceipt.netTotal, - ); - } + const { ending_cash } = defaultShift; - // this.props.receiptStore.defaultReceipt.clear(); - this.props.paymentStore.add({ - receipt: this.props.receiptStore.defaultReceipt._id.toString(), - date: Date.now(), - paid: parseInt( - this.props.stateStore.payment_state[0].value, - 10, - ), - type: this.props.stateStore.payment_state[0].selected, - dateUpdated: Date.now(), - syncStatus: false, - }); - this.props.receiptStore.add( - this.props.receiptStore.defaultReceipt, - ); - this.props.receiptStore.setPreviousReceipt( - this.props.receiptStore.defaultReceipt, - ); - let discountValueForDisplay = this.props.receiptStore - .defaultReceipt.discounts; - let taxesValueForDisplay = this.props.receiptStore - .defaultReceipt.taxesValue; - this.props.receiptStore.newReceipt(); - this.props.receiptStore.setLastScannedBarcode(""); - this.props.receiptStore.unselectReceiptLine(); - this.props.navigation.navigate("Sales", { - cash: this.props.stateStore.payment_state[0].value, - change: parseFloat( - parseFloat( - this.props.stateStore.payment_state[0].value, - 10, - ) - - (parseFloat(totalPurchase, 10) - - parseFloat(discountValueForDisplay, 10) + - parseFloat(taxesValueForDisplay, 10)), - 10, - ), - }); - }, - }, - { - text: "Yes", - onPress: () => { - this.props.shiftStore.defaultShift.addTotalDiscount( - receiptCurrent.discounts, - ); - this.props.shiftStore.defaultShift.addNumberOfTransaction(); - this.props.shiftStore.defaultShift.addTotalTaxes( - receiptCurrent.taxesValue, - ); - this.props.shiftStore.defaultShift.addTotalTaxes( - receiptCurrent.taxesValue, - ); - // Let me print first - let totalAmountDue = 0.0; - this.props.receiptStore.defaultReceipt.lines.map(val => { - const { defaultShift } = this.props.shiftStore; - defaultShift.addCommission(parseInt(val.commission_amount, 10)); + // Set the end cash + defaultShift.setEndCash( + ending_cash + defaultReceipt.netTotal, + ); + } - totalAmountDue = - parseInt(totalAmountDue, 10) + - parseInt(val.price.toFixed(2), 10) * - parseInt(val.qty.toFixed(2), 10); - }); - this.props.shiftStore.defaultShift.addTotalSales(totalAmountDue); - if (res) { - const writePromises = []; + // this.props.receiptStore.defaultReceipt.clear(); + this.props.paymentStore.add({ + receipt: this.props.receiptStore.defaultReceipt._id.toString(), + date: Date.now(), + paid: parseInt( + this.props.stateStore.payment_state[0].value, + 10, + ), + type: this.props.stateStore.payment_state[0].selected, + dateUpdated: Date.now(), + syncStatus: false, + }); + this.props.receiptStore.add( + this.props.receiptStore.defaultReceipt, + ); + this.props.receiptStore.setPreviousReceipt( + this.props.receiptStore.defaultReceipt, + ); + let discountValueForDisplay = this.props.receiptStore + .defaultReceipt.discounts; + let taxesValueForDisplay = this.props.receiptStore + .defaultReceipt.taxesValue; + this.props.receiptStore.newReceipt(); + this.props.receiptStore.setLastScannedBarcode(""); + this.props.receiptStore.unselectReceiptLine(); + this.props.navigation.navigate("Sales", { + cash: this.props.stateStore.payment_state[0].value, + change: parseFloat( + parseFloat( + this.props.stateStore.payment_state[0].value, + 10, + ) - + (parseFloat(totalPurchase, 10) - + parseFloat(discountValueForDisplay, 10) + + parseFloat(taxesValueForDisplay, 10)), + 10, + ), + }); + }, + }, + { + text: "Yes", + onPress: () => { + this.props.shiftStore.defaultShift.addTotalDiscount( + receiptCurrent.discounts, + ); + this.props.shiftStore.defaultShift.addNumberOfTransaction(); + this.props.shiftStore.defaultShift.addTotalTaxes( + receiptCurrent.taxesValue, + ); + this.props.shiftStore.defaultShift.addTotalTaxes( + receiptCurrent.taxesValue, + ); + // Let me print first + let totalAmountDue = 0.0; + this.props.receiptStore.defaultReceipt.lines.map(val => { + const { defaultShift } = this.props.shiftStore; + defaultShift.addCommission( + parseInt(val.commission_amount, 10), + ); - writePromises.push(BluetoothSerial.write(TinyPOS.init())); + totalAmountDue = + parseInt(totalAmountDue, 10) + + parseInt(val.price.toFixed(2), 10) * + parseInt(val.qty.toFixed(2), 10); + }); + this.props.shiftStore.defaultShift.addTotalSales( + totalAmountDue, + ); + if (res) { + const writePromises = []; - // Header - writePromises.push( - BluetoothSerial.write( - TinyPOS.bufferedText( - `${ - this.props.printerStore.companySettings.length > 0 - ? this.props.printerStore.companySettings[0].name.toString() - : "Bai Web and Mobile Lab" - }`, - { align: "center", size: "doubleheight" }, - true, - ), - ), - ); + writePromises.push(BluetoothSerial.write(TinyPOS.init())); - writePromises.push( - BluetoothSerial.write( - TinyPOS.bufferedText( - `${ - this.props.printerStore.companySettings.length > 0 - ? this.props.printerStore.companySettings[0].header.toString() - : "" - }`, - { align: "center", size: "normal" }, - true, - ), - ), - ); + // Header + writePromises.push( + BluetoothSerial.write( + TinyPOS.bufferedText( + `${ + this.props.printerStore.companySettings.length > 0 + ? this.props.printerStore.companySettings[0].name.toString() + : "Bai Web and Mobile Lab" + }`, + { align: "center", size: "doubleheight" }, + true, + ), + ), + ); - writePromises.push( - BluetoothSerial.write( - TinyPOS.bufferedText( - "================================", - { size: "normal" }, - true, - ), - ), - ); + writePromises.push( + BluetoothSerial.write( + TinyPOS.bufferedText( + `${ + this.props.printerStore.companySettings.length > 0 + ? this.props.printerStore.companySettings[0].header.toString() + : "" + }`, + { align: "center", size: "normal" }, + true, + ), + ), + ); - // Date - writePromises.push( - BluetoothSerial.write( - TinyPOS.bufferedText( - `${moment().format("YYYY/MM/D hh:mm:ss SSS")}`, - { size: "normal" }, - true, - ), - ), - ); + writePromises.push( + BluetoothSerial.write( + TinyPOS.bufferedText( + "================================", + { size: "normal" }, + true, + ), + ), + ); - writePromises.push( - BluetoothSerial.write( - TinyPOS.bufferedText( - "================================", - { size: "normal" }, - true, - ), - ), - ); - writePromises.push( - BluetoothSerial.write( - TinyPOS.bufferedText( - "Cashier: " + - `${ - this.props.attendantStore.defaultAttendant - .user_name - }`, - { align: "left", size: "normal" }, - true, - ), - ), - ); - writePromises.push( - BluetoothSerial.write( - TinyPOS.bufferedText( - "Transaction No.:" + `${finalReceiptNumber}`, - { align: "left", size: "normal" }, - true, - ), - ), - ); - writePromises.push( - BluetoothSerial.write( - TinyPOS.bufferedText( - "================================", - { size: "normal" }, - true, - ), - ), - ); - writePromises.push( - BluetoothSerial.write( - TinyPOS.bufferedText( - "Purchases", - { align: "center", size: "normal" }, - true, - ), - ), - ); - writePromises.push( - BluetoothSerial.write( - TinyPOS.bufferedText( - "Items Amount ", - { align: "left", size: "normal", weight: "bold" }, - true, - ), - ), - ); + // Date + writePromises.push( + BluetoothSerial.write( + TinyPOS.bufferedText( + `${moment().format("YYYY/MM/D hh:mm:ss SSS")}`, + { size: "normal" }, + true, + ), + ), + ); - this.props.receiptStore.defaultReceipt.lines.map(val => { - let finalLines = ""; + writePromises.push( + BluetoothSerial.write( + TinyPOS.bufferedText( + "================================", + { size: "normal" }, + true, + ), + ), + ); + writePromises.push( + BluetoothSerial.write( + TinyPOS.bufferedText( + "Cashier: " + + `${ + this.props.attendantStore.defaultAttendant + .user_name + }`, + { align: "left", size: "normal" }, + true, + ), + ), + ); + writePromises.push( + BluetoothSerial.write( + TinyPOS.bufferedText( + "Transaction No.:" + `${finalReceiptNumber}`, + { align: "left", size: "normal" }, + true, + ), + ), + ); + writePromises.push( + BluetoothSerial.write( + TinyPOS.bufferedText( + "================================", + { size: "normal" }, + true, + ), + ), + ); + writePromises.push( + BluetoothSerial.write( + TinyPOS.bufferedText( + "Purchases", + { align: "center", size: "normal" }, + true, + ), + ), + ); + writePromises.push( + BluetoothSerial.write( + TinyPOS.bufferedText( + "Items Amount ", + { align: "left", size: "normal", weight: "bold" }, + true, + ), + ), + ); - const name = val.item_name; + this.props.receiptStore.defaultReceipt.lines.map(val => { + let finalLines = ""; - if (name.length > 14) { - let quotientValue = name.length / 14; - for ( - let quotient = 0; - quotient < parseInt(quotientValue, 10); - quotient += 1 - ) { - let currentCounter = quotient * 14; - let nameCounter = ""; - for ( - let n = currentCounter; - n < (quotient + 1) * 14; - n += 1 - ) { - nameCounter = nameCounter + name[n]; - } - writePromises.push( - BluetoothSerial.write( - TinyPOS.bufferedText( - `${nameCounter}`, - { align: "left", size: "normal" }, - true, - ), - ), - ); - } - if ( - name.length - parseInt(quotientValue, 10) * 14 > - 0 - ) { - let nameCounterOverflow = ""; - for ( - let m = parseInt(quotientValue, 10) * 14; - m < name.length; - m += 1 - ) { - nameCounterOverflow = nameCounterOverflow + name[m]; - } - writePromises.push( - BluetoothSerial.write( - TinyPOS.bufferedText( - `${nameCounterOverflow}`, - { align: "left", size: "normal" }, - true, - ), - ), - ); - } - } else { - writePromises.push( - BluetoothSerial.write( - TinyPOS.bufferedText( - `${name}`, - { align: "left", size: "normal" }, - true, - ), - ), - ); - } + const name = val.item_name; - let priceString = formatNumber( - parseFloat(val.price, 10), - ).toString(); - let qtyString = val.qty.toString(); - let amountString = formatNumber( - parseFloat(val.price, 10) * parseFloat(val.qty, 10), - ).toString(); + if (name.length > 14) { + let quotientValue = name.length / 14; + for ( + let quotient = 0; + quotient < parseInt(quotientValue, 10); + quotient += 1 + ) { + let currentCounter = quotient * 14; + let nameCounter = ""; + for ( + let n = currentCounter; + n < (quotient + 1) * 14; + n += 1 + ) { + nameCounter = nameCounter + name[n]; + } + writePromises.push( + BluetoothSerial.write( + TinyPOS.bufferedText( + `${nameCounter}`, + { align: "left", size: "normal" }, + true, + ), + ), + ); + } + if ( + name.length - parseInt(quotientValue, 10) * 14 > + 0 + ) { + let nameCounterOverflow = ""; + for ( + let m = parseInt(quotientValue, 10) * 14; + m < name.length; + m += 1 + ) { + nameCounterOverflow = nameCounterOverflow + name[m]; + } + writePromises.push( + BluetoothSerial.write( + TinyPOS.bufferedText( + `${nameCounterOverflow}`, + { align: "left", size: "normal" }, + true, + ), + ), + ); + } + } else { + writePromises.push( + BluetoothSerial.write( + TinyPOS.bufferedText( + `${name}`, + { align: "left", size: "normal" }, + true, + ), + ), + ); + } - for (let ps = 0; ps < 12 - priceString.length; ps += 1) { - finalLines = finalLines + " "; - } + let priceString = formatNumber( + parseFloat(val.price, 10), + ).toString(); + let qtyString = val.qty.toString(); + let amountString = formatNumber( + parseFloat(val.price, 10) * parseFloat(val.qty, 10), + ).toString(); - finalLines = finalLines + priceString; + for (let ps = 0; ps < 12 - priceString.length; ps += 1) { + finalLines = finalLines + " "; + } - for (let qt = 0; qt < 6 - qtyString.length; qt += 1) { - finalLines = finalLines + " "; - } - finalLines = finalLines + qtyString; + finalLines = finalLines + priceString; - for (let as = 0; as < 14 - amountString.length; as += 1) { - finalLines = finalLines + " "; - } + for (let qt = 0; qt < 6 - qtyString.length; qt += 1) { + finalLines = finalLines + " "; + } + finalLines = finalLines + qtyString; - finalLines = finalLines + amountString; - writePromises.push( - BluetoothSerial.write( - TinyPOS.bufferedText( - `${finalLines}`, - { align: "left", size: "normal" }, - true, - ), - ), - ); - totalPurchase = - parseFloat(totalPurchase, 10) + - parseFloat(val.price, 10) * parseFloat(val.qty, 10); - }); - writePromises.push( - BluetoothSerial.write( - TinyPOS.bufferedText( - "================================", - { align: "left", size: "normal", weight: "bold" }, - true, - ), - ), - ); + for (let as = 0; as < 14 - amountString.length; as += 1) { + finalLines = finalLines + " "; + } - let subTotal = "Sub Total"; - let sub = formatNumber( - parseFloat( - this.props.receiptStore.defaultReceipt.subtotal, - 10, - ), - ).toString(); - for (let t = 0; t < 23 - sub.length; t += 1) { - subTotal = subTotal + " "; - } - subTotal = subTotal + sub; - writePromises.push( - BluetoothSerial.write( - TinyPOS.bufferedText( - `${subTotal}`, - { align: "left", size: "normal" }, - true, - ), - ), - ); - let taxValue = "Tax"; - let tax = formatNumber( - parseFloat( - this.props.receiptStore.defaultReceipt.taxesValue, - 10, - ), - ).toString(); - for (let t = 0; t < 29 - tax.length; t += 1) { - taxValue = taxValue + " "; - } - taxValue = taxValue + tax; - writePromises.push( - BluetoothSerial.write( - TinyPOS.bufferedText( - `${taxValue}`, - { align: "left", size: "normal" }, - true, - ), - ), - ); - let discountValue = "Discount"; - let discount = formatNumber( - parseFloat( - this.props.receiptStore.defaultReceipt.discounts, - 10, - ), - ).toString(); - for (let d = 0; d < 24 - discount.length; d += 1) { - discountValue = discountValue + " "; - } - discountValue = discountValue + discount; - writePromises.push( - BluetoothSerial.write( - TinyPOS.bufferedText( - `${discountValue}`, - { align: "left", size: "normal" }, - true, - ), - ), - ); + finalLines = finalLines + amountString; + writePromises.push( + BluetoothSerial.write( + TinyPOS.bufferedText( + `${finalLines}`, + { align: "left", size: "normal" }, + true, + ), + ), + ); + totalPurchase = + parseFloat(totalPurchase, 10) + + parseFloat(val.price, 10) * parseFloat(val.qty, 10); + }); + writePromises.push( + BluetoothSerial.write( + TinyPOS.bufferedText( + "================================", + { align: "left", size: "normal", weight: "bold" }, + true, + ), + ), + ); - let total = ""; - total = total + "Total Amount"; + let subTotal = "Sub Total"; + let sub = formatNumber( + parseFloat( + this.props.receiptStore.defaultReceipt.subtotal, + 10, + ), + ).toString(); + for (let t = 0; t < 23 - sub.length; t += 1) { + subTotal = subTotal + " "; + } + subTotal = subTotal + sub; + writePromises.push( + BluetoothSerial.write( + TinyPOS.bufferedText( + `${subTotal}`, + { align: "left", size: "normal" }, + true, + ), + ), + ); + let taxValue = "Tax"; + let tax = formatNumber( + parseFloat( + this.props.receiptStore.defaultReceipt.taxesValue, + 10, + ), + ).toString(); + for (let t = 0; t < 29 - tax.length; t += 1) { + taxValue = taxValue + " "; + } + taxValue = taxValue + tax; + writePromises.push( + BluetoothSerial.write( + TinyPOS.bufferedText( + `${taxValue}`, + { align: "left", size: "normal" }, + true, + ), + ), + ); + let discountValue = "Discount"; + let discount = formatNumber( + parseFloat( + this.props.receiptStore.defaultReceipt.discounts, + 10, + ), + ).toString(); + for (let d = 0; d < 24 - discount.length; d += 1) { + discountValue = discountValue + " "; + } + discountValue = discountValue + discount; + writePromises.push( + BluetoothSerial.write( + TinyPOS.bufferedText( + `${discountValue}`, + { align: "left", size: "normal" }, + true, + ), + ), + ); - for ( - let totalLength = 0; - totalLength < - 20 - - formatNumber(parseFloat(totalPurchase, 10)).toString() - .length; - totalLength += 1 - ) { - total = total + " "; - } - total = - total + - formatNumber( - parseFloat(totalPurchase, 10) - - parseFloat( - this.props.receiptStore.defaultReceipt.discounts, - 10, - ) + - parseFloat( - this.props.receiptStore.defaultReceipt.taxesValue, - 10, - ), - ).toString(); + let total = ""; + total = total + "Total Amount"; - writePromises.push( - BluetoothSerial.write( - TinyPOS.bufferedText( - `${total}`, - { align: "left", size: "normal", weight: "bold" }, - true, - ), - ), - ); - let cash = "Cash"; - for ( - let cashLength = 0; - cashLength < - 28 - - formatNumber( - parseFloat( - this.props.stateStore.payment_state[0].value, - 10, - ), - ).toString().length; - cashLength += 1 - ) { - cash = cash + " "; - } - cash = - cash + - formatNumber( - parseFloat( - this.props.stateStore.payment_state[0].value, - 10, - ), - ).toString(); - writePromises.push( - BluetoothSerial.write( - TinyPOS.bufferedText( - `${cash}`, - { align: "left", size: "normal", weight: "bold" }, - true, - ), - ), - ); - let change = "Change"; - let changeValue = formatNumber( - parseFloat( - parseFloat( - this.props.stateStore.payment_state[0].value, - 10, - ) - - (parseFloat(totalPurchase, 10) - - parseFloat( - this.props.receiptStore.defaultReceipt.discounts, - 10, - ) + - parseFloat( - this.props.receiptStore.defaultReceipt.taxesValue, - 10, - )), - 10, - ), - ).toString(); - for ( - let changeLength = 0; - changeLength < 26 - changeValue.length; - changeLength += 1 - ) { - change = change + " "; - } - change = change + changeValue; + for ( + let totalLength = 0; + totalLength < + 20 - + formatNumber(parseFloat(totalPurchase, 10)).toString() + .length; + totalLength += 1 + ) { + total = total + " "; + } + total = + total + + formatNumber( + parseFloat(totalPurchase, 10) - + parseFloat( + this.props.receiptStore.defaultReceipt.discounts, + 10, + ) + + parseFloat( + this.props.receiptStore.defaultReceipt.taxesValue, + 10, + ), + ).toString(); - writePromises.push( - BluetoothSerial.write( - TinyPOS.bufferedText( - `${change}`, - { align: "left", size: "normal", weight: "bold" }, - true, - ), - ), - ); - writePromises.push( - BluetoothSerial.write( - TinyPOS.bufferedText( - "================================", - { size: "normal" }, - true, - ), - ), - ); - writePromises.push( - BluetoothSerial.write( - TinyPOS.bufferedText( - "This serves as your", - { align: "center", size: "doubleheight" }, - true, - ), - ), - ); - writePromises.push( - BluetoothSerial.write( - TinyPOS.bufferedText( - "Official Receipt\n", - { align: "center", size: "doubleheight" }, - true, - ), - ), - ); - writePromises.push( - BluetoothSerial.write( - TinyPOS.bufferedText( - `${ - this.props.printerStore.companySettings.length > 0 - ? this.props.printerStore.companySettings[0].footer.toString() - : "" - }`, - { align: "center", size: "normal" }, - true, - ), - ), - ); - writePromises.push( - BluetoothSerial.write( - TinyPOS.bufferedText( - "\n" + - "POS Provider:\n" + - "Bai Web and Mobile Lab\n" + - "Insular Life Bldg, Don Apolinar\n" + - "Velez cor. Oldarico Akut St.,\n" + - "Cagayan de Oro, 9000,\n" + - "Misamis Oriental\n" + - "Accred. No.: 1548769536521458745632\n" + - "Date Issued: 11/25/2018\n" + - "Valid Until: 11/24/2018\n\n", - { align: "left", size: "normal" }, - true, - ), - ), - ); - writePromises.push( - BluetoothSerial.write( - TinyPOS.bufferedText( - "THIS RECEIPT SHALL BE VALID FOR\n" + - "FIVE(5) YEARS FROM THE DATE OF\n" + - "THE PERMIT TO USE\n", - { align: "center", size: "normal" }, - true, - ), - ), - ); + writePromises.push( + BluetoothSerial.write( + TinyPOS.bufferedText( + `${total}`, + { align: "left", size: "normal", weight: "bold" }, + true, + ), + ), + ); + let cash = "Cash"; + for ( + let cashLength = 0; + cashLength < + 28 - + formatNumber( + parseFloat( + this.props.stateStore.payment_state[0].value, + 10, + ), + ).toString().length; + cashLength += 1 + ) { + cash = cash + " "; + } + cash = + cash + + formatNumber( + parseFloat( + this.props.stateStore.payment_state[0].value, + 10, + ), + ).toString(); + writePromises.push( + BluetoothSerial.write( + TinyPOS.bufferedText( + `${cash}`, + { align: "left", size: "normal", weight: "bold" }, + true, + ), + ), + ); + let change = "Change"; + let changeValue = formatNumber( + parseFloat( + parseFloat( + this.props.stateStore.payment_state[0].value, + 10, + ) - + (parseFloat(totalPurchase, 10) - + parseFloat( + this.props.receiptStore.defaultReceipt.discounts, + 10, + ) + + parseFloat( + this.props.receiptStore.defaultReceipt.taxesValue, + 10, + )), + 10, + ), + ).toString(); + for ( + let changeLength = 0; + changeLength < 26 - changeValue.length; + changeLength += 1 + ) { + change = change + " "; + } + change = change + changeValue; - // Add 3 new lines - writePromises.push( - BluetoothSerial.write(TinyPOS.bufferedLine(3)), - ); + writePromises.push( + BluetoothSerial.write( + TinyPOS.bufferedText( + `${change}`, + { align: "left", size: "normal", weight: "bold" }, + true, + ), + ), + ); + writePromises.push( + BluetoothSerial.write( + TinyPOS.bufferedText( + "================================", + { size: "normal" }, + true, + ), + ), + ); + writePromises.push( + BluetoothSerial.write( + TinyPOS.bufferedText( + "This serves as your", + { align: "center", size: "doubleheight" }, + true, + ), + ), + ); + writePromises.push( + BluetoothSerial.write( + TinyPOS.bufferedText( + "Official Receipt\n", + { align: "center", size: "doubleheight" }, + true, + ), + ), + ); + writePromises.push( + BluetoothSerial.write( + TinyPOS.bufferedText( + `${ + this.props.printerStore.companySettings.length > 0 + ? this.props.printerStore.companySettings[0].footer.toString() + : "" + }`, + { align: "center", size: "normal" }, + true, + ), + ), + ); + writePromises.push( + BluetoothSerial.write( + TinyPOS.bufferedText( + "\n" + + "POS Provider:\n" + + "Bai Web and Mobile Lab\n" + + "Insular Life Bldg, Don Apolinar\n" + + "Velez cor. Oldarico Akut St.,\n" + + "Cagayan de Oro, 9000,\n" + + "Misamis Oriental\n" + + "Accred. No.: 1548769536521458745632\n" + + "Date Issued: 11/25/2018\n" + + "Valid Until: 11/24/2018\n\n", + { align: "left", size: "normal" }, + true, + ), + ), + ); + writePromises.push( + BluetoothSerial.write( + TinyPOS.bufferedText( + "THIS RECEIPT SHALL BE VALID FOR\n" + + "FIVE(5) YEARS FROM THE DATE OF\n" + + "THE PERMIT TO USE\n", + { align: "center", size: "normal" }, + true, + ), + ), + ); - // Push drawer - writePromises.push( - BluetoothSerial.write(TinyPOS.kickCashDrawer()), - ); - writePromises.push( - BluetoothSerial.write(TinyPOS.kickCashDrawer()), - ); + // Add 3 new lines + writePromises.push( + BluetoothSerial.write(TinyPOS.bufferedLine(3)), + ); - Promise.all(writePromises) - .then(res2 => { - receiptCurrent.completed( - this.props.attendantStore.defaultAttendant.user_name, - ); + // Push drawer + writePromises.push( + BluetoothSerial.write(TinyPOS.kickCashDrawer()), + ); + writePromises.push( + BluetoothSerial.write(TinyPOS.kickCashDrawer()), + ); - // add to row - this.props.paymentStore.add({ - receipt: this.props.receiptStore.defaultReceipt._id.toString(), - date: Date.now(), - paid: parseInt( - this.props.stateStore.payment_state[0].value, - 10, - ), - type: this.props.stateStore.payment_state[0].selected, - dateUpdated: Date.now(), - syncStatus: false, - }); + Promise.all(writePromises) + .then(res2 => { + receiptCurrent.completed( + this.props.attendantStore.defaultAttendant.user_name, + ); - // Reset payment amount - // this.setState({ - // modalVisible: false, - // paymentAmount: 0, - // }); - this.props.stateStore.changeValue( - "modalVisible", - false, - "Payment", - ); - this.props.stateStore.changeValue( - "paymentAmount", - 0, - "Payment", - ); + // add to row + this.props.paymentStore.add({ + receipt: this.props.receiptStore.defaultReceipt._id.toString(), + date: Date.now(), + paid: parseInt( + this.props.stateStore.payment_state[0].value, + 10, + ), + type: this.props.stateStore.payment_state[0].selected, + dateUpdated: Date.now(), + syncStatus: false, + }); - Toast.show({ - text: "Transaction Completed", - duration: 5000, - }); - }) - .catch(err => { - receiptCurrent.completed( - this.props.attendantStore.defaultAttendant.user_name, - ); + // Reset payment amount + // this.setState({ + // modalVisible: false, + // paymentAmount: 0, + // }); + this.props.stateStore.changeValue( + "modalVisible", + false, + "Payment", + ); + this.props.stateStore.changeValue( + "paymentAmount", + 0, + "Payment", + ); - // add to row - this.props.paymentStore.add({ - receipt: this.props.receiptStore.defaultReceipt._id.toString(), - date: Date.now(), - paid: parseInt( - this.props.stateStore.payment_state[0].value, - 10, - ), - type: this.props.stateStore.payment_state[0].selected, - dateUpdated: Date.now(), - syncStatus: false, - }); - // this.setState({ - // modalVisible: false, - // paymentAmount: 0, - // }); - this.props.stateStore.changeValue( - "modalVisible", - false, - "Payment", - ); - this.props.stateStore.changeValue( - "paymentAmount", - 0, - "Payment", - ); - Toast.show({ - text: err.message + "Transaction Completed", - buttonText: "Okay", - position: "bottom", - duration: 5000, - }); - }); - } else { - receiptCurrent.completed( - this.props.attendantStore.defaultAttendant.user_name, - ); + Toast.show({ + text: "Transaction Completed", + duration: 5000, + }); + }) + .catch(err => { + receiptCurrent.completed( + this.props.attendantStore.defaultAttendant.user_name, + ); - // add to row - this.props.paymentStore.add({ - receipt: this.props.receiptStore.defaultReceipt._id.toString(), - date: Date.now(), - paid: parseInt( - this.props.stateStore.payment_state[0].value, - 10, - ), - type: this.props.stateStore.payment_state[0].selected, - dateUpdated: Date.now(), - syncStatus: false, - }); + // add to row + this.props.paymentStore.add({ + receipt: this.props.receiptStore.defaultReceipt._id.toString(), + date: Date.now(), + paid: parseInt( + this.props.stateStore.payment_state[0].value, + 10, + ), + type: this.props.stateStore.payment_state[0].selected, + dateUpdated: Date.now(), + syncStatus: false, + }); + // this.setState({ + // modalVisible: false, + // paymentAmount: 0, + // }); + this.props.stateStore.changeValue( + "modalVisible", + false, + "Payment", + ); + this.props.stateStore.changeValue( + "paymentAmount", + 0, + "Payment", + ); + Toast.show({ + text: err.message + "Transaction Completed", + buttonText: "Okay", + position: "bottom", + duration: 5000, + }); + }); + } else { + receiptCurrent.completed( + this.props.attendantStore.defaultAttendant.user_name, + ); - // this.setState({ - // modalVisible: false, - // paymentAmount: 0, - // }); - this.props.stateStore.changeValue( - "modalVisible", - false, - "Payment", - ); - this.props.stateStore.changeValue( - "paymentAmount", - 0, - "Payment", - ); - Toast.show({ - text: "Transaction Complete. [Unable to Connect Printer]", - buttonText: "Okay", - position: "bottom", - duration: 6000, - }); - } + // add to row + this.props.paymentStore.add({ + receipt: this.props.receiptStore.defaultReceipt._id.toString(), + date: Date.now(), + paid: parseInt( + this.props.stateStore.payment_state[0].value, + 10, + ), + type: this.props.stateStore.payment_state[0].selected, + dateUpdated: Date.now(), + syncStatus: false, + }); - const { defaultShift } = this.props.shiftStore; + // this.setState({ + // modalVisible: false, + // paymentAmount: 0, + // }); + this.props.stateStore.changeValue( + "modalVisible", + false, + "Payment", + ); + this.props.stateStore.changeValue( + "paymentAmount", + 0, + "Payment", + ); + Toast.show({ + text: "Transaction Complete. [Unable to Connect Printer]", + buttonText: "Okay", + position: "bottom", + duration: 6000, + }); + } - // If shift started and shift hasn't ended - if (defaultShift.shiftStarted && !defaultShift.shiftEnded) { - // Set the default receipt - const { defaultReceipt } = this.props.receiptStore; + const { defaultShift } = this.props.shiftStore; - // set shift - defaultReceipt.setShift(defaultShift._id); + // If shift started and shift hasn't ended + if (defaultShift.shiftStarted && !defaultShift.shiftEnded) { + // Set the default receipt + const { defaultReceipt } = this.props.receiptStore; - const { ending_cash } = defaultShift; + // set shift + defaultReceipt.setShift(defaultShift._id); - // Set the end cash - defaultShift.setEndCash( - ending_cash + defaultReceipt.netTotal, - ); - } + const { ending_cash } = defaultShift; - // this.props.receiptStore.defaultReceipt.clear(); - this.props.receiptStore.add( - this.props.receiptStore.defaultReceipt, - ); - this.props.receiptStore.setPreviousReceipt( - this.props.receiptStore.defaultReceipt, - ); - let discountValueForDisplay = this.props.receiptStore - .defaultReceipt.discounts; - let taxesValueForDisplay = this.props.receiptStore - .defaultReceipt.taxesValue; - this.props.receiptStore.newReceipt(); - this.props.receiptStore.setLastScannedBarcode(""); - this.props.receiptStore.unselectReceiptLine(); - this.props.navigation.navigate("Sales", { - cash: this.props.stateStore.payment_state[0].value, - change: parseFloat( - parseFloat( - this.props.stateStore.payment_state[0].value, - 10, - ) - - (parseFloat(totalPurchase, 10) - - parseFloat(discountValueForDisplay, 10) + - parseFloat(taxesValueForDisplay, 10)), - 10, - ), - }); - }, - }, - ], + // Set the end cash + defaultShift.setEndCash( + ending_cash + defaultReceipt.netTotal, ); - }); - } - } else { - Alert.alert("Alert", "Please Enter valid Amount"); - } - } + } - onBack() { - this.props.navigation.goBack(); + // this.props.receiptStore.defaultReceipt.clear(); + this.props.receiptStore.add( + this.props.receiptStore.defaultReceipt, + ); + this.props.receiptStore.setPreviousReceipt( + this.props.receiptStore.defaultReceipt, + ); + let discountValueForDisplay = this.props.receiptStore + .defaultReceipt.discounts; + let taxesValueForDisplay = this.props.receiptStore + .defaultReceipt.taxesValue; + this.props.receiptStore.newReceipt(); + this.props.receiptStore.setLastScannedBarcode(""); + this.props.receiptStore.unselectReceiptLine(); + this.props.navigation.navigate("Sales", { + cash: this.props.stateStore.payment_state[0].value, + change: parseFloat( + parseFloat( + this.props.stateStore.payment_state[0].value, + 10, + ) - + (parseFloat(totalPurchase, 10) - + parseFloat(discountValueForDisplay, 10) + + parseFloat(taxesValueForDisplay, 10)), + 10, + ), + }); + }, + }, + ], + ); + }); + } + } else { + Alert.alert("Alert", "Please Enter valid Amount"); } + } - onPrinterChange(value) { - // this.setState({ itemSelected: value }); - this.props.stateStore.changeValue("itemSelected", value, "Payment"); - BluetoothSerial.connect("DC:0D:30:0B:77:B1") - .then(res => { - // this.setState({ connection: true }); - this.props.stateStore.changeValue("connection", true, "Payment"); - }) - .catch(() => { - // this.setState({ connection: false }); - this.props.stateStore.changeValue("connection", false, "Payment"); - }); - } + onBack() { + this.props.navigation.goBack(); + } - onPrinterPress() { - this.props.navigation.navigate("Settings"); - } + onPrinterChange(value) { + // this.setState({ itemSelected: value }); + this.props.stateStore.changeValue("itemSelected", value, "Payment"); + BluetoothSerial.connect("DC:0D:30:0B:77:B1") + .then(res => { + // this.setState({ connection: true }); + this.props.stateStore.changeValue("connection", true, "Payment"); + }) + .catch(() => { + // this.setState({ connection: false }); + this.props.stateStore.changeValue("connection", false, "Payment"); + }); + } - onConnectDevice() { - if (this.props.printerStore.rows.length > 0) { - for (let i = 0; i < this.props.printerStore.rows.length; i += 1) { - if (this.props.printerStore.rows[i].defaultPrinter) { - // this.setState({ connectionStatus: "Connecting..." }); - this.props.stateStore.changeValue( - "connectionStatus", - "Connecting...", - "Payment", - ); + onPrinterPress() { + this.props.navigation.navigate("Settings"); + } - BluetoothSerial.connect(this.props.printerStore.rows[i].macAddress) - .then(() => { - // this.setState({ connection: true }); - this.props.stateStore.changeValue("connection", true, "Payment"); + onConnectDevice() { + if (this.props.printerStore.rows.length > 0) { + for (let i = 0; i < this.props.printerStore.rows.length; i += 1) { + if (this.props.printerStore.rows[i].defaultPrinter) { + // this.setState({ connectionStatus: "Connecting..." }); + this.props.stateStore.changeValue( + "connectionStatus", + "Connecting...", + "Payment", + ); - this.props.printerStore.setDefaultPrinter({ - _id: this.props.printerStore.rows[i]._id, - name: this.props.printerStore.rows[i].name, - macAddress: this.props.printerStore.rows[i].macAddress, - defaultPrinter: this.props.printerStore.rows[i].defaultPrinter, - }); - // this.setState({ connectionStatus: "Connected" }); - this.props.stateStore.changeValue( - "connectionStatus", - "Connected", - "Payment", - ); - }) - .catch(() => { - BluetoothSerial.connect( - this.props.printerStore.rows[i].macAddress, - ) - .then(() => { - // this.setState({ connection: true }); - this.props.stateStore.changeValue( - "connection", - true, - "Payment", - ); + BluetoothSerial.connect(this.props.printerStore.rows[i].macAddress) + .then(() => { + // this.setState({ connection: true }); + this.props.stateStore.changeValue("connection", true, "Payment"); - this.props.printerStore.setDefaultPrinter({ - _id: this.props.printerStore.rows[i]._id, - name: this.props.printerStore.rows[i].name, - macAddress: this.props.printerStore.rows[i].macAddress, - defaultPrinter: this.props.printerStore.rows[i] - .defaultPrinter, - }); - // this.setState({ connectionStatus: "Connected" }); - this.props.stateStore.changeValue( - "connectionStatus", - "Connected", - "Payment", - ); - }) - .catch(() => { - // this.setState({ connectionStatus: "Not Connected" }); - this.props.stateStore.changeValue( - "connectionStatus", - "Not Connected", - "Payment", - ); - }); - }); - } - } - } else { - Toast.show({ - text: "No added printer device", - buttonText: "Okay", - position: "bottom", - duration: 6000, + this.props.printerStore.setDefaultPrinter({ + _id: this.props.printerStore.rows[i]._id, + name: this.props.printerStore.rows[i].name, + macAddress: this.props.printerStore.rows[i].macAddress, + defaultPrinter: this.props.printerStore.rows[i].defaultPrinter, + }); + // this.setState({ connectionStatus: "Connected" }); + this.props.stateStore.changeValue( + "connectionStatus", + "Connected", + "Payment", + ); + }) + .catch(() => { + BluetoothSerial.connect( + this.props.printerStore.rows[i].macAddress, + ) + .then(() => { + // this.setState({ connection: true }); + this.props.stateStore.changeValue( + "connection", + true, + "Payment", + ); + + this.props.printerStore.setDefaultPrinter({ + _id: this.props.printerStore.rows[i]._id, + name: this.props.printerStore.rows[i].name, + macAddress: this.props.printerStore.rows[i].macAddress, + defaultPrinter: this.props.printerStore.rows[i] + .defaultPrinter, + }); + // this.setState({ connectionStatus: "Connected" }); + this.props.stateStore.changeValue( + "connectionStatus", + "Connected", + "Payment", + ); + }) + .catch(() => { + // this.setState({ connectionStatus: "Not Connected" }); + this.props.stateStore.changeValue( + "connectionStatus", + "Not Connected", + "Payment", + ); + }); }); } + } + } else { + Toast.show({ + text: "No added printer device", + buttonText: "Okay", + position: "bottom", + duration: 6000, + }); } - searchCustomer(text) { - this.props.customerStore.search(text).then(result => { - for (let i = 0; i < result.length; i += 1) { - let existing = false; - for (let v = 0; v < this.state.arrayObjects.length; v += 1) { - if (result[i]._id === this.state.arrayObjects[v]._id) { - existing = true; - } - } - if (!existing) { - this.state.arrayObjects.push(result[i]); - } - } - }); - } - onSaveCustomer() { - if (this.props.stateStore.payment_state[0].customerName) { - if ( - EmailValidator.validate( - this.props.stateStore.payment_state[0].customerEmail, - ) - ) { - this.props.customerStore.add({ - name: this.props.stateStore.payment_state[0].customerName, - email: this.props.stateStore.payment_state[0].customerEmail, - phoneNumber: this.props.stateStore.payment_state[0] - .customerPhoneNumber, - note: this.props.stateStore.payment_state[0].customerNotes, - }); - // this.setState({ - // modalVisible: false, - // customerName: "", - // customerEmail: "", - // customerPhoneNumber: "", - // customerNotes: "", - // }); - this.props.stateStore.changeValue("modalVisible", false, "Payment"); - this.props.stateStore.changeValue("customerName", "", "Payment"); - this.props.stateStore.changeValue("customerEmail", "", "Payment"); - this.props.stateStore.changeValue("customerPhoneNumber", "", "Payment"); - this.props.stateStore.changeValue("customerNotes", "", "Payment"); - } else { - Alert.alert("Invalid Email", "Please enter valid email"); - } - } else { - Alert.alert("Invalid Name", "Please enter valid name"); + } + searchCustomer(text) { + this.props.customerStore.search(text).then(result => { + for (let i = 0; i < result.length; i += 1) { + let existing = false; + for (let v = 0; v < this.state.arrayObjects.length; v += 1) { + if (result[i]._id === this.state.arrayObjects[v]._id) { + existing = true; + } } - } - onCancelAddCustomer() { - // this.setState({ - // modalVisible: false, - // customerName: "", - // customerEmail: "", - // customerPhoneNumber: "", - // customerNotes: "", - // }); + if (!existing) { + this.state.arrayObjects.push(result[i]); + } + } + }); + } + onSaveCustomer() { + if (this.props.stateStore.payment_state[0].customerName) { + if ( + EmailValidator.validate( + this.props.stateStore.payment_state[0].customerEmail, + ) + ) { + this.props.customerStore.add({ + name: this.props.stateStore.payment_state[0].customerName, + email: this.props.stateStore.payment_state[0].customerEmail, + phoneNumber: this.props.stateStore.payment_state[0] + .customerPhoneNumber, + note: this.props.stateStore.payment_state[0].customerNotes, + }); + // this.setState({ + // modalVisible: false, + // customerName: "", + // customerEmail: "", + // customerPhoneNumber: "", + // customerNotes: "", + // }); this.props.stateStore.changeValue("modalVisible", false, "Payment"); this.props.stateStore.changeValue("customerName", "", "Payment"); this.props.stateStore.changeValue("customerEmail", "", "Payment"); this.props.stateStore.changeValue("customerPhoneNumber", "", "Payment"); this.props.stateStore.changeValue("customerNotes", "", "Payment"); + } else { + Alert.alert("Invalid Email", "Please enter valid email"); + } + } else { + Alert.alert("Invalid Name", "Please enter valid name"); } + } + onCancelAddCustomer() { + // this.setState({ + // modalVisible: false, + // customerName: "", + // customerEmail: "", + // customerPhoneNumber: "", + // customerNotes: "", + // }); + this.props.stateStore.changeValue("modalVisible", false, "Payment"); + this.props.stateStore.changeValue("customerName", "", "Payment"); + this.props.stateStore.changeValue("customerEmail", "", "Payment"); + this.props.stateStore.changeValue("customerPhoneNumber", "", "Payment"); + this.props.stateStore.changeValue("customerNotes", "", "Payment"); + } - render() { - return ( - this.onConnectDevice()} - onPickerChange={text => - this.props.stateStore.changeValue("selected", text, "Payment") - } - onValueChange={text => this.onValueChange(text)} - defaultCustomer={this.props.receiptStore.defaultCustomer.name.toString() ? this.props.receiptStore.defaultCustomer.name.toString() : "Default customer" } - onPay={() => this.onPay()} - onPrinterChange={value => this.onPrinterChange(value)} - onChange={value => - this.props.stateStore.changeValue( - "value", - value.toString(), - "Payment", - ) - } - onChangeAmountChange={value => - this.props.stateStore.changeValue( - "amountChange", - value.toString(), - "Payment", - ) - } - searchCustomer={text => this.searchCustomer(text)} - searchedCustomers={this.state.arrayObjects} - modalVisibleChange={text => - this.props.stateStore.changeValue("modalVisible", text, "Payment") - } - navigation={() => { - this.getBluetoothState(true); - this.onBack(); - }} - onPrinterPress={() => this.onPrinterPress()} - onChangeCustomerName={text => - this.props.stateStore.changeValue("customerName", text, "Payment") - } - onChangeCustomerEmail={text => - this.props.stateStore.changeValue("customerEmail", text, "Payment") - } - onChangeCustomerPhoneNumber={text => - this.props.stateStore.changeValue( - "customerPhoneNumber", - text, - "Payment", - ) - } - onChangeCustomerNotes={text => - this.props.stateStore.changeValue("customerNotes", text, "Payment") - } - onSaveCustomer={() => this.onSaveCustomer()} - onCancelAddCustomer={() => this.onCancelAddCustomer()} - currency={ - this.props.printerStore.companySettings[0].countryCode - ? this.props.printerStore.companySettings[0].countryCode - : "" - } - /> - ); - } + render() { + return ( + this.onConnectDevice()} + onPickerChange={text => + this.props.stateStore.changeValue("selected", text, "Payment") + } + onValueChange={text => this.onValueChange(text)} + defaultCustomer={ + this.props.receiptStore.defaultCustomer.name.toString() + ? this.props.receiptStore.defaultCustomer.name.toString() + : "Default customer" + } + onPay={() => this.onPay()} + onPrinterChange={value => this.onPrinterChange(value)} + onChange={value => + this.props.stateStore.changeValue( + "value", + value.toString(), + "Payment", + ) + } + onChangeAmountChange={value => + this.props.stateStore.changeValue( + "amountChange", + value.toString(), + "Payment", + ) + } + searchCustomer={text => this.searchCustomer(text)} + searchedCustomers={this.state.arrayObjects} + modalVisibleChange={text => + this.props.stateStore.changeValue("modalVisible", text, "Payment") + } + navigation={() => { + this.getBluetoothState(true); + this.onBack(); + }} + onPrinterPress={() => this.onPrinterPress()} + onChangeCustomerName={text => + this.props.stateStore.changeValue("customerName", text, "Payment") + } + onChangeCustomerEmail={text => + this.props.stateStore.changeValue("customerEmail", text, "Payment") + } + onChangeCustomerPhoneNumber={text => + this.props.stateStore.changeValue( + "customerPhoneNumber", + text, + "Payment", + ) + } + onChangeCustomerNotes={text => + this.props.stateStore.changeValue("customerNotes", text, "Payment") + } + onSaveCustomer={() => this.onSaveCustomer()} + onCancelAddCustomer={() => this.onCancelAddCustomer()} + currency={ + this.props.printerStore.companySettings[0].countryCode + ? this.props.printerStore.companySettings[0].countryCode + : "" + } + /> + ); + } } diff --git a/src/container/SalesContainer/index.js b/src/container/SalesContainer/index.js index 8d31b2b..cf08b2e 100644 --- a/src/container/SalesContainer/index.js +++ b/src/container/SalesContainer/index.js @@ -25,718 +25,720 @@ Sound.setCategory("Playback"); const beep = new Sound("beep.mp3", Sound.MAIN_BUNDLE); @inject( - "itemStore", - "customerStore", - "receiptStore", - "discountStore", - "categoryStore", - "paymentStore", - "printerStore", - "shiftStore", - "attendantStore", - "stateStore", + "itemStore", + "customerStore", + "receiptStore", + "discountStore", + "categoryStore", + "paymentStore", + "printerStore", + "shiftStore", + "attendantStore", + "stateStore", ) @observer export default class SalesContainer extends React.Component { - constructor(props) { - super(props); - - } - - componentWillMount() { - this.props.stateStore.initializeState(); - this.getBluetoothState(); - const { params } = this.props.navigation.state; - if (params) { - this.props.stateStore.changeValue( - "cash", - parseFloat(params.cash), - "Sales", - ); - this.props.stateStore.changeValue( - "change", - parseFloat(params.change), - "Sales", + constructor(props) { + super(props); + } + + componentWillMount() { + this.props.stateStore.initializeState(); + this.getBluetoothState(); + const { params } = this.props.navigation.state; + if (params) { + this.props.stateStore.changeValue( + "cash", + parseFloat(params.cash), + "Sales", + ); + this.props.stateStore.changeValue( + "change", + parseFloat(params.change), + "Sales", + ); + } + } + + async getBluetoothState() { + const isEnabled = await BluetoothStatus.state(); + if (!isEnabled) { + BluetoothStatus.enable(true); + } + } + componentDidMount() { + if (this.props.stateStore.sales_state[0].selectedCategoryIndex === -1) { + this.props.itemStore.itemsBasedOnCategorySelected("All"); + } else if ( + this.props.stateStore.sales_state[0].selectedCategoryIndex === -2 + ) { + this.props.itemStore.favorites(); + } + SplashScreen.hide(); + } + + onItemClick(index) { + const line = ReceiptLine.create({ + item: index._id, + sold_by: index.soldBy, + item_name: index.name, + qty: parseInt(1, 10), + price: parseFloat(index.price), + date: Date.now(), + }); + this.props.receiptStore.setReceiptLine(line); + if (index.price <= 0) { + this.props.stateStore.changeValue("priceModalVisible", true, "Sales"); + } else { + // let lengthValue = 0; + // // line + // if (index.taxesValue !== undefined) { + // lengthValue = index.taxesValue.length; + // } + const receipt = this.props.receiptStore.defaultReceipt; + // if (lengthValue > 0) { + // receipt.addReceiptTax(index); + // } + // Add line to receipt + receipt.add(line); + } + + // Get receipt line + } + onBarcodeRead(barcodeValue) { + if (this.props.stateStore.sales_state[0].barcodeStatus === "idle") { + if ( + barcodeValue.toString() !== this.props.receiptStore.lastScannedBarcode + ) { + this.props.receiptStore.setLastScannedBarcode(barcodeValue); + + // play the beep + beep.play(); + + // barcode search promises + this.props.itemStore.searchByBarcode(barcodeValue).then(result => { + const resultItem = result; + + if (resultItem) { + const line = ReceiptLine.create({ + item: resultItem._id, + item_name: resultItem.name, + qty: parseInt(1, 10), + price: parseFloat(resultItem.price), + date: Date.now(), + }); + const lineIndex = this.props.receiptStore.defaultReceipt.add(line); + this.props.receiptStore.setReceiptLine( + this.props.receiptStore.defaultReceipt.lines[lineIndex], ); - } - } - - async getBluetoothState() { - const isEnabled = await BluetoothStatus.state(); - if (!isEnabled) { - BluetoothStatus.enable(true); - } - } - componentDidMount() { - if (this.props.stateStore.sales_state[0].selectedCategoryIndex === -1) { - this.props.itemStore.itemsBasedOnCategorySelected("All"); - } else if ( - this.props.stateStore.sales_state[0].selectedCategoryIndex === -2 - ) { - this.props.itemStore.favorites(); - } - SplashScreen.hide(); - } + } else { + Toast.show({ + text: "No corresponding item based from the barcode found.", + duration: 5000, + type: "danger", + }); + } + this.props.stateStore.changeValue("barcodeStatus", "idle", "Sales"); + }); - onItemClick(index) { + // Pending barcode status + this.props.stateStore.changeValue("barcodeStatus", "pending", "Sales"); + } + } + } + + onChangeSalesSearchText(text) { + this.props.itemStore.search(text); + } + async searchStatusChange(bool) { + BluetoothStatus.disable(bool); + BluetoothStatus.enable(!bool); + this.onCategoryClick(-1); + this.props.stateStore.changeValue("searchStatus", bool, "Sales"); + } + onCategoryClick(id, index) { + this.props.stateStore.changeValue("selectedCategoryIndex", index, "Sales"); + + if (index >= 0) { + this.props.stateStore.changeValue("categoryFilter", true, "Sales"); + this.props.stateStore.changeValue("categoryValue", id, "Sales"); + + this.props.itemStore.itemsBasedOnCategorySelected(id); + } else if (index === -1) { + this.props.stateStore.changeValue("categoryFilter", false, "Sales"); + + this.props.itemStore.itemsBasedOnCategorySelected("All"); + } else if (index === -2) { + this.props.itemStore.favorites(); + } + } + + onDeleteClick() { + this.props.stateStore.changeValue("deleteDialogVisible", true, "Sales"); + } + + onDeleteReceiptLine() { + this.props.receiptStore.unselectReceiptLine(); + this.props.receiptStore.defaultReceipt.clear(); + this.props.stateStore.changeValue("deleteDialogVisible", false, "Sales"); + } + + onBarcodeClick() { + this.props.stateStore.changeValue("salesListStatus", true, "Sales"); + } + + onCloseClick(text) { + this.props.stateStore.changeValue("salesListStatus", false, "Sales"); + } + + onDiscountClick() { + if (this.props.receiptStore.defaultReceipt.lines.length === 0) { + Alert.alert("Discount", "Please add an item.", [{ text: "Ok" }]); + } else { + this.props.stateStore.changeValue("discountSelection", true, "Sales"); + } + } + + onPaymentClick(text) { + const { defaultShift } = this.props.shiftStore; + + if (defaultShift.shiftStarted && !defaultShift.shiftEnded) { + if ( + this.props.shiftStore.defaultShift.attendant === + this.props.attendantStore.defaultAttendant.user_name + ) { + this.props.navigation.navigate("Payment", { + value: text.netTotal.toFixed(2), + receipt: true, + }); + } else { + Toast.show({ + text: "Its not your shift", + buttonText: "Okay", + type: "danger", + }); + } + } else { + Toast.show({ + text: "Set the shift!", + buttonText: "Okay", + type: "danger", + }); + } + } + + onBluetoothScan(text) { + let barcodeValue = text; + this.props.stateStore.changeValue("barcodeScannerInput", "", "Sales"); + this.props.itemStore.searchByBarcode(barcodeValue).then(result => { + // Get receipt line + + if (result) { const line = ReceiptLine.create({ - item: index._id, - sold_by: index.soldBy, - item_name: index.name, - qty: parseInt(1, 10), - price: parseFloat(index.price), - date: Date.now(), + item: result._id, + item_name: result.name, + qty: parseInt(1, 10), + price: parseFloat(result.price), + date: Date.now(), }); - this.props.receiptStore.setReceiptLine(line); - if (index.price <= 0) { - this.props.stateStore.changeValue("priceModalVisible", true, "Sales"); - } else { - // let lengthValue = 0; - // // line - // if (index.taxesValue !== undefined) { - // lengthValue = index.taxesValue.length; - // } - const receipt = this.props.receiptStore.defaultReceipt; - // if (lengthValue > 0) { - // receipt.addReceiptTax(index); - // } - // Add line to receipt - receipt.add(line); - } - - // Get receipt line - } - onBarcodeRead(barcodeValue) { - if (this.props.stateStore.sales_state[0].barcodeStatus === "idle") { - if ( - barcodeValue.toString() !== this.props.receiptStore.lastScannedBarcode - ) { - this.props.receiptStore.setLastScannedBarcode(barcodeValue); - - // play the beep - beep.play(); - - // barcode search promises - this.props.itemStore.searchByBarcode(barcodeValue).then(result => { - const resultItem = result; - - if (resultItem) { - const line = ReceiptLine.create({ - item: resultItem._id, - item_name: resultItem.name, - qty: parseInt(1, 10), - price: parseFloat(resultItem.price), - date: Date.now(), - }); - const lineIndex = this.props.receiptStore.defaultReceipt.add(line); - this.props.receiptStore.setReceiptLine( - this.props.receiptStore.defaultReceipt.lines[lineIndex], - ); - } else { - Toast.show({ - text: "No corresponding item based from the barcode found.", - duration: 5000, - type: "danger", - }); - } - this.props.stateStore.changeValue("barcodeStatus", "idle", "Sales"); - }); - - // Pending barcode status - this.props.stateStore.changeValue("barcodeStatus", "pending", "Sales"); - } - } - } - onChangeSalesSearchText(text) { - this.props.itemStore.search(text); - } - async searchStatusChange(bool) { - BluetoothStatus.disable(bool); - BluetoothStatus.enable(!bool); - this.onCategoryClick(-1); - this.props.stateStore.changeValue("searchStatus", bool, "Sales"); - } - onCategoryClick(id, index) { - this.props.stateStore.changeValue("selectedCategoryIndex", index, "Sales"); + // line + const receipt = this.props.receiptStore.defaultReceipt; - if (index >= 0) { - this.props.stateStore.changeValue("categoryFilter", true, "Sales"); - this.props.stateStore.changeValue("categoryValue", id, "Sales"); + // Add line to receipt + const lineIndex = receipt.add(line); - this.props.itemStore.itemsBasedOnCategorySelected(id); - } else if (index === -1) { - this.props.stateStore.changeValue("categoryFilter", false, "Sales"); + // Set the selectedline + this.props.receiptStore.setReceiptLine(receipt.lines[lineIndex]); - this.props.itemStore.itemsBasedOnCategorySelected("All"); - } else if (index === -2) { - this.props.itemStore.favorites(); + // zero price + if (result.price <= 0) { + this.props.stateStore.changeValue("priceModalVisible", true, "Sales"); } - } - - onDeleteClick() { - this.props.stateStore.changeValue("deleteDialogVisible", true, "Sales"); - } - - onDeleteReceiptLine() { - this.props.receiptStore.unselectReceiptLine(); - this.props.receiptStore.defaultReceipt.clear(); - this.props.stateStore.changeValue("deleteDialogVisible", false, "Sales"); - } - - onBarcodeClick() { - this.props.stateStore.changeValue("salesListStatus", true, "Sales"); - } - - onCloseClick(text) { - this.props.stateStore.changeValue("salesListStatus", false, "Sales"); - } - - onDiscountClick() { - if (this.props.receiptStore.defaultReceipt.lines.length === 0) { - Alert.alert("Discount", "Please add an item.", [{ text: "Ok" }]); - } else { - this.props.stateStore.changeValue("discountSelection", true, "Sales"); + } else { + Toast.show({ + text: "No corresponding item based from the barcode found.", + duration: 1000, + buttonText: "Okay", + type: "danger", + }); + } + }); + } + onCancelDiscount(value) { + this.props.discountStore.unsetDiscount(); + const receipt = this.props.receiptStore.defaultReceipt; + receipt.cancelDiscount(); + } + onDiscountChange(discount, index) { + this.props.stateStore.changeValue("selectedDiscount", discount, "Sales"); + this.props.stateStore.changeValue("selectedDiscountIndex", index, "Sales"); + } + + onDiscountEdit(val) { + const receipt = this.props.receiptStore.defaultReceipt; + if (this.props.stateStore.sales_state[0].discountSelectionStatus) { + receipt.addOnTheFlyReceiptDiscount({ + value: parseFloat(val.onTheFlyDiscountValue, 10), + percentageType: val.percentageType, + }); + } else { + const discount = this.props.discountStore.rows[ + this.props.stateStore.sales_state[0].selectedDiscountIndex + ]; + this.props.discountStore.setDiscount(discount); + receipt.addReceiptDiscount(discount); + } + + // hide modal + this.props.stateStore.changeValue("discountSelection", false, "Sales"); + } + + confirmReceiptDeleteDialog() { + return ( + + this.props.stateStore.changeValue( + "deleteDialogVisible", + false, + "Sales", + ) } - } - - onPaymentClick(text) { - const { defaultShift } = this.props.shiftStore; - - if (defaultShift.shiftStarted && !defaultShift.shiftEnded) { - if ( - this.props.shiftStore.defaultShift.attendant === - this.props.attendantStore.defaultAttendant.user_name - ) { - this.props.navigation.navigate("Payment", { - value: text.netTotal.toFixed(2), - receipt: true, - }); - } else { - Toast.show({ - text: "Its not your shift", - buttonText: "Okay", - type: "danger", - }); - } - } else { - Toast.show({ - text: "Set the shift!", - buttonText: "Okay", - type: "danger", - }); + positiveButton={{ + title: "YES", + onPress: () => this.onDeleteReceiptLine(), + }} + negativeButton={{ + title: "NO", + onPress: () => + this.props.stateStore.changeValue( + "deleteDialogVisible", + false, + "Sales", + ), + }} + /> + ); + } + + discountSelectionDialog() { + return ( + { - // Get receipt line - - if (result) { - const line = ReceiptLine.create({ - item: result._id, - item_name: result.name, - qty: parseInt(1, 10), - price: parseFloat(result.price), - date: Date.now(), - }); - - // line - const receipt = this.props.receiptStore.defaultReceipt; - - // Add line to receipt - const lineIndex = receipt.add(line); - - // Set the selectedline - this.props.receiptStore.setReceiptLine(receipt.lines[lineIndex]); - - // zero price - if (result.price <= 0) { - this.props.stateStore.changeValue("priceModalVisible", true, "Sales"); - } - } else { - Toast.show({ - text: "No corresponding item based from the barcode found.", - duration: 1000, - buttonText: "Okay", - type: "danger", - }); - } - }); - } - onCancelDiscount(value) { - this.props.discountStore.unsetDiscount(); - const receipt = this.props.receiptStore.defaultReceipt; - receipt.cancelDiscount(); - } - onDiscountChange(discount, index) { - this.props.stateStore.changeValue("selectedDiscount", discount, "Sales"); - this.props.stateStore.changeValue("selectedDiscountIndex", index, "Sales"); - } - - onDiscountEdit(val) { - const receipt = this.props.receiptStore.defaultReceipt; - if (this.props.stateStore.sales_state[0].discountSelectionStatus) { - receipt.addOnTheFlyReceiptDiscount({ - value: parseFloat(val.onTheFlyDiscountValue, 10), - percentageType: val.percentageType, - }); - } else { - const discount = this.props.discountStore.rows[ - this.props.stateStore.sales_state[0].selectedDiscountIndex - ]; - this.props.discountStore.setDiscount(discount); - receipt.addReceiptDiscount(discount); + onCancelDiscount={value => this.onCancelDiscount(value)} + onDiscountChange={(discount, index) => + this.onDiscountChange(discount, index) } - - // hide modal - this.props.stateStore.changeValue("discountSelection", false, "Sales"); - } - - confirmReceiptDeleteDialog() { - return ( - - this.props.stateStore.changeValue( - "deleteDialogVisible", - false, - "Sales", - ) - } - positiveButton={{ - title: "YES", - onPress: () => this.onDeleteReceiptLine(), - }} - negativeButton={{ - title: "NO", - onPress: () => - this.props.stateStore.changeValue( - "deleteDialogVisible", - false, - "Sales", - ), - }} - /> - ); - } - - discountSelectionDialog() { - return ( - this.onCancelDiscount(value)} - onDiscountChange={(discount, index) => - this.onDiscountChange(discount, index) - } - selectedDiscount={this.props.stateStore.sales_state[0].selectedDiscount} - discountSelection={ - this.props.stateStore.sales_state[0].discountSelection - } - discountSelectionStatus={ - this.props.stateStore.sales_state[0].discountSelectionStatus - } - onClick={() => - this.props.stateStore.changeValue("discountSelection", false, "Sales") - } - onDiscountEdit={value => this.onDiscountEdit(value)} - changeSelectionStatus={value => - this.props.stateStore.changeValue( - "discountSelectionStatus", - value, - "Sales", - ) - } - /> - ); - } - - // function is never used... - // note to future: ikaw na bahala remove ani. - onPriceExit(price) { - if (!price) { - Toast.show({ - text: "Zero-price items are not allowed. Please set the price.", - buttonText: "Okay", - duration: 5000, - type: "warning", - }); - } else { - this.props.stateStore.changeValue("priceModalVisible", false, "Sales"); + selectedDiscount={this.props.stateStore.sales_state[0].selectedDiscount} + discountSelection={ + this.props.stateStore.sales_state[0].discountSelection } - } - - onPriceSubmit(value) { - // line - - const line = this.props.receiptStore.selectedLine; - if (line) { - line.setPrice(value); - const receipt = this.props.receiptStore.defaultReceipt; - // Add line to receipt - receipt.add(line); // hide modal - this.props.stateStore.changeValue("priceModalVisible", false, "Sales"); - this.props.stateStore.changeValue("addReceiptLineStatus", false, "Sales"); - - // kwan bug(?) - this.props.receiptStore.unselectReceiptLine(); + discountSelectionStatus={ + this.props.stateStore.sales_state[0].discountSelectionStatus } - // set the current line price - } - - priceInputDialog() { - // current price - let price = 0; - - if (this.props.receiptStore.selectedLine) { - price = this.props.receiptStore.selectedLine.price; + onClick={() => + this.props.stateStore.changeValue("discountSelection", false, "Sales") } - - return ( - this.onPriceExit()} - onClose={() => - this.props.stateStore.changeValue("priceModalVisible", false, "Sales") - } - onSubmit={value => - this.onPriceSubmit(value, this.props.receiptStore.selectedLine) - } - price={price} - /> - ); - } - - onQuantityExit() { - this.props.stateStore.changeValue("quantityModalVisible", false, "Sales"); - } - - quantityEditDialog() { - // current qty - let qty = 0; - let price = 0; - let soldBy = ""; - let commission_name = ""; - let commission_rate = 0; - let commission_amount = 0; - let discount_rate = 0; - - if (this.props.receiptStore.selectedLine) { - qty = this.props.receiptStore.selectedLine.qty; - price = this.props.receiptStore.selectedLine.price; - soldBy = this.props.receiptStore.selectedLine.sold_by; - commission_name = this.props.receiptStore.selectedLine - .commission_attendant_name; - commission_rate = this.props.receiptStore.selectedLine.commission_rate; - commission_amount = this.props.receiptStore.selectedLine - .commission_amount; - discount_rate = this.props.receiptStore.selectedLine - .discount_rate; + onDiscountEdit={value => this.onDiscountEdit(value)} + changeSelectionStatus={value => + this.props.stateStore.changeValue( + "discountSelectionStatus", + value, + "Sales", + ) } - - return ( - this.onQuantityExit()} - attendants={this.props.attendantStore.rows - .slice() - .filter(e => e.role !== "Cashier" && e.role !== "Owner")} - visible={this.props.stateStore.sales_state[0].quantityModalVisible} - onSubmit={quantity => this.onQuantitySubmit(quantity)} - /> - ); - } - summaryDialog() { - return ( - { - this.props.stateStore.changeValue( - "visibleSummaryModal", - false, - "Sales", - ); - this.props.receiptStore.setPreviuosReceiptToNull(); - }} - /> - ); - } - onQuantitySubmit(quantity) { - // line - this.setState({onChangeStatues: false}); - const line = this.props.receiptStore.selectedLine; - - const qty = parseFloat(quantity.quantity) - ? parseFloat(quantity.quantity) - : parseFloat(quantity.defaultQty); - - if (line.sold_by === "Each") { - if (isFloat(qty)) { - Toast.show({ - text: "Quantity not possible for each.", - buttonText: "Okay", - type: "warning", - }); - } else { - // Toast boy - Toast.show({ - text: "Receipt line is modified.", - buttonText: "Okay", - duration: 5000, - }); - line.setQuantity(Number(qty.toFixed(2))); - } - } else { - // Toast boy - Toast.show({ - text: "Receipt line is modified.", - buttonText: "Okay", - duration: 5000, - }); - line.setQuantity(Number(qty.toFixed(2))); + /> + ); + } + + // function is never used... + // note to future: ikaw na bahala remove ani. + onPriceExit(price) { + if (!price) { + Toast.show({ + text: "Zero-price items are not allowed. Please set the price.", + buttonText: "Okay", + duration: 5000, + type: "warning", + }); + } else { + this.props.stateStore.changeValue("priceModalVisible", false, "Sales"); + } + } + + onPriceSubmit(value) { + // line + + const line = this.props.receiptStore.selectedLine; + if (line) { + line.setPrice(value); + const receipt = this.props.receiptStore.defaultReceipt; + // Add line to receipt + receipt.add(line); // hide modal + this.props.stateStore.changeValue("priceModalVisible", false, "Sales"); + this.props.stateStore.changeValue("addReceiptLineStatus", false, "Sales"); + + // kwan bug(?) + this.props.receiptStore.unselectReceiptLine(); + } + // set the current line price + } + + priceInputDialog() { + // current price + let price = 0; + + if (this.props.receiptStore.selectedLine) { + price = this.props.receiptStore.selectedLine.price; + } + + return ( + this.onPriceExit()} + onClose={() => + this.props.stateStore.changeValue("priceModalVisible", false, "Sales") } - - const price = parseFloat(quantity.price) - ? parseFloat(quantity.price) - : parseFloat(quantity.defaultPrice); - - // set the price - line.setPrice(Number(price.toFixed(2))); - line.setDiscountRate(parseFloat(quantity.discount) > 0 ? parseFloat(quantity.discount) : 0); - if ( - quantity.attendantName !== "No Attendant" && - quantity.commission && - quantity.commission_amount - ) { - - - this.props.attendantStore.find(quantity.attendantName).then(result => { - - let discountValue = parseFloat(quantity.discount) > 0 ? (price * qty) - ((parseFloat(quantity.discount) / 100) * (price * qty)) : (price * qty); - line.setCommissionAttendantName(quantity.attendantName); - line.setCommissionRate(result.commission, 10); - line.setCommissionAmount((parseFloat(result.commission, 10) / 100) * discountValue); - }); + onSubmit={value => + this.onPriceSubmit(value, this.props.receiptStore.selectedLine) } - // unselect the line - this.props.receiptStore.unselectReceiptLine(); - - // remove the receipt store - this.props.stateStore.changeValue("quantityModalVisible", false, "Sales"); - } - - onReceiptLineDelete(index) { - // Unselect - this.props.receiptStore.unselectReceiptLine(); - - // Receipt - const receipt = this.props.receiptStore.defaultReceipt; - - // Lines - const receiptLine = receipt.lines[index]; - - // Delete the receipt - receipt.deleteLine(receiptLine); - - // Toast boy. - Toast.show({ - text: "Receipt line is deleted.", - buttonText: "Okay", - duration: 5000, - }); - - // Unselect - } - - onReceiptLineEdit(index) { - // receipt - const receipt = this.props.receiptStore.defaultReceipt; - - // Set the receipt line - const receiptLine = receipt.lines[index]; - - // do the boys - // Modal - this.props.receiptStore.setReceiptLine(receiptLine); - - this.props.stateStore.changeValue("quantityModalVisible", true, "Sales"); - } - onEndReached(text) { - this.props.stateStore.changeValue("fetching", true, "Sales"); - if (this.props.stateStore.sales_state[0].fetching) { - if (text === "item") { - this.props.itemStore.getFromDb(20); - this.props.stateStore.changeValue("fetching", false, "Sales"); - } else if (text === "category") { - this.props.categoryStore.getFromDb(20); - this.props.stateStore.changeValue("fetching", false, "Sales"); - } + price={price} + /> + ); + } + + onQuantityExit() { + this.props.stateStore.changeValue("quantityModalVisible", false, "Sales"); + } + + quantityEditDialog() { + // current qty + let qty = 0; + let price = 0; + let soldBy = ""; + let commission_name = ""; + let commission_rate = 0; + let commission_amount = 0; + let discount_rate = 0; + + if (this.props.receiptStore.selectedLine) { + qty = this.props.receiptStore.selectedLine.qty; + price = this.props.receiptStore.selectedLine.price; + soldBy = this.props.receiptStore.selectedLine.sold_by; + commission_name = this.props.receiptStore.selectedLine + .commission_attendant_name; + commission_rate = this.props.receiptStore.selectedLine.commission_rate; + commission_amount = this.props.receiptStore.selectedLine + .commission_amount; + discount_rate = this.props.receiptStore.selectedLine.discount_rate; + } + + return ( + this.onQuantityExit()} + attendants={this.props.attendantStore.rows + .slice() + .filter(e => e.role !== "Cashier" && e.role !== "Owner")} + visible={this.props.stateStore.sales_state[0].quantityModalVisible} + onSubmit={quantity => this.onQuantitySubmit(quantity)} + /> + ); + } + summaryDialog() { + return ( + { - item.edit({ - name: item.name, - soldBy: item.soldBy, - price: unformat(item.price), - sku: item.sku, - barcode: item.barcode, - category: item.category, - colorAndShape: JSON.stringify(JSON.parse(item.colorAndShape)), - favorite: "false", - taxes: JSON.stringify(item.taxes), - // dateUpdated: Date.now(), - // syncStatus: false, - }); - this.props.itemStore.detachItemFromFavorites(item); - }, - }, - ], - ); - } else { - Alert.alert( - "Favorite Item", // title - "Are you sure you want to set item as favorite?", - [ - { text: "No", style: "cancel" }, - { - text: "Yes", - onPress: () => { - item.edit({ - name: item.name, - soldBy: item.soldBy, - price: unformat(item.price), - sku: item.sku, - barcode: item.barcode, - category: item.category, - colorAndShape: JSON.stringify(JSON.parse(item.colorAndShape)), - favorite: "true", - taxes: JSON.stringify(item.taxes), - // dateUpdated: Date.now(), - // syncStatus: false, - }); - }, - }, - ], - ); + cash={this.props.stateStore.sales_state[0].cash} + change={this.props.stateStore.sales_state[0].change} + visibility={this.props.receiptStore.previousReceipt ? true : false} + lines={ + this.props.receiptStore.previousReceipt + ? this.props.receiptStore.previousReceipt.lines.slice() + : [] } - } - render() { - return ( - - {this.discountSelectionDialog()} - {this.summaryDialog()} - {this.confirmReceiptDeleteDialog()} - {this.quantityEditDialog()} - {this.priceInputDialog()} - 0 - ? this.props.printerStore.bluetooth[0].status - : false - } - onBluetoothScan={text => this.onBluetoothScan(text)} - onChangeSalesSearchText={text => this.onChangeSalesSearchText(text)} - searchStatus={this.props.stateStore.sales_state[0].searchStatus} - barcodeScannerInput={ - this.props.stateStore.sales_state[0].barcodeScannerInput - } - onChangeBarcodeScannerInput={text => - this.props.stateStore.changeValue( - "barcodeScannerInput", - text, - "Sales", - ) - } - onSearchClick={text => this.searchStatusChange(text)} - onBarcodeRead={text => this.onBarcodeRead(text)} - onCloseClick={text => this.onCloseClick(text)} - salesListStatus={this.props.stateStore.sales_state[0].salesListStatus} - categoryData={this.props.categoryStore.rows - .slice() - .sort(function(a, b) { - return a.name < b.name ? -1 : 1; - })} - itemData={ - this.props.stateStore.sales_state[0].categoryFilter || - this.props.stateStore.sales_state[0].searchStatus || - this.props.stateStore.sales_state[0].selectedCategoryIndex === -2 - ? this.props.itemStore.queriedRows.slice().sort(function(a, b) { - return a.name < b.name ? -1 : 1; - }) - : this.props.itemStore.rows.slice().sort(function(a, b) { - return a.name < b.name ? -1 : 1; - }) - } - receiptDefault={this.props.receiptStore.defaultReceipt} - navigation={this.props.navigation} - selectedCategoryIndex={ - this.props.stateStore.sales_state[0].selectedCategoryIndex - } - onCategoryClick={(id, index) => this.onCategoryClick(id, index)} - onItemClick={index => this.onItemClick(index)} - // footer - onDeleteClick={() => this.onDeleteClick()} - onBarcodeClick={() => this.onBarcodeClick()} - onDiscountClick={() => this.onDiscountClick()} - // receipt line - onReceiptLineEdit={index => this.onReceiptLineEdit(index)} - onReceiptLineDelete={index => this.onReceiptLineDelete(index)} - onPaymentClick={text => this.onPaymentClick(text)} - // empty rows - isDiscountsEmpty={this.props.discountStore.isEmptyRows} - onEndReached={text => this.onEndReached(text)} - onLongPressItem={values => this.onLongPressItem(values)} - /> - + details={ + this.props.receiptStore.previousReceipt && + this.props.receiptStore.previousReceipt.lines + ? this.props.receiptStore.previousReceipt + : {} + } + onClose={() => { + this.props.stateStore.changeValue( + "visibleSummaryModal", + false, + "Sales", + ); + this.props.receiptStore.setPreviuosReceiptToNull(); + }} + /> + ); + } + onQuantitySubmit(quantity) { + // line + this.setState({ onChangeStatues: false }); + const line = this.props.receiptStore.selectedLine; + + const qty = parseFloat(quantity.quantity) + ? parseFloat(quantity.quantity) + : parseFloat(quantity.defaultQty); + + if (line.sold_by === "Each") { + if (isFloat(qty)) { + Toast.show({ + text: "Quantity not possible for each.", + buttonText: "Okay", + type: "warning", + }); + } else { + // Toast boy + Toast.show({ + text: "Receipt line is modified.", + buttonText: "Okay", + duration: 5000, + }); + line.setQuantity(Number(qty.toFixed(2))); + } + } else { + // Toast boy + Toast.show({ + text: "Receipt line is modified.", + buttonText: "Okay", + duration: 5000, + }); + line.setQuantity(Number(qty.toFixed(2))); + } + + const price = parseFloat(quantity.price) + ? parseFloat(quantity.price) + : parseFloat(quantity.defaultPrice); + + // set the price + line.setPrice(Number(price.toFixed(2))); + line.setDiscountRate( + parseFloat(quantity.discount) > 0 ? parseFloat(quantity.discount) : 0, + ); + if ( + quantity.attendantName !== "No Attendant" && + quantity.commission && + quantity.commission_amount + ) { + this.props.attendantStore.find(quantity.attendantName).then(result => { + let discountValue = + parseFloat(quantity.discount) > 0 + ? price * qty - parseFloat(quantity.discount) / 100 * (price * qty) + : price * qty; + line.setCommissionAttendantName(quantity.attendantName); + line.setCommissionRate(result.commission, 10); + line.setCommissionAmount( + parseFloat(result.commission, 10) / 100 * discountValue, ); - } + }); + } + // unselect the line + this.props.receiptStore.unselectReceiptLine(); + + // remove the receipt store + this.props.stateStore.changeValue("quantityModalVisible", false, "Sales"); + } + + onReceiptLineDelete(index) { + // Unselect + this.props.receiptStore.unselectReceiptLine(); + + // Receipt + const receipt = this.props.receiptStore.defaultReceipt; + + // Lines + const receiptLine = receipt.lines[index]; + + // Delete the receipt + receipt.deleteLine(receiptLine); + + // Toast boy. + Toast.show({ + text: "Receipt line is deleted.", + buttonText: "Okay", + duration: 5000, + }); + + // Unselect + } + + onReceiptLineEdit(index) { + // receipt + const receipt = this.props.receiptStore.defaultReceipt; + + // Set the receipt line + const receiptLine = receipt.lines[index]; + + // do the boys + // Modal + this.props.receiptStore.setReceiptLine(receiptLine); + + this.props.stateStore.changeValue("quantityModalVisible", true, "Sales"); + } + onEndReached(text) { + this.props.stateStore.changeValue("fetching", true, "Sales"); + if (this.props.stateStore.sales_state[0].fetching) { + if (text === "item") { + this.props.itemStore.getFromDb(20); + this.props.stateStore.changeValue("fetching", false, "Sales"); + } else if (text === "category") { + this.props.categoryStore.getFromDb(20); + this.props.stateStore.changeValue("fetching", false, "Sales"); + } + } + } + onLongPressItem(item) { + if (this.props.stateStore.sales_state[0].selectedCategoryIndex === -2) { + Alert.alert( + "Favorite Item", // title + "Are you sure you want to remove item from favorites?", + [ + { text: "No", style: "cancel" }, + { + text: "Yes", + onPress: () => { + item.edit({ + name: item.name, + soldBy: item.soldBy, + price: unformat(item.price), + sku: item.sku, + barcode: item.barcode, + category: item.category, + colorAndShape: JSON.stringify(JSON.parse(item.colorAndShape)), + favorite: "false", + taxes: JSON.stringify(item.taxes), + // dateUpdated: Date.now(), + // syncStatus: false, + }); + this.props.itemStore.detachItemFromFavorites(item); + }, + }, + ], + ); + } else { + Alert.alert( + "Favorite Item", // title + "Are you sure you want to set item as favorite?", + [ + { text: "No", style: "cancel" }, + { + text: "Yes", + onPress: () => { + item.edit({ + name: item.name, + soldBy: item.soldBy, + price: unformat(item.price), + sku: item.sku, + barcode: item.barcode, + category: item.category, + colorAndShape: JSON.stringify(JSON.parse(item.colorAndShape)), + favorite: "true", + taxes: JSON.stringify(item.taxes), + // dateUpdated: Date.now(), + // syncStatus: false, + }); + }, + }, + ], + ); + } + } + render() { + return ( + + {this.discountSelectionDialog()} + {this.summaryDialog()} + {this.confirmReceiptDeleteDialog()} + {this.quantityEditDialog()} + {this.priceInputDialog()} + 0 + ? this.props.printerStore.bluetooth[0].status + : false + } + onBluetoothScan={text => this.onBluetoothScan(text)} + onChangeSalesSearchText={text => this.onChangeSalesSearchText(text)} + searchStatus={this.props.stateStore.sales_state[0].searchStatus} + barcodeScannerInput={ + this.props.stateStore.sales_state[0].barcodeScannerInput + } + onChangeBarcodeScannerInput={text => + this.props.stateStore.changeValue( + "barcodeScannerInput", + text, + "Sales", + ) + } + onSearchClick={text => this.searchStatusChange(text)} + onBarcodeRead={text => this.onBarcodeRead(text)} + onCloseClick={text => this.onCloseClick(text)} + salesListStatus={this.props.stateStore.sales_state[0].salesListStatus} + categoryData={this.props.categoryStore.rows + .slice() + .sort(function(a, b) { + return a.name < b.name ? -1 : 1; + })} + itemData={ + this.props.stateStore.sales_state[0].categoryFilter || + this.props.stateStore.sales_state[0].searchStatus || + this.props.stateStore.sales_state[0].selectedCategoryIndex === -2 + ? this.props.itemStore.queriedRows.slice().sort(function(a, b) { + return a.name < b.name ? -1 : 1; + }) + : this.props.itemStore.rows.slice().sort(function(a, b) { + return a.name < b.name ? -1 : 1; + }) + } + receiptDefault={this.props.receiptStore.defaultReceipt} + navigation={this.props.navigation} + selectedCategoryIndex={ + this.props.stateStore.sales_state[0].selectedCategoryIndex + } + onCategoryClick={(id, index) => this.onCategoryClick(id, index)} + onItemClick={index => this.onItemClick(index)} + // footer + onDeleteClick={() => this.onDeleteClick()} + onBarcodeClick={() => this.onBarcodeClick()} + onDiscountClick={() => this.onDiscountClick()} + // receipt line + onReceiptLineEdit={index => this.onReceiptLineEdit(index)} + onReceiptLineDelete={index => this.onReceiptLineDelete(index)} + onPaymentClick={text => this.onPaymentClick(text)} + // empty rows + isDiscountsEmpty={this.props.discountStore.isEmptyRows} + onEndReached={text => this.onEndReached(text)} + onLongPressItem={values => this.onLongPressItem(values)} + /> + + ); + } } diff --git a/src/container/SettingsContainer/index.js b/src/container/SettingsContainer/index.js index 5f00d5c..7af9e5d 100644 --- a/src/container/SettingsContainer/index.js +++ b/src/container/SettingsContainer/index.js @@ -425,7 +425,7 @@ export default class SettingsContainer extends React.Component { pin_code: values.pin, role: values.role, canLogin: values.canLogin, - commission: parseInt(values.commission,10), + commission: parseInt(values.commission, 10), dateUpdated: Date.now(), syncStatus: false, }); @@ -450,10 +450,9 @@ export default class SettingsContainer extends React.Component { pin_code: values.pin, role: values.role, canLogin: values.canLogin, - commission: parseInt(values.commission,10), + commission: parseInt(values.commission, 10), - - dateUpdated: Date.now(), + dateUpdated: Date.now(), syncStatus: false, }); Toast.show({ @@ -525,8 +524,8 @@ export default class SettingsContainer extends React.Component { pin_code: values.pin, role: values.role, canLogin: values.canLogin, - commission: parseInt(values.commission,10), - dateUpdated: Date.now(), + commission: parseInt(values.commission, 10), + dateUpdated: Date.now(), syncStatus: false, }); Toast.show({ @@ -550,10 +549,9 @@ export default class SettingsContainer extends React.Component { pin_code: values.pin, role: values.role, canLogin: values.canLogin, - commission: parseInt(values.commission,10), - + commission: parseInt(values.commission, 10), - dateUpdated: Date.now(), + dateUpdated: Date.now(), syncStatus: false, }); Toast.show({ diff --git a/src/container/ShiftContainer/index.js b/src/container/ShiftContainer/index.js index 2af3d9e..4ecd88c 100644 --- a/src/container/ShiftContainer/index.js +++ b/src/container/ShiftContainer/index.js @@ -10,384 +10,369 @@ import ShiftScreen from "@screens/Shift"; @inject("shiftStore", "attendantStore", "shiftReportsStore", "printerStore") @observer export default class ShiftContainer extends React.Component { - constructor(props) { - super(props); - this.state = { - pay: "", - }; - } - openShift() { - this.props.shiftStore.defaultShift.setBeginCash(parseFloat(this.state.pay)); - const { defaultShift } = this.props.shiftStore; + constructor(props) { + super(props); + this.state = { + pay: "", + }; + } + openShift() { + this.props.shiftStore.defaultShift.setBeginCash(parseFloat(this.state.pay)); + const { defaultShift } = this.props.shiftStore; - if (defaultShift.beginning_cash) { - // Boy - defaultShift.startShift(); - defaultShift.setAttendant( - this.props.attendantStore.defaultAttendant.user_name, - ); + if (defaultShift.beginning_cash) { + // Boy + defaultShift.startShift(); + defaultShift.setAttendant( + this.props.attendantStore.defaultAttendant.user_name, + ); - this.props.shiftReportsStore.add({ - date: Date.now(), - shift: defaultShift._id, - status: "Opened", - shiftNumber: this.props.shiftReportsStore.rows.length + 1, - attendant: this.props.attendantStore.defaultAttendant.user_name, - }); - // Yeah - this.props.navigation.navigate("Sales"); - } else { - Toast.show({ - text: "Enter a beginning cash!", - buttonText: "Okay", - type: "danger", - position: "top", - }); - } - this.setState({ pay: "" }); + this.props.shiftReportsStore.add({ + date: Date.now(), + shift: defaultShift._id, + status: "Opened", + shiftNumber: this.props.shiftReportsStore.rows.length + 1, + attendant: this.props.attendantStore.defaultAttendant.user_name, + }); + // Yeah + this.props.navigation.navigate("Sales"); + } else { + Toast.show({ + text: "Enter a beginning cash!", + buttonText: "Okay", + type: "danger", + position: "top", + }); } + this.setState({ pay: "" }); + } - closeShift(money) { - if (money) { - const { defaultShift } = this.props.shiftStore; + closeShift(money) { + if (money) { + const { defaultShift } = this.props.shiftStore; - defaultShift.changeStatus(); - defaultShift.changeActualMoney(money); - defaultShift.endShift(); - } else { - Toast.show({ - text: "Invalid Amount", - buttonText: "Okay", - type: "danger", - position: "top", - }); - } + defaultShift.changeStatus(); + defaultShift.changeActualMoney(money); + defaultShift.endShift(); + } else { + Toast.show({ + text: "Invalid Amount", + buttonText: "Okay", + type: "danger", + position: "top", + }); } + } - reshift() { - this.props.shiftStore.newShift(); - } + reshift() { + this.props.shiftStore.newShift(); + } - onAmountChange(text) { - this.props.shiftStore.defaultShift.setBeginCash(parseFloat(text)); - } + onAmountChange(text) { + this.props.shiftStore.defaultShift.setBeginCash(parseFloat(text)); + } - onAttendantChange(index) { - // nononononone - if (index !== 0) { - const attendant = this.props.attendantStore.rows[index - 1]; + onAttendantChange(index) { + // nononononone + if (index !== 0) { + const attendant = this.props.attendantStore.rows[index - 1]; - this.props.attendantStore.setAttendant(attendant); - this.props.shiftStore.defaultShift.setAttendant(attendant.user_name); - } else { - this.props.attendantStore.setAttendant(null); - this.props.shiftStore.defaultShift.setAttendant(""); - } + this.props.attendantStore.setAttendant(attendant); + this.props.shiftStore.defaultShift.setAttendant(attendant.user_name); + } else { + this.props.attendantStore.setAttendant(null); + this.props.shiftStore.defaultShift.setAttendant(""); } + } - payInClick(money) { - if (this.props.shiftStore.defaultShift.attendant === this.props.attendantStore.defaultAttendant.user_name) { - if (money.reason){ - this.setState({ pay: "" }); - - const { defaultShift } = this.props.shiftStore; - - // Pay in - - defaultShift.addPay({ - date: Date.now(), - amount: parseFloat(money.pay), - reason: money.reason, - flow: "In", - }); - // End cash - defaultShift.setEndCash(defaultShift.ending_cash + parseFloat(money.pay)); - if (this.props.printerStore.rows.length > 0){ - for (let i = 0; i < this.props.printerStore.rows.length; i += 1) { - if (this.props.printerStore.rows[i].defaultPrinter) { + payInClick(money) { + if ( + this.props.shiftStore.defaultShift.attendant === + this.props.attendantStore.defaultAttendant.user_name + ) { + if (money.reason) { + this.setState({ pay: "" }); - BluetoothSerial.connect(this.props.printerStore.rows[i].macAddress).then(() => { - const writePromises = []; + const { defaultShift } = this.props.shiftStore; - writePromises.push(BluetoothSerial.write(TinyPOS.init())); - // Header - writePromises.push( - BluetoothSerial.write( - TinyPOS.bufferedText( - "Date: " + - `${moment().format("YYYY/MM/D hh:mm:ss SSS")}`, - { size: "normal" }, - true, - ), - ), - ); - writePromises.push( - BluetoothSerial.write( - TinyPOS.bufferedText( - "Cashier: " + - `${ - defaultShift.attendant - }`, - { align: "left", size: "normal" }, - true, - ), - ), - ); + // Pay in - writePromises.push( - BluetoothSerial.write( - TinyPOS.bufferedText( - "Type: " + - `${ - money.type - }`, - { align: "left", size: "normal" }, - true, - ), - ), - ); - writePromises.push( - BluetoothSerial.write( - TinyPOS.bufferedText( - "Amount: " + - `${ - money.pay - }`, - { align: "left", size: "normal" }, - true, - ), - ), - ); + defaultShift.addPay({ + date: Date.now(), + amount: parseFloat(money.pay), + reason: money.reason, + flow: "In", + }); + // End cash + defaultShift.setEndCash( + defaultShift.ending_cash + parseFloat(money.pay), + ); + if (this.props.printerStore.rows.length > 0) { + for (let i = 0; i < this.props.printerStore.rows.length; i += 1) { + if (this.props.printerStore.rows[i].defaultPrinter) { + BluetoothSerial.connect( + this.props.printerStore.rows[i].macAddress, + ) + .then(() => { + const writePromises = []; - writePromises.push( - BluetoothSerial.write( - TinyPOS.bufferedText( - "Reason: " + - `${ - money.reason - }` + "\n\n\n", - { align: "left", size: "normal" }, - true, - ), - ), - ); - Promise.all(writePromises); + writePromises.push(BluetoothSerial.write(TinyPOS.init())); + // Header + writePromises.push( + BluetoothSerial.write( + TinyPOS.bufferedText( + "Date: " + + `${moment().format("YYYY/MM/D hh:mm:ss SSS")}`, + { size: "normal" }, + true, + ), + ), + ); + writePromises.push( + BluetoothSerial.write( + TinyPOS.bufferedText( + "Cashier: " + `${defaultShift.attendant}`, + { align: "left", size: "normal" }, + true, + ), + ), + ); - }).catch((e) => { - Toast.show({ - text: e, - buttonText: "Okay", - type: "danger", - position: "bottom", - duration: 3000, - }); - }); - } - } - } + writePromises.push( + BluetoothSerial.write( + TinyPOS.bufferedText( + "Type: " + `${money.type}`, + { align: "left", size: "normal" }, + true, + ), + ), + ); + writePromises.push( + BluetoothSerial.write( + TinyPOS.bufferedText( + "Amount: " + `${money.pay}`, + { align: "left", size: "normal" }, + true, + ), + ), + ); - Toast.show({ - text: "Added Cash", - buttonText: "Okay", - duration: 3000, - }); - } else { - Toast.show({ - text: "Input valid reason", + writePromises.push( + BluetoothSerial.write( + TinyPOS.bufferedText( + "Reason: " + `${money.reason}` + "\n\n\n", + { align: "left", size: "normal" }, + true, + ), + ), + ); + Promise.all(writePromises); + }) + .catch(e => { + Toast.show({ + text: e, buttonText: "Okay", type: "danger", position: "bottom", - duration: 2000, + duration: 3000, + }); }); } - } else { - Toast.show({ - text: "Its not your shift", - buttonText: "Okay", - type: "danger", - position: "bottom", - duration: 2000, - }); + } } + + Toast.show({ + text: "Added Cash", + buttonText: "Okay", + duration: 3000, + }); + } else { + Toast.show({ + text: "Input valid reason", + buttonText: "Okay", + type: "danger", + position: "bottom", + duration: 2000, + }); + } + } else { + Toast.show({ + text: "Its not your shift", + buttonText: "Okay", + type: "danger", + position: "bottom", + duration: 2000, + }); } + } - payOutClick(money) { - if ( - this.props.shiftStore.defaultShift.attendant === - this.props.attendantStore.defaultAttendant.user_name - ) { - if (money.reason){ - this.setState({ pay: "" }); - const { defaultShift } = this.props.shiftStore; + payOutClick(money) { + if ( + this.props.shiftStore.defaultShift.attendant === + this.props.attendantStore.defaultAttendant.user_name + ) { + if (money.reason) { + this.setState({ pay: "" }); + const { defaultShift } = this.props.shiftStore; - const newCash = defaultShift.ending_cash - parseFloat(money.pay); + const newCash = defaultShift.ending_cash - parseFloat(money.pay); - if (defaultShift.ending_cash < parseFloat(money.pay)) { - Toast.show({ - text: "Cash pay-out is greater than the cash available.", - buttonText: "Okay", - type: "danger", - position: "bottom", - duration: 3000, - }); - } else { - defaultShift.addPay({ - date: Date.now(), - amount: parseFloat(money.pay), - reason: money.reason, - flow: "Out", - }); - - defaultShift.setEndCash(newCash); - if (this.props.printerStore.rows.length > 0){ - for (let i = 0; i < this.props.printerStore.rows.length; i += 1) { - if (this.props.printerStore.rows[i].defaultPrinter) { - BluetoothSerial.connect(this.props.printerStore.rows[i].macAddress).then(() => { - const writePromises = []; + if (defaultShift.ending_cash < parseFloat(money.pay)) { + Toast.show({ + text: "Cash pay-out is greater than the cash available.", + buttonText: "Okay", + type: "danger", + position: "bottom", + duration: 3000, + }); + } else { + defaultShift.addPay({ + date: Date.now(), + amount: parseFloat(money.pay), + reason: money.reason, + flow: "Out", + }); - writePromises.push(BluetoothSerial.write(TinyPOS.init())); - // Header - writePromises.push( - BluetoothSerial.write( - TinyPOS.bufferedText( - "Date: " + - `${moment().format("YYYY/MM/D hh:mm:ss SSS")}`, - { size: "normal" }, - true, - ), - ), - ); - writePromises.push( - BluetoothSerial.write( - TinyPOS.bufferedText( - "Cashier: " + - `${ - defaultShift.attendant - }`, - { align: "left", size: "normal" }, - true, - ), - ), - ); + defaultShift.setEndCash(newCash); + if (this.props.printerStore.rows.length > 0) { + for (let i = 0; i < this.props.printerStore.rows.length; i += 1) { + if (this.props.printerStore.rows[i].defaultPrinter) { + BluetoothSerial.connect( + this.props.printerStore.rows[i].macAddress, + ) + .then(() => { + const writePromises = []; - writePromises.push( - BluetoothSerial.write( - TinyPOS.bufferedText( - "Type: " + - `${ - money.type - }`, - { align: "left", size: "normal" }, - true, - ), - ), - ); - writePromises.push( - BluetoothSerial.write( - TinyPOS.bufferedText( - "Amount: " + - `${ - money.pay - }`, - { align: "left", size: "normal" }, - true, - ), - ), - ); + writePromises.push(BluetoothSerial.write(TinyPOS.init())); + // Header + writePromises.push( + BluetoothSerial.write( + TinyPOS.bufferedText( + "Date: " + + `${moment().format("YYYY/MM/D hh:mm:ss SSS")}`, + { size: "normal" }, + true, + ), + ), + ); + writePromises.push( + BluetoothSerial.write( + TinyPOS.bufferedText( + "Cashier: " + `${defaultShift.attendant}`, + { align: "left", size: "normal" }, + true, + ), + ), + ); - writePromises.push( - BluetoothSerial.write( - TinyPOS.bufferedText( - "Reason: " + - `${ - money.reason - }` + "\n\n\n", - { align: "left", size: "normal" }, - true, - ), - ), - ); - Promise.all(writePromises); + writePromises.push( + BluetoothSerial.write( + TinyPOS.bufferedText( + "Type: " + `${money.type}`, + { align: "left", size: "normal" }, + true, + ), + ), + ); + writePromises.push( + BluetoothSerial.write( + TinyPOS.bufferedText( + "Amount: " + `${money.pay}`, + { align: "left", size: "normal" }, + true, + ), + ), + ); - }).catch((e) => { - Toast.show({ - text: e, - buttonText: "Okay", - type: "danger", - position: "bottom", - duration: 3000, - }); - }); - } - } - } + writePromises.push( + BluetoothSerial.write( + TinyPOS.bufferedText( + "Reason: " + `${money.reason}` + "\n\n\n", + { align: "left", size: "normal" }, + true, + ), + ), + ); + Promise.all(writePromises); + }) + .catch(e => { Toast.show({ - text: "Removed Cash", - buttonText: "Okay", - type: "danger", - position: "bottom", - duration: 3000, + text: e, + buttonText: "Okay", + type: "danger", + position: "bottom", + duration: 3000, }); - } - } else { - Toast.show({ - text: "Input valid reason", - buttonText: "Okay", - type: "danger", - position: "bottom", - duration: 2000, - }); + }); + } } - - } else { - Toast.show({ - text: "Its not your shift", - buttonText: "Okay", - type: "danger", - position: "bottom", - duration: 2000, - }); + } + Toast.show({ + text: "Removed Cash", + buttonText: "Okay", + type: "danger", + position: "bottom", + duration: 3000, + }); } + } else { + Toast.show({ + text: "Input valid reason", + buttonText: "Okay", + type: "danger", + position: "bottom", + duration: 2000, + }); + } + } else { + Toast.show({ + text: "Its not your shift", + buttonText: "Okay", + type: "danger", + position: "bottom", + duration: 2000, + }); } + } - onNumberPress(text) { - this.setState({ pay: this.state.pay + text }); - } - onDeletePress() { - this.setState({ pay: this.state.pay.slice(0, -1) }); - } + onNumberPress(text) { + this.setState({ pay: this.state.pay + text }); + } + onDeletePress() { + this.setState({ pay: this.state.pay.slice(0, -1) }); + } - render() { - return ( - this.onNumberPress(text)} - onDeletePress={text => this.onDeletePress(text)} - navigation={this.props.navigation} - openShift={() => this.openShift()} - closeShift={money => this.closeShift(money)} - reshift={() => this.reshift()} - payInClick={money => this.payInClick(money)} - payOutClick={money => this.payOutClick(money)} - dropsClick={money => this.dropsClick(money)} - shiftStarted={this.props.shiftStore.defaultShift.shiftStarted} - shiftEnded={this.props.shiftStore.defaultShift.shiftEnded} - shiftBeginning={this.props.shiftStore.defaultShift.shift_beginning} - shiftEnd={this.props.shiftStore.defaultShift.shift_end} - cashBeginning={this.props.shiftStore.defaultShift.beginning_cash} - cashEnd={this.props.shiftStore.defaultShift.ending_cash} - shiftAttendant={this.props.shiftStore.defaultShift.attendant} - attendant={this.props.attendantStore.defaultAttendant} - pays={this.props.shiftStore.defaultShift.pays.slice()} - amountOnChange={text => this.onAmountChange(text)} - attendantOnChange={text => this.onAttendantChange(text)} - attendants={this.props.attendantStore.rows.slice()} - /> - ); - } + render() { + return ( + this.onNumberPress(text)} + onDeletePress={text => this.onDeletePress(text)} + navigation={this.props.navigation} + openShift={() => this.openShift()} + closeShift={money => this.closeShift(money)} + reshift={() => this.reshift()} + payInClick={money => this.payInClick(money)} + payOutClick={money => this.payOutClick(money)} + dropsClick={money => this.dropsClick(money)} + shiftStarted={this.props.shiftStore.defaultShift.shiftStarted} + shiftEnded={this.props.shiftStore.defaultShift.shiftEnded} + shiftBeginning={this.props.shiftStore.defaultShift.shift_beginning} + shiftEnd={this.props.shiftStore.defaultShift.shift_end} + cashBeginning={this.props.shiftStore.defaultShift.beginning_cash} + cashEnd={this.props.shiftStore.defaultShift.ending_cash} + shiftAttendant={this.props.shiftStore.defaultShift.attendant} + attendant={this.props.attendantStore.defaultAttendant} + pays={this.props.shiftStore.defaultShift.pays.slice()} + amountOnChange={text => this.onAmountChange(text)} + attendantOnChange={text => this.onAttendantChange(text)} + attendants={this.props.attendantStore.rows.slice()} + /> + ); + } } diff --git a/src/store/PosStore/AttendantStore.js b/src/store/PosStore/AttendantStore.js index 7526f71..44171d7 100644 --- a/src/store/PosStore/AttendantStore.js +++ b/src/store/PosStore/AttendantStore.js @@ -1,11 +1,11 @@ import { types, destroy } from "mobx-state-tree"; import { assignUUID } from "./Utils"; import { - editFields, - saveSnapshotToDB, - openAndSyncDB, - syncDB, - deleteObject, + editFields, + saveSnapshotToDB, + openAndSyncDB, + syncDB, + deleteObject, } from "./DbFunctions"; let db = openAndSyncDB("attendants", true); @@ -14,121 +14,121 @@ let db = openAndSyncDB("attendants", true); let replicationHandler = null; export const Attendant = types - .model("Attendant", { - _id: types.identifier(), - user_name: types.string, - pin_code: types.string, - canLogin: types.optional(types.boolean, false), - role: types.optional(types.string, ""), - dateUpdated: types.optional(types.Date, Date.now), - syncStatus: types.optional(types.boolean, false), - commission: types.optional(types.number, 0), - }) - .preProcessSnapshot(snapshot => assignUUID(snapshot, "Attendant")) - .actions(self => ({ - postProcessSnapshot(snapshot) { - saveSnapshotToDB(db, snapshot); - }, - edit(data) { - editFields(self, data); - }, - delete() { - deleteObject(self, db); - }, - changeStatus() { - // self.dateUpdated = Date.now; - self.syncStatus = true; - }, - })); + .model("Attendant", { + _id: types.identifier(), + user_name: types.string, + pin_code: types.string, + canLogin: types.optional(types.boolean, false), + role: types.optional(types.string, ""), + dateUpdated: types.optional(types.Date, Date.now), + syncStatus: types.optional(types.boolean, false), + commission: types.optional(types.number, 0), + }) + .preProcessSnapshot(snapshot => assignUUID(snapshot, "Attendant")) + .actions(self => ({ + postProcessSnapshot(snapshot) { + saveSnapshotToDB(db, snapshot); + }, + edit(data) { + editFields(self, data); + }, + delete() { + deleteObject(self, db); + }, + changeStatus() { + // self.dateUpdated = Date.now; + self.syncStatus = true; + }, + })); const AttendantStore = types - .model("AttendantStore", { - rows: types.optional(types.array(Attendant), []), - defaultAttendant: types.maybe(types.reference(Attendant)), - date: "2018-08-09", - }) - .views(self => ({ - get hasAttendant() { - return self.defaultAttendant ? true : false; - }, - })) - .actions(self => ({ - delete(row) { - destroy(row); - }, - initSync(session) { - replicationHandler = syncDB(db, "attendants", session); - replicationHandler.on("complete", function() { - if (self.rows.length === 0) { - self.getFromDb(20); - } - }); - }, - destroyDb() { - self.defaultAttendant = null; - db.destroy().then(function() { - self.clear(); - db = openAndSyncDB("attendants", true); - }); - }, - add(data) { - self.rows.push(data); - }, - setAttendant(attendant) { - self.defaultAttendant = attendant; - }, - changeDate(data) { - self.date = data; - }, - clear() { - self.rows.clear(); - }, - async find(id) { - let obj = await self.rows.find(data => { - return data._id === id; - }); - if (obj) { - return obj; - } else { - await db.get(id).then(doc => { - return Attendant.create(JSON.parse(JSON.stringify(doc))); - }); - } - return null; - }, - getData() { - return new Promise(function(resolve, reject) { - db.allDocs({ include_docs: true }).then(result => { - resolve({ result: result.total_rows, rowsLength: self.rows.length }); - }); - }); - }, - getFromDb(numberRows) { - db.allDocs({ include_docs: true }).then(entries => { - if (entries.total_rows > 0) { - const { rows } = entries; - for (let i = 0; i < rows.length; i++) { - // doc - const { doc } = rows[i]; - - // Attendant - const attendant = Attendant.create({ - _id: doc._id, - user_name: doc.user_name, - pin_code: doc.pin_code, - role: doc.role, - canLogin: doc.canLogin ? doc.canLogin : false, - commission: doc.commission, - dateUpdated: doc.dateUpdated, - syncStatus: doc.syncStatus, - }); + .model("AttendantStore", { + rows: types.optional(types.array(Attendant), []), + defaultAttendant: types.maybe(types.reference(Attendant)), + date: "2018-08-09", + }) + .views(self => ({ + get hasAttendant() { + return self.defaultAttendant ? true : false; + }, + })) + .actions(self => ({ + delete(row) { + destroy(row); + }, + initSync(session) { + replicationHandler = syncDB(db, "attendants", session); + replicationHandler.on("complete", function() { + if (self.rows.length === 0) { + self.getFromDb(20); + } + }); + }, + destroyDb() { + self.defaultAttendant = null; + db.destroy().then(function() { + self.clear(); + db = openAndSyncDB("attendants", true); + }); + }, + add(data) { + self.rows.push(data); + }, + setAttendant(attendant) { + self.defaultAttendant = attendant; + }, + changeDate(data) { + self.date = data; + }, + clear() { + self.rows.clear(); + }, + async find(id) { + let obj = await self.rows.find(data => { + return data._id === id; + }); + if (obj) { + return obj; + } else { + await db.get(id).then(doc => { + return Attendant.create(JSON.parse(JSON.stringify(doc))); + }); + } + return null; + }, + getData() { + return new Promise(function(resolve, reject) { + db.allDocs({ include_docs: true }).then(result => { + resolve({ result: result.total_rows, rowsLength: self.rows.length }); + }); + }); + }, + getFromDb(numberRows) { + db.allDocs({ include_docs: true }).then(entries => { + if (entries.total_rows > 0) { + const { rows } = entries; + for (let i = 0; i < rows.length; i++) { + // doc + const { doc } = rows[i]; - self.add(attendant); - } - } + // Attendant + const attendant = Attendant.create({ + _id: doc._id, + user_name: doc.user_name, + pin_code: doc.pin_code, + role: doc.role, + canLogin: doc.canLogin ? doc.canLogin : false, + commission: doc.commission, + dateUpdated: doc.dateUpdated, + syncStatus: doc.syncStatus, }); - }, - })); + + self.add(attendant); + } + } + }); + }, + })); const Store = AttendantStore.create({}); diff --git a/src/store/PosStore/ReceiptStore.js b/src/store/PosStore/ReceiptStore.js index 3b6c40a..018d33e 100644 --- a/src/store/PosStore/ReceiptStore.js +++ b/src/store/PosStore/ReceiptStore.js @@ -3,10 +3,10 @@ import DeviceInfo from "react-native-device-info"; import { Customer } from "./CustomerStore"; import { assignUUID } from "./Utils"; import { - editFields, - openAndSyncDB, - saveSnapshotToDB, - syncDB, + editFields, + openAndSyncDB, + saveSnapshotToDB, + syncDB, } from "./DbFunctions"; let db = openAndSyncDB("receipts", true); @@ -16,637 +16,642 @@ let customerDB = openAndSyncDB("customers"); let replicationHandler = null; export const ReceiptLine = types - .model("ReceiptLine", { - _id: types.identifier(), - item: types.string, // identifier item - item_name: types.maybe(types.string), // history purposes - sold_by: types.optional(types.string, ""), - price: types.number, - qty: types.number, - commission_attendant_name: types.optional(types.string, ""), - commission_rate: types.optional(types.number, 0), - commission_amount: types.optional(types.number, 0), - discount_rate: types.optional(types.number,0) - }) - .preProcessSnapshot(snapshot => assignUUID(snapshot, "ReceiptLine")) - .views(self => ({ - get total() { - if (self.discount_rate > 0){ - return (self.price * self.qty) - ((self.price * self.qty) * (self.discount_rate / 100)); - } - return self.price * self.qty; - }, - })) - .actions(self => ({ - setQuantity(qty) { - self.qty = qty; - }, - setPrice(price) { - self.price = price; - }, - setCommissionAttendantName(name) { - self.commission_attendant_name = name; - }, - setCommissionRate(rate) { - self.commission_rate = rate; - }, - setCommissionAmount(amount) { - self.commission_amount = amount; - }, - setDiscountRate(amount){ - self.discount_rate = amount; - }, + .model("ReceiptLine", { + _id: types.identifier(), + item: types.string, // identifier item + item_name: types.maybe(types.string), // history purposes + sold_by: types.optional(types.string, ""), + price: types.number, + qty: types.number, + commission_attendant_name: types.optional(types.string, ""), + commission_rate: types.optional(types.number, 0), + commission_amount: types.optional(types.number, 0), + discount_rate: types.optional(types.number, 0), + }) + .preProcessSnapshot(snapshot => assignUUID(snapshot, "ReceiptLine")) + .views(self => ({ + get total() { + if (self.discount_rate > 0) { + return ( + self.price * self.qty - + self.price * self.qty * (self.discount_rate / 100) + ); + } + return self.price * self.qty; + }, + })) + .actions(self => ({ + setQuantity(qty) { + self.qty = qty; + }, + setPrice(price) { + self.price = price; + }, + setCommissionAttendantName(name) { + self.commission_attendant_name = name; + }, + setCommissionRate(rate) { + self.commission_rate = rate; + }, + setCommissionAmount(amount) { + self.commission_amount = amount; + }, + setDiscountRate(amount) { + self.discount_rate = amount; + }, - edit(data) { - editFields(self, data); - }, - delete() { - getRoot(self).deleteLine(self); - }, - })); + edit(data) { + editFields(self, data); + }, + delete() { + getRoot(self).deleteLine(self); + }, + })); export const Receipt = types - .model("Receipt", { - _id: types.identifier(), - date: types.Date, - status: types.optional( - types.enumeration("Status", [ - "current", - "completed", - "draft", - "cancelled", - ]), - "draft", - ), - reason: types.optional(types.string, ""), - customer: types.string, - lines: types.optional(types.array(ReceiptLine), []), - discountName: types.optional(types.string, ""), - discount: types.optional(types.string, ""), - discountValue: types.optional(types.number, 0), - receiptNumber: types.optional(types.number, 0), - discountType: types.optional(types.string, "percentage"), - taxesValue: types.optional(types.number, 0), - shift: types.optional(types.string, ""), - deviceId: types.optional(types.string, DeviceInfo.getDeviceId()), - dateUpdated: types.optional(types.Date, Date.now), - syncStatus: types.optional(types.boolean, false), - attendant: types.optional(types.string, ""), - }) - .preProcessSnapshot(snapshot => assignUUID(snapshot, "Receipt")) - .views(self => ({ - get grandTotal() { - if (self.lines.length !== 0) { - let total = 0; - for (let i = 0; i < self.lines.length; i++) { - total = total + self.lines[i].total; - } - if (self.taxesValue > 0) { - total = total + self.taxesValue; - } - return total; - } - return 0; - }, - get discounts() { - let total = 0; - if (self.lines.length !== 0){ + .model("Receipt", { + _id: types.identifier(), + date: types.Date, + status: types.optional( + types.enumeration("Status", [ + "current", + "completed", + "draft", + "cancelled", + ]), + "draft", + ), + reason: types.optional(types.string, ""), + customer: types.string, + lines: types.optional(types.array(ReceiptLine), []), + discountName: types.optional(types.string, ""), + discount: types.optional(types.string, ""), + discountValue: types.optional(types.number, 0), + receiptNumber: types.optional(types.number, 0), + discountType: types.optional(types.string, "percentage"), + taxesValue: types.optional(types.number, 0), + shift: types.optional(types.string, ""), + deviceId: types.optional(types.string, DeviceInfo.getDeviceId()), + dateUpdated: types.optional(types.Date, Date.now), + syncStatus: types.optional(types.boolean, false), + attendant: types.optional(types.string, ""), + }) + .preProcessSnapshot(snapshot => assignUUID(snapshot, "Receipt")) + .views(self => ({ + get grandTotal() { + if (self.lines.length !== 0) { + let total = 0; + for (let i = 0; i < self.lines.length; i++) { + total = total + self.lines[i].total; + } + if (self.taxesValue > 0) { + total = total + self.taxesValue; + } + return total; + } + return 0; + }, + get discounts() { + let total = 0; + if (self.lines.length !== 0) { + for (let i = 0; i < self.lines.length; i++) { + if (self.lines[i].discount_rate > 0) { + total += + self.lines[i].price * + self.lines[i].qty * + (self.lines[i].discount_rate / 100); + } + } + } + if (self.discountType === "percentage") { + return self.discountValue * self.grandTotal + total; + } else if (self.discountType === "fixDiscount") { + return self.discountValue + total; + } + }, + get netTotal() { + let discountValue = self.discountValue; + if (self.discountType === "percentage") { + discountValue = discountValue * self.grandTotal; + } - for (let i = 0; i < self.lines.length; i++) { - if (self.lines[i].discount_rate > 0){ - total += ((self.lines[i].price * self.lines[i].qty) * (self.lines[i].discount_rate / 100)); - } - } - } - if (self.discountType === "percentage") { - return (self.discountValue * self.grandTotal) + total; - } else if (self.discountType === "fixDiscount") { - return self.discountValue + total; - } - }, - get netTotal() { - let discountValue = self.discountValue; - if (self.discountType === "percentage") { - discountValue = discountValue * self.grandTotal; - } + let netTotal = self.grandTotal - discountValue; - let netTotal = self.grandTotal - discountValue; + if (netTotal <= 0) { + netTotal = 0; + } - if (netTotal <= 0) { - netTotal = 0; - } + return netTotal; + }, + get grandQuantity() { + if (self.lines.length !== 0) { + let total = 0; + for (let i = 0; i < self.lines.length; i++) { + const { qty } = self.lines[i]; + total = total + qty; + } + return total; + } + return 0; + }, + get subtotal() { + if (self.lines.length !== 0) { + let total = 0; + for (let i = 0; i < self.lines.length; i++) { + total = total + self.lines[i].total; + } + return total; + } + return 0; + }, + })) + .actions(self => ({ + postProcessSnapshot(snapshot) { + saveSnapshotToDB(db, snapshot); + }, + edit(data) { + editFields(self, data); + }, + add(line) { + // change to receiptline + const resLine = self.lines.find( + findLine => + findLine.item === line.item && findLine.price === line.price, + ); - return netTotal; - }, - get grandQuantity() { - if (self.lines.length !== 0) { - let total = 0; - for (let i = 0; i < self.lines.length; i++) { - const { qty } = self.lines[i]; - total = total + qty; - } - return total; - } - return 0; - }, - get subtotal() { - if (self.lines.length !== 0) { - let total = 0; - for (let i = 0; i < self.lines.length; i++) { - total = total + self.lines[i].total; - } - return total; - } - return 0; - }, - })) - .actions(self => ({ - postProcessSnapshot(snapshot) { - saveSnapshotToDB(db, snapshot); - }, - edit(data) { - editFields(self, data); - }, - add(line) { - // change to receiptline - const resLine = self.lines.find( - findLine => - findLine.item === line.item && findLine.price === line.price, - ); + if (resLine) { + resLine.qty = resLine.qty + line.qty; + } else { + self.lines.push(line); + } - if (resLine) { - resLine.qty = resLine.qty + line.qty; - } else { - self.lines.push(line); - } + return self.lines.length - 1; + }, + cancelDiscount() { + self.discount = ""; + self.discountName = ""; + self.discountValue = 0; + self.discountType = "percentage"; + }, + addReceiptDiscount(discount) { + if (discount.percentageType === "percentage") { + self.discountName = discount.name; + self.discount = discount._id; + self.discountValue = discount.value / 100; + self.discountType = discount.percentageType; + } else if (discount.percentageType === "fixDiscount") { + self.discountName = discount.name; + self.discount = discount._id; + self.discountValue = discount.value; + self.discountType = discount.percentageType; + } + }, + addOnTheFlyReceiptDiscount(discount) { + if (discount.percentageType === "percentage") { + self.discount = ""; + self.discountName = "On The Fly Discount"; + self.discountValue = discount.value / 100; + self.discountType = discount.percentageType; + } else if (discount.percentageType === "fixDiscount") { + self.discount = ""; + self.discountName = "On The Fly Discount"; + self.discountValue = discount.value; + self.discountType = discount.percentageType; + } + }, - return self.lines.length - 1; - }, - cancelDiscount() { - self.discount = ""; - self.discountName = ""; - self.discountValue = 0; - self.discountType = "percentage"; - }, - addReceiptDiscount(discount) { - if (discount.percentageType === "percentage") { - self.discountName = discount.name; - self.discount = discount._id; - self.discountValue = discount.value / 100; - self.discountType = discount.percentageType; - } else if (discount.percentageType === "fixDiscount") { - self.discountName = discount.name; - self.discount = discount._id; - self.discountValue = discount.value; - self.discountType = discount.percentageType; - } - }, - addOnTheFlyReceiptDiscount(discount) { - if (discount.percentageType === "percentage") { - self.discount = ""; - self.discountName = "On The Fly Discount"; - self.discountValue = discount.value / 100; - self.discountType = discount.percentageType; - } else if (discount.percentageType === "fixDiscount") { - self.discount = ""; - self.discountName = "On The Fly Discount"; - self.discountValue = discount.value; - self.discountType = discount.percentageType; - } - }, - - addReceiptTax(tax) { - const taxObject = JSON.parse(tax.taxes); - let includedTax = 0; - let addedTax = 0; - let taxInitalValue = 0; - for (let i = 0; i < taxObject.length; i += 1) { - if ( - taxObject[i].activate && - taxObject[i].type === "Included in the price" - ) { - includedTax = includedTax + parseInt(taxObject[i].rate, 10); - } else if ( - taxObject[i].activate && - taxObject[i].type === "Added to the price" - ) { - addedTax = addedTax + parseInt(taxObject[i].rate, 10); - } - } - if (addedTax > 0) { - taxInitalValue = - taxInitalValue + - tax.price / (1 + includedTax / 100) * (addedTax / 100); - self.taxesValue = self.taxesValue + taxInitalValue; - } else { - self.taxesValue = self.taxesValue + taxInitalValue; - } - }, - find(id) { - return self.lines.filter(line => line._id === id)[0]; - }, - setShift(shift) { - self.shift = shift; - }, - setDeviceId(id) { - self.deviceId = id; - }, - // edit(data) { - // Object.keys(data).forEach(key => { - // if (key !== "_id") { - // self[key] = data[key]; - // } - // }); - // }, - deleteLine(line) { - // I don't understand how MobX works here. - const index = self.lines.indexOf(line); + addReceiptTax(tax) { + const taxObject = JSON.parse(tax.taxes); + let includedTax = 0; + let addedTax = 0; + let taxInitalValue = 0; + for (let i = 0; i < taxObject.length; i += 1) { + if ( + taxObject[i].activate && + taxObject[i].type === "Included in the price" + ) { + includedTax = includedTax + parseInt(taxObject[i].rate, 10); + } else if ( + taxObject[i].activate && + taxObject[i].type === "Added to the price" + ) { + addedTax = addedTax + parseInt(taxObject[i].rate, 10); + } + } + if (addedTax > 0) { + taxInitalValue = + taxInitalValue + + tax.price / (1 + includedTax / 100) * (addedTax / 100); + self.taxesValue = self.taxesValue + taxInitalValue; + } else { + self.taxesValue = self.taxesValue + taxInitalValue; + } + }, + find(id) { + return self.lines.filter(line => line._id === id)[0]; + }, + setShift(shift) { + self.shift = shift; + }, + setDeviceId(id) { + self.deviceId = id; + }, + // edit(data) { + // Object.keys(data).forEach(key => { + // if (key !== "_id") { + // self[key] = data[key]; + // } + // }); + // }, + deleteLine(line) { + // I don't understand how MobX works here. + const index = self.lines.indexOf(line); - self.lines.splice(index, 1); - }, - delete() { - ReceiptStore.delete(self); // Reference - }, - clear() { - self.discount = ""; - self.discountValue = 0; - self.taxesValue = 0; + self.lines.splice(index, 1); + }, + delete() { + ReceiptStore.delete(self); // Reference + }, + clear() { + self.discount = ""; + self.discountValue = 0; + self.taxesValue = 0; - // Yay! - self.lines.splice(0, self.lines.length); - }, - completed(attendant) { - self.attendant = attendant; + // Yay! + self.lines.splice(0, self.lines.length); + }, + completed(attendant) { + self.attendant = attendant; - self.status = "completed"; - }, - cancelled(obj) { - self.status = "cancelled"; - self.dateUpdated = Date.now(); - self.syncStatus = false; - }, - changeReason(reasonVal) { - self.reason = reasonVal; - }, - changeStatus() { - // self.dateUpdate = Date.now; - self.syncStatus = true; - }, - })); + self.status = "completed"; + }, + cancelled(obj) { + self.status = "cancelled"; + self.dateUpdated = Date.now(); + self.syncStatus = false; + }, + changeReason(reasonVal) { + self.reason = reasonVal; + }, + changeStatus() { + // self.dateUpdate = Date.now; + self.syncStatus = true; + }, + })); const Store = types - .model("ReceiptStore", { - rows: types.optional(types.array(types.reference(Receipt)), []), - defaultCustomer: types.optional(types.reference(Customer), ""), - defaultReceipt: types.maybe(types.reference(Receipt)), - previousReceipt: types.maybe(types.reference(Receipt)), - selectedLine: types.maybe(types.reference(ReceiptLine)), - lastScannedBarcode: types.optional(types.string, ""), - commissions: types.optional(types.string, "[]"), - }) - .actions(self => ({ - initSync(session) { - replicationHandler = syncDB(db, "receipts", session); - replicationHandler.on("complete", function() { - if (self.rows.length === 0) { - // self.getFromDb(20); - } - }); - }, - destroyDb() { - self.defaultCustomer = ""; - self.defaultReceipt = null; - self.selectedLine = null; - self.lastScannedBarcode = ""; + .model("ReceiptStore", { + rows: types.optional(types.array(types.reference(Receipt)), []), + defaultCustomer: types.optional(types.reference(Customer), ""), + defaultReceipt: types.maybe(types.reference(Receipt)), + previousReceipt: types.maybe(types.reference(Receipt)), + selectedLine: types.maybe(types.reference(ReceiptLine)), + lastScannedBarcode: types.optional(types.string, ""), + commissions: types.optional(types.string, "[]"), + }) + .actions(self => ({ + initSync(session) { + replicationHandler = syncDB(db, "receipts", session); + replicationHandler.on("complete", function() { + if (self.rows.length === 0) { + // self.getFromDb(20); + } + }); + }, + destroyDb() { + self.defaultCustomer = ""; + self.defaultReceipt = null; + self.selectedLine = null; + self.lastScannedBarcode = ""; - db.destroy().then(function() { - self.clearRows(); - db = openAndSyncDB("receipts", true); - // rowsOptions = {}; - }); - }, - clearRows() { - self.rows.clear(); - }, - emptyCommissions() { - self.commissions = JSON.stringify([]); - }, - addCommissions(objectCommission) { - const cat = JSON.parse(self.commissions); - cat.push(objectCommission); - self.commissions = JSON.stringify(cat); - }, - updateCommissions(obj) { - if (obj) { - let existing = false; - let objectLength = JSON.parse(self.commissions); + db.destroy().then(function() { + self.clearRows(); + db = openAndSyncDB("receipts", true); + // rowsOptions = {}; + }); + }, + clearRows() { + self.rows.clear(); + }, + emptyCommissions() { + self.commissions = JSON.stringify([]); + }, + addCommissions(objectCommission) { + const cat = JSON.parse(self.commissions); + cat.push(objectCommission); + self.commissions = JSON.stringify(cat); + }, + updateCommissions(obj) { + if (obj) { + let existing = false; + let objectLength = JSON.parse(self.commissions); - for (let i = 0; i < objectLength.length; i += 1) { - if (obj.commission_attendant_name === objectLength[i].name) { - objectLength[i].amount += obj.commission_amount; - existing = true; - self.commissions = JSON.stringify(objectLength); - } - } - if (!existing) { - self.addCommissions({ - name: obj.commission_attendant_name, - amount: obj.commission_amount, - }); - } - } - }, - setPreviuosReceiptToNull() { - self.previousReceipt = null; - }, - setPreviousReceipt(obj) { - self.previousReceipt = obj; - }, - setCustomer(customer) { - self.defaultCustomer = customer; - }, - setReceipt(receipt) { - self.defaultReceipt = receipt; - }, - async setDefaultCustomer() { - return await customerDB - .find({ - selector: { - name: { $eq: "Default customer" }, - }, - }) - .then(result => { - const { docs } = result; - if (docs.length === 0) { - const newCustomer = Customer.create({ - name: "Default customer", - email: "default@bai.ph", - phoneNumber: "09213887721", - note: "Default note", - }); - self.setCustomer(newCustomer); - } else { - const customer = Customer.create({ - _id: docs[0]._id, - name: docs[0].name, - email: docs[0].email, - phoneNumber: docs[0].phoneNumber, - note: docs[0].note, - }); - self.setCustomer(customer); - } - return Promise.resolve("Success"); - }); - }, - setReceiptLine(line) { - self.selectedLine = line; - }, - add(data) { - self.rows.push(data); - }, - findReceipt(id) { - let obj = self.rows.find(data => { - return data._id === id; + for (let i = 0; i < objectLength.length; i += 1) { + if (obj.commission_attendant_name === objectLength[i].name) { + objectLength[i].amount += obj.commission_amount; + existing = true; + self.commissions = JSON.stringify(objectLength); + } + } + if (!existing) { + self.addCommissions({ + name: obj.commission_attendant_name, + amount: obj.commission_amount, + }); + } + } + }, + setPreviuosReceiptToNull() { + self.previousReceipt = null; + }, + setPreviousReceipt(obj) { + self.previousReceipt = obj; + }, + setCustomer(customer) { + self.defaultCustomer = customer; + }, + setReceipt(receipt) { + self.defaultReceipt = receipt; + }, + async setDefaultCustomer() { + return await customerDB + .find({ + selector: { + name: { $eq: "Default customer" }, + }, + }) + .then(result => { + const { docs } = result; + if (docs.length === 0) { + const newCustomer = Customer.create({ + name: "Default customer", + email: "default@bai.ph", + phoneNumber: "09213887721", + note: "Default note", }); - - if (obj) { - return obj; - } else { - db.get(id).then(doc => { - return Receipt.create(JSON.parse(JSON.stringify(doc))); - }); - } - return null; - }, - delete(row) { - const index = self.rows.indexOf(row); - self.rows.splice(index, 1); - destroy(row); - }, - newReceipt() { - self.numberOfReceipts().then(response => { - const newReceipt = Receipt.create({ - date: Date.parse(new Date().toDateString()), - status: "current", - customer: self.defaultCustomer._id, - receiptNumber: parseInt(response, 10) + 1, - dateUpdated: Date.now(), - syncStatus: false, - }); - self.setReceipt(newReceipt); + self.setCustomer(newCustomer); + } else { + const customer = Customer.create({ + _id: docs[0]._id, + name: docs[0].name, + email: docs[0].email, + phoneNumber: docs[0].phoneNumber, + note: docs[0].note, }); - }, - getReceiptsForItemSalesReport(date) { - return new Promise((resolve, reject) => { - db - .find({ - selector: { - date: { - $regex: `.*${Date.parse(new Date(date).toDateString())}.*`, - }, - status: { $eq: "completed" }, - }, - }) + self.setCustomer(customer); + } + return Promise.resolve("Success"); + }); + }, + setReceiptLine(line) { + self.selectedLine = line; + }, + add(data) { + self.rows.push(data); + }, + findReceipt(id) { + let obj = self.rows.find(data => { + return data._id === id; + }); - .then(result => { - const { docs } = result; - return resolve(docs); - }); - }); - }, + if (obj) { + return obj; + } else { + db.get(id).then(doc => { + return Receipt.create(JSON.parse(JSON.stringify(doc))); + }); + } + return null; + }, + delete(row) { + const index = self.rows.indexOf(row); + self.rows.splice(index, 1); + destroy(row); + }, + newReceipt() { + self.numberOfReceipts().then(response => { + const newReceipt = Receipt.create({ + date: Date.parse(new Date().toDateString()), + status: "current", + customer: self.defaultCustomer._id, + receiptNumber: parseInt(response, 10) + 1, + dateUpdated: Date.now(), + syncStatus: false, + }); + self.setReceipt(newReceipt); + }); + }, + getReceiptsForItemSalesReport(date) { + return new Promise((resolve, reject) => { + db + .find({ + selector: { + date: { + $regex: `.*${Date.parse(new Date(date).toDateString())}.*`, + }, + status: { $eq: "completed" }, + }, + }) - currentReceipt() { - if (!self.defaultReceipt || self.defaultReceipt.status === "completed") { - db - .find({ - selector: { - status: { $eq: "current" }, - }, - }) - .then(async result => { - const { docs } = result; - let receiptNumber = await self.numberOfReceipts(); - // if no docs - if (docs.length === 0) { - const newReceipt = Receipt.create({ - date: Date.parse(new Date().toDateString()), - status: "current", - customer: self.defaultCustomer._id, - receiptNumber: parseInt(receiptNumber, 10) + 1, - dateUpdated: Date.now(), - syncStatus: false, - }); + .then(result => { + const { docs } = result; + return resolve(docs); + }); + }); + }, - self.setReceipt(newReceipt); - } else { - const receipt = Receipt.create({ - _id: docs[0]._id, - date: Date.parse(new Date(docs[0].date).toDateString()), - status: docs[0].status, - reason: docs[0].reason, - customer: docs[0].customer, - discount: docs[0].discount, - discountName: docs[0].discountName, - discountValue: docs[0].discountValue, - discountType: docs[0].discountType, - receiptNumber: docs[0].receiptNumber, - dateUpdated: docs[0].dateUpdated, - syncStatus: docs[0].syncStatus, - attendant: docs[0].attendant, - }); - const { lines } = docs[0]; - // - // lines.map(item => { - // console.log(JSON.parse(JSON.stringify(item))) - // receipt.add(JSON.parse(JSON.stringify(item))); - // }); - Object.keys(lines).map(key => { - receipt.add(lines[key]); - }); - self.setReceipt(receipt); - } - return self.defaultReceipt; - }); - } - if (self.rows.length === 0) { - self.getFromDb(20); + currentReceipt() { + if (!self.defaultReceipt || self.defaultReceipt.status === "completed") { + db + .find({ + selector: { + status: { $eq: "current" }, + }, + }) + .then(async result => { + const { docs } = result; + let receiptNumber = await self.numberOfReceipts(); + // if no docs + if (docs.length === 0) { + const newReceipt = Receipt.create({ + date: Date.parse(new Date().toDateString()), + status: "current", + customer: self.defaultCustomer._id, + receiptNumber: parseInt(receiptNumber, 10) + 1, + dateUpdated: Date.now(), + syncStatus: false, + }); + + self.setReceipt(newReceipt); + } else { + const receipt = Receipt.create({ + _id: docs[0]._id, + date: Date.parse(new Date(docs[0].date).toDateString()), + status: docs[0].status, + reason: docs[0].reason, + customer: docs[0].customer, + discount: docs[0].discount, + discountName: docs[0].discountName, + discountValue: docs[0].discountValue, + discountType: docs[0].discountType, + receiptNumber: docs[0].receiptNumber, + dateUpdated: docs[0].dateUpdated, + syncStatus: docs[0].syncStatus, + attendant: docs[0].attendant, + }); + const { lines } = docs[0]; + // + // lines.map(item => { + // console.log(JSON.parse(JSON.stringify(item))) + // receipt.add(JSON.parse(JSON.stringify(item))); + // }); + Object.keys(lines).map(key => { + receipt.add(lines[key]); + }); + self.setReceipt(receipt); } - }, - unselectReceiptLine() { - self.selectedLine = null; - }, - setLastScannedBarcode(barcodeValue) { - self.lastScannedBarcode = barcodeValue; - }, - getShiftReceipts(shift) { - return new Promise((resolve, reject) => { - db - .find({ - selector: { - shift: { $regex: `.*${shift}.*` }, - }, - }) - .then(result => { - const { docs } = result; - return resolve(docs); - }); - }); - }, - async getFromDb(numberRows) { - // rowsOptions.limit = numberRows; - // rowsOptions.include_docs = true; - // rowsOptions.descending = true; - // rowsOptions.startKey = 21; - // rowsOptions.endKey = 20; - // rowsOptions.skip = 0; + return self.defaultReceipt; + }); + } + if (self.rows.length === 0) { + self.getFromDb(20); + } + }, + unselectReceiptLine() { + self.selectedLine = null; + }, + setLastScannedBarcode(barcodeValue) { + self.lastScannedBarcode = barcodeValue; + }, + getShiftReceipts(shift) { + return new Promise((resolve, reject) => { + db + .find({ + selector: { + shift: { $regex: `.*${shift}.*` }, + }, + }) + .then(result => { + const { docs } = result; + return resolve(docs); + }); + }); + }, + async getFromDb(numberRows) { + // rowsOptions.limit = numberRows; + // rowsOptions.include_docs = true; + // rowsOptions.descending = true; + // rowsOptions.startKey = 21; + // rowsOptions.endKey = 20; + // rowsOptions.skip = 0; - // db.allDocs(rowsOptions).then(entries => { - // if (entries && entries.rows.length > 0) { - // - // // rowsOptions.startKey = 21; - // // rowsOptions.endKey = 20; - // for (let i = 0; i < entries.rows.length; i++) { - // const { doc } = entries.rows[i]; - // console.log(doc.receiptNumber) - // console.log(doc.lines) - // const receiptObj = Receipt.create({ - // _id: doc._id, - // date: Date.parse(new Date(doc.date).toDateString()), - // status: doc.status, - // reason: doc.reason, - // customer: doc.customer, - // receiptNumber: doc.receiptNumber, - // discountName: doc.discountName, - // discount: doc.discount, - // discountValue: doc.discountValue, - // discountType: doc.discountType, - // dateUpdated: doc.dateUpdated, - // syncStatus: doc.syncStatus, - // attendant: doc.attendant, - // }); - // Object.keys(doc.lines).map(key => { - // receiptObj.add(doc.lines[key]); - // }); - // self.add(receiptObj); - // } - // } - // }); - // db.allDocs().then(function (result){ - // return Promise.all(result.rows.map(function (row){ - // return db.remove(row.id,row.value.rev) - // })) - // }) + // db.allDocs(rowsOptions).then(entries => { + // if (entries && entries.rows.length > 0) { + // + // // rowsOptions.startKey = 21; + // // rowsOptions.endKey = 20; + // for (let i = 0; i < entries.rows.length; i++) { + // const { doc } = entries.rows[i]; + // console.log(doc.receiptNumber) + // console.log(doc.lines) + // const receiptObj = Receipt.create({ + // _id: doc._id, + // date: Date.parse(new Date(doc.date).toDateString()), + // status: doc.status, + // reason: doc.reason, + // customer: doc.customer, + // receiptNumber: doc.receiptNumber, + // discountName: doc.discountName, + // discount: doc.discount, + // discountValue: doc.discountValue, + // discountType: doc.discountType, + // dateUpdated: doc.dateUpdated, + // syncStatus: doc.syncStatus, + // attendant: doc.attendant, + // }); + // Object.keys(doc.lines).map(key => { + // receiptObj.add(doc.lines[key]); + // }); + // self.add(receiptObj); + // } + // } + // }); + // db.allDocs().then(function (result){ + // return Promise.all(result.rows.map(function (row){ + // return db.remove(row.id,row.value.rev) + // })) + // }) - let maximumReceiptNumber = (await self.numberOfReceipts()) - 1; - let minimumReceiptNumber = maximumReceiptNumber - 20; + let maximumReceiptNumber = (await self.numberOfReceipts()) - 1; + let minimumReceiptNumber = maximumReceiptNumber - 20; - await db - .find({ - selector: { - receiptNumber: { - $gt: minimumReceiptNumber, - $lte: maximumReceiptNumber, - }, - }, - }) - .then(async result => { - if (result && result.docs.length > 0) { - for (let x = 0; x < result.docs.length; x++) { - const doc = result.docs[x]; + await db + .find({ + selector: { + receiptNumber: { + $gt: minimumReceiptNumber, + $lte: maximumReceiptNumber, + }, + }, + }) + .then(async result => { + if (result && result.docs.length > 0) { + for (let x = 0; x < result.docs.length; x++) { + const doc = result.docs[x]; - const receiptObj = Receipt.create({ - _id: doc._id, - date: Date.parse(new Date(doc.date).toDateString()), - status: doc.status, - reason: doc.reason, - customer: doc.customer, - receiptNumber: doc.receiptNumber, - discountName: doc.discountName, - discount: doc.discount, - discountValue: doc.discountValue, - discountType: doc.discountType, - dateUpdated: doc.dateUpdated, - syncStatus: doc.syncStatus, - attendant: doc.attendant, - }); - Object.keys(doc.lines).map(key => { - receiptObj.add(doc.lines[key]); - }); - self.add(receiptObj); - } - } - }); - }, - async find(key) { - return await db.get(key).then(receipt => { - const receiptObject = Receipt.create({ - _id: receipt._id, - date: receipt.date, - status: receipt.status, - customer: receipt.customer, - discountName: receipt.discountName, - discount: receipt.discount, - discountType: receipt.discountType, - discountValue: receipt.discountValue, - receiptNumber: receipt.receiptNumber, - dateUpdated: receipt.dateUpdated, - syncStatus: receipt.syncStatus, - attendant: receipt.attendant, - }); - Object.keys(receipt.lines).map(index => { - receiptObject.add(receipt.lines[index]); - }); - return Promise.resolve(receiptObject); - }); - }, - numberOfReceipts() { - return new Promise((resolve, reject) => { - db.allDocs().then(entries => { - return resolve(entries.total_rows); - }); - }); - }, - })); + const receiptObj = Receipt.create({ + _id: doc._id, + date: Date.parse(new Date(doc.date).toDateString()), + status: doc.status, + reason: doc.reason, + customer: doc.customer, + receiptNumber: doc.receiptNumber, + discountName: doc.discountName, + discount: doc.discount, + discountValue: doc.discountValue, + discountType: doc.discountType, + dateUpdated: doc.dateUpdated, + syncStatus: doc.syncStatus, + attendant: doc.attendant, + }); + Object.keys(doc.lines).map(key => { + receiptObj.add(doc.lines[key]); + }); + self.add(receiptObj); + } + } + }); + }, + async find(key) { + return await db.get(key).then(receipt => { + const receiptObject = Receipt.create({ + _id: receipt._id, + date: receipt.date, + status: receipt.status, + customer: receipt.customer, + discountName: receipt.discountName, + discount: receipt.discount, + discountType: receipt.discountType, + discountValue: receipt.discountValue, + receiptNumber: receipt.receiptNumber, + dateUpdated: receipt.dateUpdated, + syncStatus: receipt.syncStatus, + attendant: receipt.attendant, + }); + Object.keys(receipt.lines).map(index => { + receiptObject.add(receipt.lines[index]); + }); + return Promise.resolve(receiptObject); + }); + }, + numberOfReceipts() { + return new Promise((resolve, reject) => { + db.allDocs().then(entries => { + return resolve(entries.total_rows); + }); + }); + }, + })); const ReceiptStore = Store.create({}); diff --git a/src/store/PosStore/ShiftStore.js b/src/store/PosStore/ShiftStore.js index c9617a9..e7b1d0b 100644 --- a/src/store/PosStore/ShiftStore.js +++ b/src/store/PosStore/ShiftStore.js @@ -1,367 +1,366 @@ import { types } from "mobx-state-tree"; import { assignUUID } from "./Utils"; import { - saveSnapshotToDB, - openAndSyncDB, - syncDB, - editFields, + saveSnapshotToDB, + openAndSyncDB, + syncDB, + editFields, } from "./DbFunctions"; let db = openAndSyncDB("shifts", true); let rowsOptions = {}; export const Pay = types.model("Pay", { - date: types.Date, - amount: types.number, - reason: types.string, - flow: types.enumeration("Flow", ["In", "Out", "Drops"]), + date: types.Date, + amount: types.number, + reason: types.string, + flow: types.enumeration("Flow", ["In", "Out", "Drops"]), }); export const Shift = types - .model("Shift", { - _id: types.identifier(), - beginning_cash: types.maybe(types.number), - ending_cash: types.maybe(types.number), - short: types.maybe(types.number), - actual_money: types.optional(types.number, 0), - total_sales: types.optional(types.number, 0), - total_discounts: types.optional(types.number, 0), - total_taxes: types.optional(types.number, 0), - shift_beginning: types.maybe(types.Date), - shift_end: types.maybe(types.Date), - attendant: types.optional(types.string, ""), - status: types.optional(types.string, "Opened"), - numberOfTransaction: types.optional(types.number, 0), - commissions: types.optional(types.number, 0), - pays: types.optional(types.array(Pay), []), - reportType: types.optional(types.string, "XReading"), - dateUpdated: types.optional(types.Date, Date.now), - syncStatus: types.optional(types.boolean, false), - }) - .preProcessSnapshot(snapshot => assignUUID(snapshot, "Shift")) - .views(self => ({ - get shiftEnded() { - return self.shift_end ? true : false; - }, - get shiftStarted() { - return self.shift_beginning ? true : false; - }, - get totalPayOut() { - let totalPayOut = 0; - for (let i = 0; i < self.pays.length; i += 1) { - if (self.pays[i].flow === "Out") { - totalPayOut = totalPayOut + self.pays[i].amount; - } - } - return totalPayOut; - }, - get totalPayIn() { - let totalPayIn = 0; - for (let i = 0; i < self.pays.length; i += 1) { - if (self.pays[i].flow === "In") { - totalPayIn = totalPayIn + self.pays[i].amount; - } - } - return totalPayIn; - }, - get totalDrops() { - let drops = 0; - for (let i = 0; i < self.pays.length; i += 1) { - if (self.pays[i].flow === "Drops") { - drops = drops + self.pays[i].amount; - } - } - return drops; - }, - get totalCashSales() { - let totalCashSales = - self.total_sales + self.total_discounts - self.total_taxes; - return totalCashSales; - }, - get totalNetSales() { - let totalNetSales = self.total_sales - self.commissions; - return totalNetSales; - }, - get computeShort() { - let shortValue = self.actual_money - self.ending_cash; - return shortValue; - }, - get expectedDrawer() { - return parseInt(self.ending_cash, 10) - parseInt(self.commissions, 10); - }, - })) - .actions(self => ({ - postProcessSnapshot(snapshot) { - saveSnapshotToDB(db, snapshot); - }, - edit(data) { - editFields(self, data); - }, - addPay(pay) { - self.pays.push(pay); - }, - addNumberOfTransaction() { - self.numberOfTransaction += 1; - }, - addTotalSales(amount) { - self.total_sales = self.total_sales + amount; - }, - addTotalDiscount(amount) { - self.total_discounts = self.total_discounts + amount; - }, - addTotalTaxes(amount) { - self.total_taxes = self.total_taxes + amount; - }, - startShift() { - self.shift_beginning = Date.now(); - }, - endShift() { - self.shift_end = Date.now(); - }, - setBeginCash(cash) { - self.beginning_cash = cash; - self.ending_cash = cash; - }, - setEndCash(cash) { - self.ending_cash = cash; - }, - setAttendant(attendant) { - self.attendant = attendant; - }, - changeStatus() { - // self.dateUpdated = Date.now; - // if(self.status === "Closed"){ - // self.syncStatus = true; - // } - self.status = "Closed"; - }, - changeSyncStatus() { - self.syncStatus = true; - }, - changeActualMoney(money) { - self.actual_money = parseInt(money, 10); - }, - setType() { - self.reportType = "ZReading"; - }, - changeShort() { - self.short = 0; - }, - changeValues(obj) { - self.beginning_cash += obj.beginning_cash; - self.ending_cash += obj.ending_cash; - self.short += obj.short; - self.actual_money += obj.actual_money; - self.total_sales += obj.total_sales; - self.total_discounts += obj.total_discounts; - self.total_taxes += obj.total_taxes; - self.numberOfTransaction += obj.numberOfTransaction; - }, - minusValues(obj) { - self.numberOfTransaction -= 1; - self.ending_cash -= obj.total; - self.total_sales -= obj.total; - self.total_discounts -= obj.receipt.discountValue; - self.total_taxes -= obj.receipt.taxesValue; - }, - addCommission(commission) { - self.commissions = self.commissions + commission; - }, - })); + .model("Shift", { + _id: types.identifier(), + beginning_cash: types.maybe(types.number), + ending_cash: types.maybe(types.number), + short: types.maybe(types.number), + actual_money: types.optional(types.number, 0), + total_sales: types.optional(types.number, 0), + total_discounts: types.optional(types.number, 0), + total_taxes: types.optional(types.number, 0), + shift_beginning: types.maybe(types.Date), + shift_end: types.maybe(types.Date), + attendant: types.optional(types.string, ""), + status: types.optional(types.string, "Opened"), + numberOfTransaction: types.optional(types.number, 0), + commissions: types.optional(types.number, 0), + pays: types.optional(types.array(Pay), []), + reportType: types.optional(types.string, "XReading"), + dateUpdated: types.optional(types.Date, Date.now), + syncStatus: types.optional(types.boolean, false), + }) + .preProcessSnapshot(snapshot => assignUUID(snapshot, "Shift")) + .views(self => ({ + get shiftEnded() { + return self.shift_end ? true : false; + }, + get shiftStarted() { + return self.shift_beginning ? true : false; + }, + get totalPayOut() { + let totalPayOut = 0; + for (let i = 0; i < self.pays.length; i += 1) { + if (self.pays[i].flow === "Out") { + totalPayOut = totalPayOut + self.pays[i].amount; + } + } + return totalPayOut; + }, + get totalPayIn() { + let totalPayIn = 0; + for (let i = 0; i < self.pays.length; i += 1) { + if (self.pays[i].flow === "In") { + totalPayIn = totalPayIn + self.pays[i].amount; + } + } + return totalPayIn; + }, + get totalDrops() { + let drops = 0; + for (let i = 0; i < self.pays.length; i += 1) { + if (self.pays[i].flow === "Drops") { + drops = drops + self.pays[i].amount; + } + } + return drops; + }, + get totalCashSales() { + let totalCashSales = + self.total_sales + self.total_discounts - self.total_taxes; + return totalCashSales; + }, + get totalNetSales() { + let totalNetSales = self.total_sales - self.commissions; + return totalNetSales; + }, + get computeShort() { + let shortValue = self.actual_money - self.ending_cash; + return shortValue; + }, + get expectedDrawer() { + return parseInt(self.ending_cash, 10) - parseInt(self.commissions, 10); + }, + })) + .actions(self => ({ + postProcessSnapshot(snapshot) { + saveSnapshotToDB(db, snapshot); + }, + edit(data) { + editFields(self, data); + }, + addPay(pay) { + self.pays.push(pay); + }, + addNumberOfTransaction() { + self.numberOfTransaction += 1; + }, + addTotalSales(amount) { + self.total_sales = self.total_sales + amount; + }, + addTotalDiscount(amount) { + self.total_discounts = self.total_discounts + amount; + }, + addTotalTaxes(amount) { + self.total_taxes = self.total_taxes + amount; + }, + startShift() { + self.shift_beginning = Date.now(); + }, + endShift() { + self.shift_end = Date.now(); + }, + setBeginCash(cash) { + self.beginning_cash = cash; + self.ending_cash = cash; + }, + setEndCash(cash) { + self.ending_cash = cash; + }, + setAttendant(attendant) { + self.attendant = attendant; + }, + changeStatus() { + // self.dateUpdated = Date.now; + // if(self.status === "Closed"){ + // self.syncStatus = true; + // } + self.status = "Closed"; + }, + changeSyncStatus() { + self.syncStatus = true; + }, + changeActualMoney(money) { + self.actual_money = parseInt(money, 10); + }, + setType() { + self.reportType = "ZReading"; + }, + changeShort() { + self.short = 0; + }, + changeValues(obj) { + self.beginning_cash += obj.beginning_cash; + self.ending_cash += obj.ending_cash; + self.short += obj.short; + self.actual_money += obj.actual_money; + self.total_sales += obj.total_sales; + self.total_discounts += obj.total_discounts; + self.total_taxes += obj.total_taxes; + self.numberOfTransaction += obj.numberOfTransaction; + }, + minusValues(obj) { + self.numberOfTransaction -= 1; + self.ending_cash -= obj.total; + self.total_sales -= obj.total; + self.total_discounts -= obj.receipt.discountValue; + self.total_taxes -= obj.receipt.taxesValue; + }, + addCommission(commission) { + self.commissions = self.commissions + commission; + }, + })); const ShiftStore = types - .model("ShiftStore", { - defaultShift: types.maybe(types.reference(Shift)), - zReading: types.maybe(types.reference(Shift)), - }) - .actions(self => ({ - initSync(session) { - syncDB(db, "shifts", session, () => {}); - }, - setShift(shift) { - self.defaultShift = shift; - }, - destroyDb() { - db.destroy().then(function() { - db = openAndSyncDB("shifts", true); - rowsOptions = {}; - self.newShift(); - }); - }, - addPay(obj) { - Object.keys(obj).map(key => { - self.defaultShift.addPay(obj[key]); - }); - }, - newShift() { - self.defaultShift = Shift.create({}); - }, - setZReading(obj) { - self.zReading = Shift.create({}); - }, - setZReadingFromDb(obj) { - self.zReading = obj; - }, - setNewValues(obj) { - self.defaultShift.minusValues(obj); - }, - findShift(id) { - return new Promise(function(resolve, reject) { - db.get(id).then(doc => { - if (doc) { - resolve(Shift.create(JSON.parse(JSON.stringify(doc)))); - } else { - resolve(null); - } - }); + .model("ShiftStore", { + defaultShift: types.maybe(types.reference(Shift)), + zReading: types.maybe(types.reference(Shift)), + }) + .actions(self => ({ + initSync(session) { + syncDB(db, "shifts", session, () => {}); + }, + setShift(shift) { + self.defaultShift = shift; + }, + destroyDb() { + db.destroy().then(function() { + db = openAndSyncDB("shifts", true); + rowsOptions = {}; + self.newShift(); + }); + }, + addPay(obj) { + Object.keys(obj).map(key => { + self.defaultShift.addPay(obj[key]); + }); + }, + newShift() { + self.defaultShift = Shift.create({}); + }, + setZReading(obj) { + self.zReading = Shift.create({}); + }, + setZReadingFromDb(obj) { + self.zReading = obj; + }, + setNewValues(obj) { + self.defaultShift.minusValues(obj); + }, + findShift(id) { + return new Promise(function(resolve, reject) { + db.get(id).then(doc => { + if (doc) { + resolve(Shift.create(JSON.parse(JSON.stringify(doc)))); + } else { + resolve(null); + } + }); + }); + }, + findCurrentShift(name) { + db + .createIndex({ + index: { fields: ["attendant"] }, + }) + .then(function() { + db + .find({ + selector: { + attendant: { $regex: name }, + shift_end: { $regex: null }, + }, + }) + .then(result => { + // const shiftObj = Shift.create({ + // _id: result._id, + // beginning_cash: result.beginning_cash, + // ending_cash: result.ending_cash, + // shift_beginning: result.shift_beginning, + // shift_end: result.shift_end, + // attendant: result.attendant, + // short: result.short, + // actual_money: result.actual_money, + // numberOfTransaction: result.numberOfTransaction, + // total_sales: result.total_sales, + // total_discounts: result.total_discounts, + // total_taxes: result.total_taxes, + // status: result.status, + // reportType: result.reportType, + // dateUpdated: Date.now(), + // syncStatus: false, + // }); + // self.setShift(shiftObj); }); - }, - findCurrentShift(name) { - db - .createIndex({ - index: { fields: ["attendant"] }, - }) - .then(function() { - db - .find({ - selector: { - attendant: { $regex: name }, - shift_end: { $regex: null }, - }, - }) - .then(result => { - // const shiftObj = Shift.create({ - // _id: result._id, - // beginning_cash: result.beginning_cash, - // ending_cash: result.ending_cash, - // shift_beginning: result.shift_beginning, - // shift_end: result.shift_end, - // attendant: result.attendant, - // short: result.short, - // actual_money: result.actual_money, - // numberOfTransaction: result.numberOfTransaction, - // total_sales: result.total_sales, - // total_discounts: result.total_discounts, - // total_taxes: result.total_taxes, - // status: result.status, - // reportType: result.reportType, - // dateUpdated: Date.now(), - // syncStatus: false, - // }); - // self.setShift(shiftObj); - }); - }); - }, - getFromDb(numberRows, attendantName) { - rowsOptions.limit = numberRows; - rowsOptions.include_docs = true; - db.allDocs(rowsOptions).then(entries => { - if (entries && entries.rows.length > 0) { - let check = false; - for (let i = 0; i < entries.rows.length; i++) { - const { doc } = entries.rows[i]; - if (entries.rows[i].doc.shift_end === null) { - check = true; + }); + }, + getFromDb(numberRows, attendantName) { + rowsOptions.limit = numberRows; + rowsOptions.include_docs = true; + db.allDocs(rowsOptions).then(entries => { + if (entries && entries.rows.length > 0) { + let check = false; + for (let i = 0; i < entries.rows.length; i++) { + const { doc } = entries.rows[i]; + if (entries.rows[i].doc.shift_end === null) { + check = true; - const shiftObj = Shift.create({ - _id: doc._id, - beginning_cash: doc.beginning_cash, - ending_cash: doc.ending_cash, - shift_beginning: doc.shift_beginning, - shift_end: doc.shift_end, - attendant: doc.attendant, - short: doc.short, - commissions: doc.commissions ? doc.commissions : 0, - actual_money: doc.actual_money, - numberOfTransaction: doc.numberOfTransaction, - total_sales: doc.total_sales, - total_discounts: doc.total_discounts, - total_taxes: doc.total_taxes, - status: doc.status, - reportType: doc.reportType, - dateUpdated: Date.now(), - syncStatus: false, - }); + const shiftObj = Shift.create({ + _id: doc._id, + beginning_cash: doc.beginning_cash, + ending_cash: doc.ending_cash, + shift_beginning: doc.shift_beginning, + shift_end: doc.shift_end, + attendant: doc.attendant, + short: doc.short, + commissions: doc.commissions ? doc.commissions : 0, + actual_money: doc.actual_money, + numberOfTransaction: doc.numberOfTransaction, + total_sales: doc.total_sales, + total_discounts: doc.total_discounts, + total_taxes: doc.total_taxes, + status: doc.status, + reportType: doc.reportType, + dateUpdated: Date.now(), + syncStatus: false, + }); - Object.keys(doc.pays).map(key => { - shiftObj.addPay(doc.pays[key]); - }); - self.setShift(shiftObj); - } - if (entries.rows[i].doc.reportType === "ZReading") { - const zReadingObj = Shift.create({ - _id: entries.rows[i].doc._id, - beginning_cash: entries.rows[i].doc.beginning_cash, - ending_cash: entries.rows[i].doc.ending_cash, - shift_beginning: entries.rows[i].doc.shift_beginning, - shift_end: entries.rows[i].doc.shift_end, - attendant: entries.rows[i].doc.attendant, - short: entries.rows[i].doc.short, - actual_money: entries.rows[i].doc.actual_money, - commissions: entries.rows[i].doc.commissions - ? entries.rows[i].doc.commissions - : 0, - numberOfTransaction: entries.rows[i].doc.numberOfTransaction, - total_sales: entries.rows[i].doc.total_sales, - total_discounts: entries.rows[i].doc.total_discounts, - total_taxes: entries.rows[i].doc.total_taxes, - status: entries.rows[i].doc.status, - reportType: entries.rows[i].doc.reportType, - dateUpdated: Date.now(), - syncStatus: false, - }); - Object.keys(entries.rows[i].doc.pays).map(key => { - zReadingObj.addPay(entries.rows[i].doc.pays[key]); - }); - self.setZReadingFromDb(zReadingObj); - } - } - if (!check) { - self.newShift(); - // self.zReading = self.defaultShift - } - } else { - self.newShift(); - - // self.zReading = self.defaultShift - } - }); + Object.keys(doc.pays).map(key => { + shiftObj.addPay(doc.pays[key]); + }); + self.setShift(shiftObj); + } + if (entries.rows[i].doc.reportType === "ZReading") { + const zReadingObj = Shift.create({ + _id: entries.rows[i].doc._id, + beginning_cash: entries.rows[i].doc.beginning_cash, + ending_cash: entries.rows[i].doc.ending_cash, + shift_beginning: entries.rows[i].doc.shift_beginning, + shift_end: entries.rows[i].doc.shift_end, + attendant: entries.rows[i].doc.attendant, + short: entries.rows[i].doc.short, + actual_money: entries.rows[i].doc.actual_money, + commissions: entries.rows[i].doc.commissions + ? entries.rows[i].doc.commissions + : 0, + numberOfTransaction: entries.rows[i].doc.numberOfTransaction, + total_sales: entries.rows[i].doc.total_sales, + total_discounts: entries.rows[i].doc.total_discounts, + total_taxes: entries.rows[i].doc.total_taxes, + status: entries.rows[i].doc.status, + reportType: entries.rows[i].doc.reportType, + dateUpdated: Date.now(), + syncStatus: false, + }); + Object.keys(entries.rows[i].doc.pays).map(key => { + zReadingObj.addPay(entries.rows[i].doc.pays[key]); + }); + self.setZReadingFromDb(zReadingObj); + } + } + if (!check) { + self.newShift(); + // self.zReading = self.defaultShift + } + } else { + self.newShift(); - // db.allDocs().then(function (result){ - // return Promise.all(result.rows.map(function (row){ - // return db.remove(row.id,row.value.rev) - // })) - // }) - }, - async find(key) { - return await db.get(key).then(report => { - const reportObject = Shift.create({ - _id: report._id, - beginning_cash: report.beginning_cash, - ending_cash: report.ending_cash, - shift_beginning: report.shift_beginning, - shift_end: report.shift_end, - total_sales: report.total_sales, - actual_money: report.actual_money, - numberOfTransaction: report.numberOfTransaction, - total_discounts: report.total_discounts, - total_taxes: report.total_taxes, - attendant: report.attendant, - status: report.status, + // self.zReading = self.defaultShift + } + }); - commissions: report.commissions, - reportType: report.reportType, - dateUpdated: report.dateUpdated, - syncStatus: report.syncStatus, - }); - Object.keys(report.pays).map(index => { - reportObject.addPay(report.pays[index]); - }); - return Promise.resolve(reportObject); - }); - }, - })); + // db.allDocs().then(function (result){ + // return Promise.all(result.rows.map(function (row){ + // return db.remove(row.id,row.value.rev) + // })) + // }) + }, + async find(key) { + return await db.get(key).then(report => { + const reportObject = Shift.create({ + _id: report._id, + beginning_cash: report.beginning_cash, + ending_cash: report.ending_cash, + shift_beginning: report.shift_beginning, + shift_end: report.shift_end, + total_sales: report.total_sales, + actual_money: report.actual_money, + numberOfTransaction: report.numberOfTransaction, + total_discounts: report.total_discounts, + total_taxes: report.total_taxes, + attendant: report.attendant, + status: report.status, + commissions: report.commissions, + reportType: report.reportType, + dateUpdated: report.dateUpdated, + syncStatus: report.syncStatus, + }); + Object.keys(report.pays).map(index => { + reportObject.addPay(report.pays[index]); + }); + return Promise.resolve(reportObject); + }); + }, + })); const shiftStore = ShiftStore.create({}); diff --git a/src/stories/components/AttendantsFormComponent.js b/src/stories/components/AttendantsFormComponent.js index d2755d5..3585804 100644 --- a/src/stories/components/AttendantsFormComponent.js +++ b/src/stories/components/AttendantsFormComponent.js @@ -5,273 +5,273 @@ import * as React from "react"; import { Dimensions, View } from "react-native"; import { - Text, - Input, - Button, - Item, - Picker, - Grid, - Col, - CheckBox, + Text, + Input, + Button, + Item, + Picker, + Grid, + Col, + CheckBox, } from "native-base"; import Icon from "react-native-vector-icons/MaterialCommunityIcons"; class AddAttendantComponent extends React.Component { - constructor(props) { - super(props); - this.state = { - id: "", - attendantName: "", - pin: "", - confirmPin: "", - securityPinStatus: true, - securityConfirmPinStatus: true, - status: "Save Attendant", - role: "Owner", - canLogin: false, - commission: "", - }; + constructor(props) { + super(props); + this.state = { + id: "", + attendantName: "", + pin: "", + confirmPin: "", + securityPinStatus: true, + securityConfirmPinStatus: true, + status: "Save Attendant", + role: "Owner", + canLogin: false, + commission: "", + }; + } + componentWillReceiveProps(nextProps) { + const { attendantInfo } = nextProps; + if (attendantInfo._id) { + this.setState({ status: "Edit Attendant" }); } - componentWillReceiveProps(nextProps) { - const { attendantInfo } = nextProps; - if (attendantInfo._id) { - this.setState({ status: "Edit Attendant" }); - } - if (attendantInfo.user_name || attendantInfo.attendantName) { - this.setState({ - id: attendantInfo._id - ? attendantInfo._id - : attendantInfo.id - ? attendantInfo.id - : "", - attendantName: attendantInfo.user_name - ? attendantInfo.user_name - : attendantInfo.attendantName - ? attendantInfo.attendantName - : "", - role: attendantInfo.role - ? attendantInfo.role - : attendantInfo.role - ? attendantInfo.role - : "Cashier", - pin: attendantInfo.pin_code - ? attendantInfo.pin_code - : attendantInfo.pin - ? attendantInfo.pin - : "", - confirmPin: attendantInfo.pin_code - ? attendantInfo.pin_code - : attendantInfo.confirmPin - ? attendantInfo.confirmPin - : "", - securityPinStatus: true, - securityConfirmPinStatus: true, - canLogin: attendantInfo.canLogin, - commission: attendantInfo.commission.toString(), - }); - } else { - this.setState({ - id: "", - attendantName: "", - pin: "", - confirmPin: "", - securityPinStatus: true, - securityConfirmPinStatus: true, - status: "Save Attendant", - role: "Owner", - canLogin: false, - commission: "", - }); - } + if (attendantInfo.user_name || attendantInfo.attendantName) { + this.setState({ + id: attendantInfo._id + ? attendantInfo._id + : attendantInfo.id + ? attendantInfo.id + : "", + attendantName: attendantInfo.user_name + ? attendantInfo.user_name + : attendantInfo.attendantName + ? attendantInfo.attendantName + : "", + role: attendantInfo.role + ? attendantInfo.role + : attendantInfo.role + ? attendantInfo.role + : "Cashier", + pin: attendantInfo.pin_code + ? attendantInfo.pin_code + : attendantInfo.pin + ? attendantInfo.pin + : "", + confirmPin: attendantInfo.pin_code + ? attendantInfo.pin_code + : attendantInfo.confirmPin + ? attendantInfo.confirmPin + : "", + securityPinStatus: true, + securityConfirmPinStatus: true, + canLogin: attendantInfo.canLogin, + commission: attendantInfo.commission.toString(), + }); + } else { + this.setState({ + id: "", + attendantName: "", + pin: "", + confirmPin: "", + securityPinStatus: true, + securityConfirmPinStatus: true, + status: "Save Attendant", + role: "Owner", + canLogin: false, + commission: "", + }); } - render() { - const rolesData = this.props.rolesData.map(roles => ( - - )); - return ( - ( + + )); + return ( + + + this.setState({ attendantName: text })} + placeholder="Attendant Name" + /> + + {/**/} + {/* this.setState({ attendantName: text })}*/} + {/*/>*/} + this.setState({ role: value })} + > + {rolesData} + + {this.state.role !== "Owner" ? ( + + this.setState({ commission: text })} + placeholder="Commission" + /> + + + ) : null} + + + - - this.setState({ attendantName: text })} - placeholder="Attendant Name" - /> - - {/**/} - {/* this.setState({ attendantName: text })}*/} - {/*/>*/} - this.setState({ role: value })} - > - {rolesData} - - {this.state.role !== "Owner" ? ( - - this.setState({ commission: text })} - placeholder="Commission" - /> - - - ) : null} - - - - - this.setState({ - canLogin: !this.state.canLogin, - }) - } - color="gray" - /> - + + this.setState({ + canLogin: !this.state.canLogin, + }) + } + color="gray" + /> + - - Can login - - - + + Can login + + + - {/**/} - {this.state.canLogin ? ( - - this.setState({ pin: text })} - placeholder="Pin" - secureTextEntry={this.state.securityPinStatus} - /> - - this.setState({ - securityPinStatus: !this.state.securityPinStatus, - }) - } - /> - - ) : null} - {this.state.canLogin ? ( - - this.setState({ confirmPin: text })} - placeholder="Confirm Pin" - secureTextEntry={this.state.securityConfirmPinStatus} - /> - - this.setState({ - securityConfirmPinStatus: !this.state - .securityConfirmPinStatus, - }) - } - /> - - ) : null} + {/**/} + {this.state.canLogin ? ( + + this.setState({ pin: text })} + placeholder="Pin" + secureTextEntry={this.state.securityPinStatus} + /> + + this.setState({ + securityPinStatus: !this.state.securityPinStatus, + }) + } + /> + + ) : null} + {this.state.canLogin ? ( + + this.setState({ confirmPin: text })} + placeholder="Confirm Pin" + secureTextEntry={this.state.securityConfirmPinStatus} + /> + + this.setState({ + securityConfirmPinStatus: !this.state + .securityConfirmPinStatus, + }) + } + /> + + ) : null} - + - - - ); - } + {this.state.status} + + ) : this.state.status === "Edit Attendant" ? ( + + {this.state.status} + + ) : null} + + + + ); + } } export default AddAttendantComponent; diff --git a/src/stories/components/CardShiftEndComponent.js b/src/stories/components/CardShiftEndComponent.js index 35b7f3a..a7c6610 100644 --- a/src/stories/components/CardShiftEndComponent.js +++ b/src/stories/components/CardShiftEndComponent.js @@ -6,189 +6,199 @@ import Icon from "react-native-vector-icons/MaterialCommunityIcons"; let MoneyCurrency = require("money-currencies"); export default class CardShiftEndComponent extends React.Component { - constructor(props) { - super(props); - this.state = { - pay: "", - reason: "", - visibility: false, - actualMoney: "", - }; - } + constructor(props) { + super(props); + this.state = { + pay: "", + reason: "", + visibility: false, + actualMoney: "", + }; + } - render() { - let mc = new MoneyCurrency( - this.props.currency ? this.props.currency : "PHP", - ); + render() { + let mc = new MoneyCurrency( + this.props.currency ? this.props.currency : "PHP", + ); - const disabled = this.props.pay === "" ? true : false; + const disabled = this.props.pay === "" ? true : false; - const disabledStyle = { - flex: 1, - borderRadius: 0, - backgroundColor: "lightgray", - }; + const disabledStyle = { + flex: 1, + borderRadius: 0, + backgroundColor: "lightgray", + }; - // Pay-In - const payInStyle = disabled - ? disabledStyle - : { - flex: 1, - borderTopRightRadius: 0, - borderBottomRightRadius: 0, - backgroundColor: "green", - }; + // Pay-In + const payInStyle = disabled + ? disabledStyle + : { + flex: 1, + borderTopRightRadius: 0, + borderBottomRightRadius: 0, + backgroundColor: "green", + }; - // Pay-Out - const payOutStyle = disabled - ? disabledStyle - : { - flex: 1, - borderTopLeftRadius: 0, - borderBottomLeftRadius: 0, - backgroundColor: "firebrick", - }; + // Pay-Out + const payOutStyle = disabled + ? disabledStyle + : { + flex: 1, + borderTopLeftRadius: 0, + borderBottomLeftRadius: 0, + backgroundColor: "firebrick", + }; - return ( + return ( + + + this.setState({ actualMoney: this.state.actualMoney.slice(0, -1) }) + } + onPressClose={() => this.props.shiftClick(this.state.actualMoney)} + onFocusValue={() => this.setState({ actualMoney: "" })} + actualMoney={this.state.actualMoney} + modalBreakDownVisible={this.state.visibility} + onChangeActualMoney={money => + this.setState({ actualMoney: this.state.actualMoney + money }) + } + onChangeVisibility={() => this.setState({ visibility: false })} + /> + + + Shift details{" "} + + (The cash you wanted to put into the register or get out from the + register.) + + +
- - this.setState({ actualMoney: this.state.actualMoney.slice(0, -1) }) - } - onPressClose={() => this.props.shiftClick(this.state.actualMoney)} - onFocusValue={() => this.setState({ actualMoney: "" })} - actualMoney={this.state.actualMoney} - modalBreakDownVisible={this.state.visibility} - onChangeActualMoney={money => - this.setState({ actualMoney: this.state.actualMoney + money }) - } - onChangeVisibility={() => this.setState({ visibility: false })} + + this.setState({ pay: text })} /> - - Shift details - (The cash you wanted to put into the register or get out from the - register.) - - - - - this.setState({ pay: text })} - /> - - - this.setState({ reason: text })} - /> - - - - - - - - - - - Shift started - - {this.props.shiftBeginning.toLocaleTimeString("en-US")} - - - - Beginning Cash - {mc.moneyFormat(this.props.cashBeginning)} - - - Ending Cash - {mc.moneyFormat(this.props.cashEnd)} - - - - + + + this.setState({ reason: text })} + /> + +
+ + + + + + + + Shift started + + {this.props.shiftBeginning.toLocaleTimeString("en-US")} + + + + Beginning Cash + {mc.moneyFormat(this.props.cashBeginning)} + + + Ending Cash + {mc.moneyFormat(this.props.cashEnd)} - ); - } + + +
+
+ ); + } } diff --git a/src/stories/components/EntryComponent.js b/src/stories/components/EntryComponent.js index 4403a50..d8cfb8f 100644 --- a/src/stories/components/EntryComponent.js +++ b/src/stories/components/EntryComponent.js @@ -5,103 +5,101 @@ import { formatNumber } from "accounting-js"; let MoneyCurrency = require("money-currencies"); export default class EntryComponent extends React.Component { - constructor(props) { - super(props); - const { width, height } = Dimensions.get("window"); - this.state = { width, height }; - } + constructor(props) { + super(props); + const { width, height } = Dimensions.get("window"); + this.state = { width, height }; + } - // TODO: layout for responsive - onLayout() {} + // TODO: layout for responsive + onLayout() {} - withPrice() { - if (this.props.value.price) { - let mc = new MoneyCurrency( - this.props.currency ? this.props.currency : "PHP", - ); + withPrice() { + if (this.props.value.price) { + let mc = new MoneyCurrency( + this.props.currency ? this.props.currency : "PHP", + ); - return ( - - - {mc.moneyFormat(formatNumber(this.props.value.price))} - - - ); - } else { - return ; - } + return ( + + + {mc.moneyFormat(formatNumber(this.props.value.price))} + + + ); + } else { + return ; } + } - render() { - return ( - - this.props.onPress(this.props.value)} - onLongPress={() => this.props.onLongPress(this.props.value)} - > - - {this.props.value.colorAndShape ? ( - - ) : ( - - )} - - + this.props.onPress(this.props.value)} + onLongPress={() => this.props.onLongPress(this.props.value)} + > + + {this.props.value.colorAndShape ? ( + + ) : ( + + )} - style={{ - alignItems: "center", - justifyContent: "center", - width: Dimensions.get("window").width * 0.08, - height: Dimensions.get("window").height * 0.08, - }} - > - - - {this.props.value.name} - - - - - {this.withPrice()} + + + {this.props.value.name} + - ); - } + + + {this.withPrice()} + + ); + } } diff --git a/src/stories/components/QuantityModalComponent.js b/src/stories/components/QuantityModalComponent.js index 946ce26..fde738c 100644 --- a/src/stories/components/QuantityModalComponent.js +++ b/src/stories/components/QuantityModalComponent.js @@ -7,352 +7,368 @@ import Icon from "react-native-vector-icons/MaterialCommunityIcons"; import ModalKeypadComponent from "./ModalKeypadComponent"; export default class QuantityModalComponent extends React.Component { - constructor(props) { - super(props); - this.state = { - quantity: "", - status: "Qty", - price: "", - discount: "", - commission: "", - commission_amount: "", - defaultQty: "", - defaultPrice: "", - attendantName: "No Attendant" - }; - } + constructor(props) { + super(props); + this.state = { + quantity: "", + status: "Qty", + price: "", + discount: "", + commission: "", + commission_amount: "", + defaultQty: "", + defaultPrice: "", + attendantName: "No Attendant", + }; + } - componentWillReceiveProps(nextProps) { - const { quantity } = nextProps; - const { price } = nextProps; - const { commission_rate } = nextProps; - const { commission_name } = nextProps; - const { commission_amount } = nextProps; - const { discount_rate } = nextProps; - this.setState({ - quantity: quantity.toString(), - price: price.toString(), - defaultQty: quantity.toString(), - defaultPrice: price.toString(), - attendantName: commission_name.toString(), - commission: commission_rate.toString(), - commission_amount: commission_amount.toString(), - discount: discount_rate.toString(), - }); - } + componentWillReceiveProps(nextProps) { + const { quantity } = nextProps; + const { price } = nextProps; + const { commission_rate } = nextProps; + const { commission_name } = nextProps; + const { commission_amount } = nextProps; + const { discount_rate } = nextProps; + this.setState({ + quantity: quantity.toString(), + price: price.toString(), + defaultQty: quantity.toString(), + defaultPrice: price.toString(), + attendantName: commission_name.toString(), + commission: commission_rate.toString(), + commission_amount: commission_amount.toString(), + discount: discount_rate.toString(), + }); + } - onChangeEditStatus(val) { - this.setState({ status: val }); - } + onChangeEditStatus(val) { + this.setState({ status: val }); + } - onChangeText(text) { - this.setState({ quantity: text }); - } + onChangeText(text) { + this.setState({ quantity: text }); + } - onNumberPress(text) { - if (this.state.quantity === "0") { - this.setState({ quantity: text }); - } else { - this.setState({ quantity: this.state.quantity.concat(text) }); - } - } - onNumberDiscountPress(text) { - if (this.state.price === "0") { - this.setState({ discount: text }); - } else { - this.setState({ discount: this.state.discount.concat(text) }); - } - } - onNumberPricePress(text) { - if (this.state.price === "0") { - this.setState({ price: text }); - } else { - this.setState({ price: this.state.price.concat(text) }); - } - } - onNumberCommissionPress(text) { - if (this.state.quantity === "0") { - this.setState({ commission: text }); - } else { - this.setState({ - commission: this.state.commission.concat(text), - commission_amount: ( - parseInt(this.state.commission.concat(text), 10) / - 100 * - (this.state.discount ? parseInt(this.state.discount,10) * (parseInt(this.state.price, 10) * parseInt(this.state.quantity, 10)) : (parseInt(this.state.price, 10) * parseInt(this.state.quantity, 10)) ) - ).toString(), - }); - } + onNumberPress(text) { + if (this.state.quantity === "0") { + this.setState({ quantity: text }); + } else { + this.setState({ quantity: this.state.quantity.concat(text) }); } - onDeletePress() { - this.setState({ quantity: this.state.quantity.slice(0, -1) }); + } + onNumberDiscountPress(text) { + if (this.state.price === "0") { + this.setState({ discount: text }); + } else { + this.setState({ discount: this.state.discount.concat(text) }); } - onDeletePricePress() { - this.setState({ price: this.state.price.slice(0, -1) }); + } + onNumberPricePress(text) { + if (this.state.price === "0") { + this.setState({ price: text }); + } else { + this.setState({ price: this.state.price.concat(text) }); } - onDeleteCommissionPress() { - this.setState({ - commission: this.state.commission.slice(0, -1), - commission_amount: - this.state.commission.slice(0, -1) !== "" - ? ( - parseInt(this.state.commission.slice(0, -1), 10) / - 100 * - parseInt(this.state.price, 10) - ).toString() - : "", - }); + } + onNumberCommissionPress(text) { + if (this.state.quantity === "0") { + this.setState({ commission: text }); + } else { + this.setState({ + commission: this.state.commission.concat(text), + commission_amount: ( + parseInt(this.state.commission.concat(text), 10) / + 100 * + (this.state.discount + ? parseInt(this.state.discount, 10) * + (parseInt(this.state.price, 10) * + parseInt(this.state.quantity, 10)) + : parseInt(this.state.price, 10) * + parseInt(this.state.quantity, 10)) + ).toString(), + }); } - onDeleteDiscountPress() { - this.setState({ - discount: this.state.discount.slice(0, -1), - }); - } - computeCommission(value){ - let commissionValue = this.props.attendants.filter(attendant => attendant._id === value); + } + onDeletePress() { + this.setState({ quantity: this.state.quantity.slice(0, -1) }); + } + onDeletePricePress() { + this.setState({ price: this.state.price.slice(0, -1) }); + } + onDeleteCommissionPress() { + this.setState({ + commission: this.state.commission.slice(0, -1), + commission_amount: + this.state.commission.slice(0, -1) !== "" + ? ( + parseInt(this.state.commission.slice(0, -1), 10) / + 100 * + parseInt(this.state.price, 10) + ).toString() + : "", + }); + } + onDeleteDiscountPress() { + this.setState({ + discount: this.state.discount.slice(0, -1), + }); + } + computeCommission(value) { + let commissionValue = this.props.attendants.filter( + attendant => attendant._id === value, + ); - let priceQty = parseFloat(this.state.price,10) * parseFloat(this.state.quantity,10); - let discountValue = parseFloat(this.state.discount) > 0 ? (priceQty) - ((parseFloat(this.state.discount) / 100) * (priceQty)) : (priceQty); + let priceQty = + parseFloat(this.state.price, 10) * parseFloat(this.state.quantity, 10); + let discountValue = + parseFloat(this.state.discount) > 0 + ? priceQty - parseFloat(this.state.discount) / 100 * priceQty + : priceQty; - this.setState({ - attendantName: value, - commission_amount: ((parseFloat(commissionValue[0].commission, 10) / 100) * discountValue).toString() - }); - } - render() { - const attendants = this.props.attendants.map(attendant => ( - - )); + this.setState({ + attendantName: value, + commission_amount: ( + parseFloat(commissionValue[0].commission, 10) / + 100 * + discountValue + ).toString(), + }); + } + render() { + const attendants = this.props.attendants.map(attendant => ( + + )); - return ( - null} - animationType="slide" - transparent={true} - visible={this.props.visible} + return ( + null} + animationType="slide" + transparent={true} + visible={this.props.visible} + > + + + - + Edit Transaction Line + + this.props.onClick()} + > + + + + + + + + + - - - - Edit Transaction Line - - this.props.onClick()} - > - - - - - - - - - - - {this.state.status === "Qty" ? ( -
- - this.onChangeText(text)} - /> - -
- ) : this.state.status === "Price" ? ( -
- - this.onNumberCommissionPress(text)} - /> - -
- ) : this.state.status === "Discount" ? ( -
- - this.onNumberCommissionPress(text)} - /> - - - -
- ) : this.state.status === "Commission" ? ( -
- { - this.computeCommission(value); - } - } - > - - {attendants} - - - this.onChangePrice(text)} - /> - -
- ) : null} - {this.state.status !== "Commission" ? ( - - - this.state.status === "Qty" - ? this.onNumberPress(text) - : this.state.status === "Price" - ? this.onNumberPricePress(text) - : this.state.status === "Commission" - ? this.onNumberCommissionPress(text) - : this.state.status === "Discount" ? this.onNumberDiscountPress(text) : "" - } - onDeletePress={() => - this.state.status === "Qty" - ? this.onDeletePress() - : this.state.status === "Price" - ? this.onDeletePricePress() - : this.state.status === "Commission" - ? this.onDeleteCommissionPress() - : this.state.status === "Discount" ? this.onDeleteDiscountPress() : "" - } - /> - - - ) : null} + {this.state.status === "Qty" ? ( +
+ + this.onChangeText(text)} + /> + +
+ ) : this.state.status === "Price" ? ( +
+ + this.onNumberCommissionPress(text)} + /> + +
+ ) : this.state.status === "Discount" ? ( +
+ + this.onNumberCommissionPress(text)} + /> - - + + +
+ ) : this.state.status === "Commission" ? ( +
+ { + this.computeCommission(value); + }} + > + + {attendants} + + + this.onChangePrice(text)} + /> + +
+ ) : null} + {this.state.status !== "Commission" ? ( + + + this.state.status === "Qty" + ? this.onNumberPress(text) + : this.state.status === "Price" + ? this.onNumberPricePress(text) + : this.state.status === "Commission" + ? this.onNumberCommissionPress(text) + : this.state.status === "Discount" + ? this.onNumberDiscountPress(text) + : "" + } + onDeletePress={() => + this.state.status === "Qty" + ? this.onDeletePress() + : this.state.status === "Price" + ? this.onDeletePricePress() + : this.state.status === "Commission" + ? this.onDeleteCommissionPress() + : this.state.status === "Discount" + ? this.onDeleteDiscountPress() + : "" + } + /> -
- ); - } + ) : null} + + +
+ + + ); + } } diff --git a/src/stories/components/ReceiptLinesComponent.js b/src/stories/components/ReceiptLinesComponent.js index 507dc35..295bfea 100644 --- a/src/stories/components/ReceiptLinesComponent.js +++ b/src/stories/components/ReceiptLinesComponent.js @@ -7,122 +7,122 @@ import { formatNumber } from "accounting-js"; let MoneyCurrency = require("money-currencies"); export default class ReceiptLinesComponent extends React.Component { - closeRow(rowMap, id) { - rowMap[id].closeRow(); - } + closeRow(rowMap, id) { + rowMap[id].closeRow(); + } - _renderItem = (data, rowMap) => { - let mc = new MoneyCurrency( - this.props.currency ? this.props.currency : "PHP", - ); + _renderItem = (data, rowMap) => { + let mc = new MoneyCurrency( + this.props.currency ? this.props.currency : "PHP", + ); - const { item } = data; - return ( - - {item.item_name} - {formatNumber(item.qty)} - - {mc.moneyFormat(formatNumber(item.total.toFixed(2)))} {item.discount_rate ? "(" + item.discount_rate + ")" : null} + const { item } = data; + return ( + + {item.item_name} + {formatNumber(item.qty)} + + {mc.moneyFormat(formatNumber(item.total.toFixed(2)))}{" "} + {item.discount_rate ? "(" + item.discount_rate + ")" : null} + + + ); + }; - - - ); - }; + _renderHiddenItem = (data, rowMap) => { + const { item, index } = data; + return ( + + + + + ); + }; - _renderHiddenItem = (data, rowMap) => { - const { item, index } = data; - return ( - - - - - ); - }; - - render() { - return ( - item._id} - renderItem={this._renderItem} - renderHiddenItem={this._renderHiddenItem} - leftOpenValue={75} - rightOpenValue={-75} - style={{ marginBottom: 10 }} - /> - ); - } + render() { + return ( + item._id} + renderItem={this._renderItem} + renderHiddenItem={this._renderHiddenItem} + leftOpenValue={75} + rightOpenValue={-75} + style={{ marginBottom: 10 }} + /> + ); + } } const styles = StyleSheet.create({ - rowFront: { - backgroundColor: "white", - borderBottomColor: "#eee", - borderBottomWidth: 1, - height: 50, - flexDirection: "row", - alignItems: "center", - paddingLeft: 30, - paddingRight: 30, - }, - rowNoFront: { - backgroundColor: "white", - borderBottomColor: "#eee", - borderBottomWidth: 1, - height: 0, - flexDirection: "row", - alignItems: "center", - paddingLeft: 30, - paddingRight: 30, - }, - rowFrontName: { - flex: 3, - fontWeight: "bold", - }, + rowFront: { + backgroundColor: "white", + borderBottomColor: "#eee", + borderBottomWidth: 1, + height: 50, + flexDirection: "row", + alignItems: "center", + paddingLeft: 30, + paddingRight: 30, + }, + rowNoFront: { + backgroundColor: "white", + borderBottomColor: "#eee", + borderBottomWidth: 1, + height: 0, + flexDirection: "row", + alignItems: "center", + paddingLeft: 30, + paddingRight: 30, + }, + rowFrontName: { + flex: 3, + fontWeight: "bold", + }, - rowFrontQuantity: { - flex: 1, - textAlign: "right", - }, + rowFrontQuantity: { + flex: 1, + textAlign: "right", + }, - rowFrontTotal: { - flex: 2, - textAlign: "right", - }, + rowFrontTotal: { + flex: 2, + textAlign: "right", + }, - rowBack: { - flex: 1, - flexDirection: "row", - justifyContent: "space-between", - }, + rowBack: { + flex: 1, + flexDirection: "row", + justifyContent: "space-between", + }, - rowBackEdit: { - width: 75, - height: 50, - }, + rowBackEdit: { + width: 75, + height: 50, + }, - rowBackDelete: { - width: 75, - height: 50, - }, + rowBackDelete: { + width: 75, + height: 50, + }, }); diff --git a/src/stories/components/SearchableDropdownComponent.js b/src/stories/components/SearchableDropdownComponent.js index d31b069..f0bde7a 100644 --- a/src/stories/components/SearchableDropdownComponent.js +++ b/src/stories/components/SearchableDropdownComponent.js @@ -4,71 +4,71 @@ import SearchableDropdown from "react-native-searchable-dropdown"; import { Col, Grid } from "react-native-easy-grid"; export default class SearchableDropdownComponent extends React.Component { - constructor(props) { - super(props); - this.state = { - barcodeState: false, - }; - } + constructor(props) { + super(props); + this.state = { + barcodeState: false, + }; + } - render() { - return ( - - - { - if (text){ - this.props.searchCustomer(text); - } - } } - onItemSelect={item => item} - // containerStyle={{ - // padding: 5 - // }} - textInputStyle={{ - fontSize: 18, - padding: 12, - borderWidth: 2, - borderColor: "#DCDCDC", - }} - itemStyle={{ - padding: 10, - marginTop: 2, - backgroundColor: "#ddd", - borderColor: "#bbb", - borderWidth: 1, - borderRadius: 5, - }} - itemTextStyle={{ - color: "#222", - }} - itemsContainerStyle={{ - maxHeight: 140, - }} - defaultIndex={0} - items={this.props.searchedCustomers} - placeholder="Customer" - resetValue={false} - underlineColorAndroid="transparent" - enableEmptySections - editable={false} - /> - - - - - - ); - } + render() { + return ( + + + { + if (text) { + this.props.searchCustomer(text); + } + }} + onItemSelect={item => item} + // containerStyle={{ + // padding: 5 + // }} + textInputStyle={{ + fontSize: 18, + padding: 12, + borderWidth: 2, + borderColor: "#DCDCDC", + }} + itemStyle={{ + padding: 10, + marginTop: 2, + backgroundColor: "#ddd", + borderColor: "#bbb", + borderWidth: 1, + borderRadius: 5, + }} + itemTextStyle={{ + color: "#222", + }} + itemsContainerStyle={{ + maxHeight: 140, + }} + defaultIndex={0} + items={this.props.searchedCustomers} + placeholder="Customer" + resetValue={false} + underlineColorAndroid="transparent" + enableEmptySections + editable={false} + /> + + + + + + ); + } }