so I want to take a bills that's not been paid since last month and take a bills for this month so I have this query to check that
const pastBills = await Customer.find({
id_customer: (
await Meteran.find({
$and: [
{
id_usage: {
$nin: (await Bills.find()).map((bill) => bill.id_usage),
},
},
],
})
).map((meter) => meter.id_customer).length === 2,
});
I want to check which customer_id is the same with the customer_id in meteran that have two different id_usage that's not in the bills. but even thought I have two different id_usage that's not in the bills it returned an empty array can anyone help me to solve this?
Related
I am building an order form that limits how many items you can order based on the stock of the item. I have a menu collection which has items
// menu
{ id: "lasagna", name: "Lasagna", price: 10, stock: 15 }
{ id: "carrot-soup", name: "Carrot Soup", price: 10, stock: 15 }
{ id: "chicken-pot-pie", name: "Chicken Pot Pie", price: 10, stock: 15 }
And an orders collection
// orders
{ id: <auto>, name: "Sarah", cart: {lasagna: 1, carrot-soup: 3}, ... }
{ id: <auto>, name: "Wendy", cart: {chicken-pot-pie: 2, carrot-soup: 1}, ... }
{ id: <auto>, name: "Linda", cart: {lasagna: 3}, ... }
4 carrot-soup has been ordered so the stock should be updated
// updated stock
{ id: "carrot-soup", name: "Carrot Soup", stock: 11 }
Orders are inserted from my Form component
function Form(props) {
// ...
// send order to firestore
const onSubmit = async _event => {
try {
const order = { cart, name, email, phone, sms }
dispatch({ action: "order-add" })
const id = await addDocument(store, "orders", order)
dispatch({ action: "order-add-success", payload: { ...order, id } })
}
catch (err) {
dispatch({ action: "order-add-error", payload: err })
}
}
return <form>...</form>
}
This is my database addDocument function
import { addDoc, collection, serverTimeStamp } from "firebase/firestore"
async function addDocument(store, coll, data) {
const docRef = await addDoc(collection(store, coll), { ...data, timestamp: serverTimestamp() })
return docRef.id
}
How should I decrement the stock field in my menu collection?
Ideally the client should have only read access to menu but to update the stock the client would need write access.
Another possibility is to have the client query the orders, sum the items, and subtract them from the read-only menu. But giving the client read access to other people's orders seems wrong too.
I am new to firestore and don't see a good way to design this.
You should deffinitely use a cloud function to update the stock. Create a function onCreate and onDelete functions trigger. If users can change data you would also need to onWrite function trigger.
Depending on the amount of data you have you woould need to create a custom queue system to update the stock. Belive me! It took me almost 2 years to figure out to solve this. I have even spoken with the Firebase engeeners at the last Firebase Summit in Madrid.
Usualy you would use a transaction to update the state. I would recommend you to do so if you don't have to much data to store.
In my case the amount of data was so large that those transactions would randomly fail so the stock wasn't correct at all. You can see my StackOverflow answer here. The first time I tought I had an answer. You know it took me years to solve this because I asked the same question on a Firebase Summit in Amsterdam. I asked one of the Engeeners who worked on the Realtime Database before they went to Google.
There is a solution to store the stock in chunks but even that would cause random errors with our data. Each time we improved our solution the random errors reduced but still remained.
The solution we are still using is to have a custom queue and work each change one by one. The downside of this is that it takes some time to calculate a lot of data changes but it is 100% acurate.
Just in case we still have a "recalculator" who recalculates one day again and checks if everything worked as it should.
Sorry for the long aswer. For me it looks like you are building a similar system like we have. If you plan to create a warehouse management system like we did I would rather point you to the right direction.
In the end it depends on the amount of data you have and how often or fast you change it.
Here is a solution based on Tarik Huber's advice.
First I include functions and admin
const functions = require("firebase-functions")
const admin = require("firebase-admin")
admin.initializeApp()
Then I create increment and decrement helpers
const menuRef = admin.firestore().collection("menu")
const increment = ([ id, n ]) =>
menuRef.doc(id).update({
stock: admin.firestore.FieldValue.increment(n)
})
const decrement = ([ id, n ]) =>
increment([ id, n * -1 ])
Here is the onCreate and onDelete hooks
exports.updateStockOnCreate =
functions
.firestore
.document("orders/{orderid}")
.onCreate(snap => Promise.all(Object.entries(snap.get("cart") ?? {}).map(decrement)))
exports.updateStockOnDelete =
functions
.firestore
.document("orders/{orderid}")
.onDelete(snap => Promise.all(Object.entries(snap.get("cart") ?? {}).map(increment)))
To handle onUpdate I compare the cart before and after using a diff helper
exports.updateStockOnUpdate =
functions
.firestore
.document("orders/{orderid}")
.onUpdate(snap => Promise.all(diff(snap.before.get("cart"), snap.after.get("cart")).map(increment)))
Here is the diff helper
function diff (before = {}, after = {}) {
const changes = []
const keys = new Set(Object.keys(before).concat(Object.keys(after)))
for (const k of keys) {
const delta = (before[k] ?? 0) - (after[k] ?? 0)
if (delta !== 0)
changes.push([k, delta])
}
return changes
}
I'm trying to retrieve the prorated invoice price from stripe when the customer increases the quantity of a subscription item. For example, the basic plan is $10 and the option to add an extra 2000 api calls per month is $4.99. If the customers wants 4000 more api calls per month then they would be increasing the subscription items quantity for the $4.99 price from 1 to 2. The price will vary per say the customer decided to increase the quantity half way through the billing period. In this case they should be charged $2.49. The next billing period should then charge the $4.99 at the start.
After attempting to retrieve the upcoming invoices using stripe.invoices.retrieveUpcoming({...}) It returns the wrong price each time. Its always more than it needs to be. Seems to be 2 times the base plan of $10 and only one of the $4.99 prices. This is my code from my backend (its an array element in an array of routes.):
{
url: '/invoice-amount',
type: eRequestType.GET,
handler: async (req, res) => {
const { proration_date, subscription, price, customer } = JSON.parse(req.headers["invoice-details"])
try {
const sub = await stripe.subscriptions.retrieve(subscription)
let siID = null, oldQuantity = null
for (let si of sub.items.data) { if (si.price.id === price) { siID = si.id; oldQuantity = si.quantity } }
if(!siID) {
const invoice = await stripe.invoices.retrieveUpcoming({
customer,
subscription_items: [{price}],
// subscription_proration_date: proration_date
})
return res.json({"amount": invoice.amount_due})
}
else {
const invoice = await stripe.invoices.retrieveUpcoming({
// customer,
subscription,
subscription_items: [{ id: siID, price, quantity: oldQuantity + 1}],
subscription_proration_date: proration_date
})
return res.json({"amount": invoice.amount_due})
}
}
catch (error) {
console.log(error)
res.json({ "error": error.message })
}
}
}
Calling that route from the front end looks like this:
async function fetchInvoiceAmount() {
return axios.get('/invoice-amount', {
headers: {
"invoice-details": JSON.stringify({
"proration_date": Math.floor(Date.now() / 1000),
"subscription": props.subId,
"price": ePrices.EXTRA_API_CALLS,
"customer": props.user.cust_id
})
}
})
}
When I test This code with a customer subscribed to my monthly plan at $10 per month and they are not paying for then extra api calls the route returns {"amount": 499} or $4.99. This seems to be correct. After reviewing the stripe docs, it mentions not passing in a subscription id and only passing in subscription_items will return the amount if the item was added to the subscription. But like from earlier, what if the customer signs up half way through the month? It should not be returning {"amount": 499} but should be returning {"amount": 249}. The real problem arises when the customer already has at least one subscription item to the $4.99 price. The route then returns {"amount": 2497}. When analyzing this output, I believe that its increasing the base price of $10 to a quantity of 2 and not touching the api price of $4.99.
How do I get this to return the prorated amount for only the one quantity increase of the api call price?
If all you want to do is preview the change in quantity, you should be able to do it like this:
const invoice = await stripe.invoices.retrieveUpcoming({
// customer,
subscription,
subscription_items: [{ id: siID, quantity: oldQuantity + 1}],
subscription_proration_date: proration_date
})
I have this query in loop:
const currentDatas = await Promise.all(nearestStations.map(async (ns: any) => {
return await this.stationCurrentDataRepo.findOne({
where: { stationId: parseInt(ns[0], 10) },
order: { date: 'DESC' },
});
}));
I want to optimize that to don't make hundreds queries and get the data in one query.
What I need is to get newest record (sort by date) for every stationId from array of ids ($in array of ids). I need all data from every found document meeting what I specified above.
In MongoDB this is done with aggregation pipeline and $group operator.
i have my model called "Conversations", and my model "Messages", right now i want to retrieve all conversations with the last Message attached (only 1 message per conversation), so i filtered the conversationids and i queried the messages, but i'm not able to get this messages (last messages) for each conversation, thanks in advance.
let conversations = await ConversationModel.find({});
const conversationIds = conversations.map(conversation => conversation._id)
// ConversationIds is basically ["conversation1", "conversation2", "conversation3"]
// Te problem is here, i want to attach the las message for each conversation, if i put limit(1)
// i will get 1 record for all query, but i want the last message record for each conversation.
MessageModel.find({ _id: { "$in" : conversationIds} }, ...);
From information gathered in comments; This is possible to achieve in a case where MessageModel documents contain a time-stamp to identify latest of them.
Idea: Filter messages based on conversationIds via $match, sort them by timestamp for the next stage where $group on conversation reference (lets say conversation_id) and pick latest of them by $first accumulator.
Aggregation Query: playground link
db.collection.aggregate([
{
$match: {
conversation_id: {
$in: conversationIds
}
}
},
{
$sort: {
timestamp: -1
}
},
{
$group: {
_id: "$conversation_id",
latest_doc: {
$first: "$$ROOT"
}
}
}
]);
I currently have the following data structure in Redis
client.hmset('user:' + user.id, 'id', user.id, 'user', JSON.stringify(meta));
client.zadd(['user:user_by_created_time', meta.created_time, 'user:' + user.id]);
client.zadd(['user:user_by_age', meta.age, 'user:' + user.id]);
I then when to get the first 10 users sorted by age, when there are more than 10, I should be able to pass an offset that allows me to use pagination.
What I currently have is the following
client.zrangebyscore(['user:user_by_age', '-inf', '+inf'], (err, results) => {
const multi = client.multi();
results.forEach(result => {
multi.hgetall(result);
});
multi.exec((err, results) => { ... });
});
I'm a bit stuck on how to continue with this, I know it's possible to sort a list, but I can't figure out how to only get 10 users after a specific offset.
I'm using the Node Redis client: https://github.com/NodeRedis/node_redis
To paginate with sorted sets use ZRANGE, not ZRANGEBYSCORE. The arguments are the ranks, so to get the first 10 users you use ZRANGE user:user_by_age 0 9, to get the next 10 you use ZRANGE user:user_by_age 10 19, etc.