identify user role by flo id

This commit is contained in:
Abhishek Sinha 2020-01-30 20:15:38 +05:30
parent e5701e86d1
commit 88a9fb40a9

View File

@ -9842,6 +9842,10 @@
function onLoadStartUp() {
showMessage("Starting the app! Please Wait!")
floDapps.launchStartUp().then(result => {
// identify and unlock user functions
ecommerce.actions.doShreeGanesh();
console.log(result)
showMessage(result)
showMessage(`Welcome ${myFloID}`)
@ -9851,6 +9855,10 @@
<script>
function system_message(msg='', type='') {
console.log(msg);
}
function extend(Child, Parent) {
var Temp = function() {};
Temp.prototype = Parent.prototype;
@ -9865,84 +9873,281 @@
throw new Error('Not a Number');
}
}
/*https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze*/
function deepFreeze(object) {
// Retrieve the property names defined on object
var propNames = Object.getOwnPropertyNames(object);
// Freeze properties before freezing self
for (let name of propNames) {
let value = object[name];
object[name] =
value && typeof value === "object" ? deepFreeze(value) : value;
}
return Object.freeze(object);
}
function randomNoRepeats(array) {
var copy = array.slice(0);
return function() {
if (copy.length < 1) {
copy = array.slice(0);
}
var index = Math.floor(Math.random() * copy.length);
var item = copy[index];
copy.splice(index, 1);
return item;
};
}
function removeWhiteSpaces(text='') {
return text.replace(/\s/g,'');
}
async function ajaxGet(url) {
try {
//await the response of the fetch call
let response = await fetch(url);
//proceed once the first promise is resolved.
let data = await response.json();
//proceed only when the second promise is resolved
return data;
} catch (error) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onload = function() {
if (xhr.status === 200) {
callback(xhr.responseText);
} else {
showMessage(`WARNING: Failed to get data from ${url}.`);
throw new Error(`Request to ${url} failed: ${xhr.status}`);
}
};
xhr.send();
}
}
//AJAX Post
function ajaxPost(url = ``, data = {}) {
return fetch(url, {
method: "POST", // *GET, POST, PUT, DELETE, etc.
mode: "cors", // no-cors, cors, *same-origin
cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
credentials: "same-origin", // include, *same-origin, omit
headers: {
"Content-Type": "application/json"
// "Content-Type": "application/x-www-form-urlencoded",
},
redirect: "follow", // manual, *follow, error
referrer: "no-referrer", // no-referrer, *client
body: JSON.stringify(data) // body data type must match "Content-Type" header
}).then(response => response.json()); // parses response to JSON
}
// Create unique id
function unique_id() {
return `${+new Date()}_${Math.random()
.toString(36)
.substr(2, 9)}`;
}
</script>
<script>
const ecommerce = {
SUBJECT: 'TEST_ECOMMERCE',
DATA_TYPE: 'EC1',
product_categories: ['Electronics', 'Clothes & Accessories', 'Home Appliances'],
sellers_list: [
{
seller_id: 'FGtPEBu2NFFYkqFrA9NDBJJLpVhyuPubDj',
category: 'Electronics',
approved_by: 'F72fAV6aG8JrzR3N9F43vBE59q1FqWhBAp',
certificate: '3046022100b2478a07e2fb5f0d315e3bd59c2e1b6bbba424a1e40099d32af057fc813b04d502210080289da78d0e319a1e9efc28b9bb61ace98d4d57e655c9c790d430baa890f293'
},
{
seller_id: 'FGtPEBu2NFFYkqFrA9NDBJJLpVhyuPubDj',
category: 'Clothes & Accessories',
approved_by: 'F72fAV6aG8JrzR3N9F43vBE59q1FqWhBAp',
certificate: '304402206c382d922419763533a023cd578062d0feb5cd5ccafef110e73ef71b7219aefe02202169aba0de969b98a5e9f995a6fd1035c3b12466d1c0dcc2fd3628d1043437e7'
},
{
seller_id: 'FGtPEBu2NFFYkqFrA9NDBJJLpVhyuPubDj',
category: 'Home Appliances',
approved_by: 'F72fAV6aG8JrzR3N9F43vBE59q1FqWhBAp',
certificate: '3045022100955c6c45cb06a6c58f818b99f0191ea054c9e21840aa6f6a13dec35780b6b5ac022032b0e3c9ed451d440e7b009a862a3805346d1fa82c7f8d060e1d6b263cec2ccc'
},
{
seller_id: 'FM1NzncALbWCcBVF5zbgzSmUbwQgW7tUfv',
category: 'Clothes & Accessories',
approved_by: 'F72fAV6aG8JrzR3N9F43vBE59q1FqWhBAp',
certificate: '304402200bc20546978989d910388c26ec48c730287eba65c60e83a56ef4ca78bdf39f7202203e95040ce9ebcaeefdf019b3d9396f2acaed4740cfbdce33120b5139a2ba9023'
},
],
cashiers_list: [
{
cashier_flo_id: 'FByrY4vc1NRfbkqAqABtUyhhNzMZsKUjqr',
upi_id: 'john_doe@upi',
approved_by: 'F72fAV6aG8JrzR3N9F43vBE59q1FqWhBAp',
certificate: '3045022100ace8fd3635600a06045807401a67f6657e2750c7ddef486986dc942e29a781870220338f29ab91ff0692868224186c02b7b2ad4fc372d27bd5d7dff16d44a643b620'
},
{
cashier_flo_id: 'FHU7dfBVDLZwp3fLRJ5cr7nEABBeeU9Z4T',
upi_id: 'jane_doe@upi',
approved_by: 'F72fAV6aG8JrzR3N9F43vBE59q1FqWhBAp',
certificate: '304402202aad9d2200e65ef141bd6694827f616dfa16f2f055c4999ace783766cd57fb300220487ec999ab2683b7d604e8c30de2dfea622d28ad781cbc06de20ead3f487a81a'
},
],
couriers_list: [
{
courier_guy_flo_id: 'FToFgkZHhLfkQqLQUsjBZxKVWyrEMsC4hf',
location: 'Ranchi',
approved_by: 'F72fAV6aG8JrzR3N9F43vBE59q1FqWhBAp',
certificate: '30450221008c65a37120d3be0a36e9a8aef737646f8477dc8f0070ee872b870563277e0f2a02203215dc61dce5386d9d8d543f13f3973fde8d097890f907cbba60dd548ca9853b'
},
{
courier_guy_flo_id: 'FPMpZJY1ca9pru3mT8KUCHCaauBe8UNQ3a',
location: 'Ranchi',
approved_by: 'F72fAV6aG8JrzR3N9F43vBE59q1FqWhBAp',
certificate: '3045022045653951beaa1d2d52742592f1ebe4c4ba79ef3bb452a13d2b28b56494358a8702210083c30538b4d498f2226d23b796928d00ba7dd51e91f581db9868d28a80af4721'
}
],
master_configurations: {},
master_configuration_flo_id: '',
actions: {},
blocked_flo_ids: [],
users: {},
products: {},
};
ecommerce.actions = {
parse_flo_comments: async function() {
text = `masterFLOPubKey=03EA5E2CAB18DA585400D6EC569438D415FAF200528E05D0E2B9BEAA2B5C3DCA90
#!#SUBJECT='TEST_ECOMMERCE'
#!#DATA_TYPE=EC1
#!#product_categories = Electronics,Clothes & Accessories,Home Appliances
#!#cashiers=
{
"FByrY4vc1NRfbkqAqABtUyhhNzMZsKUjqr": {
"upi_id": "johnDoe@upi",
"approved_by": "RE13EurYPSUUn4sGujJL64nKbSwJwqhc8BxTU9RzWzZrLwT2jXas",
"certificate": "3044022026ce8c16420bb4f0f24d0aafccb7a6fb1ac2154b2d77d9304afde7044fbaaa9b02206e6b39e6af181c3d919a79d3569cf946dee444e2bf0b5519b1d07f97b1174d47"
},
"FHU7dfBVDLZwp3fLRJ5cr7nEABBeeU9Z4T": {
"upi_id": "janeDoe@upi",
"approved_by": "RE13EurYPSUUn4sGujJL64nKbSwJwqhc8BxTU9RzWzZrLwT2jXas",
"certificate": "3046022100d26d9aaf23a9f2d8679663abb251d4b990cf366297f6ce78b3e5f28ede3ba0a9022100ef7f826fecec82adebb80527c04b338b691b8eb1c38bfaf6417bc3515cc0edfb"
}
}
#!#sellers_list= {
"FGtPEBu2NFFYkqFrA9NDBJJLpVhyuPubDj":{
"seller_id": "FGtPEBu2NFFYkqFrA9NDBJJLpVhyuPubDj",
"category": "Electronics",
"approved_by": "RE13EurYPSUUn4sGujJL64nKbSwJwqhc8BxTU9RzWzZrLwT2jXas",
"location": "Yamaha Service Centre, Shail Yamaha, Argora Housing Colony, Argora, Ranchi, Jharkhand",
"certificate": "3045022100f9afd666d55fb0d6b3c4f5d5e0672c9ec1a26eb08703a38ff8d5c8b08c0b8cd502205582e27980796ce5d29aeeb5ab9282ea1d8e412ee0f6b0af7ccb9dcdfd9e0224"
},
"FGtPEBu2NFFYkqFrA9NDBJJLpVhyuPubDj": {
"seller_id": "FGtPEBu2NFFYkqFrA9NDBJJLpVhyuPubDj",
"category": "Clothes & Accessories",
"approved_by": "RE13EurYPSUUn4sGujJL64nKbSwJwqhc8BxTU9RzWzZrLwT2jXas",
"location": "Head Office: JK Street Daladili Chowk Ratu, City Office: JK News Pipra Toli Argora Road Ranchi, Ranchi, Jharkhand 834002",
"certificate": "304402203ee790bc46ca28dd17a540c33031053d061881617f0fea38039e8e0cf1954e6c02202d1bbb1630b633c6a692be914552e87998b292249c9f179ced508ad3a81a692a"
},
"FGtPEBu2NFFYkqFrA9NDBJJLpVhyuPubDj": {
"seller_id": "FGtPEBu2NFFYkqFrA9NDBJJLpVhyuPubDj",
"category": "Home Appliances",
"approved_by": "RE13EurYPSUUn4sGujJL64nKbSwJwqhc8BxTU9RzWzZrLwT2jXas",
"location": "Argora Housing Colony, Argora, Ranchi, Jharkhand 834002",
"certificate": "304402203f8748dc073fe8fa3ae7244ce6b094fc50558c1652aa7f42ab5ec28bcac2261e02205c0738accb31251c8250af9a8d53476b66fc1f072f19eda50fec6a05a6349e59"
},
"FM1NzncALbWCcBVF5zbgzSmUbwQgW7tUfv": {
"seller_id": "FM1NzncALbWCcBVF5zbgzSmUbwQgW7tUfv",
"category": "Clothes & Accessories",
"approved_by": "RE13EurYPSUUn4sGujJL64nKbSwJwqhc8BxTU9RzWzZrLwT2jXas",
"location": "Circular Rd, Lalpur, Ranchi, Jharkhand 834001",
"certificate": "304502205af1b49c4cd1ee56ab49369dce632e1be5fed08c97d2ce18d598394ba4d7ec48022100dac3e84ece805e202e93b1c3a031bfb348827dd03de50cd8baa881c6da2a0f3c"
}
}
#!#couriers_list={
"FToFgkZHhLfkQqLQUsjBZxKVWyrEMsC4hf":
{
"courier_guy_flo_id": "FToFgkZHhLfkQqLQUsjBZxKVWyrEMsC4hf",
"location": "Baralal St, Upper Bazar, Ranchi, Jharkhand 834001",
"approved_by": "RE13EurYPSUUn4sGujJL64nKbSwJwqhc8BxTU9RzWzZrLwT2jXas",
"certificate": "304602210083b770973892a4eaa41d22d893c6d57d20ec02930ba752d4c6a90fdaa92479070221008476dc34dafe462214e687ca84b93a3da891c8d5282218c6c5372b0a1629e17d"
},
"FPMpZJY1ca9pru3mT8KUCHCaauBe8UNQ3a": {
"courier_guy_flo_id": "FPMpZJY1ca9pru3mT8KUCHCaauBe8UNQ3a",
"location": "Ground Floor A.R.K Complex Lalpur Chowk Beside Lalpur Thana, Hazaribag Rd, Income Tax Colony, Lalpur, Ranchi, Jharkhand 834001",
"approved_by": "RE13EurYPSUUn4sGujJL64nKbSwJwqhc8BxTU9RzWzZrLwT2jXas",
"certificate": "3045022100d89826c28465bfd8b6d97b3cc5e024634a483ebc67a5514ad68cb7fe83e3a90d02207f200a25a295e77b2f7eff34d7d0e28d94711c77ad30011c7bde52d69bac49c7"
}
}`
text = removeWhiteSpaces(text);
return text;
const master_data = await ajaxGet(`${floGlobals.apiURL.FLO[1]}/api/txs/?address=${ecommerce.master_configuration_flo_id}`);
if(typeof master_data==="object" && typeof master_data.txs==="object") {
let text = '';
let tx_cmnt_arr = [];
for(txt of master_data.txs) {
if(txt.vin[0].addr === ecommerce.master_configuration_flo_id) {
if(txt.floData.length===0) break;
tx_cmnt_arr.push(txt.floData);
}
}
tx_cmnt_arr.reverse().map(m=>text += m.replace('text:', ''));
return text;
}
},
fetch_configs: async function() {
const floData = await this.parse_flo_comments();
let RMAssets = floData.trim();
let floAssetsArray = RMAssets.split("#!#");
if (
floAssetsArray.length > 0 &&
typeof floAssetsArray[0] !== undefined &&
floAssetsArray[0].trim() !== "" &&
typeof floAssetsArray[1] !== undefined &&
floAssetsArray[1].trim() !== ""
) {
try {
floAssetsArray.map(function(assets_string) {
let k = assets_string.split("=");
if (k[1].indexOf(",") > 0 && k[1].indexOf("{") == -1) {
k[1] = k[1]
.split(",")
.map(val =>
!isNaN(val) ? parseFloat(val) : val.trim()
)
.filter(v => ![null, "", undefined, NaN].includes(v));
} else if (!isNaN(k[1])) {
k[1] = parseFloat(k[1]);
}
if (typeof k[1] == "string" && k[1].indexOf("{") >= 0) {
k[1] = JSON.parse(k[1].replace(/ /g, ""));
}
return Object.defineProperty(
ecommerce.master_configurations,
k[0],
{
value: k[1],
writable: false,
configurable: false,
enumerable: true
}
);
});
deepFreeze(ecommerce.master_configurations);
console.log(ecommerce);
return ecommerce;
} catch (error) {
console.error(
"FATAL ERROR: Failed to fetch master configuration: ",
error
);
}
}
return false;
},
doShreeGanesh: async function() {
// fetch configs from master comment
await this.fetch_configs();
// Identify logged in user as either buyer, seller, cashier or courier
const loggedInUser = new ecommerce.users.current_user({
flo_id: myFloID,
});
deepFreeze(loggedInUser.user_info);
},
}
ecommerce.users = {
current_user: function User(user_details='') {
if(typeof User.instance === 'object') return User.instance;
if(ecommerce.sellers_list.map(m=>m.seller_id)
if(Object.keys(ecommerce.master_configurations.sellers_list)
.includes(user_details.flo_id)) {
User.prototype.user_info = new ecommerce.user_types.sellers(user_details);
} else if(ecommerce.cashiers_list.map(m=>m.cashier_flo_id)
const seller_details = {};
seller_details.approved_by = ecommerce.master_configurations.sellers_list[myFloID].approved_by;
seller_details.certificate = ecommerce.master_configurations.sellers_list[myFloID].certificate;
seller_details.location = ecommerce.master_configurations.sellers_list[myFloID].location;
User.prototype.user_info = new ecommerce.users.user_types.sellers(seller_details);
} else if(Object.keys(ecommerce.master_configurations.cashiers_list)
.includes(user_details.flo_id)) {
User.prototype.user_info = new ecommerce.user_types.cashiers(user_details);
} else if(ecommerce.couriers_list.map(m=>m.courier_guy_flo_id)
const cashier_details = {};
cashier_details.upi_id = ecommerce.master_configurations.cashiers[myFloID].upi_id;
cashier_details.approved_by = ecommerce.master_configurations.cashiers[myFloID].approved_by;
cashier_details.certificate = ecommerce.master_configurations.cashiers[myFloID].certificate;
User.prototype.user_info = new ecommerce.users.user_types.cashiers(user_details);
} else if(Object.keys(ecommerce.master_configurations.couriers_list)
.includes(user_details.flo_id)) {
User.prototype.user_info = new ecommerce.user_types.couriers(user_details);
const courier_details = {};
courier_details.location = ecommerce.master_configurations.couriers_list[myFloID].location;
courier_details.approved_by = ecommerce.master_configurations.couriers_list[myFloID].approved_by;
courier_details.certificate = ecommerce.master_configurations.couriers_list[myFloID].certificate;
User.prototype.user_info = new ecommerce.users.user_types.couriers(user_details);
} else {
User.prototype.user_info = new ecommerce.user_types.buyers(user_details);
user_details.location = user_details.location || "";
User.prototype.user_info = new ecommerce.users.user_types.buyers(user_details);
}
User.instance = this;
@ -9951,69 +10156,79 @@
user_types: {
buyers: function Buyer(buyer_details={}) {
this.buyer_id = buyer_details.flo_id;
for (const key in buyer_details) {
if (buyer_details.hasOwnProperty(key)) {
const obj = buyer_details[key];
this[key] = obj;
}
}
this.buyer_id = myFloID;
this.user_role = "BUYER";
this.buy_list = [];
this.total_buying_price = 0;
},
sellers: function Seller(seller_details={}) {
this.seller_id = seller_details.flo_id;
for (const key in seller_details) {
if (seller_details.hasOwnProperty(key)) {
const obj = seller_details[key];
this[key] = obj;
}
}
this.seller_id = myFloID;
this.user_role = "SELLER";
this.approved_by = seller_details.approved_by;
this.certificate = seller_details.certificate;
},
cashiers: function Cashier(cashier_details={}) {
this.cashier_flo_id = cashier_details.flo_id;
this.upi_id = cashier_details.upi_id;
for (const key in cashier_details) {
if (cashier_details.hasOwnProperty(key)) {
const obj = cashier_details[key];
this[key] = obj;
}
}
this.cashier_flo_id = myFloID;
this.user_role = "CASHIER";
this.approved_by = cashier_details.approved_by;
this.certificate = cashier_details.certificate;
},
couriers: function Courier(courier_details={}) {
this.courier_guy_flo_id = courier_details.flo_id;
this.location = courier_details.location;
for (const key in courier_details) {
if (courier_details.hasOwnProperty(key)) {
const obj = courier_details[key];
this[key] = obj;
}
}
this.courier_guy_flo_id = myFloID;
this.user_role = "COURIER";
this.approved_by = courier_details.approved_by;
this.certificate = courier_details.certificate;
},
},
products: {
physical_products: function(data) {
for (const key in data) {
if (data.hasOwnProperty(key)) {
const obj = data[key];
this[key] = obj;
}
}
this.product_type = "PHYSICAL";
},
digital_products: function() {
for (const key in data) {
if (data.hasOwnProperty(key)) {
const obj = data[key];
this[key] = obj;
}
}
this.product_type = "DIGITAL";
},
},
features_categories: {
}
}
</script>
<!-- Product functions -->
<!-- Products -->
<script>
ecommerce.products
ecommerce.products = {
physical_products: function(data) {
for (const key in data) {
if (data.hasOwnProperty(key)) {
const obj = data[key];
this[key] = obj;
}
}
this.product_type = "PHYSICAL";
},
digital_products: function() {
for (const key in data) {
if (data.hasOwnProperty(key)) {
const obj = data[key];
this[key] = obj;
}
}
this.product_type = "DIGITAL";
},
}
</script>
<!-- Seller functions -->
<script>
ecommerce.user_types.sellers.prototype = {
ecommerce.users.user_types.sellers.prototype = {
add_new_product: function(product_details) {
let productClass = null;
if(product_details.product_type==="PHYSICAL") {
@ -10048,7 +10263,7 @@
<!-- Buyer functions -->
<script>
ecommerce.user_types.buyers.prototype = {
ecommerce.users.user_types.buyers.prototype = {
add_item_to_bucket: function(item) {
const current_list = Object.values(this.buy_list)
.map(m=>m.product_name);
@ -10093,34 +10308,76 @@
}
},
buy_item: async function(item) {
// Check if Seller is live or not
// If Seller is live place a Buy order
const final_buy_list = {
buyer_id: myFloID,
shopping_details: this.buy_list,
total_shopping_price: this.total_buying_price,
date_of_purchase: + new Date(),
location: null,
try {
// Check if Seller is live or not
// If Seller is live place a Buy order
const final_buy_list = {
purchaseId: floCrypto.generateNewID().floID,
buyer_id: myFloID,
shopping_details: this.buy_list,
total_shopping_price: this.total_buying_price,
date_of_purchase: + new Date(),
location: 'Ranchi',
}
final_buy_list.buyer_signature = floCrypto.signData(JSON.stringify(final_buy_list), myPrivKey);
// Send buy info to server
floCloudAPI.sendGeneralData(final_buy_list, this.DATA_TYPE, { receiverID: floGlobals.adminID, senderIDs: [myFloID] });
// Store info in local history
compactIDB.addData('my_orders_history', final_buy_list);
this.reset_bucket_list();
// Generate Cashier UPI for payment
} catch (error) {
throw new Error(error);
}
const purchaseId = Crypto.SHA256(JSON.stringify(final_buy_list));
final_buy_list.purchaseId = purchaseId;
final_buy_list.buyer_signature = floCrypto.signData(JSON.stringify(final_buy_list), myPrivKey);
// Send buy info to server
floCloudAPI.sendGeneralData(general_data_obj, this.DATA_TYPE, { receiverID: floGlobals.adminID, senderIDs: [myFloID] });
// Store info in local history
compactIDB.addData('my_orders_history', final_buy_list);
this.reset_bucket_list();
},
build_orders_object: function(cityname='') {
Orders = {};
Orders.city = {};
Orders.city[cityname] = {};
Orders.city[cityname].buy_orders = [];
Orders.city[cityname].sell_orders = [];
return Orders;
},
reset_bucket_list: function() {
this.total_buying_price = 0;
this.buy_list = [];
}
},
set_delivery_receiving_address: function() {
if (typeof(Storage) == "undefined") {
system_message('LocalStorage not supported.');
throw new Error('LocalStorage not supported.');
}
let FloECommerceUserAddress = localStorage.getItem("FloECommerceUserAddress");
if (FloECommerceUserAddress===null) {
FloECommerceUserAddress = prompt("Please enter your local address. We will fetch local services near you.");
if(typeof FloECommerceUserAddress!=="string" && FloECommerceUserAddress.length<1) {
system_message('Invalid Address. Please refresh to enter address again.');
return;
}
localStorage.setItem("FloECommerceUserAddress", FloECommerceUserAddress);
}
},
reset_delivery_receiving_address: function(new_addr='') {
if(typeof new_addr==='string' && new_addr.length>0)
localStorage.setItem("FloECommerceUserAddress", new_addr);
},
}
</script>
<script>
try {
} catch (error) {
throw new Error(error)
}
</script>
</html>