Best JavaScript code snippet using mountebank
scripts.js
Source:scripts.js  
1// File that creates the purchase details search table2purchaseDetailsSearchTableCreatorFile = 'model/purchase/purchaseDetailsSearchTableCreator.php';3// File that creates the customer details search table4customerDetailsSearchTableCreatorFile = 'model/customer/customerDetailsSearchTableCreator.php';5// File that creates the item details search table6itemDetailsSearchTableCreatorFile = 'model/item/itemDetailsSearchTableCreator.php';7// File that creates the vendor details search table8vendorDetailsSearchTableCreatorFile = 'model/vendor/vendorDetailsSearchTableCreator.php';9// File that creates the sale details search table10saleDetailsSearchTableCreatorFile = 'model/sale/saleDetailsSearchTableCreator.php';11// File that creates the purchase reports search table12purchaseReportsSearchTableCreatorFile = 'model/purchase/purchaseReportsSearchTableCreator.php';13// File that creates the customer reports search table14customerReportsSearchTableCreatorFile = 'model/customer/customerReportsSearchTableCreator.php';15// File that creates the item reports search table16itemReportsSearchTableCreatorFile = 'model/item/itemReportsSearchTableCreator.php';17// File that creates the vendor reports search table18vendorReportsSearchTableCreatorFile = 'model/vendor/vendorReportsSearchTableCreator.php';19// File that creates the sale reports search table20saleReportsSearchTableCreatorFile = 'model/sale/saleReportsSearchTableCreator.php';21// File that returns the last inserted vendorID22vendorLastInsertedIDFile = 'model/vendor/populateLastVendorID.php';23// File that returns the last inserted customerID24customerLastInsertedIDFile = 'model/customer/populateLastCustomerID.php';25// File that returns the last inserted purchaseID26purchaseLastInsertedIDFile = 'model/purchase/populateLastPurchaseIDForPurchaseTab.php';27// File that returns the last inserted saleID28saleLastInsertedIDFile = 'model/sale/populateLastSaleIDForSaleTab.php';29// File that returns the last inserted productID for item details tab30itemLastInsertedIDFile = 'model/item/populateLastProductID.php';31// File that returns purchaseIDs32showPurchaseIDSuggestionsFile = 'model/purchase/showPurchaseIDs.php';33// File that returns saleIDs34showSaleIDSuggestionsFile = 'model/sale/showSaleIDs.php';35// File that returns vendorIDs36showVendorIDSuggestionsFile = 'model/vendor/showVendorIDs.php';37// File that returns customerIDs38showCustomerIDSuggestionsFile = 'model/customer/showCustomerIDs.php';39// File that returns customerIDs for sale tab40showCustomerIDSuggestionsForSaleTabFile = 'model/customer/showCustomerIDsForSaleTab.php';41// File that returns itemNumbers42showItemNumberSuggestionsFile = 'model/item/showItemNumber.php';43// File that returns itemNumbers in image tab44showItemNumberSuggestionsForImageTabFile = 'model/item/showItemNumberForImageTab.php';45// File that returns itemNumbers for purchase tab46showItemNumberForPurchaseTabFile = 'model/item/showItemNumberForPurchaseTab.php';47// File that returns itemNumbers for sale tab48showItemNumberForSaleTabFile = 'model/item/showItemNumberForSaleTab.php';49// File that returns itemNames50showItemNamesFile = 'model/item/showItemNames.php';51// File that returns stock 52getItemStockFile = 'model/item/getItemStock.php';53// File that returns item name54getItemNameFile = 'model/item/getItemName.php';55// File that updates an image56updateImageFile = 'model/image/updateImage.php';57// File that deletes an image58deleteImageFile = 'model/image/deleteImage.php';59// File that creates the filtered purchase report table60purchaseFilteredReportCreatorFile = 'model/purchase/purchaseFilteredReportTableCreator.php';61// File that creates the filtered sale report table62saleFilteredReportCreatorFile = 'model/sale/saleFilteredReportTableCreator.php';63$(document).ready(function(){64	// Style the dropdown boxes. You need to explicitly set the width 65    // in order to fix the dropdown box not visible issue when tab is hidden66	$('.chosenSelect').chosen({ width: "95%"});67	68	// Initiate tooltips69	$('.invTooltip').tooltip(); 70	71	// Listen to customer add button72	$('#addCustomer').on('click', function(){73		addCustomer();74	});75	76	// Listen to vendor add button77	$('#addVendor').on('click', function(){78		addVendor();79	});80	81	// Listen to item add button82	$('#addItem').on('click', function(){83		addItem();84	});85	86	// Listen to purchase add button87	$('#addPurchase').on('click', function(){88		addPurchase();89	});90	91	// Listen to sale add button92	$('#addSaleButton').on('click', function(){93		addSale();94	});95	96	// Listen to update button in item details tab97	$('#updateItemDetailsButton').on('click', function(){98		updateItem();99	});100	101	// Listen to update button in customer details tab102	$('#updateCustomerDetailsButton').on('click', function(){103		updateCustomer();104	});105	106	// Listen to update button in vendor details tab107	$('#updateVendorDetailsButton').on('click', function(){108		updateVendor();109	});110	111	// Listen to update button in purchase details tab112	$('#updatePurchaseDetailsButton').on('click', function(){113		updatePurchase();114	});115	116	// Listen to update button in sale details tab117	$('#updateSaleDetailsButton').on('click', function(){118		updateSale();119	});120	121	// Listen to delete button in item details tab122	$('#deleteItem').on('click', function(){123		// Confirm before deleting124		bootbox.confirm('Are you sure you want to delete?', function(result){125			if(result){126				deleteItem();127			}128		});129	});130	131	// Listen to delete button in customer details tab132	$('#deleteCustomerButton').on('click', function(){133		// Confirm before deleting134		bootbox.confirm('Are you sure you want to delete?', function(result){135			if(result){136				deleteCustomer();137			}138		});139	});140	141	// Listen to delete button in vendor details tab142	$('#deleteVendorButton').on('click', function(){143		// Confirm before deleting144		bootbox.confirm('Are you sure you want to delete?', function(result){145			if(result){146				deleteVendor();147			}148		});149	});150	151	// Listen to item name text box in item details tab152	$('#itemDetailsItemName').keyup(function(){153		showSuggestions('itemDetailsItemName', showItemNamesFile, 'itemDetailsItemNameSuggestionsDiv');154	});155	156	// Remove the item names suggestions dropdown in the item details tab157	// when user selects an item from it158	$(document).on('click', '#itemDetailsItemNamesSuggestionsList li', function(){159		$('#itemDetailsItemName').val($(this).text());160		$('#itemDetailsItemNamesSuggestionsList').fadeOut();161	});162	163	// Listen to item number text box in item details tab164	$('#itemDetailsItemNumber').keyup(function(){165		showSuggestions('itemDetailsItemNumber', showItemNumberSuggestionsFile, 'itemDetailsItemNumberSuggestionsDiv');166	});167	168	// Remove the item numbers suggestions dropdown in the item details tab169	// when user selects an item from it170	$(document).on('click', '#itemDetailsItemNumberSuggestionsList li', function(){171		$('#itemDetailsItemNumber').val($(this).text());172		$('#itemDetailsItemNumberSuggestionsList').fadeOut();173		getItemDetailsToPopulate();174	});175	176	// Listen to item number text box in sale details tab177	$('#saleDetailsItemNumber').keyup(function(){178		showSuggestions('saleDetailsItemNumber', showItemNumberForSaleTabFile, 'saleDetailsItemNumberSuggestionsDiv');179	});180	181	// Remove the item numbers suggestions dropdown in the sale details tab182	// when user selects an item from it183	$(document).on('click', '#saleDetailsItemNumberSuggestionsList li', function(){184		$('#saleDetailsItemNumber').val($(this).text());185		$('#saleDetailsItemNumberSuggestionsList').fadeOut();186		getItemDetailsToPopulateForSaleTab();187	});188	189	190	// Listen to item number text box in item image tab191	$('#itemImageItemNumber').keyup(function(){192		showSuggestions('itemImageItemNumber', showItemNumberSuggestionsForImageTabFile, 'itemImageItemNumberSuggestionsDiv');193	});194	195	// Remove the item numbers suggestions dropdown in the item image tab196	// when user selects an item from it197	$(document).on('click', '#itemImageItemNumberSuggestionsList li', function(){198		$('#itemImageItemNumber').val($(this).text());199		$('#itemImageItemNumberSuggestionsList').fadeOut();200		getItemName('itemImageItemNumber', getItemNameFile, 'itemImageItemName');201	});202	203	// Clear the image from item tab when Clear button is clicked204	$('#itemClear').on('click', function(){205		$('#imageContainer').empty();206	});207	208	// Clear the image from sale tab when Clear button is clicked209	$('#saleClear').on('click', function(){210		$('#saleDetailsImageContainer').empty();211	});212	213	// Refresh the purchase report datatable in the purchase report tab when Clear button is clicked214	$('#purchaseFilterClear').on('click', function(){215		reportsPurchaseTableCreator('purchaseReportsTableDiv', purchaseReportsSearchTableCreatorFile, 'purchaseReportsTable');216	});217	218	// Refresh the sale report datatable in the sale report tab when Clear button is clicked219	$('#saleFilterClear').on('click', function(){220		reportsSaleTableCreator('saleReportsTableDiv', saleReportsSearchTableCreatorFile, 'saleReportsTable');221	});222	223	224	// Listen to item number text box in purchase details tab225	$('#purchaseDetailsItemNumber').keyup(function(){226		showSuggestions('purchaseDetailsItemNumber', showItemNumberForPurchaseTabFile, 'purchaseDetailsItemNumberSuggestionsDiv');227	});228	229	// remove the item numbers suggestions dropdown in the purchase details tab230	// when user selects an item from it231	$(document).on('click', '#purchaseDetailsItemNumberSuggestionsList li', function(){232		$('#purchaseDetailsItemNumber').val($(this).text());233		$('#purchaseDetailsItemNumberSuggestionsList').fadeOut();234		235		// Display the item name for the selected item number236		getItemName('purchaseDetailsItemNumber', getItemNameFile, 'purchaseDetailsItemName');237		238		// Display the current stock for the selected item number239		getItemStockToPopulate('purchaseDetailsItemNumber', getItemStockFile, 'purchaseDetailsCurrentStock');240	});241	242	// Listen to CustomerID text box in customer details tab243	$('#customerDetailsCustomerID').keyup(function(){244		showSuggestions('customerDetailsCustomerID', showCustomerIDSuggestionsFile, 'customerDetailsCustomerIDSuggestionsDiv');245	});246	247	// Remove the CustomerID suggestions dropdown in the customer details tab248	// when user selects an item from it249	$(document).on('click', '#customerDetailsCustomerIDSuggestionsList li', function(){250		$('#customerDetailsCustomerID').val($(this).text());251		$('#customerDetailsCustomerIDSuggestionsList').fadeOut();252		getCustomerDetailsToPopulate();253	});254	255	// Listen to CustomerID text box in sale details tab256	$('#saleDetailsCustomerID').keyup(function(){257		showSuggestions('saleDetailsCustomerID', showCustomerIDSuggestionsForSaleTabFile, 'saleDetailsCustomerIDSuggestionsDiv');258	});259	260	// Remove the CustomerID suggestions dropdown in the sale details tab261	// when user selects an item from it262	$(document).on('click', '#saleDetailsCustomerIDSuggestionsList li', function(){263		$('#saleDetailsCustomerID').val($(this).text());264		$('#saleDetailsCustomerIDSuggestionsList').fadeOut();265		getCustomerDetailsToPopulateSaleTab();266	});267	268	269	// Listen to VendorID text box in vendor details tab270	$('#vendorDetailsVendorID').keyup(function(){271		showSuggestions('vendorDetailsVendorID', showVendorIDSuggestionsFile, 'vendorDetailsVendorIDSuggestionsDiv');272	});273	274	// Remove the VendorID suggestions dropdown in the vendor details tab275	// when user selects an item from it276	$(document).on('click', '#vendorDetailsVendorIDSuggestionsList li', function(){277		$('#vendorDetailsVendorID').val($(this).text());278		$('#vendorDetailsVendorIDSuggestionsList').fadeOut();279		getVendorDetailsToPopulate();280	});281	282	283	// Listen to PurchaseID text box in purchase details tab284	$('#purchaseDetailsPurchaseID').keyup(function(){285		showSuggestions('purchaseDetailsPurchaseID', showPurchaseIDSuggestionsFile, 'purchaseDetailsPurchaseIDSuggestionsDiv');286	});287	288	// Remove the PurchaseID suggestions dropdown in the customer details tab289	// when user selects an item from it290	$(document).on('click', '#purchaseDetailsPurchaseIDSuggestionsList li', function(){291		$('#purchaseDetailsPurchaseID').val($(this).text());292		$('#purchaseDetailsPurchaseIDSuggestionsList').fadeOut();293		getPurchaseDetailsToPopulate();294	});295	296	297	// Listen to saleID text box in sale details tab298	$('#saleDetailsSaleID').keyup(function(){299		showSuggestions('saleDetailsSaleID', showSaleIDSuggestionsFile, 'saleDetailsSaleIDSuggestionsDiv');300	});301	302	// Remove the SaleID suggestions dropdown in the sale details tab303	// when user selects an item from it304	$(document).on('click', '#saleDetailsSaleIDSuggestionsList li', function(){305		$('#saleDetailsSaleID').val($(this).text());306		$('#saleDetailsSaleIDSuggestionsList').fadeOut();307		getSaleDetailsToPopulate();308	});309	// Listen to image update button310	$('#updateImageButton').on('click', function(){311		processImage('imageForm', updateImageFile, 'itemImageMessage');312	});313	314	// Listen to image delete button315	$('#deleteImageButton').on('click', function(){316		processImage('imageForm', deleteImageFile, 'itemImageMessage');317	});318	319	// Initiate datepickers320	$('.datepicker').datepicker({321		format: 'yyyy-mm-dd',322		todayHighlight: true,323		todayBtn: 'linked',324		orientation: 'bottom left'325	});326	327	// Calculate Total in purchase tab328	$('#purchaseDetailsQuantity, #purchaseDetailsUnitPrice').change(function(){329		calculateTotalInPurchaseTab();330	});331	// Calculate Total in sale tab332	$('#saleDetailsDiscount, #saleDetailsQuantity, #saleDetailsUnitPrice').change(function(){333		calculateTotalInSaleTab();334	});335	336	// Close any suggestions lists from the page when a user clicks on the page337	$(document).on('click', function(){338		$('.suggestionsList').fadeOut();339	});340	// Load searchable datatables for customer, purchase, item, vendor, sale341	searchTableCreator('itemDetailsTableDiv', itemDetailsSearchTableCreatorFile, 'itemDetailsTable');342	searchTableCreator('purchaseDetailsTableDiv', purchaseDetailsSearchTableCreatorFile, 'purchaseDetailsTable');343	searchTableCreator('customerDetailsTableDiv', customerDetailsSearchTableCreatorFile, 'customerDetailsTable');344	searchTableCreator('saleDetailsTableDiv', saleDetailsSearchTableCreatorFile, 'saleDetailsTable');345	searchTableCreator('vendorDetailsTableDiv', vendorDetailsSearchTableCreatorFile, 'vendorDetailsTable');346	347	// Load searchable datatables for customer, purchase, item, vendor, sale reports348	reportsTableCreator('itemReportsTableDiv', itemReportsSearchTableCreatorFile, 'itemReportsTable');349	reportsPurchaseTableCreator('purchaseReportsTableDiv', purchaseReportsSearchTableCreatorFile, 'purchaseReportsTable');350	reportsTableCreator('customerReportsTableDiv', customerReportsSearchTableCreatorFile, 'customerReportsTable');351	reportsSaleTableCreator('saleReportsTableDiv', saleReportsSearchTableCreatorFile, 'saleReportsTable');352	reportsTableCreator('vendorReportsTableDiv', vendorReportsSearchTableCreatorFile, 'vendorReportsTable');353	354	// Initiate popovers355	$(document).on('mouseover', '.itemDetailsHover', function(){356		// Create item details popover boxes357		$('.itemDetailsHover').popover({358			container: 'body',359			title: 'Item Details',360			trigger: 'hover',361			html: true,362			placement: 'right',363			content: fetchData364		});365	});366	367	// Listen to refresh buttons368	$('#searchTablesRefresh, #reportsTablesRefresh').on('click', function(){369		searchTableCreator('itemDetailsTableDiv', itemDetailsSearchTableCreatorFile, 'itemDetailsTable');370		searchTableCreator('purchaseDetailsTableDiv', purchaseDetailsSearchTableCreatorFile, 'purchaseDetailsTable');371		searchTableCreator('customerDetailsTableDiv', customerDetailsSearchTableCreatorFile, 'customerDetailsTable');372		searchTableCreator('vendorDetailsTableDiv', vendorDetailsSearchTableCreatorFile, 'vendorDetailsTable');373		searchTableCreator('saleDetailsTableDiv', saleDetailsSearchTableCreatorFile, 'saleDetailsTable');374		375		reportsTableCreator('itemReportsTableDiv', itemReportsSearchTableCreatorFile, 'itemReportsTable');376		reportsPurchaseTableCreator('purchaseReportsTableDiv', purchaseReportsSearchTableCreatorFile, 'purchaseReportsTable');377		reportsTableCreator('customerReportsTableDiv', customerReportsSearchTableCreatorFile, 'customerReportsTable');378		reportsTableCreator('vendorReportsTableDiv', vendorReportsSearchTableCreatorFile, 'vendorReportsTable');379		reportsSaleTableCreator('saleReportsTableDiv', saleReportsSearchTableCreatorFile, 'saleReportsTable');380	});381	382	383	// Listen to purchase report show button384	$('#showPurchaseReport').on('click', function(){385		filteredPurchaseReportTableCreator('purchaseReportStartDate', 'purchaseReportEndDate', purchaseFilteredReportCreatorFile, 'purchaseReportsTableDiv', 'purchaseFilteredReportsTable');386	});387	388	// Listen to sale report show button389	$('#showSaleReport').on('click', function(){390		filteredSaleReportTableCreator('saleReportStartDate', 'saleReportEndDate', saleFilteredReportCreatorFile, 'saleReportsTableDiv', 'saleFilteredReportsTable');391	});392	393});394// Function to fetch data to show in popovers395function fetchData(){396	var fetch_data = '';397	var element = $(this);398	var id = element.attr('id');399	400	$.ajax({401		url: 'model/item/getItemDetailsForPopover.php',402		method: 'POST',403		async: false,404		data: {id:id},405		success: function(data){406			fetch_data = data;407		}408	});409	return fetch_data;410}411// Function to call the script that process imageURL in DB412function processImage(imageFormID, scriptPath, messageDivID){413	var form = $('#' + imageFormID)[0];414	var formData = new FormData(form);415	$.ajax({416		url: scriptPath,417		method: 'POST',418		data: formData,419		contentType: false,420		processData: false,421		success: function(data){422			$('#' + messageDivID).html(data);423		}424	});425}426// Function to create searchable datatables for customer, item, purchase, sale427function searchTableCreator(tableContainerDiv, tableCreatorFileUrl, table){428	var tableContainerDivID = '#' + tableContainerDiv;429	var tableID = '#' + table;430	$(tableContainerDivID).load(tableCreatorFileUrl, function(){431		// Initiate the Datatable plugin once the table is added to the DOM432		$(tableID).DataTable();433	});434}435// Function to create reports datatables for customer, item, purchase, sale436function reportsTableCreator(tableContainerDiv, tableCreatorFileUrl, table){437	var tableContainerDivID = '#' + tableContainerDiv;438	var tableID = '#' + table;439	$(tableContainerDivID).load(tableCreatorFileUrl, function(){440		// Initiate the Datatable plugin once the table is added to the DOM441		$(tableID).DataTable({442			dom: 'lBfrtip',443			//dom: 'lfBrtip',444			//dom: 'Bfrtip',445			buttons: [446				'copy',447				'csv', 'excel',448				{extend: 'pdf', orientation: 'landscape', pageSize: 'LEGAL'},449				'print'450			]451		});452	});453}454// Function to create reports datatables for purchase455function reportsPurchaseTableCreator(tableContainerDiv, tableCreatorFileUrl, table){456	var tableContainerDivID = '#' + tableContainerDiv;457	var tableID = '#' + table;458	$(tableContainerDivID).load(tableCreatorFileUrl, function(){459		// Initiate the Datatable plugin once the table is added to the DOM460		$(tableID).DataTable({461			dom: 'lBfrtip',462			buttons: [463				'copy',464				{extend: 'csv', footer: true, title: 'Purchase Report'},465				{extend: 'excel', footer: true, title: 'Purchase Report'},466				{extend: 'pdf', footer: true, orientation: 'landscape', pageSize: 'LEGAL', title: 'Purchase Report'},467				{extend: 'print', footer: true, title: 'Purchase Report'},468			],469			"footerCallback": function ( row, data, start, end, display ) {470				var api = this.api(), data;471	 472				// Remove the formatting to get integer data for summation473				var intVal = function ( i ) {474					return typeof i === 'string' ?475						i.replace(/[\$,]/g, '')*1 :476						typeof i === 'number' ?477							i : 0;478				};479	 480				// Quantity total over all pages481				quantityTotal = api482					.column( 6 )483					.data()484					.reduce( function (a, b) {485						return intVal(a) + intVal(b);486					}, 0 );487	 488				// Quantity for current page489				quantityFilteredTotal = api490					.column( 6, { page: 'current'} )491					.data()492					.reduce( function (a, b) {493						return intVal(a) + intVal(b);494					}, 0 );495				496				// Unit price total over all pages497				unitPriceTotal = api498					.column( 7 )499					.data()500					.reduce( function (a, b) {501						return intVal(a) + intVal(b);502					}, 0 );503				504				// Unit price for current page505				unitPriceFilteredTotal = api506					.column( 7, { page: 'current'} )507					.data()508					.reduce( function (a, b) {509						return intVal(a) + intVal(b);510					}, 0 );511					512				// Full price total over all pages513				fullPriceTotal = api514					.column( 8 )515					.data()516					.reduce( function (a, b) {517						return intVal(a) + intVal(b);518					}, 0 );519				520				// Full price for current page521				fullPriceFilteredTotal = api522					.column( 8, { page: 'current'} )523					.data()524					.reduce( function (a, b) {525						return intVal(a) + intVal(b);526					}, 0 );527	 528				// Update footer columns529				$( api.column( 6 ).footer() ).html(quantityFilteredTotal +' ('+ quantityTotal +' total)');530				$( api.column( 7 ).footer() ).html(unitPriceFilteredTotal +' ('+ unitPriceTotal +' total)');531				$( api.column( 8 ).footer() ).html(fullPriceFilteredTotal +' ('+ fullPriceTotal +' total)');532			}533		});534	});535}536// Function to create reports datatables for sale537function reportsSaleTableCreator(tableContainerDiv, tableCreatorFileUrl, table){538	var tableContainerDivID = '#' + tableContainerDiv;539	var tableID = '#' + table;540	$(tableContainerDivID).load(tableCreatorFileUrl, function(){541		// Initiate the Datatable plugin once the table is added to the DOM542		$(tableID).DataTable({543			dom: 'lBfrtip',544			buttons: [545				'copy',546				{extend: 'csv', footer: true, title: 'Sale Report'},547				{extend: 'excel', footer: true, title: 'Sale Report'},548				{extend: 'pdf', footer: true, orientation: 'landscape', pageSize: 'LEGAL', title: 'Sale Report'},549				{extend: 'print', footer: true, title: 'Sale Report'},550			],551			"footerCallback": function ( row, data, start, end, display ) {552				var api = this.api(), data;553	 554				// Remove the formatting to get integer data for summation555				var intVal = function ( i ) {556					return typeof i === 'string' ?557						i.replace(/[\$,]/g, '')*1 :558						typeof i === 'number' ?559							i : 0;560				};561	 562				// Quantity Total over all pages563				quantityTotal = api564					.column( 7 )565					.data()566					.reduce( function (a, b) {567						return intVal(a) + intVal(b);568					}, 0 );569	 570				// Quantity Total over this page571				quantityFilteredTotal = api572					.column( 7, { page: 'current'} )573					.data()574					.reduce( function (a, b) {575						return intVal(a) + intVal(b);576					}, 0 );577				578				// Unit price Total over all pages579				unitPriceTotal = api580					.column( 8 )581					.data()582					.reduce( function (a, b) {583						return intVal(a) + intVal(b);584					}, 0 );585				586				// Unit price total over current page587				unitPriceFilteredTotal = api588					.column( 8, { page: 'current'} )589					.data()590					.reduce( function (a, b) {591						return intVal(a) + intVal(b);592					}, 0 );593					594				// Full price Total over all pages595				fullPriceTotal = api596					.column( 9 )597					.data()598					.reduce( function (a, b) {599						return intVal(a) + intVal(b);600					}, 0 );601				602				// Full price total over current page603				fullPriceFilteredTotal = api604					.column( 9, { page: 'current'} )605					.data()606					.reduce( function (a, b) {607						return intVal(a) + intVal(b);608					}, 0 );609	 610				// Update footer columns611				$( api.column( 7 ).footer() ).html(quantityFilteredTotal +' ('+ quantityTotal +' total)');612				$( api.column( 8 ).footer() ).html(unitPriceFilteredTotal +' ('+ unitPriceTotal +' total)');613				$( api.column( 9 ).footer() ).html(fullPriceFilteredTotal +' ('+ fullPriceTotal +' total)');614			}615		});616	});617}618// Function to create filtered datatable for sale details with total values619function filteredSaleReportTableCreator(startDate, endDate, scriptPath, tableDIV, tableID){620	var startDate = $('#' + startDate).val();621	var endDate = $('#' + endDate).val();622	$.ajax({623		url: scriptPath,624		method: 'POST',625		data: {626			startDate:startDate,627			endDate:endDate,628		},629		success: function(data){630			$('#' + tableDIV).empty();631			$('#' + tableDIV).html(data);632		},633		complete: function(){634			// Initiate the Datatable plugin once the table is added to the DOM635			$('#' + tableID).DataTable({636				dom: 'lBfrtip',637				buttons: [638					'copy',639					{extend: 'csv', footer: true, title: 'Sale Report'},640					{extend: 'excel', footer: true, title: 'Sale Report'},641					{extend: 'pdf', footer: true, orientation: 'landscape', pageSize: 'LEGAL', title: 'Sale Report'},642					{extend: 'print', footer: true, title: 'Sale Report'},643				],644				"footerCallback": function ( row, data, start, end, display ) {645					var api = this.api(), data;646		 647					// Remove the formatting to get integer data for summation648					var intVal = function ( i ) {649						return typeof i === 'string' ?650							i.replace(/[\$,]/g, '')*1 :651							typeof i === 'number' ?652								i : 0;653					};654		 655					// Total over all pages656					quantityTotal = api657						.column( 7 )658						.data()659						.reduce( function (a, b) {660							return intVal(a) + intVal(b);661						}, 0 );662		 663					// Total over this page664					quantityFilteredTotal = api665						.column( 7, { page: 'current'} )666						.data()667						.reduce( function (a, b) {668							return intVal(a) + intVal(b);669						}, 0 );670					671					// Total over all pages672					unitPriceTotal = api673						.column( 8 )674						.data()675						.reduce( function (a, b) {676							return intVal(a) + intVal(b);677						}, 0 );678					679					// Quantity total680					unitPriceFilteredTotal = api681						.column( 8, { page: 'current'} )682						.data()683						.reduce( function (a, b) {684							return intVal(a) + intVal(b);685						}, 0 );686						687					// Full total over all pages688					fullPriceTotal = api689						.column( 9 )690						.data()691						.reduce( function (a, b) {692							return intVal(a) + intVal(b);693						}, 0 );694					695					// Full total over current page696					fullPriceFilteredTotal = api697						.column( 9, { page: 'current'} )698						.data()699						.reduce( function (a, b) {700							return intVal(a) + intVal(b);701						}, 0 );702		 703					// Update footer columns704					$( api.column( 7 ).footer() ).html(quantityFilteredTotal +' ('+ quantityTotal +' total)');705					$( api.column( 8 ).footer() ).html(unitPriceFilteredTotal +' ('+ unitPriceTotal +' total)');706					$( api.column( 9 ).footer() ).html(fullPriceFilteredTotal +' ('+ fullPriceTotal +' total)');707				}708			});709		}710	});711}712// Function to create filtered datatable for purchase details with total values713function filteredPurchaseReportTableCreator(startDate, endDate, scriptPath, tableDIV, tableID){714	var startDate = $('#' + startDate).val();715	var endDate = $('#' + endDate).val();716	$.ajax({717		url: scriptPath,718		method: 'POST',719		data: {720			startDate:startDate,721			endDate:endDate,722		},723		success: function(data){724			$('#' + tableDIV).empty();725			$('#' + tableDIV).html(data);726		},727		complete: function(){728			// Initiate the Datatable plugin once the table is added to the DOM729			$('#' + tableID).DataTable({730				dom: 'lBfrtip',731				buttons: [732					'copy',733					{extend: 'csv', footer: true, title: 'Purchase Report'},734					{extend: 'excel', footer: true, title: 'Purchase Report'},735					{extend: 'pdf', footer: true, orientation: 'landscape', pageSize: 'LEGAL', title: 'Purchase Report'},736					{extend: 'print', footer: true, title: 'Purchase Report'}737				],738				"footerCallback": function ( row, data, start, end, display ) {739					var api = this.api(), data;740		 741					// Remove the formatting to get integer data for summation742					var intVal = function ( i ) {743						return typeof i === 'string' ?744							i.replace(/[\$,]/g, '')*1 :745							typeof i === 'number' ?746								i : 0;747					};748		 749					// Quantity total over all pages750					quantityTotal = api751						.column( 6 )752						.data()753						.reduce( function (a, b) {754							return intVal(a) + intVal(b);755						}, 0 );756		 757					// Quantity for current page758					quantityFilteredTotal = api759						.column( 6, { page: 'current'} )760						.data()761						.reduce( function (a, b) {762							return intVal(a) + intVal(b);763						}, 0 );764					765					// Unit price total over all pages766					unitPriceTotal = api767						.column( 7 )768						.data()769						.reduce( function (a, b) {770							return intVal(a) + intVal(b);771						}, 0 );772					773					// Unit price for current page774					unitPriceFilteredTotal = api775						.column( 7, { page: 'current'} )776						.data()777						.reduce( function (a, b) {778							return intVal(a) + intVal(b);779						}, 0 );780					781					// Full price total over all pages782					fullPriceTotal = api783						.column( 8 )784						.data()785						.reduce( function (a, b) {786							return intVal(a) + intVal(b);787						}, 0 );788					789					// Full price for current page790					fullPriceFilteredTotal = api791						.column( 8, { page: 'current'} )792						.data()793						.reduce( function (a, b) {794							return intVal(a) + intVal(b);795						}, 0 );796		 797					// Update footer columns798					$( api.column( 6 ).footer() ).html(quantityFilteredTotal +' ('+ quantityTotal +' total)');799					$( api.column( 7 ).footer() ).html(unitPriceFilteredTotal +' ('+ unitPriceTotal +' total)');800					$( api.column( 8 ).footer() ).html(fullPriceFilteredTotal +' ('+ fullPriceTotal +' total)');801				}802			});803		}804	});805}806// Calculate Total Purchase value in purchase details tab807function calculateTotalInPurchaseTab(){808	var quantityPT = $('#purchaseDetailsQuantity').val();809	var unitPricePT = $('#purchaseDetailsUnitPrice').val();810	$('#purchaseDetailsTotal').val(Number(quantityPT) * Number(unitPricePT));811}812// Calculate Total sale value in sale details tab813function calculateTotalInSaleTab(){814	var quantityST = $('#saleDetailsQuantity').val();815	var unitPriceST = $('#saleDetailsUnitPrice').val();816	var discountST = $('#saleDetailsDiscount').val();817	$('#saleDetailsTotal').val(Number(unitPriceST) * ((100 - Number(discountST)) / 100) * Number(quantityST));818}819// Function to call the insertCustomer.php script to insert customer data to db820function addCustomer() {821	var customerDetailsCustomerFullName = $('#customerDetailsCustomerFullName').val();822	var customerDetailsCustomerEmail = $('#customerDetailsCustomerEmail').val();823	var customerDetailsCustomerMobile = $('#customerDetailsCustomerMobile').val();824	var customerDetailsCustomerPhone2 = $('#customerDetailsCustomerPhone2').val();825	var customerDetailsCustomerAddress = $('#customerDetailsCustomerAddress').val();826	var customerDetailsCustomerAddress2 = $('#customerDetailsCustomerAddress2').val();827	var customerDetailsCustomerCity = $('#customerDetailsCustomerCity').val();828	var customerDetailsCustomerDistrict = $('#customerDetailsCustomerDistrict option:selected').text();829	var customerDetailsStatus = $('#customerDetailsStatus option:selected').text();830	831	$.ajax({832		url: 'model/customer/insertCustomer.php',833		method: 'POST',834		data: {835			customerDetailsCustomerFullName:customerDetailsCustomerFullName,836			customerDetailsCustomerEmail:customerDetailsCustomerEmail,837			customerDetailsCustomerMobile:customerDetailsCustomerMobile,838			customerDetailsCustomerPhone2:customerDetailsCustomerPhone2,839			customerDetailsCustomerAddress:customerDetailsCustomerAddress,840			customerDetailsCustomerAddress2:customerDetailsCustomerAddress2,841			customerDetailsCustomerCity:customerDetailsCustomerCity,842			customerDetailsCustomerDistrict:customerDetailsCustomerDistrict,843			customerDetailsStatus:customerDetailsStatus,844		},845		success: function(data){846			$('#customerDetailsMessage').fadeIn();847			$('#customerDetailsMessage').html(data);848		},849		complete: function(data){850			populateLastInsertedID(customerLastInsertedIDFile, 'customerDetailsCustomerID');851			searchTableCreator('customerDetailsTableDiv', customerDetailsSearchTableCreatorFile, 'customerDetailsTable');852			reportsTableCreator('customerReportsTableDiv', customerReportsSearchTableCreatorFile, 'customerReportsTable');853		}854	});855}856// Function to call the insertVendor.php script to insert vendor data to db857function addVendor() {858	var vendorDetailsVendorFullName = $('#vendorDetailsVendorFullName').val();859	var vendorDetailsVendorEmail = $('#vendorDetailsVendorEmail').val();860	var vendorDetailsVendorMobile = $('#vendorDetailsVendorMobile').val();861	var vendorDetailsVendorPhone2 = $('#vendorDetailsVendorPhone2').val();862	var vendorDetailsVendorAddress = $('#vendorDetailsVendorAddress').val();863	var vendorDetailsVendorAddress2 = $('#vendorDetailsVendorAddress2').val();864	var vendorDetailsVendorCity = $('#vendorDetailsVendorCity').val();865	var vendorDetailsVendorDistrict = $('#vendorDetailsVendorDistrict option:selected').text();866	var vendorDetailsStatus = $('#vendorDetailsStatus option:selected').text();867	868	$.ajax({869		url: 'model/vendor/insertVendor.php',870		method: 'POST',871		data: {872			vendorDetailsVendorFullName:vendorDetailsVendorFullName,873			vendorDetailsVendorEmail:vendorDetailsVendorEmail,874			vendorDetailsVendorMobile:vendorDetailsVendorMobile,875			vendorDetailsVendorPhone2:vendorDetailsVendorPhone2,876			vendorDetailsVendorAddress:vendorDetailsVendorAddress,877			vendorDetailsVendorAddress2:vendorDetailsVendorAddress2,878			vendorDetailsVendorCity:vendorDetailsVendorCity,879			vendorDetailsVendorDistrict:vendorDetailsVendorDistrict,880			vendorDetailsStatus:vendorDetailsStatus,881		},882		success: function(data){883			$('#vendorDetailsMessage').fadeIn();884			$('#vendorDetailsMessage').html(data);885		},886		complete: function(data){887			populateLastInsertedID(vendorLastInsertedIDFile, 'vendorDetailsVendorID');888			searchTableCreator('vendorDetailsTableDiv', vendorDetailsSearchTableCreatorFile, 'vendorDetailsTable');889			reportsTableCreator('vendorReportsTableDiv', vendorReportsSearchTableCreatorFile, 'vendorReportsTable');890			$('#purchaseDetailsVendorName').load('model/vendor/getVendorNames.php');891		}892	});893}894// Function to call the insertItem.php script to insert item data to db895function addItem() {896	var itemDetailsItemNumber = $('#itemDetailsItemNumber').val();897	var itemDetailsItemName = $('#itemDetailsItemName').val();898	var itemDetailsDiscount = $('#itemDetailsDiscount').val();899	var itemDetailsQuantity = $('#itemDetailsQuantity').val();900	var itemDetailsUnitPrice = $('#itemDetailsUnitPrice').val();901	var itemDetailsStatus = $('#itemDetailsStatus').val();902	var itemDetailsDescription = $('#itemDetailsDescription').val();903	904	$.ajax({905		url: 'model/item/insertItem.php',906		method: 'POST',907		data: {908			itemDetailsItemNumber:itemDetailsItemNumber,909			itemDetailsItemName:itemDetailsItemName,910			itemDetailsDiscount:itemDetailsDiscount,911			itemDetailsQuantity:itemDetailsQuantity,912			itemDetailsUnitPrice:itemDetailsUnitPrice,913			itemDetailsStatus:itemDetailsStatus,914			itemDetailsDescription:itemDetailsDescription,915		},916		success: function(data){917			$('#itemDetailsMessage').fadeIn();918			$('#itemDetailsMessage').html(data);919		},920		complete: function(){921			populateLastInsertedID(itemLastInsertedIDFile, 'itemDetailsProductID');922			getItemStockToPopulate('itemDetailsItemNumber', getItemStockFile, itemDetailsTotalStock);923			searchTableCreator('itemDetailsTableDiv', itemDetailsSearchTableCreatorFile, 'itemDetailsTable');924			reportsTableCreator('itemReportsTableDiv', itemReportsSearchTableCreatorFile, 'itemReportsTable');925		}926	});927}928// Function to call the insertPurchase.php script to insert purchase data to db929function addPurchase() {930	var purchaseDetailsItemNumber = $('#purchaseDetailsItemNumber').val();931	var purchaseDetailsPurchaseDate = $('#purchaseDetailsPurchaseDate').val();932	var purchaseDetailsItemName = $('#purchaseDetailsItemName').val();933	var purchaseDetailsQuantity = $('#purchaseDetailsQuantity').val();934	var purchaseDetailsUnitPrice = $('#purchaseDetailsUnitPrice').val();935	var purchaseDetailsVendorName = $('#purchaseDetailsVendorName').val();936	937	$.ajax({938		url: 'model/purchase/insertPurchase.php',939		method: 'POST',940		data: {941			purchaseDetailsItemNumber:purchaseDetailsItemNumber,942			purchaseDetailsPurchaseDate:purchaseDetailsPurchaseDate,943			purchaseDetailsItemName:purchaseDetailsItemName,944			purchaseDetailsQuantity:purchaseDetailsQuantity,945			purchaseDetailsUnitPrice:purchaseDetailsUnitPrice,946			purchaseDetailsVendorName:purchaseDetailsVendorName,947		},948		success: function(data){949			$('#purchaseDetailsMessage').fadeIn();950			$('#purchaseDetailsMessage').html(data);951		},952		complete: function(){953			getItemStockToPopulate('purchaseDetailsItemNumber', getItemStockFile, 'purchaseDetailsCurrentStock');954			populateLastInsertedID(purchaseLastInsertedIDFile, 'purchaseDetailsPurchaseID');955			searchTableCreator('purchaseDetailsTableDiv', purchaseDetailsSearchTableCreatorFile, 'purchaseDetailsTable');956			reportsPurchaseTableCreator('purchaseReportsTableDiv', purchaseReportsSearchTableCreatorFile, 'purchaseReportsTable');957			searchTableCreator('itemDetailsTableDiv', itemDetailsSearchTableCreatorFile, 'itemDetailsTable');958			reportsTableCreator('itemReportsTableDiv', itemReportsSearchTableCreatorFile, 'itemReportsTable');959		}960	});961}962// Function to call the insertSale.php script to insert sale data to db963function addSale() {964	var saleDetailsItemNumber = $('#saleDetailsItemNumber').val();965	var saleDetailsItemName = $('#saleDetailsItemName').val();966	var saleDetailsDiscount = $('#saleDetailsDiscount').val();967	var saleDetailsQuantity = $('#saleDetailsQuantity').val();968	var saleDetailsUnitPrice = $('#saleDetailsUnitPrice').val();969	var saleDetailsCustomerID = $('#saleDetailsCustomerID').val();970	var saleDetailsCustomerName = $('#saleDetailsCustomerName').val();971	var saleDetailsSaleDate = $('#saleDetailsSaleDate').val();972	973	$.ajax({974		url: 'model/sale/insertSale.php',975		method: 'POST',976		data: {977			saleDetailsItemNumber:saleDetailsItemNumber,978			saleDetailsItemName:saleDetailsItemName,979			saleDetailsDiscount:saleDetailsDiscount,980			saleDetailsQuantity:saleDetailsQuantity,981			saleDetailsUnitPrice:saleDetailsUnitPrice,982			saleDetailsCustomerID:saleDetailsCustomerID,983			saleDetailsCustomerName:saleDetailsCustomerName,984			saleDetailsSaleDate:saleDetailsSaleDate,985		},986		success: function(data){987			$('#saleDetailsMessage').fadeIn();988			$('#saleDetailsMessage').html(data);989		},990		complete: function(){991			getItemStockToPopulate('saleDetailsItemNumber', getItemStockFile, 'saleDetailsTotalStock');992			populateLastInsertedID(saleLastInsertedIDFile, 'saleDetailsSaleID');993			searchTableCreator('saleDetailsTableDiv', saleDetailsSearchTableCreatorFile, 'saleDetailsTable');994			reportsSaleTableCreator('saleReportsTableDiv', saleReportsSearchTableCreatorFile, 'saleReportsTable');995			searchTableCreator('itemDetailsTableDiv', itemDetailsSearchTableCreatorFile, 'itemDetailsTable');996			reportsTableCreator('itemReportsTableDiv', itemReportsSearchTableCreatorFile, 'itemReportsTable');997		}998	});999}1000// Function to send itemNumber so that item details can be pulled from db1001// to be displayed on item details tab1002function getItemDetailsToPopulate(){1003	// Get the itemNumber entered in the text box1004	var itemNumber = $('#itemDetailsItemNumber').val();1005	var defaultImgUrl = 'data/item_images/imageNotAvailable.jpg';1006	var defaultImageData = '<img class="img-fluid" src="data/item_images/imageNotAvailable.jpg">';1007	1008	// Call the populateItemDetails.php script to get item details1009	// relevant to the itemNumber which the user entered1010	$.ajax({1011		url: 'model/item/populateItemDetails.php',1012		method: 'POST',1013		data: {itemNumber:itemNumber},1014		dataType: 'json',1015		success: function(data){1016			//$('#itemDetailsItemNumber').val(data.itemNumber);1017			$('#itemDetailsProductID').val(data.productID);1018			$('#itemDetailsItemName').val(data.itemName);1019			$('#itemDetailsDiscount').val(data.discount);1020			$('#itemDetailsTotalStock').val(data.stock);1021			$('#itemDetailsUnitPrice').val(data.unitPrice);1022			$('#itemDetailsDescription').val(data.description);1023			$('#itemDetailsStatus').val(data.status).trigger("chosen:updated");1024			newImgUrl = 'data/item_images/' + data.itemNumber + '/' + data.imageURL;1025			1026			// Set the item image1027			if(data.imageURL == 'imageNotAvailable.jpg' || data.imageURL == ''){1028				$('#imageContainer').html(defaultImageData);1029			} else {1030				$('#imageContainer').html('<img class="img-fluid" src="' + newImgUrl + '">');1031			}1032		}1033	});1034}1035// Function to send itemNumber so that item details can be pulled from db1036// to be displayed on sale details tab1037function getItemDetailsToPopulateForSaleTab(){1038	// Get the itemNumber entered in the text box1039	var itemNumber = $('#saleDetailsItemNumber').val();1040	var defaultImgUrl = 'data/item_images/imageNotAvailable.jpg';1041	var defaultImageData = '<img class="img-fluid" src="data/item_images/imageNotAvailable.jpg">';1042	1043	// Call the populateItemDetails.php script to get item details1044	// relevant to the itemNumber which the user entered1045	$.ajax({1046		url: 'model/item/populateItemDetails.php',1047		method: 'POST',1048		data: {itemNumber:itemNumber},1049		dataType: 'json',1050		success: function(data){1051			//$('#saleDetailsItemNumber').val(data.itemNumber);1052			$('#saleDetailsItemName').val(data.itemName);1053			$('#saleDetailsDiscount').val(data.discount);1054			$('#saleDetailsTotalStock').val(data.stock);1055			$('#saleDetailsUnitPrice').val(data.unitPrice);1056			newImgUrl = 'data/item_images/' + data.itemNumber + '/' + data.imageURL;1057			1058			// Set the item image1059			if(data.imageURL == 'imageNotAvailable.jpg' || data.imageURL == ''){1060				$('#saleDetailsImageContainer').html(defaultImageData);1061			} else {1062				$('#saleDetailsImageContainer').html('<img class="img-fluid" src="' + newImgUrl + '">');1063			}1064		},1065		complete: function() {1066			//$('#saleDetailsDiscount, #saleDetailsQuantity, #saleDetailsUnitPrice').trigger('change');1067			calculateTotalInSaleTab();1068		}1069	});1070}1071// Function to send itemNumber so that item name can be pulled from db1072function getItemName(itemNumberTextBoxID, scriptPath, itemNameTextbox){1073	// Get the itemNumber entered in the text box1074	var itemNumber = $('#' + itemNumberTextBoxID).val();1075	// Call the script to get item details1076	$.ajax({1077		url: scriptPath,1078		method: 'POST',1079		data: {itemNumber:itemNumber},1080		dataType: 'json',1081		success: function(data){1082			$('#' + itemNameTextbox).val(data.itemName);1083		},1084		error: function (xhr, ajaxOptions, thrownError) {1085      }1086	});1087}1088// Function to send itemNumber so that item stock can be pulled from db1089function getItemStockToPopulate(itemNumberTextbox, scriptPath, stockTextbox){1090	// Get the itemNumber entered in the text box1091	var itemNumber = $('#' + itemNumberTextbox).val();1092	1093	// Call the script to get stock details1094	$.ajax({1095		url: scriptPath,1096		method: 'POST',1097		data: {itemNumber:itemNumber},1098		dataType: 'json',1099		success: function(data){1100			$('#' + stockTextbox).val(data.stock);1101		},1102		error: function (xhr, ajaxOptions, thrownError) {1103        //alert(xhr.status);1104        //alert(thrownError);1105		//console.warn(xhr.responseText)1106      }1107	});1108}1109// Function to populate last inserted ID1110function populateLastInsertedID(scriptPath, textBoxID){1111	$.ajax({1112		url: scriptPath,1113		method: 'POST',1114		dataType: 'json',1115		success: function(data){1116			$('#' + textBoxID).val(data);1117		}1118	});1119}1120// Function to show suggestions1121function showSuggestions(textBoxID, scriptPath, suggestionsDivID){1122	// Get the value entered by the user1123	var textBoxValue = $('#' + textBoxID).val();1124	1125	// Call the showPurchaseIDs.php script only if there is a value in the1126	// purchase ID textbox1127	if(textBoxValue != ''){1128		$.ajax({1129			url: scriptPath,1130			method: 'POST',1131			data: {textBoxValue:textBoxValue},1132			success: function(data){1133				$('#' + suggestionsDivID).fadeIn();1134				$('#' + suggestionsDivID).html(data);1135			}1136		});1137	}1138}1139// Function to delte item from db1140function deleteItem(){1141	// Get the item number entered by the user1142	var itemDetailsItemNumber = $('#itemDetailsItemNumber').val();1143	1144	// Call the deleteItem.php script only if there is a value in the1145	// item number textbox1146	if(itemDetailsItemNumber != ''){1147		$.ajax({1148			url: 'model/item/deleteItem.php',1149			method: 'POST',1150			data: {itemDetailsItemNumber:itemDetailsItemNumber},1151			success: function(data){1152				$('#itemDetailsMessage').fadeIn();1153				$('#itemDetailsMessage').html(data);1154			},1155			complete: function(){1156				searchTableCreator('itemDetailsTableDiv', itemDetailsSearchTableCreatorFile, 'itemDetailsTable');1157				reportsTableCreator('itemReportsTableDiv', itemReportsSearchTableCreatorFile, 'itemReportsTable');1158			}1159		});1160	}1161}1162// Function to delete item from db1163function deleteCustomer(){1164	// Get the customerID entered by the user1165	var customerDetailsCustomerID = $('#customerDetailsCustomerID').val();1166	1167	// Call the deleteCustomer.php script only if there is a value in the1168	// item number textbox1169	if(customerDetailsCustomerID != ''){1170		$.ajax({1171			url: 'model/customer/deleteCustomer.php',1172			method: 'POST',1173			data: {customerDetailsCustomerID:customerDetailsCustomerID},1174			success: function(data){1175				$('#customerDetailsMessage').fadeIn();1176				$('#customerDetailsMessage').html(data);1177			},1178			complete: function(){1179				searchTableCreator('customerDetailsTableDiv', customerDetailsSearchTableCreatorFile, 'customerDetailsTable');1180				reportsTableCreator('customerReportsTableDiv', customerReportsSearchTableCreatorFile, 'customerReportsTable');1181			}1182		});1183	}1184}1185// Function to delete vendor from db1186function deleteVendor(){1187	// Get the vendorID entered by the user1188	var vendorDetailsVendorID = $('#vendorDetailsVendorID').val();1189	1190	// Call the deleteVendor.php script only if there is a value in the1191	// vendor ID textbox1192	if(vendorDetailsVendorID != ''){1193		$.ajax({1194			url: 'model/vendor/deleteVendor.php',1195			method: 'POST',1196			data: {vendorDetailsVendorID:vendorDetailsVendorID},1197			success: function(data){1198				$('#vendorDetailsMessage').fadeIn();1199				$('#vendorDetailsMessage').html(data);1200			},1201			complete: function(){1202				searchTableCreator('vendorDetailsTableDiv', vendorDetailsSearchTableCreatorFile, 'vendorDetailsTable');1203				reportsTableCreator('vendorReportsTableDiv', vendorReportsSearchTableCreatorFile, 'vendorReportsTable');1204			}1205		});1206	}1207}1208// Function to send customerID so that customer details can be pulled from db1209// to be displayed on customer details tab1210function getCustomerDetailsToPopulate(){1211	// Get the customerID entered in the text box1212	var customerDetailsCustomerID = $('#customerDetailsCustomerID').val();1213	1214	// Call the populateItemDetails.php script to get item details1215	// relevant to the itemNumber which the user entered1216	$.ajax({1217		url: 'model/customer/populateCustomerDetails.php',1218		method: 'POST',1219		data: {customerID:customerDetailsCustomerID},1220		dataType: 'json',1221		success: function(data){1222			//$('#customerDetailsCustomerID').val(data.customerID);1223			$('#customerDetailsCustomerFullName').val(data.fullName);1224			$('#customerDetailsCustomerMobile').val(data.mobile);1225			$('#customerDetailsCustomerPhone2').val(data.phone2);1226			$('#customerDetailsCustomerEmail').val(data.email);1227			$('#customerDetailsCustomerAddress').val(data.address);1228			$('#customerDetailsCustomerAddress2').val(data.address2);1229			$('#customerDetailsCustomerCity').val(data.city);1230			$('#customerDetailsCustomerDistrict').val(data.district).trigger("chosen:updated");1231			$('#customerDetailsStatus').val(data.status).trigger("chosen:updated");1232		}1233	});1234}1235// Function to send customerID so that customer details can be pulled from db1236// to be displayed on sale details tab1237function getCustomerDetailsToPopulateSaleTab(){1238	// Get the customerID entered in the text box1239	var customerDetailsCustomerID = $('#saleDetailsCustomerID').val();1240	1241	// Call the populateCustomerDetails.php script to get customer details1242	// relevant to the customerID which the user entered1243	$.ajax({1244		url: 'model/customer/populateCustomerDetails.php',1245		method: 'POST',1246		data: {customerID:customerDetailsCustomerID},1247		dataType: 'json',1248		success: function(data){1249			//$('#saleDetailsCustomerID').val(data.customerID);1250			$('#saleDetailsCustomerName').val(data.fullName);1251		}1252	});1253}1254// Function to send vendorID so that vendor details can be pulled from db1255// to be displayed on vendor details tab1256function getVendorDetailsToPopulate(){1257	// Get the vendorID entered in the text box1258	var vendorDetailsVendorID = $('#vendorDetailsVendorID').val();1259	1260	// Call the populateVendorDetails.php script to get vendor details1261	// relevant to the vendorID which the user entered1262	$.ajax({1263		url: 'model/vendor/populateVendorDetails.php',1264		method: 'POST',1265		data: {vendorDetailsVendorID:vendorDetailsVendorID},1266		dataType: 'json',1267		success: function(data){1268			//$('#vendorDetailsVendorID').val(data.vendorID);1269			$('#vendorDetailsVendorFullName').val(data.fullName);1270			$('#vendorDetailsVendorMobile').val(data.mobile);1271			$('#vendorDetailsVendorPhone2').val(data.phone2);1272			$('#vendorDetailsVendorEmail').val(data.email);1273			$('#vendorDetailsVendorAddress').val(data.address);1274			$('#vendorDetailsVendorAddress2').val(data.address2);1275			$('#vendorDetailsVendorCity').val(data.city);1276			$('#vendorDetailsVendorDistrict').val(data.district).trigger("chosen:updated");1277			$('#vendorDetailsStatus').val(data.status).trigger("chosen:updated");1278		}1279	});1280}1281// Function to send purchaseID so that purchase details can be pulled from db1282// to be displayed on purchase details tab1283function getPurchaseDetailsToPopulate(){1284	// Get the purchaseID entered in the text box1285	var purchaseDetailsPurchaseID = $('#purchaseDetailsPurchaseID').val();1286	1287	// Call the populatePurchaseDetails.php script to get item details1288	// relevant to the itemNumber which the user entered1289	$.ajax({1290		url: 'model/purchase/populatePurchaseDetails.php',1291		method: 'POST',1292		data: {purchaseDetailsPurchaseID:purchaseDetailsPurchaseID},1293		dataType: 'json',1294		success: function(data){1295			//$('#purchaseDetailsPurchaseID').val(data.customerID);1296			$('#purchaseDetailsItemNumber').val(data.itemNumber);1297			$('#purchaseDetailsPurchaseDate').val(data.purchaseDate);1298			$('#purchaseDetailsItemName').val(data.itemName);1299			$('#purchaseDetailsQuantity').val(data.quantity);1300			$('#purchaseDetailsUnitPrice').val(data.unitPrice);1301			$('#purchaseDetailsVendorName').val(data.vendorName).trigger("chosen:updated");1302		},1303		complete: function(){1304			calculateTotalInPurchaseTab();1305			getItemStockToPopulate('purchaseDetailsItemNumber', getItemStockFile, 'purchaseDetailsCurrentStock');1306		}1307	});1308}1309// Function to send saleID so that sale details can be pulled from db1310// to be displayed on sale details tab1311function getSaleDetailsToPopulate(){1312	// Get the saleID entered in the text box1313	var saleDetailsSaleID = $('#saleDetailsSaleID').val();1314	1315	// Call the populateSaleDetails.php script to get item details1316	// relevant to the itemNumber which the user entered1317	$.ajax({1318		url: 'model/sale/populateSaleDetails.php',1319		method: 'POST',1320		data: {saleDetailsSaleID:saleDetailsSaleID},1321		dataType: 'json',1322		success: function(data){1323			//$('#saleDetailsSaleID').val(data.saleID);1324			$('#saleDetailsItemNumber').val(data.itemNumber);1325			$('#saleDetailsCustomerID').val(data.customerID);1326			$('#saleDetailsCustomerName').val(data.customerName);1327			$('#saleDetailsItemName').val(data.itemName);1328			$('#saleDetailsSaleDate').val(data.saleDate);1329			$('#saleDetailsDiscount').val(data.discount);1330			$('#saleDetailsQuantity').val(data.quantity);1331			$('#saleDetailsUnitPrice').val(data.unitPrice);1332		},1333		complete: function(){1334			calculateTotalInSaleTab();1335			getItemStockToPopulate('saleDetailsItemNumber', getItemStockFile, 'saleDetailsTotalStock');1336		}1337	});1338}1339// Function to call the upateItemDetails.php script to UPDATE item data in db1340function updateItem() {1341	var itemDetailsItemNumber = $('#itemDetailsItemNumber').val();1342	var itemDetailsItemName = $('#itemDetailsItemName').val();1343	var itemDetailsDiscount = $('#itemDetailsDiscount').val();1344	var itemDetailsQuantity = $('#itemDetailsQuantity').val();1345	var itemDetailsUnitPrice = $('#itemDetailsUnitPrice').val();1346	var itemDetailsStatus = $('#itemDetailsStatus').val();1347	var itemDetailsDescription = $('#itemDetailsDescription').val();1348	1349	$.ajax({1350		url: 'model/item/updateItemDetails.php',1351		method: 'POST',1352		data: {1353			itemNumber:itemDetailsItemNumber,1354			itemDetailsItemName:itemDetailsItemName,1355			itemDetailsDiscount:itemDetailsDiscount,1356			itemDetailsQuantity:itemDetailsQuantity,1357			itemDetailsUnitPrice:itemDetailsUnitPrice,1358			itemDetailsStatus:itemDetailsStatus,1359			itemDetailsDescription:itemDetailsDescription,1360		},1361		success: function(data){1362			var result = $.parseJSON(data);1363			$('#itemDetailsMessage').fadeIn();1364			$('#itemDetailsMessage').html(result.alertMessage);1365			if(result.newStock != null){1366				$('#itemDetailsTotalStock').val(result.newStock);1367			}1368		},1369		complete: function(){1370			searchTableCreator('itemDetailsTableDiv', itemDetailsSearchTableCreatorFile, 'itemDetailsTable');			1371			searchTableCreator('purchaseDetailsTableDiv', purchaseDetailsSearchTableCreatorFile, 'purchaseDetailsTable');1372			searchTableCreator('saleDetailsTableDiv', saleDetailsSearchTableCreatorFile, 'saleDetailsTable');1373			reportsTableCreator('itemReportsTableDiv', itemReportsSearchTableCreatorFile, 'itemReportsTable');1374			reportsPurchaseTableCreator('purchaseReportsTableDiv', purchaseReportsSearchTableCreatorFile, 'purchaseReportsTable');1375			reportsSaleTableCreator('saleReportsTableDiv', saleReportsSearchTableCreatorFile, 'saleReportsTable');1376		}1377	});1378}1379// Function to call the upateCustomerDetails.php script to UPDATE customer data in db1380function updateCustomer() {1381	var customerDetailsCustomerID = $('#customerDetailsCustomerID').val();1382	var customerDetailsCustomerFullName = $('#customerDetailsCustomerFullName').val();1383	var customerDetailsCustomerMobile = $('#customerDetailsCustomerMobile').val();1384	var customerDetailsCustomerPhone2 = $('#customerDetailsCustomerPhone2').val();1385	var customerDetailsCustomerAddress = $('#customerDetailsCustomerAddress').val();1386	var customerDetailsCustomerEmail = $('#customerDetailsCustomerEmail').val();1387	var customerDetailsCustomerAddress2 = $('#customerDetailsCustomerAddress2').val();1388	var customerDetailsCustomerCity = $('#customerDetailsCustomerCity').val();1389	var customerDetailsCustomerDistrict = $('#customerDetailsCustomerDistrict').val();1390	var customerDetailsStatus = $('#customerDetailsStatus option:selected').text();1391	1392	$.ajax({1393		url: 'model/customer/updateCustomerDetails.php',1394		method: 'POST',1395		data: {1396			customerDetailsCustomerID:customerDetailsCustomerID,1397			customerDetailsCustomerFullName:customerDetailsCustomerFullName,1398			customerDetailsCustomerMobile:customerDetailsCustomerMobile,1399			customerDetailsCustomerPhone2:customerDetailsCustomerPhone2,1400			customerDetailsCustomerAddress:customerDetailsCustomerAddress,1401			customerDetailsCustomerEmail:customerDetailsCustomerEmail,1402			customerDetailsCustomerAddress2:customerDetailsCustomerAddress2,1403			customerDetailsCustomerCity:customerDetailsCustomerCity,1404			customerDetailsCustomerDistrict:customerDetailsCustomerDistrict,1405			customerDetailsStatus:customerDetailsStatus,1406		},1407		success: function(data){1408			$('#customerDetailsMessage').fadeIn();1409			$('#customerDetailsMessage').html(data);1410		},1411		complete: function(){1412			searchTableCreator('customerDetailsTableDiv', customerDetailsSearchTableCreatorFile, 'customerDetailsTable');1413			reportsTableCreator('customerReportsTableDiv', customerReportsSearchTableCreatorFile, 'customerReportsTable');1414			searchTableCreator('saleDetailsTableDiv', saleDetailsSearchTableCreatorFile, 'saleDetailsTable');1415			reportsSaleTableCreator('saleReportsTableDiv', saleReportsSearchTableCreatorFile, 'saleReportsTable');1416		}1417	});1418}1419// Function to call the upateVendorDetails.php script to UPDATE vendor data in db1420function updateVendor() {1421	var vendorDetailsVendorID = $('#vendorDetailsVendorID').val();1422	var vendorDetailsVendorFullName = $('#vendorDetailsVendorFullName').val();1423	var vendorDetailsVendorMobile = $('#vendorDetailsVendorMobile').val();1424	var vendorDetailsVendorPhone2 = $('#vendorDetailsVendorPhone2').val();1425	var vendorDetailsVendorAddress = $('#vendorDetailsVendorAddress').val();1426	var vendorDetailsVendorEmail = $('#vendorDetailsVendorEmail').val();1427	var vendorDetailsVendorAddress2 = $('#vendorDetailsVendorAddress2').val();1428	var vendorDetailsVendorCity = $('#vendorDetailsVendorCity').val();1429	var vendorDetailsVendorDistrict = $('#vendorDetailsVendorDistrict').val();1430	var vendorDetailsStatus = $('#vendorDetailsStatus option:selected').text();1431	1432	$.ajax({1433		url: 'model/vendor/updateVendorDetails.php',1434		method: 'POST',1435		data: {1436			vendorDetailsVendorID:vendorDetailsVendorID,1437			vendorDetailsVendorFullName:vendorDetailsVendorFullName,1438			vendorDetailsVendorMobile:vendorDetailsVendorMobile,1439			vendorDetailsVendorPhone2:vendorDetailsVendorPhone2,1440			vendorDetailsVendorAddress:vendorDetailsVendorAddress,1441			vendorDetailsVendorEmail:vendorDetailsVendorEmail,1442			vendorDetailsVendorAddress2:vendorDetailsVendorAddress2,1443			vendorDetailsVendorCity:vendorDetailsVendorCity,1444			vendorDetailsVendorDistrict:vendorDetailsVendorDistrict,1445			vendorDetailsStatus:vendorDetailsStatus,1446		},1447		success: function(data){1448			$('#vendorDetailsMessage').fadeIn();1449			$('#vendorDetailsMessage').html(data);1450		},1451		complete: function(){1452			searchTableCreator('purchaseDetailsTableDiv', purchaseDetailsSearchTableCreatorFile, 'purchaseDetailsTable');1453			searchTableCreator('vendorDetailsTableDiv', vendorDetailsSearchTableCreatorFile, 'vendorDetailsTable');1454			reportsPurchaseTableCreator('purchaseReportsTableDiv', purchaseReportsSearchTableCreatorFile, 'purchaseReportsTable');1455			reportsTableCreator('vendorReportsTableDiv', vendorReportsSearchTableCreatorFile, 'vendorReportsTable');1456		}1457	});1458}1459// Function to call the updatePurchase.php script to update purchase data to db1460function updatePurchase() {1461	var purchaseDetailsItemNumber = $('#purchaseDetailsItemNumber').val();1462	var purchaseDetailsPurchaseDate = $('#purchaseDetailsPurchaseDate').val();1463	var purchaseDetailsItemName = $('#purchaseDetailsItemName').val();1464	var purchaseDetailsQuantity = $('#purchaseDetailsQuantity').val();1465	var purchaseDetailsUnitPrice = $('#purchaseDetailsUnitPrice').val();1466	var purchaseDetailsPurchaseID = $('#purchaseDetailsPurchaseID').val();1467	var purchaseDetailsVendorName = $('#purchaseDetailsVendorName').val();1468	1469	$.ajax({1470		url: 'model/purchase/updatePurchase.php',1471		method: 'POST',1472		data: {1473			purchaseDetailsItemNumber:purchaseDetailsItemNumber,1474			purchaseDetailsPurchaseDate:purchaseDetailsPurchaseDate,1475			purchaseDetailsItemName:purchaseDetailsItemName,1476			purchaseDetailsQuantity:purchaseDetailsQuantity,1477			purchaseDetailsUnitPrice:purchaseDetailsUnitPrice,1478			purchaseDetailsPurchaseID:purchaseDetailsPurchaseID,1479			purchaseDetailsVendorName:purchaseDetailsVendorName,1480		},1481		success: function(data){1482			$('#purchaseDetailsMessage').fadeIn();1483			$('#purchaseDetailsMessage').html(data);1484		},1485		complete: function(){1486			getItemStockToPopulate('purchaseDetailsItemNumber', getItemStockFile, 'purchaseDetailsCurrentStock');1487			searchTableCreator('purchaseDetailsTableDiv', purchaseDetailsSearchTableCreatorFile, 'purchaseDetailsTable');1488			reportsPurchaseTableCreator('purchaseReportsTableDiv', purchaseReportsSearchTableCreatorFile, 'purchaseReportsTable');1489			searchTableCreator('itemDetailsTableDiv', itemDetailsSearchTableCreatorFile, 'itemDetailsTable');1490			reportsTableCreator('itemReportsTableDiv', itemReportsSearchTableCreatorFile, 'itemReportsTable');1491		}1492	});1493}1494// Function to call the updateSale.php script to update sale data to db1495function updateSale() {1496	var saleDetailsItemNumber = $('#saleDetailsItemNumber').val();1497	var saleDetailsSaleDate = $('#saleDetailsSaleDate').val();1498	var saleDetailsItemName = $('#saleDetailsItemName').val();1499	var saleDetailsQuantity = $('#saleDetailsQuantity').val();1500	var saleDetailsUnitPrice = $('#saleDetailsUnitPrice').val();1501	var saleDetailsSaleID = $('#saleDetailsSaleID').val();1502	var saleDetailsCustomerName = $('#saleDetailsCustomerName').val();1503	var saleDetailsDiscount = $('#saleDetailsDiscount').val();1504	var saleDetailsCustomerID = $('#saleDetailsCustomerID').val();1505	1506	$.ajax({1507		url: 'model/sale/updateSale.php',1508		method: 'POST',1509		data: {1510			saleDetailsItemNumber:saleDetailsItemNumber,1511			saleDetailsSaleDate:saleDetailsSaleDate,1512			saleDetailsItemName:saleDetailsItemName,1513			saleDetailsQuantity:saleDetailsQuantity,1514			saleDetailsUnitPrice:saleDetailsUnitPrice,1515			saleDetailsSaleID:saleDetailsSaleID,1516			saleDetailsCustomerName:saleDetailsCustomerName,1517			saleDetailsDiscount:saleDetailsDiscount,1518			saleDetailsCustomerID:saleDetailsCustomerID,1519		},1520		success: function(data){1521			$('#saleDetailsMessage').fadeIn();1522			$('#saleDetailsMessage').html(data);1523		},1524		complete: function(){			1525			getItemStockToPopulate('saleDetailsItemNumber', getItemStockFile, 'saleDetailsTotalStock');1526			searchTableCreator('saleDetailsTableDiv', saleDetailsSearchTableCreatorFile, 'saleDetailsTable');1527			reportsSaleTableCreator('saleReportsTableDiv', saleReportsSearchTableCreatorFile, 'saleReportsTable');1528			searchTableCreator('itemDetailsTableDiv', itemDetailsSearchTableCreatorFile, 'itemDetailsTable');1529			reportsTableCreator('itemReportsTableDiv', itemReportsSearchTableCreatorFile, 'itemReportsTable');1530		}1531	});...feedback_conversion_2017-11-12.py
Source:feedback_conversion_2017-11-12.py  
1#Python 3+ Script for jsonifying feedback table data as of 2017-11-12 made by Jordie06082#Apologies for the boilerplated and squirrely code in parts, this has been my first foray into python3#4#Before starting ensure you have installed the mysqlclient package https://github.com/PyMySQL/mysqlclient-python5#It can be downloaded from command line with pip:6#pip install mysqlclient7#8#tgstation no longer supports MySQL which has been superseded by MariaDB, a drop-in replacement.9#Before running this script you will need to migrate to MariaDB.10#Migrating is very easy to do, for details on how see: https://mariadb.com/kb/en/library/upgrading-from-mysql-to-mariadb/11#12#You will also have to create a new feedback table for inserting converted data to per the schema:13#CREATE TABLE `feedback_new` (14#  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,15#  `datetime` datetime NOT NULL,16#  `round_id` int(11) unsigned NOT NULL,17#  `key_name` varchar(32) NOT NULL,18#  `key_type` enum('text', 'amount', 'tally', 'nested tally', 'associative') NOT NULL,19#  `version` tinyint(3) unsigned NOT NULL,20#  `json` json NOT NULL,21#  PRIMARY KEY (`id`)22#) ENGINE=MyISAM23#This is to prevent the destruction of legacy data and allow rollbacks to be performed in the event of an error during conversion24#Once conversion is complete remember to rename the old and new feedback tables; it's up to you if you want to keep the old table25#26#To view the parameters for this script, execute it with the argument --help27#All the positional arguments are required, remember to include prefixes in your table names if you use them28#An example of the command used to execute this script from powershell:29#python feedback_conversion_2017-11-12.py "localhost" "root" "password" "feedback" "SS13_feedback" "SS13_feedback_new"30#I found that this script would complete conversion of 10000 rows approximately every 2-3 seconds31#Depending on the size of your feedback table and the computer used it may take several minutes for the script to finish32#33#The script has been tested to complete with tgstation's feedback table as of 2017-10-23 01:34:0634#Due to the complexity of data that has potentially changed formats multiple times and suffered errors when recording I cannot guarantee it'll always execute successfully35#In the event of an error the new feedback table is automatically truncated36#The source table is never modified so you don't have to worry about losing any data due to errors37#Note that some feedback keys are renamed or coalesced into one, additionnaly some have been entirely removed38#39#While this script can be run with your game server(s) active, it may interfere with other database operations and any feedback created after the script has started won't be converted40import MySQLdb41import argparse42import json43import re44import sys45from datetime import datetime46def parse_text(details):47    if not details:48        return49    if details.startswith('"') and details.endswith('"'):50        details = details[1:-1] #the first and last " aren't removed by splitting the dictionary51        details = details.split('" | "')52    else:53        if "_" in details:54            details = details.split(' ')55    return details56def parse_tally(details):57    if not details:58        return59    overflowed = None60    if len(details) >= 65535: #a string this long means the data hit the 64KB character limit of TEXT columns61        overflowed = True62    if details.startswith('"') and details.endswith('"'):63        details = details[details.find('"')+1:details.rfind('"')] #unlike others some of the tally data has extra characters to remove64        split_details = details.split('" | "')65    else:66        split_details = details.split(' ')67    if overflowed:68        split_details = split_details[:-1] #since the string overflowed the last element will be incomplete and needs to be ignored69    details = {}70    for i in split_details:71        increment = 172        if '|' in i and i[i.find('|')+1:]:73            increment = float(i[i.find('|')+1:])74            i = i[:i.find('|')]75        if i in details:76            details[i] += increment77        else:78            details[i] = increment79    for i in details:80        details[i] = '{0:g}'.format(details[i]) #remove .0 from floats that have it to conform with DM81    return details82def parse_nested(var_name, details):83    if not details:84        return85    #group by data before pipe86    if var_name in ("admin_toggle", "preferences_verb", "changeling_objective", "cult_objective", "traitor_objective", "wizard_objective", "mining_equipment_bought", "vending_machine_usage", "changeling_powers", "wizard_spell_improved", "testmerged_prs"):87        if details.startswith('"') and details.endswith('"'):88            details = details[1:-1]89            split_details = details.split('" | "')90        else:91            split_details = details.split(' ')92        details = {}93        for i in split_details:94            if "|" in i and i[:i.find('|')] not in details:95                details[i[:i.find('|')]] = {}96            elif "|" not in i and i[i.find('|')+1:] not in details:97                details[i[i.find('|')+1:]] = 098        for i in split_details:99            if "|" in i:100                if details[i[:i.find('|')]] is not dict:101                    continue102                if i[i.find('|')+1:] in details[i[:i.find('|')]]:103                    details[i[:i.find('|')]][i[i.find('|')+1:]] += 1104                else:105                    details[i[:i.find('|')]][i[i.find('|')+1:]] = 1106            else:107                if i in details and type(details[i]) is not dict: #sometimes keys that should have a value after a pipe just don't and would otherwise error here108                    details[i] += 1109        return details110    #group by data after pipe111    elif var_name in ("cargo_imports", "traitor_uplink_items_bought", "export_sold_cost", "item_used_for_combat", "played_url"):112        if details.startswith('"') and details.endswith('"'):113            details = details[1:-1]114            split_details = details.split('" | "')115        else:116            split_details = details.split(' ')117        details = {}118        for i in split_details:119            if i == i[i.rfind('|')+1:]: #there's no pipe and data to group by, so we fill it in120                i = "{0}|missing data".format(i)121            details[i[i.rfind('|')+1:]] = {}122        for i in split_details:123            if i == i[i.rfind('|')+1:]:124                i = "{0}|missing data".format(i)125            if i[:i.find('|')] in details[i[i.rfind('|')+1:]]:126                details[i[i.rfind('|')+1:]][i[:i.find('|')]] += 1127            else:128                details[i[i.rfind('|')+1:]][i[:i.find('|')]] = 1129        return details130    elif var_name == "hivelord_core":131        if details.startswith('"') and details.endswith('"'):132            details = details[1:-1]133            split_details = details.split('" | "')134        else:135            split_details = details.split(' ')136        details = {}137        for i in split_details:138            if i[:i.find('|')] not in details:139                details[i[:i.find('|')]] = {}140                if "used" in i:141                    if "used" not in details:142                        details[i[:i.find('|')]]["used"] = {}143        for i in split_details:144            if "used" in i:145                if "used" not in details[i[:i.find('|')]]:146                    details[i[:i.find('|')]]["used"] = {}147                    details[i[:i.find('|')]]["used"][i[i.rfind('|')+1:]] = 1148                else:149                    if i[i.rfind('|')+1:] in details[i[:i.find('|')]]["used"]:150                        details[i[:i.find('|')]]["used"][i[i.rfind('|')+1:]] += 1151                    else:152                        details[i[:i.find('|')]]["used"][i[i.rfind('|')+1:]] = 1153            elif "|" in i:154                if i[i.find('|')+1:] in details[i[:i.find('|')]]:155                    details[i[:i.find('|')]][i[i.find('|')+1:]] += 1156                else:157                    details[i[:i.find('|')]][i[i.find('|')+1:]] = 1158        return details159    elif var_name == "job_preferences":160        if details.startswith('"') and details.endswith('"'):161            details = details[1:-1]162            split_details = details.split('|-" | "|')163        else:164            split_details = details.split('|- |')165        details = {}166        for i in split_details:167            if i.startswith('|'):168                i = i[1:]169            if i[:i.find('|')] not in details:170                details[i[:i.find('|')]] = {}171        for i in split_details:172            if i.startswith('|'):173                i = i[1:]174            if i.endswith('-'):175                i = i[:-2]176            sub_split = i.split('|')177            job = sub_split[0]178            sub_split = sub_split[1:]179            for o in sub_split:180                details[job][o[:o.find('=')].lower()] = o[o.find('=')+1:]181        return details182def parse_associative(var_name, details):183    if not details:184        return185    if var_name == "colonies_dropped":186        if details.startswith('"') and details.endswith('"'):187            details = details[1:-1]188        split_details = details.split('|')189        details = {}190        details["1"] = {"x" : split_details[0], "y" : split_details[1], "z" : split_details[2]}191        return details192    elif var_name == "commendation":193        if details.startswith('"') and details.endswith('"'):194            details = details[1:-1]195        if '}" | "{' in details:196            split_details = details.split('}" | "{')197        else:198            split_details = details.split('} {')199        details = {}200        for i in split_details:201            params = []202            sub_split = i.split(',')203            for o in sub_split:204                o = re.sub('[^A-Za-z0-9 ]', '', o[o.find(':')+1:]) #remove all the formatting and escaped characters from being pre-encoded as json205                params.append(o)206            details[len(details)+1] = {"commender" : params[0], "commendee" : params[1], "medal" : params[2], "reason" : params[3]}207        return details208    elif var_name == "high_research_level":209        if details.startswith('"') and details.endswith('"'):210            details = details[1:-1]211            split_details = details.split('" | "')212        else:213            split_details = details.split(' ')214        details = {}215        levels = {}216        for i in split_details:217            x = {i[:-1] : i[-1:]}218            levels.update(x)219        details["1"] = levels220        return details221def parse_special(var_name, var_value, details):222    #old data is essentially a tally in text form223    if var_name == "immortality_talisman":224        if details.startswith('"') and details.endswith('"'):225            split_details = details.split('" | "')226        else:227            split_details = details.split(' ')228        return len(split_details)229    #now records channel names, so we have to fill in whats missing230    elif var_name == "newscaster_channels":231        details = ["missing data"]232        details *= var_value233        return details234    #all the channels got renamed, plus we ignore any with an amount of zero235    elif var_name == "radio_usage":236        if details.startswith('"') and details.endswith('"'):237            details = details[details.find('C'):-1]238            split_details = details.split('" | "')239        else:240            split_details = details.split(' ')241        details = {}242        new_keys = {"COM":"common", "SCI":"science", "HEA":"command", "MED":"medical", "ENG":"engineering", "SEC":"security", "DTH":"centcom", "SYN":"syndicate", "SRV":"service", "CAR":"supply", "OTH":"other", "PDA":"PDA", "RC":"request console"}243        for i in split_details:244            if i.endswith('0'):245                continue246            if i[:i.find('-')] not in new_keys:247                continue248            details[new_keys[i[:i.find('-')]]] = i[i.find('-')+1:]249        return details250    #all of the data tracked by this is invalid due to recording the incorrect type251    elif var_name == "shuttle_gib":252        return {"missing data":1}253    #all records have a  prefix of 'slimebirth_' that needs to be removed254    elif var_name == "slime_babies_born":255        if details.startswith('"') and details.endswith('"'):256            details = details[1:-1]257            split_details = details.split('" | "')258        else:259            split_details = details.split(' ')260        details = {}261        for i in split_details:262            if i[i.find('_')+1:].replace('_', ' ') in details:263                details[i[i.find('_')+1:].replace('_', ' ')] += 1264            else:265                details[i[i.find('_')+1:].replace('_', ' ')] = 1266        return details267    #spaces were replaced by underscores, we need to undo this268    elif var_name == "slime_core_harvested":269        if details.startswith('"') and details.endswith('"'):270            details = details[1:-1]271            split_details = details.split('" | "')272        else:273            split_details = details.split(' ')274        details = {}275        for i in split_details:276            if i.replace('_', ' ') in details:277                details[i.replace('_', ' ')] += 1278            else:279                details[i.replace('_', ' ')] = 1280        return details281def parse_multirow(var_name, var_value, details, multirows_completed):282    if var_name in ("ahelp_close", "ahelp_icissue", "ahelp_reject", "ahelp_reopen", "ahelp_resolve", "ahelp_unresolved"):283        ahelp_vars = {"ahelp_close":"closed", "ahelp_icissue":"IC", "ahelp_reject":"rejected", "ahelp_reopen":"reopened", "ahelp_resolve":"resolved", "ahelp_unresolved":"unresolved"}284        details = {ahelp_vars[var_name]:var_value}285        del ahelp_vars[var_name]286        query_where = "round_id = {0} AND (".format(query_row[2])287        for c, i in enumerate(ahelp_vars):288            if c:289                query_where += " OR "290            query_where += "var_name = \"{0}\"".format(i)291        query_where += ")"292        cursor.execute("SELECT var_name, var_value FROM {0} WHERE {1}".format(current_table, query_where))293        rows = cursor.fetchall()294        if rows:295            for r in rows:296                details[ahelp_vars[r[0]]] = r[1]297        keys = list(ahelp_vars.keys())298        keys.append(var_name)299        multirows_completed += keys300        return details301    elif var_name in ("alert_comms_blue", "alert_comms_green"):302        level_vars = {"alert_comms_blue":"1", "alert_comms_green":"0"}303        details = {level_vars[var_name]:var_value}304        del  level_vars[var_name]305        i = list(level_vars)[0]306        cursor.execute("SELECT var_value FROM {0} WHERE round_id = {1} AND var_name = \"{2}\"".format(current_table, query_row[2], i))307        row = cursor.fetchone()308        if row:309            details[level_vars[i]] = row[0]310        keys = list(level_vars.keys())311        keys.append(var_name)312        multirows_completed += keys313        return details314    elif var_name in ("alert_keycard_auth_bsa", "alert_keycard_auth_maint"):315        auth_vars = {"alert_keycard_auth_maint":("emergency maintenance access", "enabled"), "alert_keycard_auth_bsa":("bluespace artillery", "unlocked")}316        i = list(auth_vars[var_name])317        details = {i[0]:{i[1]:var_value}}318        del auth_vars[var_name]319        i = list(auth_vars)[0]320        cursor.execute("SELECT var_value FROM {0} WHERE round_id = {1} AND var_name = \"{2}\"".format(current_table, query_row[2], i))321        row = cursor.fetchone()322        if row:323            o = list(auth_vars[i])324            details[o[0]] = {o[1]:row[0]}325        keys = list(auth_vars.keys())326        keys.append(var_name)327        multirows_completed += keys328        return details329    elif var_name in ("arcade_loss_hp_emagged", "arcade_loss_hp_normal", "arcade_loss_mana_emagged", "arcade_loss_mana_normal", "arcade_win_emagged", "arcade_win_normal"):330        result_vars = {"arcade_loss_hp_emagged":("loss", "hp", "emagged"), "arcade_loss_hp_normal":("loss", "hp", "normal"), "arcade_loss_mana_emagged":("loss", "mana", "emagged"), "arcade_loss_mana_normal":("loss", "mana", "normal"), "arcade_win_emagged":("win", "emagged"), "arcade_win_normal":("win", "normal")}331        i = list(result_vars[var_name])332        del result_vars[var_name]333        if i[0] == "loss":334            details = {i[0]:{i[1]:{i[2]:var_value}}}335        else:336            details = {i[0]:{i[1]:var_value}}337        query_where = "round_id = {0} AND (".format(query_row[2])338        for c, i in enumerate(result_vars):339            if c:340                query_where += " OR "341            query_where += "var_name = \"{0}\"".format(i)342        query_where += ")"343        cursor.execute("SELECT var_name, var_value FROM {0} WHERE {1}".format(current_table, query_where))344        rows = cursor.fetchall()345        if rows:346            for r in rows:347                i = list(result_vars[r[0]])348                if i[0] not in details:349                    details[i[0]] = {}350                if i[0] == "loss":351                    if i[1] not in details[i[0]]:352                        details[i[0]][i[1]] = {}353                    details[i[0]][i[1]][i[2]] = r[1]354                else:355                    details[i[0]][i[1]] = r[1]356        keys = list(result_vars.keys())357        keys.append(var_name)358        multirows_completed += keys359        return details360    elif var_name in ("cyborg_engineering", "cyborg_janitor", "cyborg_medical", "cyborg_miner", "cyborg_peacekeeper", "cyborg_security", "cyborg_service", "cyborg_standard"):361        module_vars = {"cyborg_engineering":"Engineering", "cyborg_janitor":"Janitor", "cyborg_medical":"Medical", "cyborg_miner":"Miner", "cyborg_peacekeeper":"Peacekeeper", "cyborg_security":"Security", "cyborg_service":"Service", "cyborg_standard":"Standard"}362        details = {module_vars[var_name]:var_value}363        del module_vars[var_name]364        query_where = "round_id = {0} AND (".format(query_row[2])365        for c, i in enumerate(module_vars):366            if c:367                query_where += " OR "368            query_where += "var_name = \"{0}\"".format(i)369        query_where += ")"370        cursor.execute("SELECT var_name, var_value FROM {0} WHERE {1}".format(current_table, query_where))371        rows = cursor.fetchall()372        if rows:373            for r in rows:374                details[module_vars[r[0]]] = r[1]375        keys = list(module_vars.keys())376        keys.append(var_name)377        multirows_completed += keys378        return details379    elif var_name in ("escaped_human", "escaped_total", "round_end_clients", "round_end_ghosts", "survived_human", "survived_total"):380        round_vars = {"escaped_human":("escapees", "human"), "escaped_total":("escapees", "total"), "round_end_clients":("clients"), "round_end_ghosts":("ghosts"), "survived_human":("survivors", "human"), "survived_total":("survivors", "total")}381        if var_name in ("round_end_clients", "round_end_ghosts"):382            i = round_vars[var_name]383            details = {i:var_value}384        else:385            i = list(round_vars[var_name])386            details = {i[0]:{i[1]:var_value}}387        del round_vars[var_name]388        query_where = "round_id = {0} AND (".format(query_row[2])389        for c, i in enumerate(round_vars):390            if c:391                query_where += " OR "392            query_where += "var_name = \"{0}\"".format(i)393        query_where += ")"394        cursor.execute("SELECT var_name, var_value FROM {0} WHERE {1}".format(current_table, query_where))395        rows = cursor.fetchall()396        if rows:397            for r in rows:398                if r[0] in ("round_end_clients", "round_end_ghosts"):399                    i = round_vars[r[0]]400                    details[i] = r[1]401                else:402                    i = list(round_vars[r[0]])403                    if i[0] not in details:404                        details[i[0]] = {}405                    details[i[0]][i[1]] = r[1]406        keys = list(round_vars.keys())407        keys.append(var_name)408        multirows_completed += keys409        return details410    elif var_name in ("mecha_durand_created", "mecha_firefighter_created", "mecha_gygax_created", "mecha_honker_created", "mecha_odysseus_created", "mecha_phazon_created", "mecha_ripley_created"):411        mecha_vars ={"mecha_durand_created":"Durand", "mecha_firefighter_created":"APLU \"Firefighter\"", "mecha_gygax_created":"Gygax", "mecha_honker_created":"H.O.N.K", "mecha_odysseus_created":"Odysseus", "mecha_phazon_created":"Phazon", "mecha_ripley_created":"APLU \"Ripley\""}412        details = {mecha_vars[var_name]:var_value}413        del mecha_vars[var_name]414        query_where = "round_id = {0} AND (".format(query_row[2])415        for c, i in enumerate(mecha_vars):416            if c:417                query_where += " OR "418            query_where += "var_name = \"{0}\"".format(i)419        query_where += ")"420        cursor.execute("SELECT var_name, var_value FROM {0} WHERE {1}".format(current_table, query_where))421        rows = cursor.fetchall()422        if rows:423            for r in rows:424                details[mecha_vars[r[0]]] = r[1]425        keys = list(mecha_vars.keys())426        keys.append(var_name)427        multirows_completed += keys428        return details429def pick_parsing(var_name, var_value, details, multirows_completed):430    if var_name in text_keys:431        return parse_text(details)432    elif var_name in amount_keys:433        return var_value434    elif var_name in simple_tallies:435        return parse_tally(details)436    elif var_name in nested_tallies:437        return parse_nested(var_name, details)438    elif var_name in associatives:439        return parse_associative(var_name, details)440    elif var_name in special_cases:441        return parse_special(var_name, var_value, details)442    elif var_name in multirow:443        return parse_multirow(var_name, var_value, details, multirows_completed)444    else:445        return False446if sys.version_info[0] < 3:447    raise Exception("Python must be at least version 3 for this script.")448text_keys = ["religion_book", "religion_deity", "religion_name", "shuttle_fasttravel", "shuttle_manipulator", "shuttle_purchase", "shuttle_reason", "station_renames"]449amount_keys = ["admin_cookies_spawned", "cyborg_ais_created", "cyborg_frames_built", "cyborg_mmis_filled", "newscaster_newspapers_printed", "newscaster_stories", "nuclear_challenge_mode"]450simple_tallies = ["admin_secrets_fun_used", "admin_verb", "assembly_made", "brother_success", "cell_used", "changeling_power_purchase", "changeling_success", "chaplain_weapon", "chemical_reaction", "circuit_printed", "clockcult_scripture_recited", "contamination", "cult_runes_scribed", "engine_started", "event_admin_cancelled", "event_ran", "food_harvested", "food_made", "gun_fired", "handcuffs", "item_deconstructed", "item_printed", "jaunter", "lazarus_injector", "megafauna_kills", "mining_voucher_redeemed", "mobs_killed_mining", "object_crafted", "ore_mined", "pick_used_mining", "slime_cores_used", "surgeries_completed", "time_dilation_current", "traitor_random_uplink_items_gotten", "traitor_success", "voice_of_god", "warp_cube", "wisp_lantern", "wizard_spell_learned", "wizard_success", "zone_targeted"]451nested_tallies = ["admin_toggle", "cargo_imports", "changeling_objective", "changeling_powers", "cult_objective", "export_sold_cost", "hivelord_core", "item_used_for_combat", "job_preferences", "mining_equipment_bought", "played_url", "preferences_verb", "testmerged_prs", "traitor_objective", "traitor_uplink_items_bought", "vending_machine_usage", "wizard_objective", "wizard_spell_improved"]452associatives = ["colonies_dropped", "commendation", "high_research_level"]453special_cases = ["immortality_talisman", "newscaster_channels", "radio_usage", "shuttle_gib", "slime_babies_born", "slime_core_harvested"]454multirow = ["ahelp_close", "ahelp_icissue", "ahelp_reject", "ahelp_reopen", "ahelp_resolve", "ahelp_unresolved", "alert_comms_blue", "alert_comms_green", "alert_keycard_auth_bsa", "alert_keycard_auth_maint", "arcade_loss_hp_emagged", "arcade_loss_hp_normal", "arcade_loss_mana_emagged", "arcade_loss_mana_normal", "arcade_win_emagged", "arcade_win_normal", "cyborg_engineering", "cyborg_janitor", "cyborg_medical", "cyborg_miner", "cyborg_peacekeeper", "cyborg_security", "cyborg_service", "cyborg_standard", "escaped_human", "escaped_total", "mecha_durand_created", "mecha_firefighter_created", "mecha_gygax_created", "mecha_honker_created", "mecha_odysseus_created", "mecha_phazon_created", "mecha_ripley_created", "round_end_clients", "round_end_ghosts", "survived_human", "survived_total"]455renames = {"ahelp_stats":["ahelp_close", "ahelp_icissue", "ahelp_reject", "ahelp_reopen", "ahelp_resolve", "ahelp_unresolved"], "ais_created":["cyborg_ais_created"], "arcade_results":["arcade_loss_hp_emagged", "arcade_loss_hp_normal", "arcade_loss_mana_emagged", "arcade_loss_mana_normal", "arcade_win_emagged", "arcade_win_normal"], "cyborg_modules":["cyborg_engineering", "cyborg_janitor", "cyborg_medical", "cyborg_miner", "cyborg_peacekeeper", "cyborg_security", "cyborg_service", "cyborg_standard"], "immortality_talisman_uses":["immortality_talisman"], "keycard_auths":["alert_keycard_auth_bsa", "alert_keycard_auth_maint"], "mechas_created":["mecha_durand_created", "mecha_firefighter_created", "mecha_gygax_created", "mecha_honker_created", "mecha_odysseus_created", "mecha_phazon_created", "mecha_ripley_created"], "mmis_filled":["cyborg_mmis_filled"], "newspapers_printed":["newscaster_newspapers_printed"], "round_end_stats":["escaped_human", "escaped_total", "round_end_clients", "round_end_ghosts", "survived_human", "survived_total"], "security_level_changes":["alert_comms_blue", "alert_comms_green"]}456key_types = {"amount":["ais_created", "immortality_talisman_uses", "mmis_filled", "newspapers_printed", "admin_cookies_spawned", "cyborg_frames_built", "newscaster_stories", "nuclear_challenge_mode"],457"associative":["colonies_dropped", "commendation", "high_research_level"],458"nested tally":["admin_toggle", "arcade_results", "cargo_imports", "changeling_objective", "changeling_powers", "cult_objective", "export_sold_cost", "hivelord_core", "item_used_for_combat", "job_preferences", "keycard_auths", "mining_equipment_bought", "played_url", "preferences_verb", "round_end_stats", "testmerged_prs", "traitor_objective", "traitor_uplink_items_bought", "vending_machine_usage", "wizard_objective", "wizard_spell_improved"],459"tally":[ "admin_secrets_fun_used", "admin_verb", "ahelp_stats", "assembly_made", "brother_success", "cell_used", "changeling_power_purchase", "changeling_success", "chaplain_weapon", "chemical_reaction", "circuit_printed", "clockcult_scripture_recited", "contamination", "cult_runes_scribed", "cyborg_modules", "engine_started", "event_admin_cancelled", "event_ran", "food_harvested", "food_made", "gun_fired", "handcuffs", "item_deconstructed", "item_printed", "jaunter", "lazarus_injector", "mechas_created", "megafauna_kills", "mining_voucher_redeemed", "mobs_killed_mining", "object_crafted", "ore_mined", "pick_used_mining", "radio_usage", "security_level_changes", "shuttle_gib", "slime_babies_born", "slime_cores_used", "slime_core_harvested", "surgeries_completed", "time_dilation_current", "traitor_random_uplink_items_gotten", "traitor_success", "voice_of_god", "warp_cube", "wisp_lantern", "wizard_spell_learned", "wizard_success", "zone_targeted"],460"text":["shuttle_fasttravel", "shuttle_manipulator", "shuttle_purchase", "shuttle_reason", "newscaster_channels", "religion_book", "religion_deity", "religion_name", "station_renames"]}461multirows_completed = []462query_values = ""463current_round = 0464parser = argparse.ArgumentParser()465parser.add_argument("address", help="MySQL server address (use localhost for the current computer)")466parser.add_argument("username", help="MySQL login username")467parser.add_argument("password", help="MySQL login username")468parser.add_argument("database", help="Database name")469parser.add_argument("curtable", help="Name of the current feedback table (remember prefixes if you use them)")470parser.add_argument("newtable", help="Name of the new table to insert to, can't be same as the source table (remember prefixes)")471args = parser.parse_args()472db=MySQLdb.connect(host=args.address, user=args.username, passwd=args.password, db=args.database)473cursor=db.cursor()474cursor.execute("SELECT @@GLOBAL.version_comment")475db_version = "".join([x for x in cursor.fetchone()])476database_mysql = False477if 'MySQL' in db_version:478    database_mysql = True479elif 'mariadb' not in db_version:480    choice = input("Unable to determine database version installed, are you using MySQL? Type Yes or No and press enter...").lower()481    if choice == "yes":482        database_mysql = True483if database_mysql == True:484    print("WARNING Database detected to be MySQL: tgstation no longer supports MySQL which has been superseded by MariaDB, a drop-in replacement.\nBefore running this script you will need to migrate to MariaDB.\nMigrating is very easy to do, for details on how see: https://mariadb.com/kb/en/library/upgrading-from-mysql-to-mariadb/")485    input("Press enter to quit...")486    quit()487current_table = args.curtable488new_table = args.newtable489cursor.execute("SELECT max(id), max(round_id) FROM {0}".format(current_table))490query_id = cursor.fetchone()491max_id = query_id[0]492max_round_id = query_id[1]493start_time = datetime.now()494print("Beginning conversion at {0}".format(start_time.strftime("%Y-%m-%d %H:%M:%S")))495try:496    for current_id in range(max_id):497        if current_id % 10000 == 0:498            cur_time = datetime.now()499            print("Reached row ID {0} Duration: {1}".format(current_id, cur_time - start_time))500        cursor.execute("SELECT * FROM {0} WHERE id = {1}".format(current_table, current_id))501        query_row = cursor.fetchone()502        if not query_row:503            continue504        else:505            if current_round != query_row[2] or current_round == max_round_id:506                multirows_completed.clear()507                if query_values:508                    query_values = query_values[:-1]509                    query_values += ';'510                    cursor.execute("INSERT INTO {0} (datetime, round_id, key_name, key_type, version, json) VALUES {1}".format(new_table, query_values))511                    query_values = ""512            current_round = query_row[2]513            if query_row[3] in multirows_completed:514                continue515            parsed_data = pick_parsing(query_row[3], query_row[4], query_row[5], multirows_completed)516            if not parsed_data:517                continue518            json_data = {}519            json_data["data"] = parsed_data520            new_key = query_row[3]521            for r in renames:522                if new_key in renames[r]:523                    new_key = r524                    break525            new_key_type = None526            for t in key_types:527                if new_key in key_types[t]:528                    new_key_type = t529                    break530            dequoted_json = re.sub("\'", "\\'", json.dumps(json_data))531            query_values += "('{0}',{1},'{2}','{3}',{4},'{5}'),".format(query_row[1], query_row[2], new_key, new_key_type, 1, dequoted_json)532    end_time = datetime.now()533    print("Conversion completed at {0}".format(datetime.now().strftime("%Y-%m-%d %H:%M:%S")))534    print("Script duration: {0}".format(end_time - start_time))535except Exception as e:536    cursor.execute("SELECT round_id FROM {0} WHERE id = {1}".format(current_table, current_id-1))537    query_round_id = cursor.fetchone()538    end_time = datetime.now()539    print("Error encountered on row ID {0} at {1}".format(current_id, datetime.now().strftime("%Y-%m-%d %H:%M:%S")))540    print("Note SQL insertion errors will be due to data from round ID {0}".format(query_round_id[0])) #since data is inserted when the round id changes on a new row541    print("Script duration: {0}".format(end_time - start_time))542    cursor.execute("TRUNCATE {0} ".format(new_table))543    raise e...main2.py
Source:main2.py  
1import pyrebase2import os3from flask import Flask,render_template, request, redirect, session, url_for, flash4from datetime import date5#from firebase_admin import db6#from firebase import firebase7app = Flask(__name__)8app.secret_key = 'random string'9config = {10    "apiKey": "AIzaSyCAwWLzDUZ0dOT2PmeoMfaDi6P1KConsfY",11    "authDomain": "placement-maintenance.firebaseapp.com",12    "databaseURL": "https://placement-maintenance.firebaseio.com",13    "projectId": "placement-maintenance",14    "storageBucket": "placement-maintenance.appspot.com",15    "messagingSenderId": "462647699028",16    "appId": "1:462647699028:web:1e564d98447ec9a286afc1",17    "measurementId": "G-W39CEJ0LYT"18}19firebase = pyrebase.initialize_app(config)20auth = firebase.auth()21#database = firebase.database()22db = firebase.database()23personal_details=dict()24academic_details=dict()25comp_list=dict()26email=""27t_date = date.today().strftime("%Y-%m-%d")28today_date=t_date.split('-')29sel_comp=''30#import firebase_admin31#from firebase_admin import credentials32'''if (not len(firebase_admin._apps)):33    cred = credentials.Certificate('path/to/serviceAccountKey.json') 34    default_app = firebase_admin.initialize_app(cred)'''35@app.route("/")36def home():37        if session.get('email',False):38		return render_template('home3.html')39	return render_template('login.html')40@app.route('/login', methods=['GET', 'POST'])41def login():42	try:43		if (request.method == 'POST'):44			email = request.form['name']45			password = request.form['password']46			global company_details47			company_details=dict()48			data3=db.child("Companies").get()49                        for value3 in data3.each() :50                                company_details[value3.key()]=value3.val()51			if email == 'dlshreyas30@gmail.com' and password == '123456789' :52                                return render_template('admin_dashboard.html',company_details=company_details)53			#global usn54			#usn=request.form['f_usn']55			user = auth.sign_in_with_email_and_password(email, password)56			session['email'] = email57                        58			data=db.child("Student Details").get()59                        for value in data.each() :60                                st_data=db.child("Student Details").child(value.key()).child("Personal Details").get()61                                if st_data.val()['Email'] == email :62                                        for v in st_data.each() :63                                                personal_details[v.key()]=v.val()64                                        global usn65                                        usn=value.key()66                                        data2=db.child("Student Details").child(usn).child("Academic Details").get()67                                        for value2 in data2.each() :68                                                academic_details[value2.key()]=value2.val()69                        return redirect(url_for('dashboard'))70	except:71		#flash('Something went wrong!!')72                pass73	flash('Incorrect Mail or Password')74	return render_template('login.html')75@app.route('/register', methods=['GET', 'POST'])76def register():77	if (request.method == 'POST'):78		email = request.form['email']79		password1 = request.form['password']80		password2 = request.form['confirm_password']81                82		if password1 == password2 and password1!="" and email!="":83                        try :84                                user = auth.create_user_with_email_and_password(email, password1)85                                user = auth.refresh(user['refreshToken'])86                                auth.send_email_verification(user['idToken'])87                                user = auth.sign_in_with_email_and_password(email, password1)88                                session['email'] = email89                        except :90                                flash("Email ID already exists")91                                return render_template('register.html')92			global usn93			usn=request.form['usn']94			db.child("Student Details").child(usn).child("Personal Details").set({"First Name" : request.form['fname'].upper(),95                                                                                       "Last Name" : request.form['lname'].upper(),96                                                                                       "Father's Name" : request.form['f_fname'].upper(),97                                                                                       "DOB" : request.form['dd'],98                                                                                       "Gender" : request.form['gen'],99                                                                                       "Phone" : request.form['no'],100                                                                                       "Address" : request.form['add'],101                                                                                       "City" : request.form['city'].upper(),102                                                                                       "State" : request.form['state'].upper(),103                                                                                        "Email" : request.form['email']})104			db.child("Student Details").child(usn).child("Academic Details").child("10th Details").set(105                                                                                                           {106                                                                                                            "Board" : request.form['board'].upper(),107                                                                                                            "Aggregate" : request.form['aggregate'],108                                                                                                            "YOP" : request.form['yop']109                                                                                                            }110                                                                                                           )111                        db.child("Student Details").child(usn).child("Academic Details").child("12th Details").set(112                                                                                                            {113                                                                                                                "Board" : request.form['board2'].upper(),114                                                                                                               "Aggregate" : request.form['aggregate2'],115                                                                                                               "YOP" : request.form['yop2']116                                                                                                             }117                                                                                                           )118                        db.child("Student Details").child(usn).child("Academic Details").child("UG Details").set(119                                                                                                          {120                                                                                                                "USN":request.form['usn'],121                                                                                                                "Branch":request.form['branch'].upper(),122                                                                                                                "Sem":request.form['sem'],123                                                                                                                "CGPA":request.form['cgpa']124                                                                                                           }125                                                                                                        )126                        data=db.child("Student Details").child(usn).child("Personal Details").get()127                        for value in data.each() :128                                personal_details[value.key()]=value.val()129                        data2=db.child("Student Details").child(usn).child("Academic Details").get()130                        for value2 in data2.each() :131                                academic_details[value2.key()]=value2.val()132                        data3=db.child("Companies").get()133                        for value3 in data3.each() :134                                global company_details135                                company_details=dict()136                                company_details[value3.key()]=value3.val()137                        return redirect(url_for('dashboard'))138	return render_template('register.html')139@app.route("/forgot_password")140def forgot_password():141	return render_template('forgot_password.html')142@app.route("/forgot_form",methods=['GET', 'POST'])143def forgot_form():144	if (request.method == 'POST'):145		email = request.form['name']146		if email!="":147			auth.send_password_reset_email(email)148	return render_template('login.html')149@app.route("/logout")150def logout():151	session.pop(email,None)152	return render_template('login.html')153@app.route("/home")154def h():155        return render_template("home3.html")        156@app.route("/profile")157def profile():     158        return render_template('profile.html',personal_details=personal_details,academic_details=academic_details)159@app.route("/news")160def news():161        global company_details162	company_details=dict()163	data3=db.child("Companies").get()164        for value3 in data3.each() :165                company_details[value3.key()]=value3.val()166        global c_list167        c_list=[]168        d=db.child("Companies").get()169        for each_data in d.each():170            try :171                if usn in each_data.val()["Students"]:172                    c_list.append(each_data.key())173            except :174                pass175        #today_date=t_date.split('-')176        return render_template('news.html',company_details=company_details,academic_details=academic_details,c_list=c_list,today_date=today_date)177@app.route("/update",methods=['GET','POST'])178def update():179        db.child("Companies").child(request.form['comp_name']).child("Students").child(usn).set({"Name":personal_details['First Name']+" "+personal_details['Last Name']})180        flash("Applied for "+request.form['comp_name'])181        c_list.append(request.form['comp_name'])182        183        return render_template('news.html',company_details=company_details,academic_details=academic_details,c_list=c_list,today_date=today_date)184@app.route("/adminlogin")185def adminlogin():186        return render_template('adminlogin.html')187@app.route("/view_companies")188def view_companies():189        global company_details190        company_details=dict()191        data3=db.child("Companies").get()192        for value3 in data3.each() :193                company_details[value3.key()]=value3.val()194        return render_template('view_comp.html',company_details=company_details)195@app.route("/add_company",methods=['GET','POST'])196def add_company():197        if (request.method == 'POST') :198                db.child("Companies").child(request.form['comp_name']).set(199                                           { "Eligibility":200                                             { "Branch":request.form['comp_bran'],201                                               "GPA":request.form['comp_gpa'],202                                               "JOB ROLE":request.form['job_role'],203                                               "DRIVE DATE":request.form['drive_date']204                                                }})205                flash(request.form['comp_name']+" added")206                return render_template('add_comp.html',t_date=t_date)207        return render_template('add_comp.html',t_date=t_date)208@app.route("/reg_students",methods=['GET','POST'])209def reg_students():210        try:211                st_list=dict()212                reg_st=db.child("Companies").child(request.form['comp_name']).child("Students").get()213                for each_st in reg_st.each():214                        st_list[each_st.key()]=each_st.val()215                company_name=request.form['comp_name']216                return render_template('reg_students.html',st_list=st_list,company_name=company_name)217        except:218                flash("No Students registered for "+request.form['comp_name'])219                return render_template('view_comp.html',company_details=company_details)220@app.route("/dashboard")221def dashboard():222        global c_list223        c_list=[]224        global s_list225        s_list = []226        d=db.child("Companies").get()227        for each_data in d.each():228            try :229                if usn in each_data.val()["Students"]:230                    c_list.append(each_data.key())231                if usn in each_data.val()['Selected Students'] :232                	s_list.append(each_data.key())233            except :234                pass235        return render_template('dashboard.html',c_list=c_list,company_details=company_details,s_list = s_list)236@app.route("/upload",methods=['GET','POST'])237def upload():238        firebase_storage=firebase.storage()239        firebase_storage.child("Resume/"+usn+".pdf").put(request.files['fileToUpload'])240        return render_template("dashboard.html")241@app.route("/pro_update",methods=['GET','POST'])242def pro_update():243        if (request.method == 'POST') :244                global usn245		usn=request.form['usn']246		db.child("Student Details").child(usn).child("Personal Details").set({"First Name" : request.form['fname'].upper(),247                                                                                       "Last Name" : request.form['lname'].upper(),248                                                                                       "Father's Name" : request.form['f_fname'].upper(),249                                                                                       "DOB" : request.form['dd'],250                                                                                       "Gender" : request.form['gen'],251                                                                                       "Phone" : request.form['no'],252                                                                                       "Address" : request.form['add'],253                                                                                       "City" : request.form['city'].upper(),254                                                                                       "State" : request.form['state'].upper(),255                                                                                        "Email" : request.form['email']})256		db.child("Student Details").child(usn).child("Academic Details").child("10th Details").set(257                                                                                                           {258                                                                                                            "Board" : request.form['board'].upper(),259                                                                                                            "Aggregate" : request.form['aggregate'],260                                                                                                            "YOP" : request.form['yop']261                                                                                                            }262                                                                                                           )263                db.child("Student Details").child(usn).child("Academic Details").child("12th Details").set(264                                                                                                            {265                                                                                                                "Board" : request.form['board2'].upper(),266                                                                                                               "Aggregate" : request.form['aggregate2'],267                                                                                                               "YOP" : request.form['yop2']268                                                                                                             }269                                                                                                           )270                db.child("Student Details").child(usn).child("Academic Details").child("UG Details").set(271                                                                                                          {272                                                                                                                "USN":request.form['usn'],273                                                                                                                "Branch":request.form['branch'].upper(),274                                                                                                                "Sem":request.form['sem'],275                                                                                                                "CGPA":request.form['cgpa']276                                                                                                           }277                                                                                                        )278                data=db.child("Student Details").child(usn).child("Personal Details").get()279                for value in data.each() :280                        personal_details[value.key()]=value.val()281                data2=db.child("Student Details").child(usn).child("Academic Details").get()282                for value2 in data2.each() :283                        academic_details[value2.key()]=value2.val()284                data3=db.child("Companies").get()285                for value3 in data3.each() :286                        global company_details287                        company_details=dict()288                        company_details[value3.key()]=value3.val()289                        290                return render_template('profile.html',personal_details=personal_details,academic_details=academic_details)291        return render_template('profile.html',personal_details=personal_details,academic_details=academic_details)292@app.route('/add_selected_students',methods=['GET','POST'])293def add_selected_students():294    try :295        if request.method == 'POST' :296            global sel_comp297            sel_comp = request.form['sel_comp']298            data = db.child("Companies").child(sel_comp).child("Students").get()299            reg_students=dict()300            for value in data.each() :301                reg_students[value.key()] = value.val()302            return render_template('add_selected_students2.html',reg_students=reg_students)303    except:304        flash('No Students Registered!!!')305    return render_template('add_selected_students.html',company_details=company_details)306@app.route('/up_selected_students',methods=['GET','POST'])307def up_selected_students():308    if request.method == 'POST' :309        data = request.form.getlist('sel_students')310        sel_students = dict() 311        for value in data :312            data2 = value.split('|')313            sel_students[data2[0]] = data2[1]314        for key,value in sel_students.items() :315            db.child('Companies').child(sel_comp).child('Selected Students').child(key).set(316                                                                                            {317                                                                                                'Name' : value318                                                                                            }319                                                                                        )320        flash('Selected students for '+sel_comp+' added')321        return redirect(url_for('add_selected_students'))322    return redirect(url_for('add_selected_students'))323@app.route('/view_graph')324def view_graph():325    return render_template('view_graph.html')326                        327@app.route('/admin_dashboard')328def admin_dashboard() :329	global company_details330	company_details = dict()331	data3=db.child("Companies").get()332	for value3 in data3.each() :333		company_details[value3.key()]=value3.val()334	return render_template('admin_dashboard.html',company_details=company_details)335@app.route('/get_sel_students',methods=['GET','POST'])336def get_sel_students() :337	try:338		st_list=dict()339		reg_st = db.child("Companies").child(request.form['comp_name']).child('Selected Students').get()340		for each_st in reg_st.each():341			st_list[each_st.key()]=each_st.val()342		company_name=request.form['comp_name']343		return render_template('sel_comp_students.html',st_list=st_list,company_name=company_name)344	except:345		flash("No Students selected for "+request.form['comp_name'])346		return render_template('admin_dashboard.html',company_details=company_details)347app.run(debug=True)...prepare_ec2_servers.py
Source:prepare_ec2_servers.py  
...11import os12import json13from typing import Dict, Any14DEFAULT_KEY_PAIR_NAME = "mephisto-server-key"15def update_details(16    open_file,17    new_data: Dict[str, Any],18):19    """20    Overwrite the contents of the open file with the given data.21    """22    open_file.seek(0)23    open_file.truncate(0)24    json.dump(new_data, open_file, sort_keys=True, indent=4)25def launch_ec2_fallback(26    iam_profile: str,  # Iam role name, should be saved in aws credentials27    domain_name: str,28    ssh_ip_block: str,29    access_logs_key: str,30    key_pair_name: str = DEFAULT_KEY_PAIR_NAME,31    server_details_file: str = DEFAULT_FALLBACK_FILE,32    instance_type: str = FALLBACK_INSTANCE_TYPE,33) -> Dict[str, Any]:34    """35    This function is used to set up a mephisto36    vpc and fallback server for the AWS setup. At the moment37    it requires that you already have a domain registered,38    and it is up to you to delegate the domain to the39    amazon nameservers created by this function. This40    function will request the ssl certificate from amazon41    At the moment, it only works on the us-east region.42    Feel free to open a PR to extend this functionality43    if you need another region!44    """45    assert not domain_name.startswith("www."), (46        "You should provide a domain name without www, like 'example.com', "47        "or 'crowdsourcing.example.com'"48    )49    key_pair_name = DEFAULT_KEY_PAIR_NAME if key_pair_name is None else key_pair_name50    server_details_file = (51        DEFAULT_FALLBACK_FILE if server_details_file is None else server_details_file52    )53    instance_type = FALLBACK_INSTANCE_TYPE if instance_type is None else instance_type54    session = boto3.Session(profile_name=iam_profile, region_name="us-east-2")55    try:56        with open(server_details_file, "r") as saved_details_file:57            existing_details = json.load(saved_details_file)58    except:59        existing_details = {"domain": domain_name, "cidr": ssh_ip_block}60    with open(server_details_file, "w+") as saved_details_file:61        # Get a ssl certificate for the domain62        cert_details = existing_details.get("cert_details")63        if cert_details is None:64            print("Getting a certificate for the given domain...")65            cert_details = ec2_helpers.get_certificate(session, domain_name)66            existing_details["cert_details"] = cert_details67            update_details(saved_details_file, existing_details)68        else:69            print("Using existing certificate")70        # Create a hosted zone for the given domain71        hosted_zone_id = existing_details.get("hosted_zone_id")72        if hosted_zone_id is None:73            print("Creating hosted zone for the given domain...")74            hosted_zone_id = ec2_helpers.create_hosted_zone(session, domain_name)75            existing_details["hosted_zone_id"] = hosted_zone_id76            update_details(saved_details_file, existing_details)77        else:78            print(f"Using existing hosted zone {hosted_zone_id}")79        # Create the VPC to hold the servers80        vpc_details = existing_details.get("vpc_details")81        if vpc_details is None:82            print("Initializing VPC...")83            vpc_details = ec2_helpers.create_mephisto_vpc(session)84            existing_details["vpc_details"] = vpc_details85            update_details(saved_details_file, existing_details)86        else:87            print(f"Using existing vpc {vpc_details['vpc_id']}")88        # Set up a security group for everything89        security_group_id = existing_details.get("security_group_id")90        if security_group_id is None:91            print("Creating security group...")92            security_group_id = ec2_helpers.create_security_group(93                session, vpc_details["vpc_id"], ssh_ip_block94            )95            existing_details["security_group_id"] = security_group_id96            update_details(saved_details_file, existing_details)97        else:98            print(f"Using existing security group {security_group_id}")99        # Create a keypair for the server100        key_pair_filename = existing_details.get("key_pair_filename")101        if key_pair_filename is None:102            print(f"Generating keypair named {key_pair_name}")103            key_pair_filename = ec2_helpers.create_key_pair(session, key_pair_name)104            existing_details["key_pair_filename"] = key_pair_filename105            existing_details["key_pair_name"] = key_pair_name106            update_details(saved_details_file, existing_details)107        else:108            print(f"Using existing keypair at {key_pair_filename}")109        # Create the instance running the fallback server110        instance_id = existing_details.get("instance_id")111        if instance_id is None:112            print("Creating a new instance for fallback server...")113            instance_id = ec2_helpers.create_instance(114                session,115                key_pair_name,116                security_group_id,117                vpc_details["subnet_1_id"],118                "mephisto-default-fallover",119                instance_type=instance_type,120            )121            existing_details["instance_id"] = instance_id122            update_details(saved_details_file, existing_details)123        else:124            print(f"Using existing instance {instance_id}")125        # Create load balancer126        balancer_arn = existing_details.get("balancer_arn")127        if balancer_arn is None:128            print("Creating load balancer...")129            balancer_arn = ec2_helpers.create_load_balancer(130                session,131                [vpc_details["subnet_1_id"], vpc_details["subnet_2_id"]],132                security_group_id,133                vpc_details["vpc_id"],134            )135            print("Registering to hosted zone")136            ec2_helpers.register_zone_records(137                session,138                existing_details["hosted_zone_id"],139                domain_name,140                balancer_arn,141                cert_details["Name"],142                cert_details["Value"],143            )144            existing_details["balancer_arn"] = balancer_arn145            update_details(saved_details_file, existing_details)146        else:147            print(f"Using existing balancer {balancer_arn}")148        # Create the target group for the fallback instance149        target_group_arn = existing_details.get("target_group_arn")150        if target_group_arn is None:151            print("Creating target group...")152            target_group_arn = ec2_helpers.create_target_group(153                session, vpc_details["vpc_id"], instance_id154            )155            existing_details["target_group_arn"] = target_group_arn156            update_details(saved_details_file, existing_details)157        else:158            print(f"Using existing target group {target_group_arn}")159        # Create listener in balancer to direct to target group160        listener_arn = existing_details.get("listener_arn")161        if listener_arn is None:162            print("Creating listener for load balancer...")163            listener_arn = ec2_helpers.configure_base_balancer(164                session,165                balancer_arn,166                cert_details["arn"],167                target_group_arn,168            )169            existing_details["listener_arn"] = listener_arn170            update_details(saved_details_file, existing_details)171        else:172            print(f"Using existing listener {listener_arn}")173        # Finally, deploy the fallback server contents:174        ec2_helpers.deploy_fallback_server(175            session, instance_id, key_pair_name, access_logs_key176        )177        existing_details["access_logs_key"] = access_logs_key178        update_details(saved_details_file, existing_details)179    return existing_details180# TODO(CLEAN) Hydrize181def main():182    iam_role_name = input("Please enter local profile name for IAM role\n>> ")183    ec2_helpers.setup_ec2_credentials(iam_role_name)184    domain_name = input("Please provide the domain name you will be using\n>> ")185    ssh_ip_block = input("Provide the CIDR IP block for ssh access\n>> ")186    access_logs_key = input(187        "Please provide a key password to use for accessing server logs\n>> "188    )189    launch_ec2_fallback(iam_role_name, domain_name, ssh_ip_block, access_logs_key)190if __name__ == "__main__":...magento.py
Source:magento.py  
1import requests2# from config import Config3from app import app4# app.config.from_object(Config)5headers = {"Authorization": "Bearer " + app.config['MAGENTO_TOKEN']}6def get_mage_orders():7    r = requests.get(app.config['MAGENTO_REST_URL'] + '/' + 8                    app.config['MAGENTO_STORE'] + '/' +9                    'V1/orders/items?searchCriteria=all',10                    headers=headers11                    )12    return r.json()13def get_mage_orders_with_name_filter(mage_product_name):14    r = requests.get(app.config['MAGENTO_REST_URL'] + '/' + 15                    app.config['MAGENTO_STORE'] + '/' +16                    'V1/orders/items?' +17                    'searchCriteria[filter_groups][0][filters][0][field]=name&' +18                    'searchCriteria[filter_groups][0][filters][0][value]=%25' + mage_product_name + '%25&' +19                    'searchCriteria[filter_groups][0][filters][0][condition_type]=like&' +20                    'searchCriteria[filter_groups][1][filters][0][field]=product_type&' +21                    'searchCriteria[filter_groups][1][filters][0][value]=virtual&' +22                    'searchCriteria[filter_groups][1][filters][0][condition_type]=eq&' +23                    'searchCriteria[filter_groups][2][filters][0][field]=product_id&' +24                    'searchCriteria[filter_groups][2][filters][0][value]=102&' +25                    'searchCriteria[filter_groups][2][filters][0][condition_type]=neq&' +26                    'searchCriteria[filter_groups][3][filters][0][field]=product_id&' +27                    'searchCriteria[filter_groups][3][filters][0][value]=103&' +28                    'searchCriteria[filter_groups][3][filters][0][condition_type]=neq&' +29                    'searchCriteria[filter_groups][4][filters][0][field]=product_id&' +30                    'searchCriteria[filter_groups][4][filters][0][value]=104&' +31                    'searchCriteria[filter_groups][4][filters][0][condition_type]=neq',32                    headers=headers33                    )34    return r.json()35def mage_get_all_order_ids(orders_json):36    '''37    Return a list with just the orders information you need38    '''39    order_id_list = []40    for order_item in orders_json["items"]:41        order_id = order_item["order_id"]42        print(order_id)43        order_id_list.append(order_item["order_id"])44    # remove duplicate45    order_id_list = list(dict.fromkeys(order_id_list))46    return order_id_list47def mage_get_details_from_single_order(order_id):48    '''49    Return all details from single magento order50    '''51    r = requests.get(app.config['MAGENTO_REST_URL'] + '/' + 52                    app.config['MAGENTO_STORE'] + '/' +53                    'V1/orders/' + str(order_id),54                    headers=headers55                    )56    return r.json()57def mage_return_order_important_details_only(order_details):58    '''59    Takes in input a json with all order details60    and return a list with just the details you need61    '''62    # if order is canceled then do nothing63    if order_details["status"] == "canceled":64        return None65    order_details_dict = {}66    order_details_dict["email"] = order_details["customer_email"]67    order_details_dict["creazione"] = order_details["created_at"]68    order_details_dict["nome"] = order_details["billing_address"]["firstname"]69    order_details_dict["cognome"] = order_details["billing_address"]["lastname"]70    order_details_dict["tel"] = order_details["billing_address"]["telephone"]71    order_details_dict["increment_id"] = order_details["increment_id"]72    for detail in order_details["items"]:73        if detail["product_type"] == "virtual":74            order_details_dict["prenotazione"] = detail["sku"]75            order_details_dict["data"], order_details_dict["ora"] = detail["sku"].split('-') # Coperto cena Venerdi 11-21:0076            order_details_dict["data"] = order_details_dict["data"][-2:] # 1177            order_details_dict["quantita"] = detail["qty_ordered"]78    return order_details_dict79def mage_return_order_important_details_only_bambu(order_details):80    '''81    Takes in input a json with all order details82    and return a list with just the details you need83    '''84    # if order is canceled then do nothing85    if order_details["status"] == "canceled":86        return None87    order_details_dict = {}88    order_details_dict["email"] = order_details["customer_email"]89    order_details_dict["creazione"] = order_details["created_at"]90    order_details_dict["nome"] = order_details["billing_address"]["firstname"]91    order_details_dict["cognome"] = order_details["billing_address"]["lastname"]92    order_details_dict["tel"] = order_details["billing_address"]["telephone"]93    order_details_dict["increment_id"] = order_details["increment_id"]94    for detail in order_details["items"]:95        if detail["product_type"] == "virtual":96            order_details_dict["prenotazione"] = detail["sku"]97            order_details_dict["data"] = detail["sku"].split(' ')[1] + detail["sku"].split(' ')[2] #['Coperto', '26', 'Giugno', 'Menu', 'Emiliano']98            order_details_dict["ora"] = "20:00"99            order_details_dict["quantita"] = detail["qty_ordered"]100    return order_details_dict101def mage_group_all_order_details_important(order_id_list):102    mage_final_details_list = []103    for order_id in order_id_list:104        json_all_detail_single_order = mage_get_details_from_single_order(order_id)105        #single_order_important_details_only = mage_return_order_important_details_only(json_all_detail_single_order)106        single_order_important_details_only = mage_return_order_important_details_only_bambu(json_all_detail_single_order)107        if single_order_important_details_only is not None:108            mage_final_details_list.append(single_order_important_details_only)109    return mage_final_details_list110def mage_get_salable_quantity():111    all_skus = mage_get_all_skus()112    mage_final_salable_list = []113    for sku in all_skus["items"]:114        sku_salable_dict = {}115        sku_salable_dict["sku"] = sku["sku"]116        sku_salable_dict["salable_qty"] = mage_get_this_product_salable_qty(sku["sku"])117        mage_final_salable_list.append(sku_salable_dict)118    return mage_final_salable_list119def mage_get_all_skus():120    r = requests.get(app.config['MAGENTO_REST_URL'] + '/' + 121                    app.config['MAGENTO_STORE'] + '/' +122                    'V1/products?' +123                    'fields=items[sku,name,id]&' +124                    'searchCriteria[filter_groups][0][filters][0][field]=sku&' +125                    'searchCriteria[filter_groups][0][filters][0][value]=%25Menu%25&' +126                    'searchCriteria[filter_groups][0][filters][0][condition_type]=like&' +127                    'searchCriteria[filter_groups][1][filters][0][field]=type_id&' +128                    'searchCriteria[filter_groups][1][filters][0][value]=virtual&' +129                    'searchCriteria[filter_groups][1][filters][0][condition_type]=eq&' +130                    'searchCriteria[filter_groups][2][filters][0][field]=status&' +131                    'searchCriteria[filter_groups][2][filters][0][value]=1&' +132                    'searchCriteria[filter_groups][2][filters][0][condition_type]=eq',133                    headers=headers134                    )135    return r.json()136def mage_get_this_product_salable_qty(sku):137    r = requests.get(app.config['MAGENTO_REST_URL'] + '/' + 138                    app.config['MAGENTO_STORE'] + '/' +139                    'V1/inventory/get-product-salable-quantity/' +140                    sku.replace(' ', '%20') +141                    '/1', #the default stockid142                    headers=headers143                    )144    return r.text145    146        ...rename_table_fieldnames.py
Source:rename_table_fieldnames.py  
1# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors2# License: GNU General Public License v3. See license.txt3import frappe4from frappe.model.utils.rename_field import rename_field5from frappe.modules import scrub, get_doctype_module6rename_map = {7	"Opportunity": [8		["enquiry_details", "items"]9	],10	"Quotation": [11		["quotation_details", "items"],12		["other_charges", "taxes"]13	],14	"Sales Order": [15		["sales_order_details", "items"],16		["other_charges", "taxes"],17		["packing_details", "packed_items"]18	],19	"Delivery Note": [20		["delivery_note_details", "items"],21		["other_charges", "taxes"],22		["packing_details", "packed_items"]23	],24	"Sales Invoice": [25		["entries", "items"],26		["other_charges", "taxes"],27		["packing_details", "packed_items"],28		["advance_adjustment_details", "advances"]29	],30	"Material Request": [31		["indent_details", "items"]32	],33	"Supplier Quotation": [34		["quotation_items", "items"],35		["other_charges", "taxes"]36	],37	"Purchase Order": [38		["po_details", "items"],39		["other_charges", "taxes"],40		["po_raw_material_details", "supplied_items"]41	],42	"Purchase Receipt": [43		["purchase_receipt_details", "items"],44		["other_charges", "taxes"],45		["pr_raw_material_details", "supplied_items"]46	],47	"Purchase Invoice": [48		["entries", "items"],49		["other_charges", "taxes"],50		["advance_allocation_details", "advances"]51	],52	"Production Order": [53		["production_order_operations", "operations"]54	],55	"BOM": [56		["bom_operations", "operations"],57		["bom_materials", "items"],58		["flat_bom_details", "exploded_items"]59	],60	"Payment Reconciliation": [61		["payment_reconciliation_payments", "payments"],62		["payment_reconciliation_invoices", "invoices"]63	],64	"Sales Taxes and Charges Template": [65		["other_charges", "taxes"],66		["valid_for_territories", "territories"]67	],68	"Purchase Taxes and Charges Template": [69		["other_charges", "taxes"]70	],71	"Shipping Rule": [72		["shipping_rule_conditions", "conditions"],73		["valid_for_territories", "territories"]74	],75	"Price List": [76		["valid_for_territories", "territories"]77	],78	"Appraisal": [79		["appraisal_details", "goals"]80	],81	"Appraisal Template": [82		["kra_sheet", "goals"]83	],84	"Bank Reconciliation": [85		["entries", "journal_entries"]86	],87	"Cost Center": [88		["budget_details", "budgets"]89	],90	"C-Form": [91		["invoice_details", "invoices"]92	],93	"Employee": [94		["employee_leave_approvers", "leave_approvers"],95		["educational_qualification_details", "education"],96		["previous_experience_details", "external_work_history"],97		["experience_in_company_details", "internal_work_history"]98	],99	"Expense Claim": [100		["expense_voucher_details", "expenses"]101	],102	"Fiscal Year": [103		["fiscal_year_companies", "companies"]104	],105	"Holiday List": [106		["holiday_list_details", "holidays"]107	],108	"Installation Note": [109		["installed_item_details", "items"]110	],111	"Item": [112		["item_reorder", "reorder_levels"],113		["uom_conversion_details", "uoms"],114		["item_supplier_details", "supplier_items"],115		["item_customer_details", "customer_items"],116		["item_tax", "taxes"],117		["item_specification_details", "quality_parameters"],118		["item_website_specifications", "website_specifications"]119	],120	"Item Group": [121		["item_website_specifications", "website_specifications"]122	],123	"Landed Cost Voucher": [124		["landed_cost_purchase_receipts", "purchase_receipts"],125		["landed_cost_items", "items"],126		["landed_cost_taxes_and_charges", "taxes"]127	],128	"Maintenance Schedule": [129		["item_maintenance_detail", "items"],130		["maintenance_schedule_detail", "schedules"]131	],132	"Maintenance Visit": [133		["maintenance_visit_details", "purposes"]134	],135	"Packing Slip": [136		["item_details", "items"]137	],138	"Customer": [139		["party_accounts", "accounts"]140	],141	"Customer Group": [142		["party_accounts", "accounts"]143	],144	"Supplier": [145		["party_accounts", "accounts"]146	],147	"Supplier Type": [148		["party_accounts", "accounts"]149	],150	"Payment Tool": [151		["payment_tool_details", "vouchers"]152	],153	"Production Planning Tool": [154		["pp_so_details", "sales_orders"],155		["pp_details", "items"]156	],157	"Quality Inspection": [158		["qa_specification_details", "readings"]159	],160	"Salary Slip": [161		["earning_details", "earnings"],162		["deduction_details", "deductions"]163	],164	"Salary Structure": [165		["earning_details", "earnings"],166		["deduction_details", "deductions"]167	],168	"Product Bundle": [169		["sales_bom_items", "items"]170	],171	"SMS Settings": [172		["static_parameter_details", "parameters"]173	],174	"Stock Entry": [175		["mtn_details", "items"]176	],177	"Sales Partner": [178		["partner_target_details", "targets"]179	],180	"Sales Person": [181		["target_details", "targets"]182	],183	"Territory": [184		["target_details", "targets"]185	],186	"Time Log Batch": [187		["time_log_batch_details", "time_logs"]188	],189	"Workstation": [190		["workstation_operation_hours", "working_hours"]191	],192	"Payment Reconciliation Payment": [193		["journal_voucher", "journal_entry"],194	],195	"Purchase Invoice Advance": [196		["journal_voucher", "journal_entry"],197	],198	"Sales Invoice Advance": [199		["journal_voucher", "journal_entry"],200	],201	"Journal Entry": [202		["entries", "accounts"]203	],204	"Monthly Distribution": [205		["budget_distribution_details", "percentages"]206	]207}208def execute():209	# rename doctypes210	tables = frappe.db.sql_list("show tables")211	for old_dt, new_dt in [["Journal Voucher Detail", "Journal Entry Account"],212		["Journal Voucher", "Journal Entry"],213		["Budget Distribution Detail", "Monthly Distribution Percentage"],214		["Budget Distribution", "Monthly Distribution"]]:215			if "tab"+new_dt not in tables:216				frappe.rename_doc("DocType", old_dt, new_dt, force=True)217	# reload new child doctypes218	frappe.reload_doc("manufacturing", "doctype", "production_order_operation")219	frappe.reload_doc("manufacturing", "doctype", "workstation_working_hour")220	frappe.reload_doc("stock", "doctype", "item_variant")221	frappe.reload_doc("accounts", "doctype", "party_account")222	frappe.reload_doc("accounts", "doctype", "fiscal_year_company")223	#rename table fieldnames224	for dn in rename_map:225		if not frappe.db.exists("DocType", dn):226			continue227		frappe.reload_doc(get_doctype_module(dn), "doctype", scrub(dn))228	for dt, field_list in rename_map.items():229		if not frappe.db.exists("DocType", dt):230			continue231		for field in field_list:232			rename_field(dt, field[0], field[1])233	# update voucher type234	for old, new in [["Bank Voucher", "Bank Entry"], ["Cash Voucher", "Cash Entry"],235		["Credit Card Voucher", "Credit Card Entry"], ["Contra Voucher", "Contra Entry"],236		["Write Off Voucher", "Write Off Entry"], ["Excise Voucher", "Excise Entry"]]:...test_action_links.py
Source:test_action_links.py  
1import os2import unittest3import json4from cloudsplaining.scan.managed_policy_detail import ManagedPolicyDetails5from cloudsplaining.scan.group_details import GroupDetailList6from cloudsplaining.scan.role_details import RoleDetailList7from cloudsplaining.scan.user_details import UserDetailList8from cloudsplaining.scan.authorization_details import AuthorizationDetails9example_authz_details_file = os.path.abspath(10    os.path.join(11        os.path.dirname(__file__),12        os.path.pardir,13        "files",14        "example-authz-details.json",15    )16)17with open(example_authz_details_file) as f:18    contents = f.read()19    auth_details_json = json.loads(contents)20class TestActionLinks(unittest.TestCase):21    def test_infrastructure_modification_actions(self):22        policy_details = ManagedPolicyDetails(auth_details_json.get("Policies"))23        infra_mod_actions = sorted(policy_details.all_infrastructure_modification_actions)24        self.assertTrue(len(infra_mod_actions) > 3000)25    def test_group_details_infra_mod_actions(self):26        group_details_json_input = auth_details_json["GroupDetailList"]27        policy_details = ManagedPolicyDetails(auth_details_json.get("Policies"))28        group_detail_list = GroupDetailList(group_details_json_input, policy_details)29        results = group_detail_list.all_infrastructure_modification_actions_by_inline_policies30        print(json.dumps(results, indent=4))31        expected_results = [32            "s3:GetObject",33            "s3:PutObjectAcl"34        ]35        self.assertListEqual(results, expected_results)36        self.assertTrue(len(results) >= 2)37    def test_role_details_infra_mod_actions(self):38        role_details_json_input = auth_details_json["RoleDetailList"]39        policy_details = ManagedPolicyDetails(auth_details_json.get("Policies"))40        role_detail_list = RoleDetailList(role_details_json_input, policy_details)41        results = role_detail_list.all_infrastructure_modification_actions_by_inline_policies42        expected_results = [43            "ec2:AssociateIamInstanceProfile",44            "ec2:DisassociateIamInstanceProfile",45            "iam:AddRoleToInstanceProfile",46            "iam:CreateAccessKey",47            "iam:CreateInstanceProfile",48            "iam:PassRole",49            "s3:GetObject",50            "secretsmanager:GetSecretValue"51        ]52        print(json.dumps(results, indent=4))53        self.assertListEqual(results, expected_results)54    def test_user_details_infra_mod_actions(self):55        user_details_json_input = auth_details_json["UserDetailList"]56        policy_details = ManagedPolicyDetails(auth_details_json.get("Policies"))57        group_details_json_input = auth_details_json["GroupDetailList"]58        group_detail_list = GroupDetailList(group_details_json_input, policy_details)59        user_detail_list = UserDetailList(60            user_details=user_details_json_input,61            policy_details=policy_details,62            all_group_details=group_detail_list63        )64        results = user_detail_list.all_infrastructure_modification_actions_by_inline_policies65        expected_results = [66            "s3:GetObject",67            "s3:PutObject",68            "s3:PutObjectAcl"69        ]70        print(json.dumps(results, indent=4))71        self.assertListEqual(results, expected_results)72    def test_authorization_files_action_links(self):73        authorization_details = AuthorizationDetails(auth_details_json)74        results = authorization_details.links75        """76        # It will look like this, but :77        {78            "a4b:AssociateContactWithAddressBook": "https://docs.aws.amazon.com/a4b/latest/APIReference/API_AssociateContactWithAddressBook.html",79            "a4b:AssociateDeviceWithRoom": "https://docs.aws.amazon.com/a4b/latest/APIReference/API_AssociateDeviceWithRoom.html",80            ...81        }82        """83        print(len(results.keys()))84        self.assertTrue(len(results.keys()) > 3500)...hr_payroll_estate.py
Source:hr_payroll_estate.py  
1from trytond.pool import Pool, PoolMeta2from trytond.pyson import Eval3__all__ = ['SalaryRule']4class SalaryRule(metaclass=PoolMeta):5    __name__ = 'salary.rule'6    def get_estate_details_for_employee(self, employee):7        '''Fetch employee estate details'''8        pool = Pool()9        current_estate_details_for_employee = None10        estate_table = pool.get('estate.allotment')11        employee_estate_details = estate_table.search(12            [13                ('employee', '=', employee),14                ('date_of_vacation', '=', None),15            ]16        )17        if employee_estate_details != []:18            current_estate_details_for_employee = employee_estate_details[0]19        return current_estate_details_for_employee20    21    22    def calculate_LICF(self, payslip, employee, contract):23        employee_estate_details = self.get_estate_details_for_employee(employee)24        amount = None25        if employee_estate_details:26            license_fee = employee_estate_details.license_fee27            garage_fee = employee_estate_details.garage_fee28            servant_quarter_fee = employee_estate_details.servant_quarter_fee29            amount = license_fee + garage_fee + servant_quarter_fee30        return amount31    def calculate_WTR(self, payslip, employee, contract):32        employee_estate_details = self.get_estate_details_for_employee(employee)33        amount = employee_estate_details.water_charges...Using AI Code Generation
1var request = require('request');2var options = {3  headers: {4  }5};6request(options, function (error, response, body) {7  if (!error && response.statusCode == 200) {8    console.log(body);9  }10});11var request = require('request');12var options = {13  headers: {14  }15};16request(options, function (error, response, body) {17  if (!error && response.statusCode == 200) {18    console.log(body);19  }20});21var request = require('request');22var options = {23  headers: {24  }25};26request(options, function (error, response, body) {27  if (!error && response.statusCode == 200) {28    console.log(body);29  }30});31var request = require('request');32var options = {33  headers: {34  },35  json: {36      {37          {38            "is": {39              "headers": {40              },41              "body": "{\"name\":\"John\"}"42            }43          }44      }45  }46};47request(options, function (error, response, body) {48  if (!error && response.statusCode == 200) {49    console.log(body);50  }51});52var request = require('request');53var options = {Using AI Code Generation
1const mb = require('mountebank');2mb.create({3}, () => {4    console.log('Mountebank running on port 2525');5    mb.post('/imposters', {6        stubs: [{7            responses: [{8                is: {9                }10            }]11        }]12    }, (error, response) => {13        if (error) {14            console.log('Error creating imposter: ' + error.message);15        } else {16            console.log('Imposter created');17            console.log('Imposter details: ' + JSON.stringify(response.body, null, 2));18        }19    });20});21const mb = require('mountebank');22mb.create({23}, () => {24    console.log('Mountebank running on port 2525');25    mb.post('/imposters', {26        stubs: [{27            responses: [{28                is: {29                }30            }]31        }]32    }, (error, response) => {33        if (error) {34            console.log('Error creating imposter: ' + error.message);35        } else {36            console.log('Imposter created');37            console.log('Imposter details: ' + JSON.stringify(response.body, null, 2));38        }39    });40});41const mb = require('mountebank');42mb.create({43}, () => {44    console.log('Mountebank running on port 2525');45    mb.post('/imposters', {Using AI Code Generation
1var mb = require('mountebank');2mb.create({ port: 2525, pidfile: 'mb.pid', logfile: 'mb.log', protofile: 'mb.proto' }, function (error, mb) {3    if (error) {4        console.log("Error: " + error);5    } else {6        console.log("Success: " + mb);7    }8});9mb.details(function (error, details) {10    if (error) {11        console.log("Error: " + error);12    } else {13        console.log("Success: " + details);14    }15});Using AI Code Generation
1var mb = require('mountebank');2var mb = mb.create({ port: 2525, pidfile: 'mb.pid', logfile: 'mb.log' });3mb.start(function () {4    mb.post('/imposters', {5            {6                    {7                        is: {8                            headers: { 'Content-Type': 'text/plain' },9                        }10                    }11            }12    }, function (error, response) {13        console.log(response.statusCode);14        mb.get('/imposters/3000', function (error, response) {15            console.log(response.body);16        });17    });18});19var mb = require('mountebank');20var mb = mb.create({ port: 2525, pidfile: 'mb.pid', logfile: 'mb.log' });21mb.start(function () {22    mb.post('/imposters', {23            {24                    {25                        is: {26                            headers: { 'Content-Type': 'text/plain' },27                        }28                    }29            }30    }, function (error, response) {31        console.log(response.statusCode);32        mb.get('/imposters/3000', function (error, response) {33            console.log(response.body);34        });35    });36});37var mb = require('mountebank');38var mb = mb.create({ port: 2525, pidfile: 'mb.pid', logfile: 'mb.log' });39mb.start(function () {40    mb.post('/imposters', {41            {42                    {43                        is: {44                            headers: { 'Content-Type': 'text/plain' },45                        }46                    }47            }48    }, function (error, response) {49        console.log(response.statusCode);50        mb.get('/imposters/3000', function (Using AI Code Generation
1var mb = require('mountebank');2var port = 2525;3var mbServer = mb.create({port: port, pidfile: 'mb.pid', logfile: 'mb.log', protofile: 'mb.proto', ipWhitelist: ['*']});4mbServer.start()5    .then(function () {6        console.log('mountebank started on port %s', port);7        console.log('mountebank process id: %s', mbServer.process.pid);8        return mbServer.post('/imposters', {9                {10                        {11                            is: {12                            }13                        }14                }15        });16    })17    .then(function (response) {18        console.log('POST /imposters response: %s', JSON.stringify(response.body));19        return mbServer.get('/imposters/4545');20    })21    .then(function (response) {22        console.log('GET /imposters/4545 response: %s', JSON.stringify(response.body));23        return mbServer.del('/imposters/4545');24    })25    .then(function (response) {26        console.log('DELETE /imposters/4545 response: %s', JSON.stringify(response.body));27        return mbServer.stop();28    })29    .then(function () {30        console.log('mountebank stopped');31    })32    .catch(function (error) {33        console.error('mountebank error: %s', error.message);34    });35POST /imposters response: {"port":4545,"protocol":"http","stubs":[{"responses":[{"is":{"statusCode":200,"body":"Hello World!"}}]}]}36GET /imposters/4545 response: {"port":4545,"protocol":"http","stubs":[{"responses":[{"is":{"statusCode":200,"body":"Hello World!"}}]}]}37DELETE /imposters/4545 response: {"port":4545,"protocol":"http","stubs":[{"responses":[{"is":{"statusCode":200,"body":"Hello World!"}}]}]}Using AI Code Generation
1var mb = require('mountebank');2var details = mb.details();3console.log(details);4var mb = require('mountebank');5var mbPort = 2525;6var mbProtocol = 'http';7var mbHost = 'localhost';8var mb = mb.create(mbUrl);9mb.post('/imposters', {10        {11                {12                    is: {13                        headers: { 'Content-Type': 'text/html' },14                    }15                }16        }17}, function (error, response) {18    console.log('POST /imposters response', response.statusCode);19});20var mb = require('mountebank');21var details = mb.details();22console.log(details);23var mb = require('mountebank');24var mbPort = 2525;25var mbProtocol = 'http';26var mbHost = 'localhost';27var mb = mb.create(mbUrl);28mb.post('/imposters', {29        {30                {31                    is: {32                        headers: { 'Content-Type': 'text/html' },33                    }34                }35        }36}, function (error, response) {37    console.log('POST /imposters response', response.statusCode);38});39var mb = require('mountebank');40var details = mb.details();41console.log(details);42var mb = require('mountebank');43var mbPort = 2525;44var mbProtocol = 'http';45var mbHost = 'localhost';46var mb = mb.create(mbUrl);47mb.post('/imposters',Using AI Code Generation
1var mb = require('mountebank');2var port = 2525;3var protocol = 'http';4var options = {5};6var mb = mb.create(options);7mb.start()8    .then(function () {9        mb.post('/imposters', {10                {11                        {12                            is: {13                            }14                        }15                }16        })17            .then(function (response) {18                var imposter = response.body;19                console.log('Created imposter with name', imposter.name);20                return mb.get('/imposters/' + imposter.port);21            })22            .then(function (response) {23                var imposter = response.body;24                console.log('Got imposter with name', imposter.name);25            })26            .finally(mb.stop);27    });Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
