Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import * as functions from 'firebase-functions';
- import * as admin from 'firebase-admin';
- import * as moment from 'moment';
- const nodemailer = require('nodemailer');
- const cors = require('cors')({ origin: true });
- // import * as firebase from 'firebase';
- const Firestore = require('@google-cloud/firestore');
- const db = new Firestore({
- projectId: 'envite-f33e1'
- });
- // Start writing Firebase Functions
- // https://firebase.google.com/docs/functions/typescript
- admin.initializeApp();
- const trackedEventKeys: Array<string> = [
- 'app_button_click',
- // 'login',
- // 'logout',
- // 'update_cart',
- 'user_joined_chat',
- 'new_user',
- 'new_invitation',
- 'new_chat',
- 'chat_deleted',
- 'product_submit_order',
- // 'chat_opened',
- // 'chat_closed',
- 'navigate',
- 'product_discussed',
- // 'product_added_to_cart',
- // 'product_removed_from_cart',
- 'visit'
- ];
- // const batch = db.batch();
- // const db = firebase.firestore();
- export const processProductEvents = functions.firestore
- .document('statistics/{statisticsId}/product/{productId}')
- .onWrite((change: any, context: any) => {
- const products = db.collection(`statistics/${context.params.statisticsId}/product`)
- .orderBy('sessions', 'desc')
- .orderBy('discussions', 'desc')
- .limit(10);
- products.get()
- .then((snapshot: any) => {
- const pArr: any = [];
- snapshot.docs.forEach((p: any) => {
- pArr.push(p.data())
- });
- db.collection('statistics')
- .doc(context.params.statisticsId)
- .collection('accumulated')
- .doc('product')
- .set({
- chart_data: pArr
- }, { merge: true });
- console.log('[processProductEvents]')
- })
- return null;
- });
- export const processUserEvents = functions.firestore
- .document('statistics/{statisticsId}/users/{userId}')
- .onWrite((change: any, context: any) => {
- const users = db.collection(`statistics/${context.params.statisticsId}/users`)
- .orderBy('registrations', 'desc')
- .orderBy('invitations', 'desc')
- .limit(10);
- users.get()
- .then((snapshot: any) => {
- const uArr: any = [];
- snapshot.docs.forEach((p: any) => {
- uArr.push({ ...p.data(), id: p.id })
- });
- db.collection('statistics')
- .doc(context.params.statisticsId)
- .collection('accumulated')
- .doc('users')
- .set({
- chart_data: uArr
- }, { merge: true });
- console.log('[processUsersEvents]')
- })
- return null;
- });
- export const processChatEvents = functions.firestore
- .document('statistics/{statisticsId}/chat/{chatId}')
- .onWrite((change, context) => {
- // Get value of the newly added rating
- const afterData = change.after.data();
- const beforeData = change.before.data();
- const before: boolean = change.before.exists;
- const after: boolean = change.after.exists;
- // Get a reference to the restaurant
- const chatRef = db.collection('statistics')
- .doc(context.params.statisticsId)
- .collection('accumulated')
- .doc('chat');
- // Update aggregations in a transaction
- return db.runTransaction((transaction: any) => {
- return transaction.get(chatRef).then((chatDoc: any) => {
- if (before === false && after === true) {
- return transaction.set(chatRef, {
- total: admin.firestore.FieldValue.increment(1),
- opened: admin.firestore.FieldValue.increment(1),
- }, { merge: true });
- } else if (before === true && after === true && afterData && beforeData) {
- if (afterData.openedBy.length === 0 && beforeData.openedBy.length > 0) {
- return transaction.set(chatRef, {
- total: admin.firestore.FieldValue.increment(0),
- opened: admin.firestore.FieldValue.increment(-1),
- }, { merge: true });
- } else if (afterData.openedBy.length > 0 && beforeData.openedBy.length === 0) {
- return transaction.set(chatRef, {
- total: admin.firestore.FieldValue.increment(0),
- opened: admin.firestore.FieldValue.increment(1),
- }, { merge: true });
- }
- } else if (before === true && after === false && beforeData) {
- if (beforeData.openedBy.length > 0) {
- return transaction.set(chatRef, {
- total: admin.firestore.FieldValue.increment(-1),
- opened: admin.firestore.FieldValue.increment(-1),
- }, { merge: true });
- } else {
- return transaction.set(chatRef, {
- total: admin.firestore.FieldValue.increment(-1),
- opened: admin.firestore.FieldValue.increment(0),
- }, { merge: true });
- }
- } else {
- throw new Error(`Unkown firestore event! before: '${before}', after: '${after}'`);
- }
- });
- });
- });
- export const processEvents = functions.firestore
- .document('statistics/{statisticsId}/events/{eventId}')
- .onWrite((change: any, context: any) => {
- const data = change.after.data();
- const before: boolean = change.before.exists;
- const after: boolean = change.after.exists;
- let incrementValue: number = 1;
- console.log('------------[' + data.key + ']--------------')
- db.collection('statistics')
- .doc(context.params.statisticsId)
- .collection('goals')
- .where('key', '==', data.key)
- .get()
- .then((snapshot: any) => {
- snapshot.docs.forEach((g: any) => {
- db.collection('statistics')
- .doc(context.params.statisticsId)
- .collection('goals')
- .doc(g.id)
- .update({
- visits: admin.firestore.FieldValue.increment(incrementValue) || incrementValue
- });
- });
- });
- switch (data.key) {
- case 'navigate':
- if (!before) {
- db.collection('statistics')
- .doc(context.params.statisticsId)
- .collection('product')
- .where('url', '==', data.val.url)
- .get()
- .then((snapshot: any) => {
- snapshot.docs.forEach((p: any) => {
- db.collection('statistics')
- .doc(context.params.statisticsId)
- .collection('product')
- .doc(p.id)
- .update({
- sessions: admin.firestore.FieldValue.increment(incrementValue) || incrementValue
- });
- });
- });
- db.collection('statistics')
- .doc(context.params.statisticsId)
- .collection('goals')
- .where('type', '==', 'url')
- .where('url', '==', data.val.url)
- .get()
- .then((snapshot: any) => {
- snapshot.docs.forEach((g: any) => {
- db.collection('statistics')
- .doc(context.params.statisticsId)
- .collection('goals')
- .doc(g.id)
- .update({
- visits: admin.firestore.FieldValue.increment(incrementValue) || incrementValue
- });
- });
- });
- }
- break;
- case 'product_discussed':
- db.collection('statistics')
- .doc(context.params.statisticsId)
- .collection('product')
- .doc(data.val.productId)
- .set({
- url: data.val.productUrl,
- image: data.val.imgSource,
- name: data.val.productName,
- discussions: admin.firestore.FieldValue.increment(1),
- cost: data.val.productCost
- }, { merge: true });
- break;
- case 'new_invitation':
- !before && db.collection('statistics')
- .doc(context.params.statisticsId)
- .collection('users')
- .doc(data.val.referrer)
- .set({
- invitations: admin.firestore.FieldValue.increment(1),
- }, { merge: true });
- break;
- case 'user_joined_chat':
- !before && db.collection('statistics')
- .doc(context.params.statisticsId)
- .collection('users')
- .doc(data.val.referrer)
- .set({
- registrations: admin.firestore.FieldValue.increment(1),
- }, { merge: true });
- break;
- case 'visit':
- if (data.user_id && data.val.nonUniqueVisits <= 2) {
- db.collection('statistics')
- .doc(context.params.statisticsId)
- .collection('users')
- .doc(data.user_id)
- .set({
- sessions: admin.firestore.FieldValue.increment(1),
- }, { merge: true });
- }
- if (!before) {
- db.collection('statistics')
- .doc(context.params.statisticsId)
- .collection('accumulated')
- .doc('visits')
- .collection('visits_info')
- .doc('devices')
- .set({
- [data.val.device]: admin.firestore.FieldValue.increment(incrementValue) || incrementValue
- }, { merge: true });
- db.collection('statistics')
- .doc(context.params.statisticsId)
- .collection('accumulated')
- .doc('visits')
- .collection('visits_info')
- .doc('countries')
- .set({
- [data.val.country]: admin.firestore.FieldValue.increment(incrementValue) || incrementValue
- }, { merge: true });
- db.collection('statistics')
- .doc(context.params.statisticsId)
- .collection('accumulated')
- .doc('visits')
- .collection('visits_info')
- .doc('browsers')
- .set({
- [data.val.browser]: admin.firestore.FieldValue.increment(incrementValue) || incrementValue
- }, { merge: true });
- }
- break;
- case 'chat_opened': {
- db.collection('statistics')
- .doc(context.params.statisticsId)
- .collection('chat')
- .doc(data.val.chatId)
- .set({
- creator_id: data.user_id,
- name: '',
- openedBy: admin.firestore.FieldValue.arrayUnion(data.user_id),
- }, { merge: true })
- console.log('TTTTTTTTTTTTTTTTTTTT', data.website_id, data.val.chatId, data.user_id)
- db.collection('websites')
- .doc(data.website_id)
- .collection('chats')
- .doc(data.val.chatId)
- .set({
- openedBy: admin.firestore.FieldValue.arrayUnion(data.user_id),
- }, { merge: true })
- db.collection('websites')
- .doc(data.website_id)
- .collection('chats')
- .doc(data.val.chatId)
- .collection("messgaes")
- .orderBy("created_at", "desc")
- .limit(1)
- .get()
- .then((messagesArray: any) => {
- messagesArray.docs.forEach((message: any) => {
- db.collection('websites')
- .doc(data.website_id)
- .collection('chats')
- .doc(data.val.chatId)
- .collection("messgaes")
- .doc(message.id)
- .set({
- seen_by: admin.firestore.FieldValue.arrayUnion(data.user_id),
- not_seen_by: admin.firestore.FieldValue.arrayRemove(data.user_id),
- }, { merge: true })
- })
- });
- }
- break;
- case 'chat_closed': {
- db.collection('statistics')
- .doc(context.params.statisticsId)
- .collection('chat')
- .doc(data.val.chatId)
- .set({
- openedBy: admin.firestore.FieldValue.arrayRemove(data.user_id),
- }, { merge: true })
- db.collection('websites')
- .doc(data.website_id)
- .collection('chats')
- .doc(data.val.chatId)
- .set({
- openedBy: admin.firestore.FieldValue.arrayRemove(data.user_id),
- }, { merge: true })
- }
- break;
- case 'chat_deleted':
- db.collection('statistics')
- .doc(context.params.statisticsId)
- .collection('chat')
- .doc(data.val.chatId)
- .delete();
- break;
- case 'product_submit_order':
- if (!before) {
- const total = +data.val.grand_total;
- const user_id = data.user_id;
- const currency = data.val.currency;
- const total_quantity = data.val.total_quantity;
- incrementValue = total_quantity;
- console.log('INCREMENT', incrementValue, user_id)
- db.collection(`statistics/${context.params.statisticsId}/users`)
- .doc(user_id)
- .set({
- sales: {
- [currency]: admin.firestore.FieldValue.increment(total) || total
- }
- }, { merge: true })
- .catch((error: any) => {
- console.log('Error updating document:', error);
- });
- const productIdsArr = data.val.items;
- for (let k in productIdsArr) {
- db.collection(`statistics/${context.params.statisticsId}/product`)
- .doc(k)
- .set({
- total_sales: {
- [currency]: admin.firestore.FieldValue.increment(+productIdsArr[k]['price']) || +productIdsArr[k]['price']
- },
- sales: admin.firestore.FieldValue.increment(productIdsArr[k]['qty']) || productIdsArr[k]['qty']
- }, { merge: true })
- .catch((error: any) => {
- console.log('Error updating document:', error);
- });
- }
- db.collection('statistics')
- .doc(context.params.statisticsId)
- .collection('accumulated')
- .doc('product')
- .set({
- sales: admin.firestore.FieldValue.increment(total_quantity) || total_quantity,
- total_sales: {
- [currency]: admin.firestore.FieldValue.increment(total) || total
- }
- }, { merge: true });
- db.collection('websites')
- .doc(data.website_id)
- .collection('orders')
- .add({
- currency: data.val.currency,
- discount: data.val.discount,
- grand_total: data.val.grand_total,
- items: data.val.items,
- order_id: data.val.order_id,
- total_quantity: data.val.total_quantity,
- is_read: false,
- user_id: user_id,
- created_at: moment(Date.now()).valueOf()
- })
- }
- break;
- default: ;
- }
- if (trackedEventKeys.includes(data.key) && before === false && after === true) {
- db.collection('statistics')
- .doc(context.params.statisticsId)
- .collection('events_accumulated')
- .doc(data.key)
- .collection('daily_log')
- .doc(moment(Date.now()).format("YYYY-MM-DD"))
- .set({
- [moment(Date.now()).format("YYYY-MM-DD HH:00")]: admin.firestore.FieldValue.increment(incrementValue) || incrementValue
- }, { merge: true });
- console.log('[' + data.key + ']');
- }
- return null;
- });
- // Create a new function which is triggered on changes to /status/{uid}
- // Note: This is a Realtime Database trigger, *not* Cloud Firestore.
- export const onUserStatusChanged = functions.database.ref('/status/{combinedId}').onUpdate(
- async (change, context) => {
- const [uid, websiteId] = context.params.combinedId.split('-');
- // Get the data written to Realtime Database
- const eventStatus = change.after.val();
- if (eventStatus.statistics_id && websiteId) {
- db.collection('statistics')
- .doc(eventStatus.statistics_id)
- .collection('chat')
- .where('openedBy', 'array-contains', uid)
- .get()
- .then((snapshot: any) => {
- snapshot.docs.forEach((c: any) => {
- db.collection('statistics')
- .doc(eventStatus.statistics_id)
- .collection('chat')
- .doc(c.id)
- .update({
- openedBy: admin.firestore.FieldValue.arrayRemove(uid),
- });
- });
- });
- db.collection('websites')
- .doc(websiteId)
- .collection('chats')
- .where('openedBy', 'array-contains', uid)
- .get()
- .then((snapshot: any) => {
- snapshot.docs.forEach((c: any) => {
- db.collection('websites')
- .doc(websiteId)
- .collection('chats')
- .doc(c.id)
- .update({
- openedBy: admin.firestore.FieldValue.arrayRemove(uid),
- });
- });
- });
- }
- // Then use other event data to create a reference to the
- // corresponding Firestore document.
- const userStatusFirestoreRef = db.doc(`user_statuses/${context.params.combinedId}`);
- // It is likely that the Realtime Database change that triggered
- // this event has already been overwritten by a fast change in
- // online / offline status, so we'll re-read the current data
- // and compare the timestamps.
- const statusSnapshot = await change.after.ref.once('value');
- const status = statusSnapshot.val();
- // If the current timestamp for this data is newer than
- // the data that triggered this event, we exit this function.
- if (status.last_changed > eventStatus.last_changed) {
- return null;
- }
- // Otherwise, we convert the last_changed field to a Date
- eventStatus.last_changed = new Date(eventStatus.last_changed);
- // ... and write it to Firestore.
- return userStatusFirestoreRef.set(eventStatus);
- });
- export const getGeneratedPasswordResetUrl = functions.https.onRequest((req: any, res: any) => {
- const userEmail = 'mamuka.anjaparidze01@gmail.com';
- admin.auth().generatePasswordResetLink(userEmail).then((link) => {
- console.log("rame data");
- // Construct password reset email template, embed the link and send
- // using custom SMTP server.
- console.log(userEmail, link)
- let transporter = nodemailer.createTransport({
- service: 'gmail',
- auth: {
- user: 'shamatavamariami@gmail.com',
- pass: 'ulpisejqkllasggv'
- }
- });
- cors(req, res, () => {
- // getting dest email by query string
- // const dest = req.query.dest;
- const mailOptions = {
- from: 'Your Account Name <yourgmailaccount@gmail.com>', // Something like: Jane Doe <janedoe@gmail.com>
- to: 'msham16@freeuni.edu.ge',
- subject: 'I\'M A PICKLE!!!', // email subject
- // html: `<div style="background:blue; width:300px; height:300px">
- // ${link} <p style="font-size: 16px;">Pickle Riiiiiiiiiiiiiiiick!!</p>
- // <br />
- // <img src="https://images.prod.meredith.com/product/fc8754735c8a9b4aebb786278e7265a5/1538025388228/l/rick-and-morty-pickle-rick-sticker"/>
- // <div>`
- html: `<div style="width: 500px; height: 100%;">
- <div
- style="background:blue;width:500px;height:700px;display:flex;justify-content:center;align-items: center;">
- <div
- style="background:white; width:350px; height: 550px; display: flex; justify-content: center; align-items: center; ">
- <h1>FORGOT YOUR PASSWORD?</h1></div>
- </div>
- <div style="display: flex; flex-direction: column; margin-top: -50px;">
- <span style="margin: 0 auto;">Email sent by eNvite Team</span>
- <span style="margin: 0 auto">Copyright © 2019 eNvite Ltd. All rights reserved.</span>
- </div>
- </div>`
- };
- // returning result
- return transporter.sendMail(mailOptions, (erro: any, info: any) => {
- if (erro) {
- return res.send(erro.toString());
- }
- return res.send('Sended');
- });
- });
- })
- .catch((error) => {
- // Some error occurred.
- console.log(error)
- });
- // res.status(200).send(userEmail);
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement