I have a problem I tried solving on my own, but didn’t get far (tried different approaches but all of them ended up in a big wall of code, that eventually did not do what I needed). So I’m here asking for any advice, solution, code snippets you can offer. Thanks in advance!
I have an SQL db with tables PARTS, ASSEMBLIES and FORMULA. As names suggest assemblies are made out of parts but can also be made out of other assemblies. How assemblies are made is written in table FORMULA. In my application I can enter how many assemblies have been made (increase stock). But when I increase stock for an assembly, I need to decrease stock for corresponding parts and (sub)assemblies. For better understanding I’ll illustrate this with an example;
PARTS
partID partStock
p1 100
p2 100
p3 100
ASSEMBLIES
assID assStock
ass1 10
ass2 10
FORMULA
assID parts isAssembly quantity
ass1 p1 no 1
ass1 p2 no 2
ass1 ass2 yes 1
ass2 p3 no 2
Explanation of the table: ass1 is assembled from 1x p1 + 2x p2 + 1x ass2 (which is another assembly) and ass2 is assembled from 2x p3
So when I increase stock of ass1 for 10 (this is not a problem, I can do it), I would also need to decrease stock for p1(10), p2(20), ass2(10). And if stock for ass2 would be <10, I’d need to decrease stock of p3(for a remaining number).
Does anyone even understand what I want to do here? 😀
Any suggestions are welcome, thank you very much! Oh, and I’m writing my web app in C#. 🙂
EDIT: As it has been pointed out in comments, I firstly search for an idea (design pattern) how to accomplish this. Actual SQL queries and coding is not such a big problem.. If anyone has some helpful code, its a bonus. 😉
Personally I would start with merging the part and assembly tables, this makes your model and calculations a easier to understand. Especially since an assembly can be a part of an other assembly as well. It will probably also make other things like inventory overviews a lot easier.
Your tables could look like this:
PARTS:
FORMULA
Technically the ‘isAssembly’ field in the Parts table isn’t required because a part is an assembly when there are formulas for it.
To update the stock when parts are assembled you can recursively update the stock of the additional parts that need to be build.
The pseudo code for ‘building’ assemblies will be roughly like this:
You do need to make sure you don’t save any changes to the database until the whole function is done, otherwise you might have decreased the stock on one part before the function fails because another part is out of stock.