Skip to content

Instantly share code, notes, and snippets.

@scriptpapi
Created July 26, 2022 08:07
Show Gist options
  • Save scriptpapi/a065ace0eec2c6461b4b696fe0510e60 to your computer and use it in GitHub Desktop.
Save scriptpapi/a065ace0eec2c6461b4b696fe0510e60 to your computer and use it in GitHub Desktop.
write to csv using pure html and js
<html>
<head>
<script>
var csvFile = null
var merchantList = []
var merchants = []
var updateResult = []
var success = 0
var failed = 0
setTimeout(function () {
document.getElementById("file-selector").onchange = function () {
csvFile = this.files[0]
}
}, 1000)
function renderNumMerchants() {
console.log("Number of merchants in the list: " + merchantList.length.toString())
let numOfMerchantsElem = document.createElement("p")
numOfMerchantsElem.innerText = "Number of merchants in the list: " + merchantList.length.toString()
document.getElementById("console").appendChild(numOfMerchantsElem)
let numSuccess = document.createElement("p")
numSuccess.id = "numSuccess"
numSuccess.innerText = "Success count: " + success.toString()
document.getElementById("console").appendChild(numSuccess)
let numFailed = document.createElement("p")
numFailed.id = "numFailed"
numFailed.innerText = "Failed count: " + failed.toString()
document.getElementById("console").appendChild(numFailed)
let loadingIndicator = document.createElement("p")
loadingIndicator.id = "loadingIndicator"
loadingIndicator.innerText = "Updating merchants... please wait."
document.getElementById("console").appendChild(loadingIndicator)
}
function updateSuccessCount() {
success++
document.getElementById("numSuccess").innerText = "Success count: " + success.toString()
}
function updateFailedCount() {
failed++
document.getElementById("numSuccess").innerText = "Failed count: " + failed.toString()
}
function renderDoneIndicator() {
let doneElem = document.createElement("b")
doneElem.id = "done"
doneElem.innerText = "Done updating. Refresh the page before re-using this tool."
document.getElementById("console").appendChild(doneElem)
}
async function readFile(event) {
var array = event.target.result.split('\n')
let parsedRows = []
array.forEach(row => parsedRows.push(row.replace("\n", "").replace("\r", "").split(",")))
let keys = parsedRows[0]
parsedRows.shift()
parsedRows.forEach((parsedRow) => {
let newMerchantObject = {}
parsedRow.forEach((o, index) => {
newMerchantObject[keys[index]] = o
})
merchantList.push(newMerchantObject)
})
console.log(merchantList)
renderNumMerchants()
var merchantUpdateJob = new Promise((resolve, reject) => {
merchantList.forEach(async (merchant, index, array) => {
const requestOptions = {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
copyMerchantProfile: document.getElementById("copyMerchantProfile").value,
newMerchantDetails: {
name: merchant.merchantName,
categoryCode: merchant.categoryCode,
mobilePhone: merchant.mobilePhone, // OPTIONAL
email: merchant.email, // OPTIONAL
city: merchant.city,
countryCode: merchant.countryCode,
postCode: merchant.postcode,
stateProvince: merchant.stateProvince,
street1: merchant.street1,
street2: merchant.street2, // OPTIONAL
goodsDescription: merchant.goodsDescription,
webSite: merchant.website,
locale: merchant.locale,
timeZone: merchant.timeZone,
amexSafeKeyMid: merchant.amexSafeKeyMid, // OPTIONAL
bankMerchantId: merchant.bankMerchantId,
}
})
};
await fetch("http://localhost:3000/" + merchant.merchantId, requestOptions)
.then(async (response) => {
response.json()
.then((response_data) => {
if (response_data.result == "SUCCESS") {
updateResult.push({
newMerchant: merchant.merchantId,
copiedFrom: document.getElementById("copyMerchantProfile").value,
result: "SUCCESS",
administrativePassword: response_data.administrativePassword,
details: "SUCCESS"
})
updateSuccessCount()
}
else if (response_data.result == "FAILED") {
updateResult.push({
newMerchant: merchant.merchantId,
copiedFrom: document.getElementById("copyMerchantProfile").value,
result: "FAILED",
administrativePassword: "FAILED",
details: response_data.details
})
updateFailedCount()
}
else {
updateResult.push({
newMerchant: merchant.merchantId,
copiedFrom: document.getElementById("copyMerchantProfile").value,
result: "FAILED",
administrativePassword: "FAILED",
details: "UNKNOWN"
})
updateFailedCount()
}
})
.catch((data_error) => {
updateResult.push({
newMerchant: merchant.merchantId,
copiedFrom: document.getElementById("copyMerchantProfile").value,
result: "FAILED",
administrativePassword: "FAILED",
details: "UNKNOWN"
})
updateFailedCount()
})
updateFailedCount()
})
.catch((error) => {
updateResult.push({
newMerchant: merchant.merchantId,
copiedFrom: document.getElementById("copyMerchantProfile").value,
result: "FAILED",
administrativePassword: "FAILED",
details: "UNKNOWN"
})
updateFailedCount()
})
if (index === array.length - 1) resolve();
});
});
merchantUpdateJob.then(() => {
renderDoneIndicator()
});
}
function updateMerchants() {
const reader = new FileReader()
reader.addEventListener('load', readFile);
reader.readAsText(csvFile);
}
function exportResults() {
let csvContent = "newMerchant,copiedFrom,result,administrativePassword,details" + "\n";
updateResult.forEach((result_row) => {
let row = result_row.newMerchant + "," + result_row.copiedFrom + "," + result_row.result + "," + result_row.administrativePassword + "," + result_row.details
csvContent += row + "\n";
});
var textFile = null
var data = new Blob([csvContent], { type: 'text/csv' });
if (textFile !== null) {
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(data);
console.log(textFile)
window.open(textFile);
}
</script>
</head>
<body>
<h1>MPGS Bulk Migrator</h1>
<p>Choose a csv with migs merchant info list</p>
<form>
<input type="file" id="file-selector" accept=".csv">
<input type="button" value="Update Merchants" onclick="updateMerchants();" />
<input type="button" value="Export results" onclick="exportResults();" />
</form>
<form>
<label for="copyMerchantProfile">Copy MID configurations:</label>
<input type="text" id="copyMerchantProfile">
</form>
<div id="console">
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment